@foldrun/core 17.4.0 → 18.0.1
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/blob-cache.js +8 -5
- package/dist/src/blob-store.js +5 -0
- package/dist/src/blob-sweeper.js +69 -41
- package/dist/src/history.d.ts +7 -1
- package/dist/src/history.js +45 -13
- package/dist/src/s3-blob-store.js +89 -16
- package/dist/src/translator.d.ts +7 -0
- package/dist/src/translator.js +30 -0
- package/dist/src/workspace-revisions.d.ts +12 -2
- package/dist/src/workspace-revisions.js +150 -42
- package/package.json +1 -1
- package/src/blob-cache.ts +8 -5
- package/src/blob-store.ts +4 -0
- package/src/blob-sweeper.ts +62 -34
- package/src/history.ts +55 -14
- package/src/s3-blob-store.ts +86 -15
- package/src/translator.ts +28 -0
- package/src/workspace-revisions.ts +139 -40
package/dist/src/blob-cache.js
CHANGED
|
@@ -181,13 +181,15 @@ export function blobCache(opts) {
|
|
|
181
181
|
function startFill(k, tenant, sha, f) {
|
|
182
182
|
return gate(async () => {
|
|
183
183
|
inFlight++;
|
|
184
|
-
|
|
184
|
+
// downloadToFile writes `<dl>.part` and renames it to `dl` once the hash
|
|
185
|
+
// matched; `dl` is then renamed into the cache. Both names are removed
|
|
186
|
+
// below whatever happens: a fill that failed (a final error, retries
|
|
187
|
+
// spent) would otherwise leave its bytes in tmp/, outside the count
|
|
188
|
+
// that maxBytes holds, until the next start-up sweep.
|
|
189
|
+
const dl = path.join(tmpDir, `${tenant}-${sha}.${process.pid}.dl`);
|
|
185
190
|
try {
|
|
186
191
|
const final = fileOf(tenant, sha);
|
|
187
192
|
fs.mkdirSync(path.dirname(final), { recursive: true });
|
|
188
|
-
// downloadToFile resumes a cut body with a Range and checks the hash
|
|
189
|
-
// before it renames `part` to its name; nothing is left on a mismatch.
|
|
190
|
-
const dl = `${part}.dl`;
|
|
191
193
|
const { size } = await downloadToFile(store, blobObjectKey(tenant, sha), dl, { sha256: sha });
|
|
192
194
|
fs.renameSync(dl, final);
|
|
193
195
|
const e = { size, pins: f.waiters, tick: ++tick };
|
|
@@ -203,7 +205,8 @@ export function blobCache(opts) {
|
|
|
203
205
|
}
|
|
204
206
|
finally {
|
|
205
207
|
inFlight--;
|
|
206
|
-
fs.rmSync(part
|
|
208
|
+
fs.rmSync(`${dl}.part`, { force: true });
|
|
209
|
+
fs.rmSync(dl, { force: true });
|
|
207
210
|
}
|
|
208
211
|
});
|
|
209
212
|
}
|
package/dist/src/blob-store.js
CHANGED
|
@@ -205,6 +205,11 @@ export async function downloadToFile(store, key, dest, opts = {}) {
|
|
|
205
205
|
continue;
|
|
206
206
|
}
|
|
207
207
|
}
|
|
208
|
+
else if (have === 0) {
|
|
209
|
+
// An empty object: nothing to fetch, but the file must still exist to
|
|
210
|
+
// be checked and renamed into place like any other.
|
|
211
|
+
fs.writeFileSync(part, "");
|
|
212
|
+
}
|
|
208
213
|
if (fs.statSync(part).size !== size) {
|
|
209
214
|
if (attempt + 1 >= max)
|
|
210
215
|
throw new BlobTransientError(`download of ${key} stopped short`);
|
package/dist/src/blob-sweeper.js
CHANGED
|
@@ -26,8 +26,15 @@
|
|
|
26
26
|
// Refusals (nothing deleted, said in the report): the store cannot list; the
|
|
27
27
|
// database holds no revision at all while the bucket holds objects (a wiped or
|
|
28
28
|
// not-yet-restored database); a retained manifest cannot be read (its blobs are
|
|
29
|
-
// unknown).
|
|
30
|
-
//
|
|
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.
|
|
31
38
|
//
|
|
32
39
|
// An account that was deleted needs no special case: its rows and pins are gone,
|
|
33
40
|
// so everything under its prefix is unreferenced, waits the delay, and goes.
|
|
@@ -53,15 +60,17 @@ export async function sweepBlobs(deps, marks, opts) {
|
|
|
53
60
|
if (!opts.allowEmpty && tenants.length && !(await deps.revisions.anyRevisions())) {
|
|
54
61
|
return refuse(rep, "the database holds no revision but the store holds objects: not deleting on that evidence");
|
|
55
62
|
}
|
|
56
|
-
let budget = Math.max(0, opts.maxDeletes);
|
|
57
63
|
for (const tenant of tenants) {
|
|
58
64
|
if (!TENANT.test(tenant)) {
|
|
59
65
|
rep.foreign++;
|
|
60
66
|
continue;
|
|
61
67
|
}
|
|
62
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);
|
|
63
72
|
try {
|
|
64
|
-
|
|
73
|
+
await sweepTenant(deps, marks, opts, tenant, rep, budget);
|
|
65
74
|
}
|
|
66
75
|
catch (err) {
|
|
67
76
|
rep.errors++;
|
|
@@ -77,6 +86,8 @@ function refuse(rep, why) {
|
|
|
77
86
|
opsLog("warn", "blobs.sweep_refused", { reason: why, dryRun: rep.dryRun });
|
|
78
87
|
return rep;
|
|
79
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. */
|
|
80
91
|
async function sweepTenant(deps, marks, opts, tenant, rep, budget) {
|
|
81
92
|
const { blobs, revisions, pins } = deps;
|
|
82
93
|
const started = await marks.now();
|
|
@@ -158,55 +169,72 @@ async function sweepTenant(deps, marks, opts, tenant, rep, budget) {
|
|
|
158
169
|
}
|
|
159
170
|
}
|
|
160
171
|
// ---- sweep
|
|
172
|
+
due.sort((a, b) => (a.kind === b.kind ? 0 : a.kind === "blob" ? -1 : 1)); // blobs before manifests
|
|
161
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.
|
|
162
176
|
rep.wouldDelete += Math.min(due.length, budget);
|
|
163
177
|
rep.wouldDeleteBytes += due.slice(0, budget).reduce((a, o) => a + o.size, 0);
|
|
164
|
-
return
|
|
178
|
+
return;
|
|
165
179
|
}
|
|
166
180
|
let did = 0;
|
|
167
181
|
const since = new Date(started.getTime() - 60_000);
|
|
168
182
|
const newlyLive = new Map(); // manifest id → its blobs, for revisions made since the mark began
|
|
169
183
|
const gone = { blob: [], manifest: [] };
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
if (
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
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);
|
|
190
215
|
}
|
|
191
|
-
|
|
216
|
+
if (set.has(o.ref))
|
|
217
|
+
return void rep.skippedHeld++;
|
|
192
218
|
}
|
|
193
|
-
if (set.has(o.ref))
|
|
194
|
-
return void rep.skippedHeld++;
|
|
195
219
|
}
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
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;
|
|
205
236
|
}
|
|
206
|
-
|
|
207
|
-
if (gone[kind].length)
|
|
208
|
-
await marks.clear(tenant, kind, gone[kind]);
|
|
209
|
-
return did;
|
|
237
|
+
await clearGone();
|
|
210
238
|
}
|
|
211
239
|
const NO_GUARD = {
|
|
212
240
|
async guardDelete(_t, _k, _r, del) {
|
package/dist/src/history.d.ts
CHANGED
|
@@ -132,16 +132,22 @@ export declare function changedPathsBetweenLocal(tenant: string, scope: string,
|
|
|
132
132
|
* to when nothing more specific (a deployed commit) is on record. */
|
|
133
133
|
export declare function latestRevisionIdLocal(tenant: string, scope: string): string | null;
|
|
134
134
|
export interface RevisionView {
|
|
135
|
-
/** Newest first, or null when revisions do not serve this scope.
|
|
135
|
+
/** Newest first, or null when revisions do not serve this scope. Every page
|
|
136
|
+
* of the store up to `limit` (Infinity: all of it); `paths: false` leaves
|
|
137
|
+
* the changed paths out (rows say []), which is what makes "all" cheap. */
|
|
136
138
|
list(tenant: string, scope: string, opts: {
|
|
137
139
|
forPath?: string;
|
|
138
140
|
limit?: number;
|
|
141
|
+
paths?: boolean;
|
|
139
142
|
}): Promise<RevisionSummary[] | null>;
|
|
140
143
|
read(tenant: string, scope: string, id: string, forPath?: string): Promise<Revision | null>;
|
|
141
144
|
snapshot(tenant: string, scope: string, id: string): Promise<{
|
|
142
145
|
path: string;
|
|
143
146
|
content: string;
|
|
144
147
|
}[] | null>;
|
|
148
|
+
/** One revision by id, looked up rather than listed (paths []); null when
|
|
149
|
+
* the store has none. Optional: a view without it is asked through `list`. */
|
|
150
|
+
get?(tenant: string, scope: string, id: string): Promise<RevisionSummary | null>;
|
|
145
151
|
}
|
|
146
152
|
export declare function registerRevisionView(v: RevisionView | null): void;
|
|
147
153
|
export declare function listRevisions(tenant: string, scope: string, opts?: {
|
package/dist/src/history.js
CHANGED
|
@@ -297,6 +297,11 @@ export function resolveRevisionLocal(tenant, scope, to, now = Date.now()) {
|
|
|
297
297
|
}
|
|
298
298
|
/** The pick of resolveRevision over a newest-first list of restorable revisions. */
|
|
299
299
|
function resolveIn(all, to, now) {
|
|
300
|
+
return pick(all, target(to, now));
|
|
301
|
+
}
|
|
302
|
+
/** What a restore's `to` names: a moment, or an id (or a commit). Throws 400
|
|
303
|
+
* on something that is neither. */
|
|
304
|
+
function target(to, now) {
|
|
300
305
|
const t = to.trim();
|
|
301
306
|
if (!t || t.startsWith("-"))
|
|
302
307
|
throw Object.assign(new Error(`not a revision or a time: ${to}`), { status: 400 });
|
|
@@ -306,15 +311,22 @@ function resolveIn(all, to, now) {
|
|
|
306
311
|
: /^\d{4}-\d{2}-\d{2}/.test(t)
|
|
307
312
|
? Date.parse(t)
|
|
308
313
|
: null;
|
|
309
|
-
let hit;
|
|
310
314
|
if (moment !== null) {
|
|
311
315
|
if (Number.isNaN(moment))
|
|
312
316
|
throw Object.assign(new Error(`not a date: ${to}`), { status: 400 });
|
|
313
|
-
|
|
317
|
+
return { moment };
|
|
318
|
+
}
|
|
319
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/.test(t))
|
|
320
|
+
throw Object.assign(new Error(`not a revision or a time: ${to}`), { status: 400 });
|
|
321
|
+
return { id: t };
|
|
322
|
+
}
|
|
323
|
+
function pick(all, want) {
|
|
324
|
+
let hit;
|
|
325
|
+
if ("moment" in want) {
|
|
326
|
+
hit = all.find((r) => Date.parse(r.at) <= want.moment);
|
|
314
327
|
}
|
|
315
328
|
else {
|
|
316
|
-
|
|
317
|
-
throw Object.assign(new Error(`not a revision or a time: ${to}`), { status: 400 });
|
|
329
|
+
const t = want.id;
|
|
318
330
|
// An exact id first, then a commit: a commit deployed twice is recorded
|
|
319
331
|
// once under its own id and again under a fresh one naming it (30 Oct
|
|
320
332
|
// 2026, recordRevision), and newest-first with one predicate answered
|
|
@@ -442,20 +454,26 @@ let view = null;
|
|
|
442
454
|
export function registerRevisionView(v) {
|
|
443
455
|
view = v;
|
|
444
456
|
}
|
|
445
|
-
/** Revisions first, then the local entries older than the oldest of them.
|
|
446
|
-
|
|
457
|
+
/** Revisions first, then the local entries older than the oldest of them.
|
|
458
|
+
* `stored` is which rows came from the store (every one a restore point). */
|
|
459
|
+
async function combinedRows(tenant, scope, opts, restorableOnly = false) {
|
|
447
460
|
const limit = opts.limit ?? 200;
|
|
448
|
-
|
|
461
|
+
// The whole of `limit`, every page of it: the store's first page is not all
|
|
462
|
+
// of history (FOL-152).
|
|
463
|
+
const mine = view && scope !== "@library" ? await view.list(tenant, scope, { ...opts, limit }) : null;
|
|
449
464
|
let local = listRevisionsLocal(tenant, scope, { forPath: opts.forPath, limit: Infinity });
|
|
450
465
|
if (restorableOnly) {
|
|
451
466
|
const have = snapshotIds(tenant, scope);
|
|
452
467
|
local = local.filter((r) => have.has(r.id));
|
|
453
468
|
}
|
|
454
469
|
if (!mine || !mine.length)
|
|
455
|
-
return local.slice(0, limit);
|
|
470
|
+
return { rows: local.slice(0, limit), stored: new Set() };
|
|
456
471
|
const oldest = mine[mine.length - 1].at;
|
|
457
472
|
const seen = new Set(mine.map((r) => r.id));
|
|
458
|
-
return [...mine, ...local.filter((r) => !seen.has(r.id) && r.at < oldest)].slice(0, limit);
|
|
473
|
+
return { rows: [...mine, ...local.filter((r) => !seen.has(r.id) && r.at < oldest)].slice(0, limit), stored: seen };
|
|
474
|
+
}
|
|
475
|
+
async function combined(tenant, scope, opts, restorableOnly = false) {
|
|
476
|
+
return (await combinedRows(tenant, scope, opts, restorableOnly)).rows;
|
|
459
477
|
}
|
|
460
478
|
export async function listRevisions(tenant, scope, opts = {}) {
|
|
461
479
|
return combined(tenant, scope, opts);
|
|
@@ -465,9 +483,8 @@ export async function listRevisions(tenant, scope, opts = {}) {
|
|
|
465
483
|
* a local entry is when it has a snapshot — where asking per row would list
|
|
466
484
|
* the store once per row. */
|
|
467
485
|
export async function listRevisionsRestorable(tenant, scope, opts = {}) {
|
|
468
|
-
const rows = await
|
|
486
|
+
const { rows, stored } = await combinedRows(tenant, scope, opts);
|
|
469
487
|
const have = snapshotIds(tenant, scope);
|
|
470
|
-
const stored = view && scope !== "@library" ? new Set(((await view.list(tenant, scope, { limit: 500 })) ?? []).map((r) => r.id)) : new Set();
|
|
471
488
|
return rows.map((r) => ({ ...r, restorable: have.has(r.id) || stored.has(r.id) }));
|
|
472
489
|
}
|
|
473
490
|
export async function readRevision(tenant, scope, id, forPath) {
|
|
@@ -484,13 +501,28 @@ export async function hasSnapshot(tenant, scope, id) {
|
|
|
484
501
|
assertSafeName(id, "revision id");
|
|
485
502
|
if (hasSnapshotLocal(tenant, scope, id))
|
|
486
503
|
return true;
|
|
487
|
-
|
|
504
|
+
if (!view || scope === "@library")
|
|
505
|
+
return false;
|
|
506
|
+
// Looked up by id: a listing stops at a page, and a revision older than it
|
|
507
|
+
// was "not restorable" until 9 Nov 2026 (FOL-152).
|
|
508
|
+
if (view.get)
|
|
509
|
+
return (await view.get(tenant, scope, id)) !== null;
|
|
510
|
+
return Boolean((await view.list(tenant, scope, { limit: Infinity, paths: false }))?.some((r) => r.id === id));
|
|
488
511
|
}
|
|
489
512
|
export async function headRevision(tenant, scope) {
|
|
490
513
|
return (await combined(tenant, scope, { limit: 1 }, true))[0] ?? null;
|
|
491
514
|
}
|
|
492
515
|
export async function resolveRevision(tenant, scope, to, now = Date.now()) {
|
|
493
|
-
|
|
516
|
+
const want = target(to, now);
|
|
517
|
+
// An id in the store is one lookup; anything else (a date, a local id, a
|
|
518
|
+
// commit) is answered from ALL of history — every page of the store, without
|
|
519
|
+
// the changed paths, then the local entries.
|
|
520
|
+
if ("id" in want && view?.get && scope !== "@library") {
|
|
521
|
+
const hit = await view.get(tenant, scope, want.id);
|
|
522
|
+
if (hit)
|
|
523
|
+
return { id: hit.id, at: hit.at, by: hit.by, message: hit.message };
|
|
524
|
+
}
|
|
525
|
+
return pick(await combined(tenant, scope, { limit: Infinity, paths: false }, true), want);
|
|
494
526
|
}
|
|
495
527
|
export async function changedPathsBetween(tenant, scope, from, to) {
|
|
496
528
|
if (!from || !to)
|
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
// reason is aborted; one that fails for a transient reason is left to be
|
|
24
24
|
// resumed (and swept by abortStaleUploads / a bucket lifecycle rule if no
|
|
25
25
|
// one comes back).
|
|
26
|
+
import crypto from "node:crypto";
|
|
26
27
|
import { s3Request, forgetS3Credentials } from "./storage.js";
|
|
27
28
|
import { BlobNotFound, BlobSourceError, BlobStoreError, BlobTransientError, assertKey, bufferSource, hashRange, } from "./blob-types.js";
|
|
28
29
|
const MiB = 1024 * 1024;
|
|
@@ -30,6 +31,7 @@ const MiB = 1024 * 1024;
|
|
|
30
31
|
export const MIN_PART_BYTES = 5 * MiB;
|
|
31
32
|
/** S3's ceiling on the number of parts. */
|
|
32
33
|
export const MAX_PARTS = 10_000;
|
|
34
|
+
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
33
35
|
export const DEFAULT_S3_OPTIONS = {
|
|
34
36
|
multipartThresholdBytes: 64 * MiB,
|
|
35
37
|
partBytes: 16 * MiB,
|
|
@@ -87,12 +89,26 @@ export function s3BlobStore(cfg, given = {}) {
|
|
|
87
89
|
if (!cfg)
|
|
88
90
|
throw new Error("the s3 blob store needs FOLDRUN_S3_ENDPOINT, FOLDRUN_S3_BUCKET and credentials");
|
|
89
91
|
const o = { ...s3OptionsFromEnv(), ...given };
|
|
90
|
-
|
|
92
|
+
// Clamped to the longest timer Node keeps: past 2^31-1 ms it fires after
|
|
93
|
+
// 1 ms instead, which would cut off the complete of a multi-TiB object.
|
|
94
|
+
const requestDeadline = (bytes) => Math.min(MAX_TIMER_MS, o.requestDeadlineMs + Math.ceil((bytes / o.minBytesPerSec) * 1000));
|
|
91
95
|
/** One signed request with the failures of the network turned into
|
|
92
|
-
* BlobTransientError, so the retry wrapper above knows what to retry.
|
|
93
|
-
|
|
96
|
+
* BlobTransientError, so the retry wrapper above knows what to retry.
|
|
97
|
+
*
|
|
98
|
+
* Every request carries this driver's own deadline (its floor plus its body
|
|
99
|
+
* at minBytesPerSec) on top of the caller's signal. bounded() leaves a
|
|
100
|
+
* streamed put to the driver, so without it a server that accepts the
|
|
101
|
+
* connection and never answers would hold the single PUT, or a multipart
|
|
102
|
+
* HEAD, list, create or complete, for as long as the caller's signal lets
|
|
103
|
+
* it — forever when there is none. `sizedBy` overrides the bytes the
|
|
104
|
+
* deadline is sized by (a complete, whose small body stands for a whole
|
|
105
|
+
* object the store has to assemble). A GET passes `false`: its signal also
|
|
106
|
+
* bounds reading the body, which is the caller's to bound. */
|
|
107
|
+
const send = async (what, method, key, body, extra = {}, signal, query, mime, sizedBy) => {
|
|
108
|
+
const ms = requestDeadline(sizedBy === undefined || sizedBy === false ? (body?.length ?? 0) : sizedBy);
|
|
109
|
+
const bound = sizedBy === false ? signal : signal ? AbortSignal.any([signal, AbortSignal.timeout(ms)]) : AbortSignal.timeout(ms);
|
|
94
110
|
try {
|
|
95
|
-
return await s3Request(cfg, method, key, body, mime, extra,
|
|
111
|
+
return await s3Request(cfg, method, key, body, mime, extra, bound, query ? { query } : {});
|
|
96
112
|
}
|
|
97
113
|
catch (err) {
|
|
98
114
|
// A source that fails while it is being sent surfaces from fetch as
|
|
@@ -103,6 +119,8 @@ export function s3BlobStore(cfg, given = {}) {
|
|
|
103
119
|
throw e;
|
|
104
120
|
if (signal?.aborted && !isTimeout(signal))
|
|
105
121
|
throw err; // the caller cancelled
|
|
122
|
+
if (bound?.aborted && isTimeout(bound))
|
|
123
|
+
throw new BlobTransientError(`s3 ${what}: no answer within ${ms}ms`);
|
|
106
124
|
const name = err?.name;
|
|
107
125
|
if (name === "AbortError" || name === "TimeoutError")
|
|
108
126
|
throw new BlobTransientError(`s3 ${what}: timed out`);
|
|
@@ -122,6 +140,21 @@ export function s3BlobStore(cfg, given = {}) {
|
|
|
122
140
|
return new BlobStoreError(msg, res.status, code);
|
|
123
141
|
};
|
|
124
142
|
const drain = (res) => res.arrayBuffer().catch(() => { });
|
|
143
|
+
/** A reply's body. The request's deadline still runs while it is read, and
|
|
144
|
+
* a deadline or a dropped connection here is as transient as one before
|
|
145
|
+
* the headers came. */
|
|
146
|
+
const textOf = async (res, what) => {
|
|
147
|
+
try {
|
|
148
|
+
return await res.text();
|
|
149
|
+
}
|
|
150
|
+
catch (err) {
|
|
151
|
+
if (err?.name === "TimeoutError")
|
|
152
|
+
throw new BlobTransientError(`s3 ${what}: timed out reading the reply`);
|
|
153
|
+
if (err instanceof TypeError)
|
|
154
|
+
throw new BlobTransientError(`s3 ${what}: the reply was cut off (${err.cause?.code ?? err.message})`);
|
|
155
|
+
throw err;
|
|
156
|
+
}
|
|
157
|
+
};
|
|
125
158
|
const headObject = async (key, signal) => {
|
|
126
159
|
const res = await send("head", "HEAD", key, undefined, {}, signal);
|
|
127
160
|
if (res.status === 404) {
|
|
@@ -161,7 +194,7 @@ export function s3BlobStore(cfg, given = {}) {
|
|
|
161
194
|
const res = await send("list uploads", "GET", "", undefined, {}, signal, q);
|
|
162
195
|
if (!res.ok)
|
|
163
196
|
throw await failure(res, "list uploads");
|
|
164
|
-
const xml = await res
|
|
197
|
+
const xml = await textOf(res, "list uploads");
|
|
165
198
|
// The oldest open upload for the key: the one most likely to have parts.
|
|
166
199
|
const mine = [...xml.matchAll(/<Upload>([\s\S]*?)<\/Upload>/g)]
|
|
167
200
|
.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 }))
|
|
@@ -192,7 +225,7 @@ export function s3BlobStore(cfg, given = {}) {
|
|
|
192
225
|
}
|
|
193
226
|
if (!res.ok)
|
|
194
227
|
throw await failure(res, "list parts");
|
|
195
|
-
const xml = await res
|
|
228
|
+
const xml = await textOf(res, "list parts");
|
|
196
229
|
for (const m of xml.matchAll(/<Part>([\s\S]*?)<\/Part>/g)) {
|
|
197
230
|
const n = Number(/<PartNumber>(\d+)<\/PartNumber>/.exec(m[1])?.[1]);
|
|
198
231
|
const size = Number(/<Size>(\d+)<\/Size>/.exec(m[1])?.[1]);
|
|
@@ -228,7 +261,7 @@ export function s3BlobStore(cfg, given = {}) {
|
|
|
228
261
|
const res = await send("create upload", "POST", key, undefined, {}, signal, { uploads: "" }, opts.contentType);
|
|
229
262
|
if (!res.ok)
|
|
230
263
|
throw await failure(res, "create upload");
|
|
231
|
-
uploadId = unxml(/<UploadId>([^<]*)<\/UploadId>/.exec(await res
|
|
264
|
+
uploadId = unxml(/<UploadId>([^<]*)<\/UploadId>/.exec(await textOf(res, "create upload"))?.[1] ?? "");
|
|
232
265
|
if (!uploadId)
|
|
233
266
|
throw new BlobTransientError("s3 create upload: no upload id in the reply");
|
|
234
267
|
have = new Map();
|
|
@@ -241,6 +274,33 @@ export function s3BlobStore(cfg, given = {}) {
|
|
|
241
274
|
// AbortError, which would hide a transient or final cause.
|
|
242
275
|
let firstError = null;
|
|
243
276
|
const both = signal ? AbortSignal.any([signal, inner.signal]) : inner.signal;
|
|
277
|
+
// Each part is checked against the bytes read for it (the sha256 signed
|
|
278
|
+
// into its PUT, or the md5 a part already in the store must match), but
|
|
279
|
+
// that alone says nothing about the object: a file that changed after the
|
|
280
|
+
// caller hashed it would go up whole and consistent under the OLD content
|
|
281
|
+
// address. So the same reads also feed one sha256 of the whole object,
|
|
282
|
+
// compared with opts.sha256 before the upload is completed. A sha256
|
|
283
|
+
// cannot be put together from the parts' own, so the reads have to reach
|
|
284
|
+
// it in order: each part's hash pass waits for the one before it.
|
|
285
|
+
// Workers take part numbers in order, so chaining their passes keeps it,
|
|
286
|
+
// and the uploads still overlap. A part reused from an earlier attempt is
|
|
287
|
+
// read and hashed like the others, so a resumed upload is covered too.
|
|
288
|
+
const whole = opts.sha256 ? crypto.createHash("sha256") : null;
|
|
289
|
+
let hashed = Promise.resolve();
|
|
290
|
+
const hashPart = (start, end) => {
|
|
291
|
+
const pass = hashed.then(async () => {
|
|
292
|
+
const sha = crypto.createHash("sha256");
|
|
293
|
+
const md5 = crypto.createHash("md5");
|
|
294
|
+
for await (const chunk of source.read(start, end, both)) {
|
|
295
|
+
sha.update(chunk);
|
|
296
|
+
md5.update(chunk);
|
|
297
|
+
whole?.update(chunk);
|
|
298
|
+
}
|
|
299
|
+
return { sha256: sha.digest("hex"), md5: md5.digest("hex") };
|
|
300
|
+
});
|
|
301
|
+
hashed = pass; // a failed pass fails the ones after it: the upload is over anyway
|
|
302
|
+
return pass;
|
|
303
|
+
};
|
|
244
304
|
let next = 1;
|
|
245
305
|
const worker = async () => {
|
|
246
306
|
while (!both.aborted) {
|
|
@@ -250,14 +310,17 @@ export function s3BlobStore(cfg, given = {}) {
|
|
|
250
310
|
const [start, end] = range(n);
|
|
251
311
|
const len = end - start;
|
|
252
312
|
// Hash first: the sha256 is signed into the request, the md5 is what a
|
|
253
|
-
// part already in the store must match to be trusted.
|
|
254
|
-
|
|
313
|
+
// part already in the store must match to be trusted. (No await
|
|
314
|
+
// between taking `n` and queueing its pass: that is what keeps the
|
|
315
|
+
// whole-object hash in order.)
|
|
316
|
+
const h = await hashPart(start, end);
|
|
255
317
|
const prior = have.get(n);
|
|
256
318
|
if (prior && prior.size === len && unquote(prior.etag) === h.md5) {
|
|
257
319
|
done.set(n, prior.etag);
|
|
258
320
|
continue;
|
|
259
321
|
}
|
|
260
|
-
const res = await send(`part ${n}/${count}`, "PUT", key, { stream: source.read(start, end, both), length: len, sha256: h.sha256 }, {},
|
|
322
|
+
const res = await send(`part ${n}/${count}`, "PUT", key, { stream: source.read(start, end, both), length: len, sha256: h.sha256 }, {}, both, // send() adds the part's deadline, sized by its length
|
|
323
|
+
{ partNumber: String(n), uploadId: id });
|
|
261
324
|
if (!res.ok)
|
|
262
325
|
throw await failure(res, `part ${n}`);
|
|
263
326
|
await drain(res);
|
|
@@ -276,13 +339,23 @@ export function s3BlobStore(cfg, given = {}) {
|
|
|
276
339
|
await Promise.allSettled(pool);
|
|
277
340
|
if (firstError)
|
|
278
341
|
throw firstError.err;
|
|
342
|
+
// Every part went through hashPart, in order: `whole` is the object the
|
|
343
|
+
// store would assemble. Not the bytes asked for means not this key —
|
|
344
|
+
// a final failure, so the catch below aborts the upload.
|
|
345
|
+
if (whole) {
|
|
346
|
+
const got = whole.digest("hex");
|
|
347
|
+
if (got !== opts.sha256)
|
|
348
|
+
throw new BlobSourceError(`the bytes for ${key} do not hash to ${opts.sha256} (they hash to ${got}): the source changed after it was hashed`);
|
|
349
|
+
}
|
|
279
350
|
const xml = `<CompleteMultipartUpload>` +
|
|
280
351
|
[...done.entries()]
|
|
281
352
|
.sort((a, b) => a[0] - b[0])
|
|
282
353
|
.map(([n, etag]) => `<Part><PartNumber>${n}</PartNumber><ETag>${etag.replace(/&/g, "&").replace(/</g, "<")}</ETag></Part>`)
|
|
283
354
|
.join("") +
|
|
284
355
|
`</CompleteMultipartUpload>`;
|
|
285
|
-
|
|
356
|
+
// Assembling the parts takes the store longer the bigger the object
|
|
357
|
+
// (AWS warns of minutes), so its deadline is sized by the object.
|
|
358
|
+
const res = await send("complete upload", "POST", key, Buffer.from(xml), { "if-none-match": "*" }, signal, { uploadId: id }, "application/xml", source.size);
|
|
286
359
|
if (res.status === 412) {
|
|
287
360
|
// Someone else's identical object won. Ours is not needed.
|
|
288
361
|
await drain(res);
|
|
@@ -301,7 +374,7 @@ export function s3BlobStore(cfg, given = {}) {
|
|
|
301
374
|
if (!res.ok)
|
|
302
375
|
throw await failure(res, "complete upload");
|
|
303
376
|
// S3 can answer 200 and put the error in the body.
|
|
304
|
-
const text = await res
|
|
377
|
+
const text = await textOf(res, "complete upload");
|
|
305
378
|
if (/<Error>/.test(text)) {
|
|
306
379
|
const code = codeOf(text);
|
|
307
380
|
const msg = `s3 complete upload failed: 200 ${code ?? "error in body"}`;
|
|
@@ -336,7 +409,7 @@ export function s3BlobStore(cfg, given = {}) {
|
|
|
336
409
|
},
|
|
337
410
|
async get(key, opts = {}) {
|
|
338
411
|
assertKey(key);
|
|
339
|
-
const res = await send("get", "GET", key, undefined, opts.range ? { range: `bytes=${opts.range.start}-${opts.range.end}` } : {}, opts.signal);
|
|
412
|
+
const res = await send("get", "GET", key, undefined, opts.range ? { range: `bytes=${opts.range.start}-${opts.range.end}` } : {}, opts.signal, undefined, undefined, false);
|
|
340
413
|
if (res.status === 404) {
|
|
341
414
|
const text = await res.text().catch(() => "");
|
|
342
415
|
// A GET carries the reason a HEAD cannot: the bucket may be the thing that is missing.
|
|
@@ -388,7 +461,7 @@ export function s3BlobStore(cfg, given = {}) {
|
|
|
388
461
|
const res = await send("list uploads", "GET", "", undefined, {}, signal, q);
|
|
389
462
|
if (!res.ok)
|
|
390
463
|
throw await failure(res, "list uploads");
|
|
391
|
-
const xml = await res
|
|
464
|
+
const xml = await textOf(res, "list uploads");
|
|
392
465
|
for (const m of xml.matchAll(/<Upload>([\s\S]*?)<\/Upload>/g)) {
|
|
393
466
|
const key = unxml(/<Key>([^<]*)<\/Key>/.exec(m[1])?.[1] ?? "");
|
|
394
467
|
const id = unxml(/<UploadId>([^<]*)<\/UploadId>/.exec(m[1])?.[1] ?? "");
|
|
@@ -413,7 +486,7 @@ export function s3BlobStore(cfg, given = {}) {
|
|
|
413
486
|
const res = await send("list", "GET", "", undefined, {}, opts.signal, q);
|
|
414
487
|
if (!res.ok)
|
|
415
488
|
throw await failure(res, "list");
|
|
416
|
-
const xml = await res
|
|
489
|
+
const xml = await textOf(res, "list");
|
|
417
490
|
for (const c of xml.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)) {
|
|
418
491
|
const key = xmlText(c[1], "Key");
|
|
419
492
|
const size = Number(xmlText(c[1], "Size"));
|
|
@@ -432,7 +505,7 @@ export function s3BlobStore(cfg, given = {}) {
|
|
|
432
505
|
const res = await send("list", "GET", "", undefined, {}, opts.signal, q);
|
|
433
506
|
if (!res.ok)
|
|
434
507
|
throw await failure(res, "list");
|
|
435
|
-
const xml = await res
|
|
508
|
+
const xml = await textOf(res, "list");
|
|
436
509
|
for (const c of xml.matchAll(/<CommonPrefixes>\s*<Prefix>([^<]*)<\/Prefix>/g))
|
|
437
510
|
out.push(unxml(c[1]).replace(/^t\//, "").replace(/\/$/, ""));
|
|
438
511
|
token = /<IsTruncated>true<\/IsTruncated>/.test(xml) ? (xmlText(xml, "NextContinuationToken") ?? undefined) : undefined;
|
package/dist/src/translator.d.ts
CHANGED
|
@@ -138,6 +138,9 @@ export declare class ToolCallExtras {
|
|
|
138
138
|
keep(id: string, extra: unknown): void;
|
|
139
139
|
get(id: string): Json | undefined;
|
|
140
140
|
get size(): number;
|
|
141
|
+
/** Every kept call's extras, oldest first — for a caller that keeps them
|
|
142
|
+
* between separate requests (the LLM gateway, per account). */
|
|
143
|
+
entries(): [string, Json][];
|
|
141
144
|
}
|
|
142
145
|
export declare class StreamTranslator {
|
|
143
146
|
private started;
|
|
@@ -179,6 +182,10 @@ export declare class ResponsesStreamTranslator {
|
|
|
179
182
|
private incomplete;
|
|
180
183
|
private sawTool;
|
|
181
184
|
private sawRefusal;
|
|
185
|
+
/** The stream's last word: completed or incomplete (an answer), or the
|
|
186
|
+
* provider's error. None at all means it was cut off. */
|
|
187
|
+
private terminal;
|
|
188
|
+
private failure;
|
|
182
189
|
private id;
|
|
183
190
|
private readonly model;
|
|
184
191
|
constructor(model: string);
|
package/dist/src/translator.js
CHANGED
|
@@ -575,6 +575,11 @@ export class ToolCallExtras {
|
|
|
575
575
|
get size() {
|
|
576
576
|
return this.byId.size;
|
|
577
577
|
}
|
|
578
|
+
/** Every kept call's extras, oldest first — for a caller that keeps them
|
|
579
|
+
* between separate requests (the LLM gateway, per account). */
|
|
580
|
+
entries() {
|
|
581
|
+
return [...this.byId.entries()];
|
|
582
|
+
}
|
|
578
583
|
}
|
|
579
584
|
export class StreamTranslator {
|
|
580
585
|
started = false;
|
|
@@ -767,6 +772,10 @@ export class ResponsesStreamTranslator {
|
|
|
767
772
|
incomplete = null;
|
|
768
773
|
sawTool = false;
|
|
769
774
|
sawRefusal = false;
|
|
775
|
+
/** The stream's last word: completed or incomplete (an answer), or the
|
|
776
|
+
* provider's error. None at all means it was cut off. */
|
|
777
|
+
terminal = null;
|
|
778
|
+
failure = null;
|
|
770
779
|
id = `msg_${crypto.randomBytes(8).toString("hex")}`;
|
|
771
780
|
model;
|
|
772
781
|
constructor(model) {
|
|
@@ -869,6 +878,20 @@ export class ResponsesStreamTranslator {
|
|
|
869
878
|
const reason = r.incomplete_details?.reason;
|
|
870
879
|
if (typeof reason === "string")
|
|
871
880
|
this.incomplete = reason;
|
|
881
|
+
if (type === "response.failed") {
|
|
882
|
+
// A failure is not an answer (Codex review, 10 Nov 2026): it was
|
|
883
|
+
// ended as a normal stop, so the caller read a failed reply as done.
|
|
884
|
+
this.terminal = "failed";
|
|
885
|
+
const err = r.error ?? {};
|
|
886
|
+
this.failure = typeof err.message === "string" ? err.message : "the provider reported the response failed";
|
|
887
|
+
}
|
|
888
|
+
else
|
|
889
|
+
this.terminal = "done";
|
|
890
|
+
return out;
|
|
891
|
+
}
|
|
892
|
+
if (type === "error") {
|
|
893
|
+
this.terminal = "failed";
|
|
894
|
+
this.failure = typeof ev.message === "string" ? ev.message : "the provider sent an error mid-stream";
|
|
872
895
|
return out;
|
|
873
896
|
}
|
|
874
897
|
return out;
|
|
@@ -883,6 +906,13 @@ export class ResponsesStreamTranslator {
|
|
|
883
906
|
}
|
|
884
907
|
out.push(this.event("content_block_stop", { type: "content_block_stop", index: entry.block }));
|
|
885
908
|
}
|
|
909
|
+
// Failed, or cut off before any last word: an Anthropic error event, the
|
|
910
|
+
// shape a client reads as a failed request, never a normal stop.
|
|
911
|
+
if (this.terminal !== "done") {
|
|
912
|
+
const message = this.terminal === "failed" ? this.failure : "the provider's stream ended before the response finished";
|
|
913
|
+
out.push(this.event("error", { type: "error", error: { type: "api_error", message } }));
|
|
914
|
+
return out;
|
|
915
|
+
}
|
|
886
916
|
const reason = responsesStop(this.incomplete, this.sawTool, this.sawRefusal);
|
|
887
917
|
out.push(this.event("message_delta", {
|
|
888
918
|
type: "message_delta",
|