@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
@@ -10,7 +10,7 @@
10
10
  // at a desk. So the decision lives in core and the routes only say who made
11
11
  // it.
12
12
  import crypto from "node:crypto";
13
- import { readRun, writeRun, readFlow, mayApprove } from "./store.js";
13
+ import { readRun, writeRunAsync, readFlow, mayApprove } from "./store.js";
14
14
  import { platform } from "./platform.js";
15
15
  import { approveToken, eventToken, installKey } from "./webhook.js";
16
16
  // ----------------------------------------------------------------- links
@@ -203,7 +203,7 @@ export async function decideApproval(tenant, workspace, runId, d) {
203
203
  if (d.link !== undefined) {
204
204
  run.approvalLinksUsed = [...(run.approvalLinksUsed ?? []), linkDigest(d.link)].slice(-50);
205
205
  }
206
- writeRun(tenant, workspace, run);
206
+ await writeRunAsync(tenant, workspace, run);
207
207
  // A parked run has no process polling for this decision — the worker
208
208
  // that was driving it gave its slot back at the gate. Line it up again.
209
209
  // Runs without the marker still have their starter polling the file, and
@@ -341,7 +341,7 @@ export async function deliverEvent(tenant, workspace, runId, payload, opts = {})
341
341
  }
342
342
  for (const { s } of waiting)
343
343
  s.eventPayload = payload.slice(0, 20_000);
344
- writeRun(tenant, workspace, run);
344
+ await writeRunAsync(tenant, workspace, run);
345
345
  let decided = [];
