@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.
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 +309 -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 +357 -0
  8. package/dist/src/blob-sweeper.d.ts +70 -0
  9. package/dist/src/blob-sweeper.js +254 -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 +86 -9
  14. package/dist/src/history.js +132 -16
  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 +458 -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 +259 -0
  41. package/dist/src/workspace-revisions.js +1274 -0
  42. package/package.json +1 -1
  43. package/src/approvals.ts +3 -3
  44. package/src/blob-cache.ts +354 -0
  45. package/src/blob-pins.ts +99 -0
  46. package/src/blob-store.ts +385 -0
  47. package/src/blob-sweeper.ts +308 -0
  48. package/src/blob-types.ts +216 -0
  49. package/src/evals.ts +1 -1
  50. package/src/history.ts +182 -16
  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 +489 -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 +1324 -0
@@ -0,0 +1,65 @@
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
+ const PAGE = 500;
25
+ export async function pruneStateRevisions(deps, ws, policy, now = Date.now()) {
26
+ const keep = Math.max(0, Math.floor(policy.keep || 0));
27
+ const days = Math.max(0, policy.days || 0);
28
+ const out = { pruned: 0, kept: 0, held: 0 };
29
+ if (keep === 0 && days === 0)
30
+ return out;
31
+ const sws = { tenant: ws.tenant, workspace: ws.workspace, scope: "state" };
32
+ const cutoff = days > 0 ? now - days * 86_400_000 : -Infinity;
33
+ const doomed = [];
34
+ let seen = 0;
35
+ let before;
36
+ for (;;) {
37
+ const page = await deps.revisions.revisions(sws, { limit: PAGE, before });
38
+ if (!page.length)
39
+ break;
40
+ for (const r of page) {
41
+ const index = seen++;
42
+ if (index === 0) {
43
+ out.kept++; // the head
44
+ continue;
45
+ }
46
+ const outside = (keep > 0 && index >= keep) || Date.parse(r.at) < cutoff;
47
+ if (!outside) {
48
+ out.kept++;
49
+ continue;
50
+ }
51
+ if (deps.pins && (await deps.pins.isPinnedBeyondRevisions(ws.tenant, "manifest", r.state))) {
52
+ out.held++;
53
+ continue;
54
+ }
55
+ doomed.push(r.id);
56
+ }
57
+ before = page[page.length - 1].seq;
58
+ if (page.length < PAGE)
59
+ break;
60
+ }
61
+ // In slices: one statement per slice, never an unbounded list.
62
+ for (let i = 0; i < doomed.length; i += 200)
63
+ out.pruned += await deps.revisions.prune(sws, doomed.slice(i, i + 200));
64
+ return out;
65
+ }
@@ -93,7 +93,7 @@ export interface Driver {
93
93
  /** Where the fs driver keeps a blob. Exported because the run mirror
94
94
  * hardlinks straight to it rather than reading and rewriting the bytes. */
95
95
  export declare function blobPath(tenant: string, workspace: string, sha: string): string;
96
- interface S3Config {
96
+ export interface S3Config {
97
97
  endpoint: string;
98
98
  bucket: string;
99
99
  region: string;
@@ -109,6 +109,21 @@ export declare function regionOfEndpoint(endpoint: string): string | null;
109
109
  export declare function s3Config(): S3Config | null;
110
110
  /** For tests: forget cached role credentials. */
111
111
  export declare function forgetS3Credentials(): void;
112
+ /** A body that is not held in memory: read as it is sent. `length` and
113
+ * `sha256` (hex of the whole body) are needed up front: S3 wants a
114
+ * Content-Length (it refuses chunked uploads) and the hash is signed. */
115
+ export interface S3StreamBody {
116
+ stream: AsyncIterable<Uint8Array>;
117
+ length: number;
118
+ sha256: string;
119
+ }
120
+ export interface S3RequestOptions {
121
+ /** Sub-resource and list parameters (`uploads`, `uploadId`, `partNumber`,
122
+ * `prefix`...). Signed in canonical order. An empty value is `name=`. */
123
+ query?: Record<string, string>;
124
+ }
125
+ /** The header-signed form, for the calls the platform itself makes. */
126
+ export declare function s3Request(cfg: S3Config, method: "GET" | "PUT" | "POST" | "DELETE" | "HEAD", key: string, body?: Buffer | S3StreamBody, mime?: string, extra?: Record<string, string>, signal?: AbortSignal, opts?: S3RequestOptions): Promise<Response>;
112
127
  /**
113
128
  * The Content-Disposition a presigned GET asks the store to send back. The
114
129
  * store echoes it as a header, and header values are bytes: a raw "報告.pdf"
@@ -122,6 +137,19 @@ export declare function contentDisposition(type: "inline" | "attachment", filena
122
137
  * because a dashboard that boots and stores locally beats one that 500s.
123
138
  */
124
139
  export declare function driverFor(tenant: string, workspace: string): Driver;
140
+ /**
141
+ * Run `fn` as the only writer of this workspace's file index, in this process
142
+ * and every other one on the volume. Callers of the same workspace in this
143
+ * process queue on a promise chain first, so they do not poll the file against
144
+ * each other. Keep `fn` to index work and blob bookkeeping; bytes a caller
145
+ * already holds are uploaded BEFORE taking the lock (a blob is immutable and
146
+ * named by its hash, so that is safe) and then confirmed present inside it.
147
+ */
148
+ export declare function withFileStoreLock<T>(tenant: string, workspace: string, fn: () => Promise<T>): Promise<T>;
149
+ /** The same lock for any path: `file` is the lock file itself (its directory
150
+ * is created). Used by the local RevisionStore, which keeps its own state
151
+ * beside the data it guards. */
152
+ export declare function withFileLock<T>(file: string, fn: () => Promise<T>): Promise<T>;
125
153
  export declare function putFile(tenant: string, workspace: string, rel: string, body: Buffer, by: string): Promise<FileRecord>;
126
154
  /** Register bytes a browser PUT straight to the bucket. Same bookkeeping as
127
155
  * putFile, minus the bytes — the platform never saw them.
@@ -54,6 +54,7 @@ import crypto from "node:crypto";
54
54
  import { Readable } from "node:stream";
55
55
  import { dataRoot, singleWorkspace } from "./paths.js";
56
56
  import { assertSafeName, workspaceDir, STORAGE_DIR, adoptLegacyFilesDir } from "./store.js";
57
+ import { records } from "./records.js";
57
58
  /** The directory a run sees, and the one this module mirrors into it.
58
59
  * Declared in store.ts, where saveWorkspace also needs it; re-exported so
59
60
  * callers of this module do not need to know that. */
@@ -174,6 +175,9 @@ export function mimeFor(rel) {
174
175
  export function readIndex(tenant, workspace) {
175
176
  if (!fileStoreEnabled())
176
177
  return { version: 1, files: [] };
178
+ const port = records(tenant, workspace);
179
+ if (port)
180
+ return { version: 1, files: port.fileList(tenant, workspace) };
177
181
  try {
178
182
  const raw = JSON.parse(fs.readFileSync(indexPath(tenant, workspace), "utf8"));
179
183
  if (!Array.isArray(raw?.files))
@@ -193,6 +197,23 @@ function writeIndex(tenant, workspace, index) {
193
197
  fs.writeFileSync(tmp, JSON.stringify(index, null, 2));
194
198
  fs.renameSync(tmp, file);
195
199
  }
200
+ /** Save one record, where `index` is the index it was read from (the file
201
+ * store rewrites the whole file; the database upserts one row, which is why
202
+ * two writers of different paths never touch each other). */
203
+ function indexPut(tenant, workspace, index, record) {
204
+ const port = records(tenant, workspace);
205
+ if (port)
206
+ return port.filePut(tenant, workspace, record);
207
+ writeIndex(tenant, workspace, { version: 1, files: [...index.files.filter((f) => f.path !== record.path), record] });
208
+ }
209
+ function indexRemove(tenant, workspace, index, rel) {
210
+ const port = records(tenant, workspace);
211
+ if (port) {
212
+ port.fileDelete(tenant, workspace, rel);
213
+ return;
214
+ }
215
+ writeIndex(tenant, workspace, { version: 1, files: index.files.filter((f) => f.path !== rel) });
216
+ }
196
217
  export function listStorage(tenant, workspace) {
197
218
  return readIndex(tenant, workspace).files.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
198
219
  }
@@ -416,12 +437,17 @@ function presign(cfg, creds, method, key, ttlSec, extraQuery = {}, now = new Dat
416
437
  return `${origin}${canonicalUri}?${canonicalQuery}&X-Amz-Signature=${signature}`;
417
438
  }
418
439
  /** The header-signed form, for the calls the platform itself makes. */
419
- async function s3Request(cfg, method, key, body, mime, extra = {}) {
440
+ export async function s3Request(cfg, method, key, body, mime, extra = {}, signal, opts = {}) {
420
441
  const creds = await credentials(cfg);
421
442
  const { host, origin, canonicalUri } = target(cfg, key);
422
443
  const { amzDate, dateStamp } = stamps(new Date());
423
444
  const scope = `${dateStamp}/${cfg.region}/s3/aws4_request`;
424
- const payloadHash = sha256(body ?? Buffer.alloc(0));
445
+ const streamed = body && !Buffer.isBuffer(body) ? body : null;
446
+ const payloadHash = streamed ? streamed.sha256 : sha256(body ?? Buffer.alloc(0));
447
+ const canonicalQuery = Object.keys(opts.query ?? {})
448
+ .sort()
449
+ .map((k) => `${uriEncode(k)}=${uriEncode(opts.query[k])}`)
450
+ .join("&");
425
451
  const headers = {
426
452
  host,
427
453
  "x-amz-content-sha256": payloadHash,
@@ -438,18 +464,23 @@ async function s3Request(cfg, method, key, body, mime, extra = {}) {
438
464
  const canonicalRequest = [
439
465
  method,
440
466
  canonicalUri,
441
- "",
467
+ canonicalQuery,
442
468
  canonicalHeaders,
443
469
  signedHeaders,
444
470
  payloadHash,
445
471
  ].join("\n");
446
472
  const stringToSign = ["AWS4-HMAC-SHA256", amzDate, scope, sha256(canonicalRequest)].join("\n");
447
473
  const signature = hmac(signingKey(cfg, creds, dateStamp), stringToSign).toString("hex");
448
- const res = await fetch(`${origin}${canonicalUri}`, {
474
+ const res = await fetch(`${origin}${canonicalUri}${canonicalQuery ? `?${canonicalQuery}` : ""}`, {
449
475
  method,
450
- body: body,
476
+ body: streamed
477
+ ? Readable.toWeb(Readable.from(streamed.stream, { objectMode: false }))
478
+ : body,
479
+ ...(streamed ? { duplex: "half" } : {}),
480
+ signal,
451
481
  headers: {
452
482
  ...headers,
483
+ ...(streamed ? { "content-length": String(streamed.length) } : {}),
453
484
  Authorization: `AWS4-HMAC-SHA256 Credential=${creds.accessKeyId}/${scope}, ` +
454
485
  `SignedHeaders=${signedHeaders}, Signature=${signature}`,
455
486
  },
@@ -547,6 +578,163 @@ export function driverFor(tenant, workspace) {
547
578
  }
548
579
  return fsDriver(tenant, workspace);
549
580
  }
581
+ // ---------- the per-workspace lock ----------
582
+ //
583
+ // The index is read, changed and written back by writers in DIFFERENT pods:
584
+ // the web pod (uploads, registerUpload, deleteFile) and the worker (a run's
585
+ // harvest) share the data volume. So an in-process mutex is not enough; the
586
+ // lock has to hold across processes. It is `lockFileExclusive`'s mechanism
587
+ // (`<file>.lock` opened O_EXCL — NFS 4.1 and EFS honour it) with three
588
+ // differences this module needs:
589
+ //
590
+ // async it waits with a timer, so a busy lock never blocks the event loop
591
+ // (the sync one parks the thread with Atomics.wait);
592
+ // fenced the lock file holds a token and release only removes its own, so
593
+ // a holder whose lock was taken over as stale cannot delete the new
594
+ // holder's lock;
595
+ // renewed the holder touches the lock while it works, so the stale limit
596
+ // only ever means "the holder died", not "the holder is slow".
597
+ //
598
+ // Core has no database, so a Postgres advisory lock is not available here;
599
+ // phase 2 replaces this index (and so this lock) with rows.
600
+ //
601
+ // The lock lives BESIDE the store directory, not in it, so a workspace delete
602
+ // or rename (which removes or moves that directory) cannot pull it out from
603
+ // under its own holder.
604
+ const LOCK_STALE_MS = 30_000;
605
+ const LOCK_RENEW_MS = 5_000;
606
+ const LOCK_WAIT_MS = 30_000;
607
+ const lockQueues = new Map();
608
+ const nap = (ms) => new Promise((r) => setTimeout(r, ms));
609
+ function lockFile(tenant, workspace) {
610
+ assertSafeName(tenant, "tenant");
611
+ assertSafeName(workspace, "workspace");
612
+ return path.join(dataRoot(), tenant, STORAGE_DIR, `.${workspace}.lock`);
613
+ }
614
+ /**
615
+ * Take over a lock whose holder died, without ever deleting a live one.
616
+ *
617
+ * Two processes can both see the same stale file. If each simply removed it,
618
+ * the slower one would remove the FRESH lock the faster one had just created,
619
+ * and both would run. So the file is moved aside with rename(2) — atomic, one
620
+ * caller wins, the others get ENOENT — and what was moved is read back: if it
621
+ * is not stale after all (we raced a new holder), it is put back with link(2),
622
+ * which cannot overwrite a lock someone else took in between.
623
+ */
624
+ async function clearStale(file) {
625
+ const aside = `${file}.stale.${process.pid}.${crypto.randomBytes(4).toString("hex")}`;
626
+ try {
627
+ fs.renameSync(file, aside);
628
+ }
629
+ catch {
630
+ return; // another process got there first, or it was released
631
+ }
632
+ try {
633
+ if (Date.now() - fs.statSync(aside).mtimeMs <= LOCK_STALE_MS) {
634
+ try {
635
+ fs.linkSync(aside, file); // not stale: we moved a live lock; restore it
636
+ }
637
+ catch {
638
+ // someone already took the free name; the live holder lost its file and
639
+ // will find out at release (token check). Rare, and not made worse.
640
+ }
641
+ }
642
+ }
643
+ catch {
644
+ // vanished: nothing to restore
645
+ }
646
+ finally {
647
+ fs.rmSync(aside, { force: true });
648
+ }
649
+ }
650
+ async function takeFileLock(file) {
651
+ fs.mkdirSync(path.dirname(file), { recursive: true });
652
+ const token = `${process.pid}.${crypto.randomBytes(8).toString("hex")}`;
653
+ const deadline = Date.now() + LOCK_WAIT_MS;
654
+ for (;;) {
655
+ try {
656
+ const fd = fs.openSync(file, "wx", 0o600);
657
+ fs.writeSync(fd, token);
658
+ fs.closeSync(fd);
659
+ break;
660
+ }
661
+ catch (err) {
662
+ if (err.code !== "EEXIST")
663
+ throw err;
664
+ try {
665
+ if (Date.now() - fs.statSync(file).mtimeMs > LOCK_STALE_MS) {
666
+ await clearStale(file);
667
+ continue;
668
+ }
669
+ }
670
+ catch {
671
+ continue; // released between the open and the stat
672
+ }
673
+ if (Date.now() > deadline)
674
+ throw new Error("the file store is busy — another change is being saved; try again");
675
+ await nap(15 + Math.floor(Math.random() * 20));
676
+ }
677
+ }
678
+ const renew = setInterval(() => {
679
+ try {
680
+ const now = new Date();
681
+ fs.utimesSync(file, now, now);
682
+ }
683
+ catch {
684
+ // gone: release() notices
685
+ }
686
+ }, LOCK_RENEW_MS);
687
+ renew.unref();
688
+ return () => {
689
+ clearInterval(renew);
690
+ try {
691
+ if (fs.readFileSync(file, "utf8") === token)
692
+ fs.rmSync(file, { force: true });
693
+ }
694
+ catch {
695
+ // already gone
696
+ }
697
+ };
698
+ }
699
+ /**
700
+ * Run `fn` as the only writer of this workspace's file index, in this process
701
+ * and every other one on the volume. Callers of the same workspace in this
702
+ * process queue on a promise chain first, so they do not poll the file against
703
+ * each other. Keep `fn` to index work and blob bookkeeping; bytes a caller
704
+ * already holds are uploaded BEFORE taking the lock (a blob is immutable and
705
+ * named by its hash, so that is safe) and then confirmed present inside it.
706
+ */
707
+ export async function withFileStoreLock(tenant, workspace, fn) {
708
+ if (!fileStoreEnabled())
709
+ return fn();
710
+ const port = records(tenant, workspace);
711
+ if (port)
712
+ return port.lock(`storage:${tenant}/${workspace}`, fn);
713
+ return withFileLock(lockFile(tenant, workspace), fn);
714
+ }
715
+ /** The same lock for any path: `file` is the lock file itself (its directory
716
+ * is created). Used by the local RevisionStore, which keeps its own state
717
+ * beside the data it guards. */
718
+ export async function withFileLock(file, fn) {
719
+ const prev = lockQueues.get(file) ?? Promise.resolve();
720
+ const run = prev.catch(() => { }).then(async () => {
721
+ const release = await takeFileLock(file);
722
+ try {
723
+ return await fn();
724
+ }
725
+ finally {
726
+ release();
727
+ }
728
+ });
729
+ lockQueues.set(file, run);
730
+ try {
731
+ return await run;
732
+ }
733
+ finally {
734
+ if (lockQueues.get(file) === run)
735
+ lockQueues.delete(file);
736
+ }
737
+ }
550
738
  // ---------- the store ----------
551
739
  /**
552
740
  * Record bytes the platform already holds. Used by the upload route on the fs
@@ -583,31 +771,53 @@ async function putFileQuietly(tenant, workspace, rel, body, by) {
583
771
  throw new Error(`${norm} is ${Math.round(body.length / 1e6)}MB — the limit is ${maxBytes() / 1e6}MB`);
584
772
  }
585
773
  const sha = sha256(body);
586
- const index = readIndex(tenant, workspace);
587
- const previous = index.files.find((f) => f.path === norm);
588
- if (previous?.sha === sha)
589
- return previous; // same bytes, same name: nothing happened
590
- const projected = usedBytes(tenant, workspace) - (previous?.size ?? 0) + body.length;
591
- if (projected > quotaBytes()) {
592
- throw new Error(`workspace file quota exceeded (${quotaBytes() / 1e6}MB)`);
593
- }
594
774
  const driver = driverFor(tenant, workspace);
595
- await driver.put(blobKey(tenant, workspace, sha), body, mimeFor(norm));
596
- const record = {
597
- path: norm,
598
- sha,
599
- size: body.length,
600
- mime: mimeFor(norm),
601
- updatedAt: new Date().toISOString(),
602
- by,
603
- };
604
- writeIndex(tenant, workspace, {
605
- version: 1,
606
- files: [...index.files.filter((f) => f.path !== norm), record],
775
+ const key = blobKey(tenant, workspace, sha);
776
+ // A cheap look before the bytes move; the check inside the lock is the one
777
+ // that counts, this one only saves uploading what will be refused.
778
+ {
779
+ const seen = readIndex(tenant, workspace);
780
+ const before = seen.files.find((f) => f.path === norm);
781
+ if (before?.sha !== sha && usedBytes(tenant, workspace) - (before?.size ?? 0) + body.length > quotaBytes()) {
782
+ throw new Error(`workspace file quota exceeded (${quotaBytes() / 1e6}MB)`);
783
+ }
784
+ }
785
+ // The upload happens outside the lock: it can be long, and a blob is
786
+ // immutable and named by its hash, so two writers uploading the same one are
787
+ // harmless. What the lock guards is the index, and the blob's presence while
788
+ // the index names it (see the confirm below).
789
+ await driver.put(key, body, mimeFor(norm));
790
+ return withFileStoreLock(tenant, workspace, async () => {
791
+ const index = readIndex(tenant, workspace);
792
+ const previous = index.files.find((f) => f.path === norm);
793
+ if (previous?.sha === sha)
794
+ return previous; // same bytes, same name: nothing happened
795
+ const projected = usedBytes(tenant, workspace) - (previous?.size ?? 0) + body.length;
796
+ if (projected > quotaBytes()) {
797
+ // Nothing names the blob we just put unless another record already does.
798
+ if (!index.files.some((f) => f.sha === sha))
799
+ await driver.remove(key).catch(() => { });
800
+ throw new Error(`workspace file quota exceeded (${quotaBytes() / 1e6}MB)`);
801
+ }
802
+ // A delete or replace that ran between our upload and now may have
803
+ // collected this very blob (it was unreferenced then). We hold the bytes,
804
+ // so put them back before the index points at them. put is a no-op when
805
+ // the object is there.
806
+ if (!(await driver.has(key)))
807
+ await driver.put(key, body, mimeFor(norm));
808
+ const record = {
809
+ path: norm,
810
+ sha,
811
+ size: body.length,
812
+ mime: mimeFor(norm),
813
+ updatedAt: new Date().toISOString(),
814
+ by,
815
+ };
816
+ indexPut(tenant, workspace, index, record);
817
+ if (previous)
818
+ await collectLocked(tenant, workspace, previous.sha);
819
+ return record;
607
820
  });
608
- if (previous)
609
- await collect(tenant, workspace, previous.sha);
610
- return record;
611
821
  }
612
822
  /** Register bytes a browser PUT straight to the bucket. Same bookkeeping as
613
823
  * putFile, minus the bytes — the platform never saw them.
@@ -624,41 +834,47 @@ export async function registerUpload(tenant, workspace, rel, sha, _claimed, by)
624
834
  requireWorkspace(tenant, workspace);
625
835
  const driver = driverFor(tenant, workspace);
626
836
  const key = blobKey(tenant, workspace, sha);
627
- // Trust nothing the browser said: not that the PUT landed, not its size.
628
- const size = await driver.size(key);
629
- if (size === null) {
630
- throw new Error("no object at that key — the upload did not complete");
631
- }
632
- const index = readIndex(tenant, workspace);
633
- const previous = index.files.find((f) => f.path === norm);
634
- const record = {
635
- path: norm,
636
- sha,
637
- size,
638
- mime: mimeFor(norm),
639
- updatedAt: new Date().toISOString(),
640
- by,
641
- };
642
- const files = [...index.files.filter((f) => f.path !== norm), record];
643
- // putFile's two limits, on the real length. A refused object is removed:
644
- // nothing names it, so it would sit in the bucket unreachable and billed —
645
- // unless a record already names these bytes, which are then not ours to drop.
646
- const refuse = async (message) => {
647
- if (!index.files.some((f) => f.sha === sha))
648
- await driver.remove(key).catch(() => { });
649
- throw new Error(message);
650
- };
651
- if (size > maxBytes()) {
652
- await refuse(`${norm} is ${Math.round(size / 1e6)}MB — the limit is ${maxBytes() / 1e6}MB`);
653
- }
654
- if (bytesOf(files) > quotaBytes() && bytesOf(files) > bytesOf(index.files)) {
655
- await refuse(`workspace file quota exceeded (${quotaBytes() / 1e6}MB)`);
656
- }
657
- writeIndex(tenant, workspace, { version: 1, files });
658
- if (previous && previous.sha !== sha)
659
- await collect(tenant, workspace, previous.sha);
660
- await announceFiles(tenant, workspace, [record.path], by);
661
- return record;
837
+ return withFileStoreLock(tenant, workspace, async () => {
838
+ // Inside the lock, so a collect cannot remove the object between the
839
+ // check that it is there and the index naming it.
840
+ // Trust nothing the browser said: not that the PUT landed, not its size.
841
+ const size = await driver.size(key);
842
+ if (size === null) {
843
+ throw new Error("no object at that key — the upload did not complete");
844
+ }
845
+ const index = readIndex(tenant, workspace);
846
+ const previous = index.files.find((f) => f.path === norm);
847
+ const record = {
848
+ path: norm,
849
+ sha,
850
+ size,
851
+ mime: mimeFor(norm),
852
+ updatedAt: new Date().toISOString(),
853
+ by,
854
+ };
855
+ const files = [...index.files.filter((f) => f.path !== norm), record];
856
+ // putFile's two limits, on the real length. A refused object is removed:
857
+ // nothing names it, so it would sit in the bucket unreachable and billed —
858
+ // unless a record already names these bytes, which are then not ours to drop.
859
+ const refuse = async (message) => {
860
+ if (!index.files.some((f) => f.sha === sha))
861
+ await driver.remove(key).catch(() => { });
862
+ throw new Error(message);
863
+ };
864
+ if (size > maxBytes()) {
865
+ await refuse(`${norm} is ${Math.round(size / 1e6)}MB — the limit is ${maxBytes() / 1e6}MB`);
866
+ }
867
+ if (bytesOf(files) > quotaBytes() && bytesOf(files) > bytesOf(index.files)) {
868
+ await refuse(`workspace file quota exceeded (${quotaBytes() / 1e6}MB)`);
869
+ }
870
+ indexPut(tenant, workspace, index, record);
871
+ if (previous && previous.sha !== sha)
872
+ await collectLocked(tenant, workspace, previous.sha);
873
+ return record;
874
+ }).then(async (record) => {
875
+ await announceFiles(tenant, workspace, [record.path], by);
876
+ return record;
877
+ });
662
878
  }
663
879
  export async function readFileBytes(tenant, workspace, rel) {
664
880
  const record = getFile(tenant, workspace, rel);
@@ -694,18 +910,24 @@ export async function openFile(tenant, workspace, rel, range) {
694
910
  }
695
911
  export async function deleteFile(tenant, workspace, rel) {
696
912
  const norm = assertFilePath(rel);
697
- const index = readIndex(tenant, workspace);
698
- const record = index.files.find((f) => f.path === norm);
699
- if (!record)
700
- return false;
701
- writeIndex(tenant, workspace, { version: 1, files: index.files.filter((f) => f.path !== norm) });
702
- await collect(tenant, workspace, record.sha);
703
- // The run mirror is a cache of the index, so it follows the index.
704
- fs.rmSync(path.join(workspaceDir(tenant, workspace), STORAGE_DIR, norm), { force: true });
705
- return true;
706
- }
707
- /** Drop a blob once the last record naming it is gone. */
708
- async function collect(tenant, workspace, sha) {
913
+ return withFileStoreLock(tenant, workspace, async () => {
914
+ const index = readIndex(tenant, workspace);
915
+ const record = index.files.find((f) => f.path === norm);
916
+ if (!record)
917
+ return false;
918
+ indexRemove(tenant, workspace, index, norm);
919
+ await collectLocked(tenant, workspace, record.sha);
920
+ // The run mirror is a cache of the index, so it follows the index.
921
+ fs.rmSync(path.join(workspaceDir(tenant, workspace), STORAGE_DIR, norm), { force: true });
922
+ return true;
923
+ });
924
+ }
925
+ /** Drop a blob once the last record naming it is gone. The caller holds the
926
+ * workspace lock: the reference check and the delete are one step, and a put
927
+ * that is about to name this blob waits for the lock and then confirms the
928
+ * blob is present before it does (putFileQuietly), so neither can strand the
929
+ * other. */
930
+ async function collectLocked(tenant, workspace, sha) {
709
931
  if (readIndex(tenant, workspace).files.some((f) => f.sha === sha))
710
932
  return;
711
933
  try {
@@ -783,8 +1005,16 @@ function storeDirOf(tenant, workspace) {
783
1005
  * unreachable), and a no-op when there is no store.
784
1006
  */
785
1007
  export async function purgeWorkspaceStorage(tenant, workspace) {
1008
+ if (!fileStoreEnabled())
1009
+ return;
1010
+ return withFileStoreLock(tenant, workspace, () => purgeUnlocked(tenant, workspace));
1011
+ }
1012
+ async function purgeUnlocked(tenant, workspace) {
786
1013
  const dir = storeDirOf(tenant, workspace);
787
- if (!dir || !fs.existsSync(dir))
1014
+ const port = records(tenant, workspace);
1015
+ // With the index in the database the folder need not exist (a bucket holds
1016
+ // the objects), so the rows decide whether there is anything to purge.
1017
+ if (!dir || (!fs.existsSync(dir) && !(port && port.fileList(tenant, workspace).length)))
788
1018
  return;
789
1019
  const driver = driverFor(tenant, workspace);
790
1020
  if (driver.kind !== "fs") {
@@ -792,6 +1022,9 @@ export async function purgeWorkspaceStorage(tenant, workspace) {
792
1022
  for (const sha of shas)
793
1023
  await driver.remove(blobKey(tenant, workspace, sha)).catch(() => { });
794
1024
  }
1025
+ if (port)
1026
+ for (const f of port.fileList(tenant, workspace))
1027
+ port.fileDelete(tenant, workspace, f.path);
795
1028
  fs.rmSync(dir, { recursive: true, force: true });
796
1029
  }
797
1030
  /**
@@ -809,13 +1042,26 @@ export async function purgeWorkspaceStorage(tenant, workspace) {
809
1042
  * workspace of that name that no longer exists, never to this one.
810
1043
  */
811
1044
  export async function moveWorkspaceStorage(tenant, from, to) {
1045
+ if (!fileStoreEnabled() || from === to)
1046
+ return;
1047
+ // Both names, in a fixed order: an upload to the NEW name must not land in a
1048
+ // store this call is about to replace, and two crossing renames must not
1049
+ // each hold one lock and wait for the other.
1050
+ const [first, second] = [from, to].sort();
1051
+ return withFileStoreLock(tenant, first, () => withFileStoreLock(tenant, second, () => moveUnlocked(tenant, from, to)));
1052
+ }
1053
+ async function moveUnlocked(tenant, from, to) {
812
1054
  const src = storeDirOf(tenant, from);
813
1055
  const dest = storeDirOf(tenant, to);
814
1056
  if (!src || !dest || src === dest)
815
1057
  return;
816
- if (fs.existsSync(dest))
817
- await purgeWorkspaceStorage(tenant, to);
818
- if (!fs.existsSync(src))
1058
+ const port = records(tenant, from);
1059
+ // Whatever a store under the new name held belonged to a workspace of that
1060
+ // name that no longer exists. (The file index has not moved yet: it moves
1061
+ // below, after the bytes, so rows under `to` are that stale store's.)
1062
+ if (fs.existsSync(dest) || (port && port.fileList(tenant, to).length))
1063
+ await purgeUnlocked(tenant, to);
1064
+ if (!fs.existsSync(src) && !(port && port.fileList(tenant, from).length))
819
1065
  return;
820
1066
  const driver = driverFor(tenant, from);
821
1067
  const shas = driver.kind === "fs" ? [] : [...new Set(readIndex(tenant, from).files.map((f) => f.sha))];
@@ -823,8 +1069,12 @@ export async function moveWorkspaceStorage(tenant, from, to) {
823
1069
  throw new Error(`the ${driver.kind} store cannot move files to a new workspace name`);
824
1070
  for (const sha of shas)
825
1071
  await driver.copy(blobKey(tenant, from, sha), blobKey(tenant, to, sha));
826
- fs.mkdirSync(path.dirname(dest), { recursive: true });
827
- fs.renameSync(src, dest);
1072
+ if (fs.existsSync(src)) {
1073
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
1074
+ fs.renameSync(src, dest);
1075
+ }
1076
+ // The index follows the bytes, once they are all across.
1077
+ port?.fileMove(tenant, from, to);
828
1078
  for (const sha of shas)
829
1079
  await driver.remove(blobKey(tenant, from, sha)).catch(() => { });
830
1080
  }