@waffle-os/runtime 0.0.149 → 0.0.151
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.
- package/browser/diagnostic.ts +234 -2
- package/browser/process-broker.ts +42 -4
- package/browser/worker.ts +34 -5
- package/core/open-file.ts +126 -52
- package/dist/browser/diagnostic.js +150 -1
- package/dist/browser/process-broker.js +47 -2
- package/dist/browser/worker.js +24 -6
- package/dist/core/open-file.js +112 -50
- package/dist/fs/client.js +290 -46
- package/dist/fs/protocol.js +7 -4
- package/dist/fs/service.js +77 -16
- package/dist/fs/shared.js +6 -6
- package/dist/interrupt/rewriter-internal.js +2 -1
- package/dist/proc/abi.js +152 -16
- package/dist/proc/command-stdio.js +81 -33
- package/dist/proc/directory.js +111 -0
- package/dist/proc/errors.js +1 -0
- package/dist/proc/supervisor.js +130 -24
- package/dist/proc/table.js +9 -1
- package/dist/proc/types.js +5 -0
- package/dist/proc/worker-client.js +34 -5
- package/dist/runtime.js +3 -0
- package/dist/thread/service.js +85 -10
- package/dist/tooling/program/program-transformer.json +1 -1
- package/fs/client.ts +298 -44
- package/fs/protocol.ts +9 -4
- package/fs/service.ts +99 -19
- package/fs/shared.ts +7 -7
- package/interrupt/rewriter-internal.ts +2 -1
- package/package.json +1 -1
- package/proc/abi.ts +185 -17
- package/proc/command-stdio.ts +98 -41
- package/proc/directory.ts +131 -0
- package/proc/errors.ts +1 -0
- package/proc/supervisor.ts +173 -36
- package/proc/table.ts +11 -0
- package/proc/types.ts +6 -0
- package/proc/worker-client.ts +36 -5
- package/runtime.ts +3 -0
- package/thread/service.ts +125 -7
- package/tooling/program/program-transformer.json +1 -1
package/browser/diagnostic.ts
CHANGED
|
@@ -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 =
|
|
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
|
+
}
|
|
@@ -84,6 +84,8 @@ import {
|
|
|
84
84
|
directoryProcesses,
|
|
85
85
|
directoryAdmissionVersion,
|
|
86
86
|
commitDirectoryAdmission,
|
|
87
|
+
peekDirectoryJob,
|
|
88
|
+
peekDirectoryProcess,
|
|
87
89
|
isCollectedProcess,
|
|
88
90
|
wakeDirectory,
|
|
89
91
|
} from "../proc/directory.js";
|
|
@@ -99,13 +101,14 @@ import { type FilesystemConnection, type FilesystemIdentity, isRevoked } from ".
|
|
|
99
101
|
import type { ProcessSupervisor, RootProcessOptions } from "../proc/supervisor.js";
|
|
100
102
|
import type { CommandPrograms, ExecutableRegistry, ResolvedExecutable } from "../proc/registry.js";
|
|
101
103
|
import type { ProcessIdentityAllocator } from "../proc/identity.js";
|
|
102
|
-
import type { ProcessRecord, ProcessTable } from "../proc/table.js";
|
|
104
|
+
import type { ProcessJob, ProcessRecord, ProcessTable } from "../proc/table.js";
|
|
103
105
|
import {
|
|
104
106
|
type ChildExitEvent,
|
|
105
107
|
type ProcessContext,
|
|
106
108
|
type ProcessExit,
|
|
107
109
|
type CommandProcessContext,
|
|
108
110
|
type ProcessHandle,
|
|
111
|
+
checkedKillSignal,
|
|
109
112
|
checkedSignal,
|
|
110
113
|
checkedProcessCwd,
|
|
111
114
|
snapshotLogicalProcessIdentity,
|
|
@@ -115,6 +118,7 @@ import {
|
|
|
115
118
|
} from "../proc/types.js";
|
|
116
119
|
import { requestSignal, createSignalState, type SignalTransport } from "../proc/signals.js";
|
|
117
120
|
import {
|
|
121
|
+
OutcomeCell,
|
|
118
122
|
claimOutcome,
|
|
119
123
|
outcomeWord,
|
|
120
124
|
readOutcome,
|
|
@@ -3569,8 +3573,38 @@ export class BrowserProcessBroker {
|
|
|
3569
3573
|
Array.from(directoryProcesses(root.directory)),
|
|
3570
3574
|
);
|
|
3571
3575
|
}
|
|
3576
|
+
private isDirectoryBackedJob(entry: ProcessJob): boolean {
|
|
3577
|
+
if (entry.shared) return true;
|
|
3578
|
+
const leader =
|
|
3579
|
+
entry.leaderPid === undefined ? undefined : this.options.table.get(entry.leaderPid);
|
|
3580
|
+
return leader !== undefined && isInstance(leader.outcome, OutcomeCell);
|
|
3581
|
+
}
|
|
3582
|
+
private hasProcess(pid: number): boolean {
|
|
3583
|
+
for (const root of this.roots.values())
|
|
3584
|
+
if (peekDirectoryProcess(root.directory, pid)) return true;
|
|
3585
|
+
const record = this.options.table.get(pid);
|
|
3586
|
+
if (record && !isInstance(record.outcome, OutcomeCell)) return true;
|
|
3587
|
+
const reserved = this.reservedRoots.get(pid);
|
|
3588
|
+
return reserved !== undefined && !isInstance(reserved.outcome, OutcomeCell);
|
|
3589
|
+
}
|
|
3590
|
+
private hasJob(
|
|
3591
|
+
job: number,
|
|
3592
|
+
reserved: readonly { pid: number; signals: SignalTransport }[],
|
|
3593
|
+
): boolean {
|
|
3594
|
+
if (reserved.length > 0) return true;
|
|
3595
|
+
for (const root of this.roots.values()) if (peekDirectoryJob(root.directory, job)) return true;
|
|
3596
|
+
const entry = this.options.table.job(job);
|
|
3597
|
+
if (entry && !this.isDirectoryBackedJob(entry)) return true;
|
|
3598
|
+
for (const root of this.reservedRoots.values())
|
|
3599
|
+
if (root.job === job && !isInstance(root.outcome, OutcomeCell)) return true;
|
|
3600
|
+
return false;
|
|
3601
|
+
}
|
|
3572
3602
|
async kill(pid: number, signal: number): Promise<void> {
|
|
3573
|
-
const sig =
|
|
3603
|
+
const sig = checkedKillSignal(signal);
|
|
3604
|
+
if (sig === 0) {
|
|
3605
|
+
if (this.suspended || this.hasProcess(pid)) return;
|
|
3606
|
+
throw new ProcessError(ProcessErrno.SRCH, `unknown process ${pid}`);
|
|
3607
|
+
}
|
|
3574
3608
|
const found = this.publishProcessSignal(pid, sig);
|
|
3575
3609
|
const supervisor = await this.ready();
|
|
3576
3610
|
if (this.suspended) return;
|
|
@@ -3624,8 +3658,12 @@ export class BrowserProcessBroker {
|
|
|
3624
3658
|
signal: number,
|
|
3625
3659
|
reserved: readonly { pid: number; signals: SignalTransport }[] = [],
|
|
3626
3660
|
): Promise<void> {
|
|
3627
|
-
const sig =
|
|
3628
|
-
|
|
3661
|
+
const sig = checkedKillSignal(signal);
|
|
3662
|
+
if (sig === 0) {
|
|
3663
|
+
if (this.suspended || this.hasJob(job, reserved)) return;
|
|
3664
|
+
throw new ProcessError(ProcessErrno.SRCH, `unknown job ${job}`);
|
|
3665
|
+
}
|
|
3666
|
+
const states = this.states().filter((state) => state.job === job);
|
|
3629
3667
|
const seen = new Set(states.map((state) => state.pid));
|
|
3630
3668
|
const records = Array.from(this.options.table.values()).filter(
|
|
3631
3669
|
(record) => record.job === job && !seen.has(record.pid),
|
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 {
|
|
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
|
|
832
|
-
if (
|
|
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
|
-
|
|
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 =
|
|
48
|
+
const existing = getSharedOffset(resource);
|
|
23
49
|
if (existing) return existing.buffer;
|
|
24
50
|
const shared = buffer ?? allocateSharedControl(16);
|
|
25
|
-
const cells = new
|
|
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
|
|
29
|
-
const value = new
|
|
30
|
-
const
|
|
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
|
-
|
|
33
|
-
|
|
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
|
-
|
|
72
|
+
const state: SharedOffset = {
|
|
37
73
|
buffer: shared,
|
|
38
74
|
cells,
|
|
75
|
+
ownerStates,
|
|
39
76
|
identity,
|
|
40
77
|
section: new FilesystemSection(identity),
|
|
41
|
-
|
|
42
|
-
|
|
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
|
-
|
|
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:
|
|
59
|
-
set: (
|
|
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: () =>
|
|
65
|
-
set: (
|
|
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
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
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 =
|
|
95
|
-
if (owner === 0)
|
|
96
|
-
|
|
97
|
-
|
|
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
|
-
|
|
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
|
-
|
|
106
|
-
|
|
107
|
-
|
|
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
|
|
111
|
-
append
|
|
177
|
+
position,
|
|
178
|
+
append,
|
|
112
179
|
commit(nextOffset) {
|
|
113
180
|
if (phase !== "held") throw new Error("file offset lease is not uncommitted");
|
|
114
|
-
|
|
181
|
+
state.writeOffset(nextOffset);
|
|
115
182
|
phase = "committed";
|
|
116
183
|
},
|
|
117
184
|
release() {
|
|
118
185
|
if (phase === "released") return;
|
|
119
186
|
phase = "released";
|
|
120
|
-
|
|
121
|
-
|
|
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 =
|
|
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
|
-
|
|
153
|
-
|
|
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(
|
|
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 =
|
|
236
|
+
const owner = atomicsCompareExchange(cells, 0, 0, identity.owner);
|
|
163
237
|
if (owner === 0) return 0;
|
|
164
|
-
if (
|
|
165
|
-
|
|
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
|
-
|
|
245
|
+
atomicsWait(cells, 0, owner, 10);
|
|
172
246
|
}
|
|
173
247
|
}
|