@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/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 { type Environment, 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';
@@ -27,12 +28,28 @@ interface EnvVarCommon {
27
28
  }
28
29
 
29
30
  export interface EnvStringVar extends EnvVarCommon {
31
+ /**
32
+ * With `required: false`: optional, EXCEPT in these environments (`ULTIMATE_ENV`, else
33
+ * `NODE_ENV`) — `requiredIn: ['staging', 'production']` is a key every deploy must set and a
34
+ * laptop or a test run may leave unset. An environment no reader can name counts as listed. A
35
+ * declared `default` still answers an absent key first, and a `role` still narrows it. Without
36
+ * `required: false` the key is required everywhere already, and this changes nothing.
37
+ */
38
+ readonly requiredIn?: readonly Environment[] | undefined;
30
39
  readonly type: 'string' | 'url';
31
40
  readonly default?: string | undefined;
32
41
  readonly pattern?: RegExp | undefined;
33
42
  }
34
43
 
35
44
  export interface EnvNumberVar extends EnvVarCommon {
45
+ /**
46
+ * With `required: false`: optional, EXCEPT in these environments (`ULTIMATE_ENV`, else
47
+ * `NODE_ENV`) — `requiredIn: ['staging', 'production']` is a key every deploy must set and a
48
+ * laptop or a test run may leave unset. An environment no reader can name counts as listed. A
49
+ * declared `default` still answers an absent key first, and a `role` still narrows it. Without
50
+ * `required: false` the key is required everywhere already, and this changes nothing.
51
+ */
52
+ readonly requiredIn?: readonly Environment[] | undefined;
36
53
  readonly type: 'number' | 'integer' | 'port';
37
54
  readonly default?: number | undefined;
38
55
  readonly min?: number | undefined;
@@ -40,11 +57,27 @@ export interface EnvNumberVar extends EnvVarCommon {
40
57
  }
41
58
 
42
59
  export interface EnvBooleanVar extends EnvVarCommon {
60
+ /**
61
+ * With `required: false`: optional, EXCEPT in these environments (`ULTIMATE_ENV`, else
62
+ * `NODE_ENV`) — `requiredIn: ['staging', 'production']` is a key every deploy must set and a
63
+ * laptop or a test run may leave unset. An environment no reader can name counts as listed. A
64
+ * declared `default` still answers an absent key first, and a `role` still narrows it. Without
65
+ * `required: false` the key is required everywhere already, and this changes nothing.
66
+ */
67
+ readonly requiredIn?: readonly Environment[] | undefined;
43
68
  readonly type: 'boolean';
44
69
  readonly default?: boolean | undefined;
45
70
  }
46
71
 
47
72
  export interface EnvEnumVar<V extends string = string> extends EnvVarCommon {
73
+ /**
74
+ * With `required: false`: optional, EXCEPT in these environments (`ULTIMATE_ENV`, else
75
+ * `NODE_ENV`) — `requiredIn: ['staging', 'production']` is a key every deploy must set and a
76
+ * laptop or a test run may leave unset. An environment no reader can name counts as listed. A
77
+ * declared `default` still answers an absent key first, and a `role` still narrows it. Without
78
+ * `required: false` the key is required everywhere already, and this changes nothing.
79
+ */
80
+ readonly requiredIn?: readonly Environment[] | undefined;
48
81
  readonly type: 'enum';
49
82
  readonly values: readonly V[];
50
83
  readonly default?: V | undefined;
@@ -101,10 +134,22 @@ export interface EnvOptions {
101
134
  const TRUE_VALUES = new Set(['1', 'true', 'yes', 'on']);
102
135
  const FALSE_VALUES = new Set(['0', 'false', 'no', 'off']);
103
136
 
104
- function requiredForRole(decl: EnvVarDecl, role: Role): boolean {
105
- if (decl.required === false) return false;
106
- if (decl.role === undefined) return true;
107
- return typeof decl.role === 'string' ? decl.role === role : decl.role.includes(role);
137
+ /**
138
+ * `required: false` with `requiredIn`: required in a listed environment, and in one no reader can
139
+ * name (`undefined`) — a deploy whose name is a typo fails closed.
140
+ */
141
+ function requiredInEnvironment(decl: EnvVarDecl, environment: Environment | undefined): boolean {
142
+ if (decl.requiredIn === undefined) return false;
143
+ return environment === undefined || decl.requiredIn.includes(environment);
144
+ }
145
+
146
+ /** The role is asked first: a key another role needs is never this process's, whatever the environment. */
147
+ function requiredForRole(decl: EnvVarDecl, role: Role, environment?: Environment): boolean {
148
+ if (decl.role !== undefined) {
149
+ const matches = typeof decl.role === 'string' ? decl.role === role : decl.role.includes(role);
150
+ if (!matches) return false;
151
+ }
152
+ return decl.required !== false || requiredInEnvironment(decl, environment);
108
153
  }
109
154
 
110
155
  function expectation(decl: EnvVarDecl): string {
@@ -161,10 +206,76 @@ function parseValue(decl: EnvVarDecl, raw: string): { ok: true; value: unknown }
161
206
  }
162
207
  }
163
208
 
209
+ type EnvSource = Readonly<Record<string, string | undefined>>;
210
+
211
+ /**
212
+ * The dotenv file a missing key is added to, for the environment `source` names. In development
213
+ * and test it is the per-box file Bun loads last and the scaffold's setup writes
214
+ * (`.env.<environment>.local`) — never `.env`, which no scaffold file is. A deploy
215
+ * (`staging`/`production`, or an `ULTIMATE_ENV` that is no environment: fail closed) reads
216
+ * `.env.production`, the file `x env init --production` writes and `x deploy --method compose` reads.
217
+ */
218
+ function envFileFor(source: EnvSource): string {
219
+ const environment = tryResolveEnvironment({ env: source });
220
+ return environment === 'development' || environment === 'test'
221
+ ? `.env.${environment}.local`
222
+ : '.env.production';
223
+ }
224
+
225
+ const keyArg = (key: string): string => renderFixShellArg(key, '<KEY>');
226
+
227
+ /** `grep` over every dotenv file: a malformed value is in whichever one set it. */
228
+ const findLines = (keys: readonly string[]): string =>
229
+ `grep -n ${keys.map((key) => `-e '^${keyArg(key)}='`).join(' ')} .env*`;
230
+
231
+ /**
232
+ * ONE fix for the whole throw, and never `x env check`: that command prints this same error and
233
+ * this same line. Every missing key gets the line to add, in the file this environment loads; a
234
+ * malformed one is found where it is set. A key whose declaration carries its own `fix` keeps it:
235
+ * the command leads (generated, else the first declared), and every other declared fix follows,
236
+ * named by its key, so one refusal still says how to repair every key.
237
+ */
238
+ function fixFor(schema: EnvSchema, issues: readonly EnvIssue[], source: EnvSource): string {
239
+ const declared = issues.flatMap((issue) => {
240
+ const fix = schema[issue.key]?.fix;
241
+ return fix === undefined ? [] : [{ key: issue.key, fix }];
242
+ });
243
+ const lead = generatedFix(schema, issues, source) ?? declared.shift()?.fix;
244
+ const head = lead ?? findLines(issues.map((issue) => issue.key));
245
+ if (declared.length === 0) return head;
246
+ const rest = declared.map(({ key, fix }) => `${key}: ${fix}`).join('; ');
247
+ return `${head}${head.includes('#') ? '; then' : ' # then'}, per key — ${rest}`;
248
+ }
249
+
250
+ /** The command for the keys with no declared fix, or `undefined` when every key declares one. */
251
+ function generatedFix(
252
+ schema: EnvSchema,
253
+ issues: readonly EnvIssue[],
254
+ source: EnvSource,
255
+ ): string | undefined {
256
+ const generated = issues.filter((issue) => schema[issue.key]?.fix === undefined);
257
+ const missing = generated.filter((issue) => issue.reason === 'missing');
258
+ const invalid = generated.filter((issue) => issue.reason === 'invalid');
259
+ const malformed = invalid.map((issue) => `${issue.key} (${issue.expected})`).join(', ');
260
+ if (missing.length === 0) {
261
+ if (invalid.length === 0) return undefined;
262
+ return `${findLines(invalid.map((issue) => issue.key))} # each line to correct: ${malformed}`;
263
+ }
264
+ const lines = missing.map((issue) => `'${keyArg(issue.key)}=<value>'`);
265
+ const write = lines.length === 1 ? `echo ${lines[0]}` : `printf '%s\\n' ${lines.join(' ')}`;
266
+ const expected = missing.map((issue) => `${issue.key}: ${issue.expected}`).join('; ');
267
+ const also =
268
+ invalid.length === 0
269
+ ? ''
270
+ : `; also malformed, where ${findLines(invalid.map((issue) => issue.key))} finds them: ${malformed}`;
271
+ return `${write} >> ${envFileFor(source)} # ${expected}${also}`;
272
+ }
273
+
164
274
  /** Validate without throwing — this is what `x env check --json` prints. */
165
275
  export function checkEnv(schema: EnvSchema, options?: EnvOptions): EnvCheckReport {
166
276
  const source = options?.env ?? (process.env as Record<string, string | undefined>);
167
277
  const role = options?.role ?? resolveRole({ env: source });
278
+ const environment = tryResolveEnvironment({ env: source });
168
279
  const issues: EnvIssue[] = [];
169
280
  const values: Record<string, unknown> = {};
170
281
 
@@ -175,7 +286,7 @@ export function checkEnv(schema: EnvSchema, options?: EnvOptions): EnvCheckRepor
175
286
  values[key] = decl.default;
176
287
  continue;
177
288
  }
178
- if (requiredForRole(decl, role)) {
289
+ if (requiredForRole(decl, role, environment)) {
179
290
  issues.push({
180
291
  key,
181
292
  reason: 'missing',
@@ -183,7 +294,7 @@ export function checkEnv(schema: EnvSchema, options?: EnvOptions): EnvCheckRepor
183
294
  received: undefined,
184
295
  fix:
185
296
  decl.fix ??
186
- `grep '^${renderFixShellArg(key, '<KEY>')}=' .env.example >> .env # then give it ${expectation(decl)}`,
297
+ `echo '${keyArg(key)}=<value>' >> ${envFileFor(source)} # <value>: ${expectation(decl)}`,
187
298
  });
188
299
  } else {
189
300
  values[key] = undefined;
@@ -200,9 +311,7 @@ export function checkEnv(schema: EnvSchema, options?: EnvOptions): EnvCheckRepor
200
311
  reason: 'invalid',
201
312
  expected: expectation(decl),
202
313
  received: decl.secret === true ? '***' : raw,
203
- fix:
204
- decl.fix ??
205
- `grep -n '^${renderFixShellArg(key, '<KEY>')}=' .env # the line to set to ${expectation(decl)}`,
314
+ fix: decl.fix ?? `${findLines([key])} # the line to set to ${expectation(decl)}`,
206
315
  });
207
316
  }
208
317
 
@@ -241,10 +350,13 @@ export function defineEnv<const S extends EnvSchema>(schema: S, options?: EnvOpt
241
350
  : `${issue.key} is not ${issue.expected} (received ${issue.received ?? 'undefined'})`,
242
351
  )
243
352
  .join('; ');
244
- const keys = report.issues.map((issue) => issue.key).join(' ');
245
353
  throw new EnvMissingError({
246
354
  cause,
247
- fix: `x env check # each key to add to .env (copy .env.example): ${keys}`,
355
+ fix: fixFor(
356
+ schema,
357
+ report.issues,
358
+ options?.env ?? (process.env as Record<string, string | undefined>),
359
+ ),
248
360
  meta: { issues: described },
249
361
  });
250
362
  }
@@ -279,6 +391,8 @@ export interface EnvVarSummary {
279
391
  readonly secret: boolean;
280
392
  readonly hasDefault: boolean;
281
393
  readonly roles: readonly Role[] | 'all';
394
+ /** `requiredIn`, when an optional key names the environments that require it. */
395
+ readonly requiredIn?: readonly Environment[];
282
396
  readonly description: string | undefined;
283
397
  }
284
398
 
@@ -295,6 +409,7 @@ export function describeEnv(schema: EnvSchema): readonly EnvVarSummary[] {
295
409
  secret: decl.secret === true,
296
410
  hasDefault: decl.default !== undefined,
297
411
  roles: decl.role === undefined ? 'all' : rolesOf(decl.role),
412
+ ...(decl.requiredIn === undefined ? {} : { requiredIn: decl.requiredIn }),
298
413
  description: decl.description,
299
414
  }));
