@ultimat3/core 31.48.0 → 31.50.0

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.
package/CLAUDE.md CHANGED
@@ -20,7 +20,7 @@ change to every package. A row or rule marked `†` has its full text in
20
20
  | Time | take a `Clock` (a `SleepClock` to wait); `Date.now()` / `new Date()` only in `clock.ts`; a waiting timer only in `sleep-clock.ts` |
21
21
  | Context | never thread `ctx` as a parameter — `useContext()` |
22
22
  | A value ambient across an `await` | `asyncContext<T>(subject)` from `async-context.ts`, in **every** package — never `new AsyncLocalStorage` |
23
- | Exports | explicit in `src/index.ts`; no `export *`. Six public subpaths (`./adapter`, `./page`, `./outbound`, `./redis`, `./render-node`, `./render-nodes`), one internal (`./internal/error-status`); nothing that loads a titles table joins `./page` (`page-bundle.test.ts`); an app imports `defineError` there (`define-error-bytes.test.ts`) † |
23
+ | Exports | explicit in `src/index.ts`; no `export *`. Six public subpaths (`./adapter`, `./page`, `./outbound`, `./redis`, `./render-node`, `./render-nodes`), two internal (`./internal/error-status`, `./internal/sse-frames`: the one SSE frame reader); nothing that loads a titles table joins `./page` (`page-bundle.test.ts`); an app imports `defineError` there (`define-error-bytes.test.ts`) † |
24
24
  | Files | < 200 LOC, 500 hard ceiling, one responsibility, `kebab-case.ts`, test beside source |
25
25
  | Type claims | `type-pins.ts`, never a `.test.ts` — `tsconfig.json` excludes tests |
26
26
 
@@ -174,7 +174,7 @@ server-only, never on `page.ts`. One call site per recorder; a second is the bug
174
174
  - **Three OTLP variables, three codes** — `X_OTLP_ENDPOINT_INVALID`, `X_OTLP_HEADERS_INVALID`,
175
175
  `X_OTLP_PROTOCOL_UNSUPPORTED`. A header KEY is in the cause/fix/meta; its VALUE never is.
176
176
  - **A cause is cut at 4 KiB in the constructor** (`boundedCause`); schema's copy is pinned by `single-line-pin.test.ts`.
177
- - `error-reporter.ts`: `ErrorReporter`, an `adapterSlot` (`installErrorReporter` on `./adapter`; `configureErrorReporting` keeps clock/release/environment/enabled only), no-op default, memory reporter for tests, Sentry transport (`error-reporter-sentry.ts`, optional export). Full rule: `docs/history/core.md`. `'browser'`: only cli's `client-errors-routes.ts`, one `X_CLIENT_ERROR` per report.
177
+ - `error-reporter.ts`: `ErrorReporter`, an `adapterSlot` (`installErrorReporter` on `./adapter`; `configureErrorReporting` keeps clock/release/environment/enabled only), no-op default, memory reporter for tests, Sentry transport (`error-reporter-sentry.ts`, optional export; one warn per non-2xx, a 429 pauses; a DSN refusal never echoes its secret) †. `'browser'`: only cli's `client-errors-routes.ts`, one `X_CLIENT_ERROR` per report.
178
178
  - `METRICS_PATH` is served by `@ultimat3/cli`'s `metrics-endpoint.ts` on `METRICS_PORT` (9090), never
179
179
  the role's HTTP port; every role opens it.
180
180
 
@@ -184,6 +184,7 @@ server-only, never on `page.ts`. One call site per recorder; a second is the bug
184
184
  - **`drain()`'s memo is published BEFORE the first hook runs** — a hook may re-enter `drain()`
