@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.
Binary file
@@ -0,0 +1,71 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+ export const memory: WebAssembly.Memory;
4
+ export const __wbg_blockvolumes_free: (a: number, b: number) => void;
5
+ export const __wbg_snapshotstore_free: (a: number, b: number) => void;
6
+ export const __wbg_workspacefs_free: (a: number, b: number) => void;
7
+ export const blockvolumes_close: (a: number) => any;
8
+ export const blockvolumes_dataFresh: (a: number) => number;
9
+ export const blockvolumes_dataSize: (a: number) => number;
10
+ export const blockvolumes_ephemeral: (a: number) => number;
11
+ export const blockvolumes_handle: (a: number, b: number, c: number, d: any) => any;
12
+ export const blockvolumes_open: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number, k: number, l: number, m: number) => any;
13
+ export const blockvolumes_prefetch: (a: number, b: number, c: number) => any;
14
+ export const blockvolumes_restoreData: (a: number, b: number, c: number) => any;
15
+ export const blockvolumes_rootManifestId: (a: number) => [number, number];
16
+ export const blockvolumes_rootSize: (a: number) => number;
17
+ export const blockvolumes_rootStats: (a: number) => any;
18
+ export const blockvolumes_rootTrace: (a: number) => any;
19
+ export const blockvolumes_setEngineMemory: (a: number, b: any) => void;
20
+ export const blockvolumes_setMaxRead: (a: number, b: number, c: number, d: number) => void;
21
+ export const blockvolumes_snapshotData: (a: number) => any;
22
+ export const snapshotstore_checkBinding: (a: number, b: number, c: number, d: any) => any;
23
+ export const snapshotstore_delete: (a: number, b: number, c: number) => any;
24
+ export const snapshotstore_discardUnpersisted: (a: number) => void;
25
+ export const snapshotstore_exportFile: (a: number, b: number, c: number) => any;
26
+ export const snapshotstore_importBlob: (a: number, b: any, c: number, d: number) => any;
27
+ export const snapshotstore_importBoot: (a: number, b: number, c: number, d: number, e: number) => any;
28
+ export const snapshotstore_list: (a: number) => any;
29
+ export const snapshotstore_manifest: (a: number, b: number, c: number, d: number, e: number) => any;
30
+ export const snapshotstore_open: (a: number, b: number) => any;
31
+ export const snapshotstore_persistRam: (a: number) => any;
32
+ export const snapshotstore_prefetchRam: (a: number, b: number, c: number) => any;
33
+ export const snapshotstore_readBytes: (a: number, b: number, c: number) => any;
34
+ export const snapshotstore_restoreRam: (a: number, b: number, c: number, d: any, e: number) => any;
35
+ export const snapshotstore_save: (a: number, b: number, c: number, d: number, e: any, f: any) => any;
36
+ export const snapshotstore_snapshotBytes: (a: number, b: number, c: number) => any;
37
+ export const snapshotstore_snapshotRam: (a: number, b: any) => any;
38
+ export const workspacefs_chmod: (a: number, b: number, c: number, d: number) => any;
39
+ export const workspacefs_close: (a: number) => any;
40
+ export const workspacefs_ephemeral: (a: number) => [number, number];
41
+ export const workspacefs_mkdir: (a: number, b: number, c: number, d: number, e: number) => any;
42
+ export const workspacefs_open: (a: number, b: number, c: number, d: number, e: number, f: number, g: number) => any;
43
+ export const workspacefs_p9: (a: number, b: number, c: number) => any;
44
+ export const workspacefs_p9Reset: (a: number) => any;
45
+ export const workspacefs_readAt: (a: number, b: number, c: number, d: number, e: number) => any;
46
+ export const workspacefs_readFile: (a: number, b: number, c: number) => any;
47
+ export const workspacefs_readdir: (a: number, b: number, c: number) => any;
48
+ export const workspacefs_readlink: (a: number, b: number, c: number) => any;
49
+ export const workspacefs_rename: (a: number, b: number, c: number, d: number, e: number) => any;
50
+ export const workspacefs_restore: (a: number, b: number, c: number, d: number, e: number) => any;
51
+ export const workspacefs_rm: (a: number, b: number, c: number, d: number, e: number) => any;
52
+ export const workspacefs_snapshot: (a: number) => any;
53
+ export const workspacefs_snapshotWithSession: (a: number) => any;
54
+ export const workspacefs_stat: (a: number, b: number, c: number, d: number) => any;
55
+ export const workspacefs_symlink: (a: number, b: number, c: number, d: number, e: number) => any;
56
+ export const workspacefs_sync: (a: number) => any;
57
+ export const workspacefs_takeEvents: (a: number) => any;
58
+ export const workspacefs_write: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number) => any;
59
+ export const wasm_bindgen_5a2380350bab5903___convert__closures_____invoke___js_sys_173b2b1834468215___Function_fn_wasm_bindgen_5a2380350bab5903___JsValue_____wasm_bindgen_5a2380350bab5903___sys__Undefined___js_sys_173b2b1834468215___Function_fn_wasm_bindgen_5a2380350bab5903___JsValue_____wasm_bindgen_5a2380350bab5903___sys__Undefined_______true_: (a: number, b: number, c: any, d: any) => void;
60
+ export const wasm_bindgen_5a2380350bab5903___convert__closures_____invoke___wasm_bindgen_5a2380350bab5903___JsValue__core_6a51abefd5362b2___result__Result_____wasm_bindgen_5a2380350bab5903___JsError___true_: (a: number, b: number, c: any) => [number, number];
61
+ export const wasm_bindgen_5a2380350bab5903___convert__closures_____invoke___wasm_bindgen_5a2380350bab5903___JsValue__wasm_bindgen_5a2380350bab5903___JsValue__true__1_: (a: number, b: number, c: any) => any;
62
+ export const wasm_bindgen_5a2380350bab5903___convert__closures_____invoke_______true_: (a: number, b: number) => void;
63
+ export const __wbindgen_malloc: (a: number, b: number) => number;
64
+ export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
65
+ export const __wbindgen_free: (a: number, b: number, c: number) => void;
66
+ export const __wbindgen_exn_store: (a: number) => void;
67
+ export const __externref_table_alloc: () => number;
68
+ export const __wbindgen_externrefs: WebAssembly.Table;
69
+ export const __wbindgen_destroy_closure: (a: number, b: number) => void;
70
+ export const __externref_table_dealloc: (a: number) => void;
71
+ export const __wbindgen_start: () => void;
package/dist/rpc.js ADDED
@@ -0,0 +1,39 @@
1
+ // PodFs RPC served on a MessagePort (the page side is createWorkspaceFs in @webpodjs/sdk).
2
+ //
3
+ // page -> worker: { id, op, args: [...], settle? }
4
+ // worker -> page: { id, ok: true, value } | { id, ok: false, error: { code, errno, message } }
5
+ // { type: "events", events: [{ origin: "page" | "guest", type, path }] }
6
+ //
7
+ // ops map 1:1 onto WorkspaceFs methods: readFile(path), readAt(path, offset, len),
8
+ // write(path, offset, data, create, truncate, mode), readdir(path), mkdir(path, recursive, mode),
9
+ // rm(path, recursive, force), stat(path, follow), rename(from, to), chmod(path, mode),
10
+ // symlink(target, path), readlink(path).
11
+ //
12
+ // settle: true answers only once the guest has replayed the creates and deletes made so far (the
13
+ // agent's FsNotify replay hides a created file for a moment), or after 2 s.
14
+
15
+ const OPS = new Set(["readFile", "readAt", "write", "readdir", "mkdir", "rm", "stat", "rename", "chmod", "symlink", "readlink"]);
16
+
17
+ /**
18
+ * Serves `ws` (a WorkspaceFs) on `port`; `settle` resolves once the guest has replayed the page
19
+ * changes so far. Returns a function that broadcasts change events.
20
+ */
21
+ export function serveWorkspace(ws, port, settle = async () => {}) {
22
+ port.onmessage = async ({ data }) => {
23
+ const { id, op, args } = data ?? {};
24
+ if (!OPS.has(op) || !Array.isArray(args)) {
25
+ port.postMessage({ id, ok: false, error: { code: "EINVAL", errno: 22, message: `unknown op ${op}` } });
26
+ return;
27
+ }
28
+ try {
29
+ const value = await ws[op](...args);
30
+ if (data.settle) await settle();
31
+ const transfer = value instanceof Uint8Array ? [value.buffer] : [];
32
+ port.postMessage({ id, ok: true, value }, transfer);
33
+ } catch (e) {
34
+ port.postMessage({ id, ok: false, error: { code: e?.code ?? "EIO", errno: e?.errno ?? 5, message: String(e?.message ?? e) } });
35
+ }
36
+ };
37
+ port.start?.();
38
+ return (events) => port.postMessage({ type: "events", events });
39
+ }
package/dist/worker.js ADDED
@@ -0,0 +1,334 @@
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, waitReadable } from "./abi/index.js";
9
+ import { serveWorkspace } from "./rpc.js";
10
+
11
+ const COMPLETION_HEADER = 12;
12
+ const ready = init();
13
+ let volumes = null;
14
+ let workspace = null;
15
+ let snapshots = null;
16
+ /** The snapshot whose 9P session the workspace continues (restored at init), if any. */
17
+ let restoredSession = null;
18
+ /** restore-memory succeeded in this Worker. */
19
+ let ramResumed = false;
20
+ let attached = 0;
21
+ let stopping = false;
22
+ const pumps = [];
23
+ const broadcasts = [];
24
+ const post = (m, transfer = []) => self.postMessage(m, transfer);
25
+ const log = (level, text) => post({ type: "log", level, text });
26
+
27
+ /** Moves batches from the engine's request ring through `handle` into its reply ring. */
28
+ async function pump(name, memory, fromEngine, toEngine, handle) {
29
+ const rx = new RingConsumer(memory, fromEngine);
30
+ const tx = new RingProducer(memory, toEngine);
31
+ try {
32
+ while (!stopping) {
33
+ const batch = rx.drain(256);
34
+ if (batch.length === 0) {
35
+ await waitReadable(rx);
36
+ continue;
37
+ }
38
+ for (const reply of await handle(batch, tx)) if (reply) await tx.pushAsync(reply);
39
+ }
40
+ } catch (e) {
41
+ if (!stopping) post({ type: "error", message: `${name}: ${e?.message ?? e}` });
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Page creates and deletes the guest replays for its inotify watchers (the SDK sends them to the
47
+ * agent: rename away and back, create + unlink), by path, until the guest's own event for the
48
+ * path shows the replay done. A page write that asks to settle is answered after that: the replay
49
+ * of a create hides the file for a moment, so a guest process started right after the write could
50
+ * miss it.
51
+ */
52
+ const REPLAY_TIMEOUT_MS = 2000;
53
+ const replays = new Map(); // path -> { type, at }
54
+ const settlers = []; // { paths, resolve, at }
55
+ /** The guest speaks 9P (it mounted /workspace): page changes will be replayed. */
56
+ let guestMounted = false;
57
+
58
+ function flushEvents() {
59
+ if (!workspace) return;
60
+ const events = workspace.takeEvents();
61
+ const now = performance.now();
62
+ for (const e of events) {
63
+ if (e.type === "modify") continue;
64
+ if (e.origin === "page") {
65
+ if (guestMounted) replays.set(e.path, { type: e.type, at: now });
66
+ } else if (replays.get(e.path)?.type === e.type) {
67
+ replays.delete(e.path);
68
+ }
69
+ }
70
+ if (events.length) for (const b of broadcasts) b(events);
71
+ for (const [path, r] of replays) if (now - r.at > REPLAY_TIMEOUT_MS) replays.delete(path);
72
+ for (let i = settlers.length - 1; i >= 0; i--) {
73
+ const w = settlers[i];
74
+ if (now - w.at > REPLAY_TIMEOUT_MS || ![...w.paths].some((path) => replays.has(path))) {
75
+ settlers.splice(i, 1);
76
+ w.resolve();
77
+ }
78
+ }
79
+ }
80
+
81
+ /** Resolves once the replays of the page changes made so far are done (or have timed out). */
82
+ function settle() {
83
+ flushEvents();
84
+ if (replays.size === 0) return Promise.resolve();
85
+ return new Promise((resolve) => settlers.push({ paths: new Set(replays.keys()), resolve, at: performance.now() }));
86
+ }
87
+
88
+ async function onInit(m) {
89
+ // The packed image (webpod-build writes <image>.wpz) is read instead of the blob when present.
90
+ const packedUrl = m.packedUrl === false ? null : (m.packedUrl ?? `${m.imageUrl}.wpz`);
91
+ volumes = await BlockVolumes.open(m.podId, m.imageUrl, m.manifestUrl ?? "", m.dataSize, m.dataBackend ?? "auto", m.onConflict ?? "fail", packedUrl);
92
+ // indirect: large reads and writes may pass their data by descriptor into the engine memory
93
+ // (docs/design/blk-indirect.md); the host enables it in the engine's device spec.
94
+ const devices = [
95
+ { serial: "webpod-root", sizeBytes: volumes.rootSize, readOnly: true, indirect: true },
96
+ { serial: "webpod-data", sizeBytes: volumes.dataSize, readOnly: false, indirect: true },
97
+ ];
98
+ let wsEphemeral = "";
99
+ if (m.workspace !== false) {
100
+ const w = m.workspace ?? {};
101
+ const msize = w.msize ?? 512 * 1024;
102
+ workspace = await WorkspaceFs.open(m.podId, w.mountPoint ?? "/workspace", w.uid ?? 0, w.gid ?? 0, msize);
103
+ wsEphemeral = workspace.ephemeral;
104
+ devices.push({ class: "9p", id: "webpod-ws", msize });
105
+ setInterval(flushEvents, 30);
106
+ // Settlers waiting past the last event still time out.
107
+ setInterval(() => settlers.length && flushEvents(), 250);
108
+ setInterval(() => workspace?.sync().catch((e) => log("warn", `workspace sync: ${e?.message ?? e}`)), 1000);
109
+ }
110
+ // Snapshots live in OPFS; without it (e.g. WebKit temporary profiles) they are unavailable.
111
+ snapshots = await SnapshotStore.open(m.podId).catch((e) => {
112
+ log("warn", `snapshots unavailable: ${e?.message ?? e}`);
113
+ return null;
114
+ });
115
+ if (m.restore) await restoreSnapshot(m.restore, m.force === true);
116
+ const dataEphemeral = !volumes.ephemeral ? "" : m.dataBackend === "memory" ? "memory" : "locked";
117
+ // dataFresh: nothing was ever written to the data disk (a new pod, not restored), so a boot
118
+ // snapshot's data disk can replace it.
119
+ const dataFresh = volumes.dataFresh && !m.restore;
120
+ post({ type: "volumes", devices, ephemeral: { data: dataEphemeral, workspace: wsEphemeral }, dataFresh });
121
+ if (m.prefetch !== false) prefetch(typeof m.prefetch === "string" ? m.prefetch : `${m.imageUrl}.prefetch.json`);
122
+ }
123
+
124
+ /**
125
+ * Snapshot of the data disk and the workspace (crash-consistent per volume: each pauses its
126
+ * request queue while it is copied). Records the root image so a restore can refuse a snapshot
127
+ * taken on another image (the data disk holds the overlay's upper layer).
128
+ */
129
+ function needSnapshots() {
130
+ if (!snapshots) throw new Error("snapshots need OPFS, which does not work in this browser context");
131
+ }
132
+
133
+ async function takeSnapshot(name, meta = {}) {
134
+ needSnapshots();
135
+ const vols = { data: await volumes.snapshotData() };
136
+ if (workspace) vols.workspace = await workspace.snapshot();
137
+ return snapshots.save(name, Date.now(), { ...meta, image: volumes.rootManifestId }, vols);
138
+ }
139
+
140
+ async function restoreSnapshot(name, force) {
141
+ needSnapshots();
142
+ if (attached > 0) throw new Error("restore needs the pod stopped (before the engine attaches)");
143
+ const info = (await snapshots.list()).find((s) => s.name === name);
144
+ if (!info) throw new Error(`no snapshot ${name}`);
145
+ if (!force && info.meta.image && info.meta.image !== volumes.rootManifestId) {
146
+ throw new Error(`snapshot ${name} was taken on another image`);
147
+ }
148
+ const data = await snapshots.manifest(name, "data");
149
+ if (data) await volumes.restoreData(data);
150
+ const ws = await snapshots.manifest(name, "workspace");
151
+ restoredSession = null;
152
+ if (ws && workspace) {
153
+ // A memory snapshot's 9P session: the resumed guest's fids go on working (else it mounts again).
154
+ const p9 = await snapshots.manifest(name, "p9");
155
+ await workspace.restore(ws, p9 ? await snapshots.readBytes(p9) : undefined);
156
+ if (p9) restoredSession = name;
157
+ }
158
+ return info;
159
+ }
160
+
161
+ /**
162
+ * Memory snapshot (docs/design/snapshot.md, route (c)), with the guest stopped: guest RAM read
163
+ * straight from the engine's memory, the engine's device state, the data disk and the
164
+ * workspace, plus the binding metadata the resume will be checked against.
165
+ */
166
+ async function takeMemorySnapshot(m) {
167
+ needSnapshots();
168
+ const ram = new Uint8Array(m.memory, m.ramOffset, m.ramSize);
169
+ const vols = {
170
+ ram: await snapshots.snapshotRam(ram),
171
+ devstate: await snapshots.snapshotBytes(m.deviceState),
172
+ data: await volumes.snapshotData(),
173
+ };
174
+ if (workspace) {
175
+ // With the 9P session (fids, open files, readdir positions), which the guest RAM refers to.
176
+ const ws = await workspace.snapshotWithSession();
177
+ vols.workspace = ws.workspace;
178
+ vols.p9 = await snapshots.snapshotBytes(ws.p9);
179
+ }
180
+ return snapshots.save(m.name, Date.now(), { ...m.meta, image: volumes.rootManifestId, kind: "memory" }, vols);
181
+ }
182
+
183
+ async function memoryMismatches(name, meta) {
184
+ needSnapshots();
185
+ return snapshots.checkBinding(name, { ...meta, image: volumes.rootManifestId });
186
+ }
187
+
188
+ /** Fills the (fresh) guest RAM from a memory snapshot and returns the device state. */
189
+ async function restoreMemory(m) {
190
+ const mismatches = await memoryMismatches(m.name, m.meta ?? {});
191
+ if (mismatches.length && !m.force) throw new Error(`snapshot ${m.name} does not match this machine: ${mismatches.join("; ")}`);
192
+ const ram = new Uint8Array(m.memory, m.ramOffset, m.ramSize);
193
+ // A prefetch-memory of the same snapshot made this a copy (restoreRam uses what it loaded).
194
+ const bytes = await snapshots.restoreRam(await snapshots.manifest(m.name, "ram"), ram, m.fresh !== false);
195
+ const ahead = prefetchedState?.name === m.name ? prefetchedState.deviceState : null;
196
+ prefetchedState = null;
197
+ const deviceState = ahead ?? (await snapshots.readBytes(await snapshots.manifest(m.name, "devstate")));
198
+ // workspaceSession: the guest's 9P session was restored with the disks (init restore), so its
199
+ // /workspace mount goes on as it was; else the host mounts it again.
200
+ return { name: m.name, bytes, deviceState, workspaceSession: restoredSession === m.name };
201
+ }
202
+
203
+ /** Reads a memory snapshot's RAM and device state ahead of restore-memory (while the engine starts). */
204
+ let prefetchedState = null;
205
+ async function prefetchMemory(name) {
206
+ needSnapshots();
207
+ const ram = await snapshots.manifest(name, "ram");
208
+ if (!ram) throw new Error(`no memory snapshot ${name}`);
209
+ const bytes = await snapshots.prefetchRam(ram);
210
+ prefetchedState = { name, deviceState: await snapshots.readBytes(await snapshots.manifest(name, "devstate")) };
211
+ return { name, bytes };
212
+ }
213
+
214
+ /** Warms the root image from its boot profile (webpod-build prefetch), in the background. */
215
+ async function prefetch(url) {
216
+ let list;
217
+ try {
218
+ const r = await fetch(url);
219
+ if (!r.ok) return;
220
+ list = await r.json();
221
+ } catch {
222
+ return;
223
+ }
224
+ if (list?.manifest !== volumes.rootManifestId || !Array.isArray(list.chunks)) {
225
+ log("warn", `prefetch list ${url} does not match the image; ignored`);
226
+ return;
227
+ }
228
+ // Small batches: guest reads queue behind each one.
229
+ for (let i = 0; i < list.chunks.length && !stopping; i += 8) {
230
+ try {
231
+ await volumes.prefetch(Uint32Array.from(list.chunks.slice(i, i + 8)));
232
+ } catch (e) {
233
+ log("warn", `prefetch: ${e?.message ?? e}`);
234
+ return;
235
+ }
236
+ }
237
+ }
238
+
239
+ function onAttach(m) {
240
+ const id = m.serial ?? m.id;
241
+ if (id === "webpod-ws") {
242
+ if (!workspace) throw new Error("attach webpod-ws: workspace disabled in init");
243
+ pumps.push(pump(id, m.memory, m.fromEngine, m.toEngine, async (batch) => {
244
+ guestMounted = true;
245
+ const replies = await Promise.all(batch.map((msg) => workspace.p9(msg)));
246
+ if (settlers.length) flushEvents(); // a replay may just have finished
247
+ return replies;
248
+ }));
249
+ } else if (id === "webpod-root" || id === "webpod-data") {
250
+ const tx = new RingProducer(m.memory, m.toEngine);
251
+ volumes.setMaxRead(id, tx.maxMessageLen - COMPLETION_HEADER);
252
+ volumes.setEngineMemory(m.memory);
253
+ pumps.push(pump(id, m.memory, m.fromEngine, m.toEngine, async (batch) => volumes.handle(id, batch)));
254
+ } else {
255
+ throw new Error(`attach: unknown device ${id}`);
256
+ }
257
+ attached++;
258
+ post({ type: "ready", ...(m.serial ? { serial: m.serial } : { id }) });
259
+ }
260
+
261
+ async function onStop() {
262
+ stopping = true;
263
+ await Promise.allSettled(pumps);
264
+ // An imported boot snapshot's RAM: stored if the pod resumed from it, else dropped (a cold boot
265
+ // follows; the next import downloads what the store lacks).
266
+ if (ramResumed) await snapshots?.persistRam().catch(() => {});
267
+ else snapshots?.discardUnpersisted();
268
+ flushEvents();
269
+ await workspace?.close();
270
+ await volumes?.close();
271
+ post({ type: "stopped" });
272
+ }
273
+
274
+ self.onmessage = async ({ data: m }) => {
275
+ try {
276
+ await ready;
277
+ switch (m?.type) {
278
+ case "init":
279
+ return await onInit(m);
280
+ case "attach":
281
+ return onAttach(m);
282
+ case "fs-port":
283
+ if (!workspace) throw new Error("fs-port: workspace disabled in init");
284
+ broadcasts.push(serveWorkspace(workspace, m.port, settle));
285
+ return;
286
+ case "stats":
287
+ return post({ type: "stats", root: await volumes?.rootStats() });
288
+ case "snapshot":
289
+ return post({ type: "snapshot", info: await takeSnapshot(m.name, m.meta) });
290
+ case "restore":
291
+ return post({ type: "restored", info: await restoreSnapshot(m.name, m.force === true) });
292
+ case "snapshot-memory":
293
+ return post({ type: "snapshot-memory", info: await takeMemorySnapshot(m) });
294
+ case "memory-snapshot-check": {
295
+ const mismatches = await memoryMismatches(m.name, m.meta ?? {});
296
+ return post({ type: "memory-snapshot-check", name: m.name, ok: mismatches.length === 0, mismatches });
297
+ }
298
+ case "prefetch-memory":
299
+ return post({ type: "memory-prefetched", ...(await prefetchMemory(m.name)) });
300
+ case "restore-memory": {
301
+ const r = await restoreMemory(m);
302
+ post({ type: "memory-restored", ...r }, [r.deviceState.buffer]);
303
+ // A boot snapshot's RAM is stored once the pod is up (import kept it in memory).
304
+ ramResumed = true;
305
+ setTimeout(() => snapshots?.persistRam().catch((e) => log("warn", `persist RAM: ${e?.message ?? e}`)), 3000);
306
+ return;
307
+ }
308
+ case "fetch-boot-snapshot": {
309
+ needSnapshots();
310
+ const r = await snapshots.importBoot(m.url.endsWith("/") ? m.url : `${m.url}/`, m.name);
311
+ return post({ type: "boot-snapshot", ...r });
312
+ }
313
+ case "snapshots":
314
+ return post({ type: "snapshots", list: snapshots ? await snapshots.list() : [] });
315
+ case "delete-snapshot":
316
+ needSnapshots();
317
+ return post({ type: "snapshot-deleted", name: m.name, deleted: await snapshots.delete(m.name) });
318
+ case "export-snapshot":
319
+ needSnapshots();
320
+ return post({ type: "exported", name: m.name, file: await snapshots.exportFile(m.name) });
321
+ case "import-snapshot":
322
+ needSnapshots();
323
+ return post({ type: "imported", info: await snapshots.importBlob(m.file, m.name ?? undefined) });
324
+ case "trace":
325
+ return post({ type: "trace", ...(await volumes?.rootTrace()) });
326
+ case "stop":
327
+ return await onStop();
328
+ default:
329
+ log("warn", `unknown message ${m?.type}`);
330
+ }
331
+ } catch (e) {
332
+ post({ type: "error", message: `${m?.type}: ${e?.message ?? e}` });
333
+ }
334
+ };
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.0",
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
+ }