commit c1d186c7d2e7aa86607c6d087b239ad28ba4be5c
parent ffaf4dbba034f2fef42aa048decf9d68a7372a4d
Author: Florian Dold <dold@taler.net>
Date: Tue, 17 Nov 2026 10:04:04 +0100
wallet host: detect database loss and failed initialization
Diffstat:
5 files changed, 85 insertions(+), 14 deletions(-)
diff --git a/packages/taler-wallet-core/src/db/handle.ts b/packages/taler-wallet-core/src/db/handle.ts
@@ -176,5 +176,8 @@ export interface WalletDbHandle {
*/
getDiagnosticStats?(): unknown;
+ /** Unexpected connection loss; intentional close must not notify. */
+ subscribeUnavailable?(listener: (error: Error) => void): () => void;
+
close(): Promise<void>;
}
diff --git a/packages/taler-wallet-core/src/db/indexeddb/handle.ts b/packages/taler-wallet-core/src/db/indexeddb/handle.ts
@@ -93,6 +93,43 @@ export class IdbWalletDbHandle implements WalletDbHandle {
| Promise<{ fixupsApplied: number; schemaUpgraded: boolean }>
| undefined;
private closed = false;
+ private unavailable: Error | undefined;
+ private unavailableListeners = new Set<(error: Error) => void>();
+
+ subscribeUnavailable(listener: (error: Error) => void): () => void {
+ this.unavailableListeners.add(listener);
+ if (this.unavailable) listener(this.unavailable);
+ return () => this.unavailableListeners.delete(listener);
+ }
+
+ private invalidate(handle: IDBDatabase, error: Error): void {
+ if (this.closed || this.unavailable || this.idbHandle !== handle) return;
+ this.unavailable = error;
+ this.dbAccess = undefined;
+ handle.close();
+ for (const listener of this.unavailableListeners) listener(error);
+ }
+
+ private watchConnection(handle: IDBDatabase): void {
+ handle.addEventListener("close", () =>
+ this.invalidate(
+ handle,
+ new Error("Wallet database connection closed unexpectedly"),
+ ),
+ );
+ handle.onversionchange = () => {
+ handle.close();
+ this.invalidate(
+ handle,
+ Object.assign(
+ new Error(
+ "Wallet database changed in another client; reload the wallet",
+ ),
+ { name: "VersionError" },
+ ),
+ );
+ };
+ }
private closePromise: Promise<void> | undefined;
private notify: (n: WalletNotification) => void = () => {};
@@ -153,6 +190,7 @@ export class IdbWalletDbHandle implements WalletDbHandle {
fixupsApplied: number;
schemaUpgraded: boolean;
}> {
+ if (this.unavailable) throw this.unavailable;
if (this.closed) {
throw Error("wallet database handle is closed");
}
@@ -219,6 +257,7 @@ export class IdbWalletDbHandle implements WalletDbHandle {
{ deferCompletion: true },
);
this.idbHandle = idbHandle;
+ this.watchConnection(idbHandle);
this.dbAccess = dbAccess;
return { fixupsApplied, schemaUpgraded };
} catch (e) {
@@ -241,6 +280,7 @@ export class IdbWalletDbHandle implements WalletDbHandle {
notificationSink(n);
}
},
+ (error) => this.invalidate(idbHandle, error),
);
}
@@ -361,6 +401,7 @@ export class IdbWalletDbHandle implements WalletDbHandle {
);
published = true;
this.idbHandle = staged.handle;
+ this.watchConnection(staged.handle);
this.dbAccess = stagedAccess;
oldHandle.close();
for (const n of stagedNotifications) this.emitNotification(n);
diff --git a/packages/taler-wallet-core/src/db/query.ts b/packages/taler-wallet-core/src/db/query.ts
@@ -972,6 +972,7 @@ export class DbAccessImpl<Stores extends StoreMap> implements DbAccess<Stores> {
private stores: Stores,
private cancellationToken: CancellationToken,
private applyNotifications?: (notifs: WalletNotification[]) => void,
+ private connectionUnavailable?: (error: Error) => void,
) {}
idbHandle(): IDBDatabase {
@@ -1001,7 +1002,16 @@ export class DbAccessImpl<Stores extends StoreMap> implements DbAccess<Stores> {
this.cancellationToken,
this.applyNotifications,
);
- const tx = this.db.transaction(strStoreNames, mode);
+ let tx: IDBTransaction;
+ try {
+ tx = this.db.transaction(strStoreNames, mode);
+ } catch (error) {
+ // At transaction creation, InvalidStateError means a closing connection,
+ // not an inactive transaction or a failing request inside a transaction.
+ if (error instanceof Error && error.name === "InvalidStateError")
+ this.connectionUnavailable?.(error);
+ throw error;
+ }
const writeContext = makeTxClientContext(
tx,
accessibleStores,
diff --git a/packages/taler-wallet-core/src/wallet.ts b/packages/taler-wallet-core/src/wallet.ts
@@ -1097,6 +1097,7 @@ async function dispatchWalletCoreApiRequest(
let oc: ObservabilityContext;
const cts = CancellationToken.create();
+ ws.activeRequests.add(cts);
if (ws.initCalled && ws.config.testing.emitObservabilityEvents) {
oc = {
@@ -1185,6 +1186,8 @@ async function dispatchWalletCoreApiRequest(
id,
error: err,
};
+ } finally {
+ ws.activeRequests.delete(cts);
}
}
@@ -1315,6 +1318,11 @@ export class Wallet {
return w;
}
+ /** Lifecycle teardown also works after a failed initialization. */
+ shutdown(): Promise<void> {
+ return this.ws.shutdown();
+ }
+
addNotificationListener(f: (n: WalletNotification) => void): CancelFn {
return this.ws.addPublicNotificationListener(f);
}
@@ -1345,6 +1353,7 @@ export class InternalWalletState {
private publicListeners: NotificationListener[] = [];
initCalled = false;
+ readonly activeRequests = new Set<CancellationToken.Source>();
/**
* Proposal IDs of payments that were still claiming when this wallet
@@ -1951,6 +1960,7 @@ export class InternalWalletState {
if (this.stopped) return;
logger.trace("stopping (at internal wallet state)");
this.stopped = true;
+ for (const request of this.activeRequests) request.cancel();
this.observations.shutdown();
this.maintenanceNotifications.stop();
this.timerGroup.stopCurrentAndFutureTimers();
diff --git a/packages/wallet-webui/src/platform/wallet-host.ts b/packages/wallet-webui/src/platform/wallet-host.ts
@@ -1,5 +1,6 @@
import {
SetTimeoutTimerAPI,
+ TalerError,
type CoreApiRequestEnvelope,
type CoreApiResponse,
type WalletNotification,
@@ -17,6 +18,7 @@ import { BrowserHttpLibrary } from "./browser-http.js";
export interface RunningWalletHost {
handle(request: CoreApiRequestEnvelope): Promise<CoreApiResponse>;
stop(): Promise<void>;
+ subscribeUnavailable?(listener: (error: Error) => void): () => void;
}
export async function startIndexedDbWalletHost(
@@ -32,7 +34,7 @@ export async function startWalletHost(
db: WalletDbHandle,
notify: (notification: WalletNotification) => void,
): Promise<RunningWalletHost> {
- let wallet: Wallet;
+ let wallet: Wallet | undefined;
try {
const httpFactory = (() => new BrowserHttpLibrary()) as HttpFactory;
wallet = await Wallet.create(
@@ -41,38 +43,43 @@ export async function startWalletHost(
new SetTimeoutTimerAPI(),
new SynchronousCryptoWorkerFactoryPlain(),
);
- await wallet.handleCoreApiRequest(
+ const initialized = await wallet.handleCoreApiRequest(
WalletApiOperation.InitWallet,
"host-init",
{
config: { features: { allowHttp: false } },
},
);
+ if (initialized.type === "error")
+ throw TalerError.fromUncheckedDetail(initialized.error);
} catch (error) {
- await db.close();
+ try {
+ if (wallet) await wallet.shutdown();
+ else await db.close();
+ } catch {
+ /* Preserve initialization failure. */
+ }
throw error;
}
- const unsubscribe = wallet.addNotificationListener(notify);
+ const initializedWallet = wallet;
+ const unsubscribe = initializedWallet.addNotificationListener(notify);
let stopped = false;
return {
+ subscribeUnavailable: db.subscribeUnavailable?.bind(db),
handle(request) {
if (stopped) throw Error("wallet host is stopped");
- return wallet.handleCoreApiRequest(
+ return initializedWallet.handleCoreApiRequest(
request.operation,
request.id,
request.args,
);
},
async stop() {
- if (stopped) return;
- stopped = true;
- unsubscribe();
- try {
- await wallet.client.call(WalletApiOperation.Shutdown, {});
- } catch {
- // The host is already being torn down. Shutdown is best-effort here.
+ if (!stopped) {
+ stopped = true;
+ unsubscribe();
}
- await db.close();
+ await initializedWallet.shutdown();
},
};
}