@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
|
@@ -0,0 +1,336 @@
|
|
|
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). A manifest committed DURING the sweep that cannot be read stops that
|
|
30
|
+
// account's sweep where it is: the objects deleted before it stay deleted (they
|
|
31
|
+
// were checked), nothing after it goes. `dryRun` marks and counts nothing it
|
|
32
|
+
// would not report: it writes no records and deletes nothing.
|
|
33
|
+
//
|
|
34
|
+
// `maxDeletes` is one budget for all accounts. It is charged from the report
|
|
35
|
+
// (what was deleted, or in a dry run what would be), so an account whose sweep
|
|
36
|
+
// fails part-way still pays for what it deleted, and a dry run stops counting
|
|
37
|
+
// where a real run would stop deleting.
|
|
38
|
+
//
|
|
39
|
+
// An account that was deleted needs no special case: its rows and pins are gone,
|
|
40
|
+
// so everything under its prefix is unreferenced, waits the delay, and goes.
|
|
41
|
+
|
|
42
|
+
import type { BlobStore, BlobSweeper } from "./blob-store.ts";
|
|
43
|
+
import type { BlobPins } from "./blob-pins.ts";
|
|
44
|
+
import type { RevisionStore } from "./revision-store.ts";
|
|
45
|
+
import { loadManifest, BlobMissing } from "./publish.ts";
|
|
46
|
+
import { opsError, opsLog } from "./ops-log.ts";
|
|
47
|
+
|
|
48
|
+
export type MarkKind = "blob" | "manifest" | "workspace";
|
|
49
|
+
export interface Mark {
|
|
50
|
+
firstSeen: Date;
|
|
51
|
+
size: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Where "first seen unreferenced" is kept (a table in the platform). */
|
|
55
|
+
export interface SweepMarks {
|
|
56
|
+
/** The database's clock: every record and comparison uses it, so pods agree. */
|
|
57
|
+
now(): Promise<Date>;
|
|
58
|
+
load(tenant: string, kind: MarkKind): Promise<Map<string, Mark>>;
|
|
59
|
+
/** Record refs not yet recorded (an existing record keeps its first time). */
|
|
60
|
+
put(tenant: string, kind: MarkKind, entries: { ref: string; size: number }[], at: Date): Promise<void>;
|
|
61
|
+
clear(tenant: string, kind: MarkKind, refs: string[]): Promise<void>;
|
|
62
|
+
/** When the last run (real or dry) finished, for the schedule. */
|
|
63
|
+
lastRunAt(): Promise<Date | null>;
|
|
64
|
+
recordRun(report: SweepReport): Promise<void>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface SweepOptions {
|
|
68
|
+
dryRun: boolean;
|
|
69
|
+
/** Unreferenced for this long before deletion: the restore-point window. */
|
|
70
|
+
delayMs: number;
|
|
71
|
+
/** Never touch an object younger than this. Default one hour. */
|
|
72
|
+
minAgeMs?: number;
|
|
73
|
+
/** Delete at most this many objects in one run, all accounts together. */
|
|
74
|
+
maxDeletes: number;
|
|
75
|
+
/** Only these accounts (tests, an operator). */
|
|
76
|
+
tenants?: string[];
|
|
77
|
+
/** Go ahead even when the database holds no revision (default: refuse). */
|
|
78
|
+
allowEmpty?: boolean;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface SweepReport {
|
|
82
|
+
dryRun: boolean;
|
|
83
|
+
tenants: number;
|
|
84
|
+
scanned: number;
|
|
85
|
+
scannedBytes: number;
|
|
86
|
+
live: number;
|
|
87
|
+
/** Seen unreferenced for the first time in this run. */
|
|
88
|
+
marked: number;
|
|
89
|
+
markedBytes: number;
|
|
90
|
+
/** Unreferenced, but not for long enough yet. */
|
|
91
|
+
waiting: number;
|
|
92
|
+
deleted: number;
|
|
93
|
+
deletedBytes: number;
|
|
94
|
+
/** A dry run: due now, and what a real run would delete. */
|
|
95
|
+
wouldDelete: number;
|
|
96
|
+
wouldDeleteBytes: number;
|
|
97
|
+
/** Would have been deleted (dry run), or were due but a pin or a new revision held them. */
|
|
98
|
+
skippedHeld: number;
|
|
99
|
+
/** Not an object the sweeper owns (left alone). */
|
|
100
|
+
foreign: number;
|
|
101
|
+
errors: number;
|
|
102
|
+
refused?: string;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const TENANT = /^[A-Za-z0-9][A-Za-z0-9._@-]{0,120}$/;
|
|
106
|
+
const HEX = /^[0-9a-f]{64}$/;
|
|
107
|
+
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 });
|
|
108
|
+
|
|
109
|
+
export interface SweepDeps {
|
|
110
|
+
blobs: BlobStore & BlobSweeper;
|
|
111
|
+
revisions: RevisionStore;
|
|
112
|
+
pins?: BlobPins;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export async function sweepBlobs(deps: SweepDeps, marks: SweepMarks, opts: SweepOptions): Promise<SweepReport> {
|
|
116
|
+
const rep = empty(opts.dryRun);
|
|
117
|
+
const { blobs } = deps;
|
|
118
|
+
if (!blobs.list || !blobs.tenants || !blobs.delete) return refuse(rep, "the object store cannot list and delete");
|
|
119
|
+
let tenants: string[];
|
|
120
|
+
try {
|
|
121
|
+
tenants = opts.tenants ?? (await blobs.tenants());
|
|
122
|
+
} catch (err) {
|
|
123
|
+
opsError("blobs.sweep_failed", err, { stage: "tenants" });
|
|
124
|
+
rep.errors++;
|
|
125
|
+
return refuse(rep, "the object store could not be listed");
|
|
126
|
+
}
|
|
127
|
+
if (!opts.allowEmpty && tenants.length && !(await deps.revisions.anyRevisions())) {
|
|
128
|
+
return refuse(rep, "the database holds no revision but the store holds objects: not deleting on that evidence");
|
|
129
|
+
}
|
|
130
|
+
for (const tenant of tenants) {
|
|
131
|
+
if (!TENANT.test(tenant)) {
|
|
132
|
+
rep.foreign++;
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
rep.tenants++;
|
|
136
|
+
// Read from the report, not from what sweepTenant returns: a tenant that
|
|
137
|
+
// throws after deleting never returns, and its deletions must still count.
|
|
138
|
+
const budget = Math.max(0, opts.maxDeletes - rep.deleted - rep.wouldDelete);
|
|
139
|
+
try {
|
|
140
|
+
await sweepTenant(deps, marks, opts, tenant, rep, budget);
|
|
141
|
+
} catch (err) {
|
|
142
|
+
rep.errors++;
|
|
143
|
+
opsError("blobs.sweep_failed", err, { tenant });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
opsLog("info", "blobs.sweep", { ...rep });
|
|
147
|
+
await marks.recordRun(rep).catch((err) => opsError("blobs.sweep_not_recorded", err, {}));
|
|
148
|
+
return rep;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function refuse(rep: SweepReport, why: string): SweepReport {
|
|
152
|
+
rep.refused = why;
|
|
153
|
+
opsLog("warn", "blobs.sweep_refused", { reason: why, dryRun: rep.dryRun });
|
|
154
|
+
return rep;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Adds what it did to `rep` as it goes, so a throw part-way leaves the report
|
|
158
|
+
* (and with it the shared budget) true to what was deleted. */
|
|
159
|
+
async function sweepTenant(deps: SweepDeps, marks: SweepMarks, opts: SweepOptions, tenant: string, rep: SweepReport, budget: number): Promise<void> {
|
|
160
|
+
const { blobs, revisions, pins } = deps;
|
|
161
|
+
const started = await marks.now();
|
|
162
|
+
|
|
163
|
+
// ---- mark: the roots
|
|
164
|
+
const retained = new Set(await revisions.manifestIds(tenant));
|
|
165
|
+
const pinned = pins ? await pins.live(tenant) : { manifests: [], blobs: [] };
|
|
166
|
+
const liveBlobs = new Set<string>(pinned.blobs);
|
|
167
|
+
const liveManifests = new Set<string>([...retained, ...pinned.manifests]);
|
|
168
|
+
for (const id of liveManifests) {
|
|
169
|
+
try {
|
|
170
|
+
const m = await loadManifest({ blobs, revisions }, tenant, id);
|
|
171
|
+
for (const f of Object.values(m.files)) liveBlobs.add(f.sha);
|
|
172
|
+
} catch (err) {
|
|
173
|
+
// A manifest a revision names that cannot be read means its blobs are
|
|
174
|
+
// unknown: nothing of this account may be deleted this run. A pinned
|
|
175
|
+
// manifest that is not there yet (a publish still uploading) is fine.
|
|
176
|
+
if (err instanceof BlobMissing && !retained.has(id)) continue;
|
|
177
|
+
throw err;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// ---- what is there
|
|
182
|
+
type Obj = { key: string; kind: "blob" | "manifest"; ref: string; size: number; modifiedAt: Date };
|
|
183
|
+
const candidates = new Map<string, Obj>(); // `${kind}:${ref}`
|
|
184
|
+
const prefix = `t/${tenant}/`;
|
|
185
|
+
let live = 0;
|
|
186
|
+
for await (const o of blobs.list!(prefix)) {
|
|
187
|
+
rep.scanned++;
|
|
188
|
+
rep.scannedBytes += o.size;
|
|
189
|
+
const rest = o.key.startsWith(prefix) ? o.key.slice(prefix.length) : "";
|
|
190
|
+
let kind: "blob" | "manifest" | null = null;
|
|
191
|
+
let ref = "";
|
|
192
|
+
if (rest.startsWith("blobs/") && HEX.test(rest.slice(6))) (kind = "blob"), (ref = rest.slice(6));
|
|
193
|
+
else if (rest.startsWith("manifests/") && rest.endsWith(".json") && HEX.test(rest.slice(10, -5))) (kind = "manifest"), (ref = rest.slice(10, -5));
|
|
194
|
+
if (!kind) {
|
|
195
|
+
rep.foreign++;
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
if ((kind === "blob" ? liveBlobs : liveManifests).has(ref)) {
|
|
199
|
+
live++;
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
candidates.set(`${kind}:${ref}`, { key: o.key, kind, ref, size: o.size, modifiedAt: o.modifiedAt });
|
|
203
|
+
}
|
|
204
|
+
rep.live += live;
|
|
205
|
+
|
|
206
|
+
// ---- delay: first seen, and how long ago
|
|
207
|
+
const minAge = opts.minAgeMs ?? 3_600_000;
|
|
208
|
+
const have = { blob: await marks.load(tenant, "blob"), manifest: await marks.load(tenant, "manifest") };
|
|
209
|
+
const stale: Record<"blob" | "manifest", string[]> = { blob: [], manifest: [] };
|
|
210
|
+
const fresh: Record<"blob" | "manifest", { ref: string; size: number }[]> = { blob: [], manifest: [] };
|
|
211
|
+
const due: Obj[] = [];
|
|
212
|
+
for (const kind of ["blob", "manifest"] as const) {
|
|
213
|
+
for (const ref of have[kind].keys()) if (!candidates.has(`${kind}:${ref}`)) stale[kind].push(ref); // referenced again, or gone
|
|
214
|
+
}
|
|
215
|
+
for (const o of candidates.values()) {
|
|
216
|
+
const m = have[o.kind].get(o.ref);
|
|
217
|
+
if (!m) {
|
|
218
|
+
rep.marked++;
|
|
219
|
+
rep.markedBytes += o.size;
|
|
220
|
+
fresh[o.kind].push({ ref: o.ref, size: o.size });
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
const old = started.getTime() - m.firstSeen.getTime() >= opts.delayMs && started.getTime() - o.modifiedAt.getTime() >= minAge;
|
|
224
|
+
if (old) due.push(o);
|
|
225
|
+
else rep.waiting++;
|
|
226
|
+
}
|
|
227
|
+
if (!opts.dryRun) {
|
|
228
|
+
for (const kind of ["blob", "manifest"] as const) {
|
|
229
|
+
if (stale[kind].length) await marks.clear(tenant, kind, stale[kind]);
|
|
230
|
+
if (fresh[kind].length) await marks.put(tenant, kind, fresh[kind], started);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// ---- sweep
|
|
235
|
+
due.sort((a, b) => (a.kind === b.kind ? 0 : a.kind === "blob" ? -1 : 1)); // blobs before manifests
|
|
236
|
+
if (opts.dryRun) {
|
|
237
|
+
// The same objects, in the same order, a real run would take with this
|
|
238
|
+
// budget; adding to the report is what charges the shared budget.
|
|
239
|
+
rep.wouldDelete += Math.min(due.length, budget);
|
|
240
|
+
rep.wouldDeleteBytes += due.slice(0, budget).reduce((a, o) => a + o.size, 0);
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
let did = 0;
|
|
244
|
+
const since = new Date(started.getTime() - 60_000);
|
|
245
|
+
const newlyLive = new Map<string, Set<string>>(); // manifest id → its blobs, for revisions made since the mark began
|
|
246
|
+
const gone: Record<"blob" | "manifest", string[]> = { blob: [], manifest: [] };
|
|
247
|
+
const clearGone = async () => {
|
|
248
|
+
for (const kind of ["blob", "manifest"] as const) if (gone[kind].length) await marks.clear(tenant, kind, gone[kind]);
|
|
249
|
+
};
|
|
250
|
+
try {
|
|
251
|
+
for (const o of due) {
|
|
252
|
+
if (did >= budget) break;
|
|
253
|
+
const ran = await (pins ?? NO_GUARD).guardDelete(tenant, o.kind === "blob" ? "blob" : "manifest", o.ref, async () => {
|
|
254
|
+
// Inside the pin lock: whatever was committed since the mark began.
|
|
255
|
+
const recent = await revisions.manifestIds(tenant, { since });
|
|
256
|
+
if (o.kind === "manifest" && recent.includes(o.ref)) return void rep.skippedHeld++;
|
|
257
|
+
if (o.kind === "blob") {
|
|
258
|
+
for (const id of recent) {
|
|
259
|
+
let set = newlyLive.get(id);
|
|
260
|
+
if (!set) {
|
|
261
|
+
// A new revision's manifest that cannot be read leaves its blobs
|
|
262
|
+
// unknown, for this candidate and every one after it. Caching
|
|
263
|
+
// anything here would let a later candidate it names be deleted,
|
|
264
|
+
// so the account's sweep stops instead (the caller counts it).
|
|
265
|
+
let m;
|
|
266
|
+
try {
|
|
267
|
+
m = await loadManifest({ blobs, revisions }, tenant, id);
|
|
268
|
+
} catch (err) {
|
|
269
|
+
throw new Error(`a revision committed during the sweep names manifest ${id.slice(0, 12)}…, which cannot be read: stopping this account's sweep`, { cause: err });
|
|
270
|
+
}
|
|
271
|
+
set = new Set(Object.values(m.files).map((f) => f.sha));
|
|
272
|
+
newlyLive.set(id, set);
|
|
273
|
+
}
|
|
274
|
+
if (set.has(o.ref)) return void rep.skippedHeld++;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
await blobs.delete(o.key);
|
|
278
|
+
rep.deleted++;
|
|
279
|
+
rep.deletedBytes += o.size;
|
|
280
|
+
did++;
|
|
281
|
+
gone[o.kind].push(o.ref);
|
|
282
|
+
});
|
|
283
|
+
if (!ran) rep.skippedHeld++; // a live pin
|
|
284
|
+
}
|
|
285
|
+
} catch (err) {
|
|
286
|
+
// What was deleted before the failure is gone; its records go too, best
|
|
287
|
+
// effort (one left behind is stale next run, since its object is not
|
|
288
|
+
// listed, and is cleared then).
|
|
289
|
+
await clearGone().catch((e) => opsError("blobs.sweep_marks_not_cleared", e, { tenant }));
|
|
290
|
+
throw err;
|
|
291
|
+
}
|
|
292
|
+
await clearGone();
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
const NO_GUARD = {
|
|
296
|
+
async guardDelete(_t: string, _k: string, _r: string, del: () => Promise<void>) {
|
|
297
|
+
await del();
|
|
298
|
+
return true;
|
|
299
|
+
},
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
// ------------------------------------------------------------- an in-memory SweepMarks
|
|
303
|
+
|
|
304
|
+
/** For tests and a host without a database table (the clock is injectable). */
|
|
305
|
+
export function memorySweepMarks(clock: () => Date = () => new Date()): SweepMarks & { runs: SweepReport[]; table: Map<string, Mark> } {
|
|
306
|
+
const table = new Map<string, Mark>();
|
|
307
|
+
const runs: SweepReport[] = [];
|
|
308
|
+
const k = (t: string, kind: string, ref: string) => `${t}\0${kind}\0${ref}`;
|
|
309
|
+
return {
|
|
310
|
+
runs,
|
|
311
|
+
table,
|
|
312
|
+
async now() {
|
|
313
|
+
return clock();
|
|
314
|
+
},
|
|
315
|
+
async load(tenant, kind) {
|
|
316
|
+
const out = new Map<string, Mark>();
|
|
317
|
+
for (const [key, v] of table) {
|
|
318
|
+
const [t, kd, ref] = key.split("\0");
|
|
319
|
+
if (t === tenant && kd === kind) out.set(ref, v);
|
|
320
|
+
}
|
|
321
|
+
return out;
|
|
322
|
+
},
|
|
323
|
+
async put(tenant, kind, entries, at) {
|
|
324
|
+
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 });
|
|
325
|
+
},
|
|
326
|
+
async clear(tenant, kind, refs) {
|
|
327
|
+
for (const r of refs) table.delete(k(tenant, kind, r));
|
|
328
|
+
},
|
|
329
|
+
async lastRunAt() {
|
|
330
|
+
return runs.length ? clock() : null;
|
|
331
|
+
},
|
|
332
|
+
async recordRun(report) {
|
|
333
|
+
runs.push(report);
|
|
334
|
+
},
|
|
335
|
+
};
|
|
336
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
// The BlobStore contract and the pieces every driver shares (FOL-126).
|
|
2
|
+
// Split out of blob-store.ts so the s3 driver (s3-blob-store.ts) and the fs
|
|
3
|
+
// driver can both use the errors and the source type without importing each
|
|
4
|
+
// other.
|
|
5
|
+
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import crypto from "node:crypto";
|
|
8
|
+
|
|
9
|
+
export class BlobNotFound extends Error {
|
|
10
|
+
readonly key: string;
|
|
11
|
+
constructor(key: string) {
|
|
12
|
+
super(`no object at ${key}`);
|
|
13
|
+
this.name = "BlobNotFound";
|
|
14
|
+
this.key = key;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** A failure the caller may retry: the network, a timeout, a 5xx, a 429, a
|
|
19
|
+
* conditional-write conflict, an expired token. Everything else (403, 400,
|
|
20
|
+
* 404, a bad bucket name) is final. */
|
|
21
|
+
export class BlobTransientError extends Error {
|
|
22
|
+
readonly status?: number;
|
|
23
|
+
/** The store's own error code when it gave one (S3: `SlowDown`, ...). */
|
|
24
|
+
readonly code?: string;
|
|
25
|
+
constructor(message: string, status?: number, code?: string) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.name = "BlobTransientError";
|
|
28
|
+
this.status = status;
|
|
29
|
+
this.code = code;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The store said no and will say no again: wrong credentials, no such bucket,
|
|
34
|
+
* a malformed request. Carries the HTTP status and the store's error code. */
|
|
35
|
+
export class BlobStoreError extends Error {
|
|
36
|
+
readonly status: number;
|
|
37
|
+
readonly code?: string;
|
|
38
|
+
constructor(message: string, status: number, code?: string) {
|
|
39
|
+
super(message);
|
|
40
|
+
this.name = "BlobStoreError";
|
|
41
|
+
this.status = status;
|
|
42
|
+
this.code = code;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The bytes being uploaded stopped matching what was announced (the file was
|
|
47
|
+
* truncated, rewritten, or does not hash to the name it was given). Not
|
|
48
|
+
* retried: reading it again would give the same answer. */
|
|
49
|
+
export class BlobSourceError extends Error {
|
|
50
|
+
constructor(message: string) {
|
|
51
|
+
super(message);
|
|
52
|
+
this.name = "BlobSourceError";
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface PutOptions {
|
|
57
|
+
contentType?: string;
|
|
58
|
+
signal?: AbortSignal;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface PutSourceOptions extends PutOptions {
|
|
62
|
+
/** Hex sha256 of the whole content, when the caller has it (a blob key is
|
|
63
|
+
* one). It is signed into the request, so the store verifies it; without it
|
|
64
|
+
* the source is read once more to find it. */
|
|
65
|
+
sha256?: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface PutResult {
|
|
69
|
+
created: boolean;
|
|
70
|
+
/** The store's ETag for the object that is there, unquoted, when it said.
|
|
71
|
+
* For a single-request upload that is the md5 of the content on S3, R2 and
|
|
72
|
+
* MinIO; for a multipart upload it is `<hash>-<parts>`. */
|
|
73
|
+
etag?: string;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface HeadResult {
|
|
77
|
+
size: number;
|
|
78
|
+
/** When the object was last written, when the store says (whole seconds on
|
|
79
|
+
* S3). The garbage collector's grace period is measured from here. NOTE: a
|
|
80
|
+
* conditional put that finds the object already there does NOT refresh it,
|
|
81
|
+
* so an old blob that a new publish reuses looks old to a sweeper — the
|
|
82
|
+
* grace period alone does not protect it (see publish.ts, "the GC window"). */
|
|
83
|
+
modifiedAt?: Date;
|
|
84
|
+
etag?: string;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* A re-readable source of bytes. Streaming upload needs to read the same bytes
|
|
89
|
+
* more than once: to hash them before they are sent, and again for every retry
|
|
90
|
+
* or resumed part. So it is a *range reader*, not a one-shot stream.
|
|
91
|
+
*/
|
|
92
|
+
export interface BlobSource {
|
|
93
|
+
readonly size: number;
|
|
94
|
+
/** The bytes [start, end) as a stream. Throws BlobSourceError if the source
|
|
95
|
+
* turns out shorter than `size`. */
|
|
96
|
+
read(start: number, end: number, signal?: AbortSignal): AsyncIterable<Uint8Array>;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* What every caller gets: create-only, read, ask. There is deliberately no
|
|
101
|
+
* overwrite and no delete here — an object is named by its content, so the only
|
|
102
|
+
* write that makes sense is "put it if it is not there", and removing one is
|
|
103
|
+
* the garbage collector's job alone (BlobSweeper, below). A missed option
|
|
104
|
+
* cannot corrupt a shared object because the option does not exist.
|
|
105
|
+
*/
|
|
106
|
+
export interface BlobStore {
|
|
107
|
+
readonly kind: "fs" | "s3";
|
|
108
|
+
/** Write only if nothing is at the key. `created: false` means it was
|
|
109
|
+
* already there; for a content-addressed key that is success. The existing
|
|
110
|
+
* object is NOT verified against `body` — callers that need that compare the
|
|
111
|
+
* returned `etag` or read it back. After a retry, `created: false` can also
|
|
112
|
+
* mean "my first attempt landed and its answer was lost". */
|
|
113
|
+
putIfAbsent(key: string, body: Uint8Array, opts?: PutOptions): Promise<PutResult>;
|
|
114
|
+
/** The same, for content that should not be held in memory: streamed from the
|
|
115
|
+
* source, and — on s3, past the multipart threshold — uploaded in parts that
|
|
116
|
+
* survive an interruption and are picked up again by the next call. */
|
|
117
|
+
putSourceIfAbsent(key: string, source: BlobSource, opts?: PutSourceOptions): Promise<PutResult>;
|
|
118
|
+
/** The object as a stream, optionally one inclusive byte range. Throws BlobNotFound. */
|
|
119
|
+
get(key: string, opts?: { range?: { start: number; end: number }; signal?: AbortSignal }): Promise<ReadableStream<Uint8Array>>;
|
|
120
|
+
head(key: string, opts?: { signal?: AbortSignal }): Promise<HeadResult | null>;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Removal. Held by the garbage collector and by tests; not passed to publish. */
|
|
124
|
+
export interface BlobSweeper {
|
|
125
|
+
/** Idempotent: a missing key is the end state asked for. */
|
|
126
|
+
delete(key: string, opts?: { signal?: AbortSignal }): Promise<void>;
|
|
127
|
+
/** Throw away uploads that were started and never finished (s3 multipart
|
|
128
|
+
* uploads; fs temp files) and are older than `olderThanMs`. Returns how many.
|
|
129
|
+
* A bucket lifecycle rule (AbortIncompleteMultipartUpload) does the same on
|
|
130
|
+
* AWS and R2; this is for stores that have none, and for tests. */
|
|
131
|
+
abortStaleUploads(opts: { olderThanMs: number; prefix?: string; signal?: AbortSignal }): Promise<number>;
|
|
132
|
+
/** An account is gone: remove everything under its prefix. Only a store that
|
|
133
|
+
* can enumerate has it (the folder one); a bucket's objects are the
|
|
134
|
+
* sweeper's once the account's pins are released. */
|
|
135
|
+
purgeTenant?(tenant: string): Promise<void>;
|
|
136
|
+
/** Every object under a key prefix, with its size and last-modified time —
|
|
137
|
+
* what the sweeper walks. */
|
|
138
|
+
list?(prefix: string, opts?: { signal?: AbortSignal }): AsyncIterable<ListedObject>;
|
|
139
|
+
/** The accounts that have objects (the first key segment under `t/`). */
|
|
140
|
+
tenants?(opts?: { signal?: AbortSignal }): Promise<string[]>;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export interface ListedObject {
|
|
144
|
+
key: string;
|
|
145
|
+
size: number;
|
|
146
|
+
modifiedAt: Date;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Read a whole object. For manifests and small blobs; a large file is
|
|
150
|
+
* streamed with `get`. */
|
|
151
|
+
export async function readAll(store: BlobStore, key: string): Promise<Buffer> {
|
|
152
|
+
const chunks: Buffer[] = [];
|
|
153
|
+
const reader = (await store.get(key)).getReader();
|
|
154
|
+
for (;;) {
|
|
155
|
+
const { done, value } = await reader.read();
|
|
156
|
+
if (done) break;
|
|
157
|
+
chunks.push(Buffer.from(value));
|
|
158
|
+
}
|
|
159
|
+
return Buffer.concat(chunks);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// ---------- keys ----------
|
|
163
|
+
|
|
164
|
+
/** A key is slash-separated safe segments. Checked in every driver, because a
|
|
165
|
+
* key reaches the fs driver as a path. */
|
|
166
|
+
export function assertKey(key: string): string {
|
|
167
|
+
if (!key || key.length > 600 || key.startsWith("/") || key.split("/").some((s) => !/^[A-Za-z0-9._=-]{1,200}$/.test(s) || s === "." || s === "..")) {
|
|
168
|
+
throw new Error(`illegal object key: ${key.slice(0, 80)}`);
|
|
169
|
+
}
|
|
170
|
+
return key;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// ---------- sources ----------
|
|
174
|
+
|
|
175
|
+
export function bufferSource(buf: Uint8Array): BlobSource {
|
|
176
|
+
return {
|
|
177
|
+
size: buf.byteLength,
|
|
178
|
+
async *read(start, end) {
|
|
179
|
+
const hi = Math.min(end, buf.byteLength);
|
|
180
|
+
// Slices of at most 1 MiB, so a consumer sees a stream either way.
|
|
181
|
+
for (let at = start; at < hi; at += 1 << 20) yield buf.subarray(at, Math.min(at + (1 << 20), hi));
|
|
182
|
+
},
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** A file on disk. The size is taken now; if the file is shorter (or longer)
|
|
187
|
+
* when it is read, the read throws BlobSourceError rather than send a body
|
|
188
|
+
* that no longer matches what was announced. */
|
|
189
|
+
export function fileSource(filePath: string): BlobSource {
|
|
190
|
+
const size = fs.statSync(filePath).size;
|
|
191
|
+
return {
|
|
192
|
+
size,
|
|
193
|
+
async *read(start, end, signal) {
|
|
194
|
+
const hi = Math.min(end, size);
|
|
195
|
+
if (hi <= start) return;
|
|
196
|
+
const stream = fs.createReadStream(filePath, { start, end: hi - 1, highWaterMark: 1 << 20, signal });
|
|
197
|
+
let got = 0;
|
|
198
|
+
for await (const chunk of stream) {
|
|
199
|
+
got += (chunk as Buffer).length;
|
|
200
|
+
yield chunk as Buffer;
|
|
201
|
+
}
|
|
202
|
+
if (got !== hi - start) throw new BlobSourceError(`${filePath} changed while it was being uploaded: expected ${hi - start} bytes at ${start}, read ${got}`);
|
|
203
|
+
},
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** sha256 (and md5, which is what a single-request ETag is) of a range. */
|
|
208
|
+
export async function hashRange(source: BlobSource, start: number, end: number, signal?: AbortSignal): Promise<{ sha256: string; md5: string }> {
|
|
209
|
+
const sha = crypto.createHash("sha256");
|
|
210
|
+
const md5 = crypto.createHash("md5");
|
|
211
|
+
for await (const chunk of source.read(start, end, signal)) {
|
|
212
|
+
sha.update(chunk);
|
|
213
|
+
md5.update(chunk);
|
|
214
|
+
}
|
|
215
|
+
return { sha256: sha.digest("hex"), md5: md5.digest("hex") };
|
|
216
|
+
}
|
package/src/evals.ts
CHANGED
|
@@ -39,7 +39,7 @@ import fs from "node:fs";
|
|
|
39
39
|
import crypto from "node:crypto";
|
|
40
40
|
import path from "node:path";
|
|
41
41
|
import { deployedCommit } from "./deploy.ts";
|
|
42
|
-
import { latestRevisionId } from "./history.ts";
|
|
42
|
+
import { latestRevisionIdLocal as latestRevisionId } from "./history.ts";
|
|
43
43
|
import matter from "./matter.ts";
|
|
44
44
|
import { spawn } from "node:child_process";
|
|
45
45
|
import { hostSafeEnv } from "./host-env.ts";
|