@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.
- package/dist/src/approvals.js +3 -3
- package/dist/src/blob-cache.d.ts +58 -0
- package/dist/src/blob-cache.js +309 -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 +357 -0
- package/dist/src/blob-sweeper.d.ts +70 -0
- package/dist/src/blob-sweeper.js +254 -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 +86 -9
- package/dist/src/history.js +132 -16
- 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 +458 -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 +259 -0
- package/dist/src/workspace-revisions.js +1274 -0
- package/package.json +1 -1
- package/src/approvals.ts +3 -3
- package/src/blob-cache.ts +354 -0
- package/src/blob-pins.ts +99 -0
- package/src/blob-store.ts +385 -0
- package/src/blob-sweeper.ts +308 -0
- package/src/blob-types.ts +216 -0
- package/src/evals.ts +1 -1
- package/src/history.ts +182 -16
- 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 +489 -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 +1324 -0
|
@@ -0,0 +1,385 @@
|
|
|
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
|
+
}
|
|
214
|
+
if (fs.statSync(part).size !== size) {
|
|
215
|
+
if (attempt + 1 >= max) throw new BlobTransientError(`download of ${key} stopped short`);
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
break;
|
|
219
|
+
}
|
|
220
|
+
if (opts.sha256) {
|
|
221
|
+
const h = await hashRange(fileRange(part), 0, size, opts.signal);
|
|
222
|
+
if (h.sha256 !== opts.sha256) {
|
|
223
|
+
fs.rmSync(part, { force: true });
|
|
224
|
+
throw new BlobSourceError(`${key} does not hash to ${opts.sha256}`);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
fs.renameSync(part, dest);
|
|
228
|
+
return { size };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const fileRange = (file: string): BlobSource => ({
|
|
232
|
+
size: fs.statSync(file).size,
|
|
233
|
+
async *read(start, end) {
|
|
234
|
+
if (end > start) yield* fs.createReadStream(file, { start, end: end - 1 });
|
|
235
|
+
},
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
// ---------- the store in force ----------
|
|
239
|
+
|
|
240
|
+
/** s3 when FOLDRUN_STORAGE_DRIVER=s3 and it is fully configured, else fs.
|
|
241
|
+
* (The same fall-back rule as storage.ts's driverFor.) */
|
|
242
|
+
export function blobStore(): BlobStore & BlobSweeper {
|
|
243
|
+
if (process.env.FOLDRUN_STORAGE_DRIVER === "s3") {
|
|
244
|
+
const cfg = s3Config();
|
|
245
|
+
if (cfg) return bounded(s3BlobStore(cfg));
|
|
246
|
+
}
|
|
247
|
+
return bounded(fsBlobStore());
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// ---------- deadlines, retries, concurrency ----------
|
|
251
|
+
|
|
252
|
+
export interface Limits {
|
|
253
|
+
/** Per attempt. */
|
|
254
|
+
deadlineMs: number;
|
|
255
|
+
/** Extra attempts after the first, for transient failures only. */
|
|
256
|
+
retries: number;
|
|
257
|
+
/** Calls in flight at once, across all keys. */
|
|
258
|
+
concurrency: number;
|
|
259
|
+
/** First backoff; doubles each retry, with jitter. */
|
|
260
|
+
backoffMs: number;
|
|
261
|
+
/** The slowest link a transfer is expected to survive. A put's deadline is
|
|
262
|
+
* `deadlineMs` plus its size over this, so a 400 MB blob is not cut off at
|
|
263
|
+
* the 30 s a head gets. */
|
|
264
|
+
minBytesPerSec: number;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export const DEFAULT_LIMITS: Limits = { deadlineMs: 30_000, retries: 3, concurrency: 8, backoffMs: 200, minBytesPerSec: 1024 * 1024 };
|
|
268
|
+
|
|
269
|
+
export function limitsFromEnv(env: NodeJS.ProcessEnv = process.env): Limits {
|
|
270
|
+
const n = (v: string | undefined, d: number) => (v !== undefined && /^\d+$/.test(v) ? Number(v) : d);
|
|
271
|
+
return {
|
|
272
|
+
deadlineMs: n(env.FOLDRUN_BLOB_DEADLINE_MS, DEFAULT_LIMITS.deadlineMs),
|
|
273
|
+
retries: n(env.FOLDRUN_BLOB_RETRIES, DEFAULT_LIMITS.retries),
|
|
274
|
+
concurrency: Math.max(1, n(env.FOLDRUN_BLOB_CONCURRENCY, DEFAULT_LIMITS.concurrency)),
|
|
275
|
+
backoffMs: DEFAULT_LIMITS.backoffMs,
|
|
276
|
+
minBytesPerSec: Math.max(1, n(env.FOLDRUN_BLOB_MIN_BYTES_PER_SEC, DEFAULT_LIMITS.minBytesPerSec)),
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
class Semaphore {
|
|
281
|
+
private waiting: (() => void)[] = [];
|
|
282
|
+
private active = 0;
|
|
283
|
+
private readonly max: number;
|
|
284
|
+
constructor(max: number) {
|
|
285
|
+
this.max = max;
|
|
286
|
+
}
|
|
287
|
+
async run<T>(fn: () => Promise<T>): Promise<T> {
|
|
288
|
+
if (this.active >= this.max) await new Promise<void>((r) => this.waiting.push(r));
|
|
289
|
+
this.active++;
|
|
290
|
+
try {
|
|
291
|
+
return await fn();
|
|
292
|
+
} finally {
|
|
293
|
+
this.active--;
|
|
294
|
+
this.waiting.shift()?.();
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const isTransient = (err: unknown) =>
|
|
300
|
+
err instanceof BlobTransientError || ["ECONNRESET", "ETIMEDOUT", "EAGAIN", "EBUSY", "EMFILE"].includes((err as NodeJS.ErrnoException)?.code ?? "");
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Wrap a store so every call has a deadline (an AbortSignal handed down; the
|
|
304
|
+
* call fails with BlobTransientError if it passes), is retried on transient
|
|
305
|
+
* failure within a budget, and counts against a concurrency cap.
|
|
306
|
+
*
|
|
307
|
+
* A `get` is deadline-bound only until the stream starts: a long download is
|
|
308
|
+
* the caller's to bound. A not-found, a 4xx and a bad key are never retried.
|
|
309
|
+
*/
|
|
310
|
+
export function bounded<S extends BlobStore & Partial<BlobSweeper>>(inner: S, limits: Partial<Limits> = {}): S & BlobSweeper {
|
|
311
|
+
const L = { ...limitsFromEnv(), ...limits };
|
|
312
|
+
const gate = new Semaphore(L.concurrency);
|
|
313
|
+
/** The caller's signal and this attempt's deadline, either of which ends it. */
|
|
314
|
+
const both = (caller: AbortSignal | undefined, ms: number) => {
|
|
315
|
+
const deadline = AbortSignal.timeout(ms);
|
|
316
|
+
return caller ? AbortSignal.any([caller, deadline]) : deadline;
|
|
317
|
+
};
|
|
318
|
+
async function call<T>(what: string, caller: AbortSignal | undefined, fn: (signal: AbortSignal) => Promise<T>, bytes = 0): Promise<T> {
|
|
319
|
+
const ms = L.deadlineMs + Math.ceil((bytes / L.minBytesPerSec) * 1000);
|
|
320
|
+
return gate.run(async () => {
|
|
321
|
+
let attempt = 0;
|
|
322
|
+
for (;;) {
|
|
323
|
+
if (caller?.aborted) throw caller.reason ?? new Error(`${what}: cancelled`);
|
|
324
|
+
const signal = both(caller, ms);
|
|
325
|
+
try {
|
|
326
|
+
return await Promise.race([
|
|
327
|
+
fn(signal),
|
|
328
|
+
new Promise<never>((_, reject) =>
|
|
329
|
+
signal.addEventListener(
|
|
330
|
+
"abort",
|
|
331
|
+
() => reject(caller?.aborted ? (caller.reason ?? new Error(`${what}: cancelled`)) : new BlobTransientError(`${what}: no answer within ${ms}ms`)),
|
|
332
|
+
{ once: true },
|
|
333
|
+
),
|
|
334
|
+
),
|
|
335
|
+
]);
|
|
336
|
+
} catch (err) {
|
|
337
|
+
if (caller?.aborted || !isTransient(err) || attempt >= L.retries) throw err;
|
|
338
|
+
attempt++;
|
|
339
|
+
await new Promise((r) => setTimeout(r, L.backoffMs * 2 ** (attempt - 1) * (0.5 + Math.random())));
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
return {
|
|
345
|
+
...inner,
|
|
346
|
+
kind: inner.kind,
|
|
347
|
+
putIfAbsent: (key, body, opts) => call("put", opts?.signal, (signal) => inner.putIfAbsent(key, body, { ...opts, signal }), body.byteLength),
|
|
348
|
+
// The deadline covers getting the stream going, not draining it: the
|
|
349
|
+
// timer is cleared once the object starts to arrive. The caller's signal
|
|
350
|
+
// stays attached to the stream, so cancelling still stops the download.
|
|
351
|
+
get: (key, opts) =>
|
|
352
|
+
call("get", opts?.signal, async () => {
|
|
353
|
+
const ctl = new AbortController();
|
|
354
|
+
const timer = setTimeout(() => ctl.abort(), L.deadlineMs);
|
|
355
|
+
const onCaller = () => ctl.abort(opts?.signal?.reason);
|
|
356
|
+
opts?.signal?.addEventListener("abort", onCaller, { once: true });
|
|
357
|
+
try {
|
|
358
|
+
return await inner.get(key, { ...opts, signal: ctl.signal });
|
|
359
|
+
} finally {
|
|
360
|
+
clearTimeout(timer);
|
|
361
|
+
}
|
|
362
|
+
}),
|
|
363
|
+
// A streamed put has no fixed deadline (its length decides), so it gets the
|
|
364
|
+
// retry budget and the concurrency cap, and the s3 driver's own per-request
|
|
365
|
+
// deadlines. Cancelling is the caller's signal.
|
|
366
|
+
putSourceIfAbsent: (key, source, opts) =>
|
|
367
|
+
gate.run(async () => {
|
|
368
|
+
for (let attempt = 0; ; attempt++) {
|
|
369
|
+
if (opts?.signal?.aborted) throw opts.signal.reason ?? new Error("put: cancelled");
|
|
370
|
+
try {
|
|
371
|
+
return await inner.putSourceIfAbsent(key, source, opts);
|
|
372
|
+
} catch (err) {
|
|
373
|
+
if (opts?.signal?.aborted || !isTransient(err) || attempt >= L.retries) throw err;
|
|
374
|
+
await new Promise((r) => setTimeout(r, L.backoffMs * 2 ** attempt * (0.5 + Math.random())));
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
}),
|
|
378
|
+
abortStaleUploads: (o) => (inner.abortStaleUploads ? inner.abortStaleUploads(o) : Promise.resolve(0)),
|
|
379
|
+
head: (key, opts) => call("head", opts?.signal, (signal) => inner.head(key, { signal })),
|
|
380
|
+
delete: (key, opts) => call("delete", opts?.signal, (signal) => (inner.delete ? inner.delete(key, { signal }) : Promise.reject(new Error("this store cannot delete")))),
|
|
381
|
+
...(inner.purgeTenant ? { purgeTenant: (tenant: string) => inner.purgeTenant!(tenant) } : {}),
|
|
382
|
+
...(inner.list ? { list: (prefix: string, o?: { signal?: AbortSignal }) => inner.list!(prefix, o) } : {}),
|
|
383
|
+
...(inner.tenants ? { tenants: (o?: { signal?: AbortSignal }) => inner.tenants!(o) } : {}),
|
|
384
|
+
} as S & BlobSweeper;
|
|
385
|
+
}
|
|
@@ -0,0 +1,308 @@
|
|
|
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
|
+
|
|
35
|
+
import type { BlobStore, BlobSweeper } from "./blob-store.ts";
|
|
36
|
+
import type { BlobPins } from "./blob-pins.ts";
|
|
37
|
+
import type { RevisionStore } from "./revision-store.ts";
|
|
38
|
+
import { loadManifest, BlobMissing } from "./publish.ts";
|
|
39
|
+
import { opsError, opsLog } from "./ops-log.ts";
|
|
40
|
+
|
|
41
|
+
export type MarkKind = "blob" | "manifest" | "workspace";
|
|
42
|
+
export interface Mark {
|
|
43
|
+
firstSeen: Date;
|
|
44
|
+
size: number;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Where "first seen unreferenced" is kept (a table in the platform). */
|
|
48
|
+
export interface SweepMarks {
|
|
49
|
+
/** The database's clock: every record and comparison uses it, so pods agree. */
|
|
50
|
+
now(): Promise<Date>;
|
|
51
|
+
load(tenant: string, kind: MarkKind): Promise<Map<string, Mark>>;
|
|
52
|
+
/** Record refs not yet recorded (an existing record keeps its first time). */
|
|
53
|
+
put(tenant: string, kind: MarkKind, entries: { ref: string; size: number }[], at: Date): Promise<void>;
|
|
54
|
+
clear(tenant: string, kind: MarkKind, refs: string[]): Promise<void>;
|
|
55
|
+
/** When the last run (real or dry) finished, for the schedule. */
|
|
56
|
+
lastRunAt(): Promise<Date | null>;
|
|
57
|
+
recordRun(report: SweepReport): Promise<void>;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface SweepOptions {
|
|
61
|
+
dryRun: boolean;
|
|
62
|
+
/** Unreferenced for this long before deletion: the restore-point window. */
|
|
63
|
+
delayMs: number;
|
|
64
|
+
/** Never touch an object younger than this. Default one hour. */
|
|
65
|
+
minAgeMs?: number;
|
|
66
|
+
/** Delete at most this many objects in one run, all accounts together. */
|
|
67
|
+
maxDeletes: number;
|
|
68
|
+
/** Only these accounts (tests, an operator). */
|
|
69
|
+
tenants?: string[];
|
|
70
|
+
/** Go ahead even when the database holds no revision (default: refuse). */
|
|
71
|
+
allowEmpty?: boolean;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface SweepReport {
|
|
75
|
+
dryRun: boolean;
|
|
76
|
+
tenants: number;
|
|
77
|
+
scanned: number;
|
|
78
|
+
scannedBytes: number;
|
|
79
|
+
live: number;
|
|
80
|
+
/** Seen unreferenced for the first time in this run. */
|
|
81
|
+
marked: number;
|
|
82
|
+
markedBytes: number;
|
|
83
|
+
/** Unreferenced, but not for long enough yet. */
|
|
84
|
+
waiting: number;
|
|
85
|
+
deleted: number;
|
|
86
|
+
deletedBytes: number;
|
|
87
|
+
/** A dry run: due now, and what a real run would delete. */
|
|
88
|
+
wouldDelete: number;
|
|
89
|
+
wouldDeleteBytes: number;
|
|
90
|
+
/** Would have been deleted (dry run), or were due but a pin or a new revision held them. */
|
|
91
|
+
skippedHeld: number;
|
|
92
|
+
/** Not an object the sweeper owns (left alone). */
|
|
93
|
+
foreign: number;
|
|
94
|
+
errors: number;
|
|
95
|
+
refused?: string;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const TENANT = /^[A-Za-z0-9][A-Za-z0-9._@-]{0,120}$/;
|
|
99
|
+
const HEX = /^[0-9a-f]{64}$/;
|
|
100
|
+
const empty = (dryRun: boolean): SweepReport => ({ 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 });
|
|
101
|
+
|
|
102
|
+
export interface SweepDeps {
|
|
103
|
+
blobs: BlobStore & BlobSweeper;
|
|
104
|
+
revisions: RevisionStore;
|
|
105
|
+
pins?: BlobPins;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export async function sweepBlobs(deps: SweepDeps, marks: SweepMarks, opts: SweepOptions): Promise<SweepReport> {
|
|
109
|
+
const rep = empty(opts.dryRun);
|
|
110
|
+
const { blobs } = deps;
|
|
111
|
+
if (!blobs.list || !blobs.tenants || !blobs.delete) return refuse(rep, "the object store cannot list and delete");
|
|
112
|
+
let tenants: string[];
|
|
113
|
+
try {
|
|
114
|
+
tenants = opts.tenants ?? (await blobs.tenants());
|
|
115
|
+
} catch (err) {
|
|
116
|
+
opsError("blobs.sweep_failed", err, { stage: "tenants" });
|
|
117
|
+
rep.errors++;
|
|
118
|
+
return refuse(rep, "the object store could not be listed");
|
|
119
|
+
}
|
|
120
|
+
if (!opts.allowEmpty && tenants.length && !(await deps.revisions.anyRevisions())) {
|
|
121
|
+
return refuse(rep, "the database holds no revision but the store holds objects: not deleting on that evidence");
|
|
122
|
+
}
|
|
123
|
+
let budget = Math.max(0, opts.maxDeletes);
|
|
124
|
+
for (const tenant of tenants) {
|
|
125
|
+
if (!TENANT.test(tenant)) {
|
|
126
|
+
rep.foreign++;
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
rep.tenants++;
|
|
130
|
+
try {
|
|
131
|
+
budget -= await sweepTenant(deps, marks, opts, tenant, rep, budget);
|
|
132
|
+
} catch (err) {
|
|
133
|
+
rep.errors++;
|
|
134
|
+
opsError("blobs.sweep_failed", err, { tenant });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
opsLog("info", "blobs.sweep", { ...rep });
|
|
138
|
+
await marks.recordRun(rep).catch((err) => opsError("blobs.sweep_not_recorded", err, {}));
|
|
139
|
+
return rep;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function refuse(rep: SweepReport, why: string): SweepReport {
|
|
143
|
+
rep.refused = why;
|
|
144
|
+
opsLog("warn", "blobs.sweep_refused", { reason: why, dryRun: rep.dryRun });
|
|
145
|
+
return rep;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function sweepTenant(deps: SweepDeps, marks: SweepMarks, opts: SweepOptions, tenant: string, rep: SweepReport, budget: number): Promise<number> {
|
|
149
|
+
const { blobs, revisions, pins } = deps;
|
|
150
|
+
const started = await marks.now();
|
|
151
|
+
|
|
152
|
+
// ---- mark: the roots
|
|
153
|
+
const retained = new Set(await revisions.manifestIds(tenant));
|
|
154
|
+
const pinned = pins ? await pins.live(tenant) : { manifests: [], blobs: [] };
|
|
155
|
+
const liveBlobs = new Set<string>(pinned.blobs);
|
|
156
|
+
const liveManifests = new Set<string>([...retained, ...pinned.manifests]);
|
|
157
|
+
for (const id of liveManifests) {
|
|
158
|
+
try {
|
|
159
|
+
const m = await loadManifest({ blobs, revisions }, tenant, id);
|
|
160
|
+
for (const f of Object.values(m.files)) liveBlobs.add(f.sha);
|
|
161
|
+
} catch (err) {
|
|
162
|
+
// A manifest a revision names that cannot be read means its blobs are
|
|
163
|
+
// unknown: nothing of this account may be deleted this run. A pinned
|
|
164
|
+
// manifest that is not there yet (a publish still uploading) is fine.
|
|
165
|
+
if (err instanceof BlobMissing && !retained.has(id)) continue;
|
|
166
|
+
throw err;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// ---- what is there
|
|
171
|
+
type Obj = { key: string; kind: "blob" | "manifest"; ref: string; size: number; modifiedAt: Date };
|
|
172
|
+
const candidates = new Map<string, Obj>(); // `${kind}:${ref}`
|
|
173
|
+
const prefix = `t/${tenant}/`;
|
|
174
|
+
let live = 0;
|
|
175
|
+
for await (const o of blobs.list!(prefix)) {
|
|
176
|
+
rep.scanned++;
|
|
177
|
+
rep.scannedBytes += o.size;
|
|
178
|
+
const rest = o.key.startsWith(prefix) ? o.key.slice(prefix.length) : "";
|
|
179
|
+
let kind: "blob" | "manifest" | null = null;
|
|
180
|
+
let ref = "";
|
|
181
|
+
if (rest.startsWith("blobs/") && HEX.test(rest.slice(6))) (kind = "blob"), (ref = rest.slice(6));
|
|
182
|
+
else if (rest.startsWith("manifests/") && rest.endsWith(".json") && HEX.test(rest.slice(10, -5))) (kind = "manifest"), (ref = rest.slice(10, -5));
|
|
183
|
+
if (!kind) {
|
|
184
|
+
rep.foreign++;
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
if ((kind === "blob" ? liveBlobs : liveManifests).has(ref)) {
|
|
188
|
+
live++;
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
candidates.set(`${kind}:${ref}`, { key: o.key, kind, ref, size: o.size, modifiedAt: o.modifiedAt });
|
|
192
|
+
}
|
|
193
|
+
rep.live += live;
|
|
194
|
+
|
|
195
|
+
// ---- delay: first seen, and how long ago
|
|
196
|
+
const minAge = opts.minAgeMs ?? 3_600_000;
|
|
197
|
+
const have = { blob: await marks.load(tenant, "blob"), manifest: await marks.load(tenant, "manifest") };
|
|
198
|
+
const stale: Record<"blob" | "manifest", string[]> = { blob: [], manifest: [] };
|
|
199
|
+
const fresh: Record<"blob" | "manifest", { ref: string; size: number }[]> = { blob: [], manifest: [] };
|
|
200
|
+
const due: Obj[] = [];
|
|
201
|
+
for (const kind of ["blob", "manifest"] as const) {
|
|
202
|
+
for (const ref of have[kind].keys()) if (!candidates.has(`${kind}:${ref}`)) stale[kind].push(ref); // referenced again, or gone
|
|
203
|
+
}
|
|
204
|
+
for (const o of candidates.values()) {
|
|
205
|
+
const m = have[o.kind].get(o.ref);
|
|
206
|
+
if (!m) {
|
|
207
|
+
rep.marked++;
|
|
208
|
+
rep.markedBytes += o.size;
|
|
209
|
+
fresh[o.kind].push({ ref: o.ref, size: o.size });
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
const old = started.getTime() - m.firstSeen.getTime() >= opts.delayMs && started.getTime() - o.modifiedAt.getTime() >= minAge;
|
|
213
|
+
if (old) due.push(o);
|
|
214
|
+
else rep.waiting++;
|
|
215
|
+
}
|
|
216
|
+
if (!opts.dryRun) {
|
|
217
|
+
for (const kind of ["blob", "manifest"] as const) {
|
|
218
|
+
if (stale[kind].length) await marks.clear(tenant, kind, stale[kind]);
|
|
219
|
+
if (fresh[kind].length) await marks.put(tenant, kind, fresh[kind], started);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// ---- sweep
|
|
224
|
+
if (opts.dryRun) {
|
|
225
|
+
rep.wouldDelete += Math.min(due.length, budget);
|
|
226
|
+
rep.wouldDeleteBytes += due.slice(0, budget).reduce((a, o) => a + o.size, 0);
|
|
227
|
+
return 0;
|
|
228
|
+
}
|
|
229
|
+
let did = 0;
|
|
230
|
+
const since = new Date(started.getTime() - 60_000);
|
|
231
|
+
const newlyLive = new Map<string, Set<string>>(); // manifest id → its blobs, for revisions made since the mark began
|
|
232
|
+
const gone: Record<"blob" | "manifest", string[]> = { blob: [], manifest: [] };
|
|
233
|
+
due.sort((a, b) => (a.kind === b.kind ? 0 : a.kind === "blob" ? -1 : 1)); // blobs before manifests
|
|
234
|
+
for (const o of due) {
|
|
235
|
+
if (did >= budget) break;
|
|
236
|
+
const ran = await (pins ?? NO_GUARD).guardDelete(tenant, o.kind === "blob" ? "blob" : "manifest", o.ref, async () => {
|
|
237
|
+
// Inside the pin lock: whatever was committed since the mark began.
|
|
238
|
+
const recent = await revisions.manifestIds(tenant, { since });
|
|
239
|
+
if (o.kind === "manifest" && recent.includes(o.ref)) return void rep.skippedHeld++;
|
|
240
|
+
if (o.kind === "blob") {
|
|
241
|
+
for (const id of recent) {
|
|
242
|
+
let set = newlyLive.get(id);
|
|
243
|
+
if (!set) {
|
|
244
|
+
set = new Set();
|
|
245
|
+
try {
|
|
246
|
+
for (const f of Object.values((await loadManifest({ blobs, revisions }, tenant, id)).files)) set.add(f.sha);
|
|
247
|
+
} catch {
|
|
248
|
+
set.add(o.ref); // unreadable: keep what we were about to delete
|
|
249
|
+
}
|
|
250
|
+
newlyLive.set(id, set);
|
|
251
|
+
}
|
|
252
|
+
if (set.has(o.ref)) return void rep.skippedHeld++;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
await blobs.delete(o.key);
|
|
256
|
+
rep.deleted++;
|
|
257
|
+
rep.deletedBytes += o.size;
|
|
258
|
+
did++;
|
|
259
|
+
gone[o.kind].push(o.ref);
|
|
260
|
+
});
|
|
261
|
+
if (!ran) rep.skippedHeld++; // a live pin
|
|
262
|
+
}
|
|
263
|
+
for (const kind of ["blob", "manifest"] as const) if (gone[kind].length) await marks.clear(tenant, kind, gone[kind]);
|
|
264
|
+
return did;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const NO_GUARD = {
|
|
268
|
+
async guardDelete(_t: string, _k: string, _r: string, del: () => Promise<void>) {
|
|
269
|
+
await del();
|
|
270
|
+
return true;
|
|
271
|
+
},
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
// ------------------------------------------------------------- an in-memory SweepMarks
|
|
275
|
+
|
|
276
|
+
/** For tests and a host without a database table (the clock is injectable). */
|
|
277
|
+
export function memorySweepMarks(clock: () => Date = () => new Date()): SweepMarks & { runs: SweepReport[]; table: Map<string, Mark> } {
|
|
278
|
+
const table = new Map<string, Mark>();
|
|
279
|
+
const runs: SweepReport[] = [];
|
|
280
|
+
const k = (t: string, kind: string, ref: string) => `${t}\0${kind}\0${ref}`;
|
|
281
|
+
return {
|
|
282
|
+
runs,
|
|
283
|
+
table,
|
|
284
|
+
async now() {
|
|
285
|
+
return clock();
|
|
286
|
+
},
|
|
287
|
+
async load(tenant, kind) {
|
|
288
|
+
const out = new Map<string, Mark>();
|
|
289
|
+
for (const [key, v] of table) {
|
|
290
|
+
const [t, kd, ref] = key.split("\0");
|
|
291
|
+
if (t === tenant && kd === kind) out.set(ref, v);
|
|
292
|
+
}
|
|
293
|
+
return out;
|
|
294
|
+
},
|
|
295
|
+
async put(tenant, kind, entries, at) {
|
|
296
|
+
for (const e of entries) if (!table.has(k(tenant, kind, e.ref))) table.set(k(tenant, kind, e.ref), { firstSeen: at, size: e.size });
|
|
297
|
+
},
|
|
298
|
+
async clear(tenant, kind, refs) {
|
|
299
|
+
for (const r of refs) table.delete(k(tenant, kind, r));
|
|
300
|
+
},
|
|
301
|
+
async lastRunAt() {
|
|
302
|
+
return runs.length ? clock() : null;
|
|
303
|
+
},
|
|
304
|
+
async recordRun(report) {
|
|
305
|
+
runs.push(report);
|
|
306
|
+
},
|
|
307
|
+
};
|
|
308
|
+
}
|