@ultimat3/core 31.49.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/README.md +1 -1
- package/package.json +2 -2
- package/src/client-scope-id.ts +10 -3
- package/src/env.ts +54 -6
- package/src/outbound-attempt.ts +74 -22
- package/src/outbound-errors.ts +40 -6
- package/src/outbound-hops.ts +11 -1
- package/src/outbound-subpath.ts +1 -0
- package/src/outbound-types.ts +30 -1
- package/src/outbound.ts +1 -0
package/README.md
CHANGED
|
@@ -957,7 +957,7 @@ Server-only, on its own subpath: `import { outbound, screenDial } from '@ultimat
|
|
|
957
957
|
|
|
958
958
|
| Export | The one answer | The question it settles |
|
|
959
959
|
|---|---|---|
|
|
960
|
-
| `outbound({ url, vendor, dial, deadlineMs, method?, headers?, body?, idleMs?, maxBytes?, redirect?, retry?, idempotent?, read?, breaker?, proxy? }, deps?)` | a vendor call | a whole-call deadline clamped by the ambient request, `ctx.signal` (its reason unchanged), core's `retry()` for safe methods only (`X_OUTBOUND_RETRY_UNSAFE`), `Retry-After`, an idle watchdog and a byte cap on the body, `redirect: 'error'` by default, and
|
|
960
|
+
| `outbound({ url, vendor, dial, deadlineMs, method?, headers?, body?, idleMs?, maxBytes?, redirect?, retry?, idempotent?, read?, breaker?, proxy?, refusal? }, deps?)` | a vendor call | a whole-call deadline clamped by the ambient request, `ctx.signal` (its reason unchanged), core's `retry()` for safe methods only (`X_OUTBOUND_RETRY_UNSAFE`), `Retry-After`, an idle watchdog and a byte cap on the body, `redirect: 'error'` by default, and twelve `X_OUTBOUND_*` codes whose causes carry no query and no header. `dial: 'public'` is the SSRF screen for a user-supplied URL (resolve, classify every address, pin, re-screen each hop): never a hand-written guard. `proxy` (a URL, `{ url, headers }`, or a per-hop resolver `(target) => … \| undefined`, types `OutboundProxy`, `OutboundProxyTarget`, `OutboundProxyInit`) is chosen AFTER the screen, so a public dial is tunnelled to the approved address with `tls.serverName` intact; its credential is never logged; a bad one is `X_OUTBOUND_PROXY_INVALID`. Inventory and rotation are app code. `deps` injects `fetch`, `resolve`, `sleep`, `now`, `random`, `timer`, `env`. `fetch` is a production seam too: it is handed the screened url and `redirect: 'manual'`, the caps and rules stay `outbound()`'s, and an answer it reached by following a redirect itself is `X_OUTBOUND_TRANSPORT_REDIRECTED`. `refusal` (`OutboundRefusalRead`): `{ schema }` reads a non-2xx body whole, within `maxBytes`, and puts the schema's redacted answer at `meta.fields`; `{ detail: false }` keeps `meta.detail` at `''` |
|
|
961
961
|
| `screenDial(url, { resolve?, allowPrivate? })` → `{ pin } \| { refused } \| { unresolved }` | where a dial may land | every resolved address classified by `classifyAddress`, the connection pinned with `tls.serverName`. The framework's one `Bun.dns.lookup` (`resolveDialHost`); `@ultimat3/jobs`' webhook target and `@ultimat3/scraping` call it and keep their own codes |
|
|
962
962
|
| `deadlineSignal(ms, outer?, timer?)` | one attempt's signal | a deadline plus the caller's signal, undone on dispose (no listener left on `outer`, no timer armed) |
|
|
963
963
|
| `breaker({ name, failures, cooldownMs, classify?, clock? })` → `admit`, `succeeded`, `failed`, `released`, `state`, `failures`, `judge`, `refusal`, `run` | is a dependency down | one state machine, the trigger stays the caller's. One probe in `half-open`, lapsing after `cooldownMs`; `X_BREAKER_OPEN` names `retryAfterSeconds`; `breaker_transitions_total{name,to}`. Per process |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/core",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.50.0",
|
|
4
4
|
"description": "Ultimate's foundation: errors, context, env, config, clock, ids, logging, telemetry, lifecycle",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -55,6 +55,6 @@
|
|
|
55
55
|
"test": "bun test"
|
|
56
56
|
},
|
|
57
57
|
"dependencies": {
|
|
58
|
-
"@ultimat3/schema": "31.
|
|
58
|
+
"@ultimat3/schema": "31.50.0"
|
|
59
59
|
}
|
|
60
60
|
}
|
package/src/client-scope-id.ts
CHANGED
|
@@ -24,15 +24,22 @@ export interface ClientScopeIdOptions {
|
|
|
24
24
|
/** Minted on first need when no `SESSION_SECRET` exists: stable per process, never per request. */
|
|
25
25
|
let processKey: string | undefined;
|
|
26
26
|
|
|
27
|
-
/**
|
|
27
|
+
/**
|
|
28
|
+
* `''` for the anonymous actor; otherwise the principal, who is really acting, and the tenant. One
|
|
29
|
+
* person in two orgs is two scopes: a page, a store or a queued write rendered under one org must
|
|
30
|
+
* never be reused under the other. No org leaves the material, and so the id, as it always was.
|
|
31
|
+
*/
|
|
28
32
|
export function clientScopeId(actor: Actor, options: ClientScopeIdOptions = {}): string {
|
|
29
33
|
if (actor.kind === 'anonymous') return '';
|
|
30
|
-
const
|
|
34
|
+
const principal = [
|
|
31
35
|
actor.kind,
|
|
32
36
|
actor.id,
|
|
33
37
|
actor.onBehalfOf?.actorKind ?? null,
|
|
34
38
|
actor.onBehalfOf?.actorId ?? null,
|
|
35
|
-
]
|
|
39
|
+
];
|
|
40
|
+
const material = JSON.stringify(
|
|
41
|
+
actor.orgId === undefined ? principal : [...principal, actor.orgId],
|
|
42
|
+
);
|
|
36
43
|
return hmac('sha256', scopeKey(options), material, 'hex').slice(0, SCOPE_HEX_CHARS);
|
|
37
44
|
}
|
|
38
45
|
|
package/src/env.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// discover six missing variables.
|
|
4
4
|
|
|
5
5
|
import { numeric } from '@ultimat3/schema';
|
|
6
|
-
import { tryResolveEnvironment } from './environment';
|
|
6
|
+
import { type Environment, tryResolveEnvironment } from './environment';
|
|
7
7
|
import { describeValue, renderFixShellArg } from './error-render';
|
|
8
8
|
import { EnvMissingError } from './errors';
|
|
9
9
|
import { isRedactedKey, REDACTED, redactKeys } from './logger';
|
|
@@ -28,12 +28,28 @@ interface EnvVarCommon {
|
|
|
28
28
|
}
|
|
29
29
|
|
|
30
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;
|
|
31
39
|
readonly type: 'string' | 'url';
|
|
32
40
|
readonly default?: string | undefined;
|
|
33
41
|
readonly pattern?: RegExp | undefined;
|
|
34
42
|
}
|
|
35
43
|
|
|
36
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;
|
|
37
53
|
readonly type: 'number' | 'integer' | 'port';
|
|
38
54
|
readonly default?: number | undefined;
|
|
39
55
|
readonly min?: number | undefined;
|
|
@@ -41,11 +57,27 @@ export interface EnvNumberVar extends EnvVarCommon {
|
|
|
41
57
|
}
|
|
42
58
|
|
|
43
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;
|
|
44
68
|
readonly type: 'boolean';
|
|
45
69
|
readonly default?: boolean | undefined;
|
|
46
70
|
}
|
|
47
71
|
|
|
48
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;
|
|
49
81
|
readonly type: 'enum';
|
|
50
82
|
readonly values: readonly V[];
|
|
51
83
|
readonly default?: V | undefined;
|
|
@@ -102,10 +134,22 @@ export interface EnvOptions {
|
|
|
102
134
|
const TRUE_VALUES = new Set(['1', 'true', 'yes', 'on']);
|
|
103
135
|
const FALSE_VALUES = new Set(['0', 'false', 'no', 'off']);
|
|
104
136
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
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);
|
|
109
153
|
}
|
|
110
154
|
|
|
111
155
|
function expectation(decl: EnvVarDecl): string {
|
|
@@ -231,6 +275,7 @@ function generatedFix(
|
|
|
231
275
|
export function checkEnv(schema: EnvSchema, options?: EnvOptions): EnvCheckReport {
|
|
232
276
|
const source = options?.env ?? (process.env as Record<string, string | undefined>);
|
|
233
277
|
const role = options?.role ?? resolveRole({ env: source });
|
|
278
|
+
const environment = tryResolveEnvironment({ env: source });
|
|
234
279
|
const issues: EnvIssue[] = [];
|
|
235
280
|
const values: Record<string, unknown> = {};
|
|
236
281
|
|
|
@@ -241,7 +286,7 @@ export function checkEnv(schema: EnvSchema, options?: EnvOptions): EnvCheckRepor
|
|
|
241
286
|
values[key] = decl.default;
|
|
242
287
|
continue;
|
|
243
288
|
}
|
|
244
|
-
if (requiredForRole(decl, role)) {
|
|
289
|
+
if (requiredForRole(decl, role, environment)) {
|
|
245
290
|
issues.push({
|
|
246
291
|
key,
|
|
247
292
|
reason: 'missing',
|
|
@@ -346,6 +391,8 @@ export interface EnvVarSummary {
|
|
|
346
391
|
readonly secret: boolean;
|
|
347
392
|
readonly hasDefault: boolean;
|
|
348
393
|
readonly roles: readonly Role[] | 'all';
|
|
394
|
+
/** `requiredIn`, when an optional key names the environments that require it. */
|
|
395
|
+
readonly requiredIn?: readonly Environment[];
|
|
349
396
|
readonly description: string | undefined;
|
|
350
397
|
}
|
|
351
398
|
|
|
@@ -362,6 +409,7 @@ export function describeEnv(schema: EnvSchema): readonly EnvVarSummary[] {
|
|
|
362
409
|
secret: decl.secret === true,
|
|
363
410
|
hasDefault: decl.default !== undefined,
|
|
364
411
|
roles: decl.role === undefined ? 'all' : rolesOf(decl.role),
|
|
412
|
+
...(decl.requiredIn === undefined ? {} : { requiredIn: decl.requiredIn }),
|
|
365
413
|
description: decl.description,
|
|
366
414
|
}));
|
|
367
415
|
}
|
package/src/outbound-attempt.ts
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
// Single responsibility: ONE attempt of an `outbound()` call — its signal, its hops, its status
|
|
2
|
-
// read as a coded answer
|
|
3
|
-
// is classified here, so `retry()` above it reads a
|
|
4
|
-
//
|
|
2
|
+
// read as a coded answer (a refusal's body as the call's `refusal` asks), and its body under the
|
|
3
|
+
// idle watchdog and the cap. Every way it ends is classified here, so `retry()` above it reads a
|
|
4
|
+
// code, never an unclassified throw (measured: one from a POST ran three attempts).
|
|
5
5
|
|
|
6
|
+
import type { Schema } from '@ultimat3/schema';
|
|
6
7
|
import { retryAfterSecondsOf } from './client-retry-after';
|
|
7
8
|
import { tryUseContext } from './context';
|
|
8
9
|
import type { DeadlineTimer } from './deadline-signal';
|
|
9
10
|
import { deadlineSignal } from './deadline-signal';
|
|
10
11
|
import { isUltimateError } from './errors';
|
|
11
12
|
import { logger, redactFields } from './logger';
|
|
12
|
-
import type { OutboundSite } from './outbound-errors';
|
|
13
13
|
import {
|
|
14
14
|
callerDeadline,
|
|
15
15
|
outboundRedirected,
|
|
@@ -24,6 +24,7 @@ import type { HopCall } from './outbound-hops';
|
|
|
24
24
|
import { redactedLocation, sendHops } from './outbound-hops';
|
|
25
25
|
import type { WatchedFailure } from './outbound-read';
|
|
26
26
|
import { watchedBody } from './outbound-read';
|
|
27
|
+
import type { OutboundRefusalRead } from './outbound-types';
|
|
27
28
|
import { readWithinLimit } from './read-capped';
|
|
28
29
|
import { isRetryableStatus } from './retryable-status';
|
|
29
30
|
|
|
@@ -36,6 +37,8 @@ export interface AttemptCall extends HopCall {
|
|
|
36
37
|
readonly idleMs: number;
|
|
37
38
|
readonly maxBytes: number;
|
|
38
39
|
readonly read: 'bytes' | 'stream';
|
|
40
|
+
/** How a non-2xx body is read for the error; `undefined` is the default excerpt. */
|
|
41
|
+
readonly refusal: OutboundRefusalRead | undefined;
|
|
39
42
|
readonly now: () => number;
|
|
40
43
|
readonly timer: DeadlineTimer;
|
|
41
44
|
}
|
|
@@ -49,6 +52,12 @@ export type AttemptAnswer =
|
|
|
49
52
|
readonly stream: ReadableStream<Uint8Array>;
|
|
50
53
|
};
|
|
51
54
|
|
|
55
|
+
/** What the error carries from the body. */
|
|
56
|
+
interface RefusalBody {
|
|
57
|
+
readonly detail: string;
|
|
58
|
+
readonly fields?: unknown;
|
|
59
|
+
}
|
|
60
|
+
|
|
52
61
|
/** How many bytes of a refusal's body are read for its `meta.detail`, and how much is kept. */
|
|
53
62
|
const DETAIL_READ_BYTES = 1_024;
|
|
54
63
|
const DETAIL_CHARS = 200;
|
|
@@ -70,22 +79,64 @@ async function prefixOf(body: ReadableStream<Uint8Array>): Promise<string> {
|
|
|
70
79
|
return text;
|
|
71
80
|
}
|
|
72
81
|
|
|
73
|
-
|
|
74
|
-
async function detailOf(body: ReadableStream<Uint8Array>): Promise<string> {
|
|
75
|
-
let text = '';
|
|
82
|
+
const parsedJson = (text: string): { readonly value: unknown } | undefined => {
|
|
76
83
|
try {
|
|
77
|
-
|
|
84
|
+
return { value: JSON.parse(text) };
|
|
78
85
|
} catch {
|
|
79
|
-
return
|
|
86
|
+
return undefined;
|
|
80
87
|
}
|
|
81
|
-
|
|
82
|
-
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* A JSON OBJECT, redacted by key, or nothing: raw text is never kept. A body cut at the prefix,
|
|
92
|
+
* an array, a form (`client_secret=…`) or an HTML page carries a credential no key names.
|
|
93
|
+
*/
|
|
94
|
+
function detailOf(text: string): string {
|
|
95
|
+
const parsed = parsedJson(text)?.value;
|
|
96
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return '';
|
|
97
|
+
return JSON.stringify(redactFields(parsed as Record<string, unknown>)).slice(0, DETAIL_CHARS);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The schema's answer, redacted at any depth, or `undefined` when the body does not fit it. */
|
|
101
|
+
function fieldsOf(text: string, schema: Schema<unknown, unknown>): unknown {
|
|
102
|
+
const parsed = parsedJson(text);
|
|
103
|
+
if (parsed === undefined) return undefined;
|
|
104
|
+
const result = schema.safeParse(parsed.value);
|
|
105
|
+
if (!('value' in result) || result.issues !== undefined) return undefined;
|
|
106
|
+
return redactFields({ fields: result.value })['fields'];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function wholeBody(
|
|
110
|
+
body: ReadableStream<Uint8Array>,
|
|
111
|
+
read: OutboundRefusalRead & { readonly schema: Schema<unknown, unknown> },
|
|
112
|
+
maxBytes: number,
|
|
113
|
+
): Promise<RefusalBody> {
|
|
114
|
+
const capped = await readWithinLimit(body, maxBytes);
|
|
115
|
+
if ('over' in capped) return { detail: '' };
|
|
116
|
+
const text = new TextDecoder().decode(capped.bytes);
|
|
117
|
+
const fields = fieldsOf(text, read.schema);
|
|
118
|
+
return {
|
|
119
|
+
detail: read.detail === false ? '' : detailOf(text),
|
|
120
|
+
...(fields === undefined ? {} : { fields }),
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** What the error keeps of a refusal's body, as `read` asks. Never throws. */
|
|
125
|
+
async function refusalBodyOf(
|
|
126
|
+
body: ReadableStream<Uint8Array>,
|
|
127
|
+
read: OutboundRefusalRead | undefined,
|
|
128
|
+
maxBytes: number,
|
|
129
|
+
): Promise<RefusalBody> {
|
|
83
130
|
try {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
131
|
+
if (read?.schema !== undefined)
|
|
132
|
+
return await wholeBody(body, { ...read, schema: read.schema }, maxBytes);
|
|
133
|
+
if (read?.detail === false) {
|
|
134
|
+
await body.cancel().catch(() => undefined);
|
|
135
|
+
return { detail: '' };
|
|
136
|
+
}
|
|
137
|
+
return { detail: detailOf(await prefixOf(body)) };
|
|
87
138
|
} catch {
|
|
88
|
-
return '';
|
|
139
|
+
return { detail: '' };
|
|
89
140
|
}
|
|
90
141
|
}
|
|
91
142
|
|
|
@@ -98,11 +149,11 @@ function ambientLeftMs(): number {
|
|
|
98
149
|
|
|
99
150
|
/** A non-2xx as the code it is. The body has been read for the detail, or cancelled. */
|
|
100
151
|
async function refusalOf(
|
|
101
|
-
|
|
152
|
+
call: AttemptCall,
|
|
102
153
|
response: Response,
|
|
103
154
|
body: ReadableStream<Uint8Array>,
|
|
104
|
-
url: URL,
|
|
105
155
|
): Promise<unknown> {
|
|
156
|
+
const { site, url } = call;
|
|
106
157
|
const { status, headers } = response;
|
|
107
158
|
if (status >= 300 && status < 400) {
|
|
108
159
|
await body.cancel().catch(() => undefined);
|
|
@@ -112,12 +163,13 @@ async function refusalOf(
|
|
|
112
163
|
}
|
|
113
164
|
if (isRetryableStatus(status)) {
|
|
114
165
|
const after = retryAfterSecondsOf(headers.get('retry-after'), headers.get('date'));
|
|
115
|
-
const detail = await
|
|
166
|
+
const { detail, fields } = await refusalBodyOf(body, call.refusal, call.maxBytes);
|
|
116
167
|
return after === undefined
|
|
117
|
-
? outboundUnavailable(site, status, detail)
|
|
118
|
-
: outboundThrottled(site, status, after, detail);
|
|
168
|
+
? outboundUnavailable(site, status, detail, fields)
|
|
169
|
+
: outboundThrottled(site, status, after, detail, fields);
|
|
119
170
|
}
|
|
120
|
-
|
|
171
|
+
const { detail, fields } = await refusalBodyOf(body, call.refusal, call.maxBytes);
|
|
172
|
+
return outboundRefused(site, status, detail, fields);
|
|
121
173
|
}
|
|
122
174
|
|
|
123
175
|
export async function runAttempt(call: AttemptCall, attempt: number): Promise<AttemptAnswer> {
|
|
@@ -188,7 +240,7 @@ export async function runAttempt(call: AttemptCall, attempt: number): Promise<At
|
|
|
188
240
|
failure,
|
|
189
241
|
onSettled: release,
|
|
190
242
|
});
|
|
191
|
-
if (status < 200 || status >= 300) throw await refusalOf(call
|
|
243
|
+
if (status < 200 || status >= 300) throw await refusalOf(call, response, body);
|
|
192
244
|
if (call.read === 'stream') {
|
|
193
245
|
logAttempt(call, attempt, startedAt, status, undefined);
|
|
194
246
|
return { status, headers: response.headers, stream: body };
|
package/src/outbound-errors.ts
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
|
-
// Single responsibility: the
|
|
1
|
+
// Single responsibility: the twelve refusals `outbound()` can end on, each built from the call's
|
|
2
2
|
// redacted label. Never a query string, never a header: a cause reaches a log store and a
|
|
3
3
|
// problem document, and a signed URL's query is the credential.
|
|
4
4
|
|
|
5
|
+
import { registerErrorCodes } from './error-codes';
|
|
5
6
|
import { renderFixShellArg, renderThrowable } from './error-render';
|
|
6
7
|
import { registerErrorRetry } from './error-retry';
|
|
7
8
|
import { UltimateError } from './errors';
|
|
8
9
|
import { replaceUrlUserinfo } from './url-userinfo';
|
|
9
10
|
|
|
10
11
|
/**
|
|
11
|
-
* The
|
|
12
|
+
* The twelve codes' retry classes, registered HERE and not in `error-retry.ts`'s core table: that
|
|
12
13
|
* table rides every browser page, and these are server-only (axiom 6). The transport faults are
|
|
13
14
|
* retryable, a stated delay is `retry-after`, and every answer the same request gets again is
|
|
14
15
|
* terminal — unclassified, `retry()` would replay a 401 three times.
|
|
@@ -22,11 +23,20 @@ registerErrorRetry({
|
|
|
22
23
|
X_OUTBOUND_TOO_LARGE: 'terminal',
|
|
23
24
|
X_OUTBOUND_HOST_BLOCKED: 'terminal',
|
|
24
25
|
X_OUTBOUND_REDIRECTED: 'terminal',
|
|
26
|
+
X_OUTBOUND_TRANSPORT_REDIRECTED: 'terminal',
|
|
25
27
|
X_OUTBOUND_RETRY_UNSAFE: 'terminal',
|
|
26
28
|
X_OUTBOUND_BODY_INVALID: 'terminal',
|
|
27
29
|
X_OUTBOUND_PROXY_INVALID: 'terminal',
|
|
28
30
|
});
|
|
29
31
|
|
|
32
|
+
/**
|
|
33
|
+
* Registered here, not in `core-error-codes.ts`: that table rides every browser page, and only
|
|
34
|
+
* this server-only module throws it — the code and the module that throws it ship together.
|
|
35
|
+
*/
|
|
36
|
+
registerErrorCodes({
|
|
37
|
+
X_OUTBOUND_TRANSPORT_REDIRECTED: { title: 'an outbound transport followed a redirect itself' },
|
|
38
|
+
});
|
|
39
|
+
|
|
30
40
|
/** What a failure may say about the call: who, how, and where, never the query or a header. */
|
|
31
41
|
export interface OutboundSite {
|
|
32
42
|
readonly vendor: string;
|
|
@@ -108,17 +118,22 @@ export function outboundUnreachable(site: OutboundSite, error: unknown): Ultimat
|
|
|
108
118
|
});
|
|
109
119
|
}
|
|
110
120
|
|
|
121
|
+
/** `meta.fields` only when the caller's refusal schema answered: absent, never `undefined`. */
|
|
122
|
+
const fieldsMeta = (fields: unknown): { readonly fields?: unknown } =>
|
|
123
|
+
fields === undefined ? {} : { fields };
|
|
124
|
+
|
|
111
125
|
export function outboundThrottled(
|
|
112
126
|
site: OutboundSite,
|
|
113
127
|
status: number,
|
|
114
128
|
retryAfterSeconds: number,
|
|
115
129
|
detail = '',
|
|
130
|
+
fields?: unknown,
|
|
116
131
|
): UltimateError {
|
|
117
132
|
return new UltimateError({
|
|
118
133
|
code: 'X_OUTBOUND_THROTTLED',
|
|
119
134
|
cause: `${siteLabel(site)} answered ${String(status)} and asked to wait ${String(retryAfterSeconds)} s`,
|
|
120
135
|
fix: `await Bun.sleep(${String(retryAfterSeconds * 1000)}) # then call ${site.vendor} again, or lower the call rate at the site that calls outbound()`,
|
|
121
|
-
meta: { ...siteMeta(site), status, retryAfterSeconds, detail },
|
|
136
|
+
meta: { ...siteMeta(site), status, retryAfterSeconds, detail, ...fieldsMeta(fields) },
|
|
122
137
|
});
|
|
123
138
|
}
|
|
124
139
|
|
|
@@ -126,16 +141,22 @@ export function outboundUnavailable(
|
|
|
126
141
|
site: OutboundSite,
|
|
127
142
|
status: number,
|
|
128
143
|
detail = '',
|
|
144
|
+
fields?: unknown,
|
|
129
145
|
): UltimateError {
|
|
130
146
|
return new UltimateError({
|
|
131
147
|
code: 'X_OUTBOUND_UNAVAILABLE',
|
|
132
148
|
cause: `${siteLabel(site)} answered ${String(status)} on every attempt: the vendor's fault, not the request's`,
|
|
133
149
|
fix: `curl -sS -m 5 -o /dev/null -w '%{http_code}\\n' ${renderFixShellArg(site.origin, '<vendor origin>')} # the vendor's fault: re-run the call; if ${String(status)} persists, check ${site.vendor}'s status page`,
|
|
134
|
-
meta: { ...siteMeta(site), status, detail },
|
|
150
|
+
meta: { ...siteMeta(site), status, detail, ...fieldsMeta(fields) },
|
|
135
151
|
});
|
|
136
152
|
}
|
|
137
153
|
|
|
138
|
-
export function outboundRefused(
|
|
154
|
+
export function outboundRefused(
|
|
155
|
+
site: OutboundSite,
|
|
156
|
+
status: number,
|
|
157
|
+
detail: string,
|
|
158
|
+
fields?: unknown,
|
|
159
|
+
): UltimateError {
|
|
139
160
|
return new UltimateError({
|
|
140
161
|
code: 'X_OUTBOUND_REFUSED',
|
|
141
162
|
cause: `${siteLabel(site)} answered ${String(status)}, and the same request will get it again`,
|
|
@@ -143,7 +164,7 @@ export function outboundRefused(site: OutboundSite, status: number, detail: stri
|
|
|
143
164
|
status === 401
|
|
144
165
|
? `outbound({ url, vendor: '${site.vendor}', headers: { authorization } }) # with a refreshed credential, then call again`
|
|
145
166
|
: `outbound({ url, vendor: '${site.vendor}', body }) # with the request fixed from meta.detail and meta.status`,
|
|
146
|
-
meta: { ...siteMeta(site), status, detail },
|
|
167
|
+
meta: { ...siteMeta(site), status, detail, ...fieldsMeta(fields) },
|
|
147
168
|
});
|
|
148
169
|
}
|
|
149
170
|
|
|
@@ -178,6 +199,19 @@ export function outboundRedirected(
|
|
|
178
199
|
});
|
|
179
200
|
}
|
|
180
201
|
|
|
202
|
+
/**
|
|
203
|
+
* The app's transport (`deps.fetch`) followed a hop itself: no screen saw it, so its answer is not
|
|
204
|
+
* the vendor's to trust. No `status` in `meta`, so `outboundResponse()` never rebuilds it as that 2xx.
|
|
205
|
+
*/
|
|
206
|
+
export function outboundTransportRedirected(site: OutboundSite, reached: string): UltimateError {
|
|
207
|
+
return new UltimateError({
|
|
208
|
+
code: 'X_OUTBOUND_TRANSPORT_REDIRECTED',
|
|
209
|
+
cause: `${siteLabel(site)}: the transport passed as deps.fetch followed a redirect itself, towards ${reached}, ignoring init.redirect ('manual')`,
|
|
210
|
+
fix: `fetch(url, init) # in the transport given to outbound(): pass init through unchanged, and let outbound({ url, vendor: '${site.vendor}', redirect: 'follow' }) take each hop`,
|
|
211
|
+
meta: { ...siteMeta(site), location: reached },
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
|
|
181
215
|
export function outboundRetryUnsafe(site: OutboundSite): UltimateError {
|
|
182
216
|
return new UltimateError({
|
|
183
217
|
code: 'X_OUTBOUND_RETRY_UNSAFE',
|
package/src/outbound-hops.ts
CHANGED
|
@@ -6,7 +6,12 @@
|
|
|
6
6
|
import type { DialResolve } from './outbound-dial';
|
|
7
7
|
import { publicUrlRefusal, screenDial } from './outbound-dial';
|
|
8
8
|
import type { OutboundSite } from './outbound-errors';
|
|
9
|
-
import {
|
|
9
|
+
import {
|
|
10
|
+
outboundHostBlocked,
|
|
11
|
+
outboundRedirected,
|
|
12
|
+
outboundTransportRedirected,
|
|
13
|
+
outboundUnreachable,
|
|
14
|
+
} from './outbound-errors';
|
|
10
15
|
import { proxyFor } from './outbound-proxy';
|
|
11
16
|
import type { OutboundBody, OutboundFetch, OutboundInit, OutboundProxy } from './outbound-types';
|
|
12
17
|
import { OUTBOUND_MAX_REDIRECTS } from './outbound-types';
|
|
@@ -120,6 +125,11 @@ export async function sendHops(call: HopCall, signal: AbortSignal): Promise<Resp
|
|
|
120
125
|
redirect: 'manual',
|
|
121
126
|
};
|
|
122
127
|
const response = await call.fetch(target.url, init);
|
|
128
|
+
// A transport that ignored `redirect: 'manual'` dialled a hop no screen saw: never its answer.
|
|
129
|
+
if (response.redirected) {
|
|
130
|
+
await discard(response);
|
|
131
|
+
throw outboundTransportRedirected(call.site, redactedLocation(response.url, url));
|
|
132
|
+
}
|
|
123
133
|
const location = response.headers.get('location');
|
|
124
134
|
if (!isRedirect(response.status) || location === null || call.redirect === 'error') {
|
|
125
135
|
return response;
|
package/src/outbound-subpath.ts
CHANGED
package/src/outbound-types.ts
CHANGED
|
@@ -52,9 +52,32 @@ export type OutboundProxy =
|
|
|
52
52
|
| OutboundProxyTarget
|
|
53
53
|
| ((target: URL) => OutboundProxyTarget | undefined | Promise<OutboundProxyTarget | undefined>);
|
|
54
54
|
|
|
55
|
-
/**
|
|
55
|
+
/**
|
|
56
|
+
* "Just the call", the seam `MailFetch` already is — a test double, or a production transport.
|
|
57
|
+
* `outbound()` keeps the screen, the deadline, retries, the byte cap, the idle watchdog and every
|
|
58
|
+
* redirect rule: the transport is handed the SCREENED url (the approved address under `'public'`,
|
|
59
|
+
* with `host` and `tls.serverName` naming the name) and `init` with `signal` and `redirect:
|
|
60
|
+
* 'manual'`. It must dial that url and pass `init` through. An answer with `redirected: true` is
|
|
61
|
+
* `X_OUTBOUND_TRANSPORT_REDIRECTED`. A transport that reaches somewhere else (a tunnel, a relay)
|
|
62
|
+
* takes the address screen over: that is the app's to prove.
|
|
63
|
+
*/
|
|
56
64
|
export type OutboundFetch = (url: string, init: OutboundInit) => Promise<Response>;
|
|
57
65
|
|
|
66
|
+
/** How a refusal's body is read, per call: `OutboundRequest.refusal`. */
|
|
67
|
+
export interface OutboundRefusalRead {
|
|
68
|
+
/**
|
|
69
|
+
* The body read whole (up to the call's `maxBytes`), parsed as JSON through this schema: what it
|
|
70
|
+
* answers, credential-named fields redacted, is the error's `meta.fields`. A body that is not
|
|
71
|
+
* JSON, does not fit, or passes `maxBytes` leaves `meta.fields` unset.
|
|
72
|
+
*/
|
|
73
|
+
readonly schema?: Schema<unknown, unknown> | undefined;
|
|
74
|
+
/**
|
|
75
|
+
* `false`: `meta.detail` is `''`, the raw-body excerpt never kept. Default `true`. It does not
|
|
76
|
+
* filter `meta.fields`: a schema declares only fields that are safe to log.
|
|
77
|
+
*/
|
|
78
|
+
readonly detail?: boolean | undefined;
|
|
79
|
+
}
|
|
80
|
+
|
|
58
81
|
export interface OutboundRequest {
|
|
59
82
|
readonly url: string | URL;
|
|
60
83
|
/** A bounded label chosen in code (`'resend'`), in every log line and cause. */
|
|
@@ -81,6 +104,12 @@ export interface OutboundRequest {
|
|
|
81
104
|
/** A POST or PATCH carrying the vendor's idempotency key: retried as a safe method is. */
|
|
82
105
|
readonly idempotent?: true | undefined;
|
|
83
106
|
readonly read?: 'bytes' | 'stream' | undefined;
|
|
107
|
+
/**
|
|
108
|
+
* How a non-2xx body is read for the coded error. Unset: a redacted 200-character excerpt of
|
|
109
|
+
* the chunks that decode its first 1,024 characters, `meta.detail`. `{ schema }`: the whole body (within `maxBytes`) through the
|
|
110
|
+
* schema, its answer at `meta.fields`. `{ detail: false }`: `meta.detail` stays `''`.
|
|
111
|
+
*/
|
|
112
|
+
readonly refusal?: OutboundRefusalRead | undefined;
|
|
84
113
|
/**
|
|
85
114
|
* A signal of the caller's own, heard BESIDE the ambient `ctx.signal` — a fan-out's cancel. Its
|
|
86
115
|
* reason reaches the caller unchanged, as the context's does.
|
package/src/outbound.ts
CHANGED
|
@@ -92,6 +92,7 @@ function prepare(request: OutboundRequest, deps: OutboundDeps): AttemptCall {
|
|
|
92
92
|
idleMs: finiteCount('outbound()', 'idleMs', request.idleMs ?? OUTBOUND_IDLE_MS, 1),
|
|
93
93
|
maxBytes: finiteCount('outbound()', 'maxBytes', request.maxBytes ?? OUTBOUND_MAX_BYTES),
|
|
94
94
|
read: request.read ?? 'bytes',
|
|
95
|
+
refusal: request.refusal,
|
|
95
96
|
signal: request.signal,
|
|
96
97
|
now,
|
|
97
98
|
timer: deps.timer ?? platformDeadlineTimer,
|