@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
@@ -9,7 +9,7 @@ export async function openFilesystemBackend(options, lifecycle) {
9
9
  const { descriptor, whenBusy } = resolveVfs(options, options.implementation);
10
10
  requireVfsCapabilities(descriptor.implementation, whenBusy);
11
11
  if (descriptor.implementation === "memory")
12
- return new MemoryBackend(undefined, undefined, options.startupRoot, undefined, options.connect);
12
+ return new MemoryBackend(undefined, undefined, options.startupRoot, undefined, options.connect, options.machineId);
13
13
  if (whenBusy === "attach") {
14
14
  const { MultiTabBackend } = await import("../fs/multitab-backend.js");
15
15
  return MultiTabBackend.open({
@@ -17,6 +17,7 @@ export async function openFilesystemBackend(options, lifecycle) {
17
17
  name: options.name ?? "waffle-workspace",
18
18
  startupRoot: options.startupRoot,
19
19
  sharedRoot: options.connect,
20
+ machineId: options.machineId,
20
21
  onStartupStage: lifecycle.onStartupStage,
21
22
  signal: lifecycle.signal,
22
23
  onWaiting: lifecycle.onWaiting,
@@ -39,7 +40,8 @@ export async function openFilesystemBackend(options, lifecycle) {
39
40
  lifecycle.retainStorage(storage);
40
41
  backend = await PersistentBackend.open(storage, {
41
42
  startupRoot: options.startupRoot,
42
- sharedRoot: options.connect
43
+ sharedRoot: options.connect,
44
+ machineId: options.machineId
43
45
  });
44
46
  if (ownershipLost) {
45
47
  backend.dispose();
@@ -1,7 +1,11 @@
1
+ const DEFAULT_SOCKET_PING_MS = 15000;
2
+ const DEFAULT_SOCKET_MISSED_PINGS = 3;
3
+
1
4
  export class PreviewRouter {
2
5
  options;
3
6
  servers = new Map;
4
7
  hosts = new Map;
8
+ sockets = new Map;
5
9
  owner;
6
10
  constructor(options) {
7
11
  this.options = options;
@@ -48,6 +52,31 @@ export class PreviewRouter {
48
52
  }
49
53
  return host;
50
54
  }
55
+ closePortSockets(port) {
56
+ const active = this.sockets.get(port);
57
+ if (!active)
58
+ return;
59
+ this.sockets.delete(port);
60
+ for (const close of Array.from(active))
61
+ close();
62
+ }
63
+ close() {
64
+ const errors = [];
65
+ for (const port of Array.from(this.sockets.keys()))
66
+ this.closePortSockets(port);
67
+ for (const [port, host] of Array.from(this.hosts)) {
68
+ this.hosts.delete(port);
69
+ try {
70
+ host.close();
71
+ } catch (error) {
72
+ errors.push(error);
73
+ }
74
+ }
75
+ if (errors.length === 1)
76
+ throw errors[0];
77
+ if (errors.length > 1)
78
+ throw new AggregateError(errors, "PreviewRouter close failed");
79
+ }
51
80
  serves(port) {
52
81
  return this.servers.has(port);
53
82
  }
@@ -56,6 +85,7 @@ export class PreviewRouter {
56
85
  return;
57
86
  const previous = this.hosts.get(port);
58
87
  this.hosts.delete(port);
88
+ this.closePortSockets(port);
59
89
  this.servers.set(port, server);
60
90
  previous?.close();
61
91
  }
@@ -65,13 +95,16 @@ export class PreviewRouter {
65
95
  this.servers.delete(port);
66
96
  const previous = this.hosts.get(port);
67
97
  this.hosts.delete(port);
98
+ this.closePortSockets(port);
68
99
  previous?.close();
69
100
  }
70
101
  connectSocket(port, reply) {
71
102
  const pending = [];
72
103
  let ready = false;
73
104
  let finished = false;
105
+ let missedPings = 0;
74
106
  let connection = null;
107
+ let pingTimer;
75
108
  const send = (message, transfer = []) => {
76
109
  if (finished)
77
110
  return;
@@ -79,42 +112,112 @@ export class PreviewRouter {
79
112
  pending.push({ message, transfer });
80
113
  return;
81
114
  }
82
- reply.postMessage(message, transfer);
115
+ try {
116
+ reply.postMessage(message, transfer);
117
+ } catch {
118
+ closeTunnel();
119
+ }
83
120
  };
84
- const finish = (message) => {
85
- send(message);
121
+ const onPeerClose = () => closeTunnel();
122
+ let closing = false;
123
+ const closeTunnel = (finalMessage) => {
124
+ if (finished)
125
+ return;
126
+ if (finalMessage) {
127
+ send(finalMessage);
128
+ finished = true;
129
+ }
130
+ if (closing)
131
+ return;
132
+ closing = true;
133
+ if (pingTimer !== undefined) {
134
+ clearInterval(pingTimer);
135
+ pingTimer = undefined;
136
+ }
137
+ this.sockets.get(port)?.delete(closeTunnel);
138
+ reply.removeEventListener?.("close", onPeerClose);
139
+ reply.onmessage = null;
140
+ const activeConnection = connection;
141
+ connection = null;
142
+ try {
143
+ activeConnection?.close();
144
+ } catch {}
86
145
  finished = true;
87
146
  if (ready)
88
147
  reply.close();
89
148
  };
149
+ reply.addEventListener?.("close", onPeerClose);
90
150
  reply.onmessage = (event) => {
91
151
  const message = event.data;
92
- if (!message || typeof message !== "object" || !("type" in message) || !connection)
152
+ if (!message || typeof message !== "object" || !("type" in message))
153
+ return;
154
+ missedPings = 0;
155
+ if (message.type === "ping") {
156
+ send({ type: "pong" });
157
+ return;
158
+ }
159
+ if (message.type === "pong")
93
160
  return;
94
- if (message.type === "data" && "chunk" in message && message.chunk instanceof Uint8Array)
95
- connection.write(message.chunk);
96
161
  if (message.type === "end") {
97
- connection.close();
98
- reply.close();
162
+ closeTunnel();
163
+ return;
164
+ }
165
+ if (message.type === "data" && "chunk" in message && message.chunk instanceof Uint8Array && connection) {
166
+ connection.write(message.chunk);
99
167
  }
100
168
  };
101
- connection = this.servers.get(port)?.connect(port, {
169
+ const opened = this.servers.get(port)?.connect(port, {
102
170
  data: (chunk) => send({ type: "data", chunk }, [chunk.buffer]),
103
- end: () => finish({ type: "end" }),
104
- error: (message) => finish({ type: "error", message })
171
+ end: () => closeTunnel({ type: "end" }),
172
+ error: (message) => closeTunnel({ type: "error", message })
105
173
  }) ?? null;
106
- if (!connection) {
174
+ if (!opened) {
107
175
  ready = true;
108
- finish({ type: "error", message: "no server" });
176
+ closeTunnel({ type: "error", message: "no server" });
109
177
  return;
110
178
  }
179
+ if (finished) {
180
+ try {
181
+ opened.close();
182
+ } catch {}
183
+ } else {
184
+ connection = opened;
185
+ let portSockets = this.sockets.get(port);
186
+ if (!portSockets) {
187
+ portSockets = new Set;
188
+ this.sockets.set(port, portSockets);
189
+ }
190
+ portSockets.add(closeTunnel);
191
+ }
111
192
  ready = true;
112
- reply.postMessage({ type: "accepted" });
113
- for (const item of pending)
114
- reply.postMessage(item.message, item.transfer);
193
+ try {
194
+ reply.postMessage({ type: "accepted" });
195
+ for (const item of pending)
196
+ reply.postMessage(item.message, item.transfer);
197
+ } catch {
198
+ pending.length = 0;
199
+ closeTunnel();
200
+ return;
201
+ }
115
202
  pending.length = 0;
116
- if (finished)
203
+ if (finished) {
117
204
  reply.close();
205
+ return;
206
+ }
207
+ const pingIntervalMs = this.options.socketPingIntervalMs ?? DEFAULT_SOCKET_PING_MS;
208
+ const maxMissedPings = this.options.socketMissedPings ?? DEFAULT_SOCKET_MISSED_PINGS;
209
+ if (pingIntervalMs > 0 && maxMissedPings > 0) {
210
+ pingTimer = setInterval(() => {
211
+ if (finished)
212
+ return;
213
+ if (missedPings >= maxMissedPings) {
214
+ closeTunnel();
215
+ return;
216
+ }
217
+ missedPings++;
218
+ send({ type: "ping" });
219
+ }, pingIntervalMs);
220
+ }
118
221
  }
119
222
  onMessage(event) {
120
223
  const ask = event.data;
@@ -1,8 +1,22 @@
1
1
  import { OpenDescription } from "../core/descriptors.js";
2
- import { createNullDevice } from "../core/devices.js";
2
+ import {
3
+ createMachineIdFile,
4
+ createNullDevice,
5
+ isValidMachineId,
6
+ shareMachineIdOffset
7
+ } from "../core/devices.js";
3
8
  import { guardedStream } from "./guarded-stream.js";
4
9
  import { ProcessError } from "../proc/types.js";
5
- import { WeakMapConstructor, weakMapGet, weakMapHas, weakMapSet } from "../proc/intrinsics.js";
10
+ import { PtyEndpoint } from "../proc/pty.js";
11
+ import {
12
+ isInstance,
13
+ isSharedArrayBuffer,
14
+ sharedArrayBufferByteLength,
15
+ WeakMapConstructor,
16
+ weakMapGet,
17
+ weakMapHas,
18
+ weakMapSet
19
+ } from "../proc/intrinsics.js";
6
20
  import { hostTerminalStream } from "./terminal-output.js";
7
21
  const targets = new WeakMapConstructor;
8
22
  const pipeDestinations = new WeakMapConstructor;
@@ -14,18 +28,37 @@ export function hostPipeDestination(target, stream) {
14
28
  weakMapSet(pipeDestinations, stream, true);
15
29
  return stream;
16
30
  }
31
+ function hasTokenKind(value, kind) {
32
+ return typeof value === "object" && value !== null && "kind" in value && value.kind === kind;
33
+ }
34
+ function validateFdflags(value, label) {
35
+ const fdflags = value.fdflags;
36
+ if (typeof fdflags !== "number" || !Number.isInteger(fdflags) || fdflags < 0 || fdflags > 31)
37
+ throw new TypeError(`invalid ${label} flags`);
38
+ return fdflags;
39
+ }
17
40
  function nullDeviceToken(value) {
18
- if (typeof value !== "object" || value === null || !("kind" in value) || value.kind !== "null-device")
41
+ if (!hasTokenKind(value, "null-device"))
19
42
  return;
20
- const fdflags = "fdflags" in value ? value.fdflags : undefined;
21
- if (typeof fdflags !== "number" || !Number.isInteger(fdflags) || fdflags < 0 || fdflags > 31)
22
- throw new TypeError("invalid null device flags");
43
+ validateFdflags(value, "null device");
44
+ return value;
45
+ }
46
+ function machineIdFileToken(value) {
47
+ if (!hasTokenKind(value, "machine-id-file"))
48
+ return;
49
+ const machineId = value.machineId;
50
+ if (typeof machineId !== "string" || !isValidMachineId(machineId))
51
+ throw new TypeError("invalid machine-id file token");
52
+ const offset = value.offset;
53
+ if (!isSharedArrayBuffer(offset) || sharedArrayBufferByteLength(offset) !== 8)
54
+ throw new TypeError("invalid machine-id file offset");
55
+ validateFdflags(value, "machine-id file");
23
56
  return value;
24
57
  }
25
58
  function terminalToken(value) {
26
- if (typeof value !== "object" || value === null || !("kind" in value) || value.kind !== "web-terminal")
59
+ if (!hasTokenKind(value, "web-terminal"))
27
60
  return;
28
- if (!("target" in value) || value.target !== 0 && value.target !== 1 && value.target !== 2)
61
+ if (value.target !== 0 && value.target !== 1 && value.target !== 2)
29
62
  throw new TypeError("invalid browser terminal target");
30
63
  if ("pipe" in value && value.pipe !== true)
31
64
  throw new TypeError("invalid browser terminal kind");
@@ -55,10 +88,17 @@ export function createRuntimeTerminalCodec(options) {
55
88
  const resource = descriptor.resource;
56
89
  if (resource.kind === "device" && resource.device === "null")
57
90
  return { kind: "null-device", fdflags: resource.fdflags ?? 0 };
91
+ if (resource.kind === "device" && resource.device === "machine-id" && resource.virtualFile)
92
+ return {
93
+ kind: "machine-id-file",
94
+ machineId: resource.virtualFile.machineId,
95
+ offset: shareMachineIdOffset(resource.virtualFile),
96
+ fdflags: resource.fdflags ?? 0
97
+ };
58
98
  if (resource.kind !== "terminal" && resource.kind !== "pipe")
59
99
  return options.fallback.export(descriptor, pid);
60
100
  const target = weakMapGet(targets, resource);
61
- if (target === undefined && resource.kind === "pipe")
101
+ if (target === undefined && (resource.kind === "pipe" || isInstance(resource, PtyEndpoint)))
62
102
  return options.fallback.export(descriptor, pid);
63
103
  if (target === undefined)
64
104
  throw new ProcessError(NOSYS, "terminal has no transferable browser destination");
@@ -70,6 +110,9 @@ export function createRuntimeTerminalCodec(options) {
70
110
  const nullDevice = nullDeviceToken(value);
71
111
  if (nullDevice)
72
112
  return new OpenDescription(createNullDevice(nullDevice.fdflags));
113
+ const machineIdFile = machineIdFileToken(value);
114
+ if (machineIdFile)
115
+ return new OpenDescription(createMachineIdFile(machineIdFile.machineId, machineIdFile.fdflags, machineIdFile.offset));
73
116
  const token = terminalToken(value);
74
117
  if (!token)
75
118
  return options.fallback.import(value, pid);
@@ -91,7 +134,7 @@ export function createRuntimeTerminalCodec(options) {
91
134
  return new OpenDescription(stream);
92
135
  },
93
136
  discard(value) {
94
- if (nullDeviceToken(value) || terminalToken(value))
137
+ if (nullDeviceToken(value) || machineIdFileToken(value) || terminalToken(value))
95
138
  return;
96
139
  options.fallback.discard(value);
97
140
  }
@@ -1,3 +1,5 @@
1
+ import { validateMachineId } from "../core/devices.js";
2
+ import { FILESYSTEM_REQUEST_LIMITS } from "../fs/request-memory.js";
1
3
  import {
2
4
  localMemory,
3
5
  localPublication
@@ -36,6 +38,7 @@ import {
36
38
  export { getVfsDescriptor, VfsError } from "../fs/vfs.js";
37
39
  export const WORKSPACE_TAKEN_OVER = "This workspace was opened in another tab. Reload to continue here.";
38
40
  export const UNSAVED_CHANGES_LOST = "Unsaved changes in this tab weren't kept. Copy them before reloading.";
41
+ const MAX_CONCURRENT_REQUESTS = Math.max(1, Math.floor(FILESYSTEM_REQUEST_LIMITS.outstanding / 4));
39
42
  function workerError(data) {
40
43
  if (!data || typeof data !== "object" || !("type" in data) || data.type !== "filesystem-error" || !("message" in data) || typeof data.message !== "string")
41
44
  return;
@@ -64,7 +67,9 @@ export class SharedFilesystem {
64
67
  workspace;
65
68
  worker;
66
69
  writes = Promise.resolve();
67
- failure;
70
+ activeRequests = 0;
71
+ requestWaiters = [];
72
+ requestWaiterHead = 0;
68
73
  socketAttachments = new Set;
69
74
  fatal;
70
75
  _state = Object.freeze({ status: "opening" });
@@ -80,6 +85,7 @@ export class SharedFilesystem {
80
85
  onOwnershipLost;
81
86
  onStateChange;
82
87
  constructor(options = {}, onStartupStage, reservations) {
88
+ const explicitMachineId = options.machineId !== undefined ? validateMachineId(options.machineId) : undefined;
83
89
  const projectionBudget = options[localMemory];
84
90
  if (projectionBudget !== undefined && !(projectionBudget instanceof MemoryBudget))
85
91
  throw new TypeError("localMemory requires a same-realm MemoryBudget");
@@ -119,6 +125,8 @@ export class SharedFilesystem {
119
125
  this.client = client = new FilesystemClient(connection.client, {
120
126
  connect: (identity) => this.connect(identity)
121
127
  });
128
+ if (explicitMachineId !== undefined)
129
+ client.shared.setMachineId(explicitMachineId);
122
130
  this.workspace = options.workspace ? createWorkspaceVfs(client, projectionBudget) : undefined;
123
131
  worker.addEventListener("message", (event) => this.receiveMessage(event, onStartupStage));
124
132
  worker.addEventListener("error", (event) => {
@@ -139,6 +147,7 @@ export class SharedFilesystem {
139
147
  const message = {
140
148
  connect: connection.server,
141
149
  name: options.name,
150
+ machineId: explicitMachineId,
142
151
  mode: this.vfs.mode,
143
152
  implementation: this.vfs.implementation,
144
153
  whenBusy: selection.whenBusy
@@ -186,6 +195,9 @@ export class SharedFilesystem {
186
195
  get state() {
187
196
  return this._state;
188
197
  }
198
+ get machineId() {
199
+ return this.client.machineId;
200
+ }
189
201
  ownershipRetained() {
190
202
  return this._ownershipRetained;
191
203
  }
@@ -207,6 +219,10 @@ export class SharedFilesystem {
207
219
  if (this.stopped || this.disposal && !this.joinedReady())
208
220
  return;
209
221
  if (event.data?.type === "filesystem-ownership-lost") {
222
+ if (this.vfs.multiTab === "shared-host") {
223
+ this.loseOwnership();
224
+ return;
225
+ }
210
226
  this.ownershipLost = true;
211
227
  this.fail(new Error(`${WORKSPACE_TAKEN_OVER} ${UNSAVED_CHANGES_LOST}`));
212
228
  this.onOwnershipLost?.();
@@ -241,6 +257,25 @@ export class SharedFilesystem {
241
257
  Promise.resolve(pending).catch(() => {});
242
258
  } catch {}
243
259
  }
260
+ canCleanDisposeAfterOwnershipLoss() {
261
+ return this.ownershipLost && this.vfs.multiTab === "shared-host" && !this._ownershipRetained;
262
+ }
263
+ loseOwnership() {
264
+ this.ownershipLost = true;
265
+ const error = new Error(`${WORKSPACE_TAKEN_OVER} ${UNSAVED_CHANGES_LOST}`);
266
+ for (const cancel of this.socketAttachments)
267
+ cancel(error);
268
+ this.fatal ??= error;
269
+ this.abortQueuedRequests();
270
+ if (!this.stopped) {
271
+ revokeFilesystemService(this.client.connection);
272
+ if (!this.joinedReady())
273
+ this.stop();
274
+ }
275
+ if (!this.disposal)
276
+ this.setState("failed", this.fatal);
277
+ this.onOwnershipLost?.();
278
+ }
244
279
  fail(error, released) {
245
280
  for (const cancel of this.socketAttachments)
246
281
  cancel(error);
@@ -286,6 +321,7 @@ export class SharedFilesystem {
286
321
  if (this.clientStopped)
287
322
  return;
288
323
  this.clientStopped = true;
324
+ this.abortQueuedRequests();
289
325
  this.workspace?.close().catch(() => {});
290
326
  this.client.dispose();
291
327
  }
@@ -445,13 +481,91 @@ export class SharedFilesystem {
445
481
  await waitForFilesystemQuiescence(connection);
446
482
  this.reap(connection);
447
483
  }
484
+ requestAbortError() {
485
+ if (this.fatal)
486
+ return this.fatal;
487
+ if (this.disposal || this.stopped || this.clientStopped)
488
+ return new FilesystemError(11);
489
+ const transport = this.client.transportError();
490
+ if (transport)
491
+ return transport;
492
+ if (isRevoked(this.client.connection))
493
+ return new FilesystemError(11);
494
+ return;
495
+ }
496
+ dequeueRequestWaiter() {
497
+ if (!this.requestWaiters || this.requestWaiterHead >= this.requestWaiters.length)
498
+ return;
499
+ const waiter = this.requestWaiters[this.requestWaiterHead];
500
+ this.requestWaiters[this.requestWaiterHead] = undefined;
501
+ this.requestWaiterHead++;
502
+ if (this.requestWaiterHead >= this.requestWaiters.length) {
503
+ this.requestWaiters.length = 0;
504
+ this.requestWaiterHead = 0;
505
+ } else if (this.requestWaiterHead >= 64 && this.requestWaiterHead * 2 >= this.requestWaiters.length) {
506
+ this.requestWaiters = this.requestWaiters.slice(this.requestWaiterHead);
507
+ this.requestWaiterHead = 0;
508
+ }
509
+ return waiter;
510
+ }
511
+ abortQueuedRequests() {
512
+ if (!this.requestWaiters || this.requestWaiterHead >= this.requestWaiters.length)
513
+ return;
514
+ const waiters = this.requestWaiters;
515
+ const start = this.requestWaiterHead;
516
+ this.requestWaiters = [];
517
+ this.requestWaiterHead = 0;
518
+ for (let index = start;index < waiters.length; index++) {
519
+ waiters[index]?.(false);
520
+ }
521
+ }
522
+ acquireRequestSlot() {
523
+ const aborted = this.requestAbortError();
524
+ if (aborted)
525
+ throw aborted;
526
+ if (this.activeRequests < MAX_CONCURRENT_REQUESTS) {
527
+ this.activeRequests++;
528
+ return;
529
+ }
530
+ return this.waitForRequestSlot();
531
+ }
532
+ async waitForRequestSlot() {
533
+ const acquired = await new Promise((resolve) => {
534
+ this.requestWaiters.push(resolve);
535
+ });
536
+ if (!acquired)
537
+ throw this.requestAbortError() ?? new FilesystemError(11);
538
+ const aborted = this.requestAbortError();
539
+ if (!aborted)
540
+ return;
541
+ this.releaseRequestSlot();
542
+ throw aborted;
543
+ }
544
+ releaseRequestSlot() {
545
+ if (this.requestAbortError()) {
546
+ this.activeRequests--;
547
+ this.abortQueuedRequests();
548
+ return;
549
+ }
550
+ const next = this.dequeueRequestWaiter();
551
+ if (next) {
552
+ next(true);
553
+ return;
554
+ }
555
+ this.activeRequests--;
556
+ }
448
557
  async request(operation, args = [], bytes, publication) {
449
558
  this.assertLive();
559
+ const waiting = this.acquireRequestSlot();
560
+ if (waiting)
561
+ await waiting;
450
562
  try {
451
563
  return await this.client.asyncCall(operation, args, bytes, publication);
452
564
  } catch (error) {
453
565
  this.assertLive();
454
566
  throw error;
567
+ } finally {
568
+ this.releaseRequestSlot();
455
569
  }
456
570
  }
457
571
  mutate(operation, args, bytes) {
@@ -462,28 +576,25 @@ export class SharedFilesystem {
462
576
  if (publication)
463
577
  this.client.cancelPublication(publication);
464
578
  });
465
- this.writes = result.catch((error) => {
466
- this.failure ??= error;
467
- });
579
+ this.writes = result.catch(() => {});
468
580
  return result;
469
581
  }
470
582
  async drain() {
471
583
  await this.writes;
472
584
  this.assertLive();
473
- if (this.failure !== undefined) {
474
- const error = this.failure;
475
- this.failure = undefined;
476
- throw error;
477
- }
478
585
  }
479
586
  async flush(path) {
480
587
  await this.drain();
481
588
  await this.request("flush", path === undefined ? [] : [path]);
482
589
  }
483
590
  async resolvePath(path) {
484
- await this.writes;
591
+ await this.drain();
485
592
  return this.request("resolvePath", [path]);
486
593
  }
594
+ async stat(path, options) {
595
+ await this.drain();
596
+ return this.request("statPath", [path, options?.follow !== false]);
597
+ }
487
598
  async lookup(path) {
488
599
  await this.drain();
489
600
  return this.request("lookup", [path]);
@@ -536,6 +647,7 @@ export class SharedFilesystem {
536
647
  });
537
648
  this.disposal.catch(() => {});
538
649
  revokeFilesystemService(this.client.connection);
650
+ this.abortQueuedRequests();
539
651
  const quiescence = waitForFilesystemQuiescence(this.client.connection);
540
652
  quiescence.catch((reason) => {
541
653
  this._ownershipRetained = true;
@@ -591,7 +703,7 @@ export class SharedFilesystem {
591
703
  return this.disposal;
592
704
  }
593
705
  if (this.joinedReady() && !this.stopped)
594
- return this.disposeReady(this.fatal);
706
+ return this.disposeReady(this.canCleanDisposeAfterOwnershipLoss() ? undefined : this.fatal);
595
707
  let finish;
596
708
  this.disposal = new Promise((resolve, reject) => {
597
709
  finish = (error, released) => {
@@ -619,6 +731,7 @@ export class SharedFilesystem {
619
731
  this.finishDisposal = finish;
620
732
  this.setState("disposed");
621
733
  revokeFilesystemService(this.client.connection);
734
+ this.abortQueuedRequests();
622
735
  if (this.stopped || this.startupComplete || !this.cancellableStartup)
623
736
  finish();
624
737
  else {