@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,492 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading a response's body once its headers are in: the caller's abort that ends the read, a
|
|
3
|
+
* body that breaks off, a success whose body is not JSON, and the bounds a refusal's body is
|
|
4
|
+
* read under.
|
|
5
|
+
*
|
|
6
|
+
* A body is read through a reader this module opens, so the read can be cancelled: on the
|
|
7
|
+
* caller's abort, and at a refusal's bounds. Cancelling lets go of the body's lock and of its
|
|
8
|
+
* connection on every runtime, where the runtime's own `text()` holds both until the body ends.
|
|
9
|
+
*
|
|
10
|
+
* Apart from the transport because a Data API call, a collaboration signal and an event-stream
|
|
11
|
+
* open read their bodies by these rules too, and `@mountaya/client/events` imports the transport
|
|
12
|
+
* as a type alone: kept there, these rules would carry the transport class into that entry.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { type DateMask, decodeDates, parseJsonWithDates } from "./dates.js";
|
|
16
|
+
import {
|
|
17
|
+
answerDetailsOf,
|
|
18
|
+
errorFromBody,
|
|
19
|
+
errorFromResponse,
|
|
20
|
+
type FailureDeclaration,
|
|
21
|
+
MountayaApiError,
|
|
22
|
+
MountayaConnectionError,
|
|
23
|
+
} from "./errors.js";
|
|
24
|
+
import { abortReasonOf } from "./retry.js";
|
|
25
|
+
import type { RequestArgs } from "./transport.js";
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* REFUSAL_WAIT_MS bounds how long a refused call waits for the refusal's body, in milliseconds.
|
|
29
|
+
* The API's error envelope is small and follows the status at once, so a body still arriving
|
|
30
|
+
* after this long comes from something on the network path, and waiting on it would hold the
|
|
31
|
+
* failure back from a caller that acts on one.
|
|
32
|
+
*/
|
|
33
|
+
const REFUSAL_WAIT_MS = 5_000;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* MAX_REFUSAL_BYTES bounds how much of a refusal's body is read, in bytes. The API's error
|
|
37
|
+
* envelope is a few entries long, so a body past this is not one, and read whole it would grow
|
|
38
|
+
* the reader for as long as whatever sent it kept sending.
|
|
39
|
+
*/
|
|
40
|
+
const MAX_REFUSAL_BYTES = 64 * 1024;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* isAborted reads whether a caller's signal has aborted, afresh at every call: a signal aborts
|
|
44
|
+
* between two reads, which a check the compiler narrows once would not see.
|
|
45
|
+
*/
|
|
46
|
+
export const isAborted = (signal: AbortSignal): boolean => signal.aborted;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* settleOnAbort settles as `work` does, unless the caller's `signal` aborts first: then it rejects
|
|
50
|
+
* at once with {@link abortReasonOf} the signal, and so it does when the signal has aborted by the
|
|
51
|
+
* time `work` settles. With no signal it is `work` itself.
|
|
52
|
+
*
|
|
53
|
+
* It is what ends a call on its caller's abort where the work cannot be cancelled: a body the
|
|
54
|
+
* runtime buffered whole and exposes no stream of (React Native), read through the runtime's own
|
|
55
|
+
* `text()`. There the work is abandoned rather than stopped. A body that streams is read through
|
|
56
|
+
* {@link readText}, {@link readBytes} or {@link readFailure}, which cancel it.
|
|
57
|
+
*/
|
|
58
|
+
export const settleOnAbort = async <T>(
|
|
59
|
+
work: () => Promise<T>,
|
|
60
|
+
signal: AbortSignal | undefined,
|
|
61
|
+
): Promise<T> => {
|
|
62
|
+
if (signal === undefined) {
|
|
63
|
+
return work();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (isAborted(signal)) {
|
|
67
|
+
throw abortReasonOf(signal);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
let stopWatching = () => {};
|
|
71
|
+
const aborted = new Promise<never>((_resolve, reject) => {
|
|
72
|
+
const onAbort = () => {
|
|
73
|
+
reject(abortReasonOf(signal));
|
|
74
|
+
};
|
|
75
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
76
|
+
stopWatching = () => {
|
|
77
|
+
signal.removeEventListener("abort", onAbort);
|
|
78
|
+
};
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
try {
|
|
82
|
+
const settled = await Promise.race([work(), aborted]);
|
|
83
|
+
|
|
84
|
+
// The abort may have reached the work first and been swallowed there, as a failure's body
|
|
85
|
+
// read is: the call still ends on the abort.
|
|
86
|
+
if (isAborted(signal)) {
|
|
87
|
+
throw abortReasonOf(signal);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return settled;
|
|
91
|
+
} finally {
|
|
92
|
+
stopWatching();
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* CallReading is what a body read knows about the call it reads for: the operation a failure
|
|
98
|
+
* names, whether repeating the call is safe, the `Idempotency-Key` it sent, where it sent one,
|
|
99
|
+
* and the caller's signal.
|
|
100
|
+
*/
|
|
101
|
+
type CallReading = Pick<RequestArgs, "idempotencyKey" | "idempotent" | "operationId" | "signal">;
|
|
102
|
+
|
|
103
|
+
/** The bounds one read of a body runs under, each absent where the read has none. */
|
|
104
|
+
interface DrainBounds {
|
|
105
|
+
/** The most bytes read: a body past it is cut, and none of it is kept. */
|
|
106
|
+
readonly maxBytes?: number | undefined;
|
|
107
|
+
/** The caller's signal, whose abort cancels the body and ends the read. */
|
|
108
|
+
readonly signal?: AbortSignal | undefined;
|
|
109
|
+
/** The longest the read lasts, in milliseconds: a body still arriving then is cut. */
|
|
110
|
+
readonly timeoutMs?: number | undefined;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** What a read of a body came to. */
|
|
114
|
+
interface Drained {
|
|
115
|
+
/** The bytes that arrived, in order: all of them for a whole body, none past `maxBytes`. */
|
|
116
|
+
readonly bytes: Uint8Array<ArrayBuffer>;
|
|
117
|
+
/** What the stream failed with, where it broke off before its end. */
|
|
118
|
+
readonly brokeOff?: { readonly cause: unknown } | undefined;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** concat joins a body's chunks into one buffer of exactly their length. */
|
|
122
|
+
const concat = (chunks: readonly Uint8Array[], byteLength: number): Uint8Array<ArrayBuffer> => {
|
|
123
|
+
const bytes = new Uint8Array(byteLength);
|
|
124
|
+
let offset = 0;
|
|
125
|
+
for (const chunk of chunks) {
|
|
126
|
+
bytes.set(chunk, offset);
|
|
127
|
+
offset += chunk.byteLength;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return bytes;
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* drain reads a body to its end through a reader of its own, under `bounds`, and always lets go
|
|
135
|
+
* of the body: a read that ends early, for any reason, cancels it, which releases its connection
|
|
136
|
+
* and its lock.
|
|
137
|
+
*
|
|
138
|
+
* A body that breaks off is reported rather than thrown, with what arrived before it did, so a
|
|
139
|
+
* caller decides what a broken body means for the call it reads for. A body that hands out no
|
|
140
|
+
* reader, because something else holds one on it, is reported the same way with nothing read:
|
|
141
|
+
* what the stream refused with is the runtime's own `TypeError`, outside the family a caller
|
|
142
|
+
* catches.
|
|
143
|
+
*
|
|
144
|
+
* @throws the caller's abort reason, from {@link abortReasonOf}, where `bounds.signal` has
|
|
145
|
+
* aborted before the read or aborts during it.
|
|
146
|
+
*/
|
|
147
|
+
const drain = async (body: ReadableStream<Uint8Array>, bounds: DrainBounds): Promise<Drained> => {
|
|
148
|
+
const { maxBytes, signal, timeoutMs } = bounds;
|
|
149
|
+
|
|
150
|
+
let reader: ReadableStreamDefaultReader<Uint8Array>;
|
|
151
|
+
try {
|
|
152
|
+
reader = body.getReader();
|
|
153
|
+
} catch (cause) {
|
|
154
|
+
// The caller's abort is theirs whatever state the body is in.
|
|
155
|
+
if (signal !== undefined && isAborted(signal)) {
|
|
156
|
+
throw abortReasonOf(signal);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return { brokeOff: { cause }, bytes: concat([], 0) };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Cancelling settles a read still pending, whatever the fetch that opened the body does with
|
|
163
|
+
// the request's signal, and lets the connection go. A body already errored or closed has
|
|
164
|
+
// nothing to cancel, and its refusal is dropped for that reason.
|
|
165
|
+
const cancel = (reason?: unknown): void => {
|
|
166
|
+
reader.cancel(reason).catch(() => undefined);
|
|
167
|
+
};
|
|
168
|
+
const letGo = (): void => {
|
|
169
|
+
try {
|
|
170
|
+
reader.releaseLock();
|
|
171
|
+
} catch {
|
|
172
|
+
// A runtime that keeps the lock while a read is pending lets it go once the read settles.
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
if (signal !== undefined && isAborted(signal)) {
|
|
177
|
+
cancel(abortReasonOf(signal));
|
|
178
|
+
letGo();
|
|
179
|
+
|
|
180
|
+
throw abortReasonOf(signal);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const onAbort = (): void => {
|
|
184
|
+
if (signal !== undefined) {
|
|
185
|
+
cancel(abortReasonOf(signal));
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
189
|
+
|
|
190
|
+
const deadline = timeoutMs === undefined ? undefined : setTimeout(cancel, timeoutMs);
|
|
191
|
+
|
|
192
|
+
const chunks: Uint8Array[] = [];
|
|
193
|
+
let received = 0;
|
|
194
|
+
let brokeOff: Drained["brokeOff"];
|
|
195
|
+
try {
|
|
196
|
+
while (true) {
|
|
197
|
+
const { done, value } = await reader.read();
|
|
198
|
+
|
|
199
|
+
// A cancelled read settles as a body that ended, so the abort is read off the signal.
|
|
200
|
+
if (signal !== undefined && isAborted(signal)) {
|
|
201
|
+
throw abortReasonOf(signal);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// The deadline's cancel ends the read as a body that ended too: what arrived by then is
|
|
205
|
+
// what the read answers.
|
|
206
|
+
if (done) {
|
|
207
|
+
break;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
received += value.byteLength;
|
|
211
|
+
if (maxBytes !== undefined && received > maxBytes) {
|
|
212
|
+
// Not what the caller reads for, so none of it is kept.
|
|
213
|
+
chunks.length = 0;
|
|
214
|
+
received = 0;
|
|
215
|
+
break;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
chunks.push(value);
|
|
219
|
+
}
|
|
220
|
+
} catch (cause) {
|
|
221
|
+
if (signal !== undefined && isAborted(signal)) {
|
|
222
|
+
throw abortReasonOf(signal);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
brokeOff = { cause };
|
|
226
|
+
} finally {
|
|
227
|
+
clearTimeout(deadline);
|
|
228
|
+
signal?.removeEventListener("abort", onAbort);
|
|
229
|
+
cancel();
|
|
230
|
+
letGo();
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return { brokeOff, bytes: concat(chunks, received) };
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* The next step a body that broke off names, by whether repeating the call is safe: it is where
|
|
238
|
+
* the operation declares itself idempotent, and where the call sent a key, which the API answers
|
|
239
|
+
* with the answer it kept.
|
|
240
|
+
*/
|
|
241
|
+
const brokenBodyStep = (call: CallReading): string => {
|
|
242
|
+
if (call.idempotent) {
|
|
243
|
+
return "Retry the call, or check the network path to the API.";
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
return call.idempotencyKey === undefined
|
|
247
|
+
? "The call was answered, so check whether it took effect before repeating it, and check the network path to the API."
|
|
248
|
+
: "The call was answered, so send it again with this error's idempotencyKey, never a new one, and the API answers with the answer it kept; check the network path to the API.";
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
/** brokenBody builds the failure a success's body that broke off is reported as. */
|
|
252
|
+
const brokenBody = (call: CallReading, cause: unknown): MountayaConnectionError =>
|
|
253
|
+
new MountayaConnectionError(
|
|
254
|
+
`${call.operationId}: the response arrived and its body broke off before it was complete. ${brokenBodyStep(call)}`,
|
|
255
|
+
cause,
|
|
256
|
+
call.idempotencyKey,
|
|
257
|
+
);
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* readBuffered reads a success's body through the runtime's own reader (`text`, `arrayBuffer`),
|
|
261
|
+
* for a response whose body the runtime exposes no stream of, and reports a failed read as
|
|
262
|
+
* {@link readText} does.
|
|
263
|
+
*/
|
|
264
|
+
const readBuffered = async <T>(read: () => Promise<T>, call: CallReading): Promise<T> => {
|
|
265
|
+
try {
|
|
266
|
+
return await settleOnAbort(read, call.signal);
|
|
267
|
+
} catch (cause) {
|
|
268
|
+
if (call.signal !== undefined && isAborted(call.signal)) {
|
|
269
|
+
throw abortReasonOf(call.signal);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
throw brokenBody(call, cause);
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* streamOf reads a response's body as the stream to drain, or undefined where there is none to:
|
|
278
|
+
* a response with no body, a runtime whose fetch buffers every body and exposes no stream, a
|
|
279
|
+
* body that is no web stream, or a body something read before this client did. Read against a
|
|
280
|
+
* widened type, since `lib.dom` declares a body on every `Response`.
|
|
281
|
+
*
|
|
282
|
+
* A `fetch` wrapped around the runtime's own that reads a response without cloning it hands back
|
|
283
|
+
* a body already read. Its stream is at its end, so drained it would read as an empty body, an
|
|
284
|
+
* answer the API did not give. Left to the runtime's own reader instead, the read is refused and
|
|
285
|
+
* the refusal is reported as a body that broke off is.
|
|
286
|
+
*
|
|
287
|
+
* A `fetch` option built on another stream family answers a body that hands out no reader, a
|
|
288
|
+
* Node `Readable` for one. Its response reads that body through `text` and `arrayBuffer`, so the
|
|
289
|
+
* read is left to them, as it is for a body the runtime buffers.
|
|
290
|
+
*/
|
|
291
|
+
const streamOf = (response: Response): ReadableStream<Uint8Array> | undefined => {
|
|
292
|
+
const body: ReadableStream<Uint8Array> | null | undefined = response.body;
|
|
293
|
+
if (response.bodyUsed || body === null || body === undefined) {
|
|
294
|
+
return undefined;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
return typeof body.getReader === "function" ? body : undefined;
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* readBytes reads a success's body whole, as bytes, and reports a body that breaks off before
|
|
302
|
+
* it is complete as the connection failure it is.
|
|
303
|
+
*
|
|
304
|
+
* The response has arrived by then, so what can go wrong is the connection: a socket dropped
|
|
305
|
+
* mid-body, a proxy that cut it off. The runtime reports that as a `TypeError`, outside the
|
|
306
|
+
* family a caller catches, and a caller that classifies failures would file a dropped download
|
|
307
|
+
* as a bug in their own program. It becomes a `MountayaConnectionError`, carrying the runtime's
|
|
308
|
+
* error as its `cause`, and it is not retried: a response did arrive, and for a write its effect
|
|
309
|
+
* already happened. The message's next step says as much: a call that is safe to repeat is
|
|
310
|
+
* retried, and a write is checked for its effect before it is repeated.
|
|
311
|
+
*
|
|
312
|
+
* A caller's abort is theirs: it cancels the body, which lets go of the body's lock and of its
|
|
313
|
+
* connection on every runtime, and settles the read at once with the signal's own reason, never
|
|
314
|
+
* rewrapped. A body aborted before its read began is cancelled the same way. Where the runtime
|
|
315
|
+
* exposes no stream of the body, the read goes through the runtime's own and an abort abandons
|
|
316
|
+
* it, see {@link settleOnAbort}.
|
|
317
|
+
*
|
|
318
|
+
* @throws `MountayaConnectionError` for a body that broke off; the caller's abort reason for a
|
|
319
|
+
* read the caller aborted.
|
|
320
|
+
*/
|
|
321
|
+
export const readBytes = async (response: Response, call: CallReading): Promise<ArrayBuffer> => {
|
|
322
|
+
const body = streamOf(response);
|
|
323
|
+
if (body === undefined) {
|
|
324
|
+
return readBuffered(() => response.arrayBuffer(), call);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
const drained = await drain(body, { signal: call.signal });
|
|
328
|
+
if (drained.brokeOff !== undefined) {
|
|
329
|
+
throw brokenBody(call, drained.brokeOff.cause);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
return drained.bytes.buffer;
|
|
333
|
+
};
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* readText reads a success's body whole, as the UTF-8 text it is, under the rules of
|
|
337
|
+
* {@link readBytes}.
|
|
338
|
+
*
|
|
339
|
+
* @throws as {@link readBytes} does.
|
|
340
|
+
*/
|
|
341
|
+
export const readText = async (response: Response, call: CallReading): Promise<string> =>
|
|
342
|
+
streamOf(response) === undefined
|
|
343
|
+
? readBuffered(() => response.text(), call)
|
|
344
|
+
: new TextDecoder().decode(await readBytes(response, call));
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* readFailureText reads what a refusal's body says, as text, from at most
|
|
348
|
+
* {@link MAX_REFUSAL_BYTES} of it within {@link REFUSAL_WAIT_MS}, and never fails on the body:
|
|
349
|
+
* one past the size bound reads as `""`, and one that broke off or did not arrive whole reads as
|
|
350
|
+
* far as it arrived, which is then no envelope.
|
|
351
|
+
*
|
|
352
|
+
* The bounds keep a refusal a failure the caller hears of. The body only sharpens an error the
|
|
353
|
+
* status already classifies, so past either bound it is let go and the status decides alone.
|
|
354
|
+
*
|
|
355
|
+
* @throws the caller's abort reason for a read the caller aborted.
|
|
356
|
+
*/
|
|
357
|
+
export const readFailureText = async (
|
|
358
|
+
response: Response,
|
|
359
|
+
signal: AbortSignal | undefined,
|
|
360
|
+
): Promise<string> => {
|
|
361
|
+
const body = streamOf(response);
|
|
362
|
+
if (body === undefined) {
|
|
363
|
+
return settleOnAbort(() => response.text().catch(() => ""), signal);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
const { bytes } = await drain(body, {
|
|
367
|
+
maxBytes: MAX_REFUSAL_BYTES,
|
|
368
|
+
signal,
|
|
369
|
+
timeoutMs: REFUSAL_WAIT_MS,
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
return new TextDecoder().decode(bytes);
|
|
373
|
+
};
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* readFailure builds the error a non-2xx response maps to, reading the response's body under the
|
|
377
|
+
* bounds of {@link readFailureText} and under the caller's signal.
|
|
378
|
+
*
|
|
379
|
+
* The body only improves the message of an error the status already classifies, so a body that
|
|
380
|
+
* does not arrive, arrives past a bound or does not parse is tolerated: the status alone then
|
|
381
|
+
* decides the class, and a `402` naming no code is a `MountayaBillingError`. A caller's abort
|
|
382
|
+
* still ends the read: the caller who left is not waiting for a better message.
|
|
383
|
+
*
|
|
384
|
+
* What the call's operation declares, where the caller states it, sharpens the step the message
|
|
385
|
+
* names: a request descriptor states it as it is, so a call through the transport hands its
|
|
386
|
+
* `RequestArgs` over whole, with the `idempotencyKey` the call sent, which the error carries.
|
|
387
|
+
*
|
|
388
|
+
* @throws the caller's abort reason for a read the caller aborted.
|
|
389
|
+
*/
|
|
390
|
+
export const readFailure = async (
|
|
391
|
+
response: Response,
|
|
392
|
+
call: Pick<CallReading, "idempotencyKey" | "operationId" | "signal"> & FailureDeclaration,
|
|
393
|
+
): Promise<MountayaApiError> => {
|
|
394
|
+
const declaration: FailureDeclaration = {
|
|
395
|
+
actsAsMember: call.actsAsMember,
|
|
396
|
+
requiresSecretKey: call.requiresSecretKey,
|
|
397
|
+
};
|
|
398
|
+
|
|
399
|
+
if (streamOf(response) === undefined) {
|
|
400
|
+
return settleOnAbort(
|
|
401
|
+
() => errorFromResponse(response, call.operationId, declaration, call.idempotencyKey),
|
|
402
|
+
call.signal,
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
return errorFromBody(
|
|
407
|
+
await readFailureText(response, call.signal),
|
|
408
|
+
response,
|
|
409
|
+
call.operationId,
|
|
410
|
+
declaration,
|
|
411
|
+
call.idempotencyKey,
|
|
412
|
+
);
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* parseSuccessBody parses the body of a success a call answers with JSON, decoding no `Date` (the
|
|
417
|
+
* caller decodes the instants its mask names), and reports a body that is not JSON as an error
|
|
418
|
+
* the API answered.
|
|
419
|
+
*
|
|
420
|
+
* An answer arrived, so a body that does not decode is the base `MountayaApiError` and never a
|
|
421
|
+
* `MountayaConnectionError`, which says no answer came: it carries the answer's status, its
|
|
422
|
+
* request id and the rate-limit state its headers describe, with the runtime's `SyntaxError` as
|
|
423
|
+
* its `cause`, and no entry, since no status of the ladder classifies it. The API answers JSON or
|
|
424
|
+
* nothing, so such a body is likely something standing in its place, a captive portal's sign-in
|
|
425
|
+
* page, a proxy's own page, or a base URL that names a web application rather than the API, and
|
|
426
|
+
* the message names the network path and the base URL to check. It is not retried: an answer
|
|
427
|
+
* arrived, and for a write its effect is unknown. An empty body is no body, which every delete
|
|
428
|
+
* answers with, and parses as undefined.
|
|
429
|
+
*
|
|
430
|
+
* One rule for every call that answers JSON: a REST or Tile API call through
|
|
431
|
+
* `MountayaTransport`'s `request`, a Data API call and a collaboration signal alike.
|
|
432
|
+
*
|
|
433
|
+
* @throws the base `MountayaApiError` for a body that is not JSON, carrying the `idempotencyKey`
|
|
434
|
+
* the call sent, where it sent one.
|
|
435
|
+
*/
|
|
436
|
+
export const parseSuccessBody = (
|
|
437
|
+
text: string,
|
|
438
|
+
answer: Pick<Response, "headers" | "status">,
|
|
439
|
+
call: Pick<RequestArgs, "idempotencyKey" | "operationId" | "surface">,
|
|
440
|
+
): unknown => {
|
|
441
|
+
try {
|
|
442
|
+
return parseJsonWithDates(text);
|
|
443
|
+
} catch (cause) {
|
|
444
|
+
const details = answerDetailsOf(answer.headers);
|
|
445
|
+
const request = details.requestId === undefined ? "" : ` (request ${details.requestId})`;
|
|
446
|
+
|
|
447
|
+
throw new MountayaApiError(
|
|
448
|
+
`${call.operationId}: the ${answer.status} answer is not JSON, so it holds nothing this client can read; something on the network path may have answered in the API's place, such as a captive portal or a proxy. Check the network path to the API, and that baseUrls.${call.surface} names the API.${request}`,
|
|
449
|
+
answer.status,
|
|
450
|
+
[],
|
|
451
|
+
{ ...details, cause, idempotencyKey: call.idempotencyKey },
|
|
452
|
+
);
|
|
453
|
+
}
|
|
454
|
+
};
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* decodeSuccessDates decodes to a `Date` each instant `mask` names in a success's parsed body,
|
|
458
|
+
* and reports a string a declared field holds that names no instant as an error the API answered,
|
|
459
|
+
* as {@link parseSuccessBody} reports a body that is not JSON.
|
|
460
|
+
*
|
|
461
|
+
* The contract declares an instant there, so the answer does not decode: it is the base
|
|
462
|
+
* `MountayaApiError`, carrying the answer's status, its request id and the rate-limit state its
|
|
463
|
+
* headers describe, with the decoder's failure, which names the field, as its `cause`, and no
|
|
464
|
+
* entry. It is not retried: an answer arrived, and for a write its effect is unknown.
|
|
465
|
+
*
|
|
466
|
+
* One rule for every answer a mask decodes: a REST or Tile API call through `MountayaTransport`'s
|
|
467
|
+
* `request` and a Data API operation's result alike.
|
|
468
|
+
*
|
|
469
|
+
* @throws the base `MountayaApiError` for a declared instant that names none, carrying the
|
|
470
|
+
* `idempotencyKey` the call sent, where it sent one.
|
|
471
|
+
*/
|
|
472
|
+
export const decodeSuccessDates = (
|
|
473
|
+
body: unknown,
|
|
474
|
+
mask: DateMask | undefined,
|
|
475
|
+
answer: Pick<Response, "headers" | "status">,
|
|
476
|
+
call: Pick<RequestArgs, "idempotencyKey" | "operationId">,
|
|
477
|
+
): unknown => {
|
|
478
|
+
try {
|
|
479
|
+
return decodeDates(body, mask);
|
|
480
|
+
} catch (cause) {
|
|
481
|
+
const details = answerDetailsOf(answer.headers);
|
|
482
|
+
const request = details.requestId === undefined ? "" : ` (request ${details.requestId})`;
|
|
483
|
+
const failure = cause instanceof Error ? cause.message : String(cause);
|
|
484
|
+
|
|
485
|
+
throw new MountayaApiError(
|
|
486
|
+
`${call.operationId}: the ${answer.status} answer does not decode, since ${failure}${request}`,
|
|
487
|
+
answer.status,
|
|
488
|
+
[],
|
|
489
|
+
{ ...details, cause, idempotencyKey: call.idempotencyKey },
|
|
490
|
+
);
|
|
491
|
+
}
|
|
492
|
+
};
|