taler-typescript-core

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

commit 7ed881015f662b2b6b58012d99776b718662d4ca
parent 8f86055c0cbaae66212341aae9319adb9f2a5f52
Author: Florian Dold <dold@taler.net>
Date:   Tue, 10 Nov 2026 16:21:52 +0100

wallet-core: manage snapshots after committed database changes

Diffstat:
Apackages/taler-wallet-core/src/observations.test.ts | 227+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Apackages/taler-wallet-core/src/observations.ts | 252+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/taler-wallet-core/src/wallet.ts | 38+++++++++++++++++++++++++++++++-------
3 files changed, 510 insertions(+), 7 deletions(-)

diff --git a/packages/taler-wallet-core/src/observations.test.ts b/packages/taler-wallet-core/src/observations.test.ts @@ -0,0 +1,227 @@ +/* + * This file is part of GNU Taler + * (C) 2026 Taler Systems S.A. + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + NotificationType, + openPromise, + PeerPushCreditSnapshot, + setDangerousTimetravel, + TimerAPI, + TimerGroup, + TimerHandle, + TransactionMajorState, + TransactionMinorState, + TransactionType, + WalletNotification, +} from "@gnu-taler/taler-util"; +import { WalletObservations } from "./observations.js"; +import { constructTransactionIdentifier } from "./transactions.js"; + +class ManualTimer implements TimerAPI { + now = 0; + pending = new Set<{ due: number; callback: () => void }>(); + after(delay: number, callback: () => void): TimerHandle { + const item = { due: this.now + delay, callback }; + this.pending.add(item); + return { + clear: () => { + this.pending.delete(item); + }, + unref() {}, + }; + } + every(): TimerHandle { + throw Error("unused"); + } + advance(ms = 0): void { + this.now += ms; + for (;;) { + const item = [...this.pending].find((x) => x.due <= this.now); + if (!item) return; + this.pending.delete(item); + item.callback(); + } + } +} + +const transactionId = constructTransactionIdentifier({ + tag: TransactionType.PeerPushCredit, + peerPushCreditId: "credit", +}); + +function snapshot(): PeerPushCreditSnapshot { + return { + transaction: { + type: TransactionType.PeerPushCredit, + transactionId, + timestamp: { t_s: 1 }, + scopes: [], + txState: { + major: TransactionMajorState.Dialog, + minor: TransactionMinorState.Proposed, + }, + txActions: [], + amountRaw: "TESTKUDOS:5", + amountEffective: "TESTKUDOS:4.8", + exchangeBaseUrl: "https://exchange.example/", + info: { summary: "Lunch", expiration: undefined, iconId: undefined }, + }, + exchange: null, + confirmation: { + unavailableReasons: ["exchange-not-ready"], + }, + }; +} + +const flush = () => new Promise<void>((resolve) => setImmediate(resolve)); + +function fixture() { + const timer = new ManualTimer(); + const notifications: WalletNotification[] = []; + const observations = new WalletObservations(new TimerGroup(timer), (n) => + notifications.push(n), + ); + return { timer, notifications, observations }; +} + +test("stopping during the initial read cannot emit a snapshot or retain a subscription", async () => { + const f = fixture(); + const read = openPromise<PeerPushCreditSnapshot | null>(); + const registration = f.observations.registerPeerPushCredit( + "view", + transactionId, + () => read.promise, + ); + f.observations.stop("view"); + read.resolve(snapshot()); + await registration; + f.observations.invalidate(); + f.timer.advance(); + await flush(); + assert.deepEqual(f.notifications, []); + assert.equal(f.timer.pending.size, 0); +}); + +test("stopping or shutting down during an update suppresses its result", async () => { + for (const shutdown of [false, true]) { + const f = fixture(); + const update = openPromise<PeerPushCreditSnapshot | null>(); + let reads = 0; + await f.observations.registerPeerPushCredit( + "view", + transactionId, + async () => (++reads === 1 ? snapshot() : update.promise), + ); + f.observations.invalidate(); + f.timer.advance(); + assert.equal(reads, 2); + if (shutdown) f.observations.shutdown(); + else f.observations.stop("view"); + update.resolve(null); + await flush(); + assert.equal(f.notifications.length, 1); + assert.equal(f.timer.pending.size, 0); + } +}); + +test("updates during a read are serialized and read again before becoming idle", async () => { + const f = fixture(); + const update = openPromise<PeerPushCreditSnapshot | null>(); + let reads = 0; + await f.observations.registerPeerPushCredit( + "view", + transactionId, + async () => { + reads++; + if (reads === 2) return update.promise; + const value = snapshot(); + value.transaction.info.summary = `read ${reads}`; + return value; + }, + ); + f.observations.invalidate(); + f.timer.advance(); + f.observations.invalidate(); + f.observations.invalidate(); + f.timer.advance(); + assert.equal(reads, 2); + update.resolve(snapshot()); + await flush(); + f.timer.advance(); + await flush(); + assert.equal(reads, 3); + assert.deepEqual( + f.notifications.map((n) => + n.type === NotificationType.ObservationSnapshot ? n.revision : undefined, + ), + [1, 2, 3], + ); + f.observations.shutdown(); +}); + +test("initial read errors fail registration, later read errors end only that observation", async () => { + const f = fixture(); + await assert.rejects( + f.observations.registerPeerPushCredit("view", transactionId, async () => { + throw Error("initial error"); + }), + ); + assert.equal(f.notifications.length, 0); + let reads = 0; + await f.observations.registerPeerPushCredit( + "view", + transactionId, + async () => { + if (++reads > 1) throw Error("read failed"); + return snapshot(); + }, + ); + await f.observations.registerPeerPushCredit( + "other", + transactionId, + async () => snapshot(), + ); + f.observations.invalidate(); + f.timer.advance(); + await flush(); + assert.equal(f.notifications.length, 3); + assert.equal(f.notifications[2].type, NotificationType.ObservationError); + f.observations.invalidate(); + f.timer.advance(); + await flush(); + assert.equal(reads, 2); + f.observations.shutdown(); +}); + +test("proposed purse expiration schedules a refresh without a database write", async () => { + const f = fixture(); + let reads = 0; + const expiration = Math.floor(Date.now() / 1000) + 2; + try { + await f.observations.registerPeerPushCredit( + "view", + transactionId, + async () => { + const value = snapshot(); + value.transaction.info.expiration = { t_s: expiration }; + if (++reads > 1) value.confirmation.unavailableReasons.push("expired"); + return value; + }, + ); + assert.equal(reads, 1); + setDangerousTimetravel(3000); + f.timer.advance(3000); + await flush(); + assert.equal(reads, 2); + assert.equal(f.notifications.length, 2); + assert.equal(f.timer.pending.size, 0); + } finally { + setDangerousTimetravel(0); + f.observations.shutdown(); + } +}); diff --git a/packages/taler-wallet-core/src/observations.ts b/packages/taler-wallet-core/src/observations.ts @@ -0,0 +1,252 @@ +/* + * This file is part of GNU Taler + * (C) 2026 Taler Systems S.A. + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { + AbsoluteTime, + canonicalJson, + ErrorInfoSummary, + getErrorDetailFromException, + NotificationType, + ObservationType, + PeerPushCreditSnapshot, + TalerError, + TalerErrorCode, + TalerErrorDetail, + TransactionIdStr, + TimerGroup, + TimerHandle, + WalletNotification, +} from "@gnu-taler/taler-util"; +import type { WalletDbTransaction } from "./db/transaction.js"; + +/** Keep arbitrary protocol response bodies out of recurring snapshots. */ +export function summarizeObservationError( + error: TalerErrorDetail | undefined, +): ErrorInfoSummary | undefined { + if (!error) return undefined; + return { + code: error.code, + hint: + typeof error.hint === "string" ? error.hint.slice(0, 1024) : undefined, + message: + typeof error.message === "string" + ? error.message.slice(0, 1024) + : undefined, + }; +} + +export function validateObservationId(observationId: string): void { + if (!observationId.length || observationId.length > 256) { + throw TalerError.fromDetail( + TalerErrorCode.WALLET_CORE_API_BAD_REQUEST, + { parameter: "observationId" }, + "observationId must contain between 1 and 256 characters", + ); + } +} + +interface PeerPushCreditObservation { + observationId: string; + transactionId: TransactionIdStr; + read: () => Promise<PeerPushCreditSnapshot | null>; + revision: number; + lastValue?: string; + running: boolean; + dirty: boolean; + timer?: TimerHandle; +} + +/** In-memory subscriptions, independent of the registering request's lifetime. */ +export class WalletObservations { + private entries = new Map<string, PeerPushCreditObservation>(); + private stopped = false; + + constructor( + private timers: TimerGroup, + private notify: (notification: WalletNotification) => void, + ) {} + + async registerPeerPushCredit( + observationId: string, + transactionId: TransactionIdStr, + read: () => Promise<PeerPushCreditSnapshot | null>, + ): Promise<void> { + validateObservationId(observationId); + if (this.stopped || this.entries.has(observationId)) { + throw TalerError.fromDetail( + TalerErrorCode.WALLET_CORE_API_BAD_REQUEST, + { parameter: "observationId" }, + this.stopped ? "wallet has stopped" : "observationId is already active", + ); + } + const entry: PeerPushCreditObservation = { + observationId, + transactionId, + read, + revision: 0, + running: true, + dirty: false, + }; + // Install before reading: writes during the first read must mark it dirty. + this.entries.set(observationId, entry); + try { + const snapshot = await read(); + if (!this.isActive(entry)) return; + if (!snapshot) { + throw TalerError.fromDetail( + TalerErrorCode.WALLET_TRANSACTION_NOT_FOUND, + { transactionId }, + "observed transaction does not exist", + ); + } + this.publish(entry, snapshot); + } catch (e) { + if (this.isActive(entry)) this.stop(observationId); + throw e; + } finally { + entry.running = false; + if (entry.dirty) this.schedule(entry); + } + } + + invalidate(): void { + for (const entry of this.entries.values()) { + entry.dirty = true; + this.schedule(entry); + } + } + + stop(observationId: string): void { + const entry = this.entries.get(observationId); + if (!entry) return; + entry.timer?.clear(); + this.entries.delete(observationId); + } + + shutdown(): void { + this.stopped = true; + for (const id of this.entries.keys()) this.stop(id); + } + + private isActive(entry: PeerPushCreditObservation): boolean { + return this.entries.get(entry.observationId) === entry; + } + + private schedule(entry: PeerPushCreditObservation): void { + if (!this.isActive(entry) || entry.running) return; + entry.timer?.clear(); + entry.timer = this.timers.after(0, () => { + entry.timer = undefined; + void this.refresh(entry); + }); + } + + private async refresh(entry: PeerPushCreditObservation): Promise<void> { + if (!this.isActive(entry)) return; + entry.running = true; + entry.dirty = false; + try { + const snapshot = await entry.read(); + if (this.isActive(entry)) this.publish(entry, snapshot); + } catch (e) { + if (this.isActive(entry)) { + this.notify({ + type: NotificationType.ObservationError, + observationType: ObservationType.PeerPushCredit, + observationId: entry.observationId, + error: summarizeObservationError(getErrorDetailFromException(e))!, + }); + this.stop(entry.observationId); + } + } finally { + entry.running = false; + if (entry.dirty) this.schedule(entry); + } + } + + private publish( + entry: PeerPushCreditObservation, + snapshot: PeerPushCreditSnapshot | null, + ): void { + // Compare exactly what can appear on the wire (undefined fields omitted). + const value = canonicalJson(JSON.parse(JSON.stringify(snapshot))); + if (value !== entry.lastValue) { + entry.lastValue = value; + this.notify({ + type: NotificationType.ObservationSnapshot, + observationType: ObservationType.PeerPushCredit, + observationId: entry.observationId, + transactionId: entry.transactionId, + revision: ++entry.revision, + snapshot, + }); + } + if (!snapshot) { + this.stop(entry.observationId); + return; + } + // Confirmation can become unavailable without a database write. + const expiration = snapshot.transaction.info.expiration?.t_s; + const now = AbsoluteTime.now().t_ms; + if ( + typeof expiration === "number" && + typeof now === "number" && + !snapshot.confirmation.unavailableReasons.includes("not-proposed") && + !snapshot.confirmation.unavailableReasons.includes("expired") + ) { + entry.timer = this.timers.after( + Math.min(0x7fffffff, Math.max(1, expiration * 1000 - now + 1)), + () => { + entry.timer = undefined; + entry.dirty = true; + this.schedule(entry); + }, + ); + entry.timer.unref(); + } + } +} + +/** All persistent inputs read by peer credit snapshots, including amount recovery. */ +const observationInputWrites = new Set<string>([ + ...[ + "PeerPushCredit", + "WithdrawalGroup", + "OperationRetry", + "Exchange", + "ExchangeDetails", + "Reserve", + "ContractTerms", + "TransactionMeta", + "GlobalCurrencyExchange", + "GlobalCurrencyAuditor", + "CurrencyInfo", + "CurrencyInfoEntry", + "Coin", + "Denomination", + "DenominationFamily", + ].flatMap((name) => [`upsert${name}`, `delete${name}`]), + "deleteAllTransactionMeta", + "insertCurrencyInfoUnlessExists", +]); + +/** The caller invokes onChange only after the enclosing transaction commits. */ +export function watchObservationInputs( + tx: WalletDbTransaction, + markChanged: () => void, +): WalletDbTransaction { + return new Proxy(tx, { + get(target, prop, receiver) { + const value = Reflect.get(target, prop, receiver); + if (typeof value !== "function") return value; + return (...args: unknown[]) => { + if (typeof prop === "string" && observationInputWrites.has(prop)) + markChanged(); + return value.apply(target, args); + }; + }, + }); +} diff --git a/packages/taler-wallet-core/src/wallet.ts b/packages/taler-wallet-core/src/wallet.ts @@ -141,6 +141,7 @@ import { } from "./wallet-api-types.js"; import { updateWithdrawalDenomsForExchange } from "./withdraw.js"; import { MaintenanceNotificationThrottler } from "./maintenance-notifications.js"; +import { WalletObservations, watchObservationInputs } from "./observations.js"; const logger = new Logger("wallet.ts"); @@ -319,7 +320,8 @@ export class AdmittedWalletDbHandle implements WalletDbHandle { if (!fn) { throw Error("current database backend cannot import a foreign dump"); } - return await fn.apply(db, args); + await fn.apply(db, args); + this.onObservationInputsChanged(); }, args[2]?.cancellationToken); } @@ -331,10 +333,22 @@ export class AdmittedWalletDbHandle implements WalletDbHandle { constructor( private current: () => WalletDbHandle, private gate: DbOperationGate, + private onObservationInputsChanged: () => void = () => {}, ) {} runReadWriteTx<T>(f: (tx: WalletDbTransaction) => Promise<T>): Promise<T> { - return this.gate.runShared(() => this.current().runReadWriteTx(f)); + return this.gate.runShared(async () => { + let changed = false; + const result = await this.current().runReadWriteTx((tx) => + f( + watchObservationInputs(tx, () => { + changed = true; + }), + ), + ); + if (changed) this.onObservationInputsChanged(); + return result; + }); } exportDatabase(): Promise<any> { return this.gate.runShared(() => this.current().exportDatabase()); @@ -344,13 +358,16 @@ export class AdmittedWalletDbHandle implements WalletDbHandle { finalize: Parameters<WalletDbHandle["importDatabase"]>[1], options?: Parameters<WalletDbHandle["importDatabase"]>[2], ): Promise<void> { - return this.gate.runExclusive( - () => this.current().importDatabase(dump, finalize, options), - options?.cancellationToken, - ); + return this.gate.runExclusive(async () => { + await this.current().importDatabase(dump, finalize, options); + this.onObservationInputsChanged(); + }, options?.cancellationToken); } clearDatabase(): Promise<void> { - return this.gate.runExclusive(() => this.current().clearDatabase()); + return this.gate.runExclusive(async () => { + await this.current().clearDatabase(); + this.onObservationInputsChanged(); + }); } getAccessStats() { return this.current().getAccessStats(); @@ -1321,6 +1338,7 @@ export class InternalWalletState { private cryptoDispatcher: CryptoDispatcher; readonly timerGroup: TimerGroup; + readonly observations: WalletObservations; stopped = false; private listeners: NotificationListener[] = []; @@ -1605,10 +1623,14 @@ export class InternalWalletState { this.admittedDb = new AdmittedWalletDbHandle( () => this.dbHandle, this.dbOperationGate, + () => this.observations.invalidate(), ); this.cryptoDispatcher = new CryptoDispatcher(cryptoWorkerFactory); this.cryptoApi = this.cryptoDispatcher.cryptoApi; this.timerGroup = new TimerGroup(timer); + this.observations = new WalletObservations(this.timerGroup, (n) => + this.notify(n), + ); this.maintenanceNotifications = new MaintenanceNotificationThrottler( timer, (n) => this.deliverNotificationSynchronously(n), @@ -1810,6 +1832,7 @@ export class InternalWalletState { ); } this.clearAllCaches(); + this.observations.invalidate(); return true; } catch (e) { logger.error( @@ -1928,6 +1951,7 @@ export class InternalWalletState { if (this.stopped) return; logger.trace("stopping (at internal wallet state)"); this.stopped = true; + this.observations.shutdown(); this.maintenanceNotifications.stop(); this.timerGroup.stopCurrentAndFutureTimers(); this.cryptoDispatcher.stop();