@mountaya/client 0.0.0-stage → 0.1.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/CHANGELOG.md +104 -0
- package/LICENCE.fr.txt +280 -0
- package/LICENSE.txt +262 -0
- package/README.md +1260 -2
- package/dist/admin/index.cjs +3521 -0
- package/dist/admin/index.cjs.map +1 -0
- package/dist/admin/index.d.cts +1070 -0
- package/dist/admin/index.d.ts +1070 -0
- package/dist/admin/index.js +301 -0
- package/dist/admin/index.js.map +1 -0
- package/dist/browser.cjs +8073 -0
- package/dist/browser.cjs.map +1 -0
- package/dist/browser.d.cts +106 -0
- package/dist/browser.d.ts +106 -0
- package/dist/browser.js +53 -0
- package/dist/browser.js.map +1 -0
- package/dist/chunk-BM526BHG.js +342 -0
- package/dist/chunk-BM526BHG.js.map +1 -0
- package/dist/chunk-D2YEVTG7.js +327 -0
- package/dist/chunk-D2YEVTG7.js.map +1 -0
- package/dist/chunk-OHKVUREN.js +3500 -0
- package/dist/chunk-OHKVUREN.js.map +1 -0
- package/dist/chunk-TDTK2L5H.js +3842 -0
- package/dist/chunk-TDTK2L5H.js.map +1 -0
- package/dist/coreOperations.gen-BMYPoBbz.d.ts +1760 -0
- package/dist/coreOperations.gen-BxX5xRxw.d.cts +1760 -0
- package/dist/errors-B-GqAtQv.d.cts +75960 -0
- package/dist/errors-B-GqAtQv.d.ts +75960 -0
- package/dist/events/index.cjs +1972 -0
- package/dist/events/index.cjs.map +1 -0
- package/dist/events/index.d.cts +781 -0
- package/dist/events/index.d.ts +781 -0
- package/dist/events/index.js +826 -0
- package/dist/events/index.js.map +1 -0
- package/dist/index.cjs +8072 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +76 -0
- package/dist/index.d.ts +76 -0
- package/dist/index.js +52 -0
- package/dist/index.js.map +1 -0
- package/dist/operations.gen-CvTyzKNF.d.cts +3993 -0
- package/dist/operations.gen-DUD406TV.d.ts +3993 -0
- package/package.json +127 -4
- package/src/admin/index.ts +47 -0
- package/src/admin/rules/mountayaAdmin.ts +102 -0
- package/src/browser.ts +232 -0
- package/src/core/engines/sessionToken.ts +870 -0
- package/src/core/rules/auth.ts +1017 -0
- package/src/core/rules/clientHeader.ts +28 -0
- package/src/core/rules/dates.ts +200 -0
- package/src/core/rules/decode.ts +154 -0
- package/src/core/rules/envelope.ts +41 -0
- package/src/core/rules/errors.ts +1486 -0
- package/src/core/rules/graphql.ts +576 -0
- package/src/core/rules/headerValue.ts +42 -0
- package/src/core/rules/idempotencyKey.ts +64 -0
- package/src/core/rules/nullMask.ts +127 -0
- package/src/core/rules/nullMasks.gen.ts +416 -0
- package/src/core/rules/paginate.ts +316 -0
- package/src/core/rules/rateLimit.ts +507 -0
- package/src/core/rules/redaction.ts +219 -0
- package/src/core/rules/resourceRef.ts +110 -0
- package/src/core/rules/responseBody.ts +492 -0
- package/src/core/rules/retry.ts +386 -0
- package/src/core/rules/selection.ts +416 -0
- package/src/core/rules/sessionAnswer.ts +90 -0
- package/src/core/rules/sessionSchedule.ts +131 -0
- package/src/core/rules/sessionWait.ts +112 -0
- package/src/core/rules/transport.ts +2386 -0
- package/src/core/rules/version.gen.ts +16 -0
- package/src/core/rules/webAddress.ts +165 -0
- package/src/core/rules/webAddresses.gen.ts +30 -0
- package/src/data/operations.gen.ts +603 -0
- package/src/data/schema.gen.ts +8078 -0
- package/src/data/selection.gen.ts +472 -0
- package/src/events/index.ts +67 -0
- package/src/events/rules/agent.ts +439 -0
- package/src/events/rules/collab.ts +554 -0
- package/src/events/rules/collabNulls.gen.ts +17 -0
- package/src/events/rules/eventStream.ts +94 -0
- package/src/events/rules/openSseStream.ts +594 -0
- package/src/events/rules/sse.ts +349 -0
- package/src/index.ts +231 -0
- package/src/rest/adminOperations.gen.ts +70 -0
- package/src/rest/adminResources.gen.ts +136 -0
- package/src/rest/coreOperations.gen.ts +74 -0
- package/src/rest/coreResources.gen.ts +244 -0
- package/src/rest/dates.gen.ts +217 -0
- package/src/rest/operations.gen.ts +4341 -0
- package/src/rest/resources.gen.ts +369 -0
- package/src/rest/schema.gen.ts +56840 -0
- package/src/tiles/operations.gen.ts +206 -0
- package/src/tiles/schema.gen.ts +8408 -0
- package/src/webhooks/rules/constructWebhookEvent.ts +482 -0
- package/src/webhooks/rules/webhookEvent.ts +38 -0
- package/src/webhooks/rules/webhookEvents.gen.ts +732 -0
|
@@ -0,0 +1,594 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type FailureDeclaration,
|
|
3
|
+
isMountayaError,
|
|
4
|
+
MountayaConfigurationError,
|
|
5
|
+
MountayaConnectionError,
|
|
6
|
+
refuseOption,
|
|
7
|
+
} from "../../core/rules/errors.js";
|
|
8
|
+
import { isHeaderValue } from "../../core/rules/headerValue.js";
|
|
9
|
+
import { readFailure } from "../../core/rules/responseBody.js";
|
|
10
|
+
import { MAX_TIMER_DELAY_MS } from "../../core/rules/retry.js";
|
|
11
|
+
import { type EventStreamOutcome, readEventStream } from "./eventStream.js";
|
|
12
|
+
import { SseBufferOverflowError, type SseFrame } from "./sse.js";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* STALL_WINDOW_MS is how long a stream may deliver nothing before the read gives it up, in
|
|
16
|
+
* milliseconds: three of the 15-second intervals at which the API writes to every live event
|
|
17
|
+
* stream, a comment when it has no event to send.
|
|
18
|
+
*
|
|
19
|
+
* A connection a proxy or a sleeping network left half-open delivers nothing and never closes, so
|
|
20
|
+
* a read with no bound on its silence waits on it for as long as the page is open. The heartbeat
|
|
21
|
+
* is what tells that connection from a quiet one: a run waiting on its reader's next message, or
|
|
22
|
+
* a feed nobody is editing, still carries a comment every interval. Three missed ones is a
|
|
23
|
+
* connection that is gone rather than a heartbeat running late. The contract states no heartbeat
|
|
24
|
+
* interval, so this bound is the reader's own rather than one read off a declaration.
|
|
25
|
+
*/
|
|
26
|
+
const STALL_WINDOW_MS = 45_000;
|
|
27
|
+
|
|
28
|
+
/** SILENCE marks the wait for a chunk that {@link STALL_WINDOW_MS} ended before a chunk came. */
|
|
29
|
+
const SILENCE = Symbol("silence");
|
|
30
|
+
|
|
31
|
+
/** LET_GO marks the wait for a chunk that the request's own abort ended. */
|
|
32
|
+
const LET_GO = Symbol("let go");
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* boundSilence hands the frame reader a view of `body` that pulls one chunk per read, on demand,
|
|
36
|
+
* and fails the read still waiting on a chunk once {@link STALL_WINDOW_MS} passes with nothing
|
|
37
|
+
* arriving, with the `MountayaConnectionError` that says so. Every chunk counts, a heartbeat
|
|
38
|
+
* comment included, since a comment is what a live connection sends when it has no event.
|
|
39
|
+
*
|
|
40
|
+
* On demand, because only a read the reader is waiting on measures the network. Between two
|
|
41
|
+
* reads the caller's frame handler holds the stream (a person approving a tool, say), and that
|
|
42
|
+
* wait is the caller's: a view that read ahead would time the caller rather than the connection.
|
|
43
|
+
*
|
|
44
|
+
* `signal` is the request's own. Its abort (the caller's close, or the end of the read) ends a
|
|
45
|
+
* wait still pending and lets go of the body's lock, so the body reads as unlocked once the read
|
|
46
|
+
* is over, as a body read directly does. The body is released, never cancelled: aborting the
|
|
47
|
+
* request is what lets a fetch's connection go, and a body is its opener's to cancel.
|
|
48
|
+
*/
|
|
49
|
+
const boundSilence = (
|
|
50
|
+
body: ReadableStream<Uint8Array>,
|
|
51
|
+
operationId: string,
|
|
52
|
+
signal: AbortSignal,
|
|
53
|
+
): ReadableStream<Uint8Array> => {
|
|
54
|
+
const reader = body.getReader();
|
|
55
|
+
|
|
56
|
+
// A runtime that refuses to release a lock while a read is pending keeps it until the read
|
|
57
|
+
// settles, which the pending wait's own end below retries after.
|
|
58
|
+
const letGo = (): void => {
|
|
59
|
+
try {
|
|
60
|
+
reader.releaseLock();
|
|
61
|
+
} catch {
|
|
62
|
+
// Released once the read still pending settles; see the finally below.
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
// Ends the wait the pull in progress has pending, if one does. Each pull races a promise of its
|
|
67
|
+
// own, which the pull lets go of as it ends: a race against one promise that outlives every
|
|
68
|
+
// pull adds a reaction to it per chunk, kept for as long as the stream stays open.
|
|
69
|
+
let endWait: ((end: typeof LET_GO) => void) | undefined;
|
|
70
|
+
|
|
71
|
+
// The pending wait ends first and the lock goes after, since letting go of it rejects the read
|
|
72
|
+
// still pending, and the wait's end is what the race has to see.
|
|
73
|
+
if (signal.aborted) {
|
|
74
|
+
letGo();
|
|
75
|
+
} else {
|
|
76
|
+
signal.addEventListener(
|
|
77
|
+
"abort",
|
|
78
|
+
() => {
|
|
79
|
+
endWait?.(LET_GO);
|
|
80
|
+
letGo();
|
|
81
|
+
},
|
|
82
|
+
{ once: true },
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return new ReadableStream<Uint8Array>(
|
|
87
|
+
{
|
|
88
|
+
cancel: (reason) => reader.cancel(reason),
|
|
89
|
+
pull: async (controller) => {
|
|
90
|
+
// A read asked for once the request is over has nothing left to read.
|
|
91
|
+
if (signal.aborted) {
|
|
92
|
+
controller.close();
|
|
93
|
+
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
98
|
+
const ended = new Promise<typeof SILENCE | typeof LET_GO>((resolve) => {
|
|
99
|
+
endWait = resolve;
|
|
100
|
+
timer = setTimeout(() => resolve(SILENCE), STALL_WINDOW_MS);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
try {
|
|
104
|
+
const next = await Promise.race([reader.read(), ended]);
|
|
105
|
+
if (next === LET_GO) {
|
|
106
|
+
controller.close();
|
|
107
|
+
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (next === SILENCE) {
|
|
112
|
+
throw new MountayaConnectionError(
|
|
113
|
+
`${operationId}: the stream went silent for ${STALL_WINDOW_MS} ms, past the heartbeat every live stream carries. Reopen it from the last position it named, and check the network path to the API if it keeps going silent.`,
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (next.done) {
|
|
118
|
+
controller.close();
|
|
119
|
+
} else {
|
|
120
|
+
controller.enqueue(next.value);
|
|
121
|
+
}
|
|
122
|
+
} finally {
|
|
123
|
+
endWait = undefined;
|
|
124
|
+
clearTimeout(timer);
|
|
125
|
+
if (signal.aborted) {
|
|
126
|
+
letGo();
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
// A read-ahead queue of none: the next chunk is asked for only when the reader asks.
|
|
132
|
+
{ highWaterMark: 0 },
|
|
133
|
+
);
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* openTimeoutOf reads the bound on an open's wait for its response: `timeoutMs` when the caller
|
|
138
|
+
* states one, and {@link STALL_WINDOW_MS} otherwise.
|
|
139
|
+
*
|
|
140
|
+
* @throws `MountayaConfigurationError` for a `timeoutMs` that is not a whole number of
|
|
141
|
+
* milliseconds from 1 to 2,147,483,647, the range a timer honours, naming the operation.
|
|
142
|
+
*/
|
|
143
|
+
const openTimeoutOf = (timeoutMs: number | undefined, operationId: string): number => {
|
|
144
|
+
if (timeoutMs === undefined) {
|
|
145
|
+
return STALL_WINDOW_MS;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (Number.isInteger(timeoutMs) && timeoutMs >= 1 && timeoutMs <= MAX_TIMER_DELAY_MS) {
|
|
149
|
+
return timeoutMs;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
throw refuseOption(
|
|
153
|
+
"timeoutMs",
|
|
154
|
+
timeoutMs,
|
|
155
|
+
`pass a whole number of milliseconds from 1 to ${MAX_TIMER_DELAY_MS}, or leave it out to wait at most ${STALL_WINDOW_MS}.`,
|
|
156
|
+
operationId,
|
|
157
|
+
);
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* OpenSseStreamOptions configure one open of a resumable Server-Sent Events read
|
|
162
|
+
* over fetch. The caller supplies the network seam (doFetch + applyAuth), the URL and
|
|
163
|
+
* the operation it opens, an optional resume position and external abort, and the
|
|
164
|
+
* feature-specific policy: how to decode a raw frame and what to do with each decoded
|
|
165
|
+
* event. The vocabulary stays with the caller (decode returns the caller's own event
|
|
166
|
+
* type), so this reader knows no feature's schema.
|
|
167
|
+
*/
|
|
168
|
+
export interface OpenSseStreamOptions<TEvent> {
|
|
169
|
+
/**
|
|
170
|
+
* applyAuth folds the host's credential into the request's RequestInit.
|
|
171
|
+
*
|
|
172
|
+
* `method` reaches it because the published seam takes one, for the wording of a refusal.
|
|
173
|
+
*
|
|
174
|
+
* What the stream's operation declares does not reach it, because this reader knows the
|
|
175
|
+
* operation by name alone. An opener states it in the closure it passes, as the collaboration
|
|
176
|
+
* and agent transports do over `MountayaTransport.streamSeam`: the session token every stream
|
|
177
|
+
* requires, that it acts as the member that token names, and, by saying nothing, that no
|
|
178
|
+
* stream accepts a share token. The seam refuses a credential that cannot meet them locally,
|
|
179
|
+
* which for a share token is the only place the rule is named: the server answers one sent where
|
|
180
|
+
* it is not accepted with a 401, as if no credential had been sent. A refusal thrown here
|
|
181
|
+
* surfaces through onError like any other failed open.
|
|
182
|
+
*/
|
|
183
|
+
applyAuth: (init: RequestInit, method: string) => RequestInit;
|
|
184
|
+
/** decode turns one raw SSE frame into a typed event, or null to skip it. */
|
|
185
|
+
decode: (frame: SseFrame) => TEvent | null;
|
|
186
|
+
/** doFetch is the fetch implementation: the real one, or a test double. */
|
|
187
|
+
doFetch: typeof fetch;
|
|
188
|
+
/** lastEventId resumes the stream after a position via the Last-Event-ID header. */
|
|
189
|
+
lastEventId?: string | undefined;
|
|
190
|
+
/** onClose runs once when the body finishes, told why the read returned. */
|
|
191
|
+
onClose?: ((outcome: EventStreamOutcome) => void) | undefined;
|
|
192
|
+
/**
|
|
193
|
+
* onResponse is told of the open's answer once it arrives, a refusal's as well as a stream's,
|
|
194
|
+
* before the stream is read or the refusal classified. The openers of this entry point pass
|
|
195
|
+
* `MountayaTransport.streamSeam`'s `report`, so the client's own `onResponse` hears of every
|
|
196
|
+
* open. A fault it throws fails the open, as a fault of `applyAuth` does.
|
|
197
|
+
*/
|
|
198
|
+
onResponse?: ((response: Response) => void) | undefined;
|
|
199
|
+
/**
|
|
200
|
+
* onError runs once on a failure that is not the caller's own abort (an abort is a silent
|
|
201
|
+
* teardown and fires neither onClose nor onError).
|
|
202
|
+
*
|
|
203
|
+
* What it receives is an error of this package's family, except a fault the caller's own
|
|
204
|
+
* `applyAuth`, `decode`, `onFrame` or `onLastEventId` threw, which arrives as it was thrown:
|
|
205
|
+
* - an open the API refused raises what a request the API answered the same way raises (the
|
|
206
|
+
* class its status and first entry decide, carrying the entries, the `code` and the metadata),
|
|
207
|
+
* so a `402` is a `MountayaBillingError` and a `409` naming a held lock a `MountayaConflictError`. Its body
|
|
208
|
+
* is read under a bound on time and one on size, and past either the status alone decides the
|
|
209
|
+
* class;
|
|
210
|
+
* - a request that failed before a response arrived and a body that broke off mid-read raise a
|
|
211
|
+
* `MountayaConnectionError` carrying the runtime's failure as its `cause`, and an ok answer
|
|
212
|
+
* with no body raises one with no `cause`, since no runtime failure lies behind it;
|
|
213
|
+
* - an open with no response within {@link OpenSseStreamOptions.timeoutMs}, and a stream that
|
|
214
|
+
* delivered nothing for the stall window, raise a `MountayaConnectionError` that says which
|
|
215
|
+
* wait ran out, with no `cause`: the request is aborted and its body let go first;
|
|
216
|
+
* - a `timeoutMs` out of range raises a `MountayaConfigurationError` naming it, and nothing is
|
|
217
|
+
* opened;
|
|
218
|
+
* - a runtime whose fetch exposes no response body to stream raises a
|
|
219
|
+
* `MountayaConfigurationError`, since every reopen meets the same runtime;
|
|
220
|
+
* - a producer past the frame parser's cap raises a `SseBufferOverflowError` naming the
|
|
221
|
+
* operation, with the parser's own error as its `cause`;
|
|
222
|
+
* - a credential the transports' stream seam refuses in applyAuth, and a failure the fetch raised
|
|
223
|
+
* from inside the family, are already of the family and arrive as they were thrown.
|
|
224
|
+
*/
|
|
225
|
+
onError?: ((error: unknown) => void) | undefined;
|
|
226
|
+
/**
|
|
227
|
+
* onFrame receives each decoded event with its stream position id and returns
|
|
228
|
+
* whether to stop the read (a terminal event). Returning a promise backpressures
|
|
229
|
+
* the read: the next frame is pulled only once it settles.
|
|
230
|
+
*/
|
|
231
|
+
onFrame: (event: TEvent, id: string | undefined) => boolean | Promise<boolean>;
|
|
232
|
+
/**
|
|
233
|
+
* onLastEventId receives the stream's position when it moves to one no frame handed to
|
|
234
|
+
* onFrame carries: a record that names an `id:` and no `data:`, which dispatches no frame, or
|
|
235
|
+
* an empty `id:`, even one before the stream names any other position, which clears the
|
|
236
|
+
* position and arrives as `undefined`. A caller keeping a resume cursor records it as it records
|
|
237
|
+
* a frame's id, so a reopen from the cursor resumes from the last position the stream named. It
|
|
238
|
+
* runs only once the frames before it are handled (see `readEventStream`).
|
|
239
|
+
*
|
|
240
|
+
* A frame decode skips is neither handed to onFrame nor reported, whatever id it carries, so its
|
|
241
|
+
* position reaches a cursor only once a later frame or record names one. A reopen before then
|
|
242
|
+
* replays it, and decode skips it again.
|
|
243
|
+
*/
|
|
244
|
+
onLastEventId?: ((lastEventId: string | undefined) => void) | undefined;
|
|
245
|
+
/**
|
|
246
|
+
* operationId names the operation the stream opens, and every failure this open builds names it
|
|
247
|
+
* too: a refusal, a connection failure, and an answer with no body to read
|
|
248
|
+
* (`getAgentRunEvents: 403 FORBIDDEN …`), and so does the frame parser's overflow, which is
|
|
249
|
+
* handed on as a `SseBufferOverflowError` naming it. A failure handed on as it was thrown keeps
|
|
250
|
+
* its own message.
|
|
251
|
+
*/
|
|
252
|
+
operationId: string;
|
|
253
|
+
/** signal is an external abort that tears the open stream down like the returned close. */
|
|
254
|
+
signal?: AbortSignal | undefined;
|
|
255
|
+
/**
|
|
256
|
+
* timeoutMs bounds the open's wait for its response, in milliseconds: past it the request is
|
|
257
|
+
* aborted and onError receives a `MountayaConnectionError` naming the wait. A whole number from
|
|
258
|
+
* 1 to 2,147,483,647; anything else fails the open with a `MountayaConfigurationError` before a
|
|
259
|
+
* request is made. The agent and collaboration transports pass the client's own per-attempt
|
|
260
|
+
* `timeoutMs`, which `MountayaTransport.streamSeam` carries, so their opens wait what a request
|
|
261
|
+
* of the same client waits.
|
|
262
|
+
*
|
|
263
|
+
* Once the response arrives the wait that follows is the stream's silence, which is bounded on
|
|
264
|
+
* its own: a stream that delivers nothing, not even the heartbeat comment the API writes to
|
|
265
|
+
* every live stream, for the stall window is given up the same way.
|
|
266
|
+
*
|
|
267
|
+
* @default the stall window, 45,000 ms, so no wait on the network is unbounded.
|
|
268
|
+
*/
|
|
269
|
+
timeoutMs?: number | undefined;
|
|
270
|
+
/**
|
|
271
|
+
* waitForSession is called before each open's credential is applied, with the open's own
|
|
272
|
+
* signal, and the promise it answers is awaited, so a session token on its way is the one the
|
|
273
|
+
* open carries; `undefined` is nothing to wait for, and the open is made at once. The openers of
|
|
274
|
+
* this entry point pass `MountayaTransport.streamSeam`'s, which waits for a token the
|
|
275
|
+
* credential's source reports on its way, as a request does. What it rejects with reaches
|
|
276
|
+
* onError like any other failed open, and a close during the wait ends it silently.
|
|
277
|
+
*/
|
|
278
|
+
waitForSession?: ((signal: AbortSignal) => Promise<void> | undefined) | undefined;
|
|
279
|
+
/**
|
|
280
|
+
* url is the fully-qualified stream endpoint, or a function answering it. A function is called
|
|
281
|
+
* once, when the open is made, and what it throws reaches onError as a failed open: an opener
|
|
282
|
+
* whose resolver refuses a path (`StreamSeam.url` does, for one that leaves the API) passes the
|
|
283
|
+
* call rather than its answer.
|
|
284
|
+
*/
|
|
285
|
+
url: string | (() => string);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** What one open knows of its own teardown, shared by the request and the read that follows it. */
|
|
289
|
+
interface OpenState {
|
|
290
|
+
/**
|
|
291
|
+
* Set once the caller tears the stream down, through the returned close or their signal. It
|
|
292
|
+
* is what tells that teardown from the abort that closes the connection when a read is over.
|
|
293
|
+
*/
|
|
294
|
+
closedByCaller: boolean;
|
|
295
|
+
/** Aborts the request: on the caller's teardown, at the open's bound, and once the read ends. */
|
|
296
|
+
readonly controller: AbortController;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* requestStream makes one open's request and answers the body the stream is read from. It sets
|
|
301
|
+
* the resume position, resolves the URL and the credential, bounds the wait for the response,
|
|
302
|
+
* and reads a refusal as the error a request answered the same way raises, its message sharpened
|
|
303
|
+
* by what the opener's `declaration` states.
|
|
304
|
+
*
|
|
305
|
+
* @throws `MountayaConfigurationError` for a `timeoutMs` out of range, a `lastEventId` no request
|
|
306
|
+
* header carries, a path or a credential the seam refuses, and a runtime whose fetch exposes
|
|
307
|
+
* no body to stream; `MountayaConnectionError` for a wait that ran out, a fetch that failed and
|
|
308
|
+
* an ok answer that carries no body; the error of the API's own refusal; and what the fetch
|
|
309
|
+
* rejected with where the caller tore the stream down.
|
|
310
|
+
*/
|
|
311
|
+
const requestStream = async <TEvent>(
|
|
312
|
+
options: OpenSseStreamOptions<TEvent>,
|
|
313
|
+
state: OpenState,
|
|
314
|
+
declaration: FailureDeclaration | undefined,
|
|
315
|
+
): Promise<ReadableStream<Uint8Array>> => {
|
|
316
|
+
const { operationId } = options;
|
|
317
|
+
|
|
318
|
+
// Refused before anything is sent: a bound no timer can honour is the caller's mistake, and
|
|
319
|
+
// every open would meet it again.
|
|
320
|
+
const openTimeout = openTimeoutOf(options.timeoutMs, operationId);
|
|
321
|
+
|
|
322
|
+
// Resume after the caller's last seen id: the server replays the durable history
|
|
323
|
+
// past it before resuming the live feed, so a reconnect misses nothing. A position no
|
|
324
|
+
// request header carries is refused here, inside the read and by the rule every header's
|
|
325
|
+
// value is held to, so it reaches onError like any other failed open: it neither escapes the
|
|
326
|
+
// call before its close exists nor reads as the connection failing once the request is
|
|
327
|
+
// refused for it.
|
|
328
|
+
const headers = new Headers({ Accept: "text/event-stream" });
|
|
329
|
+
if (options.lastEventId) {
|
|
330
|
+
// Typed as a string, and still whatever a caller outside the compiler passed: a position
|
|
331
|
+
// kept as a number is read as the text a header carries it as.
|
|
332
|
+
const position = String(options.lastEventId);
|
|
333
|
+
if (!isHeaderValue(position)) {
|
|
334
|
+
throw new MountayaConfigurationError(
|
|
335
|
+
`${operationId}: lastEventId holds a character no request header carries, so the stream cannot be resumed from it. Pass the position the stream named, as it named it, or leave it out to read from the start.`,
|
|
336
|
+
);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
headers.set("Last-Event-ID", position);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// A token on its way is waited for before the credential is read, so the open carries it
|
|
343
|
+
// rather than going out under the key alone. A close during the wait aborts it, and the abort
|
|
344
|
+
// is the caller's own teardown.
|
|
345
|
+
const waiting = options.waitForSession?.(state.controller.signal);
|
|
346
|
+
if (waiting !== undefined) {
|
|
347
|
+
await waiting;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// Outside the request's own failure handling: what the URL's resolver and applyAuth throw (a
|
|
351
|
+
// path or a credential the seam refuses) is the caller's answer, never the connection's.
|
|
352
|
+
const url = typeof options.url === "function" ? options.url() : options.url;
|
|
353
|
+
const init = options.applyAuth({ headers, signal: state.controller.signal }, "GET");
|
|
354
|
+
|
|
355
|
+
// The wait for the response is bounded, and the bound ends it the way the caller's close
|
|
356
|
+
// does, through the request's own signal. `timedOut` tells the two apart afterwards.
|
|
357
|
+
let timedOut = false;
|
|
358
|
+
const deadline = setTimeout(() => {
|
|
359
|
+
timedOut = true;
|
|
360
|
+
state.controller.abort();
|
|
361
|
+
}, openTimeout);
|
|
362
|
+
|
|
363
|
+
let response: Response;
|
|
364
|
+
try {
|
|
365
|
+
response = await options.doFetch(url, init);
|
|
366
|
+
} catch (cause) {
|
|
367
|
+
// The caller's abort is theirs. The bound's abort is this reader's, and says which wait ran
|
|
368
|
+
// out, with the budget and, where the caller set it, the option that sets it. A failure
|
|
369
|
+
// already in the family (an error a fetch wrapped by this package raised) says what it is.
|
|
370
|
+
// What else rejects a fetch is the connection.
|
|
371
|
+
if (state.closedByCaller) {
|
|
372
|
+
throw cause;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
if (timedOut) {
|
|
376
|
+
throw new MountayaConnectionError(
|
|
377
|
+
options.timeoutMs === undefined
|
|
378
|
+
? `${operationId}: no response within ${openTimeout} ms. Check the network path to the API.`
|
|
379
|
+
: `${operationId}: no response within ${openTimeout} ms. Raise timeoutMs for a stream that is slow to answer, or check the network path to the API.`,
|
|
380
|
+
);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
if (isMountayaError(cause)) {
|
|
384
|
+
throw cause;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
throw new MountayaConnectionError(
|
|
388
|
+
`${operationId}: the stream failed before a response arrived. Check the network, and that the stream's URL names a host that answers.`,
|
|
389
|
+
cause,
|
|
390
|
+
);
|
|
391
|
+
} finally {
|
|
392
|
+
clearTimeout(deadline);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
options.onResponse?.(response);
|
|
396
|
+
|
|
397
|
+
if (!response.ok) {
|
|
398
|
+
// The error a request the API answered the same way raises, read from the refusal's body
|
|
399
|
+
// under the bounds every refusal's body is read under: past either one the status alone
|
|
400
|
+
// classifies it, so a refusal stays a failure the caller hears of. The caller's close ends
|
|
401
|
+
// the read as it ends the open.
|
|
402
|
+
throw await readFailure(response, {
|
|
403
|
+
...declaration,
|
|
404
|
+
operationId,
|
|
405
|
+
signal: state.controller.signal,
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// Read against a widened type: lib.dom declares a body on every Response, and a runtime
|
|
410
|
+
// whose fetch buffers every body before answering leaves it undefined.
|
|
411
|
+
const body: ReadableStream<Uint8Array> | null | undefined = response.body;
|
|
412
|
+
if (body === undefined) {
|
|
413
|
+
throw new MountayaConfigurationError(
|
|
414
|
+
`${operationId}: this runtime's fetch exposes no response body to read the stream from. Pass a fetch that streams response bodies.`,
|
|
415
|
+
);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
if (body === null) {
|
|
419
|
+
throw new MountayaConnectionError(
|
|
420
|
+
`${operationId}: the ${response.status} answer carries no body, so something on the network path answered in the API's place. Check the network path to the API.`,
|
|
421
|
+
);
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
return body;
|
|
425
|
+
};
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* openDeclaredSseStream is {@link openSseStream} for an opener that states what its operation
|
|
429
|
+
* declares about the credentials it takes, as a request descriptor states it: a refusal of the
|
|
430
|
+
* open then names the step that declaration calls for, as the same refusal of a request does. The
|
|
431
|
+
* openers of this entry point state it; a caller of {@link openSseStream} states none, and its
|
|
432
|
+
* refusals name the step every call shares.
|
|
433
|
+
*/
|
|
434
|
+
export const openDeclaredSseStream = <TEvent>(
|
|
435
|
+
options: OpenSseStreamOptions<TEvent>,
|
|
436
|
+
declaration: FailureDeclaration | undefined,
|
|
437
|
+
): (() => void) => {
|
|
438
|
+
const { operationId, signal } = options;
|
|
439
|
+
|
|
440
|
+
// The returned close aborts this controller, which closes the in-flight fetch and
|
|
441
|
+
// the body read so a caller tearing the stream down never leaks a parked read. An
|
|
442
|
+
// external options.signal is an equivalent teardown path: its abort runs the same
|
|
443
|
+
// close. `state.closedByCaller` is what tells that teardown apart from the abort that closes
|
|
444
|
+
// the connection once a read is over.
|
|
445
|
+
const state: OpenState = { closedByCaller: false, controller: new AbortController() };
|
|
446
|
+
const close = (): void => {
|
|
447
|
+
state.closedByCaller = true;
|
|
448
|
+
state.controller.abort();
|
|
449
|
+
};
|
|
450
|
+
|
|
451
|
+
if (signal?.aborted) {
|
|
452
|
+
close();
|
|
453
|
+
} else {
|
|
454
|
+
signal?.addEventListener("abort", close, { once: true });
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// Set when the caller's decode, onFrame or onLastEventId throws, so the fault is handed on
|
|
458
|
+
// as the caller's own rather than read as the connection failing under the read.
|
|
459
|
+
let callerFault = false;
|
|
460
|
+
const handle = async (frame: SseFrame): Promise<boolean> => {
|
|
461
|
+
if (state.closedByCaller) {
|
|
462
|
+
return true;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
try {
|
|
466
|
+
const event = options.decode(frame);
|
|
467
|
+
if (event === null) {
|
|
468
|
+
return false;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// The frame id is the stream position; hand it to onFrame so a caller can
|
|
472
|
+
// record it as the resume cursor. An empty id means an unnumbered frame.
|
|
473
|
+
return await options.onFrame(event, frame.id || undefined);
|
|
474
|
+
} catch (error) {
|
|
475
|
+
callerFault = true;
|
|
476
|
+
|
|
477
|
+
throw error;
|
|
478
|
+
}
|
|
479
|
+
};
|
|
480
|
+
const report = (lastEventId: string): void => {
|
|
481
|
+
if (state.closedByCaller) {
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
try {
|
|
486
|
+
options.onLastEventId?.(lastEventId || undefined);
|
|
487
|
+
} catch (error) {
|
|
488
|
+
callerFault = true;
|
|
489
|
+
|
|
490
|
+
throw error;
|
|
491
|
+
}
|
|
492
|
+
};
|
|
493
|
+
|
|
494
|
+
const read = async (): Promise<EventStreamOutcome> => {
|
|
495
|
+
const body = await requestStream(options, state, declaration);
|
|
496
|
+
|
|
497
|
+
// Read under the stall window. The request's abort, the caller's close and the end of the
|
|
498
|
+
// read alike, ends a wait still pending on the body, even one whose fetch does not tie the
|
|
499
|
+
// body to the request's signal.
|
|
500
|
+
try {
|
|
501
|
+
return await readEventStream(
|
|
502
|
+
boundSilence(body, operationId, state.controller.signal),
|
|
503
|
+
handle,
|
|
504
|
+
report,
|
|
505
|
+
);
|
|
506
|
+
} catch (cause) {
|
|
507
|
+
if (state.closedByCaller || callerFault) {
|
|
508
|
+
throw cause;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// The frame parser knows no operation, so its overflow is handed on naming this one, as
|
|
512
|
+
// the class it is and carrying the limit it enforced.
|
|
513
|
+
if (cause instanceof SseBufferOverflowError) {
|
|
514
|
+
throw new SseBufferOverflowError(cause.limit, operationId, { cause });
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
if (isMountayaError(cause)) {
|
|
518
|
+
throw cause;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
throw new MountayaConnectionError(
|
|
522
|
+
`${operationId}: the stream broke off before it ended. Reopen it from the last position it named, and check the network path to the API if it keeps breaking off.`,
|
|
523
|
+
cause,
|
|
524
|
+
);
|
|
525
|
+
}
|
|
526
|
+
};
|
|
527
|
+
|
|
528
|
+
// The read settles on a microtask at the earliest, so onFrame, onLastEventId, onClose and
|
|
529
|
+
// onError run after this call has returned the close. The request is made inside the call: the
|
|
530
|
+
// url resolver, applyAuth and doFetch are each called before it returns.
|
|
531
|
+
void (async () => {
|
|
532
|
+
// Torn down before it began, by a signal already aborted: nothing is read, authenticated
|
|
533
|
+
// or requested, and the teardown is the caller's own, which fires neither callback.
|
|
534
|
+
if (state.closedByCaller) {
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
let settled: { readonly outcome: EventStreamOutcome } | { readonly error: unknown };
|
|
539
|
+
try {
|
|
540
|
+
settled = { outcome: await read() };
|
|
541
|
+
} catch (error) {
|
|
542
|
+
settled = { error };
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
// The read is over, so the connection goes with it and the caller's signal is let go.
|
|
546
|
+
signal?.removeEventListener("abort", close);
|
|
547
|
+
state.controller.abort();
|
|
548
|
+
|
|
549
|
+
if (state.closedByCaller) {
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
if ("outcome" in settled) {
|
|
554
|
+
options.onClose?.(settled.outcome);
|
|
555
|
+
} else {
|
|
556
|
+
options.onError?.(settled.error);
|
|
557
|
+
}
|
|
558
|
+
})();
|
|
559
|
+
|
|
560
|
+
return close;
|
|
561
|
+
};
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* openSseStream opens one resumable `text/event-stream` read over fetch and returns
|
|
565
|
+
* a close function that aborts it. It is the scaffolding every SSE consumer repeats:
|
|
566
|
+
* it forwards an external abort into its own controller, sets Accept and an optional
|
|
567
|
+
* Last-Event-ID, makes the request, decodes each frame through the caller's decode,
|
|
568
|
+
* hands each decoded event to onFrame (whose return stops the read on a terminal), and
|
|
569
|
+
* settles through onClose or, on a failure, onError. The reader stays vocabulary-free:
|
|
570
|
+
* every feature keeps its own decode and schema and shares only this transport shell.
|
|
571
|
+
*
|
|
572
|
+
* The call itself never throws and always returns the close. Whatever fails, a `timeoutMs` out
|
|
573
|
+
* of range, a `lastEventId` no request header carries, a credential or a path its seam refuses,
|
|
574
|
+
* reaches onError. `onFrame`, `onLastEventId`, `onClose` and `onError` run after the close has
|
|
575
|
+
* been returned; `url`, where it is a function, `applyAuth` and `doFetch` are each called once
|
|
576
|
+
* inside the call. An open under a `signal` that has already aborted reads no credential and
|
|
577
|
+
* makes no request.
|
|
578
|
+
*
|
|
579
|
+
* The connection lives exactly as long as the read. Once the read ends for any reason (a
|
|
580
|
+
* terminal frame, the body closing, a failure) the request is aborted and its body let go, so a
|
|
581
|
+
* stopped read leaves no socket open behind it, and then onClose or onError runs, once. A caller's
|
|
582
|
+
* abort, through the returned close or `signal`, is the caller's own teardown: it fires neither,
|
|
583
|
+
* and no frame is handed over after it. The returned close is inert once the stream has settled,
|
|
584
|
+
* and the listener on `signal` is removed then, so a signal that outlives many streams holds none
|
|
585
|
+
* of them.
|
|
586
|
+
*
|
|
587
|
+
* No wait on the network is unbounded. The wait for the response ends at `timeoutMs`, and each
|
|
588
|
+
* wait for the next chunk of the body ends once the stream has delivered nothing, not even a
|
|
589
|
+
* heartbeat comment, for the stall window. Either ends the read as a `MountayaConnectionError`,
|
|
590
|
+
* the failure a caller reopens on, rather than as a read that never settles. The time a frame
|
|
591
|
+
* handler holds the read is the caller's, and never counts as the stream's silence.
|
|
592
|
+
*/
|
|
593
|
+
export const openSseStream = <TEvent>(options: OpenSseStreamOptions<TEvent>): (() => void) =>
|
|
594
|
+
openDeclaredSseStream(options, undefined);
|