Skip to content

feat(server): serve on HttpApi and HttpRouter; delete config and db - #88

Merged
allisonmahmood merged 3 commits into
mainfrom
feat/server-httpapi
Aug 29, 2026
Merged

allisonmahmood merged 3 commits into
mainfrom
feat/server-httpapi

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Problem

With auth and patches ported, Fastify was only a shell: a ManagedRuntime seam that re-bridged every request, a hand-rolled packages/config, and a Promise migration seam in packages/db. Pages, headers and the request guard still lived in the app, and the Effect lint rules the port map promised had not landed.

Solution

  • packages/serving owns the serving guarantees and their headers, the page routes (/, /healthz, /d/:patchId, /d/:patchId/v/:n, the HTML 404) as HttpRouter routes reading through patches, and the trusted-proxy Schema that resolves the client address. Tests run over NodeHttpServer.layerTest, with TestClock driving the visit top-up and expiry.
  • apps/server is wiring: one Server.layer — services over a migrated database, HttpApiBuilder.layer(PatchyApi) with both group layers behind auth's bearer middleware, the pages, one global middleware whose order is written down (proxy walk → serving headers → API guard), the expiry sweep forked in the scope — and start.ts launching it under NodeRuntime.runMain. The API guard keeps the observable contract for what the router never sees: every /api/* request but the mint spends one protected-API attempt and needs a token before a 400/404/414. The upload handler is raw, so scope and the per-token upload limit are spent before the body is read and the wire's own refusals (413, field-specific 400s) stay.
  • Deleted packages/config, packages/db and Fastify. The dev runner, the vitest template and the packed-CLI e2e migrate through sql directly; the e2e starts its own embedded Postgres and reads its assertions from SQL (it was still expecting the JSON driver, which is why cli-smoke fails on the base).
  • Lint: three local ESLint rules under eslint/ (namespace imports for Effect and service modules, no manual runtimes in tests, no Schema compiles in function bodies), proved by RuleTester; every language-service rule is an error repo-wide, with packages/cli held at warning until feat(cli): patchy on effect/unstable/cli with the agent contract #78.
  • Docs: packages/serving/CONTEXT.md takes the serving-guarantee terms, apps/server/CONTEXT.md shrinks to wiring and the guard, map/labels/README follow.

Deviations from #77, named:

  • The pre-routing classification lives in the server's API guard, not serving's raw middleware: answering it after the 401 needs auth and limits, which serving may not import. The three middleware functions are composed into one HttpRouter.middleware(…, { global: true }) at the server so their order is explicit.
  • Effect's HttpMiddleware.xForwardedHeaders trusts the leftmost address and requires X-Forwarded-Host; the contract is rightmost-untrusted through trusted networks, so serving applies its own walk.
  • Unmatched upload-like targets (/api/uploads/, /api%2Fuploads) are no longer scope-checked or upload-limited: the router normalises the former onto the real route and the latter is nobody's route, so there is no body to protect. An encoded slash is one segment, as it is for the router.
  • disable and createToken decode through HttpApi, so a malformed or absent body there is Effect's empty 400 (the derived client always sends one); only the upload keeps hand-written body refusals.
  • Authorization.identify is factored out of auth's middleware so the guard shares one header-to-identity path, and the 401 is answered as a response rather than failed as a value — an endpoint's error union was encoding it as a 400.
  • No public-url.ts existed to move. The Dockerfile is updated for the package list but could not be built here (no Docker socket); the docker CI job is the check.

Stacked on #87.

Closes #77

Built by Claude Fable 5 via Claude Code.

