@foldrun/core 17.3.0 → 18.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/src/approvals.js +3 -3
  2. package/dist/src/blob-cache.d.ts +58 -0
  3. package/dist/src/blob-cache.js +312 -0
  4. package/dist/src/blob-pins.d.ts +44 -0
  5. package/dist/src/blob-pins.js +61 -0
  6. package/dist/src/blob-store.d.ts +47 -0
  7. package/dist/src/blob-store.js +362 -0
  8. package/dist/src/blob-sweeper.d.ts +70 -0
  9. package/dist/src/blob-sweeper.js +282 -0
  10. package/dist/src/blob-types.d.ts +145 -0
  11. package/dist/src/blob-types.js +115 -0
  12. package/dist/src/evals.js +1 -1
  13. package/dist/src/history.d.ts +92 -9
  14. package/dist/src/history.js +168 -20
  15. package/dist/src/journal-store.d.ts +58 -0
  16. package/dist/src/journal-store.js +117 -0
  17. package/dist/src/manifest.d.ts +92 -0
  18. package/dist/src/manifest.js +239 -0
  19. package/dist/src/ops-log.js +26 -3
  20. package/dist/src/platform.d.ts +7 -0
  21. package/dist/src/platform.js +1 -0
  22. package/dist/src/publish.d.ts +134 -0
  23. package/dist/src/publish.js +434 -0
  24. package/dist/src/records.d.ts +72 -0
  25. package/dist/src/records.js +24 -0
  26. package/dist/src/revision-store.d.ts +161 -0
  27. package/dist/src/revision-store.js +378 -0
  28. package/dist/src/run-container.d.ts +20 -0
  29. package/dist/src/run-container.js +61 -0
  30. package/dist/src/runner.js +1 -1
  31. package/dist/src/s3-blob-store.d.ts +29 -0
  32. package/dist/src/s3-blob-store.js +531 -0
  33. package/dist/src/state-retention.d.ts +15 -0
  34. package/dist/src/state-retention.js +65 -0
  35. package/dist/src/storage.d.ts +29 -1
  36. package/dist/src/storage.js +331 -81
  37. package/dist/src/store.d.ts +41 -0
  38. package/dist/src/store.js +188 -5
  39. package/dist/src/trigger-log.js +17 -0
  40. package/dist/src/workspace-revisions.d.ts +269 -0
  41. package/dist/src/workspace-revisions.js +1382 -0
  42. package/package.json +1 -1
  43. package/src/approvals.ts +3 -3
  44. package/src/blob-cache.ts +357 -0
  45. package/src/blob-pins.ts +99 -0
  46. package/src/blob-store.ts +389 -0
  47. package/src/blob-sweeper.ts +336 -0
  48. package/src/blob-types.ts +216 -0
  49. package/src/evals.ts +1 -1
  50. package/src/history.ts +226 -19
  51. package/src/journal-store.ts +152 -0
  52. package/src/manifest.ts +274 -0
  53. package/src/ops-log.ts +25 -3
  54. package/src/platform.ts +8 -0
  55. package/src/publish.ts +520 -0
  56. package/src/records.ts +105 -0
  57. package/src/revision-store.ts +513 -0
  58. package/src/run-container.ts +62 -0
  59. package/src/runner.ts +1 -1
  60. package/src/s3-blob-store.ts +560 -0
  61. package/src/state-retention.ts +83 -0
  62. package/src/storage.ts +335 -81
  63. package/src/store.ts +178 -5
  64. package/src/trigger-log.ts +15 -0
  65. package/src/workspace-revisions.ts +1423 -0
package/src/storage.ts CHANGED
@@ -55,6 +55,7 @@ import crypto from "node:crypto";
55
55
  import { Readable } from "node:stream";
56
56
  import { dataRoot, singleWorkspace } from "./paths.ts";
57
57
  import { assertSafeName, workspaceDir, STORAGE_DIR, adoptLegacyFilesDir } from "./store.ts";
58
+ import { records } from "./records.ts";
58
59
 
59
60
  /** The directory a run sees, and the one this module mirrors into it.
60
61
  * Declared in store.ts, where saveWorkspace also needs it; re-exported so
@@ -207,6 +208,8 @@ export function mimeFor(rel: string): string {
207
208
 
208
209
  export function readIndex(tenant: string, workspace: string): Index {
209
210
  if (!fileStoreEnabled()) return { version: 1, files: [] };
211
+ const port = records(tenant, workspace);
212
+ if (port) return { version: 1, files: port.fileList(tenant, workspace) };
210
213
  try {
211
214
  const raw = JSON.parse(fs.readFileSync(indexPath(tenant, workspace), "utf8")) as Index;
212
215
  if (!Array.isArray(raw?.files)) return { version: 1, files: [] };
@@ -226,6 +229,24 @@ function writeIndex(tenant: string, workspace: string, index: Index) {
226
229
  fs.renameSync(tmp, file);
227
230
  }
228
231
 
232
+ /** Save one record, where `index` is the index it was read from (the file
233
+ * store rewrites the whole file; the database upserts one row, which is why
234
+ * two writers of different paths never touch each other). */
235
+ function indexPut(tenant: string, workspace: string, index: Index, record: FileRecord) {
236
+ const port = records(tenant, workspace);
237
+ if (port) return port.filePut(tenant, workspace, record);
238
+ writeIndex(tenant, workspace, { version: 1, files: [...index.files.filter((f) => f.path !== record.path), record] });
239
+ }
240
+
241
+ function indexRemove(tenant: string, workspace: string, index: Index, rel: string) {
242
+ const port = records(tenant, workspace);
243
+ if (port) {
244
+ port.fileDelete(tenant, workspace, rel);
245
+ return;
246
+ }
247
+ writeIndex(tenant, workspace, { version: 1, files: index.files.filter((f) => f.path !== rel) });
248
+ }
249
+
229
250
  export function listStorage(tenant: string, workspace: string): FileRecord[] {
230
251
  return readIndex(tenant, workspace).files.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
231
252
  }
@@ -325,7 +346,7 @@ function fsDriver(tenant: string, workspace: string): Driver {
325
346
 
326
347
  // ---------- s3 driver ----------
327
348
 
328
- interface S3Config {
349
+ export interface S3Config {
329
350
  endpoint: string;
330
351
  bucket: string;
331
352
  region: string;
@@ -530,20 +551,42 @@ function presign(
530
551
  return `${origin}${canonicalUri}?${canonicalQuery}&X-Amz-Signature=${signature}`;
531
552
  }
532
553
 
554
+ /** A body that is not held in memory: read as it is sent. `length` and
555
+ * `sha256` (hex of the whole body) are needed up front: S3 wants a
556
+ * Content-Length (it refuses chunked uploads) and the hash is signed. */
557
+ export interface S3StreamBody {
558
+ stream: AsyncIterable<Uint8Array>;
559
+ length: number;
560
+ sha256: string;
561
+ }
562
+
563
+ export interface S3RequestOptions {
564
+ /** Sub-resource and list parameters (`uploads`, `uploadId`, `partNumber`,
565
+ * `prefix`...). Signed in canonical order. An empty value is `name=`. */
566
+ query?: Record<string, string>;
567
+ }
568
+
533
569
  /** The header-signed form, for the calls the platform itself makes. */
534
- async function s3Request(
570
+ export async function s3Request(
535
571
  cfg: S3Config,
536
- method: "GET" | "PUT" | "DELETE" | "HEAD",
572
+ method: "GET" | "PUT" | "POST" | "DELETE" | "HEAD",
537
573
  key: string,
538
- body?: Buffer,
574
+ body?: Buffer | S3StreamBody,
539
575
  mime?: string,
540
576
  extra: Record<string, string> = {},
577
+ signal?: AbortSignal,
578
+ opts: S3RequestOptions = {},
541
579
  ): Promise<Response> {
542
580
  const creds = await credentials(cfg);
543
581
  const { host, origin, canonicalUri } = target(cfg, key);
544
582
  const { amzDate, dateStamp } = stamps(new Date());
545
583
  const scope = `${dateStamp}/${cfg.region}/s3/aws4_request`;
546
- const payloadHash = sha256(body ?? Buffer.alloc(0));
584
+ const streamed = body && !Buffer.isBuffer(body) ? (body as S3StreamBody) : null;
585
+ const payloadHash = streamed ? streamed.sha256 : sha256((body as Buffer | undefined) ?? Buffer.alloc(0));
586
+ const canonicalQuery = Object.keys(opts.query ?? {})
587
+ .sort()
588
+ .map((k) => `${uriEncode(k)}=${uriEncode(opts.query![k])}`)
589
+ .join("&");
547
590
 
548
591
  const headers: Record<string, string> = {
549
592
  host,
@@ -562,7 +605,7 @@ async function s3Request(
562
605
  const canonicalRequest = [
563
606
  method,
564
607
  canonicalUri,
565
- "",
608
+ canonicalQuery,
566
609
  canonicalHeaders,
567
610
  signedHeaders,
568
611
  payloadHash,
@@ -571,16 +614,21 @@ async function s3Request(
571
614
  const stringToSign = ["AWS4-HMAC-SHA256", amzDate, scope, sha256(canonicalRequest)].join("\n");
572
615
  const signature = hmac(signingKey(cfg, creds, dateStamp), stringToSign).toString("hex");
573
616
 
574
- const res = await fetch(`${origin}${canonicalUri}`, {
617
+ const res = await fetch(`${origin}${canonicalUri}${canonicalQuery ? `?${canonicalQuery}` : ""}`, {
575
618
  method,
576
- body: body as BodyInit | undefined,
619
+ body: streamed
620
+ ? (Readable.toWeb(Readable.from(streamed.stream, { objectMode: false })) as unknown as BodyInit)
621
+ : ((body as Buffer | undefined) as BodyInit | undefined),
622
+ ...(streamed ? { duplex: "half" } : {}),
623
+ signal,
577
624
  headers: {
578
625
  ...headers,
626
+ ...(streamed ? { "content-length": String(streamed.length) } : {}),
579
627
  Authorization:
580
628
  `AWS4-HMAC-SHA256 Credential=${creds.accessKeyId}/${scope}, ` +
581
629
  `SignedHeaders=${signedHeaders}, Signature=${signature}`,
582
630
  },
583
- });
631
+ } as RequestInit);
584
632
  return res;
585
633
  }
586
634
 
@@ -670,6 +718,154 @@ export function driverFor(tenant: string, workspace: string): Driver {
670
718
  return fsDriver(tenant, workspace);
671
719
  }
672
720
 
721
+ // ---------- the per-workspace lock ----------
722
+ //
723
+ // The index is read, changed and written back by writers in DIFFERENT pods:
724
+ // the web pod (uploads, registerUpload, deleteFile) and the worker (a run's
725
+ // harvest) share the data volume. So an in-process mutex is not enough; the
726
+ // lock has to hold across processes. It is `lockFileExclusive`'s mechanism
727
+ // (`<file>.lock` opened O_EXCL — NFS 4.1 and EFS honour it) with three
728
+ // differences this module needs:
729
+ //
730
+ // async it waits with a timer, so a busy lock never blocks the event loop
731
+ // (the sync one parks the thread with Atomics.wait);
732
+ // fenced the lock file holds a token and release only removes its own, so
733
+ // a holder whose lock was taken over as stale cannot delete the new
734
+ // holder's lock;
735
+ // renewed the holder touches the lock while it works, so the stale limit
736
+ // only ever means "the holder died", not "the holder is slow".
737
+ //
738
+ // Core has no database, so a Postgres advisory lock is not available here;
739
+ // phase 2 replaces this index (and so this lock) with rows.
740
+ //
741
+ // The lock lives BESIDE the store directory, not in it, so a workspace delete
742
+ // or rename (which removes or moves that directory) cannot pull it out from
743
+ // under its own holder.
744
+
745
+ const LOCK_STALE_MS = 30_000;
746
+ const LOCK_RENEW_MS = 5_000;
747
+ const LOCK_WAIT_MS = 30_000;
748
+ const lockQueues = new Map<string, Promise<unknown>>();
749
+ const nap = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
750
+
751
+ function lockFile(tenant: string, workspace: string) {
752
+ assertSafeName(tenant, "tenant");
753
+ assertSafeName(workspace, "workspace");
754
+ return path.join(dataRoot(), tenant, STORAGE_DIR, `.${workspace}.lock`);
755
+ }
756
+
757
+ /**
758
+ * Take over a lock whose holder died, without ever deleting a live one.
759
+ *
760
+ * Two processes can both see the same stale file. If each simply removed it,
761
+ * the slower one would remove the FRESH lock the faster one had just created,
762
+ * and both would run. So the file is moved aside with rename(2) — atomic, one
763
+ * caller wins, the others get ENOENT — and what was moved is read back: if it
764
+ * is not stale after all (we raced a new holder), it is put back with link(2),
765
+ * which cannot overwrite a lock someone else took in between.
766
+ */
767
+ async function clearStale(file: string): Promise<void> {
768
+ const aside = `${file}.stale.${process.pid}.${crypto.randomBytes(4).toString("hex")}`;
769
+ try {
770
+ fs.renameSync(file, aside);
771
+ } catch {
772
+ return; // another process got there first, or it was released
773
+ }
774
+ try {
775
+ if (Date.now() - fs.statSync(aside).mtimeMs <= LOCK_STALE_MS) {
776
+ try {
777
+ fs.linkSync(aside, file); // not stale: we moved a live lock; restore it
778
+ } catch {
779
+ // someone already took the free name; the live holder lost its file and
780
+ // will find out at release (token check). Rare, and not made worse.
781
+ }
782
+ }
783
+ } catch {
784
+ // vanished: nothing to restore
785
+ } finally {
786
+ fs.rmSync(aside, { force: true });
787
+ }
788
+ }
789
+
790
+ async function takeFileLock(file: string): Promise<() => void> {
791
+ fs.mkdirSync(path.dirname(file), { recursive: true });
792
+ const token = `${process.pid}.${crypto.randomBytes(8).toString("hex")}`;
793
+ const deadline = Date.now() + LOCK_WAIT_MS;
794
+ for (;;) {
795
+ try {
796
+ const fd = fs.openSync(file, "wx", 0o600);
797
+ fs.writeSync(fd, token);
798
+ fs.closeSync(fd);
799
+ break;
800
+ } catch (err) {
801
+ if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
802
+ try {
803
+ if (Date.now() - fs.statSync(file).mtimeMs > LOCK_STALE_MS) {
804
+ await clearStale(file);
805
+ continue;
806
+ }
807
+ } catch {
808
+ continue; // released between the open and the stat
809
+ }
810
+ if (Date.now() > deadline) throw new Error("the file store is busy — another change is being saved; try again");
811
+ await nap(15 + Math.floor(Math.random() * 20));
812
+ }
813
+ }
814
+ const renew = setInterval(() => {
815
+ try {
816
+ const now = new Date();
817
+ fs.utimesSync(file, now, now);
818
+ } catch {
819
+ // gone: release() notices
820
+ }
821
+ }, LOCK_RENEW_MS);
822
+ renew.unref();
823
+ return () => {
824
+ clearInterval(renew);
825
+ try {
826
+ if (fs.readFileSync(file, "utf8") === token) fs.rmSync(file, { force: true });
827
+ } catch {
828
+ // already gone
829
+ }
830
+ };
831
+ }
832
+
833
+ /**
834
+ * Run `fn` as the only writer of this workspace's file index, in this process
835
+ * and every other one on the volume. Callers of the same workspace in this
836
+ * process queue on a promise chain first, so they do not poll the file against
837
+ * each other. Keep `fn` to index work and blob bookkeeping; bytes a caller
838
+ * already holds are uploaded BEFORE taking the lock (a blob is immutable and
839
+ * named by its hash, so that is safe) and then confirmed present inside it.
840
+ */
841
+ export async function withFileStoreLock<T>(tenant: string, workspace: string, fn: () => Promise<T>): Promise<T> {
842
+ if (!fileStoreEnabled()) return fn();
843
+ const port = records(tenant, workspace);
844
+ if (port) return port.lock(`storage:${tenant}/${workspace}`, fn);
845
+ return withFileLock(lockFile(tenant, workspace), fn);
846
+ }
847
+
848
+ /** The same lock for any path: `file` is the lock file itself (its directory
849
+ * is created). Used by the local RevisionStore, which keeps its own state
850
+ * beside the data it guards. */
851
+ export async function withFileLock<T>(file: string, fn: () => Promise<T>): Promise<T> {
852
+ const prev = lockQueues.get(file) ?? Promise.resolve();
853
+ const run = prev.catch(() => {}).then(async () => {
854
+ const release = await takeFileLock(file);
855
+ try {
856
+ return await fn();
857
+ } finally {
858
+ release();
859
+ }
860
+ });
861
+ lockQueues.set(file, run);
862
+ try {
863
+ return await run;
864
+ } finally {
865
+ if (lockQueues.get(file) === run) lockQueues.delete(file);
866
+ }
867
+ }
868
+
673
869
  // ---------- the store ----------
674
870
 
675
871
  /**
@@ -719,32 +915,52 @@ async function putFileQuietly(
719
915
  throw new Error(`${norm} is ${Math.round(body.length / 1e6)}MB — the limit is ${maxBytes() / 1e6}MB`);
720
916
  }
721
917
  const sha = sha256(body);
722
- const index = readIndex(tenant, workspace);
723
- const previous = index.files.find((f) => f.path === norm);
724
- if (previous?.sha === sha) return previous; // same bytes, same name: nothing happened
725
-
726
- const projected = usedBytes(tenant, workspace) - (previous?.size ?? 0) + body.length;
727
- if (projected > quotaBytes()) {
728
- throw new Error(`workspace file quota exceeded (${quotaBytes() / 1e6}MB)`);
729
- }
730
-
731
918
  const driver = driverFor(tenant, workspace);
732
- await driver.put(blobKey(tenant, workspace, sha), body, mimeFor(norm));
733
-
734
- const record: FileRecord = {
735
- path: norm,
736
- sha,
737
- size: body.length,
738
- mime: mimeFor(norm),
739
- updatedAt: new Date().toISOString(),
740
- by,
741
- };
742
- writeIndex(tenant, workspace, {
743
- version: 1,
744
- files: [...index.files.filter((f) => f.path !== norm), record],
919
+ const key = blobKey(tenant, workspace, sha);
920
+ // A cheap look before the bytes move; the check inside the lock is the one
921
+ // that counts, this one only saves uploading what will be refused.
922
+ {
923
+ const seen = readIndex(tenant, workspace);
924
+ const before = seen.files.find((f) => f.path === norm);
925
+ if (before?.sha !== sha && usedBytes(tenant, workspace) - (before?.size ?? 0) + body.length > quotaBytes()) {
926
+ throw new Error(`workspace file quota exceeded (${quotaBytes() / 1e6}MB)`);
927
+ }
928
+ }
929
+ // The upload happens outside the lock: it can be long, and a blob is
930
+ // immutable and named by its hash, so two writers uploading the same one are
931
+ // harmless. What the lock guards is the index, and the blob's presence while
932
+ // the index names it (see the confirm below).
933
+ await driver.put(key, body, mimeFor(norm));
934
+
935
+ return withFileStoreLock(tenant, workspace, async () => {
936
+ const index = readIndex(tenant, workspace);
937
+ const previous = index.files.find((f) => f.path === norm);
938
+ if (previous?.sha === sha) return previous; // same bytes, same name: nothing happened
939
+
940
+ const projected = usedBytes(tenant, workspace) - (previous?.size ?? 0) + body.length;
941
+ if (projected > quotaBytes()) {
942
+ // Nothing names the blob we just put unless another record already does.
943
+ if (!index.files.some((f) => f.sha === sha)) await driver.remove(key).catch(() => {});
944
+ throw new Error(`workspace file quota exceeded (${quotaBytes() / 1e6}MB)`);
945
+ }
946
+ // A delete or replace that ran between our upload and now may have
947
+ // collected this very blob (it was unreferenced then). We hold the bytes,
948
+ // so put them back before the index points at them. put is a no-op when
949
+ // the object is there.
950
+ if (!(await driver.has(key))) await driver.put(key, body, mimeFor(norm));
951
+
952
+ const record: FileRecord = {
953
+ path: norm,
954
+ sha,
955
+ size: body.length,
956
+ mime: mimeFor(norm),
957
+ updatedAt: new Date().toISOString(),
958
+ by,
959
+ };
960
+ indexPut(tenant, workspace, index, record);
961
+ if (previous) await collectLocked(tenant, workspace, previous.sha);
962
+ return record;
745
963
  });
746
- if (previous) await collect(tenant, workspace, previous.sha);
747
- return record;
748
964
  }
749
965
 
750
966
  /** Register bytes a browser PUT straight to the bucket. Same bookkeeping as
@@ -768,39 +984,45 @@ export async function registerUpload(
768
984
  requireWorkspace(tenant, workspace);
769
985
  const driver = driverFor(tenant, workspace);
770
986
  const key = blobKey(tenant, workspace, sha);
771
- // Trust nothing the browser said: not that the PUT landed, not its size.
772
- const size = await driver.size(key);
773
- if (size === null) {
774
- throw new Error("no object at that key — the upload did not complete");
775
- }
776
- const index = readIndex(tenant, workspace);
777
- const previous = index.files.find((f) => f.path === norm);
778
- const record: FileRecord = {
779
- path: norm,
780
- sha,
781
- size,
782
- mime: mimeFor(norm),
783
- updatedAt: new Date().toISOString(),
784
- by,
785
- };
786
- const files = [...index.files.filter((f) => f.path !== norm), record];
787
- // putFile's two limits, on the real length. A refused object is removed:
788
- // nothing names it, so it would sit in the bucket unreachable and billed —
789
- // unless a record already names these bytes, which are then not ours to drop.
790
- const refuse = async (message: string): Promise<never> => {
791
- if (!index.files.some((f) => f.sha === sha)) await driver.remove(key).catch(() => {});
792
- throw new Error(message);
793
- };
794
- if (size > maxBytes()) {
795
- await refuse(`${norm} is ${Math.round(size / 1e6)}MB — the limit is ${maxBytes() / 1e6}MB`);
796
- }
797
- if (bytesOf(files) > quotaBytes() && bytesOf(files) > bytesOf(index.files)) {
798
- await refuse(`workspace file quota exceeded (${quotaBytes() / 1e6}MB)`);
799
- }
800
- writeIndex(tenant, workspace, { version: 1, files });
801
- if (previous && previous.sha !== sha) await collect(tenant, workspace, previous.sha);
802
- await announceFiles(tenant, workspace, [record.path], by);
803
- return record;
987
+ return withFileStoreLock(tenant, workspace, async () => {
988
+ // Inside the lock, so a collect cannot remove the object between the
989
+ // check that it is there and the index naming it.
990
+ // Trust nothing the browser said: not that the PUT landed, not its size.
991
+ const size = await driver.size(key);
992
+ if (size === null) {
993
+ throw new Error("no object at that key — the upload did not complete");
994
+ }
995
+ const index = readIndex(tenant, workspace);
996
+ const previous = index.files.find((f) => f.path === norm);
997
+ const record: FileRecord = {
998
+ path: norm,
999
+ sha,
1000
+ size,
1001
+ mime: mimeFor(norm),
1002
+ updatedAt: new Date().toISOString(),
1003
+ by,
1004
+ };
1005
+ const files = [...index.files.filter((f) => f.path !== norm), record];
1006
+ // putFile's two limits, on the real length. A refused object is removed:
1007
+ // nothing names it, so it would sit in the bucket unreachable and billed —
1008
+ // unless a record already names these bytes, which are then not ours to drop.
1009
+ const refuse = async (message: string): Promise<never> => {
1010
+ if (!index.files.some((f) => f.sha === sha)) await driver.remove(key).catch(() => {});
1011
+ throw new Error(message);
1012
+ };
1013
+ if (size > maxBytes()) {
1014
+ await refuse(`${norm} is ${Math.round(size / 1e6)}MB — the limit is ${maxBytes() / 1e6}MB`);
1015
+ }
1016
+ if (bytesOf(files) > quotaBytes() && bytesOf(files) > bytesOf(index.files)) {
1017
+ await refuse(`workspace file quota exceeded (${quotaBytes() / 1e6}MB)`);
1018
+ }
1019
+ indexPut(tenant, workspace, index, record);
1020
+ if (previous && previous.sha !== sha) await collectLocked(tenant, workspace, previous.sha);
1021
+ return record;
1022
+ }).then(async (record) => {
1023
+ await announceFiles(tenant, workspace, [record.path], by);
1024
+ return record;
1025
+ });
804
1026
  }
805
1027
 
806
1028
  export async function readFileBytes(
@@ -845,18 +1067,24 @@ export async function openFile(
845
1067
 
846
1068
  export async function deleteFile(tenant: string, workspace: string, rel: string): Promise<boolean> {
847
1069
  const norm = assertFilePath(rel);
848
- const index = readIndex(tenant, workspace);
849
- const record = index.files.find((f) => f.path === norm);
850
- if (!record) return false;
851
- writeIndex(tenant, workspace, { version: 1, files: index.files.filter((f) => f.path !== norm) });
852
- await collect(tenant, workspace, record.sha);
853
- // The run mirror is a cache of the index, so it follows the index.
854
- fs.rmSync(path.join(workspaceDir(tenant, workspace), STORAGE_DIR, norm), { force: true });
855
- return true;
1070
+ return withFileStoreLock(tenant, workspace, async () => {
1071
+ const index = readIndex(tenant, workspace);
1072
+ const record = index.files.find((f) => f.path === norm);
1073
+ if (!record) return false;
1074
+ indexRemove(tenant, workspace, index, norm);
1075
+ await collectLocked(tenant, workspace, record.sha);
1076
+ // The run mirror is a cache of the index, so it follows the index.
1077
+ fs.rmSync(path.join(workspaceDir(tenant, workspace), STORAGE_DIR, norm), { force: true });
1078
+ return true;
1079
+ });
856
1080
  }
857
1081
 
858
- /** Drop a blob once the last record naming it is gone. */
859
- async function collect(tenant: string, workspace: string, sha: string) {
1082
+ /** Drop a blob once the last record naming it is gone. The caller holds the
1083
+ * workspace lock: the reference check and the delete are one step, and a put
1084
+ * that is about to name this blob waits for the lock and then confirms the
1085
+ * blob is present before it does (putFileQuietly), so neither can strand the
1086
+ * other. */
1087
+ async function collectLocked(tenant: string, workspace: string, sha: string) {
860
1088
  if (readIndex(tenant, workspace).files.some((f) => f.sha === sha)) return;
861
1089
  try {
862
1090
  await driverFor(tenant, workspace).remove(blobKey(tenant, workspace, sha));
@@ -951,13 +1179,22 @@ function storeDirOf(tenant: string, workspace: string): string | null {
951
1179
  * unreachable), and a no-op when there is no store.
952
1180
  */
953
1181
  export async function purgeWorkspaceStorage(tenant: string, workspace: string): Promise<void> {
1182
+ if (!fileStoreEnabled()) return;
1183
+ return withFileStoreLock(tenant, workspace, () => purgeUnlocked(tenant, workspace));
1184
+ }
1185
+
1186
+ async function purgeUnlocked(tenant: string, workspace: string): Promise<void> {
954
1187
  const dir = storeDirOf(tenant, workspace);
955
- if (!dir || !fs.existsSync(dir)) return;
1188
+ const port = records(tenant, workspace);
1189
+ // With the index in the database the folder need not exist (a bucket holds
1190
+ // the objects), so the rows decide whether there is anything to purge.
1191
+ if (!dir || (!fs.existsSync(dir) && !(port && port.fileList(tenant, workspace).length))) return;
956
1192
  const driver = driverFor(tenant, workspace);
957
1193
  if (driver.kind !== "fs") {
958
1194
  const shas = new Set(readIndex(tenant, workspace).files.map((f) => f.sha));
959
1195
  for (const sha of shas) await driver.remove(blobKey(tenant, workspace, sha)).catch(() => {});
960
1196
  }
1197
+ if (port) for (const f of port.fileList(tenant, workspace)) port.fileDelete(tenant, workspace, f.path);
961
1198
  fs.rmSync(dir, { recursive: true, force: true });
962
1199
  }
963
1200
 
@@ -976,17 +1213,34 @@ export async function purgeWorkspaceStorage(tenant: string, workspace: string):
976
1213
  * workspace of that name that no longer exists, never to this one.
977
1214
  */
978
1215
  export async function moveWorkspaceStorage(tenant: string, from: string, to: string): Promise<void> {
1216
+ if (!fileStoreEnabled() || from === to) return;
1217
+ // Both names, in a fixed order: an upload to the NEW name must not land in a
1218
+ // store this call is about to replace, and two crossing renames must not
1219
+ // each hold one lock and wait for the other.
1220
+ const [first, second] = [from, to].sort();
1221
+ return withFileStoreLock(tenant, first, () => withFileStoreLock(tenant, second, () => moveUnlocked(tenant, from, to)));
1222
+ }
1223
+
1224
+ async function moveUnlocked(tenant: string, from: string, to: string): Promise<void> {
979
1225
  const src = storeDirOf(tenant, from);
980
1226
  const dest = storeDirOf(tenant, to);
981
1227
  if (!src || !dest || src === dest) return;
982
- if (fs.existsSync(dest)) await purgeWorkspaceStorage(tenant, to);
983
- if (!fs.existsSync(src)) return;
1228
+ const port = records(tenant, from);
1229
+ // Whatever a store under the new name held belonged to a workspace of that
1230
+ // name that no longer exists. (The file index has not moved yet: it moves
1231
+ // below, after the bytes, so rows under `to` are that stale store's.)
1232
+ if (fs.existsSync(dest) || (port && port.fileList(tenant, to).length)) await purgeUnlocked(tenant, to);
1233
+ if (!fs.existsSync(src) && !(port && port.fileList(tenant, from).length)) return;
984
1234
  const driver = driverFor(tenant, from);
985
1235
  const shas = driver.kind === "fs" ? [] : [...new Set(readIndex(tenant, from).files.map((f) => f.sha))];
986
1236
  if (shas.length && !driver.copy) throw new Error(`the ${driver.kind} store cannot move files to a new workspace name`);
987
1237
  for (const sha of shas) await driver.copy!(blobKey(tenant, from, sha), blobKey(tenant, to, sha));
988
- fs.mkdirSync(path.dirname(dest), { recursive: true });
989
- fs.renameSync(src, dest);
1238
+ if (fs.existsSync(src)) {
1239
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
1240
+ fs.renameSync(src, dest);
1241
+ }
1242
+ // The index follows the bytes, once they are all across.
1243
+ port?.fileMove(tenant, from, to);
990
1244
  for (const sha of shas) await driver.remove(blobKey(tenant, from, sha)).catch(() => {});
991
1245
  }
992
1246