300
415
  }
@@ -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, exactly as `metrics-text.ts` is to Prometheus): the format
3
- // is documented and several self-hostable monitors ingest it. Nothing here names a host, a project
4
- // or an organisation — the DSN is the app's own typed env, passed in at wiring time.
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: `"${dsn}" is not a URL`,
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: `"${url.protocol}//${url.host}${url.pathname}" has no publicKey, no projectId or a non-HTTP scheme`,
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 send = options.fetch ?? globalThis.fetch;
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
- void send(dsn.envelopeUrl, {
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
  };
@@ -55,8 +55,13 @@ 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'),
@@ -65,6 +70,8 @@ export const FRAMEWORK_ENV: readonly FrameworkEnvName[] = [
65
70
  ...contract('core', 'ULTIMATE_CURSOR_SECRET', 'ULTIMATE_SECRETS_KEY'),
66
71
  ...contract('core', 'ULTIMATE_SECRETS_RETIRED_KEYS', 'METRICS_INTERVAL_MS'),
67
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'),
68
75
  ...contract('core', 'OTEL_EXPORTER_OTLP_ENDPOINT', 'OTEL_EXPORTER_OTLP_HEADERS'),
69
76
  ...contract('core', 'OTEL_EXPORTER_OTLP_PROTOCOL', 'OTEL_TRACES_SAMPLER'),
70
77
  ...contract('core', 'OTEL_TRACES_SAMPLER_ARG'),
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';
@@ -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
- const reason: ShutdownReason = { signal, deadlineAt: systemClock.monotonic() + deadlineMs };
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, reason.deadlineAt - systemClock.monotonic());
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: `${inflight} in-flight operations still running after ${deadlineMs}ms`,
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
  }
@@ -8,8 +8,10 @@
8
8
  export type Direction = 'ltr' | 'rtl';
9
9
 
10
10
  /**
11
- * Right-to-left scripts, by primary subtag. A static CLDR-derived set rather than
12
- * `Intl.Locale.prototype.getTextInfo` so direction is deterministic across runtimes.
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('-')[0]?.toLowerCase() ?? '';
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 {
@@ -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)) return redactedStrings(value.toJSON());
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,