@threadedstack/wmd-web 0.1.52 → 0.1.54
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 +2 -2
- package/RELEASE.json +16 -15
- package/guest/arm64/vm.wasm +0 -0
- package/package.json +3 -3
- package/src/boot.js +207 -26
- package/src/edge/pins.gen.js +2 -2
- package/src/host/ckpt-chain.js +299 -0
- package/src/host/ckpt-file.js +35 -0
- package/src/host/ckpt-io.js +41 -4
- package/src/host/ckpt-point.js +9 -6
- package/src/host/ckpt-save.js +27 -3
- package/src/host/ckpt.js +84 -13
- package/src/host/layout.js +3 -0
- package/wmdpack.wasm +0 -0
package/README.md
CHANGED
|
@@ -102,8 +102,8 @@ The interface this host implements is in [docs/host-interface.md](docs/host-inte
|
|
|
102
102
|
- **Exit.** `proc_exit` sets the shared exit flag (the first code wins), tells the page,
|
|
103
103
|
and throws to unwind its own Worker. The page then terminates every Worker. A trap on
|
|
104
104
|
any thread ends the machine with code 4, as in the runner.
|
|
105
|
-
- **Memory.** One `WebAssembly.Memory({initial
|
|
106
|
-
`maximum` is 6144 + RAM pages + 1 GiB of slack (10,240 + 16,384 pages for
|
|
105
|
+
- **Memory.** One `WebAssembly.Memory({initial, maximum, shared: true})`, `initial` the minimum vm.wasm's
|
|
106
|
+
memory import declares (512 pages, 32 MiB, since IOS-2; 6144 before). `maximum` is 6144 (heap room) + RAM pages + 1 GiB of slack (10,240 + 16,384 pages for
|
|
107
107
|
`--ram 256`). Views over it are rebuilt whenever `memory.buffer` changes after a grow.
|
|
108
108
|
- **Output.** stdout and stderr go into a ring per fd in a SharedArrayBuffer
|
|
109
109
|
(`src/host/stdio.js`), 32 MiB each for a boot (`bootWmd({stdioRingBytes})`, a power of
|
package/RELEASE.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "wmd-web",
|
|
3
3
|
"version": "0.5.1",
|
|
4
|
-
"commit": "
|
|
4
|
+
"commit": "3807c88c08611e8ccece4ad96c9c1a755d87ef3f",
|
|
5
5
|
"previous": null,
|
|
6
6
|
"decisions": [
|
|
7
7
|
"D-388",
|
|
@@ -80,12 +80,12 @@
|
|
|
80
80
|
"D-661",
|
|
81
81
|
"D-666"
|
|
82
82
|
],
|
|
83
|
-
"vmSources": "
|
|
83
|
+
"vmSources": "2a7e60f9e7f01494c5141ec1ac9e38435b7f6ace",
|
|
84
84
|
"guest": {
|
|
85
85
|
"arch": "arm64",
|
|
86
86
|
"files": {
|
|
87
87
|
"vm.wasm": {
|
|
88
|
-
"sha256": "
|
|
88
|
+
"sha256": "7d16efadd83097e9b9188410187fb929b4ee5afbcb22cd387deebf1206b52376",
|
|
89
89
|
"bytes": 1575966
|
|
90
90
|
},
|
|
91
91
|
"Image": {
|
|
@@ -150,13 +150,13 @@
|
|
|
150
150
|
"bytes": 87706
|
|
151
151
|
},
|
|
152
152
|
"edge-site/wasm/linux.py": {
|
|
153
|
-
"sha256": "
|
|
154
|
-
"bytes":
|
|
153
|
+
"sha256": "54ee1c3be7af2c1517c1de0ae984b51adbbd77e0a71b277161e78320f50f1be2",
|
|
154
|
+
"bytes": 27628
|
|
155
155
|
}
|
|
156
156
|
}
|
|
157
157
|
},
|
|
158
158
|
"files": {
|
|
159
|
-
"README.md": "
|
|
159
|
+
"README.md": "f0f607498adc74465fdf90467313117fc3aad39a803efa4c8704605bb916a297",
|
|
160
160
|
"edge-site/own/HASHES.txt": "4d83edcb41399bb89eb7b1f89115886d739adac887bdde59a8d33e3a4602683a",
|
|
161
161
|
"edge-site/own/NOTICES.txt": "8ceca5406ee5833737bd5fa4a41d434bf5e4d26eff6da1e42c693176ee113101",
|
|
162
162
|
"edge-site/own/acorn/LICENSE": "76a876cf886ff9be2a8b5e2e86514fed06223c8c9f0c1e9ee9606e93841e00b7",
|
|
@@ -167,7 +167,7 @@
|
|
|
167
167
|
"edge-site/wasm/NOTICES.txt": "7ae1af355689c49eae0a3e1ca3ea85a7d0793100f6bd7f9dabc7916e191e0421",
|
|
168
168
|
"edge-site/wasm/edgejs.wasm": "7131008ab38d52ff31b0d3059c6e105e8a448775408981956ce7aff792bfd98b",
|
|
169
169
|
"edge-site/wasm/linux.cjs": "77bb31f2d92a36f8a76bb129187febd253ce79e1c1dc9d4bccc87474075fef3f",
|
|
170
|
-
"edge-site/wasm/linux.py": "
|
|
170
|
+
"edge-site/wasm/linux.py": "54ee1c3be7af2c1517c1de0ae984b51adbbd77e0a71b277161e78320f50f1be2",
|
|
171
171
|
"export-page/coi-sw.js": "0300e670b413cb2e0aae35843fc583546bbf6687df971ab6df41cfa3b0d494d7",
|
|
172
172
|
"export-page/index.html": "f5450c89e63601bbbbffef421f03491b231d1f143070012c1c5315d4b0059f43",
|
|
173
173
|
"export-page/run.css": "b57adf1e76553549c1f89ff157b7973409dedc21889cd3932948cd05b51adc6f",
|
|
@@ -176,11 +176,11 @@
|
|
|
176
176
|
"guest/arm64/Image-4k": "55ab90773d080416f1539ae2caac0a49bb98e2bb34ce9384849725fb8e601551",
|
|
177
177
|
"guest/arm64/features": "4dc6f2a114c7c87a67eb9f0fe53c52b6b8128bb30830a6be498432a3701587f4",
|
|
178
178
|
"guest/arm64/initramfs.cpio.gz": "ac7c0fc194b059579943c3d8ceaa0757c3e3e248231c2ad779260e97d5084cd3",
|
|
179
|
-
"guest/arm64/vm.wasm": "
|
|
179
|
+
"guest/arm64/vm.wasm": "7d16efadd83097e9b9188410187fb929b4ee5afbcb22cd387deebf1206b52376",
|
|
180
180
|
"package.json": "6de9aa9fabdb395651d39997c17e094f01a574f54a36f0af31bd3ffaae53cda1",
|
|
181
181
|
"src/base.js": "982f8e46dbb727ec542a494ebdb884ccd19a31ff4e091425b2d1fc01b0d4754a",
|
|
182
182
|
"src/blob.js": "bb2a2f0d87ce236280a7be2f246c926010dfe07f649c27da5e70d8eb5eaf7061",
|
|
183
|
-
"src/boot.js": "
|
|
183
|
+
"src/boot.js": "e61b07b71d505c7280af65598b3d82d93bfe65ef525879d89a900694c3823a30",
|
|
184
184
|
"src/build/builder.js": "c7794ec15b183213228776c8f4fb0950dec7e621f948358da7de8f90ef4f70ec",
|
|
185
185
|
"src/build/context.js": "d38097c61dbdadc4d41290c010425a4422f499aba473fa2b83f2a5c41e543571",
|
|
186
186
|
"src/build/dockerfile.js": "5957fe3d4ac8ff8b312f980ee04bd1d98ad4373a61f9a33e02f1ff1108b6ea53",
|
|
@@ -289,11 +289,12 @@
|
|
|
289
289
|
"src/host/chan-service.js": "d61afdcbe1a6929dd93a2f7e842c8b94c8d742db59359004d08ec3997b154288",
|
|
290
290
|
"src/host/chan-services.js": "e7f52931b6ef76a8b97b793d0a1d86fb35d20dbca3dd333d18cc4ded0806c9f7",
|
|
291
291
|
"src/host/chan.js": "bb9e76890b0efeee7cfbd8481b9fb4620b3b184459d96d62ff68ddcdc8a46f83",
|
|
292
|
-
"src/host/ckpt-
|
|
293
|
-
"src/host/ckpt-
|
|
294
|
-
"src/host/ckpt-
|
|
295
|
-
"src/host/ckpt-
|
|
296
|
-
"src/host/ckpt.js": "
|
|
292
|
+
"src/host/ckpt-chain.js": "c208a882da772acafe1373ea1d7e04723e26e870396d4202ef330d4eaf758596",
|
|
293
|
+
"src/host/ckpt-file.js": "f5955d730cc968d07811a31728c5c1beef8a618ec13d88dd3b5d1905e254621e",
|
|
294
|
+
"src/host/ckpt-io.js": "e2674314239bd05d8ab6fc89703ededdd26ed8e2c3e820cd3597883b66f3a2e4",
|
|
295
|
+
"src/host/ckpt-point.js": "e08441b52d65b18c91f7e14b6ab3ad347572a0ac96a6642cf8072b47dde404eb",
|
|
296
|
+
"src/host/ckpt-save.js": "7bb07f536005fb5e7d9db6a09169a5ce1e3865d337ab65ce798a111334c6aa07",
|
|
297
|
+
"src/host/ckpt.js": "b1160b5a97e535b2d9eede937af909ae9ee92edcd52a2d73c066ecaf57764ada",
|
|
297
298
|
"src/host/clock.js": "aba6af3a8b1a985ae340892222e4b482d33afe20f5c8b3a4c7403ce87d1e247c",
|
|
298
299
|
"src/host/csp-reason.js": "ecec797e31006896176ff4e2972f11e5d5df160fe0cd80071c39d7808ff922fc",
|
|
299
300
|
"src/host/ctl.js": "86066c8d3be8e6f6b05e831344cd72ebc446ced391fc8290e1c584940b8ab3e0",
|
|
@@ -314,7 +315,7 @@
|
|
|
314
315
|
"src/host/jit-hub.js": "cf3fc9f9d4e3fb50c41d6de5e2523f380d3c6c1feaf61c15d90cde89aec2f4c3",
|
|
315
316
|
"src/host/jit-snap.js": "3932f36047c9edeb7f59282d1c37fef19c8f5a9fe4bd0192fb93aa64030fe51d",
|
|
316
317
|
"src/host/jit.js": "72ef7334506fde2b3724cee93b52a987fbd6d45473b8de93d914db8a80ae9e17",
|
|
317
|
-
"src/host/layout.js": "
|
|
318
|
+
"src/host/layout.js": "c878b8da956da3ebc2391cf802869f12b3d74c131ffbcb9879536617728beeac",
|
|
318
319
|
"src/host/monitor.js": "ae1741ba35668bcc6192642246494433b175668933921634c699af5a0a69acc0",
|
|
319
320
|
"src/host/p9mount.js": "cd27abd769b19ed8b26050ddd8b6d61f81faa5a431924217dd0bf2593258d5b9",
|
|
320
321
|
"src/host/pinned-fetch.js": "873eb804604c150f6c8e488eb6c49fb8dc7a85108e80bf1a831904b9555726eb",
|
package/guest/arm64/vm.wasm
CHANGED
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@threadedstack/wmd-web",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.54",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"homepage": "https://github.com/threadedstack/wmd-releases",
|
|
6
6
|
"repository": {
|
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
},
|
|
10
10
|
"description": "Browser host for wmd's guest vm.wasm (Web Workers + shared memory + WASI preview1)",
|
|
11
11
|
"wmd": {
|
|
12
|
-
"tag": "v0.1.
|
|
13
|
-
"commit": "
|
|
12
|
+
"tag": "v0.1.54",
|
|
13
|
+
"commit": "3807c88c08611e8ccece4ad96c9c1a755d87ef3f",
|
|
14
14
|
"web": "0.5.1"
|
|
15
15
|
},
|
|
16
16
|
"type": "module",
|
package/src/boot.js
CHANGED
|
@@ -24,6 +24,7 @@ import {
|
|
|
24
24
|
CTL_CK_ATTACHES,
|
|
25
25
|
CTL_CK_GO,
|
|
26
26
|
CTL_CK_RESTORED,
|
|
27
|
+
CTL_CK_STREAM,
|
|
27
28
|
CTL_SPAWN_FAIL,
|
|
28
29
|
POOL_MAX,
|
|
29
30
|
SLOT_STATE,
|
|
@@ -48,7 +49,7 @@ import { ControlClient } from './host/ctl.js'
|
|
|
48
49
|
import { chooseTwin, eventsOf, putBackTwin, specKeysDiffering, twinForBoot } from './gowasm/boot-setup.js'
|
|
49
50
|
import { PAGE as CKPT_PAGE, requestCheckpoint } from './host/ckpt-point.js'
|
|
50
51
|
import {
|
|
51
|
-
CheckpointError, serviceErrorCode, assembleCheckpoint, bootKeyForChoice, specChoice, bootKeyOf, checkCheckpointFits, checkPacksFit, checkVmKeyFits, packDigestsOf, fdTableBytes, parseCheckpoint, restoreFdTable, resumePorts, sha256Hex, validateFdTable,
|
|
52
|
+
CheckpointError, serviceErrorCode, assembleCheckpoint, memChunksOf, bootKeyForChoice, specChoice, bootKeyOf, checkCheckpointFits, checkPacksFit, checkVmKeyFits, checkArgvFits, packDigestsOf, fdTableBytes, parseCheckpoint, restoreFdTable, resumePorts, sha256Hex, validateFdTable,
|
|
52
53
|
} from './host/ckpt.js'
|
|
53
54
|
import { captureJit, jitSnapStats, modulesOf, ownersNeedingHub, restoreStore } from './host/jit-snap.js'
|
|
54
55
|
export { CheckpointError, memoryStore, opfsStore } from './host/ckpt.js'
|
|
@@ -100,12 +101,14 @@ export async function edgeSetup(o = {}) {
|
|
|
100
101
|
|
|
101
102
|
const pythonLooks = new WeakMap() // the look at a service's layers, once per service object (a restore's text choice asks again)
|
|
102
103
|
/** X25: {path, version, ms} of the image's python found in the 9P service's layers (src/edge/python-look.js), kept per service; never throws (a layer that cannot be read: no python). */
|
|
103
|
-
async function pythonLook(A, svc, env, e = {}) {
|
|
104
|
+
async function pythonLook(A, svc, env, e = {}, once = null) {
|
|
104
105
|
if (!svc.layers || !svc.layers.length) return null
|
|
105
106
|
let p = pythonLooks.get(svc)
|
|
106
107
|
if (!p) {
|
|
108
|
+
// IOS-2: the look reads the boot's own download of each layer (layerOnce), so a layer is fetched once and held once
|
|
109
|
+
const fetchFn = e.fetchLayer || (once ? u => once.get(u).then(b => ({ arrayBuffer: async () => b })) : null)
|
|
107
110
|
p = import('./edge/python-look.js')
|
|
108
|
-
.then(m => m.lookForPython(svc.layers, env, { at: svc.at ?? 'rootfs', ...(
|
|
111
|
+
.then(m => m.lookForPython(svc.layers, env, { at: svc.at ?? 'rootfs', ...(fetchFn ? { fetchFn } : {}) }))
|
|
109
112
|
.catch(() => ({ path: '', version: '', ms: 0 }))
|
|
110
113
|
pythonLooks.set(svc, p)
|
|
111
114
|
}
|
|
@@ -147,7 +150,7 @@ export async function edgeAuto(o, counts = edgePlanCounts) {
|
|
|
147
150
|
return off('bundle/config/config.json is not JSON')
|
|
148
151
|
}
|
|
149
152
|
// X25: the image's python, found in the service's layers (gone at once with `python: false` and for an image whose layers are not given)
|
|
150
|
-
const imagePython = e.python === false ? null : await pythonLook(A, svc, facts.env, e)
|
|
153
|
+
const imagePython = e.python === false ? null : await pythonLook(A, svc, facts.env, e, o._layerOnce)
|
|
151
154
|
if (imagePython && typeof e.onLog === 'function') try { e.onLog(0, { type: 'python-look', ms: imagePython.ms, path: imagePython.path, version: imagePython.version }) } catch {} // the look's cost, for the page's own log
|
|
152
155
|
// a container that cannot use node in the frame loads no more of the edge code than the plan (the reason is counted); one that has a python the plan
|
|
153
156
|
// could take goes on without node (python only, src/edge/setup.js)
|
|
@@ -190,7 +193,7 @@ export async function edgeTextOptions(plain) {
|
|
|
190
193
|
const facts = A.containerFacts(svc.files, plain.args || [])
|
|
191
194
|
const pre = A.preplan(facts, { rt: e.rt, win: ABLE_WIN })
|
|
192
195
|
// python's mounts by the same rule (the switch `python: false` is this boot's choice, not the text's): the checkpoint's key does not depend on it
|
|
193
|
-
const look = await pythonLook(A, svc, facts.env, e)
|
|
196
|
+
const look = await pythonLook(A, svc, facts.env, e, plain._layerOnce)
|
|
194
197
|
const py = look?.path ? A.pythonPlanFor(facts, look, { ...e, python: undefined }, ABLE_WIN) : { use: false }
|
|
195
198
|
if (!pre.use && !py.use) return null
|
|
196
199
|
const files = A.addEdgeMounts(svc.files, pre.use ? pre.node : undefined, undefined, py.use ? A.pythonSpecTools(py.python) : [])
|
|
@@ -284,7 +287,79 @@ export function isOutOfMemory({ reserve = false, usedUp = false, said = false, m
|
|
|
284
287
|
if (!reserve && memoryBytes > memoryMaxBytes - OOM_MARGIN) return 'memory at its maximum'
|
|
285
288
|
return null
|
|
286
289
|
}
|
|
287
|
-
const VM_MIN_PAGES = 6144 // vm.wasm's memory import minimum (384 MiB)
|
|
290
|
+
const VM_MIN_PAGES = 6144 // vm.wasm's memory import minimum up to IOS-2 (384 MiB): the heap room the memory's maximum keeps above the RAM
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* IOS-2: where the LEB128 minimum of the module's `env`.`memory` import starts in `bytes`, and its value: {at, min}, or null (not a module, no such
|
|
294
|
+
* import). Reads only the import section's header and entries.
|
|
295
|
+
*/
|
|
296
|
+
function memoryImportOf(bytes) {
|
|
297
|
+
if (!bytes || bytes.length < 8 || bytes[0] !== 0 || bytes[1] !== 0x61 || bytes[2] !== 0x73 || bytes[3] !== 0x6d) return null
|
|
298
|
+
let i = 8
|
|
299
|
+
const u = () => {
|
|
300
|
+
let r = 0
|
|
301
|
+
let sh = 0
|
|
302
|
+
for (;;) {
|
|
303
|
+
if (i >= bytes.length) throw new RangeError('truncated')
|
|
304
|
+
const b = bytes[i++]
|
|
305
|
+
r += (b & 0x7f) * 2 ** sh
|
|
306
|
+
if (!(b & 0x80)) return r
|
|
307
|
+
sh += 7
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
const name = () => {
|
|
311
|
+
const n = u()
|
|
312
|
+
const t = new TextDecoder().decode(bytes.subarray(i, i + n))
|
|
313
|
+
i += n
|
|
314
|
+
return t
|
|
315
|
+
}
|
|
316
|
+
try {
|
|
317
|
+
while (i < bytes.length) {
|
|
318
|
+
const id = bytes[i++]
|
|
319
|
+
const size = u()
|
|
320
|
+
const end = i + size
|
|
321
|
+
if (id !== 2) {
|
|
322
|
+
i = end
|
|
323
|
+
continue
|
|
324
|
+
}
|
|
325
|
+
const n = u()
|
|
326
|
+
for (let k = 0; k < n; k++) {
|
|
327
|
+
const mod = name()
|
|
328
|
+
const field = name()
|
|
329
|
+
const kind = bytes[i++]
|
|
330
|
+
if (kind === 0) u() // function: type index
|
|
331
|
+
else if (kind === 1) {
|
|
332
|
+
i++ // table: element type, then limits
|
|
333
|
+
const f = u()
|
|
334
|
+
u()
|
|
335
|
+
if (f & 1) u()
|
|
336
|
+
} else if (kind === 2) {
|
|
337
|
+
const f = u()
|
|
338
|
+
const at = i
|
|
339
|
+
const min = u()
|
|
340
|
+
if (f & 1) u()
|
|
341
|
+
if (mod === 'env' && field === 'memory') return { at, min }
|
|
342
|
+
} else if (kind === 3) i += 2 // global: type, mutability
|
|
343
|
+
else return null
|
|
344
|
+
}
|
|
345
|
+
return null
|
|
346
|
+
}
|
|
347
|
+
} catch {
|
|
348
|
+
return null
|
|
349
|
+
}
|
|
350
|
+
return null
|
|
351
|
+
}
|
|
352
|
+
/** IOS-2: vm.wasm's declared minimum of memory 0, in 64 KiB pages (null when the bytes have no `env`.`memory` import). */
|
|
353
|
+
/**
|
|
354
|
+
* IOS-2: how many pages from 0 a restore reads to find pages the new instance's start wrote that the checkpoint had as zero: those below the
|
|
355
|
+
* memory's size when the instance was made (it could write nothing above), at most the checkpoint's. Each page read is committed by mobile
|
|
356
|
+
* WebKit, so a bound of VM_MIN_PAGES (384 MiB) cost a phone that much for a 32 MiB vm.wasm.
|
|
357
|
+
*/
|
|
358
|
+
export const restoreZeroScanPages = (memPages, instancePages) => Math.min(memPages, instancePages)
|
|
359
|
+
|
|
360
|
+
export const vmMemoryMinPages = bytes => memoryImportOf(bytes)?.min ?? null
|
|
361
|
+
/** IOS-2 (tests): the byte offset of that minimum's LEB128 in `bytes`. */
|
|
362
|
+
export const vmMemoryMinAt = bytes => memoryImportOf(bytes)?.at ?? null
|
|
288
363
|
|
|
289
364
|
const haveJspi = () => typeof WebAssembly.Suspending === 'function' && typeof WebAssembly.promising === 'function'
|
|
290
365
|
|
|
@@ -784,6 +859,33 @@ function packShared(bytes) {
|
|
|
784
859
|
return toShared(bytes)
|
|
785
860
|
}
|
|
786
861
|
|
|
862
|
+
/**
|
|
863
|
+
* IOS-2: one download per layer url for a boot. get(url) starts (once) the boot's own kind of download (shared memory, no-store) and gives its
|
|
864
|
+
* promise; take(url) hands that promise over and forgets it, so the map holds no bytes once the boot has the pack.
|
|
865
|
+
*/
|
|
866
|
+
export function layerOnce(signal, fetchFn = (url, sig) => fetchShared(url, sig, undefined, true)) {
|
|
867
|
+
const m = new Map()
|
|
868
|
+
return {
|
|
869
|
+
get(url) {
|
|
870
|
+
let p = m.get(url)
|
|
871
|
+
if (!p) {
|
|
872
|
+
p = fetchFn(url, signal)
|
|
873
|
+
p.catch(() => {})
|
|
874
|
+
m.set(url, p)
|
|
875
|
+
}
|
|
876
|
+
return p
|
|
877
|
+
},
|
|
878
|
+
take(url) {
|
|
879
|
+
const p = m.get(url) || null
|
|
880
|
+
m.delete(url)
|
|
881
|
+
return p
|
|
882
|
+
},
|
|
883
|
+
get size() {
|
|
884
|
+
return m.size
|
|
885
|
+
},
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
|
|
787
889
|
function toShared(bytes) {
|
|
788
890
|
const sab = new SharedArrayBuffer(bytes.byteLength)
|
|
789
891
|
new Uint8Array(sab).set(bytes)
|
|
@@ -906,6 +1008,8 @@ export async function bootWmd(o) {
|
|
|
906
1008
|
if (!globalThis.crossOriginIsolated) {
|
|
907
1009
|
throw new Error('page is not cross-origin isolated (needs COOP same-origin + COEP require-corp)')
|
|
908
1010
|
}
|
|
1011
|
+
// IOS-2: one download per layer url for this boot, shared by X25's python look and the boot's own packs
|
|
1012
|
+
if (!o._layerOnce) o = { ...o, _layerOnce: layerOnce(o.signal) }
|
|
909
1013
|
// X5 option A: `edge: { base }` is all a page says; the setup of node in the frame is done here (edgeAuto below)
|
|
910
1014
|
const plain0 = o // the options as the caller gave them: a restore chooses node in the frame from its checkpoint's choice (chooseEdge)
|
|
911
1015
|
let auto = null
|
|
@@ -1061,13 +1165,15 @@ async function bootMachine(o) {
|
|
|
1061
1165
|
o._assets = undefined // the handle keeps no reference of its own to the previous boot's assets
|
|
1062
1166
|
// W24: one download per file, with its bytes as they come. A file the caller passed as bytes, or one a restore reuses
|
|
1063
1167
|
// (o.assets), is reported once, done and cached.
|
|
1064
|
-
const download = (file, url, shared, extra = {}) => {
|
|
1168
|
+
const download = (file, url, shared, extra = {}, pre = null) => {
|
|
1065
1169
|
const kind = `download:${file}`
|
|
1066
1170
|
const base = { t: 'boot', stage: 'download', file, ...extra }
|
|
1067
1171
|
let finalUrl = url
|
|
1068
1172
|
const before = timingCount(url)
|
|
1069
1173
|
const ts = absMs()
|
|
1070
|
-
|
|
1174
|
+
const fetchIt = () => fetchShared(url, o.signal, (bytes, total) => be.progress(kind, { ...base, state: 'progress', bytes, total, cached: null }), shared, r => (finalUrl = r.url || url))
|
|
1175
|
+
// IOS-2: a layer the python look already downloaded (layerOnce) is that download; if it failed, the boot fetches it itself as before
|
|
1176
|
+
return (pre ? pre.catch(fetchIt) : fetchIt()).then(async buf => {
|
|
1071
1177
|
const tookMs = Math.round(absMs() - ts)
|
|
1072
1178
|
// the browser adds a response's Resource Timing entry a little after its body is read (Chromium: a small file was
|
|
1073
1179
|
// read before its entry existed): wait for it, at most 200 ms
|
|
@@ -1109,7 +1215,7 @@ async function bootMachine(o) {
|
|
|
1109
1215
|
? Promise.resolve(A.chanLayers.map((ls, i) => ls.map((b, j) => given(`pack:${packIds[i][j]}`, b, { port: chanSvcs[i].port }))))
|
|
1110
1216
|
: Promise.all(
|
|
1111
1217
|
chanSvcs.map((svc, i) =>
|
|
1112
|
-
Promise.all((svc.layers || []).map((l, j) => (typeof l === 'string' ? download(`pack:${packIds[i][j]}`, l, true, { port: svc.port }) : Promise.resolve(given(`pack:${packIds[i][j]}`, packShared(l), { port: svc.port }))))),
|
|
1218
|
+
Promise.all((svc.layers || []).map((l, j) => (typeof l === 'string' ? download(`pack:${packIds[i][j]}`, l, true, { port: svc.port }, o._layerOnce?.take(l)) : Promise.resolve(given(`pack:${packIds[i][j]}`, packShared(l), { port: svc.port }))))),
|
|
1113
1219
|
),
|
|
1114
1220
|
).then(downloaded)
|
|
1115
1221
|
layersP.catch(() => {})
|
|
@@ -1163,6 +1269,7 @@ async function bootMachine(o) {
|
|
|
1163
1269
|
try {
|
|
1164
1270
|
const h = await raceAbort(lazyIn.header)
|
|
1165
1271
|
checkVmKeyFits(h, vmKey)
|
|
1272
|
+
checkArgvFits(h, argv) // IOS-2: another command line (a 1024 MiB base under a 256 MiB request) is refused before its body is read
|
|
1166
1273
|
settleLayout(chooseLayout(o.args, o, h)) // X24 default: the base snapshot's own layout
|
|
1167
1274
|
// 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
|
|
1168
1275
|
// 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)
|
|
@@ -1293,7 +1400,10 @@ async function bootMachine(o) {
|
|
|
1293
1400
|
|
|
1294
1401
|
// 2. Shared memory and control block.
|
|
1295
1402
|
const tMem = absMs()
|
|
1296
|
-
|
|
1403
|
+
// IOS-2: memory 0 starts at vm.wasm's own declared minimum, and its heap grows as it is used. Mobile WebKit counts every byte of the initial
|
|
1404
|
+
// memory at once (D-516); VM_MIN_PAGES stays the heap room of the maximum. A vm.wasm that declares more (or bytes that cannot be read) gets that.
|
|
1405
|
+
const declaredMin = vmMemoryMinPages(new Uint8Array(vmBytes))
|
|
1406
|
+
let memory = new WebAssembly.Memory({ initial: declaredMin ?? VM_MIN_PAGES, maximum, shared: true })
|
|
1297
1407
|
const memoryInitialBytes = memory.buffer.byteLength
|
|
1298
1408
|
const ctlSab = createControl()
|
|
1299
1409
|
const ctl = new Int32Array(ctlSab)
|
|
@@ -1303,9 +1413,9 @@ async function bootMachine(o) {
|
|
|
1303
1413
|
restoreFdTable(ctl, restoreIn.ctl, files.length)
|
|
1304
1414
|
ckptT.pagesRestored = restoreIn.index.length
|
|
1305
1415
|
}
|
|
1306
|
-
function restoreMemory() {
|
|
1416
|
+
async function restoreMemory() {
|
|
1307
1417
|
try {
|
|
1308
|
-
restoreMemoryNow()
|
|
1418
|
+
await restoreMemoryNow()
|
|
1309
1419
|
// the snapshot restored: its cache copy may be committed now (not before: a snapshot that fails to restore must not stay cached)
|
|
1310
1420
|
const lazy = baseLazy
|
|
1311
1421
|
baseLazy = null
|
|
@@ -1323,18 +1433,26 @@ async function bootMachine(o) {
|
|
|
1323
1433
|
finish(4, `restore failed: ${err && err.message ? err.message : err}`)
|
|
1324
1434
|
}
|
|
1325
1435
|
}
|
|
1326
|
-
function restoreMemoryNow() {
|
|
1436
|
+
async function restoreMemoryNow() {
|
|
1327
1437
|
const tm = absMs()
|
|
1328
|
-
const have = memory.buffer.byteLength / CKPT_PAGE
|
|
1438
|
+
const have = memory.buffer.byteLength / CKPT_PAGE // the size the instance made: its start function wrote nothing above it
|
|
1329
1439
|
if (restoreIn.header.memPages > have) memory.grow(restoreIn.header.memPages - have)
|
|
1330
|
-
const u8 = new Uint8Array(memory.buffer)
|
|
1331
1440
|
const kept = new Uint8Array(restoreIn.header.memPages)
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1441
|
+
if (restoreIn.into) {
|
|
1442
|
+
// IOS-2: a store's lazy load: its I/O Worker reads the memory section straight into this memory (the page never holds it)
|
|
1443
|
+
const r = await restoreIn.into(memory, restoreIn.index)
|
|
1444
|
+
if (r.pages !== restoreIn.index.length) throw new Error(`the store wrote ${r.pages} of the checkpoint's ${restoreIn.index.length} memory pages`)
|
|
1445
|
+
for (const p of restoreIn.index) kept[p] = 1
|
|
1446
|
+
ckptT.memoryInto = true
|
|
1447
|
+
} else {
|
|
1448
|
+
const u8 = new Uint8Array(memory.buffer)
|
|
1449
|
+
let k = 0
|
|
1450
|
+
for (const c of restoreIn.memChunks) {
|
|
1451
|
+
for (let off = 0; off < c.length; off += CKPT_PAGE) {
|
|
1452
|
+
const p = restoreIn.index[k++]
|
|
1453
|
+
u8.set(c.subarray(off, off + CKPT_PAGE), p * CKPT_PAGE)
|
|
1454
|
+
kept[p] = 1
|
|
1455
|
+
}
|
|
1338
1456
|
}
|
|
1339
1457
|
}
|
|
1340
1458
|
// the flat layout: the guest's RAM, into its own memory (a fresh one: all zero but for these pages)
|
|
@@ -1359,7 +1477,7 @@ async function bootMachine(o) {
|
|
|
1359
1477
|
}
|
|
1360
1478
|
// pages the instance's start function wrote that were zero at the checkpoint (the runner's zero_absent): the static region
|
|
1361
1479
|
let zeroed = 0
|
|
1362
|
-
const w = new Int32Array(memory.buffer, 0,
|
|
1480
|
+
const w = new Int32Array(memory.buffer, 0, restoreZeroScanPages(restoreIn.header.memPages, have) * (CKPT_PAGE / 4))
|
|
1363
1481
|
for (let p = 0; p * (CKPT_PAGE / 4) < w.length; p++) {
|
|
1364
1482
|
if (kept[p]) continue
|
|
1365
1483
|
const lo = p * (CKPT_PAGE / 4)
|
|
@@ -1389,6 +1507,7 @@ async function bootMachine(o) {
|
|
|
1389
1507
|
}
|
|
1390
1508
|
be.now('restore', { t: 'boot', stage: 'restore', state: 'done', used: true, bytes: baseBytes, total: baseTotal, source: baseSource, tookMs: Math.round(ckptT.pagesWrittenAt) })
|
|
1391
1509
|
restoreIn.memChunks = null
|
|
1510
|
+
restoreIn.into = null
|
|
1392
1511
|
restoreIn.index = null
|
|
1393
1512
|
restoreIn.ram = null
|
|
1394
1513
|
restoreIn.jit = null
|
|
@@ -2293,6 +2412,7 @@ async function bootMachine(o) {
|
|
|
2293
2412
|
const c = ck
|
|
2294
2413
|
if (!c) return
|
|
2295
2414
|
ck = null
|
|
2415
|
+
Atomics.store(ctl, CTL_CK_STREAM, 0)
|
|
2296
2416
|
clearTimeout(c.timer)
|
|
2297
2417
|
clearInterval(c.poll)
|
|
2298
2418
|
if (c.atPoint && !c.went) {
|
|
@@ -2368,6 +2488,15 @@ async function bootMachine(o) {
|
|
|
2368
2488
|
function ckptMaybeGo() {
|
|
2369
2489
|
const c = ck
|
|
2370
2490
|
if (!c || c.went || !c.mem || !c.svc || !c.jitDone) return
|
|
2491
|
+
if (c.stream && !c.streamDone) {
|
|
2492
|
+
if (c.saving) return
|
|
2493
|
+
if (!c.mem.streamed) return ckptFail(new CheckpointError('memory', 'the guest copied its memory although the checkpoint was to be saved straight to the store'))
|
|
2494
|
+
c.saving = true
|
|
2495
|
+
clearTimeout(c.timer) // the guest is at its point: the save's own time is vCPU 0's to bound (goTimeoutMs)
|
|
2496
|
+
ckptStreamSave(c)
|
|
2497
|
+
return
|
|
2498
|
+
}
|
|
2499
|
+
Atomics.store(ctl, CTL_CK_STREAM, 0)
|
|
2371
2500
|
c.went = true
|
|
2372
2501
|
c.goAt = gnow()
|
|
2373
2502
|
Atomics.store(ctl, CTL_CK_GO, 1)
|
|
@@ -2412,7 +2541,25 @@ async function bootMachine(o) {
|
|
|
2412
2541
|
}
|
|
2413
2542
|
|
|
2414
2543
|
function ckptAssemble(c, names) {
|
|
2544
|
+
// IOS-2: a checkpoint saved straight to a store was built and written before the guest went on: its answer is ready, with the resume's times
|
|
2545
|
+
if (c.savedResult) {
|
|
2546
|
+
const st = c.savedResult.header.stats
|
|
2547
|
+
if (st) {
|
|
2548
|
+
st.resumeMs = c.resumeAt - c.goAt
|
|
2549
|
+
st.savePauseMs = c.goAt - c.pointAt
|
|
2550
|
+
}
|
|
2551
|
+
return c.resolve(c.savedResult)
|
|
2552
|
+
}
|
|
2415
2553
|
try {
|
|
2554
|
+
c.resolve(ckptBuild(c, names))
|
|
2555
|
+
} catch (err) {
|
|
2556
|
+
c.reject(err)
|
|
2557
|
+
}
|
|
2558
|
+
}
|
|
2559
|
+
|
|
2560
|
+
/** The checkpoint of a point whose parts are all in (c.mem, c.svc, c.jitSnap, c.ctlBytes): {header, sections}. Throws. */
|
|
2561
|
+
function ckptBuild(c, names) {
|
|
2562
|
+
{
|
|
2416
2563
|
const t = absMs()
|
|
2417
2564
|
const stats = {
|
|
2418
2565
|
stopLatencyMs: c.pointAt - c.t0, // request to the vCPUs stopped and the point entered (includes the guest's world stop, share drain and service stop)
|
|
@@ -2455,9 +2602,33 @@ async function bootMachine(o) {
|
|
|
2455
2602
|
ckpt.header.stats.assembleMs = absMs() - t
|
|
2456
2603
|
ckpt.header.svcStats = Object.fromEntries(Object.entries(c.svc).map(([port, d]) => [port, { bytes: d.bytes, fids: d.fids }]))
|
|
2457
2604
|
if (c.jitSnap) ckpt.header.jitStats = jitSnapStats(c.jitSnap)
|
|
2458
|
-
|
|
2605
|
+
return ckpt
|
|
2606
|
+
}
|
|
2607
|
+
}
|
|
2608
|
+
|
|
2609
|
+
/**
|
|
2610
|
+
* IOS-2: vm.checkpoint({save}) once every part is in and the guest is still at its point: the memory sections are lazy chunks over the frozen
|
|
2611
|
+
* memory (vCPU 0 found the non-zero pages and copied none), the store's Worker pulls them one at a time through its one reused buffer, and only
|
|
2612
|
+
* then does the guest go on. The page never holds a copy of the guest's memory.
|
|
2613
|
+
*/
|
|
2614
|
+
async function ckptStreamSave(c) {
|
|
2615
|
+
try {
|
|
2616
|
+
const names = await netNameList()
|
|
2617
|
+
if (ck !== c) return
|
|
2618
|
+
c.goAt = c.resumeAt = gnow() // provisional: the header is written before the guest goes on
|
|
2619
|
+
c.mem.chunks = memChunksOf(memory, c.mem.index)
|
|
2620
|
+
if (c.mem.ram) c.mem.ram.chunks = memChunksOf(ramMem, c.mem.ram.index)
|
|
2621
|
+
const ckpt = ckptBuild(c, names)
|
|
2622
|
+
ckpt.header.stats.streamed = true
|
|
2623
|
+
// IOS-2 parent: a diff over that checkpoint, made by the store's Worker from the frozen memory itself
|
|
2624
|
+
if (c.stream.parent && c.mem.ram) throw new CheckpointError('malformed', 'a diff checkpoint (save.parent) needs the RAM in memory 0; this machine keeps it in a memory of its own')
|
|
2625
|
+
const saved = await c.stream.store.save(c.stream.name, ckpt, c.stream.parent ? { parent: c.stream.parent, memory, index: c.mem.index } : undefined)
|
|
2626
|
+
if (ck !== c) return
|
|
2627
|
+
c.savedResult = { header: ckpt.header, saved, streamed: true }
|
|
2628
|
+
c.streamDone = true
|
|
2629
|
+
ckptMaybeGo()
|
|
2459
2630
|
} catch (err) {
|
|
2460
|
-
|
|
2631
|
+
ckptFail(err instanceof CheckpointError ? err : new CheckpointError('io', `saving the checkpoint failed: ${(err && err.message) || err}`))
|
|
2461
2632
|
}
|
|
2462
2633
|
}
|
|
2463
2634
|
|
|
@@ -2467,14 +2638,24 @@ async function bootMachine(o) {
|
|
|
2467
2638
|
* times. It stays usable (restore it again as often as wanted) until the caller drops it; to survive a reload save
|
|
2468
2639
|
* it with a store (opfsStore().save(name, ckpt)).
|
|
2469
2640
|
*/
|
|
2470
|
-
function checkpoint({ label = '', timeoutMs = 60_000 } = {}) {
|
|
2641
|
+
function checkpoint({ label = '', timeoutMs = 60_000, save = null } = {}) {
|
|
2642
|
+
// IOS-2: save {store, name}: the checkpoint goes straight to the store and the answer is {header, saved, streamed}, no sections. With an
|
|
2643
|
+
// OPFS store the page never holds the guest's memory (see ckptStreamSave); with another store it is taken in memory and saved, as before
|
|
2644
|
+
if (save && (!save.store || typeof save.store.save !== 'function' || !save.name)) return Promise.reject(new TypeError('checkpoint({save}): save is {store, name[, parent]}'))
|
|
2645
|
+
// IOS-2 save.parent: only the pages that changed since that checkpoint are written (host/ckpt-chain.js); a restore of this one applies the chain
|
|
2646
|
+
if (save?.parent !== undefined && (typeof save.parent !== 'string' || !save.parent)) return Promise.reject(new TypeError('checkpoint({save}): save.parent is the name of a checkpoint in the same store'))
|
|
2647
|
+
if (save?.parent && save.store.kind !== 'opfs') return Promise.reject(new TypeError('checkpoint({save: {parent}}): a diff checkpoint needs an OPFS store (opfsStore())'))
|
|
2648
|
+
if (save && save.store.kind !== 'opfs') {
|
|
2649
|
+
return checkpoint({ label, timeoutMs }).then(async ckpt => ({ header: ckpt.header, saved: await save.store.save(save.name, ckpt), streamed: false }))
|
|
2650
|
+
}
|
|
2471
2651
|
if (!ckptOn) return Promise.reject(new Error('this machine was booted without checkpoint support: bootWmd({checkpoint: true})'))
|
|
2472
2652
|
if (restoring) return Promise.reject(new CheckpointError('busy', 'a restore is running: this machine is about to end, and a checkpoint taken now would be lost'))
|
|
2473
2653
|
if (done || chanDied) return Promise.reject(new Error('the machine has ended'))
|
|
2474
2654
|
if (ck) return Promise.reject(new Error('a checkpoint is already being taken'))
|
|
2475
2655
|
if (o.edge?.busy?.()) return Promise.reject(new CheckpointError('busy', 'node runs outside the guest (page switch edge=1): its files and processes are not in a checkpoint; take it when no such program runs'))
|
|
2476
2656
|
return new Promise((resolve, reject) => {
|
|
2477
|
-
const c = (ck = { label, t0: gnow(), resolve, reject, attachesBefore: Atomics.load(ctl, CTL_CK_ATTACHES), timer: null })
|
|
2657
|
+
const c = (ck = { label, t0: gnow(), resolve, reject, attachesBefore: Atomics.load(ctl, CTL_CK_ATTACHES), timer: null, stream: save })
|
|
2658
|
+
Atomics.store(ctl, CTL_CK_STREAM, save ? 1 : 0)
|
|
2478
2659
|
c.timer = setTimeout(() => ckptFail(new CheckpointError('timeout', `the guest did not reach its checkpoint point in ${timeoutMs} ms`)), timeoutMs)
|
|
2479
2660
|
if (!requestCheckpoint(memory, ctl)) ckptFail(new CheckpointError('not-ready', 'the guest has not started its checkpoint thread yet (it does that once the kernel has booted); try again after the control session is up'))
|
|
2480
2661
|
})
|
package/src/edge/pins.gen.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// The files of node in the sandboxed frame: the path under a source (the option edge: { sources } of bootWmd), the role the frame gives the file, its
|
|
3
3
|
// sha256 and its size. The page accepts a file only when it has exactly this sha256 and size. The notice files travel with the rest.
|
|
4
4
|
// EDGE_PACKAGE is the package that holds these files, for the {name} {version} {file} of a registry source's url (null: none named).
|
|
5
|
-
export const EDGE_PACKAGE = { name: '@threadedstack/wmd-node', version: '0.1.
|
|
5
|
+
export const EDGE_PACKAGE = { name: '@threadedstack/wmd-node', version: '0.1.54' }
|
|
6
6
|
export const EDGE_PINS = [
|
|
7
7
|
{ path: 'wmd_browser_bg.wasm', role: 'wasm', sha256: '1e3db7f2c5f4be0ee44e5f2c0205cf8ca11f906d9addd5512915fad4821661c2', size: 6334959 },
|
|
8
8
|
{ path: 'wmd_browser.js', role: 'glue', sha256: 'b389b072096881ba39b22cd705d3a230af02acc5409c61fb4f997d1081c4df6f', size: 75647 },
|
|
@@ -13,5 +13,5 @@ export const EDGE_PINS = [
|
|
|
13
13
|
{ path: 'edgejs.wasm', role: 'edgejs', sha256: '7131008ab38d52ff31b0d3059c6e105e8a448775408981956ce7aff792bfd98b', size: 59169054 },
|
|
14
14
|
{ path: 'edgejs.NOTICES.txt', role: 'notice', sha256: '7ae1af355689c49eae0a3e1ca3ea85a7d0793100f6bd7f9dabc7916e191e0421', size: 363824 },
|
|
15
15
|
{ path: 'linux.cjs', role: 'linux', sha256: '77bb31f2d92a36f8a76bb129187febd253ce79e1c1dc9d4bccc87474075fef3f', size: 87706 },
|
|
16
|
-
{ path: 'linux.py', role: 'linuxpy', sha256: '
|
|
16
|
+
{ path: 'linux.py', role: 'linuxpy', sha256: '54ee1c3be7af2c1517c1de0ae984b51adbbd77e0a71b277161e78320f50f1be2', size: 27628 },
|
|
17
17
|
]
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
// IOS-2: diff checkpoints. A checkpoint saved with a parent holds only the memory pages that changed since that parent
|
|
2
|
+
// (its own memory image, resolved through the parent's chain), and the pages that were non-zero there and are zero now;
|
|
3
|
+
// every other section is whole. header.parent = {name, version} names the file it builds on, and so on down to a full
|
|
4
|
+
// checkpoint. Sections of a diff: 'mem-index' (the changed pages, increasing), 'mem' (their bytes), 'mem-zero' (pages
|
|
5
|
+
// now zero, increasing). A full checkpoint has no 'mem-zero' and no parent.
|
|
6
|
+
//
|
|
7
|
+
// The save compares the frozen machine's memory with the parent chain's pages straight from the files, and writes the
|
|
8
|
+
// changed pages from the memory through one scratch buffer; a restore applies the chain oldest first. Both run in the
|
|
9
|
+
// store's I/O Worker (ckpt-io.js), over a "dir" as saveVersioned takes it (ckpt-file.js).
|
|
10
|
+
import { CheckpointError, concat, fileOf, readHeader, readSection, readSectionInto, saveVersioned, versionsOf } from './ckpt-file.js'
|
|
11
|
+
|
|
12
|
+
export const MAX_CHAIN = 64
|
|
13
|
+
const ALIGN = 8
|
|
14
|
+
const pad = n => (ALIGN - (n % ALIGN)) % ALIGN
|
|
15
|
+
const u32 = b => new Uint32Array(b.buffer.slice(b.byteOffset, b.byteOffset + b.length))
|
|
16
|
+
|
|
17
|
+
async function openOne(dir, name, version) {
|
|
18
|
+
if (version === undefined || version === null) {
|
|
19
|
+
const vs = versionsOf(await dir.names(), name)
|
|
20
|
+
for (const v of vs.reverse()) {
|
|
21
|
+
const h = await dir.open(fileOf(name, v), false)
|
|
22
|
+
try {
|
|
23
|
+
return { h, header: readHeader(h), version: v }
|
|
24
|
+
} catch (e) {
|
|
25
|
+
h.close()
|
|
26
|
+
if (!(e instanceof CheckpointError) || !['incomplete', 'truncated'].includes(e.code)) throw e
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
throw new CheckpointError('missing', `no checkpoint named ${JSON.stringify(name)} in this browser's storage`)
|
|
30
|
+
}
|
|
31
|
+
let h
|
|
32
|
+
try {
|
|
33
|
+
h = await dir.open(fileOf(name, version), false)
|
|
34
|
+
} catch (e) {
|
|
35
|
+
if (e instanceof CheckpointError && e.code === 'missing') throw new CheckpointError('missing', `checkpoint ${JSON.stringify(name)} version ${version}, which a diff checkpoint builds on, is gone`)
|
|
36
|
+
throw e
|
|
37
|
+
}
|
|
38
|
+
try {
|
|
39
|
+
return { h, header: readHeader(h), version }
|
|
40
|
+
} catch (e) {
|
|
41
|
+
h.close()
|
|
42
|
+
throw e
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Where each page of a link's 'mem' section lies in its file (page k at offs[k]). */
|
|
47
|
+
function pageOffsets(header, count, page) {
|
|
48
|
+
const s = header.sections.find(x => x.name === 'mem')
|
|
49
|
+
if (!s) throw new CheckpointError('malformed', 'checkpoint has no section mem')
|
|
50
|
+
const offs = new Float64Array(count)
|
|
51
|
+
let off = s.off
|
|
52
|
+
let k = 0
|
|
53
|
+
for (const c of s.chunks) {
|
|
54
|
+
if (c.len % page) throw new CheckpointError('malformed', `a memory chunk is ${c.len} bytes, not whole ${page}-byte pages`)
|
|
55
|
+
for (let at = 0; at < c.len; at += page) {
|
|
56
|
+
if (k >= count) throw new CheckpointError('malformed', 'the memory section holds more pages than its index')
|
|
57
|
+
offs[k++] = off + at
|
|
58
|
+
}
|
|
59
|
+
off += c.len + pad(off + c.len)
|
|
60
|
+
}
|
|
61
|
+
if (k !== count) throw new CheckpointError('malformed', `the memory section holds ${k} pages for an index of ${count}`)
|
|
62
|
+
return offs
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The chain that ends at `name` (its newest valid version, or `version`), oldest first: [{name, version, h, header,
|
|
67
|
+
* index, zero, offs}]. The handles stay open until closeChain.
|
|
68
|
+
*/
|
|
69
|
+
export async function openChain(dir, name, { version, page = 65536 } = {}) {
|
|
70
|
+
const links = []
|
|
71
|
+
try {
|
|
72
|
+
let ref = { name, version }
|
|
73
|
+
for (;;) {
|
|
74
|
+
if (links.length >= MAX_CHAIN) throw new CheckpointError('malformed', `the chain of diff checkpoints under ${JSON.stringify(name)} is longer than ${MAX_CHAIN} (or loops)`)
|
|
75
|
+
const one = await openOne(dir, ref.name, ref.version)
|
|
76
|
+
const link = { name: ref.name, version: one.version, h: one.h, header: one.header }
|
|
77
|
+
links.unshift(link)
|
|
78
|
+
link.index = u32(concat(await readSection(one.h, one.header, 'mem-index')))
|
|
79
|
+
link.zero = one.header.sections.some(s => s.name === 'mem-zero') ? u32(concat(await readSection(one.h, one.header, 'mem-zero'))) : new Uint32Array(0)
|
|
80
|
+
link.offs = pageOffsets(one.header, link.index.length, page)
|
|
81
|
+
const p = one.header.parent
|
|
82
|
+
if (!p) break
|
|
83
|
+
if (typeof p.name !== 'string' || !Number.isInteger(p.version)) throw new CheckpointError('malformed', `checkpoint ${JSON.stringify(ref.name)} names a parent that is not {name, version}`)
|
|
84
|
+
ref = { name: p.name, version: p.version }
|
|
85
|
+
}
|
|
86
|
+
const head = links.at(-1).header
|
|
87
|
+
for (const l of links) {
|
|
88
|
+
if (l.header.vmKey !== head.vmKey || l.header.bootKey !== head.bootKey) throw new CheckpointError('stale', `diff checkpoint ${JSON.stringify(name)} builds on ${JSON.stringify(l.name)}, which another vm.wasm or boot took`)
|
|
89
|
+
}
|
|
90
|
+
return links
|
|
91
|
+
} catch (e) {
|
|
92
|
+
closeChain(links)
|
|
93
|
+
throw e
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function closeChain(links) {
|
|
98
|
+
for (const l of links || []) {
|
|
99
|
+
try {
|
|
100
|
+
l.h.close()
|
|
101
|
+
} catch {}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The memory image the chain makes: for page p, src[p] is the link that holds it (-1: zero) and pos[p] its place there; index lists the non-zero pages. */
|
|
106
|
+
export function resolveChain(links) {
|
|
107
|
+
const pages = links.reduce((m, l) => Math.max(m, l.header.memPages || 0, l.index.length ? l.index[l.index.length - 1] + 1 : 0, l.zero.length ? l.zero[l.zero.length - 1] + 1 : 0), 0)
|
|
108
|
+
const src = new Int32Array(pages).fill(-1)
|
|
109
|
+
const pos = new Int32Array(pages)
|
|
110
|
+
links.forEach((l, li) => {
|
|
111
|
+
for (const z of l.zero) src[z] = -1
|
|
112
|
+
for (let k = 0; k < l.index.length; k++) {
|
|
113
|
+
src[l.index[k]] = li
|
|
114
|
+
pos[l.index[k]] = k
|
|
115
|
+
}
|
|
116
|
+
})
|
|
117
|
+
let n = 0
|
|
118
|
+
for (let p = 0; p < pages; p++) if (src[p] >= 0) n++
|
|
119
|
+
const index = new Uint32Array(n)
|
|
120
|
+
for (let p = 0, j = 0; p < pages; p++) if (src[p] >= 0) index[j++] = p
|
|
121
|
+
return { src, pos, index }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The pages of `mem` (a view of the frozen memory) listed non-zero in `index` that differ from the chain's image, and the
|
|
126
|
+
* pages the image holds that are zero now. Each page of the image that is compared is read from its file (no copy of the
|
|
127
|
+
* image is made). Returns {changed, zero} (increasing Uint32Arrays).
|
|
128
|
+
*/
|
|
129
|
+
export function diffAgainst(links, res, mem, index, page = 65536) {
|
|
130
|
+
const scratch = new Uint8Array(page)
|
|
131
|
+
const a32 = new Uint32Array(scratch.buffer)
|
|
132
|
+
const changed = []
|
|
133
|
+
for (let k = 0; k < index.length; k++) {
|
|
134
|
+
const p = index[k]
|
|
135
|
+
const li = p < res.src.length ? res.src[p] : -1
|
|
136
|
+
if (li < 0) {
|
|
137
|
+
changed.push(p)
|
|
138
|
+
continue
|
|
139
|
+
}
|
|
140
|
+
const l = links[li]
|
|
141
|
+
const at = l.offs[res.pos[p]]
|
|
142
|
+
let got = 0
|
|
143
|
+
while (got < page) {
|
|
144
|
+
const n = l.h.read(scratch.subarray(got), { at: at + got })
|
|
145
|
+
if (!(n > 0)) break
|
|
146
|
+
got += n
|
|
147
|
+
}
|
|
148
|
+
if (got !== page) throw new CheckpointError('truncated', `checkpoint ${JSON.stringify(l.name)} is cut short at ${at}`)
|
|
149
|
+
const b32 = new Uint32Array(mem.buffer, mem.byteOffset + p * page, page / 4)
|
|
150
|
+
let same = true
|
|
151
|
+
for (let i = 0; i < a32.length; i++) {
|
|
152
|
+
if (a32[i] !== b32[i]) {
|
|
153
|
+
same = false
|
|
154
|
+
break
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (!same) changed.push(p)
|
|
158
|
+
}
|
|
159
|
+
const zero = []
|
|
160
|
+
const now = new Uint8Array(res.src.length)
|
|
161
|
+
for (const p of index) if (p < now.length) now[p] = 1
|
|
162
|
+
for (const p of res.index) if (!now[p]) zero.push(p)
|
|
163
|
+
return { changed: Uint32Array.from(changed), zero: Uint32Array.from(zero) }
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* The memory sections of a diff: 'mem-index', 'mem' (chunks of at most chunkPages pages, each copied from `mem` into one
|
|
168
|
+
* scratch buffer when the writer asks for it), 'mem-zero'.
|
|
169
|
+
*/
|
|
170
|
+
export function diffSections(mem, changed, zero, page = 65536, chunkPages = 128) {
|
|
171
|
+
const scratch = new Uint8Array(Math.min(chunkPages, Math.max(1, changed.length)) * page)
|
|
172
|
+
const chunks = []
|
|
173
|
+
for (let at = 0; at < changed.length; at += chunkPages) {
|
|
174
|
+
const m = Math.min(chunkPages, changed.length - at)
|
|
175
|
+
const f = () => {
|
|
176
|
+
const out = scratch.subarray(0, m * page)
|
|
177
|
+
for (let j = 0; j < m; j++) out.set(new Uint8Array(mem.buffer, mem.byteOffset + changed[at + j] * page, page), j * page)
|
|
178
|
+
return out
|
|
179
|
+
}
|
|
180
|
+
f.size = m * page
|
|
181
|
+
Object.defineProperty(f, 'length', { value: m * page })
|
|
182
|
+
chunks.push(f)
|
|
183
|
+
}
|
|
184
|
+
const bytesOf = a => new Uint8Array(a.buffer, a.byteOffset, a.byteLength)
|
|
185
|
+
return [
|
|
186
|
+
{ name: 'mem-index', chunks: [bytesOf(changed)] },
|
|
187
|
+
{ name: 'mem', chunks },
|
|
188
|
+
{ name: 'mem-zero', chunks: [bytesOf(zero)] },
|
|
189
|
+
]
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* A restore of a chain: each link's pages into `dest` (a view of the machine's memory), oldest first, its zero pages
|
|
194
|
+
* cleared after. {pages}: the non-zero pages of the image (what a restore of one full checkpoint of it writes).
|
|
195
|
+
*/
|
|
196
|
+
export async function chainInto(links, dest, { verify = true, page = 65536 } = {}) {
|
|
197
|
+
let written = 0
|
|
198
|
+
let scratchBytes = 0
|
|
199
|
+
for (const l of links) {
|
|
200
|
+
const r = await readSectionInto(l.h, l.header, 'mem', l.index, dest, { verify, page })
|
|
201
|
+
written += r.pages
|
|
202
|
+
scratchBytes = Math.max(scratchBytes, r.scratchBytes)
|
|
203
|
+
for (const z of l.zero) dest.fill(0, z * page, (z + 1) * page)
|
|
204
|
+
}
|
|
205
|
+
return { pages: resolveChain(links).index.length, written, scratchBytes, links: links.length }
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const MEM_SECTIONS = ['mem-index', 'mem', 'mem-zero']
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Saves `name` as a diff over `parent` (a checkpoint in the same dir, its newest version): `header` and `sections` are the
|
|
212
|
+
* checkpoint's own (its memory sections are replaced), `mem` a view of the frozen memory, `index` its non-zero pages.
|
|
213
|
+
* Resolves with saveVersioned's result plus {changed, zero, links}.
|
|
214
|
+
*/
|
|
215
|
+
export async function saveDiff(dir, name, { parent, header, sections, mem, index, page = 65536, chunkPages = 128, o = {} }) {
|
|
216
|
+
if (typeof parent !== 'string' || !parent) throw new CheckpointError('malformed', 'a diff save names its parent checkpoint')
|
|
217
|
+
if (parent === name) throw new CheckpointError('malformed', `checkpoint ${JSON.stringify(name)} cannot be its own parent: save the diff under another name (a new version would remove the one it builds on)`)
|
|
218
|
+
const links = await openChain(dir, parent, { page })
|
|
219
|
+
let changed, zero, head
|
|
220
|
+
try {
|
|
221
|
+
head = links.at(-1)
|
|
222
|
+
if (head.header.vmKey !== header.vmKey || head.header.bootKey !== header.bootKey) {
|
|
223
|
+
throw new CheckpointError('stale', `checkpoint ${JSON.stringify(parent)} was taken by another vm.wasm or boot than this machine: a diff over it cannot be restored`)
|
|
224
|
+
}
|
|
225
|
+
;({ changed, zero } = diffAgainst(links, resolveChain(links), mem, index, page))
|
|
226
|
+
} finally {
|
|
227
|
+
closeChain(links)
|
|
228
|
+
}
|
|
229
|
+
const memSecs = diffSections(mem, changed, zero, page, chunkPages)
|
|
230
|
+
const out = []
|
|
231
|
+
for (const s of sections) {
|
|
232
|
+
if (s.name === 'mem-index') out.push(memSecs[0])
|
|
233
|
+
else if (s.name === 'mem') out.push(memSecs[1], memSecs[2])
|
|
234
|
+
else if (s.name !== 'mem-zero') out.push(s)
|
|
235
|
+
}
|
|
236
|
+
const size = s => s.chunks.reduce((n, c) => n + c.length, 0)
|
|
237
|
+
const hdr = { ...header, parent: { name: parent, version: head.version }, diff: { changed: changed.length, zero: zero.length, links: links.length } }
|
|
238
|
+
hdr.sizes = Object.fromEntries(out.map(s => [s.name, size(s)]))
|
|
239
|
+
hdr.bytes = Object.values(hdr.sizes).reduce((a, b) => a + b, 0)
|
|
240
|
+
const r = await saveVersioned(dir, name, hdr, out, o)
|
|
241
|
+
return { ...r, changed, zero, links: links.length }
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Loads `name` (its newest version, or `version`) through its chain: the newest link's sections, with the memory image
|
|
246
|
+
* the chain makes ('mem-index': its non-zero pages). memory 'lazy': the 'mem' chunk is {lazy, length} and into(memory)
|
|
247
|
+
* applies the chain straight into the memory; 'copy': the image in hand, compact.
|
|
248
|
+
*/
|
|
249
|
+
export async function loadChain(dir, name, { memory = 'lazy', verify = true, page = 65536, version } = {}) {
|
|
250
|
+
const links = await openChain(dir, name, { version, page })
|
|
251
|
+
try {
|
|
252
|
+
const head = links.at(-1)
|
|
253
|
+
const res = resolveChain(links)
|
|
254
|
+
const sections = []
|
|
255
|
+
for (const s of head.header.sections) {
|
|
256
|
+
if (s.name === 'mem-zero') continue
|
|
257
|
+
if (s.name === 'mem-index') sections.push({ name: s.name, chunks: [new Uint8Array(res.index.buffer)] })
|
|
258
|
+
else if (s.name === 'mem') sections.push({ name: s.name, chunks: memory === 'lazy' ? [{ lazy: true, length: res.index.length * page }] : [await chainCompact(links, res, { verify, page })] })
|
|
259
|
+
else sections.push({ name: s.name, chunks: await readSection(head.h, head.header, s.name, { verify }) })
|
|
260
|
+
}
|
|
261
|
+
const v = head.version
|
|
262
|
+
const out = { header: head.header, sections, version: v, chain: links.map(l => ({ name: l.name, version: l.version })) }
|
|
263
|
+
if (memory === 'lazy') out.into = mem => chainIntoFile(dir, name, v, mem, { verify, page })
|
|
264
|
+
return out
|
|
265
|
+
} finally {
|
|
266
|
+
closeChain(links)
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** into() of a loaded chain: opens it again at the version loaded (its parents at the versions it names) and applies it. */
|
|
271
|
+
export async function chainIntoFile(dir, name, version, memory, { verify = true, page = 65536 } = {}) {
|
|
272
|
+
const links = await openChain(dir, name, { version, page })
|
|
273
|
+
try {
|
|
274
|
+
return await chainInto(links, new Uint8Array(memory.buffer), { verify, page })
|
|
275
|
+
} finally {
|
|
276
|
+
closeChain(links)
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export const isMemSection = n => MEM_SECTIONS.includes(n)
|
|
281
|
+
|
|
282
|
+
/** The chain's image as one compact memory section (the pages of res.index, in order), each link's chunks checked: for a load with {memory: 'copy'}. */
|
|
283
|
+
export async function chainCompact(links, res, { verify = true, page = 65536 } = {}) {
|
|
284
|
+
const out = new Uint8Array(res.index.length * page)
|
|
285
|
+
const place = new Int32Array(res.src.length).fill(-1)
|
|
286
|
+
res.index.forEach((p, j) => (place[p] = j))
|
|
287
|
+
for (let li = 0; li < links.length; li++) {
|
|
288
|
+
const l = links[li]
|
|
289
|
+
const chunks = await readSection(l.h, l.header, 'mem', { verify })
|
|
290
|
+
let k = 0
|
|
291
|
+
for (const c of chunks) {
|
|
292
|
+
for (let at = 0; at < c.length; at += page, k++) {
|
|
293
|
+
const p = l.index[k]
|
|
294
|
+
if (res.src[p] === li) out.set(c.subarray(at, at + page), place[p] * page)
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
return out
|
|
299
|
+
}
|
package/src/host/ckpt-file.js
CHANGED
|
@@ -232,6 +232,41 @@ export async function readSection(h, header, name, { verify = true } = {}) {
|
|
|
232
232
|
return out
|
|
233
233
|
}
|
|
234
234
|
|
|
235
|
+
/**
|
|
236
|
+
* IOS-2: a memory section (pages listed by `index`, PAGE bytes each, in file order) read straight into `dest` (a view of
|
|
237
|
+
* the machine's memory): each chunk goes through one scratch buffer, is checked against its SHA-256 unless verify is
|
|
238
|
+
* false, and its pages are put at index[k] * PAGE. The page never holds the section. Returns {pages, scratchBytes}.
|
|
239
|
+
*/
|
|
240
|
+
export async function readSectionInto(h, header, name, index, dest, { verify = true, page = 65536 } = {}) {
|
|
241
|
+
const s = header.sections.find(x => x.name === name)
|
|
242
|
+
if (!s) throw new CheckpointError('malformed', `checkpoint has no section ${name}`)
|
|
243
|
+
const total = s.chunks.reduce((n, c) => n + c.len, 0)
|
|
244
|
+
if (total !== index.length * page) throw new CheckpointError('malformed', `section ${name} holds ${total} bytes for ${index.length} pages`)
|
|
245
|
+
const scratch = new Uint8Array(s.chunks.reduce((m, c) => Math.max(m, c.len), 0))
|
|
246
|
+
let off = s.off
|
|
247
|
+
let k = 0
|
|
248
|
+
for (let i = 0; i < s.chunks.length; i++) {
|
|
249
|
+
const c = s.chunks[i]
|
|
250
|
+
if (c.len % page) throw new CheckpointError('malformed', `memory chunk ${i} is ${c.len} bytes, not a whole number of ${page}-byte pages`)
|
|
251
|
+
const b = scratch.subarray(0, c.len)
|
|
252
|
+
let got = 0
|
|
253
|
+
while (got < c.len) {
|
|
254
|
+
const n = h.read(b.subarray(got), { at: off + got })
|
|
255
|
+
if (!(n > 0)) break
|
|
256
|
+
got += n
|
|
257
|
+
}
|
|
258
|
+
if (got !== c.len) throw new CheckpointError('truncated', `checkpoint is cut short: wanted ${c.len} bytes at ${off}, the file has ${got}`)
|
|
259
|
+
if (verify && (await sha256Hex(b)) !== c.sha256) throw new CheckpointError('corrupt', `checkpoint section ${name}, chunk ${i} (bytes ${off}..${off + c.len}) does not match its SHA-256: the file is damaged`)
|
|
260
|
+
for (let at = 0; at < c.len; at += page) {
|
|
261
|
+
const p = index[k++]
|
|
262
|
+
if ((p + 1) * page > dest.length) throw new CheckpointError('malformed', `page ${p} is past the ${dest.length / page} pages of memory`)
|
|
263
|
+
dest.set(b.subarray(at, at + page), p * page)
|
|
264
|
+
}
|
|
265
|
+
off += c.len + pad(off + c.len)
|
|
266
|
+
}
|
|
267
|
+
return { pages: k, scratchBytes: scratch.length }
|
|
268
|
+
}
|
|
269
|
+
|
|
235
270
|
export const sectionBytes = (header, name) => header.sections.find(s => s.name === name)?.chunks.reduce((n, c) => n + c.len, 0) ?? 0
|
|
236
271
|
|
|
237
272
|
/** Concatenates chunks (for small sections). */
|
package/src/host/ckpt-io.js
CHANGED
|
@@ -2,12 +2,14 @@
|
|
|
2
2
|
// OPFS API that all three browsers give a Worker). One file per checkpoint in the directory
|
|
3
3
|
// `wmd-ckpt` of the origin's private file system: <id>.ckpt.
|
|
4
4
|
//
|
|
5
|
-
// in: {id, op:'save', name, header, sections:[{name, lens:[n]}]} -> {ok, bytes, ms, shaMs, version, leftover}
|
|
5
|
+
// in: {id, op:'save', name, header, sections:[{name, lens:[n]}], parent?, memory?, index?, page?} -> {ok, bytes, ms, shaMs, version, leftover[, changed, zero, links]}
|
|
6
|
+
// IOS-2 parent: a diff over that checkpoint (ckpt-chain.js); the memory sections come from `memory` here, not from the page
|
|
6
7
|
// The bytes are pulled, one chunk at a time: when the save is ready for chunk (si, ci) the Worker posts
|
|
7
|
-
// {need:true, saveId:id, si, ci}; the page answers {op:'chunk', saveId, si, ci, buf}. At most one chunk (32 MiB)
|
|
8
|
+
// {need:true, saveId:id, si, ci, back?}; the page answers {op:'chunk', saveId, si, ci, buf, len?} (back: the last chunk's buffer, reused, IOS-2). At most one chunk (32 MiB)
|
|
8
9
|
// waits here, and a chunk is dropped as soon as it is written. One save at a time (a second is refused: busy).
|
|
9
10
|
// {id, op:'info', name} -> {ok, header} (header only: fast, no digests)
|
|
10
|
-
// {id, op:'load', name, sections:[names] | null (all), verify} -> {ok, header, sections:{name:[ArrayBuffer]}, ms}
|
|
11
|
+
// {id, op:'load', name, sections:[names] | null (all), verify, skip?:[names]} -> {ok, header, sections:{name:[ArrayBuffer]}, ms}
|
|
12
|
+
// {id, op:'into', name, version, section, index, memory, verify, page} -> {ok, pages, scratchBytes, ms} (IOS-2: a section a load skipped, into a shared memory)
|
|
11
13
|
// {id, op:'verify', name} -> {ok, header, ms} (every digest)
|
|
12
14
|
// {id, op:'list'} -> {ok, items:[{name, size, modified}]}
|
|
13
15
|
// {id, op:'delete', name} -> {ok}
|
|
@@ -16,6 +18,7 @@
|
|
|
16
18
|
// out: {id, ok:false, code, error} on failure (code: CheckpointError.code, or 'io').
|
|
17
19
|
import { createSaver } from './ckpt-save.js'
|
|
18
20
|
import { CheckpointError, baseNames, fileOf, readHeader, readSection, saveVersioned, versionsOf, withNewest } from './ckpt-file.js'
|
|
21
|
+
import { chainIntoFile, loadChain, saveDiff } from './ckpt-chain.js'
|
|
19
22
|
|
|
20
23
|
const DIR = 'wmd-ckpt'
|
|
21
24
|
const now = () => performance.now()
|
|
@@ -76,6 +79,11 @@ async function handle(m) {
|
|
|
76
79
|
case 'save': {
|
|
77
80
|
// the chunks are pulled one at a time (startSave): the save asks for each when it is ready for it
|
|
78
81
|
try {
|
|
82
|
+
if (m.parent) {
|
|
83
|
+
// IOS-2: a diff over m.parent: the pages of the frozen memory that changed since the parent chain, read here from the memory itself
|
|
84
|
+
const r = await saveDiff(await opfsDir(), checkName(m.name), { parent: checkName(m.parent), header: m.header, sections: m._sections, mem: new Uint8Array(m.memory.buffer), index: m.index, page: m.page })
|
|
85
|
+
return { bytes: r.bytes, ms: r.ms, shaMs: r.shaMs, version: r.version, leftover: r.leftover, changed: r.changed.length, zero: r.zero.length, links: r.links }
|
|
86
|
+
}
|
|
79
87
|
const r = await saveVersioned(await opfsDir(), checkName(m.name), m.header, m._sections, {})
|
|
80
88
|
return { bytes: r.bytes, ms: r.ms, shaMs: r.shaMs, version: r.version, leftover: r.leftover }
|
|
81
89
|
} finally {
|
|
@@ -88,14 +96,43 @@ async function handle(m) {
|
|
|
88
96
|
return withHandle(m.name, async (h, version, note) => {
|
|
89
97
|
const t0 = now()
|
|
90
98
|
const header = readHeader(h)
|
|
99
|
+
if (header.parent) return { chainAt: version, skipped: note.skipped } // a diff: read through its chain below, once this handle is closed (an OPFS file has one access handle at a time)
|
|
91
100
|
const out = {}
|
|
92
101
|
const transfer = []
|
|
93
102
|
for (const name of m.sections || header.sections.map(x => x.name)) {
|
|
103
|
+
if (m.skip?.includes(name)) continue // IOS-2: left in the file ('into' reads it later)
|
|
94
104
|
out[name] = (await readSection(h, header, name, { verify: m.verify !== false })).map(u => u.buffer)
|
|
95
105
|
for (const b of out[name]) transfer.push(b)
|
|
96
106
|
}
|
|
97
107
|
return { header, sections: out, ms: now() - t0, transfer, version, skipped: note.skipped }
|
|
108
|
+
}).then(async r => {
|
|
109
|
+
if (r.chainAt === undefined) return r
|
|
110
|
+
{
|
|
111
|
+
// IOS-2: a diff checkpoint: the newest link's sections and the memory image its chain makes
|
|
112
|
+
const t0 = now()
|
|
113
|
+
const version = r.chainAt
|
|
114
|
+
const c = await loadChain(await opfsDir(), checkName(m.name), { memory: m.skip?.includes('mem') ? 'lazy' : 'copy', verify: m.verify !== false, page: m.page, version })
|
|
115
|
+
const header = c.header
|
|
116
|
+
const note = { skipped: r.skipped }
|
|
117
|
+
const out = {}
|
|
118
|
+
const transfer = []
|
|
119
|
+
for (const sec of c.sections) {
|
|
120
|
+
if (sec.chunks[0]?.lazy) continue
|
|
121
|
+
out[sec.name] = sec.chunks.map(u => (u.byteOffset === 0 && u.byteLength === u.buffer.byteLength ? u.buffer : u.slice().buffer))
|
|
122
|
+
for (const b of out[sec.name]) transfer.push(b)
|
|
123
|
+
}
|
|
124
|
+
const memLen = c.sections.find(x => x.name === 'mem').chunks.reduce((n, x) => n + x.length, 0)
|
|
125
|
+
return { header, sections: out, ms: now() - t0, transfer, version, skipped: note.skipped, chain: c.chain, memBytes: memLen }
|
|
126
|
+
}
|
|
98
127
|
})
|
|
128
|
+
case 'into': {
|
|
129
|
+
// IOS-2: one section of the version a lazy load read, straight into a shared memory (the restoring machine's), one chunk at a time
|
|
130
|
+
// a diff checkpoint's chain is applied oldest first (a full checkpoint is a chain of one)
|
|
131
|
+
if (m.section !== 'mem') throw new CheckpointError('malformed', `into: only the memory section is read this way, not ${m.section}`)
|
|
132
|
+
const t0 = now()
|
|
133
|
+
const r = await chainIntoFile(await opfsDir(), checkName(m.name), m.version, m.memory, { verify: m.verify !== false, page: m.page })
|
|
134
|
+
return { pages: r.pages, scratchBytes: r.scratchBytes, links: r.links, ms: now() - t0 }
|
|
135
|
+
}
|
|
99
136
|
case 'verify':
|
|
100
137
|
return withHandle(m.name, async h => {
|
|
101
138
|
const t0 = now()
|
|
@@ -187,7 +224,7 @@ async function handle(m) {
|
|
|
187
224
|
}
|
|
188
225
|
}
|
|
189
226
|
|
|
190
|
-
const saver = createSaver(msg => self.postMessage(msg))
|
|
227
|
+
const saver = createSaver((msg, transfer = []) => self.postMessage(msg, transfer))
|
|
191
228
|
|
|
192
229
|
self.onmessage = async e => {
|
|
193
230
|
const m = e.data
|
package/src/host/ckpt-point.js
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
// every checkpoint when the vCPUs run again. The page writes a request kind into the word at
|
|
17
17
|
// word_addr (guest memory) and notifies it; the ctl thread hands it to vCPU 0.
|
|
18
18
|
|
|
19
|
-
import { CTL_CK_ATTACHES, CTL_CK_GO, CTL_CK_HOSTREQ, CTL_CK_POINTS } from './layout.js'
|
|
19
|
+
import { CTL_CK_ATTACHES, CTL_CK_GO, CTL_CK_HOSTREQ, CTL_CK_POINTS, CTL_CK_STREAM } from './layout.js'
|
|
20
20
|
|
|
21
21
|
export const PAGE = 65536
|
|
22
22
|
/** struct vm_snapshot_hdr (guest/vm/include/vm/snapshot.h), 336 bytes: field offsets read here. */
|
|
@@ -38,7 +38,7 @@ export const WINDOW_PAGES = 16384
|
|
|
38
38
|
* back to back, CHUNK_PAGES each), pages (total), nonzero, scanMs, copyMs}. Reads the memory
|
|
39
39
|
* without atomics: the machine is frozen.
|
|
40
40
|
*/
|
|
41
|
-
export function scanMemory(memory, { now = () => performance.now(), chunkPages = CHUNK_PAGES, limitBytes = Infinity, verifyAbove = false, skip = null } = {}) {
|
|
41
|
+
export function scanMemory(memory, { now = () => performance.now(), chunkPages = CHUNK_PAGES, limitBytes = Infinity, verifyAbove = false, skip = null, copy = true } = {}) {
|
|
42
42
|
const buf = memory.buffer
|
|
43
43
|
// limitBytes: pages from here up are taken to be zero and are not read. Reading an untouched page of a shared
|
|
44
44
|
// memory commits it in WebKit (W34: a full walk of a 3968 MiB memory added about 2.2 GB of footprint), so a caller
|
|
@@ -100,7 +100,8 @@ export function scanMemory(memory, { now = () => performance.now(), chunkPages =
|
|
|
100
100
|
}
|
|
101
101
|
const t1 = now()
|
|
102
102
|
const chunks = []
|
|
103
|
-
|
|
103
|
+
// copy false (IOS-2, a checkpoint saved straight to a store): the index only; the page reads the pages while the machine stays frozen
|
|
104
|
+
for (let k = 0; copy && k < n; k += chunkPages) {
|
|
104
105
|
const m = Math.min(chunkPages, n - k)
|
|
105
106
|
const c = new Uint8Array(m * PAGE)
|
|
106
107
|
for (let j = 0; j < m; j++) c.set(new Uint8Array(buf, idx[k + j] * PAGE, PAGE), j * PAGE)
|
|
@@ -167,7 +168,9 @@ export function createCkptImports({ memory, ram = null, touched = () => null, ct
|
|
|
167
168
|
const skips = desc ? touchedSkips(memory, desc) : null
|
|
168
169
|
// RAM in memory 0 starts at a 64 KiB boundary (memory.grow), so a skipped page is all RAM
|
|
169
170
|
if (skips && (Number(new BigUint64Array(memory.buffer, desc, 6)[2]) % PAGE) !== 0) throw new Error('guest RAM is not page-aligned in memory 0')
|
|
170
|
-
|
|
171
|
+
const copy = Atomics.load(ctl, CTL_CK_STREAM) !== 1
|
|
172
|
+
cap = scanMemory(memory, { now, limitBytes: limit, verifyAbove: verifyBound, skip: skips ? skips.mem0 : null, copy })
|
|
173
|
+
cap.streamed = !copy
|
|
171
174
|
cap.limitBytes = Number.isFinite(limit) ? limit : null
|
|
172
175
|
// the live g_rsv {brk, end} of vm.wasm 50c6495e / 3aef93fc (linear address 4251160), next to what vm_heap_top() says
|
|
173
176
|
try {
|
|
@@ -177,14 +180,14 @@ export function createCkptImports({ memory, ram = null, touched = () => null, ct
|
|
|
177
180
|
} catch {}
|
|
178
181
|
cap.heapTopRet = heapTop()
|
|
179
182
|
// the flat layout: guest RAM is a memory of its own (host/ram-mem.js), every page of it the guest's
|
|
180
|
-
if (ram) cap.ram = scanMemory(ram, { now, skip: skips ? skips.ram : null })
|
|
183
|
+
if (ram) cap.ram = scanMemory(ram, { now, skip: skips ? skips.ram : null, copy })
|
|
181
184
|
} catch (err) {
|
|
182
185
|
post({ t: 'ckpt-mem-error', message: String(err && err.message ? err.message : err) })
|
|
183
186
|
Atomics.wait(ctl, CTL_CK_GO, 0, goTimeoutMs)
|
|
184
187
|
Atomics.store(ctl, CTL_CK_GO, 0)
|
|
185
188
|
return -12
|
|
186
189
|
}
|
|
187
|
-
post({ t: 'ckpt-mem', index: cap.index, chunks: cap.chunks, pages: cap.pages, scannedPages: cap.scannedPages, skippedPages: cap.skippedPages, ramScannedPages: cap.ram?.scannedPages, ramSkippedPages: cap.ram?.skippedPages, aboveNonzero: cap.aboveNonzero, brkLive: cap.brkLive, endLive: cap.endLive, heapTopRet: cap.heapTopRet, limitBytes: cap.limitBytes, nonzero: cap.nonzero, scanMs: cap.scanMs, copyMs: cap.copyMs, ram: cap.ram ? { index: cap.ram.index, chunks: cap.ram.chunks, pages: cap.ram.pages, nonzero: cap.ram.nonzero, scanMs: cap.ram.scanMs, copyMs: cap.ram.copyMs } : null, doneAt: now() }, [cap.index.buffer, ...cap.chunks, ...(cap.ram ? [cap.ram.index.buffer, ...cap.ram.chunks] : [])])
|
|
190
|
+
post({ t: 'ckpt-mem', streamed: cap.streamed, index: cap.index, chunks: cap.chunks, pages: cap.pages, scannedPages: cap.scannedPages, skippedPages: cap.skippedPages, ramScannedPages: cap.ram?.scannedPages, ramSkippedPages: cap.ram?.skippedPages, aboveNonzero: cap.aboveNonzero, brkLive: cap.brkLive, endLive: cap.endLive, heapTopRet: cap.heapTopRet, limitBytes: cap.limitBytes, nonzero: cap.nonzero, scanMs: cap.scanMs, copyMs: cap.copyMs, ram: cap.ram ? { index: cap.ram.index, chunks: cap.ram.chunks, pages: cap.ram.pages, nonzero: cap.ram.nonzero, scanMs: cap.ram.scanMs, copyMs: cap.ram.copyMs } : null, doneAt: now() }, [cap.index.buffer, ...cap.chunks, ...(cap.ram ? [cap.ram.index.buffer, ...cap.ram.chunks] : [])])
|
|
188
191
|
const r = Atomics.wait(ctl, CTL_CK_GO, 0, goTimeoutMs)
|
|
189
192
|
const go = Atomics.load(ctl, CTL_CK_GO)
|
|
190
193
|
Atomics.store(ctl, CTL_CK_GO, 0)
|
package/src/host/ckpt-save.js
CHANGED
|
@@ -5,12 +5,16 @@
|
|
|
5
5
|
// chunk(m) delivers the page's answer: bytes, or {error} (the page could not copy the chunk: out of memory).
|
|
6
6
|
// page side answerNeed(ck, need, send): copies exactly the chunk asked for and sends {op:'chunk', saveId, si, ci, buf},
|
|
7
7
|
// or {op:'chunk', ..., error} when the copy failed, so the save fails instead of waiting for ever.
|
|
8
|
+
// IOS-2: the buffer of the chunk last written goes back to the page with the next need ({need, ..., back}, transferred), and the page copies
|
|
9
|
+
// the next chunk into it ({buf: back, len}) when it is large enough: a save makes one 32 MiB buffer for a section of equal chunks, instead of a
|
|
10
|
+
// fresh copy per chunk that the Worker drops but frees only at its next GC (on a phone that was about 150 MiB of peak for a 234 MB checkpoint).
|
|
8
11
|
//
|
|
9
12
|
// One save at a time: `saving` is what refuses a second ("busy"); done() clears it, so a failed save does not block the next.
|
|
10
13
|
import { CheckpointError } from './ckpt-file.js'
|
|
11
14
|
|
|
12
15
|
export function createSaver(post) {
|
|
13
16
|
let saving = null // {id, waits: Map key -> {resolve, reject}}
|
|
17
|
+
let back = null // the buffer of the chunk delivered last: written by the time the next chunk is asked for, so it goes back to the page
|
|
14
18
|
return {
|
|
15
19
|
get busy() {
|
|
16
20
|
return !!saving
|
|
@@ -28,7 +32,10 @@ export function createSaver(post) {
|
|
|
28
32
|
const f = () =>
|
|
29
33
|
new Promise((resolve, reject) => {
|
|
30
34
|
waits.set(`${si}:${ci}`, { resolve, reject })
|
|
31
|
-
|
|
35
|
+
const b = back
|
|
36
|
+
back = null
|
|
37
|
+
if (b) post({ need: true, saveId: m.id, si, ci, back: b }, [b])
|
|
38
|
+
else post({ need: true, saveId: m.id, si, ci })
|
|
32
39
|
})
|
|
33
40
|
f.size = len
|
|
34
41
|
Object.defineProperty(f, 'length', { value: len })
|
|
@@ -44,19 +51,36 @@ export function createSaver(post) {
|
|
|
44
51
|
if (!w) return false
|
|
45
52
|
saving.waits.delete(`${m.si}:${m.ci}`)
|
|
46
53
|
if (m.error) w.reject(new CheckpointError('io', `the page could not copy checkpoint chunk ${m.si}:${m.ci} (${m.error})`))
|
|
47
|
-
else
|
|
54
|
+
else {
|
|
55
|
+
back = m.buf
|
|
56
|
+
w.resolve(new Uint8Array(m.buf, 0, m.len ?? m.buf.byteLength))
|
|
57
|
+
}
|
|
48
58
|
return true
|
|
49
59
|
},
|
|
50
60
|
/** The save ended, however it ended. */
|
|
51
61
|
done() {
|
|
52
62
|
saving = null
|
|
63
|
+
back = null
|
|
53
64
|
},
|
|
54
65
|
}
|
|
55
66
|
}
|
|
56
67
|
|
|
57
68
|
export function answerNeed(ck, need, send) {
|
|
58
69
|
try {
|
|
59
|
-
const
|
|
70
|
+
const src = ck.sections[need.si].chunks[need.ci]
|
|
71
|
+
const b = need.back
|
|
72
|
+
// a lazy chunk (IOS-2: pages of a frozen memory) copies itself into the buffer
|
|
73
|
+
const put = u8 => (src.lazy ? src.read(u8) : u8.set(src))
|
|
74
|
+
if (b instanceof ArrayBuffer && b.byteLength >= src.length) {
|
|
75
|
+
put(new Uint8Array(b, 0, src.length))
|
|
76
|
+
send({ op: 'chunk', saveId: need.saveId, si: need.si, ci: need.ci, buf: b, len: src.length }, [b])
|
|
77
|
+
return
|
|
78
|
+
}
|
|
79
|
+
let buf
|
|
80
|
+
if (src.lazy) {
|
|
81
|
+
buf = new ArrayBuffer(src.length)
|
|
82
|
+
put(new Uint8Array(buf))
|
|
83
|
+
} else buf = src.slice().buffer
|
|
60
84
|
send({ op: 'chunk', saveId: need.saveId, si: need.si, ci: need.ci, buf }, [buf])
|
|
61
85
|
} catch (e) {
|
|
62
86
|
send({ op: 'chunk', saveId: need.saveId, si: need.si, ci: need.ci, error: String((e && e.message) || e) })
|
package/src/host/ckpt.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
// svc-<port> the 9P service's state for that port (fs/svc-snapshot.js)
|
|
10
10
|
// ctl the control block's WASI fd table (Int32 cells)
|
|
11
11
|
// Taken by vm.checkpoint() (boot.js), restored by bootWmd({restore}).
|
|
12
|
-
import { FORMAT_VERSION, CheckpointError, concat, memoryFile, readHeader, readSection, sectionBytes, sha256Hex, writeCheckpoint } from './ckpt-file.js'
|
|
12
|
+
import { FORMAT_VERSION, CheckpointError, concat, memoryFile, readHeader, readSection, readSectionInto, sectionBytes, sha256Hex, writeCheckpoint } from './ckpt-file.js'
|
|
13
13
|
import { answerNeed } from './ckpt-save.js'
|
|
14
14
|
import { PAGE } from './ckpt-point.js'
|
|
15
15
|
import { validateSnap, widenRecs } from './jit-snap.js'
|
|
@@ -206,14 +206,40 @@ export function restoreFdTable(ctl, bytes, nfiles = Infinity) {
|
|
|
206
206
|
* jit: {snap (jit-snap capture)}|null, svc: {port: {segments}}, ctl (bytes), names?: [[name, ip]] (W59: the network's
|
|
207
207
|
* placeholder map, an optional section `net-names`; FORMAT_VERSION is unchanged and images without it still load)}
|
|
208
208
|
*/
|
|
209
|
+
/** IOS-2: pages per chunk of a streamed save (8 MiB): the page and the store's Worker hold one such buffer at a time. */
|
|
210
|
+
export const STREAM_CHUNK_PAGES = 128
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* IOS-2: the memory section of a checkpoint as lazy chunks over a frozen memory: {lazy: true, length, read(u8)}, CHUNK pages each, in the
|
|
214
|
+
* index's order. read() copies the chunk's pages into u8. Valid only while the machine stays at its checkpoint point (vm.checkpoint({save})).
|
|
215
|
+
*/
|
|
216
|
+
export function memChunksOf(memory, index, chunkPages = STREAM_CHUNK_PAGES) {
|
|
217
|
+
const out = []
|
|
218
|
+
for (let k = 0; k < index.length; k += chunkPages) {
|
|
219
|
+
const m = Math.min(chunkPages, index.length - k)
|
|
220
|
+
const at = k
|
|
221
|
+
out.push({
|
|
222
|
+
lazy: true,
|
|
223
|
+
length: m * PAGE,
|
|
224
|
+
read(u8) {
|
|
225
|
+
const buf = memory.buffer
|
|
226
|
+
for (let j = 0; j < m; j++) u8.set(new Uint8Array(buf, index[at + j] * PAGE, PAGE), j * PAGE)
|
|
227
|
+
},
|
|
228
|
+
})
|
|
229
|
+
}
|
|
230
|
+
return out
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const chunkOf = c => (c && c.lazy ? c : new Uint8Array(c))
|
|
234
|
+
|
|
209
235
|
export function assembleCheckpoint(p) {
|
|
210
236
|
const sections = []
|
|
211
237
|
sections.push({ name: 'mem-index', chunks: [new Uint8Array(p.mem.index.buffer, p.mem.index.byteOffset, p.mem.index.byteLength)] })
|
|
212
|
-
sections.push({ name: 'mem', chunks: p.mem.chunks.map(
|
|
238
|
+
sections.push({ name: 'mem', chunks: p.mem.chunks.map(chunkOf) })
|
|
213
239
|
// the flat layout: the guest's RAM is a memory of its own, saved as its non-zero pages the same way
|
|
214
240
|
if (p.mem.ram) {
|
|
215
241
|
sections.push({ name: 'ram-index', chunks: [new Uint8Array(p.mem.ram.index.buffer, p.mem.ram.index.byteOffset, p.mem.ram.index.byteLength)] })
|
|
216
|
-
sections.push({ name: 'ram', chunks: p.mem.ram.chunks.map(
|
|
242
|
+
sections.push({ name: 'ram', chunks: p.mem.ram.chunks.map(chunkOf) })
|
|
217
243
|
}
|
|
218
244
|
const header = {
|
|
219
245
|
...p.meta,
|
|
@@ -279,7 +305,9 @@ export function parseCheckpoint(ck) {
|
|
|
279
305
|
const svc = {}
|
|
280
306
|
for (const port of h.svcPorts || []) svc[port] = concat(get(`svc-${port}`))
|
|
281
307
|
const ctlBytes = concat(get('ctl'))
|
|
282
|
-
|
|
308
|
+
// IOS-2: a store's lazy load (load(name, {memory: 'lazy'})): the memory section is still in the file, and into(memory, index) reads it there
|
|
309
|
+
const into = typeof ck.into === 'function' ? ck.into : null
|
|
310
|
+
return { header: h, index, memChunks, ram, jit, svc, ctl: new Uint8Array(ctlBytes), names: parseNames(ck), into }
|
|
283
311
|
}
|
|
284
312
|
|
|
285
313
|
/** The flat layout's RAM sections (`<name>-index` and `<name>`): {index, chunks}, checked as the memory's are. */
|
|
@@ -399,6 +427,24 @@ export function checkVmKeyFits(h, vmKey) {
|
|
|
399
427
|
}
|
|
400
428
|
}
|
|
401
429
|
|
|
430
|
+
/**
|
|
431
|
+
* IOS-2: the command line a checkpoint's boot had (its header's boot description) against this boot's. argv is part of the boot key, so a
|
|
432
|
+
* checkpoint of another command line (another --ram, --cpus, kernel command line) can never be restored here: a base snapshot is refused for it
|
|
433
|
+
* at its header, before its body is downloaded and decoded. A header without a description (older snapshots) is left to the full check.
|
|
434
|
+
*/
|
|
435
|
+
export function checkArgvFits(h, argv) {
|
|
436
|
+
const theirs = h && h.bootDesc && Array.isArray(h.bootDesc.argv) ? h.bootDesc.argv : null
|
|
437
|
+
if (!theirs || JSON.stringify(theirs) === JSON.stringify(argv)) return
|
|
438
|
+
const at = name => {
|
|
439
|
+
const i = theirs.indexOf(name)
|
|
440
|
+
const j = argv.indexOf(name)
|
|
441
|
+
return i >= 0 && j >= 0 && theirs[i + 1] !== argv[j + 1] ? `${name} ${String(theirs[i + 1]).slice(0, 40)} -> ${name} ${String(argv[j + 1]).slice(0, 40)}` : null
|
|
442
|
+
}
|
|
443
|
+
const named = ['--ram', '--cpus', '--append', '--arch'].map(at).filter(Boolean)
|
|
444
|
+
const what = named.length ? named.join(', ') : `${theirs.slice(1).join(' ').slice(0, 80)} -> ${argv.slice(1).join(' ').slice(0, 80)}`
|
|
445
|
+
throw new CheckpointError('stale', `this checkpoint was taken by a boot with another command line (${what}): it restores only into the same one; it was refused at its header, before its body was read`)
|
|
446
|
+
}
|
|
447
|
+
|
|
402
448
|
export function checkCheckpointFits(h, { vmKey, bootKey, bootDesc, maxPages, ramPages = 0, hasJit, fmaFused = true }) {
|
|
403
449
|
if (h.format !== FORMAT_VERSION) throw new CheckpointError('version', `checkpoint format ${h.format}; this build restores format ${FORMAT_VERSION}`)
|
|
404
450
|
if (h.vmKey !== vmKey) {
|
|
@@ -477,14 +523,17 @@ export function opfsStore({ workerUrl } = {}) {
|
|
|
477
523
|
* in-memory checkpoint stays usable: the page never holds a second copy of the whole file, and the Worker holds at
|
|
478
524
|
* most one chunk. Saves are queued, one at a time. Resolves {bytes, ms, shaMs, version, leftover}.
|
|
479
525
|
*/
|
|
480
|
-
save(name, ck) {
|
|
526
|
+
save(name, ck, { parent, memory, index } = {}) {
|
|
527
|
+
// a loaded checkpoint whose memory was left in its file has no bytes to write
|
|
528
|
+
if (ck.sections.some(sec => sec.chunks.some(c => c && c.lazy && typeof c.read !== 'function'))) return Promise.reject(new CheckpointError('malformed', "this checkpoint's memory is still in its file (a lazy load): load it with {memory: 'copy'} to save it again"))
|
|
481
529
|
const run = saveQueue.catch(() => {}).then(async () => {
|
|
482
530
|
const id = next++
|
|
483
531
|
activeSaves.set(id, ck)
|
|
484
532
|
try {
|
|
485
533
|
const sections = ck.sections.map(s => ({ name: s.name, lens: s.chunks.map(c => c.length) }))
|
|
486
|
-
|
|
487
|
-
|
|
534
|
+
// IOS-2 parent: a diff over that checkpoint; the Worker reads the changed pages from `memory` (the frozen machine's), listed non-zero in `index`
|
|
535
|
+
const r = await call({ op: 'save', name, header: ck.header, sections, ...(parent ? { parent, memory, index, page: PAGE } : {}) }, [], id)
|
|
536
|
+
return { bytes: r.bytes, ms: r.ms, shaMs: r.shaMs, version: r.version, leftover: r.leftover, ...(parent ? { changed: r.changed, zero: r.zero, links: r.links } : {}) }
|
|
488
537
|
} finally {
|
|
489
538
|
activeSaves.delete(id)
|
|
490
539
|
}
|
|
@@ -497,10 +546,22 @@ export function opfsStore({ workerUrl } = {}) {
|
|
|
497
546
|
return { header: r.header, size: r.size, version: r.version, skipped: r.skipped }
|
|
498
547
|
},
|
|
499
548
|
/** Reads and verifies a checkpoint into memory: {header, sections, ms}. */
|
|
500
|
-
|
|
549
|
+
/**
|
|
550
|
+
* Reads and verifies a checkpoint: {header, sections, ms}. IOS-2, the default: the memory section stays in the file
|
|
551
|
+
* (its chunks are {lazy, length}) and into(memory, index) is added: bootWmd({restore}) / vm.restore() then have the
|
|
552
|
+
* I/O Worker read it straight into the new machine's memory, one chunk at a time (the version read here, by name).
|
|
553
|
+
* {memory: 'copy'}: every section in hand, as before (to save it again or read its bytes).
|
|
554
|
+
*/
|
|
555
|
+
async load(name, { verify = true, memory } = {}) {
|
|
556
|
+
const { lazy, skip } = opfsLoadPlan({ memory })
|
|
501
557
|
// one op: a save that lands between an info and a load could make them name different versions
|
|
502
|
-
const r = await call({ op: 'load', name, sections: null, verify })
|
|
503
|
-
|
|
558
|
+
const r = await call({ op: 'load', name, sections: null, verify, skip, page: PAGE })
|
|
559
|
+
// a diff checkpoint (r.chain): 'mem-index' is the image its chain makes, 'mem' that image (r.memBytes), no 'mem-zero'
|
|
560
|
+
const memLazy = s => (r.chain ? [{ lazy: true, length: r.memBytes }] : lazyChunks(s))
|
|
561
|
+
const sections = r.header.sections.filter(s => !(r.chain && s.name === 'mem-zero')).map(s => ({ name: s.name, chunks: lazy && s.name === 'mem' ? memLazy(s) : r.sections[s.name].map(b => new Uint8Array(b)) }))
|
|
562
|
+
const out = { header: r.header, sections, ms: r.ms, version: r.version, skipped: r.skipped, ...(r.chain ? { chain: r.chain } : {}) }
|
|
563
|
+
if (lazy) out.into = async (mem, index) => call({ op: 'into', name, version: r.version, section: 'mem', index, memory: mem, verify, page: PAGE })
|
|
564
|
+
return out
|
|
504
565
|
},
|
|
505
566
|
async verify(name) {
|
|
506
567
|
return call({ op: 'verify', name })
|
|
@@ -538,6 +599,15 @@ export function opfsStore({ workerUrl } = {}) {
|
|
|
538
599
|
}
|
|
539
600
|
}
|
|
540
601
|
|
|
602
|
+
/** IOS-2: what an OPFS load reads now: the memory section stays in the file unless {memory: 'copy'} */
|
|
603
|
+
export function opfsLoadPlan({ memory = 'lazy' } = {}) {
|
|
604
|
+
if (memory !== 'lazy' && memory !== 'copy') throw new TypeError(`load: memory is 'lazy' (the default) or 'copy', not ${JSON.stringify(memory)}`)
|
|
605
|
+
return memory === 'lazy' ? { lazy: true, skip: ['mem'] } : { lazy: false, skip: [] }
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/** IOS-2: a section left in its file: each chunk's size, no bytes */
|
|
609
|
+
const lazyChunks = s => s.chunks.map(c => ({ lazy: true, length: c.len }))
|
|
610
|
+
|
|
541
611
|
/** The same interface over memory files (tests; a page without OPFS). */
|
|
542
612
|
export function memoryStore() {
|
|
543
613
|
const files = new Map()
|
|
@@ -555,13 +625,14 @@ export function memoryStore() {
|
|
|
555
625
|
if (!f) throw new CheckpointError('missing', `no checkpoint named ${JSON.stringify(name)}`)
|
|
556
626
|
return { header: readHeader(f), size: f.getSize() }
|
|
557
627
|
},
|
|
558
|
-
async load(name, { verify = true } = {}) {
|
|
628
|
+
async load(name, { verify = true, memory } = {}) {
|
|
559
629
|
const f = files.get(name)
|
|
560
630
|
if (!f) throw new CheckpointError('missing', `no checkpoint named ${JSON.stringify(name)}`)
|
|
561
631
|
const header = readHeader(f)
|
|
562
632
|
const sections = []
|
|
563
|
-
|
|
564
|
-
|
|
633
|
+
const lazy = memory === 'lazy'
|
|
634
|
+
for (const s of header.sections) sections.push({ name: s.name, chunks: lazy && s.name === 'mem' ? lazyChunks(s) : await readSection(f, header, s.name, { verify }) })
|
|
635
|
+
return { header, sections, ms: 0, ...(lazy ? { into: (mem, index) => readSectionInto(f, header, 'mem', index, new Uint8Array(mem.buffer), { verify, page: PAGE }) } : {}) }
|
|
565
636
|
},
|
|
566
637
|
async verify(name) {
|
|
567
638
|
await this.load(name, { verify: true })
|
package/src/host/layout.js
CHANGED
|
@@ -85,6 +85,9 @@ export const CTL_CK_ATTACHES = CKPT_BASE + 1 // wmd.ctl_attach calls so far (one
|
|
|
85
85
|
export const CTL_CK_GO = CKPT_BASE + 2 // page -> vCPU 0 inside wmd.point: 0 wait, 1 return 0 (taken), 2 return -1 (failed)
|
|
86
86
|
export const CTL_CK_POINTS = CKPT_BASE + 3 // wmd.point calls so far
|
|
87
87
|
export const CTL_CK_RESTORED = CKPT_BASE + 4 // restore: the page has written the checkpoint's memory; the main thread may call vm_resume (1)
|
|
88
|
+
// IOS-2: page -> vCPU 0 before a checkpoint: 1 the point only finds the non-zero pages (no copy); the page reads them from the frozen memory while a
|
|
89
|
+
// store saves them (vm.checkpoint({save})), and lets vCPU 0 go after the save. 0: the point copies them, as before
|
|
90
|
+
export const CTL_CK_STREAM = CKPT_BASE + 5
|
|
88
91
|
|
|
89
92
|
export const CTL_INTS = CKPT_BASE + 8
|
|
90
93
|
export const CTL_BYTES = CTL_INTS * 4
|
package/wmdpack.wasm
CHANGED
|
Binary file
|