@foldrun/core 17.3.0 → 17.4.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.
Files changed (65) hide show
  1. package/dist/src/approvals.js +3 -3
  2. package/dist/src/blob-cache.d.ts +58 -0
  3. package/dist/src/blob-cache.js +309 -0
  4. package/dist/src/blob-pins.d.ts +44 -0
  5. package/dist/src/blob-pins.js +61 -0
  6. package/dist/src/blob-store.d.ts +47 -0
  7. package/dist/src/blob-store.js +357 -0
  8. package/dist/src/blob-sweeper.d.ts +70 -0
  9. package/dist/src/blob-sweeper.js +254 -0
  10. package/dist/src/blob-types.d.ts +145 -0
  11. package/dist/src/blob-types.js +115 -0
  12. package/dist/src/evals.js +1 -1
  13. package/dist/src/history.d.ts +86 -9
  14. package/dist/src/history.js +132 -16
  15. package/dist/src/journal-store.d.ts +58 -0
  16. package/dist/src/journal-store.js +117 -0
  17. package/dist/src/manifest.d.ts +92 -0
  18. package/dist/src/manifest.js +239 -0
  19. package/dist/src/ops-log.js +26 -3
  20. package/dist/src/platform.d.ts +7 -0
  21. package/dist/src/platform.js +1 -0
  22. package/dist/src/publish.d.ts +134 -0
  23. package/dist/src/publish.js +434 -0
  24. package/dist/src/records.d.ts +72 -0
  25. package/dist/src/records.js +24 -0
  26. package/dist/src/revision-store.d.ts +161 -0
  27. package/dist/src/revision-store.js +378 -0
  28. package/dist/src/run-container.d.ts +20 -0
  29. package/dist/src/run-container.js +61 -0
  30. package/dist/src/runner.js +1 -1
  31. package/dist/src/s3-blob-store.d.ts +29 -0
  32. package/dist/src/s3-blob-store.js +458 -0
  33. package/dist/src/state-retention.d.ts +15 -0
  34. package/dist/src/state-retention.js +65 -0
  35. package/dist/src/storage.d.ts +29 -1
  36. package/dist/src/storage.js +331 -81
  37. package/dist/src/store.d.ts +41 -0
  38. package/dist/src/store.js +188 -5
  39. package/dist/src/trigger-log.js +17 -0
  40. package/dist/src/workspace-revisions.d.ts +259 -0
  41. package/dist/src/workspace-revisions.js +1274 -0
  42. package/package.json +1 -1
  43. package/src/approvals.ts +3 -3
  44. package/src/blob-cache.ts +354 -0
  45. package/src/blob-pins.ts +99 -0
  46. package/src/blob-store.ts +385 -0
  47. package/src/blob-sweeper.ts +308 -0
  48. package/src/blob-types.ts +216 -0
  49. package/src/evals.ts +1 -1
  50. package/src/history.ts +182 -16
  51. package/src/journal-store.ts +152 -0
  52. package/src/manifest.ts +274 -0
  53. package/src/ops-log.ts +25 -3
  54. package/src/platform.ts +8 -0
  55. package/src/publish.ts +520 -0
  56. package/src/records.ts +105 -0
  57. package/src/revision-store.ts +513 -0
  58. package/src/run-container.ts +62 -0
  59. package/src/runner.ts +1 -1
  60. package/src/s3-blob-store.ts +489 -0
  61. package/src/state-retention.ts +83 -0
  62. package/src/storage.ts +335 -81
  63. package/src/store.ts +178 -5
  64. package/src/trigger-log.ts +15 -0
  65. package/src/workspace-revisions.ts +1324 -0
@@ -26,6 +26,7 @@ import crypto from "node:crypto";
26
26
  import { spawn, spawnSync } from "node:child_process";
27
27
  import { CAPTURE_CAP, isPlatformPath } from "./store.js";
28
28
  import { divertedSummary, isDivertedPath, overlayTestWrites } from "./test-mode.js";
29
+ import { recordStepOutputs, pinRunBase } from "./workspace-revisions.js";
29
30
  import { refusedBack, refusedLine, keptLine } from "./copy-back.js";
30
31
  import { isFileValue, fileContent, installKeyMaterial } from "./secrets.js";
31
32
  import { safeTenantSegment, systemInstallSh, SYSTEM_FROM_INPUT_SH, INSTALL_SOCKET, ROOT_ENV_RESET_SH, ROOT_SHELL_GUARD_SH, ROOT_ENV_FILE, STEP_ENV_FILE, stepEnvShell, rootEnvShell, SNAPSHOT_KEY_FILE } from "./runtime.js";
@@ -201,6 +202,39 @@ export function dropHandedIn(workspaceRoot, runId, ref) {
201
202
  const file = handedInPath(workspaceRoot, runId, ref);
202
203
  if (file)
203
204
  fs.rmSync(file, { force: true });
205
+ const base = baseRevisionPath(workspaceRoot, runId, ref);
206
+ if (base)
207
+ fs.rmSync(base, { force: true });
208
+ }
209
+ /**
210
+ * The revisions a step's stage-in started from (FOL-126 fixes), kept on the host
211
+ * beside what it was handed, for the same reason: a driver that inherits the
212
+ * step publishes its copy-back against the SAME base, not against whatever the
213
+ * heads hold by then. Platform-owned, never staged, erased with the run.
214
+ */
215
+ export function baseRevisionPath(workspaceRoot, runId, ref) {
216
+ const file = handedInPath(workspaceRoot, runId, ref);
217
+ return file ? file.replace(/\.json$/, ".base.json") : null;
218
+ }
219
+ export function writeBaseRevision(workspaceRoot, runId, ref, base) {
220
+ const file = baseRevisionPath(workspaceRoot, runId, ref);
221
+ if (!file)
222
+ return;
223
+ fs.mkdirSync(path.dirname(file), { recursive: true });
224
+ fs.writeFileSync(file, JSON.stringify(base));
225
+ }
226
+ export function readBaseRevision(workspaceRoot, runId, ref) {
227
+ const file = baseRevisionPath(workspaceRoot, runId, ref);
228
+ if (!file)
229
+ return undefined;
230
+ try {
231
+ const m = JSON.parse(fs.readFileSync(file, "utf8"));
232
+ const ok = (v) => v === null || typeof v === "string";
233
+ return m && ok(m.workspace) && ok(m.state) ? { workspace: m.workspace ?? null, state: m.state ?? null } : undefined;
234
+ }
235
+ catch {
236
+ return undefined;
237
+ }
204
238
  }
205
239
  /**
206
240
  * Every file's mtime under `dir`, relative path to milliseconds — so a copy
@@ -286,6 +320,7 @@ export function mergeAppends(was, host, next) {
286
320
  }
287
321
  export function applyContainerChanges(hostWs, containerWs, baseline, note, divert, opts = {}) {
288
322
  const applied = [];
323
+ const written = [];
289
324
  // Files a sandbox: own job's reply copied into this sandbox mid-step
290
325
  // (delegate-tools.ts copyBackFiles), path → sha256 of what was written: for
291
326
  // those, that is what the step started from. The job's change is already on
@@ -377,10 +412,16 @@ export function applyContainerChanges(hostWs, containerWs, baseline, note, diver
377
412
  // other run's ledger rows on 2026-09-14. Merge appends; keep both
378
413
  // sides of anything else.
379
414
  const hostMoved = was !== undefined && hostNow !== null && !same(hostNow);
415
+ // What the step was handed, as a sha (null: no such file; undefined: not
416
+ // known). It is the base the head is held to — unless the folder was
417
+ // merged, which already folded the other writer's change in.
418
+ const handed = was === undefined ? undefined : was === null ? null : typeof was === "string" ? was : sha(was);
419
+ let foldedIn = false;
380
420
  if (hostMoved) {
381
421
  const merged = mergeAppends(was ?? null, hostNow, next);
382
422
  if (merged) {
383
423
  next = merged;
424
+ foldedIn = true;
384
425
  }
385
426
  else {
386
427
  const ext = path.extname(rel);
@@ -390,6 +431,7 @@ export function applyContainerChanges(hostWs, containerWs, baseline, note, diver
390
431
  fs.mkdirSync(path.dirname(conflictAbs), { recursive: true });
391
432
  fs.writeFileSync(conflictAbs, next);
392
433
  applied.push(conflictRel);
434
+ written.push({ path: conflictRel.replaceAll("\\", "/"), base: null, after: next });
393
435
  note?.(`write-back conflict on ${rel.replaceAll("\\", "/")}: it changed on the workspace while this step ran, ` +
394
436
  `and not only by appending — kept the workspace's version; this step's version is ${conflictRel.replaceAll("\\", "/")}`);
395
437
  continue;
@@ -410,9 +452,22 @@ export function applyContainerChanges(hostWs, containerWs, baseline, note, diver
410
452
  fs.mkdirSync(path.dirname(target), { recursive: true });
411
453
  fs.writeFileSync(target, next);
412
454
  applied.push(rel);
455
+ // The pinned base is what the folder held before this write (null: a new
456
+ // file) — for an untouched path that is what the step was handed.
457
+ written.push({ path: rel.replaceAll("\\", "/"), base: hostNow ? sha(hostNow) : null, after: next, handed: foldedIn ? undefined : handed });
413
458
  }
414
459
  };
415
460
  walk(containerWs);
461
+ // The step's outputs as one revision (all its paths, or none). Never allowed
462
+ // to fail the copy-back: the folder is written already.
463
+ if (opts.revision && written.length) {
464
+ try {
465
+ recordStepOutputs(opts.revision.tenant, path.basename(hostWs), written, { runId: opts.revision.runId, step: opts.revision.step, base: opts.revision.base });
466
+ }
467
+ catch (err) {
468
+ note?.(`the step's files were written to the workspace but not recorded as a revision yet: ${err instanceof Error ? err.message : String(err)}`);
469
+ }
470
+ }
416
471
  return applied;
417
472
  }
418
473
  // ---------- the dependency cache ----------
@@ -1751,7 +1806,11 @@ export async function runStepInContainer(args) {
1751
1806
  args.emit("info", line);
1752
1807
  const staging = fs.mkdtempSync(path.join(os.tmpdir(), "foldrun-run-"));
1753
1808
  let containerId = "";
1809
+ // The revisions this step starts from (FOL-126 fixes): taken before the
1810
+ // folder is copied, held until the copy-back is done.
1811
+ let pinned = null;
1754
1812
  try {
1813
+ pinned = args.tenant ? await pinRunBase(args.tenant, path.basename(args.workspaceRoot), `${args.runId ?? "step"}:${crypto.randomBytes(4).toString("hex")}`) : null;
1755
1814
  // Stage the workspace copy minus what the platform owns — the vault,
1756
1815
  // hook state, run history. The container gets the trust boundary, not
1757
1816
  // the bookkeeping. One definition of "platform-owned" for this filter,
@@ -1940,6 +1999,7 @@ export async function runStepInContainer(args) {
1940
1999
  onRefused: (r) => refused.push(r),
1941
2000
  allowConfig: args.configWrites === true,
1942
2001
  onKept: (r) => kept.push(r),
2002
+ revision: args.tenant ? { tenant: args.tenant, runId: args.runId, step: containerId, base: pinned?.base ?? null } : undefined,
1943
2003
  });
1944
2004
  if (refused.length)
1945
2005
  args.emit("info", refusedLine(refused));
@@ -1965,5 +2025,6 @@ export async function runStepInContainer(args) {
1965
2025
  if (containerId)
1966
2026
  spawnSync(cli(), ["rm", "-f", containerId], { stdio: "ignore" });
1967
2027
  fs.rmSync(staging, { recursive: true, force: true });
2028
+ await pinned?.release();
1968
2029
  }
1969
2030
  }
@@ -4604,7 +4604,7 @@ function driveRunInner(tenant, workspace, run, modelOverride, tags, opts) {
4604
4604
  // /source makes one too. A re-run comes through here as well.
4605
4605
  run.drivenAt ??= new Date().toISOString();
4606
4606
  if (run.revision === undefined)
4607
- run.revision = latestRevisionId(tenant, workspace);
4607
+ run.revision = await latestRevisionId(tenant, workspace);
4608
4608
  if (run.status !== "running") {
4609
4609
  run.status = "running";
4610
4610
  run.parkedAt = null;
@@ -0,0 +1,29 @@
1
+ import { type S3Config } from "./storage.ts";
2
+ import { bufferSource, type BlobStore, type BlobSweeper } from "./blob-types.ts";
3
+ /** S3's floor for every part but the last. R2 and MinIO enforce the same. */
4
+ export declare const MIN_PART_BYTES: number;
5
+ /** S3's ceiling on the number of parts. */
6
+ export declare const MAX_PARTS = 10000;
7
+ export interface S3BlobOptions {
8
+ /** Objects at or above this many bytes go up as multipart. */
9
+ multipartThresholdBytes: number;
10
+ /** Size of every part but the last. Raised if the object would need more
11
+ * than MAX_PARTS; never below MIN_PART_BYTES. */
12
+ partBytes: number;
13
+ /** Parts in flight at once for ONE upload. */
14
+ partConcurrency: number;
15
+ /** Per-part (and per single request) deadline floor and the throughput the
16
+ * deadline assumes on top of it. */
17
+ requestDeadlineMs: number;
18
+ minBytesPerSec: number;
19
+ }
20
+ export declare const DEFAULT_S3_OPTIONS: S3BlobOptions;
21
+ export declare function s3OptionsFromEnv(env?: NodeJS.ProcessEnv): S3BlobOptions;
22
+ /** The part size for an object: the configured one, raised until the object
23
+ * fits in MAX_PARTS parts. Every part but the last is exactly this size —
24
+ * R2 requires uniform parts, S3 and MinIO do not mind. */
25
+ export declare function planPartBytes(size: number, configured: number): number;
26
+ export declare function s3BlobStore(cfg: S3Config, given?: Partial<S3BlobOptions>): BlobStore & BlobSweeper & {
27
+ checkBucket(signal?: AbortSignal): Promise<void>;
28
+ };
29
+ export { bufferSource };
@@ -0,0 +1,458 @@
1
+ // The s3 BlobStore driver (FOL-126): any S3-compatible endpoint (AWS, R2,
2
+ // MinIO), signed by the code in storage.ts — no SDK.
3
+ //
4
+ // What it does beyond "PUT/GET with a signature", each point learnt by running
5
+ // it against a real server (MinIO) instead of the in-process fake:
6
+ //
7
+ // * A conditional put is `If-None-Match: *`. 412 = "already there" and the
8
+ // reply carries the existing object's ETag, which is returned so a caller
9
+ // can tell "my bytes are there" from "something else is".
10
+ // * 409 (ConditionalRequestConflict: another put of the same key is still in
11
+ // flight) is transient: the retry then sees 412.
12
+ // * An error is read for its S3 `<Code>`, not just its status: RequestTimeout
13
+ // and BadDigest come back as 400 and ARE worth retrying; NoSuchBucket,
14
+ // AccessDenied, SignatureDoesNotMatch are final and say so by name.
15
+ // * A HEAD cannot tell a missing bucket from a missing key (both 404, no
16
+ // body). `checkBucket()` asks the bucket itself; run it at start-up.
17
+ // * An upload streams from a re-readable source (no Buffer of the whole
18
+ // object), signed with its real payload hash so the server verifies it.
19
+ // * Past a threshold the upload is multipart. Nothing is kept on the local
20
+ // side to resume it: the next call lists the in-flight uploads for the key
21
+ // and the parts already there, hashes the local parts, and uploads only
22
+ // the ones that differ. An upload that is cancelled or fails for a final
23
+ // reason is aborted; one that fails for a transient reason is left to be
24
+ // resumed (and swept by abortStaleUploads / a bucket lifecycle rule if no
25
+ // one comes back).
26
+ import { s3Request, forgetS3Credentials } from "./storage.js";
27
+ import { BlobNotFound, BlobSourceError, BlobStoreError, BlobTransientError, assertKey, bufferSource, hashRange, } from "./blob-types.js";
28
+ const MiB = 1024 * 1024;
29
+ /** S3's floor for every part but the last. R2 and MinIO enforce the same. */
30
+ export const MIN_PART_BYTES = 5 * MiB;
31
+ /** S3's ceiling on the number of parts. */
32
+ export const MAX_PARTS = 10_000;
33
+ export const DEFAULT_S3_OPTIONS = {
34
+ multipartThresholdBytes: 64 * MiB,
35
+ partBytes: 16 * MiB,
36
+ partConcurrency: 4,
37
+ requestDeadlineMs: 30_000,
38
+ minBytesPerSec: 1 * MiB,
39
+ };
40
+ export function s3OptionsFromEnv(env = process.env) {
41
+ const n = (v, d) => (v !== undefined && /^\d+$/.test(v) && Number(v) > 0 ? Number(v) : d);
42
+ const d = DEFAULT_S3_OPTIONS;
43
+ return {
44
+ multipartThresholdBytes: n(env.FOLDRUN_BLOB_MULTIPART_THRESHOLD_MB, d.multipartThresholdBytes / MiB) * MiB,
45
+ partBytes: Math.max(MIN_PART_BYTES, n(env.FOLDRUN_BLOB_PART_MB, d.partBytes / MiB) * MiB),
46
+ partConcurrency: n(env.FOLDRUN_BLOB_PART_CONCURRENCY, d.partConcurrency),
47
+ requestDeadlineMs: n(env.FOLDRUN_BLOB_DEADLINE_MS, d.requestDeadlineMs),
48
+ minBytesPerSec: d.minBytesPerSec,
49
+ };
50
+ }
51
+ /** The part size for an object: the configured one, raised until the object
52
+ * fits in MAX_PARTS parts. Every part but the last is exactly this size —
53
+ * R2 requires uniform parts, S3 and MinIO do not mind. */
54
+ export function planPartBytes(size, configured) {
55
+ let p = Math.max(MIN_PART_BYTES, configured);
56
+ if (Math.ceil(size / p) > MAX_PARTS)
57
+ p = Math.ceil(size / MAX_PARTS / MiB) * MiB;
58
+ return p;
59
+ }
60
+ // Codes that arrive with a non-5xx status but are worth another try.
61
+ const TRANSIENT_CODES = new Set([
62
+ "RequestTimeout",
63
+ "SlowDown",
64
+ "InternalError",
65
+ "ServiceUnavailable",
66
+ "BadDigest", // the body changed in flight
67
+ "XAmzContentSHA256Mismatch", // the same, seen by MinIO
68
+ "ConditionalRequestConflict",
69
+ "OperationAborted",
70
+ "ExpiredToken", // role credentials; the cache is dropped before the retry
71
+ ]);
72
+ const transientStatus = (s) => s >= 500 || s === 429 || s === 408 || s === 409;
73
+ const codeOf = (xml) => /<Code>([^<]+)<\/Code>/.exec(xml)?.[1];
74
+ // MinIO writes a quote as `&#34;`, AWS as `&quot;`; both must read back as `"`
75
+ // (a part's ETag is handed back to the store verbatim to complete the upload).
76
+ const unxml = (s) => s
77
+ .replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n)))
78
+ .replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16)))
79
+ .replace(/&lt;/g, "<")
80
+ .replace(/&gt;/g, ">")
81
+ .replace(/&quot;/g, '"')
82
+ .replace(/&apos;/g, "'")
83
+ .replace(/&amp;/g, "&");
84
+ const unquote = (etag) => (etag ? etag.replace(/^W\//, "").replace(/^"|"$/g, "") : undefined);
85
+ const isTimeout = (signal) => signal?.aborted === true && signal.reason?.name === "TimeoutError";
86
+ export function s3BlobStore(cfg, given = {}) {
87
+ if (!cfg)
88
+ throw new Error("the s3 blob store needs FOLDRUN_S3_ENDPOINT, FOLDRUN_S3_BUCKET and credentials");
89
+ const o = { ...s3OptionsFromEnv(), ...given };
90
+ const requestDeadline = (bytes) => o.requestDeadlineMs + Math.ceil((bytes / o.minBytesPerSec) * 1000);
91
+ /** One signed request with the failures of the network turned into
92
+ * BlobTransientError, so the retry wrapper above knows what to retry. */
93
+ const send = async (what, method, key, body, extra = {}, signal, query, mime) => {
94
+ try {
95
+ return await s3Request(cfg, method, key, body, mime, extra, signal, query ? { query } : {});
96
+ }
97
+ catch (err) {
98
+ // A source that fails while it is being sent surfaces from fetch as
99
+ // "fetch failed" with the real error as its cause. It is not the
100
+ // network's fault and a retry would read the same bytes.
101
+ for (let e = err, i = 0; e && i < 4; e = e.cause, i++)
102
+ if (e instanceof BlobSourceError)
103
+ throw e;
104
+ if (signal?.aborted && !isTimeout(signal))
105
+ throw err; // the caller cancelled
106
+ const name = err?.name;
107
+ if (name === "AbortError" || name === "TimeoutError")
108
+ throw new BlobTransientError(`s3 ${what}: timed out`);
109
+ const cause = err.cause;
110
+ throw new BlobTransientError(`s3 ${what}: ${cause?.code ?? cause?.message ?? err?.message ?? err}`);
111
+ }
112
+ };
113
+ /** Read an error reply: transient or final, with the store's code in the message. */
114
+ const failure = async (res, what) => {
115
+ const text = (await res.text().catch(() => "")).slice(0, 400);
116
+ const code = codeOf(text);
117
+ const msg = `s3 ${what} failed: ${res.status}${code ? ` ${code}` : ""} ${unxml(/<Message>([^<]*)<\/Message>/.exec(text)?.[1] ?? "").slice(0, 160)}`.trim();
118
+ if (code === "ExpiredToken")
119
+ forgetS3Credentials();
120
+ if (transientStatus(res.status) || (code && TRANSIENT_CODES.has(code)))
121
+ return new BlobTransientError(msg, res.status, code);
122
+ return new BlobStoreError(msg, res.status, code);
123
+ };
124
+ const drain = (res) => res.arrayBuffer().catch(() => { });
125
+ const headObject = async (key, signal) => {
126
+ const res = await send("head", "HEAD", key, undefined, {}, signal);
127
+ if (res.status === 404) {
128
+ await drain(res);
129
+ return null;
130
+ }
131
+ if (!res.ok)
132
+ throw await failure(res, "head");
133
+ await drain(res);
134
+ const size = Number(res.headers.get("content-length"));
135
+ const lm = res.headers.get("last-modified");
136
+ const etag = unquote(res.headers.get("etag"));
137
+ return { size: Number.isSafeInteger(size) && size >= 0 ? size : 0, ...(lm ? { modifiedAt: new Date(lm) } : {}), ...(etag ? { etag } : {}) };
138
+ };
139
+ // ---------- single request ----------
140
+ const putOnce = async (key, body, mime, signal) => {
141
+ const res = await send("put", "PUT", key, body, { "if-none-match": "*" }, signal, undefined, mime);
142
+ if (res.status === 412) {
143
+ await drain(res);
144
+ return { created: false, ...(unquote(res.headers.get("etag")) ? { etag: unquote(res.headers.get("etag")) } : {}) };
145
+ }
146
+ if (!res.ok)
147
+ throw await failure(res, "put");
148
+ await drain(res);
149
+ return { created: true, ...(unquote(res.headers.get("etag")) ? { etag: unquote(res.headers.get("etag")) } : {}) };
150
+ };
151
+ /** The upload to continue, if one is open for this exact key. */
152
+ const findUpload = async (key, signal) => {
153
+ let keyMarker = "";
154
+ let uploadMarker = "";
155
+ for (let page = 0; page < 20; page++) {
156
+ const q = { uploads: "", prefix: key, "max-uploads": "1000" };
157
+ if (keyMarker)
158
+ q["key-marker"] = keyMarker;
159
+ if (uploadMarker)
160
+ q["upload-id-marker"] = uploadMarker;
161
+ const res = await send("list uploads", "GET", "", undefined, {}, signal, q);
162
+ if (!res.ok)
163
+ throw await failure(res, "list uploads");
164
+ const xml = await res.text();
165
+ // The oldest open upload for the key: the one most likely to have parts.
166
+ const mine = [...xml.matchAll(/<Upload>([\s\S]*?)<\/Upload>/g)]
167
+ .map((m) => ({ key: unxml(/<Key>([^<]*)<\/Key>/.exec(m[1])?.[1] ?? ""), id: unxml(/<UploadId>([^<]*)<\/UploadId>/.exec(m[1])?.[1] ?? ""), at: Date.parse(/<Initiated>([^<]*)<\/Initiated>/.exec(m[1])?.[1] ?? "") || 0 }))
168
+ .filter((u) => u.key === key && u.id)
169
+ .sort((a, b) => a.at - b.at);
170
+ if (mine.length)
171
+ return mine[0].id;
172
+ if (!/<IsTruncated>true<\/IsTruncated>/.test(xml))
173
+ return null;
174
+ keyMarker = unxml(/<NextKeyMarker>([^<]*)<\/NextKeyMarker>/.exec(xml)?.[1] ?? "");
175
+ uploadMarker = unxml(/<NextUploadIdMarker>([^<]*)<\/NextUploadIdMarker>/.exec(xml)?.[1] ?? "");
176
+ if (!keyMarker && !uploadMarker)
177
+ return null;
178
+ }
179
+ return null;
180
+ };
181
+ const listParts = async (key, uploadId, signal) => {
182
+ const parts = new Map();
183
+ let marker = "";
184
+ for (;;) {
185
+ const q = { uploadId, "max-parts": "1000" };
186
+ if (marker)
187
+ q["part-number-marker"] = marker;
188
+ const res = await send("list parts", "GET", key, undefined, {}, signal, q);
189
+ if (res.status === 404) {
190
+ await drain(res);
191
+ return null; // NoSuchUpload: it was completed or aborted under us
192
+ }
193
+ if (!res.ok)
194
+ throw await failure(res, "list parts");
195
+ const xml = await res.text();
196
+ for (const m of xml.matchAll(/<Part>([\s\S]*?)<\/Part>/g)) {
197
+ const n = Number(/<PartNumber>(\d+)<\/PartNumber>/.exec(m[1])?.[1]);
198
+ const size = Number(/<Size>(\d+)<\/Size>/.exec(m[1])?.[1]);
199
+ const etag = unxml(/<ETag>([^<]*)<\/ETag>/.exec(m[1])?.[1] ?? "");
200
+ if (n && etag)
201
+ parts.set(n, { etag, size });
202
+ }
203
+ if (!/<IsTruncated>true<\/IsTruncated>/.test(xml))
204
+ return parts;
205
+ marker = /<NextPartNumberMarker>(\d+)<\/NextPartNumberMarker>/.exec(xml)?.[1] ?? "";
206
+ if (!marker)
207
+ return parts;
208
+ }
209
+ };
210
+ const abortUpload = async (key, uploadId) => {
211
+ // A fresh signal: the one that got us here is probably already aborted.
212
+ const res = await send("abort upload", "DELETE", key, undefined, {}, AbortSignal.timeout(10_000), { uploadId }).catch(() => null);
213
+ if (res)
214
+ await drain(res);
215
+ };
216
+ async function multipartPut(key, source, opts) {
217
+ const { signal } = opts;
218
+ // Already there: nothing to upload, and nothing to leave half-open.
219
+ const there = await headObject(key, signal);
220
+ if (there)
221
+ return { created: false, ...(there.etag ? { etag: there.etag } : {}) };
222
+ const partBytes = planPartBytes(source.size, o.partBytes);
223
+ const count = Math.ceil(source.size / partBytes);
224
+ const range = (n) => [(n - 1) * partBytes, Math.min(n * partBytes, source.size)];
225
+ let uploadId = await findUpload(key, signal);
226
+ let have = uploadId ? await listParts(key, uploadId, signal) : null;
227
+ if (!uploadId || !have) {
228
+ const res = await send("create upload", "POST", key, undefined, {}, signal, { uploads: "" }, opts.contentType);
229
+ if (!res.ok)
230
+ throw await failure(res, "create upload");
231
+ uploadId = unxml(/<UploadId>([^<]*)<\/UploadId>/.exec(await res.text())?.[1] ?? "");
232
+ if (!uploadId)
233
+ throw new BlobTransientError("s3 create upload: no upload id in the reply");
234
+ have = new Map();
235
+ }
236
+ const id = uploadId;
237
+ const done = new Map(); // part number → ETag to complete with
238
+ const inner = new AbortController();
239
+ // The error that stopped the upload, not whichever worker's rejection
240
+ // happens to sit first in the pool: the siblings it aborts reject with an
241
+ // AbortError, which would hide a transient or final cause.
242
+ let firstError = null;
243
+ const both = signal ? AbortSignal.any([signal, inner.signal]) : inner.signal;
244
+ let next = 1;
245
+ const worker = async () => {
246
+ while (!both.aborted) {
247
+ const n = next++;
248
+ if (n > count)
249
+ return;
250
+ const [start, end] = range(n);
251
+ const len = end - start;
252
+ // Hash first: the sha256 is signed into the request, the md5 is what a
253
+ // part already in the store must match to be trusted.
254
+ const h = await hashRange(source, start, end, both);
255
+ const prior = have.get(n);
256
+ if (prior && prior.size === len && unquote(prior.etag) === h.md5) {
257
+ done.set(n, prior.etag);
258
+ continue;
259
+ }
260
+ const res = await send(`part ${n}/${count}`, "PUT", key, { stream: source.read(start, end, both), length: len, sha256: h.sha256 }, {}, AbortSignal.any([both, AbortSignal.timeout(requestDeadline(len))]), { partNumber: String(n), uploadId: id });
261
+ if (!res.ok)
262
+ throw await failure(res, `part ${n}`);
263
+ await drain(res);
264
+ const etag = res.headers.get("etag");
265
+ if (!etag)
266
+ throw new BlobTransientError(`s3 part ${n}: no ETag in the reply`);
267
+ done.set(n, etag);
268
+ }
269
+ };
270
+ try {
271
+ const pool = Array.from({ length: Math.min(o.partConcurrency, count) }, () => worker().catch((err) => {
272
+ firstError ??= { err };
273
+ inner.abort(err); // stop the siblings
274
+ throw err;
275
+ }));
276
+ await Promise.allSettled(pool);
277
+ if (firstError)
278
+ throw firstError.err;
279
+ const xml = `<CompleteMultipartUpload>` +
280
+ [...done.entries()]
281
+ .sort((a, b) => a[0] - b[0])
282
+ .map(([n, etag]) => `<Part><PartNumber>${n}</PartNumber><ETag>${etag.replace(/&/g, "&amp;").replace(/</g, "&lt;")}</ETag></Part>`)
283
+ .join("") +
284
+ `</CompleteMultipartUpload>`;
285
+ const res = await send("complete upload", "POST", key, Buffer.from(xml), { "if-none-match": "*" }, signal, { uploadId: id }, "application/xml");
286
+ if (res.status === 412) {
287
+ // Someone else's identical object won. Ours is not needed.
288
+ await drain(res);
289
+ await abortUpload(key, id);
290
+ return { created: false, ...(unquote(res.headers.get("etag")) ? { etag: unquote(res.headers.get("etag")) } : {}) };
291
+ }
292
+ if (res.status === 404) {
293
+ // NoSuchUpload: a twin of this call completed (or aborted) the same
294
+ // upload. If the object is there, the work is done.
295
+ await drain(res);
296
+ const now = await headObject(key, signal);
297
+ if (now)
298
+ return { created: false, ...(now.etag ? { etag: now.etag } : {}) };
299
+ throw new BlobTransientError("s3 complete upload: the upload vanished", 404, "NoSuchUpload");
300
+ }
301
+ if (!res.ok)
302
+ throw await failure(res, "complete upload");
303
+ // S3 can answer 200 and put the error in the body.
304
+ const text = await res.text();
305
+ if (/<Error>/.test(text)) {
306
+ const code = codeOf(text);
307
+ const msg = `s3 complete upload failed: 200 ${code ?? "error in body"}`;
308
+ throw code && !TRANSIENT_CODES.has(code) && code !== "NoSuchUpload" ? new BlobStoreError(msg, 200, code) : new BlobTransientError(msg, 200, code);
309
+ }
310
+ return { created: true, ...(unquote(/<ETag>([^<]*)<\/ETag>/.exec(text)?.[1]) ? { etag: unquote(unxml(/<ETag>([^<]*)<\/ETag>/.exec(text)[1])) } : {}) };
311
+ }
312
+ catch (err) {
313
+ // Cancelled by the caller, or a final failure: nothing will come back to
314
+ // finish this, so do not leave parts for the store to bill. A transient
315
+ // failure (including a deadline) leaves the upload for the retry.
316
+ const cancelled = signal?.aborted === true && !isTimeout(signal);
317
+ const final = !(err instanceof BlobTransientError);
318
+ if (cancelled || final)
319
+ await abortUpload(key, id);
320
+ throw err;
321
+ }
322
+ }
323
+ // ---------- the interface ----------
324
+ return {
325
+ kind: "s3",
326
+ async putIfAbsent(key, body, opts = {}) {
327
+ assertKey(key);
328
+ return putOnce(key, Buffer.from(body), opts.contentType, opts.signal);
329
+ },
330
+ async putSourceIfAbsent(key, source, opts = {}) {
331
+ assertKey(key);
332
+ if (source.size >= o.multipartThresholdBytes)
333
+ return multipartPut(key, source, opts);
334
+ const sha256 = opts.sha256 ?? (await hashRange(source, 0, source.size, opts.signal)).sha256;
335
+ return putOnce(key, { stream: source.read(0, source.size, opts.signal), length: source.size, sha256 }, opts.contentType, opts.signal);
336
+ },
337
+ async get(key, opts = {}) {
338
+ assertKey(key);
339
+ const res = await send("get", "GET", key, undefined, opts.range ? { range: `bytes=${opts.range.start}-${opts.range.end}` } : {}, opts.signal);
340
+ if (res.status === 404) {
341
+ const text = await res.text().catch(() => "");
342
+ // A GET carries the reason a HEAD cannot: the bucket may be the thing that is missing.
343
+ if (codeOf(text) === "NoSuchBucket")
344
+ throw new BlobStoreError(`s3 get failed: 404 NoSuchBucket (${cfg.bucket})`, 404, "NoSuchBucket");
345
+ throw new BlobNotFound(key);
346
+ }
347
+ if (!res.ok || !res.body)
348
+ throw await failure(res, "get");
349
+ // A connection that drops mid-body is a retryable failure, not a TypeError.
350
+ const reader = res.body.getReader();
351
+ return new ReadableStream({
352
+ async pull(controller) {
353
+ try {
354
+ const { done, value } = await reader.read();
355
+ if (done)
356
+ controller.close();
357
+ else
358
+ controller.enqueue(value);
359
+ }
360
+ catch (err) {
361
+ controller.error(new BlobTransientError(`s3 get ${key}: the body was cut off (${err.cause?.code ?? err.message})`));
362
+ }
363
+ },
364
+ cancel: (reason) => reader.cancel(reason),
365
+ });
366
+ },
367
+ async head(key, opts = {}) {
368
+ assertKey(key);
369
+ return headObject(key, opts.signal);
370
+ },
371
+ async delete(key, opts = {}) {
372
+ assertKey(key);
373
+ const res = await send("delete", "DELETE", key, undefined, {}, opts.signal);
374
+ if (!res.ok && res.status !== 404)
375
+ throw await failure(res, "delete");
376
+ await drain(res);
377
+ },
378
+ async abortStaleUploads({ olderThanMs, prefix = "", signal }) {
379
+ let n = 0;
380
+ let keyMarker = "";
381
+ let uploadMarker = "";
382
+ for (;;) {
383
+ const q = { uploads: "", "max-uploads": "1000", ...(prefix ? { prefix } : {}) };
384
+ if (keyMarker)
385
+ q["key-marker"] = keyMarker;
386
+ if (uploadMarker)
387
+ q["upload-id-marker"] = uploadMarker;
388
+ const res = await send("list uploads", "GET", "", undefined, {}, signal, q);
389
+ if (!res.ok)
390
+ throw await failure(res, "list uploads");
391
+ const xml = await res.text();
392
+ for (const m of xml.matchAll(/<Upload>([\s\S]*?)<\/Upload>/g)) {
393
+ const key = unxml(/<Key>([^<]*)<\/Key>/.exec(m[1])?.[1] ?? "");
394
+ const id = unxml(/<UploadId>([^<]*)<\/UploadId>/.exec(m[1])?.[1] ?? "");
395
+ const at = Date.parse(/<Initiated>([^<]*)<\/Initiated>/.exec(m[1])?.[1] ?? "");
396
+ if (key && id && Number.isFinite(at) && Date.now() - at >= olderThanMs) {
397
+ await abortUpload(key, id);
398
+ n++;
399
+ }
400
+ }
401
+ if (!/<IsTruncated>true<\/IsTruncated>/.test(xml))
402
+ return n;
403
+ keyMarker = unxml(/<NextKeyMarker>([^<]*)<\/NextKeyMarker>/.exec(xml)?.[1] ?? "");
404
+ uploadMarker = unxml(/<NextUploadIdMarker>([^<]*)<\/NextUploadIdMarker>/.exec(xml)?.[1] ?? "");
405
+ if (!keyMarker && !uploadMarker)
406
+ return n;
407
+ }
408
+ },
409
+ async *list(prefix, opts = {}) {
410
+ let token;
411
+ do {
412
+ const q = { "list-type": "2", prefix: prefix.endsWith("/") ? prefix : `${prefix}/`, ...(token ? { "continuation-token": token } : {}) };
413
+ const res = await send("list", "GET", "", undefined, {}, opts.signal, q);
414
+ if (!res.ok)
415
+ throw await failure(res, "list");
416
+ const xml = await res.text();
417
+ for (const c of xml.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)) {
418
+ const key = xmlText(c[1], "Key");
419
+ const size = Number(xmlText(c[1], "Size"));
420
+ const lm = xmlText(c[1], "LastModified");
421
+ if (key)
422
+ yield { key, size: Number.isFinite(size) ? size : 0, modifiedAt: lm ? new Date(lm) : new Date(0) };
423
+ }
424
+ token = /<IsTruncated>true<\/IsTruncated>/.test(xml) ? (xmlText(xml, "NextContinuationToken") ?? undefined) : undefined;
425
+ } while (token);
426
+ },
427
+ async tenants(opts = {}) {
428
+ const out = [];
429
+ let token;
430
+ do {
431
+ const q = { "list-type": "2", prefix: "t/", delimiter: "/", ...(token ? { "continuation-token": token } : {}) };
432
+ const res = await send("list", "GET", "", undefined, {}, opts.signal, q);
433
+ if (!res.ok)
434
+ throw await failure(res, "list");
435
+ const xml = await res.text();
436
+ for (const c of xml.matchAll(/<CommonPrefixes>\s*<Prefix>([^<]*)<\/Prefix>/g))
437
+ out.push(unxml(c[1]).replace(/^t\//, "").replace(/\/$/, ""));
438
+ token = /<IsTruncated>true<\/IsTruncated>/.test(xml) ? (xmlText(xml, "NextContinuationToken") ?? undefined) : undefined;
439
+ } while (token);
440
+ return out;
441
+ },
442
+ /** Is the bucket there, and may we use it? A HEAD on a key cannot say. */
443
+ async checkBucket(signal) {
444
+ const res = await send("head bucket", "HEAD", "", undefined, {}, signal);
445
+ if (res.ok)
446
+ return void (await drain(res));
447
+ await drain(res);
448
+ if (res.status === 404)
449
+ throw new BlobStoreError(`s3: bucket ${cfg.bucket} does not exist (or the endpoint is wrong)`, 404, "NoSuchBucket");
450
+ throw await failure(res, "head bucket");
451
+ },
452
+ };
453
+ }
454
+ function xmlText(xml, tag) {
455
+ const m = new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`).exec(xml);
456
+ return m ? unxml(m[1]) : null;
457
+ }
458
+ export { bufferSource };
@@ -0,0 +1,15 @@
1
+ import type { Deps } from "./publish.ts";
2
+ export interface StateRetention {
3
+ keep: number;
4
+ days: number;
5
+ }
6
+ export interface PruneResult {
7
+ pruned: number;
8
+ kept: number;
9
+ /** Outside the window but held by a run or a publish: left for next time. */
10
+ held: number;
11
+ }
12
+ export declare function pruneStateRevisions(deps: Deps, ws: {
13
+ tenant: string;
14
+ workspace: string;
15
+ }, policy: StateRetention, now?: number): Promise<PruneResult>;