taler-typescript-core

Wallet core logic and WebUIs for various components
Log | Files | Refs | Submodules | README | LICENSE

commit f53ed96192adce3544282dbb3466e173d239c8b9
parent 89235519244e0b8a96f9c278d7221224c270c34e
Author: Florian Dold <dold@taler.net>
Date:   Wed, 25 Nov 2026 20:59:51 +0100

wallet-core: report restore progress and preserve IndexedDB generations

Keep the logical name of the active database when publishing a restore.
Report completed record writes for both backends and confirm which
wallet is active before reporting a rollback.

Diffstat:
Mpackages/taler-util/src/notifications.ts | 3++-
Mpackages/taler-wallet-core/src/db/handle.ts | 10++++++++--
Mpackages/taler-wallet-core/src/db/indexeddb/database.test.ts | 27+++++++++++++++++++++++----
Mpackages/taler-wallet-core/src/db/indexeddb/database.ts | 45+++++++++++++++++++++++++++++++++++++++------
Mpackages/taler-wallet-core/src/db/indexeddb/dump.ts | 20++++++++++++++++++--
Mpackages/taler-wallet-core/src/db/indexeddb/handle.ts | 46+++++++++++++++++++++++++++++-----------------
Mpackages/taler-wallet-core/src/db/migration/converter.test.ts | 6+++---
Mpackages/taler-wallet-core/src/db/sqlite/database.ts | 110+++++++++++++++++++++++++++++++++++++++++++++++++------------------------------
Mpackages/taler-wallet-core/src/db/sqlite/handle.ts | 6+++---
Mpackages/taler-wallet-core/src/db/sqlite/schema.ts | 4++++
Mpackages/taler-wallet-core/src/db/testing/runners.ts | 2+-
Mpackages/taler-wallet-core/src/index.ts | 6++++++
Mpackages/taler-wallet-core/src/maintenance-notifications.test.ts | 34++++++++++++++++++++++++++++++++++
Mpackages/taler-wallet-core/src/maintenance-notifications.ts | 2+-
Mpackages/taler-wallet-core/src/requests.ts | 50++++++++++++++++++++++++++++++++++++++++++--------
15 files changed, 281 insertions(+), 90 deletions(-)

