@foldrun/core 17.3.0 → 17.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/src/approvals.js +3 -3
  2. package/dist/src/blob-cache.d.ts +58 -0
  3. package/dist/src/blob-cache.js +309 -0
  4. package/dist/src/blob-pins.d.ts +44 -0
  5. package/dist/src/blob-pins.js +61 -0
  6. package/dist/src/blob-store.d.ts +47 -0
  7. package/dist/src/blob-store.js +357 -0
  8. package/dist/src/blob-sweeper.d.ts +70 -0
  9. package/dist/src/blob-sweeper.js +254 -0
  10. package/dist/src/blob-types.d.ts +145 -0
  11. package/dist/src/blob-types.js +115 -0
  12. package/dist/src/evals.js +1 -1
  13. package/dist/src/history.d.ts +86 -9
  14. package/dist/src/history.js +132 -16
  15. package/dist/src/journal-store.d.ts +58 -0
  16. package/dist/src/journal-store.js +117 -0
  17. package/dist/src/manifest.d.ts +92 -0
  18. package/dist/src/manifest.js +239 -0
  19. package/dist/src/ops-log.js +26 -3
  20. package/dist/src/platform.d.ts +7 -0
  21. package/dist/src/platform.js +1 -0
  22. package/dist/src/publish.d.ts +134 -0
  23. package/dist/src/publish.js +434 -0
  24. package/dist/src/records.d.ts +72 -0
  25. package/dist/src/records.js +24 -0
  26. package/dist/src/revision-store.d.ts +161 -0
  27. package/dist/src/revision-store.js +378 -0
  28. package/dist/src/run-container.d.ts +20 -0
  29. package/dist/src/run-container.js +61 -0
  30. package/dist/src/runner.js +1 -1
  31. package/dist/src/s3-blob-store.d.ts +29 -0
  32. package/dist/src/s3-blob-store.js +458 -0
  33. package/dist/src/state-retention.d.ts +15 -0
  34. package/dist/src/state-retention.js +65 -0
  35. package/dist/src/storage.d.ts +29 -1
  36. package/dist/src/storage.js +331 -81
  37. package/dist/src/store.d.ts +41 -0
  38. package/dist/src/store.js +188 -5
  39. package/dist/src/trigger-log.js +17 -0
  40. package/dist/src/workspace-revisions.d.ts +259 -0
  41. package/dist/src/workspace-revisions.js +1274 -0
  42. package/package.json +1 -1
  43. package/src/approvals.ts +3 -3
  44. package/src/blob-cache.ts +354 -0
  45. package/src/blob-pins.ts +99 -0
  46. package/src/blob-store.ts +385 -0
  47. package/src/blob-sweeper.ts +308 -0
  48. package/src/blob-types.ts +216 -0
  49. package/src/evals.ts +1 -1
  50. package/src/history.ts +182 -16
  51. package/src/journal-store.ts +152 -0
  52. package/src/manifest.ts +274 -0
  53. package/src/ops-log.ts +25 -3
  54. package/src/platform.ts +8 -0
  55. package/src/publish.ts +520 -0
  56. package/src/records.ts +105 -0
  57. package/src/revision-store.ts +513 -0
  58. package/src/run-container.ts +62 -0
  59. package/src/runner.ts +1 -1
  60. package/src/s3-blob-store.ts +489 -0
  61. package/src/state-retention.ts +83 -0
  62. package/src/storage.ts +335 -81
  63. package/src/store.ts +178 -5
  64. package/src/trigger-log.ts +15 -0
  65. package/src/workspace-revisions.ts +1324 -0
