@waffle-os/runtime 0.0.154 → 0.0.156

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/core/filesystem.ts +22 -0
  2. package/core/wasi.ts +78 -5
  3. package/dist/core/filesystem.js +1 -0
  4. package/dist/core/wasi.js +71 -6
  5. package/dist/fs/backend.js +22 -1
  6. package/dist/fs/client.js +11 -3
  7. package/dist/fs/cold-read-cache.js +23 -0
  8. package/dist/fs/guest-watch.js +267 -94
  9. package/dist/fs/indexeddb-chunks.js +88 -11
  10. package/dist/fs/indexeddb.js +78 -14
  11. package/dist/fs/memory.js +17 -1
  12. package/dist/fs/multitab-backend.js +198 -64
  13. package/dist/fs/multitab-protocol.js +1 -0
  14. package/dist/fs/persistent.js +19 -1
  15. package/dist/fs/service.js +30 -1
  16. package/dist/fs/shared.js +4 -0
  17. package/dist/fs/storage.js +107 -8
  18. package/dist/fs/watch-service.js +97 -2
  19. package/dist/fs/watch-subscriptions.js +121 -8
  20. package/dist/proc/intrinsics/core.js +5 -0
  21. package/dist/proc/intrinsics.js +1 -0
  22. package/dist/tooling/program/program-transformer.json +1 -1
  23. package/fs/backend.ts +27 -1
  24. package/fs/client.ts +11 -0
  25. package/fs/cold-read-cache.ts +38 -0
  26. package/fs/guest-watch.ts +298 -102
  27. package/fs/indexeddb-chunks.ts +103 -9
  28. package/fs/indexeddb.ts +98 -11
  29. package/fs/memory.ts +18 -0
  30. package/fs/multitab-backend.ts +273 -72
  31. package/fs/multitab-protocol.ts +1 -0
  32. package/fs/persistent.ts +38 -1
  33. package/fs/service.ts +28 -0
  34. package/fs/shared.ts +4 -0
  35. package/fs/storage.ts +128 -10
  36. package/fs/watch-service.ts +110 -3
  37. package/fs/watch-subscriptions.ts +115 -7
  38. package/package.json +1 -1
  39. package/proc/intrinsics/core.ts +7 -0
  40. package/proc/intrinsics.ts +1 -0
  41. package/testing/indexeddb-storage-browser.ts +129 -0
  42. package/tooling/program/program-transformer.json +1 -1
@@ -67,25 +67,50 @@ export function parseChunk(value: unknown, size: number, key: string): ChunkReco
67
67
  export function chunkLength(manifest: ChunkManifest, index: number): number {
68
68
  return Math.min(CHUNK_SIZE, manifest.size - index * CHUNK_SIZE);
69
69
  }
70
+ const HEX = Array.from({ length: 256 }, (_, byte) => byte.toString(16).padStart(2, "0"));
71
+ const PREPARE_CONCURRENCY = 32;
72
+
70
73
  export async function chunkChecksum(bytes: Uint8Array<ArrayBuffer>): Promise<string> {
71
74
  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
72
- return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
75
+ let hex = "";
76
+ for (let i = 0; i < digest.length; i++) hex += HEX[digest[i]!]!;
77
+ return hex;
73
78
  }
