@webpodjs/fs-worker 0.1.0 → 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 CHANGED
@@ -24,14 +24,19 @@ Serve `dist/` and pass `dist/worker.js` to `fsWorker(url, spec)`.
24
24
  ```ts
25
25
  // host -> worker
26
26
  { type: "init", podId, imageUrl, manifestUrl?, dataSize, dataBackend?: "auto"|"opfs"|"idb"|"memory",
27
- onConflict?: "fail"|"ephemeral", workspace?: false | { mountPoint?: "/workspace", uid?, gid?, msize? },
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")
28
31
  prefetch?: false | url, // default <imageUrl>.prefetch.json, fetched in the background if present
29
32
  packedUrl?: false | url, // default <imageUrl>.wpz: the packed image, read instead of the blob if present
30
33
  restore?: name, force? } // restore a snapshot before serving (refused if taken on another image)
31
34
  { 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: "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
35
40
  { type: "stats" } // -> { type: "stats", root: { fetchedBytes, transferredBytes,
36
41
  // packed, packFallback?, fetchRequests, cacheHits, memoryHits } }
37
42
  { type: "trace" } // -> { type: "trace", manifest, chunks }: boot profile
@@ -63,10 +68,12 @@ Serve `dist/` and pass `dist/worker.js` to `fsWorker(url, spec)`.
63
68
  // 3 s after restore-memory, or on stop)
64
69
  // info = { name, created (ms), volumes: { data, workspace?, p9?, ram?, devstate? } (manifest ids),
65
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)
66
73
  { type: "stop" }
67
74
  // worker -> host
68
- { type: "volumes", devices: [{ serial, sizeBytes, readOnly, indirect }, ..., { class: "9p", id, msize }],
69
- ephemeral: { data: ""|"locked"|"memory", workspace: ""|"locked"|"no-opfs" }, dataFresh }
75
+ { type: "volumes", devices: [{ serial, sizeBytes, readOnly, indirect }, ..., { class: "9p", id, msize, localPaths }],
76
+ ephemeral: { data: ""|"locked"|"memory", workspace: ""|"locked"|"no-opfs"|"shared" }, dataFresh }
70
77
  { type: "ready", serial } | { type: "ready", id } | { type: "stopped" } | { type: "log", level, text } | { type: "error", message }
71
78
  ```
72
79
 
