@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/dist/worker.js ADDED
@@ -0,0 +1,421 @@
1
+ // webpod FS Worker (docs/host-engine.md §4): serves the pod's block disks and the shared
2
+ // /workspace. Created by the host (fsWorker() in @webpodjs/sdk); must be a dedicated module Worker
3
+ // (OPFS sync access handles).
4
+ //
5
+ // host -> worker: init, attach (blk by serial, 9p by id), fs-port, stop
6
+ // worker -> host: volumes, ready, stopped, log, error
7
+ import init, { BlockVolumes, SnapshotStore, WorkspaceFs } from "./pkg/webpod_fs_wasm.js";
8
+ import { RingConsumer, RingProducer, settleWaits, waitReadable } from "./abi/index.js";
9
+ import { Replays } from "./replays.js";
10
+ import { serveWorkspace } from "./rpc.js";
11
+ import { HELLO_TIMEOUT_MS, WorkspaceClient, WorkspaceHost, tabLock } from "./tabs.js";
12
+
13
+ const COMPLETION_HEADER = 12;
14
+ const ready = init();
15
+ let volumes = null;
16
+ /** WorkspaceFs, or a WorkspaceClient while another tab of the pod holds the workspace. */
17
+ let workspace = null;
18
+ /** Serves this tab's workspace to the pod's other tabs (tabs.js), while it holds it. */
19
+ let host = null;
20
+ /** This FS Worker among the pod's tabs. */
21
+ const tabId = crypto.randomUUID();
22
+ /** The current workspace, whichever serves it (the PodFs port keeps this one). */
23
+ const current = new Proxy({}, {
24
+ get: (_, k) => {
25
+ const v = workspace?.[k];
26
+ return typeof v === "function" ? v.bind(workspace) : v;
27
+ },
28
+ });
29
+ let snapshots = null;
30
+ /** The snapshot whose 9P session the workspace continues (restored at init), if any. */
31
+ let restoredSession = null;
32
+ /** restore-memory succeeded in this Worker. */
33
+ let ramResumed = false;
34
+ let attached = 0;
35
+ let stopping = false;
36
+ const pumps = [];
37
+ const broadcasts = [];
38
+ const post = (m, transfer = []) => self.postMessage(m, transfer);
39
+ const log = (level, text) => post({ type: "log", level, text });
40
+
41
+ /** Moves batches from the engine's request ring through `handle` into its reply ring. */
42
+ async function pump(name, memory, fromEngine, toEngine, handle) {
43
+ const rx = new RingConsumer(memory, fromEngine);
44
+ const tx = new RingProducer(memory, toEngine);
45
+ try {
46
+ while (!stopping) {
47
+ const batch = rx.drain(256);
48
+ if (batch.length === 0) {
49
+ await waitReadable(rx);
50
+ continue;
51
+ }
52
+ for (const reply of await handle(batch, tx)) if (reply) await tx.pushAsync(reply);
53
+ }
54
+ } catch (e) {
55
+ if (!stopping) post({ type: "error", message: `${name}: ${e?.message ?? e}` });
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Page creates and deletes the guest replays for its inotify watchers (the SDK sends them to the
61
+ * agent), tracked by path until the guest's own event for the path shows the replay done
62
+ * (replays.js). A page write that asks to settle is answered after that: the replay of a create
63
+ * hides the file for a moment, so a guest process started right after the write could miss it.
64
+ * Page ops on a path being replayed wait for it.
65
+ */
66
+ const replays = new Replays();
67
+ /** The guest speaks 9P (it mounted /workspace): page changes will be replayed. */
68
+ let guestMounted = false;
69
+
70
+ /** Absolute paths of the workspace's local paths (not shown to the page). */
71
+ let hidden = new Set();
72
+ const isHidden = (path) => [...hidden].some((h) => path === h || path.startsWith(`${h}/`));
73
+
74
+ /** A path relative to the workspace without "." / ".." components, or null. */
75
+ function relativePath(p) {
76
+ const parts = String(p).split("/").filter((x) => x && x !== ".");
77
+ return parts.length && !parts.includes("..") ? parts.join("/") : null;
78
+ }
79
+
80
+ function flushEvents() {
81
+ if (!workspace) return;
82
+ const raw = workspace.takeEvents().filter((e) => !isHidden(e.path));
83
+ host?.broadcast(raw);
84
+ // Other tabs' changes (page:<tab>, guest:<tab>) are, to this guest, made behind it like the page's.
85
+ const local = raw.map((e) => (e.origin === "page" || e.origin === "guest" ? e : { ...e, origin: "page" }));
86
+ const events = replays.record(local, guestMounted);
87
+ if (events.length) for (const b of broadcasts) b(events, replays.seq);
88
+ }
89
+
90
+ /** Serves this tab's workspace to the pod's other tabs on `channel`. */
91
+ function startHost(podId, channel) {
92
+ host = new WorkspaceHost(workspace, channel, { id: tabId, pod: podId, flush: flushEvents, log });
93
+ }
94
+
95
+ /**
96
+ * Another tab holds the workspace (its lock): served by it (tabs.js), and queued for the lock to
97
+ * take the workspace over when that tab goes. Resolves to the WorkspaceClient, or null when no
98
+ * holder answers (one that does not share: the workspace stays this tab's own, in memory).
99
+ */
100
+ async function joinTabs(podId, args) {
101
+ const channel = new BroadcastChannel(`webpod:ws:${podId}`);
102
+ // Held while this tab lives: the holder learns when it is gone.
103
+ navigator.locks.request(tabLock(podId, tabId), () => new Promise(() => {})).catch(() => {});
104
+ const client = new WorkspaceClient(channel, { id: tabId, log });
105
+ const takeover = WorkspaceFs.takeOver(...args, () => client.session);
106
+ let timer;
107
+ const first = await Promise.race([
108
+ client.found.then(() => "client"),
109
+ takeover.then(() => "holder", () => "failed"),
110
+ new Promise((resolve) => (timer = setTimeout(() => resolve("none"), HELLO_TIMEOUT_MS))),
111
+ ]);
112
+ clearTimeout(timer);
113
+ if (first === "holder") {
114
+ // The holder went meanwhile: this tab holds it now.
115
+ client.detach();
116
+ workspace = await takeover;
117
+ startHost(podId, channel);
118
+ return workspace;
119
+ }
120
+ if (first !== "client") {
121
+ client.detach();
122
+ channel.close();
123
+ takeover.then((ws) => ws.close(), () => {});
124
+ return null;
125
+ }
126
+ takeover.then(
127
+ (ws) => {
128
+ if (workspace !== client) return void ws.close();
129
+ flushEvents();
130
+ client.detach("the workspace's holder changed");
131
+ workspace = ws;
132
+ startHost(podId, channel);
133
+ log("info", "workspace: taken over from the tab that held it");
134
+ },
135
+ (e) => log("warn", `workspace takeover: ${e?.message ?? e}`),
136
+ );
137
+ return client;
138
+ }
139
+
140
+ /** Resolves once the replays of the page changes made so far are done (or given up). */
141
+ function settle() {
142
+ flushEvents();
143
+ return replays.settle();
144
+ }
145
+
146
+ /** Resolves once nothing on `paths` is being replayed (`read`: replays.js); undefined when nothing is. */
147
+ function clearOf(paths, read) {
148
+ flushEvents();
149
+ return replays.clear(paths, read);
150
+ }
151
+
152
+ async function onInit(m) {
153
+ // The packed image (webpod-build writes <image>.wpz) is read instead of the blob when present.
154
+ const packedUrl = m.packedUrl === false ? null : (m.packedUrl ?? `${m.imageUrl}.wpz`);
155
+ volumes = await BlockVolumes.open(m.podId, m.imageUrl, m.manifestUrl ?? "", m.dataSize, m.dataBackend ?? "auto", m.onConflict ?? "fail", packedUrl);
156
+ // indirect: large reads and writes may pass their data by descriptor into the engine memory
157
+ // (docs/design/blk-indirect.md); the host enables it in the engine's device spec.
158
+ const devices = [
159
+ { serial: "webpod-root", sizeBytes: volumes.rootSize, readOnly: true, indirect: true },
160
+ { serial: "webpod-data", sizeBytes: volumes.dataSize, readOnly: false, indirect: true },
161
+ ];
162
+ let wsEphemeral = "";
163
+ if (m.workspace !== false) {
164
+ const w = m.workspace ?? {};
165
+ const msize = w.msize ?? 512 * 1024;
166
+ const mountPoint = (w.mountPoint ?? "/workspace").replace(/\/+$/, "") || "/";
167
+ const args = [m.podId, mountPoint, w.uid ?? 0, w.gid ?? 0, msize];
168
+ workspace = await WorkspaceFs.open(...args);
169
+ if (workspace.ephemeral === "") startHost(m.podId, new BroadcastChannel(`webpod:ws:${m.podId}`));
170
+ else if (workspace.ephemeral === "locked" && w.shareTabs !== false) {
171
+ // Another tab of the pod holds it: shared with that one rather than in memory here.
172
+ const own = workspace;
173
+ const shared = await joinTabs(m.podId, args);
174
+ if (shared) {
175
+ await own.close();
176
+ workspace = shared;
177
+ }
178
+ }
179
+ wsEphemeral = workspace.ephemeral;
180
+ // Kept on the guest's data disk (bind mounts the host makes): hidden from the page here.
181
+ const localPaths = (w.localPaths ?? ["node_modules"]).map(relativePath).filter((p) => p !== null);
182
+ hidden = new Set(localPaths.map((p) => `${mountPoint === "/" ? "" : mountPoint}/${p}`));
183
+ devices.push({ class: "9p", id: "webpod-ws", msize, localPaths });
184
+ // Also gives up replays without progress, waking what waits for them.
185
+ setInterval(flushEvents, 30);
186
+ setInterval(() => workspace?.sync().catch((e) => log("warn", `workspace sync: ${e?.message ?? e}`)), 1000);
187
+ }
188
+ // Snapshots live in OPFS; without it (e.g. WebKit temporary profiles) they are unavailable.
189
+ snapshots = await SnapshotStore.open(m.podId).catch((e) => {
190
+ log("warn", `snapshots unavailable: ${e?.message ?? e}`);
191
+ return null;
192
+ });
193
+ if (m.restore) await restoreSnapshot(m.restore, m.force === true);
194
+ const dataEphemeral = !volumes.ephemeral ? "" : m.dataBackend === "memory" ? "memory" : "locked";
195
+ // dataFresh: nothing was ever written to the data disk (a new pod, not restored), so a boot
196
+ // snapshot's data disk can replace it.
197
+ const dataFresh = volumes.dataFresh && !m.restore;
198
+ post({ type: "volumes", devices, ephemeral: { data: dataEphemeral, workspace: wsEphemeral }, dataFresh });
199
+ if (m.prefetch !== false) prefetch(typeof m.prefetch === "string" ? m.prefetch : `${m.imageUrl}.prefetch.json`);
200
+ }
201
+
202
+ /**
203
+ * Snapshot of the data disk and the workspace (crash-consistent per volume: each pauses its
204
+ * request queue while it is copied). Records the root image so a restore can refuse a snapshot
205
+ * taken on another image (the data disk holds the overlay's upper layer).
206
+ */
207
+ function needSnapshots() {
208
+ if (!snapshots) throw new Error("snapshots need OPFS, which does not work in this browser context");
209
+ }
210
+
211
+ async function takeSnapshot(name, meta = {}) {
212
+ needSnapshots();
213
+ const vols = { data: await volumes.snapshotData() };
214
+ if (workspace) vols.workspace = await workspace.snapshot();
215
+ return snapshots.save(name, Date.now(), { ...meta, image: volumes.rootManifestId }, vols);
216
+ }
217
+
218
+ async function restoreSnapshot(name, force) {
219
+ needSnapshots();
220
+ if (attached > 0) throw new Error("restore needs the pod stopped (before the engine attaches)");
221
+ const info = (await snapshots.list()).find((s) => s.name === name);
222
+ if (!info) throw new Error(`no snapshot ${name}`);
223
+ if (!force && info.meta.image && info.meta.image !== volumes.rootManifestId) {
224
+ throw new Error(`snapshot ${name} was taken on another image`);
225
+ }
226
+ const data = await snapshots.manifest(name, "data");
227
+ if (data) await volumes.restoreData(data);
228
+ const ws = await snapshots.manifest(name, "workspace");
229
+ restoredSession = null;
230
+ if (ws && workspace) {
231
+ // A memory snapshot's 9P session: the resumed guest's fids go on working (else it mounts again).
232
+ const p9 = await snapshots.manifest(name, "p9");
233
+ await workspace.restore(ws, p9 ? await snapshots.readBytes(p9) : undefined);
234
+ if (p9) restoredSession = name;
235
+ }
236
+ return info;
237
+ }
238
+
239
+ /**
240
+ * Memory snapshot (docs/design/snapshot.md, route (c)), with the guest stopped: guest RAM read
241
+ * straight from the engine's memory, the engine's device state, the data disk and the
242
+ * workspace, plus the binding metadata the resume will be checked against.
243
+ */
244
+ async function takeMemorySnapshot(m) {
245
+ needSnapshots();
246
+ const ram = new Uint8Array(m.memory, m.ramOffset, m.ramSize);
247
+ const vols = {
248
+ ram: await snapshots.snapshotRam(ram),
249
+ devstate: await snapshots.snapshotBytes(m.deviceState),
250
+ data: await volumes.snapshotData(),
251
+ };
252
+ if (workspace) {
253
+ // With the 9P session (fids, open files, readdir positions), which the guest RAM refers to.
254
+ const ws = await workspace.snapshotWithSession();
255
+ vols.workspace = ws.workspace;
256
+ vols.p9 = await snapshots.snapshotBytes(ws.p9);
257
+ }
258
+ return snapshots.save(m.name, Date.now(), { ...m.meta, image: volumes.rootManifestId, kind: "memory" }, vols);
259
+ }
260
+
261
+ async function memoryMismatches(name, meta) {
262
+ needSnapshots();
263
+ return snapshots.checkBinding(name, { ...meta, image: volumes.rootManifestId });
264
+ }
265
+
266
+ /** Fills the (fresh) guest RAM from a memory snapshot and returns the device state. */
267
+ async function restoreMemory(m) {
268
+ const mismatches = await memoryMismatches(m.name, m.meta ?? {});
269
+ if (mismatches.length && !m.force) throw new Error(`snapshot ${m.name} does not match this machine: ${mismatches.join("; ")}`);
270
+ const ram = new Uint8Array(m.memory, m.ramOffset, m.ramSize);
271
+ // A prefetch-memory of the same snapshot made this a copy (restoreRam uses what it loaded).
272
+ const bytes = await snapshots.restoreRam(await snapshots.manifest(m.name, "ram"), ram, m.fresh !== false);
273
+ const ahead = prefetchedState?.name === m.name ? prefetchedState.deviceState : null;
274
+ prefetchedState = null;
275
+ const deviceState = ahead ?? (await snapshots.readBytes(await snapshots.manifest(m.name, "devstate")));
276
+ // workspaceSession: the guest's 9P session was restored with the disks (init restore), so its
277
+ // /workspace mount goes on as it was; else the host mounts it again.
278
+ return { name: m.name, bytes, deviceState, workspaceSession: restoredSession === m.name };
279
+ }
280
+
281
+ /** Reads a memory snapshot's RAM and device state ahead of restore-memory (while the engine starts). */
282
+ let prefetchedState = null;
283
+ async function prefetchMemory(name) {
284
+ needSnapshots();
285
+ const ram = await snapshots.manifest(name, "ram");
286
+ if (!ram) throw new Error(`no memory snapshot ${name}`);
287
+ const bytes = await snapshots.prefetchRam(ram);
288
+ prefetchedState = { name, deviceState: await snapshots.readBytes(await snapshots.manifest(name, "devstate")) };
289
+ return { name, bytes };
290
+ }
291
+
292
+ /** Warms the root image from its boot profile (webpod-build prefetch), in the background. */
293
+ async function prefetch(url) {
294
+ let list;
295
+ try {
296
+ const r = await fetch(url);
297
+ if (!r.ok) return;
298
+ list = await r.json();
299
+ } catch {
300
+ return;
301
+ }
302
+ if (list?.manifest !== volumes.rootManifestId || !Array.isArray(list.chunks)) {
303
+ log("warn", `prefetch list ${url} does not match the image; ignored`);
304
+ return;
305
+ }
306
+ // Small batches: guest reads queue behind each one.
307
+ for (let i = 0; i < list.chunks.length && !stopping; i += 8) {
308
+ try {
309
+ await volumes.prefetch(Uint32Array.from(list.chunks.slice(i, i + 8)));
310
+ } catch (e) {
311
+ log("warn", `prefetch: ${e?.message ?? e}`);
312
+ return;
313
+ }
314
+ }
315
+ }
316
+
317
+ function onAttach(m) {
318
+ const id = m.serial ?? m.id;
319
+ if (id === "webpod-ws") {
320
+ if (!workspace) throw new Error("attach webpod-ws: workspace disabled in init");
321
+ pumps.push(pump(id, m.memory, m.fromEngine, m.toEngine, async (batch) => {
322
+ guestMounted = true;
323
+ const replies = await Promise.all(batch.map((msg) => workspace.p9(msg)));
324
+ if (replays.busy) flushEvents(); // a replay may just have finished
325
+ return replies;
326
+ }));
327
+ } else if (id === "webpod-root" || id === "webpod-data") {
328
+ const tx = new RingProducer(m.memory, m.toEngine);
329
+ volumes.setMaxRead(id, tx.maxMessageLen - COMPLETION_HEADER);
330
+ volumes.setEngineMemory(m.memory);
331
+ pumps.push(pump(id, m.memory, m.fromEngine, m.toEngine, async (batch) => volumes.handle(id, batch)));
332
+ } else {
333
+ throw new Error(`attach: unknown device ${id}`);
334
+ }
335
+ attached++;
336
+ post({ type: "ready", ...(m.serial ? { serial: m.serial } : { id }) });
337
+ }
338
+
339
+ async function onStop() {
340
+ stopping = true;
341
+ // The ring waits have no timeout: wake the pumps now, and settle every wait before the host
342
+ // terminates this Worker.
343
+ await settleWaits();
344
+ await Promise.allSettled(pumps);
345
+ // An imported boot snapshot's RAM: stored if the pod resumed from it, else dropped (a cold boot
346
+ // follows; the next import downloads what the store lacks).
347
+ if (ramResumed) await snapshots?.persistRam().catch(() => {});
348
+ else snapshots?.discardUnpersisted();
349
+ flushEvents();
350
+ host?.close();
351
+ await workspace?.close();
352
+ await volumes?.close();
353
+ await settleWaits();
354
+ post({ type: "stopped" });
355
+ }
356
+
357
+ self.onmessage = async ({ data: m }) => {
358
+ try {
359
+ await ready;
360
+ switch (m?.type) {
361
+ case "init":
362
+ return await onInit(m);
363
+ case "attach":
364
+ return onAttach(m);
365
+ case "fs-port":
366
+ if (!workspace) throw new Error("fs-port: workspace disabled in init");
367
+ broadcasts.push(serveWorkspace(current, m.port, { settle, clear: clearOf, pending: (p) => replays.pendingType(p), hidden: isHidden, replayed: (seq) => replays.replayed(seq) }));
368
+ return;
369
+ case "stats":
370
+ return post({ type: "stats", root: await volumes?.rootStats() });
371
+ case "snapshot":
372
+ return post({ type: "snapshot", info: await takeSnapshot(m.name, m.meta) });
373
+ case "restore":
374
+ return post({ type: "restored", info: await restoreSnapshot(m.name, m.force === true) });
375
+ case "snapshot-memory":
376
+ return post({ type: "snapshot-memory", info: await takeMemorySnapshot(m) });
377
+ case "memory-snapshot-check": {
378
+ const mismatches = await memoryMismatches(m.name, m.meta ?? {});
379
+ return post({ type: "memory-snapshot-check", name: m.name, ok: mismatches.length === 0, mismatches });
380
+ }
381
+ case "prefetch-memory":
382
+ return post({ type: "memory-prefetched", ...(await prefetchMemory(m.name)) });
383
+ case "restore-memory": {
384
+ const r = await restoreMemory(m);
385
+ post({ type: "memory-restored", ...r }, [r.deviceState.buffer]);
386
+ // A boot snapshot's RAM is stored once the pod is up (import kept it in memory).
387
+ ramResumed = true;
388
+ setTimeout(() => snapshots?.persistRam().catch((e) => log("warn", `persist RAM: ${e?.message ?? e}`)), 3000);
389
+ return;
390
+ }
391
+ case "fetch-boot-snapshot": {
392
+ needSnapshots();
393
+ const r = await snapshots.importBoot(m.url.endsWith("/") ? m.url : `${m.url}/`, m.name);
394
+ return post({ type: "boot-snapshot", ...r });
395
+ }
396
+ case "snapshots":
397
+ return post({ type: "snapshots", list: snapshots ? await snapshots.list() : [] });
398
+ case "delete-snapshot":
399
+ needSnapshots();
400
+ return post({ type: "snapshot-deleted", name: m.name, deleted: await snapshots.delete(m.name) });
401
+ case "export-snapshot":
402
+ needSnapshots();
403
+ return post({ type: "exported", name: m.name, file: await snapshots.exportFile(m.name) });
404
+ case "import-snapshot":
405
+ needSnapshots();
406
+ return post({ type: "imported", info: await snapshots.importBlob(m.file, m.name ?? undefined) });
407
+ case "trace":
408
+ return post({ type: "trace", ...(await volumes?.rootTrace()) });
409
+ case "flush":
410
+ // The page is going away (pagehide, hidden): the workspace and the data disk to storage.
411
+ await Promise.all([workspace?.sync(), volumes?.flush()]);
412
+ return post({ type: "flushed" });
413
+ case "stop":
414
+ return await onStop();
415
+ default:
416
+ log("warn", `unknown message ${m?.type}`);
417
+ }
418
+ } catch (e) {
419
+ post({ type: "error", message: `${m?.type}: ${e?.message ?? e}` });
420
+ }
421
+ };
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@webpodjs/fs-worker",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "FS Worker for webpod: block volumes (webpod-root/webpod-data) and the shared /workspace (9P + PodFs RPC)",
5
+ "keywords": [
6
+ "webpod",
7
+ "opfs",
8
+ "9p",
9
+ "virtio-blk",
10
+ "worker"
11
+ ],
12
+ "license": "Apache-2.0",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/mirrorange/webpod.git",
16
+ "directory": "packages/fs-worker"
17
+ },
18
+ "homepage": "https://github.com/mirrorange/webpod/tree/main/packages/fs-worker#readme",
19
+ "bugs": "https://github.com/mirrorange/webpod/issues",
20
+ "type": "module",
21
+ "exports": {
22
+ "./worker.js": "./dist/worker.js",
23
+ "./dist/*": "./dist/*",
24
+ "./package.json": "./package.json"
25
+ },
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "scripts": {
33
+ "build:wasm": "sh build.sh",
34
+ "test:browser": "node test/browser.mjs"
35
+ }
36
+ }