@ultimat3/core 31.6.1 → 31.7.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 +6 -2
- package/README.md +28 -2
- package/package.json +2 -2
- package/src/breaker-retry-budget.ts +48 -0
- package/src/config-cache.ts +30 -0
- package/src/config.ts +3 -12
- package/src/core-error-codes.ts +1 -0
- package/src/error-fingerprint.ts +28 -52
- package/src/error-reporter-sentry-hooks.ts +25 -9
- package/src/error-reporter-sentry.ts +22 -15
- package/src/exports/observability.ts +1 -1
- package/src/image/errors.ts +19 -0
- package/src/image/pipeline.ts +17 -136
- package/src/image/raster-pool.ts +185 -0
- package/src/image/raster-wire.ts +100 -0
- package/src/image/raster-worker-bundle.ts +85 -0
- package/src/image/raster-worker.ts +46 -0
- package/src/image/transform-inline.ts +169 -0
- package/src/index.ts +10 -1
- package/src/logger-redact.ts +222 -0
- package/src/logger.ts +99 -204
- package/src/map-bounded.ts +82 -0
- package/src/metric-series.ts +26 -3
- package/src/outbound.ts +9 -2
- package/src/retry-loop.ts +8 -0
- package/src/retry.ts +3 -0
- package/src/runtime-metrics.ts +33 -6
- package/src/sentry-frames.ts +175 -0
- package/src/type-pins.ts +10 -0
- package/src/visible-interval.ts +16 -6
package/src/logger.ts
CHANGED
|
@@ -6,18 +6,17 @@ import { adapterSlot } from './adapter-slot';
|
|
|
6
6
|
import { assert } from './assert';
|
|
7
7
|
import { type Clock, liveClock } from './clock';
|
|
8
8
|
import { renderCauseValue } from './error-render';
|
|
9
|
-
import { isUltimateError } from './errors';
|
|
10
9
|
import { subscribed } from './instrument';
|
|
11
10
|
import { publishRecord } from './logger-record';
|
|
12
|
-
import {
|
|
11
|
+
import { INVALID_DATE, type LogFields, redactFields, redactionGeneration } from './logger-redact';
|
|
13
12
|
|
|
13
|
+
// The redaction half lives in `logger-redact.ts`; every caller keeps importing it from here.
|
|
14
|
+
export type { LogFields } from './logger-redact';
|
|
15
|
+
export { isRedactedKey, redactFields, redactKeys } from './logger-redact';
|
|
14
16
|
// Re-exported, not redefined: `secret.ts` owns the placeholder because a `Secret` has to render
|
|
15
17
|
// it without importing the logger, and two constants spelled the same is one rename from a leak.
|
|
16
18
|
export { REDACTED } from './secret';
|
|
17
19
|
|
|
18
|
-
/** What a `Date` this file cannot render says instead — the line survives, the value is named. */
|
|
19
|
-
const INVALID_DATE = 'an invalid Date';
|
|
20
|
-
|
|
21
20
|
export const LOG_LEVELS = ['trace', 'debug', 'info', 'warn', 'error', 'fatal', 'silent'] as const;
|
|
22
21
|
|
|
23
22
|
export type LogLevel = (typeof LOG_LEVELS)[number];
|
|
@@ -32,10 +31,6 @@ const LEVEL_WEIGHT = Object.freeze<Record<LogLevel, number>>({
|
|
|
32
31
|
silent: 100,
|
|
33
32
|
});
|
|
34
33
|
|
|
35
|
-
export interface LogFields {
|
|
36
|
-
readonly [key: string]: unknown;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
34
|
export interface Logger {
|
|
40
35
|
readonly level: LogLevel;
|
|
41
36
|
trace(message: string, fields?: LogFields): void;
|
|
@@ -57,107 +52,6 @@ export interface LoggerOptions {
|
|
|
57
52
|
readonly writer?: ((line: string, level: LogLevel) => void) | undefined;
|
|
58
53
|
}
|
|
59
54
|
|
|
60
|
-
/**
|
|
61
|
-
* The exact-key FAST PATH. LOWERCASE, always: `isRedactedKey` lowercases its lookup, so
|
|
62
|
-
* `apiKey`/`accessToken`/`refreshToken` sat here for three releases matching nothing — and those
|
|
63
|
-
* are the exact field names on `@ultimat3/auth`'s `OAuthTokens`. Add through `redactKeys()` (which
|
|
64
|
-
* lowercases) rather than here. A name this set misses still meets `CREDENTIAL_NAME` below.
|
|
65
|
-
*/
|
|
66
|
-
const redactedKeys = new Set<string>([
|
|
67
|
-
'password',
|
|
68
|
-
'token',
|
|
69
|
-
'secret',
|
|
70
|
-
'authorization',
|
|
71
|
-
'cookie',
|
|
72
|
-
'set-cookie',
|
|
73
|
-
'apikey',
|
|
74
|
-
'api_key',
|
|
75
|
-
'accesstoken',
|
|
76
|
-
'access_token',
|
|
77
|
-
'refreshtoken',
|
|
78
|
-
'refresh_token',
|
|
79
|
-
'idtoken',
|
|
80
|
-
'id_token',
|
|
81
|
-
'sessiontoken',
|
|
82
|
-
'session_token',
|
|
83
|
-
'clientsecret',
|
|
84
|
-
'client_secret',
|
|
85
|
-
'privatekey',
|
|
86
|
-
'private_key',
|
|
87
|
-
// The framework's own columns (`@ultimat3/auth`): a hash is what an offline guess runs against.
|
|
88
|
-
'passwordhash',
|
|
89
|
-
'tokenhash',
|
|
90
|
-
'keyhash',
|
|
91
|
-
]);
|
|
92
|
-
|
|
93
|
-
/**
|
|
94
|
-
* The second half, for the names no list can enumerate. Exact-key matching alone let every
|
|
95
|
-
* COMPOUND credential through — `currentPassword`, `mfaSecret`, `resetToken`, `recoveryCode` — and
|
|
96
|
-
* `@ultimat3/action`'s audit walk asks this same predicate, so each was persisted in clear.
|
|
97
|
-
*
|
|
98
|
-
* Tested against the key lowercased with `_` and `-` removed, so one pattern covers the camel, the
|
|
99
|
-
* snake and the header spelling. It names what BEARS a credential and nothing wider, because a
|
|
100
|
-
* redacted field is one an operator cannot correlate on:
|
|
101
|
-
*
|
|
102
|
-
* - `password` / `passphrase` anywhere — no ordinary field carries the word.
|
|
103
|
-
* - `secret` as the LAST word (`mfaSecret`, `webhookSecret`, `appSecrets`, `secretAccessKey`), so
|
|
104
|
-
* `clientSecretEnv` and `secretsPath` — a variable name and a path — stay readable.
|
|
105
|
-
* - a `token` is a bearer UNLESS its qualifier says it is not: fail closed, with the exceptions
|
|
106
|
-
* named. `idempotencyToken`, `pageToken`, `continuationToken`, `cursorToken`, `syncToken` are
|
|
107
|
-
* dedupe and paging keys an operator greps for; everything else ending in `token` — `resetToken`,
|
|
108
|
-
* `githubToken`, `NPM_TOKEN` — is redacted without a provider list to keep current. The PLURAL
|
|
109
|
-
* is the reverse: `maxTokens` / `inputTokens` are counts on every `@ultimat3/ai` usage line, so
|
|
110
|
-
* `tokens` is redacted only behind a bearer qualifier (`accessTokens`).
|
|
111
|
-
* - key MATERIAL by its qualifier (`apiKey`, `privateKey`, `signingKey`, `encryptionKey`,
|
|
112
|
-
* `masterKey`, `hmacKey`, `secretsKey`, `accessKey`, `retiredKeys`) and the id half of a key
|
|
113
|
-
* pair (`accessKeyId`). A LOOKUP key — `cacheKey`, `primaryKey`, `idempotencyKey` — and a key's
|
|
114
|
-
* own id (`signingKeyId`) carry no qualifier on this list and stay readable.
|
|
115
|
-
* - a value that EMBEDS a credential: `connectionString`, `dsn`, a registry `authConfig`, and the
|
|
116
|
-
* service URLs that carry `user:password@` (`databaseUrl`, `REDIS_URL`). A bare `url` does not.
|
|
117
|
-
* - the one-time codes by name. Never a `code` suffix: that is the error contract's own field.
|
|
118
|
-
* - a stored hash of any of them: it is what an offline guess runs against.
|
|
119
|
-
* - a bearer by its kind as the LAST word: `credentials`, `jwt`, `bearer`, `cookies`, a session's
|
|
120
|
-
* id or key (`sessionId` IS the session), and key material by encoding (`privateKeyPem`).
|
|
121
|
-
* `credentialId`, `jwtIssuer`, `cookieName`, `privateKeyId` name a credential, not hold one.
|
|
122
|
-
* - card verification codes (`cvv`, `cvc2`) as a suffix, and a `pin` only as the WHOLE word
|
|
123
|
-
* behind an owner qualifier — three letters inside `spinner`, `shipping` or `pinned` are not one.
|
|
124
|
-
*
|
|
125
|
-
* Built from constant alternatives with no nested quantifier, so there is no input it backtracks on.
|
|
126
|
-
*/
|
|
127
|
-
const CREDENTIAL_NAME = new RegExp(
|
|
128
|
-
[
|
|
129
|
-
'passw(?:or)?d|passphrase',
|
|
130
|
-
'secrets?$',
|
|
131
|
-
'(?:api|private|signing|encryption|master|hmac|secrets?|access|retired)keys?$|accesskeyid$',
|
|
132
|
-
'(?:token|key)hash(?:es)?$',
|
|
133
|
-
'(?<!idempotency|page|continuation|cursor|sync)token$',
|
|
134
|
-
'(?:access|refresh|id|session|reset|bearer|auth|api|csrf|xsrf|captcha|card|verification|invite|magic|magiclink|device|push|workload|oauth)tokens$',
|
|
135
|
-
'authconfig$|connectionstring$|dsn$',
|
|
136
|
-
'(?:database|db|redis|replication|nats|smtp|amqp|mongo)ur[li]s?$',
|
|
137
|
-
'^totp$|totpcode$|otp$|otpcode$',
|
|
138
|
-
'(?:recovery|backup|mfa)codes?(?:hash(?:es)?)?$',
|
|
139
|
-
'credentials?$|jwts?$|bearer$|cookies?$|session(?:id|key)s?$',
|
|
140
|
-
'privatekey(?:pem|der|jwk)$',
|
|
141
|
-
'cv[vc]2?$',
|
|
142
|
-
'^(?:card|atm|security|account|user|wallet)?pin(?:code|number)?(?:hash(?:es)?)?$',
|
|
143
|
-
].join('|'),
|
|
144
|
-
);
|
|
145
|
-
|
|
146
|
-
/** Mark keys as secret everywhere. `defineEnv()` calls this for every `secret: true` var. */
|
|
147
|
-
export function redactKeys(keys: Iterable<string>): void {
|
|
148
|
-
for (const key of keys) redactedKeys.add(key.toLowerCase());
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/**
|
|
152
|
-
* The framework's ONE answer to "is this field a credential?" — the log line, the error monitor's
|
|
153
|
-
* envelope and `@ultimat3/action`'s audit row all ask it, so a value that is `[redacted]` in one
|
|
154
|
-
* cannot be plaintext in another.
|
|
155
|
-
*/
|
|
156
|
-
export function isRedactedKey(key: string): boolean {
|
|
157
|
-
const lower = key.toLowerCase();
|
|
158
|
-
return redactedKeys.has(lower) || CREDENTIAL_NAME.test(lower.replace(/[_-]/g, ''));
|
|
159
|
-
}
|
|
160
|
-
|
|
161
55
|
/**
|
|
162
56
|
* Fields injected into every line — set once by `context.ts` so `requestId`/`traceId` appear
|
|
163
57
|
* without threading the context into every call site.
|
|
@@ -225,6 +119,33 @@ export function installLogSink(sink: LogSink | undefined): () => void {
|
|
|
225
119
|
*/
|
|
226
120
|
function defaultWriter(line: string, level: LogLevel): void {
|
|
227
121
|
streamWriter(line, level);
|
|
122
|
+
for (const tee of logTees) {
|
|
123
|
+
try {
|
|
124
|
+
tee(line, level);
|
|
125
|
+
} catch {
|
|
126
|
+
// A log call is TOTAL: a tee that cannot write (a full disk under `dev.log`) costs its own
|
|
127
|
+
// copy of the line, never the caller's `log.error` nor the streams' copy, already written.
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Every installed tee, in install order. A set and never a slot: a second tee joins the first. */
|
|
133
|
+
const logTees = new Set<LogSink>();
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Hand every process-logger line to `tee` AS WELL AS the streams, until the returned release runs.
|
|
137
|
+
* The streams (or an `installLogSink` frame) still get each line, on core's own lanes — a tee adds
|
|
138
|
+
* a copy and decides nothing about where the original goes. `x dev`'s `dev.log` is the caller: a
|
|
139
|
+
* file beside the terminal, without restating which lane a level writes to. A logger given its
|
|
140
|
+
* own `writer` never reaches it, as with `installLogSink`. A tee that throws loses its own copy.
|
|
141
|
+
*/
|
|
142
|
+
export function teeLogLines(tee: LogSink): () => void {
|
|
143
|
+
// A fresh wrapper per install, so the same function teed twice is two copies and two releases.
|
|
144
|
+
const entry: LogSink = (line, level) => tee(line, level);
|
|
145
|
+
logTees.add(entry);
|
|
146
|
+
return () => {
|
|
147
|
+
logTees.delete(entry);
|
|
148
|
+
};
|
|
228
149
|
}
|
|
229
150
|
|
|
230
151
|
/** The process's streams, or the `installLogSink` seam standing in for them. */
|
|
@@ -244,83 +165,6 @@ function streamWriter(line: string, level: LogLevel): void {
|
|
|
244
165
|
stream.write(`${line}\n`);
|
|
245
166
|
}
|
|
246
167
|
|
|
247
|
-
/**
|
|
248
|
-
* TOTAL, on purpose. `lifecycle.ts` logs the value a shutdown hook threw and the value a
|
|
249
|
-
* readiness check threw — both caught, both arbitrary — so a renderer that throws here escapes
|
|
250
|
-
* `runPhase`'s catch, rejects the drain promise, and `installSignalHandlers` never reaches
|
|
251
|
-
* `process.exit(0)`: SIGTERM hangs, and `/readyz` dies with the check it was reporting on. A log
|
|
252
|
-
* line must never replace the event it describes.
|
|
253
|
-
*
|
|
254
|
-
* Degradation is per KEY, the same shape `renderMetaRecord` uses: one hostile getter must not
|
|
255
|
-
* cost a reader the fields beside it.
|
|
256
|
-
*/
|
|
257
|
-
function serialiseValue(value: unknown, depth: number): unknown {
|
|
258
|
-
try {
|
|
259
|
-
return serialise(value, depth);
|
|
260
|
-
} catch {
|
|
261
|
-
// `instanceof`, `Object.keys` and `toJSON` are all property reads on a value the framework
|
|
262
|
-
// did not build; `renderCauseValue` is the one renderer that cannot itself throw.
|
|
263
|
-
return renderCauseValue(value);
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
function serialise(value: unknown, depth: number): unknown {
|
|
268
|
-
// `JSON.stringify` raises a `TypeError` on a bigint, so the whole line died for one field.
|
|
269
|
-
if (typeof value === 'bigint') return renderCauseValue(value);
|
|
270
|
-
if (value === null || typeof value !== 'object') return value;
|
|
271
|
-
// Before every other branch: a `Secret` is redacted by VALUE, so it stays redacted under a key
|
|
272
|
-
// nobody listed — `{ dsn: secret(url) }` is the leak key-name redaction cannot see.
|
|
273
|
-
if (isSecret(value)) return REDACTED;
|
|
274
|
-
// `toISOString()` THROWS on an invalid Date, and an invalid Date is exactly the value worth
|
|
275
|
-
// logging when a schedule went wrong.
|
|
276
|
-
if (value instanceof Date) {
|
|
277
|
-
return Number.isNaN(value.getTime()) ? INVALID_DATE : value.toISOString();
|
|
278
|
-
}
|
|
279
|
-
if (isUltimateError(value)) return value.toJSON();
|
|
280
|
-
if (value instanceof Error) return { name: value.name, message: value.message };
|
|
281
|
-
if (depth >= 6) return '[depth-limit]';
|
|
282
|
-
if (Array.isArray(value)) return value.map((item) => serialiseValue(item, depth + 1));
|
|
283
|
-
const source = value as Record<string, unknown>;
|
|
284
|
-
const out: Record<string, unknown> = {};
|
|
285
|
-
for (const key of Object.keys(source)) {
|
|
286
|
-
out[key] = isRedactedKey(key) ? REDACTED : entryValue(source, key, depth);
|
|
287
|
-
}
|
|
288
|
-
return out;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
/** One field. The `try` covers the property READ — `serialiseValue` above is already total. */
|
|
292
|
-
function entryValue(source: Record<string, unknown>, key: string, depth: number): unknown {
|
|
293
|
-
try {
|
|
294
|
-
return serialiseValue(source[key], depth + 1);
|
|
295
|
-
} catch {
|
|
296
|
-
return 'a value that cannot be read';
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
/**
|
|
301
|
-
* A caller's record made safe to SERIALISE and safe to SHIP: credentials replaced by key and by
|
|
302
|
-
* value, a bigint / cycle / hostile getter degraded per field. Exported for the one other sink
|
|
303
|
-
* that sends a caller's record off the box — `error-reporter-sentry.ts`.
|
|
304
|
-
*/
|
|
305
|
-
export function redactFields(fields: LogFields): Record<string, unknown> {
|
|
306
|
-
const out: Record<string, unknown> = {};
|
|
307
|
-
const source = fields as Record<string, unknown>;
|
|
308
|
-
// `Object.keys` before the values, so the read of each value is its own guarded step: a field
|
|
309
|
-
// record is the caller's object, and enumerating it eagerly threw on the first hostile getter.
|
|
310
|
-
for (const key of ownKeys(source)) {
|
|
311
|
-
out[key] = isRedactedKey(key) ? REDACTED : entryValue(source, key, 0);
|
|
312
|
-
}
|
|
313
|
-
return out;
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
function ownKeys(source: Record<string, unknown>): readonly string[] {
|
|
317
|
-
try {
|
|
318
|
-
return Object.keys(source);
|
|
319
|
-
} catch {
|
|
320
|
-
return [];
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
|
|
324
168
|
/**
|
|
325
169
|
* The last guard. The walk above already degraded every hostile field, so reaching the fallback
|
|
326
170
|
* means the assembled line itself refused to serialise — and the answer to that is still a line,
|
|
@@ -388,12 +232,11 @@ function envLevel(): LogLevel {
|
|
|
388
232
|
// to `info` in silence, so `LOG_LEVEL=verbose` — or `DEBUG`, the spelling half the ecosystem
|
|
389
233
|
// uses — gave an operator who asked for MORE lines fewer, and nothing said the variable was the
|
|
390
234
|
// reason. This runs at module init, so the refusal is the first thing the process prints.
|
|
391
|
-
|
|
392
|
-
|
|
235
|
+
if (isLogLevel(raw)) return raw;
|
|
236
|
+
return refuse(
|
|
393
237
|
`LOG_LEVEL=${renderCauseValue(raw)} is not a log level`,
|
|
394
238
|
`set LOG_LEVEL=info (one of ${LOG_LEVELS.join(', ')}, lowercase), or unset LOG_LEVEL`,
|
|
395
239
|
);
|
|
396
|
-
return raw as LogLevel;
|
|
397
240
|
}
|
|
398
241
|
|
|
399
242
|
/**
|
|
@@ -406,15 +249,24 @@ function envLevel(): LogLevel {
|
|
|
406
249
|
* is typed here and arrives untyped: an `app.config.ts` value, a JSON file, a CLI flag.
|
|
407
250
|
*/
|
|
408
251
|
function resolveLevel(declared: LogLevel): LogLevel {
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
252
|
+
if (isLogLevel(declared)) return declared;
|
|
253
|
+
// `renderCauseValue`, never `JSON.stringify`: it raises on a bigint and on a cycle, and a level
|
|
254
|
+
// that arrived from a config file can be either — the refusal must not be replaced by a
|
|
255
|
+
// `TypeError` from building its own message. Built only HERE, on the refusal: `ctxOf` derives a
|
|
256
|
+
// logger per request, and rendering a message nobody throws was most of what that cost.
|
|
257
|
+
return refuse(
|
|
414
258
|
`${renderCauseValue(declared)} is not a log level`,
|
|
415
259
|
`pass one of ${LOG_LEVELS.join(', ')} to structuredLogger({ level })`,
|
|
416
260
|
);
|
|
417
|
-
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function isLogLevel(value: unknown): value is LogLevel {
|
|
264
|
+
return (LOG_LEVELS as readonly unknown[]).includes(value);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** `X_INVARIANT`, as `assert` throws it — called only once the refusal is certain. */
|
|
268
|
+
function refuse(cause: string, fix: string): never {
|
|
269
|
+
assert(false, cause, fix);
|
|
418
270
|
}
|
|
419
271
|
|
|
420
272
|
/** The keys a line owns. A caller field spelled like one is renamed, never allowed to replace it. */
|
|
@@ -435,17 +287,51 @@ function unreserved(fields: Record<string, unknown>): Record<string, unknown> {
|
|
|
435
287
|
|
|
436
288
|
export function structuredLogger(options?: LoggerOptions): Logger {
|
|
437
289
|
const level = options?.level === undefined ? envLevel() : resolveLevel(options.level);
|
|
438
|
-
const bound = options?.fields ?? {};
|
|
439
|
-
|
|
440
|
-
|
|
290
|
+
const bound = bind(options?.fields ?? {});
|
|
291
|
+
return derive(level, bound, options?.clock ?? liveClock, options?.writer ?? defaultWriter);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* A logger's bound fields: the caller's own, kept, and their redaction at `generation`. Redacted
|
|
296
|
+
* once when bound, and again only when `redactKeys()` has declared a new secret since — `defineEnv`
|
|
297
|
+
* runs it at boot, after a module-scope `logger.child()` may already have bound that very key.
|
|
298
|
+
*/
|
|
299
|
+
interface Bound {
|
|
300
|
+
readonly raw: LogFields;
|
|
301
|
+
redacted: Readonly<Record<string, unknown>>;
|
|
302
|
+
generation: number;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function bind(raw: LogFields): Bound {
|
|
306
|
+
return { raw, redacted: redactFields(raw), generation: redactionGeneration() };
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** The redacted snapshot, re-walked from `raw` only if a key was declared secret since. */
|
|
310
|
+
function current(bound: Bound): Readonly<Record<string, unknown>> {
|
|
311
|
+
const now = redactionGeneration();
|
|
312
|
+
if (bound.generation !== now) {
|
|
313
|
+
bound.redacted = redactFields(bound.raw);
|
|
314
|
+
bound.generation = now;
|
|
315
|
+
}
|
|
316
|
+
return bound.redacted;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* The logger itself, past every screen: `level` is already one of `LOG_LEVELS` and `bound` is
|
|
321
|
+
* already redacted. `child()` comes back through here and never through `structuredLogger`, so a
|
|
322
|
+
* per-request child (`ctxOf`) neither re-validates a level it inherited nor re-walks the fields its
|
|
323
|
+
* parent bound — only its own, once, when it binds them.
|
|
324
|
+
*/
|
|
325
|
+
function derive(level: LogLevel, bound: Bound, clock: Clock, writer: LogSink): Logger {
|
|
441
326
|
const threshold = LEVEL_WEIGHT[level];
|
|
442
327
|
|
|
443
328
|
function emit(lineLevel: LogLevel, message: string, fields?: LogFields): void {
|
|
444
329
|
if (LEVEL_WEIGHT[lineLevel] < threshold) return;
|
|
330
|
+
const context = contextFields();
|
|
445
331
|
const caller = {
|
|
446
|
-
...
|
|
447
|
-
...
|
|
448
|
-
...
|
|
332
|
+
...current(bound),
|
|
333
|
+
...(context === undefined ? undefined : redactFields(context)),
|
|
334
|
+
...(fields === undefined ? undefined : redactFields(fields)),
|
|
449
335
|
};
|
|
450
336
|
const line = {
|
|
451
337
|
ts: timestamp(clock),
|
|
@@ -469,8 +355,17 @@ export function structuredLogger(options?: LoggerOptions): Logger {
|
|
|
469
355
|
warn: (message, fields) => emit('warn', message, fields),
|
|
470
356
|
error: (message, fields) => emit('error', message, fields),
|
|
471
357
|
fatal: (message, fields) => emit('fatal', message, fields),
|
|
472
|
-
child: (fields) =>
|
|
473
|
-
|
|
358
|
+
child: (fields) => {
|
|
359
|
+
const parent = current(bound);
|
|
360
|
+
const child: Bound = {
|
|
361
|
+
raw: { ...bound.raw, ...fields },
|
|
362
|
+
redacted: { ...parent, ...redactFields(fields) },
|
|
363
|
+
generation: bound.generation,
|
|
364
|
+
};
|
|
365
|
+
return derive(level, child, clock, writer);
|
|
366
|
+
},
|
|
367
|
+
// A public door, so the level is screened again: a child cannot widen what the parent refused.
|
|
368
|
+
withLevel: (next) => derive(resolveLevel(next), bound, clock, writer),
|
|
474
369
|
};
|
|
475
370
|
}
|
|
476
371
|
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// Single responsibility: a concurrent map with a stated width — results in input order, the first
|
|
2
|
+
// rejection (or the caller's abort) stops every item not yet started and tells the in-flight ones.
|
|
3
|
+
|
|
4
|
+
import { renderThrowable } from './error-render';
|
|
5
|
+
import { UltimateError } from './errors';
|
|
6
|
+
import { finiteCount } from './finite-option';
|
|
7
|
+
|
|
8
|
+
export interface MapBoundedOptions {
|
|
9
|
+
/**
|
|
10
|
+
* How many items run at once. REQUIRED, with no default: the right width is a fact about the
|
|
11
|
+
* thing being called — a vendor's rate limit, a pool's size — and only the caller knows it.
|
|
12
|
+
*/
|
|
13
|
+
readonly width: number;
|
|
14
|
+
/** The deadline or the caller going away. Aborting stops every item not yet started. */
|
|
15
|
+
readonly signal?: AbortSignal | undefined;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* `Promise.all(items.map(fn))` with at most `width` in flight. `fn` receives a signal that aborts
|
|
20
|
+
* on the first rejection — its reason IS that rejection — or when `options.signal` aborts, so a
|
|
21
|
+
* well-behaved `fn` stops its own work too; nothing new starts after either.
|
|
22
|
+
*
|
|
23
|
+
* Rejects AT ONCE with the first failure, as `Promise.all` does: a sibling that ignores its signal
|
|
24
|
+
* cannot hold the answer hostage. A later sibling's rejection is swallowed, never unhandled.
|
|
25
|
+
*/
|
|
26
|
+
export async function mapBounded<T, R>(
|
|
27
|
+
items: readonly T[],
|
|
28
|
+
fn: (item: T, index: number, signal: AbortSignal) => R | Promise<R>,
|
|
29
|
+
options: MapBoundedOptions,
|
|
30
|
+
): Promise<R[]> {
|
|
31
|
+
const width = finiteCount('mapBounded', 'width', options.width, 1);
|
|
32
|
+
const outer = options.signal;
|
|
33
|
+
if (outer?.aborted) throw aborted(outer.reason, 0, items.length);
|
|
34
|
+
const results = new Array<R>(items.length);
|
|
35
|
+
if (items.length === 0) return results;
|
|
36
|
+
|
|
37
|
+
const controller = new AbortController();
|
|
38
|
+
let next = 0;
|
|
39
|
+
let completed = 0;
|
|
40
|
+
return new Promise<R[]>((resolve, reject) => {
|
|
41
|
+
const fail = (error: unknown): void => {
|
|
42
|
+
if (controller.signal.aborted) return;
|
|
43
|
+
outer?.removeEventListener('abort', onAbort);
|
|
44
|
+
controller.abort(error);
|
|
45
|
+
reject(error);
|
|
46
|
+
};
|
|
47
|
+
const onAbort = (): void => fail(aborted(outer?.reason, completed, items.length));
|
|
48
|
+
outer?.addEventListener('abort', onAbort, { once: true });
|
|
49
|
+
|
|
50
|
+
// No abort check here: `pull` runs only in the synchronous first loop or past the success
|
|
51
|
+
// branch's own check, so an aborted map never reaches it.
|
|
52
|
+
const pull = (): void => {
|
|
53
|
+
if (next >= items.length) return;
|
|
54
|
+
const index = next++;
|
|
55
|
+
// `.then` rather than a direct call: a SYNCHRONOUS throw in `fn` becomes this item's
|
|
56
|
+
// rejection instead of escaping the runner that pulled it.
|
|
57
|
+
Promise.resolve()
|
|
58
|
+
.then(() => fn(items[index] as T, index, controller.signal))
|
|
59
|
+
.then((value) => {
|
|
60
|
+
if (controller.signal.aborted) return;
|
|
61
|
+
results[index] = value;
|
|
62
|
+
completed += 1;
|
|
63
|
+
if (completed === items.length) {
|
|
64
|
+
outer?.removeEventListener('abort', onAbort);
|
|
65
|
+
resolve(results);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
pull();
|
|
69
|
+
}, fail);
|
|
70
|
+
};
|
|
71
|
+
for (let slot = 0; slot < Math.min(width, items.length); slot += 1) pull();
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function aborted(reason: unknown, completed: number, total: number): UltimateError {
|
|
76
|
+
return new UltimateError({
|
|
77
|
+
code: 'X_ABORTED',
|
|
78
|
+
cause: `mapBounded stopped with ${completed} of ${total} items done: its signal aborted (${renderThrowable(reason)})`,
|
|
79
|
+
fix: 'mapBounded(items, fn, { width, signal: AbortSignal.timeout(<ms>) }) # a larger <ms> or width when the signal is a deadline; a caller that went away left nothing to finish',
|
|
80
|
+
meta: { completed, total },
|
|
81
|
+
});
|
|
82
|
+
}
|
package/src/metric-series.ts
CHANGED
|
@@ -29,7 +29,7 @@ const OVERFLOW_ATTRIBUTES: MetricAttributes = Object.freeze({ [OVERFLOW_ATTRIBUT
|
|
|
29
29
|
* answer and is not slower: 644 ns/op against the join's 709, on a 3-label set. `String(value)`
|
|
30
30
|
* stays, so `1` and `'1'` are still one series rather than two rows an exporter renders alike.
|
|
31
31
|
*/
|
|
32
|
-
function
|
|
32
|
+
function buildKey(attributes: MetricAttributes): string {
|
|
33
33
|
const entries = Object.entries(attributes);
|
|
34
34
|
if (entries.length === 0) return '';
|
|
35
35
|
return JSON.stringify(
|
|
@@ -37,6 +37,23 @@ function seriesKey(attributes: MetricAttributes): string {
|
|
|
37
37
|
);
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
+
/**
|
|
41
|
+
* Keys of FROZEN label sets, by identity. A frozen set cannot spell another key later, so its key
|
|
42
|
+
* is built once however many instruments it is handed to — `recordRequest` gives one set to two
|
|
43
|
+
* (measured: two `JSON.stringify` per request before, one per distinct set now). A mutable set is
|
|
44
|
+
* keyed every call: caching it by identity would file a mutated set under its old labels.
|
|
45
|
+
*/
|
|
46
|
+
const frozenKeys = new WeakMap<MetricAttributes, string>();
|
|
47
|
+
|
|
48
|
+
function seriesKey(attributes: MetricAttributes): string {
|
|
49
|
+
if (!Object.isFrozen(attributes)) return buildKey(attributes);
|
|
50
|
+
const known = frozenKeys.get(attributes);
|
|
51
|
+
if (known !== undefined) return known;
|
|
52
|
+
const key = buildKey(attributes);
|
|
53
|
+
frozenKeys.set(attributes, key);
|
|
54
|
+
return key;
|
|
55
|
+
}
|
|
56
|
+
|
|
40
57
|
/**
|
|
41
58
|
* Reported through the logger rather than thrown: the call site is `orderCounter.add(1, …)` deep
|
|
42
59
|
* inside a request, and killing that request would turn a metrics bug into a user-visible outage
|
|
@@ -57,7 +74,9 @@ function reportOverflow(instrument: Instrument): void {
|
|
|
57
74
|
|
|
58
75
|
function createSeries(instrument: Instrument, key: string, attributes: MetricAttributes): Series {
|
|
59
76
|
const created: Series = {
|
|
60
|
-
|
|
77
|
+
// A frozen COPY, once per series: a caller reusing one mutable object for its labels used to
|
|
78
|
+
// rename the series it had already filed, so the export carried labels no point was added under.
|
|
79
|
+
attributes: Object.isFrozen(attributes) ? attributes : Object.freeze({ ...attributes }),
|
|
61
80
|
value: 0,
|
|
62
81
|
count: 0,
|
|
63
82
|
min: Number.POSITIVE_INFINITY,
|
|
@@ -71,7 +90,11 @@ function createSeries(instrument: Instrument, key: string, attributes: MetricAtt
|
|
|
71
90
|
const OVERFLOW_KEY = seriesKey(OVERFLOW_ATTRIBUTES);
|
|
72
91
|
|
|
73
92
|
export function seriesFor(instrument: Instrument, attributes: MetricAttributes): Series {
|
|
74
|
-
|
|
93
|
+
return seriesForKey(instrument, seriesKey(attributes), attributes);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** `seriesFor` with the key already built: `key` MUST be `seriesKey(attributes)`. */
|
|
97
|
+
function seriesForKey(instrument: Instrument, key: string, attributes: MetricAttributes): Series {
|
|
75
98
|
const found = instrument.series.get(key);
|
|
76
99
|
if (found !== undefined) return found;
|
|
77
100
|
// On the MISS, ahead of the ceiling — never inside `createSeries`, which the overflow branch
|
package/src/outbound.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import type { Schema } from '@ultimat3/schema';
|
|
7
7
|
import type { Breaker } from './breaker';
|
|
8
8
|
import { settleWith } from './breaker';
|
|
9
|
+
import { retryBudgetOf } from './breaker-retry-budget';
|
|
9
10
|
import { systemClock } from './clock';
|
|
10
11
|
import { tryUseContext } from './context';
|
|
11
12
|
import { platformDeadlineTimer } from './deadline-signal';
|
|
@@ -164,13 +165,19 @@ export async function outbound(
|
|
|
164
165
|
): Promise<OutboundAnswer | OutboundStreamAnswer> {
|
|
165
166
|
const call = prepare(request, deps);
|
|
166
167
|
const policy = policyFor(request, call.site);
|
|
167
|
-
|
|
168
|
-
|
|
168
|
+
// Per breaker key: retries at most a fifth of calls, so a partial outage the breaker does not
|
|
169
|
+
// trip on is not multiplied by the attempt count. A refused retry answers the last attempt's code.
|
|
170
|
+
const budget = request.breaker === undefined ? undefined : retryBudgetOf(request.breaker);
|
|
171
|
+
const work = (): Promise<AttemptAnswer> => {
|
|
172
|
+
budget?.called();
|
|
173
|
+
return retry((attempt) => runAttempt(call, attempt), policy, {
|
|
169
174
|
sleep:
|
|
170
175
|
deps.sleep ?? (request.signal === undefined ? undefined : signalledSleep(request.signal)),
|
|
171
176
|
now: call.now,
|
|
172
177
|
random: deps.random,
|
|
178
|
+
admitRetry: budget?.spend,
|
|
173
179
|
});
|
|
180
|
+
};
|
|
174
181
|
const answer = await instrumentedCall(
|
|
175
182
|
{ vendor: call.site.vendor, method: call.method, url: call.url },
|
|
176
183
|
() => (request.breaker === undefined ? work() : guarded(request.breaker, request.signal, work)),
|
package/src/retry-loop.ts
CHANGED
|
@@ -121,6 +121,12 @@ export interface RetryLoopDeps {
|
|
|
121
121
|
random?: Random | undefined;
|
|
122
122
|
/** The caller's lifetime. Nothing is tried, and nothing is waited for, once it has aborted. */
|
|
123
123
|
signal?: AbortSignal | undefined;
|
|
124
|
+
/**
|
|
125
|
+
* Asked once per retry the policy WOULD run, before its wait; `false` stops the loop with the
|
|
126
|
+
* last error, unchanged. A share of retries across calls (`breaker-retry-budget.ts`) that no
|
|
127
|
+
* per-call policy can see.
|
|
128
|
+
*/
|
|
129
|
+
admitRetry?: (() => boolean) | undefined;
|
|
124
130
|
}
|
|
125
131
|
|
|
126
132
|
/** The wait, ended at once by an abort whatever `sleep` was injected. A rejected sleep propagates. */
|
|
@@ -190,6 +196,8 @@ export async function retryLoop<T>(
|
|
|
190
196
|
// Decided BEFORE the wait, never after: a loop that sleeps and then discovers it is out of
|
|
191
197
|
// budget has already spent the caller's deadline on a wait nobody could use.
|
|
192
198
|
if (budget !== undefined && now() - startedAt + decision.delayMs > budget) throw error;
|
|
199
|
+
// Last, so a token is spent only on a retry that will actually be sent.
|
|
200
|
+
if (deps.admitRetry !== undefined && !deps.admitRetry()) throw error;
|
|
193
201
|
failed = { error };
|
|
194
202
|
await waitOut(deps, decision.delayMs);
|
|
195
203
|
}
|
package/src/retry.ts
CHANGED
|
@@ -15,6 +15,8 @@ export interface RetryDeps {
|
|
|
15
15
|
/** Monotonic ms, read only when a time budget applies. Defaults to the system clock. */
|
|
16
16
|
now?: (() => number) | undefined;
|
|
17
17
|
random?: Random | undefined;
|
|
18
|
+
/** Asked before each retry's wait; `false` ends the loop with the last error (`retryLoop`). */
|
|
19
|
+
admitRetry?: (() => boolean) | undefined;
|
|
18
20
|
}
|
|
19
21
|
|
|
20
22
|
/** A timer an abort lets go of, so a retry abandoned mid-wait holds nothing for the full delay. */
|
|
@@ -63,5 +65,6 @@ export async function retry<T>(
|
|
|
63
65
|
now: deps.now,
|
|
64
66
|
random: deps.random,
|
|
65
67
|
signal: ctx?.signal,
|
|
68
|
+
admitRetry: deps.admitRetry,
|
|
66
69
|
});
|
|
67
70
|
}
|
package/src/runtime-metrics.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// scales on, this says which series carries it, and `docker/helm` reads the same three words.
|
|
4
4
|
|
|
5
5
|
import type { Counter, Gauge } from './metrics';
|
|
6
|
-
import { counter, gauge, type Histogram, histogram } from './metrics';
|
|
6
|
+
import { counter, DEFAULT_MAX_SERIES, gauge, type Histogram, histogram } from './metrics';
|
|
7
7
|
import type { ScalingSignal } from './roles';
|
|
8
8
|
|
|
9
9
|
/**
|
|
@@ -69,15 +69,42 @@ export interface RequestSample {
|
|
|
69
69
|
* return, and no autoscaler asks the difference between 201 and 204.
|
|
70
70
|
*/
|
|
71
71
|
export function recordRequest(sample: RequestSample): void {
|
|
72
|
-
const attributes =
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
72
|
+
const attributes = requestAttributes(
|
|
73
|
+
sample.method,
|
|
74
|
+
sample.route,
|
|
75
|
+
Math.floor(sample.status / 100),
|
|
76
|
+
);
|
|
77
77
|
requests.add(1, attributes);
|
|
78
78
|
requestDuration.record(sample.durationMs / 1000, attributes);
|
|
79
79
|
}
|
|
80
80
|
|
|
81
|
+
type RequestAttributes = Readonly<{ method: string; route: string; status: string }>;
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* One FROZEN label set per (method, route, class), so the series key behind it is built once for
|
|
85
|
+
* the process (`metric-series.ts` keys a frozen set by identity) instead of twice per request.
|
|
86
|
+
* Nested maps, never a joined string key: a delimiter is spellable by a value. Bounded at the
|
|
87
|
+
* instrument's own ceiling; past it a fresh frozen set still shares its one key across both
|
|
88
|
+
* instruments, and the series store's overflow handles the cardinality.
|
|
89
|
+
*/
|
|
90
|
+
const requestLabels = new Map<string, Map<string, Map<number, RequestAttributes>>>();
|
|
91
|
+
let requestLabelCount = 0;
|
|
92
|
+
|
|
93
|
+
function requestAttributes(method: string, route: string, statusClass: number): RequestAttributes {
|
|
94
|
+
const byRoute = requestLabels.get(method);
|
|
95
|
+
const cached = byRoute?.get(route)?.get(statusClass);
|
|
96
|
+
if (cached !== undefined) return cached;
|
|
97
|
+
const built = Object.freeze({ method, route, status: `${statusClass}xx` });
|
|
98
|
+
if (requestLabelCount >= DEFAULT_MAX_SERIES) return built;
|
|
99
|
+
const routes = byRoute ?? new Map<string, Map<number, RequestAttributes>>();
|
|
100
|
+
requestLabels.set(method, routes);
|
|
101
|
+
const classes = routes.get(route) ?? new Map<number, RequestAttributes>();
|
|
102
|
+
routes.set(route, classes);
|
|
103
|
+
classes.set(statusClass, built);
|
|
104
|
+
requestLabelCount += 1;
|
|
105
|
+
return built;
|
|
106
|
+
}
|
|
107
|
+
|
|
81
108
|
/** `+1` on connect, `-1` on close, from the realtime transport. */
|
|
82
109
|
export function recordConnection(delta: number): void {
|
|
83
110
|
connections.add(delta);
|