74
- export async function preparePayload(
79
+ async function prepareOwnedPayload(
75
80
  bytes: Uint8Array,
76
81
  signal?: AbortSignal,
77
82
  ): Promise<PreparedPayload> {
78
- const chunks: ChunkRecord[] = [];
79
- for (let offset = 0; offset < bytes.length; offset += CHUNK_SIZE) {
83
+ if (!bytes.length) {
80
84
  signal?.throwIfAborted();
81
- const part = bytes.slice(offset, offset + CHUNK_SIZE);
82
- chunks.push({ bytes: part, checksum: await chunkChecksum(part) });
85
+ return {
86
+ manifest: { version: 2, size: 0, chunkSize: CHUNK_SIZE, count: 0 },
87
+ chunks: [],
88
+ };
83
89
  }
90
+ const count = Math.ceil(bytes.length / CHUNK_SIZE);
91
+ const chunks = Array.from<ChunkRecord>({ length: count });
92
+ let next = 0;
93
+ const workers = Math.min(PREPARE_CONCURRENCY, count);
94
+ await Promise.all(
95
+ Array.from({ length: workers }, async () => {
96
+ while (next < count) {
97
+ signal?.throwIfAborted();
98
+ const index = next++;
99
+ const offset = index * CHUNK_SIZE;
100
+ const part = bytes.slice(offset, offset + CHUNK_SIZE);
101
+ chunks[index] = { bytes: part, checksum: await chunkChecksum(part) };
102
+ }
103
+ }),
104
+ );
105
+ signal?.throwIfAborted();
84
106
  return {
85
- manifest: { version: 2, size: bytes.length, chunkSize: CHUNK_SIZE, count: chunks.length },
107
+ manifest: { version: 2, size: bytes.length, chunkSize: CHUNK_SIZE, count },
86
108
  chunks,
87
109
  };
88
110
  }
111
+ export function preparePayload(bytes: Uint8Array, signal?: AbortSignal): Promise<PreparedPayload> {
112
+ return prepareOwnedPayload(bytes, signal);
113
+ }
89
114
  export function validateRange(range: IndexedDBRange): void {
90
115
  if (
91
116
  !validInteger(range.offset) ||
@@ -99,7 +124,7 @@ export function deletePayload(store: IDBObjectStore, key: string): void {
99
124
  store.delete(key);
100
125
  store.delete(IDBKeyRange.bound([key, 0], [key, Number.MAX_SAFE_INTEGER]));
101
126
  }
102
- function putPayload(store: IDBObjectStore, key: string, payload: PreparedPayload): void {
127
+ export function putPayload(store: IDBObjectStore, key: string, payload: PreparedPayload): void {
103
128
  for (const [index, chunk] of payload.chunks.entries()) store.put(chunk, [key, index]);
104
129
  store.put(payload.manifest, key);
105
130
  }
@@ -165,9 +190,78 @@ function compareChunk(
165
190
 
166
191
  export async function preparePayloads(
167
192
  data: ReadonlyMap<string, Uint8Array>,
193
+ owned = false,
194
+ checkAbort?: () => void,
168
195
  ): Promise<Map<string, PreparedPayload>> {
169
196
  const prepared = new Map<string, PreparedPayload>();
170
- for (const [key, bytes] of data) prepared.set(key, await preparePayload(bytes));
197
+ checkAbort?.();
198
+ if (!data.size) return prepared;
199
+ const tasks: {
200
+ chunks: ChunkRecord[];
201
+ index: number;
202
+ bytes: Uint8Array;
203
+ offset: number;
204
+ direct: boolean;
205
+ }[] = [];
206
+ for (const [key, bytes] of data) {
207
+ if (!bytes.length) {
208
+ prepared.set(key, {
209
+ manifest: { version: 2, size: 0, chunkSize: CHUNK_SIZE, count: 0 },
210
+ chunks: [],
211
+ });
212
+ continue;
213
+ }
214
+ const count = Math.ceil(bytes.length / CHUNK_SIZE);
215
+ const chunks = Array.from<ChunkRecord>({ length: count });
216
+ prepared.set(key, {
217
+ manifest: { version: 2, size: bytes.length, chunkSize: CHUNK_SIZE, count },
218
+ chunks,
219
+ });
220
+ const direct =
221
+ owned &&
222
+ count === 1 &&
223
+ bytes.byteOffset === 0 &&
224
+ bytes.byteLength === bytes.buffer.byteLength &&
225
+ bytes.buffer instanceof ArrayBuffer;
226
+ for (let index = 0; index < count; index++)
227
+ tasks.push({ chunks, index, bytes, offset: index * CHUNK_SIZE, direct });
228
+ }
229
+ if (!tasks.length) return prepared;
230
+ let next = 0;
231
+ let failed = false;
232
+ let failure: unknown;
233
+ const fail = (error: unknown) => {
234
+ if (!failed) {
235
+ failed = true;
236
+ failure = error;
237
+ }
238
+ };
239
+ const workers = Math.min(PREPARE_CONCURRENCY, tasks.length);
240
+ await Promise.allSettled(
241
+ Array.from({ length: workers }, async () => {
242
+ while (!failed && next < tasks.length) {
243
+ try {
244
+ checkAbort?.();
245
+ } catch (error) {
246
+ fail(error);
247
+ return;
248
+ }
249
+ const task = tasks[next++]!;
250
+ const part = task.direct
251
+ ? (task.bytes as Uint8Array<ArrayBuffer>)
252
+ : task.bytes.slice(task.offset, task.offset + CHUNK_SIZE);
253
+ try {
254
+ const checksum = await chunkChecksum(part);
255
+ task.chunks[task.index] = { bytes: part, checksum };
256
+ } catch (error) {
257
+ fail(error);
258
+ return;
259
+ }
260
+ }
261
+ }),
262
+ );
263
+ if (failed) throw failure;
264
+ checkAbort?.();
171
265
  return prepared;
172
266
  }
173
267
  export function copyLegacyChunks(
package/fs/indexeddb.ts CHANGED
@@ -28,6 +28,7 @@ import {
28
28
  parseManifest,
29
29
  preparePayload,
30
30
  preparePayloads,
31
+ putPayload,
31
32
  copyLegacyChunks,
32
33
  validateRange,
33
34
  type ChunkManifest,
@@ -449,6 +450,9 @@ class PayloadSizes {
449
450
  size(key: string): number | undefined {
450
451
  return this.entries.get(key)?.size;
451
452
  }
453
+ has(key: string): boolean {
454
+ return this.entries.has(key);
455
+ }
452
456
  }
453
457
  interface CommittedTransaction {
454
458
  group: PreparedDurableGroup;
@@ -620,6 +624,24 @@ function placeManifestReads(
620
624
  }
621
625
  };
622
626
  }
627
+ /**
628
+ * The epoch read of a readwrite transaction whose scope holds "metadata": whether the epoch
629
+ * matched, or `undefined` when the transaction ended before reading it. No connection can change
630
+ * the epoch while that transaction holds "metadata", so a match stays current until it ends.
631
+ */
632
+ type EpochWitness = Promise<boolean | undefined>;
633
+
634
+ /** Settles with `promise`, or rejects with the signal's reason once it aborts. */
635
+ function raceAbort<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
636
+ if (!signal) return promise;
637
+ signal.throwIfAborted();
638
+ return new Promise<T>((resolve, reject) => {
639
+ const onAbort = () => reject(signal.reason);
640
+ signal.addEventListener("abort", onAbort, { once: true });
641
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
642
+ });
643
+ }
644
+
623
645
  function completed(tx: IDBTransaction): Promise<void> {
624
646
  return new Promise((resolve, reject) => {
625
647
  tx.oncomplete = () => resolve();
@@ -1056,6 +1078,8 @@ export class IndexedDBStorage implements StorageBackend {
1056
1078
  private ownershipError?: Error;
1057
1079
  private ownershipRetirement?: Promise<void>;
1058
1080
  private transactions = new Set<IDBTransaction>();
1081
+ /** Epoch reads of this connection's open readwrite transactions; see verifyEpoch. */
1082
+ private readonly epochWitnesses = new Set<EpochWitness>();
1059
1083
  private committedEnvelope: CommitEnvelope | undefined;
1060
1084
  private committedRecord: ChecksummedRecord | undefined;
1061
1085
  private committedPending = false;
@@ -1086,10 +1110,47 @@ export class IndexedDBStorage implements StorageBackend {
1086
1110
  return this.initialLastExclusiveEpoch;
1087
1111
  }
1088
1112
 
1089
- /** Readonly IndexedDB check verifying this connection still owns the latest epoch. */
1113
+ /**
1114
+ * Verifies this connection still owns the latest epoch. While one of its own readwrite
1115
+ * transactions holds "metadata", that transaction's epoch read answers: a readonly transaction
1116
+ * would only queue behind it, and a large checkpoint commit can hold it for seconds.
1117
+ *
1118
+ * A witness leaves the set in its transaction's complete or abort event, a task after the
1119
+ * transaction released "metadata". That gap does not weaken the answer for the multitab lease:
1120
+ * only a connection that took the storage Web Lock writes a new epoch, and the lease renewal
1121
+ * confirms this connection still holds that lock before it asks here.
1122
+ */
1090
1123
  async verifyEpoch(signal?: AbortSignal): Promise<boolean> {
1091
1124
  if (this.closed || this.ownershipError) return false;
1092
1125
  signal?.throwIfAborted();
1126
+ const witnessed = await this.witnessedEpoch(signal);
1127
+ if (witnessed !== undefined) return witnessed && !this.closed && !this.ownershipError;
1128
+ return this.readEpoch(signal);
1129
+ }
1130
+
1131
+ private async witnessedEpoch(signal?: AbortSignal): Promise<boolean | undefined> {
1132
+ for (const witness of Array.from(this.epochWitnesses)) {
1133
+ const result = await raceAbort(witness, signal);
1134
+ if (result !== undefined) return result;
1135
+ }
1136
+ return undefined;
1137
+ }
1138
+
1139
+ /** Records the epoch read of a readwrite transaction holding "metadata" until it ends. */
1140
+ private witnessEpoch(tx: IDBTransaction, read: IDBRequest): void {
1141
+ const { promise: witness, resolve } = Promise.withResolvers<boolean | undefined>();
1142
+ const end = () => {
1143
+ this.epochWitnesses.delete(witness);
1144
+ resolve(undefined);
1145
+ };
1146
+ read.addEventListener("success", () => resolve(read.result === this.epoch));
1147
+ read.addEventListener("error", () => resolve(undefined));
1148
+ tx.addEventListener("complete", end);
1149
+ tx.addEventListener("abort", end);
1150
+ this.epochWitnesses.add(witness);
1151
+ }
1152
+
1153
+ private async readEpoch(signal?: AbortSignal): Promise<boolean> {
1093
1154
  let tx: IDBTransaction | undefined;
1094
1155
  const onAbort = () => {
1095
1156
  try {
@@ -1997,11 +2058,14 @@ export class IndexedDBStorage implements StorageBackend {
1997
2058
  }
1998
2059
 
1999
2060
  private recordRecovery(state: State, extra?: readonly string[]): void {
2000
- const retained = new Set<string>(extra);
2001
- payloads(state.nodes.values(), retained);
2002
- for (const base of state.bases) if (base) payloads(base.nodes, retained);
2003
- for (const journal of state.journals.values()) payloads(journal.upserts, retained);
2004
- this.readers.recovery(retained);
2061
+ if (!extra?.length) {
2062
+ this.readers.recovery(state.payloadSizes);
2063
+ return;
2064
+ }
2065
+ const extraRoots = new Set(extra);
2066
+ this.readers.recovery({
2067
+ has: (key) => extraRoots.has(key) || state.payloadSizes.has(key),
2068
+ });
2005
2069
  }
2006
2070
 
2007
2071
  private matchSizes(
@@ -2032,6 +2096,7 @@ export class IndexedDBStorage implements StorageBackend {
2032
2096
  const done = completed(tx);
2033
2097
  const metadata = tx.objectStore("metadata");
2034
2098
  const epoch = metadata.get("epoch");
2099
+ this.witnessEpoch(tx, epoch);
2035
2100
  epoch.onsuccess = () => {
2036
2101
  try {
2037
2102
  if (epoch.result !== this.epoch) throw this.loseOwnership();
@@ -2093,7 +2158,12 @@ export class IndexedDBStorage implements StorageBackend {
2093
2158
  private async commit(batch: PersistenceBatch, committed?: CommittedTransaction): Promise<void> {
2094
2159
  if (this.committedMode !== !!committed)
2095
2160
  throw new Error("Committed storage requires a complete durable group");
2096
- const prepared = await preparePayloads(batch.data);
2161
+ const checkActive = () => {
2162
+ committed?.control.checkAbort();
2163
+ this.assertOwner();
2164
+ };
2165
+ const prepared = await preparePayloads(batch.data, true, checkActive);
2166
+ checkActive();
2097
2167
  const staged = stageChanges(this.state, batch),
2098
2168
  old = this.state;
2099
2169
  // A recovered generation may be reused. Its abandoned successors must not reconnect
@@ -2203,22 +2273,39 @@ export class IndexedDBStorage implements StorageBackend {
2203
2273
  abort(error);
2204
2274
  }
2205
2275
  };
2206
- let remaining = checking.size + pinChecks.size + (committed ? 2 : 0);
2276
+ const newKeys: string[] = [];
2277
+ const verifyKeys: string[] = [];
2278
+ for (const key of checking) {
2279
+ if (prepared.has(key) && !old?.payloadKeys.has(key)) newKeys.push(key);
2280
+ else verifyKeys.push(key);
2281
+ }
2282
+ let remaining = 1 + verifyKeys.length + pinChecks.size + (committed ? 1 : 0);
2207
2283
  const checked = () => {
2208
2284
  if (--remaining === 0) finish();
2209
2285
  };
2210
2286
  const checkEpoch = tx.objectStore("metadata").get("epoch");
2287
+ this.witnessEpoch(tx, checkEpoch);
2211
2288
  checkEpoch.onsuccess = () => {
2212
2289
  if (checkEpoch.result !== this.epoch) {
2213
2290
  abort(this.loseOwnership());
2214
2291
  return;
2215
2292
  }
2216
- if (committed) checked();
2293
+ try {
2294
+ for (const key of newKeys) {
2295
+ const supplied = prepared.get(key)!;
2296
+ const size = expected.get(key);
2297
+ if (size !== undefined && supplied.manifest.size !== size)
2298
+ throw new Error(`Invalid filesystem payload size: ${key}`);
2299
+ putPayload(data, key, supplied);
2300
+ }
2301
+ checked();
2302
+ } catch (error) {
2303
+ abort(error);
2304
+ }
2217
2305
  };
2218
2306
  if (committed) checkCommitHead(tx, committed, checked, abort);
2219
2307
  try {
2220
- if (!remaining) finish();
2221
- for (const key of checking) {
2308
+ for (const key of verifyKeys) {
2222
2309
  const get = data.get(key);
2223
2310
  get.onsuccess = () => {
2224
2311
  try {
package/fs/memory.ts CHANGED
@@ -6,7 +6,9 @@ import {
6
6
  permissionsFor,
7
7
  FilesystemError,
8
8
  fileTimeNow,
9
+ PROBE_PATH_LIMIT,
9
10
  type FileTime,
11
+ type ProbeKind,
10
12
  type SocketBinding,
11
13
  } from "../core/filesystem.js";
12
14
  import {
@@ -618,6 +620,22 @@ export class MemFS implements FileSystem {
618
620
  if (resolved.node.kind === "dir") return this.pathOf(resolved.node);
619
621
  return joinBelow(this.pathOf(resolved.parent!), "/" + resolved.name);
620
622
  }
623
+ /** The index of the first of `paths` naming a `kind` node, each walked from `directory` with
624
+ * every link followed, as a stat with the follow flag would; -1 when none does. A path that
625
+ * fails to resolve (missing, ENOTDIR, ELOOP, EACCES, an escape or an absolute path) does not
626
+ * match. Only the start directory can fail the call. */
627
+ probe(directory: FileHandle, paths: readonly string[], kind: ProbeKind, rooted = false): number {
628
+ if (paths.length > PROBE_PATH_LIMIT) throw new FilesystemError(28);
629
+ const start = this.directory(directory);
630
+ const wanted = kind === "directory" ? "dir" : "file";
631
+ for (let index = 0; index < paths.length; index++) {
632
+ const path = paths[index]!;
633
+ if (path.startsWith("/")) continue;
634
+ const resolved = this.walkNodes(start, path, false, true, undefined, rooted);
635
+ if (typeof resolved !== "number" && resolved.node?.kind === wanted) return index;
636
+ }
637
+ return -1;
638
+ }
621
639
  /** The absolute path of a live directory, by its parent edges up to the root. */
622
640
  private pathOf(dir: DirNode): string | number {
623
641
  const names: string[] = [];