@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,489 @@
|
|
|
1
|
+
// The s3 BlobStore driver (FOL-126): any S3-compatible endpoint (AWS, R2,
|
|
2
|
+
// MinIO), signed by the code in storage.ts — no SDK.
|
|
3
|
+
//
|
|
4
|
+
// What it does beyond "PUT/GET with a signature", each point learnt by running
|
|
5
|
+
// it against a real server (MinIO) instead of the in-process fake:
|
|
6
|
+
//
|
|
7
|
+
// * A conditional put is `If-None-Match: *`. 412 = "already there" and the
|
|
8
|
+
// reply carries the existing object's ETag, which is returned so a caller
|
|
9
|
+
// can tell "my bytes are there" from "something else is".
|
|
10
|
+
// * 409 (ConditionalRequestConflict: another put of the same key is still in
|
|
11
|
+
// flight) is transient: the retry then sees 412.
|
|
12
|
+
// * An error is read for its S3 `<Code>`, not just its status: RequestTimeout
|
|
13
|
+
// and BadDigest come back as 400 and ARE worth retrying; NoSuchBucket,
|
|
14
|
+
// AccessDenied, SignatureDoesNotMatch are final and say so by name.
|
|
15
|
+
// * A HEAD cannot tell a missing bucket from a missing key (both 404, no
|
|
16
|
+
// body). `checkBucket()` asks the bucket itself; run it at start-up.
|
|
17
|
+
// * An upload streams from a re-readable source (no Buffer of the whole
|
|
18
|
+
// object), signed with its real payload hash so the server verifies it.
|
|
19
|
+
// * Past a threshold the upload is multipart. Nothing is kept on the local
|
|
20
|
+
// side to resume it: the next call lists the in-flight uploads for the key
|
|
21
|
+
// and the parts already there, hashes the local parts, and uploads only
|
|
22
|
+
// the ones that differ. An upload that is cancelled or fails for a final
|
|
23
|
+
// reason is aborted; one that fails for a transient reason is left to be
|
|
24
|
+
// resumed (and swept by abortStaleUploads / a bucket lifecycle rule if no
|
|
25
|
+
// one comes back).
|
|
26
|
+
|
|
27
|
+
import { s3Request, forgetS3Credentials, type S3Config, type S3StreamBody } from "./storage.ts";
|
|
28
|
+
import {
|
|
29
|
+
BlobNotFound,
|
|
30
|
+
BlobSourceError,
|
|
31
|
+
BlobStoreError,
|
|
32
|
+
BlobTransientError,
|
|
33
|
+
assertKey,
|
|
34
|
+
bufferSource,
|
|
35
|
+
hashRange,
|
|
36
|
+
type BlobStore,
|
|
37
|
+
type BlobSweeper,
|
|
38
|
+
type BlobSource,
|
|
39
|
+
type HeadResult,
|
|
40
|
+
type PutOptions,
|
|
41
|
+
type PutResult,
|
|
42
|
+
type PutSourceOptions,
|
|
43
|
+
} from "./blob-types.ts";
|
|
44
|
+
|
|
45
|
+
const MiB = 1024 * 1024;
|
|
46
|
+
/** S3's floor for every part but the last. R2 and MinIO enforce the same. */
|
|
47
|
+
export const MIN_PART_BYTES = 5 * MiB;
|
|
48
|
+
/** S3's ceiling on the number of parts. */
|
|
49
|
+
export const MAX_PARTS = 10_000;
|
|
50
|
+
|
|
51
|
+
export interface S3BlobOptions {
|
|
52
|
+
/** Objects at or above this many bytes go up as multipart. */
|
|
53
|
+
multipartThresholdBytes: number;
|
|
54
|
+
/** Size of every part but the last. Raised if the object would need more
|
|
55
|
+
* than MAX_PARTS; never below MIN_PART_BYTES. */
|
|
56
|
+
partBytes: number;
|
|
57
|
+
/** Parts in flight at once for ONE upload. */
|
|
58
|
+
partConcurrency: number;
|
|
59
|
+
/** Per-part (and per single request) deadline floor and the throughput the
|
|
60
|
+
* deadline assumes on top of it. */
|
|
61
|
+
requestDeadlineMs: number;
|
|
62
|
+
minBytesPerSec: number;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export const DEFAULT_S3_OPTIONS: S3BlobOptions = {
|
|
66
|
+
multipartThresholdBytes: 64 * MiB,
|
|
67
|
+
partBytes: 16 * MiB,
|
|
68
|
+
partConcurrency: 4,
|
|
69
|
+
requestDeadlineMs: 30_000,
|
|
70
|
+
minBytesPerSec: 1 * MiB,
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
export function s3OptionsFromEnv(env: NodeJS.ProcessEnv = process.env): S3BlobOptions {
|
|
74
|
+
const n = (v: string | undefined, d: number) => (v !== undefined && /^\d+$/.test(v) && Number(v) > 0 ? Number(v) : d);
|
|
75
|
+
const d = DEFAULT_S3_OPTIONS;
|
|
76
|
+
return {
|
|
77
|
+
multipartThresholdBytes: n(env.FOLDRUN_BLOB_MULTIPART_THRESHOLD_MB, d.multipartThresholdBytes / MiB) * MiB,
|
|
78
|
+
partBytes: Math.max(MIN_PART_BYTES, n(env.FOLDRUN_BLOB_PART_MB, d.partBytes / MiB) * MiB),
|
|
79
|
+
partConcurrency: n(env.FOLDRUN_BLOB_PART_CONCURRENCY, d.partConcurrency),
|
|
80
|
+
requestDeadlineMs: n(env.FOLDRUN_BLOB_DEADLINE_MS, d.requestDeadlineMs),
|
|
81
|
+
minBytesPerSec: d.minBytesPerSec,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The part size for an object: the configured one, raised until the object
|
|
86
|
+
* fits in MAX_PARTS parts. Every part but the last is exactly this size —
|
|
87
|
+
* R2 requires uniform parts, S3 and MinIO do not mind. */
|
|
88
|
+
export function planPartBytes(size: number, configured: number): number {
|
|
89
|
+
let p = Math.max(MIN_PART_BYTES, configured);
|
|
90
|
+
if (Math.ceil(size / p) > MAX_PARTS) p = Math.ceil(size / MAX_PARTS / MiB) * MiB;
|
|
91
|
+
return p;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Codes that arrive with a non-5xx status but are worth another try.
|
|
95
|
+
const TRANSIENT_CODES = new Set([
|
|
96
|
+
"RequestTimeout",
|
|
97
|
+
"SlowDown",
|
|
98
|
+
"InternalError",
|
|
99
|
+
"ServiceUnavailable",
|
|
100
|
+
"BadDigest", // the body changed in flight
|
|
101
|
+
"XAmzContentSHA256Mismatch", // the same, seen by MinIO
|
|
102
|
+
"ConditionalRequestConflict",
|
|
103
|
+
"OperationAborted",
|
|
104
|
+
"ExpiredToken", // role credentials; the cache is dropped before the retry
|
|
105
|
+
]);
|
|
106
|
+
const transientStatus = (s: number) => s >= 500 || s === 429 || s === 408 || s === 409;
|
|
107
|
+
|
|
108
|
+
const codeOf = (xml: string) => /<Code>([^<]+)<\/Code>/.exec(xml)?.[1];
|
|
109
|
+
// MinIO writes a quote as `"`, AWS as `"`; both must read back as `"`
|
|
110
|
+
// (a part's ETag is handed back to the store verbatim to complete the upload).
|
|
111
|
+
const unxml = (s: string) =>
|
|
112
|
+
s
|
|
113
|
+
.replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n)))
|
|
114
|
+
.replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16)))
|
|
115
|
+
.replace(/</g, "<")
|
|
116
|
+
.replace(/>/g, ">")
|
|
117
|
+
.replace(/"/g, '"')
|
|
118
|
+
.replace(/'/g, "'")
|
|
119
|
+
.replace(/&/g, "&");
|
|
120
|
+
const unquote = (etag: string | null | undefined) => (etag ? etag.replace(/^W\//, "").replace(/^"|"$/g, "") : undefined);
|
|
121
|
+
const isTimeout = (signal?: AbortSignal) => signal?.aborted === true && (signal.reason as Error | undefined)?.name === "TimeoutError";
|
|
122
|
+
|
|
123
|
+
export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}): BlobStore & BlobSweeper & { checkBucket(signal?: AbortSignal): Promise<void> } {
|
|
124
|
+
if (!cfg) throw new Error("the s3 blob store needs FOLDRUN_S3_ENDPOINT, FOLDRUN_S3_BUCKET and credentials");
|
|
125
|
+
const o: S3BlobOptions = { ...s3OptionsFromEnv(), ...given };
|
|
126
|
+
const requestDeadline = (bytes: number) => o.requestDeadlineMs + Math.ceil((bytes / o.minBytesPerSec) * 1000);
|
|
127
|
+
|
|
128
|
+
/** One signed request with the failures of the network turned into
|
|
129
|
+
* BlobTransientError, so the retry wrapper above knows what to retry. */
|
|
130
|
+
const send = async (
|
|
131
|
+
what: string,
|
|
132
|
+
method: Parameters<typeof s3Request>[1],
|
|
133
|
+
key: string,
|
|
134
|
+
body?: Buffer | S3StreamBody,
|
|
135
|
+
extra: Record<string, string> = {},
|
|
136
|
+
signal?: AbortSignal,
|
|
137
|
+
query?: Record<string, string>,
|
|
138
|
+
mime?: string,
|
|
139
|
+
): Promise<Response> => {
|
|
140
|
+
try {
|
|
141
|
+
return await s3Request(cfg, method, key, body, mime, extra, signal, query ? { query } : {});
|
|
142
|
+
} catch (err) {
|
|
143
|
+
// A source that fails while it is being sent surfaces from fetch as
|
|
144
|
+
// "fetch failed" with the real error as its cause. It is not the
|
|
145
|
+
// network's fault and a retry would read the same bytes.
|
|
146
|
+
for (let e: unknown = err, i = 0; e && i < 4; e = (e as Error).cause, i++) if (e instanceof BlobSourceError) throw e;
|
|
147
|
+
if (signal?.aborted && !isTimeout(signal)) throw err; // the caller cancelled
|
|
148
|
+
const name = (err as Error)?.name;
|
|
149
|
+
if (name === "AbortError" || name === "TimeoutError") throw new BlobTransientError(`s3 ${what}: timed out`);
|
|
150
|
+
const cause = (err as { cause?: { code?: string; message?: string } }).cause;
|
|
151
|
+
throw new BlobTransientError(`s3 ${what}: ${cause?.code ?? cause?.message ?? (err as Error)?.message ?? err}`);
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
/** Read an error reply: transient or final, with the store's code in the message. */
|
|
156
|
+
const failure = async (res: Response, what: string): Promise<Error> => {
|
|
157
|
+
const text = (await res.text().catch(() => "")).slice(0, 400);
|
|
158
|
+
const code = codeOf(text);
|
|
159
|
+
const msg = `s3 ${what} failed: ${res.status}${code ? ` ${code}` : ""} ${unxml(/<Message>([^<]*)<\/Message>/.exec(text)?.[1] ?? "").slice(0, 160)}`.trim();
|
|
160
|
+
if (code === "ExpiredToken") forgetS3Credentials();
|
|
161
|
+
if (transientStatus(res.status) || (code && TRANSIENT_CODES.has(code))) return new BlobTransientError(msg, res.status, code);
|
|
162
|
+
return new BlobStoreError(msg, res.status, code);
|
|
163
|
+
};
|
|
164
|
+
const drain = (res: Response) => res.arrayBuffer().catch(() => {});
|
|
165
|
+
|
|
166
|
+
const headObject = async (key: string, signal?: AbortSignal): Promise<HeadResult | null> => {
|
|
167
|
+
const res = await send("head", "HEAD", key, undefined, {}, signal);
|
|
168
|
+
if (res.status === 404) {
|
|
169
|
+
await drain(res);
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
if (!res.ok) throw await failure(res, "head");
|
|
173
|
+
await drain(res);
|
|
174
|
+
const size = Number(res.headers.get("content-length"));
|
|
175
|
+
const lm = res.headers.get("last-modified");
|
|
176
|
+
const etag = unquote(res.headers.get("etag"));
|
|
177
|
+
return { size: Number.isSafeInteger(size) && size >= 0 ? size : 0, ...(lm ? { modifiedAt: new Date(lm) } : {}), ...(etag ? { etag } : {}) };
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
// ---------- single request ----------
|
|
181
|
+
|
|
182
|
+
const putOnce = async (key: string, body: Buffer | S3StreamBody, mime: string | undefined, signal: AbortSignal | undefined): Promise<PutResult> => {
|
|
183
|
+
const res = await send("put", "PUT", key, body, { "if-none-match": "*" }, signal, undefined, mime);
|
|
184
|
+
if (res.status === 412) {
|
|
185
|
+
await drain(res);
|
|
186
|
+
return { created: false, ...(unquote(res.headers.get("etag")) ? { etag: unquote(res.headers.get("etag")) } : {}) };
|
|
187
|
+
}
|
|
188
|
+
if (!res.ok) throw await failure(res, "put");
|
|
189
|
+
await drain(res);
|
|
190
|
+
return { created: true, ...(unquote(res.headers.get("etag")) ? { etag: unquote(res.headers.get("etag")) } : {}) };
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
// ---------- multipart ----------
|
|
194
|
+
|
|
195
|
+
interface PartInfo {
|
|
196
|
+
etag: string; // as the store returned it, quotes and all: complete wants it back verbatim
|
|
197
|
+
size: number;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** The upload to continue, if one is open for this exact key. */
|
|
201
|
+
const findUpload = async (key: string, signal?: AbortSignal): Promise<string | null> => {
|
|
202
|
+
let keyMarker = "";
|
|
203
|
+
let uploadMarker = "";
|
|
204
|
+
for (let page = 0; page < 20; page++) {
|
|
205
|
+
const q: Record<string, string> = { uploads: "", prefix: key, "max-uploads": "1000" };
|
|
206
|
+
if (keyMarker) q["key-marker"] = keyMarker;
|
|
207
|
+
if (uploadMarker) q["upload-id-marker"] = uploadMarker;
|
|
208
|
+
const res = await send("list uploads", "GET", "", undefined, {}, signal, q);
|
|
209
|
+
if (!res.ok) throw await failure(res, "list uploads");
|
|
210
|
+
const xml = await res.text();
|
|
211
|
+
// The oldest open upload for the key: the one most likely to have parts.
|
|
212
|
+
const mine = [...xml.matchAll(/<Upload>([\s\S]*?)<\/Upload>/g)]
|
|
213
|
+
.map((m) => ({ key: unxml(/<Key>([^<]*)<\/Key>/.exec(m[1])?.[1] ?? ""), id: unxml(/<UploadId>([^<]*)<\/UploadId>/.exec(m[1])?.[1] ?? ""), at: Date.parse(/<Initiated>([^<]*)<\/Initiated>/.exec(m[1])?.[1] ?? "") || 0 }))
|
|
214
|
+
.filter((u) => u.key === key && u.id)
|
|
215
|
+
.sort((a, b) => a.at - b.at);
|
|
216
|
+
if (mine.length) return mine[0].id;
|
|
217
|
+
if (!/<IsTruncated>true<\/IsTruncated>/.test(xml)) return null;
|
|
218
|
+
keyMarker = unxml(/<NextKeyMarker>([^<]*)<\/NextKeyMarker>/.exec(xml)?.[1] ?? "");
|
|
219
|
+
uploadMarker = unxml(/<NextUploadIdMarker>([^<]*)<\/NextUploadIdMarker>/.exec(xml)?.[1] ?? "");
|
|
220
|
+
if (!keyMarker && !uploadMarker) return null;
|
|
221
|
+
}
|
|
222
|
+
return null;
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
const listParts = async (key: string, uploadId: string, signal?: AbortSignal): Promise<Map<number, PartInfo> | null> => {
|
|
226
|
+
const parts = new Map<number, PartInfo>();
|
|
227
|
+
let marker = "";
|
|
228
|
+
for (;;) {
|
|
229
|
+
const q: Record<string, string> = { uploadId, "max-parts": "1000" };
|
|
230
|
+
if (marker) q["part-number-marker"] = marker;
|
|
231
|
+
const res = await send("list parts", "GET", key, undefined, {}, signal, q);
|
|
232
|
+
if (res.status === 404) {
|
|
233
|
+
await drain(res);
|
|
234
|
+
return null; // NoSuchUpload: it was completed or aborted under us
|
|
235
|
+
}
|
|
236
|
+
if (!res.ok) throw await failure(res, "list parts");
|
|
237
|
+
const xml = await res.text();
|
|
238
|
+
for (const m of xml.matchAll(/<Part>([\s\S]*?)<\/Part>/g)) {
|
|
239
|
+
const n = Number(/<PartNumber>(\d+)<\/PartNumber>/.exec(m[1])?.[1]);
|
|
240
|
+
const size = Number(/<Size>(\d+)<\/Size>/.exec(m[1])?.[1]);
|
|
241
|
+
const etag = unxml(/<ETag>([^<]*)<\/ETag>/.exec(m[1])?.[1] ?? "");
|
|
242
|
+
if (n && etag) parts.set(n, { etag, size });
|
|
243
|
+
}
|
|
244
|
+
if (!/<IsTruncated>true<\/IsTruncated>/.test(xml)) return parts;
|
|
245
|
+
marker = /<NextPartNumberMarker>(\d+)<\/NextPartNumberMarker>/.exec(xml)?.[1] ?? "";
|
|
246
|
+
if (!marker) return parts;
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
const abortUpload = async (key: string, uploadId: string): Promise<void> => {
|
|
251
|
+
// A fresh signal: the one that got us here is probably already aborted.
|
|
252
|
+
const res = await send("abort upload", "DELETE", key, undefined, {}, AbortSignal.timeout(10_000), { uploadId }).catch(() => null);
|
|
253
|
+
if (res) await drain(res);
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
async function multipartPut(key: string, source: BlobSource, opts: PutSourceOptions): Promise<PutResult> {
|
|
257
|
+
const { signal } = opts;
|
|
258
|
+
// Already there: nothing to upload, and nothing to leave half-open.
|
|
259
|
+
const there = await headObject(key, signal);
|
|
260
|
+
if (there) return { created: false, ...(there.etag ? { etag: there.etag } : {}) };
|
|
261
|
+
|
|
262
|
+
const partBytes = planPartBytes(source.size, o.partBytes);
|
|
263
|
+
const count = Math.ceil(source.size / partBytes);
|
|
264
|
+
const range = (n: number): [number, number] => [(n - 1) * partBytes, Math.min(n * partBytes, source.size)];
|
|
265
|
+
|
|
266
|
+
let uploadId = await findUpload(key, signal);
|
|
267
|
+
let have = uploadId ? await listParts(key, uploadId, signal) : null;
|
|
268
|
+
if (!uploadId || !have) {
|
|
269
|
+
const res = await send("create upload", "POST", key, undefined, {}, signal, { uploads: "" }, opts.contentType);
|
|
270
|
+
if (!res.ok) throw await failure(res, "create upload");
|
|
271
|
+
uploadId = unxml(/<UploadId>([^<]*)<\/UploadId>/.exec(await res.text())?.[1] ?? "");
|
|
272
|
+
if (!uploadId) throw new BlobTransientError("s3 create upload: no upload id in the reply");
|
|
273
|
+
have = new Map();
|
|
274
|
+
}
|
|
275
|
+
const id = uploadId;
|
|
276
|
+
const done = new Map<number, string>(); // part number → ETag to complete with
|
|
277
|
+
|
|
278
|
+
const inner = new AbortController();
|
|
279
|
+
// The error that stopped the upload, not whichever worker's rejection
|
|
280
|
+
// happens to sit first in the pool: the siblings it aborts reject with an
|
|
281
|
+
// AbortError, which would hide a transient or final cause.
|
|
282
|
+
let firstError: { err: unknown } | null = null;
|
|
283
|
+
const both = signal ? AbortSignal.any([signal, inner.signal]) : inner.signal;
|
|
284
|
+
let next = 1;
|
|
285
|
+
const worker = async () => {
|
|
286
|
+
while (!both.aborted) {
|
|
287
|
+
const n = next++;
|
|
288
|
+
if (n > count) return;
|
|
289
|
+
const [start, end] = range(n);
|
|
290
|
+
const len = end - start;
|
|
291
|
+
// Hash first: the sha256 is signed into the request, the md5 is what a
|
|
292
|
+
// part already in the store must match to be trusted.
|
|
293
|
+
const h = await hashRange(source, start, end, both);
|
|
294
|
+
const prior = have!.get(n);
|
|
295
|
+
if (prior && prior.size === len && unquote(prior.etag) === h.md5) {
|
|
296
|
+
done.set(n, prior.etag);
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
299
|
+
const res = await send(
|
|
300
|
+
`part ${n}/${count}`,
|
|
301
|
+
"PUT",
|
|
302
|
+
key,
|
|
303
|
+
{ stream: source.read(start, end, both), length: len, sha256: h.sha256 },
|
|
304
|
+
{},
|
|
305
|
+
AbortSignal.any([both, AbortSignal.timeout(requestDeadline(len))]),
|
|
306
|
+
{ partNumber: String(n), uploadId: id },
|
|
307
|
+
);
|
|
308
|
+
if (!res.ok) throw await failure(res, `part ${n}`);
|
|
309
|
+
await drain(res);
|
|
310
|
+
const etag = res.headers.get("etag");
|
|
311
|
+
if (!etag) throw new BlobTransientError(`s3 part ${n}: no ETag in the reply`);
|
|
312
|
+
done.set(n, etag);
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
|
|
316
|
+
try {
|
|
317
|
+
const pool = Array.from({ length: Math.min(o.partConcurrency, count) }, () =>
|
|
318
|
+
worker().catch((err) => {
|
|
319
|
+
firstError ??= { err };
|
|
320
|
+
inner.abort(err); // stop the siblings
|
|
321
|
+
throw err;
|
|
322
|
+
}),
|
|
323
|
+
);
|
|
324
|
+
await Promise.allSettled(pool);
|
|
325
|
+
if (firstError) throw (firstError as { err: unknown }).err;
|
|
326
|
+
|
|
327
|
+
const xml =
|
|
328
|
+
`<CompleteMultipartUpload>` +
|
|
329
|
+
[...done.entries()]
|
|
330
|
+
.sort((a, b) => a[0] - b[0])
|
|
331
|
+
.map(([n, etag]) => `<Part><PartNumber>${n}</PartNumber><ETag>${etag.replace(/&/g, "&").replace(/</g, "<")}</ETag></Part>`)
|
|
332
|
+
.join("") +
|
|
333
|
+
`</CompleteMultipartUpload>`;
|
|
334
|
+
const res = await send("complete upload", "POST", key, Buffer.from(xml), { "if-none-match": "*" }, signal, { uploadId: id }, "application/xml");
|
|
335
|
+
if (res.status === 412) {
|
|
336
|
+
// Someone else's identical object won. Ours is not needed.
|
|
337
|
+
await drain(res);
|
|
338
|
+
await abortUpload(key, id);
|
|
339
|
+
return { created: false, ...(unquote(res.headers.get("etag")) ? { etag: unquote(res.headers.get("etag")) } : {}) };
|
|
340
|
+
}
|
|
341
|
+
if (res.status === 404) {
|
|
342
|
+
// NoSuchUpload: a twin of this call completed (or aborted) the same
|
|
343
|
+
// upload. If the object is there, the work is done.
|
|
344
|
+
await drain(res);
|
|
345
|
+
const now = await headObject(key, signal);
|
|
346
|
+
if (now) return { created: false, ...(now.etag ? { etag: now.etag } : {}) };
|
|
347
|
+
throw new BlobTransientError("s3 complete upload: the upload vanished", 404, "NoSuchUpload");
|
|
348
|
+
}
|
|
349
|
+
if (!res.ok) throw await failure(res, "complete upload");
|
|
350
|
+
// S3 can answer 200 and put the error in the body.
|
|
351
|
+
const text = await res.text();
|
|
352
|
+
if (/<Error>/.test(text)) {
|
|
353
|
+
const code = codeOf(text);
|
|
354
|
+
const msg = `s3 complete upload failed: 200 ${code ?? "error in body"}`;
|
|
355
|
+
throw code && !TRANSIENT_CODES.has(code) && code !== "NoSuchUpload" ? new BlobStoreError(msg, 200, code) : new BlobTransientError(msg, 200, code);
|
|
356
|
+
}
|
|
357
|
+
return { created: true, ...(unquote(/<ETag>([^<]*)<\/ETag>/.exec(text)?.[1]) ? { etag: unquote(unxml(/<ETag>([^<]*)<\/ETag>/.exec(text)![1])) } : {}) };
|
|
358
|
+
} catch (err) {
|
|
359
|
+
// Cancelled by the caller, or a final failure: nothing will come back to
|
|
360
|
+
// finish this, so do not leave parts for the store to bill. A transient
|
|
361
|
+
// failure (including a deadline) leaves the upload for the retry.
|
|
362
|
+
const cancelled = signal?.aborted === true && !isTimeout(signal);
|
|
363
|
+
const final = !(err instanceof BlobTransientError);
|
|
364
|
+
if (cancelled || final) await abortUpload(key, id);
|
|
365
|
+
throw err;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// ---------- the interface ----------
|
|
370
|
+
|
|
371
|
+
return {
|
|
372
|
+
kind: "s3",
|
|
373
|
+
async putIfAbsent(key, body, opts: PutOptions = {}) {
|
|
374
|
+
assertKey(key);
|
|
375
|
+
return putOnce(key, Buffer.from(body), opts.contentType, opts.signal);
|
|
376
|
+
},
|
|
377
|
+
async putSourceIfAbsent(key, source, opts: PutSourceOptions = {}) {
|
|
378
|
+
assertKey(key);
|
|
379
|
+
if (source.size >= o.multipartThresholdBytes) return multipartPut(key, source, opts);
|
|
380
|
+
const sha256 = opts.sha256 ?? (await hashRange(source, 0, source.size, opts.signal)).sha256;
|
|
381
|
+
return putOnce(key, { stream: source.read(0, source.size, opts.signal), length: source.size, sha256 }, opts.contentType, opts.signal);
|
|
382
|
+
},
|
|
383
|
+
async get(key, opts = {}) {
|
|
384
|
+
assertKey(key);
|
|
385
|
+
const res = await send("get", "GET", key, undefined, opts.range ? { range: `bytes=${opts.range.start}-${opts.range.end}` } : {}, opts.signal);
|
|
386
|
+
if (res.status === 404) {
|
|
387
|
+
const text = await res.text().catch(() => "");
|
|
388
|
+
// A GET carries the reason a HEAD cannot: the bucket may be the thing that is missing.
|
|
389
|
+
if (codeOf(text) === "NoSuchBucket") throw new BlobStoreError(`s3 get failed: 404 NoSuchBucket (${cfg.bucket})`, 404, "NoSuchBucket");
|
|
390
|
+
throw new BlobNotFound(key);
|
|
391
|
+
}
|
|
392
|
+
if (!res.ok || !res.body) throw await failure(res, "get");
|
|
393
|
+
// A connection that drops mid-body is a retryable failure, not a TypeError.
|
|
394
|
+
const reader = (res.body as ReadableStream<Uint8Array>).getReader();
|
|
395
|
+
return new ReadableStream<Uint8Array>({
|
|
396
|
+
async pull(controller) {
|
|
397
|
+
try {
|
|
398
|
+
const { done, value } = await reader.read();
|
|
399
|
+
if (done) controller.close();
|
|
400
|
+
else controller.enqueue(value);
|
|
401
|
+
} catch (err) {
|
|
402
|
+
controller.error(new BlobTransientError(`s3 get ${key}: the body was cut off (${(err as { cause?: { code?: string } }).cause?.code ?? (err as Error).message})`));
|
|
403
|
+
}
|
|
404
|
+
},
|
|
405
|
+
cancel: (reason) => reader.cancel(reason),
|
|
406
|
+
});
|
|
407
|
+
},
|
|
408
|
+
async head(key, opts = {}) {
|
|
409
|
+
assertKey(key);
|
|
410
|
+
return headObject(key, opts.signal);
|
|
411
|
+
},
|
|
412
|
+
async delete(key, opts = {}) {
|
|
413
|
+
assertKey(key);
|
|
414
|
+
const res = await send("delete", "DELETE", key, undefined, {}, opts.signal);
|
|
415
|
+
if (!res.ok && res.status !== 404) throw await failure(res, "delete");
|
|
416
|
+
await drain(res);
|
|
417
|
+
},
|
|
418
|
+
async abortStaleUploads({ olderThanMs, prefix = "", signal }) {
|
|
419
|
+
let n = 0;
|
|
420
|
+
let keyMarker = "";
|
|
421
|
+
let uploadMarker = "";
|
|
422
|
+
for (;;) {
|
|
423
|
+
const q: Record<string, string> = { uploads: "", "max-uploads": "1000", ...(prefix ? { prefix } : {}) };
|
|
424
|
+
if (keyMarker) q["key-marker"] = keyMarker;
|
|
425
|
+
if (uploadMarker) q["upload-id-marker"] = uploadMarker;
|
|
426
|
+
const res = await send("list uploads", "GET", "", undefined, {}, signal, q);
|
|
427
|
+
if (!res.ok) throw await failure(res, "list uploads");
|
|
428
|
+
const xml = await res.text();
|
|
429
|
+
for (const m of xml.matchAll(/<Upload>([\s\S]*?)<\/Upload>/g)) {
|
|
430
|
+
const key = unxml(/<Key>([^<]*)<\/Key>/.exec(m[1])?.[1] ?? "");
|
|
431
|
+
const id = unxml(/<UploadId>([^<]*)<\/UploadId>/.exec(m[1])?.[1] ?? "");
|
|
432
|
+
const at = Date.parse(/<Initiated>([^<]*)<\/Initiated>/.exec(m[1])?.[1] ?? "");
|
|
433
|
+
if (key && id && Number.isFinite(at) && Date.now() - at >= olderThanMs) {
|
|
434
|
+
await abortUpload(key, id);
|
|
435
|
+
n++;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
if (!/<IsTruncated>true<\/IsTruncated>/.test(xml)) return n;
|
|
439
|
+
keyMarker = unxml(/<NextKeyMarker>([^<]*)<\/NextKeyMarker>/.exec(xml)?.[1] ?? "");
|
|
440
|
+
uploadMarker = unxml(/<NextUploadIdMarker>([^<]*)<\/NextUploadIdMarker>/.exec(xml)?.[1] ?? "");
|
|
441
|
+
if (!keyMarker && !uploadMarker) return n;
|
|
442
|
+
}
|
|
443
|
+
},
|
|
444
|
+
async *list(prefix, opts = {}) {
|
|
445
|
+
let token: string | undefined;
|
|
446
|
+
do {
|
|
447
|
+
const q: Record<string, string> = { "list-type": "2", prefix: prefix.endsWith("/") ? prefix : `${prefix}/`, ...(token ? { "continuation-token": token } : {}) };
|
|
448
|
+
const res = await send("list", "GET", "", undefined, {}, opts.signal, q);
|
|
449
|
+
if (!res.ok) throw await failure(res, "list");
|
|
450
|
+
const xml = await res.text();
|
|
451
|
+
for (const c of xml.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)) {
|
|
452
|
+
const key = xmlText(c[1], "Key");
|
|
453
|
+
const size = Number(xmlText(c[1], "Size"));
|
|
454
|
+
const lm = xmlText(c[1], "LastModified");
|
|
455
|
+
if (key) yield { key, size: Number.isFinite(size) ? size : 0, modifiedAt: lm ? new Date(lm) : new Date(0) };
|
|
456
|
+
}
|
|
457
|
+
token = /<IsTruncated>true<\/IsTruncated>/.test(xml) ? (xmlText(xml, "NextContinuationToken") ?? undefined) : undefined;
|
|
458
|
+
} while (token);
|
|
459
|
+
},
|
|
460
|
+
async tenants(opts = {}) {
|
|
461
|
+
const out: string[] = [];
|
|
462
|
+
let token: string | undefined;
|
|
463
|
+
do {
|
|
464
|
+
const q: Record<string, string> = { "list-type": "2", prefix: "t/", delimiter: "/", ...(token ? { "continuation-token": token } : {}) };
|
|
465
|
+
const res = await send("list", "GET", "", undefined, {}, opts.signal, q);
|
|
466
|
+
if (!res.ok) throw await failure(res, "list");
|
|
467
|
+
const xml = await res.text();
|
|
468
|
+
for (const c of xml.matchAll(/<CommonPrefixes>\s*<Prefix>([^<]*)<\/Prefix>/g)) out.push(unxml(c[1]).replace(/^t\//, "").replace(/\/$/, ""));
|
|
469
|
+
token = /<IsTruncated>true<\/IsTruncated>/.test(xml) ? (xmlText(xml, "NextContinuationToken") ?? undefined) : undefined;
|
|
470
|
+
} while (token);
|
|
471
|
+
return out;
|
|
472
|
+
},
|
|
473
|
+
/** Is the bucket there, and may we use it? A HEAD on a key cannot say. */
|
|
474
|
+
async checkBucket(signal) {
|
|
475
|
+
const res = await send("head bucket", "HEAD", "", undefined, {}, signal);
|
|
476
|
+
if (res.ok) return void (await drain(res));
|
|
477
|
+
await drain(res);
|
|
478
|
+
if (res.status === 404) throw new BlobStoreError(`s3: bucket ${cfg.bucket} does not exist (or the endpoint is wrong)`, 404, "NoSuchBucket");
|
|
479
|
+
throw await failure(res, "head bucket");
|
|
480
|
+
},
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
function xmlText(xml: string, tag: string): string | null {
|
|
485
|
+
const m = new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`).exec(xml);
|
|
486
|
+
return m ? unxml(m[1]) : null;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
export { bufferSource };
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// How long `state/` checkpoints are kept (FOL-126 fixes, 8 Nov 2026).
|
|
2
|
+
//
|
|
3
|
+
// Every step of every run writes `state/` and each is a revision on the state
|
|
4
|
+
// head; the manifests are small but the blobs are whatever the state holds
|
|
5
|
+
// (indexes, caches), and the ticket's 100 × 1 GB case is a state head that
|
|
6
|
+
// never forgets. So the state head keeps a window:
|
|
7
|
+
//
|
|
8
|
+
// keep the newest N checkpoints (0: no count limit)
|
|
9
|
+
// days and none older than D days (0: no age limit)
|
|
10
|
+
//
|
|
11
|
+
// A checkpoint goes when it is outside EITHER limit, except
|
|
12
|
+
// - the head, always (it is the state);
|
|
13
|
+
// - one whose manifest something other than a revision still holds — a run
|
|
14
|
+
// staged from it (pin holder `run`), a publish in flight — checked through
|
|
15
|
+
// the same pins the sweeper obeys. It is looked at again next time.
|
|
16
|
+
//
|
|
17
|
+
// Pruning removes the revision rows and releases the pins THOSE revisions held
|
|
18
|
+
// on their manifests; it deletes no object. The objects are the sweeper's: it
|
|
19
|
+
// deletes a manifest or blob only through guardDelete, and only when no pin is
|
|
20
|
+
// left. A manifest two checkpoints share (an unchanged state) keeps the other
|
|
21
|
+
// checkpoint's pin.
|
|
22
|
+
//
|
|
23
|
+
// The workspace head (authored files) is not pruned: that is the history page.
|
|
24
|
+
|
|
25
|
+
import type { Deps } from "./publish.ts";
|
|
26
|
+
import type { WorkspaceRef } from "./revision-store.ts";
|
|
27
|
+
|
|
28
|
+
export interface StateRetention {
|
|
29
|
+
keep: number;
|
|
30
|
+
days: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface PruneResult {
|
|
34
|
+
pruned: number;
|
|
35
|
+
kept: number;
|
|
36
|
+
/** Outside the window but held by a run or a publish: left for next time. */
|
|
37
|
+
held: number;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const PAGE = 500;
|
|
41
|
+
|
|
42
|
+
export async function pruneStateRevisions(
|
|
43
|
+
deps: Deps,
|
|
44
|
+
ws: { tenant: string; workspace: string },
|
|
45
|
+
policy: StateRetention,
|
|
46
|
+
now: number = Date.now(),
|
|
47
|
+
): Promise<PruneResult> {
|
|
48
|
+
const keep = Math.max(0, Math.floor(policy.keep || 0));
|
|
49
|
+
const days = Math.max(0, policy.days || 0);
|
|
50
|
+
const out: PruneResult = { pruned: 0, kept: 0, held: 0 };
|
|
51
|
+
if (keep === 0 && days === 0) return out;
|
|
52
|
+
const sws: WorkspaceRef = { tenant: ws.tenant, workspace: ws.workspace, scope: "state" };
|
|
53
|
+
const cutoff = days > 0 ? now - days * 86_400_000 : -Infinity;
|
|
54
|
+
const doomed: string[] = [];
|
|
55
|
+
let seen = 0;
|
|
56
|
+
let before: number | undefined;
|
|
57
|
+
for (;;) {
|
|
58
|
+
const page = await deps.revisions.revisions(sws, { limit: PAGE, before });
|
|
59
|
+
if (!page.length) break;
|
|
60
|
+
for (const r of page) {
|
|
61
|
+
const index = seen++;
|
|
62
|
+
if (index === 0) {
|
|
63
|
+
out.kept++; // the head
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
const outside = (keep > 0 && index >= keep) || Date.parse(r.at) < cutoff;
|
|
67
|
+
if (!outside) {
|
|
68
|
+
out.kept++;
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (deps.pins && (await deps.pins.isPinnedBeyondRevisions(ws.tenant, "manifest", r.state))) {
|
|
72
|
+
out.held++;
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
doomed.push(r.id);
|
|
76
|
+
}
|
|
77
|
+
before = page[page.length - 1].seq;
|
|
78
|
+
if (page.length < PAGE) break;
|
|
79
|
+
}
|
|
80
|
+
// In slices: one statement per slice, never an unbounded list.
|
|
81
|
+
for (let i = 0; i < doomed.length; i += 200) out.pruned += await deps.revisions.prune(sws, doomed.slice(i, i + 200));
|
|
82
|
+
return out;
|
|
83
|
+
}
|