From 82344b0447ddb9ff7b9530a1e23b5184b561840c Mon Sep 17 00:00:00 2001 From: Roman Zaiev Date: Sat, 21 Nov 2026 23:20:15 +0000 Subject: [PATCH] Install the documentation for agents with spindle An agent writing code with spindle knew only the README and the changelog the package installs: the tutorial and guides, where routes, dependencies and each battery are shown whole, stayed online, and never at the release it builds against. starlight-hypha-agents writes each page as Markdown and llms.txt from the same pages people read, and spindle installs them. An agent reads them only when told to, so the README gives a user the one line for their project's AGENTS.md that sends it there. The docs workflow now builds every pull request and fails if agents/ differs from what the pages write, so the installed pages cannot drift; it deploys from main alone. The theme moves to 0.8.0, which leaves what agents read to that plugin. --- .github/workflows/docs.yml | 35 +- AGENTS.md | 14 +- CHANGES.md | 5 + README.md | 13 + agents/llms.txt | 45 ++ agents/pages/guide/access.md | 242 ++++++++++ agents/pages/guide/background.md | 70 +++ agents/pages/guide/client.md | 157 +++++++ agents/pages/guide/compression.md | 78 ++++ agents/pages/guide/cookies.md | 302 ++++++++++++ agents/pages/guide/databases.md | 238 ++++++++++ agents/pages/guide/domains.md | 108 +++++ agents/pages/guide/health.md | 100 ++++ agents/pages/guide/mcp.md | 579 ++++++++++++++++++++++++ agents/pages/guide/metrics.md | 102 +++++ agents/pages/guide/middleware.md | 118 +++++ agents/pages/guide/oauth.md | 190 ++++++++ agents/pages/guide/pages.md | 204 +++++++++ agents/pages/guide/rate-limits.md | 52 +++ agents/pages/guide/serving.md | 219 +++++++++ agents/pages/guide/sse.md | 170 +++++++ agents/pages/guide/testing.md | 107 +++++ agents/pages/guide/websockets.md | 218 +++++++++ agents/pages/index.md | 74 +++ agents/pages/install.md | 23 + agents/pages/reference.md | 76 ++++ agents/pages/tutorial/bodies.md | 310 +++++++++++++ agents/pages/tutorial/client-schemas.md | 293 ++++++++++++ agents/pages/tutorial/database.md | 339 ++++++++++++++ agents/pages/tutorial/dependencies.md | 426 +++++++++++++++++ agents/pages/tutorial/first-app.md | 141 ++++++ agents/pages/tutorial/logging.md | 162 +++++++ agents/pages/tutorial/openapi.md | 228 ++++++++++ agents/pages/tutorial/routes.md | 289 ++++++++++++ agents/pages/tutorial/static-files.md | 169 +++++++ docs/astro.config.mjs | 5 + docs/bun.lock | 37 +- docs/package.json | 3 +- dune | 10 + 39 files changed, 5936 insertions(+), 15 deletions(-) create mode 100644 agents/llms.txt create mode 100644 agents/pages/guide/access.md create mode 100644 agents/pages/guide/background.md create mode 100644 agents/pages/guide/client.md create mode 100644 agents/pages/guide/compression.md create mode 100644 agents/pages/guide/cookies.md create mode 100644 agents/pages/guide/databases.md create mode 100644 agents/pages/guide/domains.md create mode 100644 agents/pages/guide/health.md create mode 100644 agents/pages/guide/mcp.md create mode 100644 agents/pages/guide/metrics.md create mode 100644 agents/pages/guide/middleware.md create mode 100644 agents/pages/guide/oauth.md create mode 100644 agents/pages/guide/pages.md create mode 100644 agents/pages/guide/rate-limits.md create mode 100644 agents/pages/guide/serving.md create mode 100644 agents/pages/guide/sse.md create mode 100644 agents/pages/guide/testing.md create mode 100644 agents/pages/guide/websockets.md create mode 100644 agents/pages/index.md create mode 100644 agents/pages/install.md create mode 100644 agents/pages/reference.md create mode 100644 agents/pages/tutorial/bodies.md create mode 100644 agents/pages/tutorial/client-schemas.md create mode 100644 agents/pages/tutorial/database.md create mode 100644 agents/pages/tutorial/dependencies.md create mode 100644 agents/pages/tutorial/first-app.md create mode 100644 agents/pages/tutorial/logging.md create mode 100644 agents/pages/tutorial/openapi.md create mode 100644 agents/pages/tutorial/routes.md create mode 100644 agents/pages/tutorial/static-files.md diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 63181ca..ca452a6 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -1,28 +1,28 @@ -# The documentation site on GitHub Pages, rebuilt on every push to main: +# The documentation site on GitHub Pages: built on every pull request, which +# fails if agents/ is not what the pages write, and deployed from main. # odoc's reference from the .mli files, then Starlight's pages around it. name: docs on: push: branches: [main] + pull_request: +# A build reads the repository and nothing more; the deploy job alone is +# given the rights to publish. permissions: contents: read - pages: write - id-token: write +# A newer push to a pull request replaces its build; main's deploys queue +# and always finish. concurrency: - group: pages - cancel-in-progress: true + group: pages-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: - deploy: + build: runs-on: ubuntu-24.04 - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} steps: - - uses: actions/configure-pages@v6 - uses: actions/checkout@v5 - uses: ocaml/setup-ocaml@v3 with: @@ -38,8 +38,23 @@ jobs: # the token, past its limit for a runner's shared address. env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # The build writes agents/ from the pages: a page changed without it + # differs here. + - run: git add --intent-to-add agents/ && git diff --exit-code agents/ - uses: actions/upload-pages-artifact@v5 with: path: _build/docs + deploy: + needs: build + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-24.04 + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - uses: actions/configure-pages@v6 - uses: actions/deploy-pages@v5 id: deployment diff --git a/AGENTS.md b/AGENTS.md index 87c653e..0cb8d97 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,8 +23,8 @@ OAuth suite's authorization server, and `make docs` Bun. Without `SPINDLE_TEST_OIDC` the rows that need the authorization server, and the test output says so. CI runs `make lint` and `make test`, against the same compose Postgres, on OCaml 5.5, and `make test` again on the oldest -versions the opam files allow. `docs.yml` publishes the site to GitHub -Pages on every push to `main`. +versions the opam files allow. `docs.yml` builds the site on every pull +request and publishes it to GitHub Pages from `main`. ## Layout @@ -49,6 +49,10 @@ docs/ the documentation site, a Starlight site in Hypha's look, from importing the examples it shows as @examples/?raw into Starlight's examples/ the programs the site shows, each a whole file, built and run +agents/ the documentation for a user's agent, generated by + starlight-hypha-agents from the pages, `make docs`: llms.txt, + the catalogue, and pages/, each page as Markdown; installed by + spindle test/ the suites: the framework, HTTP and WebSocket rows by RFC section, OAuth's by RFC, MCP's by the specification's section and access control's by OWASP ASVS's, the wire, the Postgres and SQLite kits, and test_docs, @@ -397,6 +401,12 @@ out you broke it, as it is true today. Cite one by its bold phrase. timer that decides a verdict measures the runner, which a loaded one stretches. Symptom: a test green on a laptop and red on a loaded CI runner. +- **`agents/` is generated, never edited.** starlight-hypha-agents writes + it from the site's pages as `make docs` builds them: a page changed is + `make docs` run in the same commit, because a user's agent reads what + the release installs, offline, and a page it reads must be the + release's. Symptom: the docs workflow, which builds the pages on every + pull request, fails on `agents/` differing. ## Changes and releases diff --git a/CHANGES.md b/CHANGES.md index 9317e80..3b90e38 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,10 @@ # Changes +## Unreleased + +- spindle installs its documentation for agents: each page of the site as + Markdown, and `llms.txt`, in `$(opam var spindle:doc)`. + ## 0.15.0 (2026-11-10) - Breaking: wiretype 0.7 is required. Its Melange printer names a list's diff --git a/README.md b/README.md index 373cba9..7f7225b 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,19 @@ with the bounds from your types, and every error it may answer. ![POST /split in the interactive docs at /docs](docs/src/assets/scalar.png) +## With an agent + +spindle installs its documentation at `$(opam var spindle:doc)`: each page +of the site as Markdown, the tutorial and guides among them, and +`llms.txt`, which lists them. Your agent reads it when told to, in a line in +your project's `AGENTS.md`: + +```md +Before writing code with spindle, read `$(opam var spindle:doc)/llms.txt` and +the pages it lists for the parts you need, and use those parts rather than +writing your own. +``` + ## Contributing See [AGENTS.md](AGENTS.md). diff --git a/agents/llms.txt b/agents/llms.txt new file mode 100644 index 0000000..6e484ea --- /dev/null +++ b/agents/llms.txt @@ -0,0 +1,45 @@ +# spindle + +> The web framework for modern OCaml. + +## Tutorial + +- [Install](pages/install.md) +- [Your first app](pages/tutorial/first-app.md) +- [Routes](pages/tutorial/routes.md) +- [Dependencies](pages/tutorial/dependencies.md) +- [Request bodies, responses and errors](pages/tutorial/bodies.md) +- [Logging](pages/tutorial/logging.md) +- [Static files](pages/tutorial/static-files.md) +- [Database](pages/tutorial/database.md) +- [OpenAPI](pages/tutorial/openapi.md) +- [Client schemas](pages/tutorial/client-schemas.md) + +## Guides + +- [HTML pages and templates](pages/guide/pages.md) +- [Databases](pages/guide/databases.md) +- [Cookies, sessions and CORS](pages/guide/cookies.md) +- [OAuth bearer tokens](pages/guide/oauth.md) +- [Access control](pages/guide/access.md) +- [MCP servers](pages/guide/mcp.md) +- [Middleware](pages/guide/middleware.md) +- [Server-Sent Events (SSE)](pages/guide/sse.md) +- [WebSockets](pages/guide/websockets.md) +- [HTTP client](pages/guide/client.md) +- [Background jobs](pages/guide/background.md) +- [Rate limits](pages/guide/rate-limits.md) +- [Compression](pages/guide/compression.md) +- [Testing](pages/guide/testing.md) +- [Server configuration and shutdown](pages/guide/serving.md) +- [Multicore and shared state](pages/guide/domains.md) +- [Health checks](pages/guide/health.md) +- [Metrics](pages/guide/metrics.md) + +## Reference + +- [Reference](pages/reference.md) + +## Other pages + +- [Spindle](pages/index.md): The web framework for modern OCaml. diff --git a/agents/pages/guide/access.md b/agents/pages/guide/access.md new file mode 100644 index 0000000..cea8953 --- /dev/null +++ b/agents/pages/guide/access.md @@ -0,0 +1,242 @@ +# Access control + +Decide who may do what to which object. A **policy** is a function you +write; a **check** is a dependency that enforces it, so a route gets an +object only once its policy allows the action. + +```ocaml title="access.ml" +(* Who may do what to a note: its owner reads and deletes it, anyone signed + in reads a shared one, nobody deletes a locked one, and an admin reads + every one and sees how many there are. + + curl -H 'Authorization: Bearer ada-token' localhost:8080/notes/1 + curl -i -X DELETE -H 'Authorization: Bearer alan-token' localhost:8080/notes/1 + curl -H 'Authorization: Bearer grace-token' localhost:8080/admin/count *) + +open Spindle.Syntax +module Access = Spindle.Access + +type person = { id : int; admin : bool } +type note = { owner : int; text : string; shared : bool; locked : bool } + +let people = + [ + ("ada-token", { id = 1; admin = false }); + ("alan-token", { id = 2; admin = false }); + ("grace-token", { id = 3; admin = true }); + ] + +let notes = + [ + (1, { owner = 1; text = "Write to Charles"; shared = false; locked = false }); + (2, { owner = 2; text = "Fix the bombe"; shared = true; locked = false }); + ( 3, + { owner = 1; text = "The engine's plans"; shared = false; locked = true } + ); + ] + +(* Who calls: the person the token belongs to, read once a request however + many checks read them, and named in a denial's log line by their id. *) +let me = + Access.principal + ~id:(fun p -> string_of_int p.id) + (Spindle.Dep.join + ~refuses:[ Bearer_token.signed_out ] + (let+ token = Bearer_token.bearer in + Option.to_result ~none:Bearer_token.please_sign_in + (List.assoc_opt token people))) + +type action = Read | Delete + +(* The rule, whole, in one place. *) +let policy = + Access.policy "notes" me + ~action:(function Read -> "read" | Delete -> "delete") + (fun person action note -> + match action with + | Read when person.admin || note.shared || note.owner = person.id -> + Access.Allow + | Delete when note.locked -> Access.Deny "locked" + | Delete when note.owner = person.id -> Access.Allow + | Read | Delete -> Access.Deny "not the owner") + +let note_id = Spindle.Path.param "note_id" Wiretype.int + +(* The note is loaded as any input is, and handed to its policy: a route + reaches it through Access.can and no other way. *) +let note = + Access.resource policy + (Spindle.Dep.join + ~refuses:[ Spindle.Refusal.Code.not_found ] + (let+ id = Spindle.param note_id in + Option.to_result ~none:Spindle.Refusal.not_found + (List.assoc_opt id notes))) + +type admin = Count + +let admin = + Access.policy "admin" me + ~action:(function Count -> "count") + (fun person Count () -> + if person.admin then Access.Allow else Access.Deny "no admin") + +let routes = + [ + Spindle.get ~summary:"A note" + Spindle.Path.(s "notes" / note_id) + (Spindle.Returns.json Wiretype.string) + (let+ n = Access.can Read note in + Ok n.text); + (* Someone else's note is answered as a missing one, so an id says + nothing of what exists. *) + Spindle.delete ~summary:"Delete a note" + Spindle.Path.(s "notes" / note_id) + (Spindle.Returns.empty ~status:`No_content ()) + (let+ _ = Access.can Delete note in + Ok ()); + (* A list is the application's own lookup, for the caller. *) + Spindle.get ~summary:"Your notes" + Spindle.Path.(s "notes") + (Spindle.Returns.json (Wiretype.list Wiretype.string)) + (let+ person = Access.caller me in + Ok + (List.filter_map + (fun (_, n) -> if n.owner = person.id then Some n.text else None) + notes)); + Spindle.get ~summary:"How many notes there are" + Spindle.Path.(s "admin" / s "count") + (Spindle.Returns.json Wiretype.int) + (let+ () = Access.require admin Count in + Ok (List.length notes)); + ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> + Spindle.serve env (routes @ Spindle.Openapi.routes ~title:"Notes" routes) +``` + +## The caller + +`Access.principal ~id me` names who calls, from a dependency of your own: +a session, a bearer token, or both. It refuses when there is nobody, with +your `401`. `~id` is how a denial's log line names them -- your own +identifier, never anything of their credential. However many checks a +route makes, the caller is read once a request. + +A route that needs only the caller -- a list of their own notes -- reads +`Access.caller me`. + +## The policy + +`Access.policy name caller ~action decide`: `decide` takes the caller, an +action and the object, and answers `Allow` or `Deny reason`. It is pure: a +role is a field of the caller, ownership a field of the object, and a +membership or a tenant is loaded with the object, so the rule is one +`match` in one place. + +Read roles from your database, not from a token's claims: a decision is +made on every request with what it reads then, so a role someone loses is +lost at their next request, where a claim holds until the token expires. + +## Checks + +| Check | Hands over | A denial is | +|---|---|---| +| `Access.can action resource` | the object | `404`, the same answer as a missing object, unless `~deny_as` gives another | +| `Access.require policy action` | `()` | `403 forbidden` | +| `Access.check policy` | a function judging an object you hold | `403 forbidden` | + +`Access.resource policy load` hands the object's loader to its policy. Keep +the loader out of your routes' reach, so `Access.can` is the only way to +the object: a check is then how a handler gets what it works on, and +cannot be forgotten. + +`can` reads the caller before the object, so nobody signed in is a `401` +before anything is looked up. A denial answers as a missing object by +default, so an id tells a stranger nothing about what exists; a route +whose objects are public anyway gives `~deny_as` a `403` of its own. + +`Access.check` is for an object that arrives as a value -- named in a +body, or in an MCP tool's arguments -- rather than loaded by a dependency. + +Each check declares what it refuses with, so the route's +[document](../tutorial/openapi.md) lists it. + +## Who may call a route + +Who may call a route is what it reads -- the dependencies are the whole of +it: + +| A route reads | Who may call it | +|---|---| +| `Access.can`, `require` or `check` | whoever the policy allows | +| `Access.caller`, `Bearer.claims` or `Bearer.scope` | whoever is signed in | +| none of these | anyone | + +A page anyone may read is written as any route is, and an application with +no access control writes nothing of it. + +The [document](../tutorial/openapi.md) says it for each operation, as +`x-spindle-access`: + +```json +"delete": { + "x-spindle-access": [{ "policy": "notes", "action": "delete" }], + ... +} +``` + +one entry a check, `[]` for a route that reads only the caller, and none for +one anyone may call. + +## A check forgotten + +A route meant to be guarded whose check was forgotten is anyone's -- the +commonest break of access control, and the one nobody sees. +`Access.unguarded` lists the routes that read no check, so a test says +which are meant to be anyone's, and fails, naming it, when another joins +them: + +```ocaml +let test_only_these_are_public () = + Alcotest.(check (list string)) + "public routes" [ "GET /"; "GET /about" ] + (Spindle.Access.unguarded routes) +``` + +## Lists + +Which objects a caller may see is your own query, written beside its +route, as `GET /notes` does above. A policy judges one object; filtering a +table by it is your database's work. + +## The log + +A denial writes one line on the `spindle.access` source, at `warn`: + +```console +DELETE /notes/1: notes: delete denied to 2: not the owner +``` + +with the route, the policy, the action, the caller's id and the reason as +fields. An allow writes no line. Every decision is on the request's span, +as `spindle.access.policy`, `spindle.access.action`, +`spindle.access.subject` and `spindle.access.decision`. + +## Testing a policy + +`Access.decide` answers what a policy decides, with no server: + +```ocaml +let ada = { id = 1; admin = false } +let adas = { owner = 1; text = "Write to Charles"; shared = false; locked = false } + +let decided = function Access.Allow -> "allow" | Access.Deny why -> why + +let test_the_owner_deletes () = + Alcotest.(check string) "unlocked" "allow" + (decided (Access.decide policy ada Delete adas)); + Alcotest.(check string) "locked" "locked" + (decided (Access.decide policy ada Delete { adas with locked = true })) +``` diff --git a/agents/pages/guide/background.md b/agents/pages/guide/background.md new file mode 100644 index 0000000..499a36e --- /dev/null +++ b/agents/pages/guide/background.md @@ -0,0 +1,70 @@ +# Background jobs + +Some work should not hold up the answer: sending an email, or checking on +something later. `Spindle.Background` runs work now, on its own fiber; +`Spindle.Alarm` runs it after a delay. + +```ocaml +open Spindle.Syntax + +let background : Spindle.Background.t Spindle.Dep.t = + Spindle.Dep.of_resource "background" + +let alarms : Spindle.Alarm.t Spindle.Dep.t = Spindle.Dep.of_resource "alarms" + +let sign_up = + Spindle.post + Spindle.Path.(s "sign-up") + (Spindle.Returns.empty ~status:`Created ()) + (let+ background = background + and+ alarms = alarms + and+ email = Spindle.body in + Spindle.Background.fork background ~what:"welcome email" (fun () -> + send_welcome_email email); + Spindle.Alarm.set alarms ~key:("reminder:" ^ email) ~after:Mtime.Span.day + ~what:"reminder" (fun () -> send_reminder email); + Ok ()) + +let () = + Eio_main.run @@ fun env -> + Eio.Switch.run @@ fun sw -> + let jobs = Spindle.Background.create ~sw in + let later = + Spindle.Alarm.create ~background:jobs + ~mono_clock:(Eio.Stdenv.mono_clock env) () + in + Spindle.serve env + ~resources: + [ Spindle.Dep.resource background jobs; Spindle.Dep.resource alarms later ] + [ sign_up ] +``` + +Both are made where the program starts and handed to the server as +[resources](../tutorial/dependencies.md#resources), so the route reads them +like any other input. + +## Running a job now + +- Create one with `Background.create ~sw` at startup, then call + `Background.fork t ~what f` from anywhere. It returns at once. +- If `f` raises, the exception is **logged, never raised**, as an `error` on + `spindle.background` naming `what` and the request that forked it. A bug in + a job never takes the server down. +- The fiber is a daemon: it does not keep the process from shutting down. +- It runs on the domain that forked it. + +## Running a job later + +- `Alarm.create ~background ~mono_clock ()`, then + `Alarm.set t ~key ~after ~what f`: run `f` once the span `after` has gone + by, plus the alarm's slack (`Alarm.create ?slack`, 50 ms by default). +- To wake up at an instant -- a deadline kept as a `Ptime.t` -- pass the + wait until it: `~after:(Spindle.until ~now deadline)`, with `now` read in + the handler by `let+ now = Spindle.now`. The wait is zero once the deadline + has passed, so a late alarm fires at once. +- One wake-up per key: setting a key again replaces the earlier one, and + `Alarm.cancel t ~key` drops it. +- Timing uses the monotonic clock, so changing the system time moves nothing. +- An alarm decides *when* to look, not what is true then: when it fires, read + the time and what is due afresh. Alarms live in memory, so a restart + forgets them. diff --git a/agents/pages/guide/client.md b/agents/pages/guide/client.md new file mode 100644 index 0000000..b5a6477 --- /dev/null +++ b/agents/pages/guide/client.md @@ -0,0 +1,157 @@ +# HTTP client + +`Spindle_client` calls other HTTP and HTTPS servers. It is a package of its +own, so a program that only calls out installs and links no framework: + +```sh +opam install spindle-client +``` + +```lisp +(executable + (name main) + (libraries spindle-client eio_main)) +``` + +An application on Spindle has it already: `opam install spindle` installs +it too. + +## Making a request + +```ocaml +let () = + Eio_main.run @@ fun env -> + Spindle_client.run env @@ fun client -> + match Spindle_client.call client `GET "https://example.com/" with + | Ok { status; body; _ } -> + Printf.printf "%d, %d bytes\n" + (Spindle_http.Status.to_int status) + (String.length body) + | Error e -> prerr_endline (Spindle_client.error_to_string e) +``` + +`Spindle_client.run env f` makes a client for as long as `f` runs and closes +its connections when `f` returns. + +`call client meth url` answers `Ok` with the `status` (the same +`Spindle_http.Status.t` variant your routes answer with), the `headers` (names +lower-cased) and the whole `body` -- **any status is an answer**, so a +`` `Not_found `` is `Ok`. `Error` says whether the request went out: +`` `Unsent `` (no connection, bad TLS, a URL it cannot call -- the server never +saw it, so sending it again is safe) or `` `Lost `` (it may have gone, and the +answer was cut short, unreadable, or never came before the deadline -- the +server may have acted on it). Send a +body with `~body` and `~headers`: + +```ocaml +match + Spindle_client.call client ~timeout:Mtime.Span.(10 * s) + ~headers:[ ("content-type", "application/json") ] ~body + `POST "https://api.example.com/v1/things" +with +| Ok { status = `OK; body; _ } -> decode body +| Ok r -> + Error + (Printf.sprintf "upstream answered %d" (Spindle_http.Status.to_int r.status)) +| Error e -> Error (Spindle_client.error_to_string e) +``` + +### A server on a Unix socket + +A server on this machine listening on a Unix socket is named in the URL, +its path percent-encoded as the host, as Docker's SDK names one: + +```ocaml +Spindle_client.call client `GET "http+unix://%2Frun%2Fuser%2F501%2Fapp.sock/health" +``` + +Everything else is as over TCP -- deadlines, kept connections (kept for the +socket), streams, and `ws+unix://` for a WebSocket -- and the request names +`localhost` as its host. A socket that cannot be reached is `` `Unsent ``, +naming its path. `Spindle_mcp_client.create` takes such a URL too. + +## Using a client inside a server + +Make it once, with `Spindle_client.create`, on the application's switch -- +never a request's, since the connections it keeps outlive any one request -- +and supply it to the routes as a +[resource](../tutorial/dependencies.md#resources), which they read with +`let+ client = upstream`: + +```ocaml +let upstream : Spindle_client.t Spindle.Dep.t = + Spindle.Dep.of_resource "upstream" + +let () = + Eio_main.run @@ fun env -> + Eio.Switch.run @@ fun sw -> + let client = + Spindle_client.create ~sw ~net:(Eio.Stdenv.net env) + ~mono_clock:(Eio.Stdenv.mono_clock env) () + in + Spindle.serve env ~resources:[ Spindle.Dep.resource upstream client ] routes +``` + +`create` and `run` take the same options: + +| Option | Default | | +|---|---|---| +| `~timeout` | 30 s | each call's deadline, over the whole call; a call can name its own | +| `~max_body` | 16 MiB | the longest answer read | +| `~per_host` | 4 | idle connections kept per scheme, host and port, on each domain | +| `~idle_timeout` | 15 s | how long an unused connection is kept | +| `~authenticator` | system trust store | what a server's certificate is checked against | + +Each wait is an `Mtime.Span.t`: `~timeout:Mtime.Span.(10 * s)`. + +Good to know: + +- Connections are reused when the answer was read to its end and neither side + said `close`. A call never waits for a free connection; it opens its own. + Limiting how many calls run at once is up to you. +- A request is retried only when that is safe: one that could not be written + on a reused connection, or an idempotent one (`GET`, `HEAD`, `PUT`, + `DELETE`, `OPTIONS`, `TRACE`) whose reused connection closed before any + answer. A `POST` that went out is never sent twice; it fails with + `` `Lost ``, and you decide. +- Each call logs one `debug` line on `spindle-client`, never its headers or + body. + +## Streaming a response + +`Spindle_client.stream` hands your function the `status`, `headers` and a +`body` to read piece by piece -- a streamed model answer, or a download too +large to hold: + +```ocaml +Spindle_client.stream client `GET url (fun response -> + let rec copy () = + match Spindle_client.Body.read response.body with + | Ok (`Data piece) -> print_string piece; copy () + | Ok `End -> Ok () + | Error e -> Error e + in + copy ()) +``` + +`~timeout` bounds the head, and `~read_timeout` each wait for more of the +body. A read that fails is the body's end: every read after it answers the +same error, so waiting longer means a longer `~read_timeout`, not a second +read. To stop early, return: the connection is then closed. + +## Server-Sent Events + +`Spindle_client.events client url f` asks for `text/event-stream` and hands +each event (its `name`, `data`, `id` and `retry_ms`) to `f`, which answers +`` `Continue `` or `` `Stop ``. It answers `Finished` (the server ended it) or +`Stopped`, each with the last event id, or `Answered` with the answer when it +was not an event stream. To reconnect, call it again with +`~last_event_id`. + +## WebSockets and tracing + +- `Spindle_client.websocket` opens a WebSocket: see + [WebSockets](websockets.md#connecting-as-a-client). +- A call made while a request is traced is a span of its trace, and + `Spindle_client.Otlp` sends spans to a collector: see + [Tracing](../tutorial/logging.md#tracing). diff --git a/agents/pages/guide/compression.md b/agents/pages/guide/compression.md new file mode 100644 index 0000000..ff0e0e4 --- /dev/null +++ b/agents/pages/guide/compression.md @@ -0,0 +1,78 @@ +# Compression + +Spindle can gzip its answers. It is off unless you turn it on, since it costs +CPU and the proxy in front of you often compresses already: + +```ocaml +Spindle.serve env ~compress:Spindle.Compress.default routes +``` + +A client that sends `Accept-Encoding: gzip` now gets text, JSON and the like +compressed -- here, a route answering 5,000 bytes of text: + +```console +$ curl -i -H 'accept-encoding: gzip' localhost:8080/big +HTTP/1.1 200 OK +content-type: text/plain; charset=utf-8 +vary: Accept-Encoding +content-encoding: gzip +content-length: 47 +... +``` + +## What is compressed + +`Compress.make ?min_bytes ?level ?types ()` says what is worth it; +`Compress.default` is `make ()`: + +- `min_bytes`: answers smaller than this are sent as they are. Default 1024. +- `level`: deflate's level, 1 to 9. Default 6. +- `types`: media types to compress, as `type/subtype`, `type/*` or + `type/*+suffix`. Default: text, JSON, XML, JavaScript, SVG and event + streams. + +A level outside 1 to 9, a negative `min_bytes`, or a `types` entry that is +none of the three forms raises `Invalid_argument` where it is made. + +An answer is left alone when it sets its own `Content-Encoding`, says +`Cache-Control: no-transform`, or is a range. Every answer of a listed type +says `Vary: Accept-Encoding`, compressed or not, and so does a `304`. + +## Revalidating a compressed answer + +A compressed answer is another representation, so its `ETag` is the route's +with the coding marked inside the quotes: `"v1"` becomes `"v1-gzip"`. A client +sends that tag back, and it works as the route's own: + +- **Your route sees its own tags.** `If-Match` and `If-None-Match` reach it + with the mark taken off, so a route that compares them -- `Static`, + `Files`, or yours -- answers `304` or `412` as it would uncompressed. + `If-None-Match` is unmarked only where the request takes gzip: a client + holding the compressed answer that no longer takes it is answered whole. +- **A `304` repeats the tag the client holds**, `"v1-gzip"`, and the `Vary`. + A route that sets an `ETag` and never reads `If-None-Match` is answered + `304` for the compressed tag all the same. +- **A range is never of the compressed answer**: an `If-Range` holding the + marked tag gets the whole answer, compressed. + +**Streams** are compressed as they go: each `send` reaches the client at once, +decodable on arrival. + +**Files** are never compressed as they are read. `Static` and `Files` serve a +`.br`, `.zst` or `.gz` file your build wrote beside the original instead, +when the client accepts that coding. + +## A route's own policy + +A route's `~compress` is its policy in place of the app's, under the same +name and type. A route that puts a secret in its answer beside text the +request sent -- a CSRF token next to a search term, say -- should not be +compressed, because the compressed length can leak the secret: + +```ocaml +Spindle.get ~compress:Spindle.Compress.none ... +``` + +Its answers then never vary by `Accept-Encoding`, so they carry no `Vary` +for it. The other way round, one route of an app that compresses nothing +can compress its own answers with `~compress:Spindle.Compress.default`. diff --git a/agents/pages/guide/cookies.md b/agents/pages/guide/cookies.md new file mode 100644 index 0000000..a8af656 --- /dev/null +++ b/agents/pages/guide/cookies.md @@ -0,0 +1,302 @@ +# Cookies, sessions and CORS + +Cookies, sessions, and what Spindle checks on a request before your route +runs. + +## Reading and setting cookies + +Declare a cookie once, by name and wiretype description, and use it to read and to set. +This page counts your visits: + +```ocaml +(* A cookie declared once, and used both to read it and to set it: the page + counts your visits. *) + +open Spindle.Syntax + +let visits = Spindle.Cookie.named "visits" Wiretype.int + +let count seen set_cookie = + let n = Option.value seen ~default:0 + 1 in + set_cookie (Spindle.Cookie.make visits n); + Ok (Printf.sprintf "Visit number %d." n) + +let routes = + [ + Spindle.get Spindle.Path.root Spindle.Returns.text + (let+ seen = Spindle.Cookie.optional visits + and+ set_cookie = Spindle.set_cookie in + count seen set_cookie); + ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> Spindle.serve env routes +``` + +```console +$ curl -i -c jar -b jar localhost:8080/ +HTTP/1.1 200 OK +content-type: text/plain; charset=utf-8 +set-cookie: visits=1; Path=/; HttpOnly; SameSite=Lax +... + +Visit number 1. + +$ curl -c jar -b jar localhost:8080/ +Visit number 2. +``` + +- `Cookie.optional` reads it (`None` when absent) and `Cookie.required` + refuses without it. A value that does not read -- one an older deploy + wrote, say -- is absent too, so a stale cookie never locks anyone out. +- `Cookie.make` defaults to `Path=/; HttpOnly; SameSite=Lax`. A plain + cookie lasts until the browser closes unless you give `~max_age_s` + (seconds); a signed or encrypted one is given `Max-Age` from its own + `~max_age` (below). `Cookie.clear` removes one. +- **Spindle adds `Secure` itself** on every host except a loopback one + (`localhost`, `127.0.0.1`, `::1`), where Safari would silently drop a + `Secure` cookie sent over plain http. Behind a proxy that ends TLS, list + the proxy in `~trusted_proxies` so that its word that the browser used + `https` is believed ([below](#the-clients-ip-address)). +- **Any text is a value.** What a cookie cannot hold -- a space, quote, + comma, semicolon, backslash or control character -- is percent-encoded, + and so is `%`, and reading decodes it: `Cookie.make theme "Kim Li"` is + written `theme=Kim%20Li`. A word, a tag or a token keeps its spelling, so + a script reading `document.cookie` sees it as written, and decodes the + rest with `decodeURIComponent`. + +## Signed and encrypted cookies + +Declare a cookie `signed` (readable, but tamper-proof) or `encrypted` +(sealed), then read and set it as any other. The keys they are sealed under +are the server's, given where it starts, so the cookies and the routes that +read them are values like any other: + +```ocaml +let prefs = + Spindle.Cookie.encrypted ~max_age:Mtime.Span.(30 * day) "prefs" prefs_json + +let who = + Spindle.Cookie.signed ~max_age:Mtime.Span.(8 * hour) "who" Wiretype.string + +let () = + match Sys.getenv_opt "COOKIE_SECRET" with + | None -> prerr_endline "COOKIE_SECRET is not set." + | Some secret -> ( + match Spindle.Key.of_secret secret with + | Ok key -> + Eio_main.run @@ fun env -> + Spindle.serve env ~keys:(Spindle.Key.ring key []) routes + | Error sentence -> prerr_endline sentence) +``` + +- **No keys, no start.** A route that reads a signed or encrypted cookie in + a server given no `~keys` stops it before it listens, naming the route; + one that only sets such a cookie is answered `500`, logged. A test gives + its own: `Spindle.Test.app ~keys routes`. +- `Key.of_secret` answers `Error` for a secret under 32 bytes. Read the + secret yourself, at startup. +- **Rotating a key:** `Key.ring newest retired` signs with `newest` and reads + with any, so put the new key first and the old one after it. +- **A cookie that fails its signature, its seal or its age is absent** + (`None`), never an error. +- **`~max_age` is required**, an `Mtime.Span.t`. The server checks it on + every read, not only the browser, so a copied cookie stops working when it + expires. `Cookie.make` writes it as `Max-Age`, rounded up to whole + seconds; passing `~max_age_s` to `make` can make that shorter, never + longer. +- **A signed or encrypted cookie holds any value its description writes**, since + what is sent is encoded as base64url, as a plain cookie holds any text, + percent-encoded. +- `Key.sign`/`Key.verify` and `Key.seal`/`Key.unseal` do the same for + anything else, such as a token in a link; a handler reads the server's + ring as `Spindle.keys`. They use keys derived apart from the cookies' + keys, so nothing you sign or seal with them can ever be passed off as a + cookie. + +## Sessions + +`Spindle.Session` keeps a visit's data on the server; its cookie holds only +a random id. A session is a [dependency](../tutorial/dependencies.md): a +route reads it, and is handed the session its request's cookie names. + +```ocaml +(* A session kept on the server: signing in keeps who you are, the page says + it back, and signing out ends it. The cookie holds only a random id. + + Signing in rotates the id, so one somebody planted in the browser before + signs nobody in after; signing out deletes the session, so a copy of the + cookie signs nobody in either. + + curl -c jar -b jar -X POST localhost:8080/sign-in/kim + curl -c jar -b jar localhost:8080/me + curl -c jar -b jar -X POST localhost:8080/sign-out *) + +open Spindle.Syntax + +type visit = { user : string } [@@deriving wiretype] + +(* Kept in this process's memory, and in the database with + Spindle_sqlite.Session.store or Spindle_postgres.Session.store. *) +let session = + Spindle.Session.create + ~store:(Spindle.Dep.return (Spindle.Session.memory ())) + ~idle:Mtime.Span.(14 * day) + ~absolute:Mtime.Span.(90 * day) + visit_json + +let user = Spindle.Path.string "user" + +let routes = + [ + Spindle.post + Spindle.Path.(s "sign-in" / user) + Spindle.Returns.text + (let+ user = Spindle.param user and+ session = session in + let* () = Spindle.Session.rotate session in + let* () = Spindle.Session.put session { user } in + Ok "Signed in.\n"); + Spindle.get + Spindle.Path.(s "me") + Spindle.Returns.text + (let+ session = session in + let* visit = Spindle.Session.get session in + match visit with + | Some { user } -> Ok (Printf.sprintf "You are %s.\n" user) + | None -> Ok "Nobody is signed in.\n"); + Spindle.post + Spindle.Path.(s "sign-out") + Spindle.Returns.text + (let+ session = session in + let* () = Spindle.Session.destroy session in + Ok "Signed out.\n"); + ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> Spindle.serve env routes +``` + +```console +$ curl -c jar -b jar -X POST localhost:8080/sign-in/kim +Signed in. + +$ curl -c jar -b jar localhost:8080/me +You are kim. + +$ curl -c jar -b jar -X POST localhost:8080/sign-out +Signed out. + +$ curl -c jar -b jar localhost:8080/me +Nobody is signed in. +``` + +| Call | What it does | +|---|---| +| `get` | the session's data, if its cookie names one within both limits | +| `put` | replaces the data, or starts a session holding it, with its cookie | +| `rotate` | moves the session to a new id, keeping its data: at sign-in | +| `destroy` | deletes the session and clears its cookie: sign-out | + +Each answers a `result` whose `Error` is a refusal: a store that fails is a +`500`, its words in the log and none on the wire, so each call goes on with +`let*` beside the handler's own. + +- **Sign-in rotates**, so an id somebody planted in the browser before + signs them into nothing after. `rotate` and `put` end in the same place + in either order, and `rotate` with no session does nothing. +- **A session is the request's.** Every use of it in one request is the + same session, so what a `put` wrote a later `get` reads, and the store is + asked once. +- **A session ends** `idle` after it was last used, or `absolute` after it + began, whichever comes first, on the request's clock. The cookie is named + `session` unless you pass `~cookie`, and its `Max-Age` is `absolute`, + rounded up to whole seconds. +- **Ended sessions are swept for you.** Nobody comes back for a session + that ended, so the first request to read one ten minutes after the last + sweep deletes a batch of them, and the next request another while there + are more: the store never fills with old visits, and no request waits on + more than a batch. Several servers on one database share the work. +- **Where it is kept** is `~store`, a dependency like any other. + `Session.memory ()` lives in one process and ends with it. + `Spindle_sqlite.Session.store db`, or `Spindle_postgres.Session.store + db`, keeps sessions in your database, read through the pool's + [resource](../tutorial/dependencies.md#resources): + + ```ocaml + let session = + Spindle.Session.create + ~store:(Spindle_sqlite.Session.store db) + ~idle:Mtime.Span.(14 * day) + ~absolute:Mtime.Span.(90 * day) + visit_json + ``` + + Its table, `spindle_sessions`, is a migration the package installs, + applied with `rowtype-migrate up --source spindle-sqlite` (or + `spindle-postgres`) before the server starts + ([Databases](databases.md)). + +## The client's IP address + +`Spindle.client_ip` is the address of whoever connected. Behind a reverse +proxy, list the proxy in `Spindle.serve ~trusted_proxies` (addresses or +CIDR ranges, such as `10.0.0.0/8`; none by default), and the client is the +address the proxy forwarded for. `~proxy_header` names the header it writes: +`X_forwarded_for` (the default) or `Forwarded`. The same header gives the +host and whether the browser used `https`. + +## CSRF and CORS + +- **Cross-site writes are refused by default.** A request by any method but + `GET`, `HEAD` and `OPTIONS` that a browser sent from another site is + `403 cross_origin`. Requests from curl, apps and other servers pass. + `~trusted_origins` allows other sites; `~check_origin:false` turns the + check off. +- **`Spindle.json` accepts only JSON:** a body whose `Content-Type` is not + `application/json` (or `application/...+json`) is `415`. +- **Another site's page may call your routes only if you allow it:** + + ```ocaml + Spindle.serve env + ~cors: + (Spindle.Cors.origins ~credentials:true [ "https://app.example.com" ]) + routes + ``` + + Spindle answers the preflight itself and names an allowed origin in + `Access-Control-Allow-Origin`, or answers `*` under `Spindle.Cors.any ()`, which allows no cookies; an origin you + did not allow is told nothing. An allowed origin also passes the forgery + check. + + - `~allow_headers` lists the headers a request may send: `authorization` + and `content-type` unless you say otherwise. A page that sends any + other header fails the preflight, and the browser says only that the + request was blocked. + - `~expose` lists the response headers the page's script may read (none + by default). + - `~max_age_s` is how long a browser keeps a preflight's answer (600 + seconds). + + A route's `~cors` is its policy in place of the app's, so an API can + allow a site while the pages allow none. Routes that share a policy + share a maker: + + ```ocaml + let app_site = + Spindle.Cors.origins ~credentials:true [ "https://app.example.com" ] + + let api_get = Spindle.get ~cors:app_site + let api_post = Spindle.post ~cors:app_site + ``` + + `~cors:Spindle.Cors.none` on a route allows no site under an app that + allows one. + + `Spindle.Cors.any ()` takes no `~credentials`: a policy letting every site + act as the signed-in person does not compile. Under `Cors.any ()`, a write + from another site passes only with no credential the browser attaches by itself: no + `Cookie`, and no `Authorization` in a scheme a browser keeps -- `Basic`, + `Digest`, `Negotiate`, `NTLM`. A token the page sets itself, such as + `Authorization: Bearer ...`, is served. diff --git a/agents/pages/guide/databases.md b/agents/pages/guide/databases.md new file mode 100644 index 0000000..1695471 --- /dev/null +++ b/agents/pages/guide/databases.md @@ -0,0 +1,238 @@ +# Databases + +`spindle-sqlite` and `spindle-postgres` wire a database into a server: a +pool, a readiness check, metrics, sessions, and the refusal a failure +answers. Both have the same calls, under `Spindle_sqlite` and +`Spindle_postgres`. The [Database](../tutorial/database.md) tutorial walks +through them on SQLite. + +## Running statements + +The routes read the pool through a resource, made once: + +```ocaml +let db : Spindle_sqlite.Pool.t Spindle.Dep.t = Spindle.Dep.of_resource "database" +``` + +| Call | Runs | +|---|---| +| `Pool.exec pool statement params` | one statement on a borrowed connection | +| `Pool.transaction pool (fun db -> ...)` | one transaction: `Ok` commits, `Error` rolls back | +| `Pool.use pool (fun db -> ...)` | several statements on one connection, outside a transaction | + +Inside `transaction` and `use`, a statement is `Rowtype_sqlite.run db +statement params`, or `Rowtype_postgres.run` on Postgres. `refusal` turns a +failure into an answer: a busy or closed pool and a lock held past its +wait are `503`, anything else `500`. + +## SQLite + +### Install + +```sh +opam install spindle-sqlite rowtype-migrate +``` + +```lisp +(libraries spindle spindle-sqlite rowtype rowtype-sqlite eio_main) +``` + +### The pool + +```ocaml +let () = + Eio_main.run @@ fun env -> + Spindle_sqlite.Pool.run env "app.db" @@ fun pool -> + Spindle.serve env ~resources:[ Spindle.Dep.resource db pool ] routes +``` + +`Pool.run` opens every connection before the server listens, and puts the +file in WAL mode, so a read never waits on a write. SQLite keeps +`app.db-wal` and `app.db-shm` beside the file while it is open. A file that +cannot be opened stops the program, saying why. `Pool.create ~sw +~mono_clock file` answers a `result` instead. + +| Option | Default | | +|---|---|---| +| `~size` | 8 | connections, all opened at start-up | +| `~wait` | 5 s | a borrow waiting longer is `` `Pool `Busy ``, a `503` | +| `~timeout` | 5 s | a statement waiting longer for another's write lock is `` `Not_serializable ``, a `503` | + +The durations are `Mtime.Span.t`s, written `Mtime.Span.(2 * s)`. A pool in +memory, `":memory:"`, is refused, since each connection would have a +database of its own. + +### Transactions + +`Pool.transaction` takes `~behaviour`, when it takes the write lock: + +- `Deferred`, the default, at its first write. +- `Immediate`, as it begins, for a transaction that reads and then writes. +- `Exclusive`, as it begins, keeping readers out too outside WAL mode. + +`~retries:3` runs the whole transaction again when it meets +`` `Not_serializable ``, so keep anything that is not a statement out of the +work. `~keep` commits an `Error` it names. A unique key refused is a +`` `Conflict `` naming its columns, `users.email`. + +### Migrations + +```sh +rowtype-migrate create --url sqlite:app.db # once, makes the file +rowtype-migrate up --url sqlite:app.db # before each start +rowtype-migrate status --url sqlite:app.db --check +rowtype-migrate dump --url sqlite:app.db # the schema the migrations make +``` + +### Sessions + +`Spindle_sqlite.Session.store db` keeps +[sessions](cookies.md#sessions) in the table +`spindle_sessions`, made by the migration the package ships: + +```sh +rowtype-migrate up --source spindle-sqlite --url sqlite:app.db +``` + +`Session.store ~table db` reads a table of your own, made by a migration of +yours from `Session.schema ~table`. + +## Postgres + +### Install + +```sh +opam install spindle-postgres rowtype-migrate +``` + +```lisp +(libraries spindle spindle-postgres rowtype rowtype-postgres eio_main) +``` + +To try it, a throwaway Postgres in Docker, deleted when it stops: + +```sh +docker run --rm -p 5432:5432 -e POSTGRES_PASSWORD=postgres postgres:18-alpine +``` + +### The pool + +`Pool.run` takes a connection string, a `postgres://` URL or a keyword +list: + +```ocaml title="sql_postgres.ml" +(* The same on Postgres: a pool of its connections, and a route that runs a + statement on it -- / answers the names of the databases on the server. + + docker run --rm -p 5432:5432 -e POSTGRES_PASSWORD=postgres postgres:18-alpine + dune exec examples/sql_query.exe *) + +let database = "postgres://postgres:postgres@localhost:5432/postgres" + +(* The pool makes every connection at once, so a database that refuses is a + server that does not start. *) +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> + Spindle_postgres.Pool.run env database @@ fun pool -> + Spindle.serve env + ~resources:[ Spindle.Dep.resource Databases_routes.db pool ] + Databases_routes.routes +``` + +```console +$ dune exec examples/sql_postgres.exe +$ curl localhost:8080/ +["postgres","template0","template1"] +``` + +The route it serves + +```ocaml title="databases_routes.ml" +(* The route sql_postgres serves: the names of the databases on the server, + read through the pool. *) + +open Spindle.Syntax +module S = Rowtype + +let databases = + S.list ~params:S.unit ~row:S.text + "select datname from pg_database order by datname" + +(* A borrow that waits past the pool's limit is [`Pool `Busy], which [refusal] + answers 503: an overloaded server says so rather than answering late. *) +let list_databases pool = + Spindle_postgres.Pool.exec pool databases () + |> Result.map_error Spindle_postgres.refusal + +(* The pool, as the routes read it: supplied where the server starts. *) +let db : Spindle_postgres.Pool.t Spindle.Dep.t = + Spindle.Dep.of_resource "database" + +let routes = + [ + Spindle.get Spindle.Path.root + (Spindle.Returns.json (Wiretype.list Wiretype.string)) + (let+ pool = db in + list_databases pool); + ] +``` + +`Pool.run` opens every connection before the server listens. A database +that cannot be reached stops the program, saying why. `Pool.create ~sw ~net +~mono_clock target` answers a `result` instead, its `target` read by +`Rowtype_postgres.Conninfo.of_string`. + +Every connection is bounded, so one bad query cannot hold a connection and +its locks for ever: + +| Option | Default | | +|---|---|---| +| `~statement_timeout` | 10 s | a statement running longer is ended by Postgres | +| `~idle_in_transaction_timeout` | 30 s | so is a transaction left open and idle | +| `~size` | 8 | connections, all opened at start-up | +| `~wait` | 5 s | a borrow waiting longer is `` `Pool `Busy ``, a `503` | +| `~parameters` | none | settings for each connection, `[ ("application_name", "shop") ]`, which win over the framework's | +| `~statement_cache` | the driver's | `0` behind a pooler that cannot carry named statements | + +Connecting waits 10 s for each address unless the connection string says +`connect_timeout`. The two bounds reach Postgres in whole milliseconds, +rounded up, and a span of zero lifts one. + +### Transactions + +`Pool.transaction` takes `~isolation`. At `~isolation:Serializable`, +`~retries:3` runs the transaction again when Postgres reports a conflict +with a concurrent one. A unique key refused is a `` `Conflict `` naming the +constraint, `users_email_key`, whether a statement found it or a +`DEFERRABLE` constraint refused the `COMMIT`. `refusal` answers +`` `Unsent ``, a database not reached, with a `503` too. + +### Migrations + +```sh +rowtype-migrate create --url postgres://app@db/shop # once +rowtype-migrate up --url postgres://app@db/shop # before each start +``` + +### Sessions + +`Spindle_postgres.Session.store db` keeps +[sessions](cookies.md#sessions) in the table +`spindle_sessions`, made by the migration the package ships: + +```sh +rowtype-migrate up --source spindle-postgres --url postgres://app@db/shop +``` + +## Health and metrics + +```ocaml +Spindle.Health.routes [ Spindle_sqlite.Pool.check db ] +Spindle_sqlite.Pool.measure pool metrics +``` + +`check` borrows a connection and runs `select 1`, and passes without one +while every connection is lent. `measure` reports the pool's connections, +named `sqlite` or `postgres` unless given `~name` ([Health +checks](health.md), [Metrics](metrics.md)). diff --git a/agents/pages/guide/domains.md b/agents/pages/guide/domains.md new file mode 100644 index 0000000..d2ccfb9 --- /dev/null +++ b/agents/pages/guide/domains.md @@ -0,0 +1,108 @@ +# Multicore and shared state + +Spindle serves on every core: by default it runs +`Domain.recommended_domain_count ()` domains, and your handlers run on all of +them in parallel. So anything a handler touches must be one of: + +- **Immutable after startup** -- the app, its routes, whatever you loaded + before the server started. +- **Safe from any domain** -- an `Atomic` for a count, an `Eio.Stream` or + `Eio.Promise` to hand values across, an `Eio.Mutex` around a table. Hold a + mutex only around the table itself, never across a database call or a write + to a client: every other domain waits behind it. + +If your application's state is not safe from several domains, serve it on +one, with `~domains:1`. Fibers then switch only at an effect, so code between +two effects needs no lock. + +## Shared state: a lock, or one domain + +Each visit to `/pages/` counts one, in a `Hashtbl` behind an +`Eio.Mutex`; with `--one-domain` it runs on one domain with no lock: + +```ocaml +(* A table every request writes: the visits to each page. + + A request runs on any of the server's domains, beside the others, so a + table they all write is behind a lock -- an [Eio.Mutex], which parks the + fiber waiting for it rather than its whole domain, held across nothing + but the table, never across a write to a client or a call to a database. + + A [Hashtbl] with neither a lock nor one domain is not a crash in OCaml 5 + but it is no table either: two domains adding at once lose one of the + writes, a lookup on one domain sees the other's resize half done and + finds nothing where something is, and a resize that meets another raises + from inside the table. None of it shows on a laptop's first try. + + A server that must not lock runs on one domain, [~domains:1], where a + fiber gives way only at an effect and a table touched between two needs + nothing: [--one-domain] below. The middleware example keeps a single number, + which is an [Atomic]; a table is not a number. + + dune exec examples/multidomain.exe + curl localhost:8080/pages/home + dune exec examples/multidomain.exe -- --one-domain *) + +open Spindle.Syntax + +let visits : (string, int) Hashtbl.t = Hashtbl.create 16 +let lock = Eio.Mutex.create () + +let visit page = + let n = 1 + Option.value (Hashtbl.find_opt visits page) ~default:0 in + Hashtbl.replace visits page n; + n + +let page_name = Spindle.Path.string "page" +let path = Spindle.Path.(s "pages" / page_name) + +let locked = + Spindle.get path Spindle.Returns.text + (let+ page = Spindle.param page_name in + let n = Eio.Mutex.use_rw ~protect:false lock (fun () -> visit page) in + Ok (Printf.sprintf "%s: visit number %d\n" page n)) + +let unlocked = + Spindle.get path Spindle.Returns.text + (let+ page = Spindle.param page_name in + Ok (Printf.sprintf "%s: visit number %d\n" page (visit page))) + +let () = + Spindle.Log.setup (); + let one_domain = Array.exists (String.equal "--one-domain") Sys.argv in + Eio_main.run @@ fun env -> + if one_domain then Spindle.serve env ~domains:1 [ unlocked ] + else Spindle.serve env [ locked ] +``` + +```sh +dune exec examples/multidomain.exe +``` + +or, on one domain with no lock: + +```console +$ dune exec examples/multidomain.exe -- --one-domain + +$ curl localhost:8080/pages/home +home: visit number 1 + +$ curl localhost:8080/pages/home +home: visit number 2 +``` + +A `Hashtbl` with neither a lock nor one domain loses writes, misses entries +that are there, and can raise from inside a resize -- and none of it shows on +a laptop's first try. + +## Domains and background work + +- A connection stays on the domain that accepted it, for its whole life. +- Work forked from a handler -- `Background`, `Alarm` -- runs on that + handler's domain, on its switch, `Spindle.Local.switch ()`. Outside a + server (startup code, a test), `Spindle.Local.within ~sw f` sets one. +- `Spindle.blocking f` runs `f` on a system thread, for a library that blocks. + Inside `f`, perform no Eio effect and touch nothing a fiber owns. +- Spindle raises each domain's minor heap to a million words (8 MB) so that + requests in flight are collected young. It never lowers it: + `OCAMLRUNPARAM=s=4M` asks for four million words. diff --git a/agents/pages/guide/health.md b/agents/pages/guide/health.md new file mode 100644 index 0000000..832acb2 --- /dev/null +++ b/agents/pages/guide/health.md @@ -0,0 +1,100 @@ +# Health checks + +`Spindle.Health.routes` adds the two routes an orchestrator or a load +balancer probes: + +- **`GET /livez`** runs no check: it answers `ok` while the process can + answer at all. A database outage should not get every instance restarted. +- **`GET /readyz`** runs every check, side by side, and answers `ok`, or + `503 not_ready` naming the checks that failed. Point a platform that + probes only one path here. + +```ocaml +let routes = app_routes @ Spindle.Health.routes [ Spindle_sqlite.Pool.check db ] + +let () = + Eio_main.run @@ fun env -> + Spindle_sqlite.Pool.run env "app.db" @@ fun pool -> + Spindle.serve env ~resources:[ Spindle.Dep.resource db pool ] routes +``` + +`Pool.check db` reads the pool as your routes do, through the +[resource](../tutorial/dependencies.md#resources) `db`, so the probes are +routes like the rest, made before the pool is. It borrows a connection and +runs `select 1`. A pool whose +connections are all busy passes without waiting; a closed one fails. +`Spindle_postgres.Pool.check db` is the same for Postgres. + +## Custom checks + +A check is `Spindle.Health.check name f`, where `f` is a +[dependency](../tutorial/dependencies.md) giving the function a probe +runs, which answers `Ok ()` or `Error why`. A check that reads nothing is +`Spindle.Dep.return (fun () -> ...)`; one that reads what the application +holds reads it as a route does: `Spindle.Health.check "cache" (let+ cache = +cache in fun () -> Cache.ping cache)`. Return `Error`, never raise: a check +that raises is a bug, and is answered `500`, not `503 not_ready`. This +server is taken out of service while a file named `maintenance` exists: + +```ocaml +(* The probes: /livez answers for as long as the process can, and /readyz + only while every check passes. The check here is the application's own: + a file named [maintenance] takes the server out of service, so a load + balancer sends it nobody until the file is gone. + + curl -i localhost:8080/readyz 200 + touch maintenance + curl -i localhost:8080/readyz 503 not_ready + curl -i localhost:8080/livez 200 all along *) + +let hello = Ok "Hello." + +let in_service = + Spindle.Health.check "maintenance" + (Spindle.Dep.return (fun () -> + if Sys.file_exists "maintenance" then + Error "the maintenance file is there" + else Ok ())) + +let routes = + Spindle.get Spindle.Path.root Spindle.Returns.text (Spindle.Dep.return hello) + :: Spindle.Health.routes [ in_service ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> Spindle.serve env routes +``` + +```console +$ curl localhost:8080/readyz +ok + +$ touch maintenance + +$ curl -i localhost:8080/readyz +HTTP/1.1 503 Service Unavailable +content-type: application/json +... + +{"error":"not_ready","message":"Not ready: maintenance."} + +$ curl localhost:8080/livez +ok +``` + +The answer names only the check; `why` goes to the log, as a `warn` line: +`not ready: maintenance: the maintenance file is there`. + +Good to know: + +- The framework sets no timeout on a check. A check that waits on something + bounds its own wait (the pool has its borrow wait and statement timeout), + and the prober sets how long it waits. +- A stopping server refuses new connections, so probes fail without any + check. +- Probes are logged at `debug`, since something asks every few seconds. +- `~live` and `~ready` move the routes to other paths: + `Spindle.Health.routes ~live:Spindle.Path.(s "healthz") checks`. +- Both are public unless you guard them, as `/metrics` is. `~guard` is a + `unit Dep.t` run first, whose refusal is the answer: + `Spindle.Health.routes ~guard:only_the_cluster checks`. diff --git a/agents/pages/guide/mcp.md b/agents/pages/guide/mcp.md new file mode 100644 index 0000000..8ae77a7 --- /dev/null +++ b/agents/pages/guide/mcp.md @@ -0,0 +1,579 @@ +# MCP servers + +Give an agent tools to call, and resources to read. `spindle-mcp` serves the +[Model Context Protocol](https://modelcontextprotocol.io/specification/2026-07-28), +revision 2026-07-28, over HTTP: one `POST` endpoint, added to your routes as +[health checks](health.md) are. + +```sh +opam install spindle-mcp +``` + +## A tool + +```ocaml title="forecast_tool.ml" +(* The tool mcp serves: the weather for a city. *) + +open Spindle.Syntax + +type query = { city : string } [@@deriving wiretype] +type forecast = { city : string; celsius : int } [@@deriving wiretype] + +(* What the tool reads: something the server holds, supplied as it starts. *) +let weather : (string -> int option) Spindle.Dep.t = + Spindle.Dep.of_resource "weather" + +let no_such_city = + Spindle.Refusal.Code.make "no_such_city" ~status:`Not_found + ~doc:"No forecast for that city." + +let get_forecast = + Spindle_mcp.tool "get_forecast" ~title:"Forecast" + ~doc:"Today's temperature in a city, in degrees Celsius." query_json + forecast_json + (let+ weather = weather in + fun (q : query) -> + match weather q.city with + | Some celsius -> Ok { city = q.city; celsius } + | None -> + Error (Spindle.Refusal.make no_such_city "There is no such city.")) +``` + +A tool is a name, the description of its arguments, the description of its +result, and a [dependency](../tutorial/dependencies.md) giving the +function a call runs -- as a health check is a name and a dependency giving +the function a probe runs. + +- The arguments' description is printed as the tool's `inputSchema`, and + must be an object; the result's as its `outputSchema`. Nothing else + states them. +- The function's `Ok` is the result: `structuredContent`, and its JSON as + text beside it. Its `Error` is a result too, `isError`, with the + refusal's sentence: the model reads it and can try again. So are + arguments that do not read, with every problem named. +- `~title` is for a person, `~doc` for the model. + +## Serving it + +```ocaml title="mcp.ml" +(* An MCP server: one tool an agent calls, the weather for a city, added to + the application's routes as health checks are. Point an MCP client at + http://localhost:8080/mcp. + + curl -X POST localhost:8080/mcp \ + -H 'content-type: application/json' \ + -H 'mcp-protocol-version: 2026-07-28' -H 'mcp-method: tools/list' \ + -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{ + "io.modelcontextprotocol/protocolVersion":"2026-07-28", + "io.modelcontextprotocol/clientCapabilities":{}}}}' *) + +let routes = + Spindle_mcp.routes ~name:"weather" ~version:"1.0.0" + [ Forecast_tool.get_forecast ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> + let temperatures city = List.assoc_opt city [ ("Paris", 18); ("Oslo", 4) ] in + Spindle.serve env + ~resources:[ Spindle.Dep.resource Forecast_tool.weather temperatures ] + routes +``` + +`Spindle_mcp.routes` is `POST /mcp` (or `~path`), serving +`server/discover`, `tools/list` and `tools/call` -- and, given +[resources](#resources) and [`~changes`](#watching-a-resource), the methods +that read and watch them: + +```console +$ curl -X POST localhost:8080/mcp -H 'content-type: application/json' \ + -H 'mcp-protocol-version: 2026-07-28' -H 'mcp-method: tools/call' \ + -H 'mcp-name: get_forecast' \ + -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_forecast", + "arguments":{"city":"Paris"},"_meta":{"io.modelcontextprotocol/protocolVersion": + "2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}' +{"jsonrpc":"2.0","id":1,"result":{"resultType":"complete","content":[{"type":"text", +"text":"{\"city\":\"Paris\",\"celsius\":18}"}],"structuredContent":{"city":"Paris", +"celsius":18},"isError":false,"_meta":{"io.modelcontextprotocol/serverInfo": +{"name":"weather","version":"1.0.0"}}}} +``` + +Every tool's dependency is read on every call, as every health check's is on +every probe, so the endpoint reads the same on every request: what it reads +is listed, the resources its tools read are checked as the server starts, +and a server missing one does not start. So: + +- **A tool's dependency hands over what the server holds** -- a pool, a + client -- and its function does the work. +- **A tool's dependency's refusal is that tool's alone.** One that refuses -- + nobody signed in, for a tool that reads the caller -- is that tool's error, + `isError` with the refusal's sentence, when it is called, and every other + tool is called as before. +- **What refuses for the whole endpoint is `~guard`**, read first, its + refusal the answer to every request: + + ```ocaml + Spindle_mcp.routes ~name ~version + ~guard:(Spindle.Rate.limit calls ~key:Spindle.client_ip) + tools + ``` + +## Progress, and a caller that left + +A tool that takes a while tells the caller how far it has come, and stops +when nobody is waiting any more: + +```ocaml +let export = + Spindle_mcp.tool "export" query_json report_json + (let+ db = Db.pool + and+ call = Spindle_mcp.call + and+ gone = Spindle.client_gone in + fun query -> + Export.run db query + ~progress:(fun n total -> Spindle_mcp.progress call ~total n) + ~stop:gone) +``` + +- `Spindle_mcp.call` is this call, read as `Spindle.now` is. + `Spindle_mcp.progress call n` reports `n`, of `~total` where it is known, + with a `~message` for a person. +- A client that asked for progress is answered as an event stream: each + report as it is made, then the result. One that did not is answered as + before, and the reports are dropped, so the tool is written once. +- A report not above the last is dropped, as MCP has each one larger. +- A client that cancels closes the stream. `Spindle.client_gone` resolves + once the server learns it -- at the first report it cannot write -- and + the tool stops where it can: nothing cuts it off mid-write. + +## Asking before acting + +A tool that deletes, pays or sends asks the person first: + +```ocaml +type confirm = { ok : bool } [@@deriving wiretype] + +let sure = + Spindle_mcp.Question.form "confirm" + ~message:"Delete the folder and all it holds?" confirm_json + +let delete = + Spindle_mcp.tool "delete_folder" ~asks:[ Spindle_mcp.Question.declare sure ] + folder_json Wiretype.string + (let+ db = Db.pool and+ call = Spindle_mcp.call in + fun folder -> + match Spindle_mcp.answer call sure with + | Accept { ok = true } -> Folder.delete db folder + | Accept _ | Decline | Cancel -> Ok "Nothing was deleted.") +``` + +- A question is a form: an object of strings, numbers, integers, booleans + and enums, which the client shows the person. `Spindle_mcp.routes` + raises `Invalid_argument` for any other. +- A tool's questions are asked before its function runs. A call without + their answers is answered "input required", every question at once; the + client asks the person and calls again with the answers, as MCP + 2026-07-28 has it. So the function always has its answers: + `Accept` what they filled in, `Decline`, or `Cancel` if they dismissed it. +- A client that cannot show a form is told so before anything runs. +- Claude Code shows the question, and calls again with your answer. + +## Tokens and scopes + +With `~auth`, every call needs an [OAuth bearer token](oauth.md), +and a tool may need a scope: + +```ocaml +let forecast = + Spindle_mcp.tool "get_forecast" ~scope:"weather:read" query_json + forecast_json (...) + +let routes = + let served = Spindle_mcp.routes ~auth ~name ~version [ forecast ] in + served @ [ Spindle.Bearer.metadata auth served ] +``` + +- `tools/list` names only the tools the token grants, so a model is never + shown one it cannot call; a call of one it lacks is a `403` + `insufficient_scope` naming the scope, so the client can ask for it. +- The metadata document names every tool's and resource's scope in + `scopes_supported`. + +## Who may do what + +A scope says what the *client* may do. Which notes the *person* behind the +token may delete is a [policy's](access.md), checked in the +tool as in a route. A tool's arguments name the object, so it is judged by +`Access.check`: + +```ocaml +let delete_note = + Spindle_mcp.tool "delete_note" note_ref Wiretype.string + (let+ checked = Spindle.Access.check notes and+ db = conn in + fun r -> + let* note = find db r.id in + let* note = checked Delete note in + remove db note) +``` + +- The caller is the person the token was issued for -- your `principal` + reads its subject -- never the client calling for them, so an agent may do + what its person may and nothing more. +- A denial is the tool's error, which the model reads, and is logged as a + route's is. +- Every tool's dependency is read on every call, and one that refuses -- + nobody signed in, for a tool that reads the caller -- is that tool's error + when it is called, and no other tool's. + +## Resources + +A tool is something a client asks the server to do; a resource is something +it reads -- a file, a record, a log. A resource is a URI, a name and a +dependency giving the function that reads it; a template is every resource +whose URI it matches, its variables handed to the function: + +```ocaml title="journal.ml" +(* The resource mcp_journal serves: a journal an intent, numbered lines from 1, + appended and never changed, read from a line on. *) + +open Spindle.Syntax + +type t = { lock : Eio.Mutex.t; journals : (string, string list) Hashtbl.t } +(* each journal newest line first *) + +let create () = { lock = Eio.Mutex.create (); journals = Hashtbl.create 16 } + +let append t id line = + Eio.Mutex.use_rw ~protect:true t.lock (fun () -> + let lines = Option.value (Hashtbl.find_opt t.journals id) ~default:[] in + Hashtbl.replace t.journals id (line :: lines)) + +(* The lines from [from] on, oldest first; [None] for a journal never begun. *) +let lines t id ~from = + Eio.Mutex.use_ro t.lock (fun () -> + Option.map + (fun newest_first -> + List.filteri (fun i _ -> i + 1 >= from) (List.rev newest_first)) + (Hashtbl.find_opt t.journals id)) + +let begun t id = Eio.Mutex.use_ro t.lock (fun () -> Hashtbl.mem t.journals id) + +(* What the template reads: the journals, which the server holds. *) +let journals : t Spindle.Dep.t = Spindle.Dep.of_resource "journals" + +(* A line a content, so a reader counts what it was given. A read with no + [from] answers no line: it is what a listen makes to check a caller may + read the journal, and should cost nothing. *) +let journal = + Spindle_mcp.template "haf://intents/{id}/journal{?from}" ~name:"journal" + ~doc:"An intent's journal, one JSON event a line, from line [from] on." + ~mime:"application/json" ~ttl_ms:0 + Spindle_mcp.Template.( + let+ id = required "id" Wiretype.string + and+ from = optional "from" (Wiretype.int_bounded ~min:1 ()) in + (id, from)) + (let+ journals = journals in + fun (id, from) -> + match from with + | None -> + if begun journals id then Ok [] else Error Spindle.Refusal.not_found + | Some from -> ( + match lines journals id ~from with + | Some lines -> Ok (List.map (fun l -> Spindle_mcp.Text l) lines) + | None -> Error Spindle.Refusal.not_found)) +``` + +```ocaml title="mcp_journal.ml" +(* An MCP server of resources: a journal an intent, offered as a template a + client reads from a line on, and told to a client watching it as each line + is written. + + curl -X POST localhost:8080/mcp \ + -H 'content-type: application/json' \ + -H 'mcp-protocol-version: 2026-07-28' -H 'mcp-method: resources/read' \ + -H 'mcp-name: haf://intents/0197/journal?from=1' \ + -d '{"jsonrpc":"2.0","id":1,"method":"resources/read","params":{ + "uri":"haf://intents/0197/journal?from=1","_meta":{ + "io.modelcontextprotocol/protocolVersion":"2026-07-28", + "io.modelcontextprotocol/clientCapabilities":{}}}}' *) + +let id = "0197" +let uri = "haf://intents/" ^ id ^ "/journal" + +(* A line a second, each told to whoever watches the journal. *) +let rec write ~clock journals changes n = + Journal.append journals id (Printf.sprintf {|{"event":"tick","n":%d}|} n); + Spindle_mcp.Changes.updated changes uri; + Eio.Time.Mono.sleep_span clock Mtime.Span.(1 * s); + write ~clock journals changes (n + 1) + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> + let journals = Journal.create () + and changes = Spindle_mcp.Changes.create () in + let routes = + Spindle_mcp.routes ~name:"haf" ~version:"1.0.0" + ~resources:[ Journal.journal ] ~changes [] + in + (* A listen never ends on its own: a server that is stopping ends each, + gracefully, so its client knows not to listen again. *) + Eio.Fiber.first + (fun () -> write ~clock:(Eio.Stdenv.mono_clock env) journals changes 1) + (fun () -> + Spindle.serve env + ~resources:[ Spindle.Dep.resource Journal.journals journals ] + ~on_stop:(fun () -> Spindle_mcp.Changes.close changes) + routes) +``` + +- `Spindle_mcp.resource uri ~name f` is one resource, listed by + `resources/list`. `Spindle_mcp.template text ~name variables f` is a + template, listed by `resources/templates/list`. Both are read by + `resources/read`, and given to `routes` as `~resources`. +- A template is the part of RFC 6570 that reads back from a URI one way: + `{name}`, one segment, never across a `/`, and a form-style query last, + `{?from,to}`, each of whose variables may be left out. `routes` raises + `Invalid_argument` for any other expression. +- Each variable is read by its own description, as a query parameter is: + `Template.required` for one every URI holds, `Template.optional` for a + query's that may be absent. A URI whose variables do not read is + `-32602`, naming each problem. +- The function answers its contents: `Text` as it is, or `Blob` bytes, sent + as base64, each with the URI read and the resource's `~mime`. +- `~ttl_ms` is how long a client may keep what it read, in place of + `routes`' `~ttl_ms`; something that changes as it is watched is `0`. +- `~scope` is as a tool's: a resource the token does not grant is left out + of the lists, and its read is a `403` naming the scope. + +**A read tells a caller nothing of an object they may not see.** A function +that answers `Refusal.not_found`, or `Access.forbidden` for someone else's +object -- what [`Access.can`](access.md) answers, unless told +otherwise -- is the resource not found, `-32602`, word for word what a URI +no resource has is told. Any other `Error` of the function is `-32603`, its +sentence; a refusal of the resource's dependency -- a rate limit, a caller +not signed in -- is that refusal, its status and headers. + +## Watching a resource + +A client that shows a journal as it grows does not poll it. It opens +`subscriptions/listen`, naming the URIs it watches, and the server tells it +each time one changes -- "read it again", never what changed. The server in +`mcp_journal.ml` above does this: `Spindle_mcp.Changes.create ()` is the hub, +given to `routes` as `~changes`, and `Changes.updated changes uri` says a +URI changed, from wherever the change is made. + +- A listen is one request, answered as an event stream that stays open: the + acknowledgment first, naming the URIs it watches, then one + `notifications/resources/updated` a change. While it is open the hub lists + it, and once it ends nothing of it is kept, so the server keeps no session. +- **A listen reveals nothing a read would not.** It watches a URI only where + `resources/read` would answer it for this caller -- its scope granted and + its function answering it, run once as the listen opens -- and leaves any + other out of its acknowledgment, without an error. So the check costs one + read a URI, each time a listen opens: a resource that is large should + answer a read with nothing to read cheaply, as `journal.ml`'s does with no + `from`. A listen watches at most 64 URIs. +- **It is subscribed before it is acknowledged**, so a change made the + instant after reaches it. A client that reads after the acknowledgment, + from its own place, and again on each change, misses nothing. +- **It ends three ways.** A client that closes it is gone, and nothing more + is sent. `Changes.close`, from `Spindle.serve`'s `~on_stop`, ends every + listen with the graceful result, which tells its client the server ended + it. A listen more than `~depth` (16) changes behind is dropped with no + result: its client listens again and reads from where it was, and loses + nothing, since a change says only "read it again". +- No list's changes are watched: the tools and resources a server serves + are fixed when it starts. + +## What a client is told + +The server speaks 2026-07-28 alone, and answers as that revision says: + +| | Answer | +|---|---| +| A body that is no JSON | `400`, `-32700` | +| A batch, a `null` id, a response | `400`, `-32600` | +| `MCP-Protocol-Version`, `Mcp-Method` or `Mcp-Name` missing or not the body's | `400`, `-32020` | +| Another version, or a legacy client's `initialize` | `400`, `-32022`, naming 2026-07-28 | +| `_meta` without the version or the client's capabilities | `400`, `-32602` | +| A method it does not serve | `404`, `-32601` | +| An unknown tool | `-32602` | +| A URI no resource has, or one its function will not show this caller | `-32602`, naming the URI | +| A resource method, on a server given no resources | `404`, `-32601` | +| `subscriptions/listen`, on a server given no `~changes` | `404`, `-32601` | +| `subscriptions/listen` with no `notifications` | `-32602` | +| A notification | `202`, no body | +| A request from another site's page | `403`, the application's [forgery check](cookies.md#csrf-and-cors) | +| `GET` | `405` | + +The server keeps nothing between requests: 2026-07-28 has no session, and +each call is answered on its own, on whichever domain or instance takes it. +The one thing that outlives a request is the application's +`Spindle_mcp.Changes`, which lists a listen only while it is open; it is one +process's, so behind a balancer of several instances, a change one makes +reaches only the listens it holds. + +## Calling another server's tools + +`spindle-mcp-client` calls an MCP server's tools, and reads and watches its +resources, from any Eio program, on the +[HTTP client](client.md) alone: a program that only calls +another server installs and links no framework. + +```sh +opam install spindle-mcp-client +``` + +```ocaml +(* Calling another server's tools: the weather server of mcp.ml, run + beside this one. It links spindle-client and no framework. + + dune exec examples/mcp.exe & + dune exec examples/mcp_client.exe *) + +type query = { city : string } [@@deriving wiretype] +type forecast = { city : string; celsius : int } [@@deriving wiretype] + +let () = + Eio_main.run @@ fun env -> + Spindle_client.run env @@ fun client -> + let weather = + Spindle_mcp_client.create client ~url:"http://localhost:8080/mcp" + in + match Spindle_mcp_client.tools weather with + | Error e -> prerr_endline (Spindle_mcp_client.error_to_string e) + | Ok tools -> ( + List.iter + (fun (t : Spindle_mcp_client.tool) -> print_endline t.name) + tools; + match + Spindle_mcp_client.call weather "get_forecast" query_json + { city = "Paris" } forecast_json + with + | Ok f -> Printf.printf "%s: %d°C\n" f.city f.celsius + | Error e -> prerr_endline (Spindle_mcp_client.error_to_string e)) +``` + +- `create client ~url` names the server and does no I/O. `~headers` go with + every call, a bearer token among them. +- `tools` lists every page of the server's tools. `call` writes the + arguments by one description and reads `structuredContent` by another; + `call_value` takes and gives JSON, for a program passing a model's + arguments through. +- A tool's own failure is `` `Tool_failed `` with its text; a server's + refusal is `` `Refused `` with its status and JSON-RPC code. +- `call ~progress:f` asks the server for progress and hands `f` each + report as it arrives. A caller that stops waiting cancels its fiber, which + closes the connection: that is how a call is cancelled over HTTP. +- A server that needs a token is signed in to with `~oauth`, a + [`Spindle_client.Oauth`](oauth.md#signing-in-as-a-client): + a `401` opens the browser for a person to sign in, and the call is + retried with the token, which is kept for the next. +- A server may ask a question in the middle of a call. Give `~elicit` a + function that answers it -- a person, a form, a policy -- and the call is + retried with the answer; without one, the client tells servers it answers + none, and a call that asks anyway is `` `Unanswered ``. +- Every request carries the headers 2026-07-28 asks for, an argument a + listed tool annotates with `x-mcp-header` among them, and an answer is read + as one JSON object or an event stream, whichever the server sends. + +### Reading its resources + +```ocaml +let* resources = Spindle_mcp_client.resources haf in +let* templates = Spindle_mcp_client.templates haf in +let* contents = Spindle_mcp_client.read haf "haf://intents/0197/journal?from=1" in +... +``` + +- `resources` and `templates` list every page of the server's resources and + templates, each with its name, title, description and MIME type. +- `read uri` answers the contents: `Text`, or `Blob` bytes, decoded from + base64, each with its URI and type. A URI the server has no resource at is + `` `Refused `` with the code `-32602`. Expanding a template into a URI is + the caller's: the server says what its variables mean. + +### Watching a resource + +```ocaml title="mcp_watch.ml" +(* Watching a journal as it grows: run mcp_journal, then this, which prints + each line once, in order, and carries on after a dropped listen without + losing one. *) + +let uri = "haf://intents/0197/journal" + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> + Spindle_client.run env @@ fun client -> + let clock = Eio.Stdenv.mono_clock env in + let mcp = Spindle_mcp_client.create client ~url:"http://localhost:8080/mcp" in + (* The client's own place is the cursor: the next line it has not read. *) + let next = ref 1 in + let catch_up () = + match + Spindle_mcp_client.read mcp (Printf.sprintf "%s?from=%d" uri !next) + with + | Ok contents -> + List.iter + (fun (c : Spindle_mcp_client.content) -> + match c.data with + | Text line -> + print_endline line; + incr next + | Blob _ -> ()) + contents + | Error e -> prerr_endline (Spindle_mcp_client.error_to_string e) + in + (* Read once acknowledged, so a line written since is not missed, and again + on each change; a listen dropped is listened again, a second on. *) + let rec watch () = + match + Spindle_mcp_client.listen mcp [ uri ] (fun _ -> + catch_up (); + `Continue) + with + | Ok (Dropped _) -> + Eio.Time.Mono.sleep_span clock Mtime.Span.(1 * s); + watch () + | Ok (Completed | Stopped) -> () + | Error e -> prerr_endline (Spindle_mcp_client.error_to_string e) + in + watch () +``` + +- `listen uris f` opens `subscriptions/listen` and hands `f` each + notification as it arrives: `Acknowledged` first, naming the URIs the + server watches -- one it left out it will never tell of -- then `Updated` + for each change. It runs in the caller's fiber until the listen ends or `f` + answers `` `Stop ``. +- **The client's place is the cursor.** A change is "read it again", so the + watcher reads from the next line it has not seen, once acknowledged and on + each change. A change made after the acknowledgment is always told, so + nothing written in between is missed, and several changes read once are + as good as each read alone. +- It ends `Stopped` when `f` stopped it, `Completed` when the server ended + it -- it has nothing more to say, and the watcher stops too -- or + `Dropped` when the stream ended without that: the connection lost, the + listen dropped for falling behind, or no word for `~read_timeout` (60 s). + The watcher listens again and reads from where it was, and loses nothing. + It never listens again by itself: whether to, and how long to wait first, + are the caller's. +- An error is a listen refused or never acknowledged, as any request's is. + +## Testing + +`Spindle_mcp.Test.call` sends a request as a client would -- the JSON-RPC +envelope, the `_meta` and the headers -- to an app made with +`Spindle.Test.app`: + +```ocaml +let r = + Spindle_mcp.Test.call app "tools/call" + [ ("name", String "get_forecast"); ("arguments", Object [ ("city", String "Paris") ]) ] +``` + +`Spindle_mcp.Test.events` sends the same, and reads the answer a message at +a time, for a `subscriptions/listen`: its function is handed each event as +it arrives and answers `` `Stop `` to leave. diff --git a/agents/pages/guide/metrics.md b/agents/pages/guide/metrics.md new file mode 100644 index 0000000..91b85a2 --- /dev/null +++ b/agents/pages/guide/metrics.md @@ -0,0 +1,102 @@ +# Metrics + +`Spindle.Metrics` counts what your server does and serves it at +`GET /metrics` for Prometheus. Make a registry, pass it to `serve`, and add +its route: + +```ocaml +let metrics = Spindle.Metrics.create () + +let () = + Eio_main.run @@ fun env -> + Spindle_sqlite.Pool.run env "app.db" @@ fun pool -> + Spindle_sqlite.Pool.measure pool metrics; + Spindle.serve env ~metrics + ~resources:[ Spindle.Dep.resource db pool ] + (routes @ Spindle.Metrics.routes metrics) +``` + +```sh +curl localhost:8080/metrics +``` + +```text +... +# HELP http_server_active_requests Requests being answered +# TYPE http_server_active_requests gauge +http_server_active_requests 1 +# HELP http_server_request_duration_seconds How long a request took to answer +# TYPE http_server_request_duration_seconds histogram +http_server_request_duration_seconds_bucket{http_request_method="GET",http_route="/",http_response_status_code="200",le="0.005"} 1 +... +``` + +## Built-in metrics + +With `~metrics`, the server counts, under OpenTelemetry's names: + +- `http.server.request.duration`, in seconds, by method, route and status; +- `http.server.active_requests`; +- `spindle.server.open_connections`; +- `spindle.server.body_budget.used`, the bytes of request bodies held. + +`Spindle_sqlite.Pool.measure`, and `Spindle_postgres.Pool.measure`, adds +the pool's `db.client.connection.count` (by state, `idle` or `used`) and +`db.client.connection.pending_requests`, labelled +`db.client.connection.pool.name`: `sqlite` or `postgres`, unless you pass +`Pool.measure ~name`. Two pools measured on one registry need two names. + +Prometheus sees each name with dots as underscores, its unit after and a +counter's `_total`: `http_server_request_duration_seconds`. + +A request no route answered is counted under no route, never its path, and +an unknown method as `_OTHER`, so a client cannot create a series per URL. + +## Custom metrics + +```ocaml +let orders = + Spindle.Metrics.counter metrics ~help:"Orders placed" ~labels:[ "kind" ] + "shop.orders" + +let () = Spindle.Metrics.inc orders [ "book" ] +``` + +```text +# HELP shop_orders_total Orders placed +# TYPE shop_orders_total counter +shop_orders_total{kind="book"} 1 +``` + +- **Counter**: `counter`, then `inc ?by c values`. +- **Gauge**: `gauge`, then `add g values n` (negative to go down); or + `sampled t name read`, where `read ()` is called whenever the metrics are + read. +- **Histogram**: `histogram ?buckets`, then `observe h values x`. The + default buckets are 0.005 to 10 seconds. + +Label values are given in the order of `~labels`. Use values your program +chooses, never ones a request does: each value is a series kept for the life +of the process. + +These raise `Invalid_argument`, since each is a mistake in your source: + +- a name, label or buckets Prometheus cannot read; +- a name registered twice -- except a `sampled` gauge, whose second + registration adds its series to the first (two pools under one name). + +Counting never raises: it runs inside a request, so a count with the wrong +number of label values, or a negative `~by`, is left out and logged once for +its metric. + +## Protecting /metrics + +`/metrics` is public unless you guard it. `~guard` is a `unit Dep.t` run +first, whose refusal is the answer: + +```ocaml +Spindle.Metrics.routes ~guard:only_the_scraper metrics +``` + +`~at` serves it at another path, and `Spindle.Metrics.exposition metrics` is +the same text, for sending it elsewhere. diff --git a/agents/pages/guide/middleware.md b/agents/pages/guide/middleware.md new file mode 100644 index 0000000..1ef51e1 --- /dev/null +++ b/agents/pages/guide/middleware.md @@ -0,0 +1,118 @@ +# Middleware + +A middleware is a function from a handler to a handler. It wraps every route +and the not-found answer, for what applies to everything: headers, a +maintenance page, timing. + +## Example: counting requests + +```ocaml +(* A middleware of the application's own: every request is counted before + any route answers it, and the answer says how many there have been. + + The count is an [Atomic] and not a [ref]: a request runs on any of the + domains the server serves on, beside the others, so a [ref] would lose + increments under load. *) + +open Spindle.Syntax + +let count = Atomic.make 0 + +let count_requests handler request = + Atomic.incr count; + handler request + +let saw () = Ok (Printf.sprintf "Saw %i request(s)!" (Atomic.get count)) + +let routes = + [ + (* [let+] over [Dep.return ()] runs [saw] on every request; [Dep.return + (saw ())] would make the answer once, when the route is. *) + Spindle.get Spindle.Path.root Spindle.Returns.text + (let+ () = Spindle.Dep.return () in + saw ()); + ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> + Spindle.serve env ~middleware:[ count_requests ] routes +``` + +```console +$ curl localhost:8080/ +Saw 1 request(s)! + +$ curl localhost:8080/ +Saw 2 request(s)! +``` + +## Writing middleware + +Two middlewares: one built in, and one that counts requests by the route +they matched. A header one route needs is that route's own, written where +the route is: + +```ocaml +open Spindle.Syntax + +let security = + Spindle.Middleware.headers + [ ("x-content-type-options", "nosniff"); ("referrer-policy", "same-origin") ] + +(* Counted by the route the request matched, never by its path, so + /orders/1 and /orders/2 are one count. *) +let counts : (string, int) Hashtbl.t = Hashtbl.create 16 +let lock = Eio.Mutex.create () + +let count_by_route handler request = + let response = handler request in + let route = + match Spindle.Route.matched request with + | Some r -> r.pattern + | None -> "no route" + in + Eio.Mutex.use_rw ~protect:true lock (fun () -> + Hashtbl.replace counts route + (1 + Option.value (Hashtbl.find_opt counts route) ~default:0)); + response + +let routes = + [ + Spindle.get + Spindle.Path.(s "drafts") + Spindle.Returns.text + (let+ add_header = Spindle.add_header in + add_header ("x-robots-tag", "noindex"); + Ok "Not for search engines."); + ] + +let () = + Eio_main.run @@ fun env -> + Spindle.serve env ~middleware:[ security; count_by_route ] routes +``` + +- **Order:** `[a; b]` is `a (b app)`: the first listed sees the request + first and the response last. +- **It may answer alone**, without calling the handler -- a maintenance page, + say. Around the handler, it may add headers + (`Response.add_headers`) or cookies (`Response.add_cookies`) to the + response, or answer a response of its own instead. It cannot rewrite a + stream's body, which is written after the middleware has returned. +- **It cannot reroute.** The request is matched before any middleware runs; + `Route.matched request` is that route's `Route.info`, or `None` when no + route answered. To send someone elsewhere, answer a redirect. +- **What one route needs is not middleware.** It is a dependency of that + route, as `/drafts` adds its header above, so the route lists it. +- **Declare its refusal codes** in `~refuses`, on + `Spindle.serve` or `App.make`. A code nobody declared is logged as a bug, + and raises in a test. These codes are not written into the OpenAPI document. +- **A raise is a `500`**, as a handler's is. +- Two are built in. `Middleware.headers` never overrides a header the route + set itself, and `Cache.forever` keeps the assets a build names by their + contents for a year ([static files](../tutorial/static-files.md)). + +What one route needs -- a session, a [rate +limit](rate-limits.md) -- is not middleware but a dependency of +that route, so it shows in the route and its document. Logging is the +server's own. diff --git a/agents/pages/guide/oauth.md b/agents/pages/guide/oauth.md new file mode 100644 index 0000000..930c39a --- /dev/null +++ b/agents/pages/guide/oauth.md @@ -0,0 +1,190 @@ +# OAuth bearer tokens + +Protect routes with OAuth 2.0 access tokens that an authorization server +elsewhere issues -- Auth0, Okta, WorkOS, your company's. Spindle is the +*resource server*: it checks each token and never issues one. + +```ocaml title="notes_auth.ml" +(* The authorization server oauth's tokens come from, and the resource they + are for. *) + +let auth = + Spindle.Bearer.make ~issuer:"https://id.example.com" + ~resource:"https://notes.example.com" +``` + +`issuer` is the authorization server's identifier, exactly as its tokens +write it in `iss`. `resource` is your server's own URL, which a token must +have been issued for. Both are `https` URLs with no query or fragment; +anything else raises `Invalid_argument` where you wrote it. + +## Reading the token + +```ocaml title="notes_routes.ml" +(* The routes oauth serves, each reading the checked token. *) + +open Spindle.Syntax + +let me = + Spindle.get ~summary:"Who the token was issued for" + Spindle.Path.(s "me") + (Spindle.Returns.json Wiretype.string) + (let+ (claims : Spindle.Bearer.claims) = + Spindle.Bearer.claims Notes_auth.auth + in + Ok claims.subject) + +let notes = + Spindle.get ~summary:"Your notes" + Spindle.Path.(s "notes") + (Spindle.Returns.json (Wiretype.list Wiretype.string)) + (let+ () = Spindle.Bearer.scope Notes_auth.auth "notes:read" in + Ok [ "Write to Charles" ]) + +let routes = [ me; notes ] +``` + +- `Bearer.claims auth` is the checked token: `subject`, `client_id`, + `scopes`, `expires`, `issued`, `token_id`, and `payload`, every claim, for + one of your own. +- `Bearer.scope auth "notes:read"` refuses a token that does not grant that + scope. +- Both are credentials, so the [document](../tutorial/openapi.md) lists + the `bearer` scheme and each route's scopes. + +A token is a JWT access token as [RFC 9068](https://www.rfc-editor.org/rfc/rfc9068) +defines it, and every check that RFC names is made: + +- its signature, by RS256, ES256 or EdDSA, under one of the issuer's keys -- + never `none`, and never an HMAC; +- its header's `typ` is `at+jwt`, so an ID token cannot be spent as an + access token. An issuer that leaves it out is not one these tokens can + come from: Spindle follows the RFC, not what other servers tolerate; +- `iss` is the issuer, `aud` names your resource, `exp` is still ahead and + `nbf` passed; +- `sub`, `client_id`, `iat` and `jti` are present. + +The token is read from the `Authorization` header and nowhere else: one in a +query string would be in every log it passed. No token, and nothing of its +claims, is logged; a refusal's log line says which check failed. + +## What a client is told + +A request with no token is a `401` whose challenge says where to read about +getting one: + +```console +$ curl -i localhost:8080/notes +HTTP/1.1 401 Unauthorized +www-authenticate: Bearer resource_metadata="https://notes.example.com/.well-known/oauth-protected-resource" +... + +{"error":"token_required","message":"A bearer token is needed."} +``` + +| Code | Status | When | +|---|---|---| +| `token_required` | `401` | No bearer token, or another scheme | +| `invalid_request` | `400` | A malformed `Authorization` header | +| `invalid_token` | `401` | A token that fails any check | +| `insufficient_scope` | `403` | A token without the route's scope; the challenge names it | + +The metadata document ([RFC 9728](https://www.rfc-editor.org/rfc/rfc9728)) +names your issuer and every scope your routes read, so a client that has +never seen your server can find where to get a token: + +```console +$ curl localhost:8080/.well-known/oauth-protected-resource +{"resource":"https://notes.example.com","authorization_servers":["https://id.example.com"],"scopes_supported":["notes:read"],"bearer_methods_supported":["header"]} +``` + +It is served at `/.well-known/oauth-protected-resource`, followed by your +resource's path if it has one: `https://api.example.com/mcp`'s is at +`/.well-known/oauth-protected-resource/mcp`. + +## The issuer's keys + +```ocaml title="oauth.ml" +(* A resource server: notes behind OAuth 2.0 bearer tokens, which an + authorization server elsewhere issues. Each token is checked against the + issuer's keys, fetched from its metadata; a client that has none is told + where to read about getting one. + + curl -i localhost:8080/notes + curl localhost:8080/.well-known/oauth-protected-resource *) + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> + Spindle_client.run env @@ fun client -> + let keys = + Spindle_client.Oauth.keys client ~issuer:"https://id.example.com" + in + Spindle.serve env + ~resources: + [ Spindle.Dep.resource (Spindle.Bearer.keys Notes_auth.auth) keys ] + (Notes_routes.routes + @ [ Spindle.Bearer.metadata Notes_auth.auth Notes_routes.routes ] + @ Spindle.Openapi.routes ~title:"Notes" Notes_routes.routes) +``` + +`Spindle_client.Oauth.keys` finds the issuer's metadata at its well-known +URL ([RFC 8414](https://www.rfc-editor.org/rfc/rfc8414), then OpenID Connect +Discovery), checks it names the issuer, and fetches its keys when a token +first needs them. A token naming a key it has not seen fetches them again, +at most once a minute, so a key the issuer rotates in is picked up. A fetch +that fails is a `warn` line, and tokens are refused until one succeeds. + +## Signing in, as a client + +The other side: a program that calls a protected resource, and signs a +person in to get its token. `Spindle_client.Oauth` does what MCP's +authorization asks of a client, with no framework: + +```ocaml +let oauth = + Spindle_client.Oauth.create client + ~clock:(Eio.Stdenv.clock env) + ~metadata_document:"https://app.example.com/oauth/client.json" + ~authorize:(fun url -> open_in_browser url) + +let token = + Spindle_client.Oauth.sign_in oauth ~resource:"https://notes.example.com" () +``` + +- It reads the resource's metadata ([RFC 9728](https://www.rfc-editor.org/rfc/rfc9728)) + and uses it only where it names that resource, then the authorization + server's, used only where it names that issuer. +- It identifies itself by an id registered with that server + (`~registered`), or else by the URL of its + [Client ID Metadata Document](https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/), + where the server reads them. +- `~authorize` is handed the URL a person signs in at, to open in their + browser, which is sent back to `http://127.0.0.1:/callback`, a + port the system gives. The answer is checked to be this sign-in's + (`state`) and the server's own (`iss`, + [RFC 9207](https://www.rfc-editor.org/rfc/rfc9207)) before its code is + redeemed, with PKCE by `S256` and the `resource` named + ([RFC 8707](https://www.rfc-editor.org/rfc/rfc8707)). +- Tokens are kept in `~store`, by resource -- `Oauth.in_memory ()` unless + given; a keychain or a file of the program's own otherwise -- and + `Oauth.access` refreshes one as it expires. + +An [MCP client](mcp.md#calling-another-servers-tools) given +`~oauth` does all of this by itself: a `401` signs in, and a `403` for a +scope steps up to it, keeping those granted. + +## Testing + +A test gives its own keys instead, and signs its own tokens with them: + +```ocaml +let app = + Spindle.Test.app + ~resources: + [ Spindle.Dep.resource (Spindle.Bearer.keys auth) (fun ~kid:_ -> [ key ]) ] + routes +``` + +`key` is a `Spindle_http.Jwk.t`, read from its JSON with +`Spindle_http.Jwk.of_string`. diff --git a/agents/pages/guide/pages.md b/agents/pages/guide/pages.md new file mode 100644 index 0000000..49d695b --- /dev/null +++ b/agents/pages/guide/pages.md @@ -0,0 +1,204 @@ +# HTML pages and templates + +A page is a string. `Returns.html` answers it at `200` as +`text/html; charset=utf-8`; `Response.html` does the same under any status. +Spindle has no template language: render with whichever library you like. +**Escaping what a person sent is the renderer's job**, and each of these +escapes text unless told not to. + +| Renderer | How you write a page | Turning a page into a string | +|---|---|---| +| [htmlit](https://erratique.ch/software/htmlit) | combinators, no dependencies | `Htmlit.El.to_string ~doctype:true page` | +| [TyXML](https://github.com/ocsigen/tyxml) | combinators, or HTML through `tyxml-ppx`, checked against the standard as it compiles | `Format.asprintf "%a" (Tyxml.Html.pp ()) page` | +| [html_of_jsx](https://github.com/davesnx/html_of_jsx) | JSX, in the [mlx](https://github.com/ocaml-mlx/mlx) dialect | `"" ^ JSX.render page` | +| [jingoo](https://github.com/tategakibunko/jingoo) | Jinja templates, in files | `Jingoo.Jg_template.Loaded.eval template ~models` | + +Each program serves the same page at `/hello/{name}`: + +**htmlit** + +```ocaml +(* A page made with htmlit: combinators, and no dependency of their own. + + Spindle has no template language: [Returns.html] answers the string a + renderer made, so any renderer fits, and escaping what a person sent is + the renderer's -- [El.txt] escapes, so the kim of + /hello/%3Cb%3Ekim%3C%2Fb%3E is words on the page. *) + +open Spindle.Syntax +module El = Htmlit.El + +let name = Spindle.Path.string "name" + +let greeting name = + El.page ~lang:"en" ~title:"Hello" + (El.body [ El.h1 [ El.txt ("Hello, " ^ name ^ "!") ] ]) + +let routes = + [ + Spindle.get + Spindle.Path.(s "hello" / name) + Spindle.Returns.html + (let+ name = Spindle.param name in + Ok (El.to_string ~doctype:true (greeting name))); + ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> Spindle.serve env routes +``` + +**TyXML** + +```ocaml +(* A page made with TyXML, written as HTML through its ppx: the markup is + checked against the standard as it compiles, so a [p] inside a [ul] is a + type error. + + Spindle has no template language: [Returns.html] answers the string a + renderer made, so any renderer fits, and escaping what a person sent is + the renderer's -- TyXML escapes text as it prints, so the kim of + /hello/%3Cb%3Ekim%3C%2Fb%3E is words on the page. *) + +open Spindle.Syntax +module Html = Tyxml.Html + +let name = Spindle.Path.string "name" + +let greeting name = + let hello = "Hello, " ^ name ^ "!" in + [%html + {| + Hello +

