FUNCTIONS

Execução de WASM

Suba um binário WASM, invoque por HTTP. Roda em sandbox: sem rede, sem filesystem, memória e tempo limitados. Escreva em qualquer linguagem que compile pra WASI, incluindo Go puro.

WASM execution

Upload a WASM binary, invoke it over HTTP. Runs in a sandbox: no network, no filesystem, bounded memory and time. Write it in any language that compiles to WASI, including plain Go.

SYNC resposta na mesma chamada answers in the same call

Endpoints

Endpoints

PUT /api/v1/functions/{name} envia o binário .wasm (corpo cru) uploads the .wasm binary (raw body)
POST /api/v1/functions/{name}/invoke executa a função runs the function
GET /api/v1/functions lista as funções do cliente lists the client's functions
DELETE /api/v1/functions/{name} remove uma função removes a function

A resposta do /invoke é exatamente o que a função gerou (status, headers e corpo). Não é o envelope JSON padrão, é a saída definida pelo próprio código do cliente.

The /invoke response is exactly what the function produced (status, headers and body). Not the standard JSON envelope, it's output the client's own code defines.

Como a função recebe e responde

How the function receives and responds

A função lê um envelope JSON de stdin e escreve um envelope JSON em stdout. Sem SDK, qualquer linguagem que compile pra WASI (wasm32-wasip1) funciona, incluindo Go puro (GOOS=wasip1 GOARCH=wasm go build).

The function reads a JSON envelope from stdin and writes a JSON envelope to stdout. No SDK, any language that compiles to WASI (wasm32-wasip1) works, including plain Go (GOOS=wasip1 GOARCH=wasm go build).

// stdin  → {"query": {"a":"1"}, "headers": {"content-type":"..."}, "body": "texto"}
        // stdout → {"status": 200, "headers": {"content-type":"text/plain"}, "body": "hello"}

Exemplo

Example

cat > main.go <<'EOF'
        package main
        
        import (
        	"encoding/json"
        	"io"
        	"os"
        )
        
        func main() {
        	raw, _ := io.ReadAll(os.Stdin)
        	var req struct{ Body string `json:"body"` }
        	json.Unmarshal(raw, &req)
        	json.NewEncoder(os.Stdout).Encode(map[string]any{
        		"status": 200,
        		"body":   "recebi: " + req.Body,
        	})
        }
        EOF
        GOOS=wasip1 GOARCH=wasm go build -o minha_funcao.wasm main.go
        
        curl -X PUT "https://api.alicercelabs.com.br/api/v1/functions/minha" \
          -H "Authorization: Bearer <token>" \
          --data-binary @minha_funcao.wasm
        
        curl -X POST "https://api.alicercelabs.com.br/api/v1/functions/minha/invoke" \
          -H "Authorization: Bearer <token>" \
          -d "teste"
        # → recebi: teste

Segurança do sandbox

Sandbox security

ControleControlComo funcionaHow it works
Sem rede No network
WASI preview1 não importa sockets: não existe chamada de saída possível, não é uma flag pra desligar. WASI preview1 doesn't import sockets: there's no outbound call possible, it's not a flag to turn off.
Sem filesystem No filesystem
Nenhum diretório fica visível pro módulo. No directory is visible to the module.
Memória e tempo limitados de verdade Genuinely bounded memory and time
A execução da VM é efetivamente abortada ao estourar o timeout: não é o servidor desistindo de esperar. The VM's execution is actually aborted on timeout: not the server giving up on waiting.

Fora de escopo v1: acesso da função a KV/Queue/Edge DB (é sandbox de computação pura); disparo por Cron/Queue (só invoke HTTP síncrono); domínio customizado por função.

Out of scope for v1: function access to KV/Queue/Edge DB (it's a pure compute sandbox); triggering via Cron/Queue (HTTP invoke only); custom domain per function.

Erros possíveis

Possible errors

StatusMotivoReason
400wasm inválido no deploy, nome inválido, corpo vazio/acima do limite, ou limite de funções atingidoinvalid wasm on deploy, invalid name, empty/over-limit body, or function limit reached
401token ausente ou inválidomissing or invalid token
404função não encontradafunction not found
429limite de taxa excedidorate limit exceeded
500saída da função não é um envelope JSON válido, ou ela saiu com código != 0 (stderr incluso, truncado)the function's output isn't a valid JSON envelope, or it exited with a non-zero code (stderr included, truncated)
503Functions não configurado no servidorFunctions not configured on the server
504função excedeu o timeout configuradofunction exceeded the configured timeout

Usando o SDK

Using the SDK

Deploy de um binário WASM (qualquer linguagem que compile pra WASI, incluindo Go puro) e invocação síncrona.

Deploy a WASM binary (any language that compiles to WASI, including plain Go) and invoke it synchronously.

SDKs oficiais: Go · Python · JavaScript.

Official SDKs: Go · Python · JavaScript.

Fazer deploy de uma função

Deploy a function

import (
	"context"
	"fmt"

	alicercelabs "github.com/alicercelabs/alicercesdk-go"
)

client := alicercelabs.New("alk_...")
ctx := context.Background()

wasm, err := os.ReadFile("minha_funcao.wasm")
info, err := client.Functions.Deploy(ctx, "minha", wasm)
fmt.Println(info.Name, info.SizeBytes)
from alicercelabs import AlicerceLabs

client = AlicerceLabs(api_key="alk_...")

with open("minha_funcao.wasm", "rb") as f:
    info = client.functions.deploy("minha", f.read())
print(info["name"], info["size_bytes"])
import { AlicerceLabs } from "alicercesdk-javascript";

const client = new AlicerceLabs("alk_...");

const wasm = await readFile("minha_funcao.wasm");
const info = await client.functions.deploy("minha", wasm);
console.log(info.name, info.size_bytes);

Invocar

Invoke

resp, err := client.Functions.Invoke(ctx, "minha", []byte("algum corpo"))
fmt.Println(string(resp.Content))
resp = client.functions.invoke("minha", b"algum corpo")
print(resp.content.decode())
const resp = await client.functions.invoke("minha", "algum corpo");
console.log(new TextDecoder().decode(resp.content));

Listar / remover

List / delete

fns, err := client.Functions.List(ctx)
err = client.Functions.Delete(ctx, "minha")
fns = client.functions.list()
client.functions.delete("minha")
const fns = await client.functions.list();
await client.functions.delete("minha");

Limites

Limits

1.000/dia · 41/hora. Funções por cliente: 20. Tamanho máximo do binário: 10MB. Memória máxima: 32MB. Timeout máximo: 5s (teto absoluto de 30s, mesmo com override). Tudo tunável por cliente via admin.

1,000/day · 41/hour. Functions per client: 20. Max binary size: 10MB. Max memory: 32MB. Max timeout: 5s (absolute ceiling of 30s, even with an override). All tunable per client via admin.