@@ -76,7 +83,8 @@ new pod (a boot snapshot's disk can replace it). `indirect: true`: the worker al
76
83
  indirect block requests, whose data it reads from and
77
84
  writes to the engine memory given in `attach` (`docs/design/blk-indirect.md`).
78
85
  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`).
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).
80
88
 
81
89
  ## Test
82
90
 
package/dist/abi/ring.js CHANGED
@@ -267,25 +267,97 @@ export class RingConsumer {
267
267
  return [this.#r.words, HEAD, this.#tail | 0];
268
268
  }
269
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. */
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
+ */
272
302
  async function waitWord(words, index, value, options) {
273
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
+ }
274
311
  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);
312
+ let waiter;
281
313
  if (typeof waitAsync === "function") {
282
- const res = waitAsync(words, index, value, ms);
283
- if (!res.async)
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)
284
338
  return;
285
- await Promise.race([res.value, ...timers]);
286
- return;
287
339
  }
288
- await Promise.race(timers);
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
+ }
289
361
  }
290
362
  /** Waits until the consumer has a message (or the watchdog fires; callers just re-check). */
291
363
  export async function waitReadable(c, options = {}) {
@@ -13,6 +13,11 @@ export class BlockVolumes {
13
13
  * Flushes the data disk, closes both and releases the pod lock.
14
14
  */
15
15
  close(): Promise<any>;
16
+ /**
17
+ * Flushes the data disk's writes to storage (the page is going away: `pagehide`), as a
18
+ * guest flush request does.
19
+ */
20
+ flush(): Promise<any>;
16
21
  /**
17
22
  * Handles a batch of block request messages for disk `serial`; resolves to the encoded
18
23
  * completion messages, in request order.
@@ -176,6 +181,11 @@ export class WorkspaceFs {
176
181
  * Syncs, closes OPFS handles and releases the workspace lock.
177
182
  */
178
183
  close(): Promise<any>;
184
+ /**
185
+ * The view serving another tab `client` (its page and its guest's 9P session); its changes
186
+ * are recorded as `"page:<client>"` and `"guest:<client>"`.
187
+ */
188
+ forClient(client: string): WorkspaceFs;
179
189
  mkdir(path: string, recursive: boolean, mode: number): Promise<any>;
180
190
  /**
181
191
  * Opens the workspace of `podId` (OPFS, else in memory; see `ephemeral`). Files the page
@@ -183,9 +193,21 @@ export class WorkspaceFs {
183
193
  */
184
194
  static open(pod_id: string, mount_point: string, uid: number, gid: number, msize: number): Promise<WorkspaceFs>;
185
195
  /**
186
- * Ends the 9P session (guest reboot or disconnect): drops all fids.
196
+ * Goes on with `session` (another tab's, from `p9Session` of the workspace's previous
197
+ * holder) as this view's 9P session: the fids of what this workspace has go on working,
198
+ * open ones pinned again. Resolves to the number of fids dropped.
199
+ */
200
+ p9Adopt(session: Uint8Array | number[]): Promise<any>;
201
+ /**
202
+ * Ends the 9P session (guest reboot or disconnect): drops all fids. For another tab's view,
203
+ * also forgets the session (the tab is gone).
187
204
  */
188
205
  p9Reset(): Promise<any>;
206
+ /**
207
+ * The 9P session of this view (`P9Server::save_session`), for the tab it serves to go on
208
+ * with if it takes the workspace over; `undefined` before its guest speaks 9P.
209
+ */
210
+ p9Session(): Promise<any>;
189
211
  /**
190
212
  * Answers one 9P request message; resolves to the reply, or `undefined` for a message
191
213
  * too short to answer.
@@ -228,9 +250,19 @@ export class WorkspaceFs {
228
250
  */
229
251
  sync(): Promise<any>;
230
252
  /**
231
- * Changes since the last call: `[{origin, type, path}]`, origin `"page"` or `"guest"`.
253
+ * Changes since the last call (through every view): `[{origin, type, path, dir?}]`, origin
254
+ * `"page"` or `"guest"` (this tab), `"page:<id>"` or `"guest:<id>"` (another, `forClient`);
255
+ * `dir: true` when the entry is a directory.
232
256
  */
233
257
  takeEvents(): Array<any>;
258
+ /**
259
+ * For a tab that another serves the workspace to: waits until that one releases the
260
+ * workspace lock (closes or ends), then opens it from OPFS and goes on with the 9P session
261
+ * `session()` returns then (a `Uint8Array`, the last one of this tab's guest the other sent,
262
+ * `p9Session`; or nothing), dropping the fids of what the other had not synced. Resolves to
263
+ * the opened workspace.
264
+ */
265
+ static takeOver(pod_id: string, mount_point: string, uid: number, gid: number, msize: number, session: Function): Promise<WorkspaceFs>;
234
266
  /**
235
267
  * Writes `data` at `offset`; `create` makes a missing file with `mode`, `truncate` empties
236
268
  * it first. A whole-file write is `write(path, 0, data, true, true, mode)`.
@@ -253,6 +285,7 @@ export interface InitOutput {
253
285
  readonly blockvolumes_dataFresh: (a: number) => number;
254
286
  readonly blockvolumes_dataSize: (a: number) => number;
255
287
  readonly blockvolumes_ephemeral: (a: number) => number;
288
+ readonly blockvolumes_flush: (a: number) => any;
256
289
  readonly blockvolumes_handle: (a: number, b: number, c: number, d: any) => any;
257
290
  readonly 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;
258
291
  readonly blockvolumes_prefetch: (a: number, b: number, c: number) => any;
@@ -283,10 +316,13 @@ export interface InitOutput {
283
316
  readonly workspacefs_chmod: (a: number, b: number, c: number, d: number) => any;
284
317
  readonly workspacefs_close: (a: number) => any;
285
318
  readonly workspacefs_ephemeral: (a: number) => [number, number];
319
+ readonly workspacefs_forClient: (a: number, b: number, c: number) => number;
286
320
  readonly workspacefs_mkdir: (a: number, b: number, c: number, d: number, e: number) => any;
287
321
  readonly workspacefs_open: (a: number, b: number, c: number, d: number, e: number, f: number, g: number) => any;
288
322
  readonly workspacefs_p9: (a: number, b: number, c: number) => any;
323
+ readonly workspacefs_p9Adopt: (a: number, b: number, c: number) => any;
289
324
  readonly workspacefs_p9Reset: (a: number) => any;
325
+ readonly workspacefs_p9Session: (a: number) => any;
290
326
  readonly workspacefs_readAt: (a: number, b: number, c: number, d: number, e: number) => any;
291
327
  readonly workspacefs_readFile: (a: number, b: number, c: number) => any;
292
328
  readonly workspacefs_readdir: (a: number, b: number, c: number) => any;
@@ -300,6 +336,7 @@ export interface InitOutput {
300
336
  readonly workspacefs_symlink: (a: number, b: number, c: number, d: number, e: number) => any;
301
337
  readonly workspacefs_sync: (a: number) => any;
302
338
  readonly workspacefs_takeEvents: (a: number) => any;
339
+ readonly workspacefs_takeOver: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: any) => any;
303
340
  readonly workspacefs_write: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number) => any;
304
341
  readonly 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;
305
342
  readonly 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];
@@ -53,6 +53,15 @@ export class BlockVolumes {
53
53
  const ret = wasm.blockvolumes_ephemeral(this.__wbg_ptr);
54
54
  return ret !== 0;
55
55
  }
56
+ /**
57
+ * Flushes the data disk's writes to storage (the page is going away: `pagehide`), as a
58
+ * guest flush request does.
59
+ * @returns {Promise<any>}
60
+ */
61
+ flush() {
62
+ const ret = wasm.blockvolumes_flush(this.__wbg_ptr);
63
+ return ret;
64
+ }
56
65
  /**
57
66
  * Handles a batch of block request messages for disk `serial`; resolves to the encoded
58
67
  * completion messages, in request order.
@@ -494,6 +503,18 @@ export class WorkspaceFs {
494
503
  wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
495
504
  }
496
505
  }
506
+ /**
507
+ * The view serving another tab `client` (its page and its guest's 9P session); its changes
508
+ * are recorded as `"page:<client>"` and `"guest:<client>"`.
509
+ * @param {string} client
510
+ * @returns {WorkspaceFs}
511
+ */
512
+ forClient(client) {
513
+ const ptr0 = passStringToWasm0(client, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
514
+ const len0 = WASM_VECTOR_LEN;
515
+ const ret = wasm.workspacefs_forClient(this.__wbg_ptr, ptr0, len0);
516
+ return WorkspaceFs.__wrap(ret);
517
+ }
497
518
  /**
498
519
  * @param {string} path
499
520
  * @param {boolean} recursive
@@ -537,13 +558,36 @@ export class WorkspaceFs {
537
558
  return ret;
538
559
  }
539
560
  /**
540
- * Ends the 9P session (guest reboot or disconnect): drops all fids.
561
+ * Goes on with `session` (another tab's, from `p9Session` of the workspace's previous
562
+ * holder) as this view's 9P session: the fids of what this workspace has go on working,
563
+ * open ones pinned again. Resolves to the number of fids dropped.
564
+ * @param {Uint8Array | number[]} session
565
+ * @returns {Promise<any>}
566
+ */
567
+ p9Adopt(session) {
568
+ const ptr0 = passArray8ToWasm0(session, wasm.__wbindgen_malloc);
569
+ const len0 = WASM_VECTOR_LEN;
570
+ const ret = wasm.workspacefs_p9Adopt(this.__wbg_ptr, ptr0, len0);
571
+ return ret;
572
+ }
573
+ /**
574
+ * Ends the 9P session (guest reboot or disconnect): drops all fids. For another tab's view,
575
+ * also forgets the session (the tab is gone).
541
576
  * @returns {Promise<any>}
542
577
  */
543
578
  p9Reset() {
544
579
  const ret = wasm.workspacefs_p9Reset(this.__wbg_ptr);
545
580
  return ret;
546
581
  }
582
+ /**
583
+ * The 9P session of this view (`P9Server::save_session`), for the tab it serves to go on
584
+ * with if it takes the workspace over; `undefined` before its guest speaks 9P.
585
+ * @returns {Promise<any>}
586
+ */
587
+ p9Session() {
588
+ const ret = wasm.workspacefs_p9Session(this.__wbg_ptr);
589
+ return ret;
590
+ }
547
591
  /**
548
592
  * Answers one 9P request message; resolves to the reply, or `undefined` for a message
549
593
  * too short to answer.
@@ -720,13 +764,47 @@ export class WorkspaceFs {
720
764
  return ret;
721
765
  }
722
766
  /**
723
- * Changes since the last call: `[{origin, type, path}]`, origin `"page"` or `"guest"`.
767
+ * Changes since the last call (through every view): `[{origin, type, path, dir?}]`, origin
768
+ * `"page"` or `"guest"` (this tab), `"page:<id>"` or `"guest:<id>"` (another, `forClient`);
769
+ * `dir: true` when the entry is a directory.
724
770
  * @returns {Array<any>}
725
771
  */
726
772
  takeEvents() {
727
773
  const ret = wasm.workspacefs_takeEvents(this.__wbg_ptr);
728
774
  return ret;
729
775
  }
776
+ /**
777
+ * For a tab that another serves the workspace to: waits until that one releases the
778
+ * workspace lock (closes or ends), then opens it from OPFS and goes on with the 9P session
779
+ * `session()` returns then (a `Uint8Array`, the last one of this tab's guest the other sent,
780
+ * `p9Session`; or nothing), dropping the fids of what the other had not synced. Resolves to
781
+ * the opened workspace.
782
+ * @param {string} pod_id
783
+ * @param {string} mount_point
784
+ * @param {number} uid
785
+ * @param {number} gid
786
+ * @param {number} msize
787
+ * @param {Function} session
788
+ * @returns {Promise<WorkspaceFs>}
789
+ */
790
+ static takeOver(pod_id, mount_point, uid, gid, msize, session) {
791
+ const val3 = +uid;
792
+ const val4 = +gid;
793
+ const val5 = +msize;
794
+ let ptr0, len0, ptr1, len1;
795
+ try {
796
+ ptr0 = passStringToWasm0(pod_id, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
797
+ len0 = WASM_VECTOR_LEN;
798
+ ptr1 = passStringToWasm0(mount_point, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
799
+ len1 = WASM_VECTOR_LEN;
800
+ } catch (e) {
801
+ if (ptr1) { wasm.__wbindgen_free(ptr1, len1 * 1, 1); }
802
+ if (ptr0) { wasm.__wbindgen_free(ptr0, len0 * 1, 1); }
803
+ throw e;
804
+ }
805
+ const ret = wasm.workspacefs_takeOver(ptr0, len0, ptr1, len1, val3, val4, val5, session);
806
+ return ret;
807
+ }
730
808
  /**
731
809
  * Writes `data` at `offset`; `create` makes a missing file with `mode`, `truncate` empties
732
810
  * it first. A whole-file write is `write(path, 0, data, true, true, mode)`.
@@ -974,6 +1052,16 @@ function __wbg_get_imports() {
974
1052
  const ret = result;
975
1053
  return ret;
976
1054
  },
1055
+ __wbg_instanceof_Uint8Array_d7aeb0dcb3108fea: function(arg0) {
1056
+ let result;
1057
+ try {
1058
+ result = arg0 instanceof Uint8Array;
1059
+ } catch (_) {
1060
+ result = false;
1061
+ }
1062
+ const ret = result;
1063
+ return ret;
1064
+ },
977
1065
  __wbg_keys_105f5c0857898f84: function(arg0) {
978
1066
  const ret = Object.keys(arg0);
979
1067
  return ret;
@@ -1228,7 +1316,7 @@ function __wbg_get_imports() {
1228
1316
  return ret;
1229
1317
  }, arguments); },
1230
1318
  __wbindgen_generic_0000000000000001: function(arg0, arg1) {
1231
- // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 148, ret: Externref, inner_ret: Some(Externref) }, mutable: true }) -> Externref`.
1319
+ // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 149, ret: Externref, inner_ret: Some(Externref) }, mutable: true }) -> Externref`.
1232
1320
  const ret = makeMutClosure(arg0, arg1, wasm_bindgen_5a2380350bab5903___convert__closures_____invoke___wasm_bindgen_5a2380350bab5903___JsValue__wasm_bindgen_5a2380350bab5903___JsValue__true__1_);
1233
1321
  return ret;
1234
1322
  },