@@ -0,0 +1,357 @@
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
+ import fs from "node:fs";
29
+ import path from "node:path";
30
+ import crypto from "node:crypto";
31
+ import { Readable } from "node:stream";
32
+ import { pipeline } from "node:stream/promises";
33
+ import { dataRoot } from "./paths.js";
34
+ import { s3Config } from "./storage.js";
35
+ import { s3BlobStore } from "./s3-blob-store.js";
36
+ import { BlobNotFound, BlobSourceError, BlobTransientError, assertKey, hashRange, } from "./blob-types.js";
37
+ export * from "./blob-types.js";
38
+ export { s3BlobStore };
39
+ // ---------- fs driver ----------
40
+ export function fsBlobStore(root = path.join(dataRoot(), ".objects")) {
41
+ const at = (key) => path.join(root, ...assertKey(key).split("/"));
42
+ const tmpName = (target) => `${target}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`;
43
+ return {
44
+ kind: "fs",
45
+ async putSourceIfAbsent(key, source, opts = {}) {
46
+ const target = at(key);
47
+ fs.mkdirSync(path.dirname(target), { recursive: true });
48
+ if (fs.existsSync(target))
49
+ return { created: false };
50
+ const tmp = tmpName(target);
51
+ try {
52
+ const sha = crypto.createHash("sha256");
53
+ const out = fs.createWriteStream(tmp);
54
+ await pipeline(Readable.from(source.read(0, source.size, opts.signal), { objectMode: false }), async function* (chunks) {
55
+ for await (const c of chunks) {
56
+ sha.update(c);
57
+ yield c;
58
+ }
59
+ }, out);
60
+ if (opts.sha256 && sha.digest("hex") !== opts.sha256)
61
+ throw new BlobSourceError(`the bytes for ${key} do not hash to ${opts.sha256}`);
62
+ try {
63
+ fs.linkSync(tmp, target);
64
+ return { created: true };
65
+ }
66
+ catch (err) {
67
+ if (err.code === "EEXIST")
68
+ return { created: false };
69
+ throw err;
70
+ }
71
+ }
72
+ finally {
73
+ fs.rmSync(tmp, { force: true });
74
+ }
75
+ },
76
+ async abortStaleUploads({ olderThanMs, prefix = "" }) {
77
+ // The fs driver's "incomplete uploads" are temp files a dead writer left.
78
+ let n = 0;
79
+ const walk = (dir) => {
80
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
81
+ const f = path.join(dir, e.name);
82
+ if (e.isDirectory())
83
+ walk(f);
84
+ else if (e.name.endsWith(".tmp") && path.relative(root, f).startsWith(prefix) && Date.now() - fs.statSync(f).mtimeMs >= olderThanMs) {
85
+ fs.rmSync(f, { force: true });
86
+ n++;
87
+ }
88
+ }
89
+ };
90
+ if (fs.existsSync(root))
91
+ walk(root);
92
+ return n;
93
+ },
94
+ async putIfAbsent(key, body) {
95
+ const target = at(key);
96
+ fs.mkdirSync(path.dirname(target), { recursive: true });
97
+ if (fs.existsSync(target))
98
+ return { created: false };
99
+ const tmp = `${target}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`;
100
+ fs.writeFileSync(tmp, body);
101
+ try {
102
+ // link() refuses an existing target: the atomic "create if absent".
103
+ fs.linkSync(tmp, target);
104
+ return { created: true };
105
+ }
106
+ catch (err) {
107
+ if (err.code === "EEXIST")
108
+ return { created: false };
109
+ throw err;
110
+ }
111
+ finally {
112
+ fs.rmSync(tmp, { force: true });
113
+ }
114
+ },
115
+ async get(key, opts = {}) {
116
+ const target = at(key);
117
+ if (!fs.existsSync(target))
118
+ throw new BlobNotFound(key);
119
+ const stream = fs.createReadStream(target, opts.range ? { start: opts.range.start, end: opts.range.end } : {});
120
+ return Readable.toWeb(stream);
121
+ },
122
+ async head(key) {
123
+ const target = at(key); // a bad key throws; only a missing file is null
124
+ try {
125
+ const st = fs.statSync(target);
126
+ return st.isFile() ? { size: st.size, modifiedAt: st.mtime } : null;
127
+ }
128
+ catch {
129
+ return null;
130
+ }
131
+ },
132
+ async delete(key) {
133
+ fs.rmSync(at(key), { force: true });
134
+ },
135
+ async purgeTenant(tenant) {
136
+ fs.rmSync(path.dirname(at(`t/${tenant}/x`)), { recursive: true, force: true });
137
+ },
138
+ async *list(prefix) {
139
+ const base = at(`${prefix.replace(/\/+$/, "")}/x`);
140
+ const dir = path.dirname(base);
141
+ const walk = function* (d, rel) {
142
+ let names = [];
143
+ try {
144
+ names = fs.readdirSync(d, { withFileTypes: true });
145
+ }
146
+ catch {
147
+ return;
148
+ }
149
+ for (const e of names) {
150
+ if (e.isDirectory())
151
+ yield* walk(path.join(d, e.name), `${rel}${e.name}/`);
152
+ else if (e.isFile() && !e.name.endsWith(".tmp")) {
153
+ try {
154
+ const st = fs.statSync(path.join(d, e.name));
155
+ yield { key: `${rel}${e.name}`, size: st.size, modifiedAt: st.mtime };
156
+ }
157
+ catch {
158
+ // gone meanwhile
159
+ }
160
+ }
161
+ }
162
+ };
163
+ yield* walk(dir, `${prefix.replace(/\/+$/, "")}/`);
164
+ },
165
+ async tenants() {
166
+ try {
167
+ return fs.readdirSync(path.join(root, "t"), { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
168
+ }
169
+ catch {
170
+ return [];
171
+ }
172
+ },
173
+ };
174
+ }
175
+ // ---------- download to a file ----------
176
+ /**
177
+ * Fetch an object into a file, resuming. The bytes land in `<dest>.part`;
178
+ * a connection cut mid-body (a transient error) is picked up again with a
179
+ * Range from where the file ends, and so is a `.part` a dead process left.
180
+ * The whole file is hashed against `sha256` (when given) before it is renamed
181
+ * into place; a mismatch discards it and throws BlobSourceError.
182
+ */
183
+ export async function downloadToFile(store, key, dest, opts = {}) {
184
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
185
+ const part = `${dest}.part`;
186
+ const size = (await store.head(key, { signal: opts.signal }))?.size;
187
+ if (size === undefined)
188
+ throw new BlobNotFound(key);
189
+ const max = opts.attempts ?? 5;
190
+ for (let attempt = 0;; attempt++) {
191
+ let have = fs.existsSync(part) ? fs.statSync(part).size : 0;
192
+ if (have > size) {
193
+ fs.rmSync(part, { force: true });
194
+ have = 0;
195
+ }
196
+ if (have < size) {
197
+ try {
198
+ const body = await store.get(key, { signal: opts.signal, ...(have > 0 ? { range: { start: have, end: size - 1 } } : {}) });
199
+ await pipeline(Readable.fromWeb(body), fs.createWriteStream(part, { flags: have > 0 ? "a" : "w" }));
200
+ }
201
+ catch (err) {
202
+ const transient = err instanceof BlobTransientError || err?.cause instanceof BlobTransientError;
203
+ if (!transient || attempt + 1 >= max || opts.signal?.aborted)
204
+ throw err;
205
+ continue;
206
+ }
207
+ }
208
+ if (fs.statSync(part).size !== size) {
209
+ if (attempt + 1 >= max)
210
+ throw new BlobTransientError(`download of ${key} stopped short`);
211
+ continue;
212
+ }
213
+ break;
214
+ }
215
+ if (opts.sha256) {
216
+ const h = await hashRange(fileRange(part), 0, size, opts.signal);
217
+ if (h.sha256 !== opts.sha256) {
218
+ fs.rmSync(part, { force: true });
219
+ throw new BlobSourceError(`${key} does not hash to ${opts.sha256}`);
220
+ }
221
+ }
222
+ fs.renameSync(part, dest);
223
+ return { size };
224
+ }
225
+ const fileRange = (file) => ({
226
+ size: fs.statSync(file).size,
227
+ async *read(start, end) {
228
+ if (end > start)
229
+ yield* fs.createReadStream(file, { start, end: end - 1 });
230
+ },
231
+ });
232
+ // ---------- the store in force ----------
233
+ /** s3 when FOLDRUN_STORAGE_DRIVER=s3 and it is fully configured, else fs.
234
+ * (The same fall-back rule as storage.ts's driverFor.) */
235
+ export function blobStore() {
236
+ if (process.env.FOLDRUN_STORAGE_DRIVER === "s3") {
237
+ const cfg = s3Config();
238
+ if (cfg)
239
+ return bounded(s3BlobStore(cfg));
240
+ }
241
+ return bounded(fsBlobStore());
242
+ }
243
+ export const DEFAULT_LIMITS = { deadlineMs: 30_000, retries: 3, concurrency: 8, backoffMs: 200, minBytesPerSec: 1024 * 1024 };
244
+ export function limitsFromEnv(env = process.env) {
245
+ const n = (v, d) => (v !== undefined && /^\d+$/.test(v) ? Number(v) : d);
246
+ return {
247
+ deadlineMs: n(env.FOLDRUN_BLOB_DEADLINE_MS, DEFAULT_LIMITS.deadlineMs),
248
+ retries: n(env.FOLDRUN_BLOB_RETRIES, DEFAULT_LIMITS.retries),
249
+ concurrency: Math.max(1, n(env.FOLDRUN_BLOB_CONCURRENCY, DEFAULT_LIMITS.concurrency)),
250
+ backoffMs: DEFAULT_LIMITS.backoffMs,
251
+ minBytesPerSec: Math.max(1, n(env.FOLDRUN_BLOB_MIN_BYTES_PER_SEC, DEFAULT_LIMITS.minBytesPerSec)),
252
+ };
253
+ }
254
+ class Semaphore {
255
+ waiting = [];
256
+ active = 0;
257
+ max;
258
+ constructor(max) {
259
+ this.max = max;
260
+ }
261
+ async run(fn) {
262
+ if (this.active >= this.max)
263
+ await new Promise((r) => this.waiting.push(r));
264
+ this.active++;
265
+ try {
266
+ return await fn();
267
+ }
268
+ finally {
269
+ this.active--;
270
+ this.waiting.shift()?.();
271
+ }
272
+ }
273
+ }
274
+ const isTransient = (err) => err instanceof BlobTransientError || ["ECONNRESET", "ETIMEDOUT", "EAGAIN", "EBUSY", "EMFILE"].includes(err?.code ?? "");
275
+ /**
276
+ * Wrap a store so every call has a deadline (an AbortSignal handed down; the
277
+ * call fails with BlobTransientError if it passes), is retried on transient
278
+ * failure within a budget, and counts against a concurrency cap.
279
+ *
280
+ * A `get` is deadline-bound only until the stream starts: a long download is
281
+ * the caller's to bound. A not-found, a 4xx and a bad key are never retried.
282
+ */
283
+ export function bounded(inner, limits = {}) {
284
+ const L = { ...limitsFromEnv(), ...limits };
285
+ const gate = new Semaphore(L.concurrency);
286
+ /** The caller's signal and this attempt's deadline, either of which ends it. */
287
+ const both = (caller, ms) => {
288
+ const deadline = AbortSignal.timeout(ms);
289
+ return caller ? AbortSignal.any([caller, deadline]) : deadline;
290
+ };
291
+ async function call(what, caller, fn, bytes = 0) {
292
+ const ms = L.deadlineMs + Math.ceil((bytes / L.minBytesPerSec) * 1000);
293
+ return gate.run(async () => {
294
+ let attempt = 0;
295
+ for (;;) {
296
+ if (caller?.aborted)
297
+ throw caller.reason ?? new Error(`${what}: cancelled`);
298
+ const signal = both(caller, ms);
299
+ try {
300
+ return await Promise.race([
301
+ fn(signal),
302
+ new Promise((_, reject) => signal.addEventListener("abort", () => reject(caller?.aborted ? (caller.reason ?? new Error(`${what}: cancelled`)) : new BlobTransientError(`${what}: no answer within ${ms}ms`)), { once: true })),
303
+ ]);
304
+ }
305
+ catch (err) {
306
+ if (caller?.aborted || !isTransient(err) || attempt >= L.retries)
307
+ throw err;
308
+ attempt++;
309
+ await new Promise((r) => setTimeout(r, L.backoffMs * 2 ** (attempt - 1) * (0.5 + Math.random())));
310
+ }
311
+ }
312
+ });
313
+ }
314
+ return {
315
+ ...inner,
316
+ kind: inner.kind,
317
+ putIfAbsent: (key, body, opts) => call("put", opts?.signal, (signal) => inner.putIfAbsent(key, body, { ...opts, signal }), body.byteLength),
318
+ // The deadline covers getting the stream going, not draining it: the
319
+ // timer is cleared once the object starts to arrive. The caller's signal
320
+ // stays attached to the stream, so cancelling still stops the download.
321
+ get: (key, opts) => call("get", opts?.signal, async () => {
322
+ const ctl = new AbortController();
323
+ const timer = setTimeout(() => ctl.abort(), L.deadlineMs);
324
+ const onCaller = () => ctl.abort(opts?.signal?.reason);
325
+ opts?.signal?.addEventListener("abort", onCaller, { once: true });
326
+ try {
327
+ return await inner.get(key, { ...opts, signal: ctl.signal });
328
+ }
329
+ finally {
330
+ clearTimeout(timer);
331
+ }
332
+ }),
333
+ // A streamed put has no fixed deadline (its length decides), so it gets the
334
+ // retry budget and the concurrency cap, and the s3 driver's own per-request
335
+ // deadlines. Cancelling is the caller's signal.
336
+ putSourceIfAbsent: (key, source, opts) => gate.run(async () => {
337
+ for (let attempt = 0;; attempt++) {
338
+ if (opts?.signal?.aborted)
339
+ throw opts.signal.reason ?? new Error("put: cancelled");
340
+ try {
341
+ return await inner.putSourceIfAbsent(key, source, opts);
342
+ }
343
+ catch (err) {
344
+ if (opts?.signal?.aborted || !isTransient(err) || attempt >= L.retries)
345
+ throw err;
346
+ await new Promise((r) => setTimeout(r, L.backoffMs * 2 ** attempt * (0.5 + Math.random())));
347
+ }
348
+ }
349
+ }),
350
+ abortStaleUploads: (o) => (inner.abortStaleUploads ? inner.abortStaleUploads(o) : Promise.resolve(0)),
351
+ head: (key, opts) => call("head", opts?.signal, (signal) => inner.head(key, { signal })),
352
+ delete: (key, opts) => call("delete", opts?.signal, (signal) => (inner.delete ? inner.delete(key, { signal }) : Promise.reject(new Error("this store cannot delete")))),
353
+ ...(inner.purgeTenant ? { purgeTenant: (tenant) => inner.purgeTenant(tenant) } : {}),
354
+ ...(inner.list ? { list: (prefix, o) => inner.list(prefix, o) } : {}),
355
+ ...(inner.tenants ? { tenants: (o) => inner.tenants(o) } : {}),
356
+ };
357
+ }
@@ -0,0 +1,70 @@
1
+ import type { BlobStore, BlobSweeper } from "./blob-store.ts";
2
+ import type { BlobPins } from "./blob-pins.ts";
3
+ import type { RevisionStore } from "./revision-store.ts";
4
+ export type MarkKind = "blob" | "manifest" | "workspace";
5
+ export interface Mark {
6
+ firstSeen: Date;
7
+ size: number;
8
+ }
9
+ /** Where "first seen unreferenced" is kept (a table in the platform). */
10
+ export interface SweepMarks {
11
+ /** The database's clock: every record and comparison uses it, so pods agree. */
12
+ now(): Promise<Date>;
13
+ load(tenant: string, kind: MarkKind): Promise<Map<string, Mark>>;
14
+ /** Record refs not yet recorded (an existing record keeps its first time). */
15
+ put(tenant: string, kind: MarkKind, entries: {
16
+ ref: string;
17
+ size: number;
18
+ }[], at: Date): Promise<void>;
19
+ clear(tenant: string, kind: MarkKind, refs: string[]): Promise<void>;
20
+ /** When the last run (real or dry) finished, for the schedule. */
21
+ lastRunAt(): Promise<Date | null>;
22
+ recordRun(report: SweepReport): Promise<void>;
23
+ }
24
+ export interface SweepOptions {
25
+ dryRun: boolean;
26
+ /** Unreferenced for this long before deletion: the restore-point window. */
27
+ delayMs: number;
28
+ /** Never touch an object younger than this. Default one hour. */
29
+ minAgeMs?: number;
30
+ /** Delete at most this many objects in one run, all accounts together. */
31
+ maxDeletes: number;
32
+ /** Only these accounts (tests, an operator). */
33
+ tenants?: string[];
34
+ /** Go ahead even when the database holds no revision (default: refuse). */
35
+ allowEmpty?: boolean;
36
+ }
37
+ export interface SweepReport {
38
+ dryRun: boolean;
39
+ tenants: number;
40
+ scanned: number;
41
+ scannedBytes: number;
42
+ live: number;
43
+ /** Seen unreferenced for the first time in this run. */
44
+ marked: number;
45
+ markedBytes: number;
46
+ /** Unreferenced, but not for long enough yet. */
47
+ waiting: number;
48
+ deleted: number;
49
+ deletedBytes: number;
50
+ /** A dry run: due now, and what a real run would delete. */
51
+ wouldDelete: number;
52
+ wouldDeleteBytes: number;
53
+ /** Would have been deleted (dry run), or were due but a pin or a new revision held them. */
54
+ skippedHeld: number;
55
+ /** Not an object the sweeper owns (left alone). */
56
+ foreign: number;
57
+ errors: number;
58
+ refused?: string;
59
+ }
60
+ export interface SweepDeps {
61
+ blobs: BlobStore & BlobSweeper;
62
+ revisions: RevisionStore;
63
+ pins?: BlobPins;
64
+ }
65
+ export declare function sweepBlobs(deps: SweepDeps, marks: SweepMarks, opts: SweepOptions): Promise<SweepReport>;
66
+ /** For tests and a host without a database table (the clock is injectable). */
67
+ export declare function memorySweepMarks(clock?: () => Date): SweepMarks & {
68
+ runs: SweepReport[];
69
+ table: Map<string, Mark>;
70
+ };
@@ -0,0 +1,254 @@
1
+ // The blob sweeper (FOL-126): mark and sweep, with a delay.
2
+ //
3
+ // Revisions, manifests and blobs only ever accumulate: a delete, a rename, a
4
+ // state prune and a deleted account all release PINS and ROWS and delete no
5
+ // object. This is what deletes them, and it is built so that deleting the wrong
6
+ // thing is the hard direction.
7
+ //
8
+ // MARK per account: the roots are every manifest a retained revision names
9
+ // (any head, any workspace), every manifest and blob a live pin names
10
+ // (a run's pinned base, a publish in flight, a revision's own pin), and
11
+ // the blobs of all those manifests. Everything under `t/<tenant>/` that
12
+ // is not reachable from them is a candidate. An object the sweeper does
13
+ // not recognise by its key is left alone and counted.
14
+ // DELAY a candidate is only RECORDED the first time it is seen unreferenced
15
+ // (`firstSeen`, the database clock). It is deleted only once it has been
16
+ // unreferenced continuously for `delayMs` — which is also the window a
17
+ // database can be restored to: restoring to a point inside it brings
18
+ // back revision rows whose objects are still there. Referenced again
19
+ // before then, the record is cleared. Objects younger than `minAgeMs`
20
+ // are never touched (a publish uploads before it commits).
21
+ // SWEEP each delete goes through `pins.guardDelete` (the pin lock for that
22
+ // object) and, INSIDE it, looks once more at what was committed since
23
+ // the mark began, because a publish that committed and released its pin
24
+ // after the mark would otherwise be invisible to both checks.
25
+ //
26
+ // Refusals (nothing deleted, said in the report): the store cannot list; the
27
+ // database holds no revision at all while the bucket holds objects (a wiped or
28
+ // not-yet-restored database); a retained manifest cannot be read (its blobs are
29
+ // unknown). `dryRun` marks and counts nothing it would not report: it writes no
30
+ // records and deletes nothing.
31
+ //
32
+ // An account that was deleted needs no special case: its rows and pins are gone,
33
+ // so everything under its prefix is unreferenced, waits the delay, and goes.
34
+ import { loadManifest, BlobMissing } from "./publish.js";
35
+ import { opsError, opsLog } from "./ops-log.js";
36
+ const TENANT = /^[A-Za-z0-9][A-Za-z0-9._@-]{0,120}$/;
37
+ const HEX = /^[0-9a-f]{64}$/;
38
+ const empty = (dryRun) => ({ dryRun, tenants: 0, scanned: 0, scannedBytes: 0, live: 0, marked: 0, markedBytes: 0, waiting: 0, deleted: 0, deletedBytes: 0, wouldDelete: 0, wouldDeleteBytes: 0, skippedHeld: 0, foreign: 0, errors: 0 });
39
+ export async function sweepBlobs(deps, marks, opts) {
40
+ const rep = empty(opts.dryRun);
41
+ const { blobs } = deps;
42
+ if (!blobs.list || !blobs.tenants || !blobs.delete)
43
+ return refuse(rep, "the object store cannot list and delete");
44
+ let tenants;
45
+ try {
46
+ tenants = opts.tenants ?? (await blobs.tenants());
47
+ }
48
+ catch (err) {
49
+ opsError("blobs.sweep_failed", err, { stage: "tenants" });
50
+ rep.errors++;
51
+ return refuse(rep, "the object store could not be listed");
52
+ }
53
+ if (!opts.allowEmpty && tenants.length && !(await deps.revisions.anyRevisions())) {
54
+ return refuse(rep, "the database holds no revision but the store holds objects: not deleting on that evidence");
55
+ }
56
+ let budget = Math.max(0, opts.maxDeletes);
57
+ for (const tenant of tenants) {
58
+ if (!TENANT.test(tenant)) {
59
+ rep.foreign++;
60
+ continue;
61
+ }
62
+ rep.tenants++;
63
+ try {
64
+ budget -= await sweepTenant(deps, marks, opts, tenant, rep, budget);
65
+ }
66
+ catch (err) {
67
+ rep.errors++;
68
+ opsError("blobs.sweep_failed", err, { tenant });
69
+ }
70
+ }
71
+ opsLog("info", "blobs.sweep", { ...rep });
72
+ await marks.recordRun(rep).catch((err) => opsError("blobs.sweep_not_recorded", err, {}));
73
+ return rep;
74
+ }
75
+ function refuse(rep, why) {
76
+ rep.refused = why;
77
+ opsLog("warn", "blobs.sweep_refused", { reason: why, dryRun: rep.dryRun });
78
+ return rep;
79
+ }
80
+ async function sweepTenant(deps, marks, opts, tenant, rep, budget) {
81
+ const { blobs, revisions, pins } = deps;
82
+ const started = await marks.now();
83
+ // ---- mark: the roots
84
+ const retained = new Set(await revisions.manifestIds(tenant));
85
+ const pinned = pins ? await pins.live(tenant) : { manifests: [], blobs: [] };
86
+ const liveBlobs = new Set(pinned.blobs);
87
+ const liveManifests = new Set([...retained, ...pinned.manifests]);
88
+ for (const id of liveManifests) {
89
+ try {
90
+ const m = await loadManifest({ blobs, revisions }, tenant, id);
91
+ for (const f of Object.values(m.files))
92
+ liveBlobs.add(f.sha);
93
+ }
94
+ catch (err) {
95
+ // A manifest a revision names that cannot be read means its blobs are
96
+ // unknown: nothing of this account may be deleted this run. A pinned
97
+ // manifest that is not there yet (a publish still uploading) is fine.
98
+ if (err instanceof BlobMissing && !retained.has(id))
99
+ continue;
100
+ throw err;
101
+ }
102
+ }
103
+ const candidates = new Map(); // `${kind}:${ref}`
104
+ const prefix = `t/${tenant}/`;
105
+ let live = 0;
106
+ for await (const o of blobs.list(prefix)) {
107
+ rep.scanned++;
108
+ rep.scannedBytes += o.size;
109
+ const rest = o.key.startsWith(prefix) ? o.key.slice(prefix.length) : "";
110
+ let kind = null;
111
+ let ref = "";
112
+ if (rest.startsWith("blobs/") && HEX.test(rest.slice(6)))
113
+ (kind = "blob"), (ref = rest.slice(6));
114
+ else if (rest.startsWith("manifests/") && rest.endsWith(".json") && HEX.test(rest.slice(10, -5)))
115
+ (kind = "manifest"), (ref = rest.slice(10, -5));
116
+ if (!kind) {
117
+ rep.foreign++;
118
+ continue;
119
+ }
120
+ if ((kind === "blob" ? liveBlobs : liveManifests).has(ref)) {
121
+ live++;
122
+ continue;
123
+ }
124
+ candidates.set(`${kind}:${ref}`, { key: o.key, kind, ref, size: o.size, modifiedAt: o.modifiedAt });
125
+ }
126
+ rep.live += live;
127
+ // ---- delay: first seen, and how long ago
128
+ const minAge = opts.minAgeMs ?? 3_600_000;
129
+ const have = { blob: await marks.load(tenant, "blob"), manifest: await marks.load(tenant, "manifest") };
130
+ const stale = { blob: [], manifest: [] };
131
+ const fresh = { blob: [], manifest: [] };
132
+ const due = [];
133
+ for (const kind of ["blob", "manifest"]) {
134
+ for (const ref of have[kind].keys())
135
+ if (!candidates.has(`${kind}:${ref}`))
136
+ stale[kind].push(ref); // referenced again, or gone
137
+ }
138
+ for (const o of candidates.values()) {
139
+ const m = have[o.kind].get(o.ref);
140
+ if (!m) {
141
+ rep.marked++;
142
+ rep.markedBytes += o.size;
143
+ fresh[o.kind].push({ ref: o.ref, size: o.size });
144
+ continue;
145
+ }
146
+ const old = started.getTime() - m.firstSeen.getTime() >= opts.delayMs && started.getTime() - o.modifiedAt.getTime() >= minAge;
147
+ if (old)
148
+ due.push(o);
149
+ else
150
+ rep.waiting++;
151
+ }
152
+ if (!opts.dryRun) {
153
+ for (const kind of ["blob", "manifest"]) {
154
+ if (stale[kind].length)
155
+ await marks.clear(tenant, kind, stale[kind]);
156
+ if (fresh[kind].length)
157
+ await marks.put(tenant, kind, fresh[kind], started);
158
+ }
159
+ }
160
+ // ---- sweep
161
+ if (opts.dryRun) {
162
+ rep.wouldDelete += Math.min(due.length, budget);
163
+ rep.wouldDeleteBytes += due.slice(0, budget).reduce((a, o) => a + o.size, 0);
164
+ return 0;
165
+ }
166
+ let did = 0;
167
+ const since = new Date(started.getTime() - 60_000);
168
+ const newlyLive = new Map(); // manifest id → its blobs, for revisions made since the mark began
169
+ const gone = { blob: [], manifest: [] };
170
+ due.sort((a, b) => (a.kind === b.kind ? 0 : a.kind === "blob" ? -1 : 1)); // blobs before manifests
171
+ for (const o of due) {
172
+ if (did >= budget)
173
+ break;
174
+ const ran = await (pins ?? NO_GUARD).guardDelete(tenant, o.kind === "blob" ? "blob" : "manifest", o.ref, async () => {
175
+ // Inside the pin lock: whatever was committed since the mark began.
176
+ const recent = await revisions.manifestIds(tenant, { since });
177
+ if (o.kind === "manifest" && recent.includes(o.ref))
178
+ return void rep.skippedHeld++;
179
+ if (o.kind === "blob") {
180
+ for (const id of recent) {
181
+ let set = newlyLive.get(id);
182
+ if (!set) {
183
+ set = new Set();
184
+ try {
185
+ for (const f of Object.values((await loadManifest({ blobs, revisions }, tenant, id)).files))
186
+ set.add(f.sha);
187
+ }
188
+ catch {
189
+ set.add(o.ref); // unreadable: keep what we were about to delete
190
+ }
191
+ newlyLive.set(id, set);
192
+ }
193
+ if (set.has(o.ref))
194
+ return void rep.skippedHeld++;
195
+ }
196
+ }
197
+ await blobs.delete(o.key);
198
+ rep.deleted++;
199
+ rep.deletedBytes += o.size;
200
+ did++;
201
+ gone[o.kind].push(o.ref);
202
+ });
203
+ if (!ran)
204
+ rep.skippedHeld++; // a live pin
205
+ }
206
+ for (const kind of ["blob", "manifest"])
207
+ if (gone[kind].length)
208
+ await marks.clear(tenant, kind, gone[kind]);
209
+ return did;
210
+ }
211
+ const NO_GUARD = {
212
+ async guardDelete(_t, _k, _r, del) {
213
+ await del();
214
+ return true;
215
+ },
216
+ };
217
+ // ------------------------------------------------------------- an in-memory SweepMarks
218
+ /** For tests and a host without a database table (the clock is injectable). */
219
+ export function memorySweepMarks(clock = () => new Date()) {
220
+ const table = new Map();
221
+ const runs = [];
222
+ const k = (t, kind, ref) => `${t}\0${kind}\0${ref}`;
223
+ return {
224
+ runs,
225
+ table,
226
+ async now() {
227
+ return clock();
228
+ },
229
+ async load(tenant, kind) {
230
+ const out = new Map();
231
+ for (const [key, v] of table) {
232
+ const [t, kd, ref] = key.split("\0");
233
+ if (t === tenant && kd === kind)
234
+ out.set(ref, v);
235
+ }
236
+ return out;
237
+ },
238
+ async put(tenant, kind, entries, at) {
239
+ for (const e of entries)
240
+ if (!table.has(k(tenant, kind, e.ref)))
241
+ table.set(k(tenant, kind, e.ref), { firstSeen: at, size: e.size });
242
+ },
243
+ async clear(tenant, kind, refs) {
244
+ for (const r of refs)
245
+ table.delete(k(tenant, kind, r));
246
+ },
247
+ async lastRunAt() {
248
+ return runs.length ? clock() : null;
249
+ },
250
+ async recordRun(report) {
251
+ runs.push(report);
252
+ },
253
+ };
254
+ }