@pipelex/sdk 0.69.4 → 0.71.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/artifacts.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * - {@link locateArtifacts} — a pure walk of any JSON value for the strings that
6
6
  * ARE `pipelex-storage://` references, each with every path it sits at.
7
7
  * {@link collectArtifacts} is the same walk's bare references. No network, no key.
8
- * - {@link resolveArtifacts} — the platform's bulk resolve route over a whole
8
+ * - {@link resolveArtifacts} — the server's bulk resolve route over a whole
9
9
  * list, chunked at the route's bound, one verdict per reference.
10
10
  * - {@link fetchArtifact} — a bounded `Response` for one reference: resolved
11
11
  * fresh, timed out, redirects refused, the byte cap enforced mid-stream, no
@@ -16,8 +16,9 @@
16
16
  * A produced file is never embedded in a run's results: the content carries its
17
17
  * durable `pipelex-storage://` reference beside a signed `public_url` that expires
18
18
  * on the provider's schedule. Nothing here reads that embedded link — every link
19
- * is minted fresh by the platform, and re-minted when it has expired by the time a
20
- * worker reaches it. See `docs/artifact-download.md`.
19
+ * is minted fresh by the server's bulk resolve route (the hosted platform's presigned
20
+ * link, or a self-hosted runner's own signed link), and re-minted when it has expired
21
+ * by the time a worker reaches it. See `docs/artifact-download.md`.
21
22
  *
22
23
  * `node:fs/promises`, `node:path` and `undici` come from the Node host
23
24
  * (`node-host.ts`), which a bundler building for the browser resolves to a module
@@ -31,14 +32,16 @@ import { argumentInvalidProblem, responseUnreadableProblem } from "./errors.js";
31
32
  import { ProblemError, buildProblem } from "mthds/protocol";
32
33
  import { absenceCause, loadNodeHost } from "./node-host.js";
33
34
  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";
35
+ import { eitherSignal } from "./signals.js";
36
+ import { STORED_TEXT_REFERENCE_FIELDS, STORED_TEXT_VALUE_FIELD, childNode, describesConcept, mainStuffConceptRef, mainStuffNode, storedTextKindOfNode, workingMemoryNode, } from "./stored-texts.js";
35
37
  import { parseExactJson } from "./exact-json.js";
36
38
  // ── Constants ────────────────────────────────────────────────────────
37
39
  /** The scheme of a durable storage reference. */
38
40
  export const PIPELEX_STORAGE_SCHEME = "pipelex-storage://";
39
41
  /**
40
42
  * How many references one bulk resolve request takes — the route's bound, fixed
41
- * by the platform contract rather than configured per deployment. A longer list
43
+ * by the route's contract, the same on the platform and a self-hosted runner,
44
+ * rather than configured per deployment. A longer list
42
45
  * is a `422`, so {@link resolveArtifacts} chunks at this size.
43
46
  */
44
47
  export const BULK_RESOLVE_MAX_URIS = 100;
@@ -56,9 +59,9 @@ export const DEFAULT_DOWNLOAD_MAX_TOTAL_BYTES = 4 * 1024 * 1024 * 1024;
56
59
  export const DEFAULT_DOWNLOAD_CONCURRENCY = 4;
57
60
  /**
58
61
  * A link this close to its `expires_at` is re-resolved rather than fetched: the
59
- * object store checks the signature when the request arrives, and a few seconds
60
- * of clock skew between the platform and this process must not turn a link the
61
- * platform still considers live into a `403`.
62
+ * store checks the signature when the request arrives, and a few seconds of
63
+ * clock skew between the server that signed it and this process must not turn a
64
+ * link the server still considers live into a `403`.
62
65
  */
63
66
  const EXPIRY_MARGIN_MS = 10_000;
64
67
  /** Longest filename `downloadArtifacts` writes, extension included. */
@@ -111,6 +114,11 @@ const TEXT_EXTENSION_BY_KIND = {
111
114
  html: ".html",
112
115
  json: ".json",
113
116
  };
117
+ /** The `requirement` a resolve route's refusal names in its `params`, when it names one. */
118
+ function refusalRequirement(error) {
119
+ const requirement = error.params?.requirement;
120
+ return typeof requirement === "string" ? requirement : undefined;
121
+ }
114
122
  /** An object key rendered as `.key` in a path; any other key is rendered as `["…"]`. */
115
123
  const IDENTIFIER_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
