@ultimat3/core 31.48.0 → 31.50.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +3 -2
- package/README.md +5 -3
- package/package.json +3 -2
- package/src/client-scope-id.ts +10 -3
- package/src/client-stream.ts +31 -29
- package/src/client-transport.ts +6 -1
- package/src/config-defaults.ts +4 -1
- package/src/config-jobs.ts +7 -0
- package/src/config-pwa.ts +43 -9
- package/src/config-site.ts +6 -2
- package/src/config.ts +9 -5
- package/src/drain-deadline.ts +9 -0
- package/src/env.ts +126 -11
- package/src/error-reporter-sentry.ts +71 -17
- package/src/framework-env.ts +7 -0
- package/src/index.ts +4 -0
- package/src/lifecycle-types.ts +8 -0
- package/src/lifecycle.ts +19 -4
- package/src/locale-direction.ts +23 -5
- package/src/logger-redact.ts +5 -1
- package/src/logger.ts +24 -2
- package/src/outbound-attempt.ts +76 -24
- package/src/outbound-errors.ts +40 -6
- package/src/outbound-hops.ts +19 -1
- package/src/outbound-subpath.ts +1 -0
- package/src/outbound-types.ts +30 -1
- package/src/outbound.ts +4 -1
- package/src/shared-port.ts +69 -0
- package/src/sse-frames.ts +42 -0
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,
|
|
@@ -21,9 +21,10 @@ import {
|
|
|
21
21
|
outboundUnreachable,
|
|
22
22
|
} from './outbound-errors';
|
|
23
23
|
import type { HopCall } from './outbound-hops';
|
|
24
|
-
import {
|
|
24
|
+
import { redactedLocation, sendHops } from './outbound-hops';
|
|
25
25
|
import type { WatchedFailure } from './outbound-read';
|
|
26
26
|
import { watchedBody } from './outbound-read';
|
|
27
|
+
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,26 +149,27 @@ 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);
|
|
109
160
|
const location = headers.get('location');
|
|
110
|
-
const where = location === null ? 'nowhere' :
|
|
161
|
+
const where = location === null ? 'nowhere' : redactedLocation(location, url);
|
|
111
162
|
return outboundRedirected(site, status, where);
|
|
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';
|
|
@@ -49,6 +54,10 @@ export function redactedPath(pathname: string): string {
|
|
|
49
54
|
/** Where a URL points, for a cause or `meta`: origin and the redacted path, never the query. */
|
|
50
55
|
export const redactedUrl = (url: URL): string => `${url.origin}${redactedPath(url.pathname)}`;
|
|
51
56
|
|
|
57
|
+
/** A `Location` header, redacted as `redactedUrl`; one no parser reads is named, never echoed. */
|
|
58
|
+
export const redactedLocation = (location: string, base: URL): string =>
|
|
59
|
+
URL.canParse(location, base) ? redactedUrl(new URL(location, base)) : 'an unparseable Location';
|
|
60
|
+
|
|
52
61
|
interface Target {
|
|
53
62
|
readonly url: string;
|
|
54
63
|
readonly host?: string | undefined;
|
|
@@ -116,11 +125,20 @@ export async function sendHops(call: HopCall, signal: AbortSignal): Promise<Resp
|
|
|
116
125
|
redirect: 'manual',
|
|
117
126
|
};
|
|
118
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
|
+
}
|
|
119
133
|
const location = response.headers.get('location');
|
|
120
134
|
if (!isRedirect(response.status) || location === null || call.redirect === 'error') {
|
|
121
135
|
return response;
|
|
122
136
|
}
|
|
123
137
|
await discard(response);
|
|
138
|
+
// A Location no parser reads is still the vendor's answer: a redirect, never "no response".
|
|
139
|
+
if (!URL.canParse(location, url)) {
|
|
140
|
+
throw outboundRedirected(call.site, response.status, redactedLocation(location, url));
|
|
141
|
+
}
|
|
124
142
|
const next = new URL(location, url);
|
|
125
143
|
if (hop + 1 > OUTBOUND_MAX_REDIRECTS) {
|
|
126
144
|
throw outboundRedirected(call.site, response.status, redactedUrl(next));
|
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,
|
|
@@ -176,7 +177,9 @@ export async function outbound(
|
|
|
176
177
|
deps.sleep ?? (request.signal === undefined ? undefined : signalledSleep(request.signal)),
|
|
177
178
|
now: call.now,
|
|
178
179
|
random: deps.random,
|
|
179
|
-
|
|
180
|
+
// A caller that cancelled wants no retry: refusing it ends the loop with that caller's own
|
|
181
|
+
// reason, and spends no token a real vendor failure on this key will need.
|
|
182
|
+
admitRetry: () => request.signal?.aborted !== true && (budget?.spend() ?? true),
|
|
180
183
|
});
|
|
181
184
|
};
|
|
182
185
|
const answer = await instrumentedCall(
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// Single responsibility: the shared-port seam. Whether this process is a supervised child
|
|
2
|
+
// (`ULTIMATE_CHILD=i/N`), the one place Bun.serve's `reusePort` is spelled, and the split of a
|
|
3
|
+
// container-wide count between children. `scripts/reuse-port-seam.ts` keeps the literal here.
|
|
4
|
+
|
|
5
|
+
import { assert } from './assert';
|
|
6
|
+
import { renderCauseValue } from './error-render';
|
|
7
|
+
|
|
8
|
+
type ProcessEnv = Readonly<Record<string, string | undefined>>;
|
|
9
|
+
|
|
10
|
+
/** This process's place among its siblings: `index` is zero-based, `index < count`. */
|
|
11
|
+
export interface SupervisedChild {
|
|
12
|
+
readonly index: number;
|
|
13
|
+
readonly count: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Canonical decimals only: a leading zero, a sign or a space is not something the supervisor writes. */
|
|
17
|
+
const CHILD_SHAPE = /^(0|[1-9]\d*)\/([1-9]\d*)$/;
|
|
18
|
+
|
|
19
|
+
const CHILD_FIX =
|
|
20
|
+
'unset ULTIMATE_CHILD # the production supervisor sets it for each child as <index>/<count>; set ULTIMATE_PROCESSES to choose the count';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* `ULTIMATE_CHILD`, read. Unset or empty: not a child. Anything else that is not `i/N` with
|
|
24
|
+
* `0 ≤ i < N` is REFUSED (`X_INVARIANT`): only the supervisor writes the name, and a child that read
|
|
25
|
+
* a garbled one as "unsupervised" would bind the shared port without `reusePort` and lose it.
|
|
26
|
+
*/
|
|
27
|
+
export function supervisedChild(env: ProcessEnv): SupervisedChild | undefined {
|
|
28
|
+
const raw = env['ULTIMATE_CHILD'];
|
|
29
|
+
if (raw === undefined || raw === '') return undefined;
|
|
30
|
+
const match = CHILD_SHAPE.exec(raw);
|
|
31
|
+
const index = Number(match?.[1]);
|
|
32
|
+
const count = Number(match?.[2]);
|
|
33
|
+
assert(
|
|
34
|
+
match !== null && Number.isSafeInteger(count) && index < count,
|
|
35
|
+
`ULTIMATE_CHILD=${renderCauseValue(raw)} is not <index>/<count> with 0 <= index < count`,
|
|
36
|
+
CHILD_FIX,
|
|
37
|
+
);
|
|
38
|
+
return { index, count };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The option to spread into `Bun.serve`. `{ reusePort: true }` only for a supervised child on
|
|
43
|
+
* Linux — Bun ignores `SO_REUSEPORT` elsewhere, so the key is ABSENT off Linux and for a lone
|
|
44
|
+
* process: an unsupervised second bind must keep failing with "port in use".
|
|
45
|
+
*/
|
|
46
|
+
export function sharedPortOption(
|
|
47
|
+
env: ProcessEnv,
|
|
48
|
+
platform: string = process.platform,
|
|
49
|
+
): { readonly reusePort?: true } {
|
|
50
|
+
return supervisedChild(env) !== undefined && platform === 'linux' ? { reusePort: true } : {};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const isCount = (value: number, floor: number): boolean =>
|
|
54
|
+
Number.isSafeInteger(value) && value >= floor;
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Child `index`'s share of a container-wide `total` (pool connections, job slots): the floor of an
|
|
58
|
+
* even split, the remainder to the lowest indices, never under 1 — so the shares sum to
|
|
59
|
+
* `max(total, count)`. A total under the count is the caller's to refuse or clamp first.
|
|
60
|
+
*/
|
|
61
|
+
export function childShare(total: number, index: number, count: number): number {
|
|
62
|
+
assert(
|
|
63
|
+
isCount(total, 0) && isCount(count, 1) && isCount(index, 0) && index < count,
|
|
64
|
+
`childShare(${renderCauseValue(total)}, ${renderCauseValue(index)}, ${renderCauseValue(count)}) needs whole numbers with total >= 0, count >= 1 and 0 <= index < count`,
|
|
65
|
+
'pass supervisedChild(env) as index and count, and the container-wide total as a whole number',
|
|
66
|
+
);
|
|
67
|
+
if (total <= count) return 1;
|
|
68
|
+
return Math.floor(total / count) + (index < total % count ? 1 : 0);
|
|
69
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// `@ultimat3/core/internal/sse-frames` — the ONE reader of a `text/event-stream` body's frames: the
|
|
2
|
+
// browser's `clientStream` and `@ultimat3/mcp`'s remote client both split SSE here. INTERNAL and a
|
|
3
|
+
// leaf: a package's wire reader, never an app's, and it imports nothing.
|
|
4
|
+
|
|
5
|
+
/** One complete frame: its `event` (`message` when unnamed) and its `data:` lines joined. */
|
|
6
|
+
export interface SseFrame {
|
|
7
|
+
readonly event: string;
|
|
8
|
+
readonly data: string;
|
|
9
|
+
/** The `x-ultimate-dates` value for this frame's data, when the server named any. */
|
|
10
|
+
readonly dates?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Splits a growing buffer into complete frames; the incomplete tail is handed back. A frame with
|
|
15
|
+
* no `data:` line (a keep-alive comment, a bare `event:`) is no frame. A whole body read at once
|
|
16
|
+
* is `takeFrames(`${text}\n\n`)`: its last frame needs no blank line after it.
|
|
17
|
+
*/
|
|
18
|
+
export function takeFrames(buffer: string): {
|
|
19
|
+
readonly frames: SseFrame[];
|
|
20
|
+
readonly rest: string;
|
|
21
|
+
} {
|
|
22
|
+
const frames: SseFrame[] = [];
|
|
23
|
+
const blocks = buffer.split(/\r?\n\r?\n/);
|
|
24
|
+
const rest = blocks.pop() ?? '';
|
|
25
|
+
for (const block of blocks) {
|
|
26
|
+
let event = 'message';
|
|
27
|
+
let dates: string | undefined;
|
|
28
|
+
const data: string[] = [];
|
|
29
|
+
for (const line of block.split(/\r?\n/)) {
|
|
30
|
+
// A `:` line is a comment — the server's keep-alive.
|
|
31
|
+
if (line.startsWith(':')) continue;
|
|
32
|
+
if (line.startsWith('event:')) event = line.slice(6).trim();
|
|
33
|
+
else if (line.startsWith('dates:')) dates = line.slice(6).trim();
|
|
34
|
+
else if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''));
|
|
35
|
+
}
|
|
36
|
+
if (data.length > 0) {
|
|
37
|
+
const text = data.join('\n');
|
|
38
|
+
frames.push(dates === undefined ? { event, data: text } : { event, data: text, dates });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return { frames, rest };
|
|
42
|
+
}
|