@foldrun/core 17.3.0 → 18.0.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 +312 -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 +362 -0
  8. package/dist/src/blob-sweeper.d.ts +70 -0
  9. package/dist/src/blob-sweeper.js +282 -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 +92 -9
  14. package/dist/src/history.js +168 -20
  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 +531 -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 +269 -0
  41. package/dist/src/workspace-revisions.js +1382 -0
  42. package/package.json +1 -1
  43. package/src/approvals.ts +3 -3
  44. package/src/blob-cache.ts +357 -0
  45. package/src/blob-pins.ts +99 -0
  46. package/src/blob-store.ts +389 -0
  47. package/src/blob-sweeper.ts +336 -0
  48. package/src/blob-types.ts +216 -0
  49. package/src/evals.ts +1 -1
  50. package/src/history.ts +226 -19
  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 +560 -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 +1423 -0
@@ -0,0 +1,389 @@
1
+ // BlobStore: immutable objects by key (FOL-126, phase 1).
2
+ //
3
+ // The small interface the revision work stands on. It is NOT a filesystem
4
+ // shim: no rename, no list-by-prefix, no append, no overwrite. A key is
5
+ // written once (put with `ifNoneMatch`), read as a stream, asked about
6
+ // (head), and removed (delete — only the garbage collector does that).
7
+ //
8
+ // Two drivers, both in this file:
9
+ //
10
+ // fs a directory tree under the data root. A conditional put is
11
+ // link(2) of a finished temp file onto the target: atomic, and fails
12
+ // with EEXIST if another writer got there first, on a local disk and
13
+ // on NFS alike. This is what self-host Compose and the laptop get.
14
+ // s3 any S3-compatible endpoint (R2, MinIO, AWS), signed by the code in
15
+ // storage.ts. A conditional put is `If-None-Match: *`; 412 means "it is
16
+ // already there".
17
+ //
18
+ // `bounded()` wraps either with what a production caller needs and neither
19
+ // driver should each reinvent: a deadline on every call, a retry budget for
20
+ // failures worth retrying, and a cap on calls in flight.
21
+ //
22
+ // Large objects: `putSourceIfAbsent` streams from a re-readable source (a file
23
+ // on disk) and, on s3 past a threshold, uploads in resumable parts. The s3
24
+ // driver lives in s3-blob-store.ts; the shared types and errors in
25
+ // blob-types.ts; both are re-exported here so callers import one module.
26
+ // tests/s3-blob-store.test.ts runs the s3 driver against a real MinIO
27
+ // (FOLDRUN_TEST_S3_URL), the contract suite runs it against the fake.
28
+
29
+ import fs from "node:fs";
30
+ import path from "node:path";
31
+ import crypto from "node:crypto";
32
+ import { Readable } from "node:stream";
33
+ import { pipeline } from "node:stream/promises";
34
+ import { dataRoot } from "./paths.ts";
35
+ import { s3Config } from "./storage.ts";
36
+ import { s3BlobStore } from "./s3-blob-store.ts";
37
+ import {
38
+ BlobNotFound,
39
+ BlobSourceError,
40
+ BlobTransientError,
41
+ assertKey,
42
+ hashRange,
43
+ type BlobStore,
44
+ type BlobSweeper,
45
+ type BlobSource,
46
+ type PutSourceOptions,
47
+ type ListedObject,
48
+ } from "./blob-types.ts";
49
+
50
+ export * from "./blob-types.ts";
51
+ export { s3BlobStore };
52
+
53
+ // ---------- fs driver ----------
54
+
55
+ export function fsBlobStore(root: string = path.join(dataRoot(), ".objects")): BlobStore & BlobSweeper {
56
+ const at = (key: string) => path.join(root, ...assertKey(key).split("/"));
57
+ const tmpName = (target: string) => `${target}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`;
58
+ return {
59
+ kind: "fs",
60
+ async putSourceIfAbsent(key, source, opts: PutSourceOptions = {}) {
61
+ const target = at(key);
62
+ fs.mkdirSync(path.dirname(target), { recursive: true });
63
+ if (fs.existsSync(target)) return { created: false };
64
+ const tmp = tmpName(target);
65
+ try {
66
+ const sha = crypto.createHash("sha256");
67
+ const out = fs.createWriteStream(tmp);
68
+ await pipeline(
69
+ Readable.from(source.read(0, source.size, opts.signal), { objectMode: false }),
70
+ async function* (chunks: AsyncIterable<Uint8Array>) {
71
+ for await (const c of chunks) {
72
+ sha.update(c);
73
+ yield c;
74
+ }
75
+ },
76
+ out,
77
+ );
78
+ if (opts.sha256 && sha.digest("hex") !== opts.sha256) throw new BlobSourceError(`the bytes for ${key} do not hash to ${opts.sha256}`);
79
+ try {
80
+ fs.linkSync(tmp, target);
81
+ return { created: true };
82
+ } catch (err) {
83
+ if ((err as NodeJS.ErrnoException).code === "EEXIST") return { created: false };
84
+ throw err;
85
+ }
86
+ } finally {
87
+ fs.rmSync(tmp, { force: true });
88
+ }
89
+ },
90
+ async abortStaleUploads({ olderThanMs, prefix = "" }) {
91
+ // The fs driver's "incomplete uploads" are temp files a dead writer left.
92
+ let n = 0;
93
+ const walk = (dir: string) => {
94
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
95
+ const f = path.join(dir, e.name);
96
+ if (e.isDirectory()) walk(f);
97
+ else if (e.name.endsWith(".tmp") && path.relative(root, f).startsWith(prefix) && Date.now() - fs.statSync(f).mtimeMs >= olderThanMs) {
98
+ fs.rmSync(f, { force: true });
99
+ n++;
100
+ }
101
+ }
102
+ };
103
+ if (fs.existsSync(root)) walk(root);
104
+ return n;
105
+ },
106
+ async putIfAbsent(key, body) {
107
+ const target = at(key);
108
+ fs.mkdirSync(path.dirname(target), { recursive: true });
109
+ if (fs.existsSync(target)) return { created: false };
110
+ const tmp = `${target}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`;
111
+ fs.writeFileSync(tmp, body);
112
+ try {
113
+ // link() refuses an existing target: the atomic "create if absent".
114
+ fs.linkSync(tmp, target);
115
+ return { created: true };
116
+ } catch (err) {
117
+ if ((err as NodeJS.ErrnoException).code === "EEXIST") return { created: false };
118
+ throw err;
119
+ } finally {
120
+ fs.rmSync(tmp, { force: true });
121
+ }
122
+ },
123
+ async get(key, opts = {}) {
124
+ const target = at(key);
125
+ if (!fs.existsSync(target)) throw new BlobNotFound(key);
126
+ const stream = fs.createReadStream(target, opts.range ? { start: opts.range.start, end: opts.range.end } : {});
127
+ return Readable.toWeb(stream) as unknown as ReadableStream<Uint8Array>;
128
+ },
129
+ async head(key) {
130
+ const target = at(key); // a bad key throws; only a missing file is null
131
+ try {
132
+ const st = fs.statSync(target);
133
+ return st.isFile() ? { size: st.size, modifiedAt: st.mtime } : null;
134
+ } catch {
135
+ return null;
136
+ }
137
+ },
138
+ async delete(key) {
139
+ fs.rmSync(at(key), { force: true });
140
+ },
141
+ async purgeTenant(tenant) {
142
+ fs.rmSync(path.dirname(at(`t/${tenant}/x`)), { recursive: true, force: true });
143
+ },
144
+ async *list(prefix) {
145
+ const base = at(`${prefix.replace(/\/+$/, "")}/x`);
146
+ const dir = path.dirname(base);
147
+ const walk = function* (d: string, rel: string): Generator<ListedObject> {
148
+ let names: fs.Dirent[] = [];
149
+ try {
150
+ names = fs.readdirSync(d, { withFileTypes: true });
151
+ } catch {
152
+ return;
153
+ }
154
+ for (const e of names) {
155
+ if (e.isDirectory()) yield* walk(path.join(d, e.name), `${rel}${e.name}/`);
156
+ else if (e.isFile() && !e.name.endsWith(".tmp")) {
157
+ try {
158
+ const st = fs.statSync(path.join(d, e.name));
159
+ yield { key: `${rel}${e.name}`, size: st.size, modifiedAt: st.mtime };
160
+ } catch {
161
+ // gone meanwhile
162
+ }
163
+ }
164
+ }
165
+ };
166
+ yield* walk(dir, `${prefix.replace(/\/+$/, "")}/`);
167
+ },
168
+ async tenants() {
169
+ try {
170
+ return fs.readdirSync(path.join(root, "t"), { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
171
+ } catch {
172
+ return [];
173
+ }
174
+ },
175
+ };
176
+ }
177
+
178
+ // ---------- download to a file ----------
179
+
180
+ /**
181
+ * Fetch an object into a file, resuming. The bytes land in `<dest>.part`;
182
+ * a connection cut mid-body (a transient error) is picked up again with a
183
+ * Range from where the file ends, and so is a `.part` a dead process left.
184
+ * The whole file is hashed against `sha256` (when given) before it is renamed
185
+ * into place; a mismatch discards it and throws BlobSourceError.
186
+ */
187
+ export async function downloadToFile(
188
+ store: BlobStore,
189
+ key: string,
190
+ dest: string,
191
+ opts: { sha256?: string; signal?: AbortSignal; attempts?: number } = {},
192
+ ): Promise<{ size: number }> {
193
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
194
+ const part = `${dest}.part`;
195
+ const size = (await store.head(key, { signal: opts.signal }))?.size;
196
+ if (size === undefined) throw new BlobNotFound(key);
197
+ const max = opts.attempts ?? 5;
198
+ for (let attempt = 0; ; attempt++) {
199
+ let have = fs.existsSync(part) ? fs.statSync(part).size : 0;
200
+ if (have > size) {
201
+ fs.rmSync(part, { force: true });
202
+ have = 0;
203
+ }
204
+ if (have < size) {
205
+ try {
206
+ const body = await store.get(key, { signal: opts.signal, ...(have > 0 ? { range: { start: have, end: size - 1 } } : {}) });
207
+ await pipeline(Readable.fromWeb(body as never), fs.createWriteStream(part, { flags: have > 0 ? "a" : "w" }));
208
+ } catch (err) {
209
+ const transient = err instanceof BlobTransientError || (err as { cause?: unknown })?.cause instanceof BlobTransientError;
210
+ if (!transient || attempt + 1 >= max || opts.signal?.aborted) throw err;
211
+ continue;
212
+ }
213
+ } else if (have === 0) {
214
+ // An empty object: nothing to fetch, but the file must still exist to
215
+ // be checked and renamed into place like any other.
216
+ fs.writeFileSync(part, "");
217
+ }
218
+ if (fs.statSync(part).size !== size) {
219
+ if (attempt + 1 >= max) throw new BlobTransientError(`download of ${key} stopped short`);
220
+ continue;
221
+ }
222
+ break;
223
+ }
224
+ if (opts.sha256) {
225
+ const h = await hashRange(fileRange(part), 0, size, opts.signal);
226
+ if (h.sha256 !== opts.sha256) {
227
+ fs.rmSync(part, { force: true });
228
+ throw new BlobSourceError(`${key} does not hash to ${opts.sha256}`);
229
+ }
230
+ }
231
+ fs.renameSync(part, dest);
232
+ return { size };
233
+ }
234
+
235
+ const fileRange = (file: string): BlobSource => ({
236
+ size: fs.statSync(file).size,
237
+ async *read(start, end) {
238
+ if (end > start) yield* fs.createReadStream(file, { start, end: end - 1 });
239
+ },
240
+ });
241
+
242
+ // ---------- the store in force ----------
243
+
244
+ /** s3 when FOLDRUN_STORAGE_DRIVER=s3 and it is fully configured, else fs.
245
+ * (The same fall-back rule as storage.ts's driverFor.) */
246
+ export function blobStore(): BlobStore & BlobSweeper {
247
+ if (process.env.FOLDRUN_STORAGE_DRIVER === "s3") {
248
+ const cfg = s3Config();
249
+ if (cfg) return bounded(s3BlobStore(cfg));
250
+ }
251
+ return bounded(fsBlobStore());
252
+ }
253
+
254
+ // ---------- deadlines, retries, concurrency ----------
255
+
256
+ export interface Limits {
257
+ /** Per attempt. */
258
+ deadlineMs: number;
259
+ /** Extra attempts after the first, for transient failures only. */
260
+ retries: number;
261
+ /** Calls in flight at once, across all keys. */
262
+ concurrency: number;
263
+ /** First backoff; doubles each retry, with jitter. */
264
+ backoffMs: number;
265
+ /** The slowest link a transfer is expected to survive. A put's deadline is
266
+ * `deadlineMs` plus its size over this, so a 400 MB blob is not cut off at
267
+ * the 30 s a head gets. */
268
+ minBytesPerSec: number;
269
+ }
270
+
271
+ export const DEFAULT_LIMITS: Limits = { deadlineMs: 30_000, retries: 3, concurrency: 8, backoffMs: 200, minBytesPerSec: 1024 * 1024 };
272
+
273
+ export function limitsFromEnv(env: NodeJS.ProcessEnv = process.env): Limits {
274
+ const n = (v: string | undefined, d: number) => (v !== undefined && /^\d+$/.test(v) ? Number(v) : d);
275
+ return {
276
+ deadlineMs: n(env.FOLDRUN_BLOB_DEADLINE_MS, DEFAULT_LIMITS.deadlineMs),
277
+ retries: n(env.FOLDRUN_BLOB_RETRIES, DEFAULT_LIMITS.retries),
278
+ concurrency: Math.max(1, n(env.FOLDRUN_BLOB_CONCURRENCY, DEFAULT_LIMITS.concurrency)),
279
+ backoffMs: DEFAULT_LIMITS.backoffMs,
280
+ minBytesPerSec: Math.max(1, n(env.FOLDRUN_BLOB_MIN_BYTES_PER_SEC, DEFAULT_LIMITS.minBytesPerSec)),
281
+ };
282
+ }
283
+
284
+ class Semaphore {
285
+ private waiting: (() => void)[] = [];
286
+ private active = 0;
287
+ private readonly max: number;
288
+ constructor(max: number) {
289
+ this.max = max;
290
+ }
291
+ async run<T>(fn: () => Promise<T>): Promise<T> {
292
+ if (this.active >= this.max) await new Promise<void>((r) => this.waiting.push(r));
293
+ this.active++;
294
+ try {
295
+ return await fn();
296
+ } finally {
297
+ this.active--;
298
+ this.waiting.shift()?.();
299
+ }
300
+ }
301
+ }
302
+
303
+ const isTransient = (err: unknown) =>
304
+ err instanceof BlobTransientError || ["ECONNRESET", "ETIMEDOUT", "EAGAIN", "EBUSY", "EMFILE"].includes((err as NodeJS.ErrnoException)?.code ?? "");
305
+
306
+ /**
307
+ * Wrap a store so every call has a deadline (an AbortSignal handed down; the
308
+ * call fails with BlobTransientError if it passes), is retried on transient
309
+ * failure within a budget, and counts against a concurrency cap.
310
+ *
311
+ * A `get` is deadline-bound only until the stream starts: a long download is
312
+ * the caller's to bound. A not-found, a 4xx and a bad key are never retried.
313
+ */
314
+ export function bounded<S extends BlobStore & Partial<BlobSweeper>>(inner: S, limits: Partial<Limits> = {}): S & BlobSweeper {
315
+ const L = { ...limitsFromEnv(), ...limits };
316
+ const gate = new Semaphore(L.concurrency);
317
+ /** The caller's signal and this attempt's deadline, either of which ends it. */
318
+ const both = (caller: AbortSignal | undefined, ms: number) => {
319
+ const deadline = AbortSignal.timeout(ms);
320
+ return caller ? AbortSignal.any([caller, deadline]) : deadline;
321
+ };
322
+ async function call<T>(what: string, caller: AbortSignal | undefined, fn: (signal: AbortSignal) => Promise<T>, bytes = 0): Promise<T> {
323
+ const ms = L.deadlineMs + Math.ceil((bytes / L.minBytesPerSec) * 1000);
324
+ return gate.run(async () => {
325
+ let attempt = 0;
326
+ for (;;) {
327
+ if (caller?.aborted) throw caller.reason ?? new Error(`${what}: cancelled`);
328
+ const signal = both(caller, ms);
329
+ try {
330
+ return await Promise.race([
331
+ fn(signal),
332
+ new Promise<never>((_, reject) =>
333
+ signal.addEventListener(
334
+ "abort",
335
+ () => reject(caller?.aborted ? (caller.reason ?? new Error(`${what}: cancelled`)) : new BlobTransientError(`${what}: no answer within ${ms}ms`)),
336
+ { once: true },
337
+ ),
338
+ ),
339
+ ]);
340
+ } catch (err) {
341
+ if (caller?.aborted || !isTransient(err) || attempt >= L.retries) throw err;
342
+ attempt++;
343
+ await new Promise((r) => setTimeout(r, L.backoffMs * 2 ** (attempt - 1) * (0.5 + Math.random())));
344
+ }
345
+ }
346
+ });
347
+ }
348
+ return {
349
+ ...inner,
350
+ kind: inner.kind,
351
+ putIfAbsent: (key, body, opts) => call("put", opts?.signal, (signal) => inner.putIfAbsent(key, body, { ...opts, signal }), body.byteLength),
352
+ // The deadline covers getting the stream going, not draining it: the
353
+ // timer is cleared once the object starts to arrive. The caller's signal
354
+ // stays attached to the stream, so cancelling still stops the download.
355
+ get: (key, opts) =>
356
+ call("get", opts?.signal, async () => {
357
+ const ctl = new AbortController();
358
+ const timer = setTimeout(() => ctl.abort(), L.deadlineMs);
359
+ const onCaller = () => ctl.abort(opts?.signal?.reason);
360
+ opts?.signal?.addEventListener("abort", onCaller, { once: true });
361
+ try {
362
+ return await inner.get(key, { ...opts, signal: ctl.signal });
363
+ } finally {
364
+ clearTimeout(timer);
365
+ }
366
+ }),
367
+ // A streamed put has no fixed deadline (its length decides), so it gets the
368
+ // retry budget and the concurrency cap, and the s3 driver's own per-request
369
+ // deadlines. Cancelling is the caller's signal.
370
+ putSourceIfAbsent: (key, source, opts) =>
371
+ gate.run(async () => {
372
+ for (let attempt = 0; ; attempt++) {
373
+ if (opts?.signal?.aborted) throw opts.signal.reason ?? new Error("put: cancelled");
374
+ try {
375
+ return await inner.putSourceIfAbsent(key, source, opts);
376
+ } catch (err) {
377
+ if (opts?.signal?.aborted || !isTransient(err) || attempt >= L.retries) throw err;
378
+ await new Promise((r) => setTimeout(r, L.backoffMs * 2 ** attempt * (0.5 + Math.random())));
379
+ }
380
+ }
381
+ }),
382
+ abortStaleUploads: (o) => (inner.abortStaleUploads ? inner.abortStaleUploads(o) : Promise.resolve(0)),
383
+ head: (key, opts) => call("head", opts?.signal, (signal) => inner.head(key, { signal })),
384
+ delete: (key, opts) => call("delete", opts?.signal, (signal) => (inner.delete ? inner.delete(key, { signal }) : Promise.reject(new Error("this store cannot delete")))),
385
+ ...(inner.purgeTenant ? { purgeTenant: (tenant: string) => inner.purgeTenant!(tenant) } : {}),
386
+ ...(inner.list ? { list: (prefix: string, o?: { signal?: AbortSignal }) => inner.list!(prefix, o) } : {}),
387
+ ...(inner.tenants ? { tenants: (o?: { signal?: AbortSignal }) => inner.tenants!(o) } : {}),
388
+ } as S & BlobSweeper;
389
+ }