116
124
  /**
@@ -299,7 +307,7 @@ export function isStorageReference(value) {
299
307
  }
300
308
  /**
301
309
  * A `url` a stored text may be loaded from: a `pipelex-storage://` reference, resolved through the
302
- * platform's bulk route to a link it signs, or a `data:` URL, decoded where it is. A stored text at
310
+ * server's bulk route to a link it signs, or a `data:` URL, decoded where it is. A stored text at
303
311
  * any other URL is never fetched, so a method cannot have the SDK read a host the caller did not
304
312
  * choose: the loader refuses it as `unsupported_url`.
305
313
  *
@@ -485,7 +493,7 @@ export async function resolveArtifacts(client, uris, options = {}) {
485
493
  // ── fetchArtifact ────────────────────────────────────────────────────
486
494
  /**
487
495
  * A bounded `Response` for one reference: the link is minted fresh through the
488
- * bulk route, then fetched with `redirect: "manual"` (a presigned link has no
496
+ * bulk route, then fetched with `redirect: "manual"` (a signed link has no
489
497
  * reason to redirect, and one that does is refused rather than followed), no
490
498
  * headers of ours (the link carries its own authorization in the query string,
491
499
  * and nothing must ride along to the object store), a budget covering the
@@ -505,17 +513,23 @@ export async function resolveArtifacts(client, uris, options = {}) {
505
513
  * propagate unchanged (`ApiResponseError`, `ApiUnreachableError`).
506
514
  */
507
515
  export async function fetchArtifact(client, uri, options = {}) {
508
- const bounds = fetchBounds(options);
516
+ const bounds = fetchBounds(options, client.originUrl);
509
517
  const [resolved] = await resolveArtifacts(client, [uri], { signal: options.signal });
510
518
  if (resolved.error !== null) {
511
- throw new ArtifactFetchError(resolved.error.detail, uri, resolved.error.code);
519
+ throw new ArtifactFetchError(resolved.error.detail, uri, resolved.error.code, undefined, {
520
+ requirement: refusalRequirement(resolved.error),
521
+ });
512
522
  }
513
523
  const dispatcher = await dispatcherFor(bounds.timeoutMs);
514
524
  return fetchResolvedUrl(uri, resolved.url, bounds, dispatcher, () => {
515
525
  void dispatcher?.close().catch(() => undefined);
516
526
  });
517
527
  }
518
- function fetchBounds(options) {
528
+ /**
529
+ * The bounds, defaults filled in and validated. `originUrl` is the client's own
530
+ * origin, the one on which a plain-http link is fetched without `allowHttp`.
531
+ */
532
+ function fetchBounds(options, originUrl) {
519
533
  const maxBytes = options.maxBytes ?? DEFAULT_ARTIFACT_MAX_BYTES;
520
534
  const timeoutMs = options.timeoutMs ?? DEFAULT_ARTIFACT_TIMEOUT_MS;
521
535
  requirePositive("maxBytes", maxBytes);
@@ -524,7 +538,34 @@ function fetchBounds(options) {
524
538
  throw new ArtifactOperationError(`"timeoutMs" must be a positive number no larger than ${MAX_TIMER_DELAY_MS}, got ` +
525
539
  `${String(timeoutMs)}.`, { problem: argumentInvalidProblem("timeoutMs", "not_positive") });
526
540
  }
527
- return { maxBytes, timeoutMs, allowHttp: options.allowHttp ?? false, signal: options.signal };
541
+ return {
542
+ maxBytes,
543
+ timeoutMs,
544
+ allowHttp: options.allowHttp ?? false,
545
+ clientOrigin: originOf(originUrl),
546
+ signal: options.signal,
547
+ };
548
+ }
549
+ /**
550
+ * The origin of an http(s) URL as compared: the WHATWG serialization, which
551
+ * lowercases the scheme and the host, encodes an internationalized name as IDNA,
552
+ * rewrites an IPv4 or IPv6 address in its canonical form (`127.1` is
553
+ * `127.0.0.1`) and drops a default port, so `http://localhost` and
554
+ * `http://LOCALHOST:80/` are one origin. Null for anything else, which then
555
+ * matches nothing. A name is never resolved: `127.0.0.1` and `localhost` are two
556
+ * origins.
557
+ */
558
+ function originOf(value) {
559
+ let url;
560
+ try {
561
+ url = new URL(value);
562
+ }
563
+ catch {
564
+ return null;
565
+ }
566
+ if (url.protocol !== "http:" && url.protocol !== "https:")
567
+ return null;
568
+ return url.origin;
528
569
  }
529
570
  function requirePositive(name, value) {
530
571
  if (!Number.isFinite(value) || value <= 0) {
@@ -553,25 +594,35 @@ async function dispatcherFor(timeoutMs) {
553
594
  return null;
554
595
  }
555
596
  }
556
- /** The parsed, boundary-approved URL — the object the fetch then uses verbatim. */
557
- function checkUrl(uri, downloadUrl, allowHttp) {
597
+ /**
598
+ * The parsed, boundary-approved URL — the object the fetch then uses verbatim. A
599
+ * plain-http link is fetched when the caller opted in with `allowHttp`, or when its
600
+ * origin is `clientOrigin`, the origin of the client's configured base URL: the
601
+ * client already sends its API key there, so a link to it reveals nothing the
602
+ * client does not already trust that server with. That is how a self-hosted runner
603
+ * listening on plain http hands back what it stores.
604
+ */
605
+ function checkUrl(uri, downloadUrl, allowHttp, clientOrigin) {
558
606
  let url;
559
607
  try {
560
608
  url = new URL(downloadUrl);
561
609
  }
562
610
  catch {
563
- throw new ArtifactFetchError("The platform resolved the reference to a link that is not a valid absolute URL.", uri, "unsupported_url");
611
+ throw new ArtifactFetchError("The server resolved the reference to a link that is not a valid absolute URL.", uri, "unsupported_url");
564
612
  }
565
- if (url.protocol === "http:" && !allowHttp) {
566
- throw new ArtifactFetchError("The platform resolved the reference to a plain http link, which is refused by default; " +
567
- "pass allowHttp: true to accept it (the local stack's object store hands out such links).", uri, "plain_http_refused");
613
+ if (url.protocol === "http:" &&
614
+ !allowHttp &&
615
+ (clientOrigin === null || url.origin !== clientOrigin)) {
616
+ throw new ArtifactFetchError("The server resolved the reference to a plain http link on an origin other than the " +
617
+ "client's own, which is refused by default; pass allowHttp: true to accept it (the local " +
618
+ "stack's object store hands out such links).", uri, "plain_http_refused");
568
619
  }
569
620
  if (url.protocol !== "https:" && url.protocol !== "http:") {
570
- throw new ArtifactFetchError(`The platform resolved the reference to a "${url.protocol.replace(":", "")}" link, which is not fetched; ` +
621
+ throw new ArtifactFetchError(`The server resolved the reference to a "${url.protocol.replace(":", "")}" link, which is not fetched; ` +
571
622
  "only http(s) links are.", uri, "unsupported_url");
572
623
  }
573
624
  if (url.username !== "" || url.password !== "") {
574
- throw new ArtifactFetchError("The platform resolved the reference to a link carrying credentials, which is not fetched.", uri, "unsupported_url");
625
+ throw new ArtifactFetchError("The server resolved the reference to a link carrying credentials, which is not fetched.", uri, "unsupported_url");
575
626
  }
576
627
  return url;
577
628
  }
@@ -584,7 +635,7 @@ function checkUrl(uri, downloadUrl, allowHttp) {
584
635
  async function fetchResolvedUrl(uri, downloadUrl, bounds, dispatcher, release) {
585
636
  let url;
586
637
  try {
587
- url = checkUrl(uri, downloadUrl, bounds.allowHttp);
638
+ url = checkUrl(uri, downloadUrl, bounds.allowHttp, bounds.clientOrigin);
588
639
  }
589
640
  catch (err) {
590
641
  release();
@@ -797,8 +848,20 @@ function formatMiB(bytes) {
797
848
  * text the runtime could read is never one the SDK refuses.
798
849
  */
799
850
  export const DEFAULT_STORED_TEXT_MAX_BYTES = 100 * 1024 * 1024;
851
+ /**
852
+ * The cap on the bytes of all the stored texts of one load together. Every loaded value is held
853
+ * until the load ends, as bytes and then as a string that can take twice as many, so the load
854
+ * itself must be bounded, not only each text: 256 MiB leaves room for two texts at the per-text
855
+ * cap while keeping what one load holds to a few hundred MiB of the process's memory.
856
+ */
857
+ export const DEFAULT_STORED_TEXT_MAX_TOTAL_BYTES = 256 * 1024 * 1024;
800
858
  /** How many stored texts one load reads at once. */
801
859
  export const DEFAULT_STORED_TEXT_CONCURRENCY = 8;
860
+ /**
861
+ * The `StoredTextLoadError` reason of a result that cannot say which of its values are stored
862
+ * texts ({@link lacksStoredTextConcepts}); `waitForResult` keeps polling through it for a while.
863
+ */
864
+ export const STORED_TEXT_CONCEPTS_MISSING = "concepts_missing";
802
865
  /**
803
866
  * A run's result with every stored text in `main_stuff` loaded: each value the runtime holds by
804
867
  * reference, `{ url, size, mime_type, preview }`, replaced by its inline form, `{ text }`,
@@ -808,23 +871,40 @@ export const DEFAULT_STORED_TEXT_CONCURRENCY = 8;
808
871
  *
809
872
  * Which values are stored texts is decided by concept, never by URL or MIME type: the concept at
810
873
  * 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
874
+ * results must carry them. A result that cannot say (no working memory naming the main stuff, or
875
+ * a concept of the method's own that no form describes) is returned as it is when nothing in
876
+ * `main_stuff` is shaped like a stored text's reference; when something is, it throws
877
+ * `StoredTextLoadError` with the reason `concepts_missing` rather than hand a reference on where a
878
+ * text is promised ({@link lacksStoredTextConcepts}). The runtime writes `output_form` after
879
+ * `main_stuff`, so a read can land in between: `waitForResult` keeps polling through that window
880
+ * for a few polls before it throws.
881
+ *
882
+ * A `pipelex-storage://` reference is resolved through the server's bulk route, at most
813
883
  * {@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
884
+ * `fetchArtifact`; a link within ten seconds of its `expires_at` when its read is about to start,
885
+ * having waited behind the other reads, is resolved again first. A `data:` URL is decoded, its
886
+ * size bounded from its length before it is. A stored text under any other URL
815
887
  * ({@link isLoadableStoredTextUrl}) is refused before anything is sent, since fetching it would
816
888
  * read a host the method chose rather than the caller; a result read with
817
889
  * `loadStoredTexts: false` keeps it as written. The bytes are UTF-8 by the standard's rule, and a
818
890
  * JSON value is the object they serialize.
819
891
  *
892
+ * Each text is bounded by `maxBytes` (100 MiB by default) and the load as a whole by
893
+ * `maxTotalBytes` (256 MiB by default), both checked first against the sizes the references state,
894
+ * before anything is sent, then as the bytes arrive; the first text that fails stops every other
895
+ * read in flight.
896
+ *
820
897
  * The result passed in is never changed: a new one is returned, or the same one when there is
821
898
  * nothing to load. Throws `StoredTextLoadError` naming the text that could not be loaded, where it
822
899
  * 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.
900
+ * route's error as its `cause`), the load's total over `maxTotalBytes` as
901
+ * `total_limit_exceeded`, and lets the caller's abort through.
824
902
  */
825
903
  export async function loadStoredTexts(client, results, options = {}) {
826
904
  if (results.main_stuff == null)
827
905
  return results;
906
+ if (lacksStoredTextConcepts(results))
907
+ throw conceptsMissingError(results);
828
908
  const node = mainStuffNode(results);
829
909
  if (node === null)
830
910
  return results;
@@ -879,6 +959,58 @@ export function mayHoldStoredTexts(value) {
879
959
  }
880
960
  return Object.values(fields).some(mayHoldStoredTexts);
881
961
  }
962
+ /**
963
+ * Whether a completed result cannot say which values of its `main_stuff` are stored texts while
964
+ * something there is shaped like one's reference ({@link mayHoldStoredTexts}): the working memory
965
+ * names no main stuff, or its concept is the method's own and no `output_form` / `input_form` node
966
+ * describes it, so a text in one of its fields could not be told from any other value. A native
967
+ * concept needs no form: the walk knows its shape. The runtime writes `output_form` after
968
+ * `main_stuff`, so a read can land in between; {@link loadStoredTexts} then throws
969
+ * `StoredTextLoadError` (`concepts_missing`) rather than hand a reference on.
970
+ */
971
+ export function lacksStoredTextConcepts(results) {
972
+ if (results.main_stuff == null || !mayHoldStoredTexts(results.main_stuff))
973
+ return false;
974
+ const conceptRef = mainStuffConceptRef(results);
975
+ if (conceptRef === null)
976
+ return true;
977
+ return !describesConcept(conceptRef, results);
978
+ }
979
+ /** The `concepts_missing` failure, naming the first value shaped like a stored text's reference. */
980
+ function conceptsMissingError(results) {
981
+ const shaped = firstReferenceShape(results.main_stuff);
982
+ const path = renderPath(shaped?.segments ?? []);
983
+ return new StoredTextLoadError(`The stored text at ${path} could not be loaded: the result does not say which of its values ` +
984
+ "are stored texts (its working_memory or its output_form is missing), so none is handed on " +
985
+ "as its reference; read the result again in a moment, or with loadStoredTexts: false to see " +
986
+ "it as written.", { uri: shaped?.url ?? "", path, reason: STORED_TEXT_CONCEPTS_MISSING }, { problem: responseUnreadableProblem(200, results.pipeline_run_id) });
987
+ }
988
+ /** The first value {@link mayHoldStoredTexts} answers for, depth first, with where it sits. */
989
+ function firstReferenceShape(value, segments = []) {
990
+ if (Array.isArray(value)) {
991
+ for (const [index, entry] of value.entries()) {
992
+ const found = firstReferenceShape(entry, [...segments, index]);
993
+ if (found !== null)
994
+ return found;
995
+ }
996
+ return null;
997
+ }
998
+ if (typeof value !== "object" || value === null)
999
+ return null;
1000
+ const fields = value;
1001
+ const url = fields["url"];
1002
+ if (typeof url === "string" &&
1003
+ Object.values(STORED_TEXT_VALUE_FIELD).every((field) => fields[field] == null) &&
1004
+ ("size" in fields || "preview" in fields)) {
1005
+ return { segments, url };
1006
+ }
1007
+ for (const [key, entry] of Object.entries(fields)) {
1008
+ const found = firstReferenceShape(entry, [...segments, key]);
1009
+ if (found !== null)
1010
+ return found;
1011
+ }
1012
+ return null;
1013
+ }
882
1014
  /**
883
1015
  * Whether a results read narrowed to `selection` carried every artifact the concept at each path
884
1016
  * is read from: the working memory and both forms. `undefined`, a read of every artifact, does.
@@ -895,66 +1027,139 @@ async function loadStoredTextValues(client, value, node, options, runId) {
895
1027
  if (!Number.isInteger(concurrency) || concurrency < 1) {
896
1028
  throw new ArtifactOperationError(`"concurrency" must be a positive integer, got ${String(concurrency)}.`, { problem: argumentInvalidProblem("concurrency", "not_positive") });
897
1029
  }
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
- });
1030
+ const maxTotalBytes = options.maxTotalBytes ?? DEFAULT_STORED_TEXT_MAX_TOTAL_BYTES;
1031
+ requirePositive("maxTotalBytes", maxTotalBytes);
1032
+ const maxBytes = options.maxBytes ?? DEFAULT_STORED_TEXT_MAX_BYTES;
1033
+ requirePositive("maxBytes", maxBytes);
904
1034
  // One read per distinct URL, named by the first place it was found.
905
1035
  const firstSite = new Map();
906
1036
  for (const site of sites)
907
1037
  if (!firstSite.has(site.url))
908
1038
  firstSite.set(site.url, site);
909
1039
  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]));
1040
+ // Refused before anything is sent: a text whose reference states a size over the cap on one
1041
+ // text, and texts whose stated sizes together are over the load's cap.
1042
+ let declaredTotal = 0;
1043
+ for (const url of urls) {
1044
+ const site = firstSite.get(url);
1045
+ const size = site.reference["size"];
1046
+ if (typeof size !== "number" || !(size > 0))
1047
+ continue;
1048
+ if (size > maxBytes)
1049
+ throw overTextCap(site, maxBytes, size);
1050
+ declaredTotal += size;
1051
+ if (declaredTotal > maxTotalBytes)
1052
+ throw overLoadCap(site, maxTotalBytes);
1053
+ }
1054
+ // The first failure stops new reads from starting and stops the reads in flight, through one
1055
+ // signal linked with the caller's; the load then throws that first failure once every read has
1056
+ // settled, or the caller's abort as it is.
1057
+ const stop = new AbortController();
1058
+ const stopping = eitherSignal(stop.signal, options.signal);
1059
+ // Everything after the link is in its disposal scope: a setup that fails, the bulk resolve
1060
+ // above all, must not leave a listener on a caller's long-lived signal.
1061
+ let dispatcher = null;
931
1062
  const texts = new Map();
932
- const dispatcher = await dispatcherFor(bounds.timeoutMs);
1063
+ let failed = false;
1064
+ let firstFailure;
933
1065
  try {
1066
+ const bounds = fetchBounds({
1067
+ maxBytes,
1068
+ timeoutMs: options.timeoutMs,
1069
+ allowHttp: options.allowHttp,
1070
+ signal: stopping.signal,
1071
+ }, client.originUrl);
1072
+ const references = urls.filter(isStorageReference);
1073
+ const resolved = new Map();
1074
+ const items = await resolveForTexts(client, references, firstSite, options.signal);
1075
+ references.forEach((uri, index) => resolved.set(uri, items[index]));
1076
+ // Every byte read counts against the load's budget, whatever the references state.
1077
+ let held = 0;
1078
+ const take = (bytes) => {
1079
+ held += bytes;
1080
+ return held <= maxTotalBytes;
1081
+ };
1082
+ dispatcher = await dispatcherFor(bounds.timeoutMs);
1083
+ const readOne = async (url) => {
1084
+ const site = firstSite.get(url);
1085
+ let entry = resolved.get(url);
1086
+ // A link resolved before the reads ahead of it is resolved again just before its own read.
1087
+ if (entry !== undefined && entry.error === null && isExpired(entry.expires_at)) {
1088
+ [entry] = await resolveForTexts(client, [url], firstSite, stopping.signal);
1089
+ }
1090
+ const bytes = await readStoredBytes(site, entry, bounds, maxTotalBytes, take, dispatcher);
1091
+ texts.set(url, decodeStoredValue(site, bytes, runId));
1092
+ };
934
1093
  let next = 0;
935
1094
  const worker = async () => {
936
- for (;;) {
937
- const index = next;
1095
+ while (!failed && next < urls.length) {
1096
+ const url = urls[next];
938
1097
  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));
1098
+ try {
1099
+ await readOne(url);
1100
+ }
1101
+ catch (err) {
1102
+ if (!failed) {
1103
+ failed = true;
1104
+ firstFailure = err;
1105
+ stop.abort(err);
1106
+ }
1107
+ }
945
1108
  }
946
1109
  };
947
1110
  await Promise.all(Array.from({ length: Math.min(concurrency, urls.length) }, worker));
948
1111
  }
949
1112
  finally {
1113
+ stopping.dispose();
950
1114
  void dispatcher?.close().catch(() => undefined);
951
1115
  }
1116
+ if (failed) {
1117
+ if (options.signal?.aborted === true)
1118
+ throw options.signal.reason;
1119
+ throw firstFailure;
1120
+ }
952
1121
  let loaded = structuredClone(value);
953
1122
  for (const site of sites) {
954
1123
  loaded = replaceAt(loaded, site.segments, loadedForm(site, texts.get(site.url)));
955
1124
  }
956
1125
  return loaded;
957
1126
  }
1127
+ /**
1128
+ * The bulk resolve of stored texts' references, a whole-request failure being the first text's
1129
+ * `StoredTextLoadError` (`resolve_failed`); the caller's abort goes through as it is.
1130
+ */
1131
+ async function resolveForTexts(client, references, firstSite, signal) {
1132
+ try {
1133
+ return await resolveArtifacts(client, references, { signal });
1134
+ }
1135
+ catch (err) {
1136
+ if (signal?.aborted === true)
1137
+ throw signal.reason;
1138
+ // A whole-request failure of the route, a bare runner's 404 among them, is the first text's.
1139
+ const site = firstSite.get(references[0]);
1140
+ const path = renderPath(site.segments);
1141
+ const detail = err instanceof Error ? err.message : String(err);
1142
+ throw new StoredTextLoadError(`The stored text at ${path} could not be loaded: the bulk resolve route failed: ${detail}`, {
1143
+ uri: site.url,
1144
+ path,
1145
+ reason: "resolve_failed",
1146
+ status: err instanceof ApiResponseError ? err.status : undefined,
1147
+ }, { cause: err, problem: err instanceof ProblemError ? err.problem : undefined });
1148
+ }
1149
+ }
1150
+ /** A stored text over the cap on one text; `size` when its reference or its length states it. */
1151
+ function overTextCap(site, maxBytes, size) {
1152
+ const path = renderPath(site.segments);
1153
+ const over = `over the ${formatMiB(maxBytes)} cap.`;
1154
+ return new StoredTextLoadError(`The stored text at ${path} could not be loaded: it is ` +
1155
+ (size === undefined ? over : `${formatMiB(size)}, ${over}`), { uri: site.url, path, reason: "too_large" }, { problem: downloadLimitProblem(maxBytes) });
1156
+ }
1157
+ /** A stored text that takes the load's texts together over `maxTotalBytes`. */
1158
+ function overLoadCap(site, maxTotalBytes) {
1159
+ const path = renderPath(site.segments);
1160
+ return new StoredTextLoadError(`The stored text at ${path} could not be loaded: with the texts loaded before it, the load ` +
1161
+ `is over its ${formatMiB(maxTotalBytes)} total limit (maxTotalBytes).`, { uri: site.url, path, reason: "total_limit_exceeded" }, { problem: downloadLimitProblem(maxTotalBytes) });
1162
+ }
958
1163
  /**
959
1164
  * Every stored text's reference in `value`, in walk order, the concept at each path read off
960
1165
  * `node`. Throws `StoredTextLoadError` (`unsupported_url`) for a stored text whose `url` the
@@ -1002,35 +1207,66 @@ function findStoredTexts(value, node) {
1002
1207
  visit(value, node);
1003
1208
  return sites;
1004
1209
  }
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) {
1210
+ /**
1211
+ * The bytes of one stored text: a reference's signed link fetched, or a `data:` URL decoded.
1212
+ * Nothing else is read. Every chunk is taken from the load's budget as it arrives, and the read
1213
+ * is cut once the budget is crossed.
1214
+ */
1215
+ async function readStoredBytes(site, resolved, bounds, maxTotalBytes, take, dispatcher) {
1007
1216
  const path = renderPath(site.segments);
1008
1217
  const fail = (reason, detail, extra) => {
1009
- 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 });
1218
+ throw new StoredTextLoadError(`The stored text at ${path} could not be loaded: ${detail}`, { uri: site.url, path, reason, status: extra?.status, requirement: extra?.requirement }, { cause: extra?.cause, problem: extra?.problem });
1010
1219
  };
1011
1220
  if (site.url.startsWith("data:")) {
1012
- const bytes = decodeDataUrl(site.url);
1013
- if (bytes === null)
1221
+ const bytes = decodeDataUrl(site.url, bounds.maxBytes);
1222
+ if (bytes === "malformed")
1014
1223
  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
- }
1224
+ if (bytes === "too_large")
1225
+ throw overTextCap(site, bounds.maxBytes);
1226
+ if (!take(bytes.byteLength))
1227
+ throw overLoadCap(site, maxTotalBytes);
1020
1228
  return bytes;
1021
1229
  }
1022
1230
  // Unreachable: the walk admits only a reference or a data: URL, and every reference is resolved first.
1023
1231
  if (resolved === undefined) {
1024
- return fail("unsupported_url", "its url was not resolved by the platform.");
1232
+ return fail("unsupported_url", "its url was not resolved by the bulk resolve route.");
1233
+ }
1234
+ if (resolved.error !== null) {
1235
+ return fail(resolved.error.code, resolved.error.detail, {
1236
+ requirement: refusalRequirement(resolved.error),
1237
+ });
1025
1238
  }
1026
- if (resolved.error !== null)
1027
- return fail(resolved.error.code, resolved.error.detail);
1028
1239
  const link = resolved.url;
1240
+ let reader;
1029
1241
  try {
1030
1242
  const response = await fetchResolvedUrl(site.url, link, bounds, dispatcher, () => undefined);
1031
- return new Uint8Array(await response.arrayBuffer());
1243
+ if (response.body === null)
1244
+ return new Uint8Array(0);
1245
+ reader = response.body.getReader();
1246
+ const chunks = [];
1247
+ let total = 0;
1248
+ for (;;) {
1249
+ const chunk = await reader.read();
1250
+ if (chunk.done)
1251
+ break;
1252
+ if (!take(chunk.value.byteLength)) {
1253
+ await reader.cancel().catch(() => undefined);
1254
+ throw overLoadCap(site, maxTotalBytes);
1255
+ }
1256
+ chunks.push(chunk.value);
1257
+ total += chunk.value.byteLength;
1258
+ }
1259
+ const bytes = new Uint8Array(total);
1260
+ let offset = 0;
1261
+ for (const chunk of chunks) {
1262
+ bytes.set(chunk, offset);
1263
+ offset += chunk.byteLength;
1264
+ }
1265
+ return bytes;
1032
1266
  }
1033
1267
  catch (err) {
1268
+ if (err instanceof StoredTextLoadError)
1269
+ throw err;
1034
1270
  if (bounds.signal?.aborted === true)
1035
1271
  throw bounds.signal.reason;
1036
1272
  if (err instanceof ArtifactFetchError) {
@@ -1038,28 +1274,101 @@ async function readStoredBytes(site, resolved, bounds, dispatcher) {
1038
1274
  cause: err,
1039
1275
  problem: err.problem,
1040
1276
  status: err.status,
1277
+ requirement: err.requirement,
1041
1278
  });
1042
1279
  }
1043
1280
  return fail("unknown", err instanceof Error ? err.message : String(err), { cause: err });
1044
1281
  }
1045
1282
  }
1046
- /** A `data:` URL's bytes, base64 or percent-encoded, or `null` when it is no data URL. */
1047
- function decodeDataUrl(url) {
1283
+ /**
1284
+ * The bytes a percent-encoded payload decodes to, counted in one pass that copies nothing: an
1285
+ * escape `%XX` is one byte and any other character its UTF-8 length, a surrogate pair four. A `%`
1286
+ * not followed by two hex digits makes `decodeURIComponent` refuse the payload anyway. The count
1287
+ * stops once it passes `limit`.
1288
+ */
1289
+ function percentDecodedLength(payload, limit) {
1290
+ let count = 0;
1291
+ for (let index = 0; index < payload.length && count <= limit; index += 1) {
1292
+ const code = payload.charCodeAt(index);
1293
+ if (code === 37) {
1294
+ count += 1;
1295
+ index += 2;
1296
+ }
1297
+ else if (code < 0x80) {
1298
+ count += 1;
1299
+ }
1300
+ else if (code < 0x800) {
1301
+ count += 2;
1302
+ }
1303
+ else if (code >= 0xd800 && code <= 0xdbff && index + 1 < payload.length) {
1304
+ count += 4;
1305
+ index += 1;
1306
+ }
1307
+ else {
1308
+ count += 3;
1309
+ }
1310
+ }
1311
+ return count;
1312
+ }
1313
+ /** The characters of a base64 payload that are not ASCII whitespace, counted in one pass. */
1314
+ function base64Significant(payload) {
1315
+ let count = 0;
1316
+ for (let index = 0; index < payload.length; index += 1) {
1317
+ const code = payload.charCodeAt(index);
1318
+ // Tab, line feed, form feed, carriage return and space: what forgiving-base64 drops.
1319
+ if (code !== 9 && code !== 10 && code !== 12 && code !== 13 && code !== 32)
1320
+ count += 1;
1321
+ }
1322
+ return count;
1323
+ }
1324
+ /**
1325
+ * A `data:` URL's bytes, base64 or percent-encoded; `"malformed"` when it does not decode, and
1326
+ * `"too_large"` when its bytes would be over `maxBytes`, told from the payload's length before
1327
+ * anything is decoded.
1328
+ *
1329
+ * Base64 is read as `atob` reads it (the WHATWG forgiving-base64 decode): ASCII whitespace
1330
+ * dropped, at most two `=` of padding when the length is a multiple of four, then a length that is
1331
+ * not one past a multiple of four and nothing outside the alphabet. Every test is one linear pass,
1332
+ * never a pattern a method's payload could drive into backtracking.
1333
+ */
1334
+ function decodeDataUrl(url, maxBytes) {
1048
1335
  const comma = url.indexOf(",");
1049
1336
  if (comma < 0)
1050
- return null;
1337
+ return "malformed";
1051
1338
  const header = url.slice("data:".length, comma);
1052
1339
  const payload = url.slice(comma + 1);
1053
- try {
1054
- if (/;base64$/i.test(header)) {
1055
- const binary = atob(payload);
1340
+ if (/;base64$/i.test(header)) {
1341
+ // Refused from a count that copies nothing before the whitespace is stripped, so a payload
1342
+ // over the cap is never copied: at most two of the characters counted are padding.
1343
+ if (Math.floor(((base64Significant(payload) - 2) * 3) / 4) > maxBytes)
1344
+ return "too_large";
1345
+ let data = payload.replace(/[\t\n\f\r ]+/g, "");
1346
+ if (data.length % 4 === 0 && data.endsWith("=")) {
1347
+ data = data.slice(0, data.endsWith("==") ? -2 : -1);
1348
+ }
1349
+ if (data.length % 4 === 1 || /[^A-Za-z0-9+/]/.test(data))
1350
+ return "malformed";
1351
+ if (Math.floor((data.length * 3) / 4) > maxBytes)
1352
+ return "too_large";
1353
+ try {
1354
+ const binary = atob(data);
1056
1355
  return Uint8Array.from(binary, (char) => char.charCodeAt(0));
1057
1356
  }
1058
- return new TextEncoder().encode(decodeURIComponent(payload));
1357
+ catch {
1358
+ return "malformed";
1359
+ }
1360
+ }
1361
+ // Counted exactly before anything is decoded, so a payload over the cap is never copied.
1362
+ if (percentDecodedLength(payload, maxBytes) > maxBytes)
1363
+ return "too_large";
1364
+ let bytes;
1365
+ try {
1366
+ bytes = new TextEncoder().encode(decodeURIComponent(payload));
1059
1367
  }
1060
1368
  catch {
1061
- return null;
1369
+ return "malformed";
1062
1370
  }
1371
+ return bytes.byteLength > maxBytes ? "too_large" : bytes;
1063
1372
  }
1064
1373
  /** The value one stored text holds: its UTF-8 text, or for a JSON value the object that text serializes. */
1065
1374
  function decodeStoredValue(site, bytes, runId) {
@@ -1160,7 +1469,7 @@ class ArtifactWriteError extends Error {
1160
1469
  const SKIPPED_ABORTED = "The download was aborted before this artifact was fetched.";
1161
1470
  const SKIPPED_CREDENTIAL = "The download stopped on a credential failure before this artifact was fetched.";
1162
1471
  const SKIPPED_TOTAL = "Skipped: the download's total byte limit was reached by an earlier artifact.";
1163
- function itemError(location, contentType, code, detail) {
1472
+ function itemError(location, contentType, code, detail, params) {
1164
1473
  return {
1165
1474
  uri: location.uri,
1166
1475
  kind: location.kind,
@@ -1168,7 +1477,7 @@ function itemError(location, contentType, code, detail) {
1168
1477
  path: null,
1169
1478
  content_type: contentType,
1170
1479
  size: null,
1171
- error: { code, detail },
1480
+ error: params === undefined || params === null ? { code, detail } : { code, detail, params },
1172
1481
  };
1173
1482
  }
1174
1483
  function isExpired(expiresAt) {
@@ -1241,7 +1550,7 @@ export async function downloadArtifacts(client, request) {
1241
1550
  throw new ArtifactOperationError(`"concurrency" must be a positive integer, got ${String(concurrency)}.`, { problem: argumentInvalidProblem("concurrency", "not_positive") });
1242
1551
  }
1243
1552
  requirePositive("maxTotalBytes", maxTotalBytes);
1244
- const bounds = fetchBounds(request);
1553
+ const bounds = fetchBounds(request, client.originUrl);
1245
1554
  const hasRunId = typeof request.run_id === "string" && request.run_id !== "";
1246
1555
  const hasResults = request.results != null;
1247
1556
  if (hasRunId === hasResults) {
@@ -1279,7 +1588,7 @@ export async function downloadArtifacts(client, request) {
1279
1588
  kind: reference.text === undefined ? "file" : "text",
1280
1589
  }));
1281
1590
  const uris = located.map((reference) => reference.uri);
1282
- // A stored text's MIME type is its reference's, the platform's guess from the key otherwise.
1591
+ // A stored text's MIME type is its reference's, the server's guess from the key otherwise.
1283
1592
  const contentTypeOf = (index, resolvedType) => {
1284
1593
  const stated = located[index].text?.reference["mime_type"];
1285
1594
  return typeof stated === "string" ? stated : resolvedType;
@@ -1328,7 +1637,7 @@ export async function downloadArtifacts(client, request) {
1328
1637
  const aborted = () => signal?.aborted === true;
1329
1638
  const workerBounds = { ...bounds, signal };
1330
1639
  // A credential refusal on a re-resolve stops the workers taking new items, and
1331
- // nothing else: a fetch already running is on a presigned link that does not
1640
+ // nothing else: a fetch already running is on a signed link that does not
1332
1641
  // carry the credential, so it is left to finish and its file is kept.
1333
1642
  let credentialFailure;
1334
1643
  // What the total cap is held against: the bytes of every file saved or being
@@ -1489,7 +1798,7 @@ export async function downloadArtifacts(client, request) {
1489
1798
  }
1490
1799
  }
1491
1800
  if (entry.error !== null) {
1492
- outcomes[index] = itemError(location, contentTypeOf(index, null), entry.error.code, entry.error.detail);
1801
+ outcomes[index] = itemError(location, contentTypeOf(index, null), entry.error.code, entry.error.detail, entry.error.params);
1493
1802
  continue;
1494
1803
  }
1495
1804
  outcomes[index] = await saveOne(index, entry.url, contentTypeOf(index, entry.content_type));