346
346
  for (const { i } of waiting) {
347
347
  const out = await decideApproval(tenant, workspace, runId, { decision: "approve", step: i, by: opts.by ?? "by an external event" });
@@ -0,0 +1,58 @@
1
+ import { Readable } from "node:stream";
2
+ import { type BlobStore } from "./blob-store.ts";
3
+ export interface BlobCacheOptions {
4
+ /** Where entries live. Must be node-local disk. */
5
+ dir: string;
6
+ /** The cap on bytes held, soft only while everything is pinned. */
7
+ maxBytes: number;
8
+ /** Where a miss is read from. Only `head`/`get` are used. */
9
+ store: BlobStore;
10
+ /** Downloads of different blobs at once. */
11
+ fillConcurrency?: number;
12
+ /** A `.part` older than this at start-up is a dead process's; remove it. */
13
+ stalePartMs?: number;
14
+ }
15
+ export interface CacheLease {
16
+ /** An existing, complete, hash-verified file. Read it; do not write it. */
17
+ readonly path: string;
18
+ readonly size: number;
19
+ /** Let the entry be evicted again. Safe to call twice. */
20
+ release(): void;
21
+ }
22
+ export interface CacheStats {
23
+ entries: number;
24
+ bytes: number;
25
+ maxBytes: number;
26
+ pinned: number;
27
+ hits: number;
28
+ misses: number;
29
+ /** Misses that joined a download already running. */
30
+ joined: number;
31
+ fills: number;
32
+ evictions: number;
33
+ /** Times the cache was over its cap because nothing was evictable. */
34
+ overCap: number;
35
+ peakBytes: number;
36
+ fillsInFlight: number;
37
+ }
38
+ export interface BlobCache {
39
+ acquire(tenant: string, sha: string, opts?: {
40
+ signal?: AbortSignal;
41
+ }): Promise<CacheLease>;
42
+ /** The blob as a stream (an optional inclusive byte range); pinned until the stream closes. */
43
+ stream(tenant: string, sha: string, opts?: {
44
+ signal?: AbortSignal;
45
+ range?: {
46
+ start: number;
47
+ end: number;
48
+ };
49
+ }): Promise<Readable>;
50
+ /** Run `fn` with the blob pinned. */
51
+ withBlob<T>(tenant: string, sha: string, fn: (file: string, size: number) => Promise<T>, opts?: {
52
+ signal?: AbortSignal;
53
+ }): Promise<T>;
54
+ stats(): CacheStats;
55
+ }
56
+ export declare function defaultCacheDir(env?: NodeJS.ProcessEnv): string;
57
+ export declare function cacheMaxBytesFromEnv(env?: NodeJS.ProcessEnv): number;
58
+ export declare function blobCache(opts: BlobCacheOptions): BlobCache;
@@ -0,0 +1,312 @@
1
+ // A node-local, bounded cache of blobs, keyed by sha (FOL-126, phase 3 seam).
2
+ //
3
+ // Object storage holds the truth; local disk is only a cache. A reader asks for
4
+ // (tenant, sha) and gets a file path it can open, stat, or hand to a tar. A
5
+ // miss is read through: the blob is downloaded from the BlobStore, hashed
6
+ // against its name, and only then made visible.
7
+ //
8
+ // * bounded a byte cap; past it the least recently used UNPINNED entries
9
+ // are removed. The cap is soft in one case only: when every
10
+ // entry is pinned (or one blob alone is bigger than the cap)
11
+ // the cache goes over rather than pull a file out from under a
12
+ // reader. It shrinks again as leases are released.
13
+ // * pinned `acquire` returns a lease; an entry with a live lease is never
14
+ // evicted. Release it (idempotent) when done; `stream()` and
15
+ // `withBlob()` do it for you.
16
+ // * atomic a download goes to `tmp/` and is renamed into place after the
17
+ // hash matched. No reader ever sees a partial file, and a crash
18
+ // leaves only a `.part` that the next start sweeps when old.
19
+ // * concurrent N readers of one missing blob share ONE download (single
20
+ // flight) and each gets its own pin. Fills across different
21
+ // blobs are capped (`fillConcurrency`), on top of the store's own
22
+ // concurrency cap. A reader that gives up (its signal) does not
23
+ // cancel the download the others are waiting for.
24
+ // * tenant-safe the directory is per tenant. Content addressing would let two
25
+ // tenants share a file, but then a cache hit would answer "does
26
+ // this sha exist?" without the store's authorisation; cross
27
+ // tenant dedup is a non-goal of FOL-126.
28
+ //
29
+ // What it is NOT: shared between processes. Each process keeps its own index of
30
+ // its directory. Two processes on one directory are tolerated (publish is a
31
+ // rename, eviction renames before it unlinks, a file that vanished is a miss)
32
+ // but they do not see each other's pins, so give each pod its own directory
33
+ // (an emptyDir or node disk, never the shared volume this refactor removes).
34
+ import fs from "node:fs";
35
+ import os from "node:os";
36
+ import path from "node:path";
37
+ import crypto from "node:crypto";
38
+ import { downloadToFile } from "./blob-store.js";
39
+ import { blobObjectKey } from "./manifest.js";
40
+ const SHA = /^[0-9a-f]{64}$/;
41
+ export function defaultCacheDir(env = process.env) {
42
+ return env.FOLDRUN_BLOB_CACHE_DIR || path.join(os.tmpdir(), "foldrun-blob-cache");
43
+ }
44
+ export function cacheMaxBytesFromEnv(env = process.env) {
45
+ const v = env.FOLDRUN_BLOB_CACHE_MB;
46
+ return (v && /^\d+$/.test(v) && Number(v) > 0 ? Number(v) : 2048) * 1024 * 1024;
47
+ }
48
+ export function blobCache(opts) {
49
+ const { dir, maxBytes, store } = opts;
50
+ const root = path.join(dir, "blobs");
51
+ const tmpDir = path.join(dir, "tmp");
52
+ const fillCap = Math.max(1, opts.fillConcurrency ?? 4);
53
+ fs.mkdirSync(root, { recursive: true });
54
+ fs.mkdirSync(tmpDir, { recursive: true });
55
+ const index = new Map();
56
+ const fills = new Map();
57
+ let tick = 0;
58
+ let bytes = 0;
59
+ const st = { hits: 0, misses: 0, joined: 0, fills: 0, evictions: 0, overCap: 0, peakBytes: 0 };
60
+ const keyOf = (tenant, sha) => {
61
+ if (!SHA.test(sha))
62
+ throw new Error("expected a sha256");
63
+ blobObjectKey(tenant, sha); // validates the tenant segment
64
+ return `${tenant}/${sha}`;
65
+ };
66
+ const fileOf = (tenant, sha) => path.join(root, tenant, sha.slice(0, 2), sha);
67
+ // ---- start-up: take what is on disk, oldest use first; sweep dead parts ----
68
+ {
69
+ const found = [];
70
+ for (const t of safeDir(root)) {
71
+ for (const shard of safeDir(path.join(root, t))) {
72
+ for (const name of safeDir(path.join(root, t, shard))) {
73
+ if (!SHA.test(name))
74
+ continue;
75
+ try {
76
+ const s = fs.statSync(path.join(root, t, shard, name));
77
+ if (s.isFile())
78
+ found.push({ k: `${t}/${name}`, size: s.size, at: s.mtimeMs });
79
+ }
80
+ catch { }
81
+ }
82
+ }
83
+ }
84
+ found.sort((a, b) => a.at - b.at);
85
+ for (const f of found) {
86
+ index.set(f.k, { size: f.size, pins: 0, tick: ++tick });
87
+ bytes += f.size;
88
+ }
89
+ const stale = opts.stalePartMs ?? 3600_000;
90
+ for (const n of safeDir(tmpDir)) {
91
+ try {
92
+ const f = path.join(tmpDir, n);
93
+ if (Date.now() - fs.statSync(f).mtimeMs >= stale)
94
+ fs.rmSync(f, { force: true });
95
+ }
96
+ catch { }
97
+ }
98
+ }
99
+ const gate = (() => {
100
+ let active = 0;
101
+ const waiting = [];
102
+ return async (fn) => {
103
+ if (active >= fillCap)
104
+ await new Promise((r) => waiting.push(r));
105
+ active++;
106
+ try {
107
+ return await fn();
108
+ }
109
+ finally {
110
+ active--;
111
+ waiting.shift()?.();
112
+ }
113
+ };
114
+ })();
115
+ let inFlight = 0;
116
+ /** Remove least-recently-used unpinned entries until under the cap. */
117
+ function evict() {
118
+ while (bytes > maxBytes) {
119
+ let victim = null;
120
+ for (const e of index)
121
+ if (e[1].pins === 0 && (!victim || e[1].tick < victim[1].tick))
122
+ victim = e;
123
+ if (!victim) {
124
+ st.overCap++;
125
+ return;
126
+ }
127
+ const [k, e] = victim;
128
+ index.delete(k);
129
+ bytes -= e.size;
130
+ st.evictions++;
131
+ const [tenant, sha] = k.split("/");
132
+ // Rename first: a reader that opens by path sees ENOENT (a miss), never a
133
+ // half-deleted file; an fd already open keeps reading its inode.
134
+ const gone = path.join(tmpDir, `evict-${process.pid}-${crypto.randomBytes(4).toString("hex")}`);
135
+ try {
136
+ fs.renameSync(fileOf(tenant, sha), gone);
137
+ fs.rmSync(gone, { force: true });
138
+ }
139
+ catch { }
140
+ }
141
+ }
142
+ const lease = (k, e, file) => {
143
+ let released = false;
144
+ return {
145
+ path: file,
146
+ size: e.size,
147
+ release() {
148
+ if (released)
149
+ return;
150
+ released = true;
151
+ e.pins--;
152
+ if (index.get(k) === e && bytes > maxBytes)
153
+ evict();
154
+ },
155
+ };
156
+ };
157
+ /** A hit if the file is really there at the size we recorded. */
158
+ function hit(k, tenant, sha) {
159
+ const e = index.get(k);
160
+ if (!e)
161
+ return null;
162
+ const file = fileOf(tenant, sha);
163
+ try {
164
+ if (fs.statSync(file).size !== e.size)
165
+ throw new Error("size changed");
166
+ }
167
+ catch {
168
+ // Removed or damaged behind our back (another process, a tmp cleaner).
169
+ if (e.pins === 0) {
170
+ index.delete(k);
171
+ bytes -= e.size;
172
+ }
173
+ return null;
174
+ }
175
+ e.pins++;
176
+ e.tick = ++tick;
177
+ const now = new Date();
178
+ fs.utimes(file, now, now, () => { }); // keeps the order across a restart
179
+ return lease(k, e, file);
180
+ }
181
+ function startFill(k, tenant, sha, f) {
182
+ return gate(async () => {
183
+ inFlight++;
184
+ // downloadToFile writes `<dl>.part` and renames it to `dl` once the hash
185
+ // matched; `dl` is then renamed into the cache. Both names are removed
186
+ // below whatever happens: a fill that failed (a final error, retries
187
+ // spent) would otherwise leave its bytes in tmp/, outside the count
188
+ // that maxBytes holds, until the next start-up sweep.
189
+ const dl = path.join(tmpDir, `${tenant}-${sha}.${process.pid}.dl`);
190
+ try {
191
+ const final = fileOf(tenant, sha);
192
+ fs.mkdirSync(path.dirname(final), { recursive: true });
193
+ const { size } = await downloadToFile(store, blobObjectKey(tenant, sha), dl, { sha256: sha });
194
+ fs.renameSync(dl, final);
195
+ const e = { size, pins: f.waiters, tick: ++tick };
196
+ const old = index.get(k);
197
+ if (old)
198
+ bytes -= old.size; // another process won the rename; same bytes
199
+ index.set(k, e);
200
+ bytes += size;
201
+ st.peakBytes = Math.max(st.peakBytes, bytes);
202
+ f.inserted = true;
203
+ st.fills++;
204
+ evict(); // the new entry is pinned by its waiters; others may go
205
+ }
206
+ finally {
207
+ inFlight--;
208
+ fs.rmSync(`${dl}.part`, { force: true });
209
+ fs.rmSync(dl, { force: true });
210
+ }
211
+ });
212
+ }
213
+ async function acquire(tenant, sha, o = {}) {
214
+ const k = keyOf(tenant, sha);
215
+ if (o.signal?.aborted)
216
+ throw o.signal.reason ?? new Error("cancelled");
217
+ const got = hit(k, tenant, sha);
218
+ if (got) {
219
+ st.hits++;
220
+ return got;
221
+ }
222
+ let f = fills.get(k);
223
+ if (f)
224
+ st.joined++;
225
+ else {
226
+ st.misses++;
227
+ const fill = { waiters: 0, inserted: false, promise: Promise.resolve() };
228
+ fills.set(k, fill);
229
+ fill.promise = startFill(k, tenant, sha, fill).finally(() => {
230
+ if (fills.get(k) === fill)
231
+ fills.delete(k);
232
+ });
233
+ // A failed fill rejects every waiter; nothing else holds the promise.
234
+ fill.promise.catch(() => { });
235
+ f = fill;
236
+ }
237
+ f.waiters++;
238
+ const mine = f;
239
+ let abort;
240
+ try {
241
+ await Promise.race([
242
+ mine.promise,
243
+ new Promise((_, reject) => {
244
+ if (!o.signal)
245
+ return;
246
+ abort = () => reject(o.signal.reason ?? new Error("cancelled"));
247
+ o.signal.addEventListener("abort", abort, { once: true });
248
+ }),
249
+ ]);
250
+ }
251
+ catch (err) {
252
+ // Leaving: if the entry was already pinned for us, give that pin back.
253
+ if (mine.inserted) {
254
+ const e = index.get(k);
255
+ if (e) {
256
+ e.pins--;
257
+ if (bytes > maxBytes)
258
+ evict();
259
+ }
260
+ }
261
+ else
262
+ mine.waiters--;
263
+ throw err;
264
+ }
265
+ finally {
266
+ if (abort)
267
+ o.signal.removeEventListener("abort", abort);
268
+ }
269
+ const e = index.get(k);
270
+ e.tick = ++tick;
271
+ return lease(k, e, fileOf(tenant, sha));
272
+ }
273
+ return {
274
+ acquire,
275
+ async stream(tenant, sha, o = {}) {
276
+ const l = await acquire(tenant, sha, o);
277
+ try {
278
+ const rs = fs.createReadStream(l.path, o.range ? { start: o.range.start, end: o.range.end } : {});
279
+ rs.once("close", () => l.release());
280
+ return rs;
281
+ }
282
+ catch (err) {
283
+ l.release();
284
+ throw err;
285
+ }
286
+ },
287
+ async withBlob(tenant, sha, fn, o = {}) {
288
+ const l = await acquire(tenant, sha, o);
289
+ try {
290
+ return await fn(l.path, l.size);
291
+ }
292
+ finally {
293
+ l.release();
294
+ }
295
+ },
296
+ stats() {
297
+ let pinned = 0;
298
+ for (const e of index.values())
299
+ if (e.pins > 0)
300
+ pinned++;
301
+ return { entries: index.size, bytes, maxBytes, pinned, ...st, fillsInFlight: inFlight };
302
+ },
303
+ };
304
+ }
305
+ function safeDir(d) {
306
+ try {
307
+ return fs.readdirSync(d);
308
+ }
309
+ catch {
310
+ return [];
311
+ }
312
+ }
@@ -0,0 +1,44 @@
1
+ import type { ManifestId } from "./manifest.ts";
2
+ export type PinKind = "blob" | "manifest";
3
+ export type HolderKind = "publish" | "run" | "revision";
4
+ export interface PinHolder {
5
+ kind: HolderKind;
6
+ /** publish: the op id. run: the run id. revision: the revision id. */
7
+ id: string;
8
+ }
9
+ export interface BlobPins {
10
+ /** Pin blobs (by sha) for a holder. Idempotent: a repeat extends the lease. */
11
+ pinBlobs(tenant: string, shas: readonly string[], holder: PinHolder, opts?: {
12
+ ttlMs?: number;
13
+ }): Promise<void>;
14
+ /** Pin manifests the same way. */
15
+ pinManifests(tenant: string, ids: readonly ManifestId[], holder: PinHolder, opts?: {
16
+ ttlMs?: number;
17
+ }): Promise<void>;
18
+ /** Drop every pin a holder has. Returns how many went. */
19
+ release(tenant: string, holder: PinHolder): Promise<number>;
20
+ /** Push a holder's leases out by ttlMs from now (a running run's heartbeat).
21
+ * Pins with no lease are left alone. Returns how many were renewed. */
22
+ renew(tenant: string, holder: PinHolder, ttlMs: number): Promise<number>;
23
+ /** Is anything holding this object right now (a live, unexpired pin)? */
24
+ isPinned(tenant: string, kind: PinKind, ref: string): Promise<boolean>;
25
+ /** Is a live pin on this object held by something OTHER than a revision (a
26
+ * run reading it, a publish in flight)? Retention asks this before it lets
27
+ * a revision go: the revision's own pin is the one it is about to release. */
28
+ isPinnedBeyondRevisions(tenant: string, kind: PinKind, ref: string): Promise<boolean>;
29
+ /** Everything of this account a live (unexpired) pin names, any holder: the
30
+ * sweeper's roots besides the revisions. */
31
+ live(tenant: string): Promise<{
32
+ manifests: string[];
33
+ blobs: string[];
34
+ }>;
35
+ /** The sweeper's only way to delete: runs `del` only if no live pin names
36
+ * the object, with pinning of that object held off for the duration.
37
+ * Returns whether `del` ran. */
38
+ guardDelete(tenant: string, kind: PinKind, ref: string, del: () => Promise<void>): Promise<boolean>;
39
+ }
40
+ /** No database, no sweeper: nothing to agree with. */
41
+ export declare const noPins: BlobPins;
42
+ /** How long a publish's blob pins live without a renewal: far longer than an
43
+ * upload, short enough that a crashed publisher frees its blobs the same day. */
44
+ export declare const PUBLISH_PIN_TTL_MS: number;
@@ -0,0 +1,61 @@
1
+ // Durable pins for blob GC (FOL-126, phase 2).
2
+ //
3
+ // Phase 1 left one hole open: publish confirms its blobs exist and then
4
+ // commits, and a sweeper that deletes between those two calls strands the new
5
+ // revision on a missing blob. A conditional put does not refresh an existing
6
+ // object's age, so a grace period alone cannot protect an old blob that a new
7
+ // publish reuses. The two sides have to agree on something durable.
8
+ //
9
+ // That agreement is a PIN: a row saying "this holder still needs this object".
10
+ //
11
+ // publish pins the blobs it is about to name (holder `publish:<opId>`,
12
+ // with a lease) BEFORE it checks they exist, and releases the pin
13
+ // after the commit. In between, a sweeper sees the pin.
14
+ // revision pins its two manifests, in the SAME transaction as the commit
15
+ // (holder `revision:<id>`, no lease). The sweeper's mark phase
16
+ // reads pinned manifests to learn which blobs are live. Pruning a
17
+ // revision from history releases its pin.
18
+ // run pins the manifests of the base revision it was staged from
19
+ // (holder `run:<runId>`, with a lease the worker renews), so a
20
+ // run that is still going never loses what it reads.
21
+ //
22
+ // A sweeper deletes through `guardDelete`: it takes the pin lock for that
23
+ // object, checks no live pin exists, deletes, and releases the lock. A
24
+ // publisher pins under the same lock. So either the pin lands first and the
25
+ // sweeper skips the object, or the delete finishes first and the publisher —
26
+ // which pins BEFORE it checks — finds the blob gone and uploads it again.
27
+ //
28
+ // Leases: a pin with `expiresAt` in the past does not protect anything (a
29
+ // crashed publisher must not hold a blob forever). Pins without one (a
30
+ // revision's) last until released.
31
+ //
32
+ // This file is the interface. The Postgres implementation is
33
+ // foldrun-platform/src/blob-pins.ts; an install with no database has no
34
+ // sweeper at all yet, and `noPins` is what it gets.
35
+ /** No database, no sweeper: nothing to agree with. */
36
+ export const noPins = {
37
+ async pinBlobs() { },
38
+ async pinManifests() { },
39
+ async release() {
40
+ return 0;
41
+ },
42
+ async renew() {
43
+ return 0;
44
+ },
45
+ async isPinned() {
46
+ return false;
47
+ },
48
+ async isPinnedBeyondRevisions() {
49
+ return false;
50
+ },
51
+ async live() {
52
+ return { manifests: [], blobs: [] };
53
+ },
54
+ async guardDelete(_t, _k, _r, del) {
55
+ await del();
56
+ return true;
57
+ },
58
+ };
59
+ /** How long a publish's blob pins live without a renewal: far longer than an
60
+ * upload, short enough that a crashed publisher frees its blobs the same day. */
61
+ export const PUBLISH_PIN_TTL_MS = 15 * 60_000;
@@ -0,0 +1,47 @@
1
+ import { s3BlobStore } from "./s3-blob-store.ts";
2
+ import { type BlobStore, type BlobSweeper } from "./blob-types.ts";
3
+ export * from "./blob-types.ts";
4
+ export { s3BlobStore };
5
+ export declare function fsBlobStore(root?: string): BlobStore & BlobSweeper;
6
+ /**
7
+ * Fetch an object into a file, resuming. The bytes land in `<dest>.part`;
8
+ * a connection cut mid-body (a transient error) is picked up again with a
9
+ * Range from where the file ends, and so is a `.part` a dead process left.
10
+ * The whole file is hashed against `sha256` (when given) before it is renamed
11
+ * into place; a mismatch discards it and throws BlobSourceError.
12
+ */
13
+ export declare function downloadToFile(store: BlobStore, key: string, dest: string, opts?: {
14
+ sha256?: string;
15
+ signal?: AbortSignal;
16
+ attempts?: number;
17
+ }): Promise<{
18
+ size: number;
19
+ }>;
20
+ /** s3 when FOLDRUN_STORAGE_DRIVER=s3 and it is fully configured, else fs.
21
+ * (The same fall-back rule as storage.ts's driverFor.) */
22
+ export declare function blobStore(): BlobStore & BlobSweeper;
23
+ export interface Limits {
24
+ /** Per attempt. */
25
+ deadlineMs: number;
26
+ /** Extra attempts after the first, for transient failures only. */
27
+ retries: number;
28
+ /** Calls in flight at once, across all keys. */
29
+ concurrency: number;
30
+ /** First backoff; doubles each retry, with jitter. */
31
+ backoffMs: number;
32
+ /** The slowest link a transfer is expected to survive. A put's deadline is
33
+ * `deadlineMs` plus its size over this, so a 400 MB blob is not cut off at
34
+ * the 30 s a head gets. */
35
+ minBytesPerSec: number;
36
+ }
37
+ export declare const DEFAULT_LIMITS: Limits;
38
+ export declare function limitsFromEnv(env?: NodeJS.ProcessEnv): Limits;
39
+ /**
40
+ * Wrap a store so every call has a deadline (an AbortSignal handed down; the
41
+ * call fails with BlobTransientError if it passes), is retried on transient
42
+ * failure within a budget, and counts against a concurrency cap.
43
+ *
44
+ * A `get` is deadline-bound only until the stream starts: a long download is
45
+ * the caller's to bound. A not-found, a 4xx and a bad key are never retried.
46
+ */
47
+ export declare function bounded<S extends BlobStore & Partial<BlobSweeper>>(inner: S, limits?: Partial<Limits>): S & BlobSweeper;