diff --git a/packages/taler-util/src/notifications.ts b/packages/taler-util/src/notifications.ts @@ -456,7 +456,8 @@ export interface DatabaseMaintenanceProgressNotification { operation: | "indexeddb-fixup" | "indexeddb-to-native-migration" - | "cross-backend-import"; + | "cross-backend-import" + | "database-import"; /** Token of the API request that initiated this operation, when available. */ progressToken?: string; phase: "fixup" | "copy" | "verify" | "complete" | "failed"; diff --git a/packages/taler-wallet-core/src/db/handle.ts b/packages/taler-wallet-core/src/db/handle.ts @@ -46,6 +46,12 @@ export interface WalletDbMigrationOptions { progressToken?: string; } +export interface WalletDbImportOptions extends WalletDbMigrationOptions { + onRecordProgress?: (processed: number, total: number) => void; + /** The backend discarded the staged write or rolled back the transaction. */ + onRollback?: () => void; +} + export type WalletDbBackend = "indexeddb" | "sqlite"; /** @@ -92,7 +98,7 @@ export interface WalletDbHandle { importDatabase( dump: any, finalize: WalletDbImportFinalizer, - options?: WalletDbMigrationOptions, + options?: WalletDbImportOptions, ): Promise<void>; /** @@ -104,7 +110,7 @@ export interface WalletDbHandle { importAnyDatabase?( dump: any, finalize: WalletDbImportFinalizer, - options?: WalletDbMigrationOptions, + options?: WalletDbImportOptions, ): Promise<void>; /** Remove all records, leaving an empty database of the current schema. */ diff --git a/packages/taler-wallet-core/src/db/indexeddb/database.test.ts b/packages/taler-wallet-core/src/db/indexeddb/database.test.ts @@ -17,7 +17,6 @@ import { BridgeIDBFactory, createSqliteBackend, - IDBDatabase, structuredRevive, } from "@gnu-taler/idb-bridge"; import { createNodeHelperSqlite3Impl } from "@gnu-taler/idb-bridge/node-helper-sqlite3-impl"; @@ -142,7 +141,7 @@ test("a failed fixup is retried on the next database open", async () => { } }); -test("indexeddb import commit survives reopen and failure preserves old generation", async () => { +test("namespaced IndexedDB import survives reopen and failure preserves the old generation", async () => { const sqlite3Impl = await createNodeHelperSqlite3Impl({ enableTracing: false, }); @@ -150,7 +149,16 @@ test("indexeddb import commit survives reopen and failure preserves old generati filename: ":memory:", }); BridgeIDBFactory.enableTracing = false; - const factory = new BridgeIDBFactory(backend); + // Browser storage migrations scope physical database names to their generation. + class NamespacedFactory extends BridgeIDBFactory { + override open(name: string, version?: number) { + return super.open("generation-2--" + name, version); + } + override deleteDatabase(name: string) { + return super.deleteDatabase("generation-2--" + name); + } + } + const factory = new NamespacedFactory(backend); let handle = new IdbWalletDbHandle(factory); const source = await makeIdbRunner(); const restored = await makeIdbRunner(); @@ -250,7 +258,18 @@ test("indexeddb startup selects only a published generation", async () => { const afterPublish = await openTalerDatabase(factory, async () => {}); assert.strictEqual(afterPublish.name, published.name); + await assert.rejects( + beginTalerDatabaseReplacement(factory, afterAbandon.name, async () => {}), + /generation changed/, + ); afterPublish.close(); + assert.strictEqual( + await abortTalerDatabaseReplacement(factory, published.name), + published.name, + ); + assert.ok( + (await factory.databases()).some((db) => db.name === published.name), + ); // The abandoned generation is deliberately not deleted during startup, // but its stale pending claim was cleared, so its owner can clean it safely. await abortTalerDatabaseReplacement(factory, abandoned.name); @@ -285,7 +304,7 @@ test("export closes its database connection", async () => { test("an aborted transaction without pending requests settles its promise", async () => { const handle = await makeIdbRunner(); try { - const db = (handle as any).idbHandle as IDBDatabase; + const db = (await handle.rawAccess()).idbHandle(); const tx = db.transaction(["config"], "readwrite"); const prom = promiseFromTransaction(tx); tx.abort(); diff --git a/packages/taler-wallet-core/src/db/indexeddb/database.ts b/packages/taler-wallet-core/src/db/indexeddb/database.ts @@ -255,14 +255,26 @@ export async function openTalerDatabase( onVersionChange: () => void, onUpgradeStart?: (oldVersion: number, newVersion: number) => void, ): Promise<IDBDatabase> { + return ( + await openActiveTalerDatabase(idbFactory, onVersionChange, onUpgradeStart) + ).handle; +} + +/** Keep the logical name used to open the handle. A host can namespace physical DB names. */ +export async function openActiveTalerDatabase( + idbFactory: IDBFactory, + onVersionChange: () => void, + onUpgradeStart?: (oldVersion: number, newVersion: number) => void, +): Promise<TalerDatabaseGeneration> { const state = await readMainDbState(idbFactory, true); await cleanInterruptedDatabaseReplacement(idbFactory, state); - return await openTalerDatabaseGeneration( + const handle = await openTalerDatabaseGeneration( idbFactory, state.current, onVersionChange, onUpgradeStart, ); + return { name: state.current, handle }; } interface MainDbState { @@ -468,7 +480,7 @@ async function cleanInterruptedDatabaseReplacement( ); } -export interface StagedTalerDatabase { +export interface TalerDatabaseGeneration { name: string; handle: IDBDatabase; } @@ -478,7 +490,7 @@ export async function beginTalerDatabaseReplacement( idbFactory: IDBFactory, currentName: string, onVersionChange: () => void, -): Promise<StagedTalerDatabase> { +): Promise<TalerDatabaseGeneration> { const name = `${TALER_WALLET_DB_GENERATION_PREFIX}${encodeCrock( getRandomBytes(16), )}`; @@ -538,12 +550,33 @@ export async function publishTalerDatabaseReplacement( } } -/** Delete an unpublished generation after a failed import. */ +/** Discard an unpublished generation and report which wallet is authoritative. */ export async function abortTalerDatabaseReplacement( idbFactory: IDBFactory, name: string, -): Promise<void> { - await cleanupGeneration(idbFactory, name, PENDING_DB_CONFIG_KEY, ""); +): Promise<string | undefined> { + try { + const meta = await openMetaDatabase(idbFactory); + let current: string | undefined; + try { + current = await meta.access.runAllStoresReadWriteTx( + {}, + async (tx) => (await tx.metaConfig.get(CURRENT_DB_CONFIG_KEY))?.value, + ); + } finally { + meta.handle.close(); + } + // Another owner may have published since this writer started. Never delete + // a live generation or report a rollback without an authoritative pointer. + if (current) + await cleanupGeneration(idbFactory, name, PENDING_DB_CONFIG_KEY, current); + return current; + } catch (e) { + logger.warn( + `could not confirm the active wallet database after import: ${e}`, + ); + return undefined; + } } /** Best-effort deletion of the old generation after a successful publish. */ diff --git a/packages/taler-wallet-core/src/db/indexeddb/dump.ts b/packages/taler-wallet-core/src/db/indexeddb/dump.ts @@ -15,6 +15,7 @@ import { structuredRevive, } from "@gnu-taler/idb-bridge"; import { CancellationToken, Logger } from "@gnu-taler/taler-util"; +import type { WalletDbImportOptions } from "../handle.js"; import { openDatabase } from "../query.js"; import { TALER_WALLET_MAIN_DB_NAME, @@ -178,12 +179,26 @@ async function recoverFromDump( db: IDBDatabase, dbDump: DbDumpDatabase, cancellationToken: CancellationToken, + onProgress?: WalletDbImportOptions["onRecordProgress"], ): Promise<void> { cancellationToken.throwIfCancelled(); const tx = db.transaction(Array.from(db.objectStoreNames), "readwrite"); const txProm = promiseFromTransaction(tx); try { const storeNames = db.objectStoreNames; + if ( + !Array.from(storeNames).some((name) => Object.hasOwn(dbDump.stores, name)) + ) { + throw Error("the backup contains no wallet object stores"); + } + const total = onProgress + ? Array.from(storeNames).reduce( + (n, name) => n + (dbDump.stores[name]?.records.length ?? 0), + 0, + ) + : 0; + let processed = 0; + onProgress?.(0, total); for (let i = 0; i < storeNames.length; i++) { cancellationToken.throwIfCancelled(); const name = db.objectStoreNames[i]; @@ -195,7 +210,7 @@ async function recoverFromDump( for (let rec of storeDump.records) { cancellationToken.throwIfCancelled(); await promiseFromRequest(tx.objectStore(name).put(rec.value, rec.key)); - logger.trace("importing record done"); + onProgress?.(++processed, total); } } cancellationToken.throwIfCancelled(); @@ -220,6 +235,7 @@ export async function importDb( db: IDBDatabase, dumpJson: any, cancellationToken: CancellationToken = CancellationToken.CONTINUE, + onProgress?: WalletDbImportOptions["onRecordProgress"], ): Promise<void> { cancellationToken.throwIfCancelled(); const d = structuredRevive(dumpJson); @@ -231,7 +247,7 @@ export async function importDb( `unable to import, main wallet database (${TALER_WALLET_MAIN_DB_NAME}) not found`, ); } - await recoverFromDump(db, walletDb, cancellationToken); + await recoverFromDump(db, walletDb, cancellationToken, onProgress); } else { throw Error("unable to import, doesn't look like a valid DB dump"); } diff --git a/packages/taler-wallet-core/src/db/indexeddb/handle.ts b/packages/taler-wallet-core/src/db/indexeddb/handle.ts @@ -38,7 +38,8 @@ import { abortTalerDatabaseReplacement, beginTalerDatabaseReplacement, clearDatabase, - openTalerDatabase, + openActiveTalerDatabase, + type TalerDatabaseGeneration, publishTalerDatabaseReplacement, retireTalerDatabaseGeneration, } from "./database.js"; @@ -53,6 +54,7 @@ import { WalletDbAccessStats, WalletDbHandle, WalletDbImportFinalizer, + WalletDbImportOptions, WalletDbMigrationOptions, } from "../handle.js"; import { IdbWalletTransaction } from "./transaction.js"; @@ -87,7 +89,7 @@ function notifySafely( export class IdbWalletDbHandle implements WalletDbHandle { readonly name = "indexeddb"; - private idbHandle: IDBDatabase | undefined; + private generation?: TalerDatabaseGeneration; private dbAccess: DbAccess<typeof WalletIndexedDbStoresV1> | undefined; private opening: | Promise<{ fixupsApplied: number; schemaUpgraded: boolean }> @@ -103,7 +105,8 @@ export class IdbWalletDbHandle implements WalletDbHandle { } private invalidate(handle: IDBDatabase, error: Error): void { - if (this.closed || this.unavailable || this.idbHandle !== handle) return; + if (this.closed || this.unavailable || this.generation?.handle !== handle) + return; this.unavailable = error; this.dbAccess = undefined; handle.close(); @@ -217,9 +220,9 @@ export class IdbWalletDbHandle implements WalletDbHandle { }> { let schemaUpgraded = false; let upgradeStep: string | undefined; - let idbHandle: IDBDatabase; + let generation: TalerDatabaseGeneration; try { - idbHandle = await openTalerDatabase( + generation = await openActiveTalerDatabase( this.idbFactory, async () => {}, (oldVersion, newVersion) => { @@ -249,6 +252,7 @@ export class IdbWalletDbHandle implements WalletDbHandle { } throw e; } + const idbHandle = generation.handle; const dbAccess = this.makeAccess(idbHandle); try { const fixupsApplied = await this.applyDbFixups( @@ -256,7 +260,7 @@ export class IdbWalletDbHandle implements WalletDbHandle { (n) => this.emitNotification(n), { deferCompletion: true }, ); - this.idbHandle = idbHandle; + this.generation = generation; this.watchConnection(idbHandle); this.dbAccess = dbAccess; return { fixupsApplied, schemaUpgraded }; @@ -321,7 +325,7 @@ export class IdbWalletDbHandle implements WalletDbHandle { async importDatabase( dump: any, finalize: WalletDbImportFinalizer, - options: WalletDbMigrationOptions = {}, + options: WalletDbImportOptions = {}, ): Promise<void> { const cancellationToken = options.cancellationToken ?? CancellationToken.CONTINUE; @@ -339,11 +343,10 @@ export class IdbWalletDbHandle implements WalletDbHandle { } await this.ensureOpen(); cancellationToken.throwIfCancelled(); - if (!this.idbHandle) { + if (!this.generation) { throw Error("wallet database is not open"); } - const oldHandle = this.idbHandle; - const oldName = oldHandle.name; + const { handle: oldHandle, name: oldName } = this.generation; const stagedNotifications: WalletNotification[] = []; let published = false; const staged = await beginTalerDatabaseReplacement( @@ -360,7 +363,12 @@ export class IdbWalletDbHandle implements WalletDbHandle { }); try { cancellationToken.throwIfCancelled(); - await importDb(staged.handle, dump, cancellationToken); + await importDb( + staged.handle, + dump, + cancellationToken, + options.onRecordProgress, + ); cancellationToken.throwIfCancelled(); // The imported records may predate any of the fixups, whatever the old // generation had applied. Clear the imported log and repair the staged @@ -400,7 +408,7 @@ export class IdbWalletDbHandle implements WalletDbHandle { staged.name, ); published = true; - this.idbHandle = staged.handle; + this.generation = staged; this.watchConnection(staged.handle); this.dbAccess = stagedAccess; oldHandle.close(); @@ -408,7 +416,11 @@ export class IdbWalletDbHandle implements WalletDbHandle { } catch (e) { if (!published) { staged.handle.close(); - await abortTalerDatabaseReplacement(this.idbFactory, staged.name); + const current = await abortTalerDatabaseReplacement( + this.idbFactory, + staged.name, + ); + if (current === oldName) options.onRollback?.(); } throw e; } @@ -420,10 +432,10 @@ export class IdbWalletDbHandle implements WalletDbHandle { async clearDatabase(): Promise<void> { await this.ensureOpen(); - if (!this.idbHandle) { + if (!this.generation) { throw Error("wallet database is not open"); } - await clearDatabase(this.idbHandle); + await clearDatabase(this.generation.handle); } getAccessStats(): WalletDbAccessStats | undefined { @@ -448,8 +460,8 @@ export class IdbWalletDbHandle implements WalletDbHandle { if (!this.closePromise) { this.closed = true; this.closePromise = (async () => { - this.idbHandle?.close(); - this.idbHandle = undefined; + this.generation?.handle.close(); + this.generation = undefined; this.dbAccess = undefined; await this.disposeBackend?.(); })(); diff --git a/packages/taler-wallet-core/src/db/migration/converter.test.ts b/packages/taler-wallet-core/src/db/migration/converter.test.ts @@ -775,8 +775,8 @@ test("converter: IndexedDB to sqlite, populated by the conformance corpus", asyn }); const dst = await makeSqliteRunner(); - const retainedTransactionsBefore = (src as any).idbHandle._transactions - .length; + const bridge = (await src.rawAccess()).idbHandle(); + const retainedTransactionsBefore = (bridge as any)._transactions.length; const pageSizes: number[] = []; for (const handle of [src, dst]) { const originalRun = handle.runReadWriteTx.bind(handle); @@ -906,7 +906,7 @@ test("converter: IndexedDB to sqlite, populated by the conformance corpus", asyn } } assert.strictEqual( - (src as any).idbHandle._transactions.length, + (bridge as any)._transactions.length, retainedTransactionsBefore, "completed scan transactions were retained by the IndexedDB bridge", ); diff --git a/packages/taler-wallet-core/src/db/sqlite/database.ts b/packages/taler-wallet-core/src/db/sqlite/database.ts @@ -25,14 +25,18 @@ import { decodeCrock, encodeCrock, Logger, + TalerError, + TalerErrorCode, WalletNotification, } from "@gnu-taler/taler-util"; +import type { WalletDbImportOptions } from "../handle.js"; import { WalletDbTransaction } from "../transaction.js"; import { coalesceWalletNotifications } from "../shared.js"; import { DATA_TABLES_CONDITION, SchemaMigration, schemaMigrations, + SQLITE_BACKUP_VERSIONS, SQLITE_BASELINE_SCHEMA, SQLITE_SCHEMA_VERSION, } from "./schema.js"; @@ -443,6 +447,7 @@ async function runNativeSqliteWalletTxLocked<T>( ndb: NativeSqliteWalletDb, notifyFn: (n: WalletNotification) => void, f: (tx: SqliteWalletTransaction) => Promise<T>, + onRollback?: () => void, ): Promise<T> { const tx = new SqliteWalletTransaction(ndb.db, ndb.stmtCache, ndb.stats); await ndb.txc.begin(); @@ -454,6 +459,7 @@ async function runNativeSqliteWalletTxLocked<T>( // the interesting one and must not be masked by it. try { await ndb.txc.rollback(); + onRollback?.(); } catch (rollbackErr) { logger.warn(`rollback failed: ${rollbackErr}`); } @@ -469,6 +475,7 @@ async function runNativeSqliteWalletTxLocked<T>( // bad write and the wallet's database is unusable until it restarts. try { await ndb.txc.rollback(); + onRollback?.(); } catch (rollbackErr) { logger.warn(`rollback after a failed commit failed: ${rollbackErr}`); } @@ -642,17 +649,15 @@ export async function importNativeSqliteDb( dump: NativeSqliteDbDump, finalize: (tx: WalletDbTransaction) => Promise<void>, notifyFn: (n: WalletNotification) => void, - cancellationToken: CancellationToken = CancellationToken.CONTINUE, + options: WalletDbImportOptions = {}, ): Promise<void> { + const cancellationToken = + options.cancellationToken ?? CancellationToken.CONTINUE; cancellationToken.throwIfCancelled(); - // v29 and v30 dumps have compatible row formats. Missing attention data - // starts empty, and refund snapshot columns added by v31 remain NULL. - if ( - dump.schemaVersion !== SQLITE_SCHEMA_VERSION && - dump.schemaVersion !== 29 && - dump.schemaVersion !== 30 - ) { - throw Error( + if (!SQLITE_BACKUP_VERSIONS.includes(dump.schemaVersion)) { + throw TalerError.fromDetail( + TalerErrorCode.WALLET_CORE_API_BAD_REQUEST, + { parameter: "dump" }, `cannot import a native wallet DB dump of schema version` + ` ${dump.schemaVersion} into version ${SQLITE_SCHEMA_VERSION}`, ); @@ -660,42 +665,63 @@ export async function importNativeSqliteDb( await ndb.lock.run(async () => { cancellationToken.throwIfCancelled(); const tables = await listDataTables(ndb); - await runNativeSqliteWalletTxLocked(ndb, notifyFn, async (tx) => { - // Clear and refill in one transaction: a partial import would leave - // the wallet with a mix of two databases. - for (const table of tables) { - cancellationToken.throwIfCancelled(); - await (await ndb.db.prepare(`DELETE FROM "${table}"`)).run({}); - } - for (const table of tables) { - cancellationToken.throwIfCancelled(); - const rows = dump.tables[table]; - if (!rows || rows.length === 0) { - continue; + if (!tables.some((table) => Object.hasOwn(dump.tables, table))) { + throw TalerError.fromDetail( + TalerErrorCode.WALLET_CORE_API_BAD_REQUEST, + { parameter: "dump" }, + "the backup contains no wallet data tables", + ); + } + await runNativeSqliteWalletTxLocked( + ndb, + notifyFn, + async (tx) => { + const total = options.onRecordProgress + ? tables.reduce( + (n, table) => n + (dump.tables[table]?.length ?? 0), + 0, + ) + : 0; + let processed = 0; + options.onRecordProgress?.(0, total); + // Clear and refill in one transaction: a partial import would leave + // the wallet with a mix of two databases. + for (const table of tables) { + cancellationToken.throwIfCancelled(); + await (await ndb.db.prepare(`DELETE FROM "${table}"`)).run({}); } - for (const row of rows) { + for (const table of tables) { cancellationToken.throwIfCancelled(); - const cols = Object.keys(row); - const params: Record<string, Sqlite3Value> = {}; - for (const c of cols) { - const v = row[c]; - params[c] = isDumpBlob(v) ? decodeCrock(v.$blob) : v; + const rows = dump.tables[table]; + if (!rows || rows.length === 0) { + continue; + } + for (const row of rows) { + cancellationToken.throwIfCancelled(); + const cols = Object.keys(row); + const params: Record<string, Sqlite3Value> = {}; + for (const c of cols) { + const v = row[c]; + params[c] = isDumpBlob(v) ? decodeCrock(v.$blob) : v; + } + const colList = cols.map((c) => `"${c}"`).join(", "); + const valList = cols.map((c) => `$${c}`).join(", "); + await ( + await ndb.db.prepare( + `INSERT INTO "${table}" (${colList}) VALUES (${valList})`, + ) + ).run(params); + options.onRecordProgress?.(++processed, total); } - const colList = cols.map((c) => `"${c}"`).join(", "); - const valList = cols.map((c) => `$${c}`).join(", "); - await ( - await ndb.db.prepare( - `INSERT INTO "${table}" (${colList}) VALUES (${valList})`, - ) - ).run(params); } - } - // Derived wallet state is part of the restore. Running this before the - // same COMMIT means an error cannot expose imported records with stale - // or absent materialized transactions. - cancellationToken.throwIfCancelled(); - await finalize(tx); - cancellationToken.throwIfCancelled(); - }); + // Derived wallet state is part of the restore. Running this before the + // same COMMIT means an error cannot expose imported records with stale + // or absent materialized transactions. + cancellationToken.throwIfCancelled(); + await finalize(tx); + cancellationToken.throwIfCancelled(); + }, + options.onRollback, + ); }); } diff --git a/packages/taler-wallet-core/src/db/sqlite/handle.ts b/packages/taler-wallet-core/src/db/sqlite/handle.ts @@ -19,7 +19,7 @@ import { WalletDbAccessStats, WalletDbHandle, WalletDbImportFinalizer, - WalletDbMigrationOptions, + WalletDbImportOptions, } from "../handle.js"; import { WalletDbTransaction } from "../transaction.js"; import { @@ -106,7 +106,7 @@ export class SqliteWalletDbHandle implements WalletDbHandle { async importDatabase( dump: any, finalize: WalletDbImportFinalizer, - options: WalletDbMigrationOptions = {}, + options: WalletDbImportOptions = {}, ): Promise<void> { if (dump != null && typeof dump === "object" && "databases" in dump) { throw Error( @@ -119,7 +119,7 @@ export class SqliteWalletDbHandle implements WalletDbHandle { dump, finalize, (n) => this.emitNotification(n), - options.cancellationToken, + options, ); } diff --git a/packages/taler-wallet-core/src/db/sqlite/schema.ts b/packages/taler-wallet-core/src/db/sqlite/schema.ts @@ -87,6 +87,10 @@ */ export const SQLITE_SCHEMA_VERSION = 32; +// v29 and v30 backups have compatible row formats. Missing attention data +// starts empty, and refund snapshot columns added by v31 remain NULL. +export const SQLITE_BACKUP_VERSIONS = [29, 30, SQLITE_SCHEMA_VERSION]; + /** * Tables of the IndexedDB emulation, children before parents. * diff --git a/packages/taler-wallet-core/src/db/testing/runners.ts b/packages/taler-wallet-core/src/db/testing/runners.ts @@ -37,7 +37,7 @@ import { SqliteWalletDbHandle } from "../sqlite/handle.js"; */ export async function makeIdbRunner( filename = ":memory:", -): Promise<DbTxRunner> { +): Promise<IdbWalletDbHandle> { const sqlite3Impl = await createNodeHelperSqlite3Impl({ enableTracing: false, }); diff --git a/packages/taler-wallet-core/src/index.ts b/packages/taler-wallet-core/src/index.ts @@ -42,11 +42,17 @@ export { createPairTimeline } from "./denominations.js"; export { WithdrawalGroupStatus } from "./db/records.js"; export { exportDb, importDb } from "./db/indexeddb/dump.js"; export { + TALER_WALLET_DB_GENERATION_PREFIX, TALER_WALLET_MAIN_DB_NAME, TALER_WALLET_META_DB_NAME, WalletIndexedDbStoresV1 as WalletStoresV1, } from "./db/indexeddb/schema.js"; +export { + NATIVE_DATA_TABLES, + SQLITE_BACKUP_VERSIONS, +} from "./db/sqlite/schema.js"; + export type { DbAccess } from "./db/query.js"; export type { WalletDbHandle } from "./db/handle.js"; export { IdbWalletDbHandle } from "./db/indexeddb/handle.js"; diff --git a/packages/taler-wallet-core/src/maintenance-notifications.test.ts b/packages/taler-wallet-core/src/maintenance-notifications.test.ts @@ -115,6 +115,40 @@ test("maintenance notifications deliver first and terminal events immediately", ); }); +test("concurrent import tokens do not replace each other's progress", () => { + const timer = new ManualTimer(); + const delivered: string[] = []; + const throttler = new MaintenanceNotificationThrottler( + timer, + (n) => { + if (n.type === NotificationType.DatabaseMaintenanceProgress) + delivered.push(n.step!); + }, + () => BigInt(timer.nowMs) * 1_000_000n, + ); + const offer = ( + step: string, + progressToken: string, + phase: "copy" | "failed" = "copy", + ) => + throttler.offer({ + ...progress(step, phase), + operation: "database-import", + progressToken, + }); + offer("first started", "a"); + offer("first writing", "a"); + offer("second started", "b"); + offer("second failed", "b", "failed"); + timer.advance(DATABASE_MAINTENANCE_NOTIFICATION_INTERVAL_MS); + assert.deepEqual(delivered, [ + "first started", + "second started", + "second failed", + "first writing", + ]); +}); + test("maintenance notifications coalesce progress into 500ms intervals", () => { const timer = new ManualTimer(); const delivered: DatabaseMaintenanceProgressNotification[] = []; diff --git a/packages/taler-wallet-core/src/maintenance-notifications.ts b/packages/taler-wallet-core/src/maintenance-notifications.ts @@ -56,7 +56,7 @@ export class MaintenanceNotificationThrottler { { type: NotificationType.DatabaseMaintenanceProgress } >, ): void { - const key = notification.operation; + const key = `${notification.operation}:${notification.progressToken ?? ""}`; const terminal = notification.phase === "complete" || notification.phase === "failed"; const previous = this.states.get(key); diff --git a/packages/taler-wallet-core/src/requests.ts b/packages/taler-wallet-core/src/requests.ts @@ -328,6 +328,7 @@ import { import { walletDbFixups } from "./db/indexeddb/fixups.js"; import { IdbWalletDbHandle } from "./db/indexeddb/handle.js"; import { getWalletDbDumpBackend } from "./db/migration/import.js"; +import type { WalletDbImportOptions } from "./db/handle.js"; import { WalletDbTransaction } from "./db/transaction.js"; import { checkDepositGroup, createDepositGroup } from "./deposits.js"; import { getSerializedWalletDiagnostics } from "./diagnostics.js"; @@ -1986,7 +1987,38 @@ async function importDbDump( // together. The backend keeps the old database authoritative if this // finalizer throws. const db = wex.ws.db; + const reportProgress = progressToken && dumpBackend === db.name; + let processedRecords = 0; + let totalRecords = 0; + let rolledBack = false; + const report = (phase: "copy" | "verify" | "complete" | "failed"): void => { + if (!reportProgress) return; + wex.ws.notify({ + type: NotificationType.DatabaseMaintenanceProgress, + operation: "database-import", + progressToken, + phase, + processedRecords, + totalRecords, + completedSteps: phase === "complete" ? 2 : phase === "verify" ? 1 : 0, + totalSteps: 2, + }); + }; + const options: WalletDbImportOptions = { + cancellationToken: wex.cancellationToken, + progressToken, + onRollback: () => { + rolledBack = true; + }, + }; + if (reportProgress) + options.onRecordProgress = (processed, total) => { + processedRecords = processed; + totalRecords = total; + if (processed % 64 === 0 || processed === total) report("copy"); + }; const finalize = async (tx: WalletDbTransaction): Promise<void> => { + report("verify"); await migrateRefundPurchaseSnapshotsInTx(tx); await rematerializeTransactionsAtCurrentVersion(wex, tx); await recomputeCoinAvailabilityAtCurrentVersion(tx); @@ -1994,10 +2026,7 @@ async function importDbDump( }; try { if (db.importAnyDatabase) { - await db.importAnyDatabase(dump, finalize, { - cancellationToken: wex.cancellationToken, - progressToken, - }); + await db.importAnyDatabase(dump, finalize, options); } else { if (dumpBackend !== db.name) { throw TalerError.fromDetail( @@ -2006,12 +2035,17 @@ async function importDbDump( `the ${db.name} backend cannot import a ${dumpBackend} dump`, ); } - await db.importDatabase(dump, finalize, { - cancellationToken: wex.cancellationToken, - progressToken, - }); + await db.importDatabase(dump, finalize, options); } + report("complete"); } catch (e) { + report("failed"); + if (rolledBack) { + throw TalerError.fromUncheckedDetail({ + ...getErrorDetailFromException(e), + sourceDatabaseRetained: true, + }); + } if (e instanceof CancellationToken.CancellationError) { throw TalerError.fromDetail( TalerErrorCode.WALLET_CORE_REQUEST_CANCELLED,