From e4e0f0398372a46945d6210227d6158fc28ff91c Mon Sep 17 00:00:00 2001 From: Roman Zaiev Date: Sat, 21 Nov 2026 23:19:01 +0000 Subject: [PATCH] Install the documentation for agents with the package An agent writing code with spool should read the docs of the release it builds against, but the package installed only its README, CHANGES and LICENSE. starlight-hypha-agents writes each page as Markdown and llms.txt into agents/ as the docs build, and the spool package installs it into its doc directory. An agent reads it when told to, so the README gives the one line for a project's AGENTS.md that sends it there. The docs take starlight-theme-hypha 0.8.0, a look alone, beside it. The docs workflow now builds every pull request, so a page changed without agents/ fails before it lands, and deploys only from main. `make docs` writes agents/, so it has no target of its own. --- .github/workflows/docs.yml | 35 +++- AGENTS.md | 16 +- CHANGES.md | 6 + README.md | 12 ++ agents/llms.txt | 28 +++ agents/pages/guide/dashboard.md | 293 ++++++++++++++++++++++++++ agents/pages/guide/enqueueing.md | 171 ++++++++++++++++ agents/pages/guide/handlers.md | 61 ++++++ agents/pages/guide/kinds.md | 104 ++++++++++ agents/pages/guide/limiting.md | 45 ++++ agents/pages/guide/limits.md | 20 ++ agents/pages/guide/operating.md | 186 +++++++++++++++++ agents/pages/guide/runner.md | 151 ++++++++++++++ agents/pages/guide/schedules.md | 55 +++++ agents/pages/guide/spindle.md | 152 ++++++++++++++ agents/pages/guide/table.md | 339 +++++++++++++++++++++++++++++++ agents/pages/guide/testing.md | 104 ++++++++++ agents/pages/guide/workflows.md | 41 ++++ agents/pages/index.md | 87 ++++++++ agents/pages/quick-start.md | 181 +++++++++++++++++ agents/pages/reference.md | 55 +++++ docs/astro.config.mjs | 5 + docs/bun.lock | 37 +++- docs/package.json | 3 +- dune | 10 + 25 files changed, 2182 insertions(+), 15 deletions(-) create mode 100644 agents/llms.txt create mode 100644 agents/pages/guide/dashboard.md create mode 100644 agents/pages/guide/enqueueing.md create mode 100644 agents/pages/guide/handlers.md create mode 100644 agents/pages/guide/kinds.md create mode 100644 agents/pages/guide/limiting.md create mode 100644 agents/pages/guide/limits.md create mode 100644 agents/pages/guide/operating.md create mode 100644 agents/pages/guide/runner.md create mode 100644 agents/pages/guide/schedules.md create mode 100644 agents/pages/guide/spindle.md create mode 100644 agents/pages/guide/table.md create mode 100644 agents/pages/guide/testing.md create mode 100644 agents/pages/guide/workflows.md create mode 100644 agents/pages/index.md create mode 100644 agents/pages/quick-start.md create mode 100644 agents/pages/reference.md diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 75703f6..e66fdd0 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 406bd3d..c2d7968 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,7 +13,8 @@ make test # starts the test Postgres in Podman, runs every test make lint # formatting, odoc, the release build, litany, and the dashboard's bundle rebuilt and compared make fmt # format in place make dashboard # the dashboard's page built into dashboard/assets, to commit -make docs # the documentation site into _build/docs, as Pages publishes it; docs-serve serves it +make docs # the documentation site into _build/docs, as Pages publishes it, and + # agents/ from its pages; docs-serve serves it make release VERSION=1.2.3 # tag and release ``` @@ -21,7 +22,8 @@ make release VERSION=1.2.3 # tag and release so `make lint` Bun 1.3 or later. Without `SPOOL_TEST_PG` the cases that need a server are skipped, and the test output says so. CI runs `make lint` and `make test` on OCaml 5.5. -`docs.yml` publishes the site to GitHub Pages on every push to `main`. +`docs.yml` builds the site on every pull request and publishes it to GitHub +Pages from `main`. ## Layout @@ -52,6 +54,10 @@ dashboard/ spool-dashboard, its own package over spool, spindle and into assets/ test/ the routes in-process against a real Postgres: who may do what, sensitive payloads, paging, actions, the live stream +agents/ the documentation for a user's agent, generated by + starlight-hypha-agents from the pages, `make docs`: + llms.txt, the catalogue; pages/, each page as Markdown; + installed by the spool package examples/ the programs the site shows, each built, and run against a Postgres by hand test/ @@ -141,6 +147,12 @@ you broke it. Cite an entry by its bold phrase. installs the package with OCaml alone, and never edited by hand. Symptom: `make lint`, which builds it again, finds a file that differs, or one more or fewer. +- **`agents/` is generated, never edited.** starlight-hypha-agents writes + it from the documentation's pages and its options in + `docs/astro.config.mjs`: a page changed is `make docs` run in the same + commit. Why: a user's agent reads what the release installs, offline, + and a page it reads must be the release's. Test: the docs workflow builds + the pages on every pull request and fails if `agents/` then differs. - **The queue names no driver.** It runs over `rowtype-postgres`, which hands it a listener as it hands it a pool, so a second backend is a second adapter. Symptom: `postgres-eio` named in `src/` or in its diff --git a/CHANGES.md b/CHANGES.md index 48587cd..49b5283 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,11 @@ # Changes +## Unreleased + +- The spool package installs its documentation for agents: each page as + Markdown and `llms.txt`, at `$(opam var spool:doc)`. The README's *With an + agent* gives the line for a project's `AGENTS.md` that sends an agent there. + ## 0.7.0 (2026-11-17) - A new package, `spool-dashboard`: a live dashboard for the queue, as diff --git a/README.md b/README.md index 51a71bb..e5c8f75 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,18 @@ The runner claims the job once the transaction commits, under a lease, and runs its handler outside every transaction; `Spool.Runner.start` starts it and `Spool.Runner.stop` stops it. +## With an agent + +Each release installs its documentation for an agent with it, at +`$(opam var spool:doc)`: `llms.txt`, and every page in Markdown. An agent +reads it when your project's `AGENTS.md` tells it to: + +```md +Before writing code with spool, read `$(opam var spool: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..a932af6 --- /dev/null +++ b/agents/llms.txt @@ -0,0 +1,28 @@ +# spool + +> Durable jobs for modern OCaml, backed by Postgres. + +## Start here + +- [Getting Started](pages/index.md): Durable jobs for modern OCaml, backed by Postgres. +- [Quick start](pages/quick-start.md) + +## Guides + +- [The table](pages/guide/table.md) +- [Kinds](pages/guide/kinds.md) +- [Enqueueing](pages/guide/enqueueing.md) +- [Handlers](pages/guide/handlers.md) +- [The runner](pages/guide/runner.md) +- [In a Spindle application](pages/guide/spindle.md) +- [Operating a queue](pages/guide/operating.md) +- [The dashboard](pages/guide/dashboard.md) +- [Limiting a queue](pages/guide/limiting.md) +- [Recurring jobs](pages/guide/schedules.md) +- [Workflows](pages/guide/workflows.md) +- [Testing](pages/guide/testing.md) +- [What it does not do yet](pages/guide/limits.md) + +## Reference + +- [Reference](pages/reference.md) diff --git a/agents/pages/guide/dashboard.md b/agents/pages/guide/dashboard.md new file mode 100644 index 0000000..dd35762 --- /dev/null +++ b/agents/pages/guide/dashboard.md @@ -0,0 +1,293 @@ +# The dashboard + +`spool-dashboard` watches and steers the queue from the application that +runs it: routes added to its own Spindle server, open to whom it says and +for what. + +```sh +opam install spool-dashboard +``` + +```ocaml +let db : Spindle_postgres.Pool.t Spindle.Dep.t = + Spindle.Dep.of_resource "database" + +let operator = Spindle.Access.principal ~id:Auth.user_id Auth.signed_in + +let may (user : Auth.user) (action : Spool_dashboard.action) : + Spindle.Access.decision = + match (user.role, action) with + | (Support | Admin), View | Admin, _ -> Allow + | Support, _ -> Deny "support only looks" + | Customer, _ -> Deny "not an operator" + +let routes = + Routes.routes + @ Spool_dashboard.routes ~operator ~may ~pool:db ~mono_clock () +``` + +The page at `/spool` shows, live, a column of the queue's state beside its +work. The column: + +- **States**: what waits, is blocked and runs, exactly; what completed and + was discarded in the last 24 hours, summed from spool's statistics; and + cancelled, which nothing counts without reading every finished row. A + state chosen there filters the job list. +- **Queues**, each with a switch that pauses and resumes it, the limits it + holds, and a form that sets them: how many of its jobs run at once and how + many attempts begin in a period, across every runner, and whether each + holds for every partition of it. +- **Schedules**, each with its expression and zone, its next tick, and a + button that runs it now. +- **Workers**, each runner running: its host, its queues and their slots, + and when it was last seen. + +Beside it, **a chart** of the attempts finished each minute over the last +hour, completed, retried and discarded; and **the jobs**, +newest first, by state, queue and kind, a page at a time, a selection of +them retried, cancelled or deleted at once. A job opened shows its attempts +and why each failed, oldest first, its payload, and, where it is in a +workflow, the jobs it waits for and those waiting on it, each with its state +and opened from there. + +Live updates can be paused from the page. It wears Hypha's look, light or +dark as the system is or as chosen. + +## Who may do what + +The application says, and there is no default, since the dashboard cancels +and deletes and an open default is how it ends up public. It gives two +things, through Spindle's `Access`: + +- **`operator`**: who calls, as the application knows them -- its own user, + read from its session or a bearer token. Nobody signed in is a `401`. +- **`may`**: what they may do, a function of that user and a + `Spool_dashboard.action` -- `View`, `Cancel`, `Retry`, `Delete`, + `Run_again`, `Pause`, `Resume`, `Set_limits` and `Run_schedule` -- + answering `Allow` or `Deny` with a reason. It reads what the application + keeps, a role, a flag or a scope, so a user given or refused access is a + change to their row, not to the code. + +Every route asks before it reads or does anything, and answers a denial +with a `403` and nothing more; Spindle writes each denial on its +`spindle.access` source, naming the caller and the reason, and +`Spindle.Access.unguarded` lists none of the dashboard's routes. The page +shows only what its viewer may do: a viewer allowed `View` alone sees the +queue and changes nothing. + +The live stream is one request, asked once, so it ends after `?stream_for`, +a minute unless given, and the page opens the next at once, which asks +again: someone whose access the application took away sees the queue no +longer than that. + +## What it does + +Whatever the dashboard does, it does through spool's own functions: +`Spool.jobs`, `Spool.find` and `Spool.workflow` to read, `Spool.cancel`, +`Spool.retry` and `Spool.delete` for a job or a selection, `Spool.Queue.pause`, +`resume` and `set_limits`, and `Schedule.run_now`. It can do nothing code +cannot, under the same checks. Each action is a line on the +`spool-dashboard` source, at `Info`, saying what it was done to; the line +carries its request's id, and the request's trace who made it. A kind made `~sensitive` shows "Hidden: its kind is sensitive" +where its payload would be, since spool answers none. + +The live state is one stream of Server-Sent Events, `GET /spool/api/live`. +Once a second, while anyone watches, one fiber of the process reads the +counts, the queues, the runners, the schedules and the latest statistics, +and every viewer is sent each part that changed. `mono_clock` times it. + +## Installed with OCaml alone + +The page is built into the package: its files are compiled into the library +and served from memory, the hashed ones kept a year by the browser and the +page asked for again each time. Nothing is built, fetched or reached where +it runs. It calls its routes relative to where it is served, so it works +under `~at` anywhere, and behind any prefix a proxy puts it. + +## An example + +Two runners, a schedule every minute, a queue limited to one job at a time +per customer, an import whose summary waits for its rows, a kind whose +payload is a secret, and a stream of work that sometimes fails. Spool's +tables are made first, by `rowtype-migrate up --source spool`; then +`dune exec examples/dashboard.exe` prints the dashboard's address. + +```ocaml title="dashboard.ml" +(* The dashboard in an application: Spindle serving it at /spool beside two + runners, a schedule every minute, a queue limited per customer, an import + whose summary waits for its rows, a kind whose payload is a secret, and a + stream of work that sometimes fails, so there is something to watch. + Spool's tables are made first, by rowtype-migrate up --source spool. + + dune exec examples/dashboard.exe *) + +open Spindle.Syntax +module Pg = Rowtype_postgres + +let database = + Option.value + (Sys.getenv_opt "DATABASE_URL") + ~default:"postgres://postgres:postgres@localhost:5432/postgres" + +let port = 4400 + +let one name ty = + Wiretype.Object.map Fun.id + |> Wiretype.Object.mem name ty ~enc:Fun.id + |> Wiretype.Object.finish + +let receipt = + Spool.Kind.make ~queue:"mail" "receipt.send" (one "order" Wiretype.string) + +(* One customer's syncs at a time, the customers taken in turns. *) +let sync = + Spool.Kind.make ~queue:"partner" ~max_attempts:5 ~partition:Fun.id + "partner.sync" + (one "customer" Wiretype.string) + +let charge = + Spool.Kind.make ~queue:"payments" ~sensitive:true "card.charge" + (one "card" Wiretype.string) + +let row = + Spool.Kind.make ~queue:"imports" "import.row" (one "line" Wiretype.int) + +let summary = + Spool.Kind.make ~queue:"imports" "import.summary" (one "file" Wiretype.string) + +let report = + Spool.Kind.make ~queue:"reports" "report.minute" (one "day" Wiretype.string) + +let every_minute = + Spool.Schedule.make ~name:"report.every-minute" ~cron:"* * * * *" ~zone:"UTC" + report "today" + +(* Who calls and what they may do: here, a caller is their address, and + whoever is on this machine may do anything. An application's caller is its + own user, from its sessions or tokens, and [may] reads their role. *) +let operator = Spindle.Access.principal ~id:Fun.id Spindle.client_ip + +let may ip (_ : Spool_dashboard.action) : Spindle.Access.decision = + match ip with "127.0.0.1" | "::1" -> Allow | _ -> Deny "not on this machine" + +let db : Spindle_postgres.Pool.t Spindle.Dep.t = + Spindle.Dep.of_resource "database" + +(* Work that takes a moment and fails now and then, some of it for good. *) +let work ~clock ~random ~up_to_ms ~fails _job _payload = + let took = Random.State.int random up_to_ms in + Eio.Time.Mono.sleep_span clock Mtime.Span.(took * ms); + let draw = Random.State.int random 100 in + if draw < fails then Error (Spool.Retry "the partner did not answer") + else if draw < fails + 2 then + Error (Spool.Discard "the order no longer exists") + else Ok () + +(* Each queue's kinds and how they go, for a runner of the queue. *) +let handlers ~clock ~random queue = + let work ~up_to_ms ~fails = work ~clock ~random ~up_to_ms ~fails in + match queue with + | "mail" -> [ Spool.handle receipt (work ~up_to_ms:400 ~fails:10) ] + | "partner" -> [ Spool.handle sync (work ~up_to_ms:1500 ~fails:20) ] + | "payments" -> [ Spool.handle charge (work ~up_to_ms:300 ~fails:5) ] + | "imports" -> + [ + Spool.handle row (work ~up_to_ms:200 ~fails:3); + Spool.handle summary (work ~up_to_ms:500 ~fails:0); + ] + | "reports" -> [ Spool.handle report (work ~up_to_ms:800 ~fails:0) ] + | _ -> [] + +let runner ~sw env ~random ~queues conninfo = + let clock = Eio.Stdenv.mono_clock env in + match + Spool.Runner.create ~sw ~net:(Eio.Stdenv.net env) ~mono_clock:clock + ~now:Ptime_clock.now ~schedules:[ every_minute ] ~queues + (List.concat_map (fun (queue, _) -> handlers ~clock ~random queue) queues) + conninfo + with + | Ok r -> + Spool.Runner.start r; + Ok r + | Error refused -> Error (Spool.Runner.refused_to_string refused) + +let enqueued = function + | Ok _ -> () + | Error (#Rowtype.error as e) -> prerr_endline (Rowtype.error_to_string e) + | Error (`Unencodable e) -> prerr_endline (Wiretype.Unwritable.to_string e) + | Error (`Bad_priority p) -> prerr_endline ("priority " ^ string_of_int p) + +(* An import: a job a row, and a summary once every row completed. *) +let import conn ~file = + let now = Ptime_clock.now () in + enqueued + (let* rows = Spool.enqueue_many conn ~now row (List.init 8 Fun.id) in + Spool.enqueue_after conn ~now ~waits_for:rows summary file) + +(* Something to watch: a few jobs every second, of every kind. *) +let rec generate env pool ~random n : [ `Stop_daemon ] = + let customers = [| "acme"; "globex"; "initech"; "umbrella" |] in + let now = Ptime_clock.now () in + (match + Spindle_postgres.Pool.use pool (fun conn -> + enqueued (Spool.enqueue conn ~now receipt ("A-" ^ string_of_int n)); + enqueued + (Spool.enqueue conn ~now sync + customers.(Random.State.int random (Array.length customers))); + if n mod 3 = 0 then + enqueued (Spool.enqueue conn ~now charge "4242 4242 4242 4242"); + if n mod 20 = 0 then + import conn ~file:("orders-" ^ string_of_int n ^ ".csv"); + Ok ()) + with + | Ok () -> () + | Error e -> prerr_endline (Spindle_postgres.error_to_string e)); + Eio.Time.Mono.sleep_span (Eio.Stdenv.mono_clock env) Mtime.Span.(700 * ms); + generate env pool ~random (n + 1) + +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> + Eio.Switch.run @@ fun sw -> + let random = Random.State.make_self_init () in + match Pg.Conninfo.of_string database with + | Error e -> prerr_endline e + | Ok conninfo -> ( + let net = Eio.Stdenv.net env and mono_clock = Eio.Stdenv.mono_clock env in + match Spindle_postgres.Pool.create ~sw ~net ~mono_clock conninfo with + | Error e -> prerr_endline (Rowtype.error_to_string e) + | Ok pool -> ( + let limited = + Spindle_postgres.Pool.use pool (fun conn -> + Spool.Queue.set_limits conn ~now:(Ptime_clock.now ()) + ~running:(Some 1) ~rate:None ~per_partition:true "partner") + in + (match limited with + | Ok () -> () + | Error (`Bad_limit why) -> prerr_endline why + | Error (#Spindle_postgres.error as e) -> + prerr_endline (Spindle_postgres.error_to_string e)); + let first = + runner ~sw env ~random + ~queues:[ ("mail", 4); ("partner", 4); ("imports", 2) ] + conninfo + and second = + runner ~sw env ~random + ~queues: + [ ("mail", 2); ("payments", 2); ("imports", 2); ("reports", 1) ] + conninfo + in + match (first, second) with + | Error e, _ | _, Error e -> prerr_endline e + | Ok first, Ok second -> + Eio.Fiber.fork_daemon ~sw (fun () -> generate env pool ~random 0); + Spindle.serve env ~port + ~resources:[ Spindle.Dep.resource db pool ] + ~ready:(fun _ -> + print_endline + ("The dashboard: http://localhost:" ^ string_of_int port + ^ "/spool")) + (Spool_dashboard.routes ~operator ~may ~pool:db ~mono_clock ()); + Spool.Runner.stop first; + Spool.Runner.stop second)) +``` diff --git a/agents/pages/guide/enqueueing.md b/agents/pages/guide/enqueueing.md new file mode 100644 index 0000000..25548af --- /dev/null +++ b/agents/pages/guide/enqueueing.md @@ -0,0 +1,171 @@ +# Enqueueing + +`Spool.enqueue` writes a job through the caller's connection, in its +transaction, and answers its id. + +## In your transaction + +`enqueue` writes the row and nothing else, so a rollback leaves no job; a +runner hears of it when the transaction commits. The work that made the job +owed and the job itself are one transaction, written through one +connection: + +```ocaml title="receipt.ml" +(* An order's receipt: its kind, the order taken with its receipt owed in + one transaction, and a runner that sends it. quick_start.ml runs it. *) + +open Result.Syntax +module Pg = Rowtype_postgres + +let send_receipt order = + Printf.printf "Receipt for order %d sent.\n%!" order; + Ok () + +(* {"order": 42} *) +let order = + Wiretype.Object.map Fun.id + |> Wiretype.Object.mem "order" Wiretype.int ~enc:Fun.id + |> Wiretype.Object.finish + +let receipt = Spool.Kind.make ~queue:"mail" "receipt.send" order + +let insert_order = + Rowtype.find ~params:Rowtype.text ~row:Rowtype.int + "insert into orders (email) values ($1) returning id" + +(* The order and its receipt, in one transaction: a rollback leaves neither. *) +let take_order conn ~now email = + Pg.Transaction.within conn @@ fun conn -> + let* order = Pg.run conn insert_order email in + Spool.enqueue conn ~now ~unique:(string_of_int order) receipt order + +let runner ~sw env conninfo = + Spool.Runner.create ~sw ~net:(Eio.Stdenv.net env) + ~mono_clock:(Eio.Stdenv.mono_clock env) + ~now:Ptime_clock.now + ~queues:[ ("mail", 2) ] + [ Spool.handle receipt (fun _job order -> send_receipt order) ] + conninfo +``` + +A job written outside a transaction is committed at once, as any statement +is. + +## When it runs + +A job may run `~at` an instant, `~after` a span from now, and not after +`~expires_at`; given neither `~at` nor `~after`, it runs now. A job past +`expires_at` is discarded unrun. `~priority` overrides its kind's: + +```ocaml title="enqueueing.ml" +(* Enqueueing: a job now, later, once for a key, and not after it stops + being worth running. + + dune exec examples/enqueueing.exe *) + +open Result.Syntax +module Pg = Rowtype_postgres + +let database = "postgres://postgres:postgres@localhost:5432/postgres" + +let order = + Wiretype.Object.map Fun.id + |> Wiretype.Object.mem "order" Wiretype.string ~enc:Fun.id + |> Wiretype.Object.finish + +let receipt = Spool.Kind.make ~queue:"mail" "receipt.send" order +let reminder = Spool.Kind.make ~queue:"mail" "order.remind" order + +let hours_on now hours = + Option.value + (Ptime.add_span now (Ptime.Span.of_int_s (hours * 3600))) + ~default:Ptime.max + +let schedule conn ~now order_id = + (* in an hour, and never if it has not run within a day *) + let* _ = + Spool.enqueue conn ~now ~after:Mtime.Span.hour ~expires_at:(hours_on now 24) + reminder order_id + in + (* at an instant, after every job of a higher priority due with it *) + Spool.enqueue conn ~now ~at:(hours_on now 2) ~priority:9 reminder order_id + +let explain = function + | Ok id -> "job " ^ Spool.Id.to_string id + | Error (`Bad_priority p) -> Printf.sprintf "priority %d is not 0 to 9" p + | Error (`Unencodable e) -> Wiretype.Unwritable.to_string e + | Error (#Pg.error as e) -> Pg.error_to_string e + +let () = + Eio_main.run @@ fun env -> + Eio.Switch.run @@ fun sw -> + match Pg.Conninfo.of_string database with + | Error e -> prerr_endline e + | Ok conninfo -> ( + match + Pg.connect ~sw ~net:(Eio.Stdenv.net env) + ~mono_clock:(Eio.Stdenv.mono_clock env) + conninfo + with + | Error e -> prerr_endline (Rowtype.error_to_string e) + | Ok conn -> + let now = Ptime_clock.now () in + print_endline + (explain + (Spool.enqueue conn ~now ~unique:"A-1001" receipt "A-1001")); + print_endline (explain (schedule conn ~now "A-1001")); + Pg.close conn) +``` + +A runner claims the due jobs of a queue by priority, 0 first, then by the +instant each was due, then in the order they were written. + +## Once for a key + +A `~unique` key already waiting in the kind is that job, brought to the +earlier instant and the higher priority, and its id is the answer: asking +twice is one job. A key is unique among waiting jobs only, so a change made +while its job runs is a job of its own. + +## What it answers + +The job's `Spool.Id.t`, or why it was not written, as `explain` in +`enqueueing.ml` above tells them apart: + +- `` `Bad_priority `` is a priority outside 0 to 9. A priority is a value a + caller may compute, so one outside the range is refused rather than + raised. +- `` `Unencodable `` is a payload its kind's description could not write. +- The rest is the statement's failure, as `rowtype` answers it, and inside + `Rowtype_postgres.Transaction.within`, the transaction's own. + +An id is a job's handle, for `find`, `cancel` and `retry`: a counter, so +never put where a stranger could read it. + +## Once for a period + +`~unique_for` holds a key for a period from the enqueue, whatever its job's +state: an enqueue of the kind and key within it is answered with that job, +waiting, running or already finished. + +```ocaml +Spool.enqueue conn ~now ~unique:customer ~unique_for:Mtime.Span.hour digest d +``` + +The row is kept until the period ends -- pruning waits for it, and a kind +that keeps nothing keeps the row and not its payload. Without `~unique`, the +period holds for the kind: at most one job of it enqueued in any such +period. + +## Many at once + +`Spool.enqueue_many` writes many jobs of one kind in one statement, in the +caller's transaction: + +```ocaml +Spool.enqueue_many conn ~now import_row rows +``` + +`~unique` gives each payload's key, and the first payload of a key stands for +the rest. It answers every job's id, each once and in no order -- what a job +that waits for all of them is given. diff --git a/agents/pages/guide/handlers.md b/agents/pages/guide/handlers.md new file mode 100644 index 0000000..0e3459f --- /dev/null +++ b/agents/pages/guide/handlers.md @@ -0,0 +1,61 @@ +# Handlers + +A handler is what one attempt at a job of a kind does. `Spool.handle` pairs +a kind with a function of the attempt and the payload, and the runner is +given the list: + +```ocaml title="mail.ml" +(* A handler: what one attempt at a receipt does, and what its failure asks + of the runner. runner.ml runs it. *) + +let order = + Wiretype.Object.map Fun.id + |> Wiretype.Object.mem "order" Wiretype.string ~enc:Fun.id + |> Wiretype.Object.finish + +let receipt = Spool.Kind.make ~queue:"mail" "receipt.send" order + +(* Stands for a mail service's client; [key] makes a repeated send one. *) +let send ~key order : + (unit, [ `Busy | `Slow_down of Mtime.Span.t | `No_such_address ]) result = + Printf.printf "Receipt for order %s sent, keyed %s.\n%!" order key; + Ok () + +let send_receipt (job : Spool.job) order = + match send ~key:(Spool.Id.to_string job.id) order with + | Ok () -> Ok () + | Error `Busy -> Error (Spool.Retry "the mail service is busy") + | Error (`Slow_down wait) -> + Error (Spool.Retry_in (wait, "the mail service said wait")) + | Error `No_such_address -> Error (Spool.Discard "no such address") +``` + +## What it answers + +A handler answers `Ok ()`, `Retry reason` (after the kind's backoff), +`Retry_in (span, reason)` (after what an upstream said) or `Discard reason` +(never again, and no attempt used: it cannot succeed however long it +waits). The reason is in words for an operator, kept with the attempt in +the job's `errors`. + +A failed attempt that was the job's last discards it. + +## A raise, and a timeout + +A raise is a retry whose reason names the exception's constructor, never +its argument; the log line carries the rest. An attempt past its kind's +timeout is cancelled and is a failure. + +A job's payload has no log level: no line the queue writes, at any level, +carries it. + +## The attempt + +`Spool.job` is the attempt a handler is running: its `id`, its `attempt`, +counting from one, its `max_attempts` and its `inserted_at`. + +## At least once + +What a job runs is at least once and finished once. A handler whose effect +must happen once is idempotent, or keyed by the job -- as the handler above +gives the mail service the job's id, so a receipt sent twice is one. diff --git a/agents/pages/guide/kinds.md b/agents/pages/guide/kinds.md new file mode 100644 index 0000000..9650e84 --- /dev/null +++ b/agents/pages/guide/kinds.md @@ -0,0 +1,104 @@ +# Kinds + +A kind is a kind of job: its name, its payload's +[wiretype](https://hyphatech.github.io/wiretype/) description, and how it is +run. It is a constant, made once where the program's other constants are, +and shared by the code that enqueues and the runner that handles it: + +```ocaml title="kinds.ml" +(* Kinds of job: a payload's description, and how each kind is run. + + dune exec examples/kinds.exe *) + +(* {"order": "..."} *) +let order = + Wiretype.Object.map (fun id -> id) + |> Wiretype.Object.mem "order" Wiretype.string ~enc:Fun.id + |> Wiretype.Object.finish + +let receipt = + Spool.Kind.make ~queue:"mail" ~timeout:Mtime.Span.min "receipt.send" order + +(* A report is slow, rarely worth retrying, and holds what no row should keep + once it is sent. *) +let report = + Spool.Kind.make ~queue:"reports" ~priority:5 ~max_attempts:3 + ~timeout:Mtime.Span.(30 * min) + ~backoff:(fun ~attempt -> + let minutes = 10 * attempt in + Mtime.Span.(minutes * min)) + ~keep:false "report.monthly" order + +let () = + List.iter print_endline + [ + Spool.Kind.name receipt; + Spool.Kind.name report; + Spool.Kind.name Reminder.reminder; + ] +``` + +## What a kind says + +A kind is its name, its payload's `wiretype` description, its queue, its +priority (0 to 9, 0 first), its attempts (20), its timeout (five minutes), +its backoff and whether its rows are kept once completed. Each is an +argument of `Spool.Kind.make`: + +| Argument | Unless given | What it is | +|---|---|---| +| `?queue` | `"default"` | The queue a runner claims it from | +| `?priority` | `0`, the first | 0 to 9: a job of a lower number runs before one due with it | +| `?max_attempts` | `20` | How many attempts it has before it is discarded | +| `?timeout` | five minutes | An attempt's bound: one past it is cancelled and is a failure | +| `?backoff` | 15 s doubled each attempt to at most six hours, spread by a tenth either way | How long the attempt after `attempt` waits: twenty attempts span about two and a half days | +| `?keep` | `true` | `false` deletes a job the moment it completes, so a payload that should not outlive its work does not | +| `?partition` | none | The partition a job is in, from its payload: what a queue limited per partition counts by ([Limiting a queue](limiting.md)) | +| `?sensitive` | `false` | Keeps its jobs' payloads from every answer of spool's -- `find`, `jobs`, the dashboard -- as every payload is kept from every log line | + +`report` in `kinds.ml` above gives each of them. + +Every instant the queue is given or answers is a `Ptime.t`, the caller's +`now`, and every duration an `Mtime.Span.t` named for what it bounds. + +## Its name is its identity + +A kind's name is its identity in the table: renaming one strands its +waiting jobs, so a changed payload shape is a new name. `Spool.Kind.name` +answers it. + +## The payload is an object + +The payload is an object, and `Kind.make` refuses a description of anything +else: each member is named for what it holds, so a row read in the table +says what each value is of -- a bare key names nothing -- and a kind gains +a member, with an `~absent`, without a new name: + +```ocaml title="reminder.ml" +(* A kind whose payload gained a member, read with its default from a row + written before it. kinds.ml names it. *) + +type reminder = { invoice : string; channel : string } + +(* {"invoice": "...", "channel": "email"}: "channel" was added later, and a + row written before it reads as "email". *) +let reminder_payload = + Wiretype.Object.map (fun invoice channel -> { invoice; channel }) + |> Wiretype.Object.mem "invoice" Wiretype.string ~enc:(fun r -> r.invoice) + |> Wiretype.Object.mem "channel" Wiretype.string ~absent:"email" + ~enc:(fun r -> r.channel) + |> Wiretype.Object.finish + +let reminder = Spool.Kind.make ~queue:"mail" "invoice.remind" reminder_payload +``` + +A row written before `channel` was added reads as `"email"`. A job whose +payload its kind's description no longer reads is discarded, its reason +saying so. + +## What it refuses + +An empty name or queue, a priority outside 0 to 9, attempts under one, a +timeout of zero, or a payload that is not an object raise +`Invalid_argument`: a kind is a constant written in source, so a program +that starts never meets one. diff --git a/agents/pages/guide/limiting.md b/agents/pages/guide/limiting.md new file mode 100644 index 0000000..9df6b7f --- /dev/null +++ b/agents/pages/guide/limiting.md @@ -0,0 +1,45 @@ +# Limiting a queue + +A runner's slots bound what that runner runs. A queue's limits bound what +every runner of it runs together, and they live in the table, where every +runner reads them: + +```ocaml +Spool.Queue.set_limits conn ~now "payments" + ~running:(Some 5) + ~rate:(Some { attempts = 60; per = Mtime.Span.min }) + ~per_partition:false +``` + +- **`running`**: how many of its jobs run at once, across every runner. +- **`rate`**: how many attempts begin in any period of `per`, across every + runner: a partner's API that allows sixty calls a minute. +- Each call replaces all three; `None` is no limit. + +A limit that could never let a job run -- no slot, no attempt, or a period +of nothing -- is refused as `` `Bad_limit ``, saying why. + +## Partitions + +A kind names the partition each of its jobs is in, from its payload: + +```ocaml +let charge = + Spool.Kind.make ~queue:"payments" ~partition:(fun c -> c.customer) + "charge" charge_json +``` + +With `~per_partition:true`, `running` and `rate` hold for each partition: +`~running:(Some 1)` runs one customer's jobs one at a time, in order, while +other customers' run beside them. Partitions are taken in turns -- each +one's first job, then each one's second -- the one served longest ago +first, so a customer with one job waiting is not kept behind another's +hundred. Within a partition, jobs keep their order: priority, instant, +enqueueing. + +## What it costs + +A queue with neither limits nor partitions is claimed from as before. A +limited one is claimed from under a lock of its own, one runner at a time, +counting what runs and what began in the rate's period, so its claims cost +more: keep limits for the queues that need them. diff --git a/agents/pages/guide/limits.md b/agents/pages/guide/limits.md new file mode 100644 index 0000000..c9eb8f4 --- /dev/null +++ b/agents/pages/guide/limits.md @@ -0,0 +1,20 @@ +# What it does not do yet + +- **A job's lines carry no request id or trace of the enqueuer's.** The + runner's statements reach the application's observer, but nothing ties a + job to the request that made it owed. +- **A queue's counts are exported nowhere.** `counts` answers them, and + nothing turns them into metrics. +- **A handler's own writes are not part of finishing its job.** A handler + writes to the application's tables in a transaction of its own, before + the runner records the job complete in another, so a runner that dies + between the two runs the job again: a handler's write is idempotent, + keyed by the job or by what it writes about. +- **The dashboard needs a Spindle server.** `spool-dashboard` is routes of + one, and nothing serves it without. +- **A handler that never yields cannot be stopped.** A timeout, a lost lease + and stopping cancel a fiber at its next effect, so a handler busy on the + CPU without one runs on until it ends. +- **Two clocks that disagree by more than a quarter of a lease** can run one + job in two places: a lease is an instant from the claiming runner's + `now`, compared against another's when it rescues. diff --git a/agents/pages/guide/operating.md b/agents/pages/guide/operating.md new file mode 100644 index 0000000..7c3c242 --- /dev/null +++ b/agents/pages/guide/operating.md @@ -0,0 +1,186 @@ +# Operating a queue + +`find`, `jobs`, `counts`, `cancel`, `retry`, `delete` and `run_again` are an +operator's hand, with a queue's pause and the list of runners. Each runs on +a connection of the caller's, as `enqueue` does, and takes a job by the +`Spool.Id.t` that `enqueue`, `retry` or `Runner.drain` answered. This +program enqueues a job, cancels it, retries it, finds it, and prints every +queue's counts: + +```ocaml title="operating.ml" +(* An operator's hand: a job enqueued, found, cancelled and retried, and the + queues' counts. + + dune exec examples/operating.exe *) + +module Pg = Rowtype_postgres + +let database = "postgres://postgres:postgres@localhost:5432/postgres" + +let order = + Wiretype.Object.map Fun.id + |> Wiretype.Object.mem "order" Wiretype.string ~enc:Fun.id + |> Wiretype.Object.finish + +let receipt = Spool.Kind.make ~queue:"mail" "receipt.send" order + +let state_name : Spool.state -> string = function + | Available -> "available" + | Blocked -> "blocked" + | Running -> "running" + | Completed -> "completed" + | Discarded -> "discarded" + | Cancelled -> "cancelled" + +let print_counts conn = + match Spool.counts conn with + | Error e -> prerr_endline (Rowtype.error_to_string e) + | Ok counts -> + List.iter + (fun (queue, state, n) -> + Printf.printf "%s %s %d\n" queue (state_name state) n) + counts + +let print_job conn id = + match Spool.find conn id with + | Error e -> prerr_endline (Rowtype.error_to_string e) + | Ok None -> print_endline "no such job" + | Ok (Some (job : Spool.info)) -> + Printf.printf "%s in %s: %s, attempt %d of %d\n" job.kind job.queue + (state_name job.state) job.attempt job.max_attempts; + List.iter + (fun (f : Spool.failed) -> + Printf.printf " attempt %d at %s: %s\n" f.attempt + (Ptime.to_rfc3339 f.at) f.reason) + job.errors + +let cancel conn id = + match Spool.cancel conn ~now:(Ptime_clock.now ()) id with + | Ok true -> print_endline "cancelled" + | Ok false -> print_endline "it had finished" + | Error e -> prerr_endline (Rowtype.error_to_string e) + +let retry conn id = + match Spool.retry conn ~now:(Ptime_clock.now ()) id with + | Ok (Some waiting) -> + print_endline ("waiting as " ^ Spool.Id.to_string waiting) + | Ok None -> print_endline "it was not discarded or cancelled" + | Error e -> prerr_endline (Rowtype.error_to_string e) + +let () = + Eio_main.run @@ fun env -> + Eio.Switch.run @@ fun sw -> + match Pg.Conninfo.of_string database with + | Error e -> prerr_endline e + | Ok conninfo -> ( + match + Pg.connect ~sw ~net:(Eio.Stdenv.net env) + ~mono_clock:(Eio.Stdenv.mono_clock env) + conninfo + with + | Error e -> prerr_endline (Rowtype.error_to_string e) + | Ok conn -> + (match + Spool.enqueue conn ~now:(Ptime_clock.now ()) receipt "A-1001" + with + | Ok id -> + cancel conn id; + retry conn id; + print_job conn id; + print_counts conn + | Error (#Rowtype.error as e) -> + prerr_endline (Rowtype.error_to_string e) + | Error _ -> prerr_endline "the job could not be written"); + Pg.close conn) +``` + +## Counts + +`Spool.counts` answers how many jobs each queue holds in each state. + +A `Spool.state` is one of six: `Available` (waiting, or scheduled, or to +be retried), `Blocked` (waiting for jobs it was enqueued after), `Running`, +`Completed`, `Discarded` (failed on its last attempt, expired, or given up) +and `Cancelled`. + +## Finding a job + +`Spool.find` answers a job's `Spool.info`, or `None` where there is no such +row -- a job pruned, or one completed by a kind that keeps none; `print_job` +above reads one: + +| Field | What it holds | +|---|---| +| `id`, `queue`, `kind` | The job, its queue and its kind's name | +| `state`, `priority` | Where it is, and its priority | +| `attempt`, `max_attempts` | Attempts begun, and how many it has | +| `scheduled_at` | When it may run next | +| `inserted_at`, `finished_at` | When it was written, and finished | +| `errors` | Each failed attempt: which, when, and why, in the handler's words, oldest first | +| `payload` | Its JSON, or `None` for a kind made `~sensitive` | + +## Listing jobs + +`Spool.jobs conn ~limit` answers jobs newest first, of a `~state`, a +`~queue` and a `~kind` where given; the next page is `~before` the last +one's id. `Spool.counts ~finished:false` counts only what waits, is blocked +and runs, from their indexes, without reading the finished rows retention +keeps: what a page that asks every second reads. + +## Cancelling and retrying + +A cancelled waiting job never runs and a cancelled running one is stopped +at its runner's next heartbeat; `cancel` answers `false` where it had +finished. + +A retried job is available again from its first attempt with its reasons +kept, unless a job of its kind already waits under its key, which is then +the answer, and the retried row stays as it was, so one key never runs +twice. `retry` takes a discarded or cancelled job, and answers `None` for +any other, as `cancel` and `retry` above show. + +## Deleting a job + +`Spool.delete` removes a job's row, whatever its state but running, and +answers `false` for a running job or one there is not. A job deleted before +it completed cancels what waits on it, as a cancel does. Cancel a running job +first; once it has stopped, it can be deleted. + +## Running a job again + +`Spool.run_again conn ~now id` enqueues a new job, a copy of this one -- its +kind, queue, payload and settings -- from its first attempt, whatever this +one's state, and answers the copy's id. Its work is done again, as an +operator asks, so it has no unique key and waits for nothing. `retry` is for +a job that failed for good or was cancelled; `run_again` is for any, a +completed one among them. + +## Pausing a queue + +A queue's pause is kept in the table, not in any runner, so every runner +obeys it -- one started after it among them -- until it is resumed: + +```ocaml +Spool.Queue.pause conn ~now "mail" (* no runner claims from it *) +Spool.Queue.resume conn ~now "mail" (* claimed from again, at once *) +``` + +What runs when a queue is paused runs to its end. `Spool.Queue.list` answers +every queue a runner has named, each with whether it is paused and its +limits ([Limiting a queue](limiting.md)). + +## Runners + +`Spool.Runner.list` answers the runners running: each one's host, process, +the queues it runs with how many jobs of each at once, when it started and +its last heartbeat. A runner writes its row at every heartbeat and deletes +it when it stops; one a lease late is deleted by another, so a runner killed +leaves the list within a lease. + +## What attempts came to + +`Spool.Stats.since conn instant` answers, a row a second, queue, kind and +outcome -- `Completed`, `Retried` or `Discarded` -- how many attempts +finished, how long they ran and how long they waited past their scheduled +instant, together. A runner counts each attempt in the transaction that +records it, and prunes the rows as it prunes completed jobs. diff --git a/agents/pages/guide/runner.md b/agents/pages/guide/runner.md new file mode 100644 index 0000000..55da1d2 --- /dev/null +++ b/agents/pages/guide/runner.md @@ -0,0 +1,151 @@ +# The runner + +A runner runs the named queues, each with how many of its jobs may run at +once, claiming only the kinds it has a handler for. It is made where the +program starts, started, and stopped as the program ends: + +```ocaml title="runner.ml" +(* A runner beside the application: made where the program starts, + started, and stopped as the program ends. The receipt's handler is + mail.ml. + + dune exec examples/runner.exe *) + +module Pg = Rowtype_postgres + +let database = "postgres://postgres:postgres@localhost:5432/postgres" + +let order = + Wiretype.Object.map Fun.id + |> Wiretype.Object.mem "order" Wiretype.string ~enc:Fun.id + |> Wiretype.Object.finish + +let report = Spool.Kind.make ~queue:"reports" "report.monthly" order +let build_report _order = Ok () + +(* Stands for the application's own work, a server say, until it ends. *) +let serve env = + Eio.Time.Mono.sleep_span (Eio.Stdenv.mono_clock env) Mtime.Span.min + +let run ~sw env conninfo = + match + Spool.Runner.create ~sw ~net:(Eio.Stdenv.net env) + ~mono_clock:(Eio.Stdenv.mono_clock env) + ~now:Ptime_clock.now ~pool_size:3 + ~lease:Mtime.Span.(2 * min) + ~retain_completed:Mtime.Span.hour + ~queues:[ ("mail", 4); ("reports", 1) ] + [ + Spool.handle Mail.receipt Mail.send_receipt; + Spool.handle report (fun _job order -> build_report order); + ] + conninfo + with + | Error refused -> prerr_endline (Spool.Runner.refused_to_string refused) + | Ok runner -> + Spool.Runner.start runner; + serve env; + Spool.Runner.stop ~grace:Mtime.Span.(30 * s) runner + +let () = + Eio_main.run @@ fun env -> + Eio.Switch.run @@ fun sw -> + match Pg.Conninfo.of_string database with + | Error e -> prerr_endline e + | Ok conninfo -> run ~sw env conninfo +``` + +Nothing runs until `Runner.start`, which forks a fiber per queue, the +heartbeat and the listener on the switch it was made with. + +## Where it runs + +A runner is fibers in whichever program makes it; spool is a library, and +there is no spool process to start. Runners meet only in the table, so the +same handlers can run beside the application's server or in a program of +their own: + +- **Beside the server**, as above: one process to deploy, and the jobs share + its machine and its restarts. +- **In a program of its own**: a `main` that makes the runner, starts it, + and stops it on the signal that ends the program, with no server at all. + The jobs then have their own machines, scaled and restarted apart from + the requests', and the application's server makes no runner and only + enqueues, which needs none. + +Either way, more runners are more processes pointed at one database: each +claims under its own lease, and a queue's pause and limits, kept in the +table, hold across all of them. + +## How it runs a job + +| What | How | +|---|---| +| Claiming | one statement, `for update skip locked`, in a transaction that commits before the handler starts, so runners in several processes claim from one queue without waiting on each other | +| Leases | a claim holds a job until `lease_ends_at`; the heartbeat renews every lease the runner holds every quarter lease, and a runner that cannot renew for three quarters of it stops the job itself | +| Finishing | guarded by the runner and the attempt: a finish from a runner whose lease was taken changes nothing | +| Rescue | every runner's heartbeat makes every lapsed lease available again, its attempt counted, or discarded where it was the last | +| Backoff | 15 s doubled each attempt to at most six hours, spread by a tenth either way: twenty attempts span about two and a half days | +| Waking | `enqueue` notifies the table's channel with the queue's name; the poll is the truth and a notification a hint | +| Expiry | a job past `expires_at` is discarded unrun | +| Pruning | hourly, finished rows older than their retention: a day completed, a fortnight discarded or cancelled | +| Stopping | `stop` claims nothing more, waits a grace for running jobs, then puts back the rest with their attempt not counted | + +A job is claimed, run and finished in three transactions, and the work is +in none of them, so a long job holds no connection and no row lock while it +runs. + +## Its own connections + +The runner's connections are its own -- a small pool and a listener -- +because one borrowed from the application's would lose its heartbeats +exactly when the application is busiest, and a lost heartbeat is a job run +twice. It is given a `Rowtype_postgres.Conninfo.t`, read from a connection +string by `Rowtype_postgres.Conninfo.of_string`, and makes them itself. + +## Its settings + +| Argument | Unless given | What it is | +|---|---|---| +| `~now` | | The clock every instant it writes or compares is read from | +| `?pool_size` | 2 | Its pool's connections | +| `?poll` | a second | How often a queue looks for due jobs between notifications | +| `?lease` | a minute | How long a claim holds without renewal, renewed every quarter of it | +| `?retain_completed` | a day | How long a completed row stays | +| `?retain_failed` | fourteen days | How long a discarded or cancelled row stays | +| `?observe` | none | A `Rowtype_postgres.observer` watching every statement on its pool, as an application's own | +| `~queues` | | Each queue it runs, with how many of its jobs may run at once | + +Every wait is an `Mtime.Span.t` on the monotonic clock it is given, and +every instant the `now` it is given, never the database's clock. + +## What it refuses + +Before it answers, `Runner.create` checks every statement spool runs +against the database. It answers `Error` with what it refused, and +`Runner.refused_to_string` says it in words: + +- `Unrun_queue`: a handler's kind is in no queue it runs. +- `Two_handlers`: one kind handled twice. +- `No_concurrency`: a queue given fewer than one slot. +- `Unreachable`: its pool could not be made. +- `Unmigrated`: the table is missing, or behind what spool runs -- spool's + migrations are not applied, and each problem says where. Its pool is + closed. + +## Stopping + +`Runner.stop` claims nothing more, waits up to its `?grace` (ten seconds) +for running jobs, puts back the rest, their attempt not counted, since they +were interrupted and did not fail, and closes its connections. It returns +within the grace and one statement. + +A job is also stopped when its attempt passes its kind's timeout, when its +lease is lost, and when an operator cancels it. Each cancels the handler's +fiber at its next effect. + +## Its log + +The runner logs on the `Logs` source `spool`: each attempt and what it came +to, rescued and pruned rows, and a listener lost. No line carries a job's +payload. diff --git a/agents/pages/guide/schedules.md b/agents/pages/guide/schedules.md new file mode 100644 index 0000000..b2592f6 --- /dev/null +++ b/agents/pages/guide/schedules.md @@ -0,0 +1,55 @@ +# Recurring jobs + +A schedule enqueues a kind's job at each tick of a cron expression, read in +a time zone: + +```ocaml +let nightly = + Spool.Schedule.make ~name:"report.nightly" ~cron:"0 2 * * *" + ~zone:"Europe/London" report { day = `Yesterday } + +Spool.Runner.create ~schedules:[ nightly ] ... +``` + +Give the schedule to every runner, or to any of them: **a tick is one job +however many runners hold it.** Its row in `spool_schedules` keeps the next +tick, and the transaction that enqueues the tick's job moves it on, guarded +by the value it read, so of every runner that sees the tick due, one +enqueues it. No runner is elected, and none has to fail over. + +## The expression + +Five fields -- minute, hour, day of the month, month, day of the week -- +each `*`, a value, a range `a-b`, a step `*/n` or `a-b/n`, or a list of +them; Sunday is both 0 and 7. `@hourly`, `@daily`, `@midnight`, `@weekly`, +`@monthly`, `@yearly` and `@annually` name their usual expressions. Where +both days are restricted, a day either names is a tick, as cron has it. + +## The zone + +`~zone` is required, a name of the tz database such as `Europe/London` or +`UTC`, because a business's 08:00 is local, and moves against UTC twice a +year. Where the clock goes forward and skips a tick's local time, the tick +is the instant the clock changes; where it goes back and repeats one, the +tick is its first instance alone. + +## Missed ticks, and deploys + +Ticks missed while no runner ran are enqueued once, the latest of them, so +an outage does not flood a queue. A schedule's next tick survives a deploy +while its expression and zone stay the same; change either and it starts +again from now. + +A schedule that cannot run -- an expression that does not read or names no +instant, such as the thirtieth of February, a zone the tz database does not +have, a payload that cannot be written -- raises `Invalid_argument` where it +is made, as a kind does. + +## By hand + +`Spool.Schedule.list` answers every schedule a runner has held, with its +next and last tick. `Spool.Schedule.run_now conn ~now name` enqueues its job +now, beside its ticks, which it does not move. + +In a test, `Runner.drain` enqueues every tick due at the clock's `now` +before it runs what is due. diff --git a/agents/pages/guide/spindle.md b/agents/pages/guide/spindle.md new file mode 100644 index 0000000..18237b3 --- /dev/null +++ b/agents/pages/guide/spindle.md @@ -0,0 +1,152 @@ +# In a Spindle application + +spool is a library: in an application served by +[Spindle](https://hyphatech.github.io/spindle/), a route owes a job in the +transaction its request writes in, and a runner beside the server does the +work. There is no spool process to start, and nothing of Spindle's to +change. + +```ocaml title="spindle.ml" +(* spool in a Spindle application: a route takes an order and owes its + receipt in the request's transaction, and a runner beside the server sends + it. The orders table is examples/migrations'. + + rowtype-migrate up --source spool --dir examples/migrations + dune exec examples/spindle.exe + curl localhost:8080/orders -H 'content-type: application/json' \ + -d '{"email": "ada@example.com"}' *) + +open Spindle.Syntax +module Pg = Rowtype_postgres + +let database = + Option.value + (Sys.getenv_opt "DATABASE_URL") + ~default:"postgres://postgres:postgres@localhost:5432/postgres" + +(* {"order": 42} *) +let order = + Wiretype.Object.map Fun.id + |> Wiretype.Object.mem "order" Wiretype.int ~enc:Fun.id + |> Wiretype.Object.finish + +let receipt = Spool.Kind.make ~queue:"mail" "receipt.send" order + +let send_receipt (_ : Spool.job) order = + Printf.printf "Receipt for order %d sent.\n%!" order; + Ok () + +(* {"email": "ada@example.com"} *) +let email = + Wiretype.Object.map Fun.id + |> Wiretype.Object.mem "email" Wiretype.string ~enc:Fun.id + |> Wiretype.Object.finish + +let insert_order = + Rowtype.find ~params:Rowtype.text ~row:Rowtype.int + "insert into orders (email) values ($1) returning id" + +(* The application's pool, the one its routes already read. *) +let db : Spindle_postgres.Pool.t Spindle.Dep.t = + Spindle.Dep.of_resource "database" + +(* A payload the kind cannot write, or a priority out of range, is a bug of + the program's, never the caller's. *) +let refusal = function + | `Unencodable _ | `Bad_priority _ -> + Spindle.Refusal.internal ~detail:"the receipt could not be enqueued" + | #Spindle_postgres.error as e -> Spindle_postgres.refusal e + +(* The order and its receipt in one transaction: a rollback leaves neither, + and the runner hears of the job when it commits. *) +let take_order = + Spindle.post ~summary:"Take an order, and owe its receipt" + Spindle.Path.(s "orders") + (Spindle.Returns.json order) + (let+ pool = db and+ now = Spindle.now and+ email = Spindle.json email in + Spindle_postgres.Pool.transaction pool (fun conn -> + let* id = Pg.run conn insert_order email in + let* _job = + Spool.enqueue conn ~now ~unique:(string_of_int id) receipt id + in + Ok id) + |> Result.map_error refusal) + +(* The runner starts before the server listens and stops once it has + stopped, so a job owed by the last request is still sent, or left for the + next deploy's runner. *) +let () = + Spindle.Log.setup (); + Eio_main.run @@ fun env -> + Eio.Switch.run @@ fun sw -> + let net = Eio.Stdenv.net env and mono_clock = Eio.Stdenv.mono_clock env in + match Pg.Conninfo.of_string database with + | Error e -> prerr_endline e + | Ok conninfo -> ( + match Spindle_postgres.Pool.create ~sw ~net ~mono_clock conninfo with + | Error e -> prerr_endline (Rowtype.error_to_string e) + | Ok pool -> ( + match + Spool.Runner.create ~sw ~net ~mono_clock ~now:Ptime_clock.now + ~queues:[ ("mail", 4) ] + [ Spool.handle receipt send_receipt ] + conninfo + with + | Error refused -> + prerr_endline (Spool.Runner.refused_to_string refused) + | Ok runner -> + Spool.Runner.start runner; + Spindle.serve env + ~resources:[ Spindle.Dep.resource db pool ] + [ take_order ]; + Spool.Runner.stop runner; + Spindle_postgres.Pool.close pool)) +``` + +## A job in the request's transaction + +A route reads the pool the application already holds as a resource, and +`Spindle_postgres.Pool.transaction` runs its writes in one transaction: +`Ok` commits, `Error` rolls back. `Spool.enqueue` takes the same +connection, so the order and its receipt are written together, a refusal +leaves neither, and the runner hears of the job when the transaction +commits. A unique key, here the order's id, makes a request sent twice one +job. + +What enqueueing can answer beside a statement's failure -- a payload its +kind cannot write, a priority out of range -- is the program's bug, never +the caller's, so it is an internal refusal, a `500`; +`Spindle_postgres.refusal` words the rest, a pool busy as a `503`. + +## The runner beside the server + +A runner has its own connections, made from the same connection string -- +a small pool and a listener -- because one borrowed from the application's +would lose its heartbeats when the application is busiest ([The +runner](runner.md#its-own-connections)). It is started before +the server listens, and stopped once `Spindle.serve` returns, which it does +when the process is told to stop: running jobs get their grace, and what +is left is put back for the next deploy's runner. + +A runner may instead run in a program of its own, with no server at all; +the application then only enqueues, which needs none ([Where it +runs](runner.md#where-it-runs)). + +## The dashboard + +`spool-dashboard` is routes the same server serves, beside the +application's own, behind its own sign-in: [The +dashboard](dashboard.md). + +```ocaml +Spindle.serve env ~resources:[ Spindle.Dep.resource db pool ] + ([ take_order ] + @ Spool_dashboard.routes ~operator ~may ~pool:db ~mono_clock ()) +``` + +## Kinds are one per name + +A kind's name is its identity in the table, and every runner on a database +claims every job of a kind it handles. Two programs on one database that +make a kind of one name with two payload shapes discard each other's jobs +as unreadable: one name, one kind, wherever it is made. diff --git a/agents/pages/guide/table.md b/agents/pages/guide/table.md new file mode 100644 index 0000000..1e2e470 --- /dev/null +++ b/agents/pages/guide/table.md @@ -0,0 +1,339 @@ +# The table + +spool keeps its jobs in one table, `spool_jobs` (`Spool.table`), and what +its runners share beside them in more, all made by its own +migrations. They are plain SQL, installed with the package in +`share/spool/migrations`, and applied beside your own as a history of their +own, before your application starts: + +```sh +rowtype-migrate up --source spool # spool's migrations, then yours +``` + +`--source` needs rowtype 0.5.0 or later; [rowtype's +migrations](https://hyphatech.github.io/rowtype/) say the rest of the +command. An upgrade of spool that changes the table ships a new migration, +and the same command applies it. With another migration tool, copy the +files from `$(opam var spool:share)/migrations` into its folder: they are +plain Postgres. + +## Checked before a runner starts + +A runner checks the table before it starts, and refuses a database where it +is missing or behind, naming the command to run: `Runner.create` answers +`Unmigrated`, with each problem it found. + +`Spool.statements` is every statement the package runs, for +`Rowtype_postgres.verify` beside your own. A test that runs it finds a +migration that broke one before a job does: + +```ocaml title="verify.ml" +(* A test that every statement the application runs is what its database + says, spool's among them, so a migration that renamed a column fails a + test and not a job. + + dune exec examples/verify.exe *) + +module Pg = Rowtype_postgres + +let database = "postgres://postgres:postgres@localhost:5432/postgres" + +let orders = + Rowtype.list ~params:Rowtype.unit + ~row:Rowtype.(t2 int text) + "select id, email from orders order by id" + +let check conn = + match Pg.verify conn (Spool.statements @ [ Rowtype.Any orders ]) with + | Ok () -> print_endline "Every statement agrees with the database." + | Error (`Disagreements problems) -> List.iter prerr_endline problems + | Error (#Rowtype.error as e) -> prerr_endline (Rowtype.error_to_string e) + +let () = + Eio_main.run @@ fun env -> + Eio.Switch.run @@ fun sw -> + match Pg.Conninfo.of_string database with + | Error e -> prerr_endline e + | Ok conninfo -> ( + match + Pg.connect ~sw ~net:(Eio.Stdenv.net env) + ~mono_clock:(Eio.Stdenv.mono_clock env) + conninfo + with + | Error e -> prerr_endline (Rowtype.error_to_string e) + | Ok conn -> + check conn; + Pg.close conn) +``` + +## States + +Six states, and the rest derived: *scheduled* is `available` with a later +`scheduled_at`, *retrying* is `available` with an attempt made. + +| State | What it means | +|---|---| +| `available` | waiting, or scheduled, or to be retried | +| `blocked` | waiting for jobs it was enqueued after | +| `running` | claimed by a runner, under its lease | +| `completed` | its handler answered `Ok` | +| `discarded` | failed on its last attempt, expired, or given up | +| `cancelled` | cancelled by an operator | + +## Columns + +| Column | What it holds | +|---|---| +| `queue` | The queue a runner claims it from, with that queue's concurrency. | +| `kind` | What runs it: a kind's name, its identity, so a changed payload shape is a new kind. | +| `payload` | What the job is given: an object, as its kind's description wrote it. | +| `priority` | 0 to 9, 0 first: before the instant and the order of enqueueing. | +| `state` | One of the six above. | +| `attempt` | Attempts begun: raised by the claim, so a job that kills its process uses one. | +| `max_attempts` | Its kind's attempts, when it was written. | +| `scheduled_at` | When it may run next. | +| `expires_at` | After when it is not worth running, and is discarded unrun. | +| `partition_key` | The partition its kind gave it, which a queue limited per partition counts by. | +| `unique_key` | Repeated asks of one kind with one key, folded into the job waiting. | +| `sensitive` | Whether its kind keeps its payload from every answer of spool's. | +| `unique_until` | Until when its key answers every enqueue with this job, whatever its state; its row is kept until then. | +| `runner` | The runner holding its lease, while it runs. | +| `lease_ends_at` | Until when its runner holds it, renewed while it runs; a lapsed one is rescued. | +| `inserted_at`, `attempted_at`, `finished_at` | When it was written, last claimed, and finished. | +| `errors` | Each failed attempt's attempt, instant and reason, oldest first. | + +Every instant in it is the `now` a caller gave: no statement reads the +database's clock. + +The migration that makes it + +```sql title="migrations/20261012000000_create_spool_jobs.sql" +-- create_spool_jobs: the table of jobs, spool's own, made by its first migration. + +create table spool_jobs ( + id bigint generated always as identity primary key, + queue text not null, + kind text not null, + payload jsonb not null, + priority smallint not null, + state text not null, + attempt integer not null, + max_attempts integer not null, + scheduled_at timestamptz not null, + expires_at timestamptz, + unique_key text, + runner text, + lease_ends_at timestamptz, + inserted_at timestamptz not null, + attempted_at timestamptz, + finished_at timestamptz, + errors jsonb not null, + constraint spool_jobs_state check (state in + ('available', 'running', 'completed', 'discarded', 'cancelled')), + constraint spool_jobs_priority check (priority between 0 and 9), + constraint spool_jobs_attempts check (max_attempts >= 1 and attempt >= 0), + constraint spool_jobs_running_leased check + ((state = 'running') = (runner is not null and lease_ends_at is not null)), + constraint spool_jobs_finished check + ((state in ('completed', 'discarded', 'cancelled')) = (finished_at is not null)) +); + +create index spool_jobs_due on spool_jobs (queue, priority, scheduled_at, id) + where state = 'available'; +create index spool_jobs_leased on spool_jobs (lease_ends_at) where state = 'running'; +create unique index spool_jobs_waiting_key on spool_jobs (kind, unique_key) + where state = 'available' and unique_key is not null; +create index spool_jobs_finished_at on spool_jobs (finished_at) + where state in ('completed', 'discarded', 'cancelled'); + +comment on table spool_jobs is 'Jobs: work owed, written in the transaction that made it owed, claimed by a runner under a lease, and finished once.'; +comment on column spool_jobs.queue is 'The queue a runner claims it from, with that queue''s concurrency.'; +comment on column spool_jobs.kind is 'What runs it: a kind''s name, its identity, so a changed payload shape is a new kind.'; +comment on column spool_jobs.payload is 'What the job is given: an object, as its kind''s description wrote it.'; +comment on column spool_jobs.priority is '0 to 9, 0 first: before the instant and the order of enqueueing.'; +comment on column spool_jobs.state is 'available, running, completed, discarded or cancelled; scheduled and retrying are available with a later instant or an attempt made.'; +comment on column spool_jobs.attempt is 'Attempts begun: raised by the claim, so a job that kills its process uses one.'; +comment on column spool_jobs.scheduled_at is 'When it may run next.'; +comment on column spool_jobs.expires_at is 'After when it is not worth running, and is discarded unrun.'; +comment on column spool_jobs.unique_key is 'Repeated asks of one kind with one key, folded into the job waiting.'; +comment on column spool_jobs.runner is 'The runner holding its lease, while it runs.'; +comment on column spool_jobs.lease_ends_at is 'Until when its runner holds it, renewed while it runs; a lapsed one is rescued.'; +comment on column spool_jobs.errors is 'Each failed attempt''s attempt, instant and reason, oldest first.'; +``` + +## Beside the jobs + +| Table | What it holds | +|---|---| +| `spool_queues` | A row a queue: whether it is paused, and its limits across every runner. Made when a runner first names the queue, or an operator pauses or limits it. | +| `spool_runners` | A row a runner running: its host, process, queues and last heartbeat. | +| `spool_stats` | A row a second, queue, kind and outcome: how many attempts finished, and how long they ran and waited. | +| `spool_starts` | The attempts begun in a queue with a rate, kept as long as its period. | +| `spool_partitions` | When each partition of a partitioned queue was last served. | +| `spool_schedules` | A row a schedule: its expression, zone, job, and next and last tick. | +| `spool_dependencies` | A row a job waiting for another: the waiting job, and the one it waits for. | + +The migration that makes them + +```sql title="migrations/20261116000000_create_spool_queues_runners_stats.sql" +-- create_spool_queues_runners_stats: what every runner shares beside the jobs -- each queue's +-- pause, the runners running, and what each second's attempts came to. + +create table spool_queues ( + name text primary key, + paused boolean not null, + updated_at timestamptz not null +); + +create table spool_runners ( + id text primary key, + host text not null, + pid integer not null, + queues jsonb not null, + started_at timestamptz not null, + seen_at timestamptz not null +); + +create table spool_stats ( + second timestamptz not null, + queue text not null, + kind text not null, + outcome text not null, + count integer not null, + run_us bigint not null, + wait_us bigint not null, + primary key (second, queue, kind, outcome), + constraint spool_stats_outcome check (outcome in ('completed', 'retried', 'discarded')) +); + +comment on table spool_queues is 'A queue''s settings every runner obeys: a row a queue, made when a runner first names it.'; +comment on column spool_queues.paused is 'Whether runners claim from it: a pause outlives every runner, until resumed.'; +comment on table spool_runners is 'The runners running: each upserts its row at its heartbeat, deletes it as it stops, and one a lease late is deleted by any other.'; +comment on column spool_runners.queues is 'The queues it runs and how many jobs of each it runs at once: [{"queue": ..., "slots": ...}].'; +comment on table spool_stats is 'What attempts came to, a row a second, queue, kind and outcome, added to as each finishes: what a dashboard charts.'; +comment on column spool_stats.run_us is 'The microseconds the second''s attempts ran, summed.'; +comment on column spool_stats.wait_us is 'The microseconds they waited past their scheduled instant before a runner claimed them, summed.'; +``` + +```sql title="migrations/20261116000001_limit_spool_queues.sql" +-- limit_spool_queues: a queue's limits across every runner -- how many of its jobs +-- run at once, how many attempts begin in a period, and whether both apply to +-- each partition of it -- the attempts begun that a rate counts, and when +-- each partition was last served. + +alter table spool_queues + add column running_limit integer, + add column rate_attempts integer, + add column rate_per_us bigint, + add column per_partition boolean not null default false, + add constraint spool_queues_running_limit check (running_limit >= 1), + add constraint spool_queues_rate check + ((rate_attempts is null) = (rate_per_us is null) + and rate_attempts >= 1 and rate_per_us >= 1); + +alter table spool_jobs add column partition_key text; + +create table spool_starts ( + queue text not null, + partition_key text not null, + at timestamptz not null +); + +create table spool_partitions ( + queue text not null, + partition_key text not null, + claimed_at timestamptz not null, + primary key (queue, partition_key) +); + +create index spool_starts_window on spool_starts (queue, partition_key, at); +create index spool_jobs_running_queue on spool_jobs (queue, partition_key) + where state = 'running'; + +comment on column spool_queues.running_limit is 'How many of its jobs run at once across every runner, or of each partition''s; none, no limit.'; +comment on column spool_queues.rate_attempts is 'How many attempts begin within rate_per_us, across every runner, or of each partition''s; none, no rate.'; +comment on column spool_queues.per_partition is 'Whether its limit and rate hold for each partition of it, its partitions taken in turns.'; +comment on column spool_jobs.partition_key is 'The partition its kind gave it, written at enqueue, so a claim reads a column and never a payload.'; +comment on table spool_partitions is 'When each partition of a queue that has them was last claimed from: the one served longest ago is served next.'; +comment on table spool_starts is 'Attempts begun in a queue with a rate, kept as long as its period: what the rate counts.'; +``` + +```sql title="migrations/20261116000002_create_spool_schedules.sql" +-- create_spool_schedules: recurring jobs, a row a schedule, each advanced past +-- its tick by the transaction that enqueues the tick's job, so a tick is one +-- job however many runners hold the schedule. + +create table spool_schedules ( + name text primary key, + expression text not null, + zone text not null, + kind text not null, + queue text not null, + payload jsonb not null, + priority smallint not null, + max_attempts integer not null, + partition_key text, + next_at timestamptz not null, + last_at timestamptz, + constraint spool_schedules_priority check (priority between 0 and 9), + constraint spool_schedules_attempts check (max_attempts >= 1) +); + +comment on table spool_schedules is 'Recurring jobs: written by every runner that holds the schedule, and advanced once per tick.'; +comment on column spool_schedules.expression is 'The cron expression, five fields, read in zone.'; +comment on column spool_schedules.zone is 'The tz database''s name of the zone the expression is read in.'; +comment on column spool_schedules.next_at is 'The next tick: a runner past it enqueues the latest tick due and moves this past now, in one transaction guarded by its old value.'; +comment on column spool_schedules.last_at is 'The tick last enqueued.'; +``` + +```sql title="migrations/20261116000003_hold_spool_keys.sql" +-- hold_spool_keys: a unique key held for a period from enqueueing, whatever +-- its job's state, and the row kept until the period ends. + +alter table spool_jobs add column unique_until timestamptz; + +create index spool_jobs_held_key on spool_jobs (kind, unique_key, unique_until) + where unique_until is not null; + +comment on column spool_jobs.unique_until is 'Until when its key answers every enqueue of its kind with this job, in any state; its row is kept until then.'; +``` + +```sql title="migrations/20261116000004_create_spool_dependencies.sql" +-- create_spool_dependencies: a job may wait for others, blocked until every one +-- of them completed, and cancelled once one of them cannot. + +alter table spool_jobs drop constraint spool_jobs_state; +alter table spool_jobs add constraint spool_jobs_state check (state in + ('available', 'blocked', 'running', 'completed', 'discarded', 'cancelled')); + +create table spool_dependencies ( + job bigint not null references spool_jobs (id) on delete cascade, + on_job bigint not null, + primary key (job, on_job) +); + +create index spool_dependencies_on on spool_dependencies (on_job); + +comment on table spool_dependencies is 'A job waiting for another: its job blocked until every on_job completed, or is gone, which a completed job of a kind that keeps none is.'; +comment on column spool_dependencies.on_job is 'The job waited for, with no reference, since a completed one may be pruned or deleted before its dependents run.'; +``` + +```sql title="migrations/20261116000005_mark_sensitive_jobs.sql" +-- mark_sensitive_jobs: a job whose kind says its payload is sensitive, which no +-- read of spool's answers, and the indexes an operator's listing reads. + +alter table spool_jobs add column sensitive boolean not null default false; +alter table spool_schedules add column sensitive boolean not null default false; + +create index spool_jobs_listed on spool_jobs (state, id); +create index spool_jobs_blocked on spool_jobs (queue) where state = 'blocked'; + +comment on column spool_jobs.sensitive is 'Whether its kind keeps its payload from every answer of spool''s, as from every log line.'; +``` + +```sql title="migrations/20261116000006_index_spool_finishes.sql" +-- index_spool_finishes: what finding the jobs whose attempts finished in a span +-- reads, a failure's job being scheduled or finished at or after it. + +create index spool_jobs_scheduled on spool_jobs (scheduled_at); +``` diff --git a/agents/pages/guide/testing.md b/agents/pages/guide/testing.md new file mode 100644 index 0000000..ee0ca43 --- /dev/null +++ b/agents/pages/guide/testing.md @@ -0,0 +1,104 @@ +# Testing + +`Runner.drain` runs every job due at `now ()` through the runner's own claim +and finish, one at a time on the caller's fiber, and answers what each +attempt left the job: a test moves its clock and drains, and nothing +sleeps. + +```ocaml title="testing.ml" +(* A test of a handler through the runner's own claim and finish, with a + clock the test moves, so nothing sleeps for a backoff. It needs a + database of its own, made by spool's migrations, since a drain runs every + job due in it. + + dune exec examples/testing.exe *) + +module Pg = Rowtype_postgres + +let database = "postgres://postgres:postgres@localhost:5432/postgres" + +let order = + Wiretype.Object.map Fun.id + |> Wiretype.Object.mem "order" Wiretype.string ~enc:Fun.id + |> Wiretype.Object.finish + +let receipt = Spool.Kind.make ~queue:"mail" "receipt.send" order + +let state_name : Spool.state -> string = function + | Available -> "available" + | Blocked -> "blocked" + | Running -> "running" + | Completed -> "completed" + | Discarded -> "discarded" + | Cancelled -> "cancelled" + +let ok what = function Ok v -> v | Error e -> Alcotest.failf "%s: %s" what e + +let test_a_busy_service_is_tried_again () = + Eio_main.run @@ fun env -> + Eio.Switch.run @@ fun sw -> + let at = ref (Ptime_clock.now ()) in + let now () = !at in + let busy = ref true in + let send_receipt _job _order = + if !busy then ( + busy := false; + Error (Spool.Retry "the mail service is busy")) + else Ok () + in + let conninfo = ok "conninfo" (Pg.Conninfo.of_string database) in + let runner = + Spool.Runner.create ~sw ~net:(Eio.Stdenv.net env) + ~mono_clock:(Eio.Stdenv.mono_clock env) + ~now + ~queues:[ ("mail", 1) ] + [ Spool.handle receipt send_receipt ] + conninfo + |> Result.map_error Spool.Runner.refused_to_string + |> ok "runner" + in + let conn = + Pg.connect ~sw ~net:(Eio.Stdenv.net env) + ~mono_clock:(Eio.Stdenv.mono_clock env) + conninfo + |> Result.map_error Rowtype.error_to_string + |> ok "connect" + in + let (_ : Spool.Id.t) = + Spool.enqueue conn ~now:(now ()) receipt "A-1001" + |> Result.map_error (fun _ -> "the job could not be written") + |> ok "enqueue" + in + let drain () = + Spool.Runner.drain runner |> ok "drain" + |> List.map (fun (_, state) -> state_name state) + in + Alcotest.(check (list string)) "retried" [ "available" ] (drain ()); + Alcotest.(check (list string)) "not before its backoff" [] (drain ()); + at := Option.value (Ptime.add_span !at (Ptime.Span.of_int_s 60)) ~default:!at; + Alcotest.(check (list string)) "then sent" [ "completed" ] (drain ()); + Spool.Runner.stop runner; + Pg.close conn + +let () = + Alcotest.run "receipts" + [ + ( "receipt.send", + [ + Alcotest.test_case "a busy service is tried again" `Quick + test_a_busy_service_is_tried_again; + ] ); + ] +``` + +- The runner is made as a program makes one, with a `now` the test moves, + and never started: `drain` runs the jobs, and no fiber of the runner's + does. +- Each drain answers a job's id and its state once the attempt was + finished: `Available` for one to be retried, `Completed`, `Discarded`. + A job expired before it ran is answered `Discarded` too. +- A drain claims nothing that is not due: a retried job waits its backoff, + 15 s for the first, spread by a tenth either way, until the test moves + its clock past it. +- A drain runs every job due in the database, so each test has a database + of its own, made by spool's migrations. diff --git a/agents/pages/guide/workflows.md b/agents/pages/guide/workflows.md new file mode 100644 index 0000000..b2a798b --- /dev/null +++ b/agents/pages/guide/workflows.md @@ -0,0 +1,41 @@ +# Workflows + +A job may wait for others. `Spool.enqueue_after` writes it `Blocked`, and it +runs, as any job does, once every job it waits for has completed: + +```ocaml +let* rows = Spool.enqueue_many conn ~now import_row lines in +let* _ = Spool.enqueue_after conn ~now ~waits_for:rows summary file in +``` + +That is a batch with a summary, a workflow of one level; a job that waits +for the summary makes it two. There is nothing else to learn: a workflow is +its jobs and what each waits for. + +## When one fails + +A job that ends without completing -- discarded on its last attempt, +cancelled, expired, or deleted before it completed -- cancels every job +that waits on it, however far down, each with a reason naming the job that +ended and how. What waits on a job learns how it ended in the transaction +that records it, so no job is left blocked on one that has ended. + +A job waited for that is gone counts as completed, since a completed job of +a kind that keeps none is deleted, and the rest are pruned after their +retention. One already discarded or cancelled when the job is enqueued +cancels it at once. + +A retried job that waits for others waits again: retry what it waited for +first. + +## No key + +`enqueue_after` takes no unique key. A blocked job is outside the fold of +waiting jobs by key, and once released it would meet the job its key +already names. + +## Looking at one + +`Spool.workflow conn id` answers every job connected to one by waiting, +either way, with each one's `info`, and the edges between them as `(job, +waits_for)` pairs. diff --git a/agents/pages/index.md b/agents/pages/index.md new file mode 100644 index 0000000..47eb6e7 --- /dev/null +++ b/agents/pages/index.md @@ -0,0 +1,87 @@ +# Getting Started + +Durable jobs for modern OCaml, backed by Postgres. + +spool is a durable job queue for OCaml, kept in Postgres. A job is a row +written in the transaction that made the work owed, so a rollback leaves no +job. Runners in several processes claim jobs without waiting on each other, +under leases a heartbeat renews, and a lapsed one is rescued. A handler +retries with backoff, retries after what an upstream said, or discards; a +unique key folds a second request into the job already waiting; and a test +runs every job due at its own clock, never sleeping. + +A queue's limits hold across every runner -- how many run at once, how many +begin in a period, for each customer apart -- and a queue is paused from the +table. A schedule enqueues a job each tick of a cron expression in a named +time zone, once however many runners hold it; a job may wait for others and +run once they have all completed; and `spool-dashboard` watches and steers it +all from a page of your own Spindle server. + +```ocaml title="receipt.ml" +(* An order's receipt: its kind, the order taken with its receipt owed in + one transaction, and a runner that sends it. quick_start.ml runs it. *) + +open Result.Syntax +module Pg = Rowtype_postgres + +let send_receipt order = + Printf.printf "Receipt for order %d sent.\n%!" order; + Ok () + +(* {"order": 42} *) +let order = + Wiretype.Object.map Fun.id + |> Wiretype.Object.mem "order" Wiretype.int ~enc:Fun.id + |> Wiretype.Object.finish + +let receipt = Spool.Kind.make ~queue:"mail" "receipt.send" order + +let insert_order = + Rowtype.find ~params:Rowtype.text ~row:Rowtype.int + "insert into orders (email) values ($1) returning id" + +(* The order and its receipt, in one transaction: a rollback leaves neither. *) +let take_order conn ~now email = + Pg.Transaction.within conn @@ fun conn -> + let* order = Pg.run conn insert_order email in + Spool.enqueue conn ~now ~unique:(string_of_int order) receipt order + +let runner ~sw env conninfo = + Spool.Runner.create ~sw ~net:(Eio.Stdenv.net env) + ~mono_clock:(Eio.Stdenv.mono_clock env) + ~now:Ptime_clock.now + ~queues:[ ("mail", 2) ] + [ Spool.handle receipt (fun _job order -> send_receipt order) ] + conninfo +``` + +## Install + +It needs opam, with a switch of OCaml 5.5 or later, and a Postgres to keep +the jobs in. + +```sh +opam repo add open-opam https://github.com/open-opam/opam-repository.git +opam install spool rowtype-migrate +``` + +`spool` brings the libraries it runs over: +[rowtype](https://hyphatech.github.io/rowtype/) and its Postgres backend, +`rowtype-postgres`, and [wiretype](https://hyphatech.github.io/wiretype/), +which describes a job's payload. `rowtype-migrate` is the command that makes +spool's table, beside your own. The dashboard is a package of its own, +`spool-dashboard`, for an application served by +[Spindle](https://hyphatech.github.io/spindle/): + +```sh +opam install spool-dashboard +``` + +A program names the libraries it uses in its `dune` file: + +```lisp +(libraries spool rowtype-postgres eio_main) +``` + +The [quick start](quick-start.md) runs a whole program, next, and [In a +Spindle application](guide/spindle.md) puts spool in a web server. diff --git a/agents/pages/quick-start.md b/agents/pages/quick-start.md new file mode 100644 index 0000000..b2f02d1 --- /dev/null +++ b/agents/pages/quick-start.md @@ -0,0 +1,181 @@ +# Quick start + +Work that outlives a request, kept where the rest of the application's +state is: a job is a row written in the transaction that made the work +owed, claimed by a runner under a lease, run outside every transaction, +retried with backoff, and finished once in the table however often it was +attempted. It runs over [rowtype](https://hyphatech.github.io/rowtype/)'s +Postgres backend and names no driver. + +This page takes an order and owes it a receipt, in one transaction, then +runs a runner that sends the receipt. It needs spool and `rowtype-migrate` +[installed](index.md#install), and a Postgres. + +## 1. A Postgres + +Any Postgres you can reach will do. One in a container, thrown away when it +stops: + +```sh +docker run --rm -p 5432:5432 -e POSTGRES_PASSWORD=postgres postgres:18-alpine +``` + +## 2. The tables + +spool keeps its jobs in a table of its own, made by its own migrations. The +order is yours, in a migration of your own, a SQL file in `migrations/`: + +```console +$ rowtype-migrate new create_orders +migrations/20261024000000_create_orders.sql +``` + +```sql title="migrations/20261024000000_create_orders.sql" +-- create_orders: the quick start's own table, beside spool's. + +create table orders ( + id bigint generated always as identity primary key, + email text not null +); +``` + +Apply spool's migrations, then yours: + +```sh +rowtype-migrate up --source spool --url postgres://postgres:postgres@localhost:5432/postgres +``` + +## 3. The receipt + +A kind is a job's name, the [wiretype](https://hyphatech.github.io/wiretype/) +description of its payload, and how it is run -- here, in the queue `mail`. +The payload is an object, each member named for what it holds. + +The order and its receipt are written in one transaction, through your own +connection, so a rollback leaves neither; a runner hears of the job when the +transaction commits. A runner claims the jobs of the queues it is given -- +here `mail`, two at a time -- and runs each kind's handler. Its connections +are its own, made from the connection string. + +Put this module in `bin/receipt.ml`: + +```ocaml title="receipt.ml" +(* An order's receipt: its kind, the order taken with its receipt owed in + one transaction, and a runner that sends it. quick_start.ml runs it. *) + +open Result.Syntax +module Pg = Rowtype_postgres + +let send_receipt order = + Printf.printf "Receipt for order %d sent.\n%!" order; + Ok () + +(* {"order": 42} *) +let order = + Wiretype.Object.map Fun.id + |> Wiretype.Object.mem "order" Wiretype.int ~enc:Fun.id + |> Wiretype.Object.finish + +let receipt = Spool.Kind.make ~queue:"mail" "receipt.send" order + +let insert_order = + Rowtype.find ~params:Rowtype.text ~row:Rowtype.int + "insert into orders (email) values ($1) returning id" + +(* The order and its receipt, in one transaction: a rollback leaves neither. *) +let take_order conn ~now email = + Pg.Transaction.within conn @@ fun conn -> + let* order = Pg.run conn insert_order email in + Spool.enqueue conn ~now ~unique:(string_of_int order) receipt order + +let runner ~sw env conninfo = + Spool.Runner.create ~sw ~net:(Eio.Stdenv.net env) + ~mono_clock:(Eio.Stdenv.mono_clock env) + ~now:Ptime_clock.now + ~queues:[ ("mail", 2) ] + [ Spool.handle receipt (fun _job order -> send_receipt order) ] + conninfo +``` + +## 4. The program + +The program takes one order, starts the runner, gives it two seconds to send +the receipt, and stops it. Put it in `bin/main.ml`: + +```ocaml title="quick_start.ml" +(* The quick start: one order taken, and a runner that sends its receipt; + the order, its kind and the runner are receipt.ml. + + docker run --rm -p 5432:5432 -e POSTGRES_PASSWORD=postgres postgres:18-alpine + rowtype-migrate up --source spool --dir examples/migrations --url postgres://postgres:postgres@localhost:5432/postgres + dune exec examples/quick_start.exe *) + +open Result.Syntax +module Pg = Rowtype_postgres + +let database = "postgres://postgres:postgres@localhost:5432/postgres" + +let enqueue_error = function + | #Pg.error as e -> Pg.error_to_string e + | `Unencodable e -> Wiretype.Unwritable.to_string e + | `Bad_priority p -> Printf.sprintf "priority %d is not 0 to 9" p + +let main ~sw env = + let* conninfo = Pg.Conninfo.of_string database in + let* conn = + Pg.connect ~sw ~net:(Eio.Stdenv.net env) + ~mono_clock:(Eio.Stdenv.mono_clock env) + conninfo + |> Result.map_error Rowtype.error_to_string + in + let* _job = + Receipt.take_order conn ~now:(Ptime_clock.now ()) "ada@example.com" + |> Result.map_error enqueue_error + in + let* runner = + Receipt.runner ~sw env conninfo + |> Result.map_error Spool.Runner.refused_to_string + in + Spool.Runner.start runner; + Eio.Time.Mono.sleep_span (Eio.Stdenv.mono_clock env) Mtime.Span.(2 * s); + Spool.Runner.stop runner; + Pg.close conn; + Ok () + +let () = + Eio_main.run @@ fun env -> + Eio.Switch.run @@ fun sw -> + match main ~sw env with + | Ok () -> () + | Error e -> + prerr_endline e; + exit 1 +``` + +Name the libraries it uses in `bin/dune`, with a `dune-project` holding +`(lang dune 3.18)` beside `bin/`: + +```lisp +(executable + (name main) + (libraries spool rowtype rowtype-postgres wiretype eio eio_main ptime.clock.os mtime)) +``` + +```console +$ dune exec ./bin/main.exe +Receipt for order 1 sent. +``` + +Each run takes another order and sends its receipt. + +## Next + +- [The table](guide/table.md): the migrations, and what each column + holds. +- [Kinds](guide/kinds.md) and [Enqueueing](guide/enqueueing.md): + when a job runs, and how often. +- [Handlers](guide/handlers.md) and [The + runner](guide/runner.md): what an attempt answers, and what the + runner does with it. +- [In a Spindle application](guide/spindle.md): a route that owes a + job in its request's transaction, and a runner beside the server. diff --git a/agents/pages/reference.md b/agents/pages/reference.md new file mode 100644 index 0000000..7ea9668 --- /dev/null +++ b/agents/pages/reference.md @@ -0,0 +1,55 @@ +# 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 + +A `dune` file names a library as it is installed (`spool-dashboard`); +OCaml code names it as a module (`Spool_dashboard`). + +| Package | Libraries | What it is | +|---|---|---| +| `spool` | `spool` | The queue: its table's statements, kinds, enqueueing, the runner, schedules, a queue's pause and limits, and an operator's hand; its migrations installed in `share/spool/migrations` | +| `spool-dashboard` | `spool-dashboard` | The dashboard: routes of an application's own Spindle server, its page built in | +| [`rowtype`, `rowtype-postgres`, `rowtype-migrate`](https://hyphatech.github.io/rowtype/) | the same | A statement described once, its Postgres backend, which spool runs over, and the command that applies spool's migrations, released on their own; `spool` installs `rowtype` and `rowtype-postgres` | +| [`wiretype`](https://hyphatech.github.io/wiretype/) | `wiretype` | JSON as descriptions, which a job's payload is, released on its own; installed with `spool` | +| [`spindle`, `spindle-postgres`](https://hyphatech.github.io/spindle/) | the same | The web framework the dashboard's routes are of, and its pool; installed with `spool-dashboard` | + +## spool + +- [`Spool`](https://hyphatech.github.io/spool/reference/spool/Spool/index.html) -- the table, kinds, + enqueueing, an operator's hand, and running: `table`, `statements`, + `enqueue`, `enqueue_many`, `enqueue_after`, `find`, `workflow`, `counts`, + `jobs`, `cancel`, `retry`, `run_again`, `delete` and `handle`. Its + modules: + - [`Spool.Kind`](https://hyphatech.github.io/spool/reference/spool/Spool/Kind/index.html) -- a kind + of job: its name, its payload's description, and how it is run. + - [`Spool.Runner`](https://hyphatech.github.io/spool/reference/spool/Spool/Runner/index.html) -- a + runner of queues: made, started, drained in a test, stopped, and the + list of those running. + - [`Spool.Queue`](https://hyphatech.github.io/spool/reference/spool/Spool/Queue/index.html) -- a + queue's settings every runner obeys: its pause and its limits. + - [`Spool.Schedule`](https://hyphatech.github.io/spool/reference/spool/Spool/Schedule/index.html) -- + a recurring job: its expression and zone, its ticks, and running it now. + - [`Spool.Stats`](https://hyphatech.github.io/spool/reference/spool/Spool/Stats/index.html) -- what + attempts came to, a row a second, queue, kind and outcome. + - [`Spool.Id`](https://hyphatech.github.io/spool/reference/spool/Spool/Id/index.html) -- a job's + handle. + +## spool-dashboard + +- [`Spool_dashboard`](https://hyphatech.github.io/spool/reference/spool-dashboard/Spool_dashboard/index.html) + -- the dashboard's routes, and the actions an operator may be allowed. + +## What it is built on + +- [`Rowtype` and + `Rowtype_postgres`](https://hyphatech.github.io/rowtype/) -- a statement + described once, and running one on Postgres: the connection a job is + enqueued through, its transaction, and the connection string a runner is + given. +- [`Wiretype`](https://hyphatech.github.io/wiretype/) -- JSON as + descriptions: a kind's payload. +- [`Spindle`](https://hyphatech.github.io/spindle/) -- the routes the + dashboard is, and the access an application decides them by. diff --git a/docs/astro.config.mjs b/docs/astro.config.mjs index eadd19a..1d880cc 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"; // spool's documentation site, published to GitHub Pages by @@ -38,6 +39,10 @@ export default defineConfig({ tabs: { "Start here": "rocket", 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 spool 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. links({ errorOnLocalLinks: false, diff --git a/docs/bun.lock b/docs/bun.lock index 1c81f58..6cc1308 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=="], @@ -745,6 +776,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.2.0", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.1.0" } }, "sha512-fpsYs/VVoZxfGY9/j3FQpZmN8wdLJaV1Pt38AaJNZu9uKIHcFU3halCdBveEq1HGKO1OEfJY65w1zvoFV1b3qQ=="], diff --git a/docs/package.json b/docs/package.json index 3c22fec..93caf3e 100644 --- a/docs/package.json +++ b/docs/package.json @@ -6,6 +6,7 @@ "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3", "starlight-links-validator": "^0.27.0", - "starlight-theme-hypha": "github:hyphatech/starlight-theme-hypha#v0.6.3" + "starlight-hypha-agents": "github:hyphatech/starlight-hypha-agents#v0.2.0", + "starlight-theme-hypha": "github:hyphatech/starlight-theme-hypha#v0.8.0" } } diff --git a/dune b/dune index 0bcef56..5c160e1 100644 --- a/dune +++ b/dune @@ -16,3 +16,13 @@ (files (glob_files (migrations/*.sql with_prefix migrations)))) + +; The documentation for a user's agent, agents/, written from the site's pages +; by `make docs`: spool installs it whole, so $(opam var spool:doc) holds +; llms.txt and each page. + +(install + (section doc) + (package spool) + (source_trees + (agents as .)))