Synsemadocsv0.6.xENES

HTTP server

HTTP server

A native, production HTTP server — no framework to add (async hyper/tokio). Everything is deny-by-default, so a server needs require serve(port).

serve.syn
-- Doc example: the serve response contract. Helpers return {status, value}; the
-- runtime renders them. (A real `serve on` block doesn't terminate, so the doctest
-- asserts the response shapes the handlers give — see the prose for a full server.)
intent: "doc example: serve response contract"

print("ok → " + text(status of ok({"a": 1})) + ",  fail(400) → " + text(status of fail(400, "bad")))

test "uniform response helpers carry a status + value"
    assert_eq(status of ok({"a": 1}), 200)
    assert_eq(status of created({"id": 1}), 201)
    assert_eq(status of fail(400, "bad input"), 400)
    assert_eq(status of not_found("missing"), 404)
    assert_eq((value of fail(400, "bad input"))["error"], "bad input")

Routes & params§

require serve(8080)

serve on 8080
    route "GET /products"
        give sql("SELECT id, name, price FROM products")
    route "GET /products/:id"
        give sql("SELECT * FROM products WHERE id = ?", [params.id])
    route "GET /files/*path"            -- catch-all (variable depth)
        give read_file(params.path)

Routes match by specificity (exact > :param > *catchall), not declaration order.

Auth & validation§

serve on 8080
    auth with check_token
    route "POST /products" requires auth
        expect body {name: text, price: number}    -- 400 if it doesn't match
        give created(json of request)

The auth task receives the bearer token; declare it with 2 parameters (task check(token, request)) and it also receives the request map — that's what unlocks cookie sessions (Login & sessions).

The request & responses§

request has .method .path .body .json .form .headers .cookies .query .params .user .ip .body_file (.cookies — engine v0.5.5+; .form — engine > v0.5.9). form of request is the parsed form body: urlencoded → {field: text}; multipart → text fields plus file uploads as {filename, content_type, data} (exact bytes); no form body → empty map — classic <form method="post"> posts need no fetch/JSON. .headers, .query and .params are maps — index by key (request.headers["authorization"]; header names are lowercased). Indexing a missing key errors, so guard optional ones with contains(request.headers, "x"). query and params are also bound as bare locals, so params.id works directly. When a large body spills to disk (over ~1 MiB), .body is empty and .body_file is a temp-file path — read it with read_body() / read_body_bytes().

Handler scope: request, query and params live only in the handler's own scope — a task the handler calls does not see them. Pass what the task needs as an argument (e.g. lookup_user(request)), never a bare request referenced inside that task.

Responses use the uniform helpers — ok(x), created(x), fail(code, msg), not_found(msg), respond(text, content_type), redirect(url) — or give a value directly. Any of them can carry extra headers or cookies: with_header(resp, name, value) / set_cookie(resp, name, value, opts?) — see Login & sessions.

Shared state across requests (state_*)§

A set on a global inside a handler does not persist to the next request — each request runs on its own snapshot of the globals. State shared across requests/handlers lives in an in-memory store with the life of the server: state_set(key, value), state_get(key, default?), state_incr(key, delta?), state_delete(key), state_all() (a map snapshot of every key — {"a": 1, "hits": 2}). Gone on restart; for durable state use a database or the declared memory (Memory & state).

Built in§

Discovery — what every server publishes§

A Synsema server describes itself. Everything below is derived from what is actually wired — the route table, expect, requires auth, rate_limit, describe, and the capabilities the routes' code declares. Nothing is written twice, and what can't be derived truthfully (a response schema) is left out, not invented.