@github-actions github-actions Bot added area:server Touches the server area area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:docs Touches the docs area size:l 501-1,000 changed lines labels Aug 29, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Code review (PR 88 / #77)

Two-axis review of feat/server-httpapi (d5d3fcf) against feat/patches-package (b73a0da), plus three extra axes Allison asked for: intent vs #77, method, and YAGNI. Six read-only agents, one each.

The cut is the right one. Fastify, config, and db are actually gone. Serving owns pages and the proxy schema; the server is wiring plus one guard. The named deviations mostly correct the ticket rather than dodge it. The problems that remain are a second routing table in the guard, a couple of client-visible 400/404 shifts, a mangled comment this PR introduced, and draft wording that moved with render.ts untouched.


Standards

packages/patches/src/PatchesApi.ts:1–7 — hard. [effect-service-conventions, Change discipline: preserve useful comments]. The file header is mangled (& replaced `Patches`, `Limits` and `Analytics`: the upload, the moderation reads,) and still says the server serves the group “through its runtime seam until serving mounts the whole API.” Restore the sentence; drop the seam claim — apps/server mounts HttpApiBuilder.layer(PatchyApi).

packages/api/src/respond.ts:72–78 — hard. [Errors and predicates: wrapping a real failure must keep it as cause]. request.text and JSON parse failures become new MalformedBody({}) with no cause. Add optional cause (same error is also a pure decode miss) and pass the underlying failure at those two sites. Message stays structural.

apps/server/src/ApiGuard.ts:87–97 — judgement, possible Duplicated Code. Same rateLimited helper as packages/auth/src/AuthApi.ts:33–43 and packages/patches/src/PatchesApi.ts:60–70. Extract next to refuse if a third copy is too many; not required by the spec.

No UI consistency findings. render.ts / render.test.ts moved unchanged; first-party pages still use htmlPage; renderPatchWrapper stays the sandboxed exception (iframe sandbox, srcdoc via escapeAttribute, no script/chrome).

No Effect service findings on the new serving/server shape: no Context.Service invented for one consumer, dependencies come from the environment, NodeRuntime.runMain stays at start.ts, namespace barrels (export * as Pages) are the documented form.


Spec

(a) Missing / partial

  • Classification not in serving. Ticket: “the pre-routing target classification (400/404/414) kept as observable contract inside the raw middleware” of packages/serving. It lives in apps/server ApiGuard (plus /api/* catch-all). Named deviation is sound: serving must not import auth (CONTEXT-MAP). Observable 400/414/404 after a token still hold; tokenless still 401.

  • Guarantees middleware not serving-owned. Ticket: guarantees “as one raw HttpRouter.middleware(…, { global: true }).” servingHeaders is only an HttpMiddleware; the single { global: true } is composed at the server with proxy + guard. Headers (including refusals) still apply. Observable OK.

  • xForwardedHeaders unused. Ticket: trusted-proxy Schema “feeding HttpMiddleware.xForwardedHeaders.” Custom right-to-left walk instead. Matches §6 (“has no allow-list”) and the existing attribution contract. Observable OK.

  • No public-url.ts. Named; none existed. Home page reads PatchesConfig.publicBaseUrl. Fine.

  • draft → patch on moved HTML. Port rule: “Rename what you touch.” render.ts still uses draft-frame, “Patchy draft”, “Missing draft”, <!-- draft:… -->. The file moved with zero content edits.

  • HttpApiTest through real middleware. Ticket: “HttpApiTest for the API through the real middleware.” Group tests still stub Authorization; the real bearer+guard path is only NodeHttpServer.layerTest. Socket coverage is stronger; the named harness is not used on the server.

  • Lint repo-wide vs CLI. Ticket: every language-service warning → error “repo-wide.” CLI whole-file Node rules stay warnings until feat(cli): patchy on effect/unstable/cli with the agent contract #78. Matches parent §10, not the ticket’s shorthand.

(b) Scope creep

Authorization.identify / 401-as-response is supporting work for the guard, not extra product. Dockerfile / CONTEXT-MAP / e2e Postgres updates are implied by delete-config/db and “packed-CLI e2e passes.” No material unrelated feature.

(c) Implemented but wrong (vs named contract)

  • Empty 400 on disable / createToken. Ticket/§1: keep the HTTP API’s observable refusals ({ ok: false, error }). Named: HttpApi decode yields Effect’s empty 400 (derived client always sends a body). That is a real wire change for raw HTTP; it does not keep the refusal body contract on those routes. Upload’s hand-written 400/413 still do.

  • /api%2Fuploads. Named: classified public → HTML 404, no protected-API debit/401. Router-faithful, but it is a status/content-type change vs an /api/* probe. /api/uploads/ normalizing onto the real upload remains scoped/limited.

ADR Postgres only already landed on the patches PR (ADR-0003); not missing here.


Intent vs #77

#77’s intent is the last hosting-side port: Fastify becomes a shell and should disappear; serving becomes the page capability later runtimes grow on; apps/server shrinks to the process that wires packages and listens; readers keep the page headers; agents keep the API’s statuses, auth-before-body, and “no mapping /api without a token.”

Honored. Fastify is gone from the lockfile. @patchy/config is gone. packages/db is not a package. Serving reads through Content / Patches, never ContentStore, never auth. Server is HttpApiBuilder.layer(PatchyApi) + both group layers + Pages + one global middleware (proxy → headers → guard) + Effect.repeat(sweep, Schedule.spaced("1 hour")) forked in scope. start.ts is NodeRuntime.runMain. 401 is { ok: false, error } with no _tag. Three local ESLint rules landed. CONTEXT split matches the map.

Bent, still the intent:

  1. Classification in ApiGuard, not serving — correct. A post-401 answer needs auth and limits; putting that in serving would break the package cut. Hosting now owns “cannot map the API,” which is what apps/server/CONTEXT.md says.
  2. Custom proxy walk — correct. Effect trusts leftmost and wants X-Forwarded-Host; the contract is rightmost-untrusted through an allow-list.
  3. Authorization.identify shared; 401 answered as a response — internal, and it stops the error union encoding 401 as 400.
  4. No public-url.ts — inlined next to the one consumer (PatchesApi.publicUrl).

Would a later agent be unsurprised? Yes, if they read CONTEXT-MAP.md and both CONTEXT files. The surprises are the ones the PR named: %2F as a public HTML 404, and empty-body 400s on HttpApi payloads.


Method

The cut is the smallest honest model. Serving should not own /api/* 400/404/414, and Effect HTTP middleware is HttpApp => HttpApp — writing the order down in one global (trustedProxies(servingHeaders(guard(app)))) is the framework’s shape, not a fight with it. Layer.mergeAll of three global layers would hide order in Set insertion.

Upload staying handleRaw is the right seam: scope and the per-token limit must run before a document is read. Do not “clean this up” onto .handle() — that would decode the payload first. disable / createToken are small JSON and belong on HttpApi.

Authorization.identify is the right factoring. refuse() returning a response, rather than failing, is now the API’s real error architecture because untagged { ok, error } structs collide in HttpApi’s error channel (BadRequest first → 401 becomes 400). That is a real Effect HTTP constraint, not taste. The next agent cannot “just fail with the schema.”

The wrong shape: classify plus PATCH_POST_SUFFIXES is a handwritten duplicate of the HttpApi routing table living in the wiring package.

const PATCH_POST_SUFFIXES = new Set(["disable", "pin", "unpin"]);

Adding POST /api/patches/:id/foo without editing the Set turns a 414 into a 404. That table belongs next to the routes (packages/api), with the server only composing the guard. The catch-all /api/* is the honest 404; the classifier is Fastify residue kept for status fidelity.

Serving does not install its own guarantees. Pages.layer is routes only; servingHeaders is applied by the server. Pages.test.ts has to re-attach them. A future agent mounting pages without Server.layer drops nosniff / no-store.

Tests. Split the way the spec asked: NodeHttpServer.layerTest for what a socket sees, HttpApiTest.groups for handlers (already in auth/patches), TestClock for visit top-up, a thin boot test for wiring. The 3528-line app.test.ts became focused package tests plus ~230 lines of guard tests. Dropped socket cases that encoded the old Fastify slash-normalization and %2F policy — those are the named deviations, but they are no longer proven as status+body on a socket (only as classify unit tests).


YAGNI

Verdict: mixed. Wiring and serving are the smallest model the spec asked for. The two long files are Fastify’s request-target classifier and a Schema-dressed CIDR parser, not new product.

Keep. Server.ts is one layer. start.ts only listens. serving-headers.ts is constants plus one middleware. Pages.ts is four routes, catch-all last; the visit comment is a real constraint (best-effort, cache undercount). Serving grew no Context.Service. Mint stays public; matched routes are not double-debited.

Cut or shrink (judgement, not “the spec still holds if you drop 414”):

  • TrustedProxies.ts Schema.Class Range + decodeTo / forbidden encode around parse(). This is never on the wire. Config.schema of a string that parse refuses is enough; the Class is ceremony.
  • Transitional IPv6 (::192.0.2.10) is unused in XFF. Dual-stack ::ffff: unwrap and the mapped-alias blanket refuse are real (the boot test records mapped 127.0.0.1); keep those.
  • Absolute-form rawPath and hasLexicalApiPrefix (%61pi, HtTp://host) are the classifier proving it can see spellings Node will not send on a normal origin-form request. Tokenless /%61pi/% → 401 vs /public/% HTML 404 is the leak the guard exists to stop, so some of this is load-bearing. Do not delete the lexical /api prefix check; do ask whether absolute-form needs to live here.

Do not collapse 414 vs 404. YAGNI wants a single overlong-param 414. The ticket asked to keep the 400/404/414 matrix as observable contract. Authenticated 414-vs-404 mapping is Fastify leftover and specified. If it shrinks, shrink the implementation (one table next to the routes), not the statuses.


Summary

  • Standards: 2 hard findings, 1 judgement. Worst: the mangled PatchesApi header this PR introduced (and the stale “runtime seam / serving mounts the API” claim next to it).
  • Spec: 7 missing/partial (most are named, justified deviations), 0 scope creep, 2 implemented-but-wrong. Worst: empty 400 on disable / createToken vs the { ok: false, error } refusal contract.
  • Intent: honored. The bends are the ones the PR named, and they still serve the hosting/serving cut.
  • Method: right seam, wrong second router (PATCH_POST_SUFFIXES / classify).
  • YAGNI: the server and pages are beautiful; TrustedProxies’s Schema Class and some of the classifier’s HTTP-spellings theatre are not.

I would merge after restoring the PatchesApi comment and deciding, in writing on this PR, whether empty HttpApi 400s and %2F as a public HTML 404 are accepted wire changes. The suffix set can wait for a follow-up if you do not want to grow this PR.

Reviewed by Grok 4.6 via Grok.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Thanks for the review. Follow-ups landed in 68ec55b; lint, typecheck, format, the suite (220) and the packed-CLI e2e are green on it.

Fixed

  • PatchesApi.ts header restored; the stale runtime-seam sentence is gone.
  • MalformedBody keeps the read/parse failure as cause (optional: a wrong-shape decode has none).
  • rateLimited and malformedBody live in api next to refuse; the three copies are gone.
  • Empty HttpApi 400s: createToken and disable are raw like upload, so a malformed body is { ok: false, error: "Malformed request body." } and an absent one is {} (a tokenless-body POST /api/tokens issues defaults, a bare disable disables). Socket-tested.
  • /api%2Fuploads reads as a probe of the API again: 401 without a token, { ok: false, error: "Not found." } with one. Socket-tested, along with /api/uploads/ and /api//uploads landing on the real route.
  • The guard's second routing table is gone: the 414-vs-404 shapes are read off PatchyApi's endpoints at load, so a new patch route answers 414 with no edit here (and PUT …/disable is now an honest 404).
  • TrustedProxies: plain parse behind Config.mapOrFail; no Schema.Class, no decodeTo. The mapped-IPv4 unwrap and the blanket/alias refusals stay.
  • render.ts says patch, not draft (copy, patch-frame, the <!-- patch:… --> marker); the e2e and the ui-consistency spec follow.

Left as is, on purpose

Ready to merge from my side once CI agrees.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Follow-up in 551b732: cli-smoke was failing on the lifecycle probes because importing embedded-postgres at the top of the e2e installs async-exit-hook's process-exiting signal handlers in every harness process, pre-empting the harness's own cleanup (a probe child left its temp root behind). The import is now lazy, inside startPostgres, and the handlers it adds are removed; all platform/lifecycle/signal probes and the full e2e pass locally with no temp roots left.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

CI on 551b732: cli-smoke, test (22), test (24), lint, dependency-review and label pass. docker still fails, as it does on the base: the image now builds, but scripts/verify-server-image.sh verifies the JSON-driver contract (PATCHY_DB_FILE=/data/patchy-db.json, reading /data/patchy-db.json after an upload, no Postgres). Rewriting that verifier to run the image against a Postgres is the self-hosting/Docker clean-up #87 already deferred to #79, so I have left it there rather than grow this PR. Everything else is ready to merge.

Base automatically changed from feat/patches-package to main August 29, 2026 23:22
Fastify was a shell around the ported capability packages: a runtime seam,
a hand-rolled config package and a Promise migration seam. The server now
runs on Effect's HttpApi and HttpRouter, and the two pre-port packages go.

packages/serving owns the serving guarantees and their headers, the page
routes (home, health, the patch at its latest and version URLs, the HTML
404) reading through patches, and the trusted-proxy schema that resolves
the client address (Effect's xForwardedHeaders takes the leftmost address
and has no allow-list, so the rightmost-untrusted walk lives here).

apps/server is wiring: one Server.layer with the services over a migrated
database, HttpApiBuilder.layer(PatchyApi) with both group layers behind
auth's bearer middleware, the pages, one global middleware (proxy walk,
serving headers, API guard) whose order is written down, the expiry sweep
forked in the scope, and start.ts launching it under NodeRuntime.runMain.
The API guard keeps the observable contract for what the router never
sees: every /api/* request but the mint spends one protected-API attempt
and needs a token before a 400/404/414. Auth-before-body holds on every
matched route through the bearer middleware; the upload handler is raw so
scope and the per-token upload limit are spent before the body is read,
with the wire's own refusals (413, field-specific 400s).

Also: Authorization.identify is the one header-to-identity path, shared by
the middleware and the guard; the 401 is answered as a response so an error
union cannot encode it as a 400; readBody/decodeBody in api; the packed-CLI
e2e starts its own embedded Postgres and reads its assertions from SQL; the
dev runner and the vitest template migrate through sql directly; docs and
labels follow the packages.

Closes #77
… an error

Three rules the review spec asked for, written locally under eslint/ and
proved by RuleTester: namespace imports for Effect and service modules, no
manual runtimes in tests, no Schema compiles inside function bodies. The
language-service whole-file rules are errors repo-wide now that the server
has ported; packages/cli keeps them at warning until #78, and the
per-package overrides that duplicated the base list are gone.
The patches API header this PR mangled is restored. Every payload route
answers a malformed body as { ok: false, error } and treats an absent one as
{}: createToken and disable are raw like upload. MalformedBody keeps the read
or parse failure as cause; rateLimited and malformedBody live in api next to
refuse. The guard reads the patch routes off PatchyApi instead of a second
table, and /api%2Fuploads is a 404 after the token rather than a public HTML
404. TrustedProxies is a plain parse behind Config.mapOrFail, no Schema class.
The moved page copy says patch, not draft, and the socket tests cover the
slash spellings, the encoded slash and the body answers.
@allisonmahmood
allisonmahmood merged commit fb44479 into main Aug 29, 2026
6 checks passed
@allisonmahmood
allisonmahmood deleted the feat/server-httpapi branch August 29, 2026 23:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:docs Touches the docs area area:server Touches the server area size:l 501-1,000 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(server): serve on HttpApi and HttpRouter; delete config and db

1 participant