@webpodjs/fs-worker 0.0.0-stage → 0.1.0

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 CHANGED
@@ -1,3 +1,89 @@
1
- # Temporary Holding Version
1
+ # @webpodjs/fs-worker
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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
+ prefetch?: false | url, // default <imageUrl>.prefetch.json, fetched in the background if present
29
+ packedUrl?: false | url, // default <imageUrl>.wpz: the packed image, read instead of the blob if present
30
+ restore?: name, force? } // restore a snapshot before serving (refused if taken on another image)
31
+ { type: "attach", serial: "webpod-root"|"webpod-data" | id: "webpod-ws", memory, toEngine, fromEngine }
32
+ { type: "fs-port", port: MessagePort } // transferred; page PodFs RPC (src/rpc.js); a request with
33
+ // settle: true is answered once the guest replayed the
34
+ // creates and deletes so far (or after 2 s)
35
+ { type: "stats" } // -> { type: "stats", root: { fetchedBytes, transferredBytes,
36
+ // packed, packFallback?, fetchRequests, cacheHits, memoryHits } }
37
+ { type: "trace" } // -> { type: "trace", manifest, chunks }: boot profile
38
+ { type: "snapshot", name, meta? } // -> { type: "snapshot", info }: data disk + workspace
39
+ { type: "restore", name, force? } // -> { type: "restored", info }: only before attach
40
+ { type: "snapshots" } // -> { type: "snapshots", list: info[] }
41
+ { type: "delete-snapshot", name } // -> { type: "snapshot-deleted", name, deleted }
42
+ { type: "export-snapshot", name } // -> { type: "exported", name, file: Blob } (one tar; a File with OPFS)
43
+ { type: "import-snapshot", file, name? } // -> { type: "imported", info }
44
+ { type: "snapshot-memory", name, memory, ramOffset, ramSize, deviceState, meta }
45
+ // -> { type: "snapshot-memory", info }: guest stopped; RAM read
46
+ // from the engine memory + device state + data + workspace
47
+ // with its 9P session (fids, open files, readdir positions)
48
+ { type: "memory-snapshot-check", name, meta } // -> { ok, mismatches[] } against the binding keys
49
+ { type: "prefetch-memory", name } // -> { type: "memory-prefetched", name, bytes }: reads the RAM
50
+ // (decompressed) and device state ahead, so the next
51
+ // restore-memory of name only copies; send it while the
52
+ // engine starts, before it announces its RAM
53
+ { type: "restore-memory", name, memory, ramOffset, ramSize, meta, fresh?, force? }
54
+ // -> { type: "memory-restored", bytes, deviceState, workspaceSession }
55
+ // (fills RAM; data/workspace come from init.restore = name;
56
+ // workspaceSession: the guest's 9P session came back with
57
+ // them, so /workspace stays mounted as it was, else the
58
+ // host mounts it again)
59
+ { type: "fetch-boot-snapshot", url, name } // -> { type: "boot-snapshot", info, fetchedBytes }: imports a
60
+ // published boot snapshot (`webpod-build snapshot` output at url)
61
+ // as snapshot name; downloads only the chunks the store lacks
62
+ // (its RAM stays in memory for prefetch-memory and is stored
63
+ // 3 s after restore-memory, or on stop)
64
+ // info = { name, created (ms), volumes: { data, workspace?, p9?, ram?, devstate? } (manifest ids),
65
+ // meta: { image, kind?, engine, machine, cpus, ram, devices, kernel, cmdline, ... } }
66
+ { type: "stop" }
67
+ // worker -> host
68
+ { type: "volumes", devices: [{ serial, sizeBytes, readOnly, indirect }, ..., { class: "9p", id, msize }],
69
+ ephemeral: { data: ""|"locked"|"memory", workspace: ""|"locked"|"no-opfs" }, dataFresh }
70
+ { type: "ready", serial } | { type: "ready", id } | { type: "stopped" } | { type: "log", level, text } | { type: "error", message }
71
+ ```
72
+
73
+ Block rings carry `webpod_abi::blk` messages (`docs/abi.md`), the 9p rings raw 9P2000.L messages.
74
+ `dataFresh`: nothing was ever written to the data disk and `init` restored no snapshot, i.e. a
75
+ new pod (a boot snapshot's disk can replace it). `indirect: true`: the worker also serves
76
+ indirect block requests, whose data it reads from and
77
+ writes to the engine memory given in `attach` (`docs/design/blk-indirect.md`).
78
+ The workspace is synced every second and on `stop`; change events are pushed to every page port
79
+ every 30 ms (`origin: "page"` events are what the SDK replays in the guest with `FsNotify`).
80
+
81
+ ## Test
82
+
83
+ ```sh
84
+ npm run build -w @webpodjs/sdk && ./build.sh
85
+ node test/browser.mjs chromium # also firefox, webkit (needs playwright)
86
+ ```
87
+
88
+ The test page plays the engine: it formats rings in a SharedArrayBuffer, drives both disks and the
89
+ 9P share, uses the PodFs port, then restarts the Worker and checks persistence.
@@ -0,0 +1,3 @@
1
+ // @webpodjs/abi: TypeScript side of docs/abi.md (rings), shared by the engine Worker, host Workers and the SDK.
2
+ export * from "./ring.js";
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,317 @@
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
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
271
+ /** Sleeps until the word changes from `value`, a notify, or the watchdog fires. Never blocks the thread. */
272
+ async function waitWord(words, index, value, options) {
273
+ const ms = options.watchdogMs ?? 50;
274
+ const waitAsync = Atomics.waitAsync;
275
+ const abort = options.signal
276
+ ? new Promise((r) => options.signal.addEventListener("abort", () => r(), { once: true }))
277
+ : undefined;
278
+ const timers = [sleep(ms)];
279
+ if (abort)
280
+ timers.push(abort);
281
+ if (typeof waitAsync === "function") {
282
+ const res = waitAsync(words, index, value, ms);
283
+ if (!res.async)
284
+ return;
285
+ await Promise.race([res.value, ...timers]);
286
+ return;
287
+ }
288
+ await Promise.race(timers);
289
+ }
290
+ /** Waits until the consumer has a message (or the watchdog fires; callers just re-check). */
291
+ export async function waitReadable(c, options = {}) {
292
+ if (!c.prepareWait())
293
+ return;
294
+ const [words, index, value] = c.waitTarget();
295
+ await waitWord(words, index, value, options);
296
+ }
297
+ /** Waits until `len` bytes may fit (or the watchdog fires). */
298
+ export async function waitWritable(p, len, options = {}) {
299
+ if (!p.prepareWait(len))
300
+ return;
301
+ const [words, index, value] = p.waitTarget();
302
+ await waitWord(words, index, value, options);
303
+ }
304
+ /** Names matching webpod_abi (`Ring::init` / `Ring::attach`), for engine-side code. */
305
+ export const Ring = {
306
+ init: initRing,
307
+ /** Validates an existing ring at `byteOffset` (never rewrites its header). */
308
+ attach(buffer, byteOffset = 0) {
309
+ const producer = () => new RingProducer(buffer, byteOffset);
310
+ const consumer = () => new RingConsumer(buffer, byteOffset);
311
+ producer(); // validates
312
+ return { producer, consumer };
313
+ },
314
+ };
315
+ export const waitForMessage = waitReadable;
316
+ export const waitForSpace = waitWritable;
317
+ //# sourceMappingURL=ring.js.map