@webpodjs/net-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 +175 -2
- package/dist/abi/index.js +3 -0
- package/dist/abi/ring.js +389 -0
- package/dist/pkg/webpod_net_wasm.d.ts +134 -0
- package/dist/pkg/webpod_net_wasm.js +1075 -0
- package/dist/pkg/webpod_net_wasm_bg.wasm +0 -0
- package/dist/pkg/webpod_net_wasm_bg.wasm.d.ts +33 -0
- package/dist/worker.js +213 -0
- package/package.json +32 -4
|
Binary file
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/* tslint:disable */
|
|
2
|
+
/* eslint-disable */
|
|
3
|
+
export const memory: WebAssembly.Memory;
|
|
4
|
+
export const __wbg_netpod_free: (a: number, b: number) => void;
|
|
5
|
+
export const netpod_add_peer: (a: number, b: number, c: number, d: number, e: number) => void;
|
|
6
|
+
export const netpod_ca_bundle: (a: number) => [number, number];
|
|
7
|
+
export const netpod_ca_certificate: (a: number) => [number, number];
|
|
8
|
+
export const netpod_delay: (a: number, b: number) => number;
|
|
9
|
+
export const netpod_new: (a: any, b: number, c: number, d: number, e: number) => [number, number, number];
|
|
10
|
+
export const netpod_open_inbound: (a: number, b: any) => void;
|
|
11
|
+
export const netpod_poll: (a: number, b: number) => number;
|
|
12
|
+
export const netpod_push: (a: number, b: number, c: number) => void;
|
|
13
|
+
export const netpod_push_forwarded: (a: number, b: number, c: number) => number;
|
|
14
|
+
export const netpod_remove_peer: (a: number, b: number) => void;
|
|
15
|
+
export const netpod_set_notify: (a: number, b: number) => void;
|
|
16
|
+
export const netpod_set_unix_time: (a: number, b: number) => void;
|
|
17
|
+
export const netpod_stats: (a: number) => any;
|
|
18
|
+
export const netpod_take: (a: number) => any;
|
|
19
|
+
export const netpod_take_forwarded: (a: number) => any;
|
|
20
|
+
export const set_logger: (a: any, b: number, c: number) => void;
|
|
21
|
+
export const ring_core_0_17_14__bn_mul_mont: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
|
|
22
|
+
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];
|
|
23
|
+
export const wasm_bindgen_5a2380350bab5903___convert__closures_____invoke___wasm_bindgen_5a2380350bab5903___JsValue______true_: (a: number, b: number, c: any) => void;
|
|
24
|
+
export const wasm_bindgen_5a2380350bab5903___convert__closures_____invoke___wasm_bindgen_5a2380350bab5903___JsValue__true_: (a: number, b: number) => any;
|
|
25
|
+
export const __wbindgen_malloc: (a: number, b: number) => number;
|
|
26
|
+
export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
|
|
27
|
+
export const __wbindgen_free: (a: number, b: number, c: number) => void;
|
|
28
|
+
export const __wbindgen_exn_store: (a: number) => void;
|
|
29
|
+
export const __externref_table_alloc: () => number;
|
|
30
|
+
export const __wbindgen_externrefs: WebAssembly.Table;
|
|
31
|
+
export const __wbindgen_destroy_closure: (a: number, b: number) => void;
|
|
32
|
+
export const __externref_table_dealloc: (a: number) => void;
|
|
33
|
+
export const __wbindgen_start: () => void;
|
package/dist/worker.js
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
// webpod net Worker (docs/host-engine.md §4): the guest NIC's gateway. Consumes Ethernet frames
|
|
2
|
+
// from the engine (fromEngine ring), runs webpod-net's NetStack (DHCP, DNS, transparent HTTP(S)
|
|
3
|
+
// proxy with TLS interception, browser fetch / WebSocket egress, CORS proxy, relays) and produces
|
|
4
|
+
// frames for the guest (toEngine ring). Page connections (previews, pod.fetch, pod.net.connect)
|
|
5
|
+
// arrive as "inbound" MessagePorts.
|
|
6
|
+
//
|
|
7
|
+
// host -> worker: attach { memory, toEngine, fromEngine, mac, network?, caKey?, logLevel? }, inbound { port },
|
|
8
|
+
// ca, relay-token { id, token | error }, peer { id, hostname, index, port }, peer-gone { id },
|
|
9
|
+
// stats, stop
|
|
10
|
+
// worker -> host: ready, ca { pem }, relay-token-request { id }, peer-added { id }, stats { stats },
|
|
11
|
+
// stopped, log, error
|
|
12
|
+
import init, { NetPod, set_logger } from "./pkg/webpod_net_wasm.js";
|
|
13
|
+
import { RingConsumer, RingProducer, settleWaits, waitReadable } from "./abi/index.js";
|
|
14
|
+
|
|
15
|
+
const ready = init();
|
|
16
|
+
const post = (m, transfer = []) => self.postMessage(m, transfer);
|
|
17
|
+
const log = (level, text) => post({ type: "log", level, text });
|
|
18
|
+
let pod = null;
|
|
19
|
+
let stopping = false;
|
|
20
|
+
const pendingInbound = [];
|
|
21
|
+
const pendingPeers = [];
|
|
22
|
+
/** Other pods on the page LAN: peer id -> MessagePort to its net Worker (frames, both ways). */
|
|
23
|
+
const peers = new Map();
|
|
24
|
+
const tokenWaiters = new Map();
|
|
25
|
+
let nextToken = 0;
|
|
26
|
+
let wake = null;
|
|
27
|
+
|
|
28
|
+
/** Relay tokens come from the page (getToken() cannot cross to the Worker). */
|
|
29
|
+
function requestToken() {
|
|
30
|
+
const id = ++nextToken;
|
|
31
|
+
post({ type: "relay-token-request", id });
|
|
32
|
+
return new Promise((resolve, reject) => {
|
|
33
|
+
tokenWaiters.set(id, { resolve, reject });
|
|
34
|
+
setTimeout(() => {
|
|
35
|
+
if (tokenWaiters.delete(id)) reject(new Error("no relay token from the page"));
|
|
36
|
+
}, 30000);
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The CA (certificate + key) stays in this Worker: OPFS when a key name is given. */
|
|
41
|
+
async function loadCa(name) {
|
|
42
|
+
if (!name) return "";
|
|
43
|
+
try {
|
|
44
|
+
const dir = await (await navigator.storage.getDirectory()).getDirectoryHandle("webpod-net", { create: true });
|
|
45
|
+
const file = await (await dir.getFileHandle(`${name}.ca.pem`)).getFile();
|
|
46
|
+
return await file.text();
|
|
47
|
+
} catch {
|
|
48
|
+
return "";
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function saveCa(name, bundle) {
|
|
53
|
+
if (!name) return;
|
|
54
|
+
let error = null;
|
|
55
|
+
try {
|
|
56
|
+
const dir = await (await navigator.storage.getDirectory()).getDirectoryHandle("webpod-net", { create: true });
|
|
57
|
+
const h = await dir.getFileHandle(`${name}.ca.pem`, { create: true });
|
|
58
|
+
try {
|
|
59
|
+
const w = await h.createWritable();
|
|
60
|
+
try {
|
|
61
|
+
await w.write(bundle);
|
|
62
|
+
await w.close();
|
|
63
|
+
} catch (e) {
|
|
64
|
+
await w.abort().catch(() => {});
|
|
65
|
+
throw e;
|
|
66
|
+
}
|
|
67
|
+
} catch (e) {
|
|
68
|
+
// Older Safari has no createWritable; sync access handles work in Workers.
|
|
69
|
+
error = e;
|
|
70
|
+
const s = await h.createSyncAccessHandle();
|
|
71
|
+
try {
|
|
72
|
+
s.truncate(0);
|
|
73
|
+
s.write(new TextEncoder().encode(bundle), { at: 0 });
|
|
74
|
+
s.flush();
|
|
75
|
+
} finally {
|
|
76
|
+
s.close();
|
|
77
|
+
}
|
|
78
|
+
error = null;
|
|
79
|
+
}
|
|
80
|
+
} catch (e) {
|
|
81
|
+
error = e;
|
|
82
|
+
}
|
|
83
|
+
// WebKit can report a failure after the data was written: only what reads back counts.
|
|
84
|
+
if (error && (await loadCa(name)) !== bundle) {
|
|
85
|
+
log("warn", `CA not persisted (${error?.message ?? error}); a new one is generated next boot`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Without Atomics.waitAsync a guest frame is only noticed when the watchdog fires: keep it short.
|
|
90
|
+
const idleWatchdogMs = typeof Atomics.waitAsync === "function" ? 50 : 4;
|
|
91
|
+
|
|
92
|
+
// One channel for every yield: WebKit slows down all MessagePort traffic (pod.fetch, peers) as
|
|
93
|
+
// channels pile up, and the pump yields hundreds of times a second.
|
|
94
|
+
const yieldChannel = new MessageChannel();
|
|
95
|
+
const yielding = [];
|
|
96
|
+
yieldChannel.port1.onmessage = () => yielding.shift()?.();
|
|
97
|
+
const yieldNow = () => new Promise((r) => {
|
|
98
|
+
yielding.push(r);
|
|
99
|
+
yieldChannel.port2.postMessage(null);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Moves frames and runs the stack. While anything moves it polls again immediately (several
|
|
104
|
+
* rounds per macrotask, yielding through MessageChannel so timers are not clamped); when idle it
|
|
105
|
+
* sleeps until a frame arrives, an egress completion or page command notifies, or the stack's
|
|
106
|
+
* next timer is due.
|
|
107
|
+
*/
|
|
108
|
+
async function pump(memory, fromEngine, toEngine) {
|
|
109
|
+
const rx = new RingConsumer(memory, fromEngine);
|
|
110
|
+
const tx = new RingProducer(memory, toEngine);
|
|
111
|
+
let rounds = 0;
|
|
112
|
+
try {
|
|
113
|
+
while (!stopping) {
|
|
114
|
+
const batch = rx.drain(256);
|
|
115
|
+
for (const f of batch) pod.push(f);
|
|
116
|
+
const now = performance.now();
|
|
117
|
+
const active = pod.poll(now);
|
|
118
|
+
const out = pod.take();
|
|
119
|
+
for (const f of out) if (!tx.tryPush(f)) await tx.pushAsync(f);
|
|
120
|
+
for (const [id, f] of pod.take_forwarded()) peers.get(id)?.postMessage(f, [f.buffer]);
|
|
121
|
+
if (batch.length || out.length || active) {
|
|
122
|
+
if (++rounds % 16 === 0) await yieldNow();
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
rounds = 0;
|
|
126
|
+
const d = pod.delay(performance.now());
|
|
127
|
+
const ctl = new AbortController();
|
|
128
|
+
wake = () => ctl.abort();
|
|
129
|
+
const timer = d >= 0 ? setTimeout(() => ctl.abort(), Math.max(0, Math.min(d, 1000))) : null;
|
|
130
|
+
await waitReadable(rx, { signal: ctl.signal, watchdogMs: idleWatchdogMs });
|
|
131
|
+
if (timer) clearTimeout(timer);
|
|
132
|
+
wake = null;
|
|
133
|
+
}
|
|
134
|
+
} catch (e) {
|
|
135
|
+
if (!stopping) post({ type: "error", message: `net: ${e?.message ?? e}` });
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function onAttach(m) {
|
|
140
|
+
await ready;
|
|
141
|
+
set_logger((level, text) => log(level, text), m.logLevel ?? null);
|
|
142
|
+
const network = m.network ?? {};
|
|
143
|
+
const bundle = await loadCa(m.caKey);
|
|
144
|
+
pod = new NetPod(network, bundle, requestToken, Date.now() / 1000);
|
|
145
|
+
if (!bundle) await saveCa(m.caKey, pod.ca_bundle());
|
|
146
|
+
pod.set_notify(() => wake?.());
|
|
147
|
+
setInterval(() => pod?.set_unix_time(Date.now() / 1000), 60_000);
|
|
148
|
+
for (const p of pendingInbound.splice(0)) pod.open_inbound(p);
|
|
149
|
+
for (const p of pendingPeers.splice(0)) addPeer(p);
|
|
150
|
+
post({ type: "ready" });
|
|
151
|
+
pump(m.memory, m.fromEngine, m.toEngine);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function addPeer(m) {
|
|
155
|
+
peers.get(m.id)?.close();
|
|
156
|
+
peers.set(m.id, m.port);
|
|
157
|
+
m.port.onmessage = ({ data }) => {
|
|
158
|
+
pod?.push_forwarded(data);
|
|
159
|
+
wake?.();
|
|
160
|
+
};
|
|
161
|
+
pod.add_peer(m.id, m.hostname, m.index);
|
|
162
|
+
post({ type: "peer-added", id: m.id });
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
self.onmessage = async ({ data: m }) => {
|
|
166
|
+
try {
|
|
167
|
+
switch (m.type) {
|
|
168
|
+
case "attach":
|
|
169
|
+
await onAttach(m);
|
|
170
|
+
break;
|
|
171
|
+
case "inbound":
|
|
172
|
+
if (pod) {
|
|
173
|
+
pod.open_inbound(m.port);
|
|
174
|
+
wake?.();
|
|
175
|
+
} else pendingInbound.push(m.port);
|
|
176
|
+
break;
|
|
177
|
+
case "peer":
|
|
178
|
+
if (pod) addPeer(m);
|
|
179
|
+
else pendingPeers.push(m);
|
|
180
|
+
break;
|
|
181
|
+
case "peer-gone":
|
|
182
|
+
peers.get(m.id)?.close();
|
|
183
|
+
peers.delete(m.id);
|
|
184
|
+
pod?.remove_peer(m.id);
|
|
185
|
+
break;
|
|
186
|
+
case "stats":
|
|
187
|
+
// at: when this Worker handled the request (wall clock), to tell queueing here from the page's.
|
|
188
|
+
post({ type: "stats", stats: pod ? { ...pod.stats(), peerPorts: peers.size, pendingInbound: pendingInbound.length, at: performance.timeOrigin + performance.now() } : null });
|
|
189
|
+
break;
|
|
190
|
+
case "ca":
|
|
191
|
+
await ready;
|
|
192
|
+
post({ type: "ca", pem: pod ? pod.ca_certificate() : "" });
|
|
193
|
+
break;
|
|
194
|
+
case "relay-token": {
|
|
195
|
+
const w = tokenWaiters.get(m.id);
|
|
196
|
+
if (!w) break;
|
|
197
|
+
tokenWaiters.delete(m.id);
|
|
198
|
+
if (typeof m.token === "string") w.resolve(m.token);
|
|
199
|
+
else w.reject(new Error(m.error ?? "no token"));
|
|
200
|
+
break;
|
|
201
|
+
}
|
|
202
|
+
case "stop":
|
|
203
|
+
stopping = true;
|
|
204
|
+
wake?.();
|
|
205
|
+
// The ring waits have no timeout: settle them before the host terminates this Worker.
|
|
206
|
+
await settleWaits();
|
|
207
|
+
post({ type: "stopped" });
|
|
208
|
+
break;
|
|
209
|
+
}
|
|
210
|
+
} catch (e) {
|
|
211
|
+
post({ type: "error", message: String(e?.message ?? e) });
|
|
212
|
+
}
|
|
213
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpodjs/net-worker",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Net Worker for webpod: the guest's gateway (webpod-net NetStack), browser egress and page connections",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"webpod",
|
|
7
|
+
"network",
|
|
8
|
+
"tcp-ip",
|
|
9
|
+
"worker"
|
|
10
|
+
],
|
|
11
|
+
"license": "Apache-2.0",
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "git+https://github.com/mirrorange/webpod.git",
|
|
15
|
+
"directory": "packages/net-worker"
|
|
16
|
+
},
|
|
17
|
+
"homepage": "https://github.com/mirrorange/webpod/tree/main/packages/net-worker#readme",
|
|
18
|
+
"bugs": "https://github.com/mirrorange/webpod/issues",
|
|
19
|
+
"type": "module",
|
|
20
|
+
"exports": {
|
|
21
|
+
"./worker.js": "./dist/worker.js",
|
|
22
|
+
"./dist/*": "./dist/*",
|
|
23
|
+
"./package.json": "./package.json"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"dist"
|
|
27
|
+
],
|
|
28
|
+
"publishConfig": {
|
|
29
|
+
"access": "public"
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build:wasm": "sh build.sh"
|
|
33
|
+
}
|
|
34
|
+
}
|