@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.
Files changed (62) hide show
  1. package/README.md +23 -2
  2. package/RELEASE.json +123 -16
  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 +47 -2
  8. package/src/edge/bridge.js +297 -0
  9. package/src/edge/codes.js +10 -0
  10. package/src/edge/ctl.js +199 -0
  11. package/src/edge/error-kind.js +4 -0
  12. package/src/edge/frame.html +4 -0
  13. package/src/edge/frame.js +48 -0
  14. package/src/edge/fs-route.js +301 -0
  15. package/src/edge/hist.js +46 -0
  16. package/src/edge/msg.js +106 -0
  17. package/src/edge/node-args.js +194 -0
  18. package/src/edge/node-guest-opts.js +108 -0
  19. package/src/edge/node-opts.js +82 -0
  20. package/src/edge/own/adapter.js +271 -0
  21. package/src/edge/own/capi.js +200 -0
  22. package/src/edge/own/child-host.js +196 -0
  23. package/src/edge/own/fs-bridge.js +71 -0
  24. package/src/edge/own/fs-own-route.js +356 -0
  25. package/src/edge/own/guest-spawner.js +235 -0
  26. package/src/edge/own/hub.js +430 -0
  27. package/src/edge/own/loader.js +81 -0
  28. package/src/edge/own/memcap.js +95 -0
  29. package/src/edge/own/payload-size.js +15 -0
  30. package/src/edge/own/pool.js +160 -0
  31. package/src/edge/own/procfs.js +84 -0
  32. package/src/edge/own/serdes-codec.js +317 -0
  33. package/src/edge/own/service-receiver.js +98 -0
  34. package/src/edge/own/shim-post.js +185 -0
  35. package/src/edge/own/stack-fix.js +36 -0
  36. package/src/edge/own/stdio-pipe.js +80 -0
  37. package/src/edge/own/v8-serdes.js +970 -0
  38. package/src/edge/own/wasm-counters.js +144 -0
  39. package/src/edge/own/worker.js +97 -0
  40. package/src/edge/page.js +162 -0
  41. package/src/edge/plan.js +65 -0
  42. package/src/edge/resolve.js +44 -0
  43. package/src/edge/runtime.js +94 -0
  44. package/src/edge/sdk/adapter.js +151 -0
  45. package/src/edge/sdk/forward.js +80 -0
  46. package/src/edge/sdk/napi-stub.js +50 -0
  47. package/src/edge/sdk/relay.js +17 -0
  48. package/src/edge/service-host.js +382 -0
  49. package/src/edge/service-port.js +245 -0
  50. package/src/edge/shim.js +161 -0
  51. package/src/edge/site.js +106 -0
  52. package/src/edge/spawn-guard.js +80 -0
  53. package/src/edge/tz.js +103 -0
  54. package/src/edge/worker.js +121 -0
  55. package/src/edge/workers.js +27 -0
  56. package/src/host/chan-service.js +75 -8
  57. package/src/host/chan-services.js +77 -3
  58. package/src/host/ctl.js +26 -5
  59. package/src/host/edge-go.js +7 -3
  60. package/src/host/edge-host.js +327 -0
  61. package/src/host/yamux.js +21 -8
  62. package/wmdpack.wasm +0 -0
