@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.
- package/README.md +236 -1
- package/RELEASE.json +84 -49
- 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 +231 -4
- package/src/edge/auto.js +77 -0
- package/src/edge/base.js +10 -0
- package/src/edge/bridge.js +76 -7
- package/src/edge/ctl.js +21 -4
- package/src/edge/error-kind.js +6 -0
- package/src/edge/frame-code.gen.js +6 -0
- package/src/edge/frame.js +58 -15
- package/src/edge/msg.js +3 -0
- package/src/edge/own/adapter.js +208 -19
- package/src/edge/own/exit-now.js +62 -0
- package/src/edge/own/fs-own-route.js +40 -3
- package/src/edge/own/fs-stats.js +11 -0
- package/src/edge/own/hub.js +125 -14
- package/src/edge/own/loader.js +3 -2
- package/src/edge/own/marks.js +158 -0
- package/src/edge/own/net-host.js +873 -0
- package/src/edge/own/node-globals.js +142 -0
- package/src/edge/own/pool.js +30 -1
- package/src/edge/own/service-receiver.js +7 -1
- package/src/edge/own/shim-post.js +38 -0
- package/src/edge/own/worker.js +34 -1
- package/src/edge/page.js +448 -25
- package/src/edge/pins.gen.js +17 -0
- package/src/edge/pins.js +21 -0
- package/src/edge/plan.js +45 -9
- package/src/edge/python-module.js +18 -0
- package/src/edge/python-pins.js +64 -0
- package/src/edge/python-plan.js +280 -0
- package/src/edge/python-source.js +34 -0
- package/src/edge/runtime.js +13 -2
- package/src/edge/sbx/cap.js +36 -0
- package/src/edge/sbx/common.js +186 -0
- package/src/edge/sbx/doc.js +121 -0
- package/src/edge/sbx/files.js +112 -0
- package/src/edge/sbx/frame.js +126 -0
- package/src/edge/sbx/gate.js +115 -0
- package/src/edge/sbx/sha256.js +68 -0
- package/src/edge/sbx/worker-entry.js +36 -0
- package/src/edge/sems.js +113 -0
- package/src/edge/service-host.js +57 -5
- package/src/edge/service-port.js +79 -5
- package/src/edge/setup.js +275 -0
- package/src/edge/shim.js +3 -1
- package/src/edge/watch.js +101 -0
- package/src/edge/worker.js +31 -2
- package/src/gowasm/setup.js +9 -6
- package/src/host/chan-service.js +8 -5
- package/src/host/chan-services.js +29 -4
- package/src/host/edge-host.js +58 -3
- package/wmdpack.wasm +0 -0
package/src/boot.js
CHANGED
|
@@ -48,7 +48,7 @@ import { ControlClient } from './host/ctl.js'
|
|
|
48
48
|
import { chooseTwin, eventsOf, putBackTwin, specKeysDiffering, twinForBoot } from './gowasm/boot-setup.js'
|
|
49
49
|
import { PAGE as CKPT_PAGE, requestCheckpoint } from './host/ckpt-point.js'
|
|
50
50
|
import {
|
|
51
|
-
CheckpointError, serviceErrorCode, assembleCheckpoint, bootKeyForChoice, bootKeyOf, checkCheckpointFits, checkPacksFit, checkVmKeyFits, packDigestsOf, fdTableBytes, parseCheckpoint, restoreFdTable, resumePorts, sha256Hex, validateFdTable,
|
|
51
|
+
CheckpointError, serviceErrorCode, assembleCheckpoint, bootKeyForChoice, specChoice, bootKeyOf, checkCheckpointFits, checkPacksFit, checkVmKeyFits, packDigestsOf, fdTableBytes, parseCheckpoint, restoreFdTable, resumePorts, sha256Hex, validateFdTable,
|
|
52
52
|
} from './host/ckpt.js'
|
|
53
53
|
import { captureJit, jitSnapStats, modulesOf, ownersNeedingHub, restoreStore } from './host/jit-snap.js'
|
|
54
54
|
export { CheckpointError, memoryStore, opfsStore } from './host/ckpt.js'
|
|
@@ -59,6 +59,169 @@ export { P9_CACHE_DEFAULT, P9_FEATURES_LIMIT_MS, P9_FEATURES_MAX_BYTES, P9_NAMES
|
|
|
59
59
|
import { bootGuestFeatures, p9DropNames, p9HandleFields } from './host/p9mount.js'
|
|
60
60
|
export { loadImageTar } from './registry/load-tar.js'
|
|
61
61
|
|
|
62
|
+
/** X5: the decisions of edgeSetup below, counted: `on` (node in the frame) and `off` by reason (node in the guest). */
|
|
63
|
+
export const edgePlanCounts = { on: 0, off: Object.create(null) }
|
|
64
|
+
/** X5: whether a page's `edge` option asks for node in the frame. On by default (no option, or `true`, or an object of settings): only `edge: false` turns it off. */
|
|
65
|
+
export const edgeWanted = v => v !== false && v !== null
|
|
66
|
+
/**
|
|
67
|
+
* X5: the container's node in a frame on another site, for a page that embeds the package (web/README.md "Node in the frame for an embedder").
|
|
68
|
+
* The frame site's origin is the one thing a page must give; the rest has defaults (src/edge/setup.js). Resolves {use, reason, edgeNode, bootOption(),
|
|
69
|
+
* prepare(), close(), bridge(), site}: hand `edgeNode` to containerBundle and `bootOption()` to bootWmd's `edge`, call prepare() after the boot and
|
|
70
|
+
* close() when the machine ends. With the switch off or no origin no edge module is loaded and node runs in the guest, the reason counted.
|
|
71
|
+
* What the origin means (X5 fix3p P2, web/README.md "Node in the frame for an embedder"): a container's frame runs on its origin, which the browser
|
|
72
|
+
* makes a security boundary. Containers given the SAME origin share that site's storage (IndexedDB, Cache Storage, OPFS), service names, locks and
|
|
73
|
+
* channels: a program of one can leave data for a program of another, when it reaches for the browser's objects on purpose (the runtime itself stores
|
|
74
|
+
* nothing there). An embedder that runs containers which must be kept apart gives each its own origin (a host name of its own, which needs a wildcard
|
|
75
|
+
* certificate and name, D-582); the files of the runtime are then fetched and compiled once per origin. An origin keeps its storage after its container
|
|
76
|
+
* ends: reuse of a host name for a new container must clear the site's data first, or take a new name. Kept frames never cross setups (P1).
|
|
77
|
+
* One page, one live setup per origin (check 2 F2, src/edge/setup.js): a second one gets node in the guest ("the frame site is in use") until the
|
|
78
|
+
* first one's close(), unless both passed `shareSite: true`.
|
|
79
|
+
* @param {{origin?: string, edge?: boolean, env?: string[], shareSite?: boolean}} [o]
|
|
80
|
+
*/
|
|
81
|
+
export async function edgeSetup(o = {}) {
|
|
82
|
+
const off = reason => {
|
|
83
|
+
edgePlanCounts.off[reason] = (edgePlanCounts.off[reason] || 0) + 1
|
|
84
|
+
return { use: false, reason, edgeNode: undefined, bootOption: () => undefined, prepare: () => null, close: () => {}, bridge: () => null, site: null, prepared: null }
|
|
85
|
+
}
|
|
86
|
+
if (!edgeWanted(o.edge)) return off('the switch is off')
|
|
87
|
+
// no frame site: the library makes the frame itself and the page fetches the files from the sources (src/edge/sbx/, options `sources` or `base`, default
|
|
88
|
+
// src/edge/base.js); their pins are the generated file src/edge/pins.gen.js, and a build without it runs node in the guest with one reason
|
|
89
|
+
let pinned = null
|
|
90
|
+
if (!o.origin) {
|
|
91
|
+
const F = await import('./edge/sbx/files.js')
|
|
92
|
+
if (!F.edgeSources(o)) return off('no frame site')
|
|
93
|
+
const P = await import('./edge/pins.js')
|
|
94
|
+
pinned = await (o.loadPins || P.loadEdgePins)()
|
|
95
|
+
if (!pinned) return off(P.EDGE_PINS_MISSING)
|
|
96
|
+
}
|
|
97
|
+
const { edgeSetupIn } = await import('./edge/setup.js')
|
|
98
|
+
return edgeSetupIn(pinned ? { ...o, pinned } : o, edgePlanCounts)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* X5 option A: the whole setup of node in the frame for a container, from the options bootWmd got. Only `edge: { base }` (or `edge: {}`) asks for it;
|
|
103
|
+
* `edge: false`, no `edge`, and the page bridge a page made itself (edgeSetup().bootOption(), it has onMessage) come back as they are. It reads the 9P
|
|
104
|
+
* service whose files hold bundle/config/config.json (and bundle/config/imageconfig.json), asks planEdge, adds the edge mounts to the spec (once), and
|
|
105
|
+
* returns the options with `edge` as the bridge's own option. The other fields of the object (watch, prepare, onLog, settings, a test's win and
|
|
106
|
+
* fetchFiles) go to edgeSetup. Nothing the caller passed is changed. -> {o, setup}: setup is edgeSetup's answer (use false: node runs in the guest, the
|
|
107
|
+
* reason counted and in setup.reason), or null when nothing was asked.
|
|
108
|
+
* A restore gives the same options and so the same files (the boot key is the same). The restored machine is a new machine of the same setup: its
|
|
109
|
+
* node runs come to a new bridge, the setup stays, its frame prepare is not made twice.
|
|
110
|
+
*/
|
|
111
|
+
export async function edgeAuto(o, counts = edgePlanCounts) {
|
|
112
|
+
const e = o.edge === true || o.edge === undefined ? {} : o.edge // `true` and no option are `{}`: the default base (none in the package) means node in the guest, with the reason
|
|
113
|
+
if (!e || typeof e !== 'object' || typeof e.onMessage === 'function') return { o, setup: null }
|
|
114
|
+
// F4d: a list of sources longer than the limit is a plain error here, before anything is fetched
|
|
115
|
+
const F = await import('./edge/sbx/files.js')
|
|
116
|
+
if (Array.isArray(e.sources)) F.checkCount(e.sources, 'edge.sources')
|
|
117
|
+
if (Array.isArray(e.base)) F.checkCount(e.base, 'edge.base')
|
|
118
|
+
const A = await import('./edge/auto.js')
|
|
119
|
+
const off = reason => {
|
|
120
|
+
counts.off[reason] = (counts.off[reason] || 0) + 1
|
|
121
|
+
return { o: { ...o, edge: undefined }, setup: { use: false, reason } }
|
|
122
|
+
}
|
|
123
|
+
const svc = A.findService(o)
|
|
124
|
+
if (!svc) return off('no 9P service holds bundle/config/config.json')
|
|
125
|
+
let facts
|
|
126
|
+
try {
|
|
127
|
+
facts = A.containerFacts(svc.files, o.args || [])
|
|
128
|
+
} catch {
|
|
129
|
+
return off('bundle/config/config.json is not JSON')
|
|
130
|
+
}
|
|
131
|
+
// a container that cannot use node in the frame loads no more of the edge code than the plan (the reason is counted)
|
|
132
|
+
const pre = A.preplan(facts, { rt: e.rt, win: e.win })
|
|
133
|
+
if (!pre.use) return off(pre.reason)
|
|
134
|
+
const setup = await edgeSetup({
|
|
135
|
+
...e,
|
|
136
|
+
edge: true,
|
|
137
|
+
env: facts.env,
|
|
138
|
+
user: facts.user,
|
|
139
|
+
readonlyRoot: facts.readonlyRoot,
|
|
140
|
+
hasTmpfs: facts.hasTmpfs,
|
|
141
|
+
p9port: svc.port,
|
|
142
|
+
root: svc.at ?? 'rootfs',
|
|
143
|
+
settings: { hostname: facts.hostname, ...(facts.cpus ? { cpus: facts.cpus } : {}), ...(e.settings || {}) },
|
|
144
|
+
})
|
|
145
|
+
if (!setup.use) return { o: { ...o, edge: undefined }, setup }
|
|
146
|
+
const files = A.addEdgeMounts(svc.files, setup.edgeNode)
|
|
147
|
+
const services = o.channels.services.map(s => (s === svc ? { ...s, files } : s))
|
|
148
|
+
return { o: { ...o, channels: { ...o.channels, services }, edge: setup.bootOption() }, setup }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** A browser that has everything node in the frame needs: used only to make the spec text of a checkpoint's choice (nothing is started with it). */
|
|
152
|
+
const ABLE_WIN = { SharedArrayBuffer: function SharedArrayBuffer() {}, crossOriginIsolated: true, WebAssembly: { Exception: function Exception() {} } }
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* X5 option A part 3, item 16: the options of the same container with the edge mounts of its node in the spec text, whatever this boot's own choice
|
|
156
|
+
* (edge: false, no pins, no sources and a browser that cannot included): only the tools decide the text, as X6's twin does. null: no 9P service with a
|
|
157
|
+
* spec, a spec that is not JSON, or an image without node (a checkpoint of such a container cannot have had node in the frame).
|
|
158
|
+
*/
|
|
159
|
+
async function edgeTextOptions(plain) {
|
|
160
|
+
const A = await import('./edge/auto.js')
|
|
161
|
+
const svc = A.findService(plain)
|
|
162
|
+
if (!svc) return null
|
|
163
|
+
try {
|
|
164
|
+
const e = plain.edge && typeof plain.edge === 'object' ? plain.edge : {}
|
|
165
|
+
const facts = A.containerFacts(svc.files, plain.args || [])
|
|
166
|
+
const pre = A.preplan(facts, { rt: e.rt, win: ABLE_WIN })
|
|
167
|
+
if (!pre.use) return null
|
|
168
|
+
const files = A.addEdgeMounts(svc.files, pre.node)
|
|
169
|
+
if (files === svc.files) return null // the spec already holds the mounts (the page made them itself): nothing to choose
|
|
170
|
+
return { ...plain, channels: { ...plain.channels, services: plain.channels.services.map(x => (x === svc ? { ...x, files } : x)) } }
|
|
171
|
+
} catch {
|
|
172
|
+
return null
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* X5 option A part 3, item 16: a restore keeps the choice of node in the frame its checkpoint was taken with (the rule X6 made for the Go twin, kept
|
|
178
|
+
* independent of it). `plain` is the options as the caller gave them, `auto` what edgeAuto made of them ({o, setup}; setup null when nothing was asked) and
|
|
179
|
+
* `header` the checkpoint's (or a base snapshot's) header. Which of the four spec texts (plain, twin, node, both) the header's boot description holds
|
|
180
|
+
* names the checkpoint's choice; the twin half is left to chooseTwin, which then sees a base that has the node text the checkpoint had.
|
|
181
|
+
* - the checkpoint had node and this boot has it: nothing changes;
|
|
182
|
+
* - the checkpoint had NO node and this boot would: the options without it, the setup is to be closed (`close`), one event {t: 'edge-off', rule: 'checkpoint'};
|
|
183
|
+
* - the checkpoint had node and this boot does not (edge: false, no pins, no sources, a browser that cannot): the machine keeps the checkpoint's spec text
|
|
184
|
+
* (its guest has the stub mounted), no setup, no frame, nothing fetched; every node start is refused and the stub runs the image's node in the guest;
|
|
185
|
+
* one event {t: 'edge-off', rule: 'checkpoint-node'}.
|
|
186
|
+
* A header with no description, a text that is none of the four, or an image without node change nothing: the usual check of the restore decides.
|
|
187
|
+
* -> {o, events, use, close}: `use` says the machine has its setup (the frame is used).
|
|
188
|
+
*/
|
|
189
|
+
export async function chooseEdge(plain, auto, header) {
|
|
190
|
+
const used = !!(auto && auto.setup && auto.setup.use)
|
|
191
|
+
const none = { o: auto.o, events: [], use: used, close: false }
|
|
192
|
+
if (!header || typeof header !== 'object' || (plain.edge && typeof plain.edge === 'object' && typeof plain.edge.onMessage === 'function')) return none
|
|
193
|
+
const A = await import('./edge/auto.js')
|
|
194
|
+
const svc = A.findService(plain)
|
|
195
|
+
if (!svc) return none
|
|
196
|
+
const i = plain.channels.services.indexOf(svc)
|
|
197
|
+
const withNode = await edgeTextOptions(plain)
|
|
198
|
+
if (!withNode) return none
|
|
199
|
+
const [tP, tE] = [await twinForBoot(plain), await twinForBoot(withNode)]
|
|
200
|
+
const text = (o, k) => (o.channels.services[k].files[A.BUNDLE_CONFIG])
|
|
201
|
+
const twinText = (v, k) => (v.texts || []).find(t => t.i === k)?.twin
|
|
202
|
+
const names = { plain: text(plain, i), node: text(withNode, i) }
|
|
203
|
+
if (twinText(tP, i) !== undefined) names.twin = twinText(tP, i)
|
|
204
|
+
if (twinText(tE, i) !== undefined) names.both = twinText(tE, i)
|
|
205
|
+
const n = await specChoice(header, i, svc.port, A.BUNDLE_CONFIG, names)
|
|
206
|
+
if (n === null) return none
|
|
207
|
+
const hadNode = n === 'node' || n === 'both'
|
|
208
|
+
if (hadNode === used) return none
|
|
209
|
+
if (hadNode) {
|
|
210
|
+
return { o: { ...withNode, edge: undefined }, events: [{ t: 'edge-off', rule: 'checkpoint-node', why: "the checkpoint was taken with node in the frame and node in the frame is off in this boot: the machine keeps the container's spec (node's stub is mounted in its memory) and every node start runs in the guest" }], use: false, close: false }
|
|
211
|
+
}
|
|
212
|
+
return { o: { ...plain, edge: undefined }, events: [{ t: 'edge-off', rule: 'checkpoint', why: 'the checkpoint was taken without node in the frame, so this machine runs without it (node runs in the guest)' }], use: false, close: true }
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** X5 option A: the setup closes when its machine ends (not when a restore replaces the machine). Resolves after that. */
|
|
216
|
+
export function edgeAutoEnd(setup, exited, restoring) {
|
|
217
|
+
return Promise.resolve(exited).then(
|
|
218
|
+
() => {},
|
|
219
|
+
() => {}
|
|
220
|
+
).then(() => {
|
|
221
|
+
if (!restoring()) setup.close()
|
|
222
|
+
})
|
|
223
|
+
}
|
|
224
|
+
|
|
62
225
|
const PAGE = 65536
|
|
63
226
|
/** A trap with the memory this close to its maximum is reported as out of memory. */
|
|
64
227
|
export const OOM_MARGIN = 64 << 20
|
|
@@ -698,6 +861,30 @@ export async function bootWmd(o) {
|
|
|
698
861
|
if (!globalThis.crossOriginIsolated) {
|
|
699
862
|
throw new Error('page is not cross-origin isolated (needs COOP same-origin + COEP require-corp)')
|
|
700
863
|
}
|
|
864
|
+
// X5 option A: `edge: { base }` is all a page says; the setup of node in the frame is done here (edgeAuto below)
|
|
865
|
+
const plain0 = o // the options as the caller gave them: a restore chooses node in the frame from its checkpoint's choice (chooseEdge)
|
|
866
|
+
let auto = null
|
|
867
|
+
if (o.edge === true || o.edge === undefined || (o.edge && typeof o.edge === 'object' && typeof o.edge.onMessage !== 'function')) {
|
|
868
|
+
auto = await edgeAuto(o)
|
|
869
|
+
o = auto.setup?.use ? { ...auto.o, _edgeAuto: auto.setup } : auto.o
|
|
870
|
+
}
|
|
871
|
+
if (o.restore?.header) {
|
|
872
|
+
// item 16: a checkpoint in hand decides whether node is in the frame, whatever edge says (also with edge: false and the other kinds of off)
|
|
873
|
+
const c = await chooseEdge(plain0, auto || { o: plain0, setup: null }, o.restore.header)
|
|
874
|
+
for (const e of c.events) o.onEvent?.(e)
|
|
875
|
+
if (c.close) o._edgeAuto?.close()
|
|
876
|
+
if (c.events.length || c.close) o = { ...o, channels: c.o.channels, edge: c.o.edge, _edgeAuto: c.use ? o._edgeAuto : undefined }
|
|
877
|
+
}
|
|
878
|
+
if (!o._edgePlain) o = { ...o, _edgePlain: plain0 }
|
|
879
|
+
try {
|
|
880
|
+
return await bootMachine(o)
|
|
881
|
+
} catch (e) {
|
|
882
|
+
o._edgeAuto?.close() // a boot that failed (a restore's too) leaves no frame site held
|
|
883
|
+
throw e
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
async function bootMachine(o) {
|
|
701
888
|
const t0 = absMs()
|
|
702
889
|
const timings = { t0 }
|
|
703
890
|
const ev = e => o.onEvent?.(e)
|
|
@@ -708,7 +895,7 @@ export async function bootWmd(o) {
|
|
|
708
895
|
// with the twin that this boot has off (gowasm: false, no source, a setup that is not usable) restores (part 6): its spec text stays (the guest has the stub mounts),
|
|
709
896
|
// the service's gowasm field says `off` so the page starts no twin Worker, the channel service builds a GoEdge that is off from the start (every stub is answered
|
|
710
897
|
// with the fallback, the guest compiles), and one event {t: 'gowasm-off', rule: 'checkpoint-twin'} says so.
|
|
711
|
-
|
|
898
|
+
let twin = await twinForBoot(o)
|
|
712
899
|
const twinFirst = await chooseTwin(twin, o.restore?.header || null)
|
|
713
900
|
o = twinFirst.o
|
|
714
901
|
// the twin's events are said once: now, or, for a base snapshot (o.restoreLazy), when its header is known (its choice may supersede the boot's own reason)
|
|
@@ -882,6 +1069,8 @@ export async function bootWmd(o) {
|
|
|
882
1069
|
).then(downloaded)
|
|
883
1070
|
layersP.catch(() => {})
|
|
884
1071
|
let module, files, chanLayers, tableMin, vmBytes
|
|
1072
|
+
let edgeBefore = null // the options and twin before the base snapshot's header changed node's choice
|
|
1073
|
+
let closeEdgeAfter = null
|
|
885
1074
|
let twinByBase = false // the base snapshot's header changed the twin choice (a header refused after that puts the options' choice back)
|
|
886
1075
|
let twinChosen = null // chooseTwin's answer for the base snapshot's header: its events are said when the snapshot is accepted (or the options' own, when it is refused)
|
|
887
1076
|
async function baseRefused(err) {
|
|
@@ -894,6 +1083,15 @@ export async function bootWmd(o) {
|
|
|
894
1083
|
if (!o.restoreFallback) throw err
|
|
895
1084
|
// fix 10 (F1): the machine boots cold, so it takes the options' own twin choice (spec text, gowasm field, boot key) whatever refused the snapshot, the header or
|
|
896
1085
|
// the checks of its body: this is the one place
|
|
1086
|
+
// X5 item 16: and node's own choice of the options first (the frame's stubs go back into the spec; the setup of the options' node is still open, it is
|
|
1087
|
+
// let go only once the snapshot is accepted), so the twin put back below is the one made for that spec
|
|
1088
|
+
if (edgeBefore) {
|
|
1089
|
+
o = { ...o, channels: edgeBefore.o.channels, edge: edgeBefore.o.edge, _edgeAuto: edgeBefore.o._edgeAuto }
|
|
1090
|
+
twin = edgeBefore.twin
|
|
1091
|
+
chanSvcs = o.channels?.services || []
|
|
1092
|
+
edgeBefore = null
|
|
1093
|
+
}
|
|
1094
|
+
closeEdgeAfter = null
|
|
897
1095
|
if (twinByBase) {
|
|
898
1096
|
const back = await putBackTwin(twin, o, bootDesc, { flat: flatRam, maxPages: maximum })
|
|
899
1097
|
o = back.o
|
|
@@ -923,6 +1121,18 @@ export async function bootWmd(o) {
|
|
|
923
1121
|
settleLayout(chooseLayout(o.args, o, h)) // X24 default: the base snapshot's own layout
|
|
924
1122
|
// part 4: and its own twin choice. The spec text is first used by the boot key and by the channel service's Worker, both below this point in this same
|
|
925
1123
|
// try, so the choice made here is made before either has it; only the layers and ports of the services were used before (their packs download meanwhile)
|
|
1124
|
+
// item 16: and its own choice of node in the frame (the twin below then sees the spec text of that choice)
|
|
1125
|
+
const ce = o._edgePlain ? await chooseEdge(o._edgePlain, { o, setup: { use: !!o._edgeAuto } }, h) : null
|
|
1126
|
+
if (ce && ce.o !== o) {
|
|
1127
|
+
edgeBefore = { o, twin }
|
|
1128
|
+
o = { ...o, channels: ce.o.channels, edge: ce.o.edge }
|
|
1129
|
+
twin = await twinForBoot(o)
|
|
1130
|
+
chanSvcs = o.channels?.services || []
|
|
1131
|
+
twinByBase = true
|
|
1132
|
+
for (const e of ce.events) ev(e)
|
|
1133
|
+
if (ce.close) closeEdgeAfter = o._edgeAuto
|
|
1134
|
+
if (!ce.use) o = { ...o, _edgeAuto: undefined }
|
|
1135
|
+
}
|
|
926
1136
|
const tw = await chooseTwin(twin, h)
|
|
927
1137
|
if (tw.o !== o) {
|
|
928
1138
|
o = { ...o, channels: tw.o.channels }
|
|
@@ -1011,6 +1221,8 @@ export async function bootWmd(o) {
|
|
|
1011
1221
|
restoreIn = parsed
|
|
1012
1222
|
if (!twinSaid) for (const e of twinChosen ? eventsOf(twin, twinChosen) : twin.events) ev(e) // the snapshot is accepted: the checkpoint's twin choice stands
|
|
1013
1223
|
twinSaid = true
|
|
1224
|
+
closeEdgeAfter?.close() // and its choice of node: the setup of a node that this machine does not use is let go
|
|
1225
|
+
closeEdgeAfter = null
|
|
1014
1226
|
lazyIn = null // baseLazy stays: accept() when the restore has succeeded, reject() if it fails
|
|
1015
1227
|
} catch (err) {
|
|
1016
1228
|
if (signal?.aborted) throw err
|
|
@@ -2214,7 +2426,16 @@ export async function bootWmd(o) {
|
|
|
2214
2426
|
// made against that layout's key, memory maximum and RAM memory, not this machine's
|
|
2215
2427
|
const L = chooseLayout(o.args, { ...o, ...over }, parsed.header)
|
|
2216
2428
|
// part 4: and its twin choice (the next machine's own, from the options as the caller gave them): a checkpoint taken with the twin restores whatever this boot's twin state (chooseTwin keeps its spec text and says the twin is off), the usual fit check follows, before this machine stops
|
|
2217
|
-
|
|
2429
|
+
let nextOpts = { ...o, channels: twin.plain.channels, ...over }
|
|
2430
|
+
// item 16: and its choice of node in the frame (before the twin's: the twin's texts are made on the spec text of that choice)
|
|
2431
|
+
let edgeEvents = []
|
|
2432
|
+
let closeEdge = null
|
|
2433
|
+
const ce = o._edgePlain && !('channels' in over) && !('edge' in over) ? await chooseEdge(o._edgePlain, { o: nextOpts, setup: { use: !!o._edgeAuto } }, parsed.header) : null
|
|
2434
|
+
if (ce && (ce.events.length || ce.close)) {
|
|
2435
|
+
nextOpts = { ...nextOpts, channels: ce.o.channels, edge: ce.o.edge, _edgeAuto: ce.use ? o._edgeAuto : undefined }
|
|
2436
|
+
edgeEvents = ce.events
|
|
2437
|
+
closeEdge = ce.close ? o._edgeAuto : null
|
|
2438
|
+
}
|
|
2218
2439
|
const tw = await chooseTwin(await twinForBoot(nextOpts), parsed.header)
|
|
2219
2440
|
const cfgKeys = bootDesc ? await specKeysDiffering(bootDesc, tw.o.channels?.services) : {}
|
|
2220
2441
|
let target = { key: bootKey, desc: bootDesc }
|
|
@@ -2233,6 +2454,7 @@ export async function bootWmd(o) {
|
|
|
2233
2454
|
keepHub = !!(hub && parsed.jit)
|
|
2234
2455
|
let oldHub = null
|
|
2235
2456
|
try {
|
|
2457
|
+
for (const e of edgeEvents) ev(e) // the restore is taken (the checks above passed): node's choice is said once
|
|
2236
2458
|
finish(EXIT_STOPPED, 'stopped')
|
|
2237
2459
|
await exited
|
|
2238
2460
|
memory = null
|
|
@@ -2240,6 +2462,7 @@ export async function bootWmd(o) {
|
|
|
2240
2462
|
keptHub = null
|
|
2241
2463
|
const next = await bootWmd({ ...nextOpts, checkpoint: true, restore: ckpt, assets, _adopt: oldHub, _net: { instance: netInstance, names: [...netNames] } })
|
|
2242
2464
|
heldAssets = null // the new machine holds them
|
|
2465
|
+
closeEdge?.close() // a checkpoint taken without node: the setup of the machine that had it is let go
|
|
2243
2466
|
return next
|
|
2244
2467
|
} finally {
|
|
2245
2468
|
keepHub = false
|
|
@@ -2369,7 +2592,7 @@ export async function bootWmd(o) {
|
|
|
2369
2592
|
ours.push(mc.port1)
|
|
2370
2593
|
theirs.push(mc.port2)
|
|
2371
2594
|
}
|
|
2372
|
-
chanSvc.postMessage({ t: 'edge-fs', port9p: port, mounts, root, ports: ours, yieldMs, run, own, job, kickAll }, ours)
|
|
2595
|
+
chanSvc.postMessage({ t: 'edge-fs', port9p: port, mounts, root, ports: ours, yieldMs, run, own, job, kickAll, ringMax: globalThis.__wmdRingMax }, ours) // ringMax: a page's test knob (the first run's value counts)
|
|
2373
2596
|
return theirs
|
|
2374
2597
|
},
|
|
2375
2598
|
/** X5 (edge=1 only): the page's answer or output for a node start the service asked for ({id, ev: 'reply'|'out'|'exit', ...}). */
|
|
@@ -2446,5 +2669,9 @@ export async function bootWmd(o) {
|
|
|
2446
2669
|
// fix10: the guest drops the names and attributes it keeps (9P names; plain mmap keeps none): the bridge asks it after a run whose stub went away
|
|
2447
2670
|
const edgeDropNames = () => (control && !done && !chanDied ? p9DropNames(control) : Promise.reject(new Error('edgeDropNames: the machine has ended')))
|
|
2448
2671
|
Object.assign(edgeHandle, { edgeFs: api.edgeFs, edgeMessage: api.edgeMessage, edgeYield: api.edgeYield, edgeRelease: api.edgeRelease, edgeDropNames })
|
|
2672
|
+
if (o._edgeAuto) {
|
|
2673
|
+
o._edgeAuto.prepare() // once per setup: the frame is made when the page is idle
|
|
2674
|
+
edgeAutoEnd(o._edgeAuto, exited, () => restoring)
|
|
2675
|
+
}
|
|
2449
2676
|
return api
|
|
2450
2677
|
}
|
package/src/edge/auto.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// X5 option A item 3: what bootWmd reads from a container's files to set up node in the frame by itself (src/boot.js edgeAuto), and the one thing it
|
|
2
|
+
// changes there: the three mounts of the image's node (src/host/ctl.js edgeSpecMounts). Plain functions, no browser.
|
|
3
|
+
import { EDGE_CONTAINER_DIR, NODE_PATHS, edgeSpecMounts, planEdge } from './plan.js'
|
|
4
|
+
|
|
5
|
+
export const BUNDLE_CONFIG = 'bundle/config/config.json'
|
|
6
|
+
export const BUNDLE_IMAGE = 'bundle/config/imageconfig.json'
|
|
7
|
+
const dec = new TextDecoder()
|
|
8
|
+
const enc = new TextEncoder()
|
|
9
|
+
|
|
10
|
+
/** The text of a 9P service file: its text, its bytes, or {data}. -> string, or null for a url or something else. */
|
|
11
|
+
export function textOf(v) {
|
|
12
|
+
if (typeof v === 'string') return v
|
|
13
|
+
if (v instanceof Uint8Array) return dec.decode(v)
|
|
14
|
+
if (v instanceof ArrayBuffer) return dec.decode(new Uint8Array(v))
|
|
15
|
+
if (v && typeof v === 'object' && 'data' in v) return textOf(v.data)
|
|
16
|
+
return null
|
|
17
|
+
}
|
|
18
|
+
/** `text` in the form `old` had (text stays text, bytes stay bytes, {data, mode, ...} keeps its fields). */
|
|
19
|
+
export function sameForm(old, text) {
|
|
20
|
+
if (typeof old === 'string') return text
|
|
21
|
+
if (old instanceof Uint8Array || old instanceof ArrayBuffer) return enc.encode(text)
|
|
22
|
+
return { ...old, data: sameForm(old.data, text) }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The 9P service of the container's files: the first of kind 9p (the default kind) whose files hold the bundle's config.json. */
|
|
26
|
+
export const findService = o => (o?.channels?.services || []).find(s => s && (s.kind ?? '9p') === '9p' && s.files && s.files[BUNDLE_CONFIG] !== undefined) || null
|
|
27
|
+
|
|
28
|
+
const userOf = u => (u && typeof u === 'object' ? `${u.uid ?? 0}${u.gid !== undefined ? ':' + u.gid : ''}` : String(u ?? ''))
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* What planEdge needs, read from the service's files: the spec (bundle/config/config.json) and the image's config (bundle/config/imageconfig.json).
|
|
32
|
+
* The spec's environment is the container's; the image's own is the fallback when the spec has none. Throws when the spec is not JSON.
|
|
33
|
+
* @returns {{env: string[], user: string, readonlyRoot: boolean, hasTmpfs: boolean, hostname: string, cpus: number|undefined}}
|
|
34
|
+
*/
|
|
35
|
+
export function containerFacts(files, args = []) {
|
|
36
|
+
const spec = JSON.parse(textOf(files[BUNDLE_CONFIG]) ?? '')
|
|
37
|
+
let image = {}
|
|
38
|
+
try {
|
|
39
|
+
image = JSON.parse(textOf(files[BUNDLE_IMAGE]) ?? '{}') || {}
|
|
40
|
+
} catch {
|
|
41
|
+
image = {}
|
|
42
|
+
}
|
|
43
|
+
const specEnv = spec?.process?.env
|
|
44
|
+
const env = Array.isArray(specEnv) && specEnv.length ? specEnv.map(String) : (image?.config?.Env || []).map(String)
|
|
45
|
+
// the engine's own tmpfs mounts (/dev, /dev/shm) are not the user's; any other tmpfs is, and the desktop refuses it too
|
|
46
|
+
const hasTmpfs = (spec?.mounts || []).some(m => m && m.type === 'tmpfs' && m.destination !== '/dev' && m.destination !== '/dev/shm')
|
|
47
|
+
const i = args.indexOf('--cpus')
|
|
48
|
+
const cpus = i >= 0 && Number(args[i + 1]) > 0 ? Number(args[i + 1]) : undefined
|
|
49
|
+
return { env, user: userOf(spec?.process?.user), readonlyRoot: !!spec?.root?.readonly, hasTmpfs, hostname: spec?.hostname || 'wmd-web', cpus }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The files with the edge mounts of the image's node added to the spec, once: a spec that already has them (containerBundle's `edgeNode`, or an earlier
|
|
54
|
+
* call) comes back unchanged. The mounts go where containerBundle puts them (before the /etc files). A new files object; the caller's is not changed.
|
|
55
|
+
*/
|
|
56
|
+
export function addEdgeMounts(files, node, rootfsPath = '/run/wmd9p/rootfs') {
|
|
57
|
+
const text = textOf(files[BUNDLE_CONFIG])
|
|
58
|
+
const spec = JSON.parse(text)
|
|
59
|
+
const have = new Set((spec.mounts || []).map(m => m.destination))
|
|
60
|
+
const root = spec.root?.path || rootfsPath
|
|
61
|
+
const add = edgeSpecMounts(node, root).filter(m => !have.has(m.destination))
|
|
62
|
+
if (!add.length) return files
|
|
63
|
+
const mounts = [...(spec.mounts || [])]
|
|
64
|
+
const at = mounts.findIndex(m => String(m.destination).startsWith('/etc/'))
|
|
65
|
+
mounts.splice(at < 0 ? mounts.length : at, 0, ...add)
|
|
66
|
+
const out = JSON.stringify({ ...spec, mounts }, null, 2) + '\n'
|
|
67
|
+
return { ...files, [BUNDLE_CONFIG]: sameForm(files[BUNDLE_CONFIG], out) }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export { EDGE_CONTAINER_DIR }
|
|
71
|
+
|
|
72
|
+
/** What the browser needs for node in the frame (the same test as setup.js edgeBrowserOk, here so that a container that cannot use it loads nothing more). */
|
|
73
|
+
export const browserOk = (g = globalThis) => typeof g.SharedArrayBuffer === 'function' && g.crossOriginIsolated === true && typeof g.WebAssembly?.Exception === 'function'
|
|
74
|
+
|
|
75
|
+
/** planEdge for the facts of a container (see containerFacts). -> {use, node?, reason?} */
|
|
76
|
+
export const preplan = (facts, { rt, win = globalThis } = {}) =>
|
|
77
|
+
planEdge({ enabled: true, env: facts.env, user: facts.user, readonlyRoot: facts.readonlyRoot, hasTmpfs: facts.hasTmpfs, hasJspi: browserOk(win), rt, nodePath: NODE_PATHS[0] })
|
package/src/edge/base.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// The places the files of node in the sandboxed frame come from when the embedder names none (the option edge: { sources } of bootWmd; edge: { base }
|
|
2
|
+
// is the short form for one file base). ONE constant, the same shape as X6's GOWASM_SOURCES_DEFAULT (src/gowasm/setup.js): the registry's tarball of the
|
|
3
|
+
// package first, then two file mirrors of the same package. The package and its version are not written here: only the pins (src/edge/pins.gen.js,
|
|
4
|
+
// written by the release from the files it publishes as @threadedstack/wmd-node, version = the release's) say which, in the {name} {version} {file} of
|
|
5
|
+
// the urls. A checkout or a package without pins runs node in the guest, with one calm reason.
|
|
6
|
+
export const EDGE_SOURCES_DEFAULT = [
|
|
7
|
+
{ kind: 'tgz', url: 'https://registry.npmjs.org/{name}/-/{file}-{version}.tgz' },
|
|
8
|
+
{ kind: 'file', base: 'https://cdn.jsdelivr.net/npm/{name}@{version}' },
|
|
9
|
+
{ kind: 'file', base: 'https://unpkg.com/{name}@{version}' },
|
|
10
|
+
]
|
package/src/edge/bridge.js
CHANGED
|
@@ -22,8 +22,9 @@
|
|
|
22
22
|
// that (a listing the SDK cannot take, a start error) is a fallback: the stub runs the image's node in the guest.
|
|
23
23
|
|
|
24
24
|
import { RT_DEFAULT, deliversSignals, runtimeConfig } from './runtime.js'
|
|
25
|
-
import { frameCounts } from './page.js'
|
|
25
|
+
import { frameCounts, useSite } from './page.js'
|
|
26
26
|
import { addCounts } from './own/wasm-counters.js'
|
|
27
|
+
import { pythonModuleFor } from './python-module.js'
|
|
27
28
|
|
|
28
29
|
const SIGNALS_BY_REASON = { killed: 9, terminated: 15 }
|
|
29
30
|
/** Counts under a name: the name may come from the frame (`done.reason`), so it never reaches an inherited property (check5 F4). */
|
|
@@ -32,7 +33,11 @@ const counter = () => Object.create(null)
|
|
|
32
33
|
/** Default action ends the program: HUP, INT, QUIT, ABRT, KILL, USR2, ALRM, TERM. (USR1 starts node's inspector; CHLD, WINCH, URG, CONT are ignored.) */
|
|
33
34
|
export const SIGNAL_ENDS = new Set([1, 2, 3, 6, 9, 12, 14, 15])
|
|
34
35
|
export const KILL_GRACE_MS = 3000
|
|
36
|
+
/** The fallback reason of a start that comes after the embedder's close() (X5 fix2 F1). */
|
|
37
|
+
export const EDGE_CLOSED = 'the edge setup was closed'
|
|
35
38
|
const enc = new TextEncoder()
|
|
39
|
+
/** A umask as the kernel keeps it: an integer from 0 to 0777. The stub's hello carries the caller's (X5 fix3 R1); an older stub sends none and the shim takes 022. */
|
|
40
|
+
const validUmask = u => Number.isInteger(u) && u >= 0 && u <= 0o777
|
|
36
41
|
|
|
37
42
|
export const YIELD_OPEN_MS = 0.25 // the channel loop's yield while a run is open (X5 gate 2b stage 1: 10 ms makes every crossing wait for it)
|
|
38
43
|
|
|
@@ -45,8 +50,10 @@ function envObject(env) {
|
|
|
45
50
|
return o
|
|
46
51
|
}
|
|
47
52
|
|
|
48
|
-
export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT, edgeWasm = '/wasm/edgejs.wasm', yieldMs = YIELD_OPEN_MS, run, onLog = () => {}, parallelism = 2, watch = {}, killGraceMs = KILL_GRACE_MS, site = null, handIn = null, nodeVersion = '' }) {
|
|
53
|
+
export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT, edgeWasm = '/wasm/edgejs.wasm', linuxSrc = '', yieldMs = YIELD_OPEN_MS, run, onLog = () => {}, parallelism = 2, watch = {}, killGraceMs = KILL_GRACE_MS, site = null, handIn = null, nodeVersion = '', python = null, doc = globalThis.document, owner = null }) {
|
|
49
54
|
const jobs = new Map()
|
|
55
|
+
// K1: this bridge's machine uses the frame site; when the last machine of the page that uses it ends, its kept frame goes (page.js useSite)
|
|
56
|
+
const releaseSite = useSite(owner || doc, origin)
|
|
50
57
|
// fix7 (item 8): where the time of a start goes, milliseconds summed over the runs and how many runs had each step (the frame's steps come from adapter.js stats().stages)
|
|
51
58
|
const stage = (k, v) => {
|
|
52
59
|
const e = ((stats.stages ||= {})[k] ||= { n: 0, ms: 0 })
|
|
@@ -78,13 +85,14 @@ export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT,
|
|
|
78
85
|
rt,
|
|
79
86
|
...runtimeConfig(rt, handIn), // the runtime's own files (rt=own) or the base the caller handed the SDK in under (rt=sdk)
|
|
80
87
|
edgeWasm,
|
|
88
|
+
...(linuxSrc ? { linuxSrc } : {}), // the sandboxed frame hands the shim in under a name (src/edge/sbx/)
|
|
81
89
|
args: (hello.argv || []).slice(1),
|
|
82
90
|
env: envObject(hello.env),
|
|
83
91
|
cwd: hello.cwd || '/',
|
|
84
92
|
stream: true,
|
|
85
93
|
stdin: 'pipe',
|
|
86
94
|
parallelism,
|
|
87
|
-
linux: { ...settings, uid: hello.uid, gid: hello.gid, utc: true, ...(nodeVersion ? { nodeVersion } : {}) }, // utc: a container with another TZ never gets here (edge-host.js helloRefusal)
|
|
95
|
+
linux: { ...settings, uid: hello.uid, gid: hello.gid, utc: true, ...(nodeVersion ? { nodeVersion } : {}), ...(validUmask(hello.umask) ? { umask: hello.umask } : {}), ...(typeof hello.argv?.[0] === 'string' && hello.argv[0] ? { argv0: hello.argv[0] } : {}) }, // utc: a container with another TZ never gets here (edge-host.js helloRefusal)
|
|
88
96
|
}
|
|
89
97
|
const fallback = why => {
|
|
90
98
|
if (job.ready || job.ended) return
|
|
@@ -93,6 +101,19 @@ export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT,
|
|
|
93
101
|
bump(stats.fallbackWhy, why)
|
|
94
102
|
answer({ id, ev: 'reply', fallback: why })
|
|
95
103
|
}
|
|
104
|
+
// X25 gate 2: a start of the image's python (the page's plan took it: src/edge/plan.js planPython; the service decided this start: service-host.js)
|
|
105
|
+
// runs the frame's CPython of the image's version with the container's standard library through the file route, and python's shim (edge/src/linux.py)
|
|
106
|
+
if (/^python/.test(String(hello.argv?.[0] || '').split('/').pop())) {
|
|
107
|
+
if (!python) return fallback('python in the frame is off for this container')
|
|
108
|
+
const mod = pythonModuleFor(python.version)
|
|
109
|
+
if (!mod) return fallback(`image python ${python.version} has no module here`)
|
|
110
|
+
const sbx = String(linuxSrc).startsWith('sbx:') // the sandboxed frame: the page hands the files in under their names (src/edge/sbx/worker-entry.js)
|
|
111
|
+
cfg.edgeWasm = sbx ? `sbx:${mod.file}` : mod.url
|
|
112
|
+
cfg.linuxSrc = sbx ? 'sbx:linux.py' : '/wasm/linux.py'
|
|
113
|
+
cfg.args = hello.argv.slice(1)
|
|
114
|
+
cfg.python = { argv0: python.path, execPath: python.path, ...(python.maxMiB ? { maxMiB: python.maxMiB } : {}) }
|
|
115
|
+
cfg.linux = { ...cfg.linux, execPath: python.path }
|
|
116
|
+
}
|
|
96
117
|
run({
|
|
97
118
|
vm,
|
|
98
119
|
job: id, // the service's number of this node run: the file route's port finds the stub's channel for children by it
|
|
@@ -132,6 +153,7 @@ export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT,
|
|
|
132
153
|
site?.markDown(why, { kind: 'runtime' })
|
|
133
154
|
}
|
|
134
155
|
bump(stats.fallbackWhy, why)
|
|
156
|
+
stage('fallbackMs', performance.now() - job.t0) // fix round item 4 (F5a): the page's time from the start's arrival to its answer 'run it in the guest'
|
|
135
157
|
return answer({ id, ev: 'reply', fallback: why })
|
|
136
158
|
}
|
|
137
159
|
stats.exits++
|
|
@@ -139,6 +161,11 @@ export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT,
|
|
|
139
161
|
// fix7 (F1): bytes the frame's worker says it posted and the page did not take: counted, and said on stderr (a lost error text is never silent)
|
|
140
162
|
if (r.stages) for (const [k, v] of Object.entries(r.stages)) if (typeof v === 'number') stage(k, v)
|
|
141
163
|
if (r.setupMs) stage('frameSetup', r.setupMs) // the frame worker's load + start (adapter.js), as it measures itself
|
|
164
|
+
if (r.marks) {
|
|
165
|
+
// X5 default1 round 2 (B2.1): the last 40 runs' marks (page option edgeMarks=1, own/marks.js), with the time the page waited for the run
|
|
166
|
+
;(stats.marksRuns ||= []).push({ ...r.marks, pageTotal: Math.round(performance.now() - job.t0), helloAbs: performance.timeOrigin + job.t0, exitAbs: performance.timeOrigin + performance.now() })
|
|
167
|
+
if (stats.marksRuns.length > 40) stats.marksRuns.shift()
|
|
168
|
+
}
|
|
142
169
|
if (r.files) {
|
|
143
170
|
// fix7 (F11): how the runtime's files stood against HASHES.txt, summed over the runs
|
|
144
171
|
const t = (stats.files ||= { checked: 0, ok: 0, mismatch: 0, missing: 0, unlisted: 0 })
|
|
@@ -160,6 +187,7 @@ export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT,
|
|
|
160
187
|
const t = (stats.capi ||= { messages: 0, bytes: 0, copies: 0, copyBytes: 0, maxMessage: 0, maxRecipients: 0, heldBytes: 0, heldPeak: 0 })
|
|
161
188
|
for (const k of Object.keys(t)) t[k] = ['maxMessage', 'maxRecipients', 'heldPeak'].includes(k) ? Math.max(t[k], Number(r.capi[k]) || 0) : t[k] + (Number(r.capi[k]) || 0)
|
|
162
189
|
}
|
|
190
|
+
if (Number(r.forged) > 0) stats.forgedMessages = (stats.forgedMessages || 0) + Number(r.forged) // X5 fix3p P3: messages of the runtime's Workers that were of no known kind (dropped)
|
|
163
191
|
if (r.pipes) {
|
|
164
192
|
// what the runtime handed the adapter's pipes, summed over the runs, and the bytes that came after a pipe ended (lost)
|
|
165
193
|
const t = (stats.pipes ||= { out: 0, err: 0, lateOut: 0, lateErr: 0, unreadOut: 0, unreadErr: 0 })
|
|
@@ -167,6 +195,10 @@ export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT,
|
|
|
167
195
|
}
|
|
168
196
|
if (r.outBytes) for (const k of ['stdout', 'stderr']) if (Number(r.outBytes[k]) > job.outBytes[k]) stats.outDropped += Number(r.outBytes[k]) - job.outBytes[k]
|
|
169
197
|
if (job.killedBy && r.reason !== 'exited') return answer({ id, ev: 'exit', code: 128 + job.killedBy, signal: job.killedBy })
|
|
198
|
+
// X5 fix3 R4: a program that ended by an unhandled signal of the guest's dies of that signal (the shell's `wait` and its job message are the same
|
|
199
|
+
// as for node in the guest); one that handled it and chose 128+n itself, or ended with another code, exits with its code
|
|
200
|
+
if (job.diedBy && (r.reason === 'exit' || r.reason === 'exited') && r.exitCode === 128 + job.diedBy) return answer({ id, ev: 'exit', code: r.exitCode, signal: job.diedBy })
|
|
201
|
+
if (r.signal) return answer({ id, ev: 'exit', code: 128 + r.signal, signal: r.signal }) // python: the default action of a signal ended it (adapter.js)
|
|
170
202
|
const sig = Object.hasOwn(SIGNALS_BY_REASON, r.reason) ? SIGNALS_BY_REASON[r.reason] : undefined
|
|
171
203
|
if (r.error) {
|
|
172
204
|
const msg = enc.encode(`wmd: node's frame ended with an error: ${String(r.error).split('\n')[0]}\n`)
|
|
@@ -236,15 +268,26 @@ export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT,
|
|
|
236
268
|
}
|
|
237
269
|
|
|
238
270
|
return {
|
|
239
|
-
stats: () => ({ ...stats, frames: { created: frameCounts.created, removed: frameCounts.removed, live: frameCounts.created - frameCounts.removed }, fallbackWhy: { ...stats.fallbackWhy }, lost: { ...stats.lost }, signals: { ...stats.signals }, ...(site ? { site: site.stats() } : {}) }),
|
|
271
|
+
stats: () => ({ ...stats, frames: { created: frameCounts.created, removed: frameCounts.removed, live: frameCounts.created - frameCounts.removed, kept: frameCounts.kept, reused: frameCounts.reused, stale: frameCounts.stale, released: frameCounts.released, capped: frameCounts.capped || 0 }, fallbackWhy: { ...stats.fallbackWhy }, lost: { ...stats.lost }, signals: { ...stats.signals }, ...(site ? { site: site.stats() } : {}) }),
|
|
240
272
|
/** True while a run is open (the page refuses vm.checkpoint() then). */
|
|
241
273
|
busy: () => stats.open > 0,
|
|
274
|
+
/**
|
|
275
|
+
* X5 fix2 F1: a start that comes after this bridge was closed while its machine still runs (the embedder's edge.close() came early): no run is made
|
|
276
|
+
* and no frame; the stub is told to run the image's node itself, and the fallback is counted with its reason. Any other event has no job to reach.
|
|
277
|
+
*/
|
|
278
|
+
refuse(m, why) {
|
|
279
|
+
if (!m || m.ev !== 'start') return
|
|
280
|
+
stats.fallbacks++
|
|
281
|
+
bump(stats.fallbackWhy, why)
|
|
282
|
+
answer({ id: m.id, ev: 'reply', fallback: why })
|
|
283
|
+
},
|
|
242
284
|
/** The machine this bridge belongs to has ended: every open run is ended through its control (its output has nowhere to go). */
|
|
243
285
|
close() {
|
|
244
286
|
for (const job of [...jobs.values()]) {
|
|
245
287
|
clearTimeout(job.force)
|
|
246
288
|
job.control.abort?.()
|
|
247
289
|
}
|
|
290
|
+
releaseSite()
|
|
248
291
|
},
|
|
249
292
|
onMessage(m) {
|
|
250
293
|
if (m.ev === 'start') return start(m)
|
|
@@ -260,6 +303,9 @@ export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT,
|
|
|
260
303
|
clearTimeout(job.force)
|
|
261
304
|
job.force = null
|
|
262
305
|
stats.signalsHandled = (stats.signalsHandled || 0) + 1
|
|
306
|
+
} else if (SIGNAL_ENDS.has(m.n)) {
|
|
307
|
+
// X5 fix3 R4: no handler, and the signal's default action ends the program: it ends itself with 128+n (the shim), and the stub is told it died of n
|
|
308
|
+
job.diedBy = m.n
|
|
263
309
|
}
|
|
264
310
|
}
|
|
265
311
|
else if (m.ev === 'gone') {
|
|
@@ -273,25 +319,48 @@ export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT,
|
|
|
273
319
|
/**
|
|
274
320
|
* One bridge per machine. vm.restore() builds the next machine from the first boot's options, so the page cannot keep "the bridge" in a closure of
|
|
275
321
|
* them: the machine's handle comes with every message, and a message from a machine that is not the current one makes a new bridge with that
|
|
276
|
-
* handle and closes the old one. The messages of a machine that was replaced are dropped (it has ended).
|
|
322
|
+
* handle and closes the old one. The messages of a machine that was replaced are dropped (it has ended: nobody reads an answer).
|
|
323
|
+
* A machine whose bridge was closed by close() while the machine goes on (the embedder's edge.close() came early) is not that case: its stub
|
|
324
|
+
* still waits for an answer to each node start, so a start of it goes to the bridge it had, which answers it with the fallback (X5 fix2 F1).
|
|
325
|
+
* X5 fix3p P5: a machine that sent nothing before close() gets a bridge made only to refuse (counted) and release at once. close() is final for
|
|
326
|
+
* this option; a new boot gets a new option (setup.js bootOption), and setup.close() closes every option of the setup.
|
|
277
327
|
* const per = bridgesPerMachine(machine => edgeBridge({vm: machine, ...})); per.onMessage(m, machine); per.busy(); per.current()
|
|
278
328
|
*/
|
|
279
329
|
export function bridgesPerMachine(make) {
|
|
280
330
|
let current = null
|
|
281
331
|
let machine = null
|
|
282
|
-
const retired = new WeakSet()
|
|
332
|
+
const retired = new WeakSet() // machines a restore replaced
|
|
333
|
+
const closedWith = new WeakMap() // machine -> the bridge it had when close() came
|
|
334
|
+
let closed = false // X5 fix3p P5: close() came; a machine this option has not seen yet is refused too
|
|
283
335
|
return {
|
|
284
336
|
current: () => current,
|
|
285
337
|
busy: () => !!current?.busy(),
|
|
286
338
|
onMessage(m, from) {
|
|
339
|
+
if (closed && !closedWith.has(from) && !retired.has(from)) {
|
|
340
|
+
// a machine that sent nothing before close(): it gets a bridge made only to count and answer the refusal, and released at once
|
|
341
|
+
const b = make(from)
|
|
342
|
+
b.close?.()
|
|
343
|
+
closedWith.set(from, b)
|
|
344
|
+
}
|
|
287
345
|
if (from !== machine) {
|
|
346
|
+
if (closedWith.has(from)) return closedWith.get(from)?.refuse?.(m, EDGE_CLOSED)
|
|
288
347
|
if (retired.has(from)) return
|
|
289
348
|
if (machine) retired.add(machine)
|
|
349
|
+
// the next machine's bridge first, then the old one ends: the site keeps a user throughout and its kept frame stays (K1)
|
|
350
|
+
const next = make(from)
|
|
290
351
|
current?.close?.()
|
|
291
352
|
machine = from
|
|
292
|
-
current =
|
|
353
|
+
current = next
|
|
293
354
|
}
|
|
294
355
|
current.onMessage(m)
|
|
295
356
|
},
|
|
357
|
+
/** K1: the current machine ended (no restore follows): its bridge ends its runs and releases the frame site. */
|
|
358
|
+
close() {
|
|
359
|
+
closed = true
|
|
360
|
+
if (machine) closedWith.set(machine, current)
|
|
361
|
+
current?.close?.()
|
|
362
|
+
current = null
|
|
363
|
+
machine = null
|
|
364
|
+
},
|
|
296
365
|
}
|
|
297
366
|
}
|