@waffle-os/runtime 0.0.153 → 0.0.154
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/browser/net/helper.ts +114 -19
- package/browser/net/ring.ts +18 -6
- package/browser/net/runtime.ts +2 -2
- package/browser/notification-relay.ts +105 -18
- package/browser/notification-wait.ts +45 -4
- package/browser/notification-worker.ts +169 -76
- package/browser/preview.ts +15 -2
- package/core/filesystem.ts +4 -0
- package/core/wasi.ts +49 -0
- package/dist/browser/net/helper.js +83 -18
- package/dist/browser/net/ring.js +6 -5
- package/dist/browser/net/runtime.js +2 -2
- package/dist/browser/notification-relay.js +78 -15
- package/dist/browser/notification-wait.js +37 -5
- package/dist/browser/notification-worker.js +146 -67
- package/dist/core/wasi.js +40 -0
- package/dist/fs/backend.js +7 -0
- package/dist/fs/client.js +69 -15
- package/dist/fs/dirty-admission.js +15 -8
- package/dist/fs/indexeddb.js +288 -96
- package/dist/fs/memory.js +106 -20
- package/dist/fs/multitab-backend.js +121 -37
- package/dist/fs/multitab-protocol.js +1 -0
- package/dist/fs/persistent.js +70 -16
- package/dist/fs/protocol.js +15 -7
- package/dist/fs/publication-attachment.js +9 -7
- package/dist/fs/service.js +34 -9
- package/dist/fs/shared.js +96 -6
- package/dist/proc/command-stdio.js +1 -1
- package/dist/tooling/program/program-transformer.json +1 -1
- package/fs/backend.ts +11 -0
- package/fs/client.ts +93 -16
- package/fs/dirty-admission.ts +22 -7
- package/fs/guest-watch.ts +1 -1
- package/fs/indexeddb.ts +379 -110
- package/fs/memory.ts +120 -19
- package/fs/multitab-backend.ts +206 -61
- package/fs/multitab-protocol.ts +1 -0
- package/fs/persistent.ts +82 -16
- package/fs/protocol.ts +26 -7
- package/fs/publication-attachment.ts +9 -7
- package/fs/service.ts +35 -7
- package/fs/shared.ts +106 -8
- package/package.json +1 -1
- package/proc/command-stdio.ts +1 -1
- package/testing/idle-workspace-cancellation-browser.ts +22 -13
- package/testing/indexeddb-storage-browser.ts +435 -1
- package/tooling/program/program-transformer.json +1 -1
package/fs/indexeddb.ts
CHANGED
|
@@ -422,8 +422,34 @@ interface State extends TreeState {
|
|
|
422
422
|
journals: Map<number, Journal>;
|
|
423
423
|
journalKeys: IDBValidKey[];
|
|
424
424
|
payloadKeys: Set<string>;
|
|
425
|
+
/** Payload sizes named by `nodes`, `bases` and `journals`, kept with every change to them. */
|
|
426
|
+
payloadSizes: PayloadSizes;
|
|
425
427
|
sinceCompaction: number;
|
|
426
428
|
}
|
|
429
|
+
/** The size of each payload that a node of the current tree, a recovery base or a kept journal
|
|
430
|
+
* names, counted per naming node so a lookup never scans the tree. Validation keeps every node
|
|
431
|
+
* naming one key at the size of its stored manifest. */
|
|
432
|
+
class PayloadSizes {
|
|
433
|
+
private readonly entries = new Map<string, { size: number; count: number }>();
|
|
434
|
+
add(nodes: Iterable<PersistedNode>): void {
|
|
435
|
+
for (const node of nodes) {
|
|
436
|
+
if (node.data === undefined) continue;
|
|
437
|
+
const entry = this.entries.get(node.data);
|
|
438
|
+
if (entry) entry.count++;
|
|
439
|
+
else this.entries.set(node.data, { size: node.size, count: 1 });
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
remove(nodes: Iterable<PersistedNode>): void {
|
|
443
|
+
for (const node of nodes) {
|
|
444
|
+
if (node.data === undefined) continue;
|
|
445
|
+
const entry = this.entries.get(node.data);
|
|
446
|
+
if (entry && --entry.count === 0) this.entries.delete(node.data);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
size(key: string): number | undefined {
|
|
450
|
+
return this.entries.get(key)?.size;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
427
453
|
interface CommittedTransaction {
|
|
428
454
|
group: PreparedDurableGroup;
|
|
429
455
|
envelope: CommitEnvelope;
|
|
@@ -527,12 +553,187 @@ function request<T>(value: IDBRequest<T>): Promise<T> {
|
|
|
527
553
|
void result.catch(() => {});
|
|
528
554
|
return result;
|
|
529
555
|
}
|
|
556
|
+
/** Every string key in the data store, which in chunked formats names a payload manifest. Keys
|
|
557
|
+
* order numbers, dates, strings, binary, arrays: the empty binary key is the least binary key, so
|
|
558
|
+
* values under invalid number, date or binary keys are never loaded. Layout validation still
|
|
559
|
+
* rejects those keys from the key listing. */
|
|
560
|
+
function manifestKeyRange(): IDBKeyRange {
|
|
561
|
+
return IDBKeyRange.bound("", new ArrayBuffer(0), false, true);
|
|
562
|
+
}
|
|
563
|
+
/** Pairs a bulk manifest read; each result is read once (see formatAndManifests). */
|
|
564
|
+
function pairManifests(
|
|
565
|
+
names: readonly IDBValidKey[],
|
|
566
|
+
records: readonly unknown[],
|
|
567
|
+
): Map<IDBValidKey, unknown> {
|
|
568
|
+
if (names.length !== records.length)
|
|
569
|
+
throw new VfsError("INVALID_VFS_FORMAT", "indexeddb", "Invalid payload manifests");
|
|
570
|
+
const manifests = new Map<IDBValidKey, unknown>();
|
|
571
|
+
for (const [index, key] of names.entries()) manifests.set(key, records[index]);
|
|
572
|
+
return manifests;
|
|
573
|
+
}
|
|
574
|
+
interface FormatRecords {
|
|
575
|
+
readonly format: unknown;
|
|
576
|
+
/** Manifest records by payload key, read only for chunked formats. */
|
|
577
|
+
readonly manifests?: ReadonlyMap<IDBValidKey, unknown>;
|
|
578
|
+
}
|
|
579
|
+
/** Reads the format and, for chunked formats, every manifest in the same snapshot. Legacy
|
|
580
|
+
* formats keep whole payloads at string keys, so those are never read here. */
|
|
581
|
+
function formatAndManifests(
|
|
582
|
+
metadata: IDBObjectStore,
|
|
583
|
+
data: IDBObjectStore,
|
|
584
|
+
): Promise<FormatRecords> {
|
|
585
|
+
return new Promise<FormatRecords>((resolve, reject) => {
|
|
586
|
+
const format = metadata.get("format");
|
|
587
|
+
format.onerror = requestFailed(format, reject);
|
|
588
|
+
format.onsuccess = () => {
|
|
589
|
+
if (format.result !== INDEXEDDB_FORMAT && format.result !== STAGED_FORMAT) {
|
|
590
|
+
resolve({ format: format.result });
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
// Placed from the format's success callback, so they read the same snapshot.
|
|
594
|
+
placeManifestReads(data, format.result, resolve, reject);
|
|
595
|
+
};
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
function requestFailed(failure: IDBRequest, reject: (error: unknown) => void): () => void {
|
|
599
|
+
return () => reject(failure.error ?? new Error("IndexedDB request failed"));
|
|
600
|
+
}
|
|
601
|
+
/** Requests complete in order, so the keys are ready when the values arrive. */
|
|
602
|
+
function placeManifestReads(
|
|
603
|
+
data: IDBObjectStore,
|
|
604
|
+
format: unknown,
|
|
605
|
+
resolve: (records: FormatRecords) => void,
|
|
606
|
+
reject: (error: unknown) => void,
|
|
607
|
+
): void {
|
|
608
|
+
const range = manifestKeyRange();
|
|
609
|
+
const keys = data.getAllKeys(range);
|
|
610
|
+
const values = data.getAll(range);
|
|
611
|
+
keys.onerror = requestFailed(keys, reject);
|
|
612
|
+
values.onerror = requestFailed(values, reject);
|
|
613
|
+
values.onsuccess = () => {
|
|
614
|
+
// Read each result once: WebKit builds a new array on every `result` access, which made an
|
|
615
|
+
// indexed loop over 17,000 manifests take 6.5 s.
|
|
616
|
+
try {
|
|
617
|
+
resolve({ format, manifests: pairManifests(keys.result, values.result) });
|
|
618
|
+
} catch (error) {
|
|
619
|
+
reject(error);
|
|
620
|
+
}
|
|
621
|
+
};
|
|
622
|
+
}
|
|
530
623
|
function completed(tx: IDBTransaction): Promise<void> {
|
|
531
624
|
return new Promise((resolve, reject) => {
|
|
532
625
|
tx.oncomplete = () => resolve();
|
|
533
626
|
tx.onabort = () => reject(tx.error ?? new Error("IndexedDB transaction aborted"));
|
|
534
627
|
});
|
|
535
628
|
}
|
|
629
|
+
interface ChunkCheck {
|
|
630
|
+
readonly bytes: Uint8Array<ArrayBuffer>;
|
|
631
|
+
readonly checksum: string;
|
|
632
|
+
}
|
|
633
|
+
/** One range read in progress: bytes copied as chunks arrive and the checksums still owed. */
|
|
634
|
+
interface PayloadRead {
|
|
635
|
+
readonly key: string;
|
|
636
|
+
readonly range: IndexedDBRange;
|
|
637
|
+
/** The payload size the read expects, when the caller or the index knows it. */
|
|
638
|
+
readonly expectedSize: number | undefined;
|
|
639
|
+
manifest?: ChunkManifest;
|
|
640
|
+
result?: Uint8Array<ArrayBuffer>;
|
|
641
|
+
/** End of the clamped range, and the next chunk index to request. */
|
|
642
|
+
end: number;
|
|
643
|
+
next: number;
|
|
644
|
+
readonly checks: ChunkCheck[];
|
|
645
|
+
/** Chunk requests placed and not yet answered. */
|
|
646
|
+
pending: number;
|
|
647
|
+
failure?: { cause: unknown };
|
|
648
|
+
/** Called once the manifest and every chunk have arrived. */
|
|
649
|
+
arrived: () => void;
|
|
650
|
+
fail: (error: unknown) => void;
|
|
651
|
+
}
|
|
652
|
+
function corruption<T>(parse: () => T, fallback: string): T {
|
|
653
|
+
try {
|
|
654
|
+
return parse();
|
|
655
|
+
} catch (error) {
|
|
656
|
+
throw new PayloadCorruption(error instanceof Error ? error.message : fallback);
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
/** Chunk gets one read keeps in flight. Each answer places the next from its success callback,
|
|
660
|
+
* so a large read stays one transaction without queueing every chunk at once. */
|
|
661
|
+
const CHUNK_READ_WINDOW = 16;
|
|
662
|
+
/** Starts the gets for every chunk the range touches in a payload of `size` bytes. */
|
|
663
|
+
function placeChunkReads(store: IDBObjectStore, size: number, read: PayloadRead): void {
|
|
664
|
+
const range = read.range;
|
|
665
|
+
const length = Math.max(0, Math.min(range.length, size - range.offset));
|
|
666
|
+
read.result = new Uint8Array(length);
|
|
667
|
+
read.end = range.offset + length;
|
|
668
|
+
read.next = Math.floor(range.offset / CHUNK_SIZE);
|
|
669
|
+
// An empty range, or one past the end, takes no byte from any chunk.
|
|
670
|
+
if (length) placeMoreChunks(store, read);
|
|
671
|
+
}
|
|
672
|
+
function placeMoreChunks(store: IDBObjectStore, read: PayloadRead): void {
|
|
673
|
+
while (read.pending < CHUNK_READ_WINDOW && read.next * CHUNK_SIZE < read.end)
|
|
674
|
+
placeChunk(store, read, read.next++);
|
|
675
|
+
}
|
|
676
|
+
function placeChunk(store: IDBObjectStore, read: PayloadRead, index: number): void {
|
|
677
|
+
read.pending++;
|
|
678
|
+
const get = store.get([read.key, index]);
|
|
679
|
+
get.onsuccess = () => {
|
|
680
|
+
try {
|
|
681
|
+
copyChunk(get.result, index, read);
|
|
682
|
+
read.pending--;
|
|
683
|
+
placeMoreChunks(store, read);
|
|
684
|
+
if (read.pending === 0 && read.manifest) read.arrived();
|
|
685
|
+
} catch (error) {
|
|
686
|
+
read.fail(error);
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
/** Runs first among the read's requests, which complete in the order they were placed. */
|
|
691
|
+
function acceptManifest(store: IDBObjectStore, value: unknown, read: PayloadRead): void {
|
|
692
|
+
const key = read.key;
|
|
693
|
+
if (value === undefined) throw new Error(`Missing filesystem payload: ${key}`);
|
|
694
|
+
const manifest = corruption(() => parseManifest(value, key), "Invalid payload manifest");
|
|
695
|
+
if (read.expectedSize !== undefined && manifest.size !== read.expectedSize)
|
|
696
|
+
throw new PayloadCorruption("Retained payload size mismatch");
|
|
697
|
+
read.manifest = manifest;
|
|
698
|
+
// Without a known size, the chunk requests wait for the manifest, still in this transaction.
|
|
699
|
+
if (read.expectedSize === undefined) placeChunkReads(store, manifest.size, read);
|
|
700
|
+
if (read.pending === 0) read.arrived();
|
|
701
|
+
}
|
|
702
|
+
/** Copies the chunk's part of the range now and keeps what its checksum covers. A chunk the
|
|
703
|
+
* range covers whole is checked from the copy, so only the two edge chunks stay alive. */
|
|
704
|
+
function copyChunk(record: unknown, index: number, read: PayloadRead): void {
|
|
705
|
+
const offset = read.range.offset;
|
|
706
|
+
const length = chunkLength(read.manifest!, index);
|
|
707
|
+
const chunk = corruption(() => parseChunk(record, length, read.key), "Invalid payload chunk");
|
|
708
|
+
const base = index * CHUNK_SIZE;
|
|
709
|
+
const start = Math.max(offset, base);
|
|
710
|
+
const stop = Math.min(read.end, base + length);
|
|
711
|
+
const result = read.result!;
|
|
712
|
+
result.set(chunk.bytes.subarray(start - base, stop - base), start - offset);
|
|
713
|
+
const whole = start === base && stop === base + length;
|
|
714
|
+
read.checks.push({
|
|
715
|
+
checksum: chunk.checksum,
|
|
716
|
+
bytes: whole ? result.subarray(start - offset, stop - offset) : chunk.bytes,
|
|
717
|
+
});
|
|
718
|
+
}
|
|
719
|
+
/** Digests run concurrently in small batches: digest() copies its input, so a batch bounds the
|
|
720
|
+
* extra memory while the browser overlaps the work. `admit` runs before each batch, so a read
|
|
721
|
+
* that lost its owner or its caller starts no further checksum work. */
|
|
722
|
+
const CHECKSUM_BATCH = 16;
|
|
723
|
+
async function verifyChecksums(
|
|
724
|
+
key: string,
|
|
725
|
+
checks: readonly ChunkCheck[],
|
|
726
|
+
admit: () => void,
|
|
727
|
+
): Promise<void> {
|
|
728
|
+
for (let start = 0; start < checks.length; start += CHECKSUM_BATCH) {
|
|
729
|
+
admit();
|
|
730
|
+
const batch = checks.slice(start, start + CHECKSUM_BATCH);
|
|
731
|
+
const digests = await Promise.all(batch.map((check) => chunkChecksum(check.bytes)));
|
|
732
|
+
if (digests.some((digest, index) => digest !== batch[index]!.checksum))
|
|
733
|
+
throw new PayloadCorruption(`Invalid filesystem payload chunks: ${key}`);
|
|
734
|
+
}
|
|
735
|
+
admit();
|
|
736
|
+
}
|
|
536
737
|
function payloads(nodes: Iterable<PersistedNode>, keys: Set<string>): void {
|
|
537
738
|
for (const node of nodes) if (node.data !== undefined) keys.add(node.data);
|
|
538
739
|
}
|
|
@@ -546,6 +747,42 @@ function recoveryManifest(value: unknown, key: string): ChunkManifest | undefine
|
|
|
546
747
|
return undefined;
|
|
547
748
|
}
|
|
548
749
|
}
|
|
750
|
+
/** Manifests whose chunk keys are exactly 0 to count - 1. `records` holds every manifest record
|
|
751
|
+
* read in the same snapshot as `keys`. */
|
|
752
|
+
function validateChunks(
|
|
753
|
+
keys: readonly IDBValidKey[],
|
|
754
|
+
records: ReadonlyMap<IDBValidKey, unknown>,
|
|
755
|
+
): Map<string, ChunkManifest> {
|
|
756
|
+
const manifests = new Map<string, ChunkManifest>();
|
|
757
|
+
const chunks = new Map<string, Set<number>>();
|
|
758
|
+
for (const key of keys) {
|
|
759
|
+
if (typeof key === "string") {
|
|
760
|
+
const manifest = recoveryManifest(records.get(key), key);
|
|
761
|
+
if (manifest) manifests.set(key, manifest);
|
|
762
|
+
continue;
|
|
763
|
+
}
|
|
764
|
+
if (
|
|
765
|
+
!Array.isArray(key) ||
|
|
766
|
+
key.length !== 2 ||
|
|
767
|
+
typeof key[0] !== "string" ||
|
|
768
|
+
!validInteger(key[1])
|
|
769
|
+
)
|
|
770
|
+
chunkError(String(key));
|
|
771
|
+
const indices = chunks.get(key[0]) ?? new Set<number>();
|
|
772
|
+
indices.add(key[1]);
|
|
773
|
+
chunks.set(key[0], indices);
|
|
774
|
+
}
|
|
775
|
+
for (const [key, manifest] of manifests) {
|
|
776
|
+
const indices = chunks.get(key);
|
|
777
|
+
if ((indices?.size ?? 0) !== manifest.count) {
|
|
778
|
+
manifests.delete(key);
|
|
779
|
+
continue;
|
|
780
|
+
}
|
|
781
|
+
if (indices && Array.from(indices).some((index) => index >= manifest.count))
|
|
782
|
+
manifests.delete(key);
|
|
783
|
+
}
|
|
784
|
+
return manifests;
|
|
785
|
+
}
|
|
549
786
|
function referenceIndex(nodes: Iterable<PersistedNode>): Pick<State, "references" | "parents"> {
|
|
550
787
|
const references = new Map<number, number>(),
|
|
551
788
|
parents = new Map<number, number>();
|
|
@@ -729,6 +966,29 @@ function applyChanges(
|
|
|
729
966
|
state.publication = selection.publication;
|
|
730
967
|
}
|
|
731
968
|
|
|
969
|
+
/** Moves payload sizes from the nodes a commit replaces or removes to the ones it writes. */
|
|
970
|
+
function replaceNodes(state: State, staged: StagedChanges): void {
|
|
971
|
+
for (const ino of Array.from(staged.removes).concat(Array.from(staged.upserts.keys()))) {
|
|
972
|
+
const previous = state.nodes.get(ino);
|
|
973
|
+
if (previous) state.payloadSizes.remove([previous]);
|
|
974
|
+
}
|
|
975
|
+
state.payloadSizes.add(staged.upserts.values());
|
|
976
|
+
}
|
|
977
|
+
function installBases(state: State, bases: State["bases"]): void {
|
|
978
|
+
for (const slot of [0, 1] as const) {
|
|
979
|
+
if (state.bases[slot] === bases[slot]) continue;
|
|
980
|
+
state.payloadSizes.remove(state.bases[slot]?.nodes ?? []);
|
|
981
|
+
state.payloadSizes.add(bases[slot]?.nodes ?? []);
|
|
982
|
+
}
|
|
983
|
+
state.bases = bases;
|
|
984
|
+
}
|
|
985
|
+
function dropJournal(state: State, generation: number): void {
|
|
986
|
+
const journal = state.journals.get(generation);
|
|
987
|
+
if (!journal) return;
|
|
988
|
+
state.journals.delete(generation);
|
|
989
|
+
state.payloadSizes.remove(journal.upserts);
|
|
990
|
+
}
|
|
991
|
+
|
|
732
992
|
/** Recover newest-first, copying the full tree only for a candidate with a complete chain. */
|
|
733
993
|
export function recoverIndex(
|
|
734
994
|
bases: readonly (PersistedIndex | undefined)[],
|
|
@@ -785,6 +1045,8 @@ export class IndexedDBStorage implements StorageBackend {
|
|
|
785
1045
|
private tail: Promise<void> = Promise.resolve();
|
|
786
1046
|
private readonly readers = new PayloadRetentions();
|
|
787
1047
|
private readonly readerWork = new Set<Promise<unknown>>();
|
|
1048
|
+
/** Read transactions whose bytes may already be returned but which have not settled. */
|
|
1049
|
+
private readonly nativeReads = new Set<Promise<void>>();
|
|
788
1050
|
private readonly deletingPayloads = new Set<string>();
|
|
789
1051
|
private persistenceError: unknown;
|
|
790
1052
|
private initialized = false;
|
|
@@ -1149,9 +1411,9 @@ export class IndexedDBStorage implements StorageBackend {
|
|
|
1149
1411
|
} catch {}
|
|
1150
1412
|
}
|
|
1151
1413
|
this.db.close();
|
|
1152
|
-
this.ownershipRetirement = Promise.allSettled(
|
|
1153
|
-
|
|
1154
|
-
|
|
1414
|
+
this.ownershipRetirement = Promise.allSettled(Array.from(this.readerWork).concat([this.tail]))
|
|
1415
|
+
.then(() => this.joinNativeReads())
|
|
1416
|
+
.then(() => this.retireMaintenance());
|
|
1155
1417
|
void this.ownershipRetirement.catch(() => {});
|
|
1156
1418
|
this.onOwnershipLost?.();
|
|
1157
1419
|
return error;
|
|
@@ -1225,10 +1487,16 @@ export class IndexedDBStorage implements StorageBackend {
|
|
|
1225
1487
|
const value = await this.readRecord(key, signal);
|
|
1226
1488
|
if (!(value instanceof Uint8Array)) chunkError(key);
|
|
1227
1489
|
if (value.length !== this.payloadSize(key)) chunkError(key);
|
|
1490
|
+
// readRecord awaits its transaction again after its own check.
|
|
1491
|
+
signal?.throwIfAborted();
|
|
1492
|
+
this.assertOwner();
|
|
1228
1493
|
return value;
|
|
1229
1494
|
}
|
|
1230
|
-
|
|
1231
|
-
|
|
1495
|
+
return this.readPayload(
|
|
1496
|
+
key,
|
|
1497
|
+
{ offset: 0, length: Number.MAX_SAFE_INTEGER, signal },
|
|
1498
|
+
this.knownSize(key),
|
|
1499
|
+
);
|
|
1232
1500
|
});
|
|
1233
1501
|
}
|
|
1234
1502
|
|
|
@@ -1251,27 +1519,22 @@ export class IndexedDBStorage implements StorageBackend {
|
|
|
1251
1519
|
throw new Error("Missing retained filesystem payload");
|
|
1252
1520
|
}
|
|
1253
1521
|
private payloadSize(key: string): number | undefined {
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
}
|
|
1260
|
-
for (const journal of this.state!.journals.values()) {
|
|
1261
|
-
for (const node of journal.upserts) if (node.data === key) return node.size;
|
|
1262
|
-
}
|
|
1263
|
-
return undefined;
|
|
1522
|
+
return this.readers.size(key) ?? this.state!.payloadSizes.size(key);
|
|
1523
|
+
}
|
|
1524
|
+
/** The size a read can expect before its manifest arrives, when anything names the payload. */
|
|
1525
|
+
private knownSize(key: string): number | undefined {
|
|
1526
|
+
return this.readers.size(key) ?? this.state?.payloadSizes.size(key);
|
|
1264
1527
|
}
|
|
1265
1528
|
resources(): Record<string, number> {
|
|
1266
1529
|
return { ...this.readers.resources(), indexeddbReaderWork: this.readerWork.size };
|
|
1267
1530
|
}
|
|
1268
1531
|
private retainedRange(key: string, range: IndexedDBRange): Promise<Uint8Array> {
|
|
1269
1532
|
if (this.closed) return Promise.reject(new Error("Filesystem storage is closed"));
|
|
1270
|
-
const
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1533
|
+
const size = this.readers.size(key);
|
|
1534
|
+
const work =
|
|
1535
|
+
size === undefined
|
|
1536
|
+
? Promise.reject(new PayloadCorruption("Retained payload size mismatch"))
|
|
1537
|
+
: this.readPayload(key, range, size);
|
|
1275
1538
|
this.readerWork.add(work);
|
|
1276
1539
|
void work.then(
|
|
1277
1540
|
() => this.readerWork.delete(work),
|
|
@@ -1290,8 +1553,7 @@ export class IndexedDBStorage implements StorageBackend {
|
|
|
1290
1553
|
return this.enqueue(async () => {
|
|
1291
1554
|
range.signal?.throwIfAborted();
|
|
1292
1555
|
await this.initialize(range.signal);
|
|
1293
|
-
|
|
1294
|
-
return this.readChunks(key, manifest, range);
|
|
1556
|
+
return this.readPayload(key, range, this.knownSize(key));
|
|
1295
1557
|
}).catch((error: unknown) => {
|
|
1296
1558
|
range.signal?.throwIfAborted();
|
|
1297
1559
|
throw error;
|
|
@@ -1326,52 +1588,87 @@ export class IndexedDBStorage implements StorageBackend {
|
|
|
1326
1588
|
}
|
|
1327
1589
|
}
|
|
1328
1590
|
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
} catch (error) {
|
|
1335
|
-
throw new PayloadCorruption(
|
|
1336
|
-
error instanceof Error ? error.message : "Invalid payload manifest",
|
|
1337
|
-
);
|
|
1338
|
-
}
|
|
1339
|
-
}
|
|
1340
|
-
|
|
1341
|
-
private async readChunks(
|
|
1591
|
+
/** One readonly transaction for the manifest and every chunk the range touches. With a known
|
|
1592
|
+
* size (`expectedSize`) all requests go out together, so the read costs one round trip; the
|
|
1593
|
+
* manifest must then match that size. The bytes are returned once every request has answered,
|
|
1594
|
+
* without waiting for the transaction's commit, and only after every checksum is verified. */
|
|
1595
|
+
private async readPayload(
|
|
1342
1596
|
key: string,
|
|
1343
|
-
manifest: ChunkManifest,
|
|
1344
1597
|
range: IndexedDBRange,
|
|
1598
|
+
expectedSize: number | undefined,
|
|
1345
1599
|
): Promise<Uint8Array> {
|
|
1346
|
-
const
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1600
|
+
const signal = range.signal;
|
|
1601
|
+
signal?.throwIfAborted();
|
|
1602
|
+
this.assertOwner();
|
|
1603
|
+
const tx = this.db.transaction("data", "readonly");
|
|
1604
|
+
this.transactions.add(tx);
|
|
1605
|
+
const abort = () => {
|
|
1606
|
+
try {
|
|
1607
|
+
tx.abort();
|
|
1608
|
+
} catch {}
|
|
1609
|
+
};
|
|
1610
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
1611
|
+
const settled = completed(tx);
|
|
1612
|
+
// The bytes may be returned before the native transaction settles. Ownership loss aborts it
|
|
1613
|
+
// and close and ownership retirement join it until then.
|
|
1614
|
+
const native: Promise<void> = settled.then(
|
|
1615
|
+
(): void => this.nativeSettled(tx, native),
|
|
1616
|
+
(): void => this.nativeSettled(tx, native),
|
|
1617
|
+
);
|
|
1618
|
+
this.nativeReads.add(native);
|
|
1619
|
+
const arrival = Promise.withResolvers<void>();
|
|
1620
|
+
const read: PayloadRead = {
|
|
1621
|
+
key,
|
|
1622
|
+
range,
|
|
1623
|
+
expectedSize,
|
|
1624
|
+
end: 0,
|
|
1625
|
+
next: 0,
|
|
1626
|
+
checks: [],
|
|
1627
|
+
pending: 0,
|
|
1628
|
+
arrived: arrival.resolve,
|
|
1629
|
+
fail: (error) => {
|
|
1630
|
+
read.failure ??= { cause: error };
|
|
1631
|
+
abort();
|
|
1632
|
+
},
|
|
1633
|
+
};
|
|
1370
1634
|
try {
|
|
1371
|
-
|
|
1635
|
+
// Setup can throw synchronously; the catch then aborts the transaction it opened.
|
|
1636
|
+
this.placePayloadReads(tx, read);
|
|
1637
|
+
await Promise.race([arrival.promise, settled.then(() => arrival.promise)]);
|
|
1372
1638
|
} catch (error) {
|
|
1373
|
-
|
|
1639
|
+
abort();
|
|
1640
|
+
throw signal?.aborted ? signal.reason : (this.ownershipError ?? read.failure?.cause ?? error);
|
|
1641
|
+
} finally {
|
|
1642
|
+
signal?.removeEventListener("abort", abort);
|
|
1374
1643
|
}
|
|
1644
|
+
const admit = () => {
|
|
1645
|
+
signal?.throwIfAborted();
|
|
1646
|
+
this.assertOwner();
|
|
1647
|
+
};
|
|
1648
|
+
await verifyChecksums(key, read.checks, admit);
|
|
1649
|
+
// Revocation can land while the verifier's result is delivered: check once more with no
|
|
1650
|
+
// await between this check and handing out the bytes.
|
|
1651
|
+
admit();
|
|
1652
|
+
return read.result!;
|
|
1653
|
+
}
|
|
1654
|
+
private placePayloadReads(tx: IDBTransaction, read: PayloadRead): void {
|
|
1655
|
+
const store = tx.objectStore("data");
|
|
1656
|
+
const manifest = store.get(read.key);
|
|
1657
|
+
manifest.onsuccess = () => {
|
|
1658
|
+
try {
|
|
1659
|
+
acceptManifest(store, manifest.result, read);
|
|
1660
|
+
} catch (error) {
|
|
1661
|
+
read.fail(error);
|
|
1662
|
+
}
|
|
1663
|
+
};
|
|
1664
|
+
if (read.expectedSize !== undefined) placeChunkReads(store, read.expectedSize, read);
|
|
1665
|
+
}
|
|
1666
|
+
private joinNativeReads(): Promise<unknown> {
|
|
1667
|
+
return Promise.all(Array.from(this.nativeReads));
|
|
1668
|
+
}
|
|
1669
|
+
private nativeSettled(tx: IDBTransaction, native: Promise<void>): void {
|
|
1670
|
+
this.transactions.delete(tx);
|
|
1671
|
+
this.nativeReads.delete(native);
|
|
1375
1672
|
}
|
|
1376
1673
|
|
|
1377
1674
|
recoverCommitted(): Promise<CommittedRecovery> {
|
|
@@ -1486,6 +1783,8 @@ export class IndexedDBStorage implements StorageBackend {
|
|
|
1486
1783
|
if (!this.closing) {
|
|
1487
1784
|
this.closed = true;
|
|
1488
1785
|
this.closing = Promise.all(Array.from(this.readerWork).concat([this.tail])).then(async () => {
|
|
1786
|
+
// Admitted work has finished; reads it started may still be settling natively.
|
|
1787
|
+
await this.joinNativeReads();
|
|
1489
1788
|
this.db.close();
|
|
1490
1789
|
if (this.readOnly) {
|
|
1491
1790
|
this.state = undefined;
|
|
@@ -1522,7 +1821,8 @@ export class IndexedDBStorage implements StorageBackend {
|
|
|
1522
1821
|
void settled.catch(() => {});
|
|
1523
1822
|
signal?.addEventListener("abort", abort, { once: true });
|
|
1524
1823
|
const metadata = tx.objectStore("metadata"),
|
|
1525
|
-
journal = tx.objectStore("journal")
|
|
1824
|
+
journal = tx.objectStore("journal"),
|
|
1825
|
+
data = tx.objectStore("data");
|
|
1526
1826
|
try {
|
|
1527
1827
|
const records = await Promise.all([
|
|
1528
1828
|
request(metadata.get(0)),
|
|
@@ -1530,8 +1830,8 @@ export class IndexedDBStorage implements StorageBackend {
|
|
|
1530
1830
|
request(metadata.getAllKeys()),
|
|
1531
1831
|
request(journal.getAll()),
|
|
1532
1832
|
request(journal.getAllKeys()),
|
|
1533
|
-
request(
|
|
1534
|
-
|
|
1833
|
+
request(data.getAllKeys()),
|
|
1834
|
+
formatAndManifests(metadata, data),
|
|
1535
1835
|
request(metadata.get("commit")),
|
|
1536
1836
|
request(metadata.get("active")),
|
|
1537
1837
|
settled,
|
|
@@ -1558,7 +1858,7 @@ export class IndexedDBStorage implements StorageBackend {
|
|
|
1558
1858
|
journalValues,
|
|
1559
1859
|
journalKeys,
|
|
1560
1860
|
dataKeys,
|
|
1561
|
-
format,
|
|
1861
|
+
{ format, manifests },
|
|
1562
1862
|
storedCommit,
|
|
1563
1863
|
active,
|
|
1564
1864
|
] = await this.indexRecords(signal);
|
|
@@ -1574,10 +1874,7 @@ export class IndexedDBStorage implements StorageBackend {
|
|
|
1574
1874
|
if (typeof key === "string") payloadKeys.add(key);
|
|
1575
1875
|
else if (Array.isArray(key) && typeof key[0] === "string") payloadKeys.add(key[0]);
|
|
1576
1876
|
}
|
|
1577
|
-
const physical =
|
|
1578
|
-
format === INDEXEDDB_FORMAT || format === STAGED_FORMAT
|
|
1579
|
-
? await this.validateChunks(dataKeys, signal)
|
|
1580
|
-
: undefined;
|
|
1877
|
+
const physical = manifests && validateChunks(dataKeys, manifests);
|
|
1581
1878
|
const available = physical ? new Set(physical.keys()) : payloadKeys;
|
|
1582
1879
|
const decoded = await Promise.all([decodeIndex(first), decodeIndex(second)]);
|
|
1583
1880
|
signal?.throwIfAborted();
|
|
@@ -1626,6 +1923,10 @@ export class IndexedDBStorage implements StorageBackend {
|
|
|
1626
1923
|
}
|
|
1627
1924
|
if (newest) {
|
|
1628
1925
|
const nodes = new Map(newest.nodes.map((node) => [node.ino, node]));
|
|
1926
|
+
const payloadSizes = new PayloadSizes();
|
|
1927
|
+
payloadSizes.add(nodes.values());
|
|
1928
|
+
for (const base of bases) if (base) payloadSizes.add(base.nodes);
|
|
1929
|
+
for (const journal of journals.values()) payloadSizes.add(journal.upserts);
|
|
1629
1930
|
const lastBase = Math.max(
|
|
1630
1931
|
...bases.filter((base): base is PersistedIndex => !!base).map((base) => base.generation),
|
|
1631
1932
|
);
|
|
@@ -1639,6 +1940,7 @@ export class IndexedDBStorage implements StorageBackend {
|
|
|
1639
1940
|
journals,
|
|
1640
1941
|
journalKeys,
|
|
1641
1942
|
payloadKeys,
|
|
1943
|
+
payloadSizes,
|
|
1642
1944
|
sinceCompaction: Array.from(journals.values()).filter(
|
|
1643
1945
|
(entry) => entry.generation > lastBase,
|
|
1644
1946
|
).length,
|
|
@@ -1712,42 +2014,6 @@ export class IndexedDBStorage implements StorageBackend {
|
|
|
1712
2014
|
);
|
|
1713
2015
|
}
|
|
1714
2016
|
|
|
1715
|
-
private async validateChunks(
|
|
1716
|
-
keys: IDBValidKey[],
|
|
1717
|
-
signal?: AbortSignal,
|
|
1718
|
-
): Promise<Map<string, ChunkManifest>> {
|
|
1719
|
-
const manifests = new Map<string, ChunkManifest>();
|
|
1720
|
-
const chunks = new Map<string, Set<number>>();
|
|
1721
|
-
for (const key of keys) {
|
|
1722
|
-
signal?.throwIfAborted();
|
|
1723
|
-
if (typeof key === "string") {
|
|
1724
|
-
const manifest = recoveryManifest(await this.readRecord(key, signal), key);
|
|
1725
|
-
if (manifest) manifests.set(key, manifest);
|
|
1726
|
-
continue;
|
|
1727
|
-
}
|
|
1728
|
-
if (
|
|
1729
|
-
!Array.isArray(key) ||
|
|
1730
|
-
key.length !== 2 ||
|
|
1731
|
-
typeof key[0] !== "string" ||
|
|
1732
|
-
!validInteger(key[1])
|
|
1733
|
-
)
|
|
1734
|
-
chunkError(String(key));
|
|
1735
|
-
const indices = chunks.get(key[0]) ?? new Set<number>();
|
|
1736
|
-
indices.add(key[1]);
|
|
1737
|
-
chunks.set(key[0], indices);
|
|
1738
|
-
}
|
|
1739
|
-
for (const [key, manifest] of manifests) {
|
|
1740
|
-
const indices = chunks.get(key);
|
|
1741
|
-
if ((indices?.size ?? 0) !== manifest.count) {
|
|
1742
|
-
manifests.delete(key);
|
|
1743
|
-
continue;
|
|
1744
|
-
}
|
|
1745
|
-
if (indices && Array.from(indices).some((index) => index >= manifest.count))
|
|
1746
|
-
manifests.delete(key);
|
|
1747
|
-
}
|
|
1748
|
-
return manifests;
|
|
1749
|
-
}
|
|
1750
|
-
|
|
1751
2017
|
private async fencedWrite(
|
|
1752
2018
|
work: (data: IDBObjectStore, metadata: IDBObjectStore) => void,
|
|
1753
2019
|
signal?: AbortSignal,
|
|
@@ -1988,23 +2254,26 @@ export class IndexedDBStorage implements StorageBackend {
|
|
|
1988
2254
|
nodes: new Map(),
|
|
1989
2255
|
references: new Map(),
|
|
1990
2256
|
parents: new Map(),
|
|
1991
|
-
bases,
|
|
2257
|
+
bases: [undefined, undefined],
|
|
1992
2258
|
journals: new Map(),
|
|
1993
2259
|
journalKeys: [],
|
|
1994
2260
|
payloadKeys: new Set(),
|
|
2261
|
+
payloadSizes: new PayloadSizes(),
|
|
1995
2262
|
sinceCompaction: 0,
|
|
1996
2263
|
};
|
|
1997
|
-
for (const key of discarded) if (typeof key === "number") state
|
|
2264
|
+
for (const key of discarded) if (typeof key === "number") dropJournal(state, key);
|
|
1998
2265
|
state.journalKeys = state.journalKeys.filter((key) => !discarded.has(key));
|
|
2266
|
+
replaceNodes(state, staged);
|
|
1999
2267
|
applyChanges(state, staged, batch);
|
|
2000
|
-
state
|
|
2268
|
+
installBases(state, bases);
|
|
2001
2269
|
if (entry) {
|
|
2002
2270
|
state.journals.set(entry.generation, entry);
|
|
2003
2271
|
state.journalKeys.push(entry.generation);
|
|
2272
|
+
state.payloadSizes.add(entry.upserts);
|
|
2004
2273
|
}
|
|
2005
2274
|
for (const key of batch.data.keys()) state.payloadKeys.add(key);
|
|
2006
2275
|
if (compact) {
|
|
2007
|
-
for (const key of state.journals.keys()) if (key <= cutoff) state
|
|
2276
|
+
for (const key of state.journals.keys()) if (key <= cutoff) dropJournal(state, key);
|
|
2008
2277
|
state.journalKeys = state.journalKeys.filter(
|
|
2009
2278
|
(key) => typeof key !== "number" || key > cutoff,
|
|
2010
2279
|
);
|