@threadedstack/wmd-web 0.1.53 → 0.1.55

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 CHANGED
@@ -187,6 +187,9 @@ const r2 = await buildImage({ ...builderOptions, context, timeoutMs: 30 * 60_000
187
187
  mid-build, the next build mounts the disk again and its steps come back `CACHED`. `close({keep: false})` deletes
188
188
  the disk.
189
189
  - **A second tab** that asks for a disk already open gets a temporary disk, deleted when it closes.
190
+ - **A private window** (or any page with no OPFS) gets no disk: BuildKit's storage is in the builder's memory, as
191
+ with `disk: false`, and nothing is kept after the builder closes. The builder says so in two events:
192
+ `{t: 'storage', use: 'disk', storage: 'memory', reason}` and `{t: 'disk', reason: 'memory', message}`.
190
193
  - **Features:** `RUN --mount=type=cache` and `type=secret`, `# syntax=` frontends, build args and target stages,
191
194
  `.dockerignore`, file capabilities (`setcap`), push to a registry (TLS, or plain http in `httpRegistries`), and
192
195
  `tar: true` for a Docker tar that `docker load` takes. `--mount=type=ssh` and another platform are refused before
@@ -2967,6 +2970,11 @@ engines' memory64 limit), passes `WMD_RAM_FLAT=1` to vm.wasm and hands the memor
2967
2970
  `why` is `checkpoint`, `flatRam`, `ramInMemory0` (the option named `true`), `default` (the option on by the
2968
2971
  default), `allowLargeRam` or `ram` (the RAM size alone); `options` is the layout the options alone would have
2969
2972
  chosen. The test page keeps the last one as `ck.layout`.
2973
+ - A base snapshot read with `openBase({cache: opfsBaseCache()})` in a page with no OPFS (a private window, an
2974
+ automated WebKit with an ephemeral data store) is read from the network into memory and no copy is kept
2975
+ (`opfsBaseCache().available()` says so); `info.storage` is `{storage: 'memory', reason}` and the boot sends
2976
+ `{ t: 'boot', stage: 'storage', use: 'base', storage: 'memory', reason }`. An explicit
2977
+ `vm.checkpoint({save: {store: opfsStore()}})` there still fails with `CheckpointError` code `'unavailable'`.
2970
2978
  - The default. `RAM_IN_MEMORY0.default` in `src/boot.js` is the value of `ramInMemory0` when a caller leaves it out
2971
2979
  (`undefined` or `null`); it is `true` since the flip. Named values: only exactly `true` is on, only exactly
2972
2980
  `false` is off, anything else is off. With it on, a caller's own `allowLargeRam: true` (without naming the option)
package/RELEASE.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "wmd-web",
3
3
  "version": "0.5.1",
4
- "commit": "1c2eb4f7c274b135d46e3d5a340dfe47a067ac1f",
4
+ "commit": "96fbade729d8acbea87c59bca766aad70a49ded8",
5
5
  "previous": null,
6
6
  "decisions": [
7
7
  "D-388",
@@ -156,7 +156,7 @@
156
156
  }
157
157
  },
158
158
  "files": {
159
- "README.md": "f0f607498adc74465fdf90467313117fc3aad39a803efa4c8704605bb916a297",
159
+ "README.md": "93df5cc354b723760c7c3db18de3a69eb3f124fdb7d9a56ef017a758e5b734da",
160
160
  "edge-site/own/HASHES.txt": "4d83edcb41399bb89eb7b1f89115886d739adac887bdde59a8d33e3a4602683a",
161
161
  "edge-site/own/NOTICES.txt": "8ceca5406ee5833737bd5fa4a41d434bf5e4d26eff6da1e42c693176ee113101",
162
162
  "edge-site/own/acorn/LICENSE": "76a876cf886ff9be2a8b5e2e86514fed06223c8c9f0c1e9ee9606e93841e00b7",
@@ -178,10 +178,10 @@
178
178
  "guest/arm64/initramfs.cpio.gz": "ac7c0fc194b059579943c3d8ceaa0757c3e3e248231c2ad779260e97d5084cd3",
179
179
  "guest/arm64/vm.wasm": "7d16efadd83097e9b9188410187fb929b4ee5afbcb22cd387deebf1206b52376",
180
180
  "package.json": "6de9aa9fabdb395651d39997c17e094f01a574f54a36f0af31bd3ffaae53cda1",
181
- "src/base.js": "982f8e46dbb727ec542a494ebdb884ccd19a31ff4e091425b2d1fc01b0d4754a",
181
+ "src/base.js": "c79df2c3d4a6519fb9a6ef5cda39d66a5b9bc1a6dd009d21e7455e141943079f",
182
182
  "src/blob.js": "bb2a2f0d87ce236280a7be2f246c926010dfe07f649c27da5e70d8eb5eaf7061",
183
- "src/boot.js": "7ecdbe8c614436884d18181389af73568baba9e668601568437e8b59266dfaae",
184
- "src/build/builder.js": "c7794ec15b183213228776c8f4fb0950dec7e621f948358da7de8f90ef4f70ec",
183
+ "src/boot.js": "d6d45757bbae9949de7ce0dad18c5acd3c50c64bb30cb7b1c9c155a8231ab671",
184
+ "src/build/builder.js": "57a8436acc00147d031a42cccffe508f8deb3735b0ab4f9efcc2aa1cf7c6859c",
185
185
  "src/build/context.js": "d38097c61dbdadc4d41290c010425a4422f499aba473fa2b83f2a5c41e543571",
186
186
  "src/build/dockerfile.js": "5957fe3d4ac8ff8b312f980ee04bd1d98ad4373a61f9a33e02f1ff1108b6ea53",
187
187
  "src/build/dockerignore.js": "8fc03d09da020f43ea483979b1183891b71d76f012379ab7813838ea0e53c546",
@@ -281,19 +281,20 @@
281
281
  "src/gowasm/pins.json": "0f40d8553c19915b328263077097b0c353072ec84d2afd5cf388e92a2fde9cce",
282
282
  "src/gowasm/setup.js": "4cda761d94ca28b28fc03cb846a98b6735a8e03dbbfe09ebbf4f64742f712038",
283
283
  "src/gowasm/twin-fetch.js": "c5d53ccb6ee21c0ffc76d4c9f41f2dea1ceec45a3fe26d5b98cfbd4b9aecce70",
284
- "src/host/base-cache.js": "e0a9ea65e4eb9e30e7f78b28d9e5653b395f8eaa6c5e4c75b92f123c8d6a76a9",
284
+ "src/host/base-cache.js": "83fd8f28779446eff5dff096856e868416117cd7330d1ce7a8a06c4a10b1a111",
285
285
  "src/host/base-file.js": "edb47c1eeb6b1cec627fa5894512185336b15d3f5db96a7151a8a57b34b4a2e8",
286
286
  "src/host/base-io.js": "cdd049875dce9f1417f28b27efa2c6f494cbe2a49851249150d0c1ec871a8b59",
287
- "src/host/boot-events.js": "a6567c889fa1e95ad7e917107a2593f03d14cc921827616368b3417de96faad2",
287
+ "src/host/boot-events.js": "4af19b460a18b5c4e18c3a30d3cf1e843d4881b823a4f1b052a8cad4cea6cd2b",
288
288
  "src/host/chan-service-entry.js": "18f602f9ad72323e930157cb0820568f3ef83ce49b9672443791b01551f0ffd3",
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-file.js": "da7938fa640a062e77bdfb59caad5b3b1fcbf6150e3220de3be23f253f4c4497",
293
- "src/host/ckpt-io.js": "c176b98bc9fd7669da6336d481425b980af440a7c1f95463f6f1c4808e9590bf",
292
+ "src/host/ckpt-chain.js": "c208a882da772acafe1373ea1d7e04723e26e870396d4202ef330d4eaf758596",
293
+ "src/host/ckpt-file.js": "709344bfadf7c8151d51f70787b9e9d4b074ed1f5f80af113f11215851b9c28a",
294
+ "src/host/ckpt-io.js": "92e437fb3b118c4269ecc4aafec6e17cf99936d3fc0c410e38f48b9146e791fb",
294
295
  "src/host/ckpt-point.js": "e08441b52d65b18c91f7e14b6ab3ad347572a0ac96a6642cf8072b47dde404eb",
295
296
  "src/host/ckpt-save.js": "7bb07f536005fb5e7d9db6a09169a5ce1e3865d337ab65ce798a111334c6aa07",
296
- "src/host/ckpt.js": "5b651f67742d133f246239cdb6a7dcdf688aa62c84e0ef53925077740551412b",
297
+ "src/host/ckpt.js": "371acb574e31e94201ae1ff32a7cfad85801ae3eae2896cde7d53a96430c502d",
297
298
  "src/host/clock.js": "aba6af3a8b1a985ae340892222e4b482d33afe20f5c8b3a4c7403ce87d1e247c",
298
299
  "src/host/csp-reason.js": "ecec797e31006896176ff4e2972f11e5d5df160fe0cd80071c39d7808ff922fc",
299
300
  "src/host/ctl.js": "86066c8d3be8e6f6b05e831344cd72ebc446ced391fc8290e1c584940b8ab3e0",
@@ -316,6 +317,7 @@
316
317
  "src/host/jit.js": "72ef7334506fde2b3724cee93b52a987fbd6d45473b8de93d914db8a80ae9e17",
317
318
  "src/host/layout.js": "c878b8da956da3ebc2391cf802869f12b3d74c131ffbcb9879536617728beeac",
318
319
  "src/host/monitor.js": "ae1741ba35668bcc6192642246494433b175668933921634c699af5a0a69acc0",
320
+ "src/host/opfs-avail.js": "a98945c0f1792f29bc0147de662173cc9275a43dbeb44ec575ecb8ee44d5f122",
319
321
  "src/host/p9mount.js": "cd27abd769b19ed8b26050ddd8b6d61f81faa5a431924217dd0bf2593258d5b9",
320
322
  "src/host/pinned-fetch.js": "873eb804604c150f6c8e488eb6c49fb8dc7a85108e80bf1a831904b9555726eb",
321
323
  "src/host/ram-mem.js": "bf4036d5d12be1d5d2f5223e526b0b8e225bc702ae7e60a2a59fdfe9fbbb49e3",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threadedstack/wmd-web",
3
- "version": "0.1.53",
3
+ "version": "0.1.55",
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.53",
13
- "commit": "1c2eb4f7c274b135d46e3d5a340dfe47a067ac1f",
12
+ "tag": "v0.1.55",
13
+ "commit": "96fbade729d8acbea87c59bca766aad70a49ded8",
14
14
  "web": "0.5.1"
15
15
  },
16
16
  "type": "module",
package/src/base.js CHANGED
@@ -48,7 +48,7 @@ export async function vmKeyOf(url, fetchFn = (...a) => fetch(...a)) {
48
48
  */
49
49
  export function openBase({ manifestUrl, image, cache = null, query = '', log = () => {}, fetchFn = (...a) => fetch(...a), vmKey = null, pick = es => es.at(-1), stallMs = 20_000, maxMs = 600_000, gate = true } = {}) {
50
50
  const ac = new AbortController()
51
- const info = { source: null, manifestMs: null, cacheWrite: null, attempts: [], netBytes: 0, stalled: null }
51
+ const info = { source: null, manifestMs: null, cacheWrite: null, attempts: [], netBytes: 0, stalled: null, storage: null }
52
52
  let resolveHeader
53
53
  let rejectHeader
54
54
  const header = new Promise((res, rej) => ((resolveHeader = res), (rejectHeader = rej)))
@@ -198,6 +198,17 @@ export function openBase({ manifestUrl, image, cache = null, query = '', log = (
198
198
  }
199
199
  },
200
200
  }
201
+ // IOS-3: a cache that says this page has no storage for it (OPFS in a private window) is not used: the snapshot is
202
+ // read from the network into memory and no copy is kept; info.storage (and the boot's 'storage' event) says why
203
+ if (cache) {
204
+ const a = cache.available ? await cache.available().catch(e => ({ ok: false, reason: String(e && e.message) })) : { ok: true }
205
+ if (a.ok) info.storage = { storage: cache.kind || 'cache' }
206
+ else {
207
+ info.storage = { storage: 'memory', reason: a.reason }
208
+ log(`base snapshot: no ${cache.kind || ''} cache here, nothing is kept (${a.reason})`)
209
+ cache = null
210
+ }
211
+ }
201
212
  // attempt 1: the cache (if it holds the file); attempt 2 (or 1): the network. A cached file that fails verification is deleted and the network is tried.
202
213
  for (const source of cache ? ['opfs', 'network'] : ['network']) {
203
214
  let stream = null
package/src/boot.js CHANGED
@@ -37,13 +37,13 @@ import {
37
37
  } from './host/layout.js'
38
38
  import { gcNudgeEvery } from './host/gcnudge.js'
39
39
  import { createRamMemory, haveMemory64 } from './host/ram-mem.js'
40
- import { bootFileName, cachedFromTiming, createBootEvents, createWorkerList, readBody, timingCount, vcpusOf } from './host/boot-events.js'
40
+ import { baseStorageEvent, bootFileName, cachedFromTiming, createBootEvents, createWorkerList, readBody, timingCount, vcpusOf } from './host/boot-events.js'
41
41
  import { createJitStore, readJitStats, tableMinOf } from './host/jit.js'
42
42
  import { createJitCacheHost } from './host/jit-cache.js'
43
43
  import { createPanicScanner, createThrottleMeter, createWatchdog, watchdogDefaultMs } from './host/monitor.js'
44
44
  import { BOOT_RING, MOBILE_RING, createStdio, stdioReader, stdioText } from './host/stdio.js'
45
45
  import {
46
- CONSOLE_IN_LIMIT, chanCounters, chanView, consoleInputGate, createChanBlock, markGuestGone, markServiceDead, ringBell, ringRead,
46
+ CONSOLE_IN_LIMIT, KIND_OF, chanCounters, chanView, consoleInputGate, createChanBlock, markGuestGone, markServiceDead, ringBell, ringRead,
47
47
  } from './host/chan.js'
48
48
  import { ControlClient } from './host/ctl.js'
49
49
  import { chooseTwin, eventsOf, putBackTwin, specKeysDiffering, twinForBoot } from './gowasm/boot-setup.js'
@@ -57,7 +57,7 @@ export { DiskError, deleteDisk, openDisk, sweepDisks } from './host/disk.js'
57
57
  export { NetSwitch } from './net/switch.js'
58
58
  export { ImageFiles, openImage, parseGroup, parsePasswd, resolveUser } from './image-files.js'
59
59
  export { P9_CACHE_DEFAULT, P9_FEATURES_LIMIT_MS, P9_FEATURES_MAX_BYTES, P9_NAMES_DEFAULT, P9_NAMES_FEATURE, fetchGuestFeatures, p9CacheDefault, p9FeaturesLost, p9InitCmdline, p9MountOptions, p9RunRefusal, parseGuestFeatures, readGuestFeatures } from './host/p9mount.js'
60
- import { bootGuestFeatures, p9DropNames, p9HandleFields } from './host/p9mount.js'
60
+ import { P9_MSIZE_DEFAULT, bootGuestFeatures, p9DropNames, p9HandleFields } from './host/p9mount.js'
61
61
  export { loadImageTar } from './registry/load-tar.js'
62
62
 
63
63
  /** X5: the decisions of edgeSetup below, counted: `on` (node in the frame) and `off` by reason (node in the guest). */
@@ -431,6 +431,18 @@ export function stdioRingDefault(nav = globalThis.navigator) {
431
431
  return isMobileWebKit(nav) ? MOBILE_RING : BOOT_RING
432
432
  }
433
433
 
434
+ /**
435
+ * IOS-3: the chan block's sizes when the caller names none. The block is one SharedArrayBuffer, which mobile WebKit counts
436
+ * whole the moment it is made (D-516). The console pipe (service -> page) is written only by a 'console' service: 8 MiB
437
+ * with one, 4 KiB without. Each ring (a direction of a slot): the caller's ringBytes, else 1 MiB, or in mobile WebKit
438
+ * P9_MSIZE_DEFAULT (256 KiB, one whole 9P message; a ring is a byte stream, a larger message waits for room).
439
+ * Plain alpine's block: 26.4 MB before, 5.4 MB on a phone, 18.0 MB elsewhere.
440
+ */
441
+ export function chanBlockDefaults({ services = [], ringBytes, nav = globalThis.navigator } = {}) {
442
+ const hasConsole = services.some(s => s.kind === 'console' || s.kind === KIND_OF.console)
443
+ return { ringBytes: ringBytes ?? (isMobileWebKit(nav) ? P9_MSIZE_DEFAULT : 1 << 20), pipeBytes: hasConsole ? 1 << 23 : 4096 }
444
+ }
445
+
434
446
  /**
435
447
  * W34: the bytes of live JIT modules a WebKit page can hold, so that the machine's memory at its
436
448
  * maximum + the page's own files + the engine's copies of the modules stay under 5.5 GiB (2.5 GiB
@@ -1268,6 +1280,8 @@ async function bootMachine(o) {
1268
1280
  if (lazyIn) {
1269
1281
  try {
1270
1282
  const h = await raceAbort(lazyIn.header)
1283
+ const se = baseStorageEvent(lazyIn.info) // IOS-3: no OPFS here (a private window): the snapshot is in memory only
1284
+ if (se) be.now('storage', se)
1271
1285
  checkVmKeyFits(h, vmKey)
1272
1286
  checkArgvFits(h, argv) // IOS-2: another command line (a 1024 MiB base under a 256 MiB request) is refused before its body is read
1273
1287
  settleLayout(chooseLayout(o.args, o, h)) // X24 default: the base snapshot's own layout
@@ -1413,9 +1427,9 @@ async function bootMachine(o) {
1413
1427
  restoreFdTable(ctl, restoreIn.ctl, files.length)
1414
1428
  ckptT.pagesRestored = restoreIn.index.length
1415
1429
  }
1416
- function restoreMemory() {
1430
+ async function restoreMemory() {
1417
1431
  try {
1418
- restoreMemoryNow()
1432
+ await restoreMemoryNow()
1419
1433
  // the snapshot restored: its cache copy may be committed now (not before: a snapshot that fails to restore must not stay cached)
1420
1434
  const lazy = baseLazy
1421
1435
  baseLazy = null
@@ -1433,18 +1447,26 @@ async function bootMachine(o) {
1433
1447
  finish(4, `restore failed: ${err && err.message ? err.message : err}`)
1434
1448
  }
1435
1449
  }
1436
- function restoreMemoryNow() {
1450
+ async function restoreMemoryNow() {
1437
1451
  const tm = absMs()
1438
1452
  const have = memory.buffer.byteLength / CKPT_PAGE // the size the instance made: its start function wrote nothing above it
1439
1453
  if (restoreIn.header.memPages > have) memory.grow(restoreIn.header.memPages - have)
1440
- const u8 = new Uint8Array(memory.buffer)
1441
1454
  const kept = new Uint8Array(restoreIn.header.memPages)
1442
- let k = 0
1443
- for (const c of restoreIn.memChunks) {
1444
- for (let off = 0; off < c.length; off += CKPT_PAGE) {
1445
- const p = restoreIn.index[k++]
1446
- u8.set(c.subarray(off, off + CKPT_PAGE), p * CKPT_PAGE)
1447
- kept[p] = 1
1455
+ if (restoreIn.into) {
1456
+ // IOS-2: a store's lazy load: its I/O Worker reads the memory section straight into this memory (the page never holds it)
1457
+ const r = await restoreIn.into(memory, restoreIn.index)
1458
+ if (r.pages !== restoreIn.index.length) throw new Error(`the store wrote ${r.pages} of the checkpoint's ${restoreIn.index.length} memory pages`)
1459
+ for (const p of restoreIn.index) kept[p] = 1
1460
+ ckptT.memoryInto = true
1461
+ } else {
1462
+ const u8 = new Uint8Array(memory.buffer)
1463
+ let k = 0
1464
+ for (const c of restoreIn.memChunks) {
1465
+ for (let off = 0; off < c.length; off += CKPT_PAGE) {
1466
+ const p = restoreIn.index[k++]
1467
+ u8.set(c.subarray(off, off + CKPT_PAGE), p * CKPT_PAGE)
1468
+ kept[p] = 1
1469
+ }
1448
1470
  }
1449
1471
  }
1450
1472
  // the flat layout: the guest's RAM, into its own memory (a fresh one: all zero but for these pages)
@@ -1499,6 +1521,7 @@ async function bootMachine(o) {
1499
1521
  }
1500
1522
  be.now('restore', { t: 'boot', stage: 'restore', state: 'done', used: true, bytes: baseBytes, total: baseTotal, source: baseSource, tookMs: Math.round(ckptT.pagesWrittenAt) })
1501
1523
  restoreIn.memChunks = null
1524
+ restoreIn.into = null
1502
1525
  restoreIn.index = null
1503
1526
  restoreIn.ram = null
1504
1527
  restoreIn.jit = null
@@ -1613,7 +1636,7 @@ async function bootMachine(o) {
1613
1636
  chanSab = createChanBlock({
1614
1637
  ports: chanSvcs.map(s => ({ port: s.port, kind: s.kind })),
1615
1638
  nslots: o.channels.nslots ?? 8,
1616
- ringBytes: o.channels.ringBytes ?? 1 << 20,
1639
+ ...chanBlockDefaults({ services: chanSvcs, ringBytes: o.channels.ringBytes }), // IOS-3: no console service: a 4 KiB pipe; mobile WebKit: 256 KiB rings
1617
1640
  count9p: !!o.channels.count9p, // X16: 9P counts by type and layer class (chanStats().p9Count); off by default
1618
1641
  })
1619
1642
  memTook += absMs() - tc
@@ -2611,7 +2634,9 @@ async function bootMachine(o) {
2611
2634
  if (c.mem.ram) c.mem.ram.chunks = memChunksOf(ramMem, c.mem.ram.index)
2612
2635
  const ckpt = ckptBuild(c, names)
2613
2636
  ckpt.header.stats.streamed = true
2614
- const saved = await c.stream.store.save(c.stream.name, ckpt)
2637
+ // IOS-2 parent: a diff over that checkpoint, made by the store's Worker from the frozen memory itself
2638
+ 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')
2639
+ const saved = await c.stream.store.save(c.stream.name, ckpt, c.stream.parent ? { parent: c.stream.parent, memory, index: c.mem.index } : undefined)
2615
2640
  if (ck !== c) return
2616
2641
  c.savedResult = { header: ckpt.header, saved, streamed: true }
2617
2642
  c.streamDone = true
@@ -2630,7 +2655,10 @@ async function bootMachine(o) {
2630
2655
  function checkpoint({ label = '', timeoutMs = 60_000, save = null } = {}) {
2631
2656
  // IOS-2: save {store, name}: the checkpoint goes straight to the store and the answer is {header, saved, streamed}, no sections. With an
2632
2657
  // OPFS store the page never holds the guest's memory (see ckptStreamSave); with another store it is taken in memory and saved, as before
2633
- if (save && (!save.store || typeof save.store.save !== 'function' || !save.name)) return Promise.reject(new TypeError('checkpoint({save}): save is {store, name}'))
2658
+ if (save && (!save.store || typeof save.store.save !== 'function' || !save.name)) return Promise.reject(new TypeError('checkpoint({save}): save is {store, name[, parent]}'))
2659
+ // 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
2660
+ 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'))
2661
+ if (save?.parent && save.store.kind !== 'opfs') return Promise.reject(new TypeError('checkpoint({save: {parent}}): a diff checkpoint needs an OPFS store (opfsStore())'))
2634
2662
  if (save && save.store.kind !== 'opfs') {
2635
2663
  return checkpoint({ label, timeoutMs }).then(async ckpt => ({ header: ckpt.header, saved: await save.store.save(save.name, ckpt), streamed: false }))
2636
2664
  }
@@ -10,6 +10,7 @@ import { blobBytes } from '../blob.js'
10
10
  import { bootWmd, isWebKit, memory0RamLimit, ramInMemory0On } from '../boot.js'
11
11
  import { MAIN_PROC_ID, containerBundle, fillRunRequest } from '../host/ctl.js'
12
12
  import { DiskError, deleteDisk, openDisk, sweepDisks } from '../host/disk.js'
13
+ import { opfsAvailable } from '../host/opfs-avail.js'
13
14
  import { p9OptsOfVm } from '../host/p9mount.js'
14
15
  import { loadImageTar } from '../registry/load-tar.js'
15
16
  import { packContext, readTarFile } from './context.js'
@@ -490,6 +491,38 @@ fi
490
491
  exec /usr/bin/buildkit-runc "$@"
491
492
  `
492
493
 
494
+ /**
495
+ * The builder's disk: wmd-builder-<namespace>-<arch>, or a temporary one when another tab holds it; null for disk: false.
496
+ * IOS-3: a page with no OPFS (a private window) gets no disk either: BuildKit's storage is then in the builder's memory,
497
+ * and a 'storage' event ({storage: 'memory', reason}) and a 'disk' event say so.
498
+ * available, openDisk, sweepDisks: test hooks.
499
+ */
500
+ export async function openBuilderDisk({ disk: d, archName, emit, available = opfsAvailable, openDisk: open = openDisk, sweepDisks: sweep = sweepDisks }) {
501
+ if (d === false) return null
502
+ const a = await available()
503
+ if (!a.ok) {
504
+ emit({ t: 'storage', use: 'disk', storage: 'memory', reason: a.reason })
505
+ emit({ t: 'disk', reason: 'memory', message: `no OPFS here (${a.reason}): BuildKit's storage is in the builder's memory, kept until it closes` })
506
+ return null
507
+ }
508
+ const mib = d.mib || 10240
509
+ const base = `wmd-builder-${d.namespace}-${archName}`
510
+ const swept = await sweep('wmd-builder-tmp-').catch(() => [])
511
+ if (swept.length) emit({ t: 'disk', reason: 'swept', names: swept })
512
+ let disk
513
+ try {
514
+ disk = await open({ name: base, mib, onEvent: emit })
515
+ } catch (e) {
516
+ if (!(e instanceof DiskError) || e.reason !== 'locked') throw e
517
+ const tmp = `wmd-builder-tmp-${crypto.randomUUID().slice(0, 8)}-${archName}`
518
+ emit({ t: 'disk', reason: 'locked', message: `${base} is open in another tab; this builder uses ${tmp}, deleted on close` })
519
+ disk = await open({ name: tmp, mib, onEvent: emit })
520
+ disk.temporary = true
521
+ }
522
+ emit({ t: 'disk', reason: disk.created ? 'new' : 'open', name: disk.name, mib: disk.mib, persisted: disk.persisted })
523
+ return disk
524
+ }
525
+
493
526
  export async function createBuilder(o) {
494
527
  const archName = o.arch || 'arm64'
495
528
  const arch = ARCHES[archName]
@@ -512,24 +545,7 @@ export async function createBuilder(o) {
512
545
  const image = await builderImage(o.image, { converter: o.converter, platform: arch.platform, archName, fetchFn, store: o.store })
513
546
  const digest = o.image?.tar ? o.image.sha256 : await indexDigest(image.index)
514
547
 
515
- // the disk: wmd-builder-<namespace>-<arch>, or a temporary one when another tab holds it
516
- let disk = null
517
- if (o.disk !== false) {
518
- const mib = o.disk.mib || 10240
519
- const base = `wmd-builder-${o.disk.namespace}-${archName}`
520
- const swept = await sweepDisks('wmd-builder-tmp-').catch(() => [])
521
- if (swept.length) emit({ t: 'disk', reason: 'swept', names: swept })
522
- try {
523
- disk = await openDisk({ name: base, mib, onEvent: emit })
524
- } catch (e) {
525
- if (!(e instanceof DiskError) || e.reason !== 'locked') throw e
526
- const tmp = `wmd-builder-tmp-${crypto.randomUUID().slice(0, 8)}-${archName}`
527
- emit({ t: 'disk', reason: 'locked', message: `${base} is open in another tab; this builder uses ${tmp}, deleted on close` })
528
- disk = await openDisk({ name: tmp, mib, onEvent: emit })
529
- disk.temporary = true
530
- }
531
- emit({ t: 'disk', reason: disk.created ? 'new' : 'open', name: disk.name, mib: disk.mib, persisted: disk.persisted })
532
- }
548
+ const disk = await openBuilderDisk({ disk: o.disk, archName, emit })
533
549
 
534
550
  const env = [
535
551
  ...(image.index.config?.Env || ['PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin']),
@@ -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.53' }
5
+ export const EDGE_PACKAGE = { name: '@threadedstack/wmd-node', version: '0.1.55' }
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 },
@@ -8,6 +8,7 @@
8
8
  // writer(name) -> {write(u8), commit(), abort()} the tee of a download: pieces in file order; write() applies backpressure
9
9
  // A cache is an optimisation: every failure is the caller's to log and ignore (the snapshot is verified again on every read).
10
10
  import { BASE_MAGIC } from './base-file.js'
11
+ import { opfsAvailable } from './opfs-avail.js'
11
12
 
12
13
  const MAGIC = new TextEncoder().encode(BASE_MAGIC)
13
14
  const FLUSH = 4 << 20
@@ -78,7 +79,13 @@ export function makeWriter({ put, commit, abort }) {
78
79
  }
79
80
  }
80
81
 
81
- export function opfsBaseCache({ workerUrl, dirName = 'wmd-base' } = {}) {
82
+ /**
83
+ * @param {{workerUrl?: URL|string, dirName?: string, getDirectory?: () => Promise<FileSystemDirectoryHandle>}} o
84
+ * getDirectory: a test hook (default navigator.storage.getDirectory)
85
+ */
86
+ export function opfsBaseCache({ workerUrl, dirName = 'wmd-base', getDirectory } = {}) {
87
+ const gd = getDirectory || (() => navigator.storage.getDirectory())
88
+ let avail = null
82
89
  let w = null
83
90
  let next = 1
84
91
  const pending = new Map()
@@ -106,9 +113,14 @@ export function opfsBaseCache({ workerUrl, dirName = 'wmd-base' } = {}) {
106
113
  w.postMessage({ ...msg, id }, transfer)
107
114
  })
108
115
  }
109
- const dir = async () => (await navigator.storage.getDirectory()).getDirectoryHandle(dirName, { create: true })
116
+ const dir = async () => (await gd()).getDirectoryHandle(dirName, { create: true })
110
117
  return {
111
118
  kind: 'opfs',
119
+ /** IOS-3: {ok: true} | {ok: false, reason}: no OPFS here (a private window); openBase() then keeps no copy. Asked once. */
120
+ available() {
121
+ avail ||= opfsAvailable({ getDirectory: getDirectory || (globalThis.navigator?.storage?.getDirectory ? gd : null) })
122
+ return avail
123
+ },
112
124
  async open(name) {
113
125
  let file
114
126
  try {
@@ -207,3 +207,14 @@ export function createWorkerList(at) {
207
207
  has: id => ws.has(id),
208
208
  }
209
209
  }
210
+
211
+ /**
212
+ * IOS-3: the boot event for a base snapshot cache this page could not use (OPFS in a private window): the snapshot was
213
+ * read into memory and no copy kept. null when the cache was used, or there was none.
214
+ * @param {{storage?: {storage: string, reason?: string} | null} | null} info openBase()'s info
215
+ */
216
+ export function baseStorageEvent(info) {
217
+ const s = info?.storage
218
+ if (!s || s.storage !== 'memory') return null
219
+ return { t: 'boot', stage: 'storage', use: 'base', storage: 'memory', reason: s.reason }
220
+ }
@@ -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
+ }
@@ -30,6 +30,16 @@ export class CheckpointError extends Error {
30
30
  }
31
31
  }
32
32
 
33
+ /**
34
+ * IOS-3: navigator.storage.getDirectory() refused. WebKit's ephemeral data store (a private window; Playwright's default
35
+ * WebKit context) rejects it with "UnknownError ... (e.g. out of memory)" before any file is touched: say what it is.
36
+ * Other errors are returned as they are.
37
+ */
38
+ export function opfsDirError(e) {
39
+ if (!e || !['UnknownError', 'SecurityError'].includes(e.name)) return e
40
+ return new CheckpointError('unavailable', `this page has no origin private file system here (navigator.storage.getDirectory: ${e.name}: ${e.message}). A private window, or an automated WebKit with an ephemeral data store, does this: use memoryStore() for checkpoints in memory, or a normal window`)
41
+ }
42
+
33
43
  export async function sha256Hex(u8) {
34
44
  const d = new Uint8Array(await crypto.subtle.digest('SHA-256', u8))
35
45
  let s = ''
@@ -232,6 +242,41 @@ export async function readSection(h, header, name, { verify = true } = {}) {
232
242
  return out
233
243
  }
234
244
 
245
+ /**
246
+ * IOS-2: a memory section (pages listed by `index`, PAGE bytes each, in file order) read straight into `dest` (a view of
247
+ * the machine's memory): each chunk goes through one scratch buffer, is checked against its SHA-256 unless verify is
248
+ * false, and its pages are put at index[k] * PAGE. The page never holds the section. Returns {pages, scratchBytes}.
249
+ */
250
+ export async function readSectionInto(h, header, name, index, dest, { verify = true, page = 65536 } = {}) {
251
+ const s = header.sections.find(x => x.name === name)
252
+ if (!s) throw new CheckpointError('malformed', `checkpoint has no section ${name}`)
253
+ const total = s.chunks.reduce((n, c) => n + c.len, 0)
254
+ if (total !== index.length * page) throw new CheckpointError('malformed', `section ${name} holds ${total} bytes for ${index.length} pages`)
255
+ const scratch = new Uint8Array(s.chunks.reduce((m, c) => Math.max(m, c.len), 0))
256
+ let off = s.off
257
+ let k = 0
258
+ for (let i = 0; i < s.chunks.length; i++) {
259
+ const c = s.chunks[i]
260
+ if (c.len % page) throw new CheckpointError('malformed', `memory chunk ${i} is ${c.len} bytes, not a whole number of ${page}-byte pages`)
261
+ const b = scratch.subarray(0, c.len)
262
+ let got = 0
263
+ while (got < c.len) {
264
+ const n = h.read(b.subarray(got), { at: off + got })
265
+ if (!(n > 0)) break
266
+ got += n
267
+ }
268
+ if (got !== c.len) throw new CheckpointError('truncated', `checkpoint is cut short: wanted ${c.len} bytes at ${off}, the file has ${got}`)
269
+ 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`)
270
+ for (let at = 0; at < c.len; at += page) {
271
+ const p = index[k++]
272
+ if ((p + 1) * page > dest.length) throw new CheckpointError('malformed', `page ${p} is past the ${dest.length / page} pages of memory`)
273
+ dest.set(b.subarray(at, at + page), p * page)
274
+ }
275
+ off += c.len + pad(off + c.len)
276
+ }
277
+ return { pages: k, scratchBytes: scratch.length }
278
+ }
279
+
235
280
  export const sectionBytes = (header, name) => header.sections.find(s => s.name === name)?.chunks.reduce((n, c) => n + c.len, 0) ?? 0
236
281
 
237
282
  /** Concatenates chunks (for small sections). */
@@ -2,26 +2,35 @@
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
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
+ // {id, op:'ready'} -> {ok} or {ok:false, code:'unavailable'} (no OPFS here: a private window)
14
17
  // {id, op:'usage'} -> {ok, usage, quota}
15
18
  // {id, op:'poke', name, at, xor} / {id, op:'cut', name, size} test hooks: damage a file
16
19
  // out: {id, ok:false, code, error} on failure (code: CheckpointError.code, or 'io').
17
20
  import { createSaver } from './ckpt-save.js'
18
- import { CheckpointError, baseNames, fileOf, readHeader, readSection, saveVersioned, versionsOf, withNewest } from './ckpt-file.js'
21
+ import { CheckpointError, baseNames, fileOf, opfsDirError, readHeader, readSection, saveVersioned, versionsOf, withNewest } from './ckpt-file.js'
22
+ import { chainIntoFile, loadChain, saveDiff } from './ckpt-chain.js'
19
23
 
20
24
  const DIR = 'wmd-ckpt'
21
25
  const now = () => performance.now()
22
26
 
23
27
  async function dir() {
24
- const root = await navigator.storage.getDirectory()
28
+ let root
29
+ try {
30
+ root = await navigator.storage.getDirectory()
31
+ } catch (e) {
32
+ throw opfsDirError(e) // IOS-3: a private window's (ephemeral) store has none
33
+ }
25
34
  return root.getDirectoryHandle(DIR, { create: true })
26
35
  }
27
36
 
@@ -76,6 +85,11 @@ async function handle(m) {
76
85
  case 'save': {
77
86
  // the chunks are pulled one at a time (startSave): the save asks for each when it is ready for it
78
87
  try {
88
+ if (m.parent) {
89
+ // 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
90
+ 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 })
91
+ 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 }
92
+ }
79
93
  const r = await saveVersioned(await opfsDir(), checkName(m.name), m.header, m._sections, {})
80
94
  return { bytes: r.bytes, ms: r.ms, shaMs: r.shaMs, version: r.version, leftover: r.leftover }
81
95
  } finally {
@@ -88,14 +102,43 @@ async function handle(m) {
88
102
  return withHandle(m.name, async (h, version, note) => {
89
103
  const t0 = now()
90
104
  const header = readHeader(h)
105
+ 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
106
  const out = {}
92
107
  const transfer = []
93
108
  for (const name of m.sections || header.sections.map(x => x.name)) {
109
+ if (m.skip?.includes(name)) continue // IOS-2: left in the file ('into' reads it later)
94
110
  out[name] = (await readSection(h, header, name, { verify: m.verify !== false })).map(u => u.buffer)
95
111
  for (const b of out[name]) transfer.push(b)
96
112
  }
97
113
  return { header, sections: out, ms: now() - t0, transfer, version, skipped: note.skipped }
114
+ }).then(async r => {
115
+ if (r.chainAt === undefined) return r
116
+ {
117
+ // IOS-2: a diff checkpoint: the newest link's sections and the memory image its chain makes
118
+ const t0 = now()
119
+ const version = r.chainAt
120
+ const c = await loadChain(await opfsDir(), checkName(m.name), { memory: m.skip?.includes('mem') ? 'lazy' : 'copy', verify: m.verify !== false, page: m.page, version })
121
+ const header = c.header
122
+ const note = { skipped: r.skipped }
123
+ const out = {}
124
+ const transfer = []
125
+ for (const sec of c.sections) {
126
+ if (sec.chunks[0]?.lazy) continue
127
+ out[sec.name] = sec.chunks.map(u => (u.byteOffset === 0 && u.byteLength === u.buffer.byteLength ? u.buffer : u.slice().buffer))
128
+ for (const b of out[sec.name]) transfer.push(b)
129
+ }
130
+ const memLen = c.sections.find(x => x.name === 'mem').chunks.reduce((n, x) => n + x.length, 0)
131
+ return { header, sections: out, ms: now() - t0, transfer, version, skipped: note.skipped, chain: c.chain, memBytes: memLen }
132
+ }
98
133
  })
134
+ case 'into': {
135
+ // 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
136
+ // a diff checkpoint's chain is applied oldest first (a full checkpoint is a chain of one)
137
+ if (m.section !== 'mem') throw new CheckpointError('malformed', `into: only the memory section is read this way, not ${m.section}`)
138
+ const t0 = now()
139
+ const r = await chainIntoFile(await opfsDir(), checkName(m.name), m.version, m.memory, { verify: m.verify !== false, page: m.page })
140
+ return { pages: r.pages, scratchBytes: r.scratchBytes, links: r.links, ms: now() - t0 }
141
+ }
99
142
  case 'verify':
100
143
  return withHandle(m.name, async h => {
101
144
  const t0 = now()
@@ -178,6 +221,9 @@ async function handle(m) {
178
221
  } catch {}
179
222
  return { writtenMB: Math.round(written / (1 << 20)), error: err && `${err} (at ${step})` }
180
223
  }
224
+ case 'ready': // IOS-3: whether this page has an origin private file system here
225
+ await dir()
226
+ return {}
181
227
  case 'usage': {
182
228
  const e = await navigator.storage.estimate()
183
229
  return { usage: e.usage, quota: e.quota }
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'
@@ -305,7 +305,9 @@ export function parseCheckpoint(ck) {
305
305
  const svc = {}
306
306
  for (const port of h.svcPorts || []) svc[port] = concat(get(`svc-${port}`))
307
307
  const ctlBytes = concat(get('ctl'))
308
- return { header: h, index, memChunks, ram, jit, svc, ctl: new Uint8Array(ctlBytes), names: parseNames(ck) }
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 }
309
311
  }
310
312
 
311
313
  /** The flat layout's RAM sections (`<name>-index` and `<name>`): {index, chunks}, checked as the memory's are. */
@@ -521,14 +523,17 @@ export function opfsStore({ workerUrl } = {}) {
521
523
  * in-memory checkpoint stays usable: the page never holds a second copy of the whole file, and the Worker holds at
522
524
  * most one chunk. Saves are queued, one at a time. Resolves {bytes, ms, shaMs, version, leftover}.
523
525
  */
524
- 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"))
525
529
  const run = saveQueue.catch(() => {}).then(async () => {
526
530
  const id = next++
527
531
  activeSaves.set(id, ck)
528
532
  try {
529
533
  const sections = ck.sections.map(s => ({ name: s.name, lens: s.chunks.map(c => c.length) }))
530
- const r = await call({ op: 'save', name, header: ck.header, sections }, [], id)
531
- return { bytes: r.bytes, ms: r.ms, shaMs: r.shaMs, version: r.version, leftover: r.leftover }
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 } : {}) }
532
537
  } finally {
533
538
  activeSaves.delete(id)
534
539
  }
@@ -541,10 +546,22 @@ export function opfsStore({ workerUrl } = {}) {
541
546
  return { header: r.header, size: r.size, version: r.version, skipped: r.skipped }
542
547
  },
543
548
  /** Reads and verifies a checkpoint into memory: {header, sections, ms}. */
544
- async load(name, { verify = true } = {}) {
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 })
545
557
  // one op: a save that lands between an info and a load could make them name different versions
546
- const r = await call({ op: 'load', name, sections: null, verify })
547
- return { header: r.header, sections: r.header.sections.map(s => ({ name: s.name, chunks: r.sections[s.name].map(b => new Uint8Array(b)) })), ms: r.ms, version: r.version, skipped: r.skipped }
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
548
565
  },
549
566
  async verify(name) {
550
567
  return call({ op: 'verify', name })
@@ -555,6 +572,15 @@ export function opfsStore({ workerUrl } = {}) {
555
572
  async delete(name) {
556
573
  await call({ op: 'delete', name })
557
574
  },
575
+ /** IOS-3: resolves {ok: true} when this page has an origin private file system, else {ok: false, code, reason} (a private window has none) */
576
+ async available() {
577
+ try {
578
+ await call({ op: 'ready' })
579
+ return { ok: true }
580
+ } catch (e) {
581
+ return { ok: false, code: e.code || 'io', reason: e.message }
582
+ }
583
+ },
558
584
  async usage() {
559
585
  const r = await call({ op: 'usage' })
560
586
  return { usage: r.usage, quota: r.quota }
@@ -582,6 +608,15 @@ export function opfsStore({ workerUrl } = {}) {
582
608
  }
583
609
  }
584
610
 
611
+ /** IOS-2: what an OPFS load reads now: the memory section stays in the file unless {memory: 'copy'} */
612
+ export function opfsLoadPlan({ memory = 'lazy' } = {}) {
613
+ if (memory !== 'lazy' && memory !== 'copy') throw new TypeError(`load: memory is 'lazy' (the default) or 'copy', not ${JSON.stringify(memory)}`)
614
+ return memory === 'lazy' ? { lazy: true, skip: ['mem'] } : { lazy: false, skip: [] }
615
+ }
616
+
617
+ /** IOS-2: a section left in its file: each chunk's size, no bytes */
618
+ const lazyChunks = s => s.chunks.map(c => ({ lazy: true, length: c.len }))
619
+
585
620
  /** The same interface over memory files (tests; a page without OPFS). */
586
621
  export function memoryStore() {
587
622
  const files = new Map()
@@ -599,13 +634,14 @@ export function memoryStore() {
599
634
  if (!f) throw new CheckpointError('missing', `no checkpoint named ${JSON.stringify(name)}`)
600
635
  return { header: readHeader(f), size: f.getSize() }
601
636
  },
602
- async load(name, { verify = true } = {}) {
637
+ async load(name, { verify = true, memory } = {}) {
603
638
  const f = files.get(name)
604
639
  if (!f) throw new CheckpointError('missing', `no checkpoint named ${JSON.stringify(name)}`)
605
640
  const header = readHeader(f)
606
641
  const sections = []
607
- for (const s of header.sections) sections.push({ name: s.name, chunks: await readSection(f, header, s.name, { verify }) })
608
- return { header, sections, ms: 0 }
642
+ const lazy = memory === 'lazy'
643
+ 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 }) })
644
+ return { header, sections, ms: 0, ...(lazy ? { into: (mem, index) => readSectionInto(f, header, 'mem', index, new Uint8Array(mem.buffer), { verify, page: PAGE }) } : {}) }
609
645
  },
610
646
  async verify(name) {
611
647
  await this.load(name, { verify: true })
@@ -0,0 +1,19 @@
1
+ // IOS-3: whether this page has an origin private file system. A private window, or an automated WebKit with an
2
+ // ephemeral data store, rejects navigator.storage.getDirectory() (UnknownError); where wmd itself picks OPFS (the base
3
+ // snapshot cache, the builder's disk) it then uses memory and says so in an event ({storage: 'memory', reason}).
4
+
5
+ const pageGetDirectory = () => (globalThis.navigator?.storage?.getDirectory ? () => globalThis.navigator.storage.getDirectory() : null)
6
+
7
+ /**
8
+ * @param {{getDirectory?: (() => Promise<any>) | null}} o test hook: the getDirectory to try (null: there is none)
9
+ * @returns {Promise<{ok: true} | {ok: false, reason: string}>}
10
+ */
11
+ export async function opfsAvailable({ getDirectory = pageGetDirectory() } = {}) {
12
+ if (typeof getDirectory !== 'function') return { ok: false, reason: 'navigator.storage.getDirectory is not in this browser' }
13
+ try {
14
+ await getDirectory()
15
+ return { ok: true }
16
+ } catch (e) {
17
+ return { ok: false, reason: `navigator.storage.getDirectory: ${e?.name || 'Error'}: ${e?.message || e}` }
18
+ }
19
+ }
package/wmdpack.wasm CHANGED
Binary file