@mountaya/client 0.0.0-stage → 0.2.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 +149 -0
- package/LICENCE.fr.txt +280 -0
- package/LICENSE.txt +262 -0
- package/README.md +1260 -2
- package/dist/admin/index.cjs +2895 -0
- package/dist/admin/index.cjs.map +1 -0
- package/dist/admin/index.d.cts +889 -0
- package/dist/admin/index.d.ts +889 -0
- package/dist/admin/index.js +204 -0
- package/dist/admin/index.js.map +1 -0
- package/dist/browser.cjs +5993 -0
- package/dist/browser.cjs.map +1 -0
- package/dist/browser.d.cts +70 -0
- package/dist/browser.d.ts +70 -0
- package/dist/browser.js +22 -0
- package/dist/browser.js.map +1 -0
- package/dist/chunk-CeEX7ayk.d.cts +75531 -0
- package/dist/chunk-CeEX7ayk.d.ts +75531 -0
- package/dist/chunk-Cg7Dtcb4.js +2987 -0
- package/dist/chunk-Cg7Dtcb4.js.map +1 -0
- package/dist/chunk-DJqUsgsy.d.ts +1463 -0
- package/dist/chunk-DNc8T5K1.js +241 -0
- package/dist/chunk-DNc8T5K1.js.map +1 -0
- package/dist/chunk-DTxzw3hu.d.cts +1463 -0
- package/dist/chunk-DmxQID5X.js +2289 -0
- package/dist/chunk-DmxQID5X.js.map +1 -0
- package/dist/chunk-DoZt_oIV.d.ts +3991 -0
- package/dist/chunk-DpJrqANO.js +11 -0
- package/dist/chunk-Dx8mPAdC.d.cts +3991 -0
- package/dist/chunk-X2ukY3ho.js +419 -0
- package/dist/chunk-X2ukY3ho.js.map +1 -0
- package/dist/events/index.cjs +1436 -0
- package/dist/events/index.cjs.map +1 -0
- package/dist/events/index.d.cts +772 -0
- package/dist/events/index.d.ts +772 -0
- package/dist/events/index.js +543 -0
- package/dist/events/index.js.map +1 -0
- package/dist/index.cjs +5992 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +44 -0
- package/dist/index.d.ts +44 -0
- package/dist/index.js +21 -0
- package/dist/index.js.map +1 -0
- package/package.json +126 -4
- package/src/admin/index.ts +47 -0
- package/src/admin/rules/mountayaAdmin.ts +102 -0
- package/src/browser.ts +233 -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 +428 -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 +63 -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 +138 -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 +371 -0
- package/src/rest/schema.gen.ts +57027 -0
- package/src/tiles/operations.gen.ts +206 -0
- package/src/tiles/schema.gen.ts +8406 -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,386 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Retry policy.
|
|
3
|
+
*
|
|
4
|
+
* Three things about the API shape this module, and each is easy to get wrong from the outside.
|
|
5
|
+
*
|
|
6
|
+
* **A limit is reported, never counted against.** Every 429 of every surface names its wait in
|
|
7
|
+
* `Retry-After`, but a ceiling's: the seconds left in a per-minute window, from 1 to 60, which the
|
|
8
|
+
* default budget waits out; or, for a daily bound such as the organizations one user creates or
|
|
9
|
+
* the invitations one organization sends, the seconds until the next day begins in UTC, up to
|
|
10
|
+
* 86400; or, for a spent monthly allowance, the seconds until the organization's next billing
|
|
11
|
+
* period begins. No budget a client would set waits for a spent daily bound or monthly allowance,
|
|
12
|
+
* so that error arrives at once and carries the wait. A ceiling (the seats, the published
|
|
13
|
+
* itineraries or zones, the invitations waiting, the itineraries of a personal space) is the one
|
|
14
|
+
* 429 whose entry is coded `LIMIT_REACHED`: it names no wait, since no wait lifts it, and it is
|
|
15
|
+
* never repeated, whatever the operation declares. The figures an organization is held to are its
|
|
16
|
+
* agreement's, which may raise, lower or remove them, so the client never tries to predict a 429,
|
|
17
|
+
* only to recover from one.
|
|
18
|
+
*
|
|
19
|
+
* **Every write carries a key, and the key is what makes a repeat safe.** A dropped socket does
|
|
20
|
+
* not say whether a write landed. The API answers a repeated `Idempotency-Key` with the answer it
|
|
21
|
+
* stored rather than running the write again, so a write that carried one is repeated after a
|
|
22
|
+
* 502, a 503, a 504 or no answer at all, as an operation declaring itself idempotent is, and a 409
|
|
23
|
+
* saying the key is still in use is asked again until the first attempt has finished, for as long
|
|
24
|
+
* as the call's wait budget lasts: that repeat asks whether the first attempt is done, so it is
|
|
25
|
+
* not counted against the attempts a failure may spend. A 412 is never repeated: the tag the write
|
|
26
|
+
* named is stale, and what the write should be now is its caller's to decide.
|
|
27
|
+
*
|
|
28
|
+
* **Idempotence is not readable from the HTTP method.** The Data API is GraphQL over POST, and
|
|
29
|
+
* every one of its operations is a query. A policy that refused to retry POSTs would give the
|
|
30
|
+
* surface with the tightest limit no retries at all, which is exactly backwards. So idempotence
|
|
31
|
+
* is declared by the operation, not inferred.
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
import { CEILING_CODE, KEY_IN_USE_CODE, refuseOption } from "./errors.js";
|
|
35
|
+
|
|
36
|
+
/** The public surfaces: the Data API, the Map Studio REST API and the Tile API. */
|
|
37
|
+
export type Surface = "rest" | "tiles" | "data";
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* MAX_TIMER_DELAY_MS is the longest delay, in milliseconds, a timer honours: 2^31 - 1.
|
|
41
|
+
*
|
|
42
|
+
* Past it Node and the browsers fire the timer at once, so a delay or a timeout above it is not
|
|
43
|
+
* a long wait but no wait at all. Every option that becomes a timer is held to it, and
|
|
44
|
+
* {@link sleep} clamps to it.
|
|
45
|
+
*/
|
|
46
|
+
export const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* RetryOptions configures the backoff. Defaults are deliberately modest: a client that retries
|
|
50
|
+
* hard against a per-minute limit converts one slow minute into a longer one.
|
|
51
|
+
*
|
|
52
|
+
* Each member is checked where it is given, at construction for a client's policy and before
|
|
53
|
+
* the first attempt for a call's, and a value outside its range throws a
|
|
54
|
+
* `MountayaConfigurationError` naming the member and the value. `undefined` is an omitted
|
|
55
|
+
* member, never a value.
|
|
56
|
+
*/
|
|
57
|
+
export interface RetryOptions {
|
|
58
|
+
/**
|
|
59
|
+
* Attempts after the first, as a whole number of 0 or more. `0` disables retrying.
|
|
60
|
+
*
|
|
61
|
+
* A repeat of a write whose `Idempotency-Key` is still in use (a 409 coded
|
|
62
|
+
* `IDEMPOTENCY_KEY_IN_USE`) is not counted here: it asks again whether the first request with
|
|
63
|
+
* the key has finished, and {@link RetryOptions.maxWaitMs} alone bounds it.
|
|
64
|
+
*
|
|
65
|
+
* @default 2
|
|
66
|
+
*/
|
|
67
|
+
readonly maxRetries?: number | undefined;
|
|
68
|
+
/**
|
|
69
|
+
* Base delay in milliseconds for the exponential schedule, from 0 to 2,147,483,647.
|
|
70
|
+
*
|
|
71
|
+
* @default 500
|
|
72
|
+
*/
|
|
73
|
+
readonly baseDelayMs?: number | undefined;
|
|
74
|
+
/**
|
|
75
|
+
* Ceiling in milliseconds for one delay the schedule draws, from 0 to 2,147,483,647.
|
|
76
|
+
*
|
|
77
|
+
* A `Retry-After` the response carries is not held to it: that wait is the server's to name,
|
|
78
|
+
* and is held to {@link RetryOptions.maxWaitMs} instead.
|
|
79
|
+
*
|
|
80
|
+
* @default 30000
|
|
81
|
+
*/
|
|
82
|
+
readonly maxDelayMs?: number | undefined;
|
|
83
|
+
/**
|
|
84
|
+
* The most one call waits between its attempts, all its waits together, in milliseconds from
|
|
85
|
+
* 0 to 2,147,483,647.
|
|
86
|
+
*
|
|
87
|
+
* A wait is taken only where it fits what the waits before it left. One that does not fit is
|
|
88
|
+
* not taken: the attempt settles with the error its status maps to, which on a 429 carries the
|
|
89
|
+
* seconds the answer named for the caller to schedule from. A spent daily bound or monthly
|
|
90
|
+
* allowance names a wait past any budget a client would set, so it settles at once. It is the
|
|
91
|
+
* one bound on the repeats of a write whose `Idempotency-Key` is still in use, each of which
|
|
92
|
+
* waits at least a second, so a call that leaves it at `0` repeats none of them.
|
|
93
|
+
*
|
|
94
|
+
* @default 60000
|
|
95
|
+
*/
|
|
96
|
+
readonly maxWaitMs?: number | undefined;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The policy a client takes where it names none, and what each member it omits keeps. */
|
|
100
|
+
export const defaultRetry: Required<RetryOptions> = {
|
|
101
|
+
baseDelayMs: 500,
|
|
102
|
+
maxDelayMs: 30_000,
|
|
103
|
+
maxRetries: 2,
|
|
104
|
+
maxWaitMs: 60_000,
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* retryMember reads one member of an override, refusing a value outside its range.
|
|
109
|
+
*
|
|
110
|
+
* Returns undefined for an omitted member, which {@link resolveRetry} then takes from `policy`,
|
|
111
|
+
* the policy the override is laid over and the value a refusal says an omission keeps.
|
|
112
|
+
*/
|
|
113
|
+
const retryMember = (
|
|
114
|
+
override: RetryOptions,
|
|
115
|
+
policy: Required<RetryOptions>,
|
|
116
|
+
member: keyof RetryOptions,
|
|
117
|
+
context: string | undefined,
|
|
118
|
+
): number | undefined => {
|
|
119
|
+
const value: unknown = override[member];
|
|
120
|
+
if (value === undefined) {
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (member === "maxRetries") {
|
|
125
|
+
// A count, not a timer, so it has no ceiling: a caller retrying for as long as the API
|
|
126
|
+
// answers 429 names a large count rather than an infinite one.
|
|
127
|
+
if (typeof value === "number" && Number.isInteger(value) && value >= 0) {
|
|
128
|
+
return value;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
throw refuseOption(
|
|
132
|
+
`retry.${member}`,
|
|
133
|
+
value,
|
|
134
|
+
`pass a whole number of 0 or more, or leave it out to keep ${policy.maxRetries}.`,
|
|
135
|
+
context,
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
if (typeof value === "number" && value >= 0 && value <= MAX_TIMER_DELAY_MS) {
|
|
140
|
+
return value;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
throw refuseOption(
|
|
144
|
+
`retry.${member}`,
|
|
145
|
+
value,
|
|
146
|
+
`pass a number of milliseconds from 0 to ${MAX_TIMER_DELAY_MS}, or leave it out to keep ${policy[member]}.`,
|
|
147
|
+
context,
|
|
148
|
+
);
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* resolveRetry lays an override over a policy, member by member, refusing a member that cannot
|
|
153
|
+
* work.
|
|
154
|
+
*
|
|
155
|
+
* The policy is configurable per client and per call, so a call's `retry` is laid over its
|
|
156
|
+
* client's, and a client's over the defaults. Member by member, because an override naming only
|
|
157
|
+
* `maxRetries` means "these delays, fewer attempts" rather than "no delays at all". And read
|
|
158
|
+
* member by member rather than spread, because a spread copies a member the caller wrote as
|
|
159
|
+
* `undefined` (which `RetryOptions` permits) over the value it was meant to leave alone, and
|
|
160
|
+
* a `maxRetries` of `undefined` compares false against every attempt number, so the loop would
|
|
161
|
+
* go on repeating a 429 without end.
|
|
162
|
+
*
|
|
163
|
+
* Checked here because every policy passes through here before it is read: a client's at
|
|
164
|
+
* construction, and a call's before its first attempt. A `NaN` or infinite `maxRetries` never
|
|
165
|
+
* reaches the ceiling, and a delay out of the timer's range fires at once, so each is refused
|
|
166
|
+
* where it is given rather than discovered by a call that did nothing wrong.
|
|
167
|
+
*
|
|
168
|
+
* @param context - the call a per-call override was passed to, named in a refusal.
|
|
169
|
+
* @throws `MountayaConfigurationError` for a member outside its range, or an override that is
|
|
170
|
+
* not an object.
|
|
171
|
+
*/
|
|
172
|
+
export const resolveRetry = (
|
|
173
|
+
policy: Required<RetryOptions>,
|
|
174
|
+
override: RetryOptions | undefined,
|
|
175
|
+
context?: string,
|
|
176
|
+
): Required<RetryOptions> => {
|
|
177
|
+
if (override === undefined) {
|
|
178
|
+
return policy;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (typeof override !== "object" || override === null) {
|
|
182
|
+
throw refuseOption(
|
|
183
|
+
"retry",
|
|
184
|
+
override,
|
|
185
|
+
"pass an object such as { maxRetries: 0 }, or leave it out to keep the policy as it is.",
|
|
186
|
+
context,
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
return {
|
|
191
|
+
baseDelayMs: retryMember(override, policy, "baseDelayMs", context) ?? policy.baseDelayMs,
|
|
192
|
+
maxDelayMs: retryMember(override, policy, "maxDelayMs", context) ?? policy.maxDelayMs,
|
|
193
|
+
maxRetries: retryMember(override, policy, "maxRetries", context) ?? policy.maxRetries,
|
|
194
|
+
maxWaitMs: retryMember(override, policy, "maxWaitMs", context) ?? policy.maxWaitMs,
|
|
195
|
+
};
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* transientStatuses are the statuses that say the API or a proxy failed in a way that is routinely
|
|
200
|
+
* transient: 502, 503 and 504. Every other 4xx and 5xx is a statement about the request itself or
|
|
201
|
+
* one no repeat changes, and repeating it unchanged produces the identical answer while spending
|
|
202
|
+
* a limit to do so.
|
|
203
|
+
*/
|
|
204
|
+
const transientStatuses = new Set([502, 503, 504]);
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* KEY_IN_USE_MIN_WAIT_MS is the least a repeat of a write whose key is still in use waits, in
|
|
208
|
+
* milliseconds: the second the API names on every such answer. That repeat counts against no
|
|
209
|
+
* ceiling of attempts and is bounded by the call's wait budget alone, which a wait of nothing
|
|
210
|
+
* would never spend.
|
|
211
|
+
*/
|
|
212
|
+
export const KEY_IN_USE_MIN_WAIT_MS = 1000;
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* isKeyInUse reports whether an answer is the 409 whose `Idempotency-Key` is still in use, for a
|
|
216
|
+
* request that carried one: the first request with the key has not finished.
|
|
217
|
+
*/
|
|
218
|
+
export const isKeyInUse = (args: {
|
|
219
|
+
/** Whether the request carried an `Idempotency-Key`. */
|
|
220
|
+
readonly keyed?: boolean | undefined;
|
|
221
|
+
readonly status?: number | undefined;
|
|
222
|
+
/** The classifying code of the answer's first entry. */
|
|
223
|
+
readonly code?: string | undefined;
|
|
224
|
+
}): boolean => args.keyed === true && args.status === 409 && args.code === KEY_IN_USE_CODE;
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* shouldRetry decides whether an attempt may be repeated.
|
|
228
|
+
*
|
|
229
|
+
* - A 429 is repeated whatever the operation declares: the API has said it did nothing. A 429
|
|
230
|
+
* coded `LIMIT_REACHED` is the exception, never repeated: it refuses a ceiling, which lifts when
|
|
231
|
+
* something is freed or the agreement changes and never by waiting.
|
|
232
|
+
* - A 502, a 503, a 504 and a request that never arrived are repeated where the operation
|
|
233
|
+
* declares itself idempotent or the request carried a key, which the API answers by replaying
|
|
234
|
+
* the answer it stored rather than running the write twice.
|
|
235
|
+
* - A 409 coded `IDEMPOTENCY_KEY_IN_USE` is repeated where the request carried a key: the repeat
|
|
236
|
+
* carries the same key and is answered with whatever the first attempt is answered with. It is
|
|
237
|
+
* not one of the `retries` `maxRetries` bounds: the call's wait budget alone bounds it.
|
|
238
|
+
* - Nothing else is repeated, a 412 least of all, and nothing past `maxRetries`.
|
|
239
|
+
*
|
|
240
|
+
* Whether the wait a repeat needs fits the call's budget is the loop's question, not this one's.
|
|
241
|
+
*/
|
|
242
|
+
export const shouldRetry = (args: {
|
|
243
|
+
/** The repeats the call has made that count against `maxRetries`: all but a key in use. */
|
|
244
|
+
readonly retries: number;
|
|
245
|
+
readonly maxRetries: number;
|
|
246
|
+
readonly idempotent: boolean;
|
|
247
|
+
/** Whether the request carried an `Idempotency-Key`. */
|
|
248
|
+
readonly keyed?: boolean | undefined;
|
|
249
|
+
readonly status?: number | undefined;
|
|
250
|
+
/** The classifying code of the answer's first entry, read for a 409 and a 429 alone. */
|
|
251
|
+
readonly code?: string | undefined;
|
|
252
|
+
}): boolean => {
|
|
253
|
+
if (args.status === 409) {
|
|
254
|
+
return isKeyInUse(args);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
if (args.status === 429 && args.code === CEILING_CODE) {
|
|
258
|
+
return false;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
if (args.retries >= args.maxRetries) {
|
|
262
|
+
return false;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
const safe = args.idempotent || args.keyed === true;
|
|
266
|
+
|
|
267
|
+
if (args.status === undefined) {
|
|
268
|
+
return safe;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
if (args.status === 429) {
|
|
272
|
+
return true;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
return safe && transientStatuses.has(args.status);
|
|
276
|
+
};
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* RETRY_AFTER_JITTER_MS is the most a wait `Retry-After` names is drawn longer by, in
|
|
280
|
+
* milliseconds: the clients one second refused do not all come back in the same millisecond.
|
|
281
|
+
*/
|
|
282
|
+
const RETRY_AFTER_JITTER_MS = 1000;
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* jitteredDelay draws the next delay from the exponential schedule, in milliseconds, kept as the
|
|
286
|
+
* draw computes it, a fraction of a millisecond included.
|
|
287
|
+
*
|
|
288
|
+
* The draw is uniform over `[0, exponential]`, which is **full jitter**, rather than the
|
|
289
|
+
* exponential itself. Fixed exponential backoff synchronises every client that failed at the
|
|
290
|
+
* same moment into retrying at the same moment; full jitter is what breaks that up, and it is a
|
|
291
|
+
* one-line difference for a large change in behaviour under load. A zero base stays zero at any
|
|
292
|
+
* attempt, where the product would read `0 * Infinity` once the exponential overflows.
|
|
293
|
+
*/
|
|
294
|
+
export const jitteredDelay = (args: {
|
|
295
|
+
readonly attempt: number;
|
|
296
|
+
readonly baseDelayMs: number;
|
|
297
|
+
readonly maxDelayMs: number;
|
|
298
|
+
/** Injected for tests; defaults to Math.random. */
|
|
299
|
+
readonly random?: (() => number) | undefined;
|
|
300
|
+
}): number => {
|
|
301
|
+
const exponential =
|
|
302
|
+
args.baseDelayMs === 0 ? 0 : Math.min(args.maxDelayMs, args.baseDelayMs * 2 ** args.attempt);
|
|
303
|
+
|
|
304
|
+
return (args.random ?? Math.random)() * exponential;
|
|
305
|
+
};
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* backoffDelay returns how long to wait before the next attempt, in milliseconds, the draw kept
|
|
309
|
+
* as computed: no wait is rounded to whole milliseconds.
|
|
310
|
+
*
|
|
311
|
+
* `Retry-After` wins outright when the response carries one: the server is the only party that
|
|
312
|
+
* knows when the window actually resets, and a client that backs off for less is simply
|
|
313
|
+
* generating another 429. The wait is the seconds it names plus a uniform draw from zero to
|
|
314
|
+
* {@link RETRY_AFTER_JITTER_MS}. Otherwise the delay is the schedule's draw, from
|
|
315
|
+
* {@link jitteredDelay}. One draw is made per wait either way.
|
|
316
|
+
*
|
|
317
|
+
* Whether the wait fits what the call's budget has left is the caller's to judge.
|
|
318
|
+
*/
|
|
319
|
+
export const backoffDelay = (args: {
|
|
320
|
+
readonly attempt: number;
|
|
321
|
+
readonly retryAfterSeconds?: number | undefined;
|
|
322
|
+
readonly baseDelayMs: number;
|
|
323
|
+
readonly maxDelayMs: number;
|
|
324
|
+
/** Injected for tests; defaults to Math.random. */
|
|
325
|
+
readonly random?: (() => number) | undefined;
|
|
326
|
+
}): number => {
|
|
327
|
+
if (args.retryAfterSeconds !== undefined) {
|
|
328
|
+
return args.retryAfterSeconds * 1000 + (args.random ?? Math.random)() * RETRY_AFTER_JITTER_MS;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
return jitteredDelay(args);
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* namedError builds the error a runtime's own abort machinery would: a `DOMException` carrying
|
|
336
|
+
* `name`, or, where the runtime has no `DOMException`, an `Error` carrying it.
|
|
337
|
+
*/
|
|
338
|
+
export const namedError = (name: "AbortError" | "TimeoutError", message: string): Error =>
|
|
339
|
+
typeof DOMException === "function"
|
|
340
|
+
? new DOMException(message, name)
|
|
341
|
+
: Object.assign(new Error(message), { name });
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* abortReasonOf is what a caller's abort settles a call with: the signal's own reason, or, on a
|
|
345
|
+
* runtime whose signals carry none (the polyfill React Native shipped before 0.87), the
|
|
346
|
+
* `AbortError` fetch itself rejects with there.
|
|
347
|
+
*
|
|
348
|
+
* Every place a call can be waiting when its caller aborts (the request, a backoff, a body) settles
|
|
349
|
+
* with this, so the value an aborted call rejects with does not depend on where it was.
|
|
350
|
+
*/
|
|
351
|
+
export const abortReasonOf = (signal: AbortSignal): unknown =>
|
|
352
|
+
signal.reason ?? namedError("AbortError", "This operation was aborted");
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* sleep resolves after `ms`, rejecting early if the signal aborts.
|
|
356
|
+
*
|
|
357
|
+
* A backoff that ignored the signal would keep a caller's abort waiting out the full
|
|
358
|
+
* delay, which is the one moment a caller is most likely to be watching. The rejection is
|
|
359
|
+
* {@link abortReasonOf} the signal. The timer is handed at most {@link MAX_TIMER_DELAY_MS}, since
|
|
360
|
+
* past it a timer fires at once.
|
|
361
|
+
*/
|
|
362
|
+
export const sleep = (ms: number, signal?: AbortSignal): Promise<void> =>
|
|
363
|
+
new Promise((resolve, reject) => {
|
|
364
|
+
if (signal?.aborted === true) {
|
|
365
|
+
reject(abortReasonOf(signal));
|
|
366
|
+
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
const timer = setTimeout(
|
|
371
|
+
() => {
|
|
372
|
+
signal?.removeEventListener("abort", onAbort);
|
|
373
|
+
resolve();
|
|
374
|
+
},
|
|
375
|
+
Math.min(ms, MAX_TIMER_DELAY_MS),
|
|
376
|
+
);
|
|
377
|
+
|
|
378
|
+
const onAbort = () => {
|
|
379
|
+
clearTimeout(timer);
|
|
380
|
+
if (signal !== undefined) {
|
|
381
|
+
reject(abortReasonOf(signal));
|
|
382
|
+
}
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
386
|
+
});
|