@@ -1238,7 +1326,7 @@ function __wbg_get_imports() {
1238
1326
  return ret;
1239
1327
  },
1240
1328
  __wbindgen_generic_0000000000000003: function(arg0, arg1) {
1241
- // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 150, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
1329
+ // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 151, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
1242
1330
  const ret = makeMutClosure(arg0, arg1, wasm_bindgen_5a2380350bab5903___convert__closures_____invoke_______true_);
1243
1331
  return ret;
1244
1332
  },
Binary file
@@ -8,6 +8,7 @@ export const blockvolumes_close: (a: number) => any;
8
8
  export const blockvolumes_dataFresh: (a: number) => number;
9
9
  export const blockvolumes_dataSize: (a: number) => number;
10
10
  export const blockvolumes_ephemeral: (a: number) => number;
11
+ export const blockvolumes_flush: (a: number) => any;
11
12
  export const blockvolumes_handle: (a: number, b: number, c: number, d: any) => any;
12
13
  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
14
  export const blockvolumes_prefetch: (a: number, b: number, c: number) => any;
@@ -38,10 +39,13 @@ export const snapshotstore_snapshotRam: (a: number, b: any) => any;
38
39
  export const workspacefs_chmod: (a: number, b: number, c: number, d: number) => any;
39
40
  export const workspacefs_close: (a: number) => any;
40
41
  export const workspacefs_ephemeral: (a: number) => [number, number];
42
+ export const workspacefs_forClient: (a: number, b: number, c: number) => number;
41
43
  export const workspacefs_mkdir: (a: number, b: number, c: number, d: number, e: number) => any;
42
44
  export const workspacefs_open: (a: number, b: number, c: number, d: number, e: number, f: number, g: number) => any;
43
45
  export const workspacefs_p9: (a: number, b: number, c: number) => any;
46
+ export const workspacefs_p9Adopt: (a: number, b: number, c: number) => any;
44
47
  export const workspacefs_p9Reset: (a: number) => any;
48
+ export const workspacefs_p9Session: (a: number) => any;
45
49
  export const workspacefs_readAt: (a: number, b: number, c: number, d: number, e: number) => any;
46
50
  export const workspacefs_readFile: (a: number, b: number, c: number) => any;
47
51
  export const workspacefs_readdir: (a: number, b: number, c: number) => any;
