@webpodjs/fs-worker 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +96 -2
- package/dist/abi/index.js +3 -0
- package/dist/abi/ring.js +389 -0
- package/dist/pkg/webpod_fs_wasm.d.ts +376 -0
- package/dist/pkg/webpod_fs_wasm.js +1724 -0
- package/dist/pkg/webpod_fs_wasm_bg.wasm +0 -0
- package/dist/pkg/webpod_fs_wasm_bg.wasm.d.ts +76 -0
- package/dist/replays.js +147 -0
- package/dist/rpc.js +96 -0
- package/dist/tabs.js +256 -0
- package/dist/worker.js +421 -0
- package/package.json +34 -4
|
Binary file
|
|
@@ -0,0 +1,76 @@
|
|
|
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_flush: (a: number) => any;
|
|
12
|
+
export const blockvolumes_handle: (a: number, b: number, c: number, d: any) => any;
|
|
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;
|
|
14
|
+
export const blockvolumes_prefetch: (a: number, b: number, c: number) => any;
|
|
15
|
+
export const blockvolumes_restoreData: (a: number, b: number, c: number) => any;
|
|
16
|
+
export const blockvolumes_rootManifestId: (a: number) => [number, number];
|
|
17
|
+
export const blockvolumes_rootSize: (a: number) => number;
|
|
18
|
+
export const blockvolumes_rootStats: (a: number) => any;
|
|
19
|
+
export const blockvolumes_rootTrace: (a: number) => any;
|
|
20
|
+
export const blockvolumes_setEngineMemory: (a: number, b: any) => void;
|
|
21
|
+
export const blockvolumes_setMaxRead: (a: number, b: number, c: number, d: number) => void;
|
|
22
|
+
export const blockvolumes_snapshotData: (a: number) => any;
|
|
23
|
+
export const snapshotstore_checkBinding: (a: number, b: number, c: number, d: any) => any;
|
|
24
|
+
export const snapshotstore_delete: (a: number, b: number, c: number) => any;
|
|
25
|
+
export const snapshotstore_discardUnpersisted: (a: number) => void;
|
|
26
|
+
export const snapshotstore_exportFile: (a: number, b: number, c: number) => any;
|
|
27
|
+
export const snapshotstore_importBlob: (a: number, b: any, c: number, d: number) => any;
|
|
28
|
+
export const snapshotstore_importBoot: (a: number, b: number, c: number, d: number, e: number) => any;
|
|
29
|
+
export const snapshotstore_list: (a: number) => any;
|
|
30
|
+
export const snapshotstore_manifest: (a: number, b: number, c: number, d: number, e: number) => any;
|
|
31
|
+
export const snapshotstore_open: (a: number, b: number) => any;
|
|
32
|
+
export const snapshotstore_persistRam: (a: number) => any;
|
|
33
|
+
export const snapshotstore_prefetchRam: (a: number, b: number, c: number) => any;
|
|
34
|
+
export const snapshotstore_readBytes: (a: number, b: number, c: number) => any;
|
|
35
|
+
export const snapshotstore_restoreRam: (a: number, b: number, c: number, d: any, e: number) => any;
|
|
36
|
+
export const snapshotstore_save: (a: number, b: number, c: number, d: number, e: any, f: any) => any;
|
|
37
|
+
export const snapshotstore_snapshotBytes: (a: number, b: number, c: number) => any;
|
|
38
|
+
export const snapshotstore_snapshotRam: (a: number, b: any) => any;
|
|
39
|
+
export const workspacefs_chmod: (a: number, b: number, c: number, d: number) => any;
|
|
40
|
+
export const workspacefs_close: (a: number) => any;
|
|
41
|
+
export const workspacefs_ephemeral: (a: number) => [number, number];
|
|
42
|
+
export const workspacefs_forClient: (a: number, b: number, c: number) => number;
|
|
43
|
+
export const workspacefs_mkdir: (a: number, b: number, c: number, d: number, e: number) => any;
|
|
44
|
+
export const workspacefs_open: (a: number, b: number, c: number, d: number, e: number, f: number, g: number) => any;
|
|
45
|
+
export const workspacefs_p9: (a: number, b: number, c: number) => any;
|
|
46
|
+
export const workspacefs_p9Adopt: (a: number, b: number, c: number) => any;
|
|
47
|
+
export const workspacefs_p9Reset: (a: number) => any;
|
|
48
|
+
export const workspacefs_p9Session: (a: number) => any;
|
|
49
|
+
export const workspacefs_readAt: (a: number, b: number, c: number, d: number, e: number) => any;
|
|
50
|
+
export const workspacefs_readFile: (a: number, b: number, c: number) => any;
|
|
51
|
+
export const workspacefs_readdir: (a: number, b: number, c: number) => any;
|
|
52
|
+
export const workspacefs_readlink: (a: number, b: number, c: number) => any;
|
|
53
|
+
export const workspacefs_rename: (a: number, b: number, c: number, d: number, e: number) => any;
|
|
54
|
+
export const workspacefs_restore: (a: number, b: number, c: number, d: number, e: number) => any;
|
|
55
|
+
export const workspacefs_rm: (a: number, b: number, c: number, d: number, e: number) => any;
|
|
56
|
+
export const workspacefs_snapshot: (a: number) => any;
|
|
57
|
+
export const workspacefs_snapshotWithSession: (a: number) => any;
|
|
58
|
+
export const workspacefs_stat: (a: number, b: number, c: number, d: number) => any;
|
|
59
|
+
export const workspacefs_symlink: (a: number, b: number, c: number, d: number, e: number) => any;
|
|
60
|
+
export const workspacefs_sync: (a: number) => any;
|
|
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;
|
|
63
|
+
export const workspacefs_write: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number) => any;
|
|
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;
|
|
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];
|
|
66
|
+
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;
|
|
67
|
+
export const wasm_bindgen_5a2380350bab5903___convert__closures_____invoke_______true_: (a: number, b: number) => void;
|
|
68
|
+
export const __wbindgen_malloc: (a: number, b: number) => number;
|
|
69
|
+
export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
|
|
70
|
+
export const __wbindgen_free: (a: number, b: number, c: number) => void;
|
|
71
|
+
export const __wbindgen_exn_store: (a: number) => void;
|
|
72
|
+
export const __externref_table_alloc: () => number;
|
|
73
|
+
export const __wbindgen_externrefs: WebAssembly.Table;
|
|
74
|
+
export const __wbindgen_destroy_closure: (a: number, b: number) => void;
|
|
75
|
+
export const __externref_table_dealloc: (a: number) => void;
|
|
76
|
+
export const __wbindgen_start: () => void;
|
package/dist/replays.js
ADDED
|
@@ -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
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// PodFs RPC served on a MessagePort (the page side is createWorkspaceFs in @webpodjs/sdk).
|
|
2
|
+
//
|
|
3
|
+
// page -> worker: { id, op, args: [...], settle? } | { id, op: "settle" } | { op: "replayed", args: [seq] }
|
|
4
|
+
// worker -> page: { id, ok: true, value } | { id, ok: false, error: { code, errno, message } }
|
|
5
|
+
// { type: "events", events: [{ origin: "page" | "guest", type, path, dir? }], seq }
|
|
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), sync() (contents and metadata to storage: a durable
|
|
11
|
+
// writeFile).
|
|
12
|
+
//
|
|
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.
|
|
20
|
+
|
|
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]]);
|
|
28
|
+
|
|
29
|
+
/**
|
|
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).
|
|
37
|
+
*/
|
|
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) => {
|
|
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
|
+
}
|
|
52
|
+
if (!OPS.has(op) || !Array.isArray(args)) {
|
|
53
|
+
port.postMessage({ id, ok: false, error: { code: "EINVAL", errno: 22, message: `unknown op ${op}` } });
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
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);
|
|
62
|
+
if (data.settle) await settle();
|
|
63
|
+
const transfer = value instanceof Uint8Array ? [value.buffer] : [];
|
|
64
|
+
port.postMessage({ id, ok: true, value }, transfer);
|
|
65
|
+
} catch (e) {
|
|
66
|
+
port.postMessage({ id, ok: false, error: { code: e?.code ?? "EIO", errno: e?.errno ?? 5, message: String(e?.message ?? e) } });
|
|
67
|
+
}
|
|
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
|
+
};
|
|
75
|
+
port.start?.();
|
|
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;
|
|
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
|
+
}
|