185
185
  (`@ultimat3/http`'s `handle.stop()`), and `settleWithin` invokes hooks synchronously.
186
186
  - **The drain deadline is enforced** (`lifecycle-deadline.ts`): a hook overrunning the whole drain's budget is abandoned and logged (`X_SHUTDOWN_TIMEOUT`); real monotonic time, never the injected `clock`. Full rule: `docs/history/core.md`.
187
+ - **The in-flight wait leaves the hooks behind it a slice**: with an `inflight`/`close` hook, `waitForIdle` stops `min(2s, deadlineMs / 5)` early (`laterHooksReserveMs`, `drain-deadline.ts`): a stuck request never starves the OTLP flush or pool close. Total unchanged. Handed to every hook as `ShutdownReason.inflightUntil`; a role that cuts its own work measures back from it.
187
188
  - **An exit after a drain is `drainExitCode()`** — 70 when work was abandoned (`X_SHUTDOWN_TIMEOUT`), else 0. Never a literal `process.exit(0)`.
188
189
  - **`close` hooks run last-registered first; the other phases as registered** (`runPhase`). No fourth phase.
189
190
  - **Who a health endpoint tells what is ONE rule, here** (`health-disclosure.ts`): `healthBody` +
package/README.md CHANGED
@@ -21,6 +21,7 @@ JSON.stringify({ dsn }); // the value never prints: a Secret redacts by value, a
21
21
  | an APP code's one declaration — title, HTTP status, retry and class — `defineError()` | `define-error.ts` |
22
22
  | an action's or a query's `errors:` — `checkDeclaredErrors` (the list), `judgeThrown` / `enforceDeclared` / `withDeclaredErrors` (a throw out of a handler; `X_ERROR_UNDECLARED` in test and dev, `undeclared_errors_total` in production), `describeDeclaredErrors` (a tool's description); the OpenAPI half `withDeclaredResponses`; the contract's source scan `scanHandlerSource` + `definedErrorClassCodes` (test-time). The status is passed in: `@ultimat3/http` is above this package | `declared-errors.ts`, `declared-errors-openapi.ts`, `declared-errors-scan.ts` |
23
23
  | the app's half of the HTTP status table, written by `defineError` and `@ultimat3/http`'s `registerErrorStatus` — internal, on `@ultimat3/core/internal/error-status` only | `error-status-declared.ts` |
24
+ | the one SSE frame reader (`takeFrames`), read by `clientStream` and `@ultimat3/mcp`'s remote client — internal, on `@ultimat3/core/internal/sse-frames` only | `sse-frames.ts` |
24
25
  | the one lazy `AsyncLocalStorage`, every ambient scope in the framework | `async-context.ts` |
25
26
  | request context on that seam | `context.ts` |
26
27
  | `Actor` (`user \| service \| agent \| anonymous`) | `actor.ts` |
@@ -107,8 +108,8 @@ JSON.stringify({ dsn }); // the value never prints: a Secret redacts by value, a
107
108
  | graceful drain, `/healthz`, `/readyz` | `lifecycle.ts` |
108
109
  | what a health endpoint tells whom — `healthBody(report, role, detailed)`, `healthPeerListed(peers, address)`, `DEFAULT_HEALTH_DETAIL_PEERS`; the one rule `@ultimat3/http` and the sync node's own listener both call | `health-disclosure.ts` |
109
110
  | the readiness grace between `/readyz` → 503 and the listener closing (`drain.readinessGraceMs`) | `lifecycle-grace.ts` |
110
- | the drain budget's default and domain (`drain.deadlineMs`, 25 s, 1–3600000 ms; the worker's optional `drain.workerDeadlineMs`, 1–86400000 ms; its `drain.workerRetireMs`, an hour, 0–86400000 ms) — `DRAIN_DEADLINE_DEFAULT_MS`, `DRAIN_DEADLINE_MAX_MS`, `WORKER_DRAIN_DEADLINE_MAX_MS`, `WORKER_RETIRE_DEFAULT_MS` | `drain-deadline.ts` |
111
- | `jobs.concurrency`'s default and domain — one slot count for every queue a worker serves, or a table per queue (`{ banks: 4, 'banks-long': 2 }`; a queue the table does not name runs at the default). `JOBS_CONCURRENCY_DEFAULT` (8), `type JobsConcurrency` | `config-jobs.ts` |
111
+ | the drain budget's default and domain (`drain.deadlineMs`, 25 s, 1–3600000 ms; the worker's optional `drain.workerDeadlineMs`, 1–86400000 ms; its `drain.workerRetireMs`, an hour, 0–86400000 ms) — `DRAIN_DEADLINE_DEFAULT_MS`, `DRAIN_DEADLINE_MAX_MS`, `WORKER_DRAIN_DEADLINE_MAX_MS`, `WORKER_RETIRE_DEFAULT_MS`; `laterHooksReserveMs(deadlineMs)`, the slice the in-flight wait leaves the hooks behind it (a fifth, at most 2 s; its end is `ShutdownReason.inflightUntil`) | `drain-deadline.ts` |
112
+ | `jobs.concurrency`'s default and domain — one slot count for every queue a worker serves, or a table per queue (`{ banks: 4, 'banks-long': 2 }`; a queue the table does not name runs at the default). `JOBS_CONCURRENCY_DEFAULT` (8), `type JobsConcurrency`; `JOBS_MAX_ATTEMPTS_DEFAULT` (3), `jobs.maxAttempts`' default and `@ultimat3/jobs`' `DEFAULT_RETRY.attempts` | `config-jobs.ts` |
112
113
  | SIGTERM/SIGINT → the one drain; on Windows also SIGHUP (console close) and SIGBREAK (Ctrl-Break) — `drainSignals(platform)`. With `exit: true` the process exits `drainExitCode()`: `0`, or `DRAIN_TIMEOUT_EXIT_CODE` (70, `EX_SOFTWARE`) when work was abandoned at the deadline (`X_SHUTDOWN_TIMEOUT`) | `lifecycle-signals.ts` |
