@webpodjs/net-worker 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +175 -2
- package/dist/abi/index.js +3 -0
- package/dist/abi/ring.js +317 -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 +211 -0
- package/package.json +32 -4
package/README.md
CHANGED
|
@@ -1,3 +1,176 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @webpodjs/net-worker
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The guest NIC's gateway, as a dedicated module Worker (docs/host-engine.md §4): it consumes the
|
|
4
|
+
guest's Ethernet frames from the engine's `fromEngine` ring, runs webpod-net's `NetStack` and
|
|
5
|
+
produces frames into `toEngine`.
|
|
6
|
+
|
|
7
|
+
- **Gateway** 192.168.127.1/24: DHCP (the guest gets 192.168.127.2, router and DNS = gateway, MTU
|
|
8
|
+
option 26), DNS answering fake IPs (198.18.0.0/16, stable per name for the pod's lifetime; AAAA
|
|
9
|
+
gets an empty answer).
|
|
10
|
+
- **Egress** (no proxy variables needed): HTTP/1.1 is proxied transparently through `fetch()`,
|
|
11
|
+
HTTPS too after TLS interception with the pod CA, WebSocket upgrades through the browser's
|
|
12
|
+
`WebSocket`; optionally a CORS proxy (docs/cors-proxy-protocol.md) and an L4 relay for raw TCP
|
|
13
|
+
(docs/relay-protocol.md).
|
|
14
|
+
- **Inbound**: page connections (`pod.fetch`, `pod.net.connect`, `pod.net.expose` previews)
|
|
15
|
+
arrive as `inbound` MessagePorts and become TCP connections to the guest.
|
|
16
|
+
|
|
17
|
+
`crates/webpod-net-wasm` is the wasm module (`NetPod`); `src/worker.js` moves frames and runs it.
|
|
18
|
+
|
|
19
|
+
## Build
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
sh build.sh # dist/: worker.js, pkg/ (wasm-bindgen), abi/ (ring)
|
|
23
|
+
PROFILE=dev sh build.sh
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Needs the `wasm32-unknown-unknown` target, clang with the wasm32 target (ring) and
|
|
27
|
+
wasm-bindgen-cli matching Cargo.lock. `npm run build` at the repository root does not run it (no
|
|
28
|
+
Rust toolchain assumed), so after changing `crates/webpod-net*` or `src/worker.js` run `sh build.sh`
|
|
29
|
+
again, or `dist/` keeps the old Worker. Serve `dist/` next to the page. The rings live in the
|
|
30
|
+
engine's `SharedArrayBuffer`, so the page must be cross-origin isolated, and the Worker script must
|
|
31
|
+
be served with `Cross-Origin-Embedder-Policy: require-corp` too (or through the SDK's
|
|
32
|
+
`coi-serviceworker.js`).
|
|
33
|
+
|
|
34
|
+
## Use
|
|
35
|
+
|
|
36
|
+
```js
|
|
37
|
+
import { Pod, netWorker } from "@webpodjs/sdk";
|
|
38
|
+
|
|
39
|
+
const pod = await Pod.boot({
|
|
40
|
+
persist: "my-pod", // also keys the pod CA in OPFS
|
|
41
|
+
engine: { manifestUrl, net: netWorker("/net-worker/worker.js"), fs },
|
|
42
|
+
network: {
|
|
43
|
+
corsProxy: { url: "https://cors.example/", token },
|
|
44
|
+
relay: { url: "wss://relay.example/v1/connect", getToken: () => fetch("/api/relay-token").then((r) => r.text()) },
|
|
45
|
+
routes: [
|
|
46
|
+
{ host: "*.pypi.org", via: "cors-proxy" },
|
|
47
|
+
{ host: "db.internal", ports: 5432, via: "relay" },
|
|
48
|
+
{ host: "10.0.0.0/8", via: "deny" },
|
|
49
|
+
],
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
The SDK passes `network` to the Worker before the engine attaches the NIC, and installs the pod CA
|
|
55
|
+
in the guest (the agent's `caCertificate`), so `curl https://...`, pip, npm and git trust TLS
|
|
56
|
+
interception without flags.
|
|
57
|
+
|
|
58
|
+
### Network options (`NetworkOptions`)
|
|
59
|
+
|
|
60
|
+
| Field | Meaning |
|
|
61
|
+
|---|---|
|
|
62
|
+
| `mode` | `"browser"` (default) or `"none"`: HTTP, HTTPS and WebSocket are denied unless a route allows them; no relay default |
|
|
63
|
+
| `corsProxy` | URL or `{ url, token? }` of a webpod CORS proxy, for `via: "cors-proxy"` routes |
|
|
64
|
+
| `relay` | `{ url, token? , getToken? }`: an L4 relay; raw TCP goes through it by default. `getToken()` runs in the page and is called for each relay connection (also after the relay rejects an expired token) |
|
|
65
|
+
| `routes` | `[{ host?, ports?, protocol?, via, stripHeaders? }]`, first match wins. `host`: `example.com`, `*.example.com`, `10.0.0.0/8` or `*`; `ports`: one port or `[lo, hi]`; `protocol`: `http`, `tls`, `websocket`, `tcp`, `udp`; `via`: `fetch`, `websocket`, `cors-proxy`, `relay`, `deny`. `stripHeaders: "non-safelisted"` (with `via: "fetch"`): only CORS-safelisted request headers, so no preflight (registry.npmjs.org refuses preflights); all others, `Authorization` too, are dropped |
|
|
66
|
+
| `lan`, `hostname` | join the page LAN of that name (see below); `lan: { name, allow }` limits what this guest may open connections to |
|
|
67
|
+
| `mtu` | link MTU, default 65520 like the QEMU-Wasm engine's virtio-net `host_mtu` (both must match; large frames are about 3x faster than 1500 under TCG) |
|
|
68
|
+
|
|
69
|
+
Defaults after the routes: the public npm and PyPI registries (`registry.npmjs.org`,
|
|
70
|
+
`registry.yarnpkg.com`, `pypi.org`, `files.pythonhosted.org`) through `fetch()` with
|
|
71
|
+
`stripHeaders: "non-safelisted"` (they send CORS headers but refuse the preflights that npm's and
|
|
72
|
+
pip's own headers trigger, so public packages install without a CORS proxy; for private packages
|
|
73
|
+
or `npm publish`, which need `Authorization`, route the registry through the CORS proxy), HTTP
|
|
74
|
+
and intercepted HTTPS through `fetch()`, WebSocket through the browser, raw TCP and UDP through
|
|
75
|
+
the relay if one is configured (otherwise TCP is reset and UDP answered with ICMP port
|
|
76
|
+
unreachable). `mode: "none"` drops all of these. DHCP and DNS are answered by the gateway itself: queries to
|
|
77
|
+
any server on port 53 get fake IPs unless a rule routes them (`{ host: "8.8.8.8", ports: 53,
|
|
78
|
+
protocol: "udp", via: "relay" }`). Relayed UDP is one relay stream per guest 4-tuple, one DATA frame
|
|
79
|
+
per datagram, closed after 60 s idle; the Cloudflare relay refuses UDP. A `tls` route to the relay
|
|
80
|
+
tunnels HTTPS end to end instead of intercepting it.
|
|
81
|
+
|
|
82
|
+
## Messages
|
|
83
|
+
|
|
84
|
+
Host -> Worker:
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
{ type: "attach", memory: SharedArrayBuffer, toEngine: number, fromEngine: number, mac?: string,
|
|
88
|
+
network?: object /* workerNetworkConfig(NetworkOptions): no functions */, caKey?: string | null,
|
|
89
|
+
logLevel?: "error" | "warn" | "info" | "debug" | "trace" /* default warn */ }
|
|
90
|
+
{ type: "inbound", port: MessagePort } // transferred; docs: packages/sdk/src/net/protocol.ts
|
|
91
|
+
{ type: "ca" }
|
|
92
|
+
{ type: "relay-token", id: number, token?: string, error?: string }
|
|
93
|
+
{ type: "peer", id: number, hostname: string, index: number, port: MessagePort } // transferred
|
|
94
|
+
{ type: "peer-gone", id: number }
|
|
95
|
+
{ type: "stats" }
|
|
96
|
+
{ type: "stop" }
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Worker -> host:
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
{ type: "ready" } // after attach
|
|
103
|
+
{ type: "ca", pem: string } // the CA certificate only ("" before attach)
|
|
104
|
+
{ type: "relay-token-request", id: number } // answered by the SDK with network.relay.getToken()
|
|
105
|
+
{ type: "peer-added", id: number } // the route to that peer is in place
|
|
106
|
+
{ type: "stats", stats: Stats | null } // null before attach
|
|
107
|
+
{ type: "stopped" }
|
|
108
|
+
{ type: "log", level: string, text: string } | { type: "error", message: string }
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
`netWorker()` in the SDK implements the host side, including the token round trip (a function
|
|
112
|
+
cannot be sent to a Worker). Without an `onLog` it prints warnings and errors with
|
|
113
|
+
`console.warn`: a failed `fetch()` is logged with the request's method and origin (the guest only
|
|
114
|
+
gets a 502 whose status line and body carry the reason, and browsers do not say why a fetch
|
|
115
|
+
failed).
|
|
116
|
+
|
|
117
|
+
### Stats
|
|
118
|
+
|
|
119
|
+
`stats` (`netWorker().stats()` in the SDK) returns the Worker's gauges, for soak tests, leak
|
|
120
|
+
hunting and diagnostics panels. Connection gauges drop back to 0 when traffic stops:
|
|
121
|
+
|
|
122
|
+
| Field | Meaning |
|
|
123
|
+
|---|---|
|
|
124
|
+
| `tcpFlows` | guest TCP connections the gateway terminates (all kinds) |
|
|
125
|
+
| `httpExchanges`, `websockets`, `streams`, `udpFlows` | HTTP exchanges in flight, proxied WebSockets, raw relay streams, guest UDP flows through relays |
|
|
126
|
+
| `inbound`, `pageConnections` | page connections to the guest (`pod.fetch`, previews, `pod.net.connect`) in the stack, and their MessagePorts |
|
|
127
|
+
| `sockets`, `orphans` | smoltcp sockets (listeners and the DNS / DHCP sockets included), aborted ones waiting for their RST |
|
|
128
|
+
| `buffered` | bytes held in connection buffers (both directions) |
|
|
129
|
+
| `queuedFrames` | frames queued in the gateway and the Worker (from and to the guest, for peers) |
|
|
130
|
+
| `fetches`, `egressWebsockets`, `queuedCompletions` | `fetch()` calls in flight, browser WebSockets, egress results not yet applied |
|
|
131
|
+
| `relayConnections`, `relayStreams` | WebSockets to relays, streams on them |
|
|
132
|
+
| `fakeIps`, `peers`, `peerPorts`, `pendingInbound` | names holding a fake IP, LAN peers in the stack and their ports, inbound ports waiting for attach |
|
|
133
|
+
| `wasmMemory` | bytes of wasm memory (it never shrinks) |
|
|
134
|
+
| `at` | when the Worker handled the request (`performance.timeOrigin + performance.now()`) |
|
|
135
|
+
|
|
136
|
+
## Page LAN (NET-506)
|
|
137
|
+
|
|
138
|
+
Pods of one page with the same `network.lan` name form a LAN: `curl http://pod-b:8000` from one
|
|
139
|
+
guest reaches another, over any protocol (TCP, UDP, ICMP), with real source addresses.
|
|
140
|
+
|
|
141
|
+
- **Addresses**: each member's link is a /26 in 198.19.0.0/16 (the upper half of the benchmarking
|
|
142
|
+
range, unused by real networks; fake IPs come from 198.18.0.0/16), picked by a hash of its
|
|
143
|
+
`hostname` (`lanIndex()` in the SDK; the next free one on a collision), so it is the same after a
|
|
144
|
+
reboot or a snapshot restore. The guest gets it by DHCP (gateway .1, guest .2). Pods without
|
|
145
|
+
`lan` keep 192.168.127.0/24.
|
|
146
|
+
- **Names**: every member's DNS answers the other members' host names with their real addresses.
|
|
147
|
+
- **Forwarding**: the gateway routes frames for another member's link at L3 (MAC rewrite,
|
|
148
|
+
TTL - 1) instead of terminating them, and hands them to that member's net Worker over a
|
|
149
|
+
`MessageChannel`: the SDK connects every pair of members' Workers when they attach (`peer`) and
|
|
150
|
+
disconnects them on dispose (`peer-gone`). Frames never pass through the page's main thread.
|
|
151
|
+
- **Allow list**: `lan: { name, allow: ["pod-b:8000", "db:5432-5433", "*:22", "cache"] }` limits the
|
|
152
|
+
connections this guest may open (TCP SYNs get a RST, other packets are dropped); `[]` allows
|
|
153
|
+
none. Replies within connections other members opened always pass, so isolating an untrusted
|
|
154
|
+
pod only needs its own list.
|
|
155
|
+
|
|
156
|
+
## The pod CA
|
|
157
|
+
|
|
158
|
+
Generated on first attach (P-256, valid 10 years) and kept **inside the Worker**: with a `caKey` it
|
|
159
|
+
is saved as `webpod-net/<caKey>.ca.pem` in the Worker's OPFS and reloaded next boot, so the
|
|
160
|
+
fingerprint, and every trust store the guest already wrote, survive reboots (NET-227). The page
|
|
161
|
+
only ever receives the certificate (`ca` message, NET-228). Without OPFS (e.g. WebKit with a
|
|
162
|
+
temporary profile) a new CA is generated each boot and a warning is logged.
|
|
163
|
+
|
|
164
|
+
## Scheduling
|
|
165
|
+
|
|
166
|
+
While frames or egress data move, the Worker polls again immediately, yielding through one reused
|
|
167
|
+
`MessageChannel` every 16 rounds (timers are clamped to 4 ms; a new channel per yield piles up in
|
|
168
|
+
WebKit, which then slows down every MessagePort, `pod.fetch` included). When idle it sleeps until a guest
|
|
169
|
+
frame arrives (`Atomics.waitAsync` on the ring, 50 ms watchdog; 4 ms without `waitAsync`), an
|
|
170
|
+
egress completion or page command notifies it, or the stack's next TCP timer is due.
|
|
171
|
+
|
|
172
|
+
## Tests
|
|
173
|
+
|
|
174
|
+
`bench/net/www/networker.html` attaches this Worker with the SDK's `netWorker()` to a simulated
|
|
175
|
+
guest over real rings: DHCP, DNS, every egress case, CA persistence, pod.fetch / pod.net.connect /
|
|
176
|
+
previews, and the relay token flow. `node bench/net/run-playwright.mjs <browser> networker`.
|
package/dist/abi/ring.js
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
// SPSC message ring over a SharedArrayBuffer, byte-compatible with webpod_abi::ring (docs/abi.md).
|
|
2
|
+
// Source of truth for every TS user (engine Worker, host Workers, SDK); the SDK build copies it.
|
|
3
|
+
export const RING_MAGIC = 0x47525057; // "WPRG"
|
|
4
|
+
export const RING_VERSION = 1;
|
|
5
|
+
export const RING_HEADER_SIZE = 256;
|
|
6
|
+
const HEAD = 64 / 4;
|
|
7
|
+
const TAIL = 128 / 4;
|
|
8
|
+
const CONSUMER_WAITING = 192 / 4;
|
|
9
|
+
const PRODUCER_WAITING = 196 / 4;
|
|
10
|
+
const PAD = 0xffffffff;
|
|
11
|
+
const MIN_CAPACITY = 64;
|
|
12
|
+
const MAX_CAPACITY = 1 << 30;
|
|
13
|
+
export class RingError extends Error {
|
|
14
|
+
kind;
|
|
15
|
+
constructor(kind, message) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.kind = kind;
|
|
18
|
+
this.name = "RingError";
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const padded = (len) => (len + 3) & ~3;
|
|
22
|
+
/** Formats a ring with `capacity` data bytes (power of two, 64 B .. 1 GiB) at `byteOffset`. */
|
|
23
|
+
export function initRing(buffer, byteOffset, capacity) {
|
|
24
|
+
if (capacity < MIN_CAPACITY || capacity > MAX_CAPACITY || (capacity & (capacity - 1)) !== 0) {
|
|
25
|
+
throw new RingError("bad-header", `bad ring capacity ${capacity}`);
|
|
26
|
+
}
|
|
27
|
+
if (byteOffset % 64 !== 0 || byteOffset + RING_HEADER_SIZE + capacity > buffer.byteLength) {
|
|
28
|
+
throw new RingError("bad-header", "ring region is misaligned or too small");
|
|
29
|
+
}
|
|
30
|
+
const words = new Int32Array(buffer, byteOffset, RING_HEADER_SIZE / 4);
|
|
31
|
+
for (let i = 0; i < words.length; i++)
|
|
32
|
+
Atomics.store(words, i, 0);
|
|
33
|
+
Atomics.store(words, 2, capacity);
|
|
34
|
+
Atomics.store(words, 1, RING_VERSION);
|
|
35
|
+
Atomics.store(words, 0, RING_MAGIC | 0);
|
|
36
|
+
}
|
|
37
|
+
/** Allocates a SharedArrayBuffer holding one formatted ring (tests, host-owned rings). */
|
|
38
|
+
export function createRing(capacity) {
|
|
39
|
+
const sab = new SharedArrayBuffer(RING_HEADER_SIZE + capacity);
|
|
40
|
+
initRing(sab, 0, capacity);
|
|
41
|
+
return sab;
|
|
42
|
+
}
|
|
43
|
+
class RingView {
|
|
44
|
+
buffer;
|
|
45
|
+
words;
|
|
46
|
+
data;
|
|
47
|
+
view;
|
|
48
|
+
capacity;
|
|
49
|
+
constructor(buffer, byteOffset) {
|
|
50
|
+
this.buffer = buffer;
|
|
51
|
+
if (byteOffset % 64 !== 0)
|
|
52
|
+
throw new RingError("bad-header", "ring region is not 64-byte aligned");
|
|
53
|
+
if (buffer.byteLength < byteOffset + RING_HEADER_SIZE)
|
|
54
|
+
throw new RingError("bad-header", "ring region is too small");
|
|
55
|
+
this.words = new Int32Array(buffer, byteOffset, RING_HEADER_SIZE / 4);
|
|
56
|
+
const magic = Atomics.load(this.words, 0) >>> 0;
|
|
57
|
+
if (magic !== RING_MAGIC)
|
|
58
|
+
throw new RingError("bad-header", `bad ring magic 0x${magic.toString(16)}`);
|
|
59
|
+
const version = Atomics.load(this.words, 1);
|
|
60
|
+
if (version !== RING_VERSION)
|
|
61
|
+
throw new RingError("bad-header", `unsupported ring version ${version}`);
|
|
62
|
+
const capacity = Atomics.load(this.words, 2) >>> 0;
|
|
63
|
+
if (capacity < MIN_CAPACITY || capacity > MAX_CAPACITY || (capacity & (capacity - 1)) !== 0) {
|
|
64
|
+
throw new RingError("bad-header", `bad ring capacity ${capacity}`);
|
|
65
|
+
}
|
|
66
|
+
if (buffer.byteLength < byteOffset + RING_HEADER_SIZE + capacity)
|
|
67
|
+
throw new RingError("bad-header", "ring region is too small");
|
|
68
|
+
this.capacity = capacity;
|
|
69
|
+
this.data = new Uint8Array(buffer, byteOffset + RING_HEADER_SIZE, capacity);
|
|
70
|
+
this.view = new DataView(buffer, byteOffset + RING_HEADER_SIZE, capacity);
|
|
71
|
+
}
|
|
72
|
+
get maxMessageLen() {
|
|
73
|
+
return this.capacity / 2 - 4;
|
|
74
|
+
}
|
|
75
|
+
head() {
|
|
76
|
+
return Atomics.load(this.words, HEAD) >>> 0;
|
|
77
|
+
}
|
|
78
|
+
tail() {
|
|
79
|
+
return Atomics.load(this.words, TAIL) >>> 0;
|
|
80
|
+
}
|
|
81
|
+
off(pos) {
|
|
82
|
+
return pos & (this.capacity - 1);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** Producer half. Only one producer may exist per ring. */
|
|
86
|
+
export class RingProducer {
|
|
87
|
+
#r;
|
|
88
|
+
#head;
|
|
89
|
+
/** The tail read by the last reload in #fit(); waitTarget() must wait on this value, not a fresh one. */
|
|
90
|
+
#seenTail = 0;
|
|
91
|
+
/** Attaches to a formatted ring at `byteOffset` (e.g. inside the engine's wasm memory). */
|
|
92
|
+
constructor(buffer, byteOffset = 0) {
|
|
93
|
+
this.#r = new RingView(buffer, byteOffset);
|
|
94
|
+
this.#head = this.#r.head();
|
|
95
|
+
this.#seenTail = this.#r.tail();
|
|
96
|
+
}
|
|
97
|
+
get maxMessageLen() {
|
|
98
|
+
return this.#r.maxMessageLen;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Room for a `len`-byte message: the skip to the start (0 if none), or -1 when full. Uses the
|
|
102
|
+
* cached tail while it shows enough room (tail only grows, so the cache can only under-report
|
|
103
|
+
* free space) and reloads it otherwise, or always when `fresh` (prepareWait).
|
|
104
|
+
*/
|
|
105
|
+
#fit(len, fresh = false) {
|
|
106
|
+
const r = this.#r;
|
|
107
|
+
if (len > r.maxMessageLen)
|
|
108
|
+
throw new RingError("too-large", `message of ${len} bytes does not fit the ring`);
|
|
109
|
+
if (!fresh) {
|
|
110
|
+
const record = 4 + padded(len);
|
|
111
|
+
const toEnd = r.capacity - r.off(this.#head);
|
|
112
|
+
const skip = toEnd < record ? toEnd : 0;
|
|
113
|
+
if (skip + record <= r.capacity - ((this.#head - this.#seenTail) >>> 0))
|
|
114
|
+
return skip;
|
|
115
|
+
}
|
|
116
|
+
const tail = r.tail();
|
|
117
|
+
this.#seenTail = tail;
|
|
118
|
+
const used = (this.#head - tail) >>> 0;
|
|
119
|
+
if (used > r.capacity || tail % 4 !== 0)
|
|
120
|
+
throw new RingError("corrupt", "ring corrupted by peer");
|
|
121
|
+
const record = 4 + padded(len);
|
|
122
|
+
const toEnd = r.capacity - r.off(this.#head);
|
|
123
|
+
const skip = toEnd < record ? toEnd : 0;
|
|
124
|
+
return skip + record > r.capacity - used ? -1 : skip;
|
|
125
|
+
}
|
|
126
|
+
/** Pushes `msg`, waiting (without blocking the thread) while the ring is full. */
|
|
127
|
+
async pushAsync(msg, options = {}) {
|
|
128
|
+
while (!this.tryPush(msg))
|
|
129
|
+
await waitWritable(this, msg.length, options);
|
|
130
|
+
}
|
|
131
|
+
/** Pushes one message; false when the ring is full. Wakes a sleeping consumer. */
|
|
132
|
+
tryPush(msg) {
|
|
133
|
+
const skip = this.#fit(msg.length);
|
|
134
|
+
if (skip < 0)
|
|
135
|
+
return false;
|
|
136
|
+
const r = this.#r;
|
|
137
|
+
if (skip > 0)
|
|
138
|
+
r.view.setUint32(r.off(this.#head), PAD, true);
|
|
139
|
+
const start = (this.#head + skip) >>> 0;
|
|
140
|
+
r.data.set(msg, r.off(start) + 4);
|
|
141
|
+
r.view.setUint32(r.off(start), msg.length, true);
|
|
142
|
+
this.#head = (start + 4 + padded(msg.length)) >>> 0;
|
|
143
|
+
Atomics.store(r.words, HEAD, this.#head | 0);
|
|
144
|
+
// Plain load first: the exchange (a write to the flag line both sides use) only when set.
|
|
145
|
+
if (Atomics.load(r.words, CONSUMER_WAITING) !== 0 && Atomics.exchange(r.words, CONSUMER_WAITING, 0) !== 0) {
|
|
146
|
+
Atomics.notify(r.words, HEAD);
|
|
147
|
+
}
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
/** Announces that the producer will sleep until `len` bytes fit; false if they already do. */
|
|
151
|
+
prepareWait(len) {
|
|
152
|
+
Atomics.store(this.#r.words, PRODUCER_WAITING, 1);
|
|
153
|
+
if (this.#fit(len, true) >= 0) {
|
|
154
|
+
Atomics.store(this.#r.words, PRODUCER_WAITING, 0);
|
|
155
|
+
return false;
|
|
156
|
+
}
|
|
157
|
+
return true;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* The word and value to wait on after a successful prepareWait: the tail that prepareWait saw
|
|
161
|
+
* the ring full at. Re-reading tail here would lose the wake-up when the consumer frees space
|
|
162
|
+
* in between (it clears producer_waiting and notifies before we sleep, then never again).
|
|
163
|
+
*/
|
|
164
|
+
waitTarget() {
|
|
165
|
+
return [this.#r.words, TAIL, this.#seenTail | 0];
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/** Consumer half. Only one consumer may exist per ring. */
|
|
169
|
+
export class RingConsumer {
|
|
170
|
+
#r;
|
|
171
|
+
#tail;
|
|
172
|
+
/** Last head read from shared memory; reloaded only when it shows the ring empty. */
|
|
173
|
+
#seenHead;
|
|
174
|
+
constructor(buffer, byteOffset = 0) {
|
|
175
|
+
this.#r = new RingView(buffer, byteOffset);
|
|
176
|
+
this.#tail = this.#r.tail();
|
|
177
|
+
this.#seenHead = this.#tail;
|
|
178
|
+
}
|
|
179
|
+
hasMessages() {
|
|
180
|
+
return this.#r.head() !== this.#tail;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* The next message without copying, or null when empty. `bytes` views shared memory and is valid
|
|
184
|
+
* until `release()`, which consumes it and wakes a waiting producer (returns whether it did).
|
|
185
|
+
* Not releasing leaves the message in place: the next peek returns it again.
|
|
186
|
+
*
|
|
187
|
+
* head is cached and reloaded (and validated) only when the cached value shows the ring empty,
|
|
188
|
+
* so a producer that corrupts head is detected at that reload rather than on the very next peek.
|
|
189
|
+
* Records are validated either way, so a corrupt peer can never cause an out-of-bounds access.
|
|
190
|
+
*/
|
|
191
|
+
peek() {
|
|
192
|
+
const r = this.#r;
|
|
193
|
+
const cap = r.capacity;
|
|
194
|
+
let tail = this.#tail;
|
|
195
|
+
let avail = (this.#seenHead - tail) >>> 0;
|
|
196
|
+
if (avail === 0) {
|
|
197
|
+
this.#seenHead = r.head();
|
|
198
|
+
avail = (this.#seenHead - tail) >>> 0;
|
|
199
|
+
if (avail === 0)
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
if (avail > cap || avail % 4 !== 0)
|
|
203
|
+
throw new RingError("corrupt", "ring corrupted by peer");
|
|
204
|
+
let len = r.view.getUint32(r.off(tail), true);
|
|
205
|
+
if (len === PAD) {
|
|
206
|
+
const skip = cap - r.off(tail);
|
|
207
|
+
if (skip >= avail)
|
|
208
|
+
throw new RingError("corrupt", "ring corrupted by peer");
|
|
209
|
+
tail = (tail + skip) >>> 0;
|
|
210
|
+
avail -= skip;
|
|
211
|
+
len = r.view.getUint32(r.off(tail), true);
|
|
212
|
+
}
|
|
213
|
+
if (len > cap / 2 - 4)
|
|
214
|
+
throw new RingError("corrupt", "ring corrupted by peer");
|
|
215
|
+
const record = 4 + padded(len);
|
|
216
|
+
if (record > avail || r.off(tail) + record > cap)
|
|
217
|
+
throw new RingError("corrupt", "ring corrupted by peer");
|
|
218
|
+
const start = r.off(tail) + 4;
|
|
219
|
+
const next = (tail + record) >>> 0;
|
|
220
|
+
const expected = this.#tail;
|
|
221
|
+
return {
|
|
222
|
+
bytes: r.data.subarray(start, start + len),
|
|
223
|
+
release: () => {
|
|
224
|
+
if (this.#tail !== expected)
|
|
225
|
+
throw new RingError("corrupt", "message released twice or out of order");
|
|
226
|
+
this.#tail = next;
|
|
227
|
+
Atomics.store(r.words, TAIL, next | 0);
|
|
228
|
+
// Plain load first: the exchange (a write to the flag line both sides use) only when set.
|
|
229
|
+
if (Atomics.load(r.words, PRODUCER_WAITING) === 0 || Atomics.exchange(r.words, PRODUCER_WAITING, 0) === 0) {
|
|
230
|
+
return false;
|
|
231
|
+
}
|
|
232
|
+
Atomics.notify(r.words, TAIL);
|
|
233
|
+
return true;
|
|
234
|
+
},
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
/** Pops (copies and releases) the next message, or null when empty. Wakes a waiting producer. */
|
|
238
|
+
tryPop() {
|
|
239
|
+
const m = this.peek();
|
|
240
|
+
if (!m)
|
|
241
|
+
return null;
|
|
242
|
+
const copy = m.bytes.slice();
|
|
243
|
+
m.release();
|
|
244
|
+
return copy;
|
|
245
|
+
}
|
|
246
|
+
/** Alias of `tryPop` (webpod_abi naming). */
|
|
247
|
+
pop() {
|
|
248
|
+
return this.tryPop();
|
|
249
|
+
}
|
|
250
|
+
/** Pops everything currently in the ring. */
|
|
251
|
+
drain(max = Infinity) {
|
|
252
|
+
const out = [];
|
|
253
|
+
for (let m = out.length < max ? this.tryPop() : null; m; m = out.length < max ? this.tryPop() : null)
|
|
254
|
+
out.push(m);
|
|
255
|
+
return out;
|
|
256
|
+
}
|
|
257
|
+
/** Announces that the consumer will sleep; false if messages arrived meanwhile. */
|
|
258
|
+
prepareWait() {
|
|
259
|
+
Atomics.store(this.#r.words, CONSUMER_WAITING, 1);
|
|
260
|
+
if (this.hasMessages()) {
|
|
261
|
+
Atomics.store(this.#r.words, CONSUMER_WAITING, 0);
|
|
262
|
+
return false;
|
|
263
|
+
}
|
|
264
|
+
return true;
|
|
265
|
+
}
|
|
266
|
+
waitTarget() {
|
|
267
|
+
return [this.#r.words, HEAD, this.#tail | 0];
|
|
268
|
+
}
|
|
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. */
|
|
272
|
+
async function waitWord(words, index, value, options) {
|
|
273
|
+
const ms = options.watchdogMs ?? 50;
|
|
274
|
+
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);
|
|
281
|
+
if (typeof waitAsync === "function") {
|
|
282
|
+
const res = waitAsync(words, index, value, ms);
|
|
283
|
+
if (!res.async)
|
|
284
|
+
return;
|
|
285
|
+
await Promise.race([res.value, ...timers]);
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
await Promise.race(timers);
|
|
289
|
+
}
|
|
290
|
+
/** Waits until the consumer has a message (or the watchdog fires; callers just re-check). */
|
|
291
|
+
export async function waitReadable(c, options = {}) {
|
|
292
|
+
if (!c.prepareWait())
|
|
293
|
+
return;
|
|
294
|
+
const [words, index, value] = c.waitTarget();
|
|
295
|
+
await waitWord(words, index, value, options);
|
|
296
|
+
}
|
|
297
|
+
/** Waits until `len` bytes may fit (or the watchdog fires). */
|
|
298
|
+
export async function waitWritable(p, len, options = {}) {
|
|
299
|
+
if (!p.prepareWait(len))
|
|
300
|
+
return;
|
|
301
|
+
const [words, index, value] = p.waitTarget();
|
|
302
|
+
await waitWord(words, index, value, options);
|
|
303
|
+
}
|
|
304
|
+
/** Names matching webpod_abi (`Ring::init` / `Ring::attach`), for engine-side code. */
|
|
305
|
+
export const Ring = {
|
|
306
|
+
init: initRing,
|
|
307
|
+
/** Validates an existing ring at `byteOffset` (never rewrites its header). */
|
|
308
|
+
attach(buffer, byteOffset = 0) {
|
|
309
|
+
const producer = () => new RingProducer(buffer, byteOffset);
|
|
310
|
+
const consumer = () => new RingConsumer(buffer, byteOffset);
|
|
311
|
+
producer(); // validates
|
|
312
|
+
return { producer, consumer };
|
|
313
|
+
},
|
|
314
|
+
};
|
|
315
|
+
export const waitForMessage = waitReadable;
|
|
316
|
+
export const waitForSpace = waitWritable;
|
|
317
|
+
//# sourceMappingURL=ring.js.map
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/* tslint:disable */
|
|
2
|
+
/* eslint-disable */
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* One guest NIC's network: gateway stack, egress and inbound bridge.
|
|
6
|
+
*/
|
|
7
|
+
export class NetPod {
|
|
8
|
+
free(): void;
|
|
9
|
+
[Symbol.dispose](): void;
|
|
10
|
+
/**
|
|
11
|
+
* Another pod on the page LAN: its guest is `hostname` at its LAN index's address.
|
|
12
|
+
*/
|
|
13
|
+
add_peer(id: number, hostname: string, index: number): void;
|
|
14
|
+
/**
|
|
15
|
+
* Certificate and private key, for the Worker to persist (never handed to the page).
|
|
16
|
+
*/
|
|
17
|
+
ca_bundle(): string;
|
|
18
|
+
/**
|
|
19
|
+
* The pod CA certificate (PEM) to install in the guest's trust stores.
|
|
20
|
+
*/
|
|
21
|
+
ca_certificate(): string;
|
|
22
|
+
/**
|
|
23
|
+
* Milliseconds until the stack wants to be polled again (-1: no timer).
|
|
24
|
+
*/
|
|
25
|
+
delay(now_ms: number): number;
|
|
26
|
+
/**
|
|
27
|
+
* `network`: `{ mode?: "browser" | "none", mtu?, corsProxy?: { url, token? }, relay?: { url,
|
|
28
|
+
* token? }, routes?: [{ host?, ports?: [lo, hi], protocol?, via, stripHeaders? }] }` (see
|
|
29
|
+
* packages/net-worker/README.md). `ca_bundle`: a previously exported CA (PEM, certificate and
|
|
30
|
+
* key) or empty to generate one. `get_token`: called for relay tokens when `relay.token` is
|
|
31
|
+
* absent (returns a string or a Promise). `unix_secs`: wall clock (wasm has none).
|
|
32
|
+
*/
|
|
33
|
+
constructor(network: any, ca_bundle: string, get_token: Function | null | undefined, unix_secs: number);
|
|
34
|
+
/**
|
|
35
|
+
* A page connection (preview, pod.fetch, pod.net.connect).
|
|
36
|
+
*/
|
|
37
|
+
open_inbound(port: MessagePort): void;
|
|
38
|
+
/**
|
|
39
|
+
* Run the stack; returns whether anything happened (frames in or out, completions, page
|
|
40
|
+
* commands), in which case the Worker should poll again right away.
|
|
41
|
+
*/
|
|
42
|
+
poll(now_ms: number): boolean;
|
|
43
|
+
/**
|
|
44
|
+
* An Ethernet frame from the guest.
|
|
45
|
+
*/
|
|
46
|
+
push(frame: Uint8Array | number[]): void;
|
|
47
|
+
/**
|
|
48
|
+
* A frame a peer forwarded for this guest.
|
|
49
|
+
*/
|
|
50
|
+
push_forwarded(frame: Uint8Array | number[]): boolean;
|
|
51
|
+
remove_peer(id: number): void;
|
|
52
|
+
/**
|
|
53
|
+
* Called (at most once per batch) when egress completions or page commands arrive.
|
|
54
|
+
*/
|
|
55
|
+
set_notify(f?: Function | null): void;
|
|
56
|
+
set_unix_time(secs: number): void;
|
|
57
|
+
/**
|
|
58
|
+
* Gauges for leak and load checks: the stack's, the egress's, page connections, queued
|
|
59
|
+
* frames and the wasm memory size (bytes).
|
|
60
|
+
*/
|
|
61
|
+
stats(): any;
|
|
62
|
+
/**
|
|
63
|
+
* Frames for the guest produced by the last polls.
|
|
64
|
+
*/
|
|
65
|
+
take(): Array<any>;
|
|
66
|
+
/**
|
|
67
|
+
* Guest frames for peers: `[[peerId, Uint8Array], ...]`, to post to their Workers.
|
|
68
|
+
*/
|
|
69
|
+
take_forwarded(): Array<any>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Sends log records at `level` (`"error"`, `"warn"`, `"info"`, `"debug"`; default warn) and
|
|
74
|
+
* above to `f(level, text)`.
|
|
75
|
+
*/
|
|
76
|
+
export function set_logger(f: Function, level?: string | null): void;
|
|
77
|
+
|
|
78
|
+
export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
|
|
79
|
+
|
|
80
|
+
export interface InitOutput {
|
|
81
|
+
readonly memory: WebAssembly.Memory;
|
|
82
|
+
readonly __wbg_netpod_free: (a: number, b: number) => void;
|
|
83
|
+
readonly netpod_add_peer: (a: number, b: number, c: number, d: number, e: number) => void;
|
|
84
|
+
readonly netpod_ca_bundle: (a: number) => [number, number];
|
|
85
|
+
readonly netpod_ca_certificate: (a: number) => [number, number];
|
|
86
|
+
readonly netpod_delay: (a: number, b: number) => number;
|
|
87
|
+
readonly netpod_new: (a: any, b: number, c: number, d: number, e: number) => [number, number, number];
|
|
88
|
+
readonly netpod_open_inbound: (a: number, b: any) => void;
|
|
89
|
+
readonly netpod_poll: (a: number, b: number) => number;
|
|
90
|
+
readonly netpod_push: (a: number, b: number, c: number) => void;
|
|
91
|
+
readonly netpod_push_forwarded: (a: number, b: number, c: number) => number;
|
|
92
|
+
readonly netpod_remove_peer: (a: number, b: number) => void;
|
|
93
|
+
readonly netpod_set_notify: (a: number, b: number) => void;
|
|
94
|
+
readonly netpod_set_unix_time: (a: number, b: number) => void;
|
|
95
|
+
readonly netpod_stats: (a: number) => any;
|
|
96
|
+
readonly netpod_take: (a: number) => any;
|
|
97
|
+
readonly netpod_take_forwarded: (a: number) => any;
|
|
98
|
+
readonly set_logger: (a: any, b: number, c: number) => void;
|
|
99
|
+
readonly ring_core_0_17_14__bn_mul_mont: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
|
|
100
|
+
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];
|
|
101
|
+
readonly wasm_bindgen_5a2380350bab5903___convert__closures_____invoke___wasm_bindgen_5a2380350bab5903___JsValue______true_: (a: number, b: number, c: any) => void;
|
|
102
|
+
readonly wasm_bindgen_5a2380350bab5903___convert__closures_____invoke___wasm_bindgen_5a2380350bab5903___JsValue__true_: (a: number, b: number) => any;
|
|
103
|
+
readonly __wbindgen_malloc: (a: number, b: number) => number;
|
|
104
|
+
readonly __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
|
|
105
|
+
readonly __wbindgen_free: (a: number, b: number, c: number) => void;
|
|
106
|
+
readonly __wbindgen_exn_store: (a: number) => void;
|
|
107
|
+
readonly __externref_table_alloc: () => number;
|
|
108
|
+
readonly __wbindgen_externrefs: WebAssembly.Table;
|
|
109
|
+
readonly __wbindgen_destroy_closure: (a: number, b: number) => void;
|
|
110
|
+
readonly __externref_table_dealloc: (a: number) => void;
|
|
111
|
+
readonly __wbindgen_start: () => void;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export type SyncInitInput = BufferSource | WebAssembly.Module;
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Instantiates the given `module`, which can either be bytes or
|
|
118
|
+
* a precompiled `WebAssembly.Module`.
|
|
119
|
+
*
|
|
120
|
+
* @param {{ module: SyncInitInput }} module - Passing `SyncInitInput` directly is deprecated.
|
|
121
|
+
*
|
|
122
|
+
* @returns {InitOutput}
|
|
123
|
+
*/
|
|
124
|
+
export function initSync(module: { module: SyncInitInput } | SyncInitInput): InitOutput;
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* If `module_or_path` is {RequestInfo} or {URL}, makes a request and
|
|
128
|
+
* for everything else, calls `WebAssembly.instantiate` directly.
|
|
129
|
+
*
|
|
130
|
+
* @param {{ module_or_path: InitInput | Promise<InitInput> }} module_or_path - Passing `InitInput` directly is deprecated.
|
|
131
|
+
*
|
|
132
|
+
* @returns {Promise<InitOutput>}
|
|
133
|
+
*/
|
|
134
|
+
export default function __wbg_init (module_or_path?: { module_or_path: InitInput | Promise<InitInput> } | InitInput | Promise<InitInput>): Promise<InitOutput>;
|