@sparkvault/sdk-js 11.0.1 → 11.0.2
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/dist/api-base.d.ts +14 -5
- package/dist/errors.d.ts +32 -16
- package/dist/http.d.ts +8 -0
- package/dist/index.cjs +1509 -352
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +87 -27
- package/dist/index.mjs +1509 -352
- package/dist/index.mjs.map +1 -1
- package/dist/ingots/fetch-download.d.ts +40 -10
- package/dist/ingots/index.d.ts +30 -10
- package/dist/products/identity/api.d.ts +2 -2
- package/dist/sparkvault.js +1 -1
- package/dist/sparkvault.js.map +1 -1
- package/dist/vaults/upload/api.d.ts +107 -23
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,33 +1,667 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether sending the SAME request again can succeed, read from its HTTP
|
|
3
|
+
* status: the one retry rule every client and every provider adapter applies.
|
|
4
|
+
*
|
|
5
|
+
* A retry rule restated beside every client drifts, and the copy that drifted
|
|
6
|
+
* decides whether a deliverable message is retried or abandoned, or whether a
|
|
7
|
+
* download is tried again. Each caller keeps its provider's own extras on top of
|
|
8
|
+
* this rule (a success body, a dead-token reason, a vendor error name).
|
|
9
|
+
*
|
|
10
|
+
* Browser-safe and import-free: sdk-js bundles it and sdk-mobile mirrors it.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Is this HTTP status one a retry of the same request can turn into a success?
|
|
15
|
+
*
|
|
16
|
+
* RFC 9110: 408 means the server never received the whole request, 429 that it
|
|
17
|
+
* throttled it, and a 5xx that it failed; every other status is the server's
|
|
18
|
+
* verdict on this exact request. A caller that got no response at all (a network
|
|
19
|
+
* error, a timeout) has no status to pass and decides that case itself.
|
|
20
|
+
*
|
|
21
|
+
* @param {number} status
|
|
22
|
+
* @returns {boolean}
|
|
23
|
+
*/
|
|
24
|
+
function isTransientHttpStatus(status) {
|
|
25
|
+
return status === 408 || status === 429 || status >= 500;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The upload publication contract between Forge and Core's activation.
|
|
30
|
+
*
|
|
31
|
+
* Forge stamps UPLOAD_PUBLICATION_PROTOCOL on every upload session it creates
|
|
32
|
+
* and on the final state it hands Core's activation (POST
|
|
33
|
+
* /v1/vaults/:vault_id/ingots/:ingot_id/activate); activation refuses any
|
|
34
|
+
* other version. The two services deploy separately, so a change to what
|
|
35
|
+
* either side sends or expects moves this number: a session or a finalize
|
|
36
|
+
* from the other side's contract then fails closed ("restart the upload")
|
|
37
|
+
* instead of publishing under a contract the other side does not hold.
|
|
38
|
+
*
|
|
39
|
+
* Version 2: an upload's own metadata (content type, original file name,
|
|
40
|
+
* uploader, content HMAC) travels on its upload token and its session, and
|
|
41
|
+
* activation publishes it from the session; the final state Forge sends
|
|
42
|
+
* carries only the storage facts Forge owns.
|
|
43
|
+
*
|
|
44
|
+
* Isomorphic: no Node imports.
|
|
45
|
+
*/
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The codes Core's activation refuses an upload with, which Forge's refusal
|
|
50
|
+
* map reads (the status is Core's):
|
|
51
|
+
* - UPLOAD_CONTRACT_MISMATCH (409): a finalize or session from another
|
|
52
|
+
* publication contract than Core's, a mixed deployment that converges — the
|
|
53
|
+
* upload is kept and its finalize tried again.
|
|
54
|
+
* - UPLOAD_PROTOCOL_RETIRED (410): a session from a contract Core no longer
|
|
55
|
+
* publishes, which never can be.
|
|
56
|
+
* - UPLOAD_SUPERSEDED (410): a session a later staging of its ingot
|
|
57
|
+
* superseded, which never can be.
|
|
58
|
+
* - UPLOAD_POOL_FULL (402): an upload the owner's storage pool cannot take at
|
|
59
|
+
* publication, which is final.
|
|
60
|
+
*/
|
|
61
|
+
const UPLOAD_REFUSAL_CODES = Object.freeze({
|
|
62
|
+
UPLOAD_CONTRACT_MISMATCH: 'UPLOAD_CONTRACT_MISMATCH',
|
|
63
|
+
UPLOAD_PROTOCOL_RETIRED: 'UPLOAD_PROTOCOL_RETIRED',
|
|
64
|
+
UPLOAD_SUPERSEDED: 'UPLOAD_SUPERSEDED',
|
|
65
|
+
UPLOAD_POOL_FULL: 'UPLOAD_POOL_FULL'
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The refusals of Core's that a new upload of the same file cannot remedy:
|
|
70
|
+
* the owner's storage pool cannot take it (UPLOAD_POOL_FULL), or a later
|
|
71
|
+
* upload of its ingot replaced it (UPLOAD_SUPERSEDED). Any other code Core
|
|
72
|
+
* ends an upload with ends its session alone, which a new upload starts
|
|
73
|
+
* over. Every client reads a terminal answer's code by it
|
|
74
|
+
* (transfer-retry.js): one of these is a refusal it reports in Core's words,
|
|
75
|
+
* any other a gone session.
|
|
76
|
+
*/
|
|
77
|
+
const UPLOAD_FINAL_REFUSAL_CODES = Object.freeze([
|
|
78
|
+
UPLOAD_REFUSAL_CODES.UPLOAD_POOL_FULL,
|
|
79
|
+
UPLOAD_REFUSAL_CODES.UPLOAD_SUPERSEDED
|
|
80
|
+
]);
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The response header that names the code Core refused an upload with for
|
|
84
|
+
* good: Forge sends it on every terminal answer to a tus request, a HEAD's
|
|
85
|
+
* (which has no body) included, so a client tells an upload the owner's pool
|
|
86
|
+
* cannot take from one a later upload superseded without reading a body.
|
|
87
|
+
*/
|
|
88
|
+
const UPLOAD_REFUSAL_HEADER = 'X-Upload-Refusal';
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The transfer retry policy: what every first-party client does with the
|
|
92
|
+
* answer to a Forge transfer request (a tus chunk PATCH, an offset HEAD, the
|
|
93
|
+
* receipt PATCH at the final offset), in one place, so the Node uploader
|
|
94
|
+
* (forge-tus), the browser SDK (sdk-js bundles this module) and the mobile SDK
|
|
95
|
+
* (sdk-mobile carries a generated copy) read every answer the same way.
|
|
96
|
+
*
|
|
97
|
+
* It encodes what Google Drive, Google Cloud Storage, OneDrive, Dropbox and
|
|
98
|
+
* AWS document for resumable transfers:
|
|
99
|
+
* - only a request that got no answer, 408, 425, 429 or a 5xx is retried;
|
|
100
|
+
* every other 4xx is the server's verdict on the request;
|
|
101
|
+
* - `Retry-After` is a floor, never a ceiling;
|
|
102
|
+
* - retries back off exponentially, capped, with jitter;
|
|
103
|
+
* - before a chunk is sent again the server is asked for the offset it
|
|
104
|
+
* committed, because a request whose answer was lost may have landed;
|
|
105
|
+
* - a session that is gone (404, 410) is never resumed: only a new upload
|
|
106
|
+
* from byte 0 can succeed;
|
|
107
|
+
* - a transfer's retries are bounded in time and in failures in a row, and
|
|
108
|
+
* both bounds start over whenever the server confirms progress.
|
|
109
|
+
*
|
|
110
|
+
* Forge's own answers beyond the general rule:
|
|
111
|
+
* - the 409, in two kinds: one carrying `Upload-Offset` names where the
|
|
112
|
+
* session stands (continue from there), and one without it means another
|
|
113
|
+
* request holds the session's write lease, a chunk or the finalization
|
|
114
|
+
* (retry after its `Retry-After`);
|
|
115
|
+
* - a terminal answer (a 404, 410 or 412) names the code Core ended the
|
|
116
|
+
* upload with: its error envelope in `error.details.coreCode` for the
|
|
117
|
+
* refusals it words itself, and every one of them in `X-Upload-Refusal`,
|
|
118
|
+
* which is all a HEAD's answer, having no body, can carry; the body's code
|
|
119
|
+
* wins when both name one. The code decides the verdict: a full storage
|
|
120
|
+
* pool or a later upload that replaced this one is a refusal no new upload
|
|
121
|
+
* of the same file remedies, and any other code (the file the upload was
|
|
122
|
+
* for gone, a retired contract, a replacement base that moved on, a code
|
|
123
|
+
* this policy does not know) ends the session, which a new upload can
|
|
124
|
+
* start over;
|
|
125
|
+
* - a 503 carrying `Retry-After` to the receipt (the PATCH at the final
|
|
126
|
+
* offset) is a deferral: Forge holds every byte and is still publishing,
|
|
127
|
+
* and finishes without the client, so it is asked again, each time after a
|
|
128
|
+
* longer backoff, for as long as the idle limit allows, and never counts as
|
|
129
|
+
* a failure. Forge's deferral always names when to ask again; a 503 that
|
|
130
|
+
* does not is an ordinary failure.
|
|
131
|
+
*
|
|
132
|
+
* Isomorphic: no Node imports, no host APIs, no randomness. The jitter only
|
|
133
|
+
* has to spread retries, so it hashes the transfer and the attempt
|
|
134
|
+
* (docs/CONVENTIONS.md → Randomness).
|
|
135
|
+
*/
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
/** What a client does after a transfer request, read from its answer. */
|
|
139
|
+
const TRANSFER_VERDICT = Object.freeze({
|
|
140
|
+
/** 2xx: the request did what it asked. */
|
|
141
|
+
OK: 'ok',
|
|
142
|
+
/**
|
|
143
|
+
* No answer (a reset, a timeout), 408, 425, 429, a 5xx, or a 409 without
|
|
144
|
+
* `Upload-Offset` (another request holds the session's lease): back off,
|
|
145
|
+
* never sooner than `Retry-After`, then ask the server's offset before
|
|
146
|
+
* sending a chunk again.
|
|
147
|
+
*/
|
|
148
|
+
RETRY: 'retry',
|
|
149
|
+
/** 409 with `Upload-Offset`: the session stands elsewhere; continue from that offset at once. */
|
|
150
|
+
RESYNC: 'resync',
|
|
151
|
+
/**
|
|
152
|
+
* 503 with `Retry-After` to the receipt: every byte is received and the
|
|
153
|
+
* publication is still running. Ask again after a backoff that grows with
|
|
154
|
+
* each deferral, never sooner than `Retry-After`; only the idle limit ends
|
|
155
|
+
* the asking, never the failures in a row.
|
|
156
|
+
*/
|
|
157
|
+
DEFERRED: 'deferred',
|
|
158
|
+
/**
|
|
159
|
+
* 404 or 410 naming no code, or a 404, 410 or 412 naming a code of Core's
|
|
160
|
+
* that is not a final refusal (`coreCode` carries it): the session no
|
|
161
|
+
* longer exists; only a new upload from byte 0 can succeed.
|
|
162
|
+
*/
|
|
163
|
+
GONE: 'gone',
|
|
164
|
+
/**
|
|
165
|
+
* Any other status, or a 404, 410 or 412 naming a final refusal of Core's
|
|
166
|
+
* (`coreCode`: UPLOAD_POOL_FULL, UPLOAD_SUPERSEDED): the server's verdict on
|
|
167
|
+
* this request, which repeating it, or a new upload of the same file,
|
|
168
|
+
* earns again.
|
|
169
|
+
*/
|
|
170
|
+
REFUSED: 'refused'
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
/** The failures a transfer recovers from by trying again: the verdicts a budget's `failed` records. */
|
|
174
|
+
const RETRYABLE_VERDICTS = new Set([TRANSFER_VERDICT.RETRY, TRANSFER_VERDICT.RESYNC]);
|
|
175
|
+
|
|
176
|
+
/** RFC 8470: the server refused a request sent in TLS early data; the same request succeeds once the handshake completes. */
|
|
177
|
+
const TOO_EARLY = 425;
|
|
178
|
+
|
|
179
|
+
/** Forge's answer to a receipt whose publication it deferred. */
|
|
180
|
+
const SERVICE_UNAVAILABLE = 503;
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* The statuses a terminal answer naming Core's code arrives with: Forge's 410
|
|
184
|
+
* (UPLOAD_GONE, or Core's own relayed), a relayed 404, and Core's own 412.
|
|
185
|
+
*/
|
|
186
|
+
const TERMINAL_STATUSES = new Set([404, 410, 412]);
|
|
187
|
+
|
|
188
|
+
/** Core's error codes are upper-case words joined by underscores; anything else names no code. */
|
|
189
|
+
const CORE_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
const UPLOAD_OFFSET_HEADER = 'Upload-Offset';
|
|
193
|
+
const RETRY_AFTER_HEADER = 'Retry-After';
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* How long a client waits for the answer to an offset HEAD or a receipt
|
|
197
|
+
* PATCH, whatever its other requests get: on a received upload, Forge answers
|
|
198
|
+
* either only after its own call to Core (up to 30 s) has published the
|
|
199
|
+
* upload or deferred it, so each gets twice that.
|
|
200
|
+
*/
|
|
201
|
+
const HEAD_AND_RECEIPT_TIMEOUT_MS = 60_000;
|
|
202
|
+
|
|
203
|
+
/** How a retry's delay spreads past its backoff: up to this much more. */
|
|
204
|
+
const JITTER_SPAN_MS = 1000;
|
|
205
|
+
|
|
206
|
+
/** How long a transfer may sit without progress or a sign of life by default. */
|
|
207
|
+
const DEFAULT_IDLE_LIMIT_MS = 10 * 60 * 1000;
|
|
208
|
+
|
|
209
|
+
/** How many failures in a row, without progress between them, end a transfer by default. */
|
|
210
|
+
const DEFAULT_MAX_CONSECUTIVE_FAILURES = 8;
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* @typedef {'ok'|'retry'|'resync'|'deferred'|'gone'|'refused'} TransferVerdict
|
|
214
|
+
*/
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* The verdicts a transfer recovers from by trying again that count as
|
|
218
|
+
* failures: the ones a budget's `failed` records.
|
|
219
|
+
* @typedef {'retry'|'resync'} RetryableTransferVerdict
|
|
220
|
+
*/
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* @typedef {Object} TransferOutcome
|
|
224
|
+
* @property {TransferVerdict} verdict - What the client does next
|
|
225
|
+
* @property {number|null} retryAfterMs - The answer's `Retry-After`, in ms from
|
|
226
|
+
* the answer (an HTTP-date already past reads as 0); null when absent or unreadable
|
|
227
|
+
* @property {number|null} offset - The answer's `Upload-Offset`; null when absent or unreadable
|
|
228
|
+
* @property {string|null} coreCode - The code Core ended the upload with, as a
|
|
229
|
+
* terminal answer named it (a 404, 410 or 412: its body's details or, those
|
|
230
|
+
* naming none, its `X-Upload-Refusal`): REFUSED for a final refusal
|
|
231
|
+
* (`UPLOAD_POOL_FULL`, `UPLOAD_SUPERSEDED`), GONE for any other code
|
|
232
|
+
* (`NOT_FOUND`, `UPLOAD_PROTOCOL_RETIRED`, a 412's, one this policy does not
|
|
233
|
+
* know); null when the answer names none
|
|
234
|
+
*/
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Read the answer to a transfer request the way the policy does.
|
|
238
|
+
*
|
|
239
|
+
* @param {Object} response
|
|
240
|
+
* @param {number} response.status - The HTTP status; 0 when the request got no answer
|
|
241
|
+
* @param {((name: string) => string|null)|null} [response.headers] - Reads a
|
|
242
|
+
* response header by name: a fetch `Headers`' `get` or an XHR's
|
|
243
|
+
* `getResponseHeader`, bound to its owner (`(name) => xhr.getResponseHeader(name)`)
|
|
244
|
+
* @param {unknown} [response.details] - The `details` of the error envelope the
|
|
245
|
+
* answer's body carries (`{ error: { code, message, details } }`), as the
|
|
246
|
+
* runtime's one reader of a failed answer parsed it from the whole body;
|
|
247
|
+
* where Forge names the refusal Core decided (`coreCode`), ahead of the
|
|
248
|
+
* answer's `X-Upload-Refusal`. Anything that is not an object names none.
|
|
249
|
+
* @param {boolean} [response.receipt] - The request was the receipt: the PATCH
|
|
250
|
+
* at the final offset, whose 503 carrying `Retry-After` is a deferral
|
|
251
|
+
* @param {number} [response.now] - When the answer arrived (epoch ms), which an
|
|
252
|
+
* HTTP-date `Retry-After` counts from
|
|
253
|
+
* @returns {TransferOutcome}
|
|
254
|
+
* @throws {TypeError} When the status is not a whole number, headers is not a
|
|
255
|
+
* function, or receipt is not a boolean
|
|
256
|
+
*/
|
|
257
|
+
function classifyTransferResponse({ status, headers = null, details = null, receipt = false, now = Date.now() }) {
|
|
258
|
+
if (!Number.isSafeInteger(status) || status < 0) {
|
|
259
|
+
throw new TypeError(`A transfer answer's status is a whole number (0 for no answer), not ${status}`);
|
|
260
|
+
}
|
|
261
|
+
if (headers !== null && typeof headers !== 'function') {
|
|
262
|
+
throw new TypeError('A transfer answer\'s headers are read through a function from a header name to its value');
|
|
263
|
+
}
|
|
264
|
+
if (typeof receipt !== 'boolean') {
|
|
265
|
+
throw new TypeError(`Whether a transfer request was the receipt is a boolean, not ${receipt}`);
|
|
266
|
+
}
|
|
267
|
+
if (status === 0) {
|
|
268
|
+
return { verdict: TRANSFER_VERDICT.RETRY, retryAfterMs: null, offset: null, coreCode: null };
|
|
269
|
+
}
|
|
270
|
+
const header = (name) => (headers === null ? null : headers(name));
|
|
271
|
+
const offset = readCount(header(UPLOAD_OFFSET_HEADER));
|
|
272
|
+
const coreCode = TERMINAL_STATUSES.has(status)
|
|
273
|
+
? coreCodeIn(details) ?? coreCodeOf(header(UPLOAD_REFUSAL_HEADER))
|
|
274
|
+
: null;
|
|
275
|
+
const retryAfterMs = readRetryAfterMs(header(RETRY_AFTER_HEADER), now);
|
|
276
|
+
return {
|
|
277
|
+
verdict: verdictFor(status, { offset, coreCode, deferral: receipt && retryAfterMs !== null }),
|
|
278
|
+
retryAfterMs,
|
|
279
|
+
offset,
|
|
280
|
+
coreCode
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* The verdict on a status that came with an answer: `offset` its readable
|
|
286
|
+
* `Upload-Offset`, `coreCode` the code of Core's a terminal answer names,
|
|
287
|
+
* `deferral` whether it answered the receipt with a readable `Retry-After`.
|
|
288
|
+
*/
|
|
289
|
+
function verdictFor(status, { offset, coreCode, deferral }) {
|
|
290
|
+
if (status >= 200 && status < 300) return TRANSFER_VERDICT.OK;
|
|
291
|
+
if (status === 409) return offset === null ? TRANSFER_VERDICT.RETRY : TRANSFER_VERDICT.RESYNC;
|
|
292
|
+
if (coreCode !== null) return UPLOAD_FINAL_REFUSAL_CODES.includes(coreCode) ? TRANSFER_VERDICT.REFUSED : TRANSFER_VERDICT.GONE;
|
|
293
|
+
if (status === 404 || status === 410) return TRANSFER_VERDICT.GONE;
|
|
294
|
+
if (deferral && status === SERVICE_UNAVAILABLE) return TRANSFER_VERDICT.DEFERRED;
|
|
295
|
+
if (status === TOO_EARLY || isTransientHttpStatus(status)) return TRANSFER_VERDICT.RETRY;
|
|
296
|
+
return TRANSFER_VERDICT.REFUSED;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** The code an error envelope's details name (`coreCode`), or null. */
|
|
300
|
+
function coreCodeIn(details) {
|
|
301
|
+
return details && typeof details === 'object' ? coreCodeOf(details.coreCode) : null;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** A value that is one of Core's codes (surrounding whitespace allowed), or null. */
|
|
305
|
+
function coreCodeOf(value) {
|
|
306
|
+
if (typeof value !== 'string') return null;
|
|
307
|
+
const code = value.trim();
|
|
308
|
+
return CORE_CODE.test(code) ? code : null;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** A header's non-negative whole number (surrounding whitespace allowed), or null. */
|
|
312
|
+
function readCount(value) {
|
|
313
|
+
if (typeof value !== 'string') return null;
|
|
314
|
+
const text = value.trim();
|
|
315
|
+
if (!/^\d+$/.test(text)) return null;
|
|
316
|
+
const count = Number(text);
|
|
317
|
+
return Number.isSafeInteger(count) ? count : null;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** RFC 9110 §10.2.3: `Retry-After` is delay-seconds or an HTTP-date. */
|
|
321
|
+
function readRetryAfterMs(value, now) {
|
|
322
|
+
const seconds = readCount(value);
|
|
323
|
+
if (seconds !== null) {
|
|
324
|
+
const ms = seconds * 1000;
|
|
325
|
+
return Number.isSafeInteger(ms) ? ms : null;
|
|
326
|
+
}
|
|
327
|
+
const at = typeof value === 'string' ? parseHttpDate(value.trim(), now) : null;
|
|
328
|
+
return at === null ? null : Math.max(0, at - now);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
|
332
|
+
const DAY_NAME = '(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)';
|
|
333
|
+
const LONG_DAY_NAME = '(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)';
|
|
334
|
+
const MONTH = `(${MONTHS.join('|')})`;
|
|
335
|
+
const TIME_OF_DAY = '(\\d{2}):(\\d{2}):(\\d{2})';
|
|
336
|
+
|
|
337
|
+
/** IMF-fixdate, what every current server sends: `Sun, 06 Nov 1994 08:49:37 GMT`. */
|
|
338
|
+
const IMF_FIXDATE = new RegExp(`^${DAY_NAME}, (\\d{2}) ${MONTH} (\\d{4}) ${TIME_OF_DAY} GMT$`);
|
|
339
|
+
/** The obsolete RFC 850 form a recipient still accepts: `Sunday, 06-Nov-94 08:49:37 GMT`. */
|
|
340
|
+
const RFC850_DATE = new RegExp(`^${LONG_DAY_NAME}, (\\d{2})-${MONTH}-(\\d{2}) ${TIME_OF_DAY} GMT$`);
|
|
341
|
+
/** The obsolete asctime form a recipient still accepts: `Sun Nov 6 08:49:37 1994`. */
|
|
342
|
+
const ASCTIME_DATE = new RegExp(`^${DAY_NAME} ${MONTH} ( \\d|\\d{2}) ${TIME_OF_DAY} (\\d{4})$`);
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* An HTTP-date (RFC 9110 §5.6.7, all three forms a recipient must accept) as
|
|
346
|
+
* epoch ms, or null when it is not one or names no real moment.
|
|
347
|
+
*
|
|
348
|
+
* @param {string} text
|
|
349
|
+
* @param {number} now - epoch ms, which places an RFC 850 two-digit year
|
|
350
|
+
* @returns {number|null}
|
|
351
|
+
*/
|
|
352
|
+
function parseHttpDate(text, now) {
|
|
353
|
+
let match = IMF_FIXDATE.exec(text);
|
|
354
|
+
if (match) {
|
|
355
|
+
const [, day, month, year, hours, minutes, seconds] = match;
|
|
356
|
+
return utcMs(Number(year), month, Number(day), hours, minutes, seconds);
|
|
357
|
+
}
|
|
358
|
+
match = RFC850_DATE.exec(text);
|
|
359
|
+
if (match) {
|
|
360
|
+
const [, day, month, shortYear, hours, minutes, seconds] = match;
|
|
361
|
+
return utcMs(rfc850Year(Number(shortYear), now), month, Number(day), hours, minutes, seconds);
|
|
362
|
+
}
|
|
363
|
+
match = ASCTIME_DATE.exec(text);
|
|
364
|
+
if (match) {
|
|
365
|
+
const [, month, day, hours, minutes, seconds, year] = match;
|
|
366
|
+
return utcMs(Number(year), month, Number(day.trim()), hours, minutes, seconds);
|
|
367
|
+
}
|
|
368
|
+
return null;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** RFC 9110: a two-digit year more than 50 years ahead is the latest past year with those digits. */
|
|
372
|
+
function rfc850Year(shortYear, now) {
|
|
373
|
+
const currentYear = new Date(now).getUTCFullYear();
|
|
374
|
+
const year = currentYear - (currentYear % 100) + shortYear;
|
|
375
|
+
return year > currentYear + 50 ? year - 100 : year;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** The UTC instant of a calendar date and time of day, or null for a date or time that does not exist. */
|
|
379
|
+
function utcMs(year, monthName, day, hours, minutes, seconds) {
|
|
380
|
+
const monthIndex = MONTHS.indexOf(monthName);
|
|
381
|
+
const [h, m, s] = [Number(hours), Number(minutes), Number(seconds)];
|
|
382
|
+
// A leap second (60) is a real time of day; the instant rolls into the next minute.
|
|
383
|
+
if (h > 23 || m > 59 || s > 60) return null;
|
|
384
|
+
const date = new Date(0);
|
|
385
|
+
date.setUTCFullYear(year, monthIndex, day);
|
|
386
|
+
if (date.getUTCFullYear() !== year || date.getUTCMonth() !== monthIndex || date.getUTCDate() !== day) {
|
|
387
|
+
return null;
|
|
388
|
+
}
|
|
389
|
+
return date.getTime() + ((h * 60 + m) * 60 + s) * 1000;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
const FNV_OFFSET_BASIS = 0x811c9dc5;
|
|
393
|
+
const FNV_PRIME = 0x01000193;
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* 32-bit FNV-1a over the text's UTF-8 bytes: the jitter's hash. A retry's
|
|
397
|
+
* delay only has to spread, so it hashes what identifies the retry and draws
|
|
398
|
+
* nothing (docs/CONVENTIONS.md → Randomness).
|
|
399
|
+
*
|
|
400
|
+
* @param {string} text
|
|
401
|
+
* @returns {number} An unsigned 32-bit integer
|
|
402
|
+
* @throws {TypeError} When the text is not a string
|
|
403
|
+
*/
|
|
404
|
+
function fnv1a32(text) {
|
|
405
|
+
if (typeof text !== 'string') {
|
|
406
|
+
throw new TypeError(`fnv1a32 hashes a string, not ${typeof text}`);
|
|
407
|
+
}
|
|
408
|
+
let hash = FNV_OFFSET_BASIS;
|
|
409
|
+
const mix = (byte) => {
|
|
410
|
+
hash = Math.imul(hash ^ byte, FNV_PRIME) >>> 0;
|
|
411
|
+
};
|
|
412
|
+
for (const character of text) {
|
|
413
|
+
let point = character.codePointAt(0);
|
|
414
|
+
// A lone surrogate has no UTF-8 form; it encodes as U+FFFD, as TextEncoder does.
|
|
415
|
+
if (point >= 0xd800 && point <= 0xdfff) point = 0xfffd;
|
|
416
|
+
if (point < 0x80) {
|
|
417
|
+
mix(point);
|
|
418
|
+
} else if (point < 0x800) {
|
|
419
|
+
mix(0xc0 | (point >> 6));
|
|
420
|
+
mix(0x80 | (point & 0x3f));
|
|
421
|
+
} else if (point < 0x10000) {
|
|
422
|
+
mix(0xe0 | (point >> 12));
|
|
423
|
+
mix(0x80 | ((point >> 6) & 0x3f));
|
|
424
|
+
mix(0x80 | (point & 0x3f));
|
|
425
|
+
} else {
|
|
426
|
+
mix(0xf0 | (point >> 18));
|
|
427
|
+
mix(0x80 | ((point >> 12) & 0x3f));
|
|
428
|
+
mix(0x80 | ((point >> 6) & 0x3f));
|
|
429
|
+
mix(0x80 | (point & 0x3f));
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
return hash;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** Transfers this runtime has keyed by `transferJitterKey`: with the start time, what tells them apart. */
|
|
436
|
+
let transfersKeyed = 0;
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* What a transfer's retries spread by when no session URL keys them yet (a
|
|
440
|
+
* session create) or ever (a download, whose link carries its token): the
|
|
441
|
+
* scope (the create endpoint, or the kind of transfer), when the transfer
|
|
442
|
+
* started, and this runtime's count of keyed transfers, which tell
|
|
443
|
+
* concurrent transfers apart. A transfer's token is a credential and never
|
|
444
|
+
* feeds anything observable such as a delay, so no part of the key derives
|
|
445
|
+
* from it (docs/CONVENTIONS.md → Randomness).
|
|
446
|
+
*
|
|
447
|
+
* @param {string} scope - The endpoint or the kind of transfer
|
|
448
|
+
* @returns {string} The key, for every retry of this one transfer
|
|
449
|
+
* @throws {TypeError} For a scope that is not a non-empty string
|
|
450
|
+
*/
|
|
451
|
+
function transferJitterKey(scope) {
|
|
452
|
+
if (typeof scope !== 'string' || scope.length === 0) {
|
|
453
|
+
throw new TypeError('A transfer jitter key needs the scope its transfer runs in');
|
|
454
|
+
}
|
|
455
|
+
transfersKeyed += 1;
|
|
456
|
+
return `${scope}#${Date.now()}-${transfersKeyed}`;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* How long to wait before retry `attempt` of a transfer: `baseMs` doubling per
|
|
461
|
+
* attempt, capped at `capMs`, plus a jitter in [0, 1000) ms hashed from the
|
|
462
|
+
* transfer and the attempt, and never less than the server's `Retry-After`.
|
|
463
|
+
* The same transfer and attempt always wait the same; different transfers
|
|
464
|
+
* failing together spread out.
|
|
465
|
+
*
|
|
466
|
+
* @param {Object} options
|
|
467
|
+
* @param {number} options.attempt - Which retry this is, from 1
|
|
468
|
+
* @param {number|null} [options.retryAfterMs] - The answer's `Retry-After`: a floor
|
|
469
|
+
* @param {number} [options.baseMs] - The first retry's backoff
|
|
470
|
+
* @param {number} [options.capMs] - The longest backoff, before jitter
|
|
471
|
+
* @param {string} options.jitterKey - What identifies the transfer (its session
|
|
472
|
+
* URL, or a `transferJitterKey`)
|
|
473
|
+
* @returns {number} ms
|
|
474
|
+
* @throws {TypeError} For an attempt that is not a whole number from 1, a
|
|
475
|
+
* missing jitter key, or a delay bound that is not a positive number of ms
|
|
476
|
+
*/
|
|
477
|
+
function retryDelayMs({ attempt, retryAfterMs = null, baseMs = 1000, capMs = 32000, jitterKey }) {
|
|
478
|
+
if (!Number.isSafeInteger(attempt) || attempt < 1) {
|
|
479
|
+
throw new TypeError(`A retry's attempt is a whole number from 1, not ${attempt}`);
|
|
480
|
+
}
|
|
481
|
+
if (typeof jitterKey !== 'string' || jitterKey.length === 0) {
|
|
482
|
+
throw new TypeError('A retry delay needs the key its transfer spreads by');
|
|
483
|
+
}
|
|
484
|
+
if (!isDuration(baseMs) || baseMs === 0 || !isDuration(capMs) || capMs < baseMs) {
|
|
485
|
+
throw new TypeError(`A retry backs off from a positive base (${baseMs} ms) up to a cap no smaller (${capMs} ms)`);
|
|
486
|
+
}
|
|
487
|
+
if (retryAfterMs !== null && !isDuration(retryAfterMs)) {
|
|
488
|
+
throw new TypeError(`A Retry-After floor is a non-negative number of ms, not ${retryAfterMs}`);
|
|
489
|
+
}
|
|
490
|
+
const backoff = Math.min(capMs, baseMs * 2 ** (attempt - 1));
|
|
491
|
+
const jitter = Math.floor((fnv1a32(`${jitterKey}|${attempt}`) / 2 ** 32) * JITTER_SPAN_MS);
|
|
492
|
+
return Math.max(backoff + jitter, retryAfterMs ?? 0);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
function isDuration(ms) {
|
|
496
|
+
return Number.isFinite(ms) && ms >= 0;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* @typedef {Object} TransferBudget
|
|
501
|
+
* @property {() => void} progressed - The server confirmed progress (bytes
|
|
502
|
+
* landed, or the offset it names moved forward): the failures in a row and
|
|
503
|
+
* the idle clock start over
|
|
504
|
+
* @property {() => void} alive - A sign of life the server has not confirmed
|
|
505
|
+
* (bytes are leaving, or the device is back online): the idle clock starts
|
|
506
|
+
* over and the failures in a row stand, so attempts that die before the
|
|
507
|
+
* server confirms anything still end the transfer
|
|
508
|
+
* @property {(verdict: RetryableTransferVerdict, retryAfterMs?: number|null) => boolean} failed -
|
|
509
|
+
* Records a retryable answer (RETRY or RESYNC) and says whether another
|
|
510
|
+
* attempt is allowed: the failures in a row stay under the max, and the
|
|
511
|
+
* attempt `retryAfterMs` allows would start inside the idle limit, so a
|
|
512
|
+
* transfer never sleeps on a Retry-After longer than its budget. The limit
|
|
513
|
+
* bounds when a retry is decided; a retry decided inside it still waits its
|
|
514
|
+
* own backoff, so a transfer ends within one backoff of the limit.
|
|
515
|
+
* @property {(retryAfterMs?: number|null) => boolean} deferred - Records a
|
|
516
|
+
* DEFERRED answer and says whether to ask again: only the idle limit bounds
|
|
517
|
+
* it, as `failed` applies it, because a deferral is the server at work,
|
|
518
|
+
* never a failure, so the failures in a row stand
|
|
519
|
+
* @property {number} consecutiveFailures - Retryable failures since the last progress
|
|
520
|
+
* @property {number} attempt - Failures and deferrals since the last progress:
|
|
521
|
+
* the attempt the next wait's delay is computed for, so each deferral backs
|
|
522
|
+
* the next ask off as a failure does, sparing a Core that is struggling to
|
|
523
|
+
* publish
|
|
524
|
+
* @property {number} msSinceProgress - ms since the last progress or sign of life
|
|
525
|
+
*/
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* The retry budget of one transfer: retries are bounded by failures in a row
|
|
529
|
+
* and by time without progress, deferrals by time alone, and both bounds
|
|
530
|
+
* start over whenever the server confirms progress, so a slow transfer that
|
|
531
|
+
* keeps landing bytes is never cut off while a dead one ends in bounded time.
|
|
532
|
+
*
|
|
533
|
+
* @param {Object} [options]
|
|
534
|
+
* @param {number} [options.idleLimitMs] - How long the transfer may go without
|
|
535
|
+
* progress or a sign of life
|
|
536
|
+
* @param {number} [options.maxConsecutiveFailures] - Failures in a row that end the transfer
|
|
537
|
+
* @param {() => number} [options.now] - The clock, epoch ms
|
|
538
|
+
* @returns {TransferBudget}
|
|
539
|
+
* @throws {TypeError} For a limit that is not a positive number, or a clock that is not a function
|
|
540
|
+
*/
|
|
541
|
+
function createTransferBudget({
|
|
542
|
+
idleLimitMs = DEFAULT_IDLE_LIMIT_MS,
|
|
543
|
+
maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,
|
|
544
|
+
now = () => Date.now()
|
|
545
|
+
} = {}) {
|
|
546
|
+
if (!isDuration(idleLimitMs) || idleLimitMs === 0) {
|
|
547
|
+
throw new TypeError(`A transfer's idle limit is a positive number of ms, not ${idleLimitMs}`);
|
|
548
|
+
}
|
|
549
|
+
if (!Number.isSafeInteger(maxConsecutiveFailures) || maxConsecutiveFailures < 1) {
|
|
550
|
+
throw new TypeError(`A transfer's failure limit is a whole number from 1, not ${maxConsecutiveFailures}`);
|
|
551
|
+
}
|
|
552
|
+
if (typeof now !== 'function') {
|
|
553
|
+
throw new TypeError('A transfer budget reads time from a clock function');
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
let consecutiveFailures = 0;
|
|
557
|
+
let deferrals = 0;
|
|
558
|
+
let lastSignOfLifeAt = now();
|
|
559
|
+
const msIdle = () => now() - lastSignOfLifeAt;
|
|
560
|
+
const startsInsideIdleLimit = (retryAfterMs) => {
|
|
561
|
+
if (retryAfterMs !== null && !isDuration(retryAfterMs)) {
|
|
562
|
+
throw new TypeError(`A Retry-After floor is a non-negative number of ms, not ${retryAfterMs}`);
|
|
563
|
+
}
|
|
564
|
+
return msIdle() + (retryAfterMs ?? 0) < idleLimitMs;
|
|
565
|
+
};
|
|
566
|
+
|
|
567
|
+
return Object.freeze({
|
|
568
|
+
progressed() {
|
|
569
|
+
consecutiveFailures = 0;
|
|
570
|
+
deferrals = 0;
|
|
571
|
+
lastSignOfLifeAt = now();
|
|
572
|
+
},
|
|
573
|
+
alive() {
|
|
574
|
+
lastSignOfLifeAt = now();
|
|
575
|
+
},
|
|
576
|
+
failed(verdict, retryAfterMs = null) {
|
|
577
|
+
if (!RETRYABLE_VERDICTS.has(verdict)) {
|
|
578
|
+
throw new TypeError(`A transfer budget records retryable answers only, not '${verdict}'`);
|
|
579
|
+
}
|
|
580
|
+
const allowed = startsInsideIdleLimit(retryAfterMs);
|
|
581
|
+
consecutiveFailures += 1;
|
|
582
|
+
return allowed && consecutiveFailures < maxConsecutiveFailures;
|
|
583
|
+
},
|
|
584
|
+
deferred(retryAfterMs = null) {
|
|
585
|
+
const allowed = startsInsideIdleLimit(retryAfterMs);
|
|
586
|
+
deferrals += 1;
|
|
587
|
+
return allowed;
|
|
588
|
+
},
|
|
589
|
+
get consecutiveFailures() {
|
|
590
|
+
return consecutiveFailures;
|
|
591
|
+
},
|
|
592
|
+
get attempt() {
|
|
593
|
+
return consecutiveFailures + deferrals;
|
|
594
|
+
},
|
|
595
|
+
get msSinceProgress() {
|
|
596
|
+
return msIdle();
|
|
597
|
+
}
|
|
598
|
+
});
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/** Why an offset the server names cannot be resumed from. */
|
|
602
|
+
const RESUME_OFFSET_PROBLEM = Object.freeze({
|
|
603
|
+
/** Not a non-negative whole number of bytes. */
|
|
604
|
+
INVALID: 'invalid',
|
|
605
|
+
/** Past the upload's length: resuming from it would report a partial upload complete. */
|
|
606
|
+
BEYOND_TOTAL: 'beyond_total',
|
|
607
|
+
/** Inside a chunk: a session commits whole chunks only, so the answer is corrupt. */
|
|
608
|
+
MISALIGNED: 'misaligned'
|
|
609
|
+
});
|
|
610
|
+
|
|
611
|
+
/**
|
|
612
|
+
* Why a session offset the server named (a HEAD's, or a 409's `Upload-Offset`)
|
|
613
|
+
* cannot be resumed from, or null when it can. Forge commits whole chunks, so
|
|
614
|
+
* a session stands at a multiple of its chunk size or at its total.
|
|
615
|
+
*
|
|
616
|
+
* @param {number|null} offset
|
|
617
|
+
* @param {Object} geometry
|
|
618
|
+
* @param {number} geometry.totalSize - The upload's length (a non-negative whole number)
|
|
619
|
+
* @param {number} geometry.chunkSize - The session's chunk size (a positive whole number)
|
|
620
|
+
* @returns {'invalid'|'beyond_total'|'misaligned'|null}
|
|
621
|
+
* @throws {TypeError} When the length is not a non-negative whole number or
|
|
622
|
+
* the chunk size not a positive one
|
|
623
|
+
*/
|
|
624
|
+
function resumeOffsetProblem(offset, { totalSize, chunkSize }) {
|
|
625
|
+
if (!Number.isSafeInteger(totalSize) || totalSize < 0 || !Number.isSafeInteger(chunkSize) || chunkSize < 1) {
|
|
626
|
+
throw new TypeError(`An upload's geometry is a whole length and a positive chunk size, not ${totalSize} and ${chunkSize}`);
|
|
627
|
+
}
|
|
628
|
+
if (!Number.isSafeInteger(offset) || offset < 0) return RESUME_OFFSET_PROBLEM.INVALID;
|
|
629
|
+
if (offset > totalSize) return RESUME_OFFSET_PROBLEM.BEYOND_TOTAL;
|
|
630
|
+
if (offset !== totalSize && offset % chunkSize !== 0) return RESUME_OFFSET_PROBLEM.MISALIGNED;
|
|
631
|
+
return null;
|
|
632
|
+
}
|
|
633
|
+
|
|
1
634
|
/**
|
|
2
635
|
* SparkVault SDK Error Types
|
|
3
636
|
*/
|
|
4
637
|
class SparkVaultError extends Error {
|
|
5
|
-
constructor(message, code, statusCode, details) {
|
|
638
|
+
constructor(message, code, statusCode, details, retryAfterMs = null) {
|
|
6
639
|
super(message);
|
|
7
640
|
this.name = 'SparkVaultError';
|
|
8
641
|
this.code = code;
|
|
9
642
|
this.statusCode = statusCode;
|
|
10
643
|
this.details = details;
|
|
644
|
+
this.retryAfterMs = retryAfterMs;
|
|
11
645
|
Object.setPrototypeOf(this, SparkVaultError.prototype);
|
|
12
646
|
}
|
|
13
647
|
}
|
|
14
648
|
class AuthenticationError extends SparkVaultError {
|
|
15
|
-
constructor(message, details) {
|
|
16
|
-
super(message, 'authentication_error', 401, details);
|
|
649
|
+
constructor(message, details, retryAfterMs = null) {
|
|
650
|
+
super(message, 'authentication_error', 401, details, retryAfterMs);
|
|
17
651
|
this.name = 'AuthenticationError';
|
|
18
652
|
Object.setPrototypeOf(this, AuthenticationError.prototype);
|
|
19
653
|
}
|
|
20
654
|
}
|
|
21
655
|
class AuthorizationError extends SparkVaultError {
|
|
22
|
-
constructor(message, details) {
|
|
23
|
-
super(message, 'authorization_error', 403, details);
|
|
656
|
+
constructor(message, details, retryAfterMs = null) {
|
|
657
|
+
super(message, 'authorization_error', 403, details, retryAfterMs);
|
|
24
658
|
this.name = 'AuthorizationError';
|
|
25
659
|
Object.setPrototypeOf(this, AuthorizationError.prototype);
|
|
26
660
|
}
|
|
27
661
|
}
|
|
28
662
|
class ValidationError extends SparkVaultError {
|
|
29
|
-
constructor(message, details) {
|
|
30
|
-
super(message, 'validation_error', 400, details);
|
|
663
|
+
constructor(message, details, retryAfterMs = null) {
|
|
664
|
+
super(message, 'validation_error', 400, details, retryAfterMs);
|
|
31
665
|
this.name = 'ValidationError';
|
|
32
666
|
Object.setPrototypeOf(this, ValidationError.prototype);
|
|
33
667
|
}
|
|
@@ -38,8 +672,8 @@ class ValidationError extends SparkVaultError {
|
|
|
38
672
|
* to admins, or "ask your account admin" to members.
|
|
39
673
|
*/
|
|
40
674
|
class PlanRequiredError extends SparkVaultError {
|
|
41
|
-
constructor(message, details) {
|
|
42
|
-
super(message, 'PLAN_REQUIRED', 402, details);
|
|
675
|
+
constructor(message, details, retryAfterMs = null) {
|
|
676
|
+
super(message, 'PLAN_REQUIRED', 402, details, retryAfterMs);
|
|
43
677
|
this.name = 'PlanRequiredError';
|
|
44
678
|
Object.setPrototypeOf(this, PlanRequiredError.prototype);
|
|
45
679
|
}
|
|
@@ -50,8 +684,8 @@ class PlanRequiredError extends SparkVaultError {
|
|
|
50
684
|
* the right capacity block.
|
|
51
685
|
*/
|
|
52
686
|
class QuotaExceededError extends SparkVaultError {
|
|
53
|
-
constructor(message, details) {
|
|
54
|
-
super(message, 'QUOTA_EXCEEDED', 402, details);
|
|
687
|
+
constructor(message, details, retryAfterMs = null) {
|
|
688
|
+
super(message, 'QUOTA_EXCEEDED', 402, details, retryAfterMs);
|
|
55
689
|
this.name = 'QuotaExceededError';
|
|
56
690
|
const resource = details?.resource;
|
|
57
691
|
this.resource =
|
|
@@ -66,8 +700,8 @@ class QuotaExceededError extends SparkVaultError {
|
|
|
66
700
|
* nothing, so surface a subscribe CTA rather than a sign-in prompt.
|
|
67
701
|
*/
|
|
68
702
|
class NotifySubscriptionRequiredError extends SparkVaultError {
|
|
69
|
-
constructor(message, details) {
|
|
70
|
-
super(message, 'NOTIFY_SUBSCRIPTION_REQUIRED', 403, details);
|
|
703
|
+
constructor(message, details, retryAfterMs = null) {
|
|
704
|
+
super(message, 'NOTIFY_SUBSCRIPTION_REQUIRED', 403, details, retryAfterMs);
|
|
71
705
|
this.name = 'NotifySubscriptionRequiredError';
|
|
72
706
|
Object.setPrototypeOf(this, NotifySubscriptionRequiredError.prototype);
|
|
73
707
|
}
|
|
@@ -123,24 +757,51 @@ function recordField(value) {
|
|
|
123
757
|
? value
|
|
124
758
|
: undefined;
|
|
125
759
|
}
|
|
760
|
+
function parseJson(text) {
|
|
761
|
+
try {
|
|
762
|
+
return JSON.parse(text);
|
|
763
|
+
}
|
|
764
|
+
catch {
|
|
765
|
+
return null;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
126
768
|
/**
|
|
127
|
-
* Read a failed
|
|
128
|
-
* shares
|
|
129
|
-
*
|
|
130
|
-
*
|
|
131
|
-
*
|
|
132
|
-
*
|
|
769
|
+
* Read a failed answer from its parsed body: the one reading every SDK
|
|
770
|
+
* transport shares, so an error built from an answer carries the same of it
|
|
771
|
+
* whichever client made the request, and whether fetch or an XMLHttpRequest
|
|
772
|
+
* received it. SparkVault services answer `{ error: { code, message,
|
|
773
|
+
* details } }`; a framework or gateway answers flat (`{ code, message }`,
|
|
774
|
+
* `{ message }`) or with no JSON at all, so each field falls back to its flat
|
|
775
|
+
* form and then to a default. The body is read leniently: a failure's status
|
|
776
|
+
* and class never depend on the body being JSON. The `Retry-After` is read by
|
|
777
|
+
* the transfer policy's one parser (`@sparkvault/app-sdk/transfer-retry`),
|
|
778
|
+
* never a second one: the policy reads a whole answer at once, and only its
|
|
779
|
+
* header reading is kept here, because an API answer is the service's
|
|
780
|
+
* verdict, never a transfer answer the policy's verdict applies to.
|
|
133
781
|
*/
|
|
134
|
-
|
|
135
|
-
const body = await response.json().catch(() => null);
|
|
782
|
+
function failureOf(status, body, header) {
|
|
136
783
|
const root = recordField(body) ?? {};
|
|
137
784
|
const nested = recordField(root.error);
|
|
138
785
|
return {
|
|
786
|
+
status,
|
|
139
787
|
message: stringField(nested?.message) ?? stringField(root.message) ?? stringField(root.error) ?? 'Request failed',
|
|
140
788
|
code: stringField(nested?.code) ?? stringField(root.code) ?? 'api_error',
|
|
141
789
|
details: recordField(nested?.details) ?? recordField(root.details),
|
|
790
|
+
retryAfterMs: classifyTransferResponse({ status, headers: header }).retryAfterMs,
|
|
142
791
|
};
|
|
143
792
|
}
|
|
793
|
+
/**
|
|
794
|
+
* Read a failed answer a transport holds as text (an XMLHttpRequest's
|
|
795
|
+
* `responseText`, a body it also keeps a snippet of), parsed whole, so
|
|
796
|
+
* nothing past any length is lost to the reading.
|
|
797
|
+
*/
|
|
798
|
+
function apiFailureOf(answer) {
|
|
799
|
+
return failureOf(answer.status, parseJson(answer.body), answer.header);
|
|
800
|
+
}
|
|
801
|
+
/** Read a failed fetch response; a body that is not JSON, or cannot be read, reads as none. */
|
|
802
|
+
async function readApiFailure(response) {
|
|
803
|
+
return failureOf(response.status, await response.json().catch(() => null), (name) => response.headers.get(name));
|
|
804
|
+
}
|
|
144
805
|
|
|
145
806
|
/**
|
|
146
807
|
* SparkVault resource ids: the one grammar every surface reads an id by before
|
|
@@ -476,10 +1137,14 @@ class SparkVaultApi {
|
|
|
476
1137
|
* here, when the request starts. resetSession() can swap the controller
|
|
477
1138
|
* while the request is in flight, and reading the live one afterwards would
|
|
478
1139
|
* misreport a genuine cancel as a timeout.
|
|
1140
|
+
*
|
|
1141
|
+
* @param timeoutMs - The deadline of a request whose server-side wait is
|
|
1142
|
+
* its own (a tus HEAD or receipt, which Forge answers only after its call
|
|
1143
|
+
* to Core); every other request takes the client's.
|
|
479
1144
|
*/
|
|
480
|
-
send(url, init, copy, read) {
|
|
1145
|
+
send(url, init, copy, read, timeoutMs = this.timeoutMs) {
|
|
481
1146
|
return exchange(url, init, {
|
|
482
|
-
timeoutMs
|
|
1147
|
+
timeoutMs,
|
|
483
1148
|
closeSignal: this.closeController.signal,
|
|
484
1149
|
read,
|
|
485
1150
|
fail: (failure, cause) => {
|
|
@@ -499,8 +1164,9 @@ class SparkVaultApi {
|
|
|
499
1164
|
/**
|
|
500
1165
|
* Issue a JSON API request. Returns the parsed JSON body (whatever shape it
|
|
501
1166
|
* takes; null when the body is not JSON) plus the status code. A non-2xx
|
|
502
|
-
* answer throws the subclass error carrying the server's code, message
|
|
503
|
-
* details
|
|
1167
|
+
* answer throws the subclass error carrying the server's code, message,
|
|
1168
|
+
* details and `Retry-After`, read by the one failed-answer reader every
|
|
1169
|
+
* transport shares.
|
|
504
1170
|
*/
|
|
505
1171
|
rawRequest(url, options) {
|
|
506
1172
|
// Only send Content-Type when there's actually a body — otherwise GETs
|
|
@@ -516,8 +1182,8 @@ class SparkVaultApi {
|
|
|
516
1182
|
network: 'Unable to connect. Please check your connection and try again.',
|
|
517
1183
|
}, async (response) => {
|
|
518
1184
|
if (!response.ok) {
|
|
519
|
-
const { message, code, details } = await
|
|
520
|
-
throw this.makeError(message, code,
|
|
1185
|
+
const { status, message, code, details, retryAfterMs } = await readApiFailure(response);
|
|
1186
|
+
throw this.makeError(message, code, status, details, retryAfterMs);
|
|
521
1187
|
}
|
|
522
1188
|
return { data: await readJsonBody(response), status: response.status };
|
|
523
1189
|
});
|
|
@@ -645,7 +1311,7 @@ class HttpClient {
|
|
|
645
1311
|
timeoutMs: timeout,
|
|
646
1312
|
read: async (response) => {
|
|
647
1313
|
if (!response.ok) {
|
|
648
|
-
throw this.createErrorFromResponse(
|
|
1314
|
+
throw this.createErrorFromResponse(await readApiFailure(response));
|
|
649
1315
|
}
|
|
650
1316
|
const parsed = await this.parseResponse(response);
|
|
651
1317
|
return {
|
|
@@ -683,26 +1349,34 @@ class HttpClient {
|
|
|
683
1349
|
const text = await response.text();
|
|
684
1350
|
throw new SparkVaultError(`Unexpected response format: expected JSON but received ${contentType ?? 'unknown content type'}`, 'invalid_response_format', response.status, { body: text.slice(0, 500) });
|
|
685
1351
|
}
|
|
686
|
-
|
|
1352
|
+
/**
|
|
1353
|
+
* The SDK error for a failed answer, typed by its status: the gates a host
|
|
1354
|
+
* page branches on get their own class, and every other answer is the base
|
|
1355
|
+
* error under the service's own code. Each carries the answer's
|
|
1356
|
+
* `Retry-After` (`retryAfterMs`), the floor for whoever retries it — the
|
|
1357
|
+
* SDK's own transfers when the answer is a download link's mint, and the
|
|
1358
|
+
* host page otherwise.
|
|
1359
|
+
*/
|
|
1360
|
+
createErrorFromResponse({ status, message, code, details, retryAfterMs }) {
|
|
687
1361
|
switch (status) {
|
|
688
1362
|
case 400:
|
|
689
|
-
return new ValidationError(message, details);
|
|
1363
|
+
return new ValidationError(message, details, retryAfterMs);
|
|
690
1364
|
case 401:
|
|
691
|
-
return new AuthenticationError(message, details);
|
|
1365
|
+
return new AuthenticationError(message, details, retryAfterMs);
|
|
692
1366
|
case 402:
|
|
693
1367
|
if (code === 'QUOTA_EXCEEDED')
|
|
694
|
-
return new QuotaExceededError(message, details);
|
|
1368
|
+
return new QuotaExceededError(message, details, retryAfterMs);
|
|
695
1369
|
// PLAN_REQUIRED is the canonical 402 gate; treat any other 402 as one too.
|
|
696
|
-
return new PlanRequiredError(message, details);
|
|
1370
|
+
return new PlanRequiredError(message, details, retryAfterMs);
|
|
697
1371
|
case 403:
|
|
698
1372
|
// A Notify send refused for want of a subscription is a billing gate, not
|
|
699
1373
|
// a credential problem — give it its own catchable type.
|
|
700
1374
|
if (code === 'NOTIFY_SUBSCRIPTION_REQUIRED') {
|
|
701
|
-
return new NotifySubscriptionRequiredError(message, details);
|
|
1375
|
+
return new NotifySubscriptionRequiredError(message, details, retryAfterMs);
|
|
702
1376
|
}
|
|
703
|
-
return new AuthorizationError(message, details);
|
|
1377
|
+
return new AuthorizationError(message, details, retryAfterMs);
|
|
704
1378
|
default:
|
|
705
|
-
return new SparkVaultError(message, code, status, details);
|
|
1379
|
+
return new SparkVaultError(message, code, status, details, retryAfterMs);
|
|
706
1380
|
}
|
|
707
1381
|
}
|
|
708
1382
|
unwrapApiResponse(data) {
|
|
@@ -1498,8 +2172,8 @@ class IdentityApi extends SparkVaultApi {
|
|
|
1498
2172
|
get baseUrl() {
|
|
1499
2173
|
return `${this.config.identityBaseUrl}${apiPath `/${this.config.accountId}`}`;
|
|
1500
2174
|
}
|
|
1501
|
-
makeError(message, code, statusCode, details) {
|
|
1502
|
-
return new IdentityApiError(message, code, statusCode, details);
|
|
2175
|
+
makeError(message, code, statusCode, details, retryAfterMs = null) {
|
|
2176
|
+
return new IdentityApiError(message, code, statusCode, details, retryAfterMs);
|
|
1503
2177
|
}
|
|
1504
2178
|
async request(method, endpoint, body, query) {
|
|
1505
2179
|
const { data } = await this.rawRequest(`${this.baseUrl}${endpoint}${queryString(query)}`, {
|
|
@@ -1875,8 +2549,8 @@ function mapRecommendations(raw) {
|
|
|
1875
2549
|
return result;
|
|
1876
2550
|
}
|
|
1877
2551
|
class IdentityApiError extends SparkVaultError {
|
|
1878
|
-
constructor(message, code, statusCode, details) {
|
|
1879
|
-
super(message, code, statusCode, details);
|
|
2552
|
+
constructor(message, code, statusCode, details, retryAfterMs = null) {
|
|
2553
|
+
super(message, code, statusCode, details, retryAfterMs);
|
|
1880
2554
|
this.name = 'IdentityApiError';
|
|
1881
2555
|
Object.setPrototypeOf(this, IdentityApiError.prototype);
|
|
1882
2556
|
}
|
|
@@ -10984,11 +11658,21 @@ function refused(reason) {
|
|
|
10984
11658
|
/**
|
|
10985
11659
|
* Error class for upload API errors. Inherits `code` and `statusCode` from
|
|
10986
11660
|
* SparkVaultError — no duplicate `httpStatus` field.
|
|
11661
|
+
*
|
|
11662
|
+
* A failed transfer request also carries what the transfer policy
|
|
11663
|
+
* (`@sparkvault/app-sdk/transfer-retry`) makes of its answer, read where the
|
|
11664
|
+
* answer arrived: its `verdict` and its `Upload-Offset` (`serverOffset`),
|
|
11665
|
+
* beside the `Retry-After` every SDK error carries (`retryAfterMs`). They are
|
|
11666
|
+
* the retry loop's bookkeeping, so they ride on the instance, never in
|
|
11667
|
+
* `details`. Every other failure (a cancel, a refused URL, a protocol
|
|
11668
|
+
* violation) is `refused`: nothing retries it.
|
|
10987
11669
|
*/
|
|
10988
11670
|
class UploadApiError extends SparkVaultError {
|
|
10989
|
-
constructor(message, code, statusCode, details) {
|
|
10990
|
-
super(message, code, statusCode, details);
|
|
11671
|
+
constructor(message, code, statusCode, details, outcome) {
|
|
11672
|
+
super(message, code, statusCode, details, outcome?.retryAfterMs ?? null);
|
|
10991
11673
|
this.name = 'UploadApiError';
|
|
11674
|
+
this.verdict = outcome?.verdict ?? TRANSFER_VERDICT.REFUSED;
|
|
11675
|
+
this.serverOffset = outcome?.offset ?? null;
|
|
10992
11676
|
Object.setPrototypeOf(this, UploadApiError.prototype);
|
|
10993
11677
|
}
|
|
10994
11678
|
}
|
|
@@ -11051,51 +11735,51 @@ function parseChunkSizeHeader(raw) {
|
|
|
11051
11735
|
*/
|
|
11052
11736
|
const CHUNK_INACTIVITY_TIMEOUT_MS = 60000;
|
|
11053
11737
|
/**
|
|
11054
|
-
*
|
|
11738
|
+
* How many consecutive timeouts end the finalization receipt early.
|
|
11055
11739
|
*
|
|
11056
|
-
*
|
|
11057
|
-
*
|
|
11058
|
-
*
|
|
11059
|
-
*
|
|
11060
|
-
*
|
|
11061
|
-
* never capped while a genuinely dead one still fails in bounded time.
|
|
11740
|
+
* A genuinely slow finalize shows up as ONE timeout — the PATCH that started
|
|
11741
|
+
* the re-drive — followed by 409s from the writer that is working on it.
|
|
11742
|
+
* Back-to-back timeouts mean nobody is answering at all, and spending the
|
|
11743
|
+
* whole retry budget on a black-holed socket would freeze the widget at 100%
|
|
11744
|
+
* for minutes with nothing for the user to act on.
|
|
11062
11745
|
*/
|
|
11063
|
-
const
|
|
11064
|
-
|
|
11746
|
+
const FINALIZE_MAX_CONSECUTIVE_TIMEOUTS = 2;
|
|
11747
|
+
/** The copy a person reads when the session their upload ran in no longer exists. */
|
|
11748
|
+
const SESSION_GONE_MESSAGE = 'Upload could not be finished: the server has ended this upload session. Please upload the file again.';
|
|
11065
11749
|
/**
|
|
11066
|
-
*
|
|
11067
|
-
*
|
|
11068
|
-
*
|
|
11069
|
-
* inside the finalizer, so the confirmation has to out-wait a finalization
|
|
11070
|
-
* already in flight rather than give up on it — a budget measured in seconds
|
|
11071
|
-
* rather than in the sub-second blips a chunk retry recovers from.
|
|
11750
|
+
* The copy a person reads when the server kept deferring the publication
|
|
11751
|
+
* until the upload's idle limit: nothing failed, and nothing is left for
|
|
11752
|
+
* them to do.
|
|
11072
11753
|
*/
|
|
11073
|
-
const
|
|
11074
|
-
const FINALIZE_RETRY_MS = 1000;
|
|
11754
|
+
const RECEIVED_PUBLISHING_MESSAGE = 'The server received every byte of this file and is still saving it. It finishes on its own.';
|
|
11075
11755
|
/**
|
|
11076
|
-
*
|
|
11077
|
-
*
|
|
11078
|
-
*
|
|
11079
|
-
*
|
|
11080
|
-
* Back-to-back timeouts mean nobody is answering at all, and spending the full
|
|
11081
|
-
* budget on a black-holed socket would freeze the widget at 100% for minutes
|
|
11082
|
-
* with nothing for the user to act on.
|
|
11756
|
+
* The copy a person reads for a final refusal whose answer carried no
|
|
11757
|
+
* sentence of Core's (a HEAD's, which has no body, naming Core's code in
|
|
11758
|
+
* `X-Upload-Refusal` alone): this SDK's own words for each code, none of them
|
|
11759
|
+
* asking for the file again.
|
|
11083
11760
|
*/
|
|
11084
|
-
const
|
|
11761
|
+
const REFUSAL_WORDING = new Map([
|
|
11762
|
+
[UPLOAD_REFUSAL_CODES.UPLOAD_POOL_FULL, 'This upload could not be saved: the owner\'s storage cannot take the file.'],
|
|
11763
|
+
[UPLOAD_REFUSAL_CODES.UPLOAD_SUPERSEDED, 'This upload was not saved: a newer upload of this file replaced it.'],
|
|
11764
|
+
]);
|
|
11765
|
+
/** The copy for a final refusal of a code this SDK has no words of its own for. */
|
|
11766
|
+
const REFUSED_MESSAGE = 'This upload could not be saved: the server refused it.';
|
|
11767
|
+
function cancelledError() {
|
|
11768
|
+
return new UploadApiError('Upload cancelled', 'cancelled', 0);
|
|
11769
|
+
}
|
|
11085
11770
|
/**
|
|
11086
11771
|
* A delay that a cancel cuts short: resolves after `ms`, rejects with the
|
|
11087
11772
|
* canonical cancelled error the moment the signal aborts.
|
|
11088
11773
|
*/
|
|
11089
11774
|
function abortableDelay(ms, signal) {
|
|
11090
11775
|
return new Promise((resolve, reject) => {
|
|
11091
|
-
const cancelled = () => new UploadApiError('Upload cancelled', 'cancelled', 0);
|
|
11092
11776
|
if (signal.aborted) {
|
|
11093
|
-
reject(
|
|
11777
|
+
reject(cancelledError());
|
|
11094
11778
|
return;
|
|
11095
11779
|
}
|
|
11096
11780
|
const onAbort = () => {
|
|
11097
11781
|
clearTimeout(timer);
|
|
11098
|
-
reject(
|
|
11782
|
+
reject(cancelledError());
|
|
11099
11783
|
};
|
|
11100
11784
|
const timer = setTimeout(() => {
|
|
11101
11785
|
signal.removeEventListener('abort', onAbort);
|
|
@@ -11104,63 +11788,166 @@ function abortableDelay(ms, signal) {
|
|
|
11104
11788
|
signal.addEventListener('abort', onAbort, { once: true });
|
|
11105
11789
|
});
|
|
11106
11790
|
}
|
|
11791
|
+
/** Whether the browser knows it has no network: `onLine` false is definite, true is only a hope. */
|
|
11792
|
+
function isOffline() {
|
|
11793
|
+
return typeof navigator !== 'undefined' && navigator.onLine === false;
|
|
11794
|
+
}
|
|
11107
11795
|
/**
|
|
11108
|
-
*
|
|
11109
|
-
*
|
|
11110
|
-
*
|
|
11111
|
-
* - the chunk PATCH loop — may this chunk be re-sent?
|
|
11112
|
-
* - the resume-HEAD loop — may the session's offset be re-read?
|
|
11113
|
-
* - the finalization receipt — may publication be asked about again?
|
|
11114
|
-
*
|
|
11115
|
-
* A transport-level failure (status 0 — a dropped connection, a timeout, or
|
|
11116
|
-
* the inactivity watchdog aborting a silent socket) says nothing about whether
|
|
11117
|
-
* the request reached Forge, 409 is Forge's documented "another writer holds
|
|
11118
|
-
* the session lease; re-check and retry" (on the receipt: a finalizer is
|
|
11119
|
-
* running right now), and a 5xx is a server-side blip. Every other outcome is
|
|
11120
|
-
* the server's considered answer about this exact request — a rejected offset,
|
|
11121
|
-
* a bad ISTK, a vanished session, or a 2xx carrying a protocol-violating
|
|
11122
|
-
* offset — and re-sending would only earn it again. A cancelled session is the
|
|
11123
|
-
* user's decision, never a failure to retry.
|
|
11796
|
+
* Resolve once the browser is back online; reject with the canonical
|
|
11797
|
+
* cancelled error the moment the session closes, which is the only bound on
|
|
11798
|
+
* the wait.
|
|
11124
11799
|
*/
|
|
11125
|
-
function
|
|
11126
|
-
|
|
11127
|
-
|
|
11128
|
-
|
|
11129
|
-
|
|
11130
|
-
|
|
11131
|
-
|
|
11132
|
-
|
|
11133
|
-
|
|
11134
|
-
|
|
11135
|
-
|
|
11136
|
-
|
|
11800
|
+
function waitUntilOnline(signal) {
|
|
11801
|
+
return new Promise((resolve, reject) => {
|
|
11802
|
+
if (signal.aborted) {
|
|
11803
|
+
reject(cancelledError());
|
|
11804
|
+
return;
|
|
11805
|
+
}
|
|
11806
|
+
const settle = (outcome) => {
|
|
11807
|
+
globalThis.removeEventListener('online', onOnline);
|
|
11808
|
+
signal.removeEventListener('abort', onAbort);
|
|
11809
|
+
outcome();
|
|
11810
|
+
};
|
|
11811
|
+
const onOnline = () => settle(resolve);
|
|
11812
|
+
const onAbort = () => settle(() => reject(cancelledError()));
|
|
11813
|
+
globalThis.addEventListener('online', onOnline);
|
|
11814
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
11815
|
+
// The network may have come back between the caller's check and these
|
|
11816
|
+
// listeners, and its `online` event would then never arrive.
|
|
11817
|
+
if (!isOffline())
|
|
11818
|
+
settle(resolve);
|
|
11819
|
+
});
|
|
11820
|
+
}
|
|
11821
|
+
/** A failed request of this upload's transfer; anything else is rethrown as it is. */
|
|
11822
|
+
function transferFailure(error) {
|
|
11823
|
+
if (error instanceof UploadApiError)
|
|
11824
|
+
return error;
|
|
11825
|
+
throw error;
|
|
11826
|
+
}
|
|
11827
|
+
/**
|
|
11828
|
+
* The session the upload ran in is gone (cancelled, expired, or its file
|
|
11829
|
+
* removed): only a new upload from byte 0 can store the file, which the caller
|
|
11830
|
+
* starts (`ingots.upload` / `createUpload` again, or the widget's next upload).
|
|
11831
|
+
*/
|
|
11832
|
+
function sessionGoneError(failure) {
|
|
11833
|
+
return new UploadApiError(SESSION_GONE_MESSAGE, 'session_gone', failure.statusCode ?? 0, { status: failure.statusCode, ...failure.details }, { verdict: TRANSFER_VERDICT.GONE, retryAfterMs: null, offset: null, coreCode: null });
|
|
11834
|
+
}
|
|
11835
|
+
/**
|
|
11836
|
+
* Wait out the backoff of a failed request, spending a retry of the upload's
|
|
11837
|
+
* budget, or of a deferred one, spending none for as long as the idle limit
|
|
11838
|
+
* allows; never shorter than the answer's `Retry-After`, and longer with
|
|
11839
|
+
* every failure and deferral since the last progress. Throws an answer no
|
|
11840
|
+
* retry follows as it is, and the last failure, or the deferral, once the
|
|
11841
|
+
* budget is spent. While the browser is offline a failure spends nothing: the
|
|
11842
|
+
* wait is for the network to come back (or the session to close), and the
|
|
11843
|
+
* idle clock starts over when it does.
|
|
11844
|
+
*/
|
|
11845
|
+
async function waitToRetry(budget, failure, jitterKey, sessionSignal) {
|
|
11846
|
+
const { verdict, retryAfterMs } = failure;
|
|
11847
|
+
if (verdict === TRANSFER_VERDICT.DEFERRED) {
|
|
11848
|
+
if (!budget.deferred(retryAfterMs))
|
|
11849
|
+
throw failure;
|
|
11850
|
+
}
|
|
11851
|
+
else if (verdict !== TRANSFER_VERDICT.RETRY) {
|
|
11852
|
+
throw failure;
|
|
11853
|
+
}
|
|
11854
|
+
else if (isOffline()) {
|
|
11855
|
+
await waitUntilOnline(sessionSignal);
|
|
11856
|
+
budget.alive();
|
|
11857
|
+
return;
|
|
11858
|
+
}
|
|
11859
|
+
else if (!budget.failed(verdict, retryAfterMs)) {
|
|
11860
|
+
throw failure;
|
|
11861
|
+
}
|
|
11862
|
+
const delayMs = retryDelayMs({
|
|
11863
|
+
attempt: budget.attempt,
|
|
11864
|
+
retryAfterMs,
|
|
11865
|
+
jitterKey,
|
|
11866
|
+
});
|
|
11867
|
+
await abortableDelay(delayMs, sessionSignal);
|
|
11137
11868
|
}
|
|
11138
11869
|
/**
|
|
11139
11870
|
* A server's error body, reduced to something safe to carry on an error:
|
|
11140
11871
|
* whitespace collapsed and length clipped, so an HTML error page or a stack
|
|
11141
|
-
* trace can never become the payload.
|
|
11872
|
+
* trace can never become the payload. The clip is only for what the error
|
|
11873
|
+
* carries: the body is read whole first ({@link readTransferAnswer}).
|
|
11142
11874
|
*/
|
|
11143
11875
|
const ERROR_DETAIL_MAX_CHARS = 200;
|
|
11144
11876
|
function summarizeErrorBody(body) {
|
|
11145
11877
|
return body.replace(/\s+/g, ' ').trim().slice(0, ERROR_DETAIL_MAX_CHARS);
|
|
11146
11878
|
}
|
|
11879
|
+
/**
|
|
11880
|
+
* What the transfer policy makes of a transfer request's answer, and the
|
|
11881
|
+
* error it throws when it is not a 2xx. A failed answer's body is read whole
|
|
11882
|
+
* by the SDK's one reader of a failed answer ({@link apiFailureOf}), so the
|
|
11883
|
+
* code Core ended the upload with reaches the policy however long Core's
|
|
11884
|
+
* sentence is, and an answer with no body (a HEAD's) names it in
|
|
11885
|
+
* `X-Upload-Refusal`: a final refusal throws `upload_refused` in Core's own
|
|
11886
|
+
* words (this SDK's for a HEAD's), Core's code in `details.coreCode`, and a
|
|
11887
|
+
* new upload is no remedy. The receipt's deferral throws
|
|
11888
|
+
* `upload_received_publishing`, which the upload only ever throws once the
|
|
11889
|
+
* idle limit ends the asking. Any other failure throws the request's own
|
|
11890
|
+
* copy, the server's detail and any other code of Core's in `details` (a gone
|
|
11891
|
+
* session's, which the upload reports as `session_gone`).
|
|
11892
|
+
*
|
|
11893
|
+
* @param answer - The status, the headers, and the body's whole text (empty for a 2xx)
|
|
11894
|
+
*/
|
|
11895
|
+
function readTransferAnswer(answer, read) {
|
|
11896
|
+
const served = answer.body ? apiFailureOf(answer) : null;
|
|
11897
|
+
const outcome = classifyTransferResponse({
|
|
11898
|
+
status: answer.status,
|
|
11899
|
+
headers: answer.header,
|
|
11900
|
+
details: served?.details ?? null,
|
|
11901
|
+
receipt: read.receipt,
|
|
11902
|
+
});
|
|
11903
|
+
if (outcome.verdict === TRANSFER_VERDICT.OK)
|
|
11904
|
+
return { outcome, failure: null };
|
|
11905
|
+
const { status } = answer;
|
|
11906
|
+
if (outcome.verdict === TRANSFER_VERDICT.REFUSED && outcome.coreCode !== null) {
|
|
11907
|
+
const message = served?.message ?? REFUSAL_WORDING.get(outcome.coreCode) ?? REFUSED_MESSAGE;
|
|
11908
|
+
return {
|
|
11909
|
+
outcome,
|
|
11910
|
+
failure: new UploadApiError(message, 'upload_refused', status, { status, coreCode: outcome.coreCode }, outcome),
|
|
11911
|
+
};
|
|
11912
|
+
}
|
|
11913
|
+
if (outcome.verdict === TRANSFER_VERDICT.DEFERRED) {
|
|
11914
|
+
return {
|
|
11915
|
+
outcome,
|
|
11916
|
+
failure: new UploadApiError(RECEIVED_PUBLISHING_MESSAGE, 'upload_received_publishing', status, { status }, outcome),
|
|
11917
|
+
};
|
|
11918
|
+
}
|
|
11919
|
+
const detail = summarizeErrorBody(answer.body);
|
|
11920
|
+
return {
|
|
11921
|
+
outcome,
|
|
11922
|
+
failure: new UploadApiError(read.failureMessage, read.code, status, {
|
|
11923
|
+
status,
|
|
11924
|
+
...(detail ? { serverDetail: detail } : {}),
|
|
11925
|
+
...(outcome.coreCode !== null ? { coreCode: outcome.coreCode } : {}),
|
|
11926
|
+
}, outcome),
|
|
11927
|
+
};
|
|
11928
|
+
}
|
|
11147
11929
|
const SESSION_CREATION = {
|
|
11148
11930
|
name: 'Upload session creation',
|
|
11149
11931
|
code: 'tus_create_failed',
|
|
11150
|
-
|
|
11932
|
+
failureMessage: 'The upload could not be started: the server did not open an upload session.',
|
|
11151
11933
|
networkMessage: 'Unable to start the upload. Please check your connection and try again.',
|
|
11934
|
+
receipt: false,
|
|
11152
11935
|
};
|
|
11153
11936
|
const RESUME_CHECK = {
|
|
11154
11937
|
name: 'Upload resume check',
|
|
11155
11938
|
code: 'resume_check_failed',
|
|
11156
|
-
|
|
11939
|
+
failureMessage: 'Upload could not be resumed: the server no longer recognizes this upload session.',
|
|
11157
11940
|
networkMessage: 'Unable to resume upload. Please check your connection and try again.',
|
|
11941
|
+
receipt: false,
|
|
11942
|
+
timeoutMs: HEAD_AND_RECEIPT_TIMEOUT_MS,
|
|
11158
11943
|
};
|
|
11159
11944
|
const FINALIZATION_CHECK = {
|
|
11160
11945
|
name: 'Upload finalization check',
|
|
11161
11946
|
code: 'finalization_check_failed',
|
|
11162
|
-
|
|
11947
|
+
failureMessage: 'Upload could not be confirmed: the server did not finalize the file.',
|
|
11163
11948
|
networkMessage: 'Unable to confirm upload. Please check your connection and try again.',
|
|
11949
|
+
receipt: true,
|
|
11950
|
+
timeoutMs: HEAD_AND_RECEIPT_TIMEOUT_MS,
|
|
11164
11951
|
};
|
|
11165
11952
|
class UploadApi extends SparkVaultApi {
|
|
11166
11953
|
constructor(config) {
|
|
@@ -11176,8 +11963,19 @@ class UploadApi extends SparkVaultApi {
|
|
|
11176
11963
|
this.vaultInfoMemo = new Map();
|
|
11177
11964
|
this.config = config;
|
|
11178
11965
|
}
|
|
11179
|
-
|
|
11180
|
-
|
|
11966
|
+
/**
|
|
11967
|
+
* The shared transport's errors. It raises a request that got no answer (a
|
|
11968
|
+
* dropped connection, a timeout) with status 0, which the transfer policy
|
|
11969
|
+
* retries, a cancel aside; a refused API call it raises with its status is
|
|
11970
|
+
* Core's verdict, never a transfer's, so of the policy's reading it carries
|
|
11971
|
+
* only the floor Core named (`retryAfterMs`), for whoever acts on the
|
|
11972
|
+
* refusal.
|
|
11973
|
+
*/
|
|
11974
|
+
makeError(message, code, statusCode, details, retryAfterMs = null) {
|
|
11975
|
+
const unanswered = statusCode === 0 && code !== 'cancelled';
|
|
11976
|
+
return new UploadApiError(message, code, statusCode, details, unanswered
|
|
11977
|
+
? classifyTransferResponse({ status: 0 })
|
|
11978
|
+
: { verdict: TRANSFER_VERDICT.REFUSED, retryAfterMs, offset: null, coreCode: null });
|
|
11181
11979
|
}
|
|
11182
11980
|
/**
|
|
11183
11981
|
* Issue a request to a Core route and unwrap the standard `{ data, meta }`
|
|
@@ -11294,13 +12092,22 @@ class UploadApi extends SparkVaultApi {
|
|
|
11294
12092
|
* every server-reported offset, and honors the session abort signal plus
|
|
11295
12093
|
* per-request timeouts.
|
|
11296
12094
|
*
|
|
11297
|
-
*
|
|
11298
|
-
*
|
|
11299
|
-
*
|
|
12095
|
+
* Every answer is read through the transfer policy
|
|
12096
|
+
* (`@sparkvault/app-sdk/transfer-retry`) and every retry spends one budget
|
|
12097
|
+
* ({@link TusTransfer}). A chunk that fails in transit is resent only from
|
|
12098
|
+
* an offset the server just named — a 409's own `Upload-Offset` at once,
|
|
12099
|
+
* otherwise a HEAD after the backoff ({@link offsetAfterFailure}); a session
|
|
12100
|
+
* the server no longer holds throws `session_gone`, which only a new upload
|
|
12101
|
+
* recovers from (any code of Core's the server named rides
|
|
12102
|
+
* `details.coreCode`); an upload Core refused for good (a full storage pool,
|
|
12103
|
+
* a later upload that replaced it) throws `upload_refused` in Core's words,
|
|
12104
|
+
* which no new upload recovers from. While the browser is offline, the loop
|
|
12105
|
+
* waits for the network instead of spending attempts.
|
|
11300
12106
|
*
|
|
11301
12107
|
* Resolves only once the server has confirmed finalization
|
|
11302
12108
|
* ({@link confirmServerFinalized}), so a caller that gets a resolved promise
|
|
11303
|
-
* is always looking at a published ingot
|
|
12109
|
+
* is always looking at a published ingot; a publication the server still
|
|
12110
|
+
* defers at the idle limit throws `upload_received_publishing`.
|
|
11304
12111
|
*/
|
|
11305
12112
|
async uploadFileToForge(file, forgeUrl, onProgress) {
|
|
11306
12113
|
if (typeof XMLHttpRequest === 'undefined') {
|
|
@@ -11316,15 +12123,21 @@ class UploadApi extends SparkVaultApi {
|
|
|
11316
12123
|
// The session this upload runs in: a close ends this upload even if a new
|
|
11317
12124
|
// session starts before the loop next looks.
|
|
11318
12125
|
const sessionSignal = this.getAbortSignal();
|
|
11319
|
-
const
|
|
12126
|
+
const budget = createTransferBudget();
|
|
12127
|
+
const session = await this.createTusSession(target.endpoint, target.istk, file.size, budget, sessionSignal);
|
|
11320
12128
|
// Every chunk carries the file's bytes, so the session must live under the
|
|
11321
12129
|
// endpoint it was created at.
|
|
11322
12130
|
const uploadUrl = resolveForgeSessionUrl(session.location, target.endpoint);
|
|
11323
12131
|
if (!uploadUrl) {
|
|
11324
12132
|
throw new UploadApiError('Upload session is outside the upload endpoint', 'tus_create_failed', 0);
|
|
11325
12133
|
}
|
|
11326
|
-
|
|
11327
|
-
|
|
12134
|
+
const transfer = {
|
|
12135
|
+
uploadUrl,
|
|
12136
|
+
totalSize: file.size,
|
|
12137
|
+
chunkSize: session.chunkSize,
|
|
12138
|
+
budget,
|
|
12139
|
+
sessionSignal,
|
|
12140
|
+
};
|
|
11328
12141
|
// Retries make raw progress non-monotonic (a chunk that streamed to 90%
|
|
11329
12142
|
// then failed re-reports from its start on resend); callers get only the
|
|
11330
12143
|
// high-water mark so a progress bar never runs backwards.
|
|
@@ -11337,55 +12150,90 @@ class UploadApi extends SparkVaultApi {
|
|
|
11337
12150
|
}
|
|
11338
12151
|
}
|
|
11339
12152
|
: undefined;
|
|
11340
|
-
|
|
12153
|
+
let offset = 0;
|
|
12154
|
+
for (;;) {
|
|
11341
12155
|
if (sessionSignal.aborted) {
|
|
11342
|
-
throw
|
|
12156
|
+
throw cancelledError();
|
|
12157
|
+
}
|
|
12158
|
+
// One exit, one receipt: however the loop learned that every byte is on
|
|
12159
|
+
// the server (a chunk's 204, a HEAD, a 409), publication is confirmed
|
|
12160
|
+
// before the upload resolves.
|
|
12161
|
+
if (offset === file.size) {
|
|
12162
|
+
const receipt = await this.confirmServerFinalized(transfer);
|
|
12163
|
+
if (receipt.published)
|
|
12164
|
+
return;
|
|
12165
|
+
offset = receipt.resumeAt;
|
|
12166
|
+
continue;
|
|
11343
12167
|
}
|
|
11344
12168
|
const chunkEnd = Math.min(offset + session.chunkSize, file.size);
|
|
11345
12169
|
try {
|
|
11346
|
-
offset = await this.patchChunk(
|
|
11347
|
-
|
|
11348
|
-
continue;
|
|
12170
|
+
offset = await this.patchChunk(transfer, file.slice(offset, chunkEnd), offset, monotonicProgress);
|
|
12171
|
+
transfer.budget.progressed();
|
|
11349
12172
|
}
|
|
11350
12173
|
catch (error) {
|
|
11351
|
-
|
|
11352
|
-
if (failedAttempts >= CHUNK_MAX_ATTEMPTS || !isRetryableTransferFailure(error)) {
|
|
11353
|
-
throw error;
|
|
11354
|
-
}
|
|
12174
|
+
offset = await this.offsetAfterFailure(transfer, error, offset);
|
|
11355
12175
|
}
|
|
11356
|
-
|
|
11357
|
-
|
|
11358
|
-
|
|
11359
|
-
|
|
11360
|
-
|
|
11361
|
-
|
|
11362
|
-
|
|
11363
|
-
|
|
11364
|
-
|
|
11365
|
-
|
|
11366
|
-
|
|
11367
|
-
|
|
11368
|
-
|
|
11369
|
-
|
|
11370
|
-
|
|
11371
|
-
|
|
11372
|
-
|
|
11373
|
-
|
|
11374
|
-
|
|
11375
|
-
|
|
11376
|
-
|
|
11377
|
-
|
|
12176
|
+
}
|
|
12177
|
+
}
|
|
12178
|
+
/**
|
|
12179
|
+
* Where the upload stands after a failed chunk PATCH, in the server's words:
|
|
12180
|
+
* a 409's own `Upload-Offset` at once, otherwise the session's HEAD after
|
|
12181
|
+
* the backoff. The failed chunk may have landed with its answer lost, and a
|
|
12182
|
+
* PATCH at the client's stale offset is refused, so no chunk is ever sent
|
|
12183
|
+
* again at an offset the server did not just name. The blip that killed the
|
|
12184
|
+
* PATCH is also the likeliest thing to kill the HEAD moments later, so the
|
|
12185
|
+
* HEAD is retried the same way, out of the same budget.
|
|
12186
|
+
*/
|
|
12187
|
+
async offsetAfterFailure(transfer, error, sentOffset) {
|
|
12188
|
+
let failure = transferFailure(error);
|
|
12189
|
+
for (;;) {
|
|
12190
|
+
if (failure.verdict === TRANSFER_VERDICT.RESYNC) {
|
|
12191
|
+
return this.resyncedOffset(transfer, failure, sentOffset);
|
|
12192
|
+
}
|
|
12193
|
+
await this.backOff(transfer, failure);
|
|
12194
|
+
try {
|
|
12195
|
+
const serverOffset = await this.readResumeOffset(transfer);
|
|
12196
|
+
if (serverOffset > sentOffset) {
|
|
12197
|
+
// Bytes reached the server despite the failure, so the transfer is
|
|
12198
|
+
// alive: the budget starts over rather than being spent down across
|
|
12199
|
+
// the many chunks of a large file.
|
|
12200
|
+
transfer.budget.progressed();
|
|
11378
12201
|
}
|
|
12202
|
+
return serverOffset;
|
|
11379
12203
|
}
|
|
11380
|
-
|
|
11381
|
-
|
|
11382
|
-
// alive: the budget is earned back rather than spent down across the
|
|
11383
|
-
// many chunks of a large file.
|
|
11384
|
-
failedAttempts = 0;
|
|
12204
|
+
catch (headError) {
|
|
12205
|
+
failure = transferFailure(headError);
|
|
11385
12206
|
}
|
|
11386
|
-
offset = serverOffset;
|
|
11387
12207
|
}
|
|
11388
|
-
|
|
12208
|
+
}
|
|
12209
|
+
/**
|
|
12210
|
+
* Continue from the offset a 409 named, at once and without a HEAD: the
|
|
12211
|
+
* server just said where the session stands. Past what this client sent,
|
|
12212
|
+
* the server holds more than it knew, which is progress; anywhere else the
|
|
12213
|
+
* answer contradicts the request, so it spends the budget like any failure
|
|
12214
|
+
* and repeating it ends the upload.
|
|
12215
|
+
*/
|
|
12216
|
+
resyncedOffset(transfer, failure, sentOffset) {
|
|
12217
|
+
const offset = this.checkResumeOffset(failure.serverOffset, transfer);
|
|
12218
|
+
if (offset > sentOffset) {
|
|
12219
|
+
transfer.budget.progressed();
|
|
12220
|
+
}
|
|
12221
|
+
else if (!transfer.budget.failed(TRANSFER_VERDICT.RESYNC)) {
|
|
12222
|
+
throw failure;
|
|
12223
|
+
}
|
|
12224
|
+
return offset;
|
|
12225
|
+
}
|
|
12226
|
+
/**
|
|
12227
|
+
* Wait out the backoff of a failed or deferred request to the upload's
|
|
12228
|
+
* session ({@link waitToRetry}, keyed by the session URL), or throw: a gone
|
|
12229
|
+
* session as `session_gone`, an answer no retry follows as it is, and the
|
|
12230
|
+
* last failure, or the deferral, once the budget is spent.
|
|
12231
|
+
*/
|
|
12232
|
+
async backOff(transfer, failure) {
|
|
12233
|
+
if (failure.verdict === TRANSFER_VERDICT.GONE) {
|
|
12234
|
+
throw sessionGoneError(failure);
|
|
12235
|
+
}
|
|
12236
|
+
await waitToRetry(transfer.budget, failure, transfer.uploadUrl, transfer.sessionSignal);
|
|
11389
12237
|
}
|
|
11390
12238
|
/**
|
|
11391
12239
|
* Confirm the server finalized a fully received upload — the one receipt
|
|
@@ -11399,42 +12247,62 @@ class UploadApi extends SparkVaultApi {
|
|
|
11399
12247
|
* re-drive — it short-circuits to 204 on an already-finalized session, and
|
|
11400
12248
|
* on a received-but-unfinalized one it answers only after publication.
|
|
11401
12249
|
*
|
|
11402
|
-
*
|
|
11403
|
-
*
|
|
11404
|
-
*
|
|
11405
|
-
*
|
|
12250
|
+
* While another request finalizes the receipt answers 409 with
|
|
12251
|
+
* `Retry-After`, polled again after the policy's backoff as a failure; while
|
|
12252
|
+
* the publication is deferred it answers 503 with `Retry-After`, a deferral
|
|
12253
|
+
* the receipt is polled through without spending a failure, each ask after
|
|
12254
|
+
* a longer backoff, until the idle limit throws
|
|
12255
|
+
* `upload_received_publishing`: every byte is on the server, which finishes
|
|
12256
|
+
* the publication on its own. A 503 naming no `Retry-After` is no deferral
|
|
12257
|
+
* of Forge's, so it is polled as a failure. A 400 is the server's verdict
|
|
12258
|
+
* and fails immediately, as does the refusal Core decided
|
|
12259
|
+
* (`upload_refused`); a 409 naming an earlier offset means bytes are
|
|
12260
|
+
* missing, and the upload continues from there.
|
|
11406
12261
|
*/
|
|
11407
|
-
async confirmServerFinalized(
|
|
12262
|
+
async confirmServerFinalized(transfer) {
|
|
11408
12263
|
let consecutiveTimeouts = 0;
|
|
11409
|
-
for (
|
|
12264
|
+
for (;;) {
|
|
11410
12265
|
try {
|
|
11411
|
-
await this.tusRequest(uploadUrl, {
|
|
12266
|
+
await this.tusRequest(transfer.uploadUrl, {
|
|
11412
12267
|
method: 'PATCH',
|
|
11413
12268
|
headers: {
|
|
11414
12269
|
'Tus-Resumable': TUS_VERSION,
|
|
11415
|
-
'Upload-Offset': String(totalSize),
|
|
12270
|
+
'Upload-Offset': String(transfer.totalSize),
|
|
11416
12271
|
'Content-Type': 'application/offset+octet-stream',
|
|
11417
12272
|
},
|
|
11418
12273
|
}, FINALIZATION_CHECK);
|
|
11419
|
-
return;
|
|
12274
|
+
return { published: true };
|
|
11420
12275
|
}
|
|
11421
12276
|
catch (error) {
|
|
11422
|
-
const
|
|
12277
|
+
const failure = transferFailure(error);
|
|
11423
12278
|
// Any answer at all — a 409 above all — proves someone is on the other
|
|
11424
12279
|
// end, so the timeout tally starts over.
|
|
11425
|
-
consecutiveTimeouts =
|
|
11426
|
-
if (
|
|
11427
|
-
|
|
11428
|
-
!isRetryableTransferFailure(error)) {
|
|
11429
|
-
throw error;
|
|
12280
|
+
consecutiveTimeouts = failure.code === 'timeout' ? consecutiveTimeouts + 1 : 0;
|
|
12281
|
+
if (consecutiveTimeouts >= FINALIZE_MAX_CONSECUTIVE_TIMEOUTS) {
|
|
12282
|
+
throw failure;
|
|
11430
12283
|
}
|
|
11431
|
-
|
|
12284
|
+
if (failure.verdict === TRANSFER_VERDICT.RESYNC) {
|
|
12285
|
+
const resumeAt = this.resyncedOffset(transfer, failure, transfer.totalSize);
|
|
12286
|
+
if (resumeAt < transfer.totalSize)
|
|
12287
|
+
return { published: false, resumeAt };
|
|
12288
|
+
continue;
|
|
12289
|
+
}
|
|
12290
|
+
await this.backOff(transfer, failure);
|
|
11432
12291
|
}
|
|
11433
12292
|
}
|
|
11434
12293
|
}
|
|
11435
12294
|
/**
|
|
11436
|
-
* Read the offset a failed chunk should resume from
|
|
11437
|
-
*
|
|
12295
|
+
* Read the offset a failed chunk should resume from, from the session's
|
|
12296
|
+
* HEAD. At the full offset it proves receipt only, published or not, so the
|
|
12297
|
+
* loop then takes the receipt.
|
|
12298
|
+
*/
|
|
12299
|
+
async readResumeOffset(transfer) {
|
|
12300
|
+
return this.checkResumeOffset(await this.headUploadOffset(transfer.uploadUrl, RESUME_CHECK), transfer);
|
|
12301
|
+
}
|
|
12302
|
+
/**
|
|
12303
|
+
* Judge an offset the server named for the upload to resume from — a HEAD's,
|
|
12304
|
+
* or a 409's `Upload-Offset` — the one place a server-reported resume point
|
|
12305
|
+
* is judged.
|
|
11438
12306
|
*
|
|
11439
12307
|
* Forge commits a chunk before it answers, so a PATCH that died in transit
|
|
11440
12308
|
* may have landed in full or not at all (never in part — the chunk object
|
|
@@ -11442,21 +12310,19 @@ class UploadApi extends SparkVaultApi {
|
|
|
11442
12310
|
* persisted offset knows which, and the client's arithmetic is worthless
|
|
11443
12311
|
* here.
|
|
11444
12312
|
*
|
|
11445
|
-
* Two contracts disqualify an answer. TUS sanity: an
|
|
11446
|
-
* declared total would end the loop early and report a
|
|
11447
|
-
* complete, the same trap {@link patchChunk} guards
|
|
11448
|
-
* offset. Forge chunk granularity: a session
|
|
11449
|
-
* committed chunks, so an offset that is neither
|
|
11450
|
-
* end is a corrupt session, and resuming from it
|
|
11451
|
-
* non-final chunk Forge rejects anyway.
|
|
12313
|
+
* Two contracts disqualify an answer (`resumeOffsetProblem`). TUS sanity: an
|
|
12314
|
+
* offset past the declared total would end the loop early and report a
|
|
12315
|
+
* partial upload as complete, the same trap {@link patchChunk} guards
|
|
12316
|
+
* against on a PATCH's own offset. Forge chunk granularity: a session
|
|
12317
|
+
* advances only in whole committed chunks, so an offset that is neither
|
|
12318
|
+
* chunk-aligned nor the file end is a corrupt session, and resuming from it
|
|
12319
|
+
* would send a short non-final chunk Forge rejects anyway.
|
|
11452
12320
|
*/
|
|
11453
|
-
|
|
11454
|
-
const
|
|
11455
|
-
if (offset
|
|
11456
|
-
|
|
11457
|
-
|
|
11458
|
-
if (offset % chunkSize !== 0 && offset !== totalSize) {
|
|
11459
|
-
throw new UploadApiError(`Server returned misaligned upload offset (${offset})`, 'invalid_offset', 0);
|
|
12321
|
+
checkResumeOffset(offset, transfer) {
|
|
12322
|
+
const problem = resumeOffsetProblem(offset, transfer);
|
|
12323
|
+
if (offset === null || problem !== null) {
|
|
12324
|
+
const shape = problem === RESUME_OFFSET_PROBLEM.MISALIGNED ? 'misaligned' : 'invalid';
|
|
12325
|
+
throw new UploadApiError(`Server returned ${shape} upload offset (${offset})`, 'invalid_offset', 0);
|
|
11460
12326
|
}
|
|
11461
12327
|
return offset;
|
|
11462
12328
|
}
|
|
@@ -11464,16 +12330,39 @@ class UploadApi extends SparkVaultApi {
|
|
|
11464
12330
|
* Create the TUS upload session. Forge reads only `Tus-Resumable`,
|
|
11465
12331
|
* `Upload-Length`, and `X-ISTK` on create, and returns the session URL in
|
|
11466
12332
|
* `Location` (possibly relative) plus its chunk size in `X-Chunk-Size`.
|
|
12333
|
+
*
|
|
12334
|
+
* A create the transfer policy calls RETRY (no answer, 408, 425, 429, a 5xx)
|
|
12335
|
+
* is sent again under the upload's budget: Forge refuses such a create
|
|
12336
|
+
* before it claims the token, or hands the claim back on a transient
|
|
12337
|
+
* key-service failure (503 + `Retry-After`), so the same ISTK opens the
|
|
12338
|
+
* session on a later attempt. Every other answer is final, a 401 included:
|
|
12339
|
+
* the token was already used, by an earlier attempt whose answer was lost,
|
|
12340
|
+
* and no `Location` survives to continue that session from. No session URL
|
|
12341
|
+
* exists yet to spread the retries by, and the ISTK never feeds one, so
|
|
12342
|
+
* they spread by a key of the endpoint (`transferJitterKey`).
|
|
11467
12343
|
*/
|
|
11468
|
-
async createTusSession(endpoint, istk, totalSize) {
|
|
11469
|
-
const
|
|
11470
|
-
|
|
11471
|
-
|
|
11472
|
-
|
|
11473
|
-
|
|
11474
|
-
|
|
11475
|
-
|
|
11476
|
-
|
|
12344
|
+
async createTusSession(endpoint, istk, totalSize, budget, sessionSignal) {
|
|
12345
|
+
const jitterKey = transferJitterKey(endpoint);
|
|
12346
|
+
let response;
|
|
12347
|
+
for (;;) {
|
|
12348
|
+
try {
|
|
12349
|
+
({ response } = await this.tusRequest(endpoint, {
|
|
12350
|
+
method: 'POST',
|
|
12351
|
+
headers: {
|
|
12352
|
+
'Tus-Resumable': TUS_VERSION,
|
|
12353
|
+
'Upload-Length': String(totalSize),
|
|
12354
|
+
'X-ISTK': istk,
|
|
12355
|
+
},
|
|
12356
|
+
}, SESSION_CREATION));
|
|
12357
|
+
break;
|
|
12358
|
+
}
|
|
12359
|
+
catch (error) {
|
|
12360
|
+
const failure = transferFailure(error);
|
|
12361
|
+
if (failure.verdict !== TRANSFER_VERDICT.RETRY)
|
|
12362
|
+
throw failure;
|
|
12363
|
+
await waitToRetry(budget, failure, jitterKey, sessionSignal);
|
|
12364
|
+
}
|
|
12365
|
+
}
|
|
11477
12366
|
const location = response.headers.get('Location');
|
|
11478
12367
|
if (!location) {
|
|
11479
12368
|
throw new UploadApiError('Server did not return upload location', 'tus_create_failed', response.status);
|
|
@@ -11486,23 +12375,31 @@ class UploadApi extends SparkVaultApi {
|
|
|
11486
12375
|
if (chunkSize === null) {
|
|
11487
12376
|
throw new UploadApiError('Server did not return a valid X-Chunk-Size', 'tus_create_failed', response.status, { header: 'X-Chunk-Size', received: chunkSizeHeader });
|
|
11488
12377
|
}
|
|
12378
|
+
// The session exists: the server confirmed progress.
|
|
12379
|
+
budget.progressed();
|
|
11489
12380
|
return { location, chunkSize };
|
|
11490
12381
|
}
|
|
11491
12382
|
/**
|
|
11492
12383
|
* PATCH one chunk with XMLHttpRequest (fetch exposes no upload progress).
|
|
11493
|
-
* Resolves with the server-confirmed offset for the next iteration
|
|
12384
|
+
* Resolves with the server-confirmed offset for the next iteration; a
|
|
12385
|
+
* failure carries the transfer policy's verdict on its answer, read here.
|
|
11494
12386
|
*
|
|
11495
12387
|
* The server's `Upload-Offset` is validated, never trusted: it must be a
|
|
11496
|
-
*
|
|
12388
|
+
* whole number that strictly advances past this chunk's start (this client
|
|
11497
12389
|
* never sends an empty chunk, so a non-advancing 2xx would loop forever)
|
|
11498
12390
|
* and never exceeds the file size (an inflated offset would skip real
|
|
11499
12391
|
* chunks and report a partial upload as success).
|
|
12392
|
+
*
|
|
12393
|
+
* Bytes leaving are a sign of life: they restart the transfer's idle clock
|
|
12394
|
+
* (never its failure count, which only the server's confirmation resets), so
|
|
12395
|
+
* a slow chunk is never counted as idle time.
|
|
11500
12396
|
*/
|
|
11501
|
-
patchChunk(
|
|
12397
|
+
patchChunk(transfer, chunk, chunkStart, onProgress) {
|
|
12398
|
+
const { uploadUrl, totalSize, budget } = transfer;
|
|
11502
12399
|
return new Promise((resolve, reject) => {
|
|
11503
|
-
const closeSignal =
|
|
12400
|
+
const closeSignal = transfer.sessionSignal;
|
|
11504
12401
|
if (closeSignal.aborted) {
|
|
11505
|
-
reject(
|
|
12402
|
+
reject(cancelledError());
|
|
11506
12403
|
return;
|
|
11507
12404
|
}
|
|
11508
12405
|
const xhr = new XMLHttpRequest();
|
|
@@ -11532,28 +12429,33 @@ class UploadApi extends SparkVaultApi {
|
|
|
11532
12429
|
closeSignal.addEventListener('abort', onCloseAbort);
|
|
11533
12430
|
xhr.upload.onprogress = (event) => {
|
|
11534
12431
|
resetWatchdog();
|
|
12432
|
+
budget.alive();
|
|
11535
12433
|
if (event.lengthComputable) {
|
|
11536
12434
|
onProgress?.(chunkStart + event.loaded, totalSize);
|
|
11537
12435
|
}
|
|
11538
12436
|
};
|
|
11539
12437
|
xhr.onload = () => {
|
|
11540
|
-
|
|
11541
|
-
|
|
11542
|
-
|
|
11543
|
-
|
|
11544
|
-
|
|
11545
|
-
|
|
11546
|
-
|
|
11547
|
-
finish(() =>
|
|
12438
|
+
const { status } = xhr;
|
|
12439
|
+
const { outcome, failure } = readTransferAnswer({
|
|
12440
|
+
status,
|
|
12441
|
+
header: (name) => xhr.getResponseHeader(name),
|
|
12442
|
+
body: status >= 200 && status < 300 ? '' : xhr.responseText,
|
|
12443
|
+
}, { receipt: false, code: 'chunk_upload_failed', failureMessage: `Chunk upload failed with status ${status}` });
|
|
12444
|
+
if (failure) {
|
|
12445
|
+
finish(() => reject(failure));
|
|
12446
|
+
return;
|
|
11548
12447
|
}
|
|
11549
|
-
|
|
11550
|
-
|
|
12448
|
+
const newOffset = outcome.offset;
|
|
12449
|
+
if (newOffset === null || newOffset <= chunkStart || newOffset > totalSize) {
|
|
12450
|
+
finish(() => reject(new UploadApiError(`Server returned invalid upload offset (${xhr.getResponseHeader('Upload-Offset')})`, 'invalid_offset', xhr.status)));
|
|
12451
|
+
return;
|
|
11551
12452
|
}
|
|
12453
|
+
finish(() => resolve(newOffset));
|
|
11552
12454
|
};
|
|
11553
|
-
xhr.onerror = () => finish(() => reject(new UploadApiError('Chunk upload failed', 'network_error', 0)));
|
|
12455
|
+
xhr.onerror = () => finish(() => reject(new UploadApiError('Chunk upload failed', 'network_error', 0, undefined, classifyTransferResponse({ status: 0 }))));
|
|
11554
12456
|
xhr.onabort = () => finish(() => reject(timedOut
|
|
11555
|
-
? new UploadApiError(`Chunk upload timed out after ${CHUNK_INACTIVITY_TIMEOUT_MS}ms of inactivity`, 'timeout', 0)
|
|
11556
|
-
:
|
|
12457
|
+
? new UploadApiError(`Chunk upload timed out after ${CHUNK_INACTIVITY_TIMEOUT_MS}ms of inactivity`, 'timeout', 0, undefined, classifyTransferResponse({ status: 0 }))
|
|
12458
|
+
: cancelledError()));
|
|
11557
12459
|
xhr.open('PATCH', uploadUrl);
|
|
11558
12460
|
xhr.setRequestHeader('Tus-Resumable', TUS_VERSION);
|
|
11559
12461
|
xhr.setRequestHeader('Upload-Offset', String(chunkStart));
|
|
@@ -11569,13 +12471,11 @@ class UploadApi extends SparkVaultApi {
|
|
|
11569
12471
|
* @param check - Which caller this read serves; shapes the failure copy.
|
|
11570
12472
|
*/
|
|
11571
12473
|
async headUploadOffset(uploadUrl, check) {
|
|
11572
|
-
const response = await this.tusRequest(uploadUrl, { method: 'HEAD', headers: { 'Tus-Resumable': TUS_VERSION } }, check);
|
|
11573
|
-
|
|
11574
|
-
const offset = header !== null ? parseInt(header, 10) : NaN;
|
|
11575
|
-
if (!Number.isFinite(offset) || offset < 0) {
|
|
12474
|
+
const { response, outcome } = await this.tusRequest(uploadUrl, { method: 'HEAD', headers: { 'Tus-Resumable': TUS_VERSION } }, check);
|
|
12475
|
+
if (outcome.offset === null) {
|
|
11576
12476
|
throw new UploadApiError(`${check.name} returned an invalid offset`, check.code, response.status);
|
|
11577
12477
|
}
|
|
11578
|
-
return offset;
|
|
12478
|
+
return outcome.offset;
|
|
11579
12479
|
}
|
|
11580
12480
|
/**
|
|
11581
12481
|
* Issue one bodyless TUS request: the single transport behind every
|
|
@@ -11585,26 +12485,33 @@ class UploadApi extends SparkVaultApi {
|
|
|
11585
12485
|
* Uses the raw response rather than the JSON envelope helper: TUS responses
|
|
11586
12486
|
* carry an empty body and surface state in headers. Runs through the one SDK
|
|
11587
12487
|
* transport (session close signal, deadline, failure classification) and
|
|
11588
|
-
* resolves only on a 2xx
|
|
12488
|
+
* resolves only on a 2xx, with the transfer policy's reading of it, so no
|
|
12489
|
+
* caller has to re-check `response.ok`; a non-2xx throws carrying the
|
|
12490
|
+
* policy's verdict on its answer.
|
|
11589
12491
|
*
|
|
11590
12492
|
* @param check - Which caller this request serves; shapes the failure copy.
|
|
11591
12493
|
*/
|
|
11592
12494
|
tusRequest(uploadUrl, init, check) {
|
|
12495
|
+
const timeoutMs = check.timeoutMs ?? this.timeoutMs;
|
|
11593
12496
|
return this.send(uploadUrl, { method: init.method, headers: init.headers }, {
|
|
11594
12497
|
cancelled: 'Upload cancelled',
|
|
11595
|
-
timeout: `${check.name} timed out after ${
|
|
12498
|
+
timeout: `${check.name} timed out after ${timeoutMs}ms`,
|
|
11596
12499
|
network: check.networkMessage,
|
|
11597
12500
|
}, async (response) => {
|
|
11598
|
-
|
|
11599
|
-
|
|
11600
|
-
|
|
11601
|
-
|
|
11602
|
-
|
|
11603
|
-
|
|
11604
|
-
|
|
11605
|
-
|
|
11606
|
-
|
|
11607
|
-
|
|
12501
|
+
// A failed answer's body is read whole: an unread body pins its
|
|
12502
|
+
// connection, and a retried receipt would strand one per attempt.
|
|
12503
|
+
// Forge's error envelope in it is what names the refusal Core
|
|
12504
|
+
// decided, and otherwise the only server-side detail this client
|
|
12505
|
+
// ever sees, so it rides along in `details` for support.
|
|
12506
|
+
const { outcome, failure } = readTransferAnswer({
|
|
12507
|
+
status: response.status,
|
|
12508
|
+
header: (name) => response.headers.get(name),
|
|
12509
|
+
body: response.ok ? '' : await response.text().catch(() => ''),
|
|
12510
|
+
}, check);
|
|
12511
|
+
if (failure)
|
|
12512
|
+
throw failure;
|
|
12513
|
+
return { response, outcome };
|
|
12514
|
+
}, timeoutMs);
|
|
11608
12515
|
}
|
|
11609
12516
|
}
|
|
11610
12517
|
|
|
@@ -13849,7 +14756,34 @@ class UploadRenderer {
|
|
|
13849
14756
|
statusCode: error.statusCode,
|
|
13850
14757
|
});
|
|
13851
14758
|
}
|
|
13852
|
-
else if (error.
|
|
14759
|
+
else if (error.code === 'upload_received_publishing') {
|
|
14760
|
+
// Every byte reached the server, which is still saving the file and
|
|
14761
|
+
// finishes it on its own: nothing failed, and nothing is left to do.
|
|
14762
|
+
// The host still hears it through onError, with this code, which
|
|
14763
|
+
// tells it never to upload the file again.
|
|
14764
|
+
this.setState({
|
|
14765
|
+
view: 'error',
|
|
14766
|
+
title: 'Upload Received',
|
|
14767
|
+
message: error.message,
|
|
14768
|
+
code: error.code,
|
|
14769
|
+
statusCode: error.statusCode,
|
|
14770
|
+
});
|
|
14771
|
+
}
|
|
14772
|
+
else if (error.code === 'upload_refused') {
|
|
14773
|
+
// Core refused the upload for good, in its own words (whom to contact
|
|
14774
|
+
// about a full storage pool, or the later upload that replaced this
|
|
14775
|
+
// one): a sentence that never asks for the file again.
|
|
14776
|
+
this.setState({
|
|
14777
|
+
view: 'error',
|
|
14778
|
+
title: 'Upload Not Saved',
|
|
14779
|
+
message: error.message,
|
|
14780
|
+
code: error.code,
|
|
14781
|
+
statusCode: error.statusCode,
|
|
14782
|
+
});
|
|
14783
|
+
}
|
|
14784
|
+
else if (error.statusCode === 404 && error.code !== 'session_gone') {
|
|
14785
|
+
// A vault or upload route that does not exist. A gone upload session
|
|
14786
|
+
// can answer 404 too, and its own sentence says what became of the file.
|
|
13853
14787
|
this.setState({
|
|
13854
14788
|
view: 'error',
|
|
13855
14789
|
title: 'Upload Page Not Found',
|
|
@@ -14473,38 +15407,13 @@ function readIngotAccess(entry) {
|
|
|
14473
15407
|
};
|
|
14474
15408
|
}
|
|
14475
15409
|
|
|
14476
|
-
/**
|
|
14477
|
-
* Whether sending the SAME request again can succeed, read from its HTTP
|
|
14478
|
-
* status: the one retry rule every client and every provider adapter applies.
|
|
14479
|
-
*
|
|
14480
|
-
* A retry rule restated beside every client drifts, and the copy that drifted
|
|
14481
|
-
* decides whether a deliverable message is retried or abandoned, or whether a
|
|
14482
|
-
* download is tried again. Each caller keeps its provider's own extras on top of
|
|
14483
|
-
* this rule (a success body, a dead-token reason, a vendor error name).
|
|
14484
|
-
*
|
|
14485
|
-
* Browser-safe and import-free: sdk-js bundles it and sdk-mobile mirrors it.
|
|
14486
|
-
*/
|
|
14487
|
-
|
|
14488
|
-
/**
|
|
14489
|
-
* Is this HTTP status one a retry of the same request can turn into a success?
|
|
14490
|
-
*
|
|
14491
|
-
* RFC 9110: 408 means the server never received the whole request, 429 that it
|
|
14492
|
-
* throttled it, and a 5xx that it failed; every other status is the server's
|
|
14493
|
-
* verdict on this exact request. A caller that got no response at all (a network
|
|
14494
|
-
* error, a timeout) has no status to pass and decides that case itself.
|
|
14495
|
-
*
|
|
14496
|
-
* @param {number} status
|
|
14497
|
-
* @returns {boolean}
|
|
14498
|
-
*/
|
|
14499
|
-
function isTransientHttpStatus(status) {
|
|
14500
|
-
return status === 408 || status === 429 || status >= 500;
|
|
14501
|
-
}
|
|
14502
|
-
|
|
14503
15410
|
/**
|
|
14504
15411
|
* The one browser transfer for a signed ingot download link: fetch it into a
|
|
14505
|
-
* Blob under liveness bounds
|
|
15412
|
+
* Blob under liveness bounds, resuming from the bytes it holds when the caller
|
|
15413
|
+
* can mint another link. `sv.ingots.download` uses it, and so can a caller
|
|
14506
15414
|
* that mints its own link (`createDownloadLink`, or its own authenticated
|
|
14507
|
-
* call) and needs cancellation, byte progress or the published
|
|
15415
|
+
* call) and needs cancellation, byte progress, resumption or the published
|
|
15416
|
+
* revision.
|
|
14508
15417
|
*/
|
|
14509
15418
|
/**
|
|
14510
15419
|
* Time-to-first-byte bound: how long the download host may take to return
|
|
@@ -14569,15 +15478,104 @@ function assertDownloadUrl(url, isAllowedHost = isSparkVaultOwnedHostname) {
|
|
|
14569
15478
|
}
|
|
14570
15479
|
/**
|
|
14571
15480
|
* Fetch a signed download URL as a Blob under liveness bounds: one deadline
|
|
14572
|
-
* for
|
|
14573
|
-
* Nothing caps the transfer as a whole, so file size never decides
|
|
14574
|
-
* download can finish. The link is single-use
|
|
14575
|
-
*
|
|
14576
|
-
*
|
|
14577
|
-
|
|
14578
|
-
|
|
14579
|
-
|
|
14580
|
-
|
|
15481
|
+
* for each response's headers, then an idle deadline rearmed on every body
|
|
15482
|
+
* chunk. Nothing caps the transfer as a whole, so file size never decides
|
|
15483
|
+
* whether a download can finish. The link is single-use, so a failed transfer
|
|
15484
|
+
* is retried only through `options.remint`, on a link minted for the retry. A
|
|
15485
|
+
* link that is not a Forge decrypt URL on an allowed host, the first or a
|
|
15486
|
+
* minted one, is refused before anything is sent to it (assertDownloadUrl).
|
|
15487
|
+
*/
|
|
15488
|
+
function fetchDownload(url, options = {}) {
|
|
15489
|
+
return runDownload(() => Promise.resolve(url), options);
|
|
15490
|
+
}
|
|
15491
|
+
/**
|
|
15492
|
+
* {@link fetchDownload} for a caller whose every link is minted, the first
|
|
15493
|
+
* included: a mint that fails before any byte has moved is retried under the
|
|
15494
|
+
* same policy as any other failure. `sv.ingots.download` runs this.
|
|
15495
|
+
*/
|
|
15496
|
+
function fetchMintedDownload(mint, options = {}) {
|
|
15497
|
+
return runDownload(mint, { ...options, remint: mint });
|
|
15498
|
+
}
|
|
15499
|
+
/** A failure no answer came with (a reset, a deadline, a lost connection): the policy retries it. */
|
|
15500
|
+
const UNANSWERED = classifyTransferResponse({ status: 0 });
|
|
15501
|
+
/** A failure that is this transfer's own verdict (content that is not the file held, a range that does not continue it): final. */
|
|
15502
|
+
const FINAL = { verdict: TRANSFER_VERDICT.REFUSED, retryAfterMs: null, offset: null, coreCode: null };
|
|
15503
|
+
/** `bytes <first>-<last>/<length>`: the one Content-Range form a 206 continuing a download carries. */
|
|
15504
|
+
const CONTENT_RANGE = /^bytes (\d+)-(\d+)\/(\d+)$/;
|
|
15505
|
+
/** A strong entity tag (RFC 9110 §8.8.3): an If-Range never carries a weak one. */
|
|
15506
|
+
const STRONG_ETAG = /^"[^"]*"$/;
|
|
15507
|
+
const CONTENT_CHANGED_MESSAGE = 'The file changed while it was downloading. Please try again.';
|
|
15508
|
+
/**
|
|
15509
|
+
* The transfer: an attempt on the link `firstLink` resolves to, then, while
|
|
15510
|
+
* the transfer policy retries a failure and the caller can mint, one attempt
|
|
15511
|
+
* per minted link, each after the policy's backoff. Retries are bounded by the
|
|
15512
|
+
* policy's budget, failures in a row and time without progress, both of which
|
|
15513
|
+
* start over whenever bytes arrive past what any attempt held.
|
|
15514
|
+
*/
|
|
15515
|
+
async function runDownload(firstLink, options) {
|
|
15516
|
+
const { signal, remint } = options;
|
|
15517
|
+
const state = { received: new ReceivedBytes(), budget: createTransferBudget(), held: null, furthest: 0 };
|
|
15518
|
+
// The link carries the ISTK, a credential, which never feeds anything
|
|
15519
|
+
// observable such as a delay: the retries spread by a key of the download's
|
|
15520
|
+
// kind and start instead (transferJitterKey).
|
|
15521
|
+
const jitterKey = transferJitterKey('download');
|
|
15522
|
+
for (let nextLink = firstLink;;) {
|
|
15523
|
+
const result = await attemptWith(nextLink, state, options);
|
|
15524
|
+
if (result.ok)
|
|
15525
|
+
return result.download;
|
|
15526
|
+
if (signal?.aborted)
|
|
15527
|
+
throw signal.reason;
|
|
15528
|
+
const { error, outcome } = result;
|
|
15529
|
+
if (!remint || outcome.verdict !== TRANSFER_VERDICT.RETRY || !state.budget.failed(TRANSFER_VERDICT.RETRY, outcome.retryAfterMs)) {
|
|
15530
|
+
throw error;
|
|
15531
|
+
}
|
|
15532
|
+
await waitBeforeRetry(retryDelayMs({ attempt: state.budget.attempt, retryAfterMs: outcome.retryAfterMs, jitterKey }), signal);
|
|
15533
|
+
// A link is spent once its request has reached Forge, whatever came back:
|
|
15534
|
+
// every retry fetches one minted for it.
|
|
15535
|
+
nextLink = remint;
|
|
15536
|
+
}
|
|
15537
|
+
}
|
|
15538
|
+
/**
|
|
15539
|
+
* One attempt: take its link, minted when the source mints, hold it to the
|
|
15540
|
+
* transfer-URL rule, then fetch it. A mint that fails is read the way a
|
|
15541
|
+
* transfer answer is ({@link mintOutcome}).
|
|
15542
|
+
*/
|
|
15543
|
+
async function attemptWith(source, state, options) {
|
|
15544
|
+
let link;
|
|
15545
|
+
try {
|
|
15546
|
+
link = await source();
|
|
15547
|
+
assertDownloadUrl(link, options.isAllowedHost);
|
|
15548
|
+
}
|
|
15549
|
+
catch (error) {
|
|
15550
|
+
return { ok: false, error, outcome: mintOutcome(error) };
|
|
15551
|
+
}
|
|
15552
|
+
return attemptDownload(link, state, options);
|
|
15553
|
+
}
|
|
15554
|
+
/**
|
|
15555
|
+
* The transfer policy's reading of a failed mint. The HTTP client read the
|
|
15556
|
+
* answer when it built the error: its status gives the verdict (a refused link
|
|
15557
|
+
* is a 400, so final) and the `Retry-After` it named rides on the error
|
|
15558
|
+
* (`retryAfterMs`), so a mint Core defers waits out Core's floor exactly as a
|
|
15559
|
+
* deferred Forge answer does. A failure with no status got no answer.
|
|
15560
|
+
*/
|
|
15561
|
+
function mintOutcome(error) {
|
|
15562
|
+
if (!(error instanceof SparkVaultError) || typeof error.statusCode !== 'number')
|
|
15563
|
+
return UNANSWERED;
|
|
15564
|
+
return { ...classifyTransferResponse({ status: error.statusCode }), retryAfterMs: error.retryAfterMs };
|
|
15565
|
+
}
|
|
15566
|
+
/**
|
|
15567
|
+
* Fetch one link: the rest of the file held, conditioned on its validator,
|
|
15568
|
+
* when the bytes held can be resumed, the whole file otherwise. A 206 appends
|
|
15569
|
+
* to the bytes held; any whole-file answer replaces them, so a file replaced
|
|
15570
|
+
* since the bytes held began starts over as its new content, never spliced
|
|
15571
|
+
* onto the old.
|
|
15572
|
+
*/
|
|
15573
|
+
async function attemptDownload(link, state, options) {
|
|
15574
|
+
const { signal, onProgress, expectedContentVersion } = options;
|
|
15575
|
+
const { received } = state;
|
|
15576
|
+
const resume = resumePoint(state);
|
|
15577
|
+
if (!resume)
|
|
15578
|
+
received.discard();
|
|
14581
15579
|
const controller = new AbortController();
|
|
14582
15580
|
const abortFromCaller = () => controller.abort(signal?.reason);
|
|
14583
15581
|
if (signal?.aborted) {
|
|
@@ -14586,61 +15584,231 @@ async function fetchDownload(url, options = {}) {
|
|
|
14586
15584
|
else {
|
|
14587
15585
|
signal?.addEventListener('abort', abortFromCaller, { once: true });
|
|
14588
15586
|
}
|
|
15587
|
+
// What a whole download is, once the answer has named its content.
|
|
15588
|
+
const whole = (content) => ({
|
|
15589
|
+
ok: true,
|
|
15590
|
+
download: { blob: received.toBlob(content.contentType), contentVersion: content.contentVersion },
|
|
15591
|
+
});
|
|
15592
|
+
let held = null;
|
|
15593
|
+
let delivered = false;
|
|
14589
15594
|
try {
|
|
14590
|
-
const response = await withDeadline(fetch(
|
|
15595
|
+
const response = await withDeadline(fetch(link, resume
|
|
15596
|
+
? { signal: controller.signal, headers: { Range: `bytes=${resume.at}-`, 'If-Range': resume.validator } }
|
|
15597
|
+
: { signal: controller.signal }), DOWNLOAD_TTFB_TIMEOUT_MS, controller, 'Download timed out waiting for response headers');
|
|
14591
15598
|
if (!response.ok) {
|
|
14592
|
-
|
|
14593
|
-
|
|
14594
|
-
|
|
14595
|
-
|
|
14596
|
-
|
|
15599
|
+
return {
|
|
15600
|
+
ok: false,
|
|
15601
|
+
error: new SparkVaultError(`Download failed with status ${response.status}`, 'download_failed', response.status),
|
|
15602
|
+
outcome: classifyTransferResponse({ status: response.status, headers: (name) => response.headers.get(name) }),
|
|
15603
|
+
};
|
|
14597
15604
|
}
|
|
14598
|
-
|
|
14599
|
-
|
|
14600
|
-
|
|
14601
|
-
|
|
14602
|
-
|
|
14603
|
-
|
|
14604
|
-
|
|
14605
|
-
|
|
14606
|
-
|
|
14607
|
-
|
|
14608
|
-
|
|
14609
|
-
if (!response.body) {
|
|
14610
|
-
const blob = await withDeadline(response.blob(), DOWNLOAD_BODY_TIMEOUT_MS, controller, 'Download timed out');
|
|
14611
|
-
onProgress?.(blob.size, total);
|
|
14612
|
-
return { blob, contentVersion };
|
|
14613
|
-
}
|
|
14614
|
-
const reader = response.body.getReader();
|
|
14615
|
-
const parts = [];
|
|
14616
|
-
let pending = [];
|
|
14617
|
-
let pendingBytes = 0;
|
|
14618
|
-
let loaded = 0;
|
|
14619
|
-
for (;;) {
|
|
14620
|
-
const { done, value } = await withDeadline(reader.read(), DOWNLOAD_IDLE_TIMEOUT_MS, controller, 'Download stalled: no data received');
|
|
14621
|
-
if (done)
|
|
14622
|
-
break;
|
|
14623
|
-
pending.push(value);
|
|
14624
|
-
pendingBytes += value.byteLength;
|
|
14625
|
-
loaded += value.byteLength;
|
|
14626
|
-
onProgress?.(loaded, total);
|
|
14627
|
-
if (pendingBytes >= DOWNLOAD_BLOB_FLUSH_BYTES) {
|
|
14628
|
-
// Fetch body chunks are ArrayBuffer-backed; the lib types over-generalize
|
|
14629
|
-
// to ArrayBufferLike, which the Blob constructor's part type rejects.
|
|
14630
|
-
parts.push(new Blob(pending));
|
|
14631
|
-
pending = [];
|
|
14632
|
-
pendingBytes = 0;
|
|
15605
|
+
if (resume && response.status === 206) {
|
|
15606
|
+
const continued = continuation(response, resume);
|
|
15607
|
+
if (continued instanceof SparkVaultError)
|
|
15608
|
+
return { ok: false, error: continued, outcome: FINAL };
|
|
15609
|
+
held = continued;
|
|
15610
|
+
}
|
|
15611
|
+
else {
|
|
15612
|
+
received.discard();
|
|
15613
|
+
const contentVersion = response.headers.get('x-content-version') || null;
|
|
15614
|
+
if (expectedContentVersion && contentVersion && contentVersion !== expectedContentVersion) {
|
|
15615
|
+
return { ok: false, error: new SparkVaultError(CONTENT_CHANGED_MESSAGE, 'content_changed'), outcome: FINAL };
|
|
14633
15616
|
}
|
|
15617
|
+
held = {
|
|
15618
|
+
contentType: response.headers.get('content-type') ?? '',
|
|
15619
|
+
contentVersion,
|
|
15620
|
+
total: Number(response.headers.get('content-length')) || 0,
|
|
15621
|
+
validator: resumeValidator(response.headers),
|
|
15622
|
+
};
|
|
14634
15623
|
}
|
|
14635
|
-
|
|
14636
|
-
|
|
15624
|
+
// Named before the body is read: a body that fails part-way leaves the
|
|
15625
|
+
// next attempt what it needs to resume.
|
|
15626
|
+
state.held = held;
|
|
15627
|
+
await readBody(response, controller, state, held.total, onProgress);
|
|
15628
|
+
delivered = true;
|
|
15629
|
+
return whole(held);
|
|
15630
|
+
}
|
|
15631
|
+
catch (error) {
|
|
15632
|
+
if (error instanceof ProgressCallbackFailure)
|
|
15633
|
+
return { ok: false, error: error.failure, outcome: FINAL };
|
|
15634
|
+
// Every declared byte arrived before the body failed to end: the file is
|
|
15635
|
+
// whole, and a resume would ask for a range past its end (a 416).
|
|
15636
|
+
if (held !== null && held.total > 0 && received.loaded === held.total && !signal?.aborted) {
|
|
15637
|
+
return whole(held);
|
|
14637
15638
|
}
|
|
14638
|
-
return {
|
|
15639
|
+
return { ok: false, error, outcome: UNANSWERED };
|
|
14639
15640
|
}
|
|
14640
15641
|
finally {
|
|
15642
|
+
// An attempt that ends short of its body leaves a connection that no
|
|
15643
|
+
// deadline will reap any more: abort it, or every retry leaks one socket.
|
|
15644
|
+
if (!delivered)
|
|
15645
|
+
controller.abort();
|
|
14641
15646
|
signal?.removeEventListener('abort', abortFromCaller);
|
|
14642
15647
|
}
|
|
14643
15648
|
}
|
|
15649
|
+
/** The resume point the bytes held allow, or null when the attempt fetches the whole file. */
|
|
15650
|
+
function resumePoint(state) {
|
|
15651
|
+
const { held, received } = state;
|
|
15652
|
+
if (held === null || held.validator === null || received.loaded === 0)
|
|
15653
|
+
return null;
|
|
15654
|
+
return { held, validator: held.validator, at: received.loaded };
|
|
15655
|
+
}
|
|
15656
|
+
/**
|
|
15657
|
+
* What a resume conditions its range on: the response's ETag when it is
|
|
15658
|
+
* strong and the response accepts byte ranges, or null. An edge that rewrites
|
|
15659
|
+
* a body (compression) weakens its ETag, and then nothing binds the bytes held
|
|
15660
|
+
* to the bytes a range would be served from.
|
|
15661
|
+
*/
|
|
15662
|
+
function resumeValidator(headers) {
|
|
15663
|
+
const etag = headers.get('etag');
|
|
15664
|
+
const acceptsBytes = (headers.get('accept-ranges') ?? '')
|
|
15665
|
+
.split(',')
|
|
15666
|
+
.some((unit) => unit.trim().toLowerCase() === 'bytes');
|
|
15667
|
+
return etag !== null && STRONG_ETAG.test(etag) && acceptsBytes ? etag : null;
|
|
15668
|
+
}
|
|
15669
|
+
/**
|
|
15670
|
+
* The content a 206 answering a resume continues, or why it cannot: it must
|
|
15671
|
+
* start at the first byte lacking, run to the end of the same file, and name
|
|
15672
|
+
* the publication the bytes held are when it names one (a server that honored
|
|
15673
|
+
* the range despite a changed publication would splice two of them).
|
|
15674
|
+
*/
|
|
15675
|
+
function continuation(response, resume) {
|
|
15676
|
+
const etag = response.headers.get('etag');
|
|
15677
|
+
if (etag !== null && etag.replace(/^W\//, '') !== resume.validator) {
|
|
15678
|
+
return new SparkVaultError(CONTENT_CHANGED_MESSAGE, 'content_changed');
|
|
15679
|
+
}
|
|
15680
|
+
const range = CONTENT_RANGE.exec(response.headers.get('content-range') ?? '');
|
|
15681
|
+
const [first, last, length] = range ? range.slice(1).map(Number) : [NaN, NaN, NaN];
|
|
15682
|
+
const { total } = resume.held;
|
|
15683
|
+
if (first !== resume.at || last !== length - 1 || (total > 0 && length !== total)) {
|
|
15684
|
+
return new SparkVaultError('The resumed download did not continue where it stopped', 'download_failed', response.status, { reason: 'range_mismatch' });
|
|
15685
|
+
}
|
|
15686
|
+
return { ...resume.held, total: length };
|
|
15687
|
+
}
|
|
15688
|
+
/**
|
|
15689
|
+
* Read a response body onto the bytes held under liveness bounds, reporting
|
|
15690
|
+
* cumulative progress against the file's declared length.
|
|
15691
|
+
*/
|
|
15692
|
+
async function readBody(response, controller, state, total, onProgress) {
|
|
15693
|
+
const { received } = state;
|
|
15694
|
+
// Safari 10.1-14.4 ships fetch without `Response.body`, and the SDK's
|
|
15695
|
+
// support floor reaches back into that range. There the transfer keeps
|
|
15696
|
+
// whole-transfer wall-clock semantics: blob() surfaces no chunk arrivals,
|
|
15697
|
+
// so there is no liveness to observe, and a failure holds no bytes to
|
|
15698
|
+
// resume from.
|
|
15699
|
+
if (!response.body) {
|
|
15700
|
+
received.appendBlob(await withDeadline(response.blob(), DOWNLOAD_BODY_TIMEOUT_MS, controller, 'Download timed out'));
|
|
15701
|
+
noteArrival(state);
|
|
15702
|
+
reportProgress(onProgress, received.loaded, total);
|
|
15703
|
+
return;
|
|
15704
|
+
}
|
|
15705
|
+
const reader = response.body.getReader();
|
|
15706
|
+
for (;;) {
|
|
15707
|
+
const { done, value } = await withDeadline(reader.read(), DOWNLOAD_IDLE_TIMEOUT_MS, controller, 'Download stalled: no data received');
|
|
15708
|
+
if (done)
|
|
15709
|
+
return;
|
|
15710
|
+
received.append(value);
|
|
15711
|
+
noteArrival(state);
|
|
15712
|
+
reportProgress(onProgress, received.loaded, total);
|
|
15713
|
+
}
|
|
15714
|
+
}
|
|
15715
|
+
/**
|
|
15716
|
+
* The caller's progress callback failed: its own error, which no retry can
|
|
15717
|
+
* cure. Unmarked, it would read as a transfer that lost its connection, and a
|
|
15718
|
+
* callback that throws on every report would cost a mint and a request per
|
|
15719
|
+
* chunk until the file completed.
|
|
15720
|
+
*/
|
|
15721
|
+
class ProgressCallbackFailure extends Error {
|
|
15722
|
+
constructor(failure) {
|
|
15723
|
+
super('onProgress threw');
|
|
15724
|
+
this.failure = failure;
|
|
15725
|
+
}
|
|
15726
|
+
}
|
|
15727
|
+
function reportProgress(onProgress, loaded, total) {
|
|
15728
|
+
if (!onProgress)
|
|
15729
|
+
return;
|
|
15730
|
+
try {
|
|
15731
|
+
onProgress(loaded, total);
|
|
15732
|
+
}
|
|
15733
|
+
catch (failure) {
|
|
15734
|
+
throw new ProgressCallbackFailure(failure);
|
|
15735
|
+
}
|
|
15736
|
+
}
|
|
15737
|
+
/** Bytes arrived: past the most any attempt held, progress; short of it, a sign of life. */
|
|
15738
|
+
function noteArrival(state) {
|
|
15739
|
+
if (state.received.loaded > state.furthest) {
|
|
15740
|
+
state.furthest = state.received.loaded;
|
|
15741
|
+
state.budget.progressed();
|
|
15742
|
+
}
|
|
15743
|
+
else {
|
|
15744
|
+
state.budget.alive();
|
|
15745
|
+
}
|
|
15746
|
+
}
|
|
15747
|
+
/** Wait out a retry's backoff; the caller's cancel ends the wait with the signal's reason. */
|
|
15748
|
+
function waitBeforeRetry(ms, signal) {
|
|
15749
|
+
return new Promise((resolve, reject) => {
|
|
15750
|
+
if (signal?.aborted) {
|
|
15751
|
+
reject(signal.reason);
|
|
15752
|
+
return;
|
|
15753
|
+
}
|
|
15754
|
+
const onAbort = () => {
|
|
15755
|
+
clearTimeout(timer);
|
|
15756
|
+
reject(signal?.reason);
|
|
15757
|
+
};
|
|
15758
|
+
const timer = setTimeout(() => {
|
|
15759
|
+
signal?.removeEventListener('abort', onAbort);
|
|
15760
|
+
resolve();
|
|
15761
|
+
}, ms);
|
|
15762
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
15763
|
+
});
|
|
15764
|
+
}
|
|
15765
|
+
/**
|
|
15766
|
+
* The bytes a transfer holds, in the order they arrived: at most one window
|
|
15767
|
+
* on the JS heap, the rest folded into Blob parts the platform's blob store
|
|
15768
|
+
* owns, so heap growth is capped whatever the file's size.
|
|
15769
|
+
*/
|
|
15770
|
+
class ReceivedBytes {
|
|
15771
|
+
constructor() {
|
|
15772
|
+
this.parts = [];
|
|
15773
|
+
this.pending = [];
|
|
15774
|
+
this.pendingBytes = 0;
|
|
15775
|
+
this.count = 0;
|
|
15776
|
+
}
|
|
15777
|
+
get loaded() {
|
|
15778
|
+
return this.count;
|
|
15779
|
+
}
|
|
15780
|
+
append(chunk) {
|
|
15781
|
+
this.pending.push(chunk);
|
|
15782
|
+
this.pendingBytes += chunk.byteLength;
|
|
15783
|
+
this.count += chunk.byteLength;
|
|
15784
|
+
if (this.pendingBytes >= DOWNLOAD_BLOB_FLUSH_BYTES)
|
|
15785
|
+
this.fold();
|
|
15786
|
+
}
|
|
15787
|
+
appendBlob(blob) {
|
|
15788
|
+
this.fold();
|
|
15789
|
+
this.parts.push(blob);
|
|
15790
|
+
this.count += blob.size;
|
|
15791
|
+
}
|
|
15792
|
+
discard() {
|
|
15793
|
+
this.parts = [];
|
|
15794
|
+
this.pending = [];
|
|
15795
|
+
this.pendingBytes = 0;
|
|
15796
|
+
this.count = 0;
|
|
15797
|
+
}
|
|
15798
|
+
toBlob(type) {
|
|
15799
|
+
this.fold();
|
|
15800
|
+
return new Blob(this.parts, { type });
|
|
15801
|
+
}
|
|
15802
|
+
fold() {
|
|
15803
|
+
if (this.pending.length === 0)
|
|
15804
|
+
return;
|
|
15805
|
+
// Fetch body chunks are ArrayBuffer-backed; the lib types over-generalize
|
|
15806
|
+
// to ArrayBufferLike, which the Blob constructor's part type rejects.
|
|
15807
|
+
this.parts.push(new Blob(this.pending));
|
|
15808
|
+
this.pending = [];
|
|
15809
|
+
this.pendingBytes = 0;
|
|
15810
|
+
}
|
|
15811
|
+
}
|
|
14644
15812
|
|
|
14645
15813
|
/**
|
|
14646
15814
|
* Folders Module
|
|
@@ -14815,8 +15983,6 @@ const NAME_CONFLICT_POLICIES = ['upsert', 'complete_pending', 'refuse', 'new_nam
|
|
|
14815
15983
|
* (shared with the public upload widget), with server-side finalization and
|
|
14816
15984
|
* download-host allowlisting enforced — no per-size branching.
|
|
14817
15985
|
*/
|
|
14818
|
-
const DOWNLOAD_MAX_ATTEMPTS = 3;
|
|
14819
|
-
const DOWNLOAD_RETRY_BASE_MS = 500;
|
|
14820
15986
|
class IngotsModule {
|
|
14821
15987
|
constructor(config, http) {
|
|
14822
15988
|
/** The client's transfer-host allowlist (`allowedDownloadHostPatterns`), as a download link is read against it. */
|
|
@@ -14874,6 +16040,18 @@ class IngotsModule {
|
|
|
14874
16040
|
* published, so a resolved promise never stands for a stored file whose
|
|
14875
16041
|
* ingot never went live.
|
|
14876
16042
|
*
|
|
16043
|
+
* Transient failures are retried inside the transfer; a session the server
|
|
16044
|
+
* no longer holds (it expired, was cancelled, or its ingot was removed)
|
|
16045
|
+
* rejects with code `session_gone`, and only a new upload session — a new
|
|
16046
|
+
* {@link createUpload}, or {@link upload} again — can store the file. An
|
|
16047
|
+
* upload the server refused for good (the account's storage pool cannot
|
|
16048
|
+
* take it, or a later upload replaced it) rejects with code
|
|
16049
|
+
* `upload_refused`, its message the server's own sentence and its code in
|
|
16050
|
+
* `details.coreCode`: a new upload is no remedy. A publication the server
|
|
16051
|
+
* still defers at the transfer's idle limit rejects with code
|
|
16052
|
+
* `upload_received_publishing`: every byte is received, and the server
|
|
16053
|
+
* finishes the publication on its own, so never upload the file again.
|
|
16054
|
+
*
|
|
14877
16055
|
* @param options.signal - Cancels this transfer (it rejects with code
|
|
14878
16056
|
* `cancelled`); other transfers carry on.
|
|
14879
16057
|
* @param options.onProgress - Bytes sent so far and the file size; never runs backwards.
|
|
@@ -15070,11 +16248,15 @@ class IngotsModule {
|
|
|
15070
16248
|
* Create a signed download link for an ingot (discrete primitive).
|
|
15071
16249
|
*
|
|
15072
16250
|
* Validates the returned URL against the download-host allowlist. Use this
|
|
15073
|
-
* when you want the URL itself; otherwise prefer {@link download}.
|
|
16251
|
+
* when you want the URL itself; otherwise prefer {@link download}. The link
|
|
16252
|
+
* is single-use: Forge claims it the moment a request arrives, so a retry or
|
|
16253
|
+
* a resume needs a link of its own (`fetchDownload`'s `remint`).
|
|
15074
16254
|
*
|
|
15075
16255
|
* @example
|
|
15076
16256
|
* const link = await sv.ingots.createDownloadLink(unsealed, 'ing_abc');
|
|
15077
|
-
*
|
|
16257
|
+
* const { blob } = await fetchDownload(link.downloadUrl, {
|
|
16258
|
+
* remint: async () => (await sv.ingots.createDownloadLink(unsealed, 'ing_abc')).downloadUrl,
|
|
16259
|
+
* });
|
|
15078
16260
|
*/
|
|
15079
16261
|
async createDownloadLink(vault, ingotId) {
|
|
15080
16262
|
const vaultId = requireVaultId(vault);
|
|
@@ -15096,35 +16278,26 @@ class IngotsModule {
|
|
|
15096
16278
|
/**
|
|
15097
16279
|
* Download an ingot as a Blob (high-level flow).
|
|
15098
16280
|
*
|
|
15099
|
-
*
|
|
15100
|
-
*
|
|
15101
|
-
*
|
|
15102
|
-
*
|
|
15103
|
-
*
|
|
15104
|
-
*
|
|
15105
|
-
*
|
|
15106
|
-
*
|
|
16281
|
+
* Every attempt fetches a signed link minted for it ({@link createDownloadLink}:
|
|
16282
|
+
* a link is single-use), under liveness bounds, never a cap on total
|
|
16283
|
+
* duration: a deadline on the response headers, then an idle deadline
|
|
16284
|
+
* rearmed on every body chunk. A failure the platform's transfer policy
|
|
16285
|
+
* retries (`@sparkvault/app-sdk/transfer-retry`: no answer, 408, 425, 429 or
|
|
16286
|
+
* a 5xx, a mint's included) is retried after the policy's backoff, never
|
|
16287
|
+
* sooner than `Retry-After`, until its budget ends. Once bytes have arrived
|
|
16288
|
+
* the retry resumes from the first byte it lacks, conditioned on the
|
|
16289
|
+
* publication's ETag (`If-Range`), so a stall at 90% fetches only the rest;
|
|
16290
|
+
* a file replaced meanwhile starts over as its new content, and one served
|
|
16291
|
+
* with no strong ETag starts over from its first byte. Any other refusal,
|
|
16292
|
+
* and a link that is not a Forge decrypt URL on an allowed host, is final.
|
|
15107
16293
|
*
|
|
15108
16294
|
* @example
|
|
15109
16295
|
* const blob = await sv.ingots.download(unsealed, 'ing_abc');
|
|
15110
16296
|
* const url = URL.createObjectURL(blob);
|
|
15111
16297
|
*/
|
|
15112
16298
|
async download(vault, ingotId) {
|
|
15113
|
-
|
|
15114
|
-
|
|
15115
|
-
try {
|
|
15116
|
-
const link = await this.createDownloadLink(vault, ingotId);
|
|
15117
|
-
return (await fetchDownload(link.downloadUrl, { isAllowedHost: this.allowsTransferHost })).blob;
|
|
15118
|
-
}
|
|
15119
|
-
catch (err) {
|
|
15120
|
-
lastError = err instanceof Error ? err : new Error(String(err));
|
|
15121
|
-
if (!isRetryableDownloadError(lastError) || attempt === DOWNLOAD_MAX_ATTEMPTS) {
|
|
15122
|
-
throw lastError;
|
|
15123
|
-
}
|
|
15124
|
-
await delayExponential(attempt);
|
|
15125
|
-
}
|
|
15126
|
-
}
|
|
15127
|
-
throw lastError ?? new Error('Download failed');
|
|
16299
|
+
const mint = async () => (await this.createDownloadLink(vault, ingotId)).downloadUrl;
|
|
16300
|
+
return (await fetchMintedDownload(mint, { isAllowedHost: this.allowsTransferHost })).blob;
|
|
15128
16301
|
}
|
|
15129
16302
|
/**
|
|
15130
16303
|
* Get an ingot's sharing configuration.
|
|
@@ -15327,22 +16500,6 @@ function mapInvite(wire) {
|
|
|
15327
16500
|
identityType: wire.identity_type ?? 'email',
|
|
15328
16501
|
};
|
|
15329
16502
|
}
|
|
15330
|
-
function delayExponential(attempt) {
|
|
15331
|
-
return new Promise((resolve) => setTimeout(resolve, DOWNLOAD_RETRY_BASE_MS * 2 ** (attempt - 1)));
|
|
15332
|
-
}
|
|
15333
|
-
/**
|
|
15334
|
-
* True when retrying a failed download can succeed. A validation failure always
|
|
15335
|
-
* fails the same way again, and a refused download carries its status, retried
|
|
15336
|
-
* only when the platform's retry rule (`@sparkvault/app-sdk/transient`) calls it
|
|
15337
|
-
* transient; every other failure (connectivity, an answer that could not be
|
|
15338
|
-
* read) is worth another attempt.
|
|
15339
|
-
*/
|
|
15340
|
-
function isRetryableDownloadError(err) {
|
|
15341
|
-
if (err instanceof ValidationError)
|
|
15342
|
-
return false;
|
|
15343
|
-
const status = err instanceof SparkVaultError ? err.statusCode : undefined;
|
|
15344
|
-
return typeof status !== 'number' || status < 400 || isTransientHttpStatus(status);
|
|
15345
|
-
}
|
|
15346
16503
|
|
|
15347
16504
|
/**
|
|
15348
16505
|
* Sparks Module
|
|
@@ -16052,7 +17209,7 @@ class SparkVault {
|
|
|
16052
17209
|
}
|
|
16053
17210
|
/** Get the SDK version */
|
|
16054
17211
|
static get version() {
|
|
16055
|
-
return '11.0.
|
|
17212
|
+
return '11.0.2';
|
|
16056
17213
|
}
|
|
16057
17214
|
}
|
|
16058
17215
|
if (typeof window !== 'undefined') {
|