113
114
  | is this directory inside a `bun build --compile` binary? `isCompiledBundle(import.meta.dir)` — `/$bunfs/` and Windows' `B:\~BUN\` | `bunfs.ts` |
114
115
  | which network an IP literal belongs to — `classifyAddress`, for SSRF screens; `peerAddressClass`, for a check that trusts a caller or a local name | `address-class.ts` |
@@ -956,7 +957,7 @@ Server-only, on its own subpath: `import { outbound, screenDial } from '@ultimat
956
957
 
957
958
  | Export | The one answer | The question it settles |
958
959
  |---|---|---|
959
- | `outbound({ url, vendor, dial, deadlineMs, method?, headers?, body?, idleMs?, maxBytes?, redirect?, retry?, idempotent?, read?, breaker?, proxy? }, deps?)` | a vendor call | a whole-call deadline clamped by the ambient request, `ctx.signal` (its reason unchanged), core's `retry()` for safe methods only (`X_OUTBOUND_RETRY_UNSAFE`), `Retry-After`, an idle watchdog and a byte cap on the body, `redirect: 'error'` by default, and eleven `X_OUTBOUND_*` codes whose causes carry no query and no header. `dial: 'public'` is the SSRF screen for a user-supplied URL (resolve, classify every address, pin, re-screen each hop): never a hand-written guard. `proxy` (a URL, `{ url, headers }`, or a per-hop resolver `(target) => … \| undefined`, types `OutboundProxy`, `OutboundProxyTarget`, `OutboundProxyInit`) is chosen AFTER the screen, so a public dial is tunnelled to the approved address with `tls.serverName` intact; its credential is never logged; a bad one is `X_OUTBOUND_PROXY_INVALID`. Inventory and rotation are app code. `deps` injects `fetch`, `resolve`, `sleep`, `now`, `random`, `timer`, `env` |
960
+ | `outbound({ url, vendor, dial, deadlineMs, method?, headers?, body?, idleMs?, maxBytes?, redirect?, retry?, idempotent?, read?, breaker?, proxy?, refusal? }, deps?)` | a vendor call | a whole-call deadline clamped by the ambient request, `ctx.signal` (its reason unchanged), core's `retry()` for safe methods only (`X_OUTBOUND_RETRY_UNSAFE`), `Retry-After`, an idle watchdog and a byte cap on the body, `redirect: 'error'` by default, and twelve `X_OUTBOUND_*` codes whose causes carry no query and no header. `dial: 'public'` is the SSRF screen for a user-supplied URL (resolve, classify every address, pin, re-screen each hop): never a hand-written guard. `proxy` (a URL, `{ url, headers }`, or a per-hop resolver `(target) => … \| undefined`, types `OutboundProxy`, `OutboundProxyTarget`, `OutboundProxyInit`) is chosen AFTER the screen, so a public dial is tunnelled to the approved address with `tls.serverName` intact; its credential is never logged; a bad one is `X_OUTBOUND_PROXY_INVALID`. Inventory and rotation are app code. `deps` injects `fetch`, `resolve`, `sleep`, `now`, `random`, `timer`, `env`. `fetch` is a production seam too: it is handed the screened url and `redirect: 'manual'`, the caps and rules stay `outbound()`'s, and an answer it reached by following a redirect itself is `X_OUTBOUND_TRANSPORT_REDIRECTED`. `refusal` (`OutboundRefusalRead`): `{ schema }` reads a non-2xx body whole, within `maxBytes`, and puts the schema's redacted answer at `meta.fields`; `{ detail: false }` keeps `meta.detail` at `''` |
960
961
  | `screenDial(url, { resolve?, allowPrivate? })` → `{ pin } \| { refused } \| { unresolved }` | where a dial may land | every resolved address classified by `classifyAddress`, the connection pinned with `tls.serverName`. The framework's one `Bun.dns.lookup` (`resolveDialHost`); `@ultimat3/jobs`' webhook target and `@ultimat3/scraping` call it and keep their own codes |
961
962
  | `deadlineSignal(ms, outer?, timer?)` | one attempt's signal | a deadline plus the caller's signal, undone on dispose (no listener left on `outer`, no timer armed) |
962
963
  | `breaker({ name, failures, cooldownMs, classify?, clock? })` → `admit`, `succeeded`, `failed`, `released`, `state`, `failures`, `judge`, `refusal`, `run` | is a dependency down | one state machine, the trigger stays the caller's. One probe in `half-open`, lapsing after `cooldownMs`; `X_BREAKER_OPEN` names `retryAfterSeconds`; `breaker_transitions_total{name,to}`. Per process |
@@ -1119,3 +1120,4 @@ a test — it is `'dev'`. Their callers are the boot (reading
1119
1120
  | `MAX_TIMER_MS` | the longest delay a timer holds, 2,147,483,647 ms: past it `setTimeout` arms ~1 ms |
1120
1121
  | `hostDecision(url, allowHosts)`, `hostMatches`, `ANY_HOST` | may a browser or scraper request leave. A wildcard (`'*'`, `'*.example.com'`) never admits an address inside the network nor `localhost`/`*.localhost` (loopback by name, and sent around an egress proxy by Chrome); an exact rule — `'localhost'`, `'127.0.0.1'` — does |
1121
1122
  | `jsonbRefusal(text)` | why `jsonb` would refuse this `JSON.stringify` output, or `undefined`. Names the class of thing, never the text |
1123
+ | `supervisedChild(env)`, `sharedPortOption(env)`, `childShare(total, index, count)` | the production multi-process seam. `supervisedChild` reads `ULTIMATE_CHILD=<index>/<count>` (set by the supervisor; unset or empty: `undefined`; anything else `X_INVARIANT`). `sharedPortOption` is the ONE place `reusePort` is spelled (`bun run reuse-port-seam`, `X_REUSEPORT_OUTSIDE_SEAM`): `{ reusePort: true }` for a supervised child on Linux, `{}` otherwise — spread it into `Bun.serve`. `childShare` splits a container-wide count: floor, remainder to the lowest indices, minimum 1 — a total below the count is the caller's to clamp first (the worker gives the indices >= total no slot, so `jobs.concurrency: 1` stays serial; `childShare` alone would give every child 1). A supervised child's log lines carry `child: <index>` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/core",
3
- "version": "31.48.0",
3
+ "version": "31.50.0",
4
4
  "description": "Ultimate's foundation: errors, context, env, config, clock, ids, logging, telemetry, lifecycle",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -33,6 +33,7 @@
33
33
  "./adapter": "./src/adapter.ts",
34
34
  "./page": "./src/page.ts",
35
35
  "./internal/error-status": "./src/error-status-declared.ts",
36
+ "./internal/sse-frames": "./src/sse-frames.ts",
36
37
  "./outbound": "./src/outbound-subpath.ts",
37
38
  "./redis": "./src/redis-client.ts",
38
39
  "./render-node": "./src/render-node.ts",
@@ -54,6 +55,6 @@
54
55
  "test": "bun test"
55
56
  },
56
57
  "dependencies": {
57
- "@ultimat3/schema": "31.48.0"
58
+ "@ultimat3/schema": "31.50.0"
58
59
  }
59
60
  }
@@ -24,15 +24,22 @@ export interface ClientScopeIdOptions {
24
24
  /** Minted on first need when no `SESSION_SECRET` exists: stable per process, never per request. */
25
25
  let processKey: string | undefined;
26
26
 
27
- /** `''` for the anonymous actor; otherwise the principal AND who is really acting. */
27
+ /**
28
+ * `''` for the anonymous actor; otherwise the principal, who is really acting, and the tenant. One
29
+ * person in two orgs is two scopes: a page, a store or a queued write rendered under one org must
30
+ * never be reused under the other. No org leaves the material, and so the id, as it always was.
31
+ */
28
32
  export function clientScopeId(actor: Actor, options: ClientScopeIdOptions = {}): string {
29
33
  if (actor.kind === 'anonymous') return '';
30
- const material = JSON.stringify([
34
+ const principal = [
31
35
  actor.kind,
32
36
  actor.id,
33
37
  actor.onBehalfOf?.actorKind ?? null,
34
38
  actor.onBehalfOf?.actorId ?? null,
35
- ]);
39
+ ];
40
+ const material = JSON.stringify(
41
+ actor.orgId === undefined ? principal : [...principal, actor.orgId],
42
+ );
36
43
  return hmac('sha256', scopeKey(options), material, 'hex').slice(0, SCOPE_HEX_CHARS);
37
44
  }
38
45
 
@@ -11,35 +11,12 @@ import { settleAnswer } from './client-transport';
11
11
  import { notifyClientWrite } from './client-writes';
12
12
  import { RECORDS_HEADER } from './record-envelope';
13
13
  import { pageClient } from './record-sink';
14
- import { DATES_HEADER } from './wire-dates';
14
+ import { takeFrames } from './sse-frames';
15
+ import { DATES_HEADER, reviveWireDates } from './wire-dates';
15
16
 
16
17
  /** What `clientStream` reads: a write's request, never a raw body or a flight. */
17
18
  export type StreamRequest = StreamDispatch;
18
19
 
19
- interface Frame {
20
- readonly event: string;
21
- readonly data: string;
22
- }
23
-
24
- /** Splits a growing buffer into complete frames; the incomplete tail is handed back. */
25
- export function takeFrames(buffer: string): { readonly frames: Frame[]; readonly rest: string } {
26
- const frames: Frame[] = [];
27
- const blocks = buffer.split(/\r?\n\r?\n/);
28
- const rest = blocks.pop() ?? '';
29
- for (const block of blocks) {
30
- let event = 'message';
31
- const data: string[] = [];
32
- for (const line of block.split(/\r?\n/)) {
33
- // A `:` line is a comment — the server's keep-alive.
34
- if (line.startsWith(':')) continue;
35
- if (line.startsWith('event:')) event = line.slice(6).trim();
36
- else if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''));
37
- }
38
- if (data.length > 0) frames.push({ event, data: data.join('\n') });
39
- }
40
- return { frames, rest };
41
- }
42
-
43
20
  export async function* clientStream<TChunk = unknown, TOutput = unknown>(
44
21
  req: StreamRequest,
45
22
  ): AsyncGenerator<TChunk, TOutput, undefined> {
@@ -50,7 +27,7 @@ export async function* clientStream<TChunk = unknown, TOutput = unknown>(
50
27
  // `call()`'s answer, so it is settled exactly as `call()` settles it.
51
28
  if (!(response.headers.get('content-type') ?? '').startsWith('text/event-stream')) {
52
29
  const answer = {
53
- text: await response.text(),
30
+ text: await midBody(req.url, () => response.text()),
54
31
  enveloped: response.headers.get(RECORDS_HEADER) === '1',
55
32
  dates: response.headers.get(DATES_HEADER),
56
33
  };
@@ -65,13 +42,16 @@ export async function* clientStream<TChunk = unknown, TOutput = unknown>(
65
42
  let buffer = '';
66
43
  try {
67
44
  for (;;) {
68
- const { done, value } = await reader.read();
45
+ const { done, value } = await midBody(req.url, () => reader.read());
69
46
  buffer += decoder.decode(value, { stream: !done });
70
47
  const taken = takeFrames(done ? `${buffer}\n\n` : buffer);
71
48
  buffer = taken.rest;
72
49
  for (const frame of taken.frames) {
73
- if (frame.event === 'chunk') yield JSON.parse(frame.data) as TChunk;
74
- else if (frame.event === 'done') return JSON.parse(frame.data) as TOutput;
50
+ // Both frames name their instants on a `dates:` line, so a chunk is revived as `done` is.
51
+ const parsed = (): Promise<unknown> =>
52
+ midBody(req.url, () => reviveWireDates(JSON.parse(frame.data), frame.dates ?? null));
53
+ if (frame.event === 'chunk') yield (await parsed()) as TChunk;
54
+ else if (frame.event === 'done') return (await parsed()) as TOutput;
75
55
  else if (frame.event === 'error') {
76
56
  const status = problemStatus(frame.data);
77
57
  throw (
@@ -96,6 +76,28 @@ export async function* clientStream<TChunk = unknown, TOutput = unknown>(
96
76
  }
97
77
  }
98
78
 
79
+ /**
80
+ * A body the network cut (`TypeError`: `failure: 'network'`) or a frame that is not JSON
81
+ * (`SyntaxError`: `'body'`), coded and terminal — a write may already have landed. Anything else,
82
+ * an abort included, passes through: the same reading as `dispatch`'s.
83
+ */
84
+ async function midBody<T>(url: string, work: () => T | Promise<T>): Promise<T> {
85
+ try {
86
+ return await work();
87
+ } catch (error) {
88
+ const network = error instanceof TypeError;
89
+ if (!network && !(error instanceof SyntaxError)) throw error;
90
+ const failure = network ? 'network' : 'body';
91
+ throw transportFailed(
92
+ failure,
93
+ `${url}'s stream broke mid-body (${failure})`,
94
+ undefined,
95
+ { url },
96
+ error,
97
+ );
98
+ }
99
+ }
100
+
99
101
  function problemStatus(text: string): number {
100
102
  try {
101
103
  const status = (JSON.parse(text) as { status?: unknown }).status;
@@ -56,7 +56,12 @@ export async function clientTransport<T = unknown>(req: TransportRequest): Promi
56
56
  signal: req.signal,
57
57
  // A stream is read once, so a second attempt re-sends a body that is already spent —
58
58
  // and fails as the network would, until the attempts run out. One attempt, always.
59
- retry: req.rawBody instanceof ReadableStream ? ONCE : req.retry,
59
+ // An unkeyed write is ONCE too: re-sent after a gateway 5xx it may land twice — `rpc`'s
60
+ // rule, one layer down, so a direct caller is held to it as well.
61
+ retry:
62
+ req.rawBody instanceof ReadableStream || (!read && req.idempotencyKey === undefined)
63
+ ? ONCE
64
+ : req.retry,
60
65
  run: (signal) => dispatch(req, read, issued, signal),
61
66
  // `dispatch` makes every wire failure `X_CLIENT_TRANSPORT_FAILED`; a bare throw that
62
67
  // reaches the flight is a caller hook's, never the network's.
@@ -6,6 +6,7 @@ import {
6
6
  JOBS_CONCURRENCY_DEFAULT,
7
7
  JOBS_DEAD_RETENTION_MS_DEFAULT,
8
8
  JOBS_DONE_RETENTION_MS_DEFAULT,
9
+ JOBS_MAX_ATTEMPTS_DEFAULT,
9
10
  JOBS_OUTBOX_RETENTION_MS_DEFAULT,
10
11
  } from './config-jobs';
11
12
  import { DRAIN_DEADLINE_DEFAULT_MS, WORKER_RETIRE_DEFAULT_MS } from './drain-deadline';
@@ -46,7 +47,9 @@ export function configDefaults(): Omit<AppConfig, Sectioned> {
46
47
  jobs: {
47
48
  queues: ['default'],
48
49
  concurrency: JOBS_CONCURRENCY_DEFAULT,
49
- maxAttempts: 5,
50
+ // `@ultimat3/jobs`' own default retry reads the same constant: the key is the worker's default
51
+ // for a job that declares none, so the default moves no app that never set it.
52
+ maxAttempts: JOBS_MAX_ATTEMPTS_DEFAULT,
50
53
  backoff: 'exponential',
51
54
  visibilityTimeoutMs: 30_000,
52
55
  doneRetentionMs: JOBS_DONE_RETENTION_MS_DEFAULT,
@@ -14,6 +14,13 @@ import { isJsonObject } from './json-object';
14
14
  */
15
15
  export const JOBS_CONCURRENCY_DEFAULT = 8;
16
16
 
17
+ /**
18
+ * `jobs.maxAttempts` when no layer says, and `@ultimat3/jobs`' `DEFAULT_RETRY.attempts`: the
19
+ * worker's default for a job that declares no retry. ONE constant, so the config default and the
20
+ * policy a factory's job falls back to cannot drift apart.
21
+ */
22
+ export const JOBS_MAX_ATTEMPTS_DEFAULT = 3;
23
+
17
24
  /**
18
25
  * `jobs.doneRetentionMs` when no layer says: how long a `done` row and its step records are kept
19
26
  * before the boot's hourly purge deletes them. Two weeks — every incident is read inside it, and
package/src/config-pwa.ts CHANGED
@@ -10,8 +10,12 @@
10
10
  // `x dev`, saw a served app and shipped it would meet the missing title in CI. Two checks, two
11
11
  // subjects (a config file, and a function argument a library caller supplies directly).
12
12
 
13
+ import { booleanIssue } from './config-shape';
13
14
  import { describeValue } from './error-render';
14
15
 
16
+ /** The block's three switches, each refused unless a boolean. */
17
+ const PWA_SWITCHES = ['enabled', 'backgroundSync', 'push'] as const;
18
+
15
19
  /**
16
20
  * `installPrompt` was removed 2026-08, same rule: `@ultimat3/pwa`'s `installController` is
17
21
  * real and complete, nothing ever threaded the flag into it, and both tracked apps plus every
@@ -189,7 +193,13 @@ export const PWA_FIX =
189
193
  * object crosses into the framework, so every value here is `unknown` however the interface types it.
190
194
  */
191
195
  export function pwaIssues(pwa: PwaConfig, issues: string[]): boolean {
192
- if (!pwa.enabled) return false;
196
+ // `typeof`, never truthiness: `enabled: 'false'` turned the PWA ON. A switch's own message is its
197
+ // remedy, so these are pushed before `before` and never earn the install-block fix line.
198
+ for (const key of PWA_SWITCHES) {
199
+ const issue = booleanIssue(`pwa.${key}`, pwa[key]);
200
+ if (issue !== undefined) issues.push(issue);
201
+ }
202
+ if (pwa.enabled !== true) return false;
193
203
  const before = issues.length;
194
204
  const { name, colors } = pwa;
195
205
  if (typeof name !== 'string' || name.trim() === '') {
@@ -285,10 +295,11 @@ const isVapidSubject = (value: unknown): boolean => {
285
295
  * emits no worker for a push handler to live in.
286
296
  */
287
297
  export function pwaPushIssues(pwa: PwaConfig, issues: string[]): boolean {
288
- if (!pwa.enabled) return false;
298
+ if (pwa.enabled !== true) return false;
289
299
  const before = issues.length;
290
300
  const vapid: unknown = pwa.vapid;
291
- if (!pwa.push) {
301
+ // A non-boolean `push` is `pwaIssues`' refusal already; here it is read as off.
302
+ if (pwa.push !== true) {
292
303
  if (vapid !== undefined) {
293
304
  issues.push('pwa.vapid is set while pwa.push is false, so nothing reads it');
294
305
  }
@@ -337,19 +348,42 @@ const absolute = (value: unknown): boolean => typeof value === 'string' && value
337
348
  const texts = (value: unknown): readonly unknown[] =>
338
349
  value !== null && typeof value === 'object' ? Object.values(value) : [value];
339
350
 
351
+ const isTextList = (value: unknown): boolean =>
352
+ Array.isArray(value) && (value as readonly unknown[]).every((entry) => typeof entry === 'string');
353
+
340
354
  /** The optional manifest members, screened for the one mistake a browser drops them for silently. */
341
355
  function manifestIssues(pwa: PwaConfig, issues: string[]): void {
342
356
  if (pwa.id !== undefined && !absolute(pwa.id)) {
343
357
  issues.push(`pwa.id must be an absolute path like "/", and is ${describeValue(pwa.id)}`);
344
358
  }
345
- for (const [i, shortcut] of (pwa.shortcuts ?? []).entries()) {
346
- if (!absolute(shortcut?.url)) {
347
- issues.push(
348
- `pwa.shortcuts[${i}].url must be an absolute path, and is ${describeValue(shortcut?.url)}`,
349
- );
359
+ const categories: unknown = pwa.categories;
360
+ if (categories !== undefined && !isTextList(categories)) {
361
+ issues.push(`pwa.categories must be a list of strings, not ${describeValue(categories)}`);
362
+ }
363
+ // Not a list at all is the structure check's refusal already; here, an entry of the wrong kind.
364
+ const neverCache: unknown = pwa.offline?.neverCache;
365
+ if (Array.isArray(neverCache) && !isTextList(neverCache)) {
366
+ issues.push(`pwa.offline.neverCache must list path strings, not ${describeValue(neverCache)}`);
367
+ }
368
+ const shortcuts: unknown = pwa.shortcuts ?? [];
369
+ const screenshots: unknown = pwa.screenshots ?? [];
370
+ // A list first: `shortcuts: 'x'` reached `.entries()` as a native TypeError.
371
+ if (!Array.isArray(shortcuts)) {
372
+ issues.push(`pwa.shortcuts must be a list, not ${describeValue(shortcuts)}`);
373
+ } else {
374
+ for (const [i, shortcut] of (shortcuts as readonly (PwaShortcut | undefined)[]).entries()) {
375
+ if (!absolute(shortcut?.url)) {
376
+ issues.push(
377
+ `pwa.shortcuts[${i}].url must be an absolute path, and is ${describeValue(shortcut?.url)}`,
378
+ );
379
+ }
350
380
  }
351
381
  }
352
- for (const [i, screenshot] of (pwa.screenshots ?? []).entries()) {
382
+ if (!Array.isArray(screenshots)) {
383
+ issues.push(`pwa.screenshots must be a list, not ${describeValue(screenshots)}`);
384
+ return;
385
+ }
386
+ for (const [i, screenshot] of (screenshots as readonly (PwaScreenshot | undefined)[]).entries()) {
353
387
  if (!texts(screenshot?.src).every(absolute)) {
354
388
  issues.push(
355
389
  `pwa.screenshots[${i}].src must be an absolute path (or one per locale), and is ${describeValue(screenshot?.src)}`,
@@ -161,7 +161,11 @@ function originIssue(origin: string): string | undefined {
161
161
  }
162
162
 
163
163
  /** A favicon names one SVG under the app's site assets, never an arbitrary URL or path. */
164
- function faviconIssue(favicon: string): string | undefined {
164
+ function faviconIssue(favicon: unknown): string | undefined {
165
+ // The type first: an untyped config's `favicon: 42` reached `.startsWith` as a native TypeError.
166
+ if (typeof favicon !== 'string') {
167
+ return `site.favicon must be a site asset path like "assets/favicon.svg", not ${describeValue(favicon)}`;
168
+ }
165
169
  if (!favicon.startsWith('assets/')) {
166
170
  return `site.favicon "${favicon}" must be a site asset path starting with assets/`;
167
171
  }
@@ -182,7 +186,7 @@ export function siteIssues(config: SiteSections, issues: string[]): void {
182
186
  const issue = originIssue(origin);
183
187
  if (issue !== undefined) issues.push(issue);
184
188
  }
185
- const favicon = config.site.favicon;
189
+ const favicon: unknown = config.site.favicon;
186
190
  if (favicon !== undefined) {
187
191
  const issue = faviconIssue(favicon);
188
192
  if (issue !== undefined) issues.push(issue);
package/src/config.ts CHANGED
@@ -108,6 +108,7 @@ const DATABASE_DRIVERS = ['postgres'] as const;
108
108
 
109
109
  export interface DatabaseConfig {
110
110
  readonly driver: (typeof DATABASE_DRIVERS)[number];
111
+ /** `true` requires TLS when the URL states no `sslmode`; a URL's own `sslmode` is never overridden. */
111
112
  readonly ssl: boolean;
112
113
  /**
113
114
  * Every `tenant:` table carries a forced policy (`x db gen`) the serving role must be subject to
@@ -137,6 +138,7 @@ export interface DatabaseConfig {
137
138
  * exist is `cache.tiers` and only that; a rung the environment cannot supply refuses the boot.
138
139
  */
139
140
  export interface CacheConfig {
141
+ /** At least 1: the rungs refuse a lease of no length, so 0 is refused here rather than at boot. */
140
142
  readonly defaultTtlMs: number;
141
143
  /** Order is fixed by `CACHE_TIERS`; listing order here selects rungs, it does not rank them. */
142
144
  readonly tiers: readonly CacheTierName[];
@@ -159,15 +161,17 @@ export interface JobsConfig {
159
161
  */
160
162
  readonly queues: readonly string[];
161
163
  /**
162
- * Slots per worker process: one number for every queue it serves, or a table per queue
163
- * (`{ banks: 4, 'banks-long': 2 }`, a queue it does not name at `JOBS_CONCURRENCY_DEFAULT`).
164
+ * Slots per worker CONTAINER: one number for every queue it serves, or a table per queue
165
+ * (`{ banks: 4 }`; one it does not name at `JOBS_CONCURRENCY_DEFAULT`). Over N processes the
166
+ * runtime gives the indices >= total 0 slots, then `childShare`s the rest: `1` stays serial.
164
167
  */
165
168
  readonly concurrency: JobsConcurrency;
166
169
  /**
167
- * Runs one worker process holds at once across every queue it serves (`jobWorker`'s
168
- * `maxInFlight`), the per-queue `concurrency` still bounding each under it. Unset: no process cap.
170
+ * Runs one worker CONTAINER holds at once across its queues (`jobWorker`'s `maxInFlight`, split
171
+ * across its processes as `concurrency` is), each queue's `concurrency` under it. Unset: no cap.
169
172
  */
170
173
  readonly maxInFlight?: number | undefined;
174
+ /** With `backoff`: the retry of a job that declares none. A job's own `retry` wins. */
171
175
  readonly maxAttempts: number;
172
176
  readonly backoff: (typeof JOB_BACKOFFS)[number];
173
177
  readonly visibilityTimeoutMs: number;
@@ -308,7 +312,7 @@ function validate(config: AppConfig): void {
308
312
  config.jobs[key] === undefined ? undefined : countIssue(`jobs.${key}`, config.jobs[key], 1),
309
313
  ),
310
314
  oneOfIssue('jobs.backoff', config.jobs.backoff, JOB_BACKOFFS),
311
- countIssue('cache.defaultTtlMs', config.cache.defaultTtlMs, 0),
315
+ countIssue('cache.defaultTtlMs', config.cache.defaultTtlMs, 1),
312
316
  oneOfIssue('database.driver', config.database.driver, DATABASE_DRIVERS),
313
317
  booleanIssue('database.ssl', config.database.ssl),
314
318
  booleanIssue('database.rowSecurity', config.database.rowSecurity),
@@ -33,6 +33,15 @@ export const WORKER_DRAIN_DEADLINE_MAX_MS = 86_400_000;
33
33
  */
34
34
  export const WORKER_RETIRE_DEFAULT_MS = 3_600_000;
35
35
 
36
+ /**
37
+ * The slice of a `deadlineMs` drain the in-flight wait never spends, kept for the `inflight` and
38
+ * `close` hooks behind it: a fifth, at most 2 s. The lifecycle hands its end to every hook as
39
+ * `ShutdownReason.inflightUntil`; `x verify`'s `X_JOB_OUTLASTS_DRAIN` grades against the same one.
40
+ */
41
+ export function laterHooksReserveMs(deadlineMs: number): number {
42
+ return Math.min(2_000, Math.floor(deadlineMs / 5));
43
+ }
44
+
36
45
  const DEADLINE_KEY = 'drain.deadlineMs';
37
46
  const WORKER_DEADLINE_KEY = 'drain.workerDeadlineMs';
38
47
  const WORKER_RETIRE_KEY = 'drain.workerRetireMs';