taler-typescript-core

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

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

wallet host: restart after database or initialization failures

Diffstat:
Mpackages/wallet-webui/src/api/contracts.ts | 8+++++++-
Apackages/wallet-webui/src/platform/host-recovery.ts | 215+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Apackages/wallet-webui/test/host-recovery.test.ts | 192+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 414 insertions(+), 1 deletion(-)

diff --git a/packages/wallet-webui/src/api/contracts.ts b/packages/wallet-webui/src/api/contracts.ts @@ -4,12 +4,18 @@ import type { WalletCoreApiClient } from "@gnu-taler/taler-wallet-core"; export type ConnectionStatus = | { state: "connecting" } | { state: "connected" } - | { state: "disconnected"; reason: string; unknownMutationIds: string[] }; + | { + state: "disconnected"; + reason: string; + unknownMutationIds: string[]; + recovery?: { detail: unknown; automatic: boolean; nextRetryAt?: number }; + }; export interface WalletConnection { readonly client: WalletCoreApiClient; subscribeNotifications(listener: (n: WalletNotification) => void): () => void; subscribeStatus(listener: (status: ConnectionStatus) => void): () => void; + retryHost?(): void; close(): void; } diff --git a/packages/wallet-webui/src/platform/host-recovery.ts b/packages/wallet-webui/src/platform/host-recovery.ts @@ -0,0 +1,215 @@ +/* + * This file is part of GNU Taler + * (C) 2026 Taler Systems S.A. + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +import { + getErrorDetailFromException, + type CoreApiRequestEnvelope, + type CoreApiResponse, + type WalletNotification, +} from "@gnu-taler/taler-util"; +import type { ConnectionStatus } from "../api/contracts.js"; +import { unavailableCoreResponse } from "../api/rpc.js"; +import type { RunningWalletHost } from "./wallet-host.js"; + +const delays = [0, 1000, 2000, 4000, 8000, 16000, 32000, 60000]; + +/** One owner, one host generation, no replay of requests across generations. */ +export class RecoveringWalletHost implements RunningWalletHost { + status: ConnectionStatus = { state: "connecting" }; + private current?: RunningWalletHost; + private unsubscribe?: () => void; + private attempt?: Promise<void>; + private retiring: Promise<void> = Promise.resolve(); + private timer?: ReturnType<typeof setTimeout>; + private failures = 0; + private generation = 0; + private stopped = false; + private stopPromise?: Promise<void>; + private opened = false; + private terminal = false; + + constructor( + private create: ( + recovering: boolean, + notify: (n: WalletNotification) => void, + ) => Promise<RunningWalletHost>, + private notify: (n: WalletNotification) => void, + private changed: (status: ConnectionStatus) => void, + ) {} + + private publish(status: ConnectionStatus) { + this.status = status; + this.changed(status); + } + + private failed(error: unknown) { + if (this.stopped) return; + const detail = getErrorDetailFromException(error); + const reason = error instanceof Error ? error.message : String(error); + // Nested database-open errors preserve their DOMException as cause. + let cause = error; + while (cause instanceof Error) { + if ( + cause.name === "VersionError" || + cause.name === "StorageRecoveryRequired" + ) + this.terminal = true; + cause = cause.cause; + } + const delay = delays[Math.min(this.failures++, delays.length - 1)]; + this.publish({ + state: "disconnected", + reason, + unknownMutationIds: [], + recovery: { + detail, + automatic: !this.terminal, + nextRetryAt: this.terminal ? undefined : Date.now() + delay, + }, + }); + if (!this.terminal) + this.timer = setTimeout(() => { + this.timer = undefined; + void this.start().catch(() => {}); + }, delay); + } + + private lost(host: RunningWalletHost, error: Error) { + if (this.current !== host || this.stopped) return; + this.current = undefined; + this.generation++; + this.unsubscribe?.(); + this.unsubscribe = undefined; + // Never create another writer until teardown has finished. + this.retiring = host.stop(); + void this.retiring.catch(() => {}); + this.failed(error); + } + + start(): Promise<void> { + if (this.stopped || this.current || this.terminal) return Promise.resolve(); + if (this.attempt) return this.attempt; + if (this.timer !== undefined) return Promise.resolve(); + const generation = ++this.generation; + const run = async () => { + try { + await this.retiring; + if (this.stopped) return; + const reopening = this.opened; + this.opened = true; + const host = await this.create(reopening, (n) => { + if (!this.stopped && generation === this.generation) this.notify(n); + }); + if (this.stopped) { + await host.stop(); + return; + } + this.current = host; + const unsubscribe = host.subscribeUnavailable?.((error) => + this.lost(host, error), + ); + if (this.current === host) this.unsubscribe = unsubscribe; + else unsubscribe?.(); + if (this.current === host) this.publish({ state: "connected" }); + } catch (error) { + this.failed(error); + throw error; + } + }; + this.attempt = run().finally(() => { + this.attempt = undefined; + }); + return this.attempt; + } + + retryNow() { + if (this.terminal || this.stopped) return; + clearTimeout(this.timer); + this.timer = undefined; + void this.start().catch(() => {}); + } + + async handle(request: CoreApiRequestEnvelope) { + if (this.status.state === "connecting") await this.start().catch(() => {}); + const host = this.current; + if (!host || this.stopped) + return unavailableCoreResponse( + request, + "Wallet host is recovering; request was not sent", + ); + let response: CoreApiResponse; + try { + response = await host.handle(request); + } catch (error) { + response = { + type: "error", + id: request.id, + operation: request.operation, + error: getErrorDetailFromException(error), + }; + } + if (this.current !== host) + return unavailableCoreResponse( + request, + "Wallet host was interrupted; outcome may be unknown", + ); + if (response.type === "response") this.failures = 0; + return response; + } + + stop(): Promise<void> { + return (this.stopPromise ??= this.stopOnce()); + } + + private async stopOnce() { + this.stopped = true; + this.generation++; + clearTimeout(this.timer); + this.timer = undefined; + this.unsubscribe?.(); + const host = this.current; + this.current = undefined; + await this.attempt?.catch(() => {}); + await this.retiring; + await host?.stop(); + } +} + +/** Recovery must never turn a deleted database into a new empty wallet. */ +export function existingDatabaseFactory(factory: IDBFactory): IDBFactory { + return new Proxy(factory, { + get(target, property) { + if (property === "open") + return (name: string, version?: number) => { + const request = target.open(name, version); + let missing = false; + request.addEventListener("upgradeneeded", (event) => { + if (event.oldVersion === 0) { + missing = true; + request.transaction?.abort(); + } + }); + return new Proxy(request, { + get(target, property) { + if (property === "error" && missing) + return Object.assign( + new Error( + "Existing wallet database is missing; storage recovery is required", + ), + { name: "StorageRecoveryRequired" }, + ); + const value = Reflect.get(target, property, target); + return typeof value === "function" ? value.bind(target) : value; + }, + set(target, property, value) { + return Reflect.set(target, property, value, target); + }, + }); + }; + const value = Reflect.get(target, property, target); + return typeof value === "function" ? value.bind(target) : value; + }, + }); +} diff --git a/packages/wallet-webui/test/host-recovery.test.ts b/packages/wallet-webui/test/host-recovery.test.ts @@ -0,0 +1,192 @@ +/* + * This file is part of GNU Taler + * (C) 2026 Taler Systems S.A. + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { RecoveringWalletHost } from "../src/platform/host-recovery.js"; +import type { ConnectionStatus } from "../src/api/contracts.js"; +import type { RunningWalletHost } from "../src/platform/wallet-host.js"; +const tick = () => new Promise<void>((r) => setImmediate(r)); + +test("closed host is stopped once; recovery never replays an interrupted request", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 1000 }); + let fail!: (error: Error) => void, complete!: () => void; + let starts = 0, + stops = 0, + requests = 0; + const statuses: ConnectionStatus[] = []; + const recovery = new RecoveringWalletHost( + async (reopening) => { + assert.equal(reopening, starts++ > 0); + return { + subscribeUnavailable(listener) { + fail = listener; + return () => {}; + }, + async stop() { + stops++; + }, + async handle(request) { + requests++; + await new Promise<void>((r) => (complete = r)); + return { type: "response", ...request, result: {} }; + }, + } as RunningWalletHost; + }, + () => {}, + (s) => statuses.push(s), + ); + t.after(() => recovery.stop()); + await Promise.all([recovery.start(), recovery.start()]); + const request = recovery.handle({ + id: "pay", + operation: "confirmPay", + args: {}, + }); + fail(new Error("database closed")); + fail(new Error("duplicate event")); + t.mock.timers.tick(0); + await tick(); + assert.equal(starts, 2); + assert.equal(stops, 1); + complete(); + await request; + assert.equal(requests, 1); + assert.deepEqual( + statuses.map((s) => s.state), + ["connected", "disconnected", "connected"], + ); +}); + +test("failed initialization backs off, coalesces retries and keeps diagnostics", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 1000 }); + let attempts = 0; + const recovery = new RecoveringWalletHost( + async () => { + attempts++; + throw Error("injected init failure"); + }, + () => {}, + () => {}, + ); + t.after(() => recovery.stop()); + await assert.rejects(recovery.start()); + t.mock.timers.tick(0); + await tick(); + assert.equal(attempts, 2); + await recovery.start(); + assert.equal(attempts, 2); + t.mock.timers.tick(999); + await tick(); + assert.equal(attempts, 2); + t.mock.timers.tick(1); + await tick(); + assert.equal(attempts, 3); + assert.equal(recovery.status.state, "disconnected"); + recovery.retryNow(); + recovery.retryNow(); + await tick(); + assert.equal(attempts, 4); + for (const delay of [4000, 8000, 16000, 32000, 60000, 60000]) { + const before: number = attempts; + t.mock.timers.tick(delay - 1); + await tick(); + assert.equal(attempts, before); + t.mock.timers.tick(1); + await tick(); + assert.equal(attempts, before + 1); + } +}); + +test("incompatible storage stops retries", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout"] }); + let attempts = 0; + const recovery = new RecoveringWalletHost( + async () => { + attempts++; + throw Object.assign(Error("schema too new"), { name: "VersionError" }); + }, + () => {}, + () => {}, + ); + await assert.rejects(recovery.start()); + recovery.retryNow(); + t.mock.timers.tick(120000); + await tick(); + assert.equal(attempts, 1); + assert.equal( + recovery.status.state === "disconnected" && + recovery.status.recovery?.automatic, + false, + ); + await recovery.stop(); +}); + +test("replacement waits for teardown and ignores retired notifications", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout"] }); + let fail!: (error: Error) => void, finishStop!: () => void; + let oldNotify!: (n: any) => void; + let starts = 0, + notifications = 0; + const recovery = new RecoveringWalletHost( + async (_reopening, notify) => { + const first = starts++ === 0; + if (first) oldNotify = notify; + return { + subscribeUnavailable(listener) { + fail = listener; + return () => {}; + }, + stop: () => + first + ? new Promise<void>((r) => (finishStop = r)) + : Promise.resolve(), + handle: async (request) => ({ + type: "response", + ...request, + result: {}, + }), + } as RunningWalletHost; + }, + () => notifications++, + () => {}, + ); + await recovery.start(); + fail(Error("closed")); + oldNotify({ type: "balance-change" }); + t.mock.timers.tick(0); + await tick(); + assert.equal(starts, 1); + finishStop(); + await tick(); + assert.equal(starts, 2); + assert.equal(notifications, 0); + await Promise.all([recovery.stop(), recovery.stop()]); +}); + +test("a synchronous host failure returns an error without replaying the request", async () => { + let requests = 0; + const recovery = new RecoveringWalletHost( + async () => ({ + stop: async () => {}, + handle() { + requests++; + throw Error("injected dispatch failure"); + }, + }), + () => {}, + () => {}, + ); + await recovery.start(); + const response = await recovery.handle({ + id: "pay", + operation: "confirmPay", + args: {}, + }); + assert.equal(response.type, "error"); + assert.equal(requests, 1); + assert.match(JSON.stringify(response), /injected dispatch failure/); + await recovery.stop(); +});