@@ -0,0 +1,200 @@
1
+ // The host half of node's messages between threads (worker_threads, MessagePort) for the napi engine of wasmer-napi.
2
+ //
3
+ // The engine (edge/vendor/wasmer-napi/src/snapi_js.rs, "wasmerNapiHostCapi...") expects five functions on the global of every
4
+ // Worker, read when its module loads:
5
+ // __wasmerCapiShare(registry, handle, { value }) keep a value under a handle for another thread to take
6
+ // __wasmerCapiObtain(registry, handle) the { value } kept under the handle, or undefined
7
+ // __wasmerCapiWait(registry, handle) a promise that settles once the handle's value is here (the sender's thread
8
+ // wakes the receiver's loop before the value may have crossed)
9
+ // __wasmerCapiDelete(registry, handle) the value is no longer needed (by any thread)
10
+ // __wasmerCapiMessageScope() a number below 4096 that no other thread of the program has: the handles
11
+ // a thread makes carry it in their top 12 bits
12
+ // Every Worker of one runtime keeps its own table. A share is copied (structured clone) to every other Worker over one
13
+ // BroadcastChannel, which all Workers of the runtime join under a name the page makes; a delete is broadcast the same way, so
14
+ // copies nobody took are dropped when the taker is done. A value that cannot be cloned makes `share` throw (the engine
15
+ // reports it as a pending exception on the sender's side).
16
+ //
17
+ // installCapi(globalThis, { channel, scope, BroadcastChannel?, log? }) -> { close() } (log: a function that gets one line per call)
18
+
19
+ import { decode, encode } from './serdes-codec.js'
20
+ import { makeSerdesBinding } from './v8-serdes.js'
21
+ import { BIG_SHARE, payloadBytes } from './payload-size.js'
22
+
23
+ /** How many deleted handles one thread remembers (fix7 F8). */
24
+ const GONE_LIMIT = 4096
25
+
26
+ const key = (registry, handle) => `${registry}:${handle}`
27
+
28
+ export function installCapi(g, { channel, scope, BroadcastChannel: BC = g.BroadcastChannel, relay = null, log = null }) {
29
+ if (!Number.isInteger(scope) || scope < 0 || scope > 4095) throw new Error(`capi: scope ${scope} is not below 4096`)
30
+ const table = new Map()
31
+ const waiting = new Map()
32
+ const gone = new Map() // handles deleted: key -> 'here' (this thread deleted it) or 'from <scope>' (another thread's delete arrived); a late copy (a resend that crossed the delete) is not kept
33
+ // fix7 (F8): the record is bounded, oldest first (a program that makes a message per second would grow it without end). A late copy of a handle
34
+ // older than the last GONE_LIMIT deletes is kept: it stays in the table until a delete or the end of the run, as a copy nobody asked for.
35
+ const markGone = (k, who) => {
36
+ gone.delete(k)
37
+ gone.set(k, who)
38
+ if (gone.size > GONE_LIMIT) for (const old of gone.keys()) {
39
+ gone.delete(old)
40
+ if (gone.size <= GONE_LIMIT) break
41
+ }
42
+ }
43
+ const mine = new Map() // what this thread shared and nobody has deleted: a Worker that starts later asks for it (see 'hello')
44
+ // the way to the other Workers: a BroadcastChannel (unit tests) or `relay(message)` (the page forwards it to every Worker and each
45
+ // Worker's `receive`). A BroadcastChannel cannot carry what node's messages carry (a SharedArrayBuffer comes out as a messageerror and
46
+ // the whole message is lost), a Worker's postMessage to the page and from the page to a Worker can.
47
+ const bc = !relay && channel && BC ? new BC(channel) : null
48
+ const open = !!(bc || relay)
49
+ const send = (msg) => (relay ? relay({ ...msg, from: scope }) : bc.postMessage(msg))
50
+ const put = (k, envelope) => {
51
+ table.set(k, envelope)
52
+ const ws = waiting.get(k)
53
+ if (ws) {
54
+ waiting.delete(k)
55
+ for (const w of ws) w.resolve(undefined)
56
+ }
57
+ }
58
+ const receive = (d) => {
59
+ if (!d || d.from === scope) return
60
+ if (log) log(`got ${d.t} ${d.handle}`)
61
+ if (d.t === 'share') {
62
+ if (!gone.has(key(d.registry, d.handle))) put(key(d.registry, d.handle), d.envelope)
63
+ else if (log) log(`late copy of ${d.handle} dropped (deleted ${gone.get(key(d.registry, d.handle))})`)
64
+ } else if (d.t === 'delete') {
65
+ table.delete(key(d.registry, d.handle))
66
+ mine.delete(key(d.registry, d.handle))
67
+ markGone(key(d.registry, d.handle), 'from ' + d.from)
68
+ } else if (d.t === 'hello') {
69
+ if (log) log(`hello: sending again ${[...mine.values()].map((m) => m.handle).join(',') || 'nothing'}`)
70
+ // a large share is held by the page and sent to whoever asks (hub.js), so a new thread does not make the sender copy it again
71
+ for (const [, m] of mine) if (payloadBytes(m.envelope) < BIG_SHARE) send({ t: 'share', registry: m.registry, handle: m.handle, envelope: m.envelope })
72
+ }
73
+ }
74
+ if (bc) {
75
+ bc.onmessage = (e) => receive(e.data)
76
+ bc.onmessageerror = () => {
77
+ if (log) log('a message from another Worker could not be read here (messageerror)')
78
+ }
79
+ }
80
+ // a broadcast only reaches the Workers that exist: the first message of a new node Worker is shared by its parent before the
81
+ // Worker's own thread starts. The new thread says hello, and every thread sends again what it shared and still keeps.
82
+ if (open) send({ t: 'hello' })
83
+
84
+ g.__wasmerCapiShare = (registry, handle, envelope) => {
85
+ if (log) log(`share ${handle} ${typeof envelope?.value} ${String(Object.prototype.toString.call(envelope?.value))}`)
86
+ // the clone happens first: a value that cannot cross makes the call throw before anything is kept
87
+ try {
88
+ if (open) send({ t: 'share', registry, handle, envelope })
89
+ } catch (e) {
90
+ if (log) {
91
+ let what = ''
92
+ try {
93
+ const v = envelope && envelope.value
94
+ what = v && typeof v === 'object' ? Object.keys(v).map((k) => `${k}:${typeof v[k]}`).join(',') : typeof v
95
+ } catch (e2) {
96
+ what = 'unreadable ' + String(e2)
97
+ }
98
+ log(`share ${handle} could not be copied: ${String((e && e.name) || '')} ${String((e && e.message) || e).slice(0, 200)} (${what})`)
99
+ }
100
+ throw e
101
+ }
102
+ mine.set(key(registry, handle), { registry, handle, envelope })
103
+ put(key(registry, handle), envelope)
104
+ }
105
+ g.__wasmerCapiObtain = (registry, handle) => {
106
+ if (log) log(`obtain ${handle} ${table.has(key(registry, handle))}`)
107
+ return table.get(key(registry, handle))
108
+ }
109
+ g.__wasmerCapiWait = (registry, handle) => {
110
+ const k = key(registry, handle)
111
+ if (log) log(`wait ${registry}:${handle} ${table.has(k)}`)
112
+ if (table.has(k)) return Promise.resolve(undefined)
113
+ // not here (yet): a small share is on its way to every Worker; a large one is held by the page, which sends it to the Worker that asks
114
+ if (open) send({ t: 'want', registry, handle })
115
+ return new Promise((resolve, reject) => {
116
+ const list = waiting.get(k) || []
117
+ list.push({ resolve, reject })
118
+ waiting.set(k, list)
119
+ })
120
+ }
121
+ g.__wasmerCapiDelete = (registry, handle) => {
122
+ if (log) log(`delete ${handle}`)
123
+ table.delete(key(registry, handle))
124
+ mine.delete(key(registry, handle))
125
+ markGone(key(registry, handle), 'here')
126
+ if (open) send({ t: 'delete', registry, handle })
127
+ }
128
+ // what this thread knows about a handle (diagnostics): in the table, shared by this thread, or deleted (and by whom)
129
+ g.__wasmerCapiInfo = (registry, handle) => ({ inTable: table.has(key(registry, handle)), mine: mine.has(key(registry, handle)), gone: gone.get(key(registry, handle)) || null, tableSize: table.size })
130
+ g.__wasmerCapiMessageScope = () => scope
131
+ return {
132
+ receive,
133
+ close() {
134
+ if (bc) bc.close()
135
+ for (const ws of waiting.values()) for (const w of ws) w.reject(new Error('capi: closed'))
136
+ waiting.clear()
137
+ },
138
+ table,
139
+ goneLimit: GONE_LIMIT,
140
+ goneSize: () => gone.size,
141
+ }
142
+ }
143
+
144
+ // The engine (snapi_js.rs, v8.serialize and v8.deserialize) keeps what a serializer wrote in a table on the global of the Worker it
145
+ // runs on and writes only an id into the buffer. A buffer that crosses to another thread (the error of a node Worker, a message with
146
+ // a serialized value) then reads an id the other thread does not have ("payload is no longer available"). This puts the engine's
147
+ // table in front of the same capi shares the messages use: `set` shares the value, `get` takes it, `delete` drops it. The ids
148
+ // carry the Worker's number in their top 12 bits so no two Workers make the same one. Install it before the engine's module loads.
149
+ export function installSerdesState(g, { scope, note = null }) {
150
+ let next = scope * 2 ** 20 + 1
151
+ // fix5 round 6 item 3 (diagnostics, only with `note`): one line per share, read and miss; a miss says why (never arrived, deleted here,
152
+ // deleted by another thread) and which thread wrote the id (its top 12 bits)
153
+ const say = (ev, id, extra = '') => note && note(`SERDES ${Math.round(performance.timeOrigin + performance.now()) % 1e7} s${scope} ${ev} ${id} w${Math.floor(id / 2 ** 20)}${extra}`)
154
+ const seen = new Set()
155
+ const state = {
156
+ get next() {
157
+ return next
158
+ },
159
+ set next(v) {
160
+ next = v
161
+ },
162
+ // the value travels inside the buffer when the codec carries it (the patched engine asks; serdes-codec.js)
163
+ codec: {
164
+ encode: (value) => {
165
+ const bytes = encode(value)
166
+ if (note) say(bytes ? 'inline' : 'byid', 0, ` ${bytes ? bytes.length : 0}`)
167
+ return bytes
168
+ },
169
+ decode,
170
+ },
171
+ values: {
172
+ set: (id, value) => {
173
+ say('share', id)
174
+ return g.__wasmerCapiShare(0x53455244, id, { value })
175
+ },
176
+ has: (id) => {
177
+ const hit = g.__wasmerCapiObtain(0x53455244, id) !== undefined
178
+ if (note) {
179
+ if (hit) say('has', id, seen.has(id) ? ' AGAIN' : '')
180
+ else {
181
+ const i = g.__wasmerCapiInfo ? g.__wasmerCapiInfo(0x53455244, id) : {}
182
+ say('MISS', id, ` ${seen.has(id) ? 'read-before-here' : i.gone ? 'deleted-' + i.gone.replace(' ', '-') : i.mine ? 'mine-not-in-table' : 'never-arrived'} table=${i.tableSize}`)
183
+ }
184
+ seen.add(id)
185
+ }
186
+ return hit
187
+ },
188
+ get: (id) => g.__wasmerCapiObtain(0x53455244, id)?.value,
189
+ delete: (id) => {
190
+ say('delete', id)
191
+ return g.__wasmerCapiDelete(0x53455244, id)
192
+ },
193
+ },
194
+ // fix7 (F3, F4): the Serializer and Deserializer the engine gives node: V8's own wire format (v8-serdes.js). `bufferOf` is set by the program's
195
+ // shim (shim-post.js) once node's Buffer exists: v8.serialize gives a Buffer.
196
+ binding: () => makeSerdesBinding({ bufferOf: (u8) => (state.bufferOf ? state.bufferOf(u8) : u8) }),
197
+ bufferOf: null,
198
+ }
199
+ g[Symbol.for('wasmer.napi.serdes.state')] = state
200
+ }
@@ -0,0 +1,196 @@
1
+ // The page's end of the child process interface of the own runtime (edge/browser/src/child.rs `PageChild`).
2
+ //
3
+ // The runtime asks four things of the page (methods of the route that carries the file calls, see fs-bridge.js):
4
+ // child_start [{path, argv, env, cwd}] -> {id} an error with a Linux errno name when the file cannot be run
5
+ // child_stdin [id, eof] data = bytes -> null
6
+ // child_read [id] -> Uint8Array waits for the next event of the child: 1 + bytes = standard output,
7
+ // 2 + bytes = standard error, 3 + int32 LE code + uint8 signal = exit
8
+ // child_signal [id, n] -> null
9
+ //
10
+ // What runs the child is a `spawner`, one function (it may be async; guest-spawner.js is):
11
+ // spawner({path, argv, env, cwd}) -> child | throws {code: 'ENOENT'}
12
+ // child: { write(bytes), end(), kill(n), onOut(fn(bytes)), onErr(fn(bytes)), onExit(fn(code, signal)) }
13
+ // Callbacks may be set right after the call returns; events that come first are held. The real spawner (a container's own process,
14
+ // reached through the wmd service) is guest-spawner.js; `standInSpawner` below is what the browser tests use.
15
+
16
+ const ENDED_KEEP = 4096
17
+ const TAG = { out: 1, err: 2, exit: 3 }
18
+
19
+ export class ChildHost {
20
+ #spawner
21
+ #next = 1
22
+ #kids = new Map()
23
+ #ended = new Set() // ids whose exit was read, the last ENDED_KEEP of them (fix7 F9: the runtime closes a child's input after the exit)
24
+ /** Counters of the calls and events of this host (a hang is told by which one is missing): start, started, startFailed, stdin, read, signal, exits. */
25
+ stats
26
+
27
+ constructor(spawner, stats = {}) {
28
+ this.#spawner = spawner
29
+ this.stats = stats
30
+ }
31
+
32
+ get count() {
33
+ return this.#kids.size
34
+ }
35
+
36
+ async handle(method, args, data) {
37
+ try {
38
+ switch (method) {
39
+ case 'child_start':
40
+ bump(this.stats, 'start')
41
+ return { value: { id: await this.#start(args[0]) } }
42
+ case 'child_stdin': {
43
+ if (!this.#kids.has(args[0]) && this.#ended.has(args[0])) {
44
+ // the child ended and its exit was read: closing its input is nothing to do, data to it is a broken pipe
45
+ if (data && data.length) throw Object.assign(new Error('the child ended'), { code: 'EPIPE' })
46
+ bump(this.stats, 'stdinAfterExit')
47
+ return { value: null }
48
+ }
49
+ const k = this.#kid(args[0])
50
+ bump(this.stats, 'stdin')
51
+ if (data && data.length) k.child.write(data)
52
+ if (args[1]) k.child.end()
53
+ return { value: null }
54
+ }
55
+ case 'child_read':
56
+ bump(this.stats, 'read')
57
+ return { value: await this.#read(this.#kid(args[0]), args[0]) }
58
+ case 'child_signal':
59
+ bump(this.stats, 'signal')
60
+ this.#kid(args[0]).child.kill(Number(args[1]))
61
+ return { value: null }
62
+ default:
63
+ return { error: { code: 'ENOSYS', message: 'no such child call: ' + method } }
64
+ }
65
+ } catch (e) {
66
+ bump(this.stats, 'failed')
67
+ bump(this.stats, 'failed_' + method)
68
+ this.stats.lastError = String((e && e.code) || '') + ' ' + String((e && e.message) || e).slice(0, 120)
69
+ return { error: { code: (e && e.code) || 'EIO', message: String((e && e.message) || e) } }
70
+ }
71
+ }
72
+
73
+ #kid(id) {
74
+ const k = this.#kids.get(id)
75
+ if (!k) throw Object.assign(new Error('no such child ' + id), { code: 'ESRCH' })
76
+ return k
77
+ }
78
+
79
+ async #start(req) {
80
+ const child = await this.#spawner(req)
81
+ const id = this.#next++
82
+ const k = { child, events: [], waiter: null }
83
+ const push = ev => {
84
+ k.events.push(ev)
85
+ if (k.waiter) {
86
+ const w = k.waiter
87
+ k.waiter = null
88
+ w()
89
+ }
90
+ }
91
+ child.onOut(b => push(frame(TAG.out, b)))
92
+ child.onErr(b => push(frame(TAG.err, b)))
93
+ child.onExit((code, signal) => {
94
+ bump(this.stats, 'exits')
95
+ const e = new Uint8Array(6)
96
+ e[0] = TAG.exit
97
+ new DataView(e.buffer).setInt32(1, code | 0, true)
98
+ e[5] = signal || 0
99
+ push(e)
100
+ })
101
+ this.#kids.set(id, k)
102
+ bump(this.stats, 'started')
103
+ return id
104
+ }
105
+
106
+ async #read(k, id) {
107
+ while (!k.events.length) await new Promise(r => (k.waiter = r))
108
+ const ev = k.events.shift()
109
+ if (ev[0] === TAG.exit) {
110
+ this.#kids.delete(id)
111
+ this.#ended.add(id)
112
+ if (this.#ended.size > ENDED_KEEP) this.#ended.delete(this.#ended.values().next().value)
113
+ }
114
+ return ev
115
+ }
116
+
117
+ /** Ends every child still running (the program ended). */
118
+ killAll() {
119
+ for (const k of this.#kids.values()) k.child.kill(9)
120
+ }
121
+ }
122
+
123
+ const bump = (o, k) => (o[k] = (o[k] || 0) + 1)
124
+
125
+ function frame(tag, bytes) {
126
+ const f = new Uint8Array(bytes.length + 1)
127
+ f[0] = tag
128
+ f.set(bytes, 1)
129
+ return f
130
+ }
131
+
132
+ /**
133
+ * A stand-in for the page's spawner: it runs `sh -c '<script>'` for a script of echo, printf, cat, exit and sleep (a line is a
134
+ * command, `;` separates them), and `cat` with no arguments copies standard input. Anything else exits 127. This is not a shell;
135
+ * it is the piece the tests need until the real spawner exists (item 6 of the report names what is left to join).
136
+ */
137
+ export function standInSpawner(req) {
138
+ const base = String(req.path).split('/').pop()
139
+ if (base !== 'sh') throw Object.assign(new Error('no such file: ' + req.path), { code: 'ENOENT' })
140
+ const argv = req.argv || []
141
+ const ci = argv.indexOf('-c')
142
+ const script = ci >= 0 ? String(argv[ci + 1] ?? '') : ''
143
+ const enc = new TextEncoder()
144
+ let outFn = () => {}
145
+ let errFn = () => {}
146
+ let exitFn = () => {}
147
+ let done = false
148
+ let stdinCb = null
149
+ const stdin = []
150
+ let stdinEnded = false
151
+ const finish = (code, sig = 0) => {
152
+ if (done) return
153
+ done = true
154
+ queueMicrotask(() => exitFn(code, sig))
155
+ }
156
+ const say = (fn, s) => fn(enc.encode(s))
157
+ ;(async () => {
158
+ await new Promise((r) => setTimeout(r, 0)) // the callbacks are set after the (async) ChildHost has the child
159
+ for (const raw of script.split(';')) {
160
+ if (done) return
161
+ const cmd = raw.trim()
162
+ if (!cmd) continue
163
+ const m = /^(echo|printf|cat|exit|sleep)\b\s*(.*)$/.exec(cmd)
164
+ if (!m) {
165
+ say(errFn, `sh: ${cmd.split(/\s/)[0]}: not found\n`)
166
+ return finish(127)
167
+ }
168
+ const rest = m[2].replace(/^(['"])(.*)\1$/, '$2')
169
+ if (m[1] === 'echo') say(outFn, rest + '\n')
170
+ else if (m[1] === 'printf') say(outFn, rest.replace(/\\n/g, '\n'))
171
+ else if (m[1] === 'exit') return finish(Number(rest) | 0)
172
+ else if (m[1] === 'sleep') await new Promise(r => setTimeout(r, Number(rest) * 1000))
173
+ else if (m[1] === 'cat') {
174
+ while (!stdinEnded || stdin.length) {
175
+ if (stdin.length) outFn(stdin.shift())
176
+ else await new Promise(r => (stdinCb = r))
177
+ }
178
+ }
179
+ }
180
+ finish(0)
181
+ })()
182
+ return {
183
+ write: b => {
184
+ stdin.push(b)
185
+ stdinCb?.()
186
+ },
187
+ end: () => {
188
+ stdinEnded = true
189
+ stdinCb?.()
190
+ },
191
+ kill: n => finish(0, n),
192
+ onOut: f => (outFn = f),
193
+ onErr: f => (errFn = f),
194
+ onExit: f => (exitFn = f),
195
+ }
196
+ }
@@ -0,0 +1,71 @@
1
+ // The page's end of a file call from the runtime (edge/browser/src/fsroute.rs `call`). A Worker that wants a file call writes a
2
+ // request into shared memory and posts {type: 'fs', slot}; the slot is nine 32-bit words at that address:
3
+ // 0 state (0 waiting, 1 answered, 2 reply too small) 1 kind (0 JSON, 1 bytes) 2 length 3 capacity 4 reply buffer
4
+ // 5 request 6 request length 7 data 8 data length
5
+ // serveFsCall reads the request, runs the route, writes the reply and wakes the Worker. The route is
6
+ // `route.handle(method, args, data)` returning {value} or {error: {code, message}} (or a promise of one); a Uint8Array value
7
+ // is sent as bytes. A reply that does not fit the buffer is answered with state 2 and the size, and the Worker asks again.
8
+
9
+ const enc = new TextEncoder()
10
+ const dec = new TextDecoder()
11
+
12
+ export function encodeReply(res) {
13
+ if (res && res.error) return { kind: 0, bytes: enc.encode(JSON.stringify({ e: res.error.code, m: res.error.message })) }
14
+ const v = res ? res.value : null
15
+ if (v instanceof Uint8Array) return { kind: 1, bytes: v }
16
+ return { kind: 0, bytes: enc.encode(JSON.stringify({ v: v === undefined ? null : v })) }
17
+ }
18
+
19
+ /** Serves one call. Returns a promise that settles when the Worker has been answered. */
20
+ export async function serveFsCall(memory, slot, route, onDone) {
21
+ const slotWords = () => new Int32Array(memory.buffer, slot, 9)
22
+ const w = slotWords()
23
+ const cap = w[3]
24
+ const replyPtr = w[4]
25
+ const inLen = w[6] + w[8] // read now: once the Worker is woken the slot is its own again (it is freed and may be written over)
26
+ let outLen = 0
27
+ let method = ''
28
+ let result
29
+ try {
30
+ const bytes = new Uint8Array(memory.buffer)
31
+ const req = JSON.parse(dec.decode(bytes.slice(w[5], w[5] + w[6])))
32
+ method = req.m
33
+ const data = w[8] ? bytes.slice(w[7], w[7] + w[8]) : new Uint8Array(0)
34
+ result = await route.handle(req.m, req.a, data)
35
+ } catch (e) {
36
+ result = { error: { code: 'EIO', message: String((e && e.message) || e) } }
37
+ }
38
+ let failed = null
39
+ try {
40
+ const { kind, bytes } = encodeReply(result)
41
+ const out = slotWords()
42
+ outLen = bytes.length
43
+ if (bytes.length > cap) {
44
+ Atomics.store(out, 2, bytes.length)
45
+ Atomics.store(out, 0, 2)
46
+ } else {
47
+ new Uint8Array(memory.buffer, replyPtr, bytes.length).set(bytes)
48
+ Atomics.store(out, 2, bytes.length)
49
+ Atomics.store(out, 1, kind)
50
+ Atomics.store(out, 0, 1)
51
+ }
52
+ } catch (e) {
53
+ // A reply that cannot be written must still end the wait of the Worker (it waits with no limit): it gets an I/O error.
54
+ failed = e
55
+ const out = slotWords()
56
+ const err = enc.encode(JSON.stringify({ e: 'EIO', m: 'reply failed: ' + String((e && e.message) || e).slice(0, 120) }))
57
+ if (err.length <= cap) {
58
+ new Uint8Array(memory.buffer, replyPtr, err.length).set(err)
59
+ Atomics.store(out, 2, err.length)
60
+ Atomics.store(out, 1, 0)
61
+ Atomics.store(out, 0, 1)
62
+ } else {
63
+ Atomics.store(out, 2, err.length)
64
+ Atomics.store(out, 0, 2)
65
+ }
66
+ }
67
+ Atomics.notify(slotWords(), 0)
68
+ if (onDone) onDone(method, inLen, outLen)
69
+ if (failed) throw failed
70
+ return method
71
+ }