diff --git a/tests/helpers/memory-indexeddb.ts b/tests/helpers/memory-indexeddb.ts index 50238e7a..7eae6491 100644 --- a/tests/helpers/memory-indexeddb.ts +++ b/tests/helpers/memory-indexeddb.ts @@ -24,6 +24,27 @@ type StoreState = { indexes: Map; }; +/** One named database: its schema, rows and version. */ +type DatabaseState = { + stores: Map; + version: number; + latest: FakeDatabase | null; + /** Transactions that have not finished, in creation order. */ + transactions: FakeTransaction[]; +}; + +function storeOf(state: DatabaseState, name: string): StoreState { + const store = state.stores.get(name); + if (!store) { + throw new DOMException("Store does not exist.", "NotFoundError"); + } + return store; +} + +// The fake decides when a transaction's task has ended with a real macrotask, +// so a test that fakes timers cannot keep a transaction alive by accident. +const realSetTimeout = globalThis.setTimeout.bind(globalThis); + type FakeKeyRange = | Readonly<{ fakeKind: "ONLY"; @@ -221,23 +242,26 @@ class FakeDatabase { onversionchange: ((event: IDBVersionChangeEvent) => unknown) | null = null; onclose: ((event: Event) => unknown) | null = null; - constructor(private readonly owner: MemoryIndexedDbFactory) {} + constructor( + private readonly owner: MemoryIndexedDbFactory, + readonly state: DatabaseState, + ) {} get objectStoreNames(): DOMStringList { - return stringList(this.owner.storeNames()); + return stringList(this.state.stores.keys()); } createObjectStore( name: string, options?: IDBObjectStoreParameters, ): IDBObjectStore { - if (this.owner.hasStore(name)) { + if (this.state.stores.has(name)) { throw new DOMException("Store already exists.", "ConstraintError"); } if (typeof options?.keyPath !== "string") { throw new DOMException("The fake requires a string key path.", "DataError"); } - this.owner.createStore(name, { + this.state.stores.set(name, { keyPath: options.keyPath, autoIncrement: options.autoIncrement ?? false, data: new Map(), @@ -247,13 +271,13 @@ class FakeDatabase { } deleteObjectStore(name: string): void { - if (!this.owner.deleteStore(name)) { + if (!this.state.stores.delete(name)) { throw new DOMException("Store does not exist.", "NotFoundError"); } } schemaObjectStore(name: string): IDBObjectStore { - const state = this.owner.store(name); + const state = storeOf(this.state, name); return new FakeObjectStore(null, state) as unknown as IDBObjectStore; } @@ -261,7 +285,7 @@ class FakeDatabase { name: string, transaction: FakeUpgradeTransaction, ): IDBObjectStore { - const state = this.owner.store(name); + const state = storeOf(this.state, name); return new FakeObjectStore( null, state, @@ -278,7 +302,12 @@ class FakeDatabase { } const names = typeof storeNames === "string" ? [storeNames] : [...storeNames]; - const transaction = new FakeTransaction(this.owner, names, mode); + const transaction = new FakeTransaction( + this.owner, + this.state, + names, + mode, + ); this.owner.noteTransaction(transaction); return transaction as unknown as IDBTransaction; } @@ -307,19 +336,108 @@ class FakeTransaction { error: DOMException | null = null; readonly mode: IDBTransactionMode; private active = true; + /** + * Native "active" state: a request may be placed only in the task that + * created the transaction or while one of its request events (and the + * microtasks that event queued) is being handled. + */ + private accepting = true; + /** Held back until every earlier overlapping transaction finishes. */ + private started = false; + private readonly deferred: Array<() => void> = []; private completionQueued = false; private pending = 0; private readonly workingStores: Map; constructor( private readonly owner: MemoryIndexedDbFactory, + private readonly database: DatabaseState, private readonly names: readonly string[], mode: IDBTransactionMode, ) { this.mode = mode; this.workingStores = new Map( - names.map((name) => [name, cloneStore(owner.store(name))]), + names.map((name) => [name, cloneStore(storeOf(database, name))]), ); + database.transactions.push(this); + this.startIfUnblocked(); + this.deactivateAfterTask(); + } + + /** + * Native IndexedDB runs transactions with overlapping scopes in creation + * order unless both are readonly. A later one starts from the rows the + * earlier one committed. + */ + startIfUnblocked(): void { + if (this.started || !this.active) return; + const earlier = this.database.transactions.slice( + 0, + this.database.transactions.indexOf(this), + ); + if (earlier.some((transaction) => transaction.blocks(this))) return; + this.started = true; + for (const name of this.names) { + const fresh = cloneStore(storeOf(this.database, name)); + const working = this.workingStores.get(name)!; + working.data = fresh.data; + working.indexes = fresh.indexes; + } + for (const callback of this.deferred.splice(0)) { + this.owner.scheduleTransaction(callback, this.mode); + } + if (!this.accepting) this.commitIfIdle(); + } + + private blocks(later: FakeTransaction): boolean { + return ( + this.active && + (this.mode === "readwrite" || later.mode === "readwrite") && + this.names.some((name) => later.names.includes(name)) + ); + } + + private schedule(callback: () => void): void { + if (this.started) { + this.owner.scheduleTransaction(callback, this.mode); + } else { + this.deferred.push(callback); + } + } + + private deactivateAfterTask(): void { + realSetTimeout(() => { + this.accepting = false; + this.commitIfIdle(); + }, 0); + } + + /** A native transaction with no request left commits once inactive. */ + private commitIfIdle(): void { + if (this.started && this.pending === 0) this.queueCompletion(); + } + + private assertAccepting(): void { + if (!this.active || !this.accepting) { + throw new DOMException( + "The transaction is not active.", + "TransactionInactiveError", + ); + } + } + + private dispatch(handler: () => void): void { + this.accepting = true; + handler(); + this.deactivateAfterTask(); + } + + private finish(): void { + const index = this.database.transactions.indexOf(this); + if (index >= 0) this.database.transactions.splice(index, 1); + for (const transaction of [...this.database.transactions]) { + transaction.startIfUnblocked(); + } } objectStore(name: string): IDBObjectStore { @@ -341,22 +459,23 @@ class FakeTransaction { } request(operation: () => Value): IDBRequest { + this.assertAccepting(); const request = createRequest(); this.pending += 1; - this.owner.scheduleTransaction(() => { + this.schedule(() => { if (!this.active) return; try { request.result = structuredClone(operation()); - request.onsuccess?.(new Event("success")); + this.dispatch(() => request.onsuccess?.(new Event("success"))); } catch (error) { request.error = asException(error); - request.onerror?.(new Event("error")); + this.dispatch(() => request.onerror?.(new Event("error"))); this.abortWith(request.error); } if (!this.active) return; this.pending -= 1; this.queueCompletion(); - }, this.mode); + }); return request as unknown as IDBRequest; } @@ -368,12 +487,13 @@ class FakeTransaction { }>[], direction: IDBCursorDirection, ): IDBRequest { + this.assertAccepting(); const request = createRequest(); let position = 0; this.pending += 1; const emit = () => { - this.owner.scheduleTransaction(() => { + this.schedule(() => { if (!this.active) return; let continued = false; let eventReturned = false; @@ -445,12 +565,12 @@ class FakeTransaction { }, } as unknown as IDBCursorWithValue; } - request.onsuccess?.(new Event("success")); + this.dispatch(() => request.onsuccess?.(new Event("success"))); eventReturned = true; if (continued || !this.active) return; this.pending -= 1; this.queueCompletion(); - }, this.mode); + }); }; emit(); @@ -472,7 +592,7 @@ class FakeTransaction { return; } this.completionQueued = true; - this.owner.scheduleTransaction(() => { + this.schedule(() => { this.completionQueued = false; if (!this.active || this.pending !== 0) return; const commitFailure = @@ -485,18 +605,20 @@ class FakeTransaction { } if (this.mode === "readwrite") { for (const [name, state] of this.workingStores) { - this.owner.replaceStore(name, cloneStore(state)); + this.database.stores.set(name, cloneStore(state)); } } this.active = false; + this.finish(); this.oncomplete?.(new Event("complete")); - }, this.mode); + }); } private abortWith(error: DOMException): void { if (!this.active) return; this.active = false; this.error = error; + this.finish(); this.owner.scheduleLifecycle(() => { this.onerror?.(new Event("error")); this.onabort?.(new Event("abort")); @@ -721,14 +843,36 @@ class FakeIndex { } /** - * Minimal deterministic IndexedDB model for adapter contract tests. It models - * request ordering, transaction-level commit/rollback and upgrade blocking; - * it is not intended to polyfill IndexedDB for application code. + * Minimal deterministic IndexedDB model for adapter contract tests. It is not + * intended to polyfill IndexedDB for application code. + * + * Modeled like a browser: + * - request ordering and transaction-level commit/rollback; + * - one database per name (`open(name)`), so two names never share rows; + * - transactions with overlapping scopes run one after another unless both + * are readonly, and a later one sees what the earlier one committed; + * - a request placed after the transaction's task ended, outside a request + * event and its microtasks, throws `TransactionInactiveError`, and a + * transaction with nothing left to do commits on its own; + * - upgrade blocking, through `blockNextOpen`/`releaseBlockedOpen`. + * + * Not modeled (05-08) — use a browser capability spec for these: + * - key comparison is by `String`/JSON, and a compound (array) index key path + * is not read, so such an index orders by primary key; + * - opening a higher version does not fire `versionchange` on open + * connections, and `onblocked` fires only for `blockNextOpen`; tests drive + * `triggerVersionChange` by hand; + * - the upgrade transaction ends synchronously, so an abort requested from an + * asynchronous step inside `onupgradeneeded` is not rolled back; + * - quota: writes never fail for lack of space unless a test injects it with + * `failNextWriteCommit`. + * + * `seed`, `readRaw` and the lifecycle triggers act on the database opened + * most recently. */ export class MemoryIndexedDbFactory { - private stores = new Map(); - private databaseVersion = 0; - private latestDatabase = new FakeDatabase(this); + private readonly databases = new Map(); + private current: DatabaseState = this.databaseNamed(""); private blockedRequest: Readonly<{ request: MutableOpenRequest; targetVersion: number; @@ -741,8 +885,8 @@ export class MemoryIndexedDbFactory { lastTransaction: FakeTransaction | null = null; readonly factory: IDBFactory = { - open: (_name: string, version?: number) => - this.open(version ?? 1) as unknown as IDBOpenDBRequest, + open: (name: string, version?: number) => + this.open(name, version ?? 1) as unknown as IDBOpenDBRequest, cmp: compareKeys, } as IDBFactory; @@ -782,10 +926,12 @@ export class MemoryIndexedDbFactory { }) as unknown as IDBKeyRange, }; - open(version: number): MutableOpenRequest { - const database = new FakeDatabase(this); - database.version = this.databaseVersion; - this.latestDatabase = database; + open(name: string, version: number): MutableOpenRequest { + const state = this.databaseNamed(name); + const database = new FakeDatabase(this, state); + database.version = state.version; + state.latest = database; + this.current = state; const request: MutableOpenRequest = { ...createRequest(), result: database as unknown as IDBDatabase, @@ -802,7 +948,7 @@ export class MemoryIndexedDbFactory { database, }; request.onblocked?.({ - oldVersion: this.databaseVersion, + oldVersion: state.version, newVersion: version, } as IDBVersionChangeEvent); return; @@ -848,25 +994,25 @@ export class MemoryIndexedDbFactory { } triggerVersionChange(newVersion: number): void { - this.latestDatabase.fireVersionChange(newVersion); + this.current.latest?.fireVersionChange(newVersion); } triggerForcedClose(): void { - this.latestDatabase.fireForcedClose(); + this.current.latest?.fireForcedClose(); } isConnectionClosed(): boolean { - return this.latestDatabase.closed; + return this.current.latest?.closed ?? true; } seed(storeName: string, value: unknown): void { - const state = this.store(storeName); + const state = storeOf(this.current, storeName); const key = primaryKey(state, value); state.data.set(key, structuredClone(value)); } readRaw(storeName: string, key: string): unknown { - const value = this.store(storeName).data.get(key); + const value = storeOf(this.current, storeName).data.get(key); return value === undefined ? undefined : structuredClone(value); } @@ -896,39 +1042,34 @@ export class MemoryIndexedDbFactory { } storeNames(): Iterable { - return this.stores.keys(); + return this.current.stores.keys(); } hasStore(name: string): boolean { - return this.stores.has(name); + return this.current.stores.has(name); } - store(name: string): StoreState { - const state = this.stores.get(name); + private databaseNamed(name: string): DatabaseState { + let state = this.databases.get(name); if (!state) { - throw new DOMException("Store does not exist.", "NotFoundError"); + state = { + stores: new Map(), + version: 0, + latest: null, + transactions: [], + }; + this.databases.set(name, state); } return state; } - createStore(name: string, state: StoreState): void { - this.stores.set(name, state); - } - - replaceStore(name: string, state: StoreState): void { - this.stores.set(name, state); - } - - deleteStore(name: string): boolean { - return this.stores.delete(name); - } - private finishOpen( request: MutableOpenRequest, targetVersion: number, database: FakeDatabase, ): void { - if (targetVersion < this.databaseVersion) { + const state = database.state; + if (targetVersion < state.version) { request.error = new DOMException( "Requested version is older.", "VersionError", @@ -936,9 +1077,9 @@ export class MemoryIndexedDbFactory { request.onerror?.(new Event("error")); return; } - if (targetVersion > this.databaseVersion) { - const before = cloneStores(this.stores); - const oldVersion = this.databaseVersion; + if (targetVersion > state.version) { + const before = cloneStores(state.stores); + const oldVersion = state.version; const upgrade = new FakeUpgradeTransaction(database); request.transaction = upgrade as unknown as IDBTransaction; database.version = targetVersion; @@ -948,7 +1089,7 @@ export class MemoryIndexedDbFactory { } as IDBVersionChangeEvent); request.transaction = null; if (upgrade.aborted) { - this.stores = before; + state.stores = before; database.version = oldVersion; request.error = new DOMException( "Upgrade transaction aborted.", @@ -957,9 +1098,9 @@ export class MemoryIndexedDbFactory { request.onerror?.(new Event("error")); return; } - this.databaseVersion = targetVersion; + state.version = targetVersion; } - database.version = this.databaseVersion; + database.version = state.version; request.result = database as unknown as IDBDatabase; request.onsuccess?.(new Event("success")); } diff --git a/tests/unit/memory-indexeddb-fidelity.test.ts b/tests/unit/memory-indexeddb-fidelity.test.ts new file mode 100644 index 00000000..ad5dc91e --- /dev/null +++ b/tests/unit/memory-indexeddb-fidelity.test.ts @@ -0,0 +1,120 @@ +import { describe, expect, it } from "vitest"; + +import { MemoryIndexedDbFactory } from "../helpers/memory-indexeddb.ts"; + +/** + * 05-08. Where the fake used to part from native IndexedDB, each case pins + * the native result, so a test built on the fake cannot pass on a behavior no + * browser has. + */ + +function settle(request: IDBRequest): Promise { + return new Promise((resolve, reject) => { + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); +} + +function outcome(transaction: IDBTransaction): Promise { + return new Promise((resolve) => { + transaction.oncomplete = () => resolve("complete"); + transaction.onabort = () => + resolve(`abort:${transaction.error?.name ?? "none"}`); + }); +} + +async function openWithStore( + memory: MemoryIndexedDbFactory, + name: string, +): Promise { + const request = memory.factory.open(name, 1); + request.onupgradeneeded = () => { + request.result.createObjectStore("s", { keyPath: "k" }); + }; + return await settle(request); +} + +describe("05-08 memory IndexedDB matches native semantics the adapters rely on", () => { + it("(a) runs overlapping readwrite transactions one after another", async () => { + const memory = new MemoryIndexedDbFactory(); + const database = await openWithStore(memory, "a"); + memory.seed("s", { k: "counter", n: 0 }); + const first = database.transaction(["s"], "readwrite"); + const second = database.transaction(["s"], "readwrite"); + const settled = [outcome(first), outcome(second)]; + for (const transaction of [first, second]) { + const read = transaction.objectStore("s").get("counter"); + read.onsuccess = () => { + const { n } = read.result as { n: number }; + transaction.objectStore("s").put({ k: "counter", n: n + 1 }); + }; + } + + expect(await Promise.all(settled)).toEqual(["complete", "complete"]); + expect(memory.readRaw("s", "counter")).toEqual({ k: "counter", n: 2 }); + }); + + it("(b) rejects a request placed after the transaction's task ended", async () => { + const memory = new MemoryIndexedDbFactory(); + const database = await openWithStore(memory, "b"); + const transaction = database.transaction(["s"], "readwrite"); + const settled = outcome(transaction); + await new Promise((resolve) => setTimeout(resolve, 5)); + + expect(() => + transaction.objectStore("s").put({ k: "late" }), + ).toThrow(expect.objectContaining({ name: "TransactionInactiveError" })); + // A transaction with no request left commits on its own. + expect(await settled).toBe("complete"); + expect(memory.readRaw("s", "late")).toBeUndefined(); + }); + + it("(b) keeps a transaction active for requests placed in a success callback's microtasks", async () => { + const memory = new MemoryIndexedDbFactory(); + const database = await openWithStore(memory, "b2"); + const transaction = database.transaction(["s"], "readwrite"); + const settled = outcome(transaction); + const read = transaction.objectStore("s").get("absent"); + read.onsuccess = () => { + void Promise.resolve().then(() => { + transaction.objectStore("s").put({ k: "chained" }); + }); + }; + + expect(await settled).toBe("complete"); + expect(memory.readRaw("s", "chained")).toEqual({ k: "chained" }); + }); + + it("(d) keeps databases of different names apart", async () => { + const memory = new MemoryIndexedDbFactory(); + const userA = await openWithStore(memory, "user-A"); + await settle( + userA.transaction(["s"], "readwrite").objectStore("s").put({ + k: "secret-of-A", + }), + ); + let upgraded = false; + const request = memory.factory.open("user-B", 1); + request.onupgradeneeded = () => { + upgraded = true; + request.result.createObjectStore("s", { keyPath: "k" }); + }; + const userB = await settle(request); + + expect(upgraded).toBe(true); + expect( + await settle( + userB.transaction(["s"], "readonly").objectStore("s").get( + "secret-of-A", + ), + ), + ).toBeUndefined(); + expect( + await settle( + userA.transaction(["s"], "readonly").objectStore("s").get( + "secret-of-A", + ), + ), + ).toEqual({ k: "secret-of-A" }); + }); +});