@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.
- package/dist/src/approvals.js +3 -3
- package/dist/src/blob-cache.d.ts +58 -0
- package/dist/src/blob-cache.js +312 -0
- package/dist/src/blob-pins.d.ts +44 -0
- package/dist/src/blob-pins.js +61 -0
- package/dist/src/blob-store.d.ts +47 -0
- package/dist/src/blob-store.js +362 -0
- package/dist/src/blob-sweeper.d.ts +70 -0
- package/dist/src/blob-sweeper.js +282 -0
- package/dist/src/blob-types.d.ts +145 -0
- package/dist/src/blob-types.js +115 -0
- package/dist/src/evals.js +1 -1
- package/dist/src/history.d.ts +92 -9
- package/dist/src/history.js +168 -20
- package/dist/src/journal-store.d.ts +58 -0
- package/dist/src/journal-store.js +117 -0
- package/dist/src/manifest.d.ts +92 -0
- package/dist/src/manifest.js +239 -0
- package/dist/src/ops-log.js +26 -3
- package/dist/src/platform.d.ts +7 -0
- package/dist/src/platform.js +1 -0
- package/dist/src/publish.d.ts +134 -0
- package/dist/src/publish.js +434 -0
- package/dist/src/records.d.ts +72 -0
- package/dist/src/records.js +24 -0
- package/dist/src/revision-store.d.ts +161 -0
- package/dist/src/revision-store.js +378 -0
- package/dist/src/run-container.d.ts +20 -0
- package/dist/src/run-container.js +61 -0
- package/dist/src/runner.js +1 -1
- package/dist/src/s3-blob-store.d.ts +29 -0
- package/dist/src/s3-blob-store.js +531 -0
- package/dist/src/state-retention.d.ts +15 -0
- package/dist/src/state-retention.js +65 -0
- package/dist/src/storage.d.ts +29 -1
- package/dist/src/storage.js +331 -81
- package/dist/src/store.d.ts +41 -0
- package/dist/src/store.js +188 -5
- package/dist/src/trigger-log.js +17 -0
- package/dist/src/workspace-revisions.d.ts +269 -0
- package/dist/src/workspace-revisions.js +1382 -0
- package/package.json +1 -1
- package/src/approvals.ts +3 -3
- package/src/blob-cache.ts +357 -0
- package/src/blob-pins.ts +99 -0
- package/src/blob-store.ts +389 -0
- package/src/blob-sweeper.ts +336 -0
- package/src/blob-types.ts +216 -0
- package/src/evals.ts +1 -1
- package/src/history.ts +226 -19
- package/src/journal-store.ts +152 -0
- package/src/manifest.ts +274 -0
- package/src/ops-log.ts +25 -3
- package/src/platform.ts +8 -0
- package/src/publish.ts +520 -0
- package/src/records.ts +105 -0
- package/src/revision-store.ts +513 -0
- package/src/run-container.ts +62 -0
- package/src/runner.ts +1 -1
- package/src/s3-blob-store.ts +560 -0
- package/src/state-retention.ts +83 -0
- package/src/storage.ts +335 -81
- package/src/store.ts +178 -5
- package/src/trigger-log.ts +15 -0
- package/src/workspace-revisions.ts +1423 -0
package/package.json
CHANGED
package/src/approvals.ts
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
// it.
|
|
12
12
|
|
|
13
13
|
import crypto from "node:crypto";
|
|
14
|
-
import { readRun,
|
|
14
|
+
import { readRun, writeRunAsync, readFlow, mayApprove, type FlowInfo, type RunRecord } from "./store.ts";
|
|
15
15
|
import { platform } from "./platform.ts";
|
|
16
16
|
import { approveToken, eventToken, installKey } from "./webhook.ts";
|
|
17
17
|
|
|
@@ -276,7 +276,7 @@ export async function decideApproval(
|
|
|
276
276
|
if (d.link !== undefined) {
|
|
277
277
|
run.approvalLinksUsed = [...(run.approvalLinksUsed ?? []), linkDigest(d.link)].slice(-50);
|
|
278
278
|
}
|
|
279
|
-
|
|
279
|
+
await writeRunAsync(tenant, workspace, run);
|
|
280
280
|
|
|
281
281
|
// A parked run has no process polling for this decision — the worker
|
|
282
282
|
// that was driving it gave its slot back at the gate. Line it up again.
|
|
@@ -434,7 +434,7 @@ export async function deliverEvent(
|
|
|
434
434
|
throw new ApprovalError(opts.step === undefined ? "this run is not waiting for an event" : `step ${opts.step} is not waiting for an event`, 409);
|
|
435
435
|
}
|
|
436
436
|
for (const { s } of waiting) s.eventPayload = payload.slice(0, 20_000);
|
|
437
|
-
|
|
437
|
+
await writeRunAsync(tenant, workspace, run);
|
|
438
438
|
let decided: number[] = [];
|
|
439
439
|
for (const { i } of waiting) {
|
|
440
440
|
const out = await decideApproval(tenant, workspace, runId, { decision: "approve", step: i, by: opts.by ?? "by an external event" });
|
|
@@ -0,0 +1,357 @@
|
|
|
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
|
+
|
|
35
|
+
import fs from "node:fs";
|
|
36
|
+
import os from "node:os";
|
|
37
|
+
import path from "node:path";
|
|
38
|
+
import crypto from "node:crypto";
|
|
39
|
+
import { Readable } from "node:stream";
|
|
40
|
+
import { downloadToFile, type BlobStore } from "./blob-store.ts";
|
|
41
|
+
import { blobObjectKey } from "./manifest.ts";
|
|
42
|
+
|
|
43
|
+
export interface BlobCacheOptions {
|
|
44
|
+
/** Where entries live. Must be node-local disk. */
|
|
45
|
+
dir: string;
|
|
46
|
+
/** The cap on bytes held, soft only while everything is pinned. */
|
|
47
|
+
maxBytes: number;
|
|
48
|
+
/** Where a miss is read from. Only `head`/`get` are used. */
|
|
49
|
+
store: BlobStore;
|
|
50
|
+
/** Downloads of different blobs at once. */
|
|
51
|
+
fillConcurrency?: number;
|
|
52
|
+
/** A `.part` older than this at start-up is a dead process's; remove it. */
|
|
53
|
+
stalePartMs?: number;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface CacheLease {
|
|
57
|
+
/** An existing, complete, hash-verified file. Read it; do not write it. */
|
|
58
|
+
readonly path: string;
|
|
59
|
+
readonly size: number;
|
|
60
|
+
/** Let the entry be evicted again. Safe to call twice. */
|
|
61
|
+
release(): void;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface CacheStats {
|
|
65
|
+
entries: number;
|
|
66
|
+
bytes: number;
|
|
67
|
+
maxBytes: number;
|
|
68
|
+
pinned: number;
|
|
69
|
+
hits: number;
|
|
70
|
+
misses: number;
|
|
71
|
+
/** Misses that joined a download already running. */
|
|
72
|
+
joined: number;
|
|
73
|
+
fills: number;
|
|
74
|
+
evictions: number;
|
|
75
|
+
/** Times the cache was over its cap because nothing was evictable. */
|
|
76
|
+
overCap: number;
|
|
77
|
+
peakBytes: number;
|
|
78
|
+
fillsInFlight: number;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
interface Entry {
|
|
82
|
+
size: number;
|
|
83
|
+
pins: number;
|
|
84
|
+
/** Monotonic use counter: the larger, the more recent. */
|
|
85
|
+
tick: number;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
interface Fill {
|
|
89
|
+
promise: Promise<void>;
|
|
90
|
+
/** Readers waiting; each is handed a pin when the entry is inserted. */
|
|
91
|
+
waiters: number;
|
|
92
|
+
inserted: boolean;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface BlobCache {
|
|
96
|
+
acquire(tenant: string, sha: string, opts?: { signal?: AbortSignal }): Promise<CacheLease>;
|
|
97
|
+
/** The blob as a stream (an optional inclusive byte range); pinned until the stream closes. */
|
|
98
|
+
stream(tenant: string, sha: string, opts?: { signal?: AbortSignal; range?: { start: number; end: number } }): Promise<Readable>;
|
|
99
|
+
/** Run `fn` with the blob pinned. */
|
|
100
|
+
withBlob<T>(tenant: string, sha: string, fn: (file: string, size: number) => Promise<T>, opts?: { signal?: AbortSignal }): Promise<T>;
|
|
101
|
+
stats(): CacheStats;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const SHA = /^[0-9a-f]{64}$/;
|
|
105
|
+
|
|
106
|
+
export function defaultCacheDir(env: NodeJS.ProcessEnv = process.env): string {
|
|
107
|
+
return env.FOLDRUN_BLOB_CACHE_DIR || path.join(os.tmpdir(), "foldrun-blob-cache");
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function cacheMaxBytesFromEnv(env: NodeJS.ProcessEnv = process.env): number {
|
|
111
|
+
const v = env.FOLDRUN_BLOB_CACHE_MB;
|
|
112
|
+
return (v && /^\d+$/.test(v) && Number(v) > 0 ? Number(v) : 2048) * 1024 * 1024;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function blobCache(opts: BlobCacheOptions): BlobCache {
|
|
116
|
+
const { dir, maxBytes, store } = opts;
|
|
117
|
+
const root = path.join(dir, "blobs");
|
|
118
|
+
const tmpDir = path.join(dir, "tmp");
|
|
119
|
+
const fillCap = Math.max(1, opts.fillConcurrency ?? 4);
|
|
120
|
+
fs.mkdirSync(root, { recursive: true });
|
|
121
|
+
fs.mkdirSync(tmpDir, { recursive: true });
|
|
122
|
+
|
|
123
|
+
const index = new Map<string, Entry>();
|
|
124
|
+
const fills = new Map<string, Fill>();
|
|
125
|
+
let tick = 0;
|
|
126
|
+
let bytes = 0;
|
|
127
|
+
const st = { hits: 0, misses: 0, joined: 0, fills: 0, evictions: 0, overCap: 0, peakBytes: 0 };
|
|
128
|
+
|
|
129
|
+
const keyOf = (tenant: string, sha: string) => {
|
|
130
|
+
if (!SHA.test(sha)) throw new Error("expected a sha256");
|
|
131
|
+
blobObjectKey(tenant, sha); // validates the tenant segment
|
|
132
|
+
return `${tenant}/${sha}`;
|
|
133
|
+
};
|
|
134
|
+
const fileOf = (tenant: string, sha: string) => path.join(root, tenant, sha.slice(0, 2), sha);
|
|
135
|
+
|
|
136
|
+
// ---- start-up: take what is on disk, oldest use first; sweep dead parts ----
|
|
137
|
+
{
|
|
138
|
+
const found: { k: string; size: number; at: number }[] = [];
|
|
139
|
+
for (const t of safeDir(root)) {
|
|
140
|
+
for (const shard of safeDir(path.join(root, t))) {
|
|
141
|
+
for (const name of safeDir(path.join(root, t, shard))) {
|
|
142
|
+
if (!SHA.test(name)) continue;
|
|
143
|
+
try {
|
|
144
|
+
const s = fs.statSync(path.join(root, t, shard, name));
|
|
145
|
+
if (s.isFile()) found.push({ k: `${t}/${name}`, size: s.size, at: s.mtimeMs });
|
|
146
|
+
} catch {}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
found.sort((a, b) => a.at - b.at);
|
|
151
|
+
for (const f of found) {
|
|
152
|
+
index.set(f.k, { size: f.size, pins: 0, tick: ++tick });
|
|
153
|
+
bytes += f.size;
|
|
154
|
+
}
|
|
155
|
+
const stale = opts.stalePartMs ?? 3600_000;
|
|
156
|
+
for (const n of safeDir(tmpDir)) {
|
|
157
|
+
try {
|
|
158
|
+
const f = path.join(tmpDir, n);
|
|
159
|
+
if (Date.now() - fs.statSync(f).mtimeMs >= stale) fs.rmSync(f, { force: true });
|
|
160
|
+
} catch {}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const gate = (() => {
|
|
165
|
+
let active = 0;
|
|
166
|
+
const waiting: (() => void)[] = [];
|
|
167
|
+
return async <T>(fn: () => Promise<T>): Promise<T> => {
|
|
168
|
+
if (active >= fillCap) await new Promise<void>((r) => waiting.push(r));
|
|
169
|
+
active++;
|
|
170
|
+
try {
|
|
171
|
+
return await fn();
|
|
172
|
+
} finally {
|
|
173
|
+
active--;
|
|
174
|
+
waiting.shift()?.();
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
})();
|
|
178
|
+
let inFlight = 0;
|
|
179
|
+
|
|
180
|
+
/** Remove least-recently-used unpinned entries until under the cap. */
|
|
181
|
+
function evict() {
|
|
182
|
+
while (bytes > maxBytes) {
|
|
183
|
+
let victim: [string, Entry] | null = null;
|
|
184
|
+
for (const e of index) if (e[1].pins === 0 && (!victim || e[1].tick < victim[1].tick)) victim = e;
|
|
185
|
+
if (!victim) {
|
|
186
|
+
st.overCap++;
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const [k, e] = victim;
|
|
190
|
+
index.delete(k);
|
|
191
|
+
bytes -= e.size;
|
|
192
|
+
st.evictions++;
|
|
193
|
+
const [tenant, sha] = k.split("/");
|
|
194
|
+
// Rename first: a reader that opens by path sees ENOENT (a miss), never a
|
|
195
|
+
// half-deleted file; an fd already open keeps reading its inode.
|
|
196
|
+
const gone = path.join(tmpDir, `evict-${process.pid}-${crypto.randomBytes(4).toString("hex")}`);
|
|
197
|
+
try {
|
|
198
|
+
fs.renameSync(fileOf(tenant, sha), gone);
|
|
199
|
+
fs.rmSync(gone, { force: true });
|
|
200
|
+
} catch {}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const lease = (k: string, e: Entry, file: string): CacheLease => {
|
|
205
|
+
let released = false;
|
|
206
|
+
return {
|
|
207
|
+
path: file,
|
|
208
|
+
size: e.size,
|
|
209
|
+
release() {
|
|
210
|
+
if (released) return;
|
|
211
|
+
released = true;
|
|
212
|
+
e.pins--;
|
|
213
|
+
if (index.get(k) === e && bytes > maxBytes) evict();
|
|
214
|
+
},
|
|
215
|
+
};
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
/** A hit if the file is really there at the size we recorded. */
|
|
219
|
+
function hit(k: string, tenant: string, sha: string): CacheLease | null {
|
|
220
|
+
const e = index.get(k);
|
|
221
|
+
if (!e) return null;
|
|
222
|
+
const file = fileOf(tenant, sha);
|
|
223
|
+
try {
|
|
224
|
+
if (fs.statSync(file).size !== e.size) throw new Error("size changed");
|
|
225
|
+
} catch {
|
|
226
|
+
// Removed or damaged behind our back (another process, a tmp cleaner).
|
|
227
|
+
if (e.pins === 0) {
|
|
228
|
+
index.delete(k);
|
|
229
|
+
bytes -= e.size;
|
|
230
|
+
}
|
|
231
|
+
return null;
|
|
232
|
+
}
|
|
233
|
+
e.pins++;
|
|
234
|
+
e.tick = ++tick;
|
|
235
|
+
const now = new Date();
|
|
236
|
+
fs.utimes(file, now, now, () => {}); // keeps the order across a restart
|
|
237
|
+
return lease(k, e, file);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function startFill(k: string, tenant: string, sha: string, f: Fill): Promise<void> {
|
|
241
|
+
return gate(async () => {
|
|
242
|
+
inFlight++;
|
|
243
|
+
// downloadToFile writes `<dl>.part` and renames it to `dl` once the hash
|
|
244
|
+
// matched; `dl` is then renamed into the cache. Both names are removed
|
|
245
|
+
// below whatever happens: a fill that failed (a final error, retries
|
|
246
|
+
// spent) would otherwise leave its bytes in tmp/, outside the count
|
|
247
|
+
// that maxBytes holds, until the next start-up sweep.
|
|
248
|
+
const dl = path.join(tmpDir, `${tenant}-${sha}.${process.pid}.dl`);
|
|
249
|
+
try {
|
|
250
|
+
const final = fileOf(tenant, sha);
|
|
251
|
+
fs.mkdirSync(path.dirname(final), { recursive: true });
|
|
252
|
+
const { size } = await downloadToFile(store, blobObjectKey(tenant, sha), dl, { sha256: sha });
|
|
253
|
+
fs.renameSync(dl, final);
|
|
254
|
+
const e: Entry = { size, pins: f.waiters, tick: ++tick };
|
|
255
|
+
const old = index.get(k);
|
|
256
|
+
if (old) bytes -= old.size; // another process won the rename; same bytes
|
|
257
|
+
index.set(k, e);
|
|
258
|
+
bytes += size;
|
|
259
|
+
st.peakBytes = Math.max(st.peakBytes, bytes);
|
|
260
|
+
f.inserted = true;
|
|
261
|
+
st.fills++;
|
|
262
|
+
evict(); // the new entry is pinned by its waiters; others may go
|
|
263
|
+
} finally {
|
|
264
|
+
inFlight--;
|
|
265
|
+
fs.rmSync(`${dl}.part`, { force: true });
|
|
266
|
+
fs.rmSync(dl, { force: true });
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
async function acquire(tenant: string, sha: string, o: { signal?: AbortSignal } = {}): Promise<CacheLease> {
|
|
272
|
+
const k = keyOf(tenant, sha);
|
|
273
|
+
if (o.signal?.aborted) throw o.signal.reason ?? new Error("cancelled");
|
|
274
|
+
const got = hit(k, tenant, sha);
|
|
275
|
+
if (got) {
|
|
276
|
+
st.hits++;
|
|
277
|
+
return got;
|
|
278
|
+
}
|
|
279
|
+
let f = fills.get(k);
|
|
280
|
+
if (f) st.joined++;
|
|
281
|
+
else {
|
|
282
|
+
st.misses++;
|
|
283
|
+
const fill: Fill = { waiters: 0, inserted: false, promise: Promise.resolve() };
|
|
284
|
+
fills.set(k, fill);
|
|
285
|
+
fill.promise = startFill(k, tenant, sha, fill).finally(() => {
|
|
286
|
+
if (fills.get(k) === fill) fills.delete(k);
|
|
287
|
+
});
|
|
288
|
+
// A failed fill rejects every waiter; nothing else holds the promise.
|
|
289
|
+
fill.promise.catch(() => {});
|
|
290
|
+
f = fill;
|
|
291
|
+
}
|
|
292
|
+
f.waiters++;
|
|
293
|
+
const mine = f;
|
|
294
|
+
let abort: (() => void) | undefined;
|
|
295
|
+
try {
|
|
296
|
+
await Promise.race([
|
|
297
|
+
mine.promise,
|
|
298
|
+
new Promise<never>((_, reject) => {
|
|
299
|
+
if (!o.signal) return;
|
|
300
|
+
abort = () => reject(o.signal!.reason ?? new Error("cancelled"));
|
|
301
|
+
o.signal.addEventListener("abort", abort, { once: true });
|
|
302
|
+
}),
|
|
303
|
+
]);
|
|
304
|
+
} catch (err) {
|
|
305
|
+
// Leaving: if the entry was already pinned for us, give that pin back.
|
|
306
|
+
if (mine.inserted) {
|
|
307
|
+
const e = index.get(k);
|
|
308
|
+
if (e) {
|
|
309
|
+
e.pins--;
|
|
310
|
+
if (bytes > maxBytes) evict();
|
|
311
|
+
}
|
|
312
|
+
} else mine.waiters--;
|
|
313
|
+
throw err;
|
|
314
|
+
} finally {
|
|
315
|
+
if (abort) o.signal!.removeEventListener("abort", abort);
|
|
316
|
+
}
|
|
317
|
+
const e = index.get(k)!;
|
|
318
|
+
e.tick = ++tick;
|
|
319
|
+
return lease(k, e, fileOf(tenant, sha));
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
return {
|
|
323
|
+
acquire,
|
|
324
|
+
async stream(tenant, sha, o = {}) {
|
|
325
|
+
const l = await acquire(tenant, sha, o);
|
|
326
|
+
try {
|
|
327
|
+
const rs = fs.createReadStream(l.path, o.range ? { start: o.range.start, end: o.range.end } : {});
|
|
328
|
+
rs.once("close", () => l.release());
|
|
329
|
+
return rs;
|
|
330
|
+
} catch (err) {
|
|
331
|
+
l.release();
|
|
332
|
+
throw err;
|
|
333
|
+
}
|
|
334
|
+
},
|
|
335
|
+
async withBlob(tenant, sha, fn, o = {}) {
|
|
336
|
+
const l = await acquire(tenant, sha, o);
|
|
337
|
+
try {
|
|
338
|
+
return await fn(l.path, l.size);
|
|
339
|
+
} finally {
|
|
340
|
+
l.release();
|
|
341
|
+
}
|
|
342
|
+
},
|
|
343
|
+
stats(): CacheStats {
|
|
344
|
+
let pinned = 0;
|
|
345
|
+
for (const e of index.values()) if (e.pins > 0) pinned++;
|
|
346
|
+
return { entries: index.size, bytes, maxBytes, pinned, ...st, fillsInFlight: inFlight };
|
|
347
|
+
},
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function safeDir(d: string): string[] {
|
|
352
|
+
try {
|
|
353
|
+
return fs.readdirSync(d);
|
|
354
|
+
} catch {
|
|
355
|
+
return [];
|
|
356
|
+
}
|
|
357
|
+
}
|
package/src/blob-pins.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
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
|
+
|
|
36
|
+
import type { ManifestId } from "./manifest.ts";
|
|
37
|
+
|
|
38
|
+
export type PinKind = "blob" | "manifest";
|
|
39
|
+
export type HolderKind = "publish" | "run" | "revision";
|
|
40
|
+
|
|
41
|
+
export interface PinHolder {
|
|
42
|
+
kind: HolderKind;
|
|
43
|
+
/** publish: the op id. run: the run id. revision: the revision id. */
|
|
44
|
+
id: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface BlobPins {
|
|
48
|
+
/** Pin blobs (by sha) for a holder. Idempotent: a repeat extends the lease. */
|
|
49
|
+
pinBlobs(tenant: string, shas: readonly string[], holder: PinHolder, opts?: { ttlMs?: number }): Promise<void>;
|
|
50
|
+
/** Pin manifests the same way. */
|
|
51
|
+
pinManifests(tenant: string, ids: readonly ManifestId[], holder: PinHolder, opts?: { ttlMs?: number }): Promise<void>;
|
|
52
|
+
/** Drop every pin a holder has. Returns how many went. */
|
|
53
|
+
release(tenant: string, holder: PinHolder): Promise<number>;
|
|
54
|
+
/** Push a holder's leases out by ttlMs from now (a running run's heartbeat).
|
|
55
|
+
* Pins with no lease are left alone. Returns how many were renewed. */
|
|
56
|
+
renew(tenant: string, holder: PinHolder, ttlMs: number): Promise<number>;
|
|
57
|
+
/** Is anything holding this object right now (a live, unexpired pin)? */
|
|
58
|
+
isPinned(tenant: string, kind: PinKind, ref: string): Promise<boolean>;
|
|
59
|
+
/** Is a live pin on this object held by something OTHER than a revision (a
|
|
60
|
+
* run reading it, a publish in flight)? Retention asks this before it lets
|
|
61
|
+
* a revision go: the revision's own pin is the one it is about to release. */
|
|
62
|
+
isPinnedBeyondRevisions(tenant: string, kind: PinKind, ref: string): Promise<boolean>;
|
|
63
|
+
/** Everything of this account a live (unexpired) pin names, any holder: the
|
|
64
|
+
* sweeper's roots besides the revisions. */
|
|
65
|
+
live(tenant: string): Promise<{ manifests: string[]; blobs: string[] }>;
|
|
66
|
+
/** The sweeper's only way to delete: runs `del` only if no live pin names
|
|
67
|
+
* the object, with pinning of that object held off for the duration.
|
|
68
|
+
* Returns whether `del` ran. */
|
|
69
|
+
guardDelete(tenant: string, kind: PinKind, ref: string, del: () => Promise<void>): Promise<boolean>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** No database, no sweeper: nothing to agree with. */
|
|
73
|
+
export const noPins: BlobPins = {
|
|
74
|
+
async pinBlobs() {},
|
|
75
|
+
async pinManifests() {},
|
|
76
|
+
async release() {
|
|
77
|
+
return 0;
|
|
78
|
+
},
|
|
79
|
+
async renew() {
|
|
80
|
+
return 0;
|
|
81
|
+
},
|
|
82
|
+
async isPinned() {
|
|
83
|
+
return false;
|
|
84
|
+
},
|
|
85
|
+
async isPinnedBeyondRevisions() {
|
|
86
|
+
return false;
|
|
87
|
+
},
|
|
88
|
+
async live() {
|
|
89
|
+
return { manifests: [], blobs: [] };
|
|
90
|
+
},
|
|
91
|
+
async guardDelete(_t, _k, _r, del) {
|
|
92
|
+
await del();
|
|
93
|
+
return true;
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/** How long a publish's blob pins live without a renewal: far longer than an
|
|
98
|
+
* upload, short enough that a crashed publisher frees its blobs the same day. */
|
|
99
|
+
export const PUBLISH_PIN_TTL_MS = 15 * 60_000;
|