@pipelex/sdk 0.69.2 → 0.69.5

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.
@@ -375,12 +375,33 @@ export declare function fetchArtifact(client: Pick<ArtifactCapableClient, "resol
375
375
  * text the runtime could read is never one the SDK refuses.
376
376
  */
377
377
  export declare const DEFAULT_STORED_TEXT_MAX_BYTES: number;
378
+ /**
379
+ * The cap on the bytes of all the stored texts of one load together. Every loaded value is held
380
+ * until the load ends, as bytes and then as a string that can take twice as many, so the load
381
+ * itself must be bounded, not only each text: 256 MiB leaves room for two texts at the per-text
382
+ * cap while keeping what one load holds to a few hundred MiB of the process's memory.
383
+ */
384
+ export declare const DEFAULT_STORED_TEXT_MAX_TOTAL_BYTES: number;
378
385
  /** How many stored texts one load reads at once. */
379
386
  export declare const DEFAULT_STORED_TEXT_CONCURRENCY = 8;
387
+ /**
388
+ * The `StoredTextLoadError` reason of a result that cannot say which of its values are stored
389
+ * texts ({@link lacksStoredTextConcepts}); `waitForResult` keeps polling through it for a while.
390
+ */
391
+ export declare const STORED_TEXT_CONCEPTS_MISSING = "concepts_missing";
380
392
  /** The bounds `loadStoredTexts` applies. Every one has a safe default. */
381
393
  export interface LoadStoredTextsOptions {
382
- /** Refuse a stored text over this many bytes, before and while reading it. Default 100 MiB. */
394
+ /**
395
+ * Refuse a stored text over this many bytes: against the size its reference states before
396
+ * anything is sent, then while reading it. Default 100 MiB.
397
+ */
383
398
  maxBytes?: number;
399
+ /**
400
+ * Refuse the load once its stored texts together cross this many bytes: against the sizes their
401
+ * references state before anything is sent, then counted as the bytes arrive, every read in
402
+ * flight then stopped. Default 256 MiB ({@link DEFAULT_STORED_TEXT_MAX_TOTAL_BYTES}).
403
+ */
404
+ maxTotalBytes?: number;
384
405
  /** Budget for each text's exchange — connect, headers and body. Default 120 s. */
385
406
  timeoutMs?: number;
386
407
  /** Accept a plain `http:` link, as the local stack's object store hands out. Off by default. */
@@ -399,19 +420,34 @@ export interface LoadStoredTextsOptions {
399
420
  *
400
421
  * Which values are stored texts is decided by concept, never by URL or MIME type: the concept at
401
422
  * each path comes from the run's working memory and output form ({@link mainStuffNode}), so the
402
- * results must carry them; a result that carries neither is returned as it is. A
403
- * `pipelex-storage://` reference is resolved through the platform's bulk route, at most
423
+ * results must carry them. A result that cannot say (no working memory naming the main stuff, or
424
+ * a concept of the method's own that no form describes) is returned as it is when nothing in
425
+ * `main_stuff` is shaped like a stored text's reference; when something is, it throws
426
+ * `StoredTextLoadError` with the reason `concepts_missing` rather than hand a reference on where a
427
+ * text is promised ({@link lacksStoredTextConcepts}). The runtime writes `output_form` after
428
+ * `main_stuff`, so a read can land in between: `waitForResult` keeps polling through that window
429
+ * for a few polls before it throws.
430
+ *
431
+ * A `pipelex-storage://` reference is resolved through the platform's bulk route, at most
404
432
  * {@link BULK_RESOLVE_MAX_URIS} per request, and its signed link fetched under the same bounds as
405
- * `fetchArtifact`, and a `data:` URL is decoded. A stored text under any other URL
433
+ * `fetchArtifact`; a link within ten seconds of its `expires_at` when its read is about to start,
434
+ * having waited behind the other reads, is resolved again first. A `data:` URL is decoded, its
435
+ * size bounded from its length before it is. A stored text under any other URL
406
436
  * ({@link isLoadableStoredTextUrl}) is refused before anything is sent, since fetching it would
407
437
  * read a host the method chose rather than the caller; a result read with
408
438
  * `loadStoredTexts: false` keeps it as written. The bytes are UTF-8 by the standard's rule, and a
409
439
  * JSON value is the object they serialize.
410
440
  *
441
+ * Each text is bounded by `maxBytes` (100 MiB by default) and the load as a whole by
442
+ * `maxTotalBytes` (256 MiB by default), both checked first against the sizes the references state,
443
+ * before anything is sent, then as the bytes arrive; the first text that fails stops every other
444
+ * read in flight.
445
+ *
411
446
  * The result passed in is never changed: a new one is returned, or the same one when there is
412
447
  * nothing to load. Throws `StoredTextLoadError` naming the text that could not be loaded, where it
413
448
  * sits and why, a whole-request failure of the resolve route included (`resolve_failed`, the
414
- * route's error as its `cause`), and lets the caller's abort through.
449
+ * route's error as its `cause`), the load's total over `maxTotalBytes` as
450
+ * `total_limit_exceeded`, and lets the caller's abort through.
415
451
  */
416
452
  export declare function loadStoredTexts(client: Pick<ArtifactCapableClient, "resolveStorageUrls">, results: RunResults, options?: LoadStoredTextsOptions): Promise<RunResults>;
417
453
  /**
@@ -432,6 +468,18 @@ export declare function withConceptArtifacts(client: Pick<ArtifactCapableClient,
432
468
  * deciding; a `false` says no stored text the runtime made can be there.
433
469
  */
434
470
  export declare function mayHoldStoredTexts(value: unknown): boolean;
471
+ /**
472
+ * Whether a completed result cannot say which values of its `main_stuff` are stored texts while
473
+ * something there is shaped like one's reference ({@link mayHoldStoredTexts}): the working memory
474
+ * names no main stuff, or its concept is the method's own and no `output_form` / `input_form` node
475
+ * describes it, so a text in one of its fields could not be told from any other value. A native
476
+ * concept needs no form: the walk knows its shape. The runtime writes `output_form` after
477
+ * `main_stuff`, so a read can land in between; {@link loadStoredTexts} then throws
478
+ * `StoredTextLoadError` (`concepts_missing`) rather than hand a reference on.
479
+ */
480
+ export declare function lacksStoredTextConcepts(results: ConceptSource & {
481
+ main_stuff?: unknown;
482
+ }): boolean;
435
483
  /**
436
484
  * Whether a results read narrowed to `selection` carried every artifact the concept at each path
437
485
  * is read from: the working memory and both forms. `undefined`, a read of every artifact, does.
package/dist/artifacts.js CHANGED
@@ -31,7 +31,8 @@ import { argumentInvalidProblem, responseUnreadableProblem } from "./errors.js";
31
31
  import { ProblemError, buildProblem } from "mthds/protocol";
32
32
  import { absenceCause, loadNodeHost } from "./node-host.js";
33
33
  import { MAX_TIMER_DELAY_MS, isTimerDelay } from "./timers.js";
34
- import { STORED_TEXT_REFERENCE_FIELDS, STORED_TEXT_VALUE_FIELD, childNode, mainStuffNode, storedTextKindOfNode, workingMemoryNode, } from "./stored-texts.js";
34
+ import { eitherSignal } from "./signals.js";
35
+ import { STORED_TEXT_REFERENCE_FIELDS, STORED_TEXT_VALUE_FIELD, childNode, describesConcept, mainStuffConceptRef, mainStuffNode, storedTextKindOfNode, workingMemoryNode, } from "./stored-texts.js";
35
36
  import { parseExactJson } from "./exact-json.js";
36
37
  // ── Constants ────────────────────────────────────────────────────────
37
38
  /** The scheme of a durable storage reference. */
@@ -797,8 +798,20 @@ function formatMiB(bytes) {
797
798
  * text the runtime could read is never one the SDK refuses.
798
799
  */
799
800
  export const DEFAULT_STORED_TEXT_MAX_BYTES = 100 * 1024 * 1024;
801
+ /**
802
+ * The cap on the bytes of all the stored texts of one load together. Every loaded value is held
803
+ * until the load ends, as bytes and then as a string that can take twice as many, so the load
804
+ * itself must be bounded, not only each text: 256 MiB leaves room for two texts at the per-text
805
+ * cap while keeping what one load holds to a few hundred MiB of the process's memory.
806
+ */
807
+ export const DEFAULT_STORED_TEXT_MAX_TOTAL_BYTES = 256 * 1024 * 1024;
800
808
  /** How many stored texts one load reads at once. */
801
809
  export const DEFAULT_STORED_TEXT_CONCURRENCY = 8;
810
+ /**
811
+ * The `StoredTextLoadError` reason of a result that cannot say which of its values are stored
812
+ * texts ({@link lacksStoredTextConcepts}); `waitForResult` keeps polling through it for a while.
813
+ */
814
+ export const STORED_TEXT_CONCEPTS_MISSING = "concepts_missing";
802
815
  /**
803
816
  * A run's result with every stored text in `main_stuff` loaded: each value the runtime holds by
804
817
  * reference, `{ url, size, mime_type, preview }`, replaced by its inline form, `{ text }`,
@@ -808,23 +821,40 @@ export const DEFAULT_STORED_TEXT_CONCURRENCY = 8;
808
821
  *
809
822
  * Which values are stored texts is decided by concept, never by URL or MIME type: the concept at
810
823
  * each path comes from the run's working memory and output form ({@link mainStuffNode}), so the
811
- * results must carry them; a result that carries neither is returned as it is. A
812
- * `pipelex-storage://` reference is resolved through the platform's bulk route, at most
824
+ * results must carry them. A result that cannot say (no working memory naming the main stuff, or
825
+ * a concept of the method's own that no form describes) is returned as it is when nothing in
826
+ * `main_stuff` is shaped like a stored text's reference; when something is, it throws
827
+ * `StoredTextLoadError` with the reason `concepts_missing` rather than hand a reference on where a
828
+ * text is promised ({@link lacksStoredTextConcepts}). The runtime writes `output_form` after
829
+ * `main_stuff`, so a read can land in between: `waitForResult` keeps polling through that window
830
+ * for a few polls before it throws.
831
+ *
832
+ * A `pipelex-storage://` reference is resolved through the platform's bulk route, at most
813
833
  * {@link BULK_RESOLVE_MAX_URIS} per request, and its signed link fetched under the same bounds as
814
- * `fetchArtifact`, and a `data:` URL is decoded. A stored text under any other URL
834
+ * `fetchArtifact`; a link within ten seconds of its `expires_at` when its read is about to start,
835
+ * having waited behind the other reads, is resolved again first. A `data:` URL is decoded, its
836
+ * size bounded from its length before it is. A stored text under any other URL
815
837
  * ({@link isLoadableStoredTextUrl}) is refused before anything is sent, since fetching it would
816
838
  * read a host the method chose rather than the caller; a result read with
817
839
  * `loadStoredTexts: false` keeps it as written. The bytes are UTF-8 by the standard's rule, and a
818
840
  * JSON value is the object they serialize.
819
841
  *
842
+ * Each text is bounded by `maxBytes` (100 MiB by default) and the load as a whole by
843
+ * `maxTotalBytes` (256 MiB by default), both checked first against the sizes the references state,
844
+ * before anything is sent, then as the bytes arrive; the first text that fails stops every other
845
+ * read in flight.
846
+ *
820
847
  * The result passed in is never changed: a new one is returned, or the same one when there is
821
848
  * nothing to load. Throws `StoredTextLoadError` naming the text that could not be loaded, where it
822
849
  * sits and why, a whole-request failure of the resolve route included (`resolve_failed`, the
823
- * route's error as its `cause`), and lets the caller's abort through.
850
+ * route's error as its `cause`), the load's total over `maxTotalBytes` as
851
+ * `total_limit_exceeded`, and lets the caller's abort through.
824
852
  */
825
853
  export async function loadStoredTexts(client, results, options = {}) {
826
854
  if (results.main_stuff == null)
827
855
  return results;
856
+ if (lacksStoredTextConcepts(results))
857
+ throw conceptsMissingError(results);
828
858
  const node = mainStuffNode(results);
829
859
  if (node === null)
830
860
  return results;
@@ -879,6 +909,58 @@ export function mayHoldStoredTexts(value) {
879
909
  }
880
910
  return Object.values(fields).some(mayHoldStoredTexts);
881
911
  }
912
+ /**
913
+ * Whether a completed result cannot say which values of its `main_stuff` are stored texts while
914
+ * something there is shaped like one's reference ({@link mayHoldStoredTexts}): the working memory
915
+ * names no main stuff, or its concept is the method's own and no `output_form` / `input_form` node
916
+ * describes it, so a text in one of its fields could not be told from any other value. A native
917
+ * concept needs no form: the walk knows its shape. The runtime writes `output_form` after
918
+ * `main_stuff`, so a read can land in between; {@link loadStoredTexts} then throws
919
+ * `StoredTextLoadError` (`concepts_missing`) rather than hand a reference on.
920
+ */
921
+ export function lacksStoredTextConcepts(results) {
922
+ if (results.main_stuff == null || !mayHoldStoredTexts(results.main_stuff))
923
+ return false;
924
+ const conceptRef = mainStuffConceptRef(results);
925
+ if (conceptRef === null)
926
+ return true;
927
+ return !describesConcept(conceptRef, results);
928
+ }
929
+ /** The `concepts_missing` failure, naming the first value shaped like a stored text's reference. */
930
+ function conceptsMissingError(results) {
931
+ const shaped = firstReferenceShape(results.main_stuff);
932
+ const path = renderPath(shaped?.segments ?? []);
933
+ return new StoredTextLoadError(`The stored text at ${path} could not be loaded: the result does not say which of its values ` +
934
+ "are stored texts (its working_memory or its output_form is missing), so none is handed on " +
935
+ "as its reference; read the result again in a moment, or with loadStoredTexts: false to see " +
936
+ "it as written.", { uri: shaped?.url ?? "", path, reason: STORED_TEXT_CONCEPTS_MISSING }, { problem: responseUnreadableProblem(200, results.pipeline_run_id) });
937
+ }
938
+ /** The first value {@link mayHoldStoredTexts} answers for, depth first, with where it sits. */
939
+ function firstReferenceShape(value, segments = []) {
940
+ if (Array.isArray(value)) {
941
+ for (const [index, entry] of value.entries()) {
942
+ const found = firstReferenceShape(entry, [...segments, index]);
943
+ if (found !== null)
944
+ return found;
945
+ }
946
+ return null;
947
+ }
948
+ if (typeof value !== "object" || value === null)
949
+ return null;
950
+ const fields = value;
951
+ const url = fields["url"];
952
+ if (typeof url === "string" &&
953
+ Object.values(STORED_TEXT_VALUE_FIELD).every((field) => fields[field] == null) &&
954
+ ("size" in fields || "preview" in fields)) {
955
+ return { segments, url };
956
+ }
957
+ for (const [key, entry] of Object.entries(fields)) {
958
+ const found = firstReferenceShape(entry, [...segments, key]);
959
+ if (found !== null)
960
+ return found;
961
+ }
962
+ return null;
963
+ }
882
964
  /**
883
965
  * Whether a results read narrowed to `selection` carried every artifact the concept at each path
884
966
  * is read from: the working memory and both forms. `undefined`, a read of every artifact, does.
@@ -895,66 +977,139 @@ async function loadStoredTextValues(client, value, node, options, runId) {
895
977
  if (!Number.isInteger(concurrency) || concurrency < 1) {
896
978
  throw new ArtifactOperationError(`"concurrency" must be a positive integer, got ${String(concurrency)}.`, { problem: argumentInvalidProblem("concurrency", "not_positive") });
897
979
  }
898
- const bounds = fetchBounds({
899
- maxBytes: options.maxBytes ?? DEFAULT_STORED_TEXT_MAX_BYTES,
900
- timeoutMs: options.timeoutMs,
901
- allowHttp: options.allowHttp,
902
- signal: options.signal,
903
- });
980
+ const maxTotalBytes = options.maxTotalBytes ?? DEFAULT_STORED_TEXT_MAX_TOTAL_BYTES;
981
+ requirePositive("maxTotalBytes", maxTotalBytes);
982
+ const maxBytes = options.maxBytes ?? DEFAULT_STORED_TEXT_MAX_BYTES;
983
+ requirePositive("maxBytes", maxBytes);
904
984
  // One read per distinct URL, named by the first place it was found.
905
985
  const firstSite = new Map();
906
986
  for (const site of sites)
907
987
  if (!firstSite.has(site.url))
908
988
  firstSite.set(site.url, site);
909
989
  const urls = [...firstSite.keys()];
910
- const references = urls.filter(isStorageReference);
911
- const resolved = new Map();
912
- let items;
913
- try {
914
- items = await resolveArtifacts(client, references, { signal: options.signal });
915
- }
916
- catch (err) {
917
- if (options.signal?.aborted === true)
918
- throw options.signal.reason;
919
- // A whole-request failure of the route, a bare runner's 404 among them, is the first text's.
920
- const site = firstSite.get(references[0]);
921
- const path = renderPath(site.segments);
922
- const detail = err instanceof Error ? err.message : String(err);
923
- throw new StoredTextLoadError(`The stored text at ${path} could not be loaded: the platform's bulk resolve route failed: ${detail}`, {
924
- uri: site.url,
925
- path,
926
- reason: "resolve_failed",
927
- status: err instanceof ApiResponseError ? err.status : undefined,
928
- }, { cause: err, problem: err instanceof ProblemError ? err.problem : undefined });
929
- }
930
- references.forEach((uri, index) => resolved.set(uri, items[index]));
990
+ // Refused before anything is sent: a text whose reference states a size over the cap on one
991
+ // text, and texts whose stated sizes together are over the load's cap.
992
+ let declaredTotal = 0;
993
+ for (const url of urls) {
994
+ const site = firstSite.get(url);
995
+ const size = site.reference["size"];
996
+ if (typeof size !== "number" || !(size > 0))
997
+ continue;
998
+ if (size > maxBytes)
999
+ throw overTextCap(site, maxBytes, size);
1000
+ declaredTotal += size;
1001
+ if (declaredTotal > maxTotalBytes)
1002
+ throw overLoadCap(site, maxTotalBytes);
1003
+ }
1004
+ // The first failure stops new reads from starting and stops the reads in flight, through one
1005
+ // signal linked with the caller's; the load then throws that first failure once every read has
1006
+ // settled, or the caller's abort as it is.
1007
+ const stop = new AbortController();
1008
+ const stopping = eitherSignal(stop.signal, options.signal);
1009
+ // Everything after the link is in its disposal scope: a setup that fails, the bulk resolve
1010
+ // above all, must not leave a listener on a caller's long-lived signal.
1011
+ let dispatcher = null;
931
1012
  const texts = new Map();
932
- const dispatcher = await dispatcherFor(bounds.timeoutMs);
1013
+ let failed = false;
1014
+ let firstFailure;
933
1015
  try {
1016
+ const bounds = fetchBounds({
1017
+ maxBytes,
1018
+ timeoutMs: options.timeoutMs,
1019
+ allowHttp: options.allowHttp,
1020
+ signal: stopping.signal,
1021
+ });
1022
+ const references = urls.filter(isStorageReference);
1023
+ const resolved = new Map();
1024
+ const items = await resolveForTexts(client, references, firstSite, options.signal);
1025
+ references.forEach((uri, index) => resolved.set(uri, items[index]));
1026
+ // Every byte read counts against the load's budget, whatever the references state.
1027
+ let held = 0;
1028
+ const take = (bytes) => {
1029
+ held += bytes;
1030
+ return held <= maxTotalBytes;
1031
+ };
1032
+ dispatcher = await dispatcherFor(bounds.timeoutMs);
1033
+ const readOne = async (url) => {
1034
+ const site = firstSite.get(url);
1035
+ let entry = resolved.get(url);
1036
+ // A link resolved before the reads ahead of it is resolved again just before its own read.
1037
+ if (entry !== undefined && entry.error === null && isExpired(entry.expires_at)) {
1038
+ [entry] = await resolveForTexts(client, [url], firstSite, stopping.signal);
1039
+ }
1040
+ const bytes = await readStoredBytes(site, entry, bounds, maxTotalBytes, take, dispatcher);
1041
+ texts.set(url, decodeStoredValue(site, bytes, runId));
1042
+ };
934
1043
  let next = 0;
935
1044
  const worker = async () => {
936
- for (;;) {
937
- const index = next;
1045
+ while (!failed && next < urls.length) {
1046
+ const url = urls[next];
938
1047
  next += 1;
939
- if (index >= urls.length)
940
- return;
941
- const url = urls[index];
942
- const site = firstSite.get(url);
943
- const bytes = await readStoredBytes(site, resolved.get(url), bounds, dispatcher);
944
- texts.set(url, decodeStoredValue(site, bytes, runId));
1048
+ try {
1049
+ await readOne(url);
1050
+ }
1051
+ catch (err) {
1052
+ if (!failed) {
1053
+ failed = true;
1054
+ firstFailure = err;
1055
+ stop.abort(err);
1056
+ }
1057
+ }
945
1058
  }
946
1059
  };
947
1060
  await Promise.all(Array.from({ length: Math.min(concurrency, urls.length) }, worker));
948
1061
  }
949
1062
  finally {
1063
+ stopping.dispose();
950
1064
  void dispatcher?.close().catch(() => undefined);
951
1065
  }
1066
+ if (failed) {
1067
+ if (options.signal?.aborted === true)
1068
+ throw options.signal.reason;
1069
+ throw firstFailure;
1070
+ }
952
1071
  let loaded = structuredClone(value);
953
1072
  for (const site of sites) {
954
1073
  loaded = replaceAt(loaded, site.segments, loadedForm(site, texts.get(site.url)));
955
1074
  }
956
1075
  return loaded;
957
1076
  }
1077
+ /**
1078
+ * The bulk resolve of stored texts' references, a whole-request failure being the first text's
1079
+ * `StoredTextLoadError` (`resolve_failed`); the caller's abort goes through as it is.
1080
+ */
1081
+ async function resolveForTexts(client, references, firstSite, signal) {
1082
+ try {
1083
+ return await resolveArtifacts(client, references, { signal });
1084
+ }
1085
+ catch (err) {
1086
+ if (signal?.aborted === true)
1087
+ throw signal.reason;
1088
+ // A whole-request failure of the route, a bare runner's 404 among them, is the first text's.
1089
+ const site = firstSite.get(references[0]);
1090
+ const path = renderPath(site.segments);
1091
+ const detail = err instanceof Error ? err.message : String(err);
1092
+ throw new StoredTextLoadError(`The stored text at ${path} could not be loaded: the platform's bulk resolve route failed: ${detail}`, {
1093
+ uri: site.url,
1094
+ path,
1095
+ reason: "resolve_failed",
1096
+ status: err instanceof ApiResponseError ? err.status : undefined,
1097
+ }, { cause: err, problem: err instanceof ProblemError ? err.problem : undefined });
1098
+ }
1099
+ }
1100
+ /** A stored text over the cap on one text; `size` when its reference or its length states it. */
1101
+ function overTextCap(site, maxBytes, size) {
1102
+ const path = renderPath(site.segments);
1103
+ const over = `over the ${formatMiB(maxBytes)} cap.`;
1104
+ return new StoredTextLoadError(`The stored text at ${path} could not be loaded: it is ` +
1105
+ (size === undefined ? over : `${formatMiB(size)}, ${over}`), { uri: site.url, path, reason: "too_large" }, { problem: downloadLimitProblem(maxBytes) });
1106
+ }
1107
+ /** A stored text that takes the load's texts together over `maxTotalBytes`. */
1108
+ function overLoadCap(site, maxTotalBytes) {
1109
+ const path = renderPath(site.segments);
1110
+ return new StoredTextLoadError(`The stored text at ${path} could not be loaded: with the texts loaded before it, the load ` +
1111
+ `is over its ${formatMiB(maxTotalBytes)} total limit (maxTotalBytes).`, { uri: site.url, path, reason: "total_limit_exceeded" }, { problem: downloadLimitProblem(maxTotalBytes) });
1112
+ }
958
1113
  /**
959
1114
  * Every stored text's reference in `value`, in walk order, the concept at each path read off
960
1115
  * `node`. Throws `StoredTextLoadError` (`unsupported_url`) for a stored text whose `url` the
@@ -1002,21 +1157,24 @@ function findStoredTexts(value, node) {
1002
1157
  visit(value, node);
1003
1158
  return sites;
1004
1159
  }
1005
- /** The bytes of one stored text: a reference's signed link fetched, or a `data:` URL decoded. Nothing else is read. */
1006
- async function readStoredBytes(site, resolved, bounds, dispatcher) {
1160
+ /**
1161
+ * The bytes of one stored text: a reference's signed link fetched, or a `data:` URL decoded.
1162
+ * Nothing else is read. Every chunk is taken from the load's budget as it arrives, and the read
1163
+ * is cut once the budget is crossed.
1164
+ */
1165
+ async function readStoredBytes(site, resolved, bounds, maxTotalBytes, take, dispatcher) {
1007
1166
  const path = renderPath(site.segments);
1008
1167
  const fail = (reason, detail, extra) => {
1009
1168
  throw new StoredTextLoadError(`The stored text at ${path} could not be loaded: ${detail}`, { uri: site.url, path, reason, status: extra?.status }, { cause: extra?.cause, problem: extra?.problem });
1010
1169
  };
1011
1170
  if (site.url.startsWith("data:")) {
1012
- const bytes = decodeDataUrl(site.url);
1013
- if (bytes === null)
1171
+ const bytes = decodeDataUrl(site.url, bounds.maxBytes);
1172
+ if (bytes === "malformed")
1014
1173
  return fail("unsupported_url", "its data URL does not decode.");
1015
- if (bytes.byteLength > bounds.maxBytes) {
1016
- return fail("too_large", `it is ${formatMiB(bytes.byteLength)}, over the ${formatMiB(bounds.maxBytes)} cap.`, {
1017
- problem: downloadLimitProblem(bounds.maxBytes),
1018
- });
1019
- }
1174
+ if (bytes === "too_large")
1175
+ throw overTextCap(site, bounds.maxBytes);
1176
+ if (!take(bytes.byteLength))
1177
+ throw overLoadCap(site, maxTotalBytes);
1020
1178
  return bytes;
1021
1179
  }
1022
1180
  // Unreachable: the walk admits only a reference or a data: URL, and every reference is resolved first.
@@ -1026,11 +1184,36 @@ async function readStoredBytes(site, resolved, bounds, dispatcher) {
1026
1184
  if (resolved.error !== null)
1027
1185
  return fail(resolved.error.code, resolved.error.detail);
1028
1186
  const link = resolved.url;
1187
+ let reader;
1029
1188
  try {
1030
1189
  const response = await fetchResolvedUrl(site.url, link, bounds, dispatcher, () => undefined);
1031
- return new Uint8Array(await response.arrayBuffer());
1190
+ if (response.body === null)
1191
+ return new Uint8Array(0);
1192
+ reader = response.body.getReader();
1193
+ const chunks = [];
1194
+ let total = 0;
1195
+ for (;;) {
1196
+ const chunk = await reader.read();
1197
+ if (chunk.done)
1198
+ break;
1199
+ if (!take(chunk.value.byteLength)) {
1200
+ await reader.cancel().catch(() => undefined);
1201
+ throw overLoadCap(site, maxTotalBytes);
1202
+ }
1203
+ chunks.push(chunk.value);
1204
+ total += chunk.value.byteLength;
1205
+ }
1206
+ const bytes = new Uint8Array(total);
1207
+ let offset = 0;
1208
+ for (const chunk of chunks) {
1209
+ bytes.set(chunk, offset);
1210
+ offset += chunk.byteLength;
1211
+ }
1212
+ return bytes;
1032
1213
  }
1033
1214
  catch (err) {
1215
+ if (err instanceof StoredTextLoadError)
1216
+ throw err;
1034
1217
  if (bounds.signal?.aborted === true)
1035
1218
  throw bounds.signal.reason;
1036
1219
  if (err instanceof ArtifactFetchError) {
@@ -1043,23 +1226,95 @@ async function readStoredBytes(site, resolved, bounds, dispatcher) {
1043
1226
  return fail("unknown", err instanceof Error ? err.message : String(err), { cause: err });
1044
1227
  }
1045
1228
  }
1046
- /** A `data:` URL's bytes, base64 or percent-encoded, or `null` when it is no data URL. */
1047
- function decodeDataUrl(url) {
1229
+ /**
1230
+ * The bytes a percent-encoded payload decodes to, counted in one pass that copies nothing: an
1231
+ * escape `%XX` is one byte and any other character its UTF-8 length, a surrogate pair four. A `%`
1232
+ * not followed by two hex digits makes `decodeURIComponent` refuse the payload anyway. The count
1233
+ * stops once it passes `limit`.
1234
+ */
1235
+ function percentDecodedLength(payload, limit) {
1236
+ let count = 0;
1237
+ for (let index = 0; index < payload.length && count <= limit; index += 1) {
1238
+ const code = payload.charCodeAt(index);
1239
+ if (code === 37) {
1240
+ count += 1;
1241
+ index += 2;
1242
+ }
1243
+ else if (code < 0x80) {
1244
+ count += 1;
1245
+ }
1246
+ else if (code < 0x800) {
1247
+ count += 2;
1248
+ }
1249
+ else if (code >= 0xd800 && code <= 0xdbff && index + 1 < payload.length) {
1250
+ count += 4;
1251
+ index += 1;
1252
+ }
1253
+ else {
1254
+ count += 3;
1255
+ }
1256
+ }
1257
+ return count;
1258
+ }
1259
+ /** The characters of a base64 payload that are not ASCII whitespace, counted in one pass. */
1260
+ function base64Significant(payload) {
1261
+ let count = 0;
1262
+ for (let index = 0; index < payload.length; index += 1) {
1263
+ const code = payload.charCodeAt(index);
1264
+ // Tab, line feed, form feed, carriage return and space: what forgiving-base64 drops.
1265
+ if (code !== 9 && code !== 10 && code !== 12 && code !== 13 && code !== 32)
1266
+ count += 1;
1267
+ }
1268
+ return count;
1269
+ }
1270
+ /**
1271
+ * A `data:` URL's bytes, base64 or percent-encoded; `"malformed"` when it does not decode, and
1272
+ * `"too_large"` when its bytes would be over `maxBytes`, told from the payload's length before
1273
+ * anything is decoded.
1274
+ *
1275
+ * Base64 is read as `atob` reads it (the WHATWG forgiving-base64 decode): ASCII whitespace
1276
+ * dropped, at most two `=` of padding when the length is a multiple of four, then a length that is
1277
+ * not one past a multiple of four and nothing outside the alphabet. Every test is one linear pass,
1278
+ * never a pattern a method's payload could drive into backtracking.
1279
+ */
1280
+ function decodeDataUrl(url, maxBytes) {
1048
1281
  const comma = url.indexOf(",");
1049
1282
  if (comma < 0)
1050
- return null;
1283
+ return "malformed";
1051
1284
  const header = url.slice("data:".length, comma);
1052
1285
  const payload = url.slice(comma + 1);
1053
- try {
1054
- if (/;base64$/i.test(header)) {
1055
- const binary = atob(payload);
1286
+ if (/;base64$/i.test(header)) {
1287
+ // Refused from a count that copies nothing before the whitespace is stripped, so a payload
1288
+ // over the cap is never copied: at most two of the characters counted are padding.
1289
+ if (Math.floor(((base64Significant(payload) - 2) * 3) / 4) > maxBytes)
1290
+ return "too_large";
1291
+ let data = payload.replace(/[\t\n\f\r ]+/g, "");
1292
+ if (data.length % 4 === 0 && data.endsWith("=")) {
1293
+ data = data.slice(0, data.endsWith("==") ? -2 : -1);
1294
+ }
1295
+ if (data.length % 4 === 1 || /[^A-Za-z0-9+/]/.test(data))
1296
+ return "malformed";
1297
+ if (Math.floor((data.length * 3) / 4) > maxBytes)
1298
+ return "too_large";
1299
+ try {
1300
+ const binary = atob(data);
1056
1301
  return Uint8Array.from(binary, (char) => char.charCodeAt(0));
1057
1302
  }
1058
- return new TextEncoder().encode(decodeURIComponent(payload));
1303
+ catch {
1304
+ return "malformed";
1305
+ }
1306
+ }
1307
+ // Counted exactly before anything is decoded, so a payload over the cap is never copied.
1308
+ if (percentDecodedLength(payload, maxBytes) > maxBytes)
1309
+ return "too_large";
1310
+ let bytes;
1311
+ try {
1312
+ bytes = new TextEncoder().encode(decodeURIComponent(payload));
1059
1313
  }
1060
1314
  catch {
1061
- return null;
1315
+ return "malformed";
1062
1316
  }
1317
+ return bytes.byteLength > maxBytes ? "too_large" : bytes;
1063
1318
  }
1064
1319
  /** The value one stored text holds: its UTF-8 text, or for a JSON value the object that text serializes. */
1065
1320
  function decodeStoredValue(site, bytes, runId) {