@threadedstack/wmd-web 0.1.30 → 0.1.32
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 +23 -2
- package/RELEASE.json +123 -16
- package/guest/arm64/Image +1 -1
- package/guest/arm64/Image-4k +1 -1
- package/guest/arm64/initramfs.cpio.gz +0 -0
- package/package.json +3 -3
- package/src/boot.js +47 -2
- package/src/edge/bridge.js +297 -0
- package/src/edge/codes.js +10 -0
- package/src/edge/ctl.js +199 -0
- package/src/edge/error-kind.js +4 -0
- package/src/edge/frame.html +4 -0
- package/src/edge/frame.js +48 -0
- package/src/edge/fs-route.js +301 -0
- package/src/edge/hist.js +46 -0
- package/src/edge/msg.js +106 -0
- package/src/edge/node-args.js +194 -0
- package/src/edge/node-guest-opts.js +108 -0
- package/src/edge/node-opts.js +82 -0
- package/src/edge/own/adapter.js +271 -0
- package/src/edge/own/capi.js +200 -0
- package/src/edge/own/child-host.js +196 -0
- package/src/edge/own/fs-bridge.js +71 -0
- package/src/edge/own/fs-own-route.js +356 -0
- package/src/edge/own/guest-spawner.js +235 -0
- package/src/edge/own/hub.js +430 -0
- package/src/edge/own/loader.js +81 -0
- package/src/edge/own/memcap.js +95 -0
- package/src/edge/own/payload-size.js +15 -0
- package/src/edge/own/pool.js +160 -0
- package/src/edge/own/procfs.js +84 -0
- package/src/edge/own/serdes-codec.js +317 -0
- package/src/edge/own/service-receiver.js +98 -0
- package/src/edge/own/shim-post.js +185 -0
- package/src/edge/own/stack-fix.js +36 -0
- package/src/edge/own/stdio-pipe.js +80 -0
- package/src/edge/own/v8-serdes.js +970 -0
- package/src/edge/own/wasm-counters.js +144 -0
- package/src/edge/own/worker.js +97 -0
- package/src/edge/page.js +162 -0
- package/src/edge/plan.js +65 -0
- package/src/edge/resolve.js +44 -0
- package/src/edge/runtime.js +94 -0
- package/src/edge/sdk/adapter.js +151 -0
- package/src/edge/sdk/forward.js +80 -0
- package/src/edge/sdk/napi-stub.js +50 -0
- package/src/edge/sdk/relay.js +17 -0
- package/src/edge/service-host.js +382 -0
- package/src/edge/service-port.js +245 -0
- package/src/edge/shim.js +161 -0
- package/src/edge/site.js +106 -0
- package/src/edge/spawn-guard.js +80 -0
- package/src/edge/tz.js +103 -0
- package/src/edge/worker.js +121 -0
- package/src/edge/workers.js +27 -0
- package/src/host/chan-service.js +75 -8
- package/src/host/chan-services.js +77 -3
- package/src/host/ctl.js +26 -5
- package/src/host/edge-go.js +7 -3
- package/src/host/edge-host.js +327 -0
- package/src/host/yamux.js +21 -8
- package/wmdpack.wasm +0 -0
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// Worker pool of wmd's own runtime (X5 own runtime, step 3).
|
|
2
|
+
//
|
|
3
|
+
// A WASIX thread runs on a Web Worker. A thread that is blocked (in Atomics.wait, which is how a Rust mutex or a
|
|
4
|
+
// pipe read waits) cannot make a Worker start: creation is delivered through the event loop of the creator. So the
|
|
5
|
+
// request goes to the page, whose main thread never blocks, and the page hands out a Worker from this pool. The pool
|
|
6
|
+
// starts Workers in advance (`spare`), reuses a Worker whose task ended, and grows on demand up to `max`.
|
|
7
|
+
//
|
|
8
|
+
// The pool knows the life of a Worker, not what it runs. Messages a Worker sends:
|
|
9
|
+
// { type: 'ready' } its runtime instance is up and it waits for a task
|
|
10
|
+
// { type: 'done' } its task ended; it is idle again
|
|
11
|
+
// { type: 'crash' } its task threw (a trap): the instance is not safe to reuse, so it is ended like an error event
|
|
12
|
+
// anything else handed to onMessage(slotId, data)
|
|
13
|
+
// A task is any object; it is posted to the Worker as it is.
|
|
14
|
+
|
|
15
|
+
export class WorkerPool {
|
|
16
|
+
#create
|
|
17
|
+
#init
|
|
18
|
+
#onMessage
|
|
19
|
+
#onFailure
|
|
20
|
+
#spare
|
|
21
|
+
#max
|
|
22
|
+
#slots = new Map()
|
|
23
|
+
#next = 1
|
|
24
|
+
#closed = false
|
|
25
|
+
created = 0
|
|
26
|
+
|
|
27
|
+
constructor({ create, init = () => {}, spare = 0, max = 256, onMessage = () => {}, onFailure = () => {} }) {
|
|
28
|
+
this.#create = create
|
|
29
|
+
this.#init = init
|
|
30
|
+
this.#spare = spare
|
|
31
|
+
this.#max = max
|
|
32
|
+
this.#onMessage = onMessage
|
|
33
|
+
this.#onFailure = onFailure
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
get live() {
|
|
37
|
+
return this.#slots.size
|
|
38
|
+
}
|
|
39
|
+
get starting() {
|
|
40
|
+
return this.#count('starting')
|
|
41
|
+
}
|
|
42
|
+
get idle() {
|
|
43
|
+
return this.#count('idle')
|
|
44
|
+
}
|
|
45
|
+
get busy() {
|
|
46
|
+
return this.#count('busy')
|
|
47
|
+
}
|
|
48
|
+
// every Worker of the pool, started or not (the page forwards the threads' messages to all of them)
|
|
49
|
+
get workers() {
|
|
50
|
+
return [...this.#slots.values()].map((s) => s.worker)
|
|
51
|
+
}
|
|
52
|
+
get closed() {
|
|
53
|
+
return this.#closed
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
#count(state) {
|
|
57
|
+
let n = 0
|
|
58
|
+
for (const s of this.#slots.values()) if (s.state === state) n++
|
|
59
|
+
return n
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Workers that can take a task now or soon: idle ones, and starting ones that no task waits on.
|
|
63
|
+
#available() {
|
|
64
|
+
let n = 0
|
|
65
|
+
for (const s of this.#slots.values()) if (s.state === 'idle' || (s.state === 'starting' && s.queue.length === 0)) n++
|
|
66
|
+
return n
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Start Workers until `n` (default: the spare count) are available.
|
|
70
|
+
warm(n = this.#spare) {
|
|
71
|
+
if (this.#closed) throw new Error('pool closed')
|
|
72
|
+
while (this.#available() < n && this.#slots.size < this.#max) this.#start()
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
#start() {
|
|
76
|
+
const worker = this.#create()
|
|
77
|
+
const slot = { id: this.#next++, worker, state: 'starting', queue: [], task: null }
|
|
78
|
+
this.#slots.set(slot.id, slot)
|
|
79
|
+
this.created++
|
|
80
|
+
worker.addEventListener('message', (e) => this.#message(slot, e.data))
|
|
81
|
+
worker.addEventListener('error', (e) => this.#crash(slot, e))
|
|
82
|
+
this.#init(worker, slot.id)
|
|
83
|
+
return slot
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Give a task to a Worker; returns its slot id. Throws when the pool is closed or at its limit.
|
|
87
|
+
dispatch(task, transfer) {
|
|
88
|
+
if (this.#closed) throw new Error('pool closed')
|
|
89
|
+
let slot
|
|
90
|
+
for (const s of this.#slots.values()) {
|
|
91
|
+
if (s.state === 'idle') {
|
|
92
|
+
slot = s
|
|
93
|
+
break
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (!slot) {
|
|
97
|
+
for (const s of this.#slots.values()) {
|
|
98
|
+
if (s.state === 'starting' && s.queue.length === 0) {
|
|
99
|
+
slot = s
|
|
100
|
+
break
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (!slot) {
|
|
105
|
+
if (this.#slots.size >= this.#max) throw new RangeError('worker limit reached (' + this.#max + ')')
|
|
106
|
+
slot = this.#start()
|
|
107
|
+
}
|
|
108
|
+
if (slot.state === 'idle') this.#send(slot, task, transfer)
|
|
109
|
+
else slot.queue.push({ task, transfer })
|
|
110
|
+
if (this.#spare) this.warm()
|
|
111
|
+
return slot.id
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
#send(slot, task, transfer) {
|
|
115
|
+
slot.state = 'busy'
|
|
116
|
+
slot.task = task
|
|
117
|
+
slot.worker.postMessage(task, transfer)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
#message(slot, data) {
|
|
121
|
+
if (this.#closed || !this.#slots.has(slot.id)) return
|
|
122
|
+
const type = data && data.type
|
|
123
|
+
if (type === 'ready') {
|
|
124
|
+
if (slot.state !== 'starting') return
|
|
125
|
+
slot.state = 'idle'
|
|
126
|
+
const next = slot.queue.shift()
|
|
127
|
+
if (next) this.#send(slot, next.task, next.transfer)
|
|
128
|
+
} else if (type === 'done') {
|
|
129
|
+
slot.state = 'idle'
|
|
130
|
+
slot.task = null
|
|
131
|
+
} else if (type === 'crash') {
|
|
132
|
+
this.#crash(slot, { message: data.error })
|
|
133
|
+
} else {
|
|
134
|
+
this.#onMessage(slot.id, data)
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
#crash(slot, e) {
|
|
139
|
+
if (this.#closed || !this.#slots.has(slot.id)) return
|
|
140
|
+
this.#slots.delete(slot.id)
|
|
141
|
+
try {
|
|
142
|
+
slot.worker.terminate()
|
|
143
|
+
} catch {}
|
|
144
|
+
const lost = []
|
|
145
|
+
if (slot.task) lost.push(slot.task)
|
|
146
|
+
for (const q of slot.queue) lost.push(q.task)
|
|
147
|
+
this.#onFailure(slot.id, lost, new Error(String((e && e.message) || e || 'worker error')))
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// End every Worker (starting ones too). Later dispatch calls throw. Safe to call twice.
|
|
151
|
+
terminateAll() {
|
|
152
|
+
this.#closed = true
|
|
153
|
+
for (const s of this.#slots.values()) {
|
|
154
|
+
try {
|
|
155
|
+
s.worker.terminate()
|
|
156
|
+
} catch {}
|
|
157
|
+
}
|
|
158
|
+
this.#slots.clear()
|
|
159
|
+
}
|
|
160
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// /proc/self/stat and /proc/self/statm of the program, made by the page (round 3, item 3).
|
|
2
|
+
//
|
|
3
|
+
// Edge.js's `process.memoryUsage().rss` and `.rss()` are libuv's `uv_resident_set_memory` (libuv src/unix/linux.c, MIT): it reads
|
|
4
|
+
// /proc/self/stat, takes the 24th field (resident pages) and multiplies it by getpagesize(). In WASIX there is no /proc, the read fails
|
|
5
|
+
// and node reads 0. The page knows the one number that is the program's memory here: the size of the module's memory (all the program's
|
|
6
|
+
// threads share it). These two files show it, read at the time the file is opened. Everything else goes to the file route.
|
|
7
|
+
//
|
|
8
|
+
// withProc(route, memoryBytes) -> a route with the same `handle`, `queueSignal` and `children` that answers the two files itself.
|
|
9
|
+
|
|
10
|
+
export const PAGE_SIZE = 65536 // wasi-libc's page size, which wasix-libc's getpagesize() returns (checked in the browser run of the report)
|
|
11
|
+
const enc = new TextEncoder()
|
|
12
|
+
const FIRST = 2 ** 40 // handle ids of these files; the route's own ids count up from 1
|
|
13
|
+
const FILES = new Set(['/proc/self/stat', '/proc/self/statm'])
|
|
14
|
+
const EROFS = { error: { code: 'EROFS', message: 'EROFS' } }
|
|
15
|
+
const EBADF = { error: { code: 'EBADF', message: 'EBADF' } }
|
|
16
|
+
|
|
17
|
+
const statOf = (size, ino) => ({ k: 'f', s: size, a: '0', m: '0', c: '0', i: ino, nl: 1, md: 0o100444, u: 0, g: 0, rd: 0 })
|
|
18
|
+
|
|
19
|
+
const statDir = (ino) => ({ k: 'd', s: 4096, a: '0', m: '0', c: '0', i: ino, nl: 2, md: 0o40555, u: 0, g: 0, rd: 0 })
|
|
20
|
+
|
|
21
|
+
function content(path, bytes) {
|
|
22
|
+
const pages = Math.ceil(bytes / PAGE_SIZE)
|
|
23
|
+
if (path === '/proc/self/statm') return enc.encode(`${pages} ${pages} 0 0 0 ${pages} 0\n`)
|
|
24
|
+
// pid (comm) state ppid pgrp session tty_nr tpgid flags minflt cminflt majflt cmajflt utime stime cutime cstime priority nice
|
|
25
|
+
// num_threads itrealvalue starttime vsize rss ...: field 24 is rss in pages
|
|
26
|
+
return enc.encode(`1 (node) S 0 1 1 0 -1 4194560 0 0 0 0 0 0 0 0 20 0 1 0 0 ${bytes} ${pages} 18446744073709551615 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0\n`)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function withProc(route, memoryBytes) {
|
|
30
|
+
const open = new Map()
|
|
31
|
+
let next = FIRST
|
|
32
|
+
const clean = (p) => String(p ?? '').replace(/\/+$/, '') || '/'
|
|
33
|
+
const handle = (method, args, data) => {
|
|
34
|
+
// linux.cjs's control request `meminfo` (the shim fills process.memoryUsage().rss from it when the engine says 0). The file route
|
|
35
|
+
// of the page answers { rss: 0 }; here it is the module's memory.
|
|
36
|
+
if (method === 'ctl') {
|
|
37
|
+
let q = null
|
|
38
|
+
try {
|
|
39
|
+
q = JSON.parse(String(args[0] ?? ''))
|
|
40
|
+
} catch {}
|
|
41
|
+
if (q && q.op === 'meminfo') return { value: JSON.stringify({ rss: memoryBytes() }) }
|
|
42
|
+
}
|
|
43
|
+
if (method === 'stat' || method === 'open' || method === 'readdir') {
|
|
44
|
+
const p = clean(args[0])
|
|
45
|
+
// the directories on the way (the file system resolves the path part by part)
|
|
46
|
+
if (p === '/proc/self' || p === '/proc') {
|
|
47
|
+
if (method === 'stat') return { value: statDir(p === '/proc' ? 5 : 6) }
|
|
48
|
+
if (method === 'readdir') {
|
|
49
|
+
const names = p === '/proc' ? [['self', 'd']] : [['stat', 'f'], ['statm', 'f']]
|
|
50
|
+
return { value: { l: names.map(([n, k]) => ({ n, ...(k === 'd' ? statDir(6) : statOf(1, n === 'stat' ? 3 : 4)) })), d: true } }
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (FILES.has(p)) {
|
|
54
|
+
if (method === 'stat') return { value: statOf(content(p, memoryBytes()).length, p.endsWith('m') ? 4 : 3) }
|
|
55
|
+
const f = args[1] || {}
|
|
56
|
+
if (f.w || f.c || f.cn || f.t || f.a) return EROFS
|
|
57
|
+
const h = next++
|
|
58
|
+
open.set(h, { p, bytes: content(p, memoryBytes()) })
|
|
59
|
+
return { value: { h } }
|
|
60
|
+
}
|
|
61
|
+
} else if ((method === 'read' || method === 'fstat' || method === 'close' || method === 'write' || method === 'ftruncate') && Number(args[0]) >= FIRST) {
|
|
62
|
+
const e = open.get(args[0])
|
|
63
|
+
if (method === 'close') {
|
|
64
|
+
open.delete(args[0])
|
|
65
|
+
return { value: null }
|
|
66
|
+
}
|
|
67
|
+
if (!e) return EBADF
|
|
68
|
+
if (method === 'read') return { value: e.bytes.subarray(Number(args[1] ?? 0), Number(args[1] ?? 0) + Number(args[2] ?? 0)) }
|
|
69
|
+
if (method === 'fstat') return { value: statOf(e.bytes.length, e.p.endsWith('m') ? 4 : 3) }
|
|
70
|
+
return EROFS
|
|
71
|
+
}
|
|
72
|
+
return route.handle(method, args, data)
|
|
73
|
+
}
|
|
74
|
+
return {
|
|
75
|
+
handle,
|
|
76
|
+
queueSignal: (...a) => route.queueSignal?.(...a),
|
|
77
|
+
get children() {
|
|
78
|
+
return route.children
|
|
79
|
+
},
|
|
80
|
+
get route() {
|
|
81
|
+
return route
|
|
82
|
+
},
|
|
83
|
+
}
|
|
84
|
+
}
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
// A small structured-clone codec for the napi engine's v8.serialize (wasmer-napi's `Serializer.writeValue`, patched copy).
|
|
2
|
+
//
|
|
3
|
+
// The engine used to keep the value in a table and write only an id into the buffer; another Worker reading the buffer found the id only
|
|
4
|
+
// when the share had been handled by its event loop, which may be later than the bytes (a pipe) get there: "Wasmer serializer payload is
|
|
5
|
+
// no longer available" (F12, shown by the serializer lines: a read 2 ms after the share, "never-arrived"). With this codec the value
|
|
6
|
+
// travels inside the buffer. `encode(value)` returns the bytes, or null when the value is not one it carries (a function, a symbol, a
|
|
7
|
+
// class instance, a SharedArrayBuffer, a promise, more than LIMIT bytes): the table path then takes it, as before.
|
|
8
|
+
//
|
|
9
|
+
// Carried: undefined, null, booleans, numbers, bigints, strings, Date, RegExp, Array (with holes), plain Object, Map, Set, ArrayBuffer,
|
|
10
|
+
// typed arrays and DataView (as a copy of their own bytes), Error and its subclasses of the platform (name, message, stack, cause),
|
|
11
|
+
// cycles and shared references.
|
|
12
|
+
|
|
13
|
+
export const LIMIT = 1024 * 1024
|
|
14
|
+
|
|
15
|
+
const T = { UNDEF: 0, NULL: 1, FALSE: 2, TRUE: 3, NUM: 4, BIGINT: 5, STR: 6, DATE: 7, REGEXP: 8, ARRAY: 9, OBJECT: 10, MAP: 11, SET: 12, ABUF: 13, HOLE: 14, VIEW: 15, ERROR: 16, REF: 17 }
|
|
16
|
+
const VIEWS = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, BigInt64Array, BigUint64Array, DataView]
|
|
17
|
+
const ERRORS = ['Error', 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError']
|
|
18
|
+
|
|
19
|
+
class Unsupported extends Error {}
|
|
20
|
+
|
|
21
|
+
export function encode(value) {
|
|
22
|
+
const out = []
|
|
23
|
+
let size = 0
|
|
24
|
+
const refs = new Map()
|
|
25
|
+
const u8 = (n) => {
|
|
26
|
+
out.push(Uint8Array.of(n))
|
|
27
|
+
size += 1
|
|
28
|
+
}
|
|
29
|
+
const u32 = (n) => {
|
|
30
|
+
const b = new Uint8Array(4)
|
|
31
|
+
new DataView(b.buffer).setUint32(0, n, true)
|
|
32
|
+
out.push(b)
|
|
33
|
+
size += 4
|
|
34
|
+
}
|
|
35
|
+
const f64 = (n) => {
|
|
36
|
+
const b = new Uint8Array(8)
|
|
37
|
+
new DataView(b.buffer).setFloat64(0, n, true)
|
|
38
|
+
out.push(b)
|
|
39
|
+
size += 8
|
|
40
|
+
}
|
|
41
|
+
const bytes = (b) => {
|
|
42
|
+
if ((size += b.length) > LIMIT) throw new Unsupported()
|
|
43
|
+
out.push(b)
|
|
44
|
+
}
|
|
45
|
+
const str = (s) => {
|
|
46
|
+
u32(s.length)
|
|
47
|
+
const b = new Uint8Array(s.length * 2)
|
|
48
|
+
const dv = new DataView(b.buffer)
|
|
49
|
+
for (let i = 0; i < s.length; i++) dv.setUint16(i * 2, s.charCodeAt(i), true)
|
|
50
|
+
bytes(b)
|
|
51
|
+
}
|
|
52
|
+
const walk = (v) => {
|
|
53
|
+
if (size > LIMIT) throw new Unsupported()
|
|
54
|
+
switch (typeof v) {
|
|
55
|
+
case 'undefined':
|
|
56
|
+
return u8(T.UNDEF)
|
|
57
|
+
case 'boolean':
|
|
58
|
+
return u8(v ? T.TRUE : T.FALSE)
|
|
59
|
+
case 'number':
|
|
60
|
+
u8(T.NUM)
|
|
61
|
+
return f64(v)
|
|
62
|
+
case 'bigint':
|
|
63
|
+
u8(T.BIGINT)
|
|
64
|
+
return str(v.toString())
|
|
65
|
+
case 'string':
|
|
66
|
+
u8(T.STR)
|
|
67
|
+
return str(v)
|
|
68
|
+
case 'object':
|
|
69
|
+
break
|
|
70
|
+
default:
|
|
71
|
+
throw new Unsupported()
|
|
72
|
+
}
|
|
73
|
+
if (v === null) return u8(T.NULL)
|
|
74
|
+
if (refs.has(v)) {
|
|
75
|
+
u8(T.REF)
|
|
76
|
+
return u32(refs.get(v))
|
|
77
|
+
}
|
|
78
|
+
const proto = Object.getPrototypeOf(v)
|
|
79
|
+
const remember = () => refs.set(v, refs.size)
|
|
80
|
+
if (v instanceof Date && proto === Date.prototype) {
|
|
81
|
+
remember()
|
|
82
|
+
u8(T.DATE)
|
|
83
|
+
return f64(v.getTime())
|
|
84
|
+
}
|
|
85
|
+
if (v instanceof RegExp && proto === RegExp.prototype) {
|
|
86
|
+
remember()
|
|
87
|
+
u8(T.REGEXP)
|
|
88
|
+
str(v.source)
|
|
89
|
+
return str(v.flags)
|
|
90
|
+
}
|
|
91
|
+
if (v instanceof ArrayBuffer && proto === ArrayBuffer.prototype) {
|
|
92
|
+
remember()
|
|
93
|
+
u8(T.ABUF)
|
|
94
|
+
u32(v.byteLength)
|
|
95
|
+
return bytes(new Uint8Array(v).slice())
|
|
96
|
+
}
|
|
97
|
+
if (ArrayBuffer.isView(v)) {
|
|
98
|
+
const kind = VIEWS.findIndex((C) => v instanceof C)
|
|
99
|
+
if (kind < 0) throw new Unsupported()
|
|
100
|
+
remember()
|
|
101
|
+
u8(T.VIEW)
|
|
102
|
+
u8(kind)
|
|
103
|
+
u32(v.byteLength)
|
|
104
|
+
return bytes(new Uint8Array(v.buffer, v.byteOffset, v.byteLength).slice())
|
|
105
|
+
}
|
|
106
|
+
if (v instanceof Error) {
|
|
107
|
+
const name = ERRORS.includes(v.name) && proto === globalThis[v.name].prototype ? v.name : null
|
|
108
|
+
if (!name) throw new Unsupported()
|
|
109
|
+
remember()
|
|
110
|
+
u8(T.ERROR)
|
|
111
|
+
str(name)
|
|
112
|
+
str(String(v.message))
|
|
113
|
+
str(typeof v.stack === 'string' ? v.stack : '')
|
|
114
|
+
if ('cause' in v) {
|
|
115
|
+
u8(1)
|
|
116
|
+
return walk(v.cause)
|
|
117
|
+
}
|
|
118
|
+
return u8(0)
|
|
119
|
+
}
|
|
120
|
+
if (Array.isArray(v) && proto === Array.prototype) {
|
|
121
|
+
remember()
|
|
122
|
+
u8(T.ARRAY)
|
|
123
|
+
u32(v.length)
|
|
124
|
+
for (let i = 0; i < v.length; i++) {
|
|
125
|
+
if (i in v) walk(v[i])
|
|
126
|
+
else u8(T.HOLE)
|
|
127
|
+
}
|
|
128
|
+
return
|
|
129
|
+
}
|
|
130
|
+
if (v instanceof Map && proto === Map.prototype) {
|
|
131
|
+
remember()
|
|
132
|
+
u8(T.MAP)
|
|
133
|
+
u32(v.size)
|
|
134
|
+
for (const [k, x] of v) {
|
|
135
|
+
walk(k)
|
|
136
|
+
walk(x)
|
|
137
|
+
}
|
|
138
|
+
return
|
|
139
|
+
}
|
|
140
|
+
if (v instanceof Set && proto === Set.prototype) {
|
|
141
|
+
remember()
|
|
142
|
+
u8(T.SET)
|
|
143
|
+
u32(v.size)
|
|
144
|
+
for (const x of v) walk(x)
|
|
145
|
+
return
|
|
146
|
+
}
|
|
147
|
+
if (proto === Object.prototype || proto === null) {
|
|
148
|
+
remember()
|
|
149
|
+
u8(T.OBJECT)
|
|
150
|
+
const keys = Object.keys(v)
|
|
151
|
+
u32(keys.length)
|
|
152
|
+
for (const k of keys) {
|
|
153
|
+
str(k)
|
|
154
|
+
walk(v[k])
|
|
155
|
+
}
|
|
156
|
+
return
|
|
157
|
+
}
|
|
158
|
+
throw new Unsupported()
|
|
159
|
+
}
|
|
160
|
+
try {
|
|
161
|
+
walk(value)
|
|
162
|
+
} catch (e) {
|
|
163
|
+
if (e instanceof Unsupported) return null
|
|
164
|
+
throw e
|
|
165
|
+
}
|
|
166
|
+
const all = new Uint8Array(size)
|
|
167
|
+
let at = 0
|
|
168
|
+
for (const b of out) {
|
|
169
|
+
all.set(b, at)
|
|
170
|
+
at += b.length
|
|
171
|
+
}
|
|
172
|
+
return all
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function decode(buf) {
|
|
176
|
+
const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
|
|
177
|
+
let at = 0
|
|
178
|
+
const need = (n) => {
|
|
179
|
+
if (n < 0 || at + n > buf.length) throw new RangeError('serdes codec: unexpected end of buffer')
|
|
180
|
+
}
|
|
181
|
+
const u8 = () => {
|
|
182
|
+
need(1)
|
|
183
|
+
return buf[at++]
|
|
184
|
+
}
|
|
185
|
+
const u32 = () => {
|
|
186
|
+
need(4)
|
|
187
|
+
const n = dv.getUint32(at, true)
|
|
188
|
+
at += 4
|
|
189
|
+
return n
|
|
190
|
+
}
|
|
191
|
+
const f64 = () => {
|
|
192
|
+
need(8)
|
|
193
|
+
const n = dv.getFloat64(at, true)
|
|
194
|
+
at += 8
|
|
195
|
+
return n
|
|
196
|
+
}
|
|
197
|
+
const str = () => {
|
|
198
|
+
const n = u32()
|
|
199
|
+
need(n * 2)
|
|
200
|
+
let s = ''
|
|
201
|
+
for (let i = 0; i < n; i += 4096) {
|
|
202
|
+
const part = []
|
|
203
|
+
for (let j = i; j < Math.min(n, i + 4096); j++) part.push(dv.getUint16(at + j * 2, true))
|
|
204
|
+
s += String.fromCharCode(...part)
|
|
205
|
+
}
|
|
206
|
+
at += n * 2
|
|
207
|
+
return s
|
|
208
|
+
}
|
|
209
|
+
const refs = []
|
|
210
|
+
const read = () => {
|
|
211
|
+
const t = u8()
|
|
212
|
+
switch (t) {
|
|
213
|
+
case T.UNDEF:
|
|
214
|
+
return undefined
|
|
215
|
+
case T.NULL:
|
|
216
|
+
return null
|
|
217
|
+
case T.FALSE:
|
|
218
|
+
return false
|
|
219
|
+
case T.TRUE:
|
|
220
|
+
return true
|
|
221
|
+
case T.NUM:
|
|
222
|
+
return f64()
|
|
223
|
+
case T.BIGINT:
|
|
224
|
+
return BigInt(str())
|
|
225
|
+
case T.STR:
|
|
226
|
+
return str()
|
|
227
|
+
case T.REF: {
|
|
228
|
+
const i = u32()
|
|
229
|
+
if (i >= refs.length) throw new RangeError('serdes codec: bad reference')
|
|
230
|
+
return refs[i]
|
|
231
|
+
}
|
|
232
|
+
case T.DATE: {
|
|
233
|
+
const d = new Date(f64())
|
|
234
|
+
refs.push(d)
|
|
235
|
+
return d
|
|
236
|
+
}
|
|
237
|
+
case T.REGEXP: {
|
|
238
|
+
const r = new RegExp(str(), str())
|
|
239
|
+
refs.push(r)
|
|
240
|
+
return r
|
|
241
|
+
}
|
|
242
|
+
case T.ABUF: {
|
|
243
|
+
const n = u32()
|
|
244
|
+
need(n)
|
|
245
|
+
const ab = buf.slice(at, at + n).buffer
|
|
246
|
+
at += n
|
|
247
|
+
refs.push(ab)
|
|
248
|
+
return ab
|
|
249
|
+
}
|
|
250
|
+
case T.VIEW: {
|
|
251
|
+
const C = VIEWS[u8()]
|
|
252
|
+
const n = u32()
|
|
253
|
+
if (!C) throw new RangeError('serdes codec: bad view')
|
|
254
|
+
need(n)
|
|
255
|
+
const ab = buf.slice(at, at + n).buffer
|
|
256
|
+
at += n
|
|
257
|
+
const view = C === DataView ? new DataView(ab) : new C(ab)
|
|
258
|
+
refs.push(view)
|
|
259
|
+
return view
|
|
260
|
+
}
|
|
261
|
+
case T.ERROR: {
|
|
262
|
+
const name = str()
|
|
263
|
+
if (!ERRORS.includes(name)) throw new RangeError('serdes codec: bad error')
|
|
264
|
+
const e = new globalThis[name](str())
|
|
265
|
+
const stack = str()
|
|
266
|
+
refs.push(e)
|
|
267
|
+
Object.defineProperty(e, 'stack', { value: stack, writable: true, configurable: true, enumerable: false })
|
|
268
|
+
if (u8()) Object.defineProperty(e, 'cause', { value: read(), writable: true, configurable: true, enumerable: false })
|
|
269
|
+
return e
|
|
270
|
+
}
|
|
271
|
+
case T.ARRAY: {
|
|
272
|
+
const n = u32()
|
|
273
|
+
const a = []
|
|
274
|
+
refs.push(a)
|
|
275
|
+
a.length = n
|
|
276
|
+
for (let i = 0; i < n; i++) {
|
|
277
|
+
if (buf[at] === T.HOLE) {
|
|
278
|
+
at++
|
|
279
|
+
continue
|
|
280
|
+
}
|
|
281
|
+
a[i] = read()
|
|
282
|
+
}
|
|
283
|
+
return a
|
|
284
|
+
}
|
|
285
|
+
case T.MAP: {
|
|
286
|
+
const n = u32()
|
|
287
|
+
const m = new Map()
|
|
288
|
+
refs.push(m)
|
|
289
|
+
for (let i = 0; i < n; i++) {
|
|
290
|
+
const k = read()
|
|
291
|
+
m.set(k, read())
|
|
292
|
+
}
|
|
293
|
+
return m
|
|
294
|
+
}
|
|
295
|
+
case T.SET: {
|
|
296
|
+
const n = u32()
|
|
297
|
+
const s = new Set()
|
|
298
|
+
refs.push(s)
|
|
299
|
+
for (let i = 0; i < n; i++) s.add(read())
|
|
300
|
+
return s
|
|
301
|
+
}
|
|
302
|
+
case T.OBJECT: {
|
|
303
|
+
const n = u32()
|
|
304
|
+
const o = {}
|
|
305
|
+
refs.push(o)
|
|
306
|
+
for (let i = 0; i < n; i++) {
|
|
307
|
+
const k = str()
|
|
308
|
+
Object.defineProperty(o, k, { value: read(), writable: true, configurable: true, enumerable: true })
|
|
309
|
+
}
|
|
310
|
+
return o
|
|
311
|
+
}
|
|
312
|
+
default:
|
|
313
|
+
throw new RangeError(`serdes codec: unknown tag ${t}`)
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
return read()
|
|
317
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// The service's end of the seam's file messages (round 3, item 5). The adapter (adapter.js) posts, on the port it was given,
|
|
2
|
+
// {own: 'fs', id, method, args, data} one call of the program's file route or child interface
|
|
3
|
+
// {own: 'bye'} the run is over (release): the children it started end
|
|
4
|
+
// and waits for {id, reply} where reply is {value} or {error: {code, message}}. The side that owns the machine's Overlay serves
|
|
5
|
+
// them with an OwnFsRoute (fs-own-route.js) and, for `child_*` calls, the route's ChildHost (child-host.js).
|
|
6
|
+
//
|
|
7
|
+
// `serveOwnFs(port, route)` is the whole receiver. A service that has its own message handler calls `ownFsMessage(route, m)` for the
|
|
8
|
+
// messages it does not know and sends what it returns. Differences from the loop the test page used to carry:
|
|
9
|
+
// * a reply that is a promise is awaited (`child_read` waits for the child's next event; a promise cannot be posted);
|
|
10
|
+
// * a call that throws is answered as an error, never left without an answer (the program's thread waits for it);
|
|
11
|
+
// * calls are answered in the order they arrive when they do not wait, and a waiting call does not hold up the others;
|
|
12
|
+
// * a message that is not ours is ignored (the port may carry other kinds), and `bye` ends the children and the loop.
|
|
13
|
+
|
|
14
|
+
const errReply = (code, message) => ({ error: { code, message: String(message || code) } })
|
|
15
|
+
|
|
16
|
+
/** The answer to one `{own:'fs'}` message: a value or a promise of it, always {value} or {error}. */
|
|
17
|
+
export function ownFsMessage(route, m) {
|
|
18
|
+
try {
|
|
19
|
+
return route.handle(m.method, Array.isArray(m.args) ? m.args : [], m.data || new Uint8Array(0))
|
|
20
|
+
} catch (e) {
|
|
21
|
+
return errReply((e && e.code) || 'EIO', (e && e.message) || e)
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* @param {MessagePort} port
|
|
27
|
+
* @param {{handle: Function, children?: {killAll: Function}}} route an OwnFsRoute
|
|
28
|
+
* @param {{onClose?: () => void, onError?: (e: unknown) => void, onTraffic?: () => void}} [o]
|
|
29
|
+
* @returns {{close: () => void, stats: () => {served: number, waiting: number, bad: number}}}
|
|
30
|
+
*/
|
|
31
|
+
export function serveOwnFs(port, route, { onClose, onError, onTraffic, kickAll = false } = {}) {
|
|
32
|
+
let served = 0
|
|
33
|
+
let waiting = 0
|
|
34
|
+
let bad = 0
|
|
35
|
+
let open = true
|
|
36
|
+
const stop = () => {
|
|
37
|
+
if (!open) return
|
|
38
|
+
open = false
|
|
39
|
+
port.onmessage = null
|
|
40
|
+
try {
|
|
41
|
+
route.children?.killAll?.()
|
|
42
|
+
} catch (e) {
|
|
43
|
+
onError?.(e)
|
|
44
|
+
}
|
|
45
|
+
onClose?.()
|
|
46
|
+
}
|
|
47
|
+
const answer = (id, reply, method) => {
|
|
48
|
+
if (!open) return
|
|
49
|
+
try {
|
|
50
|
+
port.postMessage({ id, reply })
|
|
51
|
+
// The owner's loop has more to send after a call about a child (its bytes leave through the machine's doorbell). A file call does not
|
|
52
|
+
// ring it: each ring made the loop spin for its window (service loop, chan-service.js) and the next call waited for the spin to end
|
|
53
|
+
// (fix5 round 6: 126 us from the Worker's post to the handler, against 16 us without; kickAll gives the old behaviour back for a test).
|
|
54
|
+
if (kickAll || (typeof method === 'string' && method.startsWith('child_'))) onTraffic?.()
|
|
55
|
+
} catch (e) {
|
|
56
|
+
// a value that cannot be posted: tell the program instead of leaving it waiting
|
|
57
|
+
onError?.(e)
|
|
58
|
+
try {
|
|
59
|
+
port.postMessage({ id, reply: errReply('EIO', 'the reply could not be posted: ' + ((e && e.message) || e)) })
|
|
60
|
+
} catch {
|
|
61
|
+
// the port is gone
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
port.onmessage = (e) => {
|
|
66
|
+
const m = e.data
|
|
67
|
+
if (!m || typeof m !== 'object') return
|
|
68
|
+
if (m.own === 'bye') return stop()
|
|
69
|
+
if (m.own !== 'fs' || typeof m.method !== 'string') {
|
|
70
|
+
if (m.own === 'fs') {
|
|
71
|
+
bad++
|
|
72
|
+
answer(m.id, errReply('EINVAL', 'a file message needs a method'))
|
|
73
|
+
}
|
|
74
|
+
return
|
|
75
|
+
}
|
|
76
|
+
if (route.timing && typeof m.t0 === 'number') {
|
|
77
|
+
// fix5 round 6 (counters on): how long the message took to be taken up here, from the Worker's post to this handler
|
|
78
|
+
const h = (route.timing['hop1'] ||= { n: 0, ms: 0, inB: 0, outB: 0 })
|
|
79
|
+
h.n++
|
|
80
|
+
h.ms += performance.timeOrigin + performance.now() - m.t0
|
|
81
|
+
}
|
|
82
|
+
const r = ownFsMessage(route, m)
|
|
83
|
+
if (r && typeof r.then === 'function') {
|
|
84
|
+
waiting++
|
|
85
|
+
r.then(
|
|
86
|
+
(v) => answer(m.id, v, m.method),
|
|
87
|
+
(err) => answer(m.id, errReply((err && err.code) || 'EIO', (err && err.message) || err), m.method),
|
|
88
|
+
).finally(() => {
|
|
89
|
+
waiting--
|
|
90
|
+
served++
|
|
91
|
+
})
|
|
92
|
+
} else {
|
|
93
|
+
served++
|
|
94
|
+
answer(m.id, r, m.method)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return { close: stop, stats: () => ({ served, waiting, bad }) }
|
|
98
|
+
}
|