@foldrun/core 17.3.0 → 18.0.0

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