taler-typescript-core

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

commit d83b7d8ef49ab72bfe5b8ef063a08c0733f68ea2
parent 1a95ebbf2e64e89528f3d25c0b76e5686f7b971e
Author: Florian Dold <dold@taler.net>
Date:   Wed, 25 Nov 2026 18:50:44 +0100

wallet-core: provide watch handles for wallet views

Return a handle as soon as a view subscribes so it can dispose of a
pending registration. Renew live watches together and wait for a fresh
snapshot after a disconnect or a missed lease.

Issue: https://bugs.taler.net/n/11794

Diffstat:
Mdoc/wallet-observations.md | 30++++++++++++++++++++++++++++++
Mpackages/taler-wallet-core/src/index.ts | 1+
Apackages/taler-wallet-core/src/observation-client.ts | 355+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/wallet-webui/test/observations.test.ts | 165++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
4 files changed, 517 insertions(+), 34 deletions(-)

diff --git a/doc/wallet-observations.md b/doc/wallet-observations.md @@ -5,6 +5,30 @@ implementing https://bugs.gnunet.org/view?id=11794. `observeTransaction` support all transaction types. Preparation remains a separate operation and supplies the transaction ID to observe. +## Watching a view + +Use `createWalletObservationClient` from `@gnu-taler/taler-wallet-core` with a +connection that exposes its RPC client, notifications and current connection +status. `watchTransaction`, `watchBalanceRefreshInfo` and `watchUserAttention` +return a handle synchronously, including while registration is pending. + +```typescript +const observations = createWalletObservationClient(connection); +const watch = observations.watchTransaction(transactionId, (view) => { + renderTransaction(view); + setConfirmEnabled(view.status === "ready" && canConfirm(view.snapshot)); +}); + +// Retry a failed view or release it when its screen closes. +retryButton.onclick = () => watch.retry(); +onScreenClose(() => watch.dispose()); +``` + +A connected watch starts loading and becomes ready on its first snapshot. While loading, +disconnected or failed, it can retain the previous snapshot for display. +Reconnecting or losing a lease starts a new registration and waits for its first +snapshot. Deletion is terminal. + ## Register and receive Install the notification listener before making this request: @@ -111,6 +135,12 @@ registration and its timers, suppresses pending reads and emits same deadline when it resumes. Omitting `lease` retains the original lifetime, so losing a stop can leave a raw registration in memory until wallet shutdown. +The client probes each connected host with an empty renewal batch before +registering, then renews its active IDs together once a minute. Disposing a +watch removes it from that batch immediately. A lost stop or a crashed tab +therefore leaves at most the remainder of one lease once the host can run. +A live client continues renewing a handle until it is disposed or terminates. + Call `stopObservation({ observationId })` when closing a view. It is idempotent and cancels observation, not transaction processing. Remove the UI routing entry before stopping because notifications already queued on the transport can still diff --git a/packages/taler-wallet-core/src/index.ts b/packages/taler-wallet-core/src/index.ts @@ -30,6 +30,7 @@ export { SynchronousCryptoWorkerFactoryPlain } from "./crypto/workers/synchronou export * from "./host-common.js"; export * from "./host.js"; export * from "./versions.js"; +export * from "./observation-client.js"; export * from "./wallet-api-types.js"; export * from "./wallet.js"; diff --git a/packages/taler-wallet-core/src/observation-client.ts b/packages/taler-wallet-core/src/observation-client.ts @@ -0,0 +1,355 @@ +/* + * This file is part of GNU Taler + * (C) 2026 Taler Systems S.A. + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { + encodeCrock, + getRandomBytes, + NotificationType, + observationLeaseDurationMs, + ObservationType, + stringifyScopeInfo, + timer, + type ObservationSnapshotNotification, + type ScopeInfo, + type TimerHandle, + type TransactionIdStr, + type TransactionSnapshot, + type UserAttentionSnapshot, + type WalletNotification, + type WalletRefreshInfo, +} from "@gnu-taler/taler-util"; +import { + WalletApiOperation, + type WalletCoreApiClient, +} from "./wallet-api-types.js"; + +export type ObservationState<T> = + | { status: "loading"; snapshot?: T } + | { status: "ready"; snapshot: T } + | { status: "disconnected"; snapshot?: T } + | { status: "failed"; error: Error; snapshot?: T } + | { status: "deleted" }; + +export interface ObservationHandle { + dispose(): void; + retry(): void; +} + +export interface WalletObservationConnection { + readonly client: Pick<WalletCoreApiClient, "call">; + subscribeNotifications(listener: (n: WalletNotification) => void): () => void; + /** Optional wakeup before interacting with a previously suspended UI. */ + subscribeResume?(listener: () => void): () => void; + /** Immediately delivers the current status, then every host disconnection/reconnection. */ + subscribeStatus( + listener: (s: { + state: "connecting" | "disconnected" | "connected"; + }) => void, + ): () => void; +} + +type Listener<T> = (state: ObservationState<T>) => void; +export interface WalletObservationClient { + watchTransaction( + transactionId: TransactionIdStr, + changed: Listener<TransactionSnapshot>, + ): ObservationHandle; + watchBalanceRefreshInfo( + scope: ScopeInfo, + changed: Listener<WalletRefreshInfo>, + ): ObservationHandle; + watchUserAttention( + changed: Listener<UserAttentionSnapshot>, + ): ObservationHandle; +} + +interface Watch { + restart(): void; + disconnect(): void; + receive(n: WalletNotification): void; +} + +const clients = new WeakMap< + WalletObservationConnection, + WalletObservationClient +>(); + +/** Share a capability probe, notification listener and renewal batch on one connection. */ +export function createWalletObservationClient( + connection: WalletObservationConnection, +): WalletObservationClient { + const existing = clients.get(connection); + if (existing) return existing; + const watches = new Set<Watch>(); + const active = new Map<string, { watch: Watch; expiresAt: number }>(); + let connected = false; + let epoch = 0; + let support: Promise<void> | undefined; + let probeFailed = false; + let unsubscribe: (() => void) | undefined; + let heartbeat: TimerHandle | undefined; + let unsubscribeResume: (() => void) | undefined; + + function probe(): Promise<void> { + if (support) return support; + const host = epoch; + probeFailed = false; + return (support = connection.client + .call(WalletApiOperation.RenewObservations, { observationIds: [] }) + .then((result) => { + if ( + !Array.isArray(result?.missingObservationIds) || + result.missingObservationIds.length + ) + throw Error("Wallet host does not support observation leases"); + }) + .catch((error: unknown) => { + if (epoch === host) probeFailed = true; + throw error; + })); + } + + function stop(id: string) { + void connection.client + .call(WalletApiOperation.StopObservation, { observationId: id }) + .catch(() => {}); + } + + function expireLocal(now: number) { + for (const entry of active.values()) { + if (entry.expiresAt <= now) entry.watch.restart(); + } + } + + async function renew() { + const sentAt = Date.now(); + expireLocal(sentAt); + const ids = [...active.keys()]; + if (!ids.length) return; + // A late reply can only extend the IDs in this batch, from its send time. + // A lost renewal is retried on the next tick while the local lease is live. + try { + const { missingObservationIds } = await connection.client.call( + WalletApiOperation.RenewObservations, + { observationIds: ids }, + ); + const missing = new Set(missingObservationIds); + const now = Date.now(); + for (const id of ids) { + const entry = active.get(id); + if (!entry) continue; + if (missing.has(id) || now >= entry.expiresAt) entry.watch.restart(); + else + entry.expiresAt = Math.max( + entry.expiresAt, + sentAt + observationLeaseDurationMs, + ); + } + } catch { + expireLocal(Date.now()); + } + } + + function receive(n: WalletNotification) { + if (!("observationId" in n)) return; + const entry = active.get(n.observationId); + if (!entry) return; + if (Date.now() >= entry.expiresAt) entry.watch.restart(); + else entry.watch.receive(n); + } + + function resume() { + expireLocal(Date.now()); + } + + connection.subscribeStatus(({ state }) => { + const next = state === "connected"; + if (connected === next) { + if (next) expireLocal(Date.now()); + return; + } + connected = next; + ++epoch; + support = undefined; + for (const watch of watches) { + if (next) watch.restart(); + else watch.disconnect(); + } + }); + + function watch<T>( + type: ObservationType, + register: (id: string) => Promise<unknown>, + select: (n: ObservationSnapshotNotification) => T | null | undefined, + changed: Listener<T>, + ): ObservationHandle { + let snapshot: T | undefined; + let id: string | undefined; + let revision = 0; + let attempt = 0; + + function forget(sendStop: boolean) { + ++attempt; + if (id === undefined) return; + active.delete(id); + if (!active.size) { + heartbeat?.clear(); + heartbeat = undefined; + } + const old = id; + id = undefined; + if (sendStop) stop(old); + } + function remove() { + watches.delete(controller); + if (watches.size) return; + unsubscribe?.(); + unsubscribe = undefined; + unsubscribeResume?.(); + unsubscribeResume = undefined; + } + const controller: Watch = { + restart() { + if (!connected || !watches.has(controller)) return; + forget(true); + const current = attempt; + const host = epoch; + changed({ status: "loading", snapshot }); + void (async () => { + await probe(); + if (current !== attempt) return; + const newId = encodeCrock(getRandomBytes(24)); + id = newId; + revision = 0; + active.set(id, { + watch: controller, + expiresAt: Date.now() + observationLeaseDurationMs, + }); + if (!heartbeat) { + heartbeat = timer.every(60_000, () => void renew()); + heartbeat.unref(); + } + await register(id); + // Disposal may have raced installation on asynchronous transports. + if (current !== attempt && host === epoch) stop(newId); + })().catch((err: unknown) => { + if (current !== attempt) return; + forget(true); + changed({ + status: "failed", + snapshot, + error: err instanceof Error ? err : new Error(String(err)), + }); + }); + }, + disconnect() { + forget(false); + changed({ status: "disconnected", snapshot }); + }, + receive(n) { + if (!("observationId" in n) || n.observationType !== type) return; + if (n.type === NotificationType.ObservationEnded) { + controller.restart(); + } else if (n.type === NotificationType.ObservationError) { + forget(false); + changed({ + status: "failed", + snapshot, + error: new Error( + n.error.hint ?? n.error.message ?? "Wallet observation failed", + ), + }); + } else if ( + n.type === NotificationType.ObservationSnapshot && + n.revision > revision + ) { + const value = select(n); + if (value === undefined) return; + revision = n.revision; + if (value === null) { + forget(false); + remove(); + changed({ status: "deleted" }); + } else { + snapshot = value; + changed({ status: "ready", snapshot }); + } + } + }, + }; + watches.add(controller); + unsubscribe ??= connection.subscribeNotifications(receive); + unsubscribeResume ??= connection.subscribeResume?.(resume); + if (connected) controller.restart(); + else controller.disconnect(); + return { + retry() { + if (probeFailed) support = undefined; + controller.restart(); + }, + dispose() { + forget(true); + remove(); + }, + }; + } + + const { client } = connection; + const result: WalletObservationClient = { + watchTransaction(transactionId, changed) { + return watch( + ObservationType.Transaction, + (observationId) => + client.call(WalletApiOperation.ObserveTransaction, { + transactionId, + observationId, + lease: true, + }), + (n) => + n.observationType === ObservationType.Transaction && + n.transactionId === transactionId + ? n.snapshot + : undefined, + changed, + ); + }, + watchBalanceRefreshInfo(scopeInfo, changed) { + const key = stringifyScopeInfo(scopeInfo); + return watch( + ObservationType.BalanceRefreshInfo, + (observationId) => + client.call(WalletApiOperation.ObserveBalanceRefreshInfo, { + scopeInfo, + observationId, + lease: true, + }), + (n) => + n.observationType === ObservationType.BalanceRefreshInfo && + stringifyScopeInfo(n.scopeInfo) === key + ? n.snapshot + : undefined, + changed, + ); + }, + watchUserAttention(changed) { + return watch( + ObservationType.UserAttention, + (observationId) => + client.call(WalletApiOperation.ObserveUserAttention, { + observationId, + lease: true, + }), + (n) => + n.observationType === ObservationType.UserAttention + ? n.snapshot + : undefined, + changed, + ); + }, + }; + clients.set(connection, result); + return result; +} diff --git a/packages/wallet-webui/test/observations.test.ts b/packages/wallet-webui/test/observations.test.ts @@ -20,9 +20,15 @@ import { type TransactionIdStr, type CoreApiRequestEnvelope, type CoreApiResponse, + type RenewObservationsRequest, + type ObserveUserAttentionRequest, } from "@gnu-taler/taler-util"; -import { WalletApiOperation } from "@gnu-taler/taler-wallet-core"; -import { TransactionObservation } from "../src/api/observations.js"; +import { + createWalletObservationClient, + type ObservationState, + WalletApiOperation, +} from "@gnu-taler/taler-wallet-core"; +import type { TransactionSnapshot } from "@gnu-taler/taler-util"; import type { ConnectionStatus, WalletConnection, @@ -59,7 +65,22 @@ const snapshot: PeerPushCreditSnapshot = { confirmation: { unavailableReasons: ["not-proposed"] }, }; const tick = () => new Promise<void>((resolve) => setImmediate(resolve)); -function fixture() { +function observe(connection: WalletConnection, id: TransactionIdStr) { + let state: ObservationState<TransactionSnapshot> = { status: "loading" }; + const handle = createWalletObservationClient(connection).watchTransaction( + id, + (value) => (state = value), + ); + return { + ...handle, + get state() { + return state; + }, + }; +} +type TransactionObservation = ReturnType<typeof observe>; + +async function fixture() { const notifications = new Set<(n: WalletNotification) => void>(); let statusListener: (s: ConnectionStatus) => void = () => {}; let ack!: () => void; @@ -69,6 +90,8 @@ function fixture() { client: { async call(op: string, args: { observationId: string }) { calls.push({ op, id: args.observationId }); + if (op === WalletApiOperation.RenewObservations) + return { missingObservationIds: [] }; if (op === WalletApiOperation.ObserveTransaction) await acknowledgement; return {}; }, @@ -104,15 +127,14 @@ function fixture() { revision, snapshot: value, }); - let serial = 0; - const observer = new TransactionObservation( - connection, - transactionId, - () => {}, - () => `view-${++serial}`, - ); + const observer = observe(connection, transactionId); + const id = (index: number) => + calls.filter((c) => c.op === WalletApiOperation.ObserveTransaction)[index] + .id; + await tick(); return { observer, + id, calls, send, emit, @@ -136,12 +158,12 @@ function currentSnapshot(observer: TransactionObservation) { } test("initial notification before acknowledgement, revision filtering and complete replacement", async () => { - const f = fixture(); + const f = await fixture(); f.send("other", 50); assert.equal(currentSnapshot(f.observer), undefined); - f.send("view-1", 1); + f.send(f.id(0), 1); assert.equal(currentSnapshot(f.observer), snapshot); - f.send("view-1", 1, null); + f.send(f.id(0), 1, null); assert.equal(readState(f.observer).status === "deleted", false); const replacement: PeerPushCreditSnapshot = { ...snapshot, @@ -153,7 +175,7 @@ test("initial notification before acknowledgement, revision filtering and comple kycAmlReview: undefined, }, }; - f.send("view-1", 2, replacement); + f.send(f.id(0), 2, replacement); assert.deepEqual(currentSnapshot(f.observer), replacement); f.ack(); await tick(); @@ -162,9 +184,9 @@ test("initial notification before acknowledgement, revision filtering and comple }); test("dispose during registration stops again after acknowledgement and ignores late values", async () => { - const f = fixture(); + const f = await fixture(); f.observer.dispose(); - f.send("view-1", 1); + f.send(f.id(0), 1); f.ack(); await tick(); assert.equal(currentSnapshot(f.observer), undefined); @@ -176,21 +198,22 @@ test("dispose during registration stops again after acknowledgement and ignores }); test("reconnect replaces registration; errors permit retry and deletion ends it", async () => { - const f = fixture(); - f.send("view-1", 1); + const f = await fixture(); + f.send(f.id(0), 1); f.status({ state: "disconnected", reason: "lost", unknownMutationIds: [] }); assert.equal(readState(f.observer).status, "disconnected"); assert.equal(currentSnapshot(f.observer), snapshot); f.status({ state: "connected" }); assert.deepEqual(readState(f.observer), { status: "loading", snapshot }); - f.send("view-1", 50, null); + f.send(f.id(0), 50, null); assert.equal(readState(f.observer).status === "deleted", false); - f.send("view-2", 1); + await tick(); + f.send(f.id(1), 1); assert.equal(readState(f.observer).status, "ready"); f.emit({ type: NotificationType.ObservationError, observationType: ObservationType.Transaction, - observationId: "view-2", + observationId: f.id(1), error: { code: 1, hint: "read failed" }, }); assert.equal(failureMessage(f.observer), "read failed"); @@ -202,7 +225,8 @@ test("reconnect replaces registration; errors permit retry and deletion ends it" ); f.observer.retry(); assert.deepEqual(readState(f.observer), { status: "loading", snapshot }); - f.send("view-3", 1, null); + await tick(); + f.send(f.id(2), 1, null); assert.equal(readState(f.observer).status, "deleted"); f.status({ state: "disconnected", reason: "lost", unknownMutationIds: [] }); f.status({ state: "connected" }); @@ -265,12 +289,8 @@ test("receive preparation, observed detail and completion need no follow-up quer WalletApiOperation.PreparePeerPushCredit, { talerUri: demoActionUris["peer-receive"] }, ); - const observer = new TransactionObservation( - connection, - prepared.transactionId, - () => {}, - () => "receive", - ); + const observer = observe(connection, prepared.transactionId); + await tick(); const initial = currentSnapshot(observer); assert.equal(initial?.type, TransactionType.PeerPushCredit); assert.deepEqual( @@ -310,12 +330,8 @@ test("bank withdrawal tracking follows generic snapshots without preparing again talerWithdrawUri: "taler://withdraw/bank.demo.invalid/operation", }, ); - const observer = new TransactionObservation( - connection, - prepared.transactionId, - () => {}, - () => "bank", - ); + const observer = observe(connection, prepared.transactionId); + await tick(); try { const initial = currentSnapshot(observer); assert.ok(initial?.type === TransactionType.Withdrawal); @@ -369,3 +385,84 @@ test("the snapshot projection excludes new diagnostics but preserves key-change ["https://exchange.example/"], ); }); + +test("watches share one probe and renew only live IDs, including after a lost stop", async (t) => { + t.mock.timers.enable({ apis: ["Date", "setInterval"], now: 1000 }); + const connection = new DemoWalletConnection(); + t.after(() => connection.close()); + const call = connection.client.call.bind(connection.client); + const batches: string[][] = []; + const registrations: string[] = []; + let missing: string[] = []; + let holdSnapshot = false; + const subscribe = connection.subscribeNotifications.bind(connection); + connection.subscribeNotifications = (listener) => + subscribe((n) => { + if (!holdSnapshot) listener(n); + }); + connection.client.call = (op, args) => { + if (op === WalletApiOperation.RenewObservations) { + batches.push((args as RenewObservationsRequest).observationIds); + return Promise.resolve({ missingObservationIds: missing }) as never; + } + if (op === WalletApiOperation.StopObservation) + return Promise.reject(Error("lost stop")); + if (op === WalletApiOperation.ObserveUserAttention) { + const registration = args as ObserveUserAttentionRequest; + assert.equal(registration.lease, true); + registrations.push(registration.observationId); + } + return call(op, args); + }; + const client = createWalletObservationClient(connection); + const views: string[] = []; + const a = client.watchUserAttention(() => {}); + const b = createWalletObservationClient(connection).watchUserAttention((v) => + views.push(v.status), + ); + t.after(() => { + a.dispose(); + b.dispose(); + }); + await tick(); + assert.deepEqual(batches, [[]]); + assert.equal(registrations.length, 2); + assert.equal(views.at(-1), "ready"); + t.mock.timers.tick(60_000); + await tick(); + assert.deepEqual(batches.at(-1), registrations); + a.dispose(); + t.mock.timers.tick(60_000); + await tick(); + assert.deepEqual(batches.at(-1), [registrations[1]]); + missing = [registrations[1]]; + holdSnapshot = true; + t.mock.timers.tick(60_000); + await tick(); + assert.equal(views.at(-1), "loading"); + assert.equal(new Set(registrations).size, 3); + // Advance wall time without delivering heartbeats, then wake the client. + t.mock.timers.setTime(Date.now() + 300_000); + t.mock.timers.tick(60_000); + await tick(); + assert.equal(new Set(registrations).size, 4); + assert.equal(views.at(-1), "loading"); +}); + +test("a host that lacks lease support receives no registrations", async () => { + const connection = new DemoWalletConnection(); + const calls: WalletApiOperation[] = []; + connection.client.call = (op) => { + calls.push(op); + return Promise.reject(Error("unknown operation")); + }; + const views: string[] = []; + const handle = createWalletObservationClient(connection).watchUserAttention( + (v) => views.push(v.status), + ); + await tick(); + assert.deepEqual(views, ["loading", "failed"]); + assert.deepEqual(calls, [WalletApiOperation.RenewObservations]); + handle.dispose(); + connection.close(); +});