@threadedstack/wmd-web 0.1.39 → 0.1.41

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.
Files changed (57) hide show
  1. package/README.md +236 -1
  2. package/RELEASE.json +84 -49
  3. package/guest/arm64/Image +1 -1
  4. package/guest/arm64/Image-4k +1 -1
  5. package/guest/arm64/initramfs.cpio.gz +0 -0
  6. package/package.json +3 -3
  7. package/src/boot.js +231 -4
  8. package/src/edge/auto.js +77 -0
  9. package/src/edge/base.js +10 -0
  10. package/src/edge/bridge.js +76 -7
  11. package/src/edge/ctl.js +21 -4
  12. package/src/edge/error-kind.js +6 -0
  13. package/src/edge/frame-code.gen.js +6 -0
  14. package/src/edge/frame.js +58 -15
  15. package/src/edge/msg.js +3 -0
  16. package/src/edge/own/adapter.js +208 -19
  17. package/src/edge/own/exit-now.js +62 -0
  18. package/src/edge/own/fs-own-route.js +40 -3
  19. package/src/edge/own/fs-stats.js +11 -0
  20. package/src/edge/own/hub.js +125 -14
  21. package/src/edge/own/loader.js +3 -2
  22. package/src/edge/own/marks.js +158 -0
  23. package/src/edge/own/net-host.js +873 -0
  24. package/src/edge/own/node-globals.js +142 -0
  25. package/src/edge/own/pool.js +30 -1
  26. package/src/edge/own/service-receiver.js +7 -1
  27. package/src/edge/own/shim-post.js +38 -0
  28. package/src/edge/own/worker.js +34 -1
  29. package/src/edge/page.js +448 -25
  30. package/src/edge/pins.gen.js +17 -0
  31. package/src/edge/pins.js +21 -0
  32. package/src/edge/plan.js +45 -9
  33. package/src/edge/python-module.js +18 -0
  34. package/src/edge/python-pins.js +64 -0
  35. package/src/edge/python-plan.js +280 -0
  36. package/src/edge/python-source.js +34 -0
  37. package/src/edge/runtime.js +13 -2
  38. package/src/edge/sbx/cap.js +36 -0
  39. package/src/edge/sbx/common.js +186 -0
  40. package/src/edge/sbx/doc.js +121 -0
  41. package/src/edge/sbx/files.js +112 -0
  42. package/src/edge/sbx/frame.js +126 -0
  43. package/src/edge/sbx/gate.js +115 -0
  44. package/src/edge/sbx/sha256.js +68 -0
  45. package/src/edge/sbx/worker-entry.js +36 -0
  46. package/src/edge/sems.js +113 -0
  47. package/src/edge/service-host.js +57 -5
  48. package/src/edge/service-port.js +79 -5
  49. package/src/edge/setup.js +275 -0
  50. package/src/edge/shim.js +3 -1
  51. package/src/edge/watch.js +101 -0
  52. package/src/edge/worker.js +31 -2
  53. package/src/gowasm/setup.js +9 -6
  54. package/src/host/chan-service.js +8 -5
  55. package/src/host/chan-services.js +29 -4
  56. package/src/host/edge-host.js +58 -3
  57. package/wmdpack.wasm +0 -0