@@ -55,6 +59,7 @@ export const workspacefs_stat: (a: number, b: number, c: number, d: number) => a
55
59
  export const workspacefs_symlink: (a: number, b: number, c: number, d: number, e: number) => any;
56
60
  export const workspacefs_sync: (a: number) => any;
57
61
  export const workspacefs_takeEvents: (a: number) => any;
62
+ export const workspacefs_takeOver: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: any) => any;
58
63
  export const workspacefs_write: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number) => any;
59
64
  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
65
  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];
@@ -0,0 +1,147 @@
1
+ // Page changes the guest replays for its inotify watchers (the agent's FsNotify,
2
+ // docs/design/workspace-fs.md §3), tracked by path from the workspace's events.
3
+ //
4
+ // A page create or delete is pending until the guest's own events for the path come through the 9P
5
+ // server: a created file renamed away and linked back, then its temporary name removed (create, and
6
+ // delete of <path>.~wp), a created directory made again or touched (create or modify), a deleted
7
+ // path created and unlinked again (delete). The agent replays in order, so the guest completing one
8
+ // replay means every earlier one is done too (or was skipped: its path had changed since). While
9
+ // pending, a file is away for a moment: page operations on the path, under it or above it wait
10
+ // (`clear`; reads only on the path itself, and a directory listing shows the page's view instead:
11
+ // `pendingType`), and settle (before a guest process starts) waits for the replays (`settle`).
12
+ // The guest's own replay events are not reported to watchers.
13
+
14
+ /** Pending replays are given up after this long without progress (no agent replaying them). */
15
+ export const REPLAY_TIMEOUT_MS = 2000;
16
+
17
+ /** The agent's temporary names (`<path>.~wp`): never reported. */
18
+ const TMP = ".~wp";
19
+
20
+ /** `a` and `b` are the same path, or one is under the other. */
21
+ export function related(a, b) {
22
+ if (a === b) return true;
23
+ const [short, long] = a.length < b.length ? [a, b] : [b, a];
24
+ return long.startsWith(short.endsWith("/") ? short : `${short}/`);
25
+ }
26
+
27
+ export class Replays {
28
+ /** path -> { type, seq, at, need: alternatives, each the guest events that together complete it, seen } */
29
+ #pending = new Map();
30
+ /** { paths, read, resolve } (clear) or { upTo, resolve } (settle) */
31
+ #waiters = [];
32
+ #seq = 0;
33
+ #progress = -Infinity;
34
+
35
+ constructor(now = () => performance.now()) {
36
+ this.now = now;
37
+ }
38
+
39
+ get size() {
40
+ return this.#pending.size;
41
+ }
42
+
43
+ /** The last page change taken (the `seq` of the events broadcast so far). */
44
+ get seq() {
45
+ return this.#seq;
46
+ }
47
+
48
+ /**
49
+ * The guest has replayed the page changes up to `seq` (the agent answered their FsReplay; it
50
+ * skips them while nothing watches): no guest event needed.
51
+ */
52
+ replayed(seq) {
53
+ const now = this.now();
54
+ for (const [path, p] of this.#pending) if (p.seq <= seq) this.#pending.delete(path);
55
+ this.#progress = now;
56
+ this.#update(now);
57
+ }
58
+
59
+ /**
60
+ * Takes workspace events (`takeEvents()`): page creates and deletes become pending when
61
+ * `replayed` (the guest has the share mounted), the guest's events complete them. Returns the
62
+ * events to report to watchers, without the guest's replay events.
63
+ */
64
+ record(events, replayed) {
65
+ const now = this.now();
66
+ const out = [];
67
+ for (const e of events) {
68
+ if (e.origin === "page") {
69
+ if (replayed && e.type !== "modify") {
70
+ const need = e.type === "delete" ? [["delete"]] : e.dir ? [["create"], ["modify"]] : [["create", "tmp-delete"]];
71
+ this.#pending.set(e.path, { type: e.type, seq: ++this.#seq, at: now, need, seen: new Set() });
72
+ }
73
+ out.push(e);
74
+ continue;
75
+ }
76
+ const tmp = e.path.endsWith(TMP);
77
+ const path = tmp ? e.path.slice(0, -TMP.length) : e.path;
78
+ const r = this.#pending.get(path);
79
+ if (!r) {
80
+ if (!tmp) out.push(e);
81
+ continue;
82
+ }
83
+ // Part of the replay; its last event completes it, and every replay queued before it.
84
+ r.seen.add(tmp ? `tmp-${e.type}` : e.type);
85
+ if (r.need.some((keys) => keys.every((k) => r.seen.has(k)))) {
86
+ for (const [q, p] of this.#pending) if (p.seq <= r.seq) this.#pending.delete(q);
87
+ this.#progress = now;
88
+ }
89
+ }
90
+ this.#update(now);
91
+ return out;
92
+ }
93
+
94
+ /** Expires replays without progress and wakes the waiters that can go on. */
95
+ tick() {
96
+ this.#update(this.now());
97
+ }
98
+
99
+ /**
100
+ * Resolves once no pending replay is on, under or above one of `paths`; undefined if none is.
101
+ * `read`: only one on the paths themselves counts (a replay moves only its own entry away and
102
+ * hides no tree: an empty directory is made again, one with entries touched).
103
+ */
104
+ clear(paths, read = false) {
105
+ if (!this.#blocks(paths, read)) return undefined;
106
+ return new Promise((resolve) => this.#waiters.push({ paths, read, resolve }));
107
+ }
108
+
109
+ /**
110
+ * "create" or "delete" while the replay of that page change to `path` is pending (its entry may
111
+ * be under `<path>.~wp`, or back for a moment), else undefined.
112
+ */
113
+ pendingType(path) {
114
+ return this.#pending.get(path)?.type;
115
+ }
116
+
117
+ /** Resolves once the replays pending now are done (or given up). */
118
+ settle() {
119
+ if (this.#pending.size === 0) return Promise.resolve();
120
+ return new Promise((resolve) => this.#waiters.push({ upTo: this.#seq, resolve }));
121
+ }
122
+
123
+ /** Pending replays or waiters: `tick()` has work to do. */
124
+ get busy() {
125
+ return this.#pending.size > 0 || this.#waiters.length > 0;
126
+ }
127
+
128
+ #blocks(paths, read) {
129
+ for (const p of this.#pending.keys()) if (paths.some((q) => (read ? p === q : related(p, q)))) return true;
130
+ return false;
131
+ }
132
+
133
+ #update(now) {
134
+ let first = Infinity;
135
+ for (const [path, p] of this.#pending) {
136
+ if (now - Math.max(p.at, this.#progress) > REPLAY_TIMEOUT_MS) this.#pending.delete(path);
137
+ else first = Math.min(first, p.seq);
138
+ }
139
+ if (this.#waiters.length === 0) return;
140
+ const waiting = this.#waiters;
141
+ this.#waiters = [];
142
+ for (const w of waiting) {
143
+ if (w.paths ? !this.#blocks(w.paths, w.read) : first > w.upTo) w.resolve();
144
+ else this.#waiters.push(w);
145
+ }
146
+ }
147
+ }
package/dist/rpc.js CHANGED
@@ -1,32 +1,64 @@
1
1
  // PodFs RPC served on a MessagePort (the page side is createWorkspaceFs in @webpodjs/sdk).
2
2
  //
3
- // page -> worker: { id, op, args: [...], settle? }
3
+ // page -> worker: { id, op, args: [...], settle? } | { id, op: "settle" } | { op: "replayed", args: [seq] }
4
4
  // worker -> page: { id, ok: true, value } | { id, ok: false, error: { code, errno, message } }
5
- // { type: "events", events: [{ origin: "page" | "guest", type, path }] }
5
+ // { type: "events", events: [{ origin: "page" | "guest", type, path, dir? }], seq }
6
6
  //
7
7
  // ops map 1:1 onto WorkspaceFs methods: readFile(path), readAt(path, offset, len),
8
8
  // write(path, offset, data, create, truncate, mode), readdir(path), mkdir(path, recursive, mode),
9
9
  // rm(path, recursive, force), stat(path, follow), rename(from, to), chmod(path, mode),
10
- // symlink(target, path), readlink(path).
10
+ // symlink(target, path), readlink(path), sync() (contents and metadata to storage: a durable
11
+ // writeFile).
11
12
  //
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.
13
+ // The agent's FsNotify replay of a page create hides the file for a moment. An op on a path that is
14
+ // being replayed (the path, under it or above it; a read only the path itself) first waits for that
15
+ // replay, and a directory listing shows the page's view meanwhile: a created entry under its own
16
+ // name (not the agent's temporary one), a deleted one not back for a moment. The "settle" op is
17
+ // answered once the ops sent before it are done and the guest has replayed the creates and deletes
18
+ // made so far, or gave up (replays.js): the SDK sends it before starting a guest process. An op
19
+ // with settle: true (older SDKs) is answered that way too.
14
20
 
15
- const OPS = new Set(["readFile", "readAt", "write", "readdir", "mkdir", "rm", "stat", "rename", "chmod", "symlink", "readlink"]);
21
+ const OPS = new Set(["readFile", "readAt", "write", "readdir", "mkdir", "rm", "stat", "rename", "chmod", "symlink", "readlink", "sync"]);
22
+ const READS = new Set(["readFile", "readAt", "readdir", "stat", "readlink"]);
23
+ /** The agent's temporary name suffix (replays.js). */
24
+ const TMP = ".~wp";
25
+
26
+ /** The workspace paths an op touches. */
27
+ const paths = (op, args) => (op === "rename" ? [args[0], args[1]] : op === "symlink" ? [args[1]] : [args[0]]);
16
28
 
17
29
  /**
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.
30
+ * Serves `ws` (a WorkspaceFs) on `port`. Hooks: `settle()` resolves once the guest has replayed
31
+ * the page changes so far; `clear(paths, read)` (when it returns a promise) once nothing on those
32
+ * paths is being replayed; `pending(path)`: "create" or "delete" while that replay is pending;
33
+ * `hidden(path)`: left out of directory listings (the workspace's local paths, which the guest
34
+ * keeps on its data disk); `replayed(seq)`: the page says the guest has replayed the events
35
+ * broadcast up to `seq` (`{ op: "replayed", args: [seq] }`, no answer). Returns a function that
36
+ * broadcasts change events (and the seq they reach).
20
37
  */
21
- export function serveWorkspace(ws, port, settle = async () => {}) {
22
- port.onmessage = async ({ data }) => {
38
+ export function serveWorkspace(ws, port, { settle = async () => {}, clear = () => undefined, pending = () => undefined, hidden = () => false, replayed = () => {} } = {}) {
39
+ const running = new Set();
40
+ const serve = async (data) => {
23
41
  const { id, op, args } = data ?? {};
42
+ if (op === "replayed") {
43
+ if (Number.isInteger(args?.[0])) replayed(args[0]);
44
+ return;
45
+ }
46
+ if (op === "settle") {
47
+ await Promise.allSettled([...running]);
48
+ await settle();
49
+ port.postMessage({ id, ok: true, value: null });
50
+ return;
51
+ }
24
52
  if (!OPS.has(op) || !Array.isArray(args)) {
25
53
  port.postMessage({ id, ok: false, error: { code: "EINVAL", errno: 22, message: `unknown op ${op}` } });
26
54
  return;
27
55
  }
28
56
  try {
29
- const value = await ws[op](...args);
57
+ // Called at once when nothing waits: ops then reach the workspace in arrival order.
58
+ const gate = clear(paths(op, args).filter((p) => typeof p === "string"), READS.has(op));
59
+ if (gate) await gate;
60
+ let value = await ws[op](...args);
61
+ if (op === "readdir") value = listing(String(args[0]).replace(/\/+$/, ""), value, pending, hidden);
30
62
  if (data.settle) await settle();
31
63
  const transfer = value instanceof Uint8Array ? [value.buffer] : [];
32
64
  port.postMessage({ id, ok: true, value }, transfer);
@@ -34,6 +66,31 @@ export function serveWorkspace(ws, port, settle = async () => {}) {
34
66
  port.postMessage({ id, ok: false, error: { code: e?.code ?? "EIO", errno: e?.errno ?? 5, message: String(e?.message ?? e) } });
35
67
  }
36
68
  };
69
+ port.onmessage = ({ data }) => {
70
+ const run = serve(data);
71
+ if (data?.op === "settle") return;
72
+ running.add(run);
73
+ void run.finally(() => running.delete(run));
74
+ };
37
75
  port.start?.();
38
- return (events) => port.postMessage({ type: "events", events });
76
+ return (events, seq) => port.postMessage({ type: "events", events, seq });
77
+ }
78
+
79
+ /** `entries` of `dir` as the page sees them: without local paths, and replays in progress. */
80
+ function listing(dir, entries, pending, hidden) {
81
+ const names = new Set(entries.map((e) => e.name));
82
+ const out = [];
83
+ for (const e of entries) {
84
+ const path = `${dir}/${e.name}`;
85
+ if (hidden(path) || pending(path) === "delete") continue;
86
+ if (e.name.endsWith(TMP)) {
87
+ const name = e.name.slice(0, -TMP.length);
88
+ if (pending(`${dir}/${name}`) === "create") {
89
+ if (!names.has(name)) out.push({ ...e, name });
90
+ continue;
91
+ }
92
+ }
93
+ out.push(e);
94
+ }
95
+ return out;
39
96
  }
package/dist/tabs.js ADDED
@@ -0,0 +1,256 @@
1
+ // Other tabs of the same pod (docs/design/workspace-fs.md §4, phase 2). One FS Worker holds the
2
+ // workspace (its Web Lock, webpod:ws:<pod>) and serves it to the others on the BroadcastChannel of
3
+ // the same name: their guests' 9P messages, each in its own 9P session, and their pages' PodFs
4
+ // calls. Every change is broadcast with its origin, `page:<tab>` or `guest:<tab>`. When the
5
+ // holder goes (closed, crashed), the next tab in the lock's queue takes the workspace over from
6
+ // OPFS and goes on with the last 9P session of its guest the holder sent it.
7
+ //
8
+ // tab -> all: { t: "hello", from } | { t: "bye", from }
9
+ // holder -> all: { t: "holder", from } | { t: "events", from, events: [{ origin, type, path, dir? }] }
10
+ // tab -> holder: { t: "req", to, from, id, op, args } | { t: "attach", to, from, session }
11
+ // holder -> tab: { t: "res", to, id, ok, value | error: { code, errno, message } }
12
+ // { t: "session", to, session } (its 9P session, at most every SESSION_PUSH_MS)
13
+ //
14
+ // Same-origin documents can all join the channel (and open the OPFS workspace themselves): the
15
+ // workspace is only as isolated as the origin, so untrusted content (previews, user pages) must be
16
+ // served from another origin.
17
+
18
+ /** How long a tab waits for the holder to answer its hello before it gives up on sharing. */
19
+ export const HELLO_TIMEOUT_MS = 3000;
20
+ /** A tab's 9P session is sent to it at most this often (the fids it may lose on a takeover). */
21
+ export const SESSION_PUSH_MS = 300;
22
+
23
+ /** The ops a tab may call on the holder: the PodFs ones (sync too) and its guest's 9P. */
24
+ const OPS = new Set(["readFile", "readAt", "write", "readdir", "mkdir", "rm", "stat", "rename", "chmod", "symlink", "readlink", "sync", "p9", "p9Reset"]);
25
+
26
+ const errorOf = (e) => ({ code: e?.code ?? "EIO", errno: e?.errno ?? 5, message: String(e?.message ?? e) });
27
+
28
+ function toError({ code, errno, message }) {
29
+ const e = new Error(message);
30
+ e.code = code;
31
+ e.errno = errno;
32
+ return e;
33
+ }
34
+
35
+ /** The lock a tab holds while it lives: the holder waits on it to know when the tab is gone. */
36
+ export const tabLock = (pod, tab) => `webpod:ws:${pod}:tab:${tab}`;
37
+
38
+ /**
39
+ * The holder's side: serves `ws` (a WorkspaceFs) to the other tabs on `channel`. `flush()`
40
+ * broadcasts the workspace's pending events (the FS Worker's flushEvents, which calls
41
+ * `broadcast`); it runs before each answer, so a tab gets the events of its call first.
42
+ * `locks`: navigator.locks (the tabs' locks tell when one is gone).
43
+ */
44
+ export class WorkspaceHost {
45
+ #views = new Map();
46
+ #pushes = new Map();
47
+
48
+ constructor(ws, channel, { id, pod, flush = () => {}, locks = globalThis.navigator?.locks, log = () => {} }) {
49
+ Object.assign(this, { ws, channel, id, pod, flush, locks, log });
50
+ this.closed = false;
51
+ channel.onmessage = ({ data }) => void this.#onMessage(data);
52
+ this.announce();
53
+ }
54
+
55
+ /** Tells every tab who serves the workspace. */
56
+ announce() {
57
+ this.channel.postMessage({ t: "holder", from: this.id });
58
+ }
59
+
60
+ /** Broadcasts workspace events: this tab's own origins qualified with its id. */
61
+ broadcast(events) {
62
+ if (this.closed || this.#views.size === 0 || events.length === 0) return;
63
+ const qualify = (o) => (o === "page" || o === "guest" ? `${o}:${this.id}` : o);
64
+ this.channel.postMessage({ t: "events", from: this.id, events: events.map((e) => ({ ...e, origin: qualify(e.origin) })) });
65
+ }
66
+
67
+ /** The tabs served now. */
68
+ get clients() {
69
+ return [...this.#views.keys()];
70
+ }
71
+
72
+ close() {
73
+ this.closed = true;
74
+ this.channel.onmessage = null;
75
+ for (const t of this.#pushes.values()) clearTimeout(t);
76
+ }
77
+
78
+ #view(tab) {
79
+ let v = this.#views.get(tab);
80
+ if (!v) {
81
+ v = this.ws.forClient(tab);
82
+ this.#views.set(tab, v);
83
+ // Granted once the tab is gone (it holds it while it lives): end its 9P session.
84
+ this.locks?.request(tabLock(this.pod, tab), () => this.#drop(tab)).catch(() => {});
85
+ }
86
+ return v;
87
+ }
88
+
89
+ async #drop(tab) {
90
+ const v = this.#views.get(tab);
91
+ if (!v) return;
92
+ this.#views.delete(tab);
93
+ clearTimeout(this.#pushes.get(tab));
94
+ this.#pushes.delete(tab);
95
+ await v.p9Reset().catch((e) => this.log("warn", `tab ${tab} gone: ${e?.message ?? e}`));
96
+ }
97
+
98
+ #pushSession(tab) {
99
+ if (this.#pushes.has(tab)) return;
100
+ this.#pushes.set(tab, setTimeout(async () => {
101
+ this.#pushes.delete(tab);
102
+ const v = this.#views.get(tab);
103
+ const session = await v?.p9Session().catch(() => undefined);
104
+ if (session && !this.closed) this.channel.postMessage({ t: "session", to: tab, session });
105
+ }, SESSION_PUSH_MS));
106
+ }
107
+
108
+ async #onMessage(m) {
109
+ if (this.closed || !m || m.from === this.id) return;
110
+ switch (m.t) {
111
+ case "hello":
112
+ this.#view(m.from);
113
+ this.announce();
114
+ return;
115
+ case "bye":
116
+ return this.#drop(m.from);
117
+ case "attach":
118
+ if (m.to !== this.id || !(m.session instanceof Uint8Array)) return;
119
+ try {
120
+ const dropped = await this.#view(m.from).p9Adopt(m.session);
121
+ if (dropped) this.log("info", `tab ${m.from}: ${dropped} 9P fids not in the workspace any more`);
122
+ } catch (e) {
123
+ this.log("warn", `tab ${m.from}: its 9P session: ${e?.message ?? e}`);
124
+ }
125
+ return;
126
+ case "req": {
127
+ if (m.to !== this.id) return;
128
+ let res;
129
+ try {
130
+ if (!OPS.has(m.op) || !Array.isArray(m.args)) throw Object.assign(new Error(`unknown op ${m.op}`), { code: "EINVAL", errno: 22 });
131
+ const view = this.#view(m.from);
132
+ const value = await view[m.op](...m.args);
133
+ res = { t: "res", to: m.from, id: m.id, ok: true, value };
134
+ if (m.op === "p9") this.#pushSession(m.from);
135
+ } catch (e) {
136
+ res = { t: "res", to: m.from, id: m.id, ok: false, error: errorOf(e) };
137
+ }
138
+ this.flush();
139
+ if (!this.closed) this.channel.postMessage(res);
140
+ return;
141
+ }
142
+ }
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Another tab's side: the WorkspaceFs surface the FS Worker uses (9P, PodFs ops, takeEvents),
148
+ * served by the holder. Events of this tab's guest come back as `guest`, all others (this tab's
149
+ * page included) as `page`: changes the guest did not make, to replay in it.
150
+ */
151
+ export class WorkspaceClient {
152
+ ephemeral = "shared";
153
+ /** This tab's guest's last 9P session the holder sent (for a takeover). */
154
+ session = undefined;
155
+ #events = [];
156
+ #pending = new Map();
157
+ #nextId = 1;
158
+ #holder = null;
159
+ #found = null;
160
+
161
+ constructor(channel, { id, log = () => {} }) {
162
+ Object.assign(this, { channel, id, log });
163
+ this.closed = false;
164
+ channel.onmessage = ({ data }) => this.#onMessage(data);
165
+ this.found = new Promise((resolve) => (this.#found = resolve));
166
+ channel.postMessage({ t: "hello", from: id });
167
+ }
168
+
169
+ /** The holder's id once one has answered. */
170
+ get holder() {
171
+ return this.#holder;
172
+ }
173
+
174
+ #onMessage(m) {
175
+ if (this.closed || !m) return;
176
+ switch (m.t) {
177
+ case "holder":
178
+ if (m.from === this.#holder) return;
179
+ this.#failPending(`the workspace's holder changed`);
180
+ this.#holder = m.from;
181
+ // A new holder (the old one went): it goes on with this guest's 9P session.
182
+ if (this.session) this.channel.postMessage({ t: "attach", to: m.from, from: this.id, session: this.session });
183
+ this.#found(m.from);
184
+ return;
185
+ case "events":
186
+ if (m.from !== this.#holder) return;
187
+ for (const e of m.events) this.#events.push({ ...e, origin: e.origin === `guest:${this.id}` ? "guest" : "page" });
188
+ return;
189
+ case "session":
190
+ if (m.to === this.id && m.session instanceof Uint8Array) this.session = m.session;
191
+ return;
192
+ case "res": {
193
+ if (m.to !== this.id) return;
194
+ const p = this.#pending.get(m.id);
195
+ if (!p) return;
196
+ this.#pending.delete(m.id);
197
+ if (m.ok) p.resolve(m.value);
198
+ else p.reject(toError(m.error));
199
+ }
200
+ }
201
+ }
202
+
203
+ /** Calls in flight fail with EIO: their holder is gone (they may or may not have run). */
204
+ #failPending(why) {
205
+ for (const p of this.#pending.values()) p.reject(toError({ code: "EIO", errno: 5, message: why }));
206
+ this.#pending.clear();
207
+ }
208
+
209
+ #call(op, args) {
210
+ if (this.closed) return Promise.reject(toError({ code: "EIO", errno: 5, message: "workspace closed" }));
211
+ if (!this.#holder) return Promise.reject(toError({ code: "EIO", errno: 5, message: "no tab holds the workspace" }));
212
+ const id = this.#nextId++;
213
+ return new Promise((resolve, reject) => {
214
+ this.#pending.set(id, { resolve, reject });
215
+ this.channel.postMessage({ t: "req", to: this.#holder, from: this.id, id, op, args });
216
+ });
217
+ }
218
+
219
+ /** Stops serving calls (this tab takes the workspace over, or closes). */
220
+ detach(why = "workspace closed") {
221
+ this.closed = true;
222
+ this.channel.onmessage = null;
223
+ this.#failPending(why);
224
+ }
225
+
226
+ takeEvents() {
227
+ const e = this.#events;
228
+ this.#events = [];
229
+ return e;
230
+ }
231
+
232
+ p9 = (msg) => this.#call("p9", [msg]);
233
+ p9Reset = () => this.#call("p9Reset", []);
234
+ readFile = (path) => this.#call("readFile", [path]);
235
+ readAt = (path, offset, len) => this.#call("readAt", [path, offset, len]);
236
+ write = (path, offset, data, create, truncate, mode) => this.#call("write", [path, offset, data, create, truncate, mode]);
237
+ readdir = (path) => this.#call("readdir", [path]);
238
+ mkdir = (path, recursive, mode) => this.#call("mkdir", [path, recursive, mode]);
239
+ rm = (path, recursive, force) => this.#call("rm", [path, recursive, force]);
240
+ stat = (path, follow) => this.#call("stat", [path, follow]);
241
+ rename = (from, to) => this.#call("rename", [from, to]);
242
+ chmod = (path, mode) => this.#call("chmod", [path, mode]);
243
+ symlink = (target, path) => this.#call("symlink", [target, path]);
244
+ readlink = (path) => this.#call("readlink", [path]);
245
+ /** The holder syncs the workspace (a durable write, a flush when the page goes away). */
246
+ sync = () => this.#call("sync", []);
247
+ #held = () => Promise.reject(toError({ code: "EBUSY", errno: 16, message: "the workspace is held by another tab of this pod" }));
248
+ snapshot = () => this.#held();
249
+ snapshotWithSession = () => this.#held();
250
+ restore = () => this.#held();
251
+ close = async () => {
252
+ if (this.closed) return;
253
+ this.channel.postMessage({ t: "bye", from: this.id });
254
+ this.detach();
255
+ };
256
+ }
package/dist/worker.js CHANGED
@@ -5,13 +5,27 @@
5
5
  // host -> worker: init, attach (blk by serial, 9p by id), fs-port, stop
6
6
  // worker -> host: volumes, ready, stopped, log, error
7
7
  import init, { BlockVolumes, SnapshotStore, WorkspaceFs } from "./pkg/webpod_fs_wasm.js";
8
- import { RingConsumer, RingProducer, waitReadable } from "./abi/index.js";
8
+ import { RingConsumer, RingProducer, settleWaits, waitReadable } from "./abi/index.js";
9
+ import { Replays } from "./replays.js";
9
10
  import { serveWorkspace } from "./rpc.js";
11
+ import { HELLO_TIMEOUT_MS, WorkspaceClient, WorkspaceHost, tabLock } from "./tabs.js";
10
12
 
11
13
  const COMPLETION_HEADER = 12;
12
14
  const ready = init();
13
15
  let volumes = null;
16
+ /** WorkspaceFs, or a WorkspaceClient while another tab of the pod holds the workspace. */
14
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
+ });
15
29
  let snapshots = null;
16
30
  /** The snapshot whose 9P session the workspace continues (restored at init), if any. */
17
31
  let restoredSession = null;
@@ -44,45 +58,95 @@ async function pump(name, memory, fromEngine, toEngine, handle) {
44
58
 
45
59
  /**
46
60
  * 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.
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.
51
65
  */
52
- const REPLAY_TIMEOUT_MS = 2000;
53
- const replays = new Map(); // path -> { type, at }
54
- const settlers = []; // { paths, resolve, at }
66
+ const replays = new Replays();
55
67
  /** The guest speaks 9P (it mounted /workspace): page changes will be replayed. */
56
68
  let guestMounted = false;
57
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
+
58
80
  function flushEvents() {
59
81
  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
- }
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;
69
119
  }
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
- }
120
+ if (first !== "client") {
121
+ client.detach();
122
+ channel.close();
123
+ takeover.then((ws) => ws.close(), () => {});
124
+ return null;
78
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;
79
138
  }
80
139
 
81
- /** Resolves once the replays of the page changes made so far are done (or have timed out). */
140
+ /** Resolves once the replays of the page changes made so far are done (or given up). */
82
141
  function settle() {
83
142
  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() }));
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);
86
150
  }
87
151
 
88
152
  async function onInit(m) {
@@ -99,12 +163,26 @@ async function onInit(m) {
99
163
  if (m.workspace !== false) {
100
164
  const w = m.workspace ?? {};
101
165
  const msize = w.msize ?? 512 * 1024;
102
- workspace = await WorkspaceFs.open(m.podId, w.mountPoint ?? "/workspace", w.uid ?? 0, w.gid ?? 0, msize);
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
+ }
103
179
  wsEphemeral = workspace.ephemeral;
104
- devices.push({ class: "9p", id: "webpod-ws", msize });
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.
105
185
  setInterval(flushEvents, 30);
106
- // Settlers waiting past the last event still time out.
107
- setInterval(() => settlers.length && flushEvents(), 250);
108
186
  setInterval(() => workspace?.sync().catch((e) => log("warn", `workspace sync: ${e?.message ?? e}`)), 1000);
109
187
  }
110
188
  // Snapshots live in OPFS; without it (e.g. WebKit temporary profiles) they are unavailable.
@@ -243,7 +321,7 @@ function onAttach(m) {
243
321
  pumps.push(pump(id, m.memory, m.fromEngine, m.toEngine, async (batch) => {
244
322
  guestMounted = true;
245
323
  const replies = await Promise.all(batch.map((msg) => workspace.p9(msg)));
246
- if (settlers.length) flushEvents(); // a replay may just have finished
324
+ if (replays.busy) flushEvents(); // a replay may just have finished
247
325
  return replies;
248
326
  }));
249
327
  } else if (id === "webpod-root" || id === "webpod-data") {
@@ -260,14 +338,19 @@ function onAttach(m) {
260
338
 
261
339
  async function onStop() {
262
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();
263
344
  await Promise.allSettled(pumps);
264
345
  // An imported boot snapshot's RAM: stored if the pod resumed from it, else dropped (a cold boot
265
346
  // follows; the next import downloads what the store lacks).
266
347
  if (ramResumed) await snapshots?.persistRam().catch(() => {});
267
348
  else snapshots?.discardUnpersisted();
268
349
  flushEvents();
350
+ host?.close();
269
351
  await workspace?.close();
270
352
  await volumes?.close();
353
+ await settleWaits();
271
354
  post({ type: "stopped" });
272
355
  }
273
356
 
@@ -281,7 +364,7 @@ self.onmessage = async ({ data: m }) => {
281
364
  return onAttach(m);
282
365
  case "fs-port":
283
366
  if (!workspace) throw new Error("fs-port: workspace disabled in init");
284
- broadcasts.push(serveWorkspace(workspace, m.port, settle));
367
+ broadcasts.push(serveWorkspace(current, m.port, { settle, clear: clearOf, pending: (p) => replays.pendingType(p), hidden: isHidden, replayed: (seq) => replays.replayed(seq) }));
285
368
  return;
286
369
  case "stats":
287
370
  return post({ type: "stats", root: await volumes?.rootStats() });
@@ -323,6 +406,10 @@ self.onmessage = async ({ data: m }) => {
323
406
  return post({ type: "imported", info: await snapshots.importBlob(m.file, m.name ?? undefined) });
324
407
  case "trace":
325
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" });
326
413
  case "stop":
327
414
  return await onStop();
328
415
  default:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpodjs/fs-worker",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "FS Worker for webpod: block volumes (webpod-root/webpod-data) and the shared /workspace (9P + PodFs RPC)",
5
5
  "keywords": [
6
6
  "webpod",