taler-typescript-core

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

commit 8f2d97bd5ea7fedb2c53af24ae864549b25d32ba
parent 8972d331a7b0dd62291b6701be058df012505249
Author: Florian Dold <dold@taler.net>
Date:   Tue, 17 Nov 2026 10:04:24 +0100

wallet web UI: reconnect after wallet failures

Diffstat:
Mpackages/wallet-webui/src/api/rpc.ts | 29++++++++++++++++++++++-------
Mpackages/wallet-webui/src/platform/extension-background.ts | 75++++++++++++++++++++++++++++++++++++---------------------------------------
Mpackages/wallet-webui/src/routes/App.tsx | 30++++++++++++++++++++++++++++++
Mpackages/wallet-webui/src/workers/wallet-worker.ts | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mpackages/wallet-webui/test/rpc.test.ts | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
5 files changed, 263 insertions(+), 62 deletions(-)

diff --git a/packages/wallet-webui/src/api/rpc.ts b/packages/wallet-webui/src/api/rpc.ts @@ -20,6 +20,7 @@ import type { ConnectionStatus, WalletConnection } from "./contracts.js"; export const BROWSER_RPC_VERSION = 1 as const; export type BrowserRpcMessage = + | { version: typeof BROWSER_RPC_VERSION; kind: "retry-host" } | { version: typeof BROWSER_RPC_VERSION; kind: "request"; @@ -95,7 +96,7 @@ export class RpcWalletConnection implements WalletConnection { payload: WalletCoreRequestType<Op>, mutation: boolean, ): Promise<CoreApiResponse> { - if (this.closed) { + if (this.closed || this.status.state === "disconnected") { throw new HostDisconnectedError("wallet host is closed", "", "not-sent"); } const id = `${Date.now().toString(36)}-${++this.nextId}`; @@ -160,10 +161,9 @@ export class RpcWalletConnection implements WalletConnection { return; } if (message.kind === "status") { - this.setStatus(message.status); if (message.status.state === "disconnected") { - this.disconnect(message.status.reason); - } + this.disconnect(message.status.reason, message.status.recovery); + } else this.setStatus(message.status); return; } if (message.kind !== "response") return; @@ -178,8 +178,14 @@ export class RpcWalletConnection implements WalletConnection { for (const listener of this.statusListeners) listener(status); } - private disconnect(reason: string): void { - const unknownMutationIds: string[] = []; + private disconnect( + reason: string, + recovery?: Extract<ConnectionStatus, { state: "disconnected" }>["recovery"], + ): void { + const unknownMutationIds: string[] = + this.status.state === "disconnected" + ? [...this.status.unknownMutationIds] + : []; for (const [id, pending] of this.pending) { if (pending.mutation) unknownMutationIds.push(id); const message = pending.mutation @@ -194,7 +200,12 @@ export class RpcWalletConnection implements WalletConnection { ); } this.pending.clear(); - this.setStatus({ state: "disconnected", reason, unknownMutationIds }); + this.setStatus({ + state: "disconnected", + reason, + unknownMutationIds, + recovery, + }); } subscribeNotifications( @@ -210,6 +221,10 @@ export class RpcWalletConnection implements WalletConnection { return () => this.statusListeners.delete(listener); } + retryHost(): void { + this.transport.send({ version: BROWSER_RPC_VERSION, kind: "retry-host" }); + } + close(): void { if (this.closed) return; this.closed = true; diff --git a/packages/wallet-webui/src/platform/extension-background.ts b/packages/wallet-webui/src/platform/extension-background.ts @@ -1,4 +1,8 @@ /// <reference types="chrome" /> +import { + RecoveringWalletHost, + existingDatabaseFactory, +} from "./host-recovery.js"; import { ObservationOwner } from "./observation-owner.js"; import { Result, TalerUriAction, TalerUris } from "@gnu-taler/taler-util"; import { @@ -29,7 +33,21 @@ function disconnectPort(port: chrome.runtime.Port) { observationOwners.delete(port); } const inbox = new StoredActionInbox(new ExtensionSessionActionStore()); -let hostPromise: Promise<RunningWalletHost> | undefined; +const recovery = new RecoveringWalletHost( + (recovering, notify) => + startIndexedDbWalletHost( + recovering ? existingDatabaseFactory(indexedDB) : indexedDB, + notify, + ), + (notification) => + broadcast({ + version: BROWSER_RPC_VERSION, + kind: "notification", + notification, + }), + (status) => + broadcast({ version: BROWSER_RPC_VERSION, kind: "status", status }), +); function sendToPort( port: chrome.runtime.Port, @@ -51,54 +69,33 @@ function broadcast(message: BrowserRpcMessage): void { } } -function getHost(): Promise<RunningWalletHost> { - if (!hostPromise) { - hostPromise = startIndexedDbWalletHost(indexedDB, (notification) => { - broadcast({ - version: BROWSER_RPC_VERSION, - kind: "notification", - notification, - }); - }).catch((error) => { - hostPromise = undefined; - throw error; - }); - } - return hostPromise; +async function getHost(): Promise<RunningWalletHost> { + await recovery.start(); + return recovery; } chrome.runtime.onConnect.addListener((port) => { if (port.name !== "wallet-ui-v1") return; ports.add(port); const owner = new ObservationOwner(async (request) => - (await getHost()).handle(request), + recovery.handle(request), ); observationOwners.set(port, owner); port.onDisconnect.addListener(() => disconnectPort(port)); sendToPort(port, { version: BROWSER_RPC_VERSION, kind: "status", - status: { state: "connecting" }, - } satisfies BrowserRpcMessage); - void getHost().then( - () => - sendToPort(port, { - version: BROWSER_RPC_VERSION, - kind: "status", - status: { state: "connected" }, - } satisfies BrowserRpcMessage), - () => - sendToPort(port, { - version: BROWSER_RPC_VERSION, - kind: "status", - status: { - state: "disconnected", - reason: "wallet host failed to start", - unknownMutationIds: [], - }, - } satisfies BrowserRpcMessage), - ); + status: recovery.status, + }); + void getHost().catch(() => {}); port.onMessage.addListener(async (message: BrowserRpcMessage) => { + if ( + message?.version === BROWSER_RPC_VERSION && + message.kind === "retry-host" + ) { + recovery.retryNow(); + return; + } if (message?.version !== BROWSER_RPC_VERSION || message.kind !== "request") return; let response; @@ -310,11 +307,11 @@ chrome.runtime.onInstalled.addListener(() => { chrome.alarms.onAlarm.addListener((alarm) => { if (alarm.name === "wallet-host-wakeup") { void inbox.cleanup(); - void getHost(); + void getHost().catch(() => {}); } }); // Cold starts are idempotent: every event page/service-worker incarnation -// creates at most one wallet host promise and reopens the existing IDB wallet. +// creates at most one wallet host at a time and reopens the existing IDB wallet. void chrome.alarms.create("wallet-host-wakeup", { periodInMinutes: 1 }); -void getHost(); +void getHost().catch(() => {}); diff --git a/packages/wallet-webui/src/routes/App.tsx b/packages/wallet-webui/src/routes/App.tsx @@ -424,6 +424,35 @@ function ProtocolCapture() { ); } +function HostRecoveryNotice() { + const { connection } = useServices(); + const status = connectionStatus.value; + if (status.state !== "disconnected" || !status.recovery) return null; + return ( + <div role="status" class="m-4 rounded border p-4"> + <p> + {status.recovery.automatic + ? i18n.str`The wallet is recovering its connection. Balances and transaction status will reload automatically.` + : i18n.str`Wallet storage needs attention before it can reconnect.`} + </p> + <details> + <summary>{i18n.str`Error details`}</summary> + <pre class="whitespace-pre-wrap"> + {status.reason} + {"\n"} + {JSON.stringify(status.recovery.detail, null, 2)} + </pre> + </details> + {status.recovery.automatic && ( + <button + type="button" + onClick={() => connection.retryHost?.()} + >{i18n.str`Retry now`}</button> + )} + </div> + ); +} + function WalletShell() { const { connection, demo } = useServices(); const [, navigate] = useLocation(); @@ -464,6 +493,7 @@ function WalletShell() { : undefined } > + <HostRecoveryNotice /> <VisibleRequestProgress /> <Switch> <Route path="/" component={BalanceRoute} /> diff --git a/packages/wallet-webui/src/workers/wallet-worker.ts b/packages/wallet-webui/src/workers/wallet-worker.ts @@ -1,4 +1,9 @@ /// <reference lib="webworker" /> +import { + RecoveringWalletHost, + existingDatabaseFactory, +} from "../platform/host-recovery.js"; +import type { ConnectionStatus } from "../api/contracts.js"; import type { CoreApiRequestEnvelope, WalletNotification, @@ -90,7 +95,14 @@ const pendingStorage = new Map< >(); type CoordinationMessage = - | { version: 1; kind: "leader"; leaderId: string; ready: boolean } + | { + version: 1; + kind: "leader"; + leaderId: string; + ready: boolean; + hostStatus?: ConnectionStatus; + } + | { version: 1; kind: "retry-host" } | { version: 1; kind: "request"; @@ -152,6 +164,7 @@ async function handle( async function openGeneration( generation: StorageGeneration, + recovering = false, ): Promise<WalletDbHandle> { if (generation.backend === "sqlite") { return (await getSqliteGenerationProvider(indexedDB)).open(generation); @@ -163,7 +176,11 @@ async function openGeneration( indexedDB, `taler-wallet-generation-${generation.generation}`, ); - const db = new IdbWalletDbHandle(factory as never); + const db = new IdbWalletDbHandle( + (recovering + ? existingDatabaseFactory(factory as IDBFactory) + : factory) as never, + ); await db.ensureOpen(); return db; } @@ -227,10 +244,36 @@ async function prepareWalletHost( const backendVersion = await verifyGeneration(generation, handle); const buffered: WalletNotification[] = []; let notificationsActive = false; - const running = await startWalletHost(handle, (notification) => { + const notificationSink = (notification: WalletNotification) => { if (notificationsActive) notifyWallet(notification); else buffered.push(notification); - }); + }; + const initialHandle = handle; + let initial = true; + const running = + generation.backend === "indexeddb" + ? new RecoveringWalletHost( + async (_recovering, notify) => { + const db = initial + ? initialHandle + : await openGeneration(generation, true); + initial = false; + return startWalletHost(db, notify); + }, + notificationSink, + (status) => { + if (notificationsActive) recoveryStatus(status); + }, + ) + : await startWalletHost(handle, notificationSink); + if (running instanceof RecoveringWalletHost) { + try { + await running.start(); + } catch (error) { + await running.stop(); + throw error; + } + } handle = undefined; return { running, @@ -252,6 +295,28 @@ async function prepareWalletHost( } } +function recoveryStatus(current: ConnectionStatus): void { + if (current.state === "disconnected") pending.clear(); + const message: BrowserRpcMessage = { + version: 1, + kind: "status", + status: current, + }; + sendUi(message); + channel?.postMessage({ + version: 1, + kind: "broadcast", + message, + } satisfies CoordinationMessage); +} +function currentHostStatus(): ConnectionStatus { + return host instanceof RecoveringWalletHost + ? host.status + : host + ? { state: "connected" } + : { state: "connecting" }; +} + function notifyWallet( notification: Parameters<Parameters<typeof startWalletHost>[1]>[0], ): void { @@ -450,10 +515,31 @@ async function startActiveHost(): Promise<void> { throw new Error(detail); } metadata = await cleanupExpiredGeneration(metadata); - host = await startWalletHost( - await openGeneration(metadata.active), - notifyWallet, - ); + if (metadata.active.backend === "indexeddb") { + const generation = metadata.active; + const recovering = new RecoveringWalletHost( + async (reopening, notify) => + startWalletHost(await openGeneration(generation, reopening), notify), + notifyWallet, + recoveryStatus, + ); + host = recovering; + try { + await recovering.start(); + } catch (error) { + if (migrationBusy) { + host = undefined; + await recovering.stop(); + throw error; + } + // Keep the leadership lock while the owner retries initialization. + } + } else { + host = await startWalletHost( + await openGeneration(metadata.active), + notifyWallet, + ); + } } async function cleanupExpiredGeneration( @@ -1132,8 +1218,8 @@ function flushPending(): void { Date.now() - coordinationStartedAt >= STARTUP_HANDOVER_GRACE_MS; for (const [id, item] of pending) { if (host) { + pending.delete(id); void handle(item.request).then((response) => { - pending.delete(id); sendUi(response); }); } else if ( @@ -1204,7 +1290,7 @@ async function becomeLeader(): Promise<void> { leaderId = clientId; try { await startActiveHost(); - status("connected"); + if (currentHostStatus().state === "connected") status("connected"); } catch (error) { const metadata = await storageManager.readMetadata(); if (metadata.migration.phase !== "recovery-required") throw error; @@ -1217,14 +1303,16 @@ async function becomeLeader(): Promise<void> { version: 1, kind: "leader", leaderId: clientId, - ready: host !== undefined, + ready: currentHostStatus().state === "connected", + hostStatus: currentHostStatus(), } satisfies CoordinationMessage); }, 1500); channel?.postMessage({ version: 1, kind: "leader", leaderId: clientId, - ready: host !== undefined, + ready: currentHostStatus().state === "connected", + hostStatus: currentHostStatus(), } satisfies CoordinationMessage); await new Promise<void>(() => {}); clearInterval(heartbeat); @@ -1271,10 +1359,10 @@ if (!("locks" in navigator) || typeof BroadcastChannel === "undefined") { } leaderId = message.leaderId; lastLeaderSeen = Date.now(); - status( - message.ready ? "connected" : "connecting", - message.ready ? undefined : "wallet storage migration in progress", - ); + if (message.hostStatus) { + if (message.hostStatus.state === "disconnected") pending.clear(); + sendUi({ version: 1, kind: "status", status: message.hostStatus }); + } else status(message.ready ? "connected" : "connecting"); flushPending(); } else if (message.kind === "request" && leaderId === clientId) { const response = host @@ -1299,7 +1387,14 @@ if (!("locks" in navigator) || typeof BroadcastChannel === "undefined") { if (message.response.kind === "response") pending.delete(message.response.response.id); sendUi(message.response); + } else if (message.kind === "retry-host" && leaderId === clientId) { + if (host instanceof RecoveringWalletHost) host.retryNow(); } else if (message.kind === "broadcast") { + if ( + message.message.kind === "status" && + message.message.status.state === "disconnected" + ) + pending.clear(); sendUi(message.message); } else if (message.kind === "storage-request" && leaderId === clientId) { await handleStorageRequest(message.request, message.sender); @@ -1365,6 +1460,15 @@ self.onmessage = async ( flushPending(); return; } + if (message?.version === 1 && message.kind === "retry-host") { + if (host instanceof RecoveringWalletHost) host.retryNow(); + else + channel?.postMessage({ + version: 1, + kind: "retry-host", + } satisfies CoordinationMessage); + return; + } if (!message || message.version !== 1 || message.kind !== "request") return; if (host) { sendUi(await handle(message.request)); diff --git a/packages/wallet-webui/test/rpc.test.ts b/packages/wallet-webui/test/rpc.test.ts @@ -67,3 +67,58 @@ test("disconnect rejects a sent mutation as an unknown outcome without replay", ); assert.equal(transport.sent.length, 1); }); + +test("host recovery status preserves unknown outcomes and prevents new sends", async () => { + const transport = new FakeTransport(); + const connection = new RpcWalletConnection(transport); + const mutation = connection.client.callForResult( + WalletApiOperation.ImportDb, + { dump: {} }, + ); + const recovery = { + automatic: true, + detail: { code: 7001 }, + nextRetryAt: 1000, + }; + for (const listener of transport.messages) + listener({ + version: 1, + kind: "status", + status: { + state: "disconnected", + reason: "database closed", + unknownMutationIds: [], + recovery, + }, + }); + await assert.rejects( + mutation, + (e) => e instanceof HostDisconnectedError && e.outcome === "unknown", + ); + await assert.rejects( + connection.client.callForResult(WalletApiOperation.ImportDb, { dump: {} }), + (e) => e instanceof HostDisconnectedError && e.outcome === "not-sent", + ); + assert.equal(transport.sent.length, 1); + connection.subscribeStatus((status) => { + assert.equal(status.state, "disconnected"); + if (status.state === "disconnected") { + assert.deepEqual(status.recovery, recovery); + assert.equal(status.unknownMutationIds.length, 1); + } + }); + // Repeated leader heartbeats/retry failures must retain uncertain outcomes. + for (const listener of transport.messages) + listener({ + version: 1, + kind: "status", + status: { + state: "disconnected", + reason: "retry failed", + unknownMutationIds: [], + recovery, + }, + }); + connection.retryHost(); + assert.deepEqual(transport.sent.at(-1), { version: 1, kind: "retry-host" }); +});