@waffle-os/runtime 0.0.154 → 0.0.155

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/fs/guest-watch.ts CHANGED
@@ -1,10 +1,16 @@
1
- import { FilesystemError, type FileHandle, type WatchFileSystem } from "../core/filesystem.js";
2
- import type { WatchBatch, WatchEvent } from "./watch.js";
1
+ import {
2
+ FilesystemError,
3
+ type FileHandle,
4
+ type WatchDrainResult,
5
+ type WatchFileSystem,
6
+ } from "../core/filesystem.js";
7
+ import type { WatchBatch } from "./watch.js";
3
8
  import {
4
9
  arrayAppend,
5
10
  atomicsLoad,
6
11
  MapConstructor,
7
12
  mapDelete,
13
+ mapFirst,
8
14
  mapForEach,
9
15
  mapGet,
10
16
  mapSet,
@@ -15,6 +21,7 @@ import {
15
21
  const EAGAIN = 6;
16
22
  const EBADF = 8;
17
23
  const ECANCELED = 11;
24
+ const ENOTSUP = 58;
18
25
  const CHANGE = 1;
19
26
  const RENAME = 2;
20
27
  const OVERFLOW = 3;
@@ -33,179 +40,368 @@ export interface GuestWatchReadiness {
33
40
  }
34
41
 
35
42
  export type GuestWatchRead =
36
- /** Whole records in order; no records means end of stream. */
37
43
  | { readonly kind: "records"; readonly records: readonly Uint8Array[]; readonly length: number }
38
- /** The first pending record needs `needed` bytes. Nothing was consumed. */
39
44
  | { readonly kind: "short"; readonly needed: number }
40
45
  | { readonly kind: "error"; readonly errno: number };
41
46
 
47
+ export type GuestWatchNext =
48
+ | {
49
+ readonly kind: "records";
50
+ readonly id: number;
51
+ readonly records: readonly Uint8Array[];
52
+ readonly length: number;
53
+ }
54
+ | { readonly kind: "short"; readonly id: number; readonly needed: number }
55
+ | { readonly kind: "watch_error"; readonly id: number; readonly errno: number }
56
+ | { readonly kind: "error"; readonly errno: number };
57
+
42
58
  interface Watch {
59
+ readonly id: number;
43
60
  readonly service: number;
44
- /** cells[3] before this watch's latest service read, or before its open RPC. */
45
61
  observed: number;
46
- /** Encoded records of at most one service batch, consumed from `head`. */
47
62
  queue: Uint8Array[];
48
63
  head: number;
49
64
  ended: boolean;
65
+ errno: number;
50
66
  }
51
67
 
52
68
  const END: GuestWatchRead = { kind: "records", records: [], length: 0 };
53
69
 
54
- function failure(errno: number): GuestWatchRead {
70
+ function failure(errno: number): { readonly kind: "error"; readonly errno: number } {
55
71
  return { kind: "error", errno };
56
72
  }
57
73
 
74
+ function watchError(id: number, errno: number): GuestWatchNext {
75
+ return { kind: "watch_error", id, errno };
76
+ }
77
+
78
+ function nextOf(id: number, result: GuestWatchRead): GuestWatchNext {
79
+ return result.kind === "error" ? watchError(id, result.errno) : { ...result, id };
80
+ }
81
+
82
+ function rotate(map: Map<number, Watch>, watch: Watch): void {
83
+ mapDelete(map, watch.id);
84
+ mapSet(map, watch.id, watch);
85
+ }
86
+
58
87
  /** Process-local watch ids over the opener's filesystem session. Ids are never reused. */
59
88
  export class GuestWatchTable implements GuestWatchReadiness {
60
- private watches = new MapConstructor<number, Watch>();
61
- private nextId = 1;
62
- private revocationNotified = false;
89
+ #fs: WatchFileSystem;
90
+ #watches!: Map<number, Watch>;
91
+ #byService!: Map<number, Watch>;
92
+ #buffered!: Map<number, Watch>;
93
+ #errored!: Map<number, Watch>;
94
+ #ended!: Map<number, Watch>;
95
+ #nextId = 1;
96
+ #revocationNotified = false;
97
+ #activeCount = 0;
98
+ #observedGen = 0;
99
+ #observedCount = 0;
100
+ #tableObserved: number | undefined;
101
+ #drainMore = false;
102
+ #noDrain = false;
103
+ #flip = false;
63
104
 
64
- constructor(private readonly fs: WatchFileSystem) {}
105
+ constructor(fs: WatchFileSystem) {
106
+ this.#fs = fs;
107
+ this.drop();
108
+ }
65
109
 
66
110
  get word(): Int32Array {
67
- return this.fs.cells;
111
+ return this.#fs.cells;
68
112
  }
69
113
 
70
114
  get active(): boolean {
71
- let active = false;
72
- mapForEach(this.watches, (watch) => {
73
- if (!watch.ended) active = true;
74
- });
75
- return active;
115
+ return this.#activeCount > 0;
116
+ }
117
+
118
+ #useDrain(): boolean {
119
+ if (typeof this.#fs.drain !== "function" || this.#noDrain) return false;
120
+ if (this.#fs.canDrain === false) {
121
+ this.#tableObserved = undefined;
122
+ this.#drainMore = false;
123
+ return false;
124
+ }
125
+ return true;
126
+ }
127
+
128
+ #allObserved(generation: number): boolean {
129
+ return (
130
+ (this.#observedCount === this.#activeCount && this.#observedGen === generation) ||
131
+ (this.#useDrain() && !this.#drainMore && this.#tableObserved === generation)
132
+ );
76
133
  }
77
134
 
78
135
  pending(): boolean {
79
- if (this.fs.revoked) return !!this.fs.remote && !this.revocationNotified && this.active;
80
- return this.hasPending(false);
136
+ if (this.#fs.revoked)
137
+ return !!this.#fs.remote && !this.#revocationNotified && this.#activeCount > 0;
138
+ return (
139
+ this.#activeCount > 0 &&
140
+ (mapSize(this.#buffered) > 0 ||
141
+ mapSize(this.#errored) > 0 ||
142
+ !this.#allObserved(atomicsLoad(this.#fs.cells, 3)))
143
+ );
81
144
  }
82
145
 
83
146
  /** A read may return records, end or an error; never consumes watch state. */
84
147
  ready(): boolean {
85
- if (!mapSize(this.watches)) return false;
86
- return this.fs.revoked || this.hasPending(true);
87
- }
88
-
89
- private hasPending(includeEnded: boolean): boolean {
90
- const generation = atomicsLoad(this.fs.cells, 3);
91
- let pending = false;
92
- mapForEach(this.watches, (watch) => {
93
- if (
94
- watch.ended
95
- ? includeEnded
96
- : watch.head < watch.queue.length || watch.observed !== generation
97
- )
98
- pending = true;
99
- });
100
- return pending;
148
+ if (!mapSize(this.#watches)) return false;
149
+ return (
150
+ this.#fs.revoked ||
151
+ mapSize(this.#buffered) > 0 ||
152
+ mapSize(this.#errored) > 0 ||
153
+ mapSize(this.#ended) > 0 ||
154
+ (this.#activeCount > 0 && !this.#allObserved(atomicsLoad(this.#fs.cells, 3)))
155
+ );
156
+ }
157
+
158
+ #setObserved(watch: Watch, generation: number): void {
159
+ if (watch.observed === generation) return;
160
+ if (!watch.ended) {
161
+ if (watch.observed === this.#observedGen) this.#observedCount--;
162
+ if (generation !== this.#observedGen) {
163
+ this.#observedGen = generation;
164
+ this.#observedCount = 1;
165
+ } else this.#observedCount++;
166
+ }
167
+ watch.observed = generation;
168
+ }
169
+
170
+ #markEnded(watch: Watch): void {
171
+ if (watch.ended) return;
172
+ watch.ended = true;
173
+ this.#activeCount--;
174
+ if (watch.observed === this.#observedGen) this.#observedCount--;
175
+ watch.errno = 0;
176
+ mapDelete(this.#buffered, watch.id);
177
+ mapDelete(this.#errored, watch.id);
178
+ mapSet(this.#ended, watch.id, watch);
101
179
  }
102
180
 
103
181
  /** Throws FilesystemError from the service. */
104
182
  open(handle: FileHandle, recursive: boolean): number {
105
- if (this.nextId > LAST_ID) throw new FilesystemError(EAGAIN, "watch ids exhausted");
106
- // Sampled before the RPC: a commit after the service activates the subscription must
107
- // move the counter past this value, so the first read cannot skip its service call.
108
- const observed = atomicsLoad(this.fs.cells, 3);
109
- const service = this.fs.open(handle, recursive);
110
- const id = this.nextId++;
111
- mapSet(this.watches, id, { service, observed, queue: [], head: 0, ended: false });
183
+ if (this.#nextId > LAST_ID) throw new FilesystemError(EAGAIN, "watch ids exhausted");
184
+ const observed = atomicsLoad(this.#fs.cells, 3);
185
+ const service = this.#fs.open(handle, recursive);
186
+ const id = this.#nextId++;
187
+ const watch: Watch = { id, service, observed: NaN, queue: [], head: 0, ended: false, errno: 0 };
188
+ mapSet(this.#watches, id, watch);
189
+ mapSet(this.#byService, service, watch);
190
+ this.#activeCount++;
191
+ this.#setObserved(watch, observed);
112
192
  return id;
113
193
  }
114
194
 
115
- /** Throws FilesystemError when the service read fails. */
195
+ /** Scoped to `id`; never drains other watches. Throws FilesystemError when the service read fails. */
116
196
  read(id: number, capacity: number): GuestWatchRead {
117
- const watch = mapGet(this.watches, id);
197
+ const watch = mapGet(this.#watches, id);
118
198
  if (!watch) return failure(EBADF);
119
199
  if (watch.ended) return END;
120
- if (watch.head === watch.queue.length) {
121
- const refused = this.refill(watch);
122
- if (refused) return refused;
200
+ if (watch.head < watch.queue.length) return this.#takeFrom(watch, capacity);
201
+ const force = watch.errno !== 0;
202
+ if (force) {
203
+ watch.errno = 0;
204
+ mapDelete(this.#errored, id);
123
205
  }
124
- return take(watch, capacity);
206
+ return this.#refillSingle(watch, force) ?? this.#takeFrom(watch, capacity);
207
+ }
208
+
209
+ /** Read the next ready watch without scanning idle ones. Returns EAGAIN when nothing is ready. */
210
+ readNext(capacity: number): GuestWatchNext {
211
+ if (!mapSize(this.#watches)) return failure(EAGAIN);
212
+ if (this.#fs.revoked) {
213
+ if (this.#fs.remote) this.#revocationNotified = true;
214
+ const first = mapFirst(this.#watches)!;
215
+ rotate(this.#watches, first);
216
+ return watchError(first.id, ECANCELED);
217
+ }
218
+ if (
219
+ this.#useDrain() &&
220
+ (mapSize(this.#buffered) || mapSize(this.#errored) || !this.#drainService())
221
+ )
222
+ return this.#takeNextReady(capacity);
223
+ return this.#readNextFallback(capacity);
224
+ }
225
+
226
+ #takeNextReady(capacity: number): GuestWatchNext {
227
+ const buffered = mapFirst(this.#buffered);
228
+ if (buffered) {
229
+ const read = this.#takeFrom(buffered, capacity);
230
+ if (buffered.head < buffered.queue.length) rotate(this.#buffered, buffered);
231
+ return nextOf(buffered.id, read);
232
+ }
233
+ const ended = mapFirst(this.#ended);
234
+ const errored = mapFirst(this.#errored);
235
+ const pick = this.#flip ? (ended ?? errored) : (errored ?? ended);
236
+ if (!pick) return failure(EAGAIN);
237
+ this.#flip = !pick.ended;
238
+ if (pick.ended) {
239
+ rotate(this.#ended, pick);
240
+ return nextOf(pick.id, END);
241
+ }
242
+ const errno = pick.errno;
243
+ pick.errno = 0;
244
+ if (pick.observed === this.#observedGen) this.#observedCount--;
245
+ pick.observed = NaN;
246
+ this.#drainMore = true;
247
+ mapDelete(this.#errored, pick.id);
248
+ return watchError(pick.id, errno);
249
+ }
250
+
251
+ #readNextFallback(capacity: number): GuestWatchNext {
252
+ let result: GuestWatchNext | undefined;
253
+ let reported: Watch | undefined;
254
+ mapForEach(this.#watches, (watch) => {
255
+ if (result) return;
256
+ try {
257
+ const read = this.read(watch.id, capacity);
258
+ if (read.kind !== "error" || read.errno !== EAGAIN) {
259
+ result = nextOf(watch.id, read);
260
+ reported = watch;
261
+ }
262
+ } catch (error) {
263
+ if (!(error instanceof FilesystemError)) throw error;
264
+ result = watchError(watch.id, error.errno);
265
+ reported = watch;
266
+ }
267
+ });
268
+ if (reported) rotate(this.#watches, reported);
269
+ return result ?? failure(EAGAIN);
125
270
  }
126
271
 
127
272
  /** Throws FilesystemError when the service close fails; the id then stays open for a retry. */
128
273
  close(id: number): number {
129
- const watch = mapGet(this.watches, id);
274
+ const watch = mapGet(this.#watches, id);
130
275
  if (!watch) return EBADF;
131
- if (!this.fs.revoked) this.closeService(watch.service);
132
- mapDelete(this.watches, id);
133
- return 0;
134
- }
135
-
136
- private closeService(service: number): void {
137
- try {
138
- this.fs.close(service);
139
- } catch (error) {
140
- // Revoked meanwhile: the session's close releases the subscription.
141
- if (!(error instanceof FilesystemError) || error.errno !== ECANCELED) throw error;
276
+ if (!this.#fs.revoked) {
277
+ try {
278
+ this.#fs.close(watch.service);
279
+ } catch (error) {
280
+ if (!(error instanceof FilesystemError) || error.errno !== ECANCELED) throw error;
281
+ }
282
+ }
283
+ if (!watch.ended) {
284
+ this.#activeCount--;
285
+ if (watch.observed === this.#observedGen) this.#observedCount--;
286
+ }
287
+ mapDelete(this.#buffered, id);
288
+ mapDelete(this.#errored, id);
289
+ mapDelete(this.#ended, id);
290
+ mapDelete(this.#watches, id);
291
+ mapDelete(this.#byService, watch.service);
292
+ if (!mapSize(this.#watches)) {
293
+ this.#tableObserved = undefined;
294
+ this.#drainMore = false;
142
295
  }
296
+ return 0;
143
297
  }
144
298
 
145
299
  /** Forget every id without service calls; the session's close releases subscriptions. */
146
300
  drop(): void {
147
- this.watches = new MapConstructor();
301
+ this.#watches = new MapConstructor();
302
+ this.#byService = new MapConstructor();
303
+ this.#buffered = new MapConstructor();
304
+ this.#errored = new MapConstructor();
305
+ this.#ended = new MapConstructor();
306
+ this.#activeCount = this.#observedCount = 0;
307
+ this.#tableObserved = undefined;
308
+ this.#drainMore = false;
148
309
  }
149
310
 
150
- private refill(watch: Watch): GuestWatchRead | undefined {
151
- if (this.fs.revoked) {
152
- if (this.fs.remote) this.revocationNotified = true;
153
- return failure(ECANCELED);
311
+ #applyBatch(watch: Watch, batch: WatchBatch, generation: number): boolean {
312
+ if (batch.kind === "closed") {
313
+ this.#markEnded(watch);
314
+ return true;
154
315
  }
155
- const generation = atomicsLoad(this.fs.cells, 3);
156
- if (!this.fs.remote && generation === watch.observed) return failure(EAGAIN);
157
- // Set before the call: a commit after the service drains moves the counter again. A failed
158
- // call drained nothing, so the watch stays pending for the retry.
159
- const previous = watch.observed;
160
- watch.observed = generation;
161
- let batch: WatchBatch;
316
+ this.#setObserved(watch, generation);
317
+ watch.queue = encodeBatch(batch);
318
+ watch.head = 0;
319
+ if (watch.queue.length) mapSet(this.#buffered, watch.id, watch);
320
+ return false;
321
+ }
322
+
323
+ /** Drain ready watches in one service RPC. Returns true if drain is unsupported. */
324
+ #drainService(): boolean {
325
+ const generation = atomicsLoad(this.#fs.cells, 3);
326
+ if (!this.#drainMore && this.#allObserved(generation)) return false;
327
+ const previous = this.#tableObserved;
328
+ this.#tableObserved = generation;
329
+ let drained: WatchDrainResult;
162
330
  try {
163
- batch = this.fs.read(watch.service);
331
+ drained = this.#fs.drain!();
164
332
  } catch (error) {
165
- watch.observed = previous;
333
+ if (error instanceof FilesystemError && error.errno === ENOTSUP) {
334
+ this.#tableObserved = undefined;
335
+ this.#drainMore = false;
336
+ if (this.#fs.canDrain === undefined) this.#noDrain = true;
337
+ return true;
338
+ }
339
+ this.#tableObserved = previous;
166
340
  throw error;
167
341
  }
168
- if (batch.kind === "closed") {
169
- watch.ended = true;
170
- return END;
342
+ this.#drainMore = drained.more;
343
+ for (let index = 0; index < drained.entries.length; index++) {
344
+ const entry = drained.entries[index]!;
345
+ const watch = mapGet(this.#byService, entry.id);
346
+ if (!watch || watch.ended) continue;
347
+ if ("errno" in entry) {
348
+ watch.errno = entry.errno;
349
+ mapSet(this.#errored, watch.id, watch);
350
+ } else {
351
+ this.#applyBatch(watch, entry.batch, generation);
352
+ }
171
353
  }
172
- watch.queue = encodeBatch(batch);
173
- watch.head = 0;
354
+ return false;
355
+ }
356
+
357
+ #refillSingle(watch: Watch, force: boolean): GuestWatchRead | undefined {
358
+ if (this.#fs.revoked) {
359
+ if (this.#fs.remote) this.#revocationNotified = true;
360
+ return failure(ECANCELED);
361
+ }
362
+ const generation = atomicsLoad(this.#fs.cells, 3);
363
+ if (
364
+ !force &&
365
+ !this.#fs.remote &&
366
+ (generation === watch.observed ||
367
+ (this.#useDrain() && !this.#drainMore && generation === this.#tableObserved))
368
+ )
369
+ return failure(EAGAIN);
370
+ if (this.#applyBatch(watch, this.#fs.read(watch.service), generation)) return END;
174
371
  if (!watch.queue.length) return failure(EAGAIN);
175
372
  }
176
- }
177
373
 
178
- function take(watch: Watch, capacity: number): GuestWatchRead {
179
- const records: Uint8Array[] = [];
180
- let length = 0;
181
- while (watch.head < watch.queue.length) {
182
- const record = watch.queue[watch.head]!;
183
- if (length + record.length > capacity) break;
184
- arrayAppend(records, record);
185
- length += record.length;
186
- watch.head++;
187
- if (record[0] === OVERFLOW) watch.ended = true;
188
- }
189
- if (!length) return { kind: "short", needed: watch.queue[watch.head]!.length };
190
- if (watch.head === watch.queue.length) {
191
- watch.queue = [];
192
- watch.head = 0;
374
+ #takeFrom(watch: Watch, capacity: number): GuestWatchRead {
375
+ const records: Uint8Array[] = [];
376
+ let length = 0;
377
+ while (watch.head < watch.queue.length) {
378
+ const record = watch.queue[watch.head]!;
379
+ if (length + record.length > capacity) break;
380
+ arrayAppend(records, record);
381
+ length += record.length;
382
+ watch.head++;
383
+ if (record[0] === OVERFLOW) this.#markEnded(watch);
384
+ }
385
+ if (!length) return { kind: "short", needed: watch.queue[watch.head]!.length };
386
+ if (watch.head === watch.queue.length) {
387
+ watch.queue = [];
388
+ watch.head = 0;
389
+ mapDelete(this.#buffered, watch.id);
390
+ }
391
+ return { kind: "records", records, length };
193
392
  }
194
- return { kind: "records", records, length };
195
393
  }
196
394
 
197
395
  function encodeBatch(batch: Exclude<WatchBatch, { kind: "closed" }>): Uint8Array[] {
198
396
  if (batch.kind === "overflow") return [encodeRecord(OVERFLOW, null)];
199
397
  const records: Uint8Array[] = [];
200
- for (let index = 0; index < batch.events.length; index++)
201
- arrayAppend(records, encodeEvent(batch.events[index]!));
398
+ for (let index = 0; index < batch.events.length; index++) {
399
+ const event = batch.events[index]!;
400
+ arrayAppend(records, encodeRecord(event.type === "change" ? CHANGE : RENAME, event.name));
401
+ }
202
402
  return records;
203
403
  }
204
404
 
205
- function encodeEvent(event: WatchEvent): Uint8Array {
206
- return encodeRecord(event.type === "change" ? CHANGE : RENAME, event.name);
207
- }
208
-
209
405
  /** u8 type, three zero bytes, u32le name length or NULL_NAME, UTF-8 name padded to 4. */
210
406
  function encodeRecord(type: number, name: string | null): Uint8Array {
211
407
  const bytes = name === null ? undefined : encoder.encode(name);
@@ -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(