@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,356 @@
|
|
|
1
|
+
// The file route of wmd's own runtime: what the runtime's file system (edge/browser/src/fsroute.rs) asks, answered from wmd's
|
|
2
|
+
// Overlay, the tree the guest's 9P server reads and writes. One tree for the guest and for node.
|
|
3
|
+
//
|
|
4
|
+
// The native runtime sends one request kind per WASIX file call; so does this. A request is (method, args, data) and the answer
|
|
5
|
+
// is {value} or {error: {code, message}}; a `read` answers with bytes. Paths are the container's, absolute, as strings (UTF-8);
|
|
6
|
+
// names in the Overlay are byte strings (one char per byte), so a path goes through byteStr() on the way in and utf8() on the
|
|
7
|
+
// way out. A link is followed or not as the method says: `stat` takes the flag, the others do what POSIX does.
|
|
8
|
+
//
|
|
9
|
+
// stat(path, follow) -> {k, s, a, m, c, i, nl, md, u, g, rd} kind letter, size, times (decimal ns strings), inode, links (nl), mode, uid, gid, rdev
|
|
10
|
+
// readdir(path, offset, limit) -> {l: [{n, ...stat}], d: done} paged, sorted by name; entries are not followed
|
|
11
|
+
// open(path, {r,w,c,cn,t,a}) -> {h}
|
|
12
|
+
// read(h, off, len) -> bytes write(h, off, append) + data -> {n, p} fstat(h) ftruncate(h, size)
|
|
13
|
+
// futimes(h, atime, mtime) close(h) mkdir(path) unlink(path) rmdir(path) rename(from, to)
|
|
14
|
+
// symlink(content, path) link(source, path) readlink(path)
|
|
15
|
+
// ctl(json) -> the control request of linux.cjs (src/edge/ctl.js), as JSON text
|
|
16
|
+
//
|
|
17
|
+
// `shimFiles` ({name: text}) shows read-only files under /.wmd-edge (the shim's directory; ls / never lists it).
|
|
18
|
+
|
|
19
|
+
import { CODES } from '../codes.js'
|
|
20
|
+
import { EdgeCtl } from '../ctl.js'
|
|
21
|
+
import { resolveIn } from '../resolve.js'
|
|
22
|
+
import { EBADF, EEXIST, EINVAL, EISDIR, ENOENT, ENOTDIR, ENOSYS, EROFS, fail } from '../../fs/errno.js'
|
|
23
|
+
import { S_IFBLK, S_IFCHR, S_IFDIR, S_IFIFO, S_IFLNK, S_IFMT, S_IFSOCK, byteStr, bytesOf } from '../../fs/pack.js'
|
|
24
|
+
|
|
25
|
+
const SHIM_DIR = '/.wmd-edge'
|
|
26
|
+
const utf8 = s => new TextDecoder().decode(bytesOf(s))
|
|
27
|
+
const enc = new TextEncoder()
|
|
28
|
+
// A typed array that is a small view of a big buffer is copied before it is sent: a message to the other side carries the whole buffer of a view
|
|
29
|
+
// (a read of 8 bytes of a file in a layer's data would send the layer).
|
|
30
|
+
const tight = b => (b instanceof Uint8Array && b.byteLength < b.buffer.byteLength ? b.slice() : b)
|
|
31
|
+
const reply = value => ({ value: tight(value) })
|
|
32
|
+
const err = (code, message) => ({ error: { code, message: message || code } })
|
|
33
|
+
|
|
34
|
+
const KIND = { [S_IFDIR]: 'd', [S_IFLNK]: 'l', [S_IFCHR]: 'c', [S_IFBLK]: 'b', [S_IFIFO]: 'p', [S_IFSOCK]: 's' }
|
|
35
|
+
|
|
36
|
+
/** Every method the route serves (the runtime's file calls, the page's shim and signal calls, ctl, the child calls): a name that is not here is ENOSYS. */
|
|
37
|
+
const RING_MAX = 120
|
|
38
|
+
|
|
39
|
+
export const METHODS = new Set(['shim', 'sigq', 'ctl', 'stat', 'readdir', 'open', 'read', 'write', 'fstat', 'ftruncate', 'futimes', 'close', 'mkdir', 'unlink', 'rmdir', 'rename', 'symlink', 'link', 'readlink', 'child_start', 'child_stdin', 'child_read', 'child_signal', 'note', 'peek', 'timing'])
|
|
40
|
+
|
|
41
|
+
export class OwnFsRoute {
|
|
42
|
+
/**
|
|
43
|
+
* @param {import('../../fs/overlay.js').Overlay} fs
|
|
44
|
+
* @param {{root?: string, shimFiles?: Object<string, string>}} o root: where the container's root is in the Overlay ('rootfs' under the guest's layout)
|
|
45
|
+
*/
|
|
46
|
+
constructor(fs, { root = '', shimFiles = {} } = {}) {
|
|
47
|
+
this.fs = fs
|
|
48
|
+
this.rootPath = root
|
|
49
|
+
this.handles = new Map()
|
|
50
|
+
this.next = 1
|
|
51
|
+
this.ring = null // an array the owner keeps: the last calls and answers
|
|
52
|
+
this.serdes = null // an array the owner keeps: the serializer lines of the Workers (fix5 round 6, only with the page's serdesNote)
|
|
53
|
+
this.shim = new Map(Object.entries(shimFiles).map(([k, v]) => [SHIM_DIR + '/' + k, enc.encode(v)]))
|
|
54
|
+
this.ctl = new EdgeCtl(fs, { root, mounts: { 1: { path: '' } } })
|
|
55
|
+
this.calls = Object.create(null) // counted by the method's name, which is the frame's (check5 F4): no inherited property
|
|
56
|
+
this.children = null // a ChildHost (child-host.js), set by the page that owns the children
|
|
57
|
+
this.sigs = new Map() // signals waiting for the program (id 0) or one of its node children, taken by the shim's pending_signal
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Queues signal n for the program (id 0) or a child run by the runtime (its exec id). The shim takes it within 50 ms. */
|
|
61
|
+
queueSignal(id, n) {
|
|
62
|
+
if (!this.sigs.has(id)) this.sigs.set(id, [])
|
|
63
|
+
this.sigs.get(id).push(n)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
#root() {
|
|
67
|
+
return this.rootPath ? this.fs.resolve(this.rootPath) : this.fs.root
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
#node(path, follow = true) {
|
|
71
|
+
const root = this.#root()
|
|
72
|
+
return resolveIn(this.fs, root, root, byteStr(path), follow)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// the directory a new name goes in, and the name
|
|
76
|
+
#parent(path) {
|
|
77
|
+
const parts = byteStr(path).split('/').filter(s => s !== '')
|
|
78
|
+
if (parts.length === 0) fail(EEXIST)
|
|
79
|
+
const root = this.#root()
|
|
80
|
+
const dir = resolveIn(this.fs, root, root, parts.slice(0, -1).join('/'), true)
|
|
81
|
+
if (!dir.isDir()) fail(ENOTDIR)
|
|
82
|
+
return [dir, parts.at(-1)]
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
#stat(n) {
|
|
86
|
+
const a = this.fs.getattr(n)
|
|
87
|
+
return {
|
|
88
|
+
k: KIND[n.mode & S_IFMT] || 'f',
|
|
89
|
+
s: a.size,
|
|
90
|
+
a: String(a.atime),
|
|
91
|
+
m: String(a.mtime),
|
|
92
|
+
c: String(a.ctime),
|
|
93
|
+
i: Number(a.ino & 0xffffffffffffn),
|
|
94
|
+
nl: a.nlink,
|
|
95
|
+
md: a.mode,
|
|
96
|
+
u: a.uid,
|
|
97
|
+
g: a.gid,
|
|
98
|
+
rd: a.rdev,
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
#h(h) {
|
|
103
|
+
const e = this.handles.get(h)
|
|
104
|
+
if (!e) fail(EBADF)
|
|
105
|
+
return e
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** One request. Returns {value} or {error}; never throws. */
|
|
109
|
+
handle(method, args, data) {
|
|
110
|
+
if (typeof method !== 'string' || !METHODS.has(method)) return err('ENOSYS', 'own fs route: no such method')
|
|
111
|
+
if (method === 'timing') {
|
|
112
|
+
// counters per method (count, time inside handle, bytes in and out), off until a caller turns them on: ['on'] starts, ['read'] returns them
|
|
113
|
+
if (Array.isArray(args) && args[0] === 'on') this.timing ||= {}
|
|
114
|
+
return reply(this.timing || null)
|
|
115
|
+
}
|
|
116
|
+
const c = (this.calls[method] ||= { n: 0, errors: 0 })
|
|
117
|
+
c.n++
|
|
118
|
+
let res
|
|
119
|
+
const tm = this.timing
|
|
120
|
+
const t0 = tm ? performance.now() : 0
|
|
121
|
+
try {
|
|
122
|
+
res = this.#serve(method, Array.isArray(args) ? args : [args], data)
|
|
123
|
+
if (tm && !(res && typeof res.then === 'function')) {
|
|
124
|
+
const m = (tm[method] ||= { n: 0, ms: 0, inB: 0, outB: 0 })
|
|
125
|
+
m.n++
|
|
126
|
+
m.ms += performance.now() - t0
|
|
127
|
+
m.inB += (data && data.length) | 0
|
|
128
|
+
const v = res && res.value
|
|
129
|
+
m.outB += v instanceof Uint8Array ? v.length : 0
|
|
130
|
+
}
|
|
131
|
+
} catch (e) {
|
|
132
|
+
c.errors++
|
|
133
|
+
if (tm) {
|
|
134
|
+
const m = (tm[method] ||= { n: 0, ms: 0, inB: 0, outB: 0 })
|
|
135
|
+
m.err = (m.err || 0) + 1
|
|
136
|
+
m.n++
|
|
137
|
+
m.ms += performance.now() - t0
|
|
138
|
+
}
|
|
139
|
+
res = e && e.errno !== undefined ? err(CODES[e.errno] || 'EIO', e.message) : err('EIO', String((e && e.message) || e))
|
|
140
|
+
}
|
|
141
|
+
if (this.ring && (!method.startsWith('child_') || method === 'child_start' || method === 'child_signal') && method !== 'sigq' && method !== 'note') {
|
|
142
|
+
// the last calls with their paths and answers (a ring the owner keeps; a difference of the frame from the guest shows which call answered what)
|
|
143
|
+
const a0 = method.startsWith('child_') ? (args && args[0] && args[0].path) || String(Array.isArray(args) ? args[0] : args) : Array.isArray(args) ? args[0] : args
|
|
144
|
+
const a1 = Array.isArray(args) ? args[1] : undefined
|
|
145
|
+
const e = res && res.error
|
|
146
|
+
const rd = method === 'read' && Array.isArray(args) ? ` h${args[0]}@${args[1]}+${args[2]}=${res && res.value && res.value.length !== undefined ? res.value.length : (res && res.bytes ? res.bytes.length : '?')}` : ''
|
|
147
|
+
this.ring.push(`${method} ${typeof a0 === 'string' ? a0.slice(0, 80) : rd}${typeof a1 === 'string' ? ' ' + a1.slice(0, 80) : ''}${e ? ' -> ' + e.code : ''}`)
|
|
148
|
+
if (this.ring.length > RING_MAX) this.ring.splice(0, this.ring.length - RING_MAX)
|
|
149
|
+
}
|
|
150
|
+
return res
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
#shimStat(path) {
|
|
154
|
+
if (path === SHIM_DIR) return { k: 'd', s: 4096, a: '0', m: '0', c: '0', i: 1, nl: 2, md: 0o40555, u: 0, g: 0, rd: 0 }
|
|
155
|
+
const b = this.shim.get(path)
|
|
156
|
+
if (!b) return null
|
|
157
|
+
return { k: 'f', s: b.length, a: '0', m: '0', c: '0', i: 2, nl: 1, md: 0o100444, u: 0, g: 0, rd: 0 }
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
#serve(method, a, data) {
|
|
161
|
+
const fs = this.fs
|
|
162
|
+
const path = () => String(a[0] ?? '')
|
|
163
|
+
if (method === 'shim') {
|
|
164
|
+
// the page's shim files ({name: text}), shown under /.wmd-edge (the adapter sends them before it starts the program)
|
|
165
|
+
this.shim = new Map(Object.entries(a[0] || {}).map(([k, v]) => [SHIM_DIR + '/' + k, enc.encode(v)]))
|
|
166
|
+
return reply(null)
|
|
167
|
+
}
|
|
168
|
+
if (method.startsWith('child_')) return this.children ? this.children.handle(method, a, data) : err('ENOSYS', 'no child host on this page')
|
|
169
|
+
if (method === 'note') {
|
|
170
|
+
if (this.serdes && String(a[0]).startsWith('SERDES ')) {
|
|
171
|
+
this.serdes.push(String(a[0]).slice(0, 160))
|
|
172
|
+
if (this.serdes.length > 600) this.serdes.splice(0, 100)
|
|
173
|
+
return reply(null)
|
|
174
|
+
}
|
|
175
|
+
this.ring?.push('note ' + String(a[0] ?? '').slice(0, 160))
|
|
176
|
+
return reply(null)
|
|
177
|
+
}
|
|
178
|
+
if (method === 'sigq') {
|
|
179
|
+
this.queueSignal(Number(a[0]), Number(a[1]))
|
|
180
|
+
return reply(null)
|
|
181
|
+
}
|
|
182
|
+
if (method === 'ctl') {
|
|
183
|
+
let q = null
|
|
184
|
+
try {
|
|
185
|
+
q = JSON.parse(String(a[0] ?? ''))
|
|
186
|
+
} catch {}
|
|
187
|
+
if (q && q.op === 'signal_taken') {
|
|
188
|
+
// fix7: the shim ran a handler (or not) for signal n: the page learns it (the cut-off of a handled signal is dropped)
|
|
189
|
+
try {
|
|
190
|
+
this.onSignalTaken?.(Number(q.n) || 0, !!q.handled)
|
|
191
|
+
} catch {}
|
|
192
|
+
return reply('{}')
|
|
193
|
+
}
|
|
194
|
+
if (q && q.op === 'pending_signal') return reply(JSON.stringify({ signals: this.sigs.get(Number(q.id) || 0)?.splice(0) || [] }))
|
|
195
|
+
return reply(JSON.stringify(this.ctl.handle(String(a[0] ?? ''))))
|
|
196
|
+
}
|
|
197
|
+
if (method === 'stat' || method === 'readdir' || method === 'open') {
|
|
198
|
+
const p = path().replace(/\/+$/, '') || '/'
|
|
199
|
+
if (p === SHIM_DIR || p.startsWith(SHIM_DIR + '/')) return this.#shimServe(method, p, a)
|
|
200
|
+
}
|
|
201
|
+
switch (method) {
|
|
202
|
+
case 'stat':
|
|
203
|
+
return reply(this.#stat(this.#node(path(), a[1] !== false)))
|
|
204
|
+
case 'readdir': {
|
|
205
|
+
const dir = this.#node(path(), true)
|
|
206
|
+
if (!dir.isDir()) fail(ENOTDIR)
|
|
207
|
+
const off = Number(a[1] ?? 0)
|
|
208
|
+
const lim = Number(a[2] ?? 500)
|
|
209
|
+
const { names, nodes } = fs.listing(dir)
|
|
210
|
+
const out = []
|
|
211
|
+
for (let i = off; i < Math.min(names.length, off + lim); i++) out.push({ n: utf8(names[i]), ...this.#stat(nodes[i]) })
|
|
212
|
+
return reply({ l: out, d: off + lim >= names.length })
|
|
213
|
+
}
|
|
214
|
+
case 'open': {
|
|
215
|
+
const f = a[1] || {}
|
|
216
|
+
const create = !!(f.c || f.cn)
|
|
217
|
+
let n
|
|
218
|
+
try {
|
|
219
|
+
n = this.#node(path(), true)
|
|
220
|
+
if (f.cn) fail(EEXIST)
|
|
221
|
+
} catch (e) {
|
|
222
|
+
if (e.errno !== ENOENT || !create) throw e
|
|
223
|
+
const [dir, name] = this.#parent(path())
|
|
224
|
+
n = fs.create(dir, name, 0o644, 0, 0)
|
|
225
|
+
}
|
|
226
|
+
if (n.isDir()) fail(EISDIR)
|
|
227
|
+
fs.open(n, { write: !!(f.w || f.t || f.a), trunc: !!f.t })
|
|
228
|
+
fs.ref(n)
|
|
229
|
+
const h = this.next++
|
|
230
|
+
this.handles.set(h, { n })
|
|
231
|
+
return reply({ h })
|
|
232
|
+
}
|
|
233
|
+
case 'peek': {
|
|
234
|
+
// the first bytes of a file (at most 64), for the runtime's check of what a program file is: no handle is made
|
|
235
|
+
const n = this.#node(path(), true)
|
|
236
|
+
if (n.isDir()) fail(EISDIR)
|
|
237
|
+
return reply(fs.read(n, 0, Math.max(0, Math.min(Number(a[1] ?? 8), 64))))
|
|
238
|
+
}
|
|
239
|
+
case 'read': {
|
|
240
|
+
const e = this.#h(a[0])
|
|
241
|
+
if (e.bytes) return reply(e.bytes.subarray(Number(a[1]), Number(a[1]) + Number(a[2])))
|
|
242
|
+
return reply(fs.read(e.n, Number(a[1] ?? 0), Number(a[2] ?? 0)))
|
|
243
|
+
}
|
|
244
|
+
case 'write': {
|
|
245
|
+
const e = this.#h(a[0])
|
|
246
|
+
if (e.bytes) fail(EROFS)
|
|
247
|
+
const off = a[2] ? fs.size(e.n) : Number(a[1] ?? 0)
|
|
248
|
+
const n = fs.write(e.n, off, data)
|
|
249
|
+
return reply({ n, p: off + n })
|
|
250
|
+
}
|
|
251
|
+
case 'fstat': {
|
|
252
|
+
const e = this.#h(a[0])
|
|
253
|
+
if (e.bytes) return reply(this.#shimStat(e.path))
|
|
254
|
+
return reply(this.#stat(e.n))
|
|
255
|
+
}
|
|
256
|
+
case 'ftruncate': {
|
|
257
|
+
const e = this.#h(a[0])
|
|
258
|
+
if (e.bytes) fail(EROFS)
|
|
259
|
+
fs.setattr(e.n, { size: Number(a[1]) })
|
|
260
|
+
return reply(null)
|
|
261
|
+
}
|
|
262
|
+
case 'futimes': {
|
|
263
|
+
const e = this.#h(a[0])
|
|
264
|
+
if (e.bytes) fail(EROFS)
|
|
265
|
+
const s = {}
|
|
266
|
+
if (a[1] != null) s.atime = BigInt(a[1])
|
|
267
|
+
if (a[2] != null) s.mtime = BigInt(a[2])
|
|
268
|
+
fs.setattr(e.n, s)
|
|
269
|
+
return reply(null)
|
|
270
|
+
}
|
|
271
|
+
case 'close': {
|
|
272
|
+
const e = this.handles.get(a[0])
|
|
273
|
+
if (e) {
|
|
274
|
+
this.handles.delete(a[0])
|
|
275
|
+
if (e.n) fs.unref(e.n)
|
|
276
|
+
}
|
|
277
|
+
return reply(null)
|
|
278
|
+
}
|
|
279
|
+
case 'mkdir': {
|
|
280
|
+
const [dir, name] = this.#parent(path())
|
|
281
|
+
fs.mkdir(dir, name, 0o755, 0, 0)
|
|
282
|
+
return reply(null)
|
|
283
|
+
}
|
|
284
|
+
case 'unlink': {
|
|
285
|
+
const [dir, name] = this.#parent(path())
|
|
286
|
+
const n = fs.lookup(dir, name)
|
|
287
|
+
if (n.isDir()) fail(EISDIR)
|
|
288
|
+
fs.unlink(dir, name, false)
|
|
289
|
+
return reply(null)
|
|
290
|
+
}
|
|
291
|
+
case 'rmdir': {
|
|
292
|
+
const [dir, name] = this.#parent(path())
|
|
293
|
+
const n = fs.lookup(dir, name)
|
|
294
|
+
if (!n.isDir()) fail(ENOTDIR)
|
|
295
|
+
fs.unlink(dir, name, true)
|
|
296
|
+
return reply(null)
|
|
297
|
+
}
|
|
298
|
+
case 'rename': {
|
|
299
|
+
const [od, on] = this.#parent(path())
|
|
300
|
+
const [nd, nn] = this.#parent(String(a[1]))
|
|
301
|
+
fs.rename(od, on, nd, nn)
|
|
302
|
+
return reply(null)
|
|
303
|
+
}
|
|
304
|
+
case 'symlink': {
|
|
305
|
+
const [dir, name] = this.#parent(String(a[1]))
|
|
306
|
+
fs.symlink(dir, name, byteStr(String(a[0])), 0, 0)
|
|
307
|
+
return reply(null)
|
|
308
|
+
}
|
|
309
|
+
case 'link': {
|
|
310
|
+
const n = this.#node(path(), false)
|
|
311
|
+
const [dir, name] = this.#parent(String(a[1]))
|
|
312
|
+
fs.link(dir, name, n)
|
|
313
|
+
return reply(null)
|
|
314
|
+
}
|
|
315
|
+
case 'readlink': {
|
|
316
|
+
const n = this.#node(path(), false)
|
|
317
|
+
if ((n.mode & S_IFMT) !== S_IFLNK) fail(EINVAL)
|
|
318
|
+
return reply(utf8(fs.readlink(n)))
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
fail(ENOSYS, `own fs route: method ${method} is not served`)
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
#shimServe(method, p, a) {
|
|
325
|
+
if (method === 'stat') {
|
|
326
|
+
const s = this.#shimStat(p)
|
|
327
|
+
if (!s) fail(ENOENT)
|
|
328
|
+
return reply(s)
|
|
329
|
+
}
|
|
330
|
+
if (method === 'readdir') {
|
|
331
|
+
if (p !== SHIM_DIR) fail(ENOTDIR)
|
|
332
|
+
const names = [...this.shim.keys()].map(k => k.slice(SHIM_DIR.length + 1)).sort()
|
|
333
|
+
const off = Number(a[1] ?? 0)
|
|
334
|
+
const l = names.slice(off, off + Number(a[2] ?? 500)).map(n => ({ n, ...this.#shimStat(SHIM_DIR + '/' + n) }))
|
|
335
|
+
return reply({ l, d: true })
|
|
336
|
+
}
|
|
337
|
+
const f = a[1] || {}
|
|
338
|
+
if (f.w || f.c || f.cn || f.t || f.a) fail(EROFS)
|
|
339
|
+
const bytes = this.shim.get(p)
|
|
340
|
+
if (!bytes) fail(p === SHIM_DIR ? EISDIR : ENOENT)
|
|
341
|
+
const h = this.next++
|
|
342
|
+
this.handles.set(h, { bytes, path: p })
|
|
343
|
+
return reply({ h })
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** The run is over: every file it left open is closed. */
|
|
347
|
+
close() {
|
|
348
|
+
for (const e of this.handles.values()) if (e.n) this.fs.unref(e.n)
|
|
349
|
+
this.handles.clear()
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** Handles still open. */
|
|
353
|
+
get openHandles() {
|
|
354
|
+
return this.handles.size
|
|
355
|
+
}
|
|
356
|
+
}
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
// The page-side spawner that hands a child process to the guest (round 3, item 4). It speaks the stub's exec stream: the protocol
|
|
2
|
+
// of guest/container2wasm/cmd/edgestub/proto.go, the one wmd-edge's foreign.rs speaks on the desktop. Every frame is
|
|
3
|
+
// [type u8][length u32 big-endian][payload] at most 4 MiB of payload
|
|
4
|
+
// The page writes a header frame (0x10, JSON {kind: 'exec', path, argv, env, cwd}); the guest answers a reply frame (0x11, JSON
|
|
5
|
+
// {ok, errno, error}); then stdin (0), stdout (1), stderr (2), exit (3, JSON {code, signal}), stdin end (4), signal (5, one byte).
|
|
6
|
+
//
|
|
7
|
+
// The spawner knows nothing about how the bytes get to the guest. It is given `open()`, which returns a raw duplex byte stream to
|
|
8
|
+
// the guest's channel (the service side of the page's hand-off; X5's fix round has it, this branch does not copy it):
|
|
9
|
+
// open() -> Promise<{ read(): Promise<Uint8Array|null>, write(bytes), close() }> read gives null when the stream ended
|
|
10
|
+
// and it returns the function ChildHost (child-host.js) takes: spawner(req) -> Promise<child>, child as ChildHost describes it.
|
|
11
|
+
|
|
12
|
+
export const FRAME = { stdin: 0, stdout: 1, stderr: 2, exit: 3, stdinEOF: 4, signal: 5, stdinStart: 6, hdr: 0x10, reply: 0x11 }
|
|
13
|
+
export const MAX_FRAME = 4 << 20
|
|
14
|
+
|
|
15
|
+
const enc = new TextEncoder()
|
|
16
|
+
const dec = new TextDecoder()
|
|
17
|
+
|
|
18
|
+
export function encodeFrame(type, payload = new Uint8Array(0)) {
|
|
19
|
+
const f = new Uint8Array(5 + payload.length)
|
|
20
|
+
f[0] = type
|
|
21
|
+
new DataView(f.buffer).setUint32(1, payload.length, false)
|
|
22
|
+
f.set(payload, 5)
|
|
23
|
+
return f
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Joins the pieces a stream delivers into frames. push(bytes), then next() until it returns null. */
|
|
27
|
+
export class FrameReader {
|
|
28
|
+
#buf = new Uint8Array(0)
|
|
29
|
+
|
|
30
|
+
push(b) {
|
|
31
|
+
if (!b || !b.length) return
|
|
32
|
+
if (!this.#buf.length) this.#buf = b
|
|
33
|
+
else {
|
|
34
|
+
const m = new Uint8Array(this.#buf.length + b.length)
|
|
35
|
+
m.set(this.#buf, 0)
|
|
36
|
+
m.set(b, this.#buf.length)
|
|
37
|
+
this.#buf = m
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
next() {
|
|
42
|
+
const b = this.#buf
|
|
43
|
+
if (b.length < 5) return null
|
|
44
|
+
const n = new DataView(b.buffer, b.byteOffset, b.byteLength).getUint32(1, false)
|
|
45
|
+
if (n > MAX_FRAME) throw new Error(`edge: frame of ${n} bytes`)
|
|
46
|
+
if (b.length < 5 + n) return null
|
|
47
|
+
const frame = { type: b[0], payload: b.slice(5, 5 + n) }
|
|
48
|
+
this.#buf = b.subarray(5 + n)
|
|
49
|
+
return frame
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const sleepReject = (ms, code) => {
|
|
54
|
+
let t
|
|
55
|
+
const p = new Promise((_, rej) => (t = setTimeout(() => rej(Object.assign(new Error('the guest did not answer the exec header'), { code })), ms)))
|
|
56
|
+
return { p, cancel: () => clearTimeout(t) }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* @param {() => Promise<{read: () => Promise<Uint8Array|null>, write: (b: Uint8Array) => void, close: () => void}>} open
|
|
61
|
+
* @param {{replyTimeoutMs?: number}} [o]
|
|
62
|
+
*/
|
|
63
|
+
export function guestSpawner(open, { replyTimeoutMs = 30_000, stats = {} } = {}) {
|
|
64
|
+
const bump = k => (stats[k] = (stats[k] || 0) + 1)
|
|
65
|
+
// fix7 (F15): every failed start says at which step it failed and with what (counters by step, and the last ones in full)
|
|
66
|
+
const fail = (step, e, extra = '') => {
|
|
67
|
+
bump('fail_' + step)
|
|
68
|
+
const list = (stats.errors ||= [])
|
|
69
|
+
list.push({ step, code: String((e && e.code) || ''), msg: String((e && e.message) || e).slice(0, 160), extra, at: Date.now() })
|
|
70
|
+
if (list.length > 30) list.splice(0, list.length - 30)
|
|
71
|
+
}
|
|
72
|
+
return async function spawner(req) {
|
|
73
|
+
bump('opening')
|
|
74
|
+
let stream
|
|
75
|
+
try {
|
|
76
|
+
stream = await open()
|
|
77
|
+
} catch (e) {
|
|
78
|
+
fail('open', e)
|
|
79
|
+
throw e
|
|
80
|
+
}
|
|
81
|
+
bump('opened')
|
|
82
|
+
const reader = new FrameReader()
|
|
83
|
+
const frames = []
|
|
84
|
+
const nextFrame = async () => {
|
|
85
|
+
for (;;) {
|
|
86
|
+
const f = reader.next()
|
|
87
|
+
if (f) return f
|
|
88
|
+
const b = await stream.read()
|
|
89
|
+
if (b === null) return null
|
|
90
|
+
reader.push(b)
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
const header = { kind: 'exec', path: req.path, argv: req.argv || [], env: req.env || [], cwd: req.cwd || '/' }
|
|
94
|
+
try {
|
|
95
|
+
await stream.write(encodeFrame(FRAME.hdr, enc.encode(JSON.stringify(header))))
|
|
96
|
+
} catch (e) {
|
|
97
|
+
fail('header', e)
|
|
98
|
+
stream.close()
|
|
99
|
+
throw e
|
|
100
|
+
}
|
|
101
|
+
bump('header')
|
|
102
|
+
const timer = sleepReject(replyTimeoutMs, 'ETIMEDOUT')
|
|
103
|
+
let reply
|
|
104
|
+
// fix7 (F15): the stub's output goroutines may write a child's first bytes (or its exit) before its reply frame: they are kept and delivered after the reply,
|
|
105
|
+
// in order (before, the child failed with `spawn EINVAL`: the counters of 100 runs showed `fail_reply-frame` "the guest sent frame 1 where the reply was due")
|
|
106
|
+
const early = []
|
|
107
|
+
try {
|
|
108
|
+
for (;;) {
|
|
109
|
+
const f = await Promise.race([nextFrame(), timer.p])
|
|
110
|
+
if (f && (f.type === FRAME.stdout || f.type === FRAME.stderr || f.type === FRAME.exit)) {
|
|
111
|
+
early.push(f)
|
|
112
|
+
bump('early' + f.type)
|
|
113
|
+
if (f.type === FRAME.exit) break // the child ended: no reply is coming that matters, the reply may still follow
|
|
114
|
+
continue
|
|
115
|
+
}
|
|
116
|
+
if (!f || f.type !== FRAME.reply) throw Object.assign(new Error(f ? 'the guest sent frame ' + f.type + ' where the reply was due' : 'the guest closed the stream before it answered'), { code: 'EIO', step: f ? 'reply-frame' : 'reply-closed' })
|
|
117
|
+
reply = JSON.parse(dec.decode(f.payload))
|
|
118
|
+
bump('reply')
|
|
119
|
+
break
|
|
120
|
+
}
|
|
121
|
+
if (!reply) {
|
|
122
|
+
// an exit came first: the reply is the next frame (or the stream ends): read it so that the stream is in step
|
|
123
|
+
const f = await Promise.race([nextFrame(), timer.p])
|
|
124
|
+
if (!f || f.type !== FRAME.reply) throw Object.assign(new Error('the guest sent no reply after the child ended'), { code: 'EIO', step: 'reply-frame' })
|
|
125
|
+
reply = JSON.parse(dec.decode(f.payload))
|
|
126
|
+
bump('reply')
|
|
127
|
+
}
|
|
128
|
+
} catch (e) {
|
|
129
|
+
fail((e && e.step) || (e && e.code === 'ETIMEDOUT' ? 'reply-timeout' : 'reply-read'), e)
|
|
130
|
+
stream.close()
|
|
131
|
+
throw e
|
|
132
|
+
} finally {
|
|
133
|
+
timer.cancel()
|
|
134
|
+
}
|
|
135
|
+
if (!reply.ok) {
|
|
136
|
+
fail('reply-refused', { code: reply.errno, message: reply.error }, req.path)
|
|
137
|
+
stream.close()
|
|
138
|
+
throw Object.assign(new Error(reply.error || 'the guest could not run ' + req.path), { code: reply.errno || 'EIO' })
|
|
139
|
+
}
|
|
140
|
+
void frames
|
|
141
|
+
|
|
142
|
+
// events, held until ChildHost has set the three callbacks
|
|
143
|
+
let outFn = null
|
|
144
|
+
let errFn = null
|
|
145
|
+
let exitFn = null
|
|
146
|
+
const held = []
|
|
147
|
+
let finished = false
|
|
148
|
+
const deliver = (ev) => {
|
|
149
|
+
if (ev.k === 'out') outFn(ev.b)
|
|
150
|
+
else if (ev.k === 'err') errFn(ev.b)
|
|
151
|
+
else exitFn(ev.code, ev.signal)
|
|
152
|
+
}
|
|
153
|
+
const ready = () => outFn && errFn && exitFn
|
|
154
|
+
const push = (ev) => {
|
|
155
|
+
if (ready() && !held.length) deliver(ev)
|
|
156
|
+
else held.push(ev)
|
|
157
|
+
}
|
|
158
|
+
const flush = () => {
|
|
159
|
+
while (ready() && held.length) deliver(held.shift())
|
|
160
|
+
}
|
|
161
|
+
// one frame of the running child; true when it was the exit
|
|
162
|
+
const handle = (f) => {
|
|
163
|
+
bump('frame' + f.type)
|
|
164
|
+
if (f.type === FRAME.stdout) push({ k: 'out', b: f.payload })
|
|
165
|
+
else if (f.type === FRAME.stderr) push({ k: 'err', b: f.payload })
|
|
166
|
+
else if (f.type === FRAME.exit) {
|
|
167
|
+
const e = (() => {
|
|
168
|
+
try {
|
|
169
|
+
return JSON.parse(dec.decode(f.payload))
|
|
170
|
+
} catch {
|
|
171
|
+
return {}
|
|
172
|
+
}
|
|
173
|
+
})()
|
|
174
|
+
finished = true
|
|
175
|
+
push({ k: 'exit', code: e.code | 0, signal: e.signal | 0 })
|
|
176
|
+
return true
|
|
177
|
+
}
|
|
178
|
+
return false
|
|
179
|
+
}
|
|
180
|
+
;(async () => {
|
|
181
|
+
try {
|
|
182
|
+
for (const f of early) if (handle(f)) return
|
|
183
|
+
for (;;) {
|
|
184
|
+
const f = await nextFrame()
|
|
185
|
+
if (!f) break
|
|
186
|
+
if (handle(f)) return
|
|
187
|
+
}
|
|
188
|
+
// the stream ended with no exit frame: the host calls that a kill by signal 9
|
|
189
|
+
finished = true
|
|
190
|
+
push({ k: 'exit', code: 0, signal: 9 })
|
|
191
|
+
} catch {
|
|
192
|
+
finished = true
|
|
193
|
+
push({ k: 'exit', code: 0, signal: 9 })
|
|
194
|
+
} finally {
|
|
195
|
+
stream.close()
|
|
196
|
+
}
|
|
197
|
+
})()
|
|
198
|
+
|
|
199
|
+
let stdinEnded = false
|
|
200
|
+
const send = (type, payload) => {
|
|
201
|
+
if (finished) return
|
|
202
|
+
try {
|
|
203
|
+
return stream.write(encodeFrame(type, payload))
|
|
204
|
+
} catch {
|
|
205
|
+
// the stream is gone; the pump reports the exit
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return {
|
|
209
|
+
write(bytes) {
|
|
210
|
+
if (stdinEnded) return
|
|
211
|
+
for (let off = 0; off < bytes.length; off += MAX_FRAME) send(FRAME.stdin, bytes.subarray(off, Math.min(bytes.length, off + MAX_FRAME)))
|
|
212
|
+
},
|
|
213
|
+
end() {
|
|
214
|
+
if (stdinEnded) return
|
|
215
|
+
stdinEnded = true
|
|
216
|
+
send(FRAME.stdinEOF)
|
|
217
|
+
},
|
|
218
|
+
kill(n) {
|
|
219
|
+
send(FRAME.signal, new Uint8Array([Number(n) & 255]))
|
|
220
|
+
},
|
|
221
|
+
onOut(f) {
|
|
222
|
+
outFn = f
|
|
223
|
+
flush()
|
|
224
|
+
},
|
|
225
|
+
onErr(f) {
|
|
226
|
+
errFn = f
|
|
227
|
+
flush()
|
|
228
|
+
},
|
|
229
|
+
onExit(f) {
|
|
230
|
+
exitFn = f
|
|
231
|
+
flush()
|
|
232
|
+
},
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|