@@ -0,0 +1,873 @@
1
+ // X5 net: the page's side of node's network in the frame. The frame's runtime (edge/browser/src/net.rs) is a VirtualNetworking whose every
2
+ // operation is a `net_*` call on the file route's port (the same synchronous call path as the file calls; fs-own-route.js sends them here). This
3
+ // carries them out on the stub's own yamux session: the stub is the container's `node` and runs in the container's network namespace, so a
4
+ // connect, a listener, a name lookup and a UDP socket here are the container's, as with node in the guest (the desktop's edge/src/net.rs does
5
+ // the same over a stream to the stub). Nothing here uses the page's fetch or WebSocket: a socket either goes through the stub or fails.
6
+ //
7
+ // One NetHost belongs to one run (one stub session), so a socket of one run is not in reach of another run or another container. The streams are
8
+ // the stub's headers (guest/container2wasm/cmd/edgestub/proto.go): `connect`, `listen`, `resolve`, `bind_udp` opened by the host, and `accepted`
9
+ // opened by the stub for each connection a listener takes (edge-host.js hands those to `accepted()`, matched by the token this host gave `listen`
10
+ // in the header's `to`).
11
+ //
12
+ // Calls (args, data -> {value}; a promise of it when the call waits). Every answer is {ok: true, ...} or {ok: false, errno, error}:
13
+ // net_connect [net, addr] -> {id, addr} net: tcp, tcp4, tcp6; addr: host:port; addr is the local address
14
+ // net_listen [net, addr] -> {id, addr} addr is the bound address
15
+ // net_resolve [host] -> {addrs}
16
+ // net_udp [net, addr, v6only] -> {id, addr} net: udp4, udp6
17
+ // net_send [id] data -> {} EAGAIN when the stream's queue is over its limit (a DRAIN event follows)
18
+ // net_sendto [id, addr] data -> {} one datagram
19
+ // net_ack [id, n] -> {} the program took n bytes of the socket: the stub may send n more
20
+ // net_close [id] -> {} the writing ends after what is queued; the socket is gone for the program
21
+ // net_shutdown[id] -> {} the writing ends; reading goes on
22
+ // net_ctl [id, ctl, wait] -> {reply} a UDP control request (set_ttl, connect, ...); wait: answer with the stub's reply
23
+ // net_poll [maxBytes] -> bytes the events since the last poll, as records [kind u8][id u32 LE][len u32 LE][payload]
24
+ // (edge/browser/src/netproto.rs); waits for one; empty after pollMs; one poller
25
+ //
26
+ // Receive back-pressure: a stream's bytes are given back to the stub's window only when the program has taken them (net_ack), so a program that
27
+ // does not read stops its peer after one window (256 KiB per stream) and the bytes the page holds for it are bounded by that and the total (below).
28
+ // Send back-pressure: a send over LIMITS.SEND_PENDING queued bytes is EAGAIN and the socket gets a DRAIN event once the queue is half empty.
29
+ // One total for the run (LIMITS.TOTAL_BYTES; `totalBytes` of the constructor): the bytes held for the program (received and not yet taken, queued sends,
30
+ // datagrams waiting). The first window of each open stream counts in it: a stream is opened only while the windows of all open streams fit in the total
31
+ // (#room), so a peer that fills its window and a program that never reads cannot take the page past the total (fix round item 3). Over it, the credit of what the program takes goes back to the stub only when the run holds less than 7/8 of the total (the stub's
32
+ // window stays closed, nothing is dropped on TCP), a send is EAGAIN (a stream gets DRAIN when the run holds less) and a datagram that does not fit is
33
+ // dropped, as Linux does.
34
+
35
+ import { INITIAL_WINDOW } from '../../host/yamux.js'
36
+
37
+ const enc = new TextEncoder()
38
+ const dec = new TextDecoder()
39
+
40
+ export const EV = { DATA: 1, ACCEPT: 2, EOF: 3, END: 4, DGRAM: 5, DRAIN: 6, BYE: 7 }
41
+
42
+ export const LIMITS = {
43
+ SOCKETS: 4096, // open sockets of a run (streams: connections, listeners, datagram sockets, accepted connections) and calls still opening one; the total below allows fewer (TOTAL_BYTES / the stream window: 1024 with the default)
44
+ MIN_WINDOWS: 16, // the fewest stream windows a run's total may hold (a total under that is raised to it)
45
+ LISTENERS: 256,
46
+ BACKLOG: 511, // accepted connections of one listener the program has not been told of yet; more are reset (node's default backlog)
47
+ SEND_PENDING: 1 << 20, // bytes queued on a stream for the stub
48
+ UDP_QUEUE_BYTES: 1 << 20, // datagram bytes waiting for the program, per socket
49
+ TOTAL_BYTES: 256 << 20, // (1024 stream windows: a program with a few hundred sockets open at once must not see EMFILE where the guest gives none) all the bytes the page holds for one run: received and not yet taken by the program, queued sends, datagrams waiting. On top of the per-socket bounds
50
+ ADDR: 255,
51
+ HOST: 253,
52
+ }
53
+
54
+ const FRAME_HDR = 0x10
55
+ const FRAME_REPLY = 0x11
56
+ const FRAME_DGRAM = 0x20
57
+ const FRAME_CTL = 0x21
58
+ const FRAME_CTL_REPLY = 0x22
59
+ const MAX_FRAME = 4 << 20
60
+ const TCP_NETS = new Set(['tcp', 'tcp4', 'tcp6'])
61
+ const UDP_NETS = new Set(['udp4', 'udp6'])
62
+ const CTL_OPS = new Set(['connect', 'set_broadcast', 'set_ttl', 'set_multicast_loop_v4', 'set_multicast_loop_v6', 'set_multicast_ttl_v4', 'join_multicast_v4', 'leave_multicast_v4', 'join_multicast_v6', 'leave_multicast_v6'])
63
+
64
+ const cat = (a, b) => {
65
+ if (!a.length) return b
66
+ const o = new Uint8Array(a.length + b.length)
67
+ o.set(a)
68
+ o.set(b, a.length)
69
+ return o
70
+ }
71
+ const frame = (type, payload) => {
72
+ const p = payload instanceof Uint8Array ? payload : enc.encode(JSON.stringify(payload))
73
+ const o = new Uint8Array(5 + p.length)
74
+ o[0] = type
75
+ new DataView(o.buffer).setUint32(1, p.length)
76
+ o.set(p, 5)
77
+ return o
78
+ }
79
+ /** The next whole frame of `acc` as {type, payload, used}, or null. A frame over MAX_FRAME is {bad: true}. */
80
+ function nextFrame(acc) {
81
+ if (acc.length < 5) return null
82
+ const n = new DataView(acc.buffer, acc.byteOffset, acc.length).getUint32(1)
83
+ if (n > MAX_FRAME) return { bad: true }
84
+ if (acc.length < 5 + n) return null
85
+ return { type: acc[0], payload: acc.slice(5, 5 + n), used: 5 + n }
86
+ }
87
+
88
+ const fail = (errno, error) => ({ ok: false, errno, error: error || errno })
89
+ // A listener's token is what the stub's `accepted` streams name to reach this run's listener, so it must not be guessable: it comes from the engine's
90
+ // random source or there is none (null), and the listen is refused (X5 option A, item 14; there is no weaker fallback).
91
+ const token = () => {
92
+ const c = globalThis.crypto
93
+ if (!c || typeof c.getRandomValues !== 'function') return null
94
+ const b = new Uint8Array(16)
95
+ c.getRandomValues(b)
96
+ return Array.from(b, x => x.toString(16).padStart(2, '0')).join('')
97
+ }
98
+ const goodAddr = a => typeof a === 'string' && a.length > 0 && a.length <= LIMITS.ADDR && !/[\u0000-\u001f]/.test(a)
99
+
100
+ // What every NetHost of this page did, for a look from outside (a test page, the console): the most bytes one run held at once.
101
+ const AGG = { heldPeak: 0, runs: 0, last: [], reset() { this.heldPeak = 0 } } // `last`: the peak of held bytes and of open sockets of each run that ended, newest last (50 kept)
102
+ try {
103
+ globalThis.__wmdNetHostStats = AGG // a Worker's global too: the chan service's (service-port.js stats() carries it out)
104
+ } catch {
105
+ // a frozen global: no look from outside
106
+ }
107
+
108
+ /** What every NetHost of this realm did (for service-port.js stats()). */
109
+ export const netTotals = () => ({ heldPeak: AGG.heldPeak, runs: AGG.runs, last: AGG.last.slice() })
110
+
111
+ export class NetHost {
112
+ #open
113
+ #bell
114
+ #pollMs
115
+ #graceMs
116
+ #sockets = new Map() // id -> socket
117
+ #tokens = new Map() // listener token -> socket
118
+ #zombies = new Set() // streams the program closed, until the peer's end or the grace time
119
+ #dials = new Set() // calls that opened a stream and wait for its reply
120
+ #events = []
121
+ #waiter = null
122
+ #next = 1
123
+ #closed = false
124
+ #listeners = 0
125
+ #lastSend = 0 // when a connection last took bytes from the program (0: never)
126
+ #cap
127
+ #recv = 0 // bytes received (and the ones that came with an accepted stream) that the program has not taken (net_ack)
128
+ #sendQ = 0 // bytes written to streams that the stream has not handed on
129
+ #udpQ = 0 // datagram bytes waiting for the program
130
+ #peak = 0
131
+ #socketsPeak = 0
132
+ #withheld = new Set() // sockets whose credit is held back
133
+ #blockedB = new Set() // sockets whose send was refused for the total
134
+ #st = { udpDropped: 0, calls: 0, accepted: 0, refusedAccepts: 0, creditWithheld: 0, sendRefused: 0 }
135
+
136
+ /**
137
+ * @param {{openStream: () => object, onTraffic?: () => void, pollMs?: number, closeGraceMs?: number, totalBytes?: number}} o
138
+ * openStream: a raw stream on the stub's session (YamuxStream); onTraffic: rings the machine's doorbell after bytes are written
139
+ */
140
+ constructor({ openStream, onTraffic, pollMs = 25_000, closeGraceMs = 60_000, totalBytes = LIMITS.TOTAL_BYTES }) {
141
+ this.#cap = totalBytes
142
+ this.#open = openStream
143
+ this.#bell = () => {
144
+ try {
145
+ onTraffic?.()
146
+ } catch {
147
+ // a bell that cannot ring is no reason to fail a call
148
+ }
149
+ }
150
+ this.#pollMs = pollMs
151
+ this.#graceMs = closeGraceMs
152
+ }
153
+
154
+ stats() {
155
+ return { sockets: this.#sockets.size, listeners: this.#listeners, opening: this.#dials.size, zombies: this.#zombies.size, events: this.#events.length, closed: this.#closed, heldBytes: this.#held(), heldPeak: this.#peak, ...this.#st }
156
+ }
157
+
158
+ /** The route's entry: {value} or a promise of it. Never throws. */
159
+ handle(method, args, data) {
160
+ this.#st.calls++
161
+ const a = Array.isArray(args) ? args : []
162
+ const d = data instanceof Uint8Array ? data : new Uint8Array(0)
163
+ try {
164
+ switch (method) {
165
+ case 'net_poll':
166
+ return this.#poll(Number(a[0]))
167
+ case 'net_connect':
168
+ return this.#connect(a[0], a[1])
169
+ case 'net_listen':
170
+ return this.#listen(a[0], a[1])
171
+ case 'net_resolve':
172
+ return this.#resolve(a[0])
173
+ case 'net_udp':
174
+ return this.#udp(a[0], a[1], a[2])
175
+ case 'net_send':
176
+ return { value: this.#send(a[0], d, null) }
177
+ case 'net_sendto':
178
+ return { value: this.#send(a[0], d, a[1]) }
179
+ case 'net_ack':
180
+ return { value: this.#ack(a[0], a[1]) }
181
+ case 'net_close':
182
+ return { value: this.#closeSock(a[0]) }
183
+ case 'net_shutdown':
184
+ return { value: this.#shutdown(a[0]) }
185
+ case 'net_ctl':
186
+ return this.#ctl(a[0], a[1], a[2])
187
+ default:
188
+ return { error: { code: 'ENOSYS', message: 'net host: no such method' } }
189
+ }
190
+ } catch (e) {
191
+ return { value: fail('EIO', String((e && e.message) || e)) }
192
+ }
193
+ }
194
+
195
+ // ---- the run's total of held bytes ----
196
+
197
+ #held() {
198
+ return this.#recv + this.#sendQ + this.#udpQ
199
+ }
200
+
201
+ #note() {
202
+ const h = this.#held()
203
+ if (h > this.#peak) this.#peak = h
204
+ if (h > AGG.heldPeak) AGG.heldPeak = h
205
+ }
206
+
207
+ /** The queue of a stream the program wrote to changed: the run's sum follows. */
208
+ #sync(s) {
209
+ const p = s.st.pendingBytes > 0 ? s.st.pendingBytes : 0
210
+ this.#sendQ += p - (s.pend || 0)
211
+ s.pend = p
212
+ this.#note()
213
+ }
214
+
215
+ /** The run holds less now: the credit held back goes to the stub, the sockets whose send was refused hear DRAIN. */
216
+ #relax() {
217
+ if (!this.#withheld.size && !this.#blockedB.size) return
218
+ if (this.#held() >= this.#cap - (this.#cap >> 3)) return
219
+ for (const s of this.#withheld) {
220
+ const n = s.withheld || 0
221
+ s.withheld = 0
222
+ if (n > 0 && !s.gone) {
223
+ try {
224
+ s.st.consume(n)
225
+ } catch {
226
+ // already gone
227
+ }
228
+ }
229
+ }
230
+ const wasWithheld = this.#withheld.size > 0
231
+ this.#withheld.clear()
232
+ for (const s of this.#blockedB) {
233
+ if (s.gone || !s.blocked) continue
234
+ if (s.st.pendingBytes < LIMITS.SEND_PENDING / 2) {
235
+ s.blocked = false
236
+ this.#emit(EV.DRAIN, s.id, new Uint8Array(0))
237
+ }
238
+ }
239
+ this.#blockedB.clear()
240
+ if (wasWithheld) this.#bell()
241
+ }
242
+
243
+ // ---- opening ----
244
+
245
+ /**
246
+ * Whether one more stream may be opened. Besides LIMITS.SOCKETS, the first windows of all the open streams (what the stub may send before any credit comes
247
+ * back) must fit in the total, with this one: so the bytes the page holds for the run stay at most the total whatever the peers send (fix round item 3).
248
+ * A total under LIMITS.MIN_WINDOWS windows is raised to that, or a small total would allow no socket at all.
249
+ */
250
+ #room() {
251
+ const n = this.#sockets.size + this.#dials.size
252
+ return n < LIMITS.SOCKETS && (n + 1) * INITIAL_WINDOW <= Math.max(this.#cap, LIMITS.MIN_WINDOWS * INITIAL_WINDOW)
253
+ }
254
+
255
+ /** Opens a stream, writes the header, and waits for the stub's reply frame. -> {ok: true, st, reply, rest} or {ok: false, ...} */
256
+ #dial(header) {
257
+ if (this.#closed) return Promise.resolve(fail('ECONNABORTED', 'the run ended'))
258
+ if (!this.#room()) return Promise.resolve(fail('EMFILE', 'too many open sockets'))
259
+ let st
260
+ try {
261
+ st = this.#open()
262
+ } catch (e) {
263
+ return Promise.resolve(fail('ECONNRESET', 'the stub is gone: ' + ((e && e.message) || e)))
264
+ }
265
+ return new Promise(resolve => {
266
+ let acc = new Uint8Array(0)
267
+ let over = false
268
+ const entry = {
269
+ end: why => {
270
+ if (over) return
271
+ over = true
272
+ this.#dials.delete(entry)
273
+ try {
274
+ st.abort(why)
275
+ } catch {
276
+ // already gone
277
+ }
278
+ resolve(fail('ECONNABORTED', why))
279
+ },
280
+ }
281
+ const done = r => {
282
+ if (over) return
283
+ over = true
284
+ this.#dials.delete(entry)
285
+ resolve(r)
286
+ }
287
+ this.#dials.add(entry)
288
+ st.onData = u8 => {
289
+ if (over) return
290
+ acc = cat(acc, u8.slice())
291
+ const f = nextFrame(acc)
292
+ if (!f) return
293
+ if (f.bad || f.type !== FRAME_REPLY) {
294
+ try {
295
+ st.abort('bad reply from the stub')
296
+ } catch {
297
+ // already gone
298
+ }
299
+ return done(fail('ECONNRESET', 'bad reply from the stub'))
300
+ }
301
+ st.consume(f.used)
302
+ let reply
303
+ try {
304
+ reply = JSON.parse(dec.decode(f.payload))
305
+ } catch {
306
+ try {
307
+ st.abort('bad reply from the stub')
308
+ } catch {
309
+ // already gone
310
+ }
311
+ return done(fail('ECONNRESET', 'bad reply from the stub'))
312
+ }
313
+ const rest = acc.slice(f.used)
314
+ if (!reply || !reply.ok) {
315
+ try {
316
+ st.closeWrite()
317
+ } catch {
318
+ // already gone
319
+ }
320
+ st.onData = u8 => st.consume(u8.length)
321
+ this.#bell()
322
+ return done(fail(String((reply && reply.errno) || 'EIO'), String((reply && (reply.error || reply.errno)) || 'the stub refused')))
323
+ }
324
+ done({ ok: true, st, reply, rest })
325
+ }
326
+ st.onFin = () => done(fail('ECONNRESET', 'the stub ended the stream'))
327
+ st.onClose = () => done(fail('ECONNRESET', 'the stream to the stub is gone'))
328
+ try {
329
+ st.write(frame(FRAME_HDR, header))
330
+ } catch (e) {
331
+ done(fail('ECONNRESET', 'the stub is gone: ' + ((e && e.message) || e)))
332
+ return
333
+ }
334
+ this.#bell()
335
+ })
336
+ }
337
+
338
+ async #connect(net, addr) {
339
+ if (!TCP_NETS.has(net) || !goodAddr(addr)) return { value: fail('EINVAL', 'bad connect request') }
340
+ const r = await this.#dial({ kind: 'connect', net, addr })
341
+ if (!r.ok) return { value: r }
342
+ if (this.#closed) {
343
+ r.st.abort('the run ended')
344
+ return { value: fail('ECONNABORTED', 'the run ended') }
345
+ }
346
+ const s = this.#add({ kind: 'tcp', st: r.st })
347
+ this.#wireTcp(s, r.rest, 0)
348
+ return { value: { ok: true, id: s.id, addr: String(r.reply.addr || '') } }
349
+ }
350
+
351
+ async #listen(net, addr) {
352
+ if (!TCP_NETS.has(net) || !goodAddr(addr)) return { value: fail('EINVAL', 'bad listen request') }
353
+ if (this.#listeners >= LIMITS.LISTENERS) return { value: fail('EMFILE', 'too many listeners') }
354
+ const tok = token()
355
+ if (tok === null) return { value: fail('ENOTSUP', 'no listener without crypto.getRandomValues: its token must not be guessable') }
356
+ this.#listeners++ // taken for the wait too: a program cannot open listeners faster than they answer
357
+ let r
358
+ try {
359
+ r = await this.#dial({ kind: 'listen', net, addr, to: tok })
360
+ } finally {
361
+ this.#listeners--
362
+ }
363
+ if (!r.ok) return { value: r }
364
+ if (this.#closed) {
365
+ r.st.abort('the run ended')
366
+ return { value: fail('ECONNABORTED', 'the run ended') }
367
+ }
368
+ const s = this.#add({ kind: 'listen', st: r.st, token: tok, unpolled: 0 })
369
+ this.#listeners++
370
+ this.#tokens.set(tok, s)
371
+ r.st.onData = u8 => r.st.consume(u8.length)
372
+ r.st.onFin = () => {}
373
+ r.st.onClose = () => {
374
+ if (s.gone) return
375
+ this.#drop(s)
376
+ this.#emit(EV.END, s.id, enc.encode('ECONNABORTED'))
377
+ }
378
+ return { value: { ok: true, id: s.id, addr: String(r.reply.addr || '') } }
379
+ }
380
+
381
+ async #resolve(host) {
382
+ if (typeof host !== 'string' || host.length < 1 || host.length > LIMITS.HOST) return { value: fail('EINVAL', 'bad name') }
383
+ const r = await this.#dial({ kind: 'resolve', host })
384
+ if (!r.ok) return { value: r }
385
+ const addrs = Array.isArray(r.reply.addrs) ? r.reply.addrs.filter(x => typeof x === 'string').slice(0, 64) : []
386
+ try {
387
+ r.st.closeWrite()
388
+ } catch {
389
+ // already gone
390
+ }
391
+ r.st.onData = u8 => r.st.consume(u8.length)
392
+ this.#bell()
393
+ return { value: { ok: true, addrs } }
394
+ }
395
+
396
+ async #udp(net, addr, v6only) {
397
+ if (!UDP_NETS.has(net) || !goodAddr(addr)) return { value: fail('EINVAL', 'bad bind request') }
398
+ const r = await this.#dial({ kind: 'bind_udp', net, addr, v6only: !!v6only })
399
+ if (!r.ok) return { value: r }
400
+ if (this.#closed) {
401
+ r.st.abort('the run ended')
402
+ return { value: fail('ECONNABORTED', 'the run ended') }
403
+ }
404
+ const s = this.#add({ kind: 'udp', st: r.st, queued: 0, ctl: [], acc: new Uint8Array(0) })
405
+ const st = r.st
406
+ const onBytes = u8 => {
407
+ if (s.gone) return st.consume(u8.length)
408
+ s.acc = cat(s.acc, u8.slice())
409
+ for (;;) {
410
+ const f = nextFrame(s.acc)
411
+ if (!f) return
412
+ if (f.bad) return st.abort('bad frame from the stub')
413
+ s.acc = s.acc.slice(f.used)
414
+ st.consume(f.used)
415
+ if (f.type === FRAME_DGRAM) {
416
+ if (s.queued + f.payload.length > LIMITS.UDP_QUEUE_BYTES || this.#held() + f.payload.length > this.#cap) this.#st.udpDropped++
417
+ else {
418
+ s.queued += f.payload.length
419
+ this.#udpQ += f.payload.length
420
+ this.#note()
421
+ this.#emit(EV.DGRAM, s.id, f.payload)
422
+ }
423
+ } else if (f.type === FRAME_CTL_REPLY) {
424
+ const w = s.ctl.shift()
425
+ if (w) {
426
+ let rep = null
427
+ try {
428
+ rep = JSON.parse(dec.decode(f.payload))
429
+ } catch {
430
+ // an answer that is not JSON is an empty one
431
+ }
432
+ w({ ok: true, reply: rep })
433
+ }
434
+ }
435
+ }
436
+ }
437
+ st.onData = onBytes
438
+ st.onFin = () => {}
439
+ st.onSent = () => {
440
+ if (!s.gone) this.#sync(s)
441
+ this.#relax()
442
+ }
443
+ st.onClose = reason => this.#ended(s, reason)
444
+ if (r.rest.length) onBytes(r.rest)
445
+ return { value: { ok: true, id: s.id, addr: String(r.reply.addr || '') } }
446
+ }
447
+
448
+ // ---- sockets ----
449
+
450
+ #add(s) {
451
+ s.id = this.#next++
452
+ s.blocked = false
453
+ s.unacked = 0
454
+ s.credit = 0
455
+ s.gone = false
456
+ this.#sockets.set(s.id, s)
457
+ if (this.#sockets.size > this.#socketsPeak) this.#socketsPeak = this.#sockets.size
458
+ return s
459
+ }
460
+
461
+ /** A connection's stream handlers; `rest`: the bytes that came with the first read; `credit`: how many of them the host's reader took already. */
462
+ #wireTcp(s, rest, credit) {
463
+ const st = s.st
464
+ s.credit = credit
465
+ st.onData = u8 => {
466
+ if (s.gone || this.#closed) return st.consume(u8.length)
467
+ s.unacked += u8.length
468
+ this.#recv += u8.length
469
+ this.#note()
470
+ this.#emit(EV.DATA, s.id, u8.slice())
471
+ }
472
+ st.onFin = () => {
473
+ if (!s.gone) this.#emit(EV.EOF, s.id, new Uint8Array(0))
474
+ }
475
+ st.onClose = reason => this.#ended(s, reason)
476
+ st.onSent = () => {
477
+ if (!s.gone) this.#sync(s)
478
+ if (s.blocked && !s.gone && st.pendingBytes < LIMITS.SEND_PENDING / 2 && !this.#blockedB.has(s)) {
479
+ s.blocked = false
480
+ this.#emit(EV.DRAIN, s.id, new Uint8Array(0))
481
+ }
482
+ this.#relax()
483
+ }
484
+ if (rest && rest.length) {
485
+ if (credit) st.onDataPre = true
486
+ this.#recv += rest.length
487
+ this.#note()
488
+ s.unacked += credit ? 0 : rest.length
489
+ this.#emit(EV.DATA, s.id, rest.slice())
490
+ }
491
+ }
492
+
493
+ /** The stream of socket `s` ended: a clean end of both sides (reason null) or an error. */
494
+ #ended(s, reason) {
495
+ if (s.gone) return
496
+ this.#drop(s)
497
+ if (this.#closed) return
498
+ this.#emit(EV.END, s.id, enc.encode(reason === null || reason === undefined ? '' : 'ECONNRESET'))
499
+ }
500
+
501
+ #drop(s) {
502
+ s.gone = true
503
+ this.#recv -= (s.unacked || 0) + (s.credit || 0)
504
+ this.#sendQ -= s.pend || 0
505
+ this.#udpQ -= s.queued || 0
506
+ s.unacked = 0
507
+ s.credit = 0
508
+ s.pend = 0
509
+ s.queued = 0
510
+ s.withheld = 0
511
+ this.#withheld.delete(s)
512
+ this.#blockedB.delete(s)
513
+ queueMicrotask(() => this.#relax())
514
+ if (this.#sockets.delete(s.id) && s.kind === 'listen') {
515
+ this.#listeners--
516
+ this.#tokens.delete(s.token)
517
+ }
518
+ }
519
+
520
+ #get(id, kinds) {
521
+ if (!Number.isInteger(id) || id < 1) return fail('EINVAL', 'bad socket id')
522
+ const s = this.#sockets.get(id)
523
+ if (!s || s.gone) return fail('EBADF', 'no such socket')
524
+ if (kinds && !kinds.includes(s.kind)) return fail('ENOTSOCK', 'wrong kind of socket')
525
+ return s
526
+ }
527
+
528
+ #send(id, data, to) {
529
+ const s = this.#get(id, to === null ? ['tcp'] : ['udp'])
530
+ if (s.ok === false) return s
531
+ const st = s.st
532
+ if (st.closed || st.localFin) return fail('EPIPE', 'the writing of this socket has ended')
533
+ if (st.pendingBytes > 0 && st.pendingBytes + data.length > LIMITS.SEND_PENDING) {
534
+ s.blocked = true
535
+ return fail('EAGAIN', 'the send queue is full')
536
+ }
537
+ if (this.#held() + data.length > this.#cap) {
538
+ this.#st.sendRefused++
539
+ if (to === null) {
540
+ s.blocked = true
541
+ this.#blockedB.add(s)
542
+ }
543
+ return fail('EAGAIN', 'the run holds its total of bytes')
544
+ }
545
+ try {
546
+ if (to === null) st.write(data)
547
+ else {
548
+ if (!goodAddr(to)) return fail('EINVAL', 'bad address')
549
+ const a = enc.encode(to)
550
+ const p = new Uint8Array(2 + a.length + data.length)
551
+ new DataView(p.buffer).setUint16(0, a.length)
552
+ p.set(a, 2)
553
+ p.set(data, 2 + a.length)
554
+ st.write(frame(FRAME_DGRAM, p))
555
+ }
556
+ } catch (e) {
557
+ return fail('EPIPE', String((e && e.message) || e))
558
+ }
559
+ if (to === null) {
560
+ this.#lastSend = performance.now()
561
+ this.#sync(s)
562
+ } else this.#sync(s)
563
+ this.#bell()
564
+ return { ok: true }
565
+ }
566
+
567
+ #ack(id, n) {
568
+ const s = this.#sockets.get(id)
569
+ if (!s || s.gone || s.kind !== 'tcp' || !Number.isFinite(n) || n <= 0) return { ok: true }
570
+ let left = Math.floor(n)
571
+ const pre = Math.min(s.credit, left)
572
+ s.credit -= pre
573
+ left -= pre
574
+ this.#recv -= pre
575
+ const m = Math.min(left, s.unacked)
576
+ if (m > 0) {
577
+ s.unacked -= m
578
+ this.#recv -= m
579
+ if (this.#held() >= this.#cap) {
580
+ // the run holds its total: this credit stays here until it holds less (the stub's window for this stream closes meanwhile)
581
+ s.withheld = (s.withheld || 0) + m
582
+ this.#withheld.add(s)
583
+ this.#st.creditWithheld++
584
+ } else {
585
+ s.st.consume(m)
586
+ this.#bell()
587
+ }
588
+ }
589
+ this.#relax()
590
+ return { ok: true }
591
+ }
592
+
593
+ #shutdown(id) {
594
+ const s = this.#get(id, ['tcp'])
595
+ if (s.ok === false) return s
596
+ try {
597
+ s.st.closeWrite()
598
+ } catch {
599
+ // already gone
600
+ }
601
+ this.#bell()
602
+ return { ok: true }
603
+ }
604
+
605
+ #closeSock(id) {
606
+ const s = this.#get(id)
607
+ if (s.ok === false) return s
608
+ this.#drop(s)
609
+ const st = s.st
610
+ if (s.kind === 'udp') {
611
+ for (const w of s.ctl) w?.(fail('ECONNABORTED', 'the socket closed'))
612
+ s.ctl = []
613
+ }
614
+ // what the stub sends from now on is taken and dropped; the stub's end comes (it closes its side when ours ends) or the grace time resets the stream
615
+ st.onData = u8 => st.consume(u8.length)
616
+ st.onFin = () => {}
617
+ st.onSent = null
618
+ try {
619
+ st.closeWrite()
620
+ } catch {
621
+ // already gone
622
+ }
623
+ this.#bell()
624
+ this.#zombie(st)
625
+ return { ok: true }
626
+ }
627
+
628
+ #zombie(st) {
629
+ if (st.closed) return
630
+ this.#zombies.add(st)
631
+ let timer = null
632
+ const gone = () => {
633
+ this.#zombies.delete(st)
634
+ if (timer) clearTimeout(timer)
635
+ }
636
+ st.onClose = gone
637
+ timer = setTimeout(() => {
638
+ gone()
639
+ try {
640
+ st.abort('closed by the program; the peer did not end')
641
+ } catch {
642
+ // already gone
643
+ }
644
+ this.#bell()
645
+ }, this.#graceMs)
646
+ timer?.unref?.()
647
+ while (this.#zombies.size > LIMITS.SOCKETS) {
648
+ const old = this.#zombies.values().next().value
649
+ this.#zombies.delete(old)
650
+ try {
651
+ old.abort('too many closing streams')
652
+ } catch {
653
+ // already gone
654
+ }
655
+ }
656
+ }
657
+
658
+ async #ctl(id, ctl, wait) {
659
+ const s = this.#get(id, ['udp'])
660
+ if (s.ok === false) return { value: s }
661
+ if (!ctl || typeof ctl !== 'object' || !CTL_OPS.has(ctl.op)) return { value: fail('EINVAL', 'bad control request') }
662
+ const body = {}
663
+ for (const k of ['op', 'addr', 'val', 'ttl', 'group', 'iface']) if (ctl[k] !== undefined) body[k] = ctl[k]
664
+ if ((body.addr !== undefined && !goodAddr(body.addr)) || (body.group !== undefined && !goodAddr(body.group)) || (body.iface !== undefined && !goodAddr(String(body.iface)))) return { value: fail('EINVAL', 'bad control request') }
665
+ if (s.st.closed || s.st.localFin) return { value: fail('EBADF', 'the socket is closed') }
666
+ const p = wait ? new Promise(res => s.ctl.push(res)) : (s.ctl.push(null), null)
667
+ try {
668
+ s.st.write(frame(FRAME_CTL, body))
669
+ } catch (e) {
670
+ s.ctl.pop()
671
+ return { value: fail('EPIPE', String((e && e.message) || e)) }
672
+ }
673
+ this.#bell()
674
+ return { value: p ? await p : { ok: true } }
675
+ }
676
+
677
+ // ---- accepted connections ----
678
+
679
+ /**
680
+ * A stream the stub opened for a connection its listener took (edge-host.js): `hdr` is the stub's header, `rest` the bytes behind it (already taken
681
+ * from the stream's window by the reader). Returns false (and resets the stream) when it is not for a listener of this run.
682
+ */
683
+ accepted(st, hdr, rest) {
684
+ const reset = why => {
685
+ this.#st.refusedAccepts++
686
+ try {
687
+ st.abort(why)
688
+ } catch {
689
+ // already gone
690
+ }
691
+ return false
692
+ }
693
+ if (this.#closed) return reset('the run ended')
694
+ const l = hdr && typeof hdr.to === 'string' ? this.#tokens.get(hdr.to) : null
695
+ if (!l || l.gone) return reset('no such listener')
696
+ if (l.unpolled >= LIMITS.BACKLOG) return reset('backlog full')
697
+ if (!this.#room()) return reset('too many open sockets')
698
+ const s = this.#add({ kind: 'tcp', st })
699
+ l.unpolled++
700
+ this.#st.accepted++
701
+ const peer = typeof hdr.peer === 'string' ? hdr.peer.slice(0, LIMITS.ADDR) : ''
702
+ this.#emit(EV.ACCEPT, l.id, enc.encode(JSON.stringify({ id: s.id, peer })), l)
703
+ this.#wireTcp(s, rest instanceof Uint8Array ? rest : new Uint8Array(0), rest instanceof Uint8Array ? rest.length : 0)
704
+ return true
705
+ }
706
+
707
+ // ---- events ----
708
+
709
+ #emit(kind, id, payload, listener = null) {
710
+ if (this.#closed) return
711
+ this.#events.push({ kind, id, payload, listener })
712
+ this.#wake()
713
+ }
714
+
715
+ #wake() {
716
+ const w = this.#waiter
717
+ if (!w) return
718
+ this.#waiter = null
719
+ clearTimeout(w.timer)
720
+ w.resolve({ value: this.#take(w.max) })
721
+ }
722
+
723
+ #take(max) {
724
+ if (this.#closed) return this.#record(EV.BYE, 0, new Uint8Array(0))
725
+ let out = new Uint8Array(0)
726
+ const parts = []
727
+ let size = 0
728
+ while (this.#events.length) {
729
+ const e = this.#events[0]
730
+ const need = 9 + e.payload.length
731
+ if (size + need <= max) {
732
+ this.#events.shift()
733
+ this.#taken(e)
734
+ parts.push(this.#record(e.kind, e.id, e.payload))
735
+ size += need
736
+ continue
737
+ }
738
+ // a data event that does not fit is cut: its first bytes now, the rest stays at the head
739
+ if (e.kind === EV.DATA && max - size > 9) {
740
+ const k = max - size - 9
741
+ parts.push(this.#record(EV.DATA, e.id, e.payload.subarray(0, k)))
742
+ e.payload = e.payload.subarray(k)
743
+ size += 9 + k
744
+ }
745
+ break
746
+ }
747
+ if (parts.length) {
748
+ out = new Uint8Array(size)
749
+ let at = 0
750
+ for (const p of parts) {
751
+ out.set(p, at)
752
+ at += p.length
753
+ }
754
+ }
755
+ return out
756
+ }
757
+
758
+ #taken(e) {
759
+ if (e.kind === EV.ACCEPT && e.listener) e.listener.unpolled = Math.max(0, e.listener.unpolled - 1)
760
+ if (e.kind === EV.DGRAM) {
761
+ const s = this.#sockets.get(e.id)
762
+ if (s) {
763
+ const n = Math.min(s.queued, e.payload.length)
764
+ s.queued -= n
765
+ this.#udpQ -= n
766
+ this.#relax()
767
+ }
768
+ }
769
+ }
770
+
771
+ #record(kind, id, payload) {
772
+ const o = new Uint8Array(9 + payload.length)
773
+ o[0] = kind
774
+ const dv = new DataView(o.buffer)
775
+ dv.setUint32(1, id, true)
776
+ dv.setUint32(5, payload.length, true)
777
+ o.set(payload, 9)
778
+ return o
779
+ }
780
+
781
+ #poll(max) {
782
+ const limit = Number.isFinite(max) && max > 0 ? Math.min(max, 8 << 20) : 1 << 16
783
+ if (this.#waiter) {
784
+ // one poller: a newer poll ends the older one with nothing
785
+ const w = this.#waiter
786
+ this.#waiter = null
787
+ clearTimeout(w.timer)
788
+ w.resolve({ value: new Uint8Array(0) })
789
+ }
790
+ if (this.#closed || this.#events.length) return { value: this.#take(limit) }
791
+ return new Promise(resolve => {
792
+ const w = { resolve, max: limit, timer: null }
793
+ w.timer = setTimeout(() => {
794
+ if (this.#waiter === w) this.#waiter = null
795
+ resolve({ value: new Uint8Array(0) })
796
+ }, this.#pollMs)
797
+ w.timer?.unref?.()
798
+ this.#waiter = w
799
+ })
800
+ }
801
+
802
+ // ---- the end of the run ----
803
+
804
+ /**
805
+ * The stub is the machine's side of every socket: bytes the program wrote and that are still in the page's queue, or that the stub has not yet relayed to the
806
+ * kernel socket, are lost when the stub exits, and it exits on the run's exit frame. A process in the machine that writes and exits has its bytes in the kernel
807
+ * already. So the exit is reported to the stub only once the queues are handed on (`pendingBytes` 0 on every stream the run wrote to or is closing) and `tailMs`
808
+ * passed since the last write (the stub's read and write to the kernel socket; measured in the report), at most `capMs`. A run that wrote nothing is not delayed.
809
+ */
810
+ async settled({ capMs = 2000, tailMs = 40 } = {}) {
811
+ if (!this.#lastSend) return
812
+ const t0 = performance.now()
813
+ for (;;) {
814
+ let pending = false
815
+ for (const s of this.#sockets.values()) if (s.kind === 'tcp' && s.st.pendingBytes > 0 && !s.st.closed) pending = true
816
+ for (const st of this.#zombies) if (st.pendingBytes > 0 && !st.closed) pending = true
817
+ const now = performance.now()
818
+ if (!pending && now - this.#lastSend >= tailMs) return
819
+ if (now - t0 >= capMs) return
820
+ await new Promise(r => setTimeout(r, 4))
821
+ }
822
+ }
823
+
824
+ /** The run is over (or the frame is gone): every stream is reset, every waiting call is answered, the poller gets BYE. Safe twice. */
825
+ close() {
826
+ if (this.#closed) return
827
+ this.#closed = true
828
+ AGG.runs++
829
+ AGG.last.push({ heldPeak: this.#peak, socketsPeak: this.#socketsPeak, withheld: this.#st.creditWithheld, refused: this.#st.sendRefused })
830
+ if (AGG.last.length > 50) AGG.last.shift()
831
+ for (const d of [...this.#dials]) d.end('the run ended')
832
+ for (const s of [...this.#sockets.values()]) {
833
+ s.gone = true
834
+ for (const w of s.ctl || []) w?.(fail('ECONNABORTED', 'the run ended'))
835
+ // A connection ends the way a process's does when it exits: what the program wrote is delivered, then the end (FIN); the stub ends its side or the
836
+ // grace time resets the stream. A reset here lost the last bytes of a program that wrote and called process.exit at once (a server answering /quit),
837
+ // now that process.exit ends the run at once (exit-now.js). A listener, a UDP socket and a dial have nothing to deliver.
838
+ if (s.kind === 'tcp' && !s.st.closed) {
839
+ const st = s.st
840
+ st.onData = u8 => st.consume(u8.length)
841
+ st.onFin = () => {}
842
+ st.onSent = null
843
+ try {
844
+ st.closeWrite()
845
+ this.#zombie(st)
846
+ } catch {
847
+ // already gone
848
+ }
849
+ continue
850
+ }
851
+ try {
852
+ s.st.abort('the run ended')
853
+ } catch {
854
+ // already gone
855
+ }
856
+ }
857
+ // the streams already closing keep their own grace time (a reset of them here would cut the bytes the program wrote before it closed them)
858
+ this.#sockets.clear()
859
+ this.#tokens.clear()
860
+ this.#events = []
861
+ this.#recv = this.#sendQ = this.#udpQ = 0
862
+ this.#withheld.clear()
863
+ this.#blockedB.clear()
864
+ this.#listeners = 0
865
+ const w = this.#waiter
866
+ this.#waiter = null
867
+ if (w) {
868
+ clearTimeout(w.timer)
869
+ w.resolve({ value: this.#record(EV.BYE, 0, new Uint8Array(0)) })
870
+ }
871
+ this.#bell()
872
+ }
873
+ }