@ultimat3/core 31.47.1 → 31.49.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 +3 -2
- package/README.md +4 -2
- package/package.json +3 -2
- package/src/client-stream.ts +31 -29
- package/src/client-transport.ts +6 -1
- package/src/config-defaults.ts +4 -1
- package/src/config-jobs.ts +7 -0
- package/src/config-pwa.ts +43 -9
- package/src/config-site.ts +6 -2
- package/src/config.ts +9 -5
- package/src/drain-deadline.ts +9 -0
- package/src/env.ts +73 -6
- package/src/error-reporter-sentry.ts +71 -17
- package/src/framework-env.ts +9 -1
- package/src/index.ts +4 -0
- package/src/lifecycle-types.ts +8 -0
- package/src/lifecycle.ts +19 -4
- package/src/locale-direction.ts +23 -5
- package/src/logger-redact.ts +5 -1
- package/src/logger.ts +24 -2
- package/src/outbound-attempt.ts +2 -2
- package/src/outbound-hops.ts +8 -0
- package/src/outbound.ts +3 -1
- package/src/shared-port.ts +69 -0
- package/src/sse-frames.ts +42 -0
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`),
|
|
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
|
|
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` |
|
|
@@ -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.
|
|
3
|
+
"version": "31.49.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.
|
|
58
|
+
"@ultimat3/schema": "31.49.0"
|
|
58
59
|
}
|
|
59
60
|
}
|
package/src/client-stream.ts
CHANGED
|
@@ -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 {
|
|
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
|
-
|
|
74
|
-
|
|
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;
|
package/src/client-transport.ts
CHANGED
|
@@ -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
|
-
|
|
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.
|
package/src/config-defaults.ts
CHANGED
|
@@ -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
|
-
|
|
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,
|
package/src/config-jobs.ts
CHANGED
|
@@ -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
|
-
|
|
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 (
|
|
298
|
+
if (pwa.enabled !== true) return false;
|
|
289
299
|
const before = issues.length;
|
|
290
300
|
const vapid: unknown = pwa.vapid;
|
|
291
|
-
|
|
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
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
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
|
-
|
|
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)}`,
|
package/src/config-site.ts
CHANGED
|
@@ -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:
|
|
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
|
|
163
|
-
* (`{ banks: 4
|
|
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
|
|
168
|
-
* `
|
|
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,
|
|
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),
|
package/src/drain-deadline.ts
CHANGED
|
@@ -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';
|
package/src/env.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// discover six missing variables.
|
|
4
4
|
|
|
5
5
|
import { numeric } from '@ultimat3/schema';
|
|
6
|
+
import { tryResolveEnvironment } from './environment';
|
|
6
7
|
import { describeValue, renderFixShellArg } from './error-render';
|
|
7
8
|
import { EnvMissingError } from './errors';
|
|
8
9
|
import { isRedactedKey, REDACTED, redactKeys } from './logger';
|
|
@@ -161,6 +162,71 @@ function parseValue(decl: EnvVarDecl, raw: string): { ok: true; value: unknown }
|
|
|
161
162
|
}
|
|
162
163
|
}
|
|
163
164
|
|
|
165
|
+
type EnvSource = Readonly<Record<string, string | undefined>>;
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* The dotenv file a missing key is added to, for the environment `source` names. In development
|
|
169
|
+
* and test it is the per-box file Bun loads last and the scaffold's setup writes
|
|
170
|
+
* (`.env.<environment>.local`) — never `.env`, which no scaffold file is. A deploy
|
|
171
|
+
* (`staging`/`production`, or an `ULTIMATE_ENV` that is no environment: fail closed) reads
|
|
172
|
+
* `.env.production`, the file `x env init --production` writes and `x deploy --method compose` reads.
|
|
173
|
+
*/
|
|
174
|
+
function envFileFor(source: EnvSource): string {
|
|
175
|
+
const environment = tryResolveEnvironment({ env: source });
|
|
176
|
+
return environment === 'development' || environment === 'test'
|
|
177
|
+
? `.env.${environment}.local`
|
|
178
|
+
: '.env.production';
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const keyArg = (key: string): string => renderFixShellArg(key, '<KEY>');
|
|
182
|
+
|
|
183
|
+
/** `grep` over every dotenv file: a malformed value is in whichever one set it. */
|
|
184
|
+
const findLines = (keys: readonly string[]): string =>
|
|
185
|
+
`grep -n ${keys.map((key) => `-e '^${keyArg(key)}='`).join(' ')} .env*`;
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* ONE fix for the whole throw, and never `x env check`: that command prints this same error and
|
|
189
|
+
* this same line. Every missing key gets the line to add, in the file this environment loads; a
|
|
190
|
+
* malformed one is found where it is set. A key whose declaration carries its own `fix` keeps it:
|
|
191
|
+
* the command leads (generated, else the first declared), and every other declared fix follows,
|
|
192
|
+
* named by its key, so one refusal still says how to repair every key.
|
|
193
|
+
*/
|
|
194
|
+
function fixFor(schema: EnvSchema, issues: readonly EnvIssue[], source: EnvSource): string {
|
|
195
|
+
const declared = issues.flatMap((issue) => {
|
|
196
|
+
const fix = schema[issue.key]?.fix;
|
|
197
|
+
return fix === undefined ? [] : [{ key: issue.key, fix }];
|
|
198
|
+
});
|
|
199
|
+
const lead = generatedFix(schema, issues, source) ?? declared.shift()?.fix;
|
|
200
|
+
const head = lead ?? findLines(issues.map((issue) => issue.key));
|
|
201
|
+
if (declared.length === 0) return head;
|
|
202
|
+
const rest = declared.map(({ key, fix }) => `${key}: ${fix}`).join('; ');
|
|
203
|
+
return `${head}${head.includes('#') ? '; then' : ' # then'}, per key — ${rest}`;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** The command for the keys with no declared fix, or `undefined` when every key declares one. */
|
|
207
|
+
function generatedFix(
|
|
208
|
+
schema: EnvSchema,
|
|
209
|
+
issues: readonly EnvIssue[],
|
|
210
|
+
source: EnvSource,
|
|
211
|
+
): string | undefined {
|
|
212
|
+
const generated = issues.filter((issue) => schema[issue.key]?.fix === undefined);
|
|
213
|
+
const missing = generated.filter((issue) => issue.reason === 'missing');
|
|
214
|
+
const invalid = generated.filter((issue) => issue.reason === 'invalid');
|
|
215
|
+
const malformed = invalid.map((issue) => `${issue.key} (${issue.expected})`).join(', ');
|
|
216
|
+
if (missing.length === 0) {
|
|
217
|
+
if (invalid.length === 0) return undefined;
|
|
218
|
+
return `${findLines(invalid.map((issue) => issue.key))} # each line to correct: ${malformed}`;
|
|
219
|
+
}
|
|
220
|
+
const lines = missing.map((issue) => `'${keyArg(issue.key)}=<value>'`);
|
|
221
|
+
const write = lines.length === 1 ? `echo ${lines[0]}` : `printf '%s\\n' ${lines.join(' ')}`;
|
|
222
|
+
const expected = missing.map((issue) => `${issue.key}: ${issue.expected}`).join('; ');
|
|
223
|
+
const also =
|
|
224
|
+
invalid.length === 0
|
|
225
|
+
? ''
|
|
226
|
+
: `; also malformed, where ${findLines(invalid.map((issue) => issue.key))} finds them: ${malformed}`;
|
|
227
|
+
return `${write} >> ${envFileFor(source)} # ${expected}${also}`;
|
|
228
|
+
}
|
|
229
|
+
|
|
164
230
|
/** Validate without throwing — this is what `x env check --json` prints. */
|
|
165
231
|
export function checkEnv(schema: EnvSchema, options?: EnvOptions): EnvCheckReport {
|
|
166
232
|
const source = options?.env ?? (process.env as Record<string, string | undefined>);
|
|
@@ -183,7 +249,7 @@ export function checkEnv(schema: EnvSchema, options?: EnvOptions): EnvCheckRepor
|
|
|
183
249
|
received: undefined,
|
|
184
250
|
fix:
|
|
185
251
|
decl.fix ??
|
|
186
|
-
`
|
|
252
|
+
`echo '${keyArg(key)}=<value>' >> ${envFileFor(source)} # <value>: ${expectation(decl)}`,
|
|
187
253
|
});
|
|
188
254
|
} else {
|
|
189
255
|
values[key] = undefined;
|
|
@@ -200,9 +266,7 @@ export function checkEnv(schema: EnvSchema, options?: EnvOptions): EnvCheckRepor
|
|
|
200
266
|
reason: 'invalid',
|
|
201
267
|
expected: expectation(decl),
|
|
202
268
|
received: decl.secret === true ? '***' : raw,
|
|
203
|
-
fix:
|
|
204
|
-
decl.fix ??
|
|
205
|
-
`grep -n '^${renderFixShellArg(key, '<KEY>')}=' .env # the line to set to ${expectation(decl)}`,
|
|
269
|
+
fix: decl.fix ?? `${findLines([key])} # the line to set to ${expectation(decl)}`,
|
|
206
270
|
});
|
|
207
271
|
}
|
|
208
272
|
|
|
@@ -241,10 +305,13 @@ export function defineEnv<const S extends EnvSchema>(schema: S, options?: EnvOpt
|
|
|
241
305
|
: `${issue.key} is not ${issue.expected} (received ${issue.received ?? 'undefined'})`,
|
|
242
306
|
)
|
|
243
307
|
.join('; ');
|
|
244
|
-
const keys = report.issues.map((issue) => issue.key).join(' ');
|
|
245
308
|
throw new EnvMissingError({
|
|
246
309
|
cause,
|
|
247
|
-
fix:
|
|
310
|
+
fix: fixFor(
|
|
311
|
+
schema,
|
|
312
|
+
report.issues,
|
|
313
|
+
options?.env ?? (process.env as Record<string, string | undefined>),
|
|
314
|
+
),
|
|
248
315
|
meta: { issues: described },
|
|
249
316
|
});
|
|
250
317
|
}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
// Single responsibility: one `ErrorReporter` that speaks the Sentry ENVELOPE wire format. A
|
|
2
|
-
// serialisation, not a vendor (axiom 7,
|
|
3
|
-
//
|
|
4
|
-
//
|
|
2
|
+
// serialisation, not a vendor (axiom 7, as `metrics-text.ts` is to Prometheus): several
|
|
3
|
+
// self-hostable monitors ingest it. Nothing here names a host, a project or an organisation — the
|
|
4
|
+
// DSN is the app's own typed env, passed in at wiring time.
|
|
5
5
|
|
|
6
|
+
import { retryAfterSecondsOf } from './client-retry-after';
|
|
7
|
+
import { systemClock } from './clock';
|
|
6
8
|
import { monitorFingerprint } from './error-fingerprint';
|
|
7
|
-
import { renderThrowable } from './error-render';
|
|
9
|
+
import { describeValue, renderThrowable } from './error-render';
|
|
8
10
|
import type { ErrorReport, ErrorReporter, ErrorSeverity } from './error-reporter';
|
|
9
11
|
import {
|
|
10
12
|
admitted,
|
|
@@ -50,10 +52,11 @@ export function parseSentryDsn(dsn: string): SentryDsn {
|
|
|
50
52
|
try {
|
|
51
53
|
url = new URL(dsn);
|
|
52
54
|
} catch {
|
|
55
|
+
// Never echoed: a legacy `public:secret@` DSN carries a credential, as an OTLP header does.
|
|
53
56
|
throw new ErrorReporterDsnInvalidError({
|
|
54
|
-
cause: `
|
|
57
|
+
cause: `the DSN (${describeValue(dsn)}) is not a URL`,
|
|
55
58
|
fix: DSN_FIX,
|
|
56
|
-
meta: { dsn },
|
|
59
|
+
meta: { dsn: describeValue(dsn) },
|
|
57
60
|
});
|
|
58
61
|
}
|
|
59
62
|
const segments = url.pathname.split('/').filter((part) => part.length > 0);
|
|
@@ -63,10 +66,15 @@ export function parseSentryDsn(dsn: string): SentryDsn {
|
|
|
63
66
|
url.username === '' ||
|
|
64
67
|
projectId === undefined
|
|
65
68
|
) {
|
|
69
|
+
// The userinfo dropped, as in the cause: the key and any legacy secret stay out of `meta`.
|
|
70
|
+
// Only an HTTP URL HAS a userinfo to drop: a scheme-less `key:secret@host/1` parses as scheme
|
|
71
|
+
// `key:` over an opaque path `secret@host/1`, so it is described, never spelled.
|
|
72
|
+
const http = url.protocol === 'https:' || url.protocol === 'http:';
|
|
73
|
+
const where = http ? `${url.protocol}//${url.host}${url.pathname}` : describeValue(dsn);
|
|
66
74
|
throw new ErrorReporterDsnInvalidError({
|
|
67
|
-
cause: `"${
|
|
75
|
+
cause: `"${where}" has no publicKey, no projectId or a non-HTTP scheme`,
|
|
68
76
|
fix: DSN_FIX,
|
|
69
|
-
meta: { dsn },
|
|
77
|
+
meta: { dsn: where },
|
|
70
78
|
});
|
|
71
79
|
}
|
|
72
80
|
const prefix = segments.length === 0 ? '' : `/${segments.join('/')}`;
|
|
@@ -240,6 +248,59 @@ export function isLocalErrorSink(reporter: ErrorReporter): boolean {
|
|
|
240
248
|
return local.has(reporter);
|
|
241
249
|
}
|
|
242
250
|
|
|
251
|
+
// Delivery READS the monitor's answer: a refusal said once per status (a revoked key is a monitor
|
|
252
|
+
// never connected), a 429's pause honoured so an error storm does not hammer it, every body released.
|
|
253
|
+
|
|
254
|
+
/** A 429 that states no delay: the pause Sentry's own SDKs take. */
|
|
255
|
+
const UNSTATED_PAUSE_SECONDS = 60;
|
|
256
|
+
|
|
257
|
+
/** One envelope POST, fire-and-forget: never awaited, never thrown. */
|
|
258
|
+
type EnvelopeSend = (init: RequestInit) => void;
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* `url` is the envelope endpoint `parseSentryDsn` derived — origin, path and project id, never the
|
|
262
|
+
* key — so it is safe in a log line. The pause reads real monotonic time: it is a wait, not a date.
|
|
263
|
+
*/
|
|
264
|
+
function envelopeSender(send: typeof globalThis.fetch, url: string): EnvelopeSend {
|
|
265
|
+
const warned = new Set<number>();
|
|
266
|
+
let pausedUntil = Number.NEGATIVE_INFINITY;
|
|
267
|
+
const answered = (answer: unknown): void => {
|
|
268
|
+
// A real `fetch` resolves a `Response`; anything else is a stub with nothing to read.
|
|
269
|
+
if (!(answer instanceof Response)) return;
|
|
270
|
+
void answer.body?.cancel().catch(() => undefined);
|
|
271
|
+
if (answer.ok) return;
|
|
272
|
+
let retryAfterSeconds: number | undefined;
|
|
273
|
+
if (answer.status === 429) {
|
|
274
|
+
const headers = answer.headers;
|
|
275
|
+
retryAfterSeconds =
|
|
276
|
+
retryAfterSecondsOf(headers.get('retry-after'), headers.get('date')) ??
|
|
277
|
+
UNSTATED_PAUSE_SECONDS;
|
|
278
|
+
pausedUntil = systemClock.monotonic() + retryAfterSeconds * 1000;
|
|
279
|
+
}
|
|
280
|
+
if (warned.has(answer.status)) return;
|
|
281
|
+
warned.add(answer.status);
|
|
282
|
+
logger.warn('error reporter delivery refused; events are being dropped', {
|
|
283
|
+
url,
|
|
284
|
+
status: answer.status,
|
|
285
|
+
...(retryAfterSeconds === undefined ? {} : { retryAfterSeconds }),
|
|
286
|
+
});
|
|
287
|
+
};
|
|
288
|
+
return (init) => {
|
|
289
|
+
if (systemClock.monotonic() < pausedUntil) return;
|
|
290
|
+
// `.catch` after `.then`: a throw reading the answer is logged too, never an unhandled rejection.
|
|
291
|
+
void send(url, init)
|
|
292
|
+
.then(answered)
|
|
293
|
+
.catch((failure: unknown) => {
|
|
294
|
+
logger.warn('error reporter delivery failed', {
|
|
295
|
+
url,
|
|
296
|
+
// `renderThrowable`: this is the handler that keeps a monitor outage from becoming a
|
|
297
|
+
// second failure, so rendering the rejection may not raise one of its own.
|
|
298
|
+
error: renderThrowable(failure),
|
|
299
|
+
});
|
|
300
|
+
});
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
|
|
243
304
|
/**
|
|
244
305
|
* Fire-and-forget on purpose. A report is not the request, and awaiting the monitor would add its
|
|
245
306
|
* latency — and its outages — to every failure the app already knows how to answer.
|
|
@@ -247,7 +308,7 @@ export function isLocalErrorSink(reporter: ErrorReporter): boolean {
|
|
|
247
308
|
export function sentryErrorReporter(options: SentryReporterOptions): ErrorReporter {
|
|
248
309
|
const dsn = parseSentryDsn(options.dsn);
|
|
249
310
|
const rate = screenSampleRate(options.sampleRate);
|
|
250
|
-
const
|
|
311
|
+
const deliver = envelopeSender(options.fetch ?? globalThis.fetch, dsn.envelopeUrl);
|
|
251
312
|
const client = options.clientName ?? 'ultimate';
|
|
252
313
|
const auth = `Sentry sentry_version=7, sentry_client=${client}, sentry_key=${dsn.publicKey}`;
|
|
253
314
|
const reporter: ErrorReporter = {
|
|
@@ -273,17 +334,10 @@ export function sentryErrorReporter(options: SentryReporterOptions): ErrorReport
|
|
|
273
334
|
});
|
|
274
335
|
return;
|
|
275
336
|
}
|
|
276
|
-
|
|
337
|
+
deliver({
|
|
277
338
|
method: 'POST',
|
|
278
339
|
headers: { 'content-type': 'application/x-sentry-envelope', 'x-sentry-auth': auth },
|
|
279
340
|
body,
|
|
280
|
-
}).catch((failure: unknown) => {
|
|
281
|
-
logger.warn('error reporter delivery failed', {
|
|
282
|
-
url: dsn.envelopeUrl,
|
|
283
|
-
// `renderThrowable`: this is the `.catch` that keeps a monitor outage from becoming a
|
|
284
|
-
// second failure, so rendering the rejection may not raise one of its own.
|
|
285
|
-
error: renderThrowable(failure),
|
|
286
|
-
});
|
|
287
341
|
});
|
|
288
342
|
},
|
|
289
343
|
};
|
package/src/framework-env.ts
CHANGED
|
@@ -55,15 +55,23 @@ export const FRAMEWORK_ENV: readonly FrameworkEnvName[] = [
|
|
|
55
55
|
...contract('cli', 'S3_ENDPOINT', 'S3_BUCKET', 'S3_REGION', 'S3_FORCE_PATH_STYLE'),
|
|
56
56
|
...contract('cli', 'SCRAPE_CDP_URL', 'TLS_CERT', 'TLS_KEY'),
|
|
57
57
|
...contract('cli', 'ULTIMATE_SCHEMA_WAIT_MS'),
|
|
58
|
+
// How many processes one production container runs (`auto` or a count); `x dev` is always one.
|
|
59
|
+
...contract('cli', 'ULTIMATE_PROCESSES'),
|
|
60
|
+
// libpq's own TLS mode: stated, it keeps `database.ssl` from adding `sslmode=require`.
|
|
61
|
+
...contract('cli', 'PGSSLMODE'),
|
|
58
62
|
...toggles('cli', 'OTEL_SDK_DISABLED'),
|
|
59
63
|
...internal('cli', 'ULTIMATE_SEED_TIER', 'ULTIMATE_STATE_DIR', 'ULTIMATE_BUILD_CAPTURE'),
|
|
64
|
+
...internal('cli', 'ULTIMATE_TASK_RUN'),
|
|
60
65
|
...internal('cli', 'ULTIMATE_DEV_CHILD', 'ULTIMATE_DEV_SUPERVISOR_PID', 'X_ENV'),
|
|
61
66
|
...internal('cli', 'ULTIMATE_KEEP_GLOBAL_CLI', 'ULTIMATE_VERIFY_STEP', 'CI_RUNNER'),
|
|
62
67
|
...host('cli', 'CI', 'GITHUB_SHA', 'GITHUB_BASE_REF', 'EDITOR', 'VISUAL', 'USERPROFILE'),
|
|
68
|
+
...host('cli', 'PATH', 'GOMAXPROCS', 'RAYON_NUM_THREADS'),
|
|
63
69
|
...contract('core', 'ULTIMATE_ENV', 'ROLE', 'BUILD_ID', 'APP_VERSION', 'LOG_LEVEL'),
|
|
64
70
|
...contract('core', 'ULTIMATE_CURSOR_SECRET', 'ULTIMATE_SECRETS_KEY'),
|
|
65
71
|
...contract('core', 'ULTIMATE_SECRETS_RETIRED_KEYS', 'METRICS_INTERVAL_MS'),
|
|
66
72
|
...contract('core', 'REDIS_URL', 'VALKEY_URL'),
|
|
73
|
+
// `<index>/<count>`, written by the production supervisor into each child (`shared-port.ts`).
|
|
74
|
+
...internal('core', 'ULTIMATE_CHILD'),
|
|
67
75
|
...contract('core', 'OTEL_EXPORTER_OTLP_ENDPOINT', 'OTEL_EXPORTER_OTLP_HEADERS'),
|
|
68
76
|
...contract('core', 'OTEL_EXPORTER_OTLP_PROTOCOL', 'OTEL_TRACES_SAMPLER'),
|
|
69
77
|
...contract('core', 'OTEL_TRACES_SAMPLER_ARG'),
|
|
@@ -81,7 +89,7 @@ export const FRAMEWORK_ENV: readonly FrameworkEnvName[] = [
|
|
|
81
89
|
...contract('db', 'DATABASE_REPLICA_URL', 'DB_RETRY'),
|
|
82
90
|
...internal('db', 'ROLLBACK_ALLOW_DESTRUCTIVE'),
|
|
83
91
|
...host('jobs', 'HOSTNAME'),
|
|
84
|
-
...contract('mail', 'MAIL_FROM', 'MAIL_POOL_SIZE'),
|
|
92
|
+
...contract('mail', 'MAIL_FROM', 'MAIL_POOL_SIZE', 'MAIL_TIMEOUT_MS'),
|
|
85
93
|
...contract('mail', 'RESEND_API_KEY', 'RESEND_WEBHOOK_SECRET', 'SMTP_URL'),
|
|
86
94
|
...contract('mail', 'SES_ACCESS_KEY_ID', 'SES_SECRET_ACCESS_KEY', 'SES_SESSION_TOKEN'),
|
|
87
95
|
...contract('mail', 'SES_REGION', 'SES_ENDPOINT', 'SES_CONFIGURATION_SET'),
|
package/src/index.ts
CHANGED
|
@@ -210,6 +210,7 @@ export {
|
|
|
210
210
|
JOBS_CONCURRENCY_DEFAULT,
|
|
211
211
|
JOBS_DEAD_RETENTION_MS_DEFAULT,
|
|
212
212
|
JOBS_DONE_RETENTION_MS_DEFAULT,
|
|
213
|
+
JOBS_MAX_ATTEMPTS_DEFAULT,
|
|
213
214
|
JOBS_OUTBOX_RETENTION_MS_DEFAULT,
|
|
214
215
|
type JobsConcurrency,
|
|
215
216
|
} from './config-jobs';
|
|
@@ -331,6 +332,7 @@ export {
|
|
|
331
332
|
} from './dev-secrets';
|
|
332
333
|
export {
|
|
333
334
|
DRAIN_DEADLINE_DEFAULT_MS,
|
|
335
|
+
laterHooksReserveMs,
|
|
334
336
|
WORKER_DRAIN_DEADLINE_MAX_MS,
|
|
335
337
|
WORKER_RETIRE_DEFAULT_MS,
|
|
336
338
|
} from './drain-deadline';
|
|
@@ -994,6 +996,8 @@ export {
|
|
|
994
996
|
} from './service';
|
|
995
997
|
export { onSessionLost, sessionIsLost } from './session-lost';
|
|
996
998
|
export { isSessionRefusal, isSessionRefusalCode } from './session-refusal';
|
|
999
|
+
export type { SupervisedChild } from './shared-port';
|
|
1000
|
+
export { childShare, sharedPortOption, supervisedChild } from './shared-port';
|
|
997
1001
|
export type { FlightJoin, Scheduler, SingleFlight, SingleFlightOptions } from './single-flight';
|
|
998
1002
|
export { singleFlight } from './single-flight';
|
|
999
1003
|
export { ambientClock, noWaitClock } from './sleep-clock';
|
package/src/lifecycle-types.ts
CHANGED
|
@@ -30,6 +30,14 @@ export interface ShutdownReason {
|
|
|
30
30
|
* `waitForIdle` went on sleeping on a real `setTimeout`. `clock` still owns `uptimeMs`.
|
|
31
31
|
*/
|
|
32
32
|
readonly deadlineAt: number;
|
|
33
|
+
/**
|
|
34
|
+
* Real monotonic ms at which the drain stops waiting for in-flight work (`beginWork()`), at or
|
|
35
|
+
* before `deadlineAt`: the rest of the budget is the `inflight`/`close` hooks' reserve. The ONE
|
|
36
|
+
* owner of that instant — a role that cuts its own work short (the jobs worker's cut-off)
|
|
37
|
+
* measures back from it, so the cut work has unwound before the wait ends. Absent on a reason
|
|
38
|
+
* built outside `drain()`: read it as `deadlineAt`.
|
|
39
|
+
*/
|
|
40
|
+
readonly inflightUntil?: number | undefined;
|
|
33
41
|
}
|
|
34
42
|
|
|
35
43
|
export type ShutdownHook = (reason: ShutdownReason) => void | Promise<void>;
|
package/src/lifecycle.ts
CHANGED
|
@@ -6,7 +6,7 @@ import { installedBuildId } from './build-id';
|
|
|
6
6
|
import { type Clock, systemClock } from './clock';
|
|
7
7
|
import type { ReadinessMode } from './config-health';
|
|
8
8
|
import { assertReadinessMode } from './config-health';
|
|
9
|
-
import { DRAIN_DEADLINE_DEFAULT_MS } from './drain-deadline';
|
|
9
|
+
import { DRAIN_DEADLINE_DEFAULT_MS, laterHooksReserveMs as reserveOf } from './drain-deadline';
|
|
10
10
|
import { UltimateError } from './errors';
|
|
11
11
|
import { finiteCount } from './finite-option';
|
|
12
12
|
import { settleWithin } from './lifecycle-deadline';
|
|
@@ -285,6 +285,12 @@ function remainingBudget(reason: ShutdownReason): number {
|
|
|
285
285
|
return Math.max(0, reason.deadlineAt - systemClock.monotonic());
|
|
286
286
|
}
|
|
287
287
|
|
|
288
|
+
/** The slice of the budget kept for `inflight` and `close` hooks: a fifth, at most 2s; none without one. */
|
|
289
|
+
function laterHooksReserveMs(): number {
|
|
290
|
+
if (!registrations.some((entry) => entry.phase !== 'accept')) return 0;
|
|
291
|
+
return reserveOf(deadlineMs);
|
|
292
|
+
}
|
|
293
|
+
|
|
288
294
|
async function runPhase(phase: ShutdownPhase, reason: ShutdownReason): Promise<void> {
|
|
289
295
|
const hooks = registrations.filter((entry) => entry.phase === phase);
|
|
290
296
|
// Resources are released in reverse of acquisition, and only `close` releases any: an exporter
|
|
@@ -330,18 +336,27 @@ async function runDrain(signal: string): Promise<void> {
|
|
|
330
336
|
const grace = readinessGraceMs();
|
|
331
337
|
report('info', 'draining', { signal, deadlineMs, readinessGraceMs: grace, inflight });
|
|
332
338
|
if (grace > 0) await Bun.sleep(grace);
|
|
333
|
-
|
|
339
|
+
// A stuck request must not starve the hooks behind it to 0 ms: the OTLP flush that carries
|
|
340
|
+
// this very incident and the pool close get a slice the in-flight wait never spends. Decided
|
|
341
|
+
// BEFORE the `accept` phase and handed to it as `inflightUntil`: a role cutting its own work
|
|
342
|
+
// short (the jobs worker) must finish before this wait ends, not race it to the same instant.
|
|
343
|
+
const reserve = laterHooksReserveMs();
|
|
344
|
+
const deadlineAt = systemClock.monotonic() + deadlineMs;
|
|
345
|
+
const reason: ShutdownReason = { signal, deadlineAt, inflightUntil: deadlineAt - reserve };
|
|
334
346
|
await runPhase('accept', reason);
|
|
335
347
|
|
|
336
348
|
// Real monotonic, like `deadlineAt` itself: `waitForIdle` sleeps on a real `setTimeout`, and
|
|
337
349
|
// a budget read off an injected clock is a number that timer will never honour.
|
|
338
|
-
const remaining = Math.max(0,
|
|
350
|
+
const remaining = Math.max(0, deadlineAt - reserve - systemClock.monotonic());
|
|
339
351
|
const idle = await waitForIdle(remaining);
|
|
340
352
|
if (!idle) {
|
|
341
353
|
abandoned = true;
|
|
342
354
|
report('warn', 'X_SHUTDOWN_TIMEOUT', {
|
|
343
355
|
code: 'X_SHUTDOWN_TIMEOUT',
|
|
344
|
-
cause:
|
|
356
|
+
cause:
|
|
357
|
+
reserve === 0
|
|
358
|
+
? `${inflight} in-flight operations still running after ${deadlineMs}ms`
|
|
359
|
+
: `${inflight} in-flight operations still running ${deadlineMs - reserve}ms into the ${deadlineMs}ms drain deadline (the last ${reserve}ms are kept for the inflight and close hooks)`,
|
|
345
360
|
fix: 'drain: { deadlineMs: 600_000 } // in app.config.ts: a budget past the slowest handler, here a 10-minute one (configureLifecycle({ deadlineMs: 600_000 }) outside a framework boot) — and give the platform kill timer at least as many seconds, or shorten the handler',
|
|
346
361
|
});
|
|
347
362
|
}
|
package/src/locale-direction.ts
CHANGED
|
@@ -8,8 +8,10 @@
|
|
|
8
8
|
export type Direction = 'ltr' | 'rtl';
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
|
-
*
|
|
12
|
-
* `Intl.Locale.prototype.getTextInfo` so
|
|
11
|
+
* Languages whose usual script is right-to-left, by primary subtag: what a tag naming no script
|
|
12
|
+
* falls back to. A static CLDR-derived set rather than `Intl.Locale.prototype.getTextInfo` so
|
|
13
|
+
* direction is deterministic across runtimes. No `ku`: CLDR's likely script for it is Latin
|
|
14
|
+
* (Kurmanji); Sorani is `ckb`, and Kurdish in Arabic script says so (`ku-Arab`).
|
|
13
15
|
*/
|
|
14
16
|
const RTL_LOCALES: ReadonlySet<string> = new Set([
|
|
15
17
|
'ar',
|
|
@@ -19,7 +21,6 @@ const RTL_LOCALES: ReadonlySet<string> = new Set([
|
|
|
19
21
|
'fa',
|
|
20
22
|
'he',
|
|
21
23
|
'ks',
|
|
22
|
-
'ku',
|
|
23
24
|
'nqo',
|
|
24
25
|
'ps',
|
|
25
26
|
'sd',
|
|
@@ -28,9 +29,26 @@ const RTL_LOCALES: ReadonlySet<string> = new Set([
|
|
|
28
29
|
'yi',
|
|
29
30
|
]);
|
|
30
31
|
|
|
32
|
+
/** ISO 15924 right-to-left scripts in living use, lower-cased. */
|
|
33
|
+
const RTL_SCRIPTS: ReadonlySet<string> = new Set([
|
|
34
|
+
'adlm',
|
|
35
|
+
'arab',
|
|
36
|
+
'hebr',
|
|
37
|
+
'mand',
|
|
38
|
+
'nkoo',
|
|
39
|
+
'rohg',
|
|
40
|
+
'samr',
|
|
41
|
+
'syrc',
|
|
42
|
+
'thaa',
|
|
43
|
+
]);
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* A script subtag is four letters in second place (BCP 47), and when a tag names one it decides:
|
|
47
|
+
* `az-Arab` is rtl and `ks-Deva` ltr, whatever the language usually writes.
|
|
48
|
+
*/
|
|
31
49
|
export function isRtl(locale: string): boolean {
|
|
32
|
-
const primary = locale.split('-')
|
|
33
|
-
return RTL_LOCALES.has(primary);
|
|
50
|
+
const [primary = '', second = ''] = locale.toLowerCase().split('-');
|
|
51
|
+
return /^[a-z]{4}$/.test(second) ? RTL_SCRIPTS.has(second) : RTL_LOCALES.has(primary);
|
|
34
52
|
}
|
|
35
53
|
|
|
36
54
|
export function directionOf(locale: string): Direction {
|
package/src/logger-redact.ts
CHANGED
|
@@ -245,7 +245,11 @@ function serialise(value: unknown, depth: number): unknown {
|
|
|
245
245
|
if (value instanceof Date) {
|
|
246
246
|
return Number.isNaN(value.getTime()) ? INVALID_DATE : value.toISOString();
|
|
247
247
|
}
|
|
248
|
-
if (isUltimateError(value))
|
|
248
|
+
if (isUltimateError(value)) {
|
|
249
|
+
// `meta` is caller data under caller keys: the same key walk as a plain field, then by value.
|
|
250
|
+
const json = value.toJSON();
|
|
251
|
+
return redactedStrings({ ...json, meta: serialiseValue(json.meta, depth + 1) });
|
|
252
|
+
}
|
|
249
253
|
if (value instanceof Error) return { name: value.name, message: redactedValue(value.message) };
|
|
250
254
|
if (depth >= 6) return '[depth-limit]';
|
|
251
255
|
if (Array.isArray(value)) return value.map((item) => serialiseValue(item, depth + 1));
|
package/src/logger.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { subscribed } from './instrument';
|
|
|
10
10
|
import { publishRecord } from './logger-record';
|
|
11
11
|
import { INVALID_DATE, type LogFields, redactFields, redactionGeneration } from './logger-redact';
|
|
12
12
|
import { redactedValue } from './redact-values';
|
|
13
|
+
import { supervisedChild } from './shared-port';
|
|
13
14
|
|
|
14
15
|
// The redaction half lives in `logger-redact.ts`; every caller keeps importing it from here.
|
|
15
16
|
export type { LogFields } from './logger-redact';
|
|
@@ -279,6 +280,27 @@ function refuse(cause: string, fix: string): never {
|
|
|
279
280
|
assert(false, cause, fix);
|
|
280
281
|
}
|
|
281
282
|
|
|
283
|
+
/**
|
|
284
|
+
* Which supervised child this process is (`ULTIMATE_CHILD`), read once at load — a fact about the
|
|
285
|
+
* PROCESS, like the stream, so N children writing one container log stay told apart. `typeof`
|
|
286
|
+
* for the browser, as `envLevel` says why; a malformed value refuses here, the first line written.
|
|
287
|
+
*/
|
|
288
|
+
const PROCESS_CHILD = typeof process === 'undefined' ? undefined : supervisedChild(process.env);
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* `child: <index>` on a supervised child's line. The process's fact wins: a caller's own `child`
|
|
292
|
+
* field moves to `field.child`, as a reserved key does, so no line can claim another child.
|
|
293
|
+
*/
|
|
294
|
+
function withProcessChild(fields: Record<string, unknown>): Record<string, unknown> {
|
|
295
|
+
if (PROCESS_CHILD === undefined) return fields;
|
|
296
|
+
const { child: own, ...rest } = fields;
|
|
297
|
+
return {
|
|
298
|
+
...rest,
|
|
299
|
+
...(Object.hasOwn(fields, 'child') ? { 'field.child': own } : undefined),
|
|
300
|
+
child: PROCESS_CHILD.index,
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
|
|
282
304
|
/** The keys a line owns. A caller field spelled like one is renamed, never allowed to replace it. */
|
|
283
305
|
const RESERVED_KEYS: ReadonlySet<string> = new Set(['ts', 'level', 'msg']);
|
|
284
306
|
|
|
@@ -340,11 +362,11 @@ function derive(level: LogLevel, bound: Bound, clock: Clock, writer: LogSink): L
|
|
|
340
362
|
// The message is a string a caller interpolated: the one leaf `redactFields` never sees.
|
|
341
363
|
const message = redactedValue(raw);
|
|
342
364
|
const context = contextFields();
|
|
343
|
-
const caller = {
|
|
365
|
+
const caller = withProcessChild({
|
|
344
366
|
...current(bound),
|
|
345
367
|
...(context === undefined ? undefined : redactFields(context)),
|
|
346
368
|
...(fields === undefined ? undefined : redactFields(fields)),
|
|
347
|
-
};
|
|
369
|
+
});
|
|
348
370
|
const line = {
|
|
349
371
|
ts: timestamp(clock),
|
|
350
372
|
level: lineLevel,
|
package/src/outbound-attempt.ts
CHANGED
|
@@ -21,7 +21,7 @@ import {
|
|
|
21
21
|
outboundUnreachable,
|
|
22
22
|
} from './outbound-errors';
|
|
23
23
|
import type { HopCall } from './outbound-hops';
|
|
24
|
-
import {
|
|
24
|
+
import { redactedLocation, sendHops } from './outbound-hops';
|
|
25
25
|
import type { WatchedFailure } from './outbound-read';
|
|
26
26
|
import { watchedBody } from './outbound-read';
|
|
27
27
|
import { readWithinLimit } from './read-capped';
|
|
@@ -107,7 +107,7 @@ async function refusalOf(
|
|
|
107
107
|
if (status >= 300 && status < 400) {
|
|
108
108
|
await body.cancel().catch(() => undefined);
|
|
109
109
|
const location = headers.get('location');
|
|
110
|
-
const where = location === null ? 'nowhere' :
|
|
110
|
+
const where = location === null ? 'nowhere' : redactedLocation(location, url);
|
|
111
111
|
return outboundRedirected(site, status, where);
|
|
112
112
|
}
|
|
113
113
|
if (isRetryableStatus(status)) {
|
package/src/outbound-hops.ts
CHANGED
|
@@ -49,6 +49,10 @@ export function redactedPath(pathname: string): string {
|
|
|
49
49
|
/** Where a URL points, for a cause or `meta`: origin and the redacted path, never the query. */
|
|
50
50
|
export const redactedUrl = (url: URL): string => `${url.origin}${redactedPath(url.pathname)}`;
|
|
51
51
|
|
|
52
|
+
/** A `Location` header, redacted as `redactedUrl`; one no parser reads is named, never echoed. */
|
|
53
|
+
export const redactedLocation = (location: string, base: URL): string =>
|
|
54
|
+
URL.canParse(location, base) ? redactedUrl(new URL(location, base)) : 'an unparseable Location';
|
|
55
|
+
|
|
52
56
|
interface Target {
|
|
53
57
|
readonly url: string;
|
|
54
58
|
readonly host?: string | undefined;
|
|
@@ -121,6 +125,10 @@ export async function sendHops(call: HopCall, signal: AbortSignal): Promise<Resp
|
|
|
121
125
|
return response;
|
|
122
126
|
}
|
|
123
127
|
await discard(response);
|
|
128
|
+
// A Location no parser reads is still the vendor's answer: a redirect, never "no response".
|
|
129
|
+
if (!URL.canParse(location, url)) {
|
|
130
|
+
throw outboundRedirected(call.site, response.status, redactedLocation(location, url));
|
|
131
|
+
}
|
|
124
132
|
const next = new URL(location, url);
|
|
125
133
|
if (hop + 1 > OUTBOUND_MAX_REDIRECTS) {
|
|
126
134
|
throw outboundRedirected(call.site, response.status, redactedUrl(next));
|
package/src/outbound.ts
CHANGED
|
@@ -176,7 +176,9 @@ export async function outbound(
|
|
|
176
176
|
deps.sleep ?? (request.signal === undefined ? undefined : signalledSleep(request.signal)),
|
|
177
177
|
now: call.now,
|
|
178
178
|
random: deps.random,
|
|
179
|
-
|
|
179
|
+
// A caller that cancelled wants no retry: refusing it ends the loop with that caller's own
|
|
180
|
+
// reason, and spends no token a real vendor failure on this key will need.
|
|
181
|
+
admitRetry: () => request.signal?.aborted !== true && (budget?.spend() ?? true),
|
|
180
182
|
});
|
|
181
183
|
};
|
|
182
184
|
const answer = await instrumentedCall(
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// Single responsibility: the shared-port seam. Whether this process is a supervised child
|
|
2
|
+
// (`ULTIMATE_CHILD=i/N`), the one place Bun.serve's `reusePort` is spelled, and the split of a
|
|
3
|
+
// container-wide count between children. `scripts/reuse-port-seam.ts` keeps the literal here.
|
|
4
|
+
|
|
5
|
+
import { assert } from './assert';
|
|
6
|
+
import { renderCauseValue } from './error-render';
|
|
7
|
+
|
|
8
|
+
type ProcessEnv = Readonly<Record<string, string | undefined>>;
|
|
9
|
+
|
|
10
|
+
/** This process's place among its siblings: `index` is zero-based, `index < count`. */
|
|
11
|
+
export interface SupervisedChild {
|
|
12
|
+
readonly index: number;
|
|
13
|
+
readonly count: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Canonical decimals only: a leading zero, a sign or a space is not something the supervisor writes. */
|
|
17
|
+
const CHILD_SHAPE = /^(0|[1-9]\d*)\/([1-9]\d*)$/;
|
|
18
|
+
|
|
19
|
+
const CHILD_FIX =
|
|
20
|
+
'unset ULTIMATE_CHILD # the production supervisor sets it for each child as <index>/<count>; set ULTIMATE_PROCESSES to choose the count';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* `ULTIMATE_CHILD`, read. Unset or empty: not a child. Anything else that is not `i/N` with
|
|
24
|
+
* `0 ≤ i < N` is REFUSED (`X_INVARIANT`): only the supervisor writes the name, and a child that read
|
|
25
|
+
* a garbled one as "unsupervised" would bind the shared port without `reusePort` and lose it.
|
|
26
|
+
*/
|
|
27
|
+
export function supervisedChild(env: ProcessEnv): SupervisedChild | undefined {
|
|
28
|
+
const raw = env['ULTIMATE_CHILD'];
|
|
29
|
+
if (raw === undefined || raw === '') return undefined;
|
|
30
|
+
const match = CHILD_SHAPE.exec(raw);
|
|
31
|
+
const index = Number(match?.[1]);
|
|
32
|
+
const count = Number(match?.[2]);
|
|
33
|
+
assert(
|
|
34
|
+
match !== null && Number.isSafeInteger(count) && index < count,
|
|
35
|
+
`ULTIMATE_CHILD=${renderCauseValue(raw)} is not <index>/<count> with 0 <= index < count`,
|
|
36
|
+
CHILD_FIX,
|
|
37
|
+
);
|
|
38
|
+
return { index, count };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The option to spread into `Bun.serve`. `{ reusePort: true }` only for a supervised child on
|
|
43
|
+
* Linux — Bun ignores `SO_REUSEPORT` elsewhere, so the key is ABSENT off Linux and for a lone
|
|
44
|
+
* process: an unsupervised second bind must keep failing with "port in use".
|
|
45
|
+
*/
|
|
46
|
+
export function sharedPortOption(
|
|
47
|
+
env: ProcessEnv,
|
|
48
|
+
platform: string = process.platform,
|
|
49
|
+
): { readonly reusePort?: true } {
|
|
50
|
+
return supervisedChild(env) !== undefined && platform === 'linux' ? { reusePort: true } : {};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const isCount = (value: number, floor: number): boolean =>
|
|
54
|
+
Number.isSafeInteger(value) && value >= floor;
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Child `index`'s share of a container-wide `total` (pool connections, job slots): the floor of an
|
|
58
|
+
* even split, the remainder to the lowest indices, never under 1 — so the shares sum to
|
|
59
|
+
* `max(total, count)`. A total under the count is the caller's to refuse or clamp first.
|
|
60
|
+
*/
|
|
61
|
+
export function childShare(total: number, index: number, count: number): number {
|
|
62
|
+
assert(
|
|
63
|
+
isCount(total, 0) && isCount(count, 1) && isCount(index, 0) && index < count,
|
|
64
|
+
`childShare(${renderCauseValue(total)}, ${renderCauseValue(index)}, ${renderCauseValue(count)}) needs whole numbers with total >= 0, count >= 1 and 0 <= index < count`,
|
|
65
|
+
'pass supervisedChild(env) as index and count, and the container-wide total as a whole number',
|
|
66
|
+
);
|
|
67
|
+
if (total <= count) return 1;
|
|
68
|
+
return Math.floor(total / count) + (index < total % count ? 1 : 0);
|
|
69
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// `@ultimat3/core/internal/sse-frames` — the ONE reader of a `text/event-stream` body's frames: the
|
|
2
|
+
// browser's `clientStream` and `@ultimat3/mcp`'s remote client both split SSE here. INTERNAL and a
|
|
3
|
+
// leaf: a package's wire reader, never an app's, and it imports nothing.
|
|
4
|
+
|
|
5
|
+
/** One complete frame: its `event` (`message` when unnamed) and its `data:` lines joined. */
|
|
6
|
+
export interface SseFrame {
|
|
7
|
+
readonly event: string;
|
|
8
|
+
readonly data: string;
|
|
9
|
+
/** The `x-ultimate-dates` value for this frame's data, when the server named any. */
|
|
10
|
+
readonly dates?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Splits a growing buffer into complete frames; the incomplete tail is handed back. A frame with
|
|
15
|
+
* no `data:` line (a keep-alive comment, a bare `event:`) is no frame. A whole body read at once
|
|
16
|
+
* is `takeFrames(`${text}\n\n`)`: its last frame needs no blank line after it.
|
|
17
|
+
*/
|
|
18
|
+
export function takeFrames(buffer: string): {
|
|
19
|
+
readonly frames: SseFrame[];
|
|
20
|
+
readonly rest: string;
|
|
21
|
+
} {
|
|
22
|
+
const frames: SseFrame[] = [];
|
|
23
|
+
const blocks = buffer.split(/\r?\n\r?\n/);
|
|
24
|
+
const rest = blocks.pop() ?? '';
|
|
25
|
+
for (const block of blocks) {
|
|
26
|
+
let event = 'message';
|
|
27
|
+
let dates: string | undefined;
|
|
28
|
+
const data: string[] = [];
|
|
29
|
+
for (const line of block.split(/\r?\n/)) {
|
|
30
|
+
// A `:` line is a comment — the server's keep-alive.
|
|
31
|
+
if (line.startsWith(':')) continue;
|
|
32
|
+
if (line.startsWith('event:')) event = line.slice(6).trim();
|
|
33
|
+
else if (line.startsWith('dates:')) dates = line.slice(6).trim();
|
|
34
|
+
else if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''));
|
|
35
|
+
}
|
|
36
|
+
if (data.length > 0) {
|
|
37
|
+
const text = data.join('\n');
|
|
38
|
+
frames.push(dates === undefined ? { event, data: text } : { event, data: text, dates });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return { frames, rest };
|
|
42
|
+
}
|