URLWhatNotes
/llms.txtMarkdown index for agents: title, intent, every endpoint with the capabilities it may use (- POST /pay [net:api.stripe.com, llm]), the describe api: list, and a ## Machine-readable section pointing at the documents belowon by default
/robots.txtAllow: / + Sitemap: <base>/sitemap.xmlDisallow: / when private
/sitemap.xmlThe pages a crawler can visit without context: GET routes without path params, without requires auth, not stream, not proxyparametric routes (/blog/:slug) are not expanded — the runtime doesn't know which slugs exist. No lastmod (there is no truth to give it)
/openapi.jsonOpenAPI 3.1 of the route table (mapping below)deterministic: paths ascending, methods in the order GET/POST/PUT/PATCH/DELETE — diffable, anchorable in tests
/docsThe API, browsable: every operation with its schema, a form per path parameter and body, and Try it (a bearer-token field kept in the tab's sessionStorage; cookies travel on their own). No CDN, no third-party script. With Accept: text/markdown the same reference comes back as Markdown for agentsdocs off turns only this page off
/.well-known/synsema-authHow to authenticate here — Agent identity

Base URL (the absolute links in sitemap/robots and OpenAPI servers): domain "…" of the serve block if declared; otherwise the request's Host, with https when TLS is on or a proxy in front sends X-Forwarded-Proto: https.

Behind a proxy, declare domain. A proxy rewrites Host to the backend's authority (nginx's default $proxy_host, the built-in proxy to as well), so without domain the sitemap would say https://127.0.0.1:8090/.... X-Forwarded-Host is ignored on purpose: any client can inject it and a generic proxy passes it through — that is host header injection, and it would poison the sitemap, robots.txt and the OpenAPI servers. Same stance as X-Forwarded-For for rate limiting: the engine only trusts what you declared.

Shape and opt-outs:

serve on 8080
    describe
        about: "Bookshop API"            -- the title: /llms.txt, OpenAPI info.title, /docs
        api: ["GET /books/:id -- one book", "POST /orders -- place an order"]
        version: "1.4.0"                 -- OpenAPI info.version (default "0.0.0")
    -- private                           -- internal server: /llms.txt, /openapi.json, /sitemap.xml, /docs → 404; robots Disallow: /
    -- docs off                          -- no /docs page; /openapi.json stays published
    route "POST /orders" requires auth
        expect body {book: text, qty: number}
        give {"ok": true}

How /openapi.json is derived:

OpenAPIFrom
info.title / info.description / info.versiondescribe about:intent:"Synsema service" / intent: / describe version:
serversthe base URL above (none when it can't be known)
paths./a/{id} + parametersroute "GET /a/:id":id and *rest become {id} / {rest}, in: path, required, string
requestBodythe route's top-level expect body {…} → a JSON schema, every field required (text→string, number→number, bool→boolean, list→array, map→object). An expect inside a when is a branch, not a contract: not published
responses.200application/json; text/event-stream for a stream route; text/html when the last give is html()/render()/page(); the three negotiated types for content(); 302 for redirect(). Inferred from the code, no response schema — that is the honest limit
400 / 401 / 429an expect / requires auth / a rate limit
security + components.securitySchemesroutes with requires auth when the block has auth with: bearer, cookie, httpsig (RFC 9421) — the same three /.well-known/synsema-auth announces
operationIdget_books_id (method + path segments)
x-synsema-rate-limit{count, window} (window in seconds; a route inherits the block's) or "unlimited"
x-synsema-streaming / x-synsema-proxystream routes / proxy to routes
x-synsema-capabilitieswhat the route may touch, statically: the require lines of every task the route's code calls (transitively, through modules too) plus what the builtins it calls imply (fetchnet, sqldb, read_filefile.read, reason/decidellm, remembermemory, …). It is the contract, not a trace of what ran — the runtime still gates every call. Always present; [] when nothing

Mounted groups (mount m.api at "/v1") are published with their prefix. Each host "…" block publishes its own table under its Host.

In CI, without a server: synsema openapi app.syn --out openapi.json [--base-url https://api.example] writes the same document from the source — parse only, nothing runs, no port opens; exit 2 when the file has no serve. See CLI.

See Frontend for HTML pages and Build a website for the end-to-end walkthrough.