@dokebi/web 0.4.2 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/AI.md +250 -39
  2. package/README.md +31 -10
  3. package/dist/app-routes.d.ts +20 -0
  4. package/dist/app-routes.js +137 -0
  5. package/dist/before-hijack.d.ts +24 -0
  6. package/dist/before-hijack.js +73 -0
  7. package/dist/body.d.ts +14 -0
  8. package/dist/body.js +30 -0
  9. package/dist/cluster-ready.d.ts +67 -0
  10. package/dist/cluster-ready.js +123 -0
  11. package/dist/compilers.d.ts +16 -0
  12. package/dist/compilers.js +25 -0
  13. package/dist/compression.d.ts +40 -0
  14. package/dist/compression.js +435 -0
  15. package/dist/connections.d.ts +44 -0
  16. package/dist/connections.js +282 -0
  17. package/dist/define-errors.d.ts +76 -0
  18. package/dist/define-errors.js +161 -0
  19. package/dist/describe.d.ts +37 -0
  20. package/dist/describe.js +96 -0
  21. package/dist/errors.d.ts +1 -1
  22. package/dist/errors.js +24 -3
  23. package/dist/forms.d.ts +23 -7
  24. package/dist/forms.js +53 -13
  25. package/dist/index.d.ts +134 -4
  26. package/dist/index.js +1552 -91
  27. package/dist/options.d.ts +56 -0
  28. package/dist/options.js +320 -1
  29. package/dist/points.d.ts +159 -0
  30. package/dist/points.js +162 -1
  31. package/dist/responses.d.ts +31 -6
  32. package/dist/responses.js +68 -6
  33. package/dist/route-config.d.ts +38 -0
  34. package/dist/route-config.js +222 -0
  35. package/dist/route-hooks.d.ts +75 -0
  36. package/dist/route-hooks.js +118 -0
  37. package/dist/route-table.d.ts +55 -0
  38. package/dist/route-table.js +142 -0
  39. package/dist/seal.d.ts +49 -1
  40. package/dist/seal.js +259 -24
  41. package/dist/security-headers.d.ts +121 -0
  42. package/dist/security-headers.js +298 -0
  43. package/dist/transient-log.d.ts +42 -0
  44. package/dist/transient-log.js +95 -0
  45. package/options.schema.json +488 -1
  46. package/package.json +22 -9
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
- # @dokebi/web 0.4.2
1
+ # @dokebi/web 0.4.3
2
2
 
3
- An optional package for Node >=24.0.0 and core ^0.4.0 (public on npm). It owns an HTTP server built on Fastify 5.12.7; DBs, routers, controllers and views are not required.
3
+ An optional package for Node >=24.0.0 and core ^0.4.2 (public on npm). It owns an HTTP server built on Fastify 5.12.7; DBs, routers, controllers and views are not required.
4
4
 
5
5
  ## Public contract
6
6
 
@@ -23,6 +23,13 @@ app.register(web);
23
23
  - `register(plugin, options)`: passes a Fastify async or callback plugin and its options (`{}` when none). Native plugins keep their scope, decorators, schemas and hooks.
24
24
  - `address`: the real address after listen, undefined before. In a node:cluster worker it is set only after core `ready` (D-0034); other plugins read it in `ready`, not `start`. After shutdown the last address remains, so do not take it as a sign of availability.
25
25
  - `track(() => work)`: puts explicit work whose lifetime differs from the HTTP response into drain and returns a Promise. The caller handles its failure and stops accepting new work.