|} + [ Html.txt hello ] + {|

+ |}] + +let routes = + [ + Spindle.get + Spindle.Path.(s "hello" / name) + Spindle.Returns.html + (let+ name = Spindle.param name in + Ok (Format.asprintf "%a" (Html.pp ()) (greeting name))); + ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> Spindle.serve env routes +``` + +**html_of_jsx** + +```ocaml +(* A page made with html_of_jsx, written as JSX in mlx, an OCaml dialect + dune reads through the dialect in this package's dune-project. + + Spindle has no template language: [Returns.html] answers the string a + renderer made, so any renderer fits, and escaping what a person sent is + the renderer's -- [JSX.string] escapes, so the kim of + /hello/%3Cb%3Ekim%3C%2Fb%3E is words on the page. *) + +open Spindle.Syntax + +let name = Spindle.Path.string "name" + +let greeting name = + + (JSX.string "Hello") +

(JSX.string ("Hello, " ^ name ^ "!"))

+ + +let routes = + [ + Spindle.get + Spindle.Path.(s "hello" / name) + Spindle.Returns.html + (let+ name = Spindle.param name in + Ok ("" ^ JSX.render (greeting name))); + ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> Spindle.serve env routes +``` + +dune reads mlx through a dialect, declared once in your +`dune-project` with `mlx-pp` from the `mlx` package: + +```lisp +(dialect + (name mlx) + (implementation + (extension mlx) + (preprocess + (run mlx-pp %{input-file})))) +``` + +**jingoo** + +```ocaml +(* A page made with jingoo, from a template file in Jinja's syntax: + templates/greeting.jingoo, read once when the program starts and rendered + for every request. Run it from the repository's root, as every example + is. + + Spindle has no template language: [Returns.html] answers the string a + renderer made, so any renderer fits, and escaping what a person sent is + the renderer's -- jingoo escapes every value it writes unless told not + to, so the kim of /hello/%3Cb%3Ekim%3C%2Fb%3E is words on the + page. *) + +open Spindle.Syntax +module Jg_template = Jingoo.Jg_template +module Jg_types = Jingoo.Jg_types + +let name = Spindle.Path.string "name" + +let greeting = + Jg_template.Loaded.from_file "examples/pages/templates/greeting.jingoo" + +let routes = + [ + Spindle.get + Spindle.Path.(s "hello" / name) + Spindle.Returns.html + (let+ name = Spindle.param name in + Ok + (Jg_template.Loaded.eval greeting + ~models:[ ("name", Jg_types.Tstr name) ])); + ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> Spindle.serve env routes +``` + +```jinja title="templates/greeting.jingoo" + + + Hello +

Hello, {{ name }}!

+ +``` + +jingoo raises on a template it cannot read, so load it when the program +starts, as above, not per request. + +```console +$ curl localhost:8080/hello/kim + +...Hello

Hello, kim!

+``` + +A name with markup in it is escaped: visit `/hello/kim` and the +page reads `Hello, kim!`, tags and all, rather than a bold name. + +A refusal is still JSON, on a page's route as on any other. For an HTML +page when no route matches, pass your own answer as `~not_found` +([How routes are matched](../tutorial/routes.md#how-routes-are-matched)). +To read a form a page posts, see +[Forms and file uploads](../tutorial/bodies.md#forms-and-file-uploads); a +form posted from another site is refused by the +[cross-site check](cookies.md#csrf-and-cors). diff --git a/agents/pages/guide/rate-limits.md b/agents/pages/guide/rate-limits.md new file mode 100644 index 0000000..e6ff06b --- /dev/null +++ b/agents/pages/guide/rate-limits.md @@ -0,0 +1,52 @@ +# Rate limits + +Limit how often a client may call a route. A limit is a dependency: you list +it in the route, and the route's OpenAPI document shows its `429`. + +```ocaml +open Spindle.Syntax + +let sign_ins = Spindle.Rate.create ~limit:10 ~per:Mtime.Span.min () + +let sign_in = + Spindle.post + Spindle.Path.(s "sign-in") + Spindle.Returns.text + (let+ () = Spindle.Rate.limit sign_ins ~key:Spindle.client_ip in + Ok "in") + +let () = Eio_main.run @@ fun env -> Spindle.serve env [ sign_in ] +``` + +Ten sign-ins a minute per client pass; the eleventh is refused: + +```console +$ curl -i -X POST localhost:8080/sign-in +HTTP/1.1 429 Too Many Requests +content-type: application/json +retry-after: 6 +... + +{"error":"rate_limited","message":"That was asked too often. Please try again in a moment."} +``` + +- `Rate.create ~limit ~per ?burst ()` allows `limit` calls every `per`, an + `Mtime.Span.t`, and up to `burst` (default: `limit`) at once. Make it + once, at the top level, beside the routes that read it. A `limit` or + `burst` below one, or a `per` shorter than `limit` nanoseconds, which + leaves no time between two calls, raises `Invalid_argument` there. +- `~key` is what is counted: `Spindle.client_ip` (the client's address), or any + `string Dep.t` -- a session, a token, a path parameter. An IPv6 address is + counted by its /64, since a client may change its address within one at + will; an IPv4 address by itself. +- `Retry-After` is in whole seconds, at least one. +- Behind a proxy, `Spindle.client_ip` is the address your `~trusted_proxies` + vouch for; without them every request has the proxy's address. +- The counts are the app's, timed on the server's monotonic clock: each + app serving the limit counts its own, and several processes each count + their own. +- A test's app counts on a clock that never moves, so a limit refuses and + never refills. To wait one out, give `Spindle.Test.app ~mono_clock` an + `Eio_mock.Clock.Mono.make ()` and move it with + `Eio_mock.Clock.Mono.set_time`. Add `eio.mock` to the test's `libraries` + in its `dune` file. diff --git a/agents/pages/guide/serving.md b/agents/pages/guide/serving.md new file mode 100644 index 0000000..9fc6572 --- /dev/null +++ b/agents/pages/guide/serving.md @@ -0,0 +1,219 @@ +# Server configuration and shutdown + +`Spindle.serve env routes` is the whole server. Anything the routes need -- +a database pool, a client -- is made first, inside `Eio_main.run`, and +supplied as a [resource](../tutorial/dependencies.md#resources): + +```ocaml +let () = + Eio_main.run @@ fun env -> + Spindle_sqlite.Pool.run env "app.db" @@ fun pool -> + Spindle.serve env ~port:3000 + ~limits:(Spindle.Server.Limits.make ~max_connections:1024 ()) + ~resources:[ Spindle.Dep.resource db pool ] routes +``` + +By default it serves on `localhost:8080`, on every CPU core, stops cleanly +on SIGTERM or SIGINT, and prints where it listens. Every setting is an +optional argument, and the limits on clients are one of them, `~limits`. + +Two kinds of mistake stop the server before it listens: + +- A route table that cannot be right -- two routes answering one URL, say + -- raises `Invalid_argument`, naming the route. So does a limit out of + its range, where `Limits.make` is called. +- A `Static.directory` or a `Files.directory` that cannot be read, a + resource a route reads that `~resources` does not hold, a signed or + encrypted cookie a route reads with no `~keys`, or a host and port it + cannot listen on, is one line saying why -- in the log, or on stderr + where the program set none up -- and the program exits with status 1: + +``` +cannot listen on localhost:8080: another program holds port 8080 on 127.0.0.1 +``` + +A port is bound on every address the host names or on none, so a server +never starts on IPv6 alone beside another program holding the port on IPv4. + +## Where it listens + +| `~host` | Listens on | +|---|---| +| `"localhost"` (default) | `127.0.0.1` and `[::1]`, this machine only | +| `"0.0.0.0"` or `"::"` | every interface, IPv4 and IPv6 | +| an address, e.g. `"10.0.0.5"` | that address | +| a name | every address it resolves to | + +In a container, a pod or on a hosting platform, use `~host:"0.0.0.0"`. +Serving beyond your machine has to be asked for in code, so a laptop never +serves the network it happens to be on. + +TLS is the one thing Spindle leaves to a proxy or the platform. Behind one, +name it in `~trusted_proxies` (an address or a CIDR range) so the client's +real address and request id are read from its headers -- see +[the client's IP address](cookies.md#the-clients-ip-address). + +## Using every core + +`~domains` is how many OCaml domains serve, one per core by default. A +handler runs beside handlers on other domains, so whatever it shares must be +safe to share: immutable, an `Atomic`, an `Eio.Mutex`. An application that +is not serves with `~domains:1`. [Multicore and shared +state](domains.md) has the details. + +## Limits + +Every wait on a client is bounded, so a slow or stuck client cannot hold a +connection for ever. The defaults suit an ordinary API; change one only for +a reason. They are one value, `~limits`, made by `Spindle.Server.Limits.make`, +which takes each by its name and keeps the rest at their defaults. + +| Limit | Default | When it is passed | +|---|---|---| +| `max_body` | 1 MiB | the body is `413` | +| `body_budget` | 64 MiB | bodies held at once, across all requests; past it `503 busy` | +| `max_header_bytes` | 16 KiB | the head is `431` (`414` for a long request line) | +| `head_timeout` | 10 s | a head still arriving is `408` | +| `idle_timeout` | 60 s | an idle connection is closed | +| `body_timeout` | 20 s | a body gets 20 s, plus one second for every `min_body_rate` (500) bytes received; one that falls behind is closed | +| `handler_timeout` | 60 s | a handler still running is cancelled and answered `503 timed_out`; time spent waiting on its body is not counted | +| `send_timeout` | 30 s | a client that stops reading the answer is closed | +| `max_connections` | 512 | connections held at once, per address; the rest wait in `backlog` (128) | +| `discard_limit` | 64 KiB | a body a route left unread is read and dropped up to it; with more left, the connection is closed | +| `linger` | 1 s | a closing connection's last bytes are read and dropped, so the client gets the answer | +| `drain` | 10 s | requests in flight at shutdown are cancelled ([below](#graceful-shutdown)) | + +A wait is an `Mtime.Span.t`, named for what it bounds: +`Limits.make ~send_timeout:Mtime.Span.(60 * s) ()`. A timeout of zero is +refused where the limits are made, since the server would wait for nothing; +only `drain` and `linger` may be zero. + +A route has its own `max_body`, `body_timeout`, `min_body_rate` and +`handler_timeout` in place of these, by the same names, and keeps the server's where it gives none: +`Spindle.post ~limits:(Spindle.Route.Limits.make ~max_body:(64 * 1024 * +1024) ()) ...` ([large bodies](../tutorial/bodies.md#large-bodies)). The +rest act before a route is chosen, between requests or on the whole server, +so they are the server's alone. + +`handler_timeout` is the one limit on your own code rather than the +client's. A handler stuck on something that never comes -- a row lock, an +upstream with no deadline of its own -- would otherwise hold its connection +and whatever it took from a pool for good, until the pool is empty and +routes that never touch it stop answering too. Past the limit its handler +is cancelled, with everything it started: a database statement in flight +closes its connection, so its transaction ends with nothing kept. Work +handed to `Background` is not cancelled. A route that legitimately runs +longer, an export say, gives its own: +`Spindle.post ~limits:(Spindle.Route.Limits.make ~handler_timeout:Mtime.Span.(5 * min) ()) ...`. +A stream or a socket runs after its answer, so the limit is over by then. + +Keep `max_connections` under the process's file descriptor limit +(`ulimit -n`): every open stream and WebSocket holds a connection, and a +file being sent holds a descriptor as well. Past the limit a connection +waits: the server logs the failed accept at `warning` and tries again 10 ms +later, serving the connections it has meanwhile. + +## Graceful shutdown + +On the first SIGTERM or SIGINT: + +1. `~on_stop` runs. End your streams here -- an event stream or a broadcast + never ends on its own. +2. The server stops accepting connections. +3. Requests in flight get `drain` (10 s, a [limit](#limits)) to finish, each + answered with `Connection: close`. A stream of known length -- a file -- + counts as one until its last byte is sent; an event stream does not, + since only `~on_stop` ends it. +4. Whatever is left is cancelled, and `serve` returns. + +A second signal ends the process at once. To stop on something other than +a signal, pass your own promise as `~stop`. + +If your routes publish to a +[`Spindle.Broadcast`](sse.md#broadcasting-to-many-clients) -- +here called `hub` -- close it in `~on_stop`, so every stream reading it ends +and the drain can finish: + +```ocaml +Spindle.serve env ~on_stop:(fun () -> Spindle.Broadcast.close hub) routes +``` + +## What the server handles for you + +Spindle reads and writes HTTP/1.1 itself, and every requirement of RFC 9112 +and RFC 9110 it meets is a test, as is every one of RFC 9111's +`Cache-Control` and RFC 7239's `Forwarded`. Among them: + +- A malformed request -- a bad head, a missing, empty or doubled `Host`, a + body framed two ways -- is `400` and its connection closed, so nothing can + smuggle a second request inside the first. +- A body the route did not read is discarded before the next request on the + connection. +- `Expect: 100-continue` is answered only by a route that reads its body, + and never for a body over `max_body`. +- The server writes the fields that say how an answer is framed -- + `Content-Length`, `Transfer-Encoding`, `Connection`, `Keep-Alive`, + `Upgrade`, `TE` and `Trailer` -- and the ones it works out itself: + `Content-Type` from the route's `Returns`, `Set-Cookie` from its cookies, + `Date` and `X-Request-Id`. A route that sets any of them as a header + answers `500`. +- HTTP/1.0 clients are answered as HTTP/1.0. + +The same holds beyond HTTP itself: WebSockets are tested against RFC 6455, +a form's multipart body against RFC 7578 and RFC 2046, and Structured +Fields against RFC 9651's published test suite, run whole. + +## Every other argument + +`Spindle.serve` also takes these, each covered on its own page: + +| Argument | What it does | +|---|---| +| `~resources` | what the routes read that the program holds -- a pool, a client -- made where it starts ([Resources](../tutorial/dependencies.md#resources)) | +| `~keys` | what signed and encrypted cookies are sealed under, from a secret the program reads ([Signed and encrypted cookies](cookies.md#signed-and-encrypted-cookies)) | +| `~middleware` | wraps every route ([Middleware](middleware.md)) | +| `~refuses` | the refusal codes your middleware may answer ([Middleware](middleware.md#writing-middleware)) | +| `~not_found` | answers a request no route claims ([Routes](../tutorial/routes.md#how-routes-are-matched)) | +| `~trailing_slash` | `Strict` by default; `Redirect` answers `/a/` with a `308` to `/a` ([Routes](../tutorial/routes.md#how-routes-are-matched)) | +| `~check_origin`, `~trusted_origins` | the cross-site check on requests that change something ([CSRF and CORS](cookies.md#csrf-and-cors)) | +| `~cors` | lets other sites' pages call your routes ([CSRF and CORS](cookies.md#csrf-and-cors)) | +| `~compress` | gzip for clients that accept it ([Compression](compression.md)) | +| `~trusted_proxies`, `~proxy_header` | the proxies whose forwarding header is believed, and which header that is: `X_forwarded_for` (default) or `Forwarded` ([The client's IP address](cookies.md#the-clients-ip-address)) | +| `~trace` | sends a span for every request ([Tracing](../tutorial/logging.md#tracing)) | +| `~metrics` | counts requests and connections ([Metrics](metrics.md)) | +| `~ready` | told the address once the server listens; by default it is printed to stdout | +| `~read_clock` | the clock a handler reads as `Spindle.now`; the system clock by default | + +## Without Spindle.serve + +A program that builds its routes at run time, or wants no signal handler, +does what `Spindle.serve` does in three steps: `App.make` the routes, +`App.start` the app, and `Server.run` the instance it answers, with every +capability passed explicitly. `App.start` takes what exists only once the +program runs -- the `~resources`, the `~keys`, the `~mono_clock` its rate +limits are timed on, and the `~fs` any `Static.directory` or +`Files.directory` is read from -- and each call is an instance of its own, +so two never share what they hold. `Server.serve_on` serves on sockets you +already listen on -- a test's, on a port the system chose. + +## On a Unix socket + +A server only programs on this machine call -- a background service and +the commands that drive it -- can listen on a Unix socket instead of a +port, so who may connect is the system's to decide, by the file's owner, +and no credential is checked: + +```ocaml +match Spindle.Server.Unix_socket.listen ~sw "/run/user/501/app.sock" with +| Ok socket -> + Spindle.Server.serve_on ~mono_clock ~read_clock ~domain_mgr [ socket ] + instance +| Error e -> prerr_endline (Spindle.Server.Unix_socket.error_to_string e) +``` + +The directory that holds it must be yours and closed to everyone else +(mode `0700`), since not every system honours a socket file's own mode; +the file is made `0600` as well. A path a running server answers on is +refused, a file a killed server left is replaced, and the file is removed +when the switch ends. A client reaches it as `http+unix://` and the path, +percent-encoded -- see [the client](client.md#a-server-on-a-unix-socket). diff --git a/agents/pages/guide/sse.md b/agents/pages/guide/sse.md new file mode 100644 index 0000000..39be372 --- /dev/null +++ b/agents/pages/guide/sse.md @@ -0,0 +1,170 @@ +# Server-Sent Events (SSE) + +A Server-Sent Events stream sends events until it is done. `Broadcast` +sends one event to everyone listening. + +## A resumable event stream + +`GET /count` sends a number a second, and a client that reconnects carries +on where it left off: + +```ocaml +(* Server-Sent Events: GET /count sends a number a second, each with its id, + and a client that reconnects carries on after the last number it was sent + instead of starting again. A browser's EventSource reconnects by itself + and says where it was in the Last-Event-ID header, so resuming is the one + thing the route has to do. + + What the stream sends is declared on the route, as an answer is, so the + API's document describes each event and the compiler refuses one the + route did not declare. *) + +open Spindle.Syntax + +(* The events one stream may send are a type of their own, and each kind is + declared as one of them. *) +type counting + +let count : (int, counting) Spindle.Event.kind = + Spindle.Event.json "count" Wiretype.int + +let count_from ~mono_clock n send = + let rec go n = + let* () = send (Spindle.Event.make ~id:(string_of_int n) count n) in + Eio.Time.Mono.sleep_span mono_clock Mtime.Span.s; + go (n + 1) + in + go n + +(* The clock the count waits on is the program's, handed to the server where + it starts, so the routes are a value and a test gives a clock of its own. *) +let clock : Eio.Time.Mono.ty Eio.Resource.t Spindle.Dep.t = + Spindle.Dep.of_resource "clock" + +let routes = + [ + Spindle.get + Spindle.Path.(s "count") + (Spindle.Returns.events Spindle.Event.[ declare count ]) + (let+ mono_clock = clock + and+ last = Spindle.Header.optional "last-event-id" Wiretype.int in + Ok (count_from ~mono_clock (Option.fold ~none:1 ~some:succ last))); + ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> + Spindle.serve env + ~resources:[ Spindle.Dep.resource clock (Eio.Stdenv.mono_clock env) ] + routes +``` + +```console +$ curl -N localhost:8080/count +event: count +id: 1 +data: 1 + +event: count +id: 2 +data: 2 +... + +$ curl -N -H 'Last-Event-ID: 41' localhost:8080/count +event: count +id: 42 +data: 42 +... +``` + +- **The producer** is the function the route answers with, `fun send -> ...` + (here `count_from ~mono_clock n`, waiting on the clock the route reads as + a [resource](../tutorial/dependencies.md#resources)). It runs after + the response's head is sent, and the stream ends when it returns. +- **Declare each kind of event**: `Event.json "count" Wiretype.int`, or + `Event.text "token"` for plain text. `type counting` is declared and never + defined: it is a label every kind of this stream carries, so the compiler + refuses an event declared for another stream. +- **`send` answers `Error Gone` once the client has gone**, so a loop + written with `let*` ends there. It also answers `Error Gone` after the + producer has returned, so a fiber left holding `send` writes nothing. +- **Resuming:** give each event an id (`Event.make ~id`). A browser sends + the last one back as `Last-Event-ID` when it reconnects. + `Event.retry ~ms` tells the browser how long to wait before it reconnects. +- A quiet stream gets a `: keep-alive` comment every 15 seconds + (`Returns.events ~keep_alive`). `Event.comment` sends one of your own. +- The OpenAPI document describes each kind of event the route declares. + +## Broadcasting to many clients + +`Broadcast` sends one event to every subscriber of a topic, within one +process: + +```ocaml +open Spindle.Syntax + +type room + +let count : (int, room) Spindle.Event.kind = + Spindle.Event.json "count" Wiretype.int + +let hub : (unit, room Spindle.Event.t) Spindle.Broadcast.t = + Spindle.Broadcast.create ~depth:16 () + +let room = Spindle.Path.string "room" + +let events = + Spindle.get + Spindle.Path.(s "rooms" / room / s "events") + (Spindle.Returns.events Spindle.Event.[ declare count ]) + (let+ room = Spindle.param room and+ gone = Spindle.client_gone in + Ok + (fun send -> + Spindle.Broadcast.subscribe hub ~topic:room () (fun sub -> + Spindle.Broadcast.forward ~until:gone sub send))) + +(* Anywhere else: make the event once, and everybody gets it. *) +let () = + Spindle.Broadcast.publish hub ~topic:"lobby" (Spindle.Event.make count 1) +``` + +- **An event is encoded once**, however many subscribers get it. +- **A subscription lasts as long as its work.** `Broadcast.subscribe` runs + the function it is given and unsubscribes however it ends -- returned, + raised or cancelled -- so a subscription cannot be left behind. +- **`Broadcast.forward` sends every event until the subscription ends**, + and answers the first `Error` `send` answers. +- **A client that leaves a quiet topic ends its producer.** The keep-alive + it can no longer be sent resolves `Spindle.client_gone`, and + `forward ~until:gone` unsubscribes, so the subscription and the + connection are let go without waiting for the next event. Nothing is + cancelled: a `send` already running finishes, and a producer that does + not pass `~until` learns at its next `send`. +- **A slow subscriber is dropped, never waited for.** One more than + `~depth` events (16) behind, its `forward` answers `Ok ()`. So send whole + states, not changes, and a client that reconnects is up to date. +- Each subscriber carries a tag (`()` here), which `Broadcast.subscribers` + lists: who is present, say. `Broadcast.unsubscribe` ends one subscription + from anywhere, and `Broadcast.close` every one. + +To send the state as it is, then every change, subscribe first: a change +made while the state is read then still arrives. + +```ocaml +(fun send -> + Spindle.Broadcast.subscribe hub ~topic:room () (fun sub -> + let* () = send (Spindle.Event.make count (Counts.read room)) in + Spindle.Broadcast.forward ~until:gone sub send)) +``` + +`forward`'s `send` is any function, so a subscriber that sees only some +events, or each in its own form, filters or turns them there: + +```ocaml +Spindle.Broadcast.forward ~until:gone sub (fun order -> + if Order.visible_to user order then send order else Ok ()) +``` + +To read a stream from OCaml, see [the HTTP +client](client.md#server-sent-events); to test one, see +[Testing event streams](testing.md#testing-event-streams). diff --git a/agents/pages/guide/testing.md b/agents/pages/guide/testing.md new file mode 100644 index 0000000..bf0723d --- /dev/null +++ b/agents/pages/guide/testing.md @@ -0,0 +1,107 @@ +# Testing + +`Spindle.Test` calls your app in-process: no socket, no port, and a clock the +test sets. It works with any test library; these examples use Alcotest. + +```ocaml +let echo = + Spindle.post + Spindle.Path.(s "echo") + Spindle.Returns.text + (let+ body = Spindle.body in + Ok body) + +let test_echo () = + let app = Spindle.Test.app [ echo ] in + let r = Spindle.Test.call app `POST "/echo" ~body:"hi" in + Alcotest.(check int) "status" 200 (Spindle_http.Status.to_int r.status); + Alcotest.(check string) "body" "hi" r.body; + Alcotest.(check (option string)) + "type" (Some "text/plain; charset=utf-8") + (Spindle.Test.header r "content-type") +``` + +- `Test.app` takes `App.make`'s arguments. It raises `Invalid_argument` for a + route table `App.make` refuses, and for a `Static.directory` or + `Files.directory` route: load the files with `Static.load` and serve them + with `Static.route`, or serve a directory the test opened with + `Files.route`, instead. +- `Test.app ~resources` supplies the + [resources](../tutorial/dependencies.md#resources) the routes read, as the + server's `~resources` does: a test's own pool, say, + `Spindle.Test.app ~resources:[ Spindle.Dep.resource db test_pool ] routes`. + It needs only those the routes it calls read; calling one that reads a + resource it was not given raises `Invalid_argument`, naming it. +- `Test.app ~keys` gives the app the keys its [signed and encrypted + cookies](cookies.md#signed-and-encrypted-cookies) are sealed + under, as the server's `~keys` does. +- `Test.app ~mono_clock` is the clock its [rate + limits](rate-limits.md) are timed on: by default one that + never moves. Give it `Eio_mock.Clock.Mono.make ()` and move it with + `Eio_mock.Clock.Mono.set_time` to wait one out. Each app counts its own, + so one test's calls never count against another's. +- `Test.call app meth target` takes `?now` (a `Ptime.t`, default `Ptime.epoch`), + `?peer` (default `127.0.0.1`), `?headers` and `?body`. +- To test what a route sees behind a proxy, pass `~proxied:true`: the peer + is then a proxy the server trusts, and `~proxy_header` says which + forwarding header it writes. `~version:Spindle_http.Version.Http_1_0` + sends the request as HTTP/1.0. +- The answer's status and headers are exactly what the server would write, + cookies included, minus `connection`. A stream is run to its end. +- `r.status` is a `Spindle_http.Status.t`, as every status in the API is, + in its one spelling: match on `` `Conflict ``, never `` `Code 409 ``, or + compare its `Status.to_int`. +- A refusal with a code the route does not declare, or a status its route + does not list, raises `Invalid_argument`: the server would only log that + bug, the test fails on it. + +## Testing cookies and sign-in + +`Test.browser` keeps the cookies the app sets, as a browser does, and sends +them on later calls: + +```ocaml +let b = Spindle.Test.browser app in +let _ = Spindle.Test.Browser.call b `POST "/sign-in" ~body in +let me = Spindle.Test.Browser.call b `GET "/me" in ... +``` + +A cookie is dropped when the app clears it or when its age is past a later +call's `~now`. `Test.Browser.cookies b` lists what it holds. + +## Testing event streams + +`Test.events` hands each event to your function until it answers `` `Stop ``. +Here, three events of the [count stream](sse.md): + +```ocaml +let test_count () = + Eio_main.run @@ fun env -> + let app = + Spindle.Test.app + ~resources:[ Spindle.Dep.resource clock (Eio.Stdenv.mono_clock env) ] + routes + in + let seen = ref [] in + match + Spindle.Test.events app "/count" (fun e -> + seen := e.data :: !seen; + if List.length !seen = 3 then `Stop else `Continue) + with + | Ok () -> Alcotest.(check (list string)) "three" [ "1"; "2"; "3" ] (List.rev !seen) + | Error r -> Alcotest.failf "no stream: %d" (Spindle_http.Status.to_int r.status) +``` + +Each event has its `name`, `data`, `id` and `retry_ms`, as a client reads +them. +`` `Stop `` is the client leaving: the route's next `send` is `Error Gone`, +and `Spindle.client_gone` is resolved. +`Error r` is the answer when the route did not stream. + +## Testing WebSockets and real connections + +- `Test.websocket app protocol target f` opens a socket to the route and runs + `f` on the client's end; see [WebSockets](websockets.md). +- To test over a real socket, listen on a port of your own and serve the app + with `Spindle.Server.serve_on`, which runs the same loop as + `Spindle.Server.run`. diff --git a/agents/pages/guide/websockets.md b/agents/pages/guide/websockets.md new file mode 100644 index 0000000..1edfd0a --- /dev/null +++ b/agents/pages/guide/websockets.md @@ -0,0 +1,218 @@ +# WebSockets + +You declare a WebSocket **protocol** once -- what the client sends and what +the server sends -- and serve it from a route or open it from a client. Each +end gets a socket typed from its own side. + +## An echo server + +```ocaml +(* A WebSocket: GET /echo opens one, and whatever the client says comes + back to it. + + What each side sends is declared once, as a protocol, and the route + serves it: the framework runs the protocol itself -- the handshake, the + frames, ping and pong, the close -- and the handler only receives and + sends. A loop written with [let*] ends at the first thing that went + wrong, and how it ended decides how the socket is closed: a message the + description cannot read closes it with 1007. *) + +module Ws = Spindle.Websocket +open Spindle.Syntax + +type said = { text : string } [@@deriving wiretype] + +let protocol = + Ws.protocol ~client:(Ws.json said_json) ~server:(Ws.json said_json) () + +let echo ws = + let rec loop () = + let* said = Ws.receive ws in + let* () = Ws.send ws said in + loop () + in + loop () + +let routes = + [ + Spindle.get + Spindle.Path.(s "echo") + (Spindle.Returns.websocket protocol) + (Spindle.Dep.return (Ok echo)); + ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> Spindle.serve env routes +``` + +- `Ws.protocol ~client ~server ()` says what each side sends: `Ws.json` of a + wiretype description, `Ws.text` or `Ws.binary` (each a `string`). Add + `~subprotocol:"name"` to require a `Sec-WebSocket-Protocol`. +- `Spindle.Returns.websocket protocol` makes the route a socket. Its + dependency answers `Ok handler`, or a refusal before the upgrade. +- The handler calls `Ws.receive` and `Ws.send` and returns a `result`. A + `let*` loop stops at the first error: `` `Socket (`Closed c) `` (with its + code and reason), `` `Lost ``, `` `Undecodable `` for a message its + description could not read, or `` `Unwritable `` for one that cannot be + sent -- JSON its description cannot encode, or text that is not UTF-8. + They are open tags, so the loop goes on through your own work too: `let* + () = Pool.exec pool save msg in` needs no conversion. + +A plain request to the route is refused with `426`, as below. So is an +upgrade from another site's page (`403 cross_origin`; see +[`~trusted_origins`](cookies.md#csrf-and-cors)), since the +browser would attach your site's cookies to it: + +```console +$ curl -i localhost:8080/echo +HTTP/1.1 426 Upgrade Required +upgrade: websocket +... + +{"error":"upgrade_required","message":"This address opens a WebSocket, and nothing else."} +``` + +## Connecting as a client + +```ocaml +(* The other end of websocket_server.ml: a client that opens its /echo, says three + things and hears each come back. Run the server first, then this: + + dune exec examples/websocket_server.exe + dune exec examples/websocket_client.exe + + The protocol is the server's, from the client's side: this socket sends + what the client sends and receives what the server does. Two programs + declare it twice here; an application whose two ends are separate + programs puts it in a library both link, so they cannot drift apart. + + The call is a bracket: the connection lives while the function runs and + is closed after it, and the answer is what the function returned -- here, + what it heard -- or why the socket, or the handshake, ended first, which + the log has already said. *) + +open Spindle.Syntax +module Ws = Spindle.Websocket + +type said = { text : string } [@@deriving wiretype] + +let protocol = + Ws.protocol ~client:(Ws.json said_json) ~server:(Ws.json said_json) () + +let converse ws = + let rec say heard = function + | [] -> Ok (List.rev heard) + | text :: rest -> + let* () = Ws.send ws { text } in + let* back = Ws.receive ws in + say (back.text :: heard) rest + in + say [] [ "hello"; "is anybody there"; "goodbye" ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> + Spindle_client.run env @@ fun client -> + match + Spindle_client.websocket client protocol "ws://localhost:8080/echo" converse + with + | Ok heard -> List.iter (fun text -> print_endline ("heard: " ^ text)) heard + | Error _ -> () (* the socket's log line has said why *) +``` + +```console +$ dune exec examples/websocket_client.exe +heard: hello +heard: is anybody there +heard: goodbye +``` + +`Spindle_client.websocket client protocol url f` opens a `ws://` or `wss://` +URL, runs `f` on the socket and closes it when `f` returns. It answers `f`'s +result, or a call's `` `Unsent `` or `` `Lost `` (the handshake could not be +made), `` `Not_upgraded `` (the server answered without a `101`, with that +answer), how the socket ended -- its tags, above, the client's `` `Lost `` +and the socket's being one -- or a failure of `f`'s own. `~timeout` bounds the +handshake and each write. + +Both programs declare the same protocol. When the two ends are separate +programs, put it in a library both link so they cannot drift apart. + +## Closing a socket + +How the handler's loop ended is the close code: + +| The handler | Close code | +|---|---| +| returns `Ok` | 1000 | +| got a message its description could not read (`` `Undecodable ``) | 1007 | +| had a message its description could not write (`` `Unwritable ``) | 1011 | +| ends with a failure of its own -- a statement's, say -- logged | 1011 | +| raised (logged as a bug) | 1011 | +| returns `` `Socket (`Closed _) `` or `` `Lost `` | none: the socket has already ended | + +To close with another code, call `Ws.close ~code ~reason ws` and return. +Nothing raises into your handler: a socket whose peer has gone answers its +next `receive` or `send` with an error. A `send` you cut off -- under +`Eio.Time.Timeout.run`, or in an `Eio.Fiber.first` it lost -- may have +written part of its frame, so it ends the socket: the cancellation goes on, +and every later `send` answers `` `Lost ``. + +The framework handles the rest of the protocol for you: + +- ping and pong: a ping after `~keep_alive` (15 s) of silence, and a + peer silent for twice that is `` `Lost ``; +- a peer that takes nothing written for the server's `send_timeout` + (30 s) is `` `Lost ``, and one still reading, however slowly, is sent the + whole message; +- a message over `~max_message` (1 MiB) closes the socket with 1009, and one + of a kind the socket does not carry with 1003; +- a stopping server closes every socket with 1001; +- one log line when a socket ends: how long it lived and why. + +`~keep_alive` and `~max_message` are arguments of +`Spindle.Returns.websocket` and `Spindle_client.websocket`. + +## Broadcasting to many sockets + +To send one message to many sockets, encode it once with `Ws.encode +(Ws.server protocol) value` and send that to each with `Ws.send_encoded`. +Make the hub a +[`Spindle.Broadcast`](sse.md#broadcasting-to-many-clients) of +encoded messages. A handler that both receives and forwards runs two loops, +here under `Eio.Fiber.first`, which ends both when either does, and +`Broadcast.subscribe` unsubscribes once the handler returns: + +```ocaml +let hub : (unit, said Ws.encoded) Spindle.Broadcast.t = + Spindle.Broadcast.create () + +let chat ws = + Spindle.Broadcast.subscribe hub ~topic:"lobby" () @@ fun sub -> + let rec listen () = + let* said = Ws.receive ws in + Spindle.Broadcast.publish hub ~topic:"lobby" + (Ws.encode (Ws.server protocol) said); + listen () + in + Eio.Fiber.first listen (fun () -> + Spindle.Broadcast.forward sub (Ws.send_encoded ws)) +``` + +When the client leaves, `listen` ends and `forward` is cancelled. If it was +cancelled partway through a send, the socket ends, as +[Closing a socket](#closing-a-socket) says; the client has gone anyway. + +## Testing and OpenAPI + +- `Spindle.Test.websocket app protocol "/echo" f` opens a socket as a browser + does and runs `f` on the client's end, with no port. A route that refuses + the upgrade answers `Refused`. Keep-alive never fires in a test. +- The OpenAPI document lists the route as a `101`, with each side's schema + under `x-websocket`; the Zod module types it as + `{ websocket: { client, server } }`. + +To speak another protocol over a connection, see `Spindle.Response.takeover` +in the reference: the connection it hands over is `Spindle_http.Connection.t`, +as a socket's is. diff --git a/agents/pages/index.md b/agents/pages/index.md new file mode 100644 index 0000000..89b8a93 --- /dev/null +++ b/agents/pages/index.md @@ -0,0 +1,74 @@ +# Spindle + +The web framework for modern OCaml. + +```sh +opam repo add open-opam https://github.com/open-opam/opam-repository.git +opam install spindle +``` + +```ocaml +open Spindle.Syntax + +type greeting = { text : string } [@@deriving wiretype] + +let hello name = Ok { text = "Hello, " ^ name ^ "!" } +let name = Spindle.Path.string "name" + +let routes = + [ + Spindle.get + Spindle.Path.(s "hello" / name) + (Spindle.Returns.json greeting_json) + (let+ name = Spindle.param name in + hello name); + ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> + Spindle.serve env (routes @ Spindle.Openapi.routes routes) +``` + +**Beautiful and idiomatic** + +Expressive and composable, doing the heavy lifting in just a few lines of +readable code. + +**Performant** + +Multicore by design, with domains putting every core to work serving +connections in parallel. + +**Eio-native** + +OCaml 5 effects give every connection its own fiber and keep handlers in +plain direct style. + +**OpenAPI docs via Scalar** + +Interactive API docs generated from the routes, so they are never out of +date. + +**Front end in sync** + +Zod or Melange schemas generated from the routes, keeping client and +server aligned. + +**Typed end to end** + +JSON contracts derived from OCaml types, bounds and docs included. + +**HTTP from the ground up** + +Built for speed and safety, and extensively tested against RFC standards. + +**Dependencies and Resources** + +Extend any route with injectable logic and resources that compose and +swap easily. + +**Batteries included** + +WebSockets, SSE, sessions, rate limits, logs, traces and OpenTelemetry +metrics. diff --git a/agents/pages/install.md b/agents/pages/install.md new file mode 100644 index 0000000..6e91e2d --- /dev/null +++ b/agents/pages/install.md @@ -0,0 +1,23 @@ +# Install + +It needs opam, with a switch of OCaml 5.5 or later. + +```sh +opam repo add open-opam https://github.com/open-opam/opam-repository.git +opam install spindle +``` + +This installs the framework and everything it needs, `dune` and the +`ppx_wiretype` deriver included. The database and the command line are +packages of their own, so an app that uses neither never installs them; +their tutorials install them when you get there: + +| Package | Libraries | What for | +|---|---|---| +| `spindle` | `spindle`, and with it `spindle-http` and `spindle-client` | The framework, HTTP itself, and a client for calling other servers | +| `spindle-sqlite` | `spindle-sqlite` | [Database](tutorial/database.md), on SQLite ([guide](guide/databases.md#sqlite)) | +| `spindle-postgres` | `spindle-postgres` | [Database](tutorial/database.md), on Postgres ([guide](guide/databases.md#postgres)) | +| `spindle-cli` | `spindle-cli` | [Client schemas](tutorial/client-schemas.md#setting-up-the-command-line) | + +A program names the libraries it uses in its `dune` file; +[your first app](tutorial/first-app.md) writes one, next. diff --git a/agents/pages/reference.md b/agents/pages/reference.md new file mode 100644 index 0000000..6a31db7 --- /dev/null +++ b/agents/pages/reference.md @@ -0,0 +1,76 @@ +# Reference + +Every module's interface, generated by odoc from its `.mli`, where each +function says what it does, what it refuses and what it defaults to. + +## The packages + +Each library is separate, so a program links only what it uses. A `dune` +file names a library as it is installed (`spindle-http`); OCaml code names +it as a module (`Spindle_http`). + +| Package | Libraries | What it is | +|---|---|---| +| `spindle` | `spindle` | The framework; installs `spindle-http` and `spindle-client` with it | +| `spindle-http` | `spindle-http` | HTTP as both ends speak it | +| `spindle-client` | `spindle-client` | Calling another server, which installs and links no framework | +| `spindle-sqlite` | `spindle-sqlite` | A server's SQLite: a pool of one file in WAL mode, a transaction per borrow, sessions | +| `spindle-postgres` | `spindle-postgres` | A server's Postgres: bounded connections, a pool, a transaction per borrow, sessions | +| `spindle-mcp` | `spindle-mcp` | A Model Context Protocol server: the routes an agent calls tools and reads and watches resources through | +| `spindle-mcp-client` | `spindle-mcp-client`, `spindle-mcp-client.protocol` | Calling another server's tools, and reading and watching its resources, over MCP, which installs and links no framework, and MCP's messages, which both ends share | +| `spindle-cli` | `spindle-cli` | An application's command line: its API's document, Zod schemas and Melange client | +| [`wiretype`, `ppx_wiretype`](https://hyphatech.github.io/wiretype/) | `wiretype`, `ppx_wiretype` | JSON as descriptions, and the deriver that writes one, released on their own; installed with `spindle` | +| [`rowtype`, `rowtype-sqlite`, `rowtype-postgres`, `rowtype-migrate`](https://hyphatech.github.io/rowtype/) | the same | A statement described once, its SQLite and Postgres backends, and migrations, released on their own; `spindle-sqlite` and `spindle-postgres` each install `rowtype` and their backend, and `rowtype-migrate` is installed beside them (`opam install rowtype-migrate`), which builds the dialect of each backend installed | +| [`postgres-eio`](https://hyphatech.github.io/postgres-eio/) | `postgres-eio` | The Postgres driver, released on its own | + +## Spindle + +- [`Spindle`](https://hyphatech.github.io/spindle/reference/spindle/Spindle/index.html) -- routes, + paths, inputs, dependencies, answers, refusals, cookies, the server, the + log, streams, WebSockets, static files, the test client, and the API + described. The most read: + [`Dep`](https://hyphatech.github.io/spindle/reference/spindle/Spindle/Dep/index.html), + [`Path`](https://hyphatech.github.io/spindle/reference/spindle/Spindle/Path/index.html), + [`Returns`](https://hyphatech.github.io/spindle/reference/spindle/Spindle/Returns/index.html), + [`Refusal`](https://hyphatech.github.io/spindle/reference/spindle/Spindle/Refusal/index.html), + [`Log`](https://hyphatech.github.io/spindle/reference/spindle/Spindle/Log/index.html), + [`Static`](https://hyphatech.github.io/spindle/reference/spindle/Spindle/Static/index.html), + [`Openapi`](https://hyphatech.github.io/spindle/reference/spindle/Spindle/Openapi/index.html) and + [`Test`](https://hyphatech.github.io/spindle/reference/spindle/Spindle/Test/index.html). +- [`Spindle_http`](https://hyphatech.github.io/spindle/reference/spindle-http/Spindle_http/index.html) -- + HTTP as both ends speak it. +- [`Spindle_client`](https://hyphatech.github.io/spindle/reference/spindle-client/Spindle_client/index.html) -- + calling another server. +- [`Spindle_sqlite`](https://hyphatech.github.io/spindle/reference/spindle-sqlite/Spindle_sqlite/index.html) + -- a server's SQLite. +- [`Spindle_postgres`](https://hyphatech.github.io/spindle/reference/spindle-postgres/Spindle_postgres/index.html) + -- a server's Postgres. +- [`Spindle_mcp`](https://hyphatech.github.io/spindle/reference/spindle-mcp/Spindle_mcp/index.html) -- + a Model Context Protocol server. +- [`Spindle_mcp_client`](https://hyphatech.github.io/spindle/reference/spindle-mcp-client/Spindle_mcp_client/index.html) + -- calling another server's tools and reading and watching its resources, and + [`Spindle_mcp_protocol`](https://hyphatech.github.io/spindle/reference/spindle-mcp-client/Spindle_mcp_protocol/index.html) + -- MCP's messages, which both ends share. +- [`Spindle_cli`](https://hyphatech.github.io/spindle/reference/spindle-cli/Spindle_cli/index.html) -- an + application's command line. + +## What it is built on + +Each is released and documented on its own site, and links here go to its +reference there. + +- [`Wiretype`](https://hyphatech.github.io/wiretype/reference/wiretype/Wiretype/index.html) + -- JSON as descriptions, and what `[@@deriving wiretype]` writes. +- [`Rowtype`](https://hyphatech.github.io/rowtype/reference/rowtype/Rowtype/index.html) + -- a statement described once. +- [`Rowtype_sqlite`](https://hyphatech.github.io/rowtype/reference/rowtype-sqlite/Rowtype_sqlite/index.html) + and + [`Rowtype_postgres`](https://hyphatech.github.io/rowtype/reference/rowtype-postgres/Rowtype_postgres/index.html) + -- running one on each database. +- [`Rowtype_migrate`](https://hyphatech.github.io/rowtype/reference/rowtype-migrate/Rowtype_migrate/index.html) + -- migrations, and each database's way of running them: + [`Rowtype_migrate_sqlite`](https://hyphatech.github.io/rowtype/reference/rowtype-migrate/Rowtype_migrate_sqlite/index.html) + and + [`Rowtype_migrate_postgres`](https://hyphatech.github.io/rowtype/reference/rowtype-migrate/Rowtype_migrate_postgres/index.html). +- [`Postgres_eio`](https://hyphatech.github.io/postgres-eio/reference/postgres-eio/Postgres_eio/index.html) + -- the driver. diff --git a/agents/pages/tutorial/bodies.md b/agents/pages/tutorial/bodies.md new file mode 100644 index 0000000..4acffb3 --- /dev/null +++ b/agents/pages/tutorial/bodies.md @@ -0,0 +1,310 @@ +# Request bodies, responses and errors + +This page reads a JSON body, answers with JSON, and says no. Each is a value +declared on the route, so the API's document always matches what the route +does. + +## JSON in, JSON out + +An order is a record whose quantity has bounds. What was placed is another +record, answered at `201`. An item that is sold out is a refusal the +application declares: + +```ocaml +(* A JSON body in, a JSON answer out, and a refusal of the application's + own: POST /orders places an order, 201 with what was placed. + + curl -i localhost:8080/orders -H 'content-type: application/json' \ + -d '{"item": "tea", "quantity": 2}' + curl -i localhost:8080/orders -H 'content-type: application/json' \ + -d '{"item": "tea", "quantity": 0}' + curl -i localhost:8080/orders -H 'content-type: application/json' \ + -d '{"item": "cake", "quantity": 1}' *) + +open Spindle.Syntax + +(* The shape and its bounds are the description's: a quantity of 0 is a 400 + at body.quantity before the handler runs. *) +type order = { item : string; quantity : int [@min 1] [@max 20] } +[@@deriving wiretype] + +type placed = { number : int; item : string; quantity : int } +[@@deriving wiretype] + +(* A rule the description cannot know is the handler's, refused with a code + declared once, with its status and what it means. *) +let sold_out = + Spindle.Refusal.Code.make "sold_out" ~status:`Conflict + ~doc:"The item is sold out." + +let menu = [ ("tea", true); ("coffee", true); ("cake", false) ] + +let place ({ item; quantity } : order) = + match List.assoc_opt item menu with + | Some true -> Ok { number = 1; item; quantity } + | Some false | None -> + Error + (Spindle.Refusal.make sold_out + (Printf.sprintf "There is no %s left today." item)) + +let routes = + [ + Spindle.post ~refuses:[ sold_out ] + Spindle.Path.(s "orders") + (Spindle.Returns.json ~status:`Created placed_json) + (let+ order = Spindle.json order_json in + place order); + ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> Spindle.serve env routes +``` + +```console +$ curl -i localhost:8080/orders -H 'content-type: application/json' \ + -d '{"item": "tea", "quantity": 2}' +HTTP/1.1 201 Created +content-type: application/json +... + +{"number":1,"item":"tea","quantity":2} +``` + +A body of the wrong shape is answered before your handler runs, with every +problem at once: + +```console +$ curl localhost:8080/orders -H 'content-type: application/json' \ + -d '{"quantity": "two"}' +{"error":"invalid","message":"Some of that request is not what it should be.","problems":[{"at":"body.quantity","code":"unexpected_type","message":"This must be a whole number, not text."},{"at":"body.item","code":"required","message":"This is required."}]} + +$ curl localhost:8080/orders -H 'content-type: application/json' \ + -d '{"item": "tea", "quantity": 0}' +{"error":"invalid","message":"Some of that request is not what it should be.","problems":[{"at":"body.quantity","code":"too_small","message":"This must be at least 1."}]} +``` + +A rule only your data can check is the handler's own refusal: + +```console +$ curl -i localhost:8080/orders -H 'content-type: application/json' \ + -d '{"item": "cake", "quantity": 1}' +HTTP/1.1 409 Conflict +content-type: application/json +... + +{"error":"sold_out","message":"There is no cake left today."} +``` + +What happened: + +- `[@@deriving wiretype]` gives each record a description, `order_json` and + `placed_json`. The same value decodes the body, encodes the answer and + describes the shape in the API's document. A shape the deriver cannot + describe is written with + [`wiretype`'s combinators](https://hyphatech.github.io/wiretype/guide/by-hand/). +- `Spindle.json order_json` reads the body. Types, required fields and bounds + like `[@min 1]` are checked for you; a body that fails is a `400`. +- ``Returns.json ~status:`Created placed_json`` declares the answer. The + handler returns the plain record and the framework encodes it. +- `sold_out` is a refusal code, declared once with its status. The route + lists it in `~refuses`. + +## Response types + +A route is `Spindle.get`, `post`, `put`, `patch` or `delete` (or +`Spindle.route meth`), then a path, what it returns, and its inputs. What it +returns decides what the handler must give back: + +```ocaml +Spindle.get path Returns.html + (let+ ... in Ok page) (* a page, 200 *) + +Spindle.get path Returns.text + (let+ ... in Ok "Hello.") (* text, 200 *) + +Spindle.post path (Returns.json ~status:`Accepted verdict_json) + (let+ ... in Ok verdict) (* a value, encoded *) + +Spindle.post path (Returns.empty ()) + (let+ ... in Ok ()) (* nothing, 204 *) + +Spindle.get path Returns.response + (let+ ... in Ok (Response.redirect "/there")) (* a response of its own *) + +Spindle.get path (Returns.events Event.[ declare state ]) + (let+ ... in Ok (fun send -> ...)) (* declared events *) + +Spindle.get path (Returns.websocket chat) + (let+ ... in Ok (fun ws -> ...)) (* a WebSocket *) +``` + +`Returns.json` defaults to `200` and `Returns.empty` to `204`. Event streams +have [their own guide](../guide/sse.md), and so do +[WebSockets](../guide/websockets.md). + +**When success can be one of several statuses** -- made or replaced, queued +or done -- list them, each with a sentence for the document, and return the +one you reached beside the value: + +```ocaml +Spindle.put Path.(s "users" / user_id) + (Returns.json_response user_json + ~statuses:[ (`Created, "The user was made."); (`OK, "The user was replaced.") ]) + (let+ pool = db + and+ id = Spindle.param user_id + and+ body = Spindle.json user_json in + match upsert pool id body with + | Ok (`Made u) -> Ok (`Created, u) + | Ok (`Replaced u) -> Ok (`OK, u) + | Error e -> Error (Spindle_sqlite.refusal e)) +``` + +`Returns.empty_response ~statuses` is the same with no body: the handler +returns `` Ok `Created `` or `` Ok `No_content ``. Every listed status must +be a `2xx`; failing is a refusal. A JSON answer is never `204` or `205`, +which HTTP sends without a body: an answer with nothing to say is +`Returns.empty`'s. + +## Setting cookies and headers + +To set a cookie or a header, take `Spindle.set_cookie` or +`Spindle.add_header` as an input -- each is a function -- and call it: + +```ocaml +let visits = Spindle.Cookie.named "visits" Wiretype.int + +Spindle.get Path.(s "welcome") Returns.text + (let+ set_cookie = Spindle.set_cookie + and+ add_header = Spindle.add_header in + set_cookie (Spindle.Cookie.make visits 3); + add_header ("cache-control", "max-age=60"); + Ok "Welcome back.") +``` + +- What you set is sent with the answer, an `Ok` or a refusal: a session moved + before a refusal still tells the browser where it went. A field the refusal + writes itself, such as `Retry-After`, is sent in place of yours. +- Set cookies with `set_cookie`, never with `add_header ("set-cookie", …)`. +- Some fields are the server's alone to write. A handler that sets one of + them itself, or a header value containing a line break, answers `500`: + - how the answer is framed: `Content-Length`, `Transfer-Encoding`, + `Connection`, `Keep-Alive`, `Upgrade`, `TE` and `Trailer`; + - what the server derives: `Content-Type` (from the route's `Returns`), + `Set-Cookie` (from `set_cookie`), `Date` and `X-Request-Id`. +- To end the connection after an answer, return + `Response.close_connection response` from a `Returns.response` route. + +Signing in and out with a session is shown in +[Sessions](../guide/cookies.md#sessions). + +A route that builds its own answer uses `Returns.response` and `Response`: +`make`, `html`, `json`, `empty`, `redirect`, `stream`, `events`, `refusal`, +and `takeover` for a protocol spoken after HTTP (see the +[`Response` reference](https://hyphatech.github.io/spindle/reference/spindle/Spindle/Response/index.html)). + +## Errors + +An `Error` is always a `Refusal.t`, made from a **code** you declare once +with its status and meaning: + +```ocaml +let conflict = + Refusal.Code.make "conflict" ~status:`Conflict ~doc:"Somebody moved first." + +Error (Refusal.make ~detail:(Store.error_to_string e) conflict + "Somebody moved first.") +``` + +The client gets `{"error": "conflict", "message": "Somebody moved first."}`. +The `~detail` goes to the log only. + +- **List your codes** in the route's `~refuses`. Codes its inputs bring (a + JSON body's `unsupported_media_type`, say) are added for you, and so are + the framework's own the route's document lists from what it reads: + `invalid` where it reads an input, `unreadable` and `too_large` where it + reads a body, `cross_origin` for a method that changes something, + `upgrade_required` for a WebSocket, and `busy` and `internal` everywhere. + Any other -- `Refusal.not_found` from a handler, say -- goes in `~refuses` + like your own. A code nobody declared is still answered, but logged as a + bug, and `Spindle.Test.call` raises on it. +- **A name means one thing.** Two codes with the same name but a different + status or doc are refused when the app is made. +- **A code fails, and an answer succeeds.** A code's status is `4xx` or + `5xx`, and `Returns.json ~status` or `Returns.empty ~status` is `2xx`; + either the other way round is refused when the app is made. +- **A `401` code needs `~challenge`**, the `WWW-Authenticate` value, e.g. + `~challenge:{|Bearer realm="api"|}`. +- **Your own answer for a bad body**: + `Spindle.json ~refusal:(bad_body, "That is not an order.") order_json`, + where `bad_body` is a code you made with `Refusal.Code.make`. The + dependency declares it for you. The client gets only your code and + sentence; the list of problems goes to the log. + +## Forms and file uploads + +A form's fields are typed inputs, read like query parameters. A wrong one is +a problem at `form.`: + +```ocaml +let email = Spindle.Form.required "email" Wiretype.string +let remember = Spindle.Form.checked "remember" + +Spindle.post Path.(s "sign-up") (Spindle.Returns.json account_json) + (let+ email = email and+ remember = remember in + sign_up ~email ~remember) +``` + +- `Form.required`, `optional` and `list` take a wiretype description, as a query parameter does. `checked` is `true` + when the field was sent at all, since an unticked box is not sent. +- The body is read once, however many fields you read, as + `application/x-www-form-urlencoded` or `multipart/form-data`, up to the + server's `max_body`. Any other `Content-Type` is `415`. +- A route reads one body: a form field beside `Spindle.json` is refused when + the app is made. +- **Files** are `Form.File.required`, `optional` and `list`, each a + `Form.File.t` with a `filename` (text a person chose, never a path to + trust), a `content_type` and the `content`. An upload too large to hold + in memory is read with `Spindle.multipart` ([large bodies](#large-bodies)). + +**No CSRF token is needed.** A cross-site `POST` is refused with `403 +cross_origin` before any route sees it. `~check_origin:false` on +`Spindle.serve` turns that check off, and with it your forms' protection; +to accept another site of your own, list it in `~trusted_origins` instead. + +## Large bodies + +`Spindle.json` and `Spindle.body` hold the whole body, up to the server's +`max_body`. A route that takes larger bodies, or smaller, says so in its +own limits, under the server's names: + +```ocaml +Spindle.post + ~limits:(Spindle.Route.Limits.make ~max_body:(64 * 1024 * 1024) ()) + Spindle.Path.(s "import") + ... +``` + +A body held whole must fit the server's `body_budget` too, so a route that +reads one whole with a `max_body` above it is a bug: `500` and an `error` +line naming the route, and `Spindle.Test.call` raises. For an upload too +large to hold, read it as it arrives: + +- **`Spindle.body_stream ()`** hands the handler a `Spindle.Body.t`, + limited to the route's `max_body`. Read it a part at a time with + `Body.read`. A failure (too large, stopped arriving) is already the + refusal to answer with, so `let* part = Spindle.Body.read body in` goes on + through it, as a session's does. +- **`~content_types:[ "text/csv" ]`** accepts only those types, each + `type/subtype`, `type/*` or `type/*+suffix`, compared without case or + parameters. Any other type is answered `415` before a byte is read, and + the API's document lists them as the body's types. +- **`Spindle.multipart ()`** is the same body, split into the parts of + a `multipart/form-data` upload. `Multipart.next` gives a part's head (its + `name`, `filename` and content type), `Multipart.read` its bytes. Their + failures are refusals too. Nothing + is written to a temporary file; where a part goes is up to you. + +A stream can only be read while the handler runs. A route reads one body, +one way: listing a stream beside `Spindle.json` is refused when the app is +made. diff --git a/agents/pages/tutorial/client-schemas.md b/agents/pages/tutorial/client-schemas.md new file mode 100644 index 0000000..46a6897 --- /dev/null +++ b/agents/pages/tutorial/client-schemas.md @@ -0,0 +1,293 @@ +# Client schemas + +Your front end's types come from the same routes as the server: a +TypeScript module of [Zod](https://zod.dev) schemas for every body, answer +and error, or, for a front end written in OCaml, a +[Melange](https://melange.re) module with a function per route. Change a +type in OCaml, generate again, and the front end's +compiler shows you every place that must change with it. + +## Setting up the command line + +Your OCaml project gets a command line of its own: a second executable, +named after the app, built beside the server from the same routes. It never +serves anything; it writes the OpenAPI document and the client schemas into +your front end's folder -- `web/src/` below -- and exits. Install it: + +```sh +opam install spindle-cli +``` + +``` +bin/ +├── dune +├── routes.ml the routes, shared by both +├── main.ml the server +└── notes.ml the command line +``` + +```lisp title="bin/dune" +(executables + (names main notes) + (libraries spindle spindle-cli eio_main) + (preprocess + (pps ppx_wiretype))) +``` + +`notes.ml` makes the app from the routes and hands it to `Spindle_cli.run`: + +```ocaml title="bin/notes.ml" +let () = + Spindle_cli.run ~name:"notes" ~title:"Notes" + ~app:(Spindle.App.make Routes.routes) () +``` + +The app is only described, never started or served. A database app's routes +need nothing to be described: they read their pool as a +[resource](dependencies.md#resources), which the server +supplies and the command line never asks for. + +| Command | What it does | +|---|---| +| `notes api openapi [-o FILE]` | Writes the OpenAPI 3.2 document, to stdout without `-o` | +| `notes api zod [-o FILE]` | Writes the Zod schemas, to stdout without `-o` | +| `notes api melange [-o FILE]` | Writes the OCaml client for Melange, to stdout without `-o` | +| `notes api check --openapi FILE --zod FILE [--melange FILE] [--strict]` | Exits 1 when any file is not what the routes make now | + +Every command has `--help`. + +## Generating the schemas + +```sh +dune build +./_build/default/bin/notes.exe api zod -o web/src/wire.gen.ts +``` + +```typescript title="web/src/wire.gen.ts" +/* Generated from Notes's routes. Do not edit: change the routes, and generate it again. */ + +import { z } from "zod/mini"; + +/** One input that is not what it should be. */ +export const ProblemSchema = z.object({ + /** Where: path.x, query.x, body.x. */ + at: z.string(), + code: z.string(), + message: z.string(), +}); +export type Problem = z.infer; + +/** A refusal: the code a client branches on, and a sentence for a person. */ +export const RefusalSchema = z.object({ + /** The code. */ + error: z.string(), + /** A sentence. */ + message: z.string(), + /** For invalid: each input that is not what it should be. */ + problems: z.optional(z.array(ProblemSchema)), +}); +export type Refusal = z.infer; + +export const NoteSchema = z.object({ + id: z.int(), + text: z.string(), +}); +export type Note = z.infer; + +/** Every code a route may refuse with. */ +export const CodeSchema = z.enum([ + "busy", + "internal", + "invalid", +]); +export type Code = z.infer; + +/** Each route, by method and pattern: the body it reads, and what it answers. */ +export const routes = { + "GET /notes/{note_id}": { + body: null, + answer: { status: 200, schema: NoteSchema }, + }, +} as const; +``` + +Each type is a schema with its TypeScript type beside it, the error shapes +(`Problem`, `Refusal`) among them; then the codes a client may branch on, +and a table of the routes. Objects strip unknown keys, so a server that gains +a field breaks no client. + +## Using them in the front end + +The module imports `zod/mini`, which is in Zod 4 and later: + +```sh +npm install zod +``` + +Parse each answer with its schema. A refusal has the same shape on every +route, so one schema reads all of them: + +```typescript +import { NoteSchema, RefusalSchema } from "./wire.gen"; + +const res = await fetch("/notes/1"); +if (res.ok) { + const note = NoteSchema.parse(await res.json()); // a Note, checked + console.log(note.text); +} else { + const refusal = RefusalSchema.parse(await res.json()); + console.log(refusal.error, refusal.message); // "invalid", "..." +} +``` + +`routes["GET /notes/{note_id}"].answer.schema` is the same `NoteSchema`, for +code that works from the table rather than by name. + +## An OCaml front end + +A front end compiled by Melange calls the routes through a module printed +from them, as the Zod one is: + +```sh +./_build/default/bin/notes.exe api melange -o web/src/api.ml +``` + +Each shape is an OCaml type with the functions that read and write it, +and each route a function named by its operation, its inputs labelled and +typed, answering a promise of a `result`: + +```ocaml title="web/src/api.ml" +let get_notes_note_id ?origin ~note_id () = ... +(* (note, Route.error) result Js.Promise.t *) +``` + +```ocaml +Api.get_notes_note_id ~note_id:1. () +|> Js.Promise.then_ (fun result -> + (match result with + | Ok (note : Api.note) -> Js.log note.text + | Error (`Refused (r : Api.refusal)) -> Js.log r.message + | Error e -> Js.log (Api.Route.error_to_string e)); + Js.Promise.resolve ()) +``` + +A path parameter is labelled, a query parameter or a header optional where +the route does not need it, and a body is `~body`; a form's file is a +`Js.File.t`. What a call can come to is `Route.error`: `` `Invalid `` an +input that breaks its description, every problem listed and nothing sent; +`` `Lost `` no answer; `` `Refused `` the server's refusal; and +`` `Unexpected `` an answer the route does not say it gives. An integer with +no bounds within 32 bits is a `float`, which holds every whole number a +browser can. `origin` goes before every path, none unless given, so a page +calls its own origin. + +A stream of events and a WebSocket each have a function too, handed what +arrives and answering at once a value to stop it with: + +```ocaml +let stream = + Api.get_ticks ~count:3. + ~on_event:(function + | Api.Tick n -> Js.log n + | Api.Line text -> Js.log text) + () + +(* Api.Route.Stream.close stream, when the page no longer needs it; and + Api.Route.Stream.ended stream, a (unit, Route.error) result promise *) + +let socket = + Api.get_chat_room ~room:"r" ~on_message:(fun (m : Api.said) -> Js.log m.text) () + +let sent = Api.Route.Socket.send socket { text = "hi" } +``` + +A stream is read over `fetch`, so it sends headers and reads a refusal as +any route does, and nothing reconnects it: one that ends is called again by +whoever wants more. A socket's `send` is typed by what the route reads, +checked before it goes and held until the socket opens. A socket that reads +a header has no function, since a browser's WebSocket sends none of the +page's choosing, nor has a route that answers a response of any kind or +reads a body a part at a time; a cookie is the browser's to send. The +module needs no library: it is Melange over the browser's `fetch`. + +## Checking them in CI + +Commit the schemas and the OpenAPI document, and run `api check` in CI: it +exits 1 when any is not what the routes make now, so a front end is never +typed against an API that changed under it. A Makefile keeps the paths in +one place: + +```make title="Makefile" +NOTES = ./_build/default/bin/notes.exe +OPENAPI = web/src/openapi.gen.json +WIRE = web/src/wire.gen.ts + +wire: ## write the API's document and the client's Zod from the routes + dune build + $(NOTES) api openapi -o $(OPENAPI) + $(NOTES) api zod -o $(WIRE) + +check-wire: ## fail when either is not what the routes make + dune build + $(NOTES) api check --openapi $(OPENAPI) --zod $(WIRE) --strict +``` + +`--strict` also fails when anything is described loosely: see +[the report](openapi.md#the-openapi-document). + +The whole command line, routes included, in one file + +```ocaml +(* An application's command line: its API's document, its client's Zod + schemas and its OCaml client for Melange, written from the routes without + serving them. + + dune exec examples/api_cli.exe -- api openapi + dune exec examples/api_cli.exe -- api zod -o wire.gen.ts + dune exec examples/api_cli.exe -- api melange -o api.ml + dune exec examples/api_cli.exe -- api check \ + --openapi openapi.json --zod wire.gen.ts *) + +open Spindle.Syntax + +type note = { id : int; text : string } [@@deriving wiretype] + +let note_id = Spindle.Path.int "note_id" + +let routes = + [ + Spindle.get ~summary:"One note" + Spindle.Path.(s "notes" / note_id) + (Spindle.Returns.json note_json) + (let+ id = Spindle.param note_id in + Ok { id; text = "Buy milk" }); + ] + +(* The app is only described, never started, so a resource its routes read + -- a pool, a client -- need not exist. *) +let () = + Spindle_cli.run ~name:"notes" ~title:"Notes" ~app:(Spindle.App.make routes) () +``` + +## Generating them from code + +The command line calls one function you can call yourself: + +```ocaml +Spindle.Zod.schemas app (* TypeScript: zod/mini *) +Spindle.Melange.client app (* OCaml for Melange *) +``` + +Each answers a `result`; its `Error` names two different types described +under one name, two routes whose paths make one `operationId` +(`/a-b` and `/a_b`), two whose paths differ only in a parameter's +name (`/items/{id}` and `/items/{item}`), and routes told apart by a +parameter's type that answer in different ways or read different bodies. +The Melange client's also names where two names in the module would be +one: two components one name in OCaml, an operation named as a +component's function, or a route with two inputs under one label. Routes +told apart by a parameter's type are one entry, whose body and answer are +either route's. + +That is the tutorial. The [guides](../guide/pages.md) take each of the +rest a page at a time. diff --git a/agents/pages/tutorial/database.md b/agents/pages/tutorial/database.md new file mode 100644 index 0000000..c673900 --- /dev/null +++ b/agents/pages/tutorial/database.md @@ -0,0 +1,339 @@ +# Database + +Read rows into typed values, write several rows that all land or none, and +answer sensibly when the database is busy. Statements are +[`rowtype`](https://hyphatech.github.io/rowtype/)'s: a value holding its SQL +and the types of its parameters and rows. + +This page uses SQLite, a database in one file, so there is no server to +start. On Postgres every step is the same with `Spindle_postgres` in place +of `Spindle_sqlite`. [Databases](../guide/databases.md) lists each one's +settings. + +## 1. Install + +```sh +opam install spindle-sqlite rowtype-migrate +``` + +`spindle-sqlite` brings `rowtype` and `rowtype-sqlite`. `rowtype-migrate` is +the command that makes your tables. Add the libraries to `bin/dune`: + +```lisp +(executable + (name main) + (libraries spindle spindle-sqlite rowtype rowtype-sqlite eio_main) + (preprocess (pps ppx_wiretype))) +``` + +## 2. Make the table + +A table is made by a migration, a SQL file in `migrations/`: + +```console +$ rowtype-migrate new create_names +migrations/20261021000000_create_names.sql +``` + +```sql +-- create_names: the names sql_query lists and sql_transaction claims. + +create table names ( + name text primary key, + claimed_at text not null +) strict; +``` + +Make the database and apply the migration: + +```console +$ rowtype-migrate create --url sqlite:names.db +$ rowtype-migrate up --url sqlite:names.db +``` + +Run `up` before the server starts, never from the server: every instance +of it would race to apply the same file. +[rowtype's guide to migrations](https://hyphatech.github.io/rowtype/guide/migrations/) covers the +rest of the command. + +## 3. Read rows + +A statement says its SQL, its parameters and the type of each row. +`Pool.exec` runs it on a connection borrowed from the pool, and +`Spindle_sqlite.refusal` turns a failure into an answer: + +```ocaml title="names_query.ml" +(* The statement sql_query runs, and the handler that runs it on a pool. *) + +module S = Rowtype + +let claimed = + S.list ~params:S.unit ~row:S.text "select name from names order by name" + +(* A borrow that waits past the pool's limit is [`Pool `Busy], which [refusal] + answers 503: an overloaded server says so rather than answering late. *) +let list_names pool = + Spindle_sqlite.Pool.exec pool claimed () + |> Result.map_error Spindle_sqlite.refusal +``` + +A route reads the pool as a dependency, `db`, made once with +`Dep.of_resource`. The routes are then a plain value that exists before any +database does: + +```ocaml title="names_routes.ml" +(* The routes sql_query serves, reading the pool as a dependency. *) + +open Spindle.Syntax + +(* The pool, as the routes read it: supplied where the server starts. *) +let db : Spindle_sqlite.Pool.t Spindle.Dep.t = + Spindle.Dep.of_resource "database" + +let routes = + [ + Spindle.get + Spindle.Path.(s "names") + (Spindle.Returns.json (Wiretype.list Wiretype.string)) + (let+ pool = db in + Names_query.list_names pool); + ] +``` + +The program makes the pool from the database's file and hands it to the +server with `~resources`: + +```ocaml title="sql_query.ml" +(* A pool of connections to a SQLite file, and a route that runs a statement + on it: /names answers the names claimed, which sql_transaction claims. + + rowtype-migrate create --url sqlite:names.db + rowtype-migrate up --dir examples/migrations --url sqlite:names.db + dune exec examples/sql_query.exe *) + +(* The pool opens every connection at once, so a file that cannot be opened + is a server that does not start. *) +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> + Spindle_sqlite.Pool.run env "names.db" @@ fun pool -> + Spindle.serve env + ~resources:[ Spindle.Dep.resource Names_routes.db pool ] + Names_routes.routes +``` + +`Pool.run` opens every connection before the server listens. A file that +cannot be opened stops the program, saying why. A route that reads a +resource the server was not given stops it too, naming both. + +Run it from the repository's root: + +```console +$ rowtype-migrate create --url sqlite:names.db +$ rowtype-migrate up --dir examples/migrations --url sqlite:names.db +$ dune exec examples/sql_query.exe +$ curl localhost:8080/names +[] +``` + +## 4. Write in a transaction + +Claiming a name is an insert and a read in one transaction. The answer is +`201` the first time and `200` every time after: + +```ocaml title="name_claim.ml" +(* Claiming a name, in one transaction: the write sql_transaction's route + makes. *) + +open Spindle.Syntax +module S = Rowtype +module Sq = Rowtype_sqlite + +type claim = { name : string; claimed_at : Ptime.t } [@@deriving wiretype] + +(* The database says whether this request made the row: an insert that meets + one already there changes nothing, and counts none. *) +let insert_name = + S.exec_count ~params:(S.t2 S.text S.instant) + "insert into names (name, claimed_at) values ($1, $2) on conflict (name) \ + do nothing" + +let when_claimed = + S.find ~params:S.text ~row:S.instant + "select claimed_at from names where name = $1" + +(* One transaction, so the name is claimed and read in one go: [Ok] commits + both statements and a failure rolls both back. *) +let claim pool name ~now = + Spindle_sqlite.Pool.transaction ~behaviour:Immediate pool (fun db -> + let* made = Sq.run db insert_name (name, now) in + let* claimed_at = Sq.run db when_claimed name in + Ok ((if made = 1 then `Created else `OK), { name; claimed_at })) + |> Result.map_error Spindle_sqlite.refusal +``` + +`Pool.transaction` borrows a connection and runs the function in one +transaction. `Ok` commits and `Error` rolls back. `~behaviour:Immediate` +takes SQLite's write lock as the transaction begins, which a transaction +that reads and then writes needs. + +The handler returns the status beside the value, so the route lists both +with `Returns.json_response`, as `sql_transaction.ml` below does. + +```console +$ curl -i -X PUT localhost:8080/names/ada +HTTP/1.1 201 Created +... +{"name":"ada","claimed_at":"2026-10-08T09:24:46.621Z"} + +$ curl -i -X PUT localhost:8080/names/ada +HTTP/1.1 200 OK +... +{"name":"ada","claimed_at":"2026-10-08T09:24:46.621Z"} +``` + +The rest of the app: its route and its server + +```ocaml title="sql_transaction.ml" +(* A write in one transaction, and an answer that says what became of it: + PUT /names/{name} claims a name, 201 the first time and 200 every time + after, with when it was first claimed. + + rowtype-migrate create --url sqlite:names.db + rowtype-migrate up --dir examples/migrations --url sqlite:names.db + dune exec examples/sql_transaction.exe + curl -i -X PUT localhost:8080/names/ada 201 + curl -i -X PUT localhost:8080/names/ada 200 *) + +open Spindle.Syntax + +let name = Spindle.Path.string "name" + +let db : Spindle_sqlite.Pool.t Spindle.Dep.t = + Spindle.Dep.of_resource "database" + +(* Every branch returns the status it reached, and the route lists each with + when it happens, which is what the API's document says of it. *) +let routes = + [ + Spindle.put ~summary:"Claim a name" + Spindle.Path.(s "names" / name) + (Spindle.Returns.json_response Name_claim.claim_json + ~statuses: + [ + (`Created, "The name was free, and is now claimed."); + (`OK, "The name was claimed already."); + ]) + (let+ pool = db and+ name = Spindle.param name and+ now = Spindle.now in + Name_claim.claim pool name ~now); + ] + +(* The table is the migration's, made before the server starts: a server + that made it would race every other instance of itself to. *) +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> + Spindle_sqlite.Pool.run env "names.db" @@ fun pool -> + Spindle.serve env ~resources:[ Spindle.Dep.resource db pool ] routes +``` + +## 5. Answer failures + +`refusal` turns any failure you do not handle into a status, and logs the +detail: + +| Failure | Answer | +|---|---| +| `` `Pool `Busy ``, no connection free within the wait | `503`, logged as a warning | +| `` `Pool `Closed ``, the server is shutting down | `503`, logged as a warning | +| `` `Not_serializable ``, a lock held past the wait | `503` | +| anything else | `500` | + +A `503` carries `Retry-After: 1`, since asking again may succeed. + +Handle the failures you expect before `refusal`. A unique key refused is a +`` `Conflict `` naming the columns, `users.email` on SQLite, or the +constraint, `users_email_key` on Postgres: + +```ocaml +match Spindle_sqlite.Pool.exec pool add_user (name, email) with +| Ok id -> Ok id +| Error (`Conflict (Some "users.email")) -> + Error (Spindle.Refusal.make email_taken "That address is taken.") +| Error e -> Error (Spindle_sqlite.refusal e) +``` + +`email_taken` is a refusal code of your own, listed in the route's +`~refuses` so its documentation shows it: + +```ocaml +let email_taken = + Spindle.Refusal.Code.make "email_taken" ~status:`Conflict + ~doc:"An account already uses this email address." +``` + +To log a failure rather than answer it, `error_to_string` gives its words, +never a parameter's value: + +```ocaml +Logs.err (fun m -> m "could not list: %s" (Spindle_sqlite.error_to_string e)) +``` + +If your own errors are an ordinary variant, wrap the work's errors once, +and the transaction's own failures stay apart from them: + +```ocaml +let transaction pool ~failed work = + match + Spindle_sqlite.Pool.transaction pool (fun db -> + Result.map_error (fun e -> `Work e) (work db)) + with + | Ok v -> Ok v + | Error (`Work e) -> Error e + | Error ((`Pool _ | #Rowtype_sqlite.Transaction.failure) as f) -> + Error (failed f) +``` + +## 6. Open the transaction in the handler + +A transaction holds its rows locked while it is open. Let the dependencies +run first, the body read and the cookies parsed, and open the transaction +inside the handler, around the database work alone: + +```ocaml +let add_item = + Spindle.post + Spindle.Path.(s "orders" / order_id / s "items") + (Spindle.Returns.json ~status:`Created item_json) + (let+ pool = db + and+ id = Spindle.param order_id + and+ item = Spindle.json item_json in + match + Spindle_sqlite.Pool.transaction ~behaviour:Immediate pool (fun db -> + let* () = Sq.run db reserve (id, item.sku) in + let* () = Sq.run db insert_item (id, item.sku, item.quantity) in + Ok item) + with + | Ok item -> + notify id item; (* only once the work is committed *) + Ok item + | Error e -> Error (Spindle_sqlite.refusal e)) +``` + +- **Read inside, not before.** A dependency hands over a credential, a + cookie or a token, never a resolved user: a row read before the + transaction and written inside it is a race. +- **What is not the database comes after.** A publish, a stream or a call to + another server goes after the transaction returns, so it runs only once + the work is kept. + +## 7. Keep sessions in the database + +`Spindle_sqlite.Session.store db` keeps +[sessions](../guide/cookies.md#sessions) in the table +`spindle_sessions`. The package ships the migration that makes it, and +`--source` applies it before yours: + +```console +$ rowtype-migrate up --source spindle-sqlite --url sqlite:names.db +``` diff --git a/agents/pages/tutorial/dependencies.md b/agents/pages/tutorial/dependencies.md new file mode 100644 index 0000000..aa7eb1f --- /dev/null +++ b/agents/pages/tutorial/dependencies.md @@ -0,0 +1,426 @@ +# Dependencies + +A handler needs things from the request: a path parameter, a query string, +a header, a cookie, the body -- and things built from them, like who is +signed in or which page of a list was asked for. Each of these is a +*dependency*, and a handler lists the ones it reads. + +## How it works + +Each input is a value of type `'a Spindle.Dep.t`. A handler lists them with +`let+ … and+ …` -- read it as a parameter list: + +```ocaml +open Spindle.Syntax + +(let+ id = Spindle.param user_id + and+ page = Spindle.Query.optional "page" Wiretype.int + and+ now = Spindle.now in + answer id ~page ~now) +``` + +`open Spindle.Syntax` brings in `let+` and `and+`, and `let*` for the +`result` a handler answers (`Result.bind`), and nothing else. Every +input is worked out before the code after `in` runs, and that code sees +plain values: an `int64` (if `user_id` is a `Path.int64`), an `int option`, +a `Ptime.t`. + +- **A bad request is answered all at once.** Every wrong path parameter, + query parameter and header is reported in one `400`, each problem + at its place (`path.user_id`, `query.page`). Only when those are all fine + is the body read, and its problems (`body.items[2].count`) are then + reported together the same way. The handler never runs. +- **A route's inputs are known without running it.** That is what the API's + [document](openapi.md) is made from. +- **A dependency can be made of other dependencies**, and a route lists it + just like a built-in. + +## A query parameter + +A query parameter is read by the wiretype description of its type -- the +one a JSON body's member would be -- so the handler is handed a `float` and is arithmetic and nothing else: + +```ocaml +(* A typed query parameter: /fahrenheit?celsius=21 answers + {"fahrenheit":69.8}. The parameter arrives as a float, so the handler is + arithmetic and nothing else; /fahrenheit?celsius=warm and a missing one + are refused at [query.celsius] before it runs. *) + +open Spindle.Syntax + +type reading = { fahrenheit : float } [@@deriving wiretype] + +let to_fahrenheit celsius = Ok { fahrenheit = (celsius *. 9. /. 5.) +. 32. } +let celsius = Spindle.Query.required "celsius" Wiretype.number + +let routes = + [ + Spindle.get + Spindle.Path.(s "fahrenheit") + (Spindle.Returns.json reading_json) + (let+ celsius = celsius in + to_fahrenheit celsius); + ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> + Spindle.serve env (routes @ Spindle.Openapi.routes routes) +``` + +```console +$ curl 'localhost:8080/fahrenheit?celsius=21' +{"fahrenheit":69.8} + +$ curl 'localhost:8080/fahrenheit?celsius=warm' +{"error":"invalid","message":"Some of that request is not what it should be.","problems":[{"at":"query.celsius","code":"unexpected_type","message":"This must be a number."}]} + +$ curl localhost:8080/fahrenheit +{"error":"invalid","message":"Some of that request is not what it should be.","problems":[{"at":"query.celsius","code":"required","message":"This is required."}]} +``` + +- `Query.required` refuses a missing parameter; `Query.optional` hands over + an `option`, and `Query.list` every value given. +- `Openapi.routes routes` serves the API's own document beside it: the + [OpenAPI](openapi.md) page. + +## Custom dependencies + +A page of a list is two query parameters, read as one value, each held to +its bounds by its description: + +```ocaml title="paging.ml" +(* A dependency of the application's own: a page of a list, read from two + query parameters, which dependencies serves. *) + +open Spindle.Syntax + +type page = { page : int; per_page : int } + +(* Two query parameters read as one value, each by the description a body's + member would be: a number outside its bounds is a problem at its place, + as a number that does not parse is, and the document says both bounds. *) +let paging = + let+ page = Spindle.Query.default "page" (Wiretype.int_bounded ~min:1 ()) 1 + and+ per_page = + Spindle.Query.default "per_page" + (Wiretype.int_bounded ~min:1 ~max:100 ()) + 10 + in + { page; per_page } +``` + +A route lists it like any built-in: + +```ocaml title="dependencies.ml" +(* Inputs, and a dependency of the application's own made of them: a page + of a list, read from two query parameters, and refused at the one that + is not a page's. + + curl 'localhost:8080/books?page=2&per_page=2' + curl -i 'localhost:8080/books?page=0' + curl -i 'localhost:8080/books?page=two' *) + +open Spindle.Syntax + +let books = [ "Emma"; "Middlemarch"; "Persuasion"; "Ulysses"; "Walden" ] + +let books_on { Paging.page; per_page } = + Ok (List.filteri (fun i _ -> i / per_page = page - 1) books) + +let routes = + [ + Spindle.get + Spindle.Path.(s "books") + (Spindle.Returns.json (Wiretype.list Wiretype.string)) + (let+ paging = Paging.paging in + books_on paging); + ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> Spindle.serve env routes +``` + +```console +$ curl 'localhost:8080/books?page=2&per_page=2' +["Persuasion","Ulysses"] + +$ curl 'localhost:8080/books?page=0&per_page=500' +{"error":"invalid","message":"Some of that request is not what it should be.","problems":[{"at":"query.page","code":"too_small","message":"This must be at least 1."},{"at":"query.per_page","code":"too_large","message":"This must be at most 100."}]} + +$ curl 'localhost:8080/books?page=two&per_page=x' +{"error":"invalid","message":"Some of that request is not what it should be.","problems":[{"at":"query.page","code":"unexpected_type","message":"This must be a whole number."},{"at":"query.per_page","code":"unexpected_type","message":"This must be a whole number."}]} +``` + +- A bound is the description's, as it is a body member's: + `Wiretype.int_bounded`, `number_bounded`, `string_bounded` and the rest, + refused with wiretype's code -- `too_small`, `too_large`, + `not_a_multiple`, `too_short`, `too_long` -- and said in the document. +- `Dep.join` makes a dependency that may refuse: write a `let+` block that + answers `Ok` or `Error`, and wrap it. `Ok v` gives `v`; `Error` refuses + the request. `~refuses` names the codes it may refuse with, so the + document lists them; a `400` about an input needs none. + + ```ocaml + let bearer = + Spindle.Dep.join ~refuses:[ signed_out ] + (let+ token = Spindle.Header.optional "authorization" Wiretype.string in + Option.to_result ~none:(Spindle.Refusal.make signed_out "Sign in.") token) + ``` +- `Dep.problem ~at ~code message` reports a wrong value at its place, + alongside every other problem in the request. +- `Dep.map f d` derives a value that cannot fail: + `Spindle.Dep.map String.lowercase_ascii email`. +- `Dep.refuse refusal` always refuses, for a route that is switched off. +- `Dep.of_body ~content_types:[ "text/csv" ] parse` reads + the whole body as a string and parses it into a type of your own. A + request of any other `Content-Type` is answered `415` before its body is + read. + +## Custom error codes + +For a refusal that isn't "this input is wrong", declare a code and list it +with `~refuses`, so the route's document names it. A bearer token read from +the `Authorization` header: + +```ocaml title="bearer_token.ml" +(* A bearer token, read from the Authorization header and refused with a + 401 when it is missing or is not one: the dependency bearer_auth's routes + list. *) + +open Spindle.Syntax + +(* A 401 names how to authenticate, in WWW-Authenticate, so the code carries + the challenge. *) +let signed_out = + Spindle.Refusal.Code.make "signed_out" ~status:`Unauthorized + ~challenge:{|Bearer realm="notes"|} ~doc:"No valid bearer token was sent." + +let please_sign_in = Spindle.Refusal.make signed_out "Please sign in." + +(* Made of the framework's own header input, read as credentials -- a + scheme compared without case, so "bearer abc" is a bearer token as + "Bearer abc" is -- and [join] turns a check that fails into a refusal of + the request. The header is optional rather than required because a + missing token is a 401, not a malformed request. [credential] names the + scheme for the document, which reads the rest: Authorization is HTTP + authentication, and a 401 means the token is needed. *) +let bearer = + Spindle.Dep.credential ~scheme:"bearer" + (Spindle.Dep.join ~refuses:[ signed_out ] + (let+ credentials = + Spindle.Header.optional "authorization" Spindle.Header.credentials + in + match credentials with + | Some { scheme = "bearer"; value = Token68 token } -> Ok token + | Some _ | None -> Error please_sign_in)) +``` + +- The header is `optional`: a missing token should be a `401`, not a `400`. +- A `401` code needs a `~challenge` (the `WWW-Authenticate` value); + the app refuses to start without one. +- Unlike an input problem, a refusal like this ends the request at once. +- `Dep.credential ~scheme:"bearer"` tells the + [document](openapi.md) that this input proves who is + asking, so it lists the scheme and which routes need it. +- The dependency hands over the token. Whose it is is the *caller*, which + `Access.principal` reads from it, and a route that reads the caller, or + a check of a policy, is called by whoever that lets through + ([Access control](../guide/access.md)). + +The rest of the app: two routes that need the token + +```ocaml title="bearer_auth.ml" +(* A dependency of the application's own: a bearer token, read from the + Authorization header and refused with a 401 when it is missing or is not + one. Whose token it is is the caller, which two routes read, and /docs + says both need a bearer token. + + curl -H 'Authorization: Bearer ada-token' localhost:8080/me + curl -H 'Authorization: Bearer ada-token' localhost:8080/notes/1 + curl -i localhost:8080/notes/1 *) + +open Spindle.Syntax +module Access = Spindle.Access + +(* What the application holds is closed over, not a dependency. *) +let people = [ ("ada-token", "Ada"); ("alan-token", "Alan") ] +let notes = [ (1, ("Ada", "Write to Charles")); (2, ("Alan", "Fix the bombe")) ] + +(* The caller: whoever the token belongs to. *) +let me = + Access.principal ~id:Fun.id + (Spindle.Dep.join + ~refuses:[ Bearer_token.signed_out ] + (let+ token = Bearer_token.bearer in + Option.to_result ~none:Bearer_token.please_sign_in + (List.assoc_opt token people))) + +type action = Read + +(* A note is its owner's. *) +let owners = + Access.policy "notes" me + ~action:(function Read -> "read") + (fun name Read (owner, _) -> + if String.equal owner name then Access.Allow + else Access.Deny "not the owner") + +let note_id = Spindle.Path.param "note_id" Wiretype.int + +let note = + Access.resource owners + (Spindle.Dep.join + ~refuses:[ Spindle.Refusal.Code.not_found ] + (let+ id = Spindle.param note_id in + Option.to_result ~none:Spindle.Refusal.not_found + (List.assoc_opt id notes))) + +let routes = + [ + Spindle.get ~summary:"Who the token belongs to" + Spindle.Path.(s "me") + (Spindle.Returns.json Wiretype.string) + (let+ name = Access.caller me in + Ok name); + (* Somebody else's note is answered as a missing one, so an id says + nothing about whether a note exists. *) + Spindle.get ~summary:"One of your notes" + Spindle.Path.(s "notes" / note_id) + (Spindle.Returns.json Wiretype.string) + (let+ _, text = Access.can Read note in + Ok text); + ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> + Spindle.serve env (routes @ Spindle.Openapi.routes ~title:"Notes" routes) +``` + +## Query, header and cookie inputs + +Query parameters, headers and cookies are read by a wiretype description +-- the one a JSON body's member is read by, and a path parameter too -- as +`Wiretype.of_text` reads one: a scalar's text is its JSON, and a string's is +itself: + +```ocaml +Spindle.Query.optional "page" Wiretype.int (* int option *) +Spindle.Query.default "limit" (Wiretype.int_bounded ~max:100 ()) 20 +Spindle.Query.required "q" Wiretype.string (* or a 400 *) +Spindle.Query.list "tag" Wiretype.string (* ?tag=a&tag=b *) +Spindle.Header.optional "x-count" Wiretype.int (* matched without case *) +Spindle.Header.joined "accept" Spindle.Header.accept (* every line, joined *) +``` + +- **A parameter sent twice** (`?role=viewer&role=admin`) is read by its + first value, as a browser's `URLSearchParams.get` reads it; `Query.list` + reads every one. A repeated parameter is a valid URL, so it never fails a + route. A form's field is read the same way. A header is the exception: one + that holds a single value sent twice is an invalid message by RFC 9110, and + is refused. +- **Any scalar description**: `Wiretype.string`, `int`, `int64`, `number`, + `bool`, `uuid ()` (a `Uuidm.t`, as a row's), `date`, `instant` (a + `Ptime.t`), their bounded forms, `enum`, and `kind` for a type of your own. + Its problems are wiretype's, as a body's are; one of no scalar -- an + object, a list -- is refused when the app is made. +- **Structured headers** have descriptions that parse them, in + `Spindle.Header`: `media_type`, `credentials`, `accept`, `weighted`, + `cache_control`, `forwarded`, and `structured_item`, `structured_list`, + `structured_dictionary`. +- **A header sent on several lines** is read whole by `Header.joined`, its + lines joined by `, `, for a field HTTP defines as a list. To any other + reader it is malformed, a `400`: a value sent twice is no message HTTP + allows. + +**A cookie is declared once**, with its name and description. That one value reads +it and sets it: + +```ocaml +let visits = Spindle.Cookie.named "visits" Wiretype.int + +Spindle.Cookie.optional visits (* an input: int option *) +Spindle.Cookie.make visits 3 (* a cookie to set *) +Spindle.Cookie.clear visits (* removes it *) +``` + +A handler sets a cookie by listing `Spindle.set_cookie` among its inputs and +calling it ([how](bodies.md#setting-cookies-and-headers)). A +cookie holds any text: `Kim Li` is written `Kim%20Li` and read back as it +was. Signed and encrypted cookies and sessions are on [their own +page](../guide/cookies.md). + +**Other built-ins**: + +- `Spindle.param`: a path parameter. +- `Spindle.now`: the instant the request is answered at, a `Ptime.t`. +- `Spindle.request`: the whole `Spindle.Request.t`. +- `Spindle.request_id`: the id on every log line of this request. +- `Spindle.peer`: the address that opened the connection, which is the + proxy when there is one. +- `Spindle.client_ip`: who is asking. It is the peer, or, when the peer is a + proxy you told the server to trust, the address that proxy forwarded for + ([the client's IP address](../guide/cookies.md#the-clients-ip-address)). +- `Spindle.set_cookie` and `Spindle.add_header`: functions that add a + cookie or a header to the answer. +- `Spindle.client_gone`: a promise resolved once the client has gone, for a + long-running [event stream](../guide/sse.md). +- `Spindle.body`, `Spindle.json`, `Spindle.body_stream` and + `Spindle.multipart`: the body, [read whole or as it + arrives](bodies.md#large-bodies). + +## How dependencies run + +- **The body is read last.** Everything else runs first, so a request + refused for a missing token never has its body read. +- **A dependency runs once per request**, however many others use it: two + dependencies that both use `bearer` read the header once. +- **Sharing works by identity.** Define a dependency once, `let current = + …`, and use that value everywhere. A function `let current () = …` called + twice makes two dependencies, which run twice. `Dep.uncached d` runs `d` + at every use on purpose. +- **What the app holds is a resource**: read like any other dependency, + but supplied once, where the server starts ([below](#resources)). + +Reading what no built-in reads + +`Dep.of_request f` runs `f` on the `Spindle.Request.t`. Say what it reads +with `~needs` (a `Custom` need names something the framework has no word +for) and how it may refuse with `~refuses`, so the document can list it; +without `~needs` it is opaque. `Dep.bind` is for a dependency that needs +another's value to decide what to read next; it is opaque too. + +## Resources + +Every dependency above is request-wide: worked out from the request, once +per request. A resource is app-wide: a database pool, a client, a +[broadcast](../guide/sse.md#broadcasting-to-many-clients) hub, made once +where the program starts. Name it with `Dep.of_resource`, read it like any +other dependency, and supply it when the server starts: + +```ocaml +let db : Spindle_sqlite.Pool.t Spindle.Dep.t = Spindle.Dep.of_resource "database" + +(let+ pool = db and+ id = Spindle.param order_id in ...) + +Spindle.serve env ~resources:[ Spindle.Dep.resource db pool ] routes +``` + +- **The routes stay a value.** They read the pool without holding it, so the + [command line](client-schemas.md) describes them with no + database, and a [test](../guide/testing.md) supplies its own. +- **A missing resource stops the server.** A route that reads one + `~resources` does not hold is refused before the server listens, naming + the route and the resource; so is one supplied twice. One read inside + `Dep.bind` is found only as it runs: unsupplied, it is a `500`, logged + by name. +- **It is no input.** A request does not carry it, so the API's document + and the client schemas never list it. +- **Make it once, at the top level.** It has an identity, as every + dependency has: the value supplied is the value read. + +[Database](database.md) shows the whole shape, and [why a +transaction is not a +dependency](database.md#6-open-the-transaction-in-the-handler). diff --git a/agents/pages/tutorial/first-app.md b/agents/pages/tutorial/first-app.md new file mode 100644 index 0000000..fcaa07b --- /dev/null +++ b/agents/pages/tutorial/first-app.md @@ -0,0 +1,141 @@ +# Your first app + +Make a project, write a server that answers one request, and run it. This +assumes [Spindle is installed](../install.md). + +## 1. Make the project + +A project is a folder with three files: + +``` +hello/ +├── dune-project +└── bin/ + ├── dune + └── main.ml +``` + +```sh +mkdir -p hello/bin +cd hello +``` + +`dune-project` marks the folder as a dune project: + +```lisp title="dune-project" +(lang dune 3.18) +``` + +`bin/dune` builds a program named `main` that uses Spindle and Eio's event +loop. The `preprocess` line lets `[@@deriving wiretype]` write a JSON +description of each of your types, which the tutorial uses from the next +page on: + +```lisp title="bin/dune" +(executable + (name main) + (libraries spindle eio_main) + (preprocess + (pps ppx_wiretype))) +``` + +`bin/main.ml` is the server: + +```ocaml title="bin/main.ml" +(* The smallest application: one route, answering at /. + + Every example keeps three things apart -- the handlers, what each + answers; the routes, which URL reaches which handler; and the server -- + so each reads on its own, and a handler is plain OCaml a test can call + without a server. *) + +let good_morning = Ok "Good morning, world!" + +let routes = + [ + Spindle.get Spindle.Path.root Spindle.Returns.text + (Spindle.Dep.return good_morning); + ] + +let () = Eio_main.run @@ fun env -> Spindle.serve env routes +``` + +## 2. Run it + +From the `hello` folder: + +```console +$ dune exec ./bin/main.exe +Listening on http://localhost:8080 (127.0.0.1 and [::1]) +``` + +`dune exec` compiles, reports any mistake with its file and line, and runs. +Open [http://localhost:8080](http://localhost:8080), or from another terminal: + +```console +$ curl localhost:8080 +Good morning, world! +``` + +`Ctrl-C` stops the server. + +:::tip[Rebuilding as you type] +`dune build --watch` in a terminal of its own compiles on every save. +::: + +## 3. What the code says + +- **The answer**, `good_morning`, is `Ok` of the text to send. An `Error` + would refuse the request instead. +- **The routes** are a list. `Spindle.get` is the method, + `Spindle.Path.root` the path `/`, and `Spindle.Returns.text` says it + answers text. The last argument says what the route reads from the request + and how it works out its answer. This route reads nothing and always gives + the same answer, so it is `Spindle.Dep.return good_morning`. The [next + page](routes.md) shows routes that read their inputs. +- **The server**: `Eio_main.run` starts the event loop, and `Spindle.serve` + serves the routes until you stop it. + +## 4. Turn on the log + +Add one line to see every request: + +```ocaml title="bin/main.ml" {2} +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> Spindle.serve env routes +``` + +Every request is now a line with its method, path, status, duration (in +nanoseconds) and an id: + +``` +10:11:03.331 info spindle-http [cm5nxptpka21] GET / 200 http.request.method=GET url.path=/ http.response.status_code=200 duration=14875 http.response.body.size=20 http.route=/ +``` + +Lines look like this in a terminal. When stderr is not a terminal -- a +container, a file, a log collector -- each line is JSON instead. + +The same id is in the answer's `x-request-id` header, so a request a user +reports can be found in the log. More in [logging](logging.md). + +## What you get for free + +Ask for something the server does not do: + +```console +$ curl -i -X DELETE localhost:8080 +HTTP/1.1 405 Method Not Allowed +content-type: application/json +allow: GET, HEAD, OPTIONS +... + +{"error":"method_not_allowed","message":"That is not something you can do here."} +``` + +- Every error in one JSON shape: a code a program can check and a sentence + a person can read. Internal errors go to the log, never to the client. +- Every CPU core serving, from the first request. +- A clean stop on `Ctrl-C`, letting requests in flight finish. + +Another port is one argument: `Spindle.serve env ~port:3000 routes`. diff --git a/agents/pages/tutorial/logging.md b/agents/pages/tutorial/logging.md new file mode 100644 index 0000000..c1183f2 --- /dev/null +++ b/agents/pages/tutorial/logging.md @@ -0,0 +1,162 @@ +# Logging + +Spindle logs every request for you, and every line your code logs during a +request carries that request's id, so one search finds everything it did. + +## Logging from your code + +Logging is [logs](https://erratique.ch/software/logs). Make a source per +part of your app, and log with fields of your own: + +```ocaml title="billing.ml" +(* A part of the application with a log source of its own, whose line + carries a field of the application's: logging serves it. *) + +(* A source per part of the application, so its level can be set alone: + APP_LOG=warn,shop.billing=debug. *) +module Log = (val Logs.src_log (Logs.Src.create "shop.billing") : Logs.LOG) + +let pence = Spindle.Path.int "pence" + +let charge pence = + Log.info (fun m -> + m "charged" ~tags:(Spindle.Log.tags [ ("shop.pence", `Int pence) ])); + Ok "Charged." +``` + +Set the levels and the format from wherever you keep your settings -- here +two environment variables. Spindle reads no environment variable itself: + +```ocaml title="logging.ml" +(* Logging: the levels and the format read from where the application keeps + its settings, and a line of the application's own, which carries the id + of the request that caused it. + + APP_LOG=debug dune exec examples/logging.exe + curl localhost:8080/charge/500 *) + +open Spindle.Syntax + +let routes = + [ + Spindle.get + Spindle.Path.(s "charge" / Billing.pence) + Spindle.Returns.text + (let+ pence = Spindle.param Billing.pence in + Billing.charge pence); + ] + +(* The framework reads no environment variable: the application hands it + two strings, and either left unset is the default. *) +let () = + match + Spindle.Log.configure ~levels:(Sys.getenv_opt "APP_LOG") + ~format:(Sys.getenv_opt "APP_LOG_FORMAT") + with + | Error why -> + prerr_endline why; + exit 1 + | Ok () -> Eio_main.run @@ fun env -> Spindle.serve env routes +``` + +```sh +APP_LOG='info,shop.billing=debug' APP_LOG_FORMAT=pretty dune exec ./bin/main.exe +``` + +```sh +curl localhost:8080/charge/500 +``` + +``` +10:24:06.913 info shop.billing [trpw9jmqsz6a] charged shop.pence=500 +10:24:06.913 info spindle-http [trpw9jmqsz6a] GET /charge/500 200 http.request.method=GET url.path=/charge/500 http.response.status_code=200 duration=259958 http.response.body.size=8 http.route=/charge/{pence} +``` + +Your line carries the request's id, `[trpw9jmqsz6a]`, without being handed +it. The second line is the access line Spindle writes for every request: +method, path, status, duration in nanoseconds, body size and route. When +the answer is a refusal, the line also has `spindle.refusal.code` (say, +`invalid`): search for that field to find every refused request. + +Lines go to stderr. The format is pretty on a terminal and JSON otherwise. +The JSON keys are the ones Datadog and an OpenTelemetry Collector read +without a mapping: + +```json +{"timestamp":"2026-10-08T09:24:07.936Z","level":"info","logger.name":"spindle-http","message":"GET /charge/500 200","request_id":"yxh81c3jxdrr","trace_id":"d94e1ed026bb56ed4360738efdab369b","span_id":"aa5e83d9ed21a352","http.request.method":"GET","url.path":"/charge/500","http.response.status_code":200,"duration":199000,"http.response.body.size":8,"http.route":"/charge/{pence}"} +``` + +`Log.configure` returns an `Error` naming what it could not read, and this +program prints it and exits: + +```console +$ APP_LOG='info,shop=loud' dune exec ./bin/main.exe +"loud" is not a log level +``` + +`Spindle.Log.setup` is the same without strings. A level is a +`Logs.level option`, where `None` turns a source off: + +```ocaml +Spindle.Log.setup ~level:(Some Logs.Info) + ~sources:[ ("shop.billing", Some Logs.Debug) ] + () +``` + +It also takes `?format`, and `?out`, a function that receives each line in +place of stderr: a test's way to keep them. + +## What each line contains + +- **The request id** is on every line the request causes -- yours, the + database's, a call to another server's -- and on fibers it forks. + `Spindle.blocking` takes it onto its systhread for you. For a domain or a + thread you start yourself, wrap the function in `Spindle.Log.carry`. +- **The trace.** In JSON, every line logged during a request also has + `trace_id` and `span_id`; the pretty format shows only the request id. A + request joins the caller's W3C `traceparent`, or starts a trace, and + `Spindle_client` passes it on to the servers it calls. +- **Field names**: put your own under a prefix (`shop.pence`), since keys + like `status`, `host` and `service` mean something to a collector. +- **Failures**: Spindle logs what a handler raises with `error.kind` and + `error.stack`, never its message, which is whatever the raiser wrote -- a + card number, a token. Your own catch-all does the same with + `~tags:(Spindle.Log.tags (Spindle.Log.raised exn bt))`, taking + `bt = Printexc.get_raw_backtrace ()` first thing. +- **Levels**: `error` is a bug, `warn` handled but degraded, `info` what + happened (the access log), `debug` how. A route polled every few seconds + can log its access line at `Debug`, as the health checks do: + `Spindle.get ~access_log:Logs.Debug …`. +- **No secrets.** Spindle never logs a header value, a body, a query string + or a statement's parameters, at any level. + +## Tracing + +To send traces to an OpenTelemetry Collector, give `Spindle.serve` an +exporter: + +```ocaml +Spindle_client.run env @@ fun client -> +Spindle_client.Otlp.run ~clock:(Eio.Stdenv.clock env) + ~endpoint:"http://collector:4318" ~service:"shop" client +@@ fun trace -> Spindle.serve env ~trace routes +``` + +Then every request is a span. A request's span is named by its method and +route (`GET /users/{id}`), a `Spindle_client` call's by its method (`GET`), +and a Postgres statement's `postgresql`. None is ever named by a path, so a +collector keeps one series per route, not one per URL. Add spans of your +own with: + +```ocaml +Spindle.Trace.span "price the order" (fun () -> price order) +``` + +- The exporter posts OTLP JSON to `/v1/traces` every five seconds, or as + soon as 512 spans wait. `?ratio` (default `1.0`) is the share of new + traces kept; a trace joined from a caller is kept when the caller kept it. +- At most 2048 spans wait; past that, and when the collector fails, spans + are dropped and counted in a `warn` line. +- Spans carry no secrets either: never a query string, header or + statement parameter. +- To send spans elsewhere, build your own with `Spindle.Trace.exporter`. diff --git a/agents/pages/tutorial/openapi.md b/agents/pages/tutorial/openapi.md new file mode 100644 index 0000000..c6a06b4 --- /dev/null +++ b/agents/pages/tutorial/openapi.md @@ -0,0 +1,228 @@ +# OpenAPI + +Spindle reads your API's OpenAPI 3.2 document from the routes themselves: +what each route reads, what it answers and every error it may refuse with +are already values on it. You write nothing beside the routes, so the +document never drifts from them. + +## Interactive docs with Scalar + +`Spindle.Openapi.routes` serves an OpenAPI document of the routes you give +it at `/openapi.json`, and interactive docs that render it at `/docs`: + +```ocaml title="openapi.ml" +(* JSON in and out, and the API's document made from the routes: + /openapi.json is OpenAPI 3.2, and /docs is a reference to read it by. + + Nothing is described twice. What a route reads, what it answers and every + code it may refuse with are values on the route, so the document is read + from them. *) + +(* [docs] is the document of the routes it is given, at /openapi.json, and + the reference over it at /docs: routes like any others, served beside + the ones they describe. *) +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> + Spindle.serve env + (Greetings.routes + @ Spindle.Openapi.routes ~title:"Greetings" Greetings.routes) +``` + +Your API docs are at `http://localhost:8080/docs`, generated from your routes +and rendered by [Scalar](https://scalar.com). Each endpoint lists its schema, +with the bounds from your types, and every error it may answer. You can send a +request from the browser with **Test Request**. + +![The reference at /docs](../../../assets/scalar.png) + +*A bill splitter's `POST /split`: the body's bounds come from `[@min]` and +`[@max]` on its type, and every status the route may answer is listed with +what it means.* + +The app in the screenshot + +```ocaml +(* A JSON body with bounds: POST /split with {"total":90,"tip":10,"people":3} + answers {"each":33}. The bounds are the type's, so a body outside them is + refused with every problem at once before [split] runs, and /docs shows + them on the request's schema. *) + +open Spindle.Syntax + +type bill = { + total : float; [@min 0.] + tip : int; [@min 0] [@max 100] (** percent *) + people : int; [@min 1] [@max 50] +} +[@@deriving wiretype] + +type share = { each : float } [@@deriving wiretype] + +let split b = + let total = b.total *. float (100 + b.tip) /. 100. in + Ok { each = total /. float b.people } + +let routes = + [ + Spindle.post + Spindle.Path.(s "split") + (Spindle.Returns.json share_json) + (let+ b = Spindle.json bill_json in + split b); + ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> + Spindle.serve env (routes @ Spindle.Openapi.routes routes) +``` + +- The page's script is compiled into the library and served by your server, + so it works offline. +- Only the routes you pass are described: `api @ site @ Spindle.Openapi.routes + api` keeps a static site out of the document. +- `~at` and `~document` move the page and the document. +- Both are public unless you guard them, as `/metrics` is. `~guard` is a + `unit Dep.t` run first, whose refusal is the answer: + `Spindle.Openapi.routes ~guard:staff_only api`. +- A mistake in the descriptions -- two different types under one name, + two paths that make one `operationId`, one path under two parameter + names, or one operation whose routes answer in different ways or read + different bodies -- raises before the server listens, and so does an + `~at` or a `~document` with a parameter in it, which is no one place. For + routes built at run time, `Spindle.Openapi.make` answers a `result` + instead. + +The routes it describes + +```ocaml title="greetings.ml" +(* The routes openapi describes: JSON in and out, and a refusal of the + application's own. *) + +open Spindle.Syntax + +(* A body and an answer are records; their descriptions are derived. *) +type greeting_request = { name : string; language : string } +[@@deriving wiretype] + +type greeting = { text : string } [@@deriving wiretype] + +(* A code is declared once, with its status and what it means, and the + document lists it under every route that may answer it. *) +let unknown_language = + Spindle.Refusal.Code.make "unknown_language" ~status:`Unprocessable_content + ~doc:"The language is not one of /languages." + +let hellos = [ ("en", "Hello"); ("fr", "Bonjour"); ("uk", "Привіт") ] +let languages = Ok (List.map fst hellos) + +let greet { name; language } = + match List.assoc_opt language hellos with + | Some hello -> Ok { text = Printf.sprintf "%s, %s!" hello name } + | None -> + Error + (Spindle.Refusal.make unknown_language + (Printf.sprintf "There is no greeting in %s." language)) + +let routes = + [ + Spindle.get ~summary:"The languages a greeting can be in" + Spindle.Path.(s "languages") + (Spindle.Returns.json (Wiretype.list Wiretype.string)) + (Spindle.Dep.return languages); + Spindle.post ~summary:"A greeting, by name" ~refuses:[ unknown_language ] + Spindle.Path.(s "greetings") + (Spindle.Returns.json greeting_json) + (let+ request = Spindle.json greeting_request_json in + greet request); + ] +``` + +## Summaries, tags and examples + +What OCaml cannot read from the types, you write on the route: + +- `~summary`, `~doc` and `~tags` on every route builder (`Spindle.get`, + `Spindle.post`, ...). +- `~examples` on an answer (`Returns.json ~examples`) or a body + (`Spindle.json ~examples`), checked against the type. +- `Dep.credential ~scheme` marks a cookie or header as proof of who is + asking, so the document names the scheme and which routes need it: + +```ocaml +let session = + Spindle.Dep.credential ~scheme:"session" + (Spindle.Cookie.optional (Spindle.Cookie.named "session" Wiretype.string)) +``` + +You can also print what each route reads and answers, without running any +of them. `Spindle.serve` makes the app from your routes for you; to get the +app yourself, call `Spindle.App.make`, which answers an `Error` naming the +route when the table is wrong: + +```ocaml +match Spindle.App.make routes with +| Ok app -> + List.iter (Format.printf "%a@." Spindle.Route.pp_info) (Spindle.App.routes app) +| Error e -> prerr_endline e +``` + +For a route that reads the `session` above and declares two codes of its +own -- `signed_out` for a request with no session, `gone` for an order that +was deleted -- it prints: + +``` +POST /orders/{order_id}/items -- Add an item + path: order_id: integer + reads: cookie session?: string, query page?: integer, body item + credentials: session + returns: 201 item + refuses: 410 gone, 401 signed_out, 415 unsupported_media_type + tags: orders +``` + +## The OpenAPI document + +To write the document to a file, use your app's command line, which the +[next page](client-schemas.md#setting-up-the-command-line) +sets up: `api openapi -o FILE`. From your own code -- a test, a script -- it +is two functions, over the `app` from `App.make`: + +```ocaml +Spindle.Openapi.document ~title:"Orders" app (* OpenAPI 3.2, as JSON *) +Spindle.Openapi.report app (* what is described loosely *) +``` + +`document` answers a `result`; its `Error` names two different types +described under one name; two routes whose paths make one +`operationId` (`/a-b` and `/a_b`), which a generated client would give one +name; two whose paths differ only in a parameter's name +(`/items/{id}` and `/items/{item}`), which OpenAPI counts as one path; and +one operation -- routes told apart by a parameter's type -- whose routes +answer in different ways or read different bodies. What to know when you +read the document: + +- **Each type with a name is a component.** Names are unique within an app. + If a type's request and answer forms differ, the request's is + `Input`. +- **A field that may be left out is an `option`, or has `[@default v]`** + (`~absent` when you write a description by hand). This holds even for a + type you only ever send: otherwise the document calls the field + required. +- **Codes are responses**, grouped by status, each with what it means; the + framework's own (`400 invalid`, `503 busy`, ...) are added from what the + route reads, and a route answering one the document does not list is a + bug, as it is for a code of your own. +- **An input is one parameter**, however many dependencies read it, and a + header's name is matched without case. Two that read it as different + things -- an `int` and a `string`, one value and a list -- are refused + when the app is made, since one document cannot say both. +- **A body is `required` where an empty one is refused.** An empty JSON + body is read as `{}`, so one is required unless every member may be left + out; a raw body is read as it arrived, empty or not, so it never is. +- **Enums and bounds** are in the schema exactly as the decoder checks them. +- **The report lists what is loose**: a route that may read more than it + declares (a `Dep.bind`, or `Dep.of_request` without `~needs`) and any + `Wiretype.Value.json`. An empty report means the document says everything. +- A route over the rest of the path, such as `Static.directory`, is left out. diff --git a/agents/pages/tutorial/routes.md b/agents/pages/tutorial/routes.md new file mode 100644 index 0000000..721e3e4 --- /dev/null +++ b/agents/pages/tutorial/routes.md @@ -0,0 +1,289 @@ +# Routes + +A route says *when somebody sends this method to this path, read these +inputs from the request and pass them to this function*. An app is a list of +routes. + +## Anatomy of a route + +Every route has four parts: + +```ocaml +Spindle.get (* 1. the method *) + Spindle.Path.(s "todos" / id) (* 2. the path: /todos/{id} *) + (Spindle.Returns.json todo_json) (* 3. what it answers *) + (let+ id = Spindle.param id in (* 4. what it reads, *) + get_todo id) (* and what it does with it *) +``` + +`let+` and `and+` come from `open Spindle.Syntax` at the top of the file, +with `let*` for a handler's `result`. + +1. **The method**: `Spindle.get`, `post`, `put`, `patch` or `delete`. Any + other method is `Spindle.route`, as in ``Spindle.route `OPTIONS``. +2. **The path**: `s "todos"` is a fixed segment; `id` is a typed parameter, + so `/todos/7` hands the handler the number `7`. +3. **What it answers**: text, HTML, JSON of a type, nothing, or a response + you build yourself, such as a redirect. [Request bodies, responses and + errors](bodies.md) lists them all. +4. **What it reads, and what it does with it**: a value built with `let+`. + It reads inputs from the request and passes them to your function, the + handler, here `get_todo`. A request that doesn't fit -- `/todos/seven` -- + gets a `400` saying what is wrong, and the handler never runs. + +## One route per method + +A small API over a list of todos: + +```ocaml +(* A route for each method on one resource, a list of todos: GET reads them, + POST adds one, PUT replaces one and DELETE removes one. Where todos are + kept is the database's job, so each handler answers as if it had done it. + + curl localhost:8080/todos + curl localhost:8080/todos/1 + curl -X POST localhost:8080/todos -H 'content-type: application/json' \ + -d '{"title": "Write a server"}' + curl -X PUT localhost:8080/todos/1 -H 'content-type: application/json' \ + -d '{"title": "Learn OCaml properly"}' + curl -X DELETE localhost:8080/todos/1 *) + +open Spindle.Syntax + +type todo = { id : int; title : string } [@@deriving wiretype] +type draft = { title : string } [@@deriving wiretype] + +(* The handlers know nothing of HTTP, so a test calls them as they are. *) +let list_todos () = + Ok [ { id = 1; title = "Learn OCaml" }; { id = 2; title = "Try Spindle" } ] + +let get_todo id = Ok { id; title = "Learn OCaml" } +let add_todo (draft : draft) = Ok { id = 3; title = draft.title } +let replace_todo id (draft : draft) = Ok { id; title = draft.title } +let delete_todo _ = Ok () + +(* A parameter is made once, so every route whose path has it reads it the + same way. *) +let id = Spindle.Path.int "id" + +let routes = + [ + Spindle.get + Spindle.Path.(s "todos") + (Spindle.Returns.json (Wiretype.list todo_json)) + (let+ () = Spindle.Dep.return () in + list_todos ()); + Spindle.get + Spindle.Path.(s "todos" / id) + (Spindle.Returns.json todo_json) + (let+ id = Spindle.param id in + get_todo id); + Spindle.post + Spindle.Path.(s "todos") + (Spindle.Returns.json ~status:`Created todo_json) + (let+ draft = Spindle.json draft_json in + add_todo draft); + Spindle.put + Spindle.Path.(s "todos" / id) + (Spindle.Returns.json todo_json) + (let+ id = Spindle.param id and+ draft = Spindle.json draft_json in + replace_todo id draft); + Spindle.delete + Spindle.Path.(s "todos" / id) + (Spindle.Returns.empty ()) + (let+ id = Spindle.param id in + delete_todo id); + ] + +let () = Eio_main.run @@ fun env -> Spindle.serve env routes +``` + +```console +$ curl localhost:8080/todos +[{"id":1,"title":"Learn OCaml"},{"id":2,"title":"Try Spindle"}] + +$ curl localhost:8080/todos/1 +{"id":1,"title":"Learn OCaml"} + +$ curl -X POST localhost:8080/todos -H 'content-type: application/json' \ + -d '{"title": "Write a server"}' +{"id":3,"title":"Write a server"} + +$ curl -X PUT localhost:8080/todos/1 -H 'content-type: application/json' \ + -d '{"title": "Learn OCaml properly"}' +{"id":1,"title":"Learn OCaml properly"} + +$ curl -i -X DELETE localhost:8080/todos/1 +HTTP/1.1 204 No Content +... + +$ curl localhost:8080/todos/seven +{"error":"invalid","message":"Some of that request is not what it should be.","problems":[{"at":"path.id","code":"unexpected_type","message":"This must be a whole number."}]} +``` + +- **`GET /todos`** reads nothing, so its input is `Spindle.Dep.return ()`. + Written `let+ () = Spindle.Dep.return () in list_todos ()`, it calls + `list_todos` on every request. `Spindle.Dep.return (list_todos ())` would + call it once, when the routes are built, and answer that same list for + ever. +- **`GET /todos/{id}`** reads the `id` with `Spindle.param`. +- **`POST /todos`** reads a JSON body with `Spindle.json draft_json`, and + answers `201 Created` through `~status`. +- **`PUT /todos/{id}`** reads two things, joined with `and+`. +- **`DELETE /todos/{id}`** answers `Spindle.Returns.empty ()`: `204 No + Content`. + +`[@@deriving wiretype]` writes `todo_json` and `draft_json` from the types. +[Request bodies](bodies.md) covers that; keeping the todos +for real is the [database](database.md) page. + +## Path parameters + +Below, `Path` is `Spindle.Path`. A parameter is read by a wiretype +description, the one a JSON body's member is read by. + +```ocaml +let order_id = Path.string "order_id" (* any segment *) +let page = Path.int "page" (* an int *) +let user_id = Path.int64 "user_id" (* an int64 *) +let file = Path.rest "file" (* every segment left *) +let invoice = Path.param "invoice" (Wiretype.uuid ()) (* a Uuidm.t *) +let year = + Path.param "year" + (Wiretype.int_bounded ~min:1900 ~max:2100 ()) (* an int, within bounds *) +let colour = + Path.param "colour" + (Wiretype.enum ~kind:"colour" colour_to_string + [ Red; Green; Blue ]) (* one of a set of words *) +let sku = + Path.param "sku" + (Wiretype.kind ~kind:"sku" ~parse:Sku.of_string + ~print:Sku.to_string Wiretype.string) (* a type of your own *) + +Path.(s "orders" / order_id / s "items") (* /orders/{order_id}/items *) +Path.(s "static" / file) (* /static/{file*} *) +Path.root (* / *) +``` + +- Make each parameter once and use it in every path that has it. Read it in + a route with `Spindle.param order_id`: you pass the parameter, never the + path built from it. +- Any scalar description reads a segment: `Wiretype.number`, `bool`, `date` + (`2026-09-30`, read as `(year, month, day)`) and the rest. A segment it + does not read -- outside its bounds or not -- is a `400` with wiretype's + problem, or the next route under `~unparsed:Next_route`. +- A segment arrives percent-decoded: `/orders/Kim%20Li` is `"Kim Li"`. +- A `kind`'s `~parse` answers `Ok` the value, or `Error` the sentence a + client is told: `Error "This is not a SKU."`. +- `Path.rest` takes every segment left, as a list: `/static/css/site.css` + is `["css"; "site.css"]`, and `/static` is `[]`. It must come last. It is + left out of the OpenAPI document. + +One parameter, read by two routes, one answering text and one JSON: + +```ocaml +(* Typed path parameters, answered as text and as JSON. + + A parameter is made once, named, and read with [Spindle.param] in every route + whose path has it; the name is where a segment that does not parse is + reported -- /users/abc is a 400 at [path.user_id]. *) + +open Spindle.Syntax + +let user_id = Spindle.Path.int64 "user_id" +let name = Spindle.Path.string "name" + +(* The answer's description is derived from its record, so a name holding a + quote is still one JSON string. *) +type user = { user_id : string; name : string } [@@deriving wiretype] + +(* The handlers take values, not a request: the route below says where each + value comes from. *) +let user_text id = Ok (Printf.sprintf "User %Ld" id) +let user_answer id name = Ok { user_id = Int64.to_string id; name } + +let routes = + [ + Spindle.get + Spindle.Path.(s "users" / user_id) + Spindle.Returns.text + (let+ id = Spindle.param user_id in + user_text id); + Spindle.get + Spindle.Path.(s "api" / s "users" / user_id / name) + (Spindle.Returns.json user_json) + (let+ id = Spindle.param user_id and+ name = Spindle.param name in + user_answer id name); + ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> Spindle.serve env routes +``` + +```console +$ curl localhost:8080/users/7 +User 7 + +$ curl localhost:8080/api/users/7/Kim%20Li +{"user_id":"7","name":"Kim Li"} + +$ curl localhost:8080/users/abc +{"error":"invalid","message":"Some of that request is not what it should be.","problems":[{"at":"path.user_id","code":"unexpected_type","message":"This must be a whole number."}]} +``` + +The parameter's name, `user_id`, is where a segment that does not parse is +reported. + +## How routes are matched + +- **A literal beats a parameter**, whatever the order of the list: + `/users/me` answers before `/users/{id}`. +- **A parameter that doesn't parse is a `400`** at `path.`. Give it + `~unparsed:Next_route` (`Path.(s "posts" / int ~unparsed:Next_route + "key")`) to make it "not this route" instead, so the next route whose + path matches answers -- `/posts/42` by its number, `/posts/blue-lamp` by + its name. Routes like these, that differ only by the parameter's type, + must give it the same name. The OpenAPI document describes them as one + operation, so they must also answer the same way and read the same body; + otherwise `Spindle.Openapi.routes` refuses them. +- **A path no route names** is `404`, or your own answer with + `Spindle.serve env ~not_found:page routes`. `page` is written as a + route's handler is, with no method or path, and answers a response: + `Spindle.Dep.return (Ok missing)` for a page that reads nothing, or + `let+ session = session in ...` for one that greets whoever is signed in. + A path another method's route names is `405`, with `Allow` listing the + methods it has. +- **A method no route declares and Spindle does not know** -- `PROPFIND`, + say -- is `501 Not Implemented`. +- **`OPTIONS`** of a path a route names is answered for you, `204` with that + `Allow`, unless you declare an `OPTIONS` route there; `OPTIONS *`, which + asks of the server, is `204` as well. +- **A trailing slash is a different path** (`404`), unless you pass + `~trailing_slash:Spindle.App.Redirect`, which answers a `308` to the path + without it. +- **`HEAD`** is answered by the `GET` route; you don't declare it. + +A route table that can't be right is refused before the server listens: +`Spindle.serve` raises `Invalid_argument` naming the route. That covers two +routes of one method that could answer the same URL, a parameter named twice +in a path, a `Path.rest` that isn't last, a `Spindle.param` its route's path +doesn't have, and a `HEAD` route. The one `Spindle.param` this cannot check +is one inside `Spindle.Dep.bind`, whose inputs are only known when it runs: +if its route's path lacks the parameter, the request answers `500`. + +## Building URLs + +Build a link or a redirect from the same path the route matches, so the two +can't drift apart: + +```ocaml +let order tail = Path.(s "orders" / order_id / tail) + +Path.url (order (Path.s "items")) [ Path.arg order_id "Kim Li" ] +(* Ok "/orders/Kim%20Li/items" *) +``` + +Each segment is percent-encoded, a segment of `.` or `..` too, which a +browser would otherwise resolve away. A parameter left out, given twice or +not in the path is an `Error` naming it. diff --git a/agents/pages/tutorial/static-files.md b/agents/pages/tutorial/static-files.md new file mode 100644 index 0000000..59d04e1 --- /dev/null +++ b/agents/pages/tutorial/static-files.md @@ -0,0 +1,169 @@ +# Static files + +Serve a directory beside your API: a built front end, its scripts and +stylesheets, a favicon. One route does it: + +```ocaml +Spindle.Static.directory "dist" +``` + +That is all a folder needs. Use `Static` for files your build made, which +are read once when the server starts; for files that change while it runs +-- uploads, reports -- use [`Files`](#files-that-change-at-run-time). + +## Serving a directory + +```ocaml +(* A directory served: public, at the root, so / is its index.html and + /style.css its stylesheet. The path is the program's working directory's, + so run it from this one: + + cd examples && dune exec ./static.exe + + The directory is read into memory once, when the server starts -- one + whose directory cannot be read does not start, and says why -- and every + request is a lookup among what was there: a file changed afterwards needs + a restart, and a path that was not there is never a file, whatever it + spells. *) + +let routes = [ Spindle.Static.directory "public" ] + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> Spindle.serve env routes +``` + +`"public"` is a folder next to where you start the program. The example's is +`examples/public`, so start it from `examples/` and ask for a file: + +```console +$ cd examples && dune exec ./static.exe +$ curl -I localhost:8080/style.css +HTTP/1.1 200 OK +content-type: text/css; charset=utf-8 +accept-ranges: bytes +etag: "4e3597b273bb16778f1093c5780a9fe2" +cache-control: no-cache +x-content-type-options: nosniff +content-length: 88 +... +``` + +`/` is the directory's `index.html`, and a path with no file is the +framework's `404`. + +- **The directory is read into memory once, when the server starts.** A + request is a lookup among those files, never a path on disk, so `../` + reaches nothing. A file you change afterwards is served after a restart. +- **A directory that cannot be read stops the server**: it logs why and + exits 1, instead of answering `404` to everything. +- **It is a route like any other**, over the rest of the path, so it goes in + the same list as your API and every other route is matched first. +- **Every file carries an `etag`**, so a browser revalidates cheaply + (`304`), and one `Range` is answered with `206`. +- **Every file carries `X-Content-Type-Options: nosniff`**, so a browser + takes the type it is given and never guesses one from the bytes. +- **A precompressed copy is served when the browser accepts it.** Beside + `app.js`, an `app.js.br`, `app.js.zst` or `app.js.gz` your build made is + sent with `Content-Encoding` and `Vary: Accept-Encoding`. See + [Compression](../guide/compression.md). +- **Names that start with a dot are skipped**, at any depth, so `.env` and + `.git` are never served. The one exception is `.well-known` at the root, + which belongs to the site (RFC 8615). `~dotfiles:true` serves them all. + +## Static files beside an API + +A built front end at the root, beside the API, with a page of its own for +what is not there: + +```ocaml +let routes = api @ [ Spindle.Static.directory ~not_found:"/404.html" "dist" ] + +let () = Eio_main.run @@ fun env -> Spindle.serve env routes +``` + +The options of `Static.directory`. The files and prefixes they name are +request paths, starting with `/` (`"/404.html"`, not `"404.html"`); a file +that is not in the directory stops the server at start: + +- `~not_found` -- the file answered, with a `404`, for a path with no file. +- `~shell:(file, prefixes)` -- answers every path under the prefixes with one + document and a `200`, for client-side pages whose ids are made at run time: + `~shell:("/app/index.html", [ "/orders/" ])`. A prefix ends in `/`, so + `/ordersheet` is not under `/orders/`. +- `~index` -- the file a directory answers with, `"index.html"` unless told. +- `~at` -- serve under a prefix instead of the root: + `~at:Path.(s "static")`. +- `~types` -- add content types by extension: + `[ (".wasm", "application/wasm") ]`. An unknown extension is served as + bytes. + +## Keeping assets a year + +Every file is served `no-cache`: a browser keeps its copy and asks again +each time, and is answered `304` while the file is the same. That is right +for any file, and you need nothing more. + +A front-end build names its scripts and stylesheets by a hash of what is in +them -- Vite's `assets/index-3f2a9c.js`, Astro's `_astro/` -- so a new +version is a new name. Those a browser can keep without asking. Say so for +the whole app, apart from what serves them: + +```ocaml +Spindle.serve env + ~middleware:[ Spindle.Cache.forever ~under:Spindle.Path.[ s "assets" ] ] + (api @ [ Spindle.Static.directory "dist" ]) +``` + +`Cache.forever` keeps every successful `GET` under those paths a year -- +`/assets/...`, never `/assetsheet` -- +whichever route answered it, and never a failure. Leave it out and nothing +is ever stale; put a prefix in it only when every name under it changes with +its bytes. Your `index.html` never goes in it: it is how a browser finds the +new names. + +## Static files in a test + +`Spindle.Test.app` refuses `Static.directory`, which reads its files when a +real server starts. In a test, load the directory yourself and serve it with +`Static.route`: + +```ocaml +match Spindle.Static.load Eio.Path.(Eio.Stdenv.cwd env / "public") with +| Ok files -> Spindle.Test.app (routes @ [ Spindle.Static.route files ]) +| Error e -> Alcotest.fail e +``` + +## Files that change at run time + +For files that change while the server runs -- uploads, generated reports -- +use `Spindle.Files`, which opens the file when the request arrives and +streams it: + +```ocaml +Spindle.Files.directory ~at:Path.(s "uploads") ~download:true "var/uploads" +``` + +- **It never leaves its directory.** A segment that is `..`, starts with a + dot, or holds a `/` or `\` is `404` before anything is opened, and a + symlink out of the directory is refused by the operating system. +- **Nothing lists a directory**: one is `404`, or its `~index` where you name + one. +- **An upload never runs as your site.** A file a browser would open as a + page of your origin -- HTML, SVG, any XML -- is sent as an attachment and + carries `Content-Security-Policy: sandbox`, so an uploaded `x.html` is + downloaded rather than run beside your cookies. `~inline_active:true` shows + one in the browser instead, still sandboxed: with no origin of its own and + none of its script run. +- `~download:true` sends each file as an attachment with its name; + `~dotfiles:true` serves names that start with a dot. +- Answers carry an `etag`, `Last-Modified` and `nosniff`, and answer + conditional requests and one `Range`, as `Static` does. +- **Replace a file by writing it elsewhere and renaming it over the old + one.** A file rewritten in place, at the same size within the clock's tick, + keeps its `etag`. + +`Spindle.Test.app` refuses `Files.directory` too. `Spindle.Files.route` takes +the same options over a directory you already hold as an `Eio.Path.t`, so a +test can serve one of its own: +`Spindle.Files.route Eio.Path.(Eio.Stdenv.cwd env / "uploads")`. diff --git a/docs/astro.config.mjs b/docs/astro.config.mjs index 249f54e..e42427d 100644 --- a/docs/astro.config.mjs +++ b/docs/astro.config.mjs @@ -2,6 +2,7 @@ import { fileURLToPath } from "node:url"; import { defineConfig } from "astro/config"; import starlight from "@astrojs/starlight"; import links from "starlight-links-validator"; +import agents from "starlight-hypha-agents"; import hypha from "starlight-theme-hypha"; // Spindle's documentation site, published to GitHub Pages by @@ -33,6 +34,10 @@ export default defineConfig({ tabs: { Tutorial: "graduation-cap", Guides: "book-open", Reference: "library" }, links: [{ label: "Hypha Stack", href: "https://hyphatech.io/stack", icon: "layers" }], }), + // Each page as Markdown and llms.txt, written into agents/ + // by the build, for the spindle package to install; the docs + // workflow holds it to the pages. + agents({ dir: "../agents" }), // The reference is odoc's, in public/, which the validator cannot see; // the tutorial links to the server it has the reader start. links({ diff --git a/docs/bun.lock b/docs/bun.lock index 56fad1e..d8b7376 100644 --- a/docs/bun.lock +++ b/docs/bun.lock @@ -7,8 +7,9 @@ "devDependencies": { "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3", + "starlight-hypha-agents": "github:hyphatech/starlight-hypha-agents#v0.2.0", "starlight-links-validator": "^0.27.0", - "starlight-theme-hypha": "github:hyphatech/starlight-theme-hypha#v0.6.3", + "starlight-theme-hypha": "github:hyphatech/starlight-theme-hypha#v0.8.0", }, }, }, @@ -295,6 +296,10 @@ "@ungap/structured-clone": ["@ungap/structured-clone@1.4.0", "", {}, "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ=="], + "acorn": ["acorn@8.19.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw=="], + + "acorn-jsx": ["acorn-jsx@5.3.2", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="], + "am-i-vibing": ["am-i-vibing@0.5.0", "", { "dependencies": { "process-ancestry": "^0.1.0" }, "bin": { "am-i-vibing": "dist/cli.mjs" } }, "sha512-KLcsDhqf1XRrJmJr+9I/C0EX2K+sGrAGZFgkmd84c8TJO9zJBu+/kFInjazu1KfJWFhWDKdRWkpBzEs7s35DVA=="], "ansi-escapes": ["ansi-escapes@7.3.0", "", { "dependencies": { "environment": "^1.0.0" } }, "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg=="], @@ -399,6 +404,10 @@ "es-module-lexer": ["es-module-lexer@3.0.4", "", {}, "sha512-BldNY5mwkVu+cQ5Ymn3e6hB9Sx8XHx4ZevWbiUyZbfKxJxYO27Hf0wfzkxIaD5CAJMaGl3YspKELj0ff/7nCMA=="], + "estree-util-is-identifier-name": ["estree-util-is-identifier-name@3.0.0", "", {}, "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg=="], + + "estree-util-visit": ["estree-util-visit@2.0.0", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/unist": "^3.0.0" } }, "sha512-m5KgiH85xAhhW8Wta0vShLcUvOsh3LLPI2YVwcbio1l7E09NTLL1EyMZFM1OyWowoH0skScNbhOPl4kcBgzTww=="], + "eventemitter3": ["eventemitter3@5.0.4", "", {}, "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw=="], "expressive-code": ["expressive-code@0.44.3", "", { "dependencies": { "@expressive-code/core": "^0.44.3", "@expressive-code/plugin-frames": "^0.44.3", "@expressive-code/plugin-shiki": "^0.44.3", "@expressive-code/plugin-text-markers": "^0.44.3" } }, "sha512-7RGslhJTNt01pdn5I3QmVh5C8ZIiSm0A+ORQ9j9r39oOgJVKjn/7dXl9rMT/SqmFLE6pJkTYI7UjW0BxJnW7OQ=="], @@ -535,8 +544,14 @@ "mdast-util-from-markdown": ["mdast-util-from-markdown@2.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "mdast-util-to-string": "^4.0.0", "micromark": "^4.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-KRLgmPaP2H1ul2bpoJkOS+9pAcDAAj9Nu1mqLnh8NLeJG5tlvj42TH80PIGBpROWlRXLk0lDrWNuZCFy/tsB4A=="], + "mdast-util-mdx": ["mdast-util-mdx@3.0.0", "", { "dependencies": { "mdast-util-from-markdown": "^2.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-JfbYLAW7XnYTTbUsmpu0kdBUVe+yKVJZBItEjwyYJiDJuZ9w4eeaqks4HQO+R7objWgS2ymV60GYpI14Ug554w=="], + + "mdast-util-mdx-expression": ["mdast-util-mdx-expression@2.0.1", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ=="], + "mdast-util-mdx-jsx": ["mdast-util-mdx-jsx@3.2.0", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "devlop": "^1.1.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0", "parse-entities": "^4.0.0", "stringify-entities": "^4.0.0", "unist-util-stringify-position": "^4.0.0", "vfile-message": "^4.0.0" } }, "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q=="], + "mdast-util-mdxjs-esm": ["mdast-util-mdxjs-esm@2.0.1", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg=="], + "mdast-util-phrasing": ["mdast-util-phrasing@4.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "unist-util-is": "^6.0.0" } }, "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w=="], "mdast-util-to-hast": ["mdast-util-to-hast@13.2.1", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "@ungap/structured-clone": "^1.0.0", "devlop": "^1.0.0", "micromark-util-sanitize-uri": "^2.0.0", "trim-lines": "^3.0.0", "unist-util-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA=="], @@ -553,10 +568,22 @@ "micromark-extension-directive": ["micromark-extension-directive@4.0.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "parse-entities": "^4.0.0" } }, "sha512-/C2nqVmXXmiseSSuCdItCMho7ybwwop6RrrRPk0KbOHW21JKoCldC+8rFOaundDoRBUWBnJJcxeA/Kvi34WQXg=="], + "micromark-extension-mdx-expression": ["micromark-extension-mdx-expression@3.0.1", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-mdx-expression": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-dD/ADLJ1AeMvSAKBwO22zG22N4ybhe7kFIZ3LsDI0GlsNr2A3KYxb0LdC1u5rj4Nw+CHKY0RVdnHX8vj8ejm4Q=="], + + "micromark-extension-mdx-jsx": ["micromark-extension-mdx-jsx@3.0.2", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "micromark-factory-mdx-expression": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-e5+q1DjMh62LZAJOnDraSSbDMvGJ8x3cbjygy2qFEi7HCeUT4BDKCvMozPozcD6WmOt6sVvYDNBKhFSz3kjOVQ=="], + + "micromark-extension-mdx-md": ["micromark-extension-mdx-md@2.0.0", "", { "dependencies": { "micromark-util-types": "^2.0.0" } }, "sha512-EpAiszsB3blw4Rpba7xTOUptcFeBFi+6PY8VnJ2hhimH+vCQDirWgsMpz7w1XcZE7LVrSAUGb9VJpG9ghlYvYQ=="], + + "micromark-extension-mdxjs": ["micromark-extension-mdxjs@3.0.0", "", { "dependencies": { "acorn": "^8.0.0", "acorn-jsx": "^5.0.0", "micromark-extension-mdx-expression": "^3.0.0", "micromark-extension-mdx-jsx": "^3.0.0", "micromark-extension-mdx-md": "^2.0.0", "micromark-extension-mdxjs-esm": "^3.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-A873fJfhnJ2siZyUrJ31l34Uqwy4xIFmvPY1oj+Ean5PHcPBYzEsvqvWGaWcfEIr11O5Dlw3p2y0tZWpKHDejQ=="], + + "micromark-extension-mdxjs-esm": ["micromark-extension-mdxjs-esm@3.0.0", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-position-from-estree": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-DJFl4ZqkErRpq/dAPyeWp15tGrcrrJho1hKK5uBS70BCtfrIFg81sqcTVu3Ta+KD1Tk5vAtBNElWxtAa+m8K9A=="], + "micromark-factory-destination": ["micromark-factory-destination@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA=="], "micromark-factory-label": ["micromark-factory-label@2.0.1", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg=="], + "micromark-factory-mdx-expression": ["micromark-factory-mdx-expression@2.0.3", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-position-from-estree": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-kQnEtA3vzucU2BkrIa8/VaSAsP+EJ3CKOvhMuJgOEGg9KDC6OAY6nSnNDVRiVNRqj7Y4SlSzcStaH/5jge8JdQ=="], + "micromark-factory-space": ["micromark-factory-space@2.1.0", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q=="], "micromark-factory-title": ["micromark-factory-title@2.0.1", "", { "dependencies": { "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw=="], @@ -579,6 +606,8 @@ "micromark-util-encode": ["micromark-util-encode@2.0.1", "", {}, "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw=="], + "micromark-util-events-to-acorn": ["micromark-util-events-to-acorn@2.0.3", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/unist": "^3.0.0", "devlop": "^1.0.0", "estree-util-visit": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-jmsiEIiZ1n7X1Rr5k8wVExBQCg5jy4UXVADItHmNk1zkwEVhBuIUKRu3fqv+hs4nxLISi2DQGlqIOGiFxgbfHg=="], + "micromark-util-html-tag-name": ["micromark-util-html-tag-name@2.0.1", "", {}, "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA=="], "micromark-util-normalize-identifier": ["micromark-util-normalize-identifier@2.0.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q=="], @@ -691,9 +720,11 @@ "space-separated-tokens": ["space-separated-tokens@2.0.2", "", {}, "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q=="], + "starlight-hypha-agents": ["starlight-hypha-agents@github:hyphatech/starlight-hypha-agents#3ee7026", { "dependencies": { "mdast-util-from-markdown": "^2.0.2", "mdast-util-mdx": "^3.0.0", "micromark-extension-mdxjs": "^3.0.0", "yaml": "^2.9.1" }, "peerDependencies": { "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3" } }, "hyphatech-starlight-hypha-agents-3ee7026", "sha512-CRpk3KikuTkpb+Sbq5wMWOibJyR9DScrqijg08vp17qul6BB/GVfYV4XVK9nGVUsGJVjfYgVlCr5j51ZmXHf+A=="], + "starlight-links-validator": ["starlight-links-validator@0.27.0", "", { "dependencies": { "@astrojs/markdown-satteri": "^0.4.0", "github-slugger": "^2.0.0", "hast-util-from-html": "^2.0.3", "is-absolute-url": "^5.0.0", "mdast-util-mdx-jsx": "^3.2.0", "mdast-util-to-hast": "^13.2.1", "picomatch": "^4.0.3", "satteri": "^0.10.3", "terminal-link": "^5.0.0", "unist-util-visit": "^5.1.0", "yaml": "^2.8.3" }, "peerDependencies": { "@astrojs/starlight": ">=0.42.0", "astro": ">=7.2.10" } }, "sha512-UvPl8L9hfWR+yWbLOEtljLmpJCGcM6AVseVy5IO9dmqdOjW4R+Y8FaYyVA5axCC8RvxM5xU7M1WTerpwU8rYbw=="], - "starlight-theme-hypha": ["starlight-theme-hypha@github:hyphatech/starlight-theme-hypha#4df8be9", { "dependencies": { "@fontsource-variable/roboto-slab": "^5.3.0", "@fontsource/inter-tight": "^5.3.0", "@lucide/astro": "1.48.0", "@tailwindcss/vite": "^4.3.3", "tailwindcss": "^4.3.3" }, "peerDependencies": { "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3" } }, "hyphatech-starlight-theme-hypha-4df8be9", "sha512-3ksSin8zktNtDQ9xnP2ihRZkXVaPMTXGxrFykNrXBR3vQT/sQffOD2vpeL+ZvObUP/KmslY4RPWJEnyxwi1npA=="], + "starlight-theme-hypha": ["starlight-theme-hypha@github:hyphatech/starlight-theme-hypha#a105fa6", { "dependencies": { "@fontsource-variable/roboto-slab": "^5.3.0", "@fontsource/inter-tight": "^5.3.0", "@lucide/astro": "1.48.0", "@tailwindcss/vite": "^4.3.3", "tailwindcss": "^4.3.3" }, "peerDependencies": { "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3" } }, "hyphatech-starlight-theme-hypha-a105fa6", "sha512-1lDTrqupxaVND5rueaGZVy2mokekMHaaDHAI3d4TBW8KujgEMRQ3Ftec3+CeXz4vG0NCEd8HCjyW13GBY/eUtQ=="], "std-env": ["std-env@4.3.0", "", {}, "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag=="], @@ -747,6 +778,8 @@ "unist-util-position": ["unist-util-position@5.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA=="], + "unist-util-position-from-estree": ["unist-util-position-from-estree@2.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-KaFVRjoqLyF6YXCbVLNad/eS4+OfPQQn2yOd7zF/h5T/CSL2v8NpN6a5TPvtbXthAGw5nG+PuTtq+DdIZr+cRQ=="], + "unist-util-stringify-position": ["unist-util-stringify-position@4.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ=="], "unist-util-visit": ["unist-util-visit@5.1.0", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.0.0" } }, "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg=="], diff --git a/docs/package.json b/docs/package.json index 0636762..c239476 100644 --- a/docs/package.json +++ b/docs/package.json @@ -5,7 +5,8 @@ "devDependencies": { "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3", + "starlight-hypha-agents": "github:hyphatech/starlight-hypha-agents#v0.2.0", "starlight-links-validator": "^0.27.0", - "starlight-theme-hypha": "github:hyphatech/starlight-theme-hypha#v0.6.3" + "starlight-theme-hypha": "github:hyphatech/starlight-theme-hypha#v0.8.0" } } diff --git a/dune b/dune index 49e7723..7916c8c 100644 --- a/dune +++ b/dune @@ -12,3 +12,13 @@ (_ (flags (:standard -w +a-4-40-41-42-44-45-48-67-70)))) + +; The documentation for a user's agent, agents/, written from the site's pages +; by `make docs`: the spindle package installs it whole, so +; $(opam var spindle:doc) holds llms.txt and each page. + +(install + (package spindle) + (section doc) + (source_trees + (agents as .)))