@webpodjs/fs-worker 0.0.0-stage → 0.1.1
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/README.md +96 -2
- package/dist/abi/index.js +3 -0
- package/dist/abi/ring.js +389 -0
- package/dist/pkg/webpod_fs_wasm.d.ts +376 -0
- package/dist/pkg/webpod_fs_wasm.js +1724 -0
- package/dist/pkg/webpod_fs_wasm_bg.wasm +0 -0
- package/dist/pkg/webpod_fs_wasm_bg.wasm.d.ts +76 -0
- package/dist/replays.js +147 -0
- package/dist/rpc.js +96 -0
- package/dist/tabs.js +256 -0
- package/dist/worker.js +421 -0
- package/package.json +34 -4
package/README.md
CHANGED
|
@@ -1,3 +1,97 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @webpodjs/fs-worker
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The pod's FS Worker (`docs/host-engine.md` §4, `docs/storage.md`, `docs/design/workspace-fs.md`).
|
|
4
|
+
One dedicated module Worker serves:
|
|
5
|
+
|
|
6
|
+
| Device | Engine class | Backend |
|
|
7
|
+
|---|---|---|
|
|
8
|
+
| `webpod-root` | blk, read-only | lazy base image over HTTP Range + OPFS chunk cache |
|
|
9
|
+
| `webpod-data` | blk | persistent disk: OPFS, IndexedDB fallback |
|
|
10
|
+
| `webpod-ws` | 9p | shared `/workspace` (inode store on OPFS, memory fallback) |
|
|
11
|
+
|
|
12
|
+
and the page side of `/workspace` over a MessagePort (`createWorkspaceFs` in `@webpodjs/sdk`).
|
|
13
|
+
|
|
14
|
+
## Build
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
./build.sh # dist/worker.js, dist/rpc.js, dist/pkg (wasm), dist/abi (copy of @webpodjs/abi)
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Serve `dist/` and pass `dist/worker.js` to `fsWorker(url, spec)`.
|
|
21
|
+
|
|
22
|
+
## Messages
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
// host -> worker
|
|
26
|
+
{ type: "init", podId, imageUrl, manifestUrl?, dataSize, dataBackend?: "auto"|"opfs"|"idb"|"memory",
|
|
27
|
+
onConflict?: "fail"|"ephemeral", workspace?: false | { mountPoint?: "/workspace", uid?, gid?, msize?,
|
|
28
|
+
localPaths?: ["node_modules"], // kept on the guest's data disk: hidden from the page (bind mounts)
|
|
29
|
+
shareTabs?: true }, // another tab holds the workspace: served by it (src/tabs.js), else
|
|
30
|
+
// in memory here (false; ephemeral.workspace "locked")
|
|
31
|
+
prefetch?: false | url, // default <imageUrl>.prefetch.json, fetched in the background if present
|
|
32
|
+
packedUrl?: false | url, // default <imageUrl>.wpz: the packed image, read instead of the blob if present
|
|
33
|
+
restore?: name, force? } // restore a snapshot before serving (refused if taken on another image)
|
|
34
|
+
{ type: "attach", serial: "webpod-root"|"webpod-data" | id: "webpod-ws", memory, toEngine, fromEngine }
|
|
35
|
+
{ type: "fs-port", port: MessagePort } // transferred; page PodFs RPC (src/rpc.js); an op on a
|
|
36
|
+
// path being replayed waits for that replay first
|
|
37
|
+
// (src/replays.js); the "settle" op is answered once
|
|
38
|
+
// the ops before it are done and the guest replayed
|
|
39
|
+
// the creates and deletes so far
|
|
40
|
+
{ type: "stats" } // -> { type: "stats", root: { fetchedBytes, transferredBytes,
|
|
41
|
+
// packed, packFallback?, fetchRequests, cacheHits, memoryHits } }
|
|
42
|
+
{ type: "trace" } // -> { type: "trace", manifest, chunks }: boot profile
|
|
43
|
+
{ type: "snapshot", name, meta? } // -> { type: "snapshot", info }: data disk + workspace
|
|
44
|
+
{ type: "restore", name, force? } // -> { type: "restored", info }: only before attach
|
|
45
|
+
{ type: "snapshots" } // -> { type: "snapshots", list: info[] }
|
|
46
|
+
{ type: "delete-snapshot", name } // -> { type: "snapshot-deleted", name, deleted }
|
|
47
|
+
{ type: "export-snapshot", name } // -> { type: "exported", name, file: Blob } (one tar; a File with OPFS)
|
|
48
|
+
{ type: "import-snapshot", file, name? } // -> { type: "imported", info }
|
|
49
|
+
{ type: "snapshot-memory", name, memory, ramOffset, ramSize, deviceState, meta }
|
|
50
|
+
// -> { type: "snapshot-memory", info }: guest stopped; RAM read
|
|
51
|
+
// from the engine memory + device state + data + workspace
|
|
52
|
+
// with its 9P session (fids, open files, readdir positions)
|
|
53
|
+
{ type: "memory-snapshot-check", name, meta } // -> { ok, mismatches[] } against the binding keys
|
|
54
|
+
{ type: "prefetch-memory", name } // -> { type: "memory-prefetched", name, bytes }: reads the RAM
|
|
55
|
+
// (decompressed) and device state ahead, so the next
|
|
56
|
+
// restore-memory of name only copies; send it while the
|
|
57
|
+
// engine starts, before it announces its RAM
|
|
58
|
+
{ type: "restore-memory", name, memory, ramOffset, ramSize, meta, fresh?, force? }
|
|
59
|
+
// -> { type: "memory-restored", bytes, deviceState, workspaceSession }
|
|
60
|
+
// (fills RAM; data/workspace come from init.restore = name;
|
|
61
|
+
// workspaceSession: the guest's 9P session came back with
|
|
62
|
+
// them, so /workspace stays mounted as it was, else the
|
|
63
|
+
// host mounts it again)
|
|
64
|
+
{ type: "fetch-boot-snapshot", url, name } // -> { type: "boot-snapshot", info, fetchedBytes }: imports a
|
|
65
|
+
// published boot snapshot (`webpod-build snapshot` output at url)
|
|
66
|
+
// as snapshot name; downloads only the chunks the store lacks
|
|
67
|
+
// (its RAM stays in memory for prefetch-memory and is stored
|
|
68
|
+
// 3 s after restore-memory, or on stop)
|
|
69
|
+
// info = { name, created (ms), volumes: { data, workspace?, p9?, ram?, devstate? } (manifest ids),
|
|
70
|
+
// meta: { image, kind?, engine, machine, cpus, ram, devices, kernel, cmdline, ... } }
|
|
71
|
+
{ type: "flush" } // -> { type: "flushed" }: workspace and data disk to storage
|
|
72
|
+
// (the SDK sends it on pagehide / hidden)
|
|
73
|
+
{ type: "stop" }
|
|
74
|
+
// worker -> host
|
|
75
|
+
{ type: "volumes", devices: [{ serial, sizeBytes, readOnly, indirect }, ..., { class: "9p", id, msize, localPaths }],
|
|
76
|
+
ephemeral: { data: ""|"locked"|"memory", workspace: ""|"locked"|"no-opfs"|"shared" }, dataFresh }
|
|
77
|
+
{ type: "ready", serial } | { type: "ready", id } | { type: "stopped" } | { type: "log", level, text } | { type: "error", message }
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Block rings carry `webpod_abi::blk` messages (`docs/abi.md`), the 9p rings raw 9P2000.L messages.
|
|
81
|
+
`dataFresh`: nothing was ever written to the data disk and `init` restored no snapshot, i.e. a
|
|
82
|
+
new pod (a boot snapshot's disk can replace it). `indirect: true`: the worker also serves
|
|
83
|
+
indirect block requests, whose data it reads from and
|
|
84
|
+
writes to the engine memory given in `attach` (`docs/design/blk-indirect.md`).
|
|
85
|
+
The workspace is synced every second and on `stop`; change events are pushed to every page port
|
|
86
|
+
every 30 ms (`origin: "page"` events are what the SDK replays in the guest with `FsNotify`; the
|
|
87
|
+
guest's replay events and `*.~wp` names are left out; `dir: true` marks a directory).
|
|
88
|
+
|
|
89
|
+
## Test
|
|
90
|
+
|
|
91
|
+
```sh
|
|
92
|
+
npm run build -w @webpodjs/sdk && ./build.sh
|
|
93
|
+
node test/browser.mjs chromium # also firefox, webkit (needs playwright)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
The test page plays the engine: it formats rings in a SharedArrayBuffer, drives both disks and the
|
|
97
|
+
9P share, uses the PodFs port, then restarts the Worker and checks persistence.
|
package/dist/abi/ring.js
ADDED
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
// SPSC message ring over a SharedArrayBuffer, byte-compatible with webpod_abi::ring (docs/abi.md).
|
|
2
|
+
// Source of truth for every TS user (engine Worker, host Workers, SDK); the SDK build copies it.
|
|
3
|
+
export const RING_MAGIC = 0x47525057; // "WPRG"
|
|
4
|
+
export const RING_VERSION = 1;
|
|
5
|
+
export const RING_HEADER_SIZE = 256;
|
|
6
|
+
const HEAD = 64 / 4;
|
|
7
|
+
const TAIL = 128 / 4;
|
|
8
|
+
const CONSUMER_WAITING = 192 / 4;
|
|
9
|
+
const PRODUCER_WAITING = 196 / 4;
|
|
10
|
+
const PAD = 0xffffffff;
|
|
11
|
+
const MIN_CAPACITY = 64;
|
|
12
|
+
const MAX_CAPACITY = 1 << 30;
|
|
13
|
+
export class RingError extends Error {
|
|
14
|
+
kind;
|
|
15
|
+
constructor(kind, message) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.kind = kind;
|
|
18
|
+
this.name = "RingError";
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const padded = (len) => (len + 3) & ~3;
|
|
22
|
+
/** Formats a ring with `capacity` data bytes (power of two, 64 B .. 1 GiB) at `byteOffset`. */
|
|
23
|
+
export function initRing(buffer, byteOffset, capacity) {
|
|
24
|
+
if (capacity < MIN_CAPACITY || capacity > MAX_CAPACITY || (capacity & (capacity - 1)) !== 0) {
|
|
25
|
+
throw new RingError("bad-header", `bad ring capacity ${capacity}`);
|
|
26
|
+
}
|
|
27
|
+
if (byteOffset % 64 !== 0 || byteOffset + RING_HEADER_SIZE + capacity > buffer.byteLength) {
|
|
28
|
+
throw new RingError("bad-header", "ring region is misaligned or too small");
|
|
29
|
+
}
|
|
30
|
+
const words = new Int32Array(buffer, byteOffset, RING_HEADER_SIZE / 4);
|
|
31
|
+
for (let i = 0; i < words.length; i++)
|
|
32
|
+
Atomics.store(words, i, 0);
|
|
33
|
+
Atomics.store(words, 2, capacity);
|
|
34
|
+
Atomics.store(words, 1, RING_VERSION);
|
|
35
|
+
Atomics.store(words, 0, RING_MAGIC | 0);
|
|
36
|
+
}
|
|
37
|
+
/** Allocates a SharedArrayBuffer holding one formatted ring (tests, host-owned rings). */
|
|
38
|
+
export function createRing(capacity) {
|
|
39
|
+
const sab = new SharedArrayBuffer(RING_HEADER_SIZE + capacity);
|
|
40
|
+
initRing(sab, 0, capacity);
|
|
41
|
+
return sab;
|
|
42
|
+
}
|
|
43
|
+
class RingView {
|
|
44
|
+
buffer;
|
|
45
|
+
words;
|
|
46
|
+
data;
|
|
47
|
+
view;
|
|
48
|
+
capacity;
|
|
49
|
+
constructor(buffer, byteOffset) {
|
|
50
|
+
this.buffer = buffer;
|
|
51
|
+
if (byteOffset % 64 !== 0)
|
|
52
|
+
throw new RingError("bad-header", "ring region is not 64-byte aligned");
|
|
53
|
+
if (buffer.byteLength < byteOffset + RING_HEADER_SIZE)
|
|
54
|
+
throw new RingError("bad-header", "ring region is too small");
|
|
55
|
+
this.words = new Int32Array(buffer, byteOffset, RING_HEADER_SIZE / 4);
|
|
56
|
+
const magic = Atomics.load(this.words, 0) >>> 0;
|
|
57
|
+
if (magic !== RING_MAGIC)
|
|
58
|
+
throw new RingError("bad-header", `bad ring magic 0x${magic.toString(16)}`);
|
|
59
|
+
const version = Atomics.load(this.words, 1);
|
|
60
|
+
if (version !== RING_VERSION)
|
|
61
|
+
throw new RingError("bad-header", `unsupported ring version ${version}`);
|
|
62
|
+
const capacity = Atomics.load(this.words, 2) >>> 0;
|
|
63
|
+
if (capacity < MIN_CAPACITY || capacity > MAX_CAPACITY || (capacity & (capacity - 1)) !== 0) {
|
|
64
|
+
throw new RingError("bad-header", `bad ring capacity ${capacity}`);
|
|
65
|
+
}
|
|
66
|
+
if (buffer.byteLength < byteOffset + RING_HEADER_SIZE + capacity)
|
|
67
|
+
throw new RingError("bad-header", "ring region is too small");
|
|
68
|
+
this.capacity = capacity;
|
|
69
|
+
this.data = new Uint8Array(buffer, byteOffset + RING_HEADER_SIZE, capacity);
|
|
70
|
+
this.view = new DataView(buffer, byteOffset + RING_HEADER_SIZE, capacity);
|
|
71
|
+
}
|
|
72
|
+
get maxMessageLen() {
|
|
73
|
+
return this.capacity / 2 - 4;
|
|
74
|
+
}
|
|
75
|
+
head() {
|
|
76
|
+
return Atomics.load(this.words, HEAD) >>> 0;
|
|
77
|
+
}
|
|
78
|
+
tail() {
|
|
79
|
+
return Atomics.load(this.words, TAIL) >>> 0;
|
|
80
|
+
}
|
|
81
|
+
off(pos) {
|
|
82
|
+
return pos & (this.capacity - 1);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** Producer half. Only one producer may exist per ring. */
|
|
86
|
+
export class RingProducer {
|
|
87
|
+
#r;
|
|
88
|
+
#head;
|
|
89
|
+
/** The tail read by the last reload in #fit(); waitTarget() must wait on this value, not a fresh one. */
|
|
90
|
+
#seenTail = 0;
|
|
91
|
+
/** Attaches to a formatted ring at `byteOffset` (e.g. inside the engine's wasm memory). */
|
|
92
|
+
constructor(buffer, byteOffset = 0) {
|
|
93
|
+
this.#r = new RingView(buffer, byteOffset);
|
|
94
|
+
this.#head = this.#r.head();
|
|
95
|
+
this.#seenTail = this.#r.tail();
|
|
96
|
+
}
|
|
97
|
+
get maxMessageLen() {
|
|
98
|
+
return this.#r.maxMessageLen;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Room for a `len`-byte message: the skip to the start (0 if none), or -1 when full. Uses the
|
|
102
|
+
* cached tail while it shows enough room (tail only grows, so the cache can only under-report
|
|
103
|
+
* free space) and reloads it otherwise, or always when `fresh` (prepareWait).
|
|
104
|
+
*/
|
|
105
|
+
#fit(len, fresh = false) {
|
|
106
|
+
const r = this.#r;
|
|
107
|
+
if (len > r.maxMessageLen)
|
|
108
|
+
throw new RingError("too-large", `message of ${len} bytes does not fit the ring`);
|
|
109
|
+
if (!fresh) {
|
|
110
|
+
const record = 4 + padded(len);
|
|
111
|
+
const toEnd = r.capacity - r.off(this.#head);
|
|
112
|
+
const skip = toEnd < record ? toEnd : 0;
|
|
113
|
+
if (skip + record <= r.capacity - ((this.#head - this.#seenTail) >>> 0))
|
|
114
|
+
return skip;
|
|
115
|
+
}
|
|
116
|
+
const tail = r.tail();
|
|
117
|
+
this.#seenTail = tail;
|
|
118
|
+
const used = (this.#head - tail) >>> 0;
|
|
119
|
+
if (used > r.capacity || tail % 4 !== 0)
|
|
120
|
+
throw new RingError("corrupt", "ring corrupted by peer");
|
|
121
|
+
const record = 4 + padded(len);
|
|
122
|
+
const toEnd = r.capacity - r.off(this.#head);
|
|
123
|
+
const skip = toEnd < record ? toEnd : 0;
|
|
124
|
+
return skip + record > r.capacity - used ? -1 : skip;
|
|
125
|
+
}
|
|
126
|
+
/** Pushes `msg`, waiting (without blocking the thread) while the ring is full. */
|
|
127
|
+
async pushAsync(msg, options = {}) {
|
|
128
|
+
while (!this.tryPush(msg))
|
|
129
|
+
await waitWritable(this, msg.length, options);
|
|
130
|
+
}
|
|
131
|
+
/** Pushes one message; false when the ring is full. Wakes a sleeping consumer. */
|
|
132
|
+
tryPush(msg) {
|
|
133
|
+
const skip = this.#fit(msg.length);
|
|
134
|
+
if (skip < 0)
|
|
135
|
+
return false;
|
|
136
|
+
const r = this.#r;
|
|
137
|
+
if (skip > 0)
|
|
138
|
+
r.view.setUint32(r.off(this.#head), PAD, true);
|
|
139
|
+
const start = (this.#head + skip) >>> 0;
|
|
140
|
+
r.data.set(msg, r.off(start) + 4);
|
|
141
|
+
r.view.setUint32(r.off(start), msg.length, true);
|
|
142
|
+
this.#head = (start + 4 + padded(msg.length)) >>> 0;
|
|
143
|
+
Atomics.store(r.words, HEAD, this.#head | 0);
|
|
144
|
+
// Plain load first: the exchange (a write to the flag line both sides use) only when set.
|
|
145
|
+
if (Atomics.load(r.words, CONSUMER_WAITING) !== 0 && Atomics.exchange(r.words, CONSUMER_WAITING, 0) !== 0) {
|
|
146
|
+
Atomics.notify(r.words, HEAD);
|
|
147
|
+
}
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
/** Announces that the producer will sleep until `len` bytes fit; false if they already do. */
|
|
151
|
+
prepareWait(len) {
|
|
152
|
+
Atomics.store(this.#r.words, PRODUCER_WAITING, 1);
|
|
153
|
+
if (this.#fit(len, true) >= 0) {
|
|
154
|
+
Atomics.store(this.#r.words, PRODUCER_WAITING, 0);
|
|
155
|
+
return false;
|
|
156
|
+
}
|
|
157
|
+
return true;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* The word and value to wait on after a successful prepareWait: the tail that prepareWait saw
|
|
161
|
+
* the ring full at. Re-reading tail here would lose the wake-up when the consumer frees space
|
|
162
|
+
* in between (it clears producer_waiting and notifies before we sleep, then never again).
|
|
163
|
+
*/
|
|
164
|
+
waitTarget() {
|
|
165
|
+
return [this.#r.words, TAIL, this.#seenTail | 0];
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/** Consumer half. Only one consumer may exist per ring. */
|
|
169
|
+
export class RingConsumer {
|
|
170
|
+
#r;
|
|
171
|
+
#tail;
|
|
172
|
+
/** Last head read from shared memory; reloaded only when it shows the ring empty. */
|
|
173
|
+
#seenHead;
|
|
174
|
+
constructor(buffer, byteOffset = 0) {
|
|
175
|
+
this.#r = new RingView(buffer, byteOffset);
|
|
176
|
+
this.#tail = this.#r.tail();
|
|
177
|
+
this.#seenHead = this.#tail;
|
|
178
|
+
}
|
|
179
|
+
hasMessages() {
|
|
180
|
+
return this.#r.head() !== this.#tail;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* The next message without copying, or null when empty. `bytes` views shared memory and is valid
|
|
184
|
+
* until `release()`, which consumes it and wakes a waiting producer (returns whether it did).
|
|
185
|
+
* Not releasing leaves the message in place: the next peek returns it again.
|
|
186
|
+
*
|
|
187
|
+
* head is cached and reloaded (and validated) only when the cached value shows the ring empty,
|
|
188
|
+
* so a producer that corrupts head is detected at that reload rather than on the very next peek.
|
|
189
|
+
* Records are validated either way, so a corrupt peer can never cause an out-of-bounds access.
|
|
190
|
+
*/
|
|
191
|
+
peek() {
|
|
192
|
+
const r = this.#r;
|
|
193
|
+
const cap = r.capacity;
|
|
194
|
+
let tail = this.#tail;
|
|
195
|
+
let avail = (this.#seenHead - tail) >>> 0;
|
|
196
|
+
if (avail === 0) {
|
|
197
|
+
this.#seenHead = r.head();
|
|
198
|
+
avail = (this.#seenHead - tail) >>> 0;
|
|
199
|
+
if (avail === 0)
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
if (avail > cap || avail % 4 !== 0)
|
|
203
|
+
throw new RingError("corrupt", "ring corrupted by peer");
|
|
204
|
+
let len = r.view.getUint32(r.off(tail), true);
|
|
205
|
+
if (len === PAD) {
|
|
206
|
+
const skip = cap - r.off(tail);
|
|
207
|
+
if (skip >= avail)
|
|
208
|
+
throw new RingError("corrupt", "ring corrupted by peer");
|
|
209
|
+
tail = (tail + skip) >>> 0;
|
|
210
|
+
avail -= skip;
|
|
211
|
+
len = r.view.getUint32(r.off(tail), true);
|
|
212
|
+
}
|
|
213
|
+
if (len > cap / 2 - 4)
|
|
214
|
+
throw new RingError("corrupt", "ring corrupted by peer");
|
|
215
|
+
const record = 4 + padded(len);
|
|
216
|
+
if (record > avail || r.off(tail) + record > cap)
|
|
217
|
+
throw new RingError("corrupt", "ring corrupted by peer");
|
|
218
|
+
const start = r.off(tail) + 4;
|
|
219
|
+
const next = (tail + record) >>> 0;
|
|
220
|
+
const expected = this.#tail;
|
|
221
|
+
return {
|
|
222
|
+
bytes: r.data.subarray(start, start + len),
|
|
223
|
+
release: () => {
|
|
224
|
+
if (this.#tail !== expected)
|
|
225
|
+
throw new RingError("corrupt", "message released twice or out of order");
|
|
226
|
+
this.#tail = next;
|
|
227
|
+
Atomics.store(r.words, TAIL, next | 0);
|
|
228
|
+
// Plain load first: the exchange (a write to the flag line both sides use) only when set.
|
|
229
|
+
if (Atomics.load(r.words, PRODUCER_WAITING) === 0 || Atomics.exchange(r.words, PRODUCER_WAITING, 0) === 0) {
|
|
230
|
+
return false;
|
|
231
|
+
}
|
|
232
|
+
Atomics.notify(r.words, TAIL);
|
|
233
|
+
return true;
|
|
234
|
+
},
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
/** Pops (copies and releases) the next message, or null when empty. Wakes a waiting producer. */
|
|
238
|
+
tryPop() {
|
|
239
|
+
const m = this.peek();
|
|
240
|
+
if (!m)
|
|
241
|
+
return null;
|
|
242
|
+
const copy = m.bytes.slice();
|
|
243
|
+
m.release();
|
|
244
|
+
return copy;
|
|
245
|
+
}
|
|
246
|
+
/** Alias of `tryPop` (webpod_abi naming). */
|
|
247
|
+
pop() {
|
|
248
|
+
return this.tryPop();
|
|
249
|
+
}
|
|
250
|
+
/** Pops everything currently in the ring. */
|
|
251
|
+
drain(max = Infinity) {
|
|
252
|
+
const out = [];
|
|
253
|
+
for (let m = out.length < max ? this.tryPop() : null; m; m = out.length < max ? this.tryPop() : null)
|
|
254
|
+
out.push(m);
|
|
255
|
+
return out;
|
|
256
|
+
}
|
|
257
|
+
/** Announces that the consumer will sleep; false if messages arrived meanwhile. */
|
|
258
|
+
prepareWait() {
|
|
259
|
+
Atomics.store(this.#r.words, CONSUMER_WAITING, 1);
|
|
260
|
+
if (this.hasMessages()) {
|
|
261
|
+
Atomics.store(this.#r.words, CONSUMER_WAITING, 0);
|
|
262
|
+
return false;
|
|
263
|
+
}
|
|
264
|
+
return true;
|
|
265
|
+
}
|
|
266
|
+
waitTarget() {
|
|
267
|
+
return [this.#r.words, HEAD, this.#tail | 0];
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
/** At most one outstanding waiter per word (see waitWord). */
|
|
271
|
+
const waiters = new WeakMap();
|
|
272
|
+
/** This thread's waiters that have not settled yet, given up ones included. */
|
|
273
|
+
const pending = new Set();
|
|
274
|
+
/**
|
|
275
|
+
* Settles this thread's outstanding ring waits (a notify on each word) and resolves once they have
|
|
276
|
+
* settled, or after `timeoutMs`. A Worker calls it before it is terminated: the waits have no
|
|
277
|
+
* timeout, and iOS 26 hung `Worker.terminate()` on the page while one was pending (T49).
|
|
278
|
+
*/
|
|
279
|
+
export async function settleWaits(timeoutMs = 200) {
|
|
280
|
+
if (pending.size === 0)
|
|
281
|
+
return;
|
|
282
|
+
const all = [...pending];
|
|
283
|
+
for (const w of all)
|
|
284
|
+
Atomics.notify(w.words, w.index);
|
|
285
|
+
let timer;
|
|
286
|
+
await Promise.race([Promise.all(all.map((w) => w.settled)), new Promise((r) => (timer = setTimeout(r, timeoutMs)))]);
|
|
287
|
+
clearTimeout(timer);
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Sleeps until the word changes from `value`, a notify, the signal aborts, or the watchdog fires.
|
|
291
|
+
* Never blocks the thread.
|
|
292
|
+
*
|
|
293
|
+
* The waitAsync has no timeout and outlives the sleep: a notify wakes every waiter on the word
|
|
294
|
+
* whatever value it waited for, so the next sleep on the same word reuses it, and a new one is
|
|
295
|
+
* made only once it has settled. A waitAsync with a timeout per sleep, raced with a timer as
|
|
296
|
+
* before, made iOS 26 slower with every sleep: wake-ups took 16x longer within five minutes of a
|
|
297
|
+
* busy ring (bench/net wa-pace.html, T49), where one outstanding waiter stays flat. The watchdog
|
|
298
|
+
* still bounds each sleep (WebKit can lose waitAsync wake-ups, P1 #133); when it finds the word
|
|
299
|
+
* changed under a waiter that never fired, that waiter is given up and the next sleep makes a
|
|
300
|
+
* fresh one.
|
|
301
|
+
*/
|
|
302
|
+
async function waitWord(words, index, value, options) {
|
|
303
|
+
const ms = options.watchdogMs ?? 50;
|
|
304
|
+
const signal = options.signal;
|
|
305
|
+
if (signal?.aborted) {
|
|
306
|
+
// As before: an aborted signal still sleeps to the watchdog, a macrotask. Callers that loop on
|
|
307
|
+
// other conditions (channel.ts) would otherwise spin in microtasks and freeze the page.
|
|
308
|
+
await new Promise((r) => setTimeout(r, ms));
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
const waitAsync = Atomics.waitAsync;
|
|
312
|
+
let waiter;
|
|
313
|
+
if (typeof waitAsync === "function") {
|
|
314
|
+
let byIndex = waiters.get(words);
|
|
315
|
+
if (!byIndex)
|
|
316
|
+
waiters.set(words, (byIndex = new Map()));
|
|
317
|
+
waiter = byIndex.get(index);
|
|
318
|
+
if (!waiter) {
|
|
319
|
+
const res = waitAsync(words, index, value);
|
|
320
|
+
if (!res.async)
|
|
321
|
+
return;
|
|
322
|
+
const map = byIndex;
|
|
323
|
+
const w = { words, index, sleepers: new Set(), settled: Promise.resolve() };
|
|
324
|
+
// One reaction per waiter: it may outlive many sleeps, and a reaction per sleep would pile
|
|
325
|
+
// up on it while the ring is quiet.
|
|
326
|
+
w.settled = res.value.then(() => {
|
|
327
|
+
pending.delete(w);
|
|
328
|
+
if (map.get(index) === w)
|
|
329
|
+
map.delete(index);
|
|
330
|
+
for (const wake of w.sleepers)
|
|
331
|
+
wake();
|
|
332
|
+
});
|
|
333
|
+
pending.add(w);
|
|
334
|
+
byIndex.set(index, w);
|
|
335
|
+
waiter = w;
|
|
336
|
+
}
|
|
337
|
+
else if (Atomics.load(words, index) !== value)
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
let timedOut = false;
|
|
341
|
+
await new Promise((resolve) => {
|
|
342
|
+
let timer;
|
|
343
|
+
const end = () => {
|
|
344
|
+
clearTimeout(timer);
|
|
345
|
+
signal?.removeEventListener("abort", end);
|
|
346
|
+
waiter?.sleepers.delete(end);
|
|
347
|
+
resolve();
|
|
348
|
+
};
|
|
349
|
+
timer = setTimeout(() => {
|
|
350
|
+
timedOut = true;
|
|
351
|
+
end();
|
|
352
|
+
}, ms);
|
|
353
|
+
signal?.addEventListener("abort", end, { once: true });
|
|
354
|
+
waiter?.sleepers.add(end);
|
|
355
|
+
});
|
|
356
|
+
if (timedOut && waiter && Atomics.load(words, index) !== value) {
|
|
357
|
+
const byIndex = waiters.get(words);
|
|
358
|
+
if (byIndex?.get(index) === waiter)
|
|
359
|
+
byIndex.delete(index);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
/** Waits until the consumer has a message (or the watchdog fires; callers just re-check). */
|
|
363
|
+
export async function waitReadable(c, options = {}) {
|
|
364
|
+
if (!c.prepareWait())
|
|
365
|
+
return;
|
|
366
|
+
const [words, index, value] = c.waitTarget();
|
|
367
|
+
await waitWord(words, index, value, options);
|
|
368
|
+
}
|
|
369
|
+
/** Waits until `len` bytes may fit (or the watchdog fires). */
|
|
370
|
+
export async function waitWritable(p, len, options = {}) {
|
|
371
|
+
if (!p.prepareWait(len))
|
|
372
|
+
return;
|
|
373
|
+
const [words, index, value] = p.waitTarget();
|
|
374
|
+
await waitWord(words, index, value, options);
|
|
375
|
+
}
|
|
376
|
+
/** Names matching webpod_abi (`Ring::init` / `Ring::attach`), for engine-side code. */
|
|
377
|
+
export const Ring = {
|
|
378
|
+
init: initRing,
|
|
379
|
+
/** Validates an existing ring at `byteOffset` (never rewrites its header). */
|
|
380
|
+
attach(buffer, byteOffset = 0) {
|
|
381
|
+
const producer = () => new RingProducer(buffer, byteOffset);
|
|
382
|
+
const consumer = () => new RingConsumer(buffer, byteOffset);
|
|
383
|
+
producer(); // validates
|
|
384
|
+
return { producer, consumer };
|
|
385
|
+
},
|
|
386
|
+
};
|
|
387
|
+
export const waitForMessage = waitReadable;
|
|
388
|
+
export const waitForSpace = waitWritable;
|
|
389
|
+
//# sourceMappingURL=ring.js.map
|