26
+ - `routeConfig({ key, plugin, check })` (setup only, [D-0076](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0076-auth-and-csrf.md) §5): declares a route `config` key another plugin reads (`auth`, `csrf`). Every route's value is checked at start, and near-miss keys (`csfr`) are reported, so a typo fails the start (`INVALID_ROUTE_CONFIG`) instead of leaving a route unprotected. An optional `routes(list)` callback then receives every route that sets the key, so the plugin can report them (@dokebi/csrf logs its exempt routes).
27
+ - `routeHook({ plugin, route })` (setup only, D-0076 §3.8): asks once per route (earlier routes too) whether to add preValidation/onResponse hooks for that route alone and config values under symbol keys; routes it leaves alone cost nothing per request. dokebi-auth uses it to protect only the routes that need it.
28
+ - Route ids (0.4.3, [D-0077](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0077-app-self-description.md)): `config: { id: 'API-12' }` names a route (1 to 64 letters, digits, `.`, `_` or `-`, starting with a letter). A wrong id fails the start with `INVALID_ROUTE_CONFIG`, the same id on two routes of one app with `DUPLICATE_ROUTE_ID`. The handler reads `request.routeOptions.config.id`.
29
+ - `routes()` (0.4.3, D-0077): every route added so far as a frozen list `[{ method, url, id?, constraints, configKeys }]` (the HEAD twin of a GET left out), complete once the server is ready. Other plugins and tools read the app's routes from it.
30
+ - Files from a folder (update feeds, installers) are [@dokebi/static](https://git.nyx-zone.com/dokebi/framework/-/blob/main/plugins/dokebi-static/README.md) (D-0147), not an option of web.
31
+ - `defineErrors({ CODE: { status, message, hint? } })` (0.4.3, D-0077): the app's error codes in one place (`src/shared/errors.ts`); `errors.CODE({ data })` makes the `DokebiError` web answers as `{ error, message, hint, data }`, and `errorCatalog(module)` reads the frozen list back (AI.md §6).
32
+ - `@dokebi/web/points` `viewData` (`dokebi-web:view-data`): a plugin contributes `{ key, value(request) }` and the value appears on every rendered page — the EJS data of @dokebi/app apps and the shared props of template-inertia. Details in AI.md §2.
26
33
 
27
34
  web becomes ready and listens in its start, after every Dokebi setup. In a `node:cluster` worker it listens in the core `ready` hook instead ([D-0034](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0034-ready-before-traffic.md)): the primary hands connections to a worker as soon as it listens, so only workers whose whole app is ready should take them. After that, `route` and `register` are FROZEN. Inside a Fastify registration function, register routes on the scope you were given. Adding plugins while running is not supported.
28
35
 
@@ -40,25 +47,33 @@ options:
40
47
  ready: /health/ready
41
48
  ```
42
49
 
43
- The defaults are host 127.0.0.1, port 0 (an ephemeral port), maxBodyBytes 1 MiB and requestTimeoutMs 30 seconds. Allowed are port 0..65535, maxBodyBytes 1..64 MiB and requestTimeoutMs 1..2147483647 ms. `requestTimeoutMs` limits receiving a request; it is not a limit on running the work and does not cancel DB calls. Before 0.4.0 the keys were `bodyLimit` and `requestTimeout`; those names are still accepted with an `OPTION_DEPRECATED` warning, and setting old and new together is an error ([D-0071](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0071-option-vocabulary.md)). Fastify construction options such as HTTPS, HTTP/2 and `serverFactory` go through the extension hook `fastifyOptions` (AI.md §8).
50
+ The defaults are host 127.0.0.1, port 0 (an ephemeral port), maxBodyBytes 1 MiB and requestTimeoutMs 30 seconds. Allowed are port 0..65535, maxBodyBytes 1..64 MiB and requestTimeoutMs 1..2147483647 ms. `requestTimeoutMs` limits receiving a request (a body that has not arrived that long after its headers gets 408 `REQUEST_TIMEOUT`; an upload route sets its own `config.requestTimeoutMs`); it is not a limit on running the work and does not cancel DB calls. Before 0.4.0 the keys were `bodyLimit` and `requestTimeout`; those names are still accepted with an `OPTION_DEPRECATED` warning, and setting old and new together is an error ([D-0071](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0071-option-vocabulary.md)). Fastify construction options such as HTTPS, HTTP/2 and `serverFactory` go through the extension hook `fastifyOptions` (AI.md §8).
44
51
 
45
- `healthRoutes` defaults to `{ live: '/health/live', ready: '/health/ready' }`. Keys missing from the object use the default path. Paths start with `/`, contain no `?`, `#` or spaces, and live and ready must differ. `false` registers neither route (when an external health server is used). The options are one `defineOptions` declaration in `src/options.ts`, which is the parser, and the build writes `options.schema.json` from it (D-0063 §3). Invalid options fail in the factory with `CoreError('INVALID_PLUGIN_OPTIONS')` (cause: core `INVALID_OPTIONS`, with paths in `details.issues`).
52
+ `healthRoutes` defaults to `{ live: '/health/live', ready: '/health/ready' }`. Keys missing from the object use the default path. Paths start with `/`, contain no `?`, `#` or spaces, and live and ready must differ. `false` registers neither route (when an external health server is used). The health routes have the route ids `web.healthLive` and `web.healthReady`; `routeIds: { healthLive, healthReady }` renames them. Every route a plugin adds has such an id (`mcp.endpoint`, `oauth.token`, …, [D-0142](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0142-plugin-route-ids.md), AI.md §2.2). The options are one `defineOptions` declaration in `src/options.ts`, which is the parser, and the build writes `options.schema.json` from it (D-0063 §3). Invalid options fail in the factory with `CoreError('INVALID_PLUGIN_OPTIONS')` (cause: core `INVALID_OPTIONS`, with paths in `details.issues`).
46
53
 
47
- Other options: `trustProxy` (below), `sealDriftMs` and `sealExclude` (seal hosts), `formBody` and `formMaxFields` (HTML form bodies, off by default), `developmentErrors` (error details outside production). The [AI guide](AI.md) has the full table.
54
+ Other options: `trustProxy` (below), `sealDriftMs` and `sealExclude` (seal hosts), `formBody` and `formMaxFields` (HTML form bodies, off by default), `developmentErrors` (error details outside production), `transientLogWindowMs`, `transientLogMaxKeys` and `transientLogLevel` (the log of retryable 503s under a burst: the first of each code and route per window in full, the rest counted into one `WEB_TRANSIENT_REPEATED` line, D-0113). The [AI guide](AI.md) has the full table.
55
+
56
+ **Response compression** (0.4.3, [D-0125](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0125-response-compression.md)) is on by default: text, JSON (Inertia visits included), JavaScript, CSS, SVG and XML bodies of at least `compression.thresholdBytes` (1024) go out as `br` (quality 4) or `gzip` (level 6), whichever the client's `Accept-Encoding` prefers, with `Vary: Accept-Encoding`. Measured: a 146 KB Inertia page of i18n-like English text leaves as 48 KB (br 4, about 1.6 ms of thread-pool CPU). 206, 304, SSE, sealed bodies, images, archives, fonts, `Cache-Control: no-transform` and bodies that already have a `Content-Encoding` are never compressed; HEAD gets the headers only; streams are compressed chunk by chunk. The zlib work runs on the thread pool, and while draining or with `compression.maxPending` (64) compressions under way answers go out uncompressed. A route opts out with `config: { compress: false }`, one response with `skipCompression(reply)` (pages that show a secret next to reflected input: BREACH, AI.md §7). Set `compression.enabled: false` when a front proxy compresses. The options and the rules are in AI.md §1.
57
+
58
+ **Security headers** (0.4.3, [D-0149](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0149-security-headers.md)) are on by default: `X-Content-Type-Options: nosniff` on every answer, `Strict-Transport-Security` on HTTPS answers only (TLS, or `X-Forwarded-Proto` from `trustProxy`), and on HTML documents a Content-Security-Policy (`default-src 'self'`, `object-src 'none'`, `frame-ancestors 'self'`, inline scripts and styles allowed, images from https), `X-Frame-Options: SAMEORIGIN`, `Referrer-Policy: strict-origin-when-cross-origin` and `Cross-Origin-Resource-Policy: same-site` (over HTTPS also `Cross-Origin-Opener-Policy`). A header a route or plugin already set is kept (storage and image downloads, static files, the mail dev inbox, the OAuth consent page); plugins add CSP sources with `web.contentSecurityPolicy` (seal adds `'wasm-unsafe-eval'`, template-inertia the Vite dev socket). Change them under `securityHeaders` in dokebi.yaml, per route with `config: { securityHeaders: { … } }`, or turn them off for a route with `config: { securityHeaders: false }`. Measured: 0.99 of Fastify on hello JSON (@fastify/helmet: 0.71).
59
+
60
+ **Overload protection** (0.4.3, [D-0150](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0150-overload-protection.md)) is on by default through @fastify/under-pressure: while the mean event loop delay of the last one-second sample is above `overload.maxEventLoopDelayMs` (200), requests get 503 `OVERLOADED` with `Retry-After` (2 s) before any handler runs; health routes and routes with `config: { overload: false }` are served. Event loop utilization, heap and RSS limits are off until set. The first refusal of each route per window is logged (D-0113). Details in AI.md §2.5.
61
+
62
+ **CORS** is [@dokebi/cors](https://git.nyx-zone.com/dokebi/framework/-/blob/main/plugins/dokebi-cors/README.md) (`npx dokebi add @dokebi/cors`); do not register @fastify/cors yourself.
48
63
 
49
64
  ## Start, shutdown and ownership
50
65
 
51
- Until the whole Application has started and the optional health is ready, business requests get 503 with the body `{ error: 'SERVICE_UNAVAILABLE', reason }`, where reason is one of `DRAINING`, `STARTING` and `NOT_READY`. A browser page gets the same as a small HTML page (D-0074). The same reason goes to the debug log `HTTP request refused`. The health routes (default `/health/live`, `/health/ready`) are reserved paths and answer 200/503. Health is per app, not an aggregate over the parent cluster.
66
+ Until the whole Application has started and the optional health is ready, business requests get 503 with the body `{ error: 'SERVICE_UNAVAILABLE', reason }`, where reason is one of `DRAINING`, `STARTING` and `NOT_READY`. A browser page gets the same as a small HTML page (D-0074). The same reason goes to the debug log `HTTP request refused`. The health routes (default `/health/live`, `/health/ready`) are reserved paths and answer 200/503. In a `@dokebi/cluster` worker the ready route answers for every worker of the cluster: 200 only when each is ready, with the slots that are and are not in `workers` ([D-0164](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0164-cluster-wide-readiness.md)); request refusals stay per worker.
52
67
 
53
- In a **node:cluster worker** (D-0036), drain first closes the listen socket so the primary sends new connections to other workers. Requests arriving on already open keep-alive connections are served instead of refused and the connection is then closed with `Connection: close`. The worker stays up at least 100 ms after closing listen so connections the primary was handing over are not dropped. A request sent on an idle keep-alive connection at the moment it closes can get `ECONNRESET`. This is an inherent HTTP race, so non-browser clients retry an idempotent request on a reused socket once (as the Node docs recommend). A single process keeps listening and answers 503, as below (the load balancer takes it out through health).
68
+ In a **node:cluster worker** (D-0036), drain first closes the listen socket so the primary sends new connections to other workers, and tells HTTP/2 sessions GOAWAY. Open HTTP/1 keep-alive connections stay open up to `drainIdleMs` (2 s): a request arriving on one is served and answered with `Connection: close`, so the client's next request goes to another worker instead of being lost to a closed socket; the wait ends as soon as no connection is left. Then the connections still idle are closed once, and a response still under way closes its own connection when it ends ([D-0107](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0107-stream-and-render-bounds.md) §1). The worker stays up at least 100 ms after closing listen so connections the primary was handing over are not dropped. Only a client that stays idle longer than `drainIdleMs` and sends at the very moment its connection closes can still get `ECONNRESET` (inherent to HTTP/1). A single process keeps listening and answers 503, as below (the load balancer takes it out through health).
54
69
 
55
- In a single process, drain refuses new requests with 503 and then waits for responses, handler Promises, registered request lifecycle hooks and track work. When the core drain deadline (`shutdown.drainTimeoutMs`, default 20 seconds) passes or `stop({ force: true })` aborts `context.drainSignal`, it stops waiting, cuts the remaining connections with `server.closeAllConnections()` and returns; core then records `DRAIN_TIMEOUT`. A client disconnect never marks handler or hook work as done. Fastify.close runs in the deferred cleanup only after every plugin's drain succeeded, and native onClose hooks run then. Shutdown failures and delays are never hidden, and the DB is never closed before unfinished work. A final forced kill in a cluster is a process policy, not a successful drain.
70
+ In a single process, drain refuses new requests with 503 and then waits for responses, handler Promises, registered request lifecycle hooks and track work. When the core drain deadline (`shutdown.drainTimeoutMs`, default 20 seconds) passes or `stop({ force: true })` aborts `context.drainSignal`, it stops waiting, cuts the remaining connections with `server.closeAllConnections()` and returns; core then records `DRAIN_TIMEOUT`. A client disconnect never marks handler or hook work as done. Fastify.close runs in the deferred cleanup only after every plugin's drain succeeded, and native onClose hooks run then. Before it, cleanup ends every connection that answers no request (idle, never used — a browser's preconnect or the spare connection a client opens after aborting a request — with a request still arriving, a TLS connection before its handshake, an HTTP/2 session without streams or without a client preface), so such a connection no longer holds stop until `headersTimeout`; responses under way finish and their connection then ends, HTTP/2 sessions with streams get GOAWAY, and upgraded (WebSocket) connections are left to their plugin. HTTP/2 (TLS or h2c) is set through `fastifyOptions`. Shutdown failures and delays are never hidden, and the DB is never closed before unfinished work. A final forced kill in a cluster is a process policy, not a successful drain.
56
71
 
57
72
  **Rule: put every Dokebi resource a Fastify `onClose` hook uses into `entry.requires`.** For example `createWeb({ app: app.view, entry: { requires: [dbPlugin] } })`. Cleanup runs in reverse initialisation order, so web must depend on the resource for the resource to be cleaned up after Fastify.close. If the resource depends on web instead, the resource closes first. Business modules declare the web, router, controller and DB they use in their own requires. Never close a borrowed pool on your own.
58
73
 
59
74
  For native callback hooks, done or the normal end of the response marks the end of the work; async hooks are awaited until their returned Promise settles. Work that continues after the response, and async work in user raw streams, parsers, custom error handlers, timers or outside events, is not tracked automatically: wait for it with track or the owning plugin's drain. Do not mix async and done in a hook. `listen`/`close`, overwriting root hooks and bypassing the reserved `dokebiHealth` config are outside the extension contract.
60
75
 
61
- Error responses follow the D-0063 §1 mapping: a Dokebi error answers with its `status` and `{ error: code, message, hint?, data? }` (plus `fix` and `details` in development); an unknown error answers 500 `{ error: 'INTERNAL_SERVER_ERROR' }`. In production (`NODE_ENV=production` or `developmentErrors: false`) `fix` and `details` are left out and 5xx messages become generic sentences. One rule picks the format ([D-0074](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0074-error-responses.md)): Inertia requests, XHR, Bearer API clients, JSON request bodies, sealed requests and `fetch()` get JSON; only a browser page (a navigation, an HTML form post) gets the same content as a small HTML page. A refused body or query string schema is 422 `{ error: 'VALIDATION_FAILED', message, hint, fields: [{ field, message }], errors: { field: message } }`, and `throw validationError({ name: 'Already taken' })` from a handler gives the same answer; an unknown route is 404 `NOT_FOUND` in the same shape. Error responders (`web.errorResponder`) let @dokebi/app draw an app's error views and send a refused HTML form back to its page, and @dokebi/template-inertia answer Inertia requests (validation redirect, error page). The pieces of that redirect are exported for your own responders (0.4.1): `isFormSubmission`, `formFieldErrors`, `formOldInput` and `formBackTarget` (AI.md §6). A 500 leaves the error log `WEB_REQUEST_FAILED` (with the full error text). The table is in [AI.md](AI.md) §6. If you register your own error handler, its security is your responsibility. HTTP authentication, rate limiting, CORS and so on are Fastify plugins the app chooses.
76
+ Error responses follow the D-0063 §1 mapping: a Dokebi error answers with its `status` and `{ error: code, message, hint?, data? }` (plus `fix` and `details` in development); an unknown error answers 500 `{ error: 'INTERNAL_SERVER_ERROR' }`. In production (`NODE_ENV=production` or `developmentErrors: false`) `fix` and `details` are left out and 5xx messages become generic sentences. One rule picks the format ([D-0074](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0074-error-responses.md)): Inertia requests, XHR, Bearer API clients, JSON request bodies, sealed requests and `fetch()` get JSON; only a browser page (a navigation, an HTML form post) gets the same content as a small HTML page. A refused body or query string schema is 422 `{ error: 'VALIDATION_FAILED', message, hint, fields: [{ field, message }], errors: { field: message } }`, and `throw validationError({ name: 'Already taken' })` from a handler gives the same answer; an unknown route is 404 `NOT_FOUND` in the same shape. Error responders (`web.errorResponder`) let @dokebi/app draw an app's error views and send a refused HTML form back to its page, and @dokebi/template-inertia answer Inertia requests (validation redirect, error page). The pieces of that redirect are exported for your own responders (0.4.1): `isFormSubmission`, `formFieldErrors`, `formOldInput` and `formBackTarget` (AI.md §6). Any 4xx error can ask for the same redirect with `data.formErrors: { field: message }` (0.4.3, D-0076 §2.5; `_form` for the whole form): @dokebi/csrf does it for an expired token. An error that would answer 500 is first offered to the contributions of `dokebi-web:error-translator` (`@dokebi/web/points`, D-0093): @dokebi/db contributes one, so a unique violation answers 409 `DB_CONFLICT` and a statement timeout 503 `DB_TIMEOUT` with `Retry-After`, in the same JSON or HTML format, logged at error as `WEB_ERROR_TRANSLATED` with the driver error as the cause. A 500 leaves the error log `WEB_REQUEST_FAILED` (with the full error text). The table is in [AI.md](AI.md) §6. If you register your own error handler, its security is your responsibility. HTTP authentication, rate limiting, CORS and so on are Fastify plugins the app chooses.
62
77
 
63
78
  ## Install and run
64
79
 
@@ -94,6 +109,12 @@ options:
94
109
 
95
110
  `constraint(strategy)` adds a Fastify route constraint strategy (`addConstraintStrategy`) during setup. Call it before the routes that use the constraint. @dokebi/app uses it to pick the app by Host (`dokebiApp`), so several routes can share one path, split by constraint value. A call after start is `FROZEN`.
96
111
 
112
+ ## Routes bound to apps (D-0132)
113
+
114
+ A route with `app: 'mcp'` (or `app: ['studio', 'admin']`) answers only on the hosts of those @dokebi/app apps; every other host gets the 404 of an unknown route. It also works on routes of `register()` scopes, and is bound at boot whatever the plugin order. Plugins that add routes take the same option, `<plugin>.app` in dokebi.yaml (`dokebi-mcp.app`, `dokebi-oauth.app`), declared with `appOption()` of `@dokebi/web/points`. @dokebi/app fills the routing (`appRouting`); without it a bound route fails the start (`ROUTE_APP_UNAVAILABLE`), and an unknown app name too (`ROUTE_APP_UNKNOWN`). Details in [AI.md §2.1](AI.md).
115
+
97
116
  ## Trusted proxies (2026-10-14)
98
117
 
99
- Only requests from `trustProxy: [address...]` (exact IPv4 and IPv6 addresses, up to 64) have their `X-Forwarded-Host` (and For and Proto) trusted. The same list goes to Fastify's `trustProxy`. `requestHost(request)` returns the host the request asked for under that rule, in lower case with the port kept. @dokebi/app's domain decision and @dokebi/websocket's Origin check use it. Example: a Cloudflare tunnel on the same machine is `[127.0.0.1, ::1]` ([ISSUE-0005](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/issues/ISSUE-0005-playground-findings.md) PG-20).
118
+ Only requests from `trustProxy: [address...]` (exact IPv4 and IPv6 addresses, up to 64) have their `X-Forwarded-Host` (and For and Proto) trusted. The same list goes to Fastify's `trustProxy`. `requestHost(request)` returns the host the request asked for under that rule (`Host`, or `:authority` over HTTP/2), in lower case with the port kept; of several `X-Forwarded-Host` entries it takes the last, the one the trusted proxy wrote (earlier entries can come from the client), as Fastify's `request.host` does. @dokebi/app's domain decision and @dokebi/websocket's Origin check use it. Example: a Cloudflare tunnel on the same machine is `[127.0.0.1, ::1]` ([ISSUE-0005](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/issues/ISSUE-0005-playground-findings.md) PG-20).
119
+
120
+ `routeHook` can return `onResponse(request, reply, done)`: a callback hook appended after existing response hooks, including on routes registered earlier. Call `done` once. The response has completed and cannot be changed; `reply.elapsedTime` is milliseconds. `@dokebi/metrics` uses this hook for bounded response collection. Routes left untouched receive no hook.
@@ -0,0 +1,20 @@
1
+ import type { PluginContext } from '@dokebi/core';
2
+ import { type WebAppRouting } from './points.js';
3
+ /**
4
+ * The app names of a setting, checked: a name, or 1 to 64 distinct names. Throws INVALID_ROUTE
5
+ * (`where` names the route or the option).
6
+ */
7
+ export declare function appNames(value: unknown, where: string): readonly string[];
8
+ /** The routing slot of one web server and the bindings it made (onRoute, start-up cost only). */
9
+ export declare class AppRoutes {
10
+ #private;
11
+ constructor(context: PluginContext);
12
+ get routing(): WebAppRouting | undefined;
13
+ set(routing: WebAppRouting): void;
14
+ /**
15
+ * onRoute: a route's `app` becomes the routing's constraint (deleted from the options so
16
+ * Fastify never sees it), and every route with that constraint is checked for an app that
17
+ * already has the same method and path.
18
+ */
19
+ route(options: Record<string, unknown>): void;
20
+ }
@@ -0,0 +1,137 @@
1
+ import { WebError } from './errors.js';
2
+ import { APP_NAME, APP_NAMES_MAX } from './points.js';
3
+ /*
4
+ * Routes bound to apps (D-0132). Any route (`web.route`, a route of a `web.register` scope, a
5
+ * plugin's own) may say which app or apps of @dokebi/app answer it: `app: 'mcp'` or
6
+ * `app: ['studio', 'admin']`. dokebi-web turns that into the host constraint app routes carry
7
+ * (`dokebiApp`), so the route answers only on the hosts of those apps and every other host gets
8
+ * the 404 of an unknown route. dokebi-app fills the routing in its setup (`web.appRouting`);
9
+ * routes are bound at boot (`server.ready()`), after every setup, so the order of plugins does
10
+ * not matter. Without @dokebi/app a bound route fails the start (fail closed: the endpoint would
11
+ * otherwise answer on every host, the very thing the binding is for).
12
+ */
13
+ /**
14
+ * The app names of a setting, checked: a name, or 1 to 64 distinct names. Throws INVALID_ROUTE
15
+ * (`where` names the route or the option).
16
+ */
17
+ export function appNames(value, where) {
18
+ const list = typeof value === 'string' ? [value] : Array.isArray(value) ? [...value] : undefined;
19
+ if (list === undefined ||
20
+ list.length === 0 ||
21
+ list.length > APP_NAMES_MAX ||
22
+ list.some((name) => typeof name !== 'string' || !APP_NAME.test(name)) ||
23
+ new Set(list).size !== list.length)
24
+ throw new WebError('INVALID_ROUTE', `${where}: app must be an app name or a list of them`, {
25
+ fix: `Give app as one app name (^[a-z][a-z0-9-]{0,31}$, the folder of src/apps/<app>) or a list of 1 to ${APP_NAMES_MAX} distinct names, for example app: mcp or app: [studio, admin].`,
26
+ });
27
+ return Object.freeze(list);
28
+ }
29
+ /** The routing slot of one web server and the bindings it made (onRoute, start-up cost only). */
30
+ export class AppRoutes {
31
+ #routing;
32
+ /** `METHOD url` → apps of the routes there carrying the routing's constraint. */
33
+ #taken = new Map();
34
+ #warned = new Set();
35
+ #context;
36
+ constructor(context) {
37
+ this.#context = context;
38
+ }
39
+ get routing() {
40
+ return this.#routing;
41
+ }
42
+ set(routing) {
43
+ if (this.#routing !== undefined)
44
+ throw new WebError('INVALID_ARGUMENT', 'The app routing is already registered', {
45
+ fix: 'Register one @dokebi/app plugin: it alone calls web.appRouting().',
46
+ });
47
+ if (routing === null ||
48
+ typeof routing !== 'object' ||
49
+ typeof routing.constraint !== 'string' ||
50
+ !Array.isArray(routing.names) ||
51
+ typeof routing.domainApp !== 'function' ||
52
+ typeof routing.domainsOf !== 'function')
53
+ throw new WebError('INVALID_ARGUMENT', 'web.appRouting() takes a WebAppRouting', {
54
+ fix: 'Pass { constraint, names, domainApp(host), domainsOf(app), fallback } (dokebi-app does).',
55
+ });
56
+ this.#routing = routing;
57
+ this.#context.logger.log('debug', 'Web app routing registered', {
58
+ constraint: routing.constraint,
59
+ apps: routing.names.slice(0, 64),
60
+ fallback: routing.fallback ?? null,
61
+ });
62
+ }
63
+ /**
64
+ * onRoute: a route's `app` becomes the routing's constraint (deleted from the options so
65
+ * Fastify never sees it), and every route with that constraint is checked for an app that
66
+ * already has the same method and path.
67
+ */
68
+ route(options) {
69
+ const methods = Array.isArray(options.method)
70
+ ? options.method.map(String)
71
+ : [String(options.method)];
72
+ const url = String(options.url);
73
+ const label = `Route ${methods.join(',')} ${url}`;
74
+ if (options.app !== undefined) {
75
+ const names = appNames(options.app, label);
76
+ delete options.app;
77
+ const routing = this.#routing;
78
+ if (routing === undefined)
79
+ throw new WebError('ROUTE_APP_UNAVAILABLE', `${label} is bound to app ${names.join(', ')}, but no app routing is registered`, {
80
+ data: { route: `${methods.join(',')} ${url}`, apps: names },
81
+ });
82
+ for (const name of names)
83
+ if (!routing.names.includes(name))
84
+ throw new WebError('ROUTE_APP_UNKNOWN', `${label} is bound to app ${name}, which is not an app (apps: ${routing.names.join(', ') || 'none'})`, { data: { route: `${methods.join(',')} ${url}`, app: name, apps: routing.names } });
85
+ const constraints = (options.constraints ?? {});
86
+ if (constraints[routing.constraint] !== undefined)
87
+ throw new WebError('INVALID_ROUTE', `${label} has both app and a ${routing.constraint} constraint`, { fix: `Give the route app only (it sets the ${routing.constraint} constraint).` });
88
+ // One name stays a string (the value app routes carry); several are the list the
89
+ // strategy of dokebi-app reads.
90
+ options.constraints = {
91
+ ...constraints,
92
+ [routing.constraint]: names.length === 1 ? names[0] : names,
93
+ };
94
+ for (const name of names)
95
+ this.#reachable(routing, name, label);
96
+ const logger = this.#context.logger;
97
+ if (logger.isEnabled('debug'))
98
+ logger.log('debug', 'Web route bound to apps', { route: label.slice(6), apps: names });
99
+ }
100
+ const routing = this.#routing;
101
+ if (routing === undefined)
102
+ return;
103
+ const value = options.constraints?.[routing.constraint];
104
+ if (value === undefined)
105
+ return;
106
+ const apps = Array.isArray(value) ? value : [String(value)];
107
+ for (const method of methods) {
108
+ const key = `${method} ${url}`;
109
+ let taken = this.#taken.get(key);
110
+ if (!taken) {
111
+ taken = new Map();
112
+ this.#taken.set(key, taken);
113
+ }
114
+ for (const app of apps) {
115
+ const other = taken.get(app);
116
+ if (other !== undefined)
117
+ throw new WebError('ROUTE_APP_CONFLICT', `${method} ${url} answers twice on app ${app}: ${other} and ${apps.join(', ')}`, { data: { route: key, app } });
118
+ }
119
+ for (const app of apps)
120
+ taken.set(app, `[${apps.join(', ')}]`);
121
+ }
122
+ }
123
+ /** A warn (once per app) for a bound app that no domain reaches: its routes answer nowhere. */
124
+ #reachable(routing, app, label) {
125
+ if (this.#warned.has(app))
126
+ return;
127
+ if (routing.domainsOf(app).length > 0 || routing.fallback === app)
128
+ return;
129
+ this.#warned.add(app);
130
+ this.#context.logger.log('warn', 'A route is bound to an app that no domain points at', {
131
+ code: 'ROUTE_APP_UNREACHABLE',
132
+ app,
133
+ route: label.slice(6),
134
+ fix: `Point a domain at ${app} (npx dokebi app link ${app} <host>), or bind the route to an app that has domains.`,
135
+ });
136
+ }
137
+ }
@@ -0,0 +1,24 @@
1
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
2
+ /** The instance property that holds the steps (`Symbol.for`, shared by name). */
3
+ export declare const BEFORE_HIJACK: unique symbol;
4
+ /**
5
+ * One step: synchronous work returns undefined; work to wait for returns its Promise. A step
6
+ * that fails throws or rejects; the transport then refuses the stream or the upgrade.
7
+ */
8
+ export type WebBeforeHijackStep = (request: FastifyRequest, reply: FastifyReply) => PromiseLike<void> | undefined;
9
+ /**
10
+ * The step list of a server, for a plugin that registers a step (push onto it). Decorated once on
11
+ * the scope it is first asked of — register from a non-encapsulated (`skip-override`) plugin so
12
+ * every route of the server sees it — and the same array afterwards.
13
+ */
14
+ export declare function beforeHijackSteps(scope: FastifyInstance): WebBeforeHijackStep[];
15
+ /**
16
+ * Runs the before-hijack steps of the request's server, for a transport about to hijack the reply.
17
+ * Undefined when there is nothing to wait for (no list, or every step was synchronous): no
18
+ * Promise and no timer on that path. Otherwise the wait, bounded by `timeoutMs`, resolving to the
19
+ * number of steps waited for, or rejecting with the first failure, or with `timeoutError()` when
20
+ * the time is up (the timer is cleared either way). A step that throws before any step is
21
+ * pending throws here; one that throws later rejects the wait, and the steps already pending stay
22
+ * handled (no unhandled rejection).
23
+ */
24
+ export declare function runBeforeHijack(request: FastifyRequest, reply: FastifyReply, timeoutMs: number, timeoutError: () => Error): Promise<number> | undefined;
@@ -0,0 +1,73 @@
1
+ /*
2
+ * D-0089: the work plugins finish in `onSend` — @dokebi/session saves the session and writes its
3
+ * cookie, @dokebi/auth writes its cookies — never runs for a hijacked reply (an SSE stream, a
4
+ * WebSocket upgrade: Fastify writes no head and runs no onSend hook). Those plugins also register
5
+ * that work as a "before-hijack" step on the server, and a transport runs the steps before it
6
+ * writes its own head, so the session is saved and the cookies go out with the stream or the 101.
7
+ *
8
+ * The list lives on the Fastify instance under `Symbol.for('dokebi.web.beforeHijack')`: a shape
9
+ * shared by name, so a plugin that does not import this module (or another installed copy of
10
+ * @dokebi/web) meets the same list. These two functions are the one implementation of both sides.
11
+ */
12
+ /** The instance property that holds the steps (`Symbol.for`, shared by name). */
13
+ export const BEFORE_HIJACK = Symbol.for('dokebi.web.beforeHijack');
14
+ /**
15
+ * The step list of a server, for a plugin that registers a step (push onto it). Decorated once on
16
+ * the scope it is first asked of — register from a non-encapsulated (`skip-override`) plugin so
17
+ * every route of the server sees it — and the same array afterwards.
18
+ */
19
+ export function beforeHijackSteps(scope) {
20
+ const known = scope[BEFORE_HIJACK];
21
+ if (known)
22
+ return known;
23
+ const steps = [];
24
+ scope.decorate(BEFORE_HIJACK, steps);
25
+ return steps;
26
+ }
27
+ /**
28
+ * Runs the before-hijack steps of the request's server, for a transport about to hijack the reply.
29
+ * Undefined when there is nothing to wait for (no list, or every step was synchronous): no
30
+ * Promise and no timer on that path. Otherwise the wait, bounded by `timeoutMs`, resolving to the
31
+ * number of steps waited for, or rejecting with the first failure, or with `timeoutError()` when
32
+ * the time is up (the timer is cleared either way). A step that throws before any step is
33
+ * pending throws here; one that throws later rejects the wait, and the steps already pending stay
34
+ * handled (no unhandled rejection).
35
+ */
36
+ export function runBeforeHijack(request, reply, timeoutMs, timeoutError) {
37
+ const steps = request.server[BEFORE_HIJACK];
38
+ if (!Array.isArray(steps))
39
+ return undefined;
40
+ let pending;
41
+ for (const step of steps) {
42
+ let waiting;
43
+ try {
44
+ waiting = step(request, reply);
45
+ }
46
+ catch (error) {
47
+ if (!pending)
48
+ throw error;
49
+ // The steps already waiting stay handled: Promise.all below takes their rejection, and the
50
+ // wait fails with this error (the first to fail), as for two rejections.
51
+ pending.push(Promise.reject(error));
52
+ break;
53
+ }
54
+ if (waiting === undefined)
55
+ continue;
56
+ pending ??= [];
57
+ pending.push(waiting);
58
+ }
59
+ if (!pending)
60
+ return undefined;
61
+ const count = pending.length;
62
+ let timer;
63
+ const timeout = new Promise((_resolve, reject) => {
64
+ timer = setTimeout(() => reject(timeoutError()), timeoutMs);
65
+ });
66
+ return Promise.race([Promise.all(pending), timeout]).then(() => {
67
+ clearTimeout(timer);
68
+ return count;
69
+ }, (error) => {
70
+ clearTimeout(timer);
71
+ throw error;
72
+ });
73
+ }
package/dist/body.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import type { FastifyRequest } from 'fastify';
2
+ /** A request over HTTP/1 (an injected one too). */
3
+ export declare function http1(request: FastifyRequest): boolean;
4
+ /** The headers say a body follows (Content-Length above 0, or a Transfer-Encoding): HTTP/1. */
5
+ export declare function hasBody(headers: Readonly<Record<string, string | string[] | undefined>>): boolean;
6
+ /**
7
+ * A body follows the head of this request: over HTTP/1 by its headers, over HTTP/2 by its HEADERS
8
+ * frame (no END_STREAM) unless it says `Content-Length: 0`. That one header is enough there:
9
+ * nghttp2 resets a stream whose DATA passes its Content-Length, so no byte of a body reaches a
10
+ * reader; and a client may end a body-less request with an empty DATA frame instead of END_STREAM
11
+ * on HEADERS (`curl -d ''`, Node's client with `end()`; audit r5: 415 on a sealed route over HTTP/2,
12
+ * served over HTTP/1).
13
+ */
14
+ export declare function bodyFollows(request: FastifyRequest): boolean;
package/dist/body.js ADDED
@@ -0,0 +1,30 @@
1
+ /*
2
+ * Whether a request carries a body, for every step that decides before any parser runs: the
3
+ * requestTimeoutMs timer, the early-answer close, the seal refusal of plain bodies and the
4
+ * sealed-form marker check. One rule for HTTP/1 and HTTP/2: an HTTP/2 request needs no
5
+ * Content-Length and has no Transfer-Encoding (RFC 9113 §8.2.2), so its headers alone do not say
6
+ * it (audit r4 step 2: a plain body without Content-Length passed a sealed route over HTTP/2).
7
+ */
8
+ /** A request over HTTP/1 (an injected one too). */
9
+ export function http1(request) {
10
+ return request.raw.httpVersionMajor !== 2;
11
+ }
12
+ /** The headers say a body follows (Content-Length above 0, or a Transfer-Encoding): HTTP/1. */
13
+ export function hasBody(headers) {
14
+ const length = headers['content-length'];
15
+ return headers['transfer-encoding'] !== undefined || (length !== undefined && length !== '0');
16
+ }
17
+ /**
18
+ * A body follows the head of this request: over HTTP/1 by its headers, over HTTP/2 by its HEADERS
19
+ * frame (no END_STREAM) unless it says `Content-Length: 0`. That one header is enough there:
20
+ * nghttp2 resets a stream whose DATA passes its Content-Length, so no byte of a body reaches a
21
+ * reader; and a client may end a body-less request with an empty DATA frame instead of END_STREAM
22
+ * on HEADERS (`curl -d ''`, Node's client with `end()`; audit r5: 415 on a sealed route over HTTP/2,
23
+ * served over HTTP/1).
24
+ */
25
+ export function bodyFollows(request) {
26
+ if (http1(request))
27
+ return hasBody(request.headers);
28
+ const stream = request.raw.stream;
29
+ return stream?.endAfterHeaders === false && request.headers['content-length'] !== '0';
30
+ }
@@ -0,0 +1,67 @@
1
+ import type { Logger } from '@dokebi/core';
2
+ export declare const READY_TOPIC = "dokebi-web/v1/ready";
3
+ /**
4
+ * How long the ready route waits for the other workers. Kubernetes' default probe timeout is 1 s;
5
+ * a worker that cannot answer an IPC message in this time would not answer a request either.
6
+ */
7
+ export declare const READY_GATHER_MS = 500;
8
+ type GatherAnswer = {
9
+ readonly slot: number;
10
+ readonly ok: true;
11
+ readonly data: unknown;
12
+ } | {
13
+ readonly slot: number;
14
+ readonly ok: false;
15
+ readonly code: string;
16
+ };
17
+ type GatherResult = {
18
+ readonly ok: true;
19
+ readonly workers: number;
20
+ readonly answers: readonly GatherAnswer[];
21
+ } | {
22
+ readonly ok: false;
23
+ readonly code: string;
24
+ };
25
+ /** The part of @dokebi/cluster's ClusterBridge this package uses. */
26
+ export interface ReadyBridge {
27
+ readonly slot: number;
28
+ readonly workers: number;
29
+ answer(topic: string, answer: () => unknown): () => void;
30
+ gather(topic: string, options: {
31
+ readonly timeoutMs: number;
32
+ }): Promise<GatherResult>;
33
+ }
34
+ /** The cluster bridge of this process, or undefined outside a @dokebi/cluster worker. */
35
+ export declare function readyBridge(): ReadyBridge | undefined;
36
+ /** One worker's answer: whether it serves requests now, and whether it is draining. */
37
+ export interface WorkerReadiness {
38
+ readonly ready: boolean;
39
+ readonly draining: boolean;
40
+ }
41
+ /** The body of the cluster's ready route. */
42
+ export interface ClusterReadyBody {
43
+ readonly ready: boolean;
44
+ readonly workers: {
45
+ /** The workers the cluster runs (slots). */
46
+ readonly total: number;
47
+ /** The slots that answered ready. */
48
+ readonly ready: readonly number[];
49
+ /** The slots that answered not ready or did not answer in time. */
50
+ readonly notReady: readonly number[];
51
+ };
52
+ /** Why the other workers could not be asked (the answer is then this worker's alone). */
53
+ readonly reason?: string;
54
+ }
55
+ /**
56
+ * This worker answers the others' question and asks them for the ready route. Concurrent probes
57
+ * share one question (a load balancer, an orchestrator and a monitor polling at once cost one
58
+ * gather), so they never fill the primary's gathers (GATHER_BUSY) nor each other's IPC.
59
+ */
60
+ export declare class ClusterReadiness {
61
+ #private;
62
+ readonly stop: () => void;
63
+ constructor(bridge: ReadyBridge, local: () => WorkerReadiness, logger: Logger, repeatWindowMs: number);
64
+ /** The cluster's readiness; called only once this worker itself is ready. */
65
+ ready(): Promise<ClusterReadyBody>;
66
+ }
67
+ export {};
@@ -0,0 +1,123 @@
1
+ import { diagnostics } from '@dokebi/core/libraries';
2
+ /*
3
+ * D-0164: the ready route of a @dokebi/cluster worker answers for the whole cluster. The workers
4
+ * share one port and a load balancer sees them as one target, so one worker that is ready while
5
+ * another still refuses requests (R2/R3 Codex T4: right after a database came back, one worker's
6
+ * ready answered 200 while the others still refused orders with 503) told the balancer to send
7
+ * traffic that then failed. Every worker answers READY_TOPIC with its own state; the ready route
8
+ * asks all of them through the cluster bridge at globalThis[Symbol.for('dokebi.cluster.bridge')]
9
+ * (this package never imports @dokebi/cluster, it matches the bridge's shape, as metrics does).
10
+ */
11
+ export const READY_TOPIC = 'dokebi-web/v1/ready';
12
+ /**
13
+ * How long the ready route waits for the other workers. Kubernetes' default probe timeout is 1 s;
14
+ * a worker that cannot answer an IPC message in this time would not answer a request either.
15
+ */
16
+ export const READY_GATHER_MS = 500;
17
+ const BRIDGE_KEY = Symbol.for('dokebi.cluster.bridge');
18
+ /** The cluster bridge of this process, or undefined outside a @dokebi/cluster worker. */
19
+ export function readyBridge() {
20
+ const value = globalThis[BRIDGE_KEY];
21
+ return value &&
22
+ typeof value.answer === 'function' &&
23
+ typeof value.gather === 'function' &&
24
+ Number.isInteger(value.slot) &&
25
+ Number.isInteger(value.workers)
26
+ ? value
27
+ : undefined;
28
+ }
29
+ const isReadiness = (value) => typeof value === 'object' &&
30
+ value !== null &&
31
+ typeof value.ready === 'boolean' &&
32
+ typeof value.draining === 'boolean';
33
+ /**
34
+ * This worker answers the others' question and asks them for the ready route. Concurrent probes
35
+ * share one question (a load balancer, an orchestrator and a monitor polling at once cost one
36
+ * gather), so they never fill the primary's gathers (GATHER_BUSY) nor each other's IPC.
37
+ */
38
+ export class ClusterReadiness {
39
+ #bridge;
40
+ #local;
41
+ #logger;
42
+ #repeats;
43
+ #pending;
44
+ stop;
45
+ constructor(bridge, local, logger, repeatWindowMs) {
46
+ this.#bridge = bridge;
47
+ this.#local = local;
48
+ this.#logger = logger;
49
+ this.#repeats = new diagnostics.Repeats({ intervalMs: repeatWindowMs });
50
+ let stop = () => { };
51
+ try {
52
+ stop = bridge.answer(READY_TOPIC, () => this.#local());
53
+ logger.log('debug', 'Web readiness answers for the cluster', {
54
+ slot: bridge.slot,
55
+ workers: bridge.workers,
56
+ });
57
+ }
58
+ catch (error) {
59
+ // A second web server in the same worker (two applications): the first one answers.
60
+ diagnostics.logError(logger, 'Web readiness topic is answered already in this worker', 'WEB_READY_TOPIC_TAKEN', error, { topic: READY_TOPIC });
61
+ }
62
+ this.stop = stop;
63
+ }
64
+ /** The cluster's readiness; called only once this worker itself is ready. */
65
+ ready() {
66
+ this.#pending ??= this.#gather().finally(() => {
67
+ this.#pending = undefined;
68
+ });
69
+ return this.#pending;
70
+ }
71
+ async #gather() {
72
+ const bridge = this.#bridge;
73
+ const result = await bridge.gather(READY_TOPIC, { timeoutMs: READY_GATHER_MS });
74
+ const total = Math.max(bridge.workers, result.ok ? result.workers : 0, 1);
75
+ if (!result.ok) {
76
+ // The primary is starting (not every worker is up yet) or stopping: the cluster is not
77
+ // ready. Anything else (busy, a lost primary) cannot say more than this worker knows.
78
+ const ready = result.code !== 'GATHER_UNAVAILABLE';
79
+ const suppressed = this.#repeats.take(result.code);
80
+ if (ready && suppressed !== undefined)
81
+ this.#logger.log('warn', 'Cluster readiness gather failed; this worker answered alone', {
82
+ code: 'WEB_READY_GATHER_FAILED',
83
+ reason: result.code,
84
+ slot: bridge.slot,
85
+ ...(suppressed ? { suppressed } : {}),
86
+ });
87
+ return {
88
+ ready,
89
+ workers: {
90
+ total,
91
+ ready: ready ? [bridge.slot] : [],
92
+ notReady: ready ? [] : [bridge.slot],
93
+ },
94
+ reason: result.code,
95
+ };
96
+ }
97
+ const ready = [];
98
+ const notReady = [];
99
+ const reasons = [];
100
+ for (const answer of result.answers) {
101
+ if (answer.ok && isReadiness(answer.data)) {
102
+ // A draining worker no longer listens: the primary hands it no new connection.
103
+ if (answer.data.draining)
104
+ continue;
105
+ (answer.data.ready ? ready : notReady).push(answer.slot);
106
+ }
107
+ else if (!answer.ok && answer.code === 'GATHER_NO_ANSWER') {
108
+ }
109
+ else {
110
+ notReady.push(answer.slot);
111
+ reasons.push(`${answer.slot}:${answer.ok ? 'INVALID' : answer.code}`);
112
+ }
113
+ }
114
+ ready.sort((a, b) => a - b);
115
+ notReady.sort((a, b) => a - b);
116
+ if (notReady.length && this.#logger.isEnabled('debug'))
117
+ this.#logger.log('debug', 'Cluster readiness: workers not ready', {
118
+ notReady: notReady.join(','),
119
+ ...(reasons.length ? { reasons: reasons.join(',') } : {}),
120
+ });
121
+ return { ready: notReady.length === 0, workers: { total, ready, notReady } };
122
+ }
123
+ }
@@ -2,6 +2,22 @@ import type { FastifyInstance, FastifyServerOptions } from 'fastify';
2
2
  export type SchemaControllerOptions = NonNullable<FastifyServerOptions['schemaController']>;
3
3
  /** A fresh controller option for one Fastify instance (each instance has its own pools). */
4
4
  export declare function lazyCompilers(): SchemaControllerOptions;
5
+ /**
6
+ * Fastify's symbols of the error handler chain (lib/symbols.js of the pinned fastify):
7
+ * `kErrorHandler` holds an instance's handler object, `kReplyNextErrorHandler` the one a reply's
8
+ * next error goes to (lib/error-handler.js). dokebi-web points the latter back at itself while it
9
+ * sends its own error answer, so an error raised then (an onSend step's) is answered by it too.
10
+ */
11
+ export declare function errorHandlerSymbols(): {
12
+ readonly kErrorHandler: symbol;
13
+ readonly kReplyNextErrorHandler: symbol;
14
+ };
15
+ /**
16
+ * `kRouteContext` holds a reply's route context (lib/symbols.js); its `config` is the route's
17
+ * config as Fastify copied it. `request.routeOptions` builds a new object on every read, so the
18
+ * per-request read of a route's `completed` observers goes through the context.
19
+ */
20
+ export declare function routeContextSymbol(): symbol;
5
21
  /**
6
22
  * After `fastify()`: when the server uses `controller` (not an extension's own), mark its compilers
7
23
  * as the defaults again so header schemas keep Fastify's case-insensitive names.