@waffle-os/runtime 0.0.148 → 0.0.150

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.
@@ -1,11 +1,30 @@
1
+ import type { Resource } from "../core/descriptors.js";
2
+ import {
3
+ claimFileOffset,
4
+ shareFileResource,
5
+ type AsyncFileOffsetLease,
6
+ } from "../core/open-file.js";
7
+ import type { FilesystemClient, FilesystemCompletion } from "../fs/client.js";
8
+ import { errno as fsErrno, PAGE } from "../fs/protocol.js";
9
+ import {
10
+ cancelTimeout,
11
+ isInstance,
12
+ PromiseConstructor,
13
+ scheduleTimeout,
14
+ typedArrayLength,
15
+ typedArraySubarray,
16
+ } from "../proc/intrinsics.ts";
1
17
  import { ProcessErrno, ProcessError } from "../proc/types.js";
2
18
 
3
19
  /** Diagnostic delivery must not retain a dead/stalled process indefinitely. */
4
20
  export const DIAGNOSTIC_STALL_TIMEOUT_MS = 5_000;
5
21
 
6
- // Guest code can replace globals after entry; diagnostics retain host timing authority.
22
+ // Guest code can replace globals after entry; diagnostics retain host timing and math authority.
7
23
  const now = performance.now.bind(performance);
8
- const delay = setTimeout;
24
+ const delay = scheduleTimeout;
25
+ const mathMin = Math.min;
26
+ const mathMax = Math.max;
27
+ const numberIsInteger = Number.isInteger;
9
28
 
10
29
  /** Drain partial writes without blocking the page/Worker event loop. Positive writes reset
11
30
  * the no-progress deadline; a draining reader always gets every byte. The synchronous fast
@@ -56,3 +75,216 @@ export function drainDiagnostic(
56
75
  } while (!step());
57
76
  })();
58
77
  }
78
+
79
+ function diagnosticWriteError(error: unknown, remaining: number, total: number): ProcessError {
80
+ if (isInstance(error, ProcessError)) return error;
81
+ const code = fsErrno(error);
82
+ return new ProcessError(
83
+ code,
84
+ `diagnostic write failed (${-code}); ${remaining} of ${total} diagnostic bytes unwritten`,
85
+ );
86
+ }
87
+
88
+ function settleAsyncDiagnosticChunk(
89
+ completion: FilesystemCompletion,
90
+ lease: AsyncFileOffsetLease,
91
+ remaining: number,
92
+ total: number,
93
+ callerSettled: boolean,
94
+ releaseLease: () => void,
95
+ onAccept: (written: number) => void,
96
+ onReject: (error: ProcessError) => void,
97
+ ): void {
98
+ let written = 0;
99
+ try {
100
+ const committed = completion.tryConsumeCommitted();
101
+ const result = committed !== undefined ? committed : completion.consumeInline();
102
+ if (lease.append) {
103
+ const appended = result as { written: number; offset: number };
104
+ lease.commit(appended.offset);
105
+ written = appended.written;
106
+ } else {
107
+ written = result as number;
108
+ if (written > 0) lease.commit(lease.position + written);
109
+ }
110
+ } catch (error) {
111
+ completion.release();
112
+ releaseLease();
113
+ if (!callerSettled) onReject(diagnosticWriteError(error, remaining, total));
114
+ return;
115
+ }
116
+ completion.release();
117
+ releaseLease();
118
+ if (callerSettled) return;
119
+ if (!numberIsInteger(written) || written <= 0 || written > remaining) {
120
+ onReject(
121
+ new ProcessError(
122
+ 29,
123
+ `diagnostic write failed (${written}); ${remaining} of ${total} diagnostic bytes unwritten`,
124
+ ),
125
+ );
126
+ return;
127
+ }
128
+ onAccept(written);
129
+ }
130
+
131
+ function dispatchAsyncDiagnosticChunk(
132
+ fs: FilesystemClient,
133
+ handle: number,
134
+ lease: AsyncFileOffsetLease,
135
+ bytes: Uint8Array,
136
+ offset: number,
137
+ total: number,
138
+ deadline: number,
139
+ onWritten: (written: number) => void,
140
+ onError: (error: ProcessError) => void,
141
+ ): void {
142
+ const remaining = total - offset;
143
+ let leaseReleased = false;
144
+ const releaseLease = () => {
145
+ if (leaseReleased) return;
146
+ leaseReleased = true;
147
+ lease.release();
148
+ };
149
+ let completion: FilesystemCompletion;
150
+ try {
151
+ if (now() >= deadline) {
152
+ releaseLease();
153
+ onError(
154
+ new ProcessError(
155
+ ProcessErrno.AGAIN,
156
+ `diagnostic reader made no progress for five seconds; ${remaining} of ${total} diagnostic bytes unwritten`,
157
+ ),
158
+ );
159
+ return;
160
+ }
161
+ const chunk = typedArraySubarray(bytes, offset, mathMin(total, offset + PAGE));
162
+ completion = lease.append
163
+ ? fs.submit("append", [handle], chunk)
164
+ : fs.submit("write", [handle, lease.position], chunk);
165
+ } catch (error) {
166
+ releaseLease();
167
+ onError(diagnosticWriteError(error, remaining, total));
168
+ return;
169
+ }
170
+ let callerSettled = false;
171
+ let settled = false;
172
+ // Once dispatched, keep the shared offset lease until the backend reports an authoritative
173
+ // commit or abort so another holder cannot reuse the same offset while the write is still live.
174
+ const timer = delay(
175
+ () => {
176
+ if (callerSettled) return;
177
+ callerSettled = true;
178
+ onError(
179
+ new ProcessError(
180
+ ProcessErrno.AGAIN,
181
+ `diagnostic reader made no progress for five seconds; ${remaining} of ${total} diagnostic bytes unwritten`,
182
+ ),
183
+ );
184
+ },
185
+ mathMax(1, deadline - now()),
186
+ );
187
+ fs.trackDeferredWrite(completion, () => {
188
+ if (settled) return;
189
+ settled = true;
190
+ cancelTimeout(timer);
191
+ settleAsyncDiagnosticChunk(
192
+ completion,
193
+ lease,
194
+ remaining,
195
+ total,
196
+ callerSettled,
197
+ releaseLease,
198
+ (written) => {
199
+ if (callerSettled) return;
200
+ callerSettled = true;
201
+ onWritten(written);
202
+ },
203
+ (error) => {
204
+ if (callerSettled) return;
205
+ callerSettled = true;
206
+ onError(error);
207
+ },
208
+ );
209
+ });
210
+ }
211
+
212
+ /** Drain diagnostic bytes to a regular file whose backend disables direct shared-memory I/O. */
213
+ export function drainAsyncFileDiagnostic(
214
+ fs: FilesystemClient,
215
+ resource: Extract<Resource, { kind: "file" }>,
216
+ bytes: Uint8Array,
217
+ active: () => boolean,
218
+ stallTimeoutMs = DIAGNOSTIC_STALL_TIMEOUT_MS,
219
+ ): Promise<void> {
220
+ return new PromiseConstructor<void>((resolve, reject) => {
221
+ const total = typedArrayLength(bytes);
222
+ if (!total) {
223
+ resolve();
224
+ return;
225
+ }
226
+ try {
227
+ shareFileResource(resource, fs.connection);
228
+ } catch (error) {
229
+ reject(diagnosticWriteError(error, total, total));
230
+ return;
231
+ }
232
+ let offset = 0;
233
+ let deadline = now() + stallTimeoutMs;
234
+ const step = (): void => {
235
+ if (offset >= total) {
236
+ resolve();
237
+ return;
238
+ }
239
+ const remaining = total - offset;
240
+ if (!active()) {
241
+ reject(
242
+ new ProcessError(
243
+ ProcessErrno.CANCELED,
244
+ `diagnostic delivery cancelled; ${remaining} of ${total} diagnostic bytes unwritten`,
245
+ ),
246
+ );
247
+ return;
248
+ }
249
+ const claim = claimFileOffset(resource, true);
250
+ if (claim.kind === "failed") {
251
+ reject(
252
+ new ProcessError(
253
+ claim.errno,
254
+ `diagnostic write failed (${-claim.errno}); ${remaining} of ${total} diagnostic bytes unwritten`,
255
+ ),
256
+ );
257
+ return;
258
+ }
259
+ if (claim.kind === "busy") {
260
+ if (now() >= deadline) {
261
+ reject(
262
+ new ProcessError(
263
+ ProcessErrno.AGAIN,
264
+ `diagnostic reader made no progress for five seconds; ${remaining} of ${total} diagnostic bytes unwritten`,
265
+ ),
266
+ );
267
+ return;
268
+ }
269
+ delay(step, 1);
270
+ return;
271
+ }
272
+ dispatchAsyncDiagnosticChunk(
273
+ fs,
274
+ resource.handle,
275
+ claim.lease,
276
+ bytes,
277
+ offset,
278
+ total,
279
+ deadline,
280
+ (written) => {
281
+ offset += written;
282
+ deadline = now() + stallTimeoutMs;
283
+ step();
284
+ },
285
+ reject,
286
+ );
287
+ };
288
+ step();
289
+ });
290
+ }
@@ -97,7 +97,7 @@ import {
97
97
  import { type FilesystemConnection, type FilesystemIdentity, isRevoked } from "../fs/protocol.js";
98
98
 
99
99
  import type { ProcessSupervisor, RootProcessOptions } from "../proc/supervisor.js";
100
- import type { ExecutableRegistry, ResolvedExecutable } from "../proc/registry.js";
100
+ import type { CommandPrograms, ExecutableRegistry, ResolvedExecutable } from "../proc/registry.js";
101
101
  import type { ProcessIdentityAllocator } from "../proc/identity.js";
102
102
  import type { ProcessRecord, ProcessTable } from "../proc/table.js";
103
103
  import {
@@ -463,6 +463,7 @@ function senderRevoked(
463
463
 
464
464
  interface CommandRootState {
465
465
  readonly root: WorkerProcessTransport;
466
+ readonly programs: CommandPrograms;
466
467
  readonly pending: Set<Promise<void>>;
467
468
  readonly failures: Map<WorkerProcessTransport, unknown>;
468
469
  stopped: boolean;
@@ -588,8 +589,8 @@ export class BrowserProcessBroker {
588
589
  (proc) => {
589
590
  const supervisor = (this.supervisor = new proc.ProcessSupervisor({
590
591
  registry: this.options.registry,
591
- byteBackedGuestOnly: (rootPid) =>
592
- rootPid !== undefined && !!this.commandRoots?.has(rootPid),
592
+ commandPrograms: (rootPid) =>
593
+ rootPid === undefined ? undefined : this.commandRoots?.get(rootPid)?.programs,
593
594
  table: this.options.table,
594
595
  launch: (context) => this.launchPrepared(context),
595
596
  launchCommand: (context) => this.launchPrepared(context),
@@ -1379,6 +1380,7 @@ export class BrowserProcessBroker {
1379
1380
  async adoptCommandRoot(
1380
1381
  transport: WorkerProcessTransport,
1381
1382
  options: RuntimeRootOptions,
1383
+ programs: CommandPrograms,
1382
1384
  ): Promise<void> {
1383
1385
  if (this.suspended || !this.supervisor) throw new Error("Process broker is unavailable");
1384
1386
  const processCapacity = directoryCapacity(transport.directory);
@@ -1398,6 +1400,7 @@ export class BrowserProcessBroker {
1398
1400
  transport.data = { filesystem: options.filesystem, pipeRegistry: registry.handle() };
1399
1401
  (this.commandRoots ??= new Map()).set(transport.pid, {
1400
1402
  root: transport,
1403
+ programs,
1401
1404
  pending: new Set(),
1402
1405
  failures: new Map(),
1403
1406
  stopped: false,
@@ -195,12 +195,16 @@ class Command {
195
195
  let adopted = false;
196
196
  let leader: Leader | undefined;
197
197
  try {
198
- await owner.adoptCommandRoot(root, {
199
- filesystem,
200
- memory: [],
201
- tryOutput: (fd, bytes) => this.deliver(fd, bytes),
202
- stop: () => this.input?.stop(),
203
- });
198
+ await owner.adoptCommandRoot(
199
+ root,
200
+ {
201
+ filesystem,
202
+ memory: [],
203
+ tryOutput: (fd, bytes) => this.deliver(fd, bytes),
204
+ stop: () => this.input?.stop(),
205
+ },
206
+ this.options.programs ?? "byte-backed",
207
+ );
204
208
  adopted = true;
205
209
  if (this.runtime.disposed) return this.disposed();
206
210
  if (!this.stopped.aborted) leader = this.spawn(owner, root);
@@ -357,6 +361,13 @@ class Command {
357
361
  return bytes.length;
358
362
  }
359
363
 
364
+ /** Reads the leader's outcome once it has one, stopping the rest of its tree when asked to. */
365
+ private leaderExit(leader: Leader): ProcessExit | null {
366
+ const exit = readOutcome(leader.state.outcome);
367
+ if (exit && this.options.onLeaderExit === "stop") this.stop();
368
+ return exit;
369
+ }
370
+
360
371
  private async join(owner: BrowserProcessBroker, root: WorkerProcessTransport, leader?: Leader) {
361
372
  const wake = workerProcessState(root).wake;
362
373
  let exit: ProcessExit | null = null;
@@ -364,7 +375,7 @@ class Command {
364
375
  const expected = Atomics.load(wake, 0);
365
376
  if (this.runtime.disposed) return this.disposed();
366
377
  if (this.stopped.aborted || this.ioFailure) this.stopInput();
367
- if (leader && !exit) exit = readOutcome(leader.state.outcome);
378
+ if (leader && !exit) exit = this.leaderExit(leader);
368
379
  if (owner.checkCommandCleanup(root, !leader || exit !== null)) {
369
380
  if (!leader || exit) return exit;
370
381
  throw new Error("Command leader retired without an outcome");
package/browser/worker.ts CHANGED
@@ -45,7 +45,12 @@ import {
45
45
  import { checkedSignal, ProcessError, type ProcessExit } from "../proc/types.js";
46
46
  import { defaultSignalTerminates, signalPending } from "../proc/signals.js";
47
47
  import { FilesystemClient } from "../fs/client.js";
48
- import { revokeFilesystem, reapFilesystem, type FilesystemConnection } from "../fs/protocol.js";
48
+ import {
49
+ isRevoked,
50
+ revokeFilesystem,
51
+ reapFilesystem,
52
+ type FilesystemConnection,
53
+ } from "../fs/protocol.js";
49
54
  import { sharedRevoked } from "../fs/shared.js";
50
55
  import { registerResolveObservation } from "../fs/resolve-observation.js";
51
56
  import { Wasi, WasiExit, type Stream } from "../core/index.js";
@@ -58,7 +63,7 @@ import {
58
63
  type TerminalOutputWriterOptions,
59
64
  type RuntimeTerminalOutput,
60
65
  } from "./terminal-output.js";
61
- import { drainDiagnostic } from "./diagnostic.js";
66
+ import { drainAsyncFileDiagnostic, drainDiagnostic } from "./diagnostic.js";
62
67
  import { withFileOffset } from "../core/open-file.js";
63
68
  import type { ProcessABI } from "../proc/abi.js";
64
69
 
@@ -828,8 +833,23 @@ async function bootstrapAllocated<R extends RuntimeWorkerRequest>(
828
833
  if (runtimeDiagnostic && "error" in result) {
829
834
  try {
830
835
  const bytes = new TextEncoder().encode(`${describeWorkerError(result.error)}\n`);
831
- const pending = drainDiagnostic(bytes, (data) => writeDiagnostic!(data));
832
- if (pending) await pending;
836
+ const stderr = wasi?.descriptors.get(2);
837
+ if (
838
+ stderr &&
839
+ (stderr.rightsBase & (1n << 6n)) !== 0n &&
840
+ stderr.resource.kind === "file" &&
841
+ fs.shared.isDirectDisabled()
842
+ ) {
843
+ await drainAsyncFileDiagnostic(
844
+ fs,
845
+ stderr.resource,
846
+ bytes,
847
+ () => !isRevoked(fs.connection),
848
+ );
849
+ } else {
850
+ const pending = drainDiagnostic(bytes, (data) => writeDiagnostic!(data));
851
+ if (pending) await pending;
852
+ }
833
853
  } catch (error) {
834
854
  collect(error);
835
855
  }
@@ -847,6 +867,13 @@ async function bootstrapAllocated<R extends RuntimeWorkerRequest>(
847
867
  ) {
848
868
  attempt(() => executor.diagnostic?.(`${describeWorkerError(result.error)}\n`));
849
869
  }
870
+ if (fs.hasDeferredWrites?.()) {
871
+ try {
872
+ await fs.settleDeferredWrites?.();
873
+ } catch (error) {
874
+ collect(error);
875
+ }
876
+ }
850
877
  const descriptorsReleased = attempt(() => {
851
878
  if (wasi) {
852
879
  disposeProcessDescriptors(wasi, discardedStdio);
@@ -1521,7 +1548,9 @@ function installProcessImports(
1521
1548
  const call = name === "poll" && observedPoll ? observedPoll.wrap(entry[1]) : entry[1];
1522
1549
  target[name] = (...args) => {
1523
1550
  checkActive();
1524
- return call(...args);
1551
+ const result = call(...args);
1552
+ checkActive();
1553
+ return result;
1525
1554
  };
1526
1555
  }
1527
1556
  }
package/core/open-file.ts CHANGED
@@ -4,14 +4,40 @@ import { FilesystemError } from "./filesystem.js";
4
4
  import { FilesystemSection, isRevoked } from "../fs/section.js";
5
5
  import type { FilesystemIdentity } from "../fs/protocol.js";
6
6
 
7
+ const atomicsLoad = Atomics.load;
8
+ const atomicsStore = Atomics.store;
9
+ const atomicsCompareExchange = Atomics.compareExchange;
10
+ const atomicsOr = Atomics.or;
11
+ const atomicsAnd = Atomics.and;
12
+ const atomicsNotify = Atomics.notify;
13
+ const atomicsWait = Atomics.wait;
14
+ const Int32ArrayConstructor = Int32Array;
15
+ const BigUint64ArrayConstructor = BigUint64Array;
16
+ const Float64ArrayConstructor = Float64Array;
17
+ const WeakMapConstructor = WeakMap;
18
+ const weakMapGet = WeakMap.prototype.get;
19
+ const weakMapSet = WeakMap.prototype.set;
20
+ const objectDefineProperties = Object.defineProperties;
21
+ const typedArrayPrototype = Object.getPrototypeOf(Int32Array.prototype);
22
+ const typedArrayBufferGetter = Object.getOwnPropertyDescriptor(typedArrayPrototype, "buffer")!.get!;
23
+ const reflectApply = Reflect.apply;
24
+
7
25
  type FileResource = Extract<Resource, { kind: "file" }>;
8
26
  interface SharedOffset {
9
27
  buffer: SharedArrayBuffer;
10
28
  cells: Int32Array<SharedArrayBuffer>;
29
+ ownerStates: Int32Array<SharedArrayBuffer>;
11
30
  identity: FilesystemIdentity;
12
31
  section: FilesystemSection;
32
+ readOffset(): number;
33
+ writeOffset(next: number): void;
34
+ readAppend(): boolean;
35
+ }
36
+ const offsets = new WeakMapConstructor<FileResource, SharedOffset>();
37
+
38
+ function getSharedOffset(resource: FileResource): SharedOffset | undefined {
39
+ return reflectApply(weakMapGet, offsets, [resource]) as SharedOffset | undefined;
13
40
  }
14
- const offsets = new WeakMap<FileResource, SharedOffset>();
15
41
 
16
42
  /** Promote the existing description in place, so every local dup keeps the same offset. */
17
43
  export function shareFileResource(
@@ -19,52 +45,66 @@ export function shareFileResource(
19
45
  identity: FilesystemIdentity,
20
46
  buffer?: SharedArrayBuffer,
21
47
  ): SharedArrayBuffer {
22
- const existing = offsets.get(resource);
48
+ const existing = getSharedOffset(resource);
23
49
  if (existing) return existing.buffer;
24
50
  const shared = buffer ?? allocateSharedControl(16);
25
- const cells = new Int32Array(shared);
51
+ const cells = new Int32ArrayConstructor(shared);
52
+ const ownerStates = new Int32ArrayConstructor(identity.ownerStates);
26
53
  // Atomics has no Float64 operation. Share the number's bits, not a signed integer
27
54
  // conversion: existing JS offsets above 2^63 must not wrap into negative positions.
28
- const offset = new BigUint64Array(shared, 8, 1);
29
- const value = new Float64Array(1);
30
- const bits = new BigUint64Array(value.buffer);
55
+ const offset = new BigUint64ArrayConstructor(shared, 8, 1);
56
+ const value = new Float64ArrayConstructor(1);
57
+ const valueBuffer = reflectApply(typedArrayBufferGetter, value, []) as ArrayBuffer;
58
+ const bits = new BigUint64ArrayConstructor(valueBuffer);
59
+ const readOffset = (): number => {
60
+ bits[0] = atomicsLoad(offset, 0);
61
+ return value[0]!;
62
+ };
63
+ const writeOffset = (next: number): void => {
64
+ value[0] = next;
65
+ atomicsStore(offset, 0, bits[0]!);
66
+ };
67
+ const readAppend = (): boolean => (atomicsLoad(cells, 1) & 1) !== 0;
31
68
  if (!buffer) {
32
- Atomics.store(cells, 1, ((resource.fdflags ?? 0) & ~1) | (resource.append ? 1 : 0));
33
- value[0] = resource.offset;
34
- Atomics.store(offset, 0, bits[0]!);
69
+ atomicsStore(cells, 1, ((resource.fdflags ?? 0) & ~1) | (resource.append ? 1 : 0));
70
+ writeOffset(resource.offset);
35
71
  }
36
- offsets.set(resource, {
72
+ const state: SharedOffset = {
37
73
  buffer: shared,
38
74
  cells,
75
+ ownerStates,
39
76
  identity,
40
77
  section: new FilesystemSection(identity),
41
- });
42
- Object.defineProperties(resource, {
78
+ readOffset,
79
+ writeOffset,
80
+ readAppend,
81
+ };
82
+ const descriptors = {
83
+ __proto__: null,
43
84
  offset: {
85
+ __proto__: null,
44
86
  enumerable: true,
45
87
  configurable: false,
46
- get: () => {
47
- bits[0] = Atomics.load(offset, 0);
48
- return value[0]!;
49
- },
50
- set: (next: number) => {
51
- value[0] = next;
52
- Atomics.store(offset, 0, bits[0]!);
53
- },
88
+ get: readOffset,
89
+ set: writeOffset,
54
90
  },
55
91
  append: {
92
+ __proto__: null,
56
93
  enumerable: true,
57
94
  configurable: false,
58
- get: () => (Atomics.load(cells, 1) & 1) !== 0,
59
- set: (value: boolean) => (value ? Atomics.or(cells, 1, 1) : Atomics.and(cells, 1, ~1)),
95
+ get: readAppend,
96
+ set: (flag: boolean) => (flag ? atomicsOr(cells, 1, 1) : atomicsAnd(cells, 1, ~1)),
60
97
  },
61
98
  fdflags: {
99
+ __proto__: null,
62
100
  enumerable: true,
63
101
  configurable: false,
64
- get: () => Atomics.load(cells, 1),
65
- set: (value: number) => Atomics.store(cells, 1, value),
102
+ get: () => atomicsLoad(cells, 1),
103
+ set: (flags: number) => atomicsStore(cells, 1, flags),
66
104
  },
67
- });
105
+ } as unknown as PropertyDescriptorMap;
106
+ objectDefineProperties(resource, descriptors);
107
+ reflectApply(weakMapSet, offsets, [resource, state]);
68
108
  return shared;
69
109
  }
70
110
 
@@ -79,46 +119,77 @@ export type OffsetClaim =
79
119
  | { kind: "busy"; word: Int32Array; observed: number }
80
120
  | { kind: "failed"; errno: number };
81
121
 
82
- /** The operation owner must drain leases before filesystem quiescence can reap this identity. */
83
- export function claimFileOffset(resource: FileResource): OffsetClaim {
84
- const state = offsets.get(resource);
85
- if (!state) throw new Error("async file offsets require a shared description");
86
- const { cells, identity, section } = state;
122
+ /** The operation owner must drain leases before filesystem quiescence can reap this identity.
123
+ * Pass `holdSection = true` only for callers that settle without awaiting transport retirement. */
124
+ export function claimFileOffset(resource: FileResource, holdSection = false): OffsetClaim {
125
+ const claim = tryClaimFileOffset(resource, holdSection);
126
+ if (!claim) throw new Error("async file offsets require a shared description");
127
+ return claim;
128
+ }
129
+
130
+ /** Claim a shared file offset when the description is shared; undefined for local descriptions.
131
+ * When `holdSection` is true, keeps the filesystem section entered until `lease.release()` so
132
+ * quiescence waits for the leased operation to settle before reaping the owner. */
133
+ export function tryClaimFileOffset(
134
+ resource: FileResource,
135
+ holdSection = false,
136
+ ): OffsetClaim | undefined {
137
+ const state = getSharedOffset(resource);
138
+ if (!state) return undefined;
139
+ const { cells, ownerStates, identity, section } = state;
87
140
  try {
88
141
  section.enter();
89
142
  } catch (error) {
90
143
  if (error instanceof FilesystemError) return { kind: "failed", errno: error.errno };
91
144
  throw error;
92
145
  }
146
+ let handedToLease = false;
147
+ let acquired = false;
93
148
  try {
94
- const owner = Atomics.compareExchange(cells, 0, 0, identity.owner);
95
- if (owner === 0) return { kind: "acquired", lease: offsetLease(resource, state) };
96
- if (Atomics.load(new Int32Array(identity.ownerStates), owner) === 2)
97
- Atomics.compareExchange(cells, 0, owner, 0);
149
+ const owner = atomicsCompareExchange(cells, 0, 0, identity.owner);
150
+ if (owner === 0) {
151
+ acquired = true;
152
+ const lease = offsetLease(state, holdSection);
153
+ handedToLease = true;
154
+ return { kind: "acquired", lease };
155
+ }
156
+ if (atomicsLoad(ownerStates, owner) === 2) atomicsCompareExchange(cells, 0, owner, 0);
98
157
  return { kind: "busy", word: cells, observed: owner };
99
158
  } finally {
100
- section.exit();
159
+ if (!handedToLease) {
160
+ if (acquired) {
161
+ atomicsCompareExchange(cells, 0, identity.owner, 0);
162
+ atomicsNotify(cells, 0);
163
+ }
164
+ section.exit();
165
+ } else if (!holdSection) {
166
+ section.exit();
167
+ }
101
168
  }
102
169
  }
103
170
 
104
- function offsetLease(
105
- resource: FileResource,
106
- { cells, identity }: SharedOffset,
107
- ): AsyncFileOffsetLease {
171
+ function offsetLease(state: SharedOffset, holdSection: boolean): AsyncFileOffsetLease {
172
+ const { cells, identity, section } = state;
173
+ const position = state.readOffset();
174
+ const append = state.readAppend();
108
175
  let phase: "held" | "committed" | "released" = "held";
109
176
  return {
110
- position: resource.offset,
111
- append: resource.append,
177
+ position,
178
+ append,
112
179
  commit(nextOffset) {
113
180
  if (phase !== "held") throw new Error("file offset lease is not uncommitted");
114
- resource.offset = nextOffset;
181
+ state.writeOffset(nextOffset);
115
182
  phase = "committed";
116
183
  },
117
184
  release() {
118
185
  if (phase === "released") return;
119
186
  phase = "released";
120
- Atomics.compareExchange(cells, 0, identity.owner, 0);
121
- Atomics.notify(cells, 0);
187
+ try {
188
+ atomicsCompareExchange(cells, 0, identity.owner, 0);
189
+ atomicsNotify(cells, 0);
190
+ } finally {
191
+ if (holdSection) section.exit();
192
+ }
122
193
  },
123
194
  };
124
195
  }
@@ -131,7 +202,7 @@ export function withFileOffset(
131
202
  operation: () => number,
132
203
  nonblocking = false,
133
204
  ): number {
134
- const state = offsets.get(resource);
205
+ const state = getSharedOffset(resource);
135
206
  if (!state) return operation();
136
207
  const { cells, identity, section } = state;
137
208
  let admitted = false;
@@ -149,25 +220,28 @@ export function withFileOffset(
149
220
  throw error;
150
221
  } finally {
151
222
  if (acquired) {
152
- Atomics.compareExchange(cells, 0, identity.owner, 0);
153
- Atomics.notify(cells, 0);
223
+ atomicsCompareExchange(cells, 0, identity.owner, 0);
224
+ atomicsNotify(cells, 0);
154
225
  }
155
226
  if (admitted) section.exit();
156
227
  }
157
228
  }
158
229
 
159
- function acquireFileOffset({ cells, identity }: SharedOffset, nonblocking: boolean): number {
230
+ function acquireFileOffset(
231
+ { cells, ownerStates, identity }: SharedOffset,
232
+ nonblocking: boolean,
233
+ ): number {
160
234
  for (;;) {
161
235
  if (isRevoked(identity)) return -11;
162
- const owner = Atomics.compareExchange(cells, 0, 0, identity.owner);
236
+ const owner = atomicsCompareExchange(cells, 0, 0, identity.owner);
163
237
  if (owner === 0) return 0;
164
- if (Atomics.load(new Int32Array(identity.ownerStates), owner) === 2) {
165
- Atomics.compareExchange(cells, 0, owner, 0);
238
+ if (atomicsLoad(ownerStates, owner) === 2) {
239
+ atomicsCompareExchange(cells, 0, owner, 0);
166
240
  continue;
167
241
  }
168
242
  if (nonblocking) return -6;
169
243
  // Revocation and reaping notify the identity signal, not this lock word.
170
244
  // Recheck both after a bounded park, even if the owner never unlocks.
171
- Atomics.wait(cells, 0, owner, 10);
245
+ atomicsWait(cells, 0, owner, 10);
172
246
  }
173
247
  }