@sparkvault/sdk-js 9.1.1 → 9.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -9950,6 +9950,18 @@ function parseChunkSizeHeader(raw) {
9950
9950
  * connection has been completely silent for the full window.
9951
9951
  */
9952
9952
  const CHUNK_INACTIVITY_TIMEOUT_MS = 60000;
9953
+ /**
9954
+ * Per-chunk retry budget for the PATCH loop.
9955
+ *
9956
+ * Forge sessions are resumable, so a chunk that fails in transit is a blip to
9957
+ * recover from rather than an upload to abandon — a multi-gigabyte transfer is
9958
+ * otherwise one dropped packet away from starting over. The budget counts only
9959
+ * failures that produced no server-side progress: a retry cycle that finds
9960
+ * bytes actually landed earns the budget back, so a slow-but-alive transfer is
9961
+ * never capped while a genuinely dead one still fails in bounded time.
9962
+ */
9963
+ const CHUNK_MAX_ATTEMPTS = 3;
9964
+ const CHUNK_RETRY_BASE_MS = 500;
9953
9965
  /**
9954
9966
  * Server-side finalization confirmation poll.
9955
9967
  *
@@ -9961,6 +9973,66 @@ const CHUNK_INACTIVITY_TIMEOUT_MS = 60000;
9961
9973
  */
9962
9974
  const FINALIZE_POLL_MAX = 10;
9963
9975
  const FINALIZE_POLL_MS = 1000;
9976
+ /** Promise-wrapped delay, for retry backoff and finalization polling. */
9977
+ /**
9978
+ * A delay that a cancel cuts short: resolves after `ms`, rejects with the
9979
+ * canonical cancelled error the moment the signal aborts.
9980
+ */
9981
+ function abortableDelay(ms, signal) {
9982
+ return new Promise((resolve, reject) => {
9983
+ const cancelled = () => new UploadApiError('Upload cancelled', 'cancelled', 0);
9984
+ if (signal.aborted) {
9985
+ reject(cancelled());
9986
+ return;
9987
+ }
9988
+ const onAbort = () => {
9989
+ clearTimeout(timer);
9990
+ reject(cancelled());
9991
+ };
9992
+ const timer = setTimeout(() => {
9993
+ signal.removeEventListener('abort', onAbort);
9994
+ resolve();
9995
+ }, ms);
9996
+ signal.addEventListener('abort', onAbort, { once: true });
9997
+ });
9998
+ }
9999
+ function delay(ms) {
10000
+ return new Promise(resolve => setTimeout(resolve, ms));
10001
+ }
10002
+ /**
10003
+ * Whether a failed chunk PATCH is worth another attempt.
10004
+ *
10005
+ * A transport-level failure (status 0 — a dropped connection, or the
10006
+ * inactivity watchdog aborting a silent socket) says nothing about whether the
10007
+ * bytes reached Forge, 409 is Forge's documented "another writer holds the
10008
+ * session lease; re-check the offset and retry", and a 5xx is a server-side
10009
+ * blip. Every other outcome is the server's considered answer about this exact
10010
+ * chunk — a rejected offset, a bad ISTK, a vanished session, or a 2xx carrying
10011
+ * a protocol-violating offset — and re-sending would only earn it again. A
10012
+ * cancelled session is the user's decision, never a failure to retry.
10013
+ */
10014
+ function isRetryableChunkFailure(error) {
10015
+ if (!(error instanceof UploadApiError))
10016
+ return false;
10017
+ // Verdicts, not blips: a cancel is the user's decision, and an invalid or
10018
+ // misaligned offset is a protocol violation the server would only repeat.
10019
+ // Both carry statusCode 0, so they must be excluded by code before the
10020
+ // status heuristic below can see them.
10021
+ if (error.code === 'cancelled' || error.code === 'invalid_offset')
10022
+ return false;
10023
+ const status = error.statusCode ?? 0;
10024
+ return status === 0 || status === 409 || status >= 500;
10025
+ }
10026
+ const RESUME_CHECK = {
10027
+ name: 'Upload resume check',
10028
+ code: 'resume_check_failed',
10029
+ networkMessage: 'Unable to resume upload. Please check your connection and try again.',
10030
+ };
10031
+ const FINALIZATION_CHECK = {
10032
+ name: 'Upload finalization check',
10033
+ code: 'finalization_check_failed',
10034
+ networkMessage: 'Unable to confirm upload. Please check your connection and try again.',
10035
+ };
9964
10036
  class UploadApi extends SparkVaultApi {
9965
10037
  constructor(config) {
9966
10038
  super(config.timeout);
@@ -10043,6 +10115,10 @@ class UploadApi extends SparkVaultApi {
10043
10115
  * every server-reported offset, and honors the session abort signal plus
10044
10116
  * per-request timeouts.
10045
10117
  *
10118
+ * A chunk that fails in transit is retried against the session's *true*
10119
+ * offset rather than failing the whole transfer — see {@link CHUNK_MAX_ATTEMPTS}
10120
+ * and {@link readResumeOffset}.
10121
+ *
10046
10122
  * Returns the TUS session URL so the caller can confirm server-side
10047
10123
  * finalization via {@link verifyUploadFinalized} before reporting success.
10048
10124
  */
@@ -10060,15 +10136,93 @@ class UploadApi extends SparkVaultApi {
10060
10136
  ? session.location
10061
10137
  : `${url.origin}${session.location}`;
10062
10138
  let offset = 0;
10139
+ let failedAttempts = 0;
10140
+ // Retries make raw progress non-monotonic (a chunk that streamed to 90%
10141
+ // then failed re-reports from its start on resend); callers get only the
10142
+ // high-water mark so a progress bar never runs backwards.
10143
+ let progressHighWater = 0;
10144
+ const monotonicProgress = onProgress
10145
+ ? (sent, total) => {
10146
+ if (sent > progressHighWater) {
10147
+ progressHighWater = sent;
10148
+ onProgress(sent, total);
10149
+ }
10150
+ }
10151
+ : undefined;
10063
10152
  while (offset < file.size) {
10064
10153
  if (this.isAborted()) {
10065
10154
  throw new UploadApiError('Upload cancelled', 'cancelled', 0);
10066
10155
  }
10067
10156
  const chunkEnd = Math.min(offset + session.chunkSize, file.size);
10068
- offset = await this.patchChunk(uploadUrl, file.slice(offset, chunkEnd), offset, file.size, onProgress);
10157
+ try {
10158
+ offset = await this.patchChunk(uploadUrl, file.slice(offset, chunkEnd), offset, file.size, monotonicProgress);
10159
+ failedAttempts = 0;
10160
+ continue;
10161
+ }
10162
+ catch (error) {
10163
+ failedAttempts += 1;
10164
+ if (failedAttempts >= CHUNK_MAX_ATTEMPTS || !isRetryableChunkFailure(error)) {
10165
+ throw error;
10166
+ }
10167
+ }
10168
+ // The backoff must not outlive a cancel: raced against the session's
10169
+ // abort signal so cancellation stays prompt mid-retry.
10170
+ await abortableDelay(CHUNK_RETRY_BASE_MS * 2 ** (failedAttempts - 1), this.getAbortSignal());
10171
+ let serverOffset;
10172
+ try {
10173
+ serverOffset = await this.readResumeOffset(uploadUrl, file.size);
10174
+ }
10175
+ catch (headError) {
10176
+ // The blip that killed the PATCH is the likeliest thing to also kill
10177
+ // this HEAD moments later. A transient resync failure spends the same
10178
+ // budget as a failed chunk — never the whole transfer, which is the
10179
+ // exact scenario the retry exists for.
10180
+ if (!isRetryableChunkFailure(headError)) {
10181
+ throw headError;
10182
+ }
10183
+ failedAttempts += 1;
10184
+ if (failedAttempts >= CHUNK_MAX_ATTEMPTS) {
10185
+ throw headError;
10186
+ }
10187
+ continue;
10188
+ }
10189
+ // Forge advances a session's offset only in whole committed chunks, so a
10190
+ // legitimate resume point is always chunk-aligned (or the file end). A
10191
+ // misaligned offset is a corrupt session, and resuming from it would
10192
+ // send a short non-final chunk Forge rejects anyway — fail it as the
10193
+ // protocol violation it is instead.
10194
+ if (serverOffset % session.chunkSize !== 0 && serverOffset !== file.size) {
10195
+ throw new UploadApiError(`Server returned misaligned upload offset (${serverOffset})`, 'invalid_offset', 0);
10196
+ }
10197
+ if (serverOffset > offset) {
10198
+ // Bytes reached the server despite the failure, so the transfer is
10199
+ // alive: the budget is earned back rather than spent down across the
10200
+ // many chunks of a large file.
10201
+ failedAttempts = 0;
10202
+ }
10203
+ offset = serverOffset;
10069
10204
  }
10070
10205
  return uploadUrl;
10071
10206
  }
10207
+ /**
10208
+ * Read the offset a failed chunk should resume from.
10209
+ *
10210
+ * Forge commits a chunk before it answers, so a PATCH that died in transit
10211
+ * may have landed in full or not at all (never in part — the chunk object
10212
+ * is written atomically before the offset advances); only the session's own
10213
+ * persisted offset knows which, and the client's arithmetic is worthless
10214
+ * here. An offset past the declared total is a protocol violation rather
10215
+ * than a resume point: honoring it would end the loop early and report a
10216
+ * partial upload as complete, the same trap {@link patchChunk} guards
10217
+ * against on a PATCH's own offset.
10218
+ */
10219
+ async readResumeOffset(uploadUrl, totalSize) {
10220
+ const offset = await this.headUploadOffset(uploadUrl, RESUME_CHECK);
10221
+ if (offset > totalSize) {
10222
+ throw new UploadApiError(`Server returned invalid upload offset (${offset})`, 'invalid_offset', 0);
10223
+ }
10224
+ return offset;
10225
+ }
10072
10226
  /**
10073
10227
  * Create the TUS upload session. Forge reads only `Tus-Resumable`,
10074
10228
  * `Upload-Length`, and `X-ISTK` on create, and returns the session URL in
@@ -10221,27 +10375,31 @@ class UploadApi extends SparkVaultApi {
10221
10375
  if (this.isAborted()) {
10222
10376
  throw new UploadApiError('Upload cancelled', 'cancelled', 0);
10223
10377
  }
10224
- const offset = await this.headUploadOffset(uploadUrl);
10378
+ const offset = await this.headUploadOffset(uploadUrl, FINALIZATION_CHECK);
10225
10379
  lastOffset = offset;
10226
10380
  if (offset >= expectedOffset) {
10227
10381
  return;
10228
10382
  }
10229
10383
  if (attempt < FINALIZE_POLL_MAX) {
10230
- await new Promise(resolve => setTimeout(resolve, FINALIZE_POLL_MS));
10384
+ await delay(FINALIZE_POLL_MS);
10231
10385
  }
10232
10386
  }
10233
10387
  throw new UploadApiError('Upload could not be confirmed: the server never finalized the file. ' +
10234
10388
  `Confirmed ${lastOffset ?? 0} of ${expectedOffset} bytes.`, 'finalization_unconfirmed', 0, { confirmedBytes: lastOffset ?? 0, expectedBytes: expectedOffset });
10235
10389
  }
10236
10390
  /**
10237
- * Read the server's persisted upload offset via a TUS HEAD request.
10391
+ * Read the server's persisted upload offset via a TUS HEAD request — the one
10392
+ * place the client asks Forge where a session really stands, for both
10393
+ * mid-upload resume and end-of-upload confirmation.
10238
10394
  *
10239
10395
  * Uses raw `fetch` rather than the JSON envelope helper: TUS responses
10240
10396
  * carry an empty body and surface state in the `Upload-Offset` header.
10241
10397
  * Honors the session abort signal and request timeout like every other
10242
10398
  * client call.
10399
+ *
10400
+ * @param check - Which caller this read serves; shapes the failure copy.
10243
10401
  */
10244
- async headUploadOffset(uploadUrl) {
10402
+ async headUploadOffset(uploadUrl, check) {
10245
10403
  const closeSignal = this.getAbortSignal();
10246
10404
  const { signal: combinedSignal, dispose } = combineTimeoutAndCloseSignals(this.timeoutMs, closeSignal);
10247
10405
  try {
@@ -10251,12 +10409,12 @@ class UploadApi extends SparkVaultApi {
10251
10409
  signal: combinedSignal,
10252
10410
  });
10253
10411
  if (!response.ok) {
10254
- throw new UploadApiError(`Upload finalization check failed: ${response.status}`, 'finalization_check_failed', response.status);
10412
+ throw new UploadApiError(`${check.name} failed: ${response.status}`, check.code, response.status);
10255
10413
  }
10256
10414
  const header = response.headers.get('Upload-Offset');
10257
10415
  const offset = header !== null ? parseInt(header, 10) : NaN;
10258
10416
  if (!Number.isFinite(offset) || offset < 0) {
10259
- throw new UploadApiError('Upload finalization check returned an invalid offset', 'finalization_check_failed', response.status);
10417
+ throw new UploadApiError(`${check.name} returned an invalid offset`, check.code, response.status);
10260
10418
  }
10261
10419
  return offset;
10262
10420
  }
@@ -10267,10 +10425,10 @@ class UploadApi extends SparkVaultApi {
10267
10425
  if (this.isAborted()) {
10268
10426
  throw new UploadApiError('Upload cancelled', 'cancelled', 0);
10269
10427
  }
10270
- throw new UploadApiError(`Upload finalization check timed out after ${this.timeoutMs}ms`, 'timeout', 0);
10428
+ throw new UploadApiError(`${check.name} timed out after ${this.timeoutMs}ms`, 'timeout', 0);
10271
10429
  }
10272
10430
  if (error instanceof TypeError) {
10273
- throw new UploadApiError('Unable to confirm upload. Please check your connection and try again.', 'network_error', 0);
10431
+ throw new UploadApiError(check.networkMessage, 'network_error', 0);
10274
10432
  }
10275
10433
  throw new UploadApiError(error instanceof Error ? error.message : 'An unexpected error occurred', 'unknown_error', 0);
10276
10434
  }
@@ -13393,7 +13551,31 @@ function mapUploadSettings(wire) {
13393
13551
  */
13394
13552
  const DOWNLOAD_MAX_ATTEMPTS = 3;
13395
13553
  const DOWNLOAD_RETRY_BASE_MS = 500;
13396
- const DOWNLOAD_FETCH_TIMEOUT_MS = 300000;
13554
+ /**
13555
+ * Time-to-first-byte bound: how long the download host may take to return
13556
+ * response headers. This bounds only the wait for a transfer to start — a
13557
+ * signed link either begins serving promptly or is not going to.
13558
+ */
13559
+ const DOWNLOAD_TTFB_TIMEOUT_MS = 30000;
13560
+ /**
13561
+ * Liveness bound on the response body: the longest tolerated gap between two
13562
+ * chunks, rearmed on every chunk. Progress, not wall clock, bounds the
13563
+ * transfer — a large file over a slow link still completes, while a stalled
13564
+ * connection fails promptly enough to retry.
13565
+ */
13566
+ const DOWNLOAD_IDLE_TIMEOUT_MS = 60000;
13567
+ /**
13568
+ * Whole-transfer bound used only where the environment exposes no readable
13569
+ * response body: `blob()` consumes the stream opaquely, so there are no chunk
13570
+ * arrivals to time and wall clock is the only bound available.
13571
+ */
13572
+ const DOWNLOAD_BODY_TIMEOUT_MS = 300000;
13573
+ /**
13574
+ * Bytes held on the JS heap before they are folded into a Blob part. Caps heap
13575
+ * growth at one window regardless of file size; the platform's blob store owns
13576
+ * everything already transferred.
13577
+ */
13578
+ const DOWNLOAD_BLOB_FLUSH_BYTES = 8 * 1024 * 1024;
13397
13579
  class IngotsModule {
13398
13580
  constructor(config, http) {
13399
13581
  this.config = config;
@@ -13626,6 +13808,11 @@ class IngotsModule {
13626
13808
  * short-lived) and retries transient transport failures with exponential
13627
13809
  * backoff. Validation failures (bad host, non-HTTPS) are never retried.
13628
13810
  *
13811
+ * Each attempt is bounded by liveness, never by total duration: a deadline
13812
+ * on the response headers, then an idle deadline rearmed on every body
13813
+ * chunk. A stalled transfer restarts from byte zero: this path requests no
13814
+ * byte range, so a full retry is the only recovery.
13815
+ *
13629
13816
  * @example
13630
13817
  * const blob = await sv.ingots.download(unsealed, 'ing_abc');
13631
13818
  * const url = URL.createObjectURL(blob);
@@ -13635,7 +13822,7 @@ class IngotsModule {
13635
13822
  for (let attempt = 1; attempt <= DOWNLOAD_MAX_ATTEMPTS; attempt++) {
13636
13823
  try {
13637
13824
  const link = await this.createDownloadLink(vault, ingotId);
13638
- return await fetchBlobWithTimeout(link.downloadUrl, DOWNLOAD_FETCH_TIMEOUT_MS);
13825
+ return await fetchBlobWithLivenessBounds(link.downloadUrl);
13639
13826
  }
13640
13827
  catch (err) {
13641
13828
  lastError = err instanceof Error ? err : new Error(String(err));
@@ -13884,21 +14071,74 @@ function isRetryableDownloadError(err) {
13884
14071
  }
13885
14072
  return true;
13886
14073
  }
13887
- async function fetchBlobWithTimeout(url, timeout) {
14074
+ /**
14075
+ * Await one transfer step under a deadline. Expiry aborts the in-flight fetch,
14076
+ * releasing the connection and erroring the response body, and surfaces a
14077
+ * retryable {@link TimeoutError}. The aborted step's own rejection lands on the
14078
+ * handler installed here, so it never escapes as an unhandled rejection.
14079
+ */
14080
+ function withDeadline(step, timeout, controller, message) {
14081
+ return new Promise((resolve, reject) => {
14082
+ const timeoutId = setTimeout(() => {
14083
+ controller.abort();
14084
+ reject(new TimeoutError(message));
14085
+ }, timeout);
14086
+ step.then((value) => {
14087
+ clearTimeout(timeoutId);
14088
+ resolve(value);
14089
+ }, (error) => {
14090
+ clearTimeout(timeoutId);
14091
+ reject(error);
14092
+ });
14093
+ });
14094
+ }
14095
+ /**
14096
+ * Fetch a signed download URL as a Blob under liveness bounds: one deadline
14097
+ * for the response headers, then an idle deadline rearmed on every body chunk.
14098
+ * Nothing caps the transfer as a whole, so file size never decides whether a
14099
+ * download can finish.
14100
+ */
14101
+ async function fetchBlobWithLivenessBounds(url) {
13888
14102
  const controller = new AbortController();
13889
- const timeoutId = setTimeout(() => controller.abort(), timeout);
13890
- try {
13891
- const response = await fetch(url, { signal: controller.signal });
13892
- if (!response.ok) {
13893
- const error = new Error(`Download failed with status ${response.status}`);
13894
- error.statusCode = response.status;
13895
- throw error;
14103
+ const response = await withDeadline(fetch(url, { signal: controller.signal }), DOWNLOAD_TTFB_TIMEOUT_MS, controller, 'Download timed out waiting for response headers');
14104
+ if (!response.ok) {
14105
+ // The TTFB timer cleared when headers arrived, so nothing else would ever
14106
+ // reap this connection: abort it or a retrying caller leaks one socket
14107
+ // per failed attempt.
14108
+ controller.abort();
14109
+ const error = new Error(`Download failed with status ${response.status}`);
14110
+ error.statusCode = response.status;
14111
+ throw error;
14112
+ }
14113
+ const contentType = response.headers.get('content-type') ?? '';
14114
+ // Where the environment exposes no readable body, the transfer keeps
14115
+ // whole-transfer wall-clock semantics: blob() surfaces no chunk arrivals, so
14116
+ // there is no liveness to observe.
14117
+ if (!response.body) {
14118
+ return withDeadline(response.blob(), DOWNLOAD_BODY_TIMEOUT_MS, controller, 'Download timed out');
14119
+ }
14120
+ const reader = response.body.getReader();
14121
+ const parts = [];
14122
+ let pending = [];
14123
+ let pendingBytes = 0;
14124
+ for (;;) {
14125
+ const { done, value } = await withDeadline(reader.read(), DOWNLOAD_IDLE_TIMEOUT_MS, controller, 'Download stalled: no data received');
14126
+ if (done)
14127
+ break;
14128
+ pending.push(value);
14129
+ pendingBytes += value.byteLength;
14130
+ if (pendingBytes >= DOWNLOAD_BLOB_FLUSH_BYTES) {
14131
+ // Fetch body chunks are ArrayBuffer-backed; the lib types over-generalize
14132
+ // to ArrayBufferLike, which the Blob constructor's part type rejects.
14133
+ parts.push(new Blob(pending));
14134
+ pending = [];
14135
+ pendingBytes = 0;
13896
14136
  }
13897
- return await response.blob();
13898
14137
  }
13899
- finally {
13900
- clearTimeout(timeoutId);
14138
+ if (pending.length > 0) {
14139
+ parts.push(new Blob(pending));
13901
14140
  }
14141
+ return new Blob(parts, { type: contentType });
13902
14142
  }
13903
14143
 
13904
14144
  /**
@@ -14765,7 +15005,7 @@ class SparkVault {
14765
15005
  }
14766
15006
  /** Get the SDK version */
14767
15007
  static get version() {
14768
- return '9.1.1';
15008
+ return '9.2.0';
14769
15009
  }
14770
15010
  }
14771
15011
  if (typeof window !== 'undefined') {