@waffle-os/runtime 0.0.156 → 0.0.157

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 (75) hide show
  1. package/browser/filesystem-backend.ts +11 -1
  2. package/browser/preview-protocol.ts +2 -0
  3. package/browser/preview.ts +128 -18
  4. package/browser/runtime-terminals.ts +65 -24
  5. package/browser/shared-fs.ts +141 -14
  6. package/browser/worker.ts +73 -6
  7. package/core/descriptors.ts +19 -2
  8. package/core/devices.ts +237 -2
  9. package/core/fd-reopen.ts +105 -20
  10. package/core/filesystem.ts +71 -0
  11. package/core/index.ts +4 -0
  12. package/core/open-file.ts +212 -18
  13. package/core/wasi.ts +397 -46
  14. package/dist/browser/filesystem-backend.js +4 -2
  15. package/dist/browser/preview.js +120 -17
  16. package/dist/browser/runtime-terminals.js +53 -10
  17. package/dist/browser/shared-fs.js +124 -11
  18. package/dist/browser/worker.js +59 -6
  19. package/dist/core/descriptors.js +9 -1
  20. package/dist/core/devices.js +211 -1
  21. package/dist/core/fd-reopen.js +79 -18
  22. package/dist/core/filesystem.js +13 -0
  23. package/dist/core/open-file.js +166 -13
  24. package/dist/core/wasi.js +353 -27
  25. package/dist/fs/backend.js +29 -2
  26. package/dist/fs/client.js +199 -6
  27. package/dist/fs/index.js +21 -1
  28. package/dist/fs/indexeddb.js +30 -2
  29. package/dist/fs/locks.js +1112 -0
  30. package/dist/fs/memory.js +109 -1
  31. package/dist/fs/multitab-backend.js +315 -195
  32. package/dist/fs/multitab-protocol.js +1 -0
  33. package/dist/fs/persistent.js +13 -6
  34. package/dist/fs/protocol.js +9 -3
  35. package/dist/fs/service.js +386 -22
  36. package/dist/fs/shared.js +54 -1
  37. package/dist/fs/storage-geometry.js +2 -0
  38. package/dist/interrupt/rewriter-internal.js +4 -1
  39. package/dist/proc/abi.js +80 -6
  40. package/dist/proc/errors.js +1 -0
  41. package/dist/proc/filesystem-codec.js +40 -9
  42. package/dist/proc/index.js +10 -1
  43. package/dist/proc/pty.js +193 -0
  44. package/dist/proc/worker-client.js +11 -2
  45. package/dist/proc/worker-pipes.js +51 -0
  46. package/dist/runtime.js +11 -2
  47. package/dist/search/engine.js +53 -0
  48. package/dist/tooling/program/program-transformer.json +1 -1
  49. package/fs/backend.ts +33 -1
  50. package/fs/client.ts +225 -6
  51. package/fs/index.ts +22 -1
  52. package/fs/indexeddb.ts +36 -2
  53. package/fs/locks.ts +1406 -0
  54. package/fs/memory.ts +114 -1
  55. package/fs/multitab-backend.ts +561 -303
  56. package/fs/multitab-protocol.ts +1 -0
  57. package/fs/persistent.ts +14 -3
  58. package/fs/protocol.ts +17 -5
  59. package/fs/service.ts +468 -23
  60. package/fs/shared.ts +60 -2
  61. package/fs/storage-geometry.ts +3 -0
  62. package/index.ts +2 -0
  63. package/interrupt/rewriter-internal.ts +4 -1
  64. package/package.json +2 -2
  65. package/proc/abi.ts +79 -6
  66. package/proc/errors.ts +1 -0
  67. package/proc/filesystem-codec.ts +39 -9
  68. package/proc/index.ts +11 -0
  69. package/proc/pty.ts +227 -0
  70. package/proc/worker-client.ts +28 -6
  71. package/proc/worker-pipes.ts +57 -0
  72. package/runtime.ts +12 -2
  73. package/search/engine.ts +49 -0
  74. package/testing/indexeddb-storage-browser.ts +173 -2
  75. package/tooling/program/program-transformer.json +1 -1
package/dist/runtime.js CHANGED
@@ -31,6 +31,7 @@ const filesystemCapabilities = {
31
31
  drain: "async",
32
32
  flush: "async",
33
33
  resolvePath: "async",
34
+ stat: "async",
34
35
  lookup: "async",
35
36
  readFile: "async",
36
37
  listFiles: "async",
@@ -40,6 +41,7 @@ const filesystemCapabilities = {
40
41
  move: "async",
41
42
  workspace: "readonly",
42
43
  state: "readonly",
44
+ machineId: "readonly",
43
45
  vfs: "readonly",
44
46
  ownershipLost: "readonly",
45
47
  onOwnershipLost: "callback",
@@ -649,9 +651,16 @@ export function createRuntime(options = {}) {
649
651
  }
650
652
  while (launching.size)
651
653
  await Promise.allSettled(Array.from(launching));
652
- if (!pendingStartup) {
654
+ if (!pendingStartup && !filesystem.ownershipLost) {
653
655
  filesystem.beginRuntimeDispose();
654
- await attempt(() => filesystem.drain());
656
+ await attempt(async () => {
657
+ try {
658
+ await filesystem.drain();
659
+ } catch (error) {
660
+ if (!filesystem.ownershipLost)
661
+ throw error;
662
+ }
663
+ });
655
664
  }
656
665
  const failuresBeforeFences = failures.length;
657
666
  await Promise.all([
@@ -19,6 +19,44 @@ function displayPath(root, relative, tool) {
19
19
  const prefix = tool === "grep" ? root.replace(/\/+$/, "/") : root;
20
20
  return prefix.endsWith("/") ? `${prefix}${relative}` : `${prefix}/${relative}`;
21
21
  }
22
+ function matchStarGlob(glob, text) {
23
+ let g = 0;
24
+ let t = 0;
25
+ let star = -1;
26
+ let match = 0;
27
+ while (t < text.length) {
28
+ if (g < glob.length && glob[g] === "*") {
29
+ star = g++;
30
+ match = t;
31
+ } else if (g < glob.length && glob[g] === text[t]) {
32
+ g++;
33
+ t++;
34
+ } else if (star !== -1) {
35
+ g = star + 1;
36
+ t = ++match;
37
+ } else {
38
+ return false;
39
+ }
40
+ }
41
+ while (g < glob.length && glob[g] === "*")
42
+ g++;
43
+ return g === glob.length;
44
+ }
45
+ function matchPathSuffix(glob, path) {
46
+ let offset = 0;
47
+ for (;; ) {
48
+ if (matchStarGlob(glob, path.slice(offset)))
49
+ return true;
50
+ let slash = path.indexOf("/", offset);
51
+ if (slash === -1)
52
+ return false;
53
+ while (slash < path.length && path[slash] === "/")
54
+ slash++;
55
+ if (slash >= path.length)
56
+ return false;
57
+ offset = slash;
58
+ }
59
+ }
22
60
 
23
61
  export class WalkSource {
24
62
  context;
@@ -84,6 +122,10 @@ export class WalkSource {
84
122
  return;
85
123
  }
86
124
  if (opened.kind === "file") {
125
+ if (!this.matchesExplicitFile(path)) {
126
+ this.context.fs.release(opened.handle);
127
+ return;
128
+ }
87
129
  this.add(entries, { kind: "file", path, handle: opened.handle, size: opened.size }, { kind: "open", handle: opened.handle });
88
130
  return;
89
131
  }
@@ -93,6 +135,17 @@ export class WalkSource {
93
135
  this.add(entries, { kind: "error", path, errno: errnoOf(error) });
94
136
  }
95
137
  }
138
+ matchesExplicitFile(path) {
139
+ if (this.context.request.plan.tool !== "grep")
140
+ return true;
141
+ const { include, exclude } = this.context.request.plan.walk;
142
+ if (include.length === 0 && exclude.length === 0)
143
+ return true;
144
+ const matches = (pattern) => matchPathSuffix(pattern.glob, path);
145
+ if (include.length > 0 && !include.some(matches))
146
+ return false;
147
+ return !exclude.some(matches);
148
+ }
96
149
  openWalk(path, handle) {
97
150
  try {
98
151
  const original = this.context.fs.walkOpen(handle, this.context.request.plan.walk);
@@ -1 +1 @@
1
- {"commit":"be2e58bebc094d5185f24f45ed2b7be27d985f30","buildToolsSha256":"b617652c1601f8722bb85c3a688a1fca4985b53f2c2066c10c76c2e693081137","optimizerSourceSha256":"34c4a040f3cf639f039823880822c6541c384c9b4eaa116d27dda8d9cb5c9f9e"}
1
+ {"commit":"009023cdfec2eef3e9e0502ad18609021dc86dd3","buildToolsSha256":"b617652c1601f8722bb85c3a688a1fca4985b53f2c2066c10c76c2e693081137","optimizerSourceSha256":"34c4a040f3cf639f039823880822c6541c384c9b4eaa116d27dda8d9cb5c9f9e"}
package/fs/backend.ts CHANGED
@@ -26,7 +26,8 @@ import {
26
26
  } from "../core/filesystem.js";
27
27
  import { MemFS, type Node, type NamespacePlan } from "./memory.js";
28
28
  import { FilesystemError, type FilesystemIdentity } from "./protocol.js";
29
- import { SharedFilesystemState, type SharedSegment } from "./shared.js";
29
+ import { machineIdFromWorkspace, SharedFilesystemState, type SharedSegment } from "./shared.js";
30
+ import { validateMachineId } from "../core/devices.js";
30
31
 
31
32
  /** Storage boundary. 3b can add asynchronous loading/commit without changing guest transport. */
32
33
  export interface FilesystemBackend {
@@ -78,6 +79,8 @@ export interface FilesystemBackend {
78
79
  beginShutdown?(): void;
79
80
  /** Whether this backend supports Unix domain socket scope attachment (defaults to true for MemoryBackend). */
80
81
  readonly supportsSockets?: boolean;
82
+ /** Whether this backend supports advisory file locks (defaults to true for single-owner backends). */
83
+ readonly supportsLocks?: boolean;
81
84
  /** Whether async execute/flush/watch rejections are handled client results rather than fatal service shutdown failures. */
82
85
  readonly asyncErrorsAreClientResults?: boolean;
83
86
  /** Re-verify lease / terminal state before publishing a prepared cold descriptor read. */
@@ -208,6 +211,7 @@ export class MemoryBackend implements FilesystemBackend {
208
211
  return (node.identity ??= this.shared.identities.create());
209
212
  }
210
213
  readonly workspaceId: string;
214
+ readonly machineId: string;
211
215
  readonly fs: MemFS;
212
216
  readonly watchAccount: RootWatchAccount;
213
217
  constructor(
@@ -216,6 +220,7 @@ export class MemoryBackend implements FilesystemBackend {
216
220
  startupRoot?: MemoryBudget | MemoryBackend,
217
221
  watchLimits?: WatchResourceLimits,
218
222
  sharedRoot?: MemoryBackendSharedRoot,
223
+ machineId?: string,
219
224
  ) {
220
225
  if (sharedRoot && startupRoot)
221
226
  throw new TypeError("an imported root cannot also own a startup root");
@@ -225,6 +230,7 @@ export class MemoryBackend implements FilesystemBackend {
225
230
  this.watchAccount = startupRoot.watchAccount;
226
231
  this.fs = startupRoot.fs;
227
232
  this.workspaceId = startupRoot.workspaceId;
233
+ this.machineId = startupRoot.machineId;
228
234
  this.shared = startupRoot.shared;
229
235
  this.startupRoot = startupRoot.startupRoot;
230
236
  this.sharedPhase = startupRoot.sharedPhase;
@@ -246,7 +252,12 @@ export class MemoryBackend implements FilesystemBackend {
246
252
  if (sharedRoot) this.sharedPhase = "imported";
247
253
  this.fs = fs;
248
254
  this.workspaceId = reservation.workspace;
255
+ this.machineId =
256
+ machineId !== undefined
257
+ ? validateMachineId(machineId)
258
+ : machineIdFromWorkspace(reservation.workspace);
249
259
  this.shared.identities.configure(reservation);
260
+ this.shared.setMachineId(this.machineId);
250
261
  const seen = new Set<Node>();
251
262
  const pending: Node[] = [fs.root];
252
263
  while (pending.length) {
@@ -300,6 +311,7 @@ export class MemoryBackend implements FilesystemBackend {
300
311
  publication,
301
312
  );
302
313
  if (this.sharedPhase !== "imported") this.shared.identities.copyFrom(previous.identities);
314
+ this.shared.setMachineId(this.machineId);
303
315
  this.shared.continueUnlinks(previous);
304
316
  this.sharedPhase = "attached";
305
317
  }
@@ -523,6 +535,8 @@ export class MemoryBackend implements FilesystemBackend {
523
535
  }
524
536
  case "lookup":
525
537
  return this.lookup(a);
538
+ case "statPath":
539
+ return this.statPath(a, b !== false);
526
540
  case "readFile": {
527
541
  const existing = this.existing(a);
528
542
  if (!existing) return;
@@ -535,6 +549,24 @@ export class MemoryBackend implements FilesystemBackend {
535
549
  throw new FilesystemError(52, `unknown filesystem operation ${operation}`);
536
550
  }
537
551
  }
552
+ private statPath(path: string, follow: boolean): unknown {
553
+ const node = this.fs.lookup(path, follow);
554
+ if (!node) return;
555
+ const handle = this.fs.handleForNode(node);
556
+ const fsStat = this.fs.stat(handle);
557
+ const stat = this.shared.stat(handle);
558
+ return {
559
+ kind: node.kind,
560
+ size: stat ? stat.size : fsStat.size,
561
+ ino: node.ino,
562
+ mtime: fileTimeMs(stat ? stat.mtime : fsStat.mtime),
563
+ ctime: fileTimeMs(stat ? stat.ctime : fsStat.ctime),
564
+ atime: fileTimeMs(stat ? stat.atime : fsStat.atime),
565
+ mode: stat ? stat.mode : fsStat.mode,
566
+ nlink: stat ? stat.nlink : fsStat.nlink,
567
+ ...(node.kind === "symlink" ? { target: node.target } : {}),
568
+ };
569
+ }
538
570
  private lookup(path: string): unknown {
539
571
  const node = this.fs.lookup(path, false);
540
572
  if (!node) return;
package/fs/client.ts CHANGED
@@ -40,10 +40,15 @@ import {
40
40
  fileTimeNow,
41
41
  isFileTime,
42
42
  permissionsFor,
43
+ type FileLockConflict,
44
+ type FileLockRange,
45
+ type FileLockSystem,
43
46
  type FileTime,
47
+ type LockWaitControl,
44
48
  type ProbeKind,
45
49
  type WatchFileSystem,
46
50
  } from "../core/filesystem.js";
51
+ import { ExecutionUnwind } from "../core/unwind.js";
47
52
  import {
48
53
  ArrayBufferConstructor,
49
54
  Int32ArrayConstructor,
@@ -377,12 +382,40 @@ export class FilesystemCompletion {
377
382
  wait(): any {
378
383
  return this.#wait();
379
384
  }
380
- #wait(cancellation?: WaitCancellation): any {
385
+ waitInterruptible(control?: LockWaitControl): any {
386
+ return this.#wait(undefined, control);
387
+ }
388
+ private checkWaitControl(control: LockWaitControl | undefined): void {
389
+ if (!control) return;
390
+ try {
391
+ control.checkActive?.();
392
+ } catch (error) {
393
+ this.cancel();
394
+ throw error;
395
+ }
396
+ if (!control.interruptPending?.()) return;
397
+ this.cancel();
398
+ throw new FilesystemError(27);
399
+ }
400
+ private parkWait(signal: Int32Array, observed: number, control?: LockWaitControl): void {
401
+ if (control?.wait) {
402
+ try {
403
+ control.wait(signal, observed, 10);
404
+ } catch (error) {
405
+ this.cancel();
406
+ throw error;
407
+ }
408
+ return;
409
+ }
410
+ atomicsWait(signal, 0, observed, control?.interruptPending ? 10 : undefined);
411
+ }
412
+ #wait(cancellation?: WaitCancellation, control?: LockWaitControl): any {
381
413
  const signal = this.client.signal;
382
414
  while (!this.ready) {
383
415
  const observed = atomicsLoad(signal, 0);
384
416
  this.check(cancellation);
385
- if (!this.ready) atomicsWait(signal, 0, observed);
417
+ this.checkWaitControl(control);
418
+ if (!this.ready) this.parkWait(signal, observed, control);
386
419
  }
387
420
  this.check(cancellation);
388
421
  if (this.consumed) return this.decoded;
@@ -528,6 +561,69 @@ function clientWatches(
528
561
  };
529
562
  }
530
563
 
564
+ function isTerminalLockReleaseErrno(code: number): boolean {
565
+ // Non-retryable release outcomes (already gone, bad fd, unsupported, revoked/cancelled/reset).
566
+ return (
567
+ code === 2 ||
568
+ code === 8 ||
569
+ code === 11 ||
570
+ code === 15 ||
571
+ code === 28 ||
572
+ code === 44 ||
573
+ code === 58
574
+ );
575
+ }
576
+
577
+ function clientLocks(
578
+ owner: number,
579
+ call: (operation: string, args: unknown[], control?: LockWaitControl) => any,
580
+ release: (operation: "lockReleaseOfd" | "lockReleasePosix", args: unknown[]) => void,
581
+ hasActivePosixLocks: () => boolean,
582
+ ): FileLockSystem {
583
+ return {
584
+ owner,
585
+ flock: (handle, ofdId, operation, control) => {
586
+ try {
587
+ return call("lockFlock", [handle, ofdId, operation], control);
588
+ } catch (error) {
589
+ if (isInstance(error, ExecutionUnwind)) throw error;
590
+ return errno(error);
591
+ }
592
+ },
593
+ setRangeLock: (handle, ofdId, pid, range: FileLockRange, blocking, control) => {
594
+ try {
595
+ return call(
596
+ "lockRange",
597
+ [handle, ofdId ?? null, pid, range.type, range.start, range.len, blocking],
598
+ blocking ? control : undefined,
599
+ );
600
+ } catch (error) {
601
+ if (isInstance(error, ExecutionUnwind)) throw error;
602
+ return errno(error);
603
+ }
604
+ },
605
+ getRangeLock: (handle, ofdId, range: FileLockRange): FileLockConflict | number => {
606
+ try {
607
+ return call("lockGetRange", [handle, ofdId ?? null, range.type, range.start, range.len]);
608
+ } catch (error) {
609
+ return errno(error);
610
+ }
611
+ },
612
+ releaseOfd: (handle, ofdId, inFlight = false) => {
613
+ release("lockReleaseOfd", [handle, ofdId, inFlight]);
614
+ },
615
+ releasePosix: (handle) => {
616
+ release("lockReleasePosix", [handle]);
617
+ },
618
+ handoffPosix: (successorOwner) => {
619
+ try {
620
+ call("lockHandoffPosix", [successorOwner]);
621
+ } catch {}
622
+ },
623
+ hasActivePosixLocks,
624
+ };
625
+ }
626
+
531
627
  /** Blocking preview1 adapter and non-blocking request/completion API for the async host.
532
628
  * Read/stat caches are validated by the service's global seqlock. A concurrent mutation invalidates
533
629
  * before changing data; a cached read that overlaps it is discarded, never returned as fresh.
@@ -621,6 +717,17 @@ export class FilesystemClient implements FileSystem {
621
717
  private readonly section: FilesystemSection;
622
718
  readonly shared: SharedFilesystemState;
623
719
  readonly watches: WatchFileSystem;
720
+ readonly locks: FileLockSystem;
721
+ get machineId(): string | undefined {
722
+ return this.shared.getMachineId();
723
+ }
724
+ private pendingLockReleases: {
725
+ readonly operation: "lockReleaseOfd" | "lockReleasePosix";
726
+ readonly args: unknown[];
727
+ readonly retainedHandle?: number;
728
+ }[] = [];
729
+ private lockReleaseTimer?: ReturnType<typeof scheduleTimeout>;
730
+ private flushingLockReleases = false;
624
731
  private watchingRevocation = false;
625
732
  private resident: ResidentAttachment | undefined;
626
733
  private workspaceStop: Promise<void> | undefined;
@@ -658,6 +765,20 @@ export class FilesystemClient implements FileSystem {
658
765
  () => !this.shared.isWatchDrainDisabled(),
659
766
  (operation, args) => this.call(operation, args),
660
767
  );
768
+ this.locks = clientLocks(
769
+ connection.owner,
770
+ (operation, args, control) => {
771
+ if (this.pendingLockReleases.length > 0) this.flushPendingLockReleases();
772
+ const completion = this.submit(operation, args);
773
+ try {
774
+ return control ? completion.waitInterruptible(control) : completion.wait();
775
+ } finally {
776
+ completion.release();
777
+ }
778
+ },
779
+ (operation, args) => this.enqueueLockRelease(operation, args),
780
+ () => this.shared.posixLockCount() > 0,
781
+ );
661
782
  connection.port.onmessage = ({ data }) => {
662
783
  if (data.segment) this.attachSegment(data.segment, data.buffer);
663
784
  else mapGet(this.completions, data.completed)?.notify();
@@ -935,10 +1056,11 @@ export class FilesystemClient implements FileSystem {
935
1056
  mapSet(this.capabilityEntries, reservation.handle, reservation.targetKey);
936
1057
  }
937
1058
  releaseReservation(reservation: FilesystemReservation): void {
938
- const state = new Int32ArrayConstructor(reservation.state);
939
- const wasClosed = atomicsLoad(state, 0);
940
- releaseFilesystemReservation(reservation);
941
- if (!wasClosed) {
1059
+ this.finishReleasedReservation(reservation, releaseFilesystemReservation(reservation));
1060
+ }
1061
+ /** Drop local handle accounting after `releaseFilesystemReservation` has already run. */
1062
+ finishReleasedReservation(reservation: FilesystemReservation, released: boolean): void {
1063
+ if (released) {
942
1064
  const count = mapGet(this.openHandles, reservation.handle) ?? 0;
943
1065
  if (count > 1) mapSet(this.openHandles, reservation.handle, count - 1);
944
1066
  else {
@@ -1094,7 +1216,102 @@ export class FilesystemClient implements FileSystem {
1094
1216
  const completion = mapGet(this.completions, id);
1095
1217
  return completion && { kind: 3, id, ready: completion.ready };
1096
1218
  }
1219
+ private retainLockReleaseHandle(handle: number): number | undefined {
1220
+ if (!Number.isInteger(handle) || handle < 0) return undefined;
1221
+ try {
1222
+ this.retain(handle);
1223
+ return handle;
1224
+ } catch {
1225
+ return undefined;
1226
+ }
1227
+ }
1228
+ private releaseLockReleaseHandle(retainedHandle: number | undefined): void {
1229
+ if (retainedHandle === undefined) return;
1230
+ try {
1231
+ this.release(retainedHandle);
1232
+ } catch {
1233
+ // Session already revoked or disposed; server teardown drops locks.
1234
+ }
1235
+ }
1236
+ private finishNextLockRelease(): void {
1237
+ const removed = this.pendingLockReleases.splice(0, 1);
1238
+ if (removed.length > 0) this.releaseLockReleaseHandle(removed[0]!.retainedHandle);
1239
+ }
1240
+ private enqueueLockRelease(
1241
+ operation: "lockReleaseOfd" | "lockReleasePosix",
1242
+ args: unknown[],
1243
+ ): void {
1244
+ if (this.disposed || this.revoked()) return;
1245
+ const handle = typeof args[0] === "number" ? args[0] : -1;
1246
+ const retainedHandle = this.retainLockReleaseHandle(handle);
1247
+ arrayAppend(this.pendingLockReleases, { operation, args, retainedHandle });
1248
+ this.flushPendingLockReleases();
1249
+ }
1250
+ private scheduleLockReleaseRetry(): void {
1251
+ if (this.lockReleaseTimer !== undefined || this.disposed || this.revoked()) return;
1252
+ this.lockReleaseTimer = scheduleTimeout(() => {
1253
+ this.lockReleaseTimer = undefined;
1254
+ this.flushPendingLockReleases();
1255
+ }, 1);
1256
+ }
1257
+ private clearLockReleaseQueue(): void {
1258
+ const pending = this.pendingLockReleases.splice(0);
1259
+ for (let i = 0; i < pending.length; i++)
1260
+ this.releaseLockReleaseHandle(pending[i]!.retainedHandle);
1261
+ if (this.lockReleaseTimer !== undefined) {
1262
+ cancelTimeout(this.lockReleaseTimer);
1263
+ this.lockReleaseTimer = undefined;
1264
+ }
1265
+ }
1266
+ private deliverNextLockRelease(): boolean {
1267
+ const next = this.pendingLockReleases[0]!;
1268
+ let completion: FilesystemCompletion;
1269
+ try {
1270
+ completion = this.submit(next.operation, next.args);
1271
+ } catch (error) {
1272
+ if (this.revoked() || isTerminalLockReleaseErrno(errno(error))) {
1273
+ this.finishNextLockRelease();
1274
+ return true;
1275
+ }
1276
+ this.scheduleLockReleaseRetry();
1277
+ return false;
1278
+ }
1279
+ try {
1280
+ completion.wait();
1281
+ this.finishNextLockRelease();
1282
+ return true;
1283
+ } catch (error) {
1284
+ if (this.revoked() || isTerminalLockReleaseErrno(errno(error))) {
1285
+ this.finishNextLockRelease();
1286
+ return true;
1287
+ }
1288
+ this.scheduleLockReleaseRetry();
1289
+ return false;
1290
+ } finally {
1291
+ completion.release();
1292
+ }
1293
+ }
1294
+ private flushPendingLockReleases(): void {
1295
+ if (this.flushingLockReleases || this.pendingLockReleases.length === 0) return;
1296
+ if (this.disposed || this.revoked()) {
1297
+ this.clearLockReleaseQueue();
1298
+ return;
1299
+ }
1300
+ this.flushingLockReleases = true;
1301
+ try {
1302
+ while (this.pendingLockReleases.length > 0) {
1303
+ if (this.disposed || this.revoked()) {
1304
+ this.clearLockReleaseQueue();
1305
+ return;
1306
+ }
1307
+ if (!this.deliverNextLockRelease()) return;
1308
+ }
1309
+ } finally {
1310
+ this.flushingLockReleases = false;
1311
+ }
1312
+ }
1097
1313
  call(operation: string, args: unknown[] = [], data?: Uint8Array): any {
1314
+ if (this.pendingLockReleases.length > 0) this.flushPendingLockReleases();
1098
1315
  const completion = this.submit(operation, args, data);
1099
1316
  try {
1100
1317
  return completion.wait();
@@ -1155,6 +1372,8 @@ export class FilesystemClient implements FileSystem {
1155
1372
  }
1156
1373
  dispose(): void {
1157
1374
  if (this.finishedDispose) return;
1375
+ this.flushPendingLockReleases();
1376
+ this.clearLockReleaseQueue();
1158
1377
  this.disposed = true;
1159
1378
  this.resident?.invalidate();
1160
1379
  this.beginWorkspaceStop();
package/fs/index.ts CHANGED
@@ -37,7 +37,12 @@ export {
37
37
  } from "./shared.js";
38
38
 
39
39
  export { PersistentBackend } from "./persistent.js";
40
- export { IndexedDBStorage } from "./indexeddb.js";
40
+ export {
41
+ IndexedDBStorage,
42
+ IndexedDBStorageBusyError,
43
+ IndexedDBStorageMissingError,
44
+ type IndexedDBStorageOptions,
45
+ } from "./indexeddb.js";
41
46
  export { OpfsStorage, type OpfsStorageOptions } from "./opfs.js";
42
47
  export type { StorageBackend, PersistedIndex, PersistedNode, PersistenceBatch } from "./storage.js";
43
48
 
@@ -70,6 +75,22 @@ export {
70
75
  export { WorkspaceArchiveError } from "./workspace-archive.js";
71
76
 
72
77
  export { FilesystemWatch, type WatchOptions, type WatchEvent, type WatchBatch } from "./watch.js";
78
+ export {
79
+ LOCK_SH,
80
+ LOCK_EX,
81
+ LOCK_NB,
82
+ LOCK_UN,
83
+ F_GETLK,
84
+ F_SETLK,
85
+ F_SETLKW,
86
+ F_OFD_GETLK,
87
+ F_OFD_SETLK,
88
+ F_OFD_SETLKW,
89
+ F_RDLCK,
90
+ F_WRLCK,
91
+ F_UNLCK,
92
+ } from "../core/filesystem.js";
93
+ export { LockTable, LockContentionError, type LockCommit } from "./locks.js";
73
94
 
74
95
  export {
75
96
  openWorkspaceRead,
package/fs/indexeddb.ts CHANGED
@@ -88,6 +88,13 @@ export class IndexedDBStorageBusyError extends Error {
88
88
  }
89
89
  }
90
90
 
91
+ export class IndexedDBStorageMissingError extends Error {
92
+ override readonly name = "IndexedDBStorageMissingError";
93
+ constructor(message = "IndexedDB storage database does not exist") {
94
+ super(message);
95
+ }
96
+ }
97
+
91
98
  export interface IndexedDBStorageOptions {
92
99
  readonly retainOpeningDebt?: (debt: Promise<void>) => void;
93
100
  indexedDB?: IDBFactory;
@@ -107,6 +114,12 @@ export interface IndexedDBStorageOptions {
107
114
  expectedEpoch?: number;
108
115
  /** Verified under exclusive arbLock before submitting steal:true on the writer lock. */
109
116
  verifyStealTarget?: (snapshot: LockManagerSnapshot) => boolean;
117
+ /**
118
+ * When false, opening an absent database aborts the upgrade transaction while holding the
119
+ * maintenance lock and rejects with IndexedDBStorageMissingError without creating the database
120
+ * or allocating epoch 1. Defaults to true.
121
+ */
122
+ createIfMissing?: boolean;
110
123
  }
111
124
  /** Retains physical native completion independently of caller-visible startup rejection. */
112
125
  class NativeDatabaseOpening {
@@ -116,6 +129,7 @@ class NativeDatabaseOpening {
116
129
  private database: IDBDatabase | undefined;
117
130
  private closing: Promise<void> | undefined;
118
131
  private blocked = false;
132
+ private missing = false;
119
133
  private readonly abort = () => this.outcome.reject(this.signal?.reason);
120
134
 
121
135
  constructor(
@@ -133,10 +147,18 @@ class NativeDatabaseOpening {
133
147
  this.completion.resolve();
134
148
  return;
135
149
  }
150
+ const createIfMissing = options.createIfMissing ?? true;
136
151
  try {
137
152
  const request = factory.open(name, 1);
138
153
  signal?.addEventListener("abort", this.abort, { once: true });
139
- request.onupgradeneeded = () => createStores(request.result);
154
+ request.onupgradeneeded = () => {
155
+ if (createIfMissing) {
156
+ createStores(request.result);
157
+ return;
158
+ }
159
+ this.missing = true;
160
+ request.transaction?.abort();
161
+ };
140
162
  request.onsuccess = () => this.delivered(request.result);
141
163
  request.onerror = () => this.failed(request.error);
142
164
  request.onblocked = () => this.blockedRequest();
@@ -153,6 +175,11 @@ class NativeDatabaseOpening {
153
175
  private delivered(database: IDBDatabase): void {
154
176
  this.stopObserving();
155
177
  this.database = database;
178
+ if (this.missing) {
179
+ this.outcome.reject(new IndexedDBStorageMissingError());
180
+ void this.retire().catch(() => {});
181
+ return;
182
+ }
156
183
  if (this.signal?.aborted || this.blocked) {
157
184
  void this.retire().catch(() => {});
158
185
  return;
@@ -165,6 +192,11 @@ class NativeDatabaseOpening {
165
192
  }
166
193
  private failed(error: DOMException | null): void {
167
194
  this.stopObserving();
195
+ if (this.missing) {
196
+ this.outcome.reject(new IndexedDBStorageMissingError());
197
+ this.completion.resolve();
198
+ return;
199
+ }
168
200
  this.outcome.reject(
169
201
  error?.name === "VersionError"
170
202
  ? new VfsError("INVALID_VFS_FORMAT", "indexeddb", "Incompatible IndexedDB database version")
@@ -1237,9 +1269,11 @@ export class IndexedDBStorage implements StorageBackend {
1237
1269
  () => maintenance.release(),
1238
1270
  );
1239
1271
  } catch (error) {
1240
- void Promise.all(debts)
1272
+ const cleanup = Promise.all(debts)
1241
1273
  .then(() => maintenance.release())
1242
1274
  .catch(() => {});
1275
+ if (error instanceof IndexedDBStorageMissingError) await cleanup;
1276
+ else void cleanup;
1243
1277
  throw error;
1244
1278
  }
1245
1279
  }