@foldrun/core 17.2.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 (70) 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/browse-egress.d.ts +31 -0
  13. package/dist/src/browse-egress.js +43 -0
  14. package/dist/src/egress.d.ts +9 -0
  15. package/dist/src/evals.js +1 -1
  16. package/dist/src/history.d.ts +86 -9
  17. package/dist/src/history.js +132 -16
  18. package/dist/src/journal-store.d.ts +58 -0
  19. package/dist/src/journal-store.js +117 -0
  20. package/dist/src/manifest.d.ts +92 -0
  21. package/dist/src/manifest.js +239 -0
  22. package/dist/src/ops-log.js +26 -3
  23. package/dist/src/platform.d.ts +7 -0
  24. package/dist/src/platform.js +1 -0
  25. package/dist/src/publish.d.ts +134 -0
  26. package/dist/src/publish.js +434 -0
  27. package/dist/src/records.d.ts +72 -0
  28. package/dist/src/records.js +24 -0
  29. package/dist/src/revision-store.d.ts +161 -0
  30. package/dist/src/revision-store.js +378 -0
  31. package/dist/src/run-container.d.ts +20 -0
  32. package/dist/src/run-container.js +61 -0
  33. package/dist/src/runner.js +22 -4
  34. package/dist/src/s3-blob-store.d.ts +29 -0
  35. package/dist/src/s3-blob-store.js +458 -0
  36. package/dist/src/state-retention.d.ts +15 -0
  37. package/dist/src/state-retention.js +65 -0
  38. package/dist/src/storage.d.ts +29 -1
  39. package/dist/src/storage.js +331 -81
  40. package/dist/src/store.d.ts +41 -0
  41. package/dist/src/store.js +188 -5
  42. package/dist/src/trigger-log.js +17 -0
  43. package/dist/src/workspace-revisions.d.ts +259 -0
  44. package/dist/src/workspace-revisions.js +1274 -0
  45. package/package.json +1 -1
  46. package/src/approvals.ts +3 -3
  47. package/src/blob-cache.ts +354 -0
  48. package/src/blob-pins.ts +99 -0
  49. package/src/blob-store.ts +385 -0
  50. package/src/blob-sweeper.ts +308 -0
  51. package/src/blob-types.ts +216 -0
  52. package/src/browse-egress.ts +49 -1
  53. package/src/egress.ts +6 -0
  54. package/src/evals.ts +1 -1
  55. package/src/history.ts +182 -16
  56. package/src/journal-store.ts +152 -0
  57. package/src/manifest.ts +274 -0
  58. package/src/ops-log.ts +25 -3
  59. package/src/platform.ts +8 -0
  60. package/src/publish.ts +520 -0
  61. package/src/records.ts +105 -0
  62. package/src/revision-store.ts +513 -0
  63. package/src/run-container.ts +62 -0
  64. package/src/runner.ts +21 -4
  65. package/src/s3-blob-store.ts +489 -0
  66. package/src/state-retention.ts +83 -0
  67. package/src/storage.ts +335 -81
  68. package/src/store.ts +178 -5
  69. package/src/trigger-log.ts +15 -0
  70. package/src/workspace-revisions.ts +1324 -0
@@ -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>;
@@ -0,0 +1,65 @@
1
+ // How long `state/` checkpoints are kept (FOL-126 fixes, 8 Nov 2026).
2
+ //
3
+ // Every step of every run writes `state/` and each is a revision on the state
4
+ // head; the manifests are small but the blobs are whatever the state holds
5
+ // (indexes, caches), and the ticket's 100 × 1 GB case is a state head that
6
+ // never forgets. So the state head keeps a window:
7
+ //
8
+ // keep the newest N checkpoints (0: no count limit)
9
+ // days and none older than D days (0: no age limit)
10
+ //
11
+ // A checkpoint goes when it is outside EITHER limit, except
12
+ // - the head, always (it is the state);
13
+ // - one whose manifest something other than a revision still holds — a run
14
+ // staged from it (pin holder `run`), a publish in flight — checked through
15
+ // the same pins the sweeper obeys. It is looked at again next time.
16
+ //
17
+ // Pruning removes the revision rows and releases the pins THOSE revisions held
18
+ // on their manifests; it deletes no object. The objects are the sweeper's: it
19
+ // deletes a manifest or blob only through guardDelete, and only when no pin is
20
+ // left. A manifest two checkpoints share (an unchanged state) keeps the other
21
+ // checkpoint's pin.
22
+ //
23
+ // The workspace head (authored files) is not pruned: that is the history page.
24
+ const PAGE = 500;
25
+ export async function pruneStateRevisions(deps, ws, policy, now = Date.now()) {
26
+ const keep = Math.max(0, Math.floor(policy.keep || 0));
27
+ const days = Math.max(0, policy.days || 0);
28
+ const out = { pruned: 0, kept: 0, held: 0 };
29
+ if (keep === 0 && days === 0)
30
+ return out;
31
+ const sws = { tenant: ws.tenant, workspace: ws.workspace, scope: "state" };
32
+ const cutoff = days > 0 ? now - days * 86_400_000 : -Infinity;
33
+ const doomed = [];
34
+ let seen = 0;
35
+ let before;
36
+ for (;;) {
37
+ const page = await deps.revisions.revisions(sws, { limit: PAGE, before });
38
+ if (!page.length)
39
+ break;
40
+ for (const r of page) {
41
+ const index = seen++;
42
+ if (index === 0) {
43
+ out.kept++; // the head
44
+ continue;
45
+ }
46
+ const outside = (keep > 0 && index >= keep) || Date.parse(r.at) < cutoff;
47
+ if (!outside) {
48
+ out.kept++;
49
+ continue;
50
+ }
51
+ if (deps.pins && (await deps.pins.isPinnedBeyondRevisions(ws.tenant, "manifest", r.state))) {
52
+ out.held++;
53
+ continue;
54
+ }
55
+ doomed.push(r.id);
56
+ }
57
+ before = page[page.length - 1].seq;
58
+ if (page.length < PAGE)
59
+ break;
60
+ }
61
+ // In slices: one statement per slice, never an unbounded list.
62
+ for (let i = 0; i < doomed.length; i += 200)
63
+ out.pruned += await deps.revisions.prune(sws, doomed.slice(i, i + 200));
64
+ return out;
65
+ }
@@ -93,7 +93,7 @@ export interface Driver {
93
93
  /** Where the fs driver keeps a blob. Exported because the run mirror
94
94
  * hardlinks straight to it rather than reading and rewriting the bytes. */
95
95
  export declare function blobPath(tenant: string, workspace: string, sha: string): string;
96
- interface S3Config {
96
+ export interface S3Config {
97
97
  endpoint: string;
98
98
  bucket: string;
99
99
  region: string;
@@ -109,6 +109,21 @@ export declare function regionOfEndpoint(endpoint: string): string | null;
109
109
  export declare function s3Config(): S3Config | null;
110
110
  /** For tests: forget cached role credentials. */
111
111
  export declare function forgetS3Credentials(): void;
112
+ /** A body that is not held in memory: read as it is sent. `length` and
113
+ * `sha256` (hex of the whole body) are needed up front: S3 wants a
114
+ * Content-Length (it refuses chunked uploads) and the hash is signed. */
115
+ export interface S3StreamBody {
116
+ stream: AsyncIterable<Uint8Array>;
117
+ length: number;
118
+ sha256: string;
119
+ }
120
+ export interface S3RequestOptions {
121
+ /** Sub-resource and list parameters (`uploads`, `uploadId`, `partNumber`,
122
+ * `prefix`...). Signed in canonical order. An empty value is `name=`. */
123
+ query?: Record<string, string>;
124
+ }
125
+ /** The header-signed form, for the calls the platform itself makes. */
126
+ export declare function s3Request(cfg: S3Config, method: "GET" | "PUT" | "POST" | "DELETE" | "HEAD", key: string, body?: Buffer | S3StreamBody, mime?: string, extra?: Record<string, string>, signal?: AbortSignal, opts?: S3RequestOptions): Promise<Response>;
112
127
  /**
113
128
  * The Content-Disposition a presigned GET asks the store to send back. The
114
129
  * store echoes it as a header, and header values are bytes: a raw "報告.pdf"
@@ -122,6 +137,19 @@ export declare function contentDisposition(type: "inline" | "attachment", filena
122
137
  * because a dashboard that boots and stores locally beats one that 500s.
123
138
  */
124
139
  export declare function driverFor(tenant: string, workspace: string): Driver;
140
+ /**
141
+ * Run `fn` as the only writer of this workspace's file index, in this process
142
+ * and every other one on the volume. Callers of the same workspace in this
143
+ * process queue on a promise chain first, so they do not poll the file against
144
+ * each other. Keep `fn` to index work and blob bookkeeping; bytes a caller
145
+ * already holds are uploaded BEFORE taking the lock (a blob is immutable and
146
+ * named by its hash, so that is safe) and then confirmed present inside it.
147
+ */
148
+ export declare function withFileStoreLock<T>(tenant: string, workspace: string, fn: () => Promise<T>): Promise<T>;
149
+ /** The same lock for any path: `file` is the lock file itself (its directory
150
+ * is created). Used by the local RevisionStore, which keeps its own state
151
+ * beside the data it guards. */
152
+ export declare function withFileLock<T>(file: string, fn: () => Promise<T>): Promise<T>;
125
153
  export declare function putFile(tenant: string, workspace: string, rel: string, body: Buffer, by: string): Promise<FileRecord>;
126
154
  /** Register bytes a browser PUT straight to the bucket. Same bookkeeping as
127
155
  * putFile, minus the bytes — the platform never saw them.