commit 1a95ebbf2e64e89528f3d25c0b76e5686f7b971e parent a3eba277d80712f98fb5c080b4721bda973fdfaa Author: Florian Dold <dold@taler.net> Date: Wed, 25 Nov 2026 18:50:09 +0100 wallet-core: add renewable leases to observations A client that disappears can leave subscriptions running for the life of the wallet. Let callers opt into five-minute leases and renew only the IDs they still use. Check expiry before publishing a snapshot or accepting a renewal. Issue: https://bugs.taler.net/n/11794 Diffstat:
14 files changed, 303 insertions(+), 41 deletions(-)
diff --git a/doc/wallet-observations.md b/doc/wallet-observations.md @@ -15,7 +15,8 @@ Install the notification listener before making this request: "operation": "observeTransaction", "args": { "transactionId": "txn:payment:example", - "observationId": "payment-screen-17" + "observationId": "payment-screen-17", + "lease": true } } ``` @@ -100,6 +101,16 @@ Observation IDs are caller-generated, nonempty strings of at most 256 characters unique across the wallet instance. Reusing an active ID is an API error. Multiple observations of the same transaction are independent. +`lease: true` on any of the three observe requests starts a five-minute lease +before the first read. Only an explicit renewal extends it. For example, +`renewObservations({ observationIds: ["a", "b"] })` returning +`{ missingObservationIds: ["a"] }` means that only `b` was renewed. An +unknown, expired or unleased ID is reported as missing. Expiry removes the +registration and its timers, suppresses pending reads and emits +`observation-ended` with reason `lease-expired`. A suspended host applies the +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. + 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 @@ -155,7 +166,7 @@ subscription state. The extension cleans up subscriptions on port disconnect. `observePeerPushCredit` and its `observationType: "peer-push-credit"` notification have been removed. Consumers must call `observeTransaction`, accept `observationType: "transaction"`, and narrow `snapshot.type`. `stopObservation` -and lifecycle rules are unchanged. Transaction lists and balances retain their +is idempotent. Transaction lists and balances retain their existing query/notification behavior. ## User attention diff --git a/packages/taler-util/src/notifications.ts b/packages/taler-util/src/notifications.ts @@ -46,6 +46,7 @@ export enum NotificationType { BalanceRefreshInfoChanged = "balance-refresh-info-changed", UserAttentionChanged = "user-attention-changed", ObservationSnapshot = "observation-snapshot", + ObservationEnded = "observation-ended", ObservationError = "observation-error", CoinRecoveryProgress = "coin-recovery-progress", BalanceChange = "balance-change", @@ -103,6 +104,13 @@ export type ObservationSnapshotNotification = }; /** Ends the observation; does not describe the outcome of the transaction. */ +export interface ObservationEndedNotification { + type: NotificationType.ObservationEnded; + observationType: ObservationType; + observationId: string; + reason: "lease-expired"; +} + export interface ObservationErrorNotification { type: NotificationType.ObservationError; observationType: ObservationType; @@ -496,6 +504,7 @@ export type WalletNotification = | { type: NotificationType.BalanceRefreshInfoChanged } | { type: NotificationType.UserAttentionChanged } | ObservationSnapshotNotification + | ObservationEndedNotification | ObservationErrorNotification | CoinRecoveryProgressNotification | BalanceChangeNotification diff --git a/packages/taler-util/src/types-taler-wallet-observations.ts b/packages/taler-util/src/types-taler-wallet-observations.ts @@ -4,7 +4,13 @@ * SPDX-License-Identifier: GPL-3.0-or-later */ -import { buildCodecForObject, codecForString } from "./codec.js"; +import { + buildCodecForObject, + codecForBoolean, + codecForList, + codecForString, + codecOptional, +} from "./codec.js"; import { assertUnreachable } from "./errors.js"; import type { ErrorInfoSummary } from "./notifications.js"; import { TalerErrorCode } from "./taler-error-codes.js"; @@ -51,18 +57,24 @@ export enum ObservationType { BalanceRefreshInfo = "balance-refresh-info", } -export interface ObserveTransactionRequest { - transactionId: TransactionIdStr; +/** A leased registration expires five minutes after registration or renewal. */ +export const observationLeaseDurationMs = 5 * 60_000; + +interface ObserveRequest { /** Fresh caller-generated ID, unique within this wallet instance. */ observationId: string; + lease?: boolean; +} + +export interface ObserveTransactionRequest extends ObserveRequest { + transactionId: TransactionIdStr; } export interface BalanceRefreshInfoRequest { scopeInfo: ScopeInfo; } -export interface ObserveBalanceRefreshInfoRequest extends BalanceRefreshInfoRequest { - observationId: string; -} +export interface ObserveBalanceRefreshInfoRequest + extends BalanceRefreshInfoRequest, ObserveRequest {} export const codecForBalanceRefreshInfoRequest = () => buildCodecForObject<BalanceRefreshInfoRequest>() .property("scopeInfo", codecForScopeInfo()) @@ -71,16 +83,15 @@ export const codecForObserveBalanceRefreshInfoRequest = () => buildCodecForObject<ObserveBalanceRefreshInfoRequest>() .property("scopeInfo", codecForScopeInfo()) .property("observationId", codecForString()) + .property("lease", codecOptional(codecForBoolean())) .build("ObserveBalanceRefreshInfoRequest"); -export interface ObserveUserAttentionRequest { - /** Fresh caller-generated ID, unique within this wallet instance. */ - observationId: string; -} +export type ObserveUserAttentionRequest = ObserveRequest; export const codecForObserveUserAttentionRequest = () => buildCodecForObject<ObserveUserAttentionRequest>() .property("observationId", codecForString()) + .property("lease", codecOptional(codecForBoolean())) .build("ObserveUserAttentionRequest"); export interface StopObservationRequest { @@ -91,6 +102,7 @@ export const codecForObserveTransactionRequest = () => buildCodecForObject<ObserveTransactionRequest>() .property("transactionId", codecForTransactionIdStr()) .property("observationId", codecForString()) + .property("lease", codecOptional(codecForBoolean())) .build("ObserveTransactionRequest"); export const codecForStopObservationRequest = () => @@ -98,6 +110,20 @@ export const codecForStopObservationRequest = () => .property("observationId", codecForString()) .build("StopObservationRequest"); +export interface RenewObservationsRequest { + observationIds: string[]; +} + +export interface RenewObservationsResponse { + /** Unknown, expired, or unleased registrations. */ + missingObservationIds: string[]; +} + +export const codecForRenewObservationsRequest = () => + buildCodecForObject<RenewObservationsRequest>() + .property("observationIds", codecForList(codecForString())) + .build("RenewObservationsRequest"); + export type PeerPushCreditConfirmationUnavailableReason = | "not-proposed" | "expired" diff --git a/packages/taler-wallet-core/src/observations.test.ts b/packages/taler-wallet-core/src/observations.test.ts @@ -8,6 +8,8 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { NotificationType, + observationLeaseDurationMs, + ObservationType, openPromise, PeerPushCreditSnapshot, setDangerousTimetravel, @@ -84,8 +86,10 @@ 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), + const observations = new WalletObservations( + new TimerGroup(timer), + (n) => notifications.push(n), + () => timer.now, ); return { timer, notifications, observations }; } @@ -244,3 +248,72 @@ test("a deadline crossed during a read schedules another read", async () => { f.observations.shutdown(); } }); + +test("only explicit renewals keep leased registrations alive", async () => { + const { observations, timer, notifications } = fixture(); + const reads = { abandoned: 0, live: 0, legacy: 0 }; + for (const id of ["abandoned", "live", "legacy"] as const) { + await observations.registerUserAttention( + id, + async () => ({ items: [], unreadCount: ++reads[id] }), + id !== "legacy", + ); + } + timer.advance(observationLeaseDurationMs - 1); + assert.deepEqual(observations.renew(["live", "legacy", "missing"]), [ + "legacy", + "missing", + ]); + observations.invalidate(); + timer.advance(); + await flush(); + assert.deepEqual(reads, { abandoned: 2, live: 2, legacy: 2 }); + timer.advance(1); + assert.deepEqual(notifications.at(-1), { + type: NotificationType.ObservationEnded, + observationType: ObservationType.UserAttention, + observationId: "abandoned", + reason: "lease-expired", + }); + observations.invalidate(); + timer.advance(); + await flush(); + assert.deepEqual(reads, { abandoned: 2, live: 3, legacy: 3 }); + assert.deepEqual(observations.renew(["abandoned", "live"]), ["abandoned"]); + observations.shutdown(); + assert.equal(timer.pending.size, 0); +}); + +test("an elapsed lease cannot publish an in-flight read or be renewed before delayed timers run", async () => { + for (const wake of ["renew", "resume", "publish"]) { + const { observations, timer, notifications } = fixture(); + const read = openPromise<PeerPushCreditSnapshot>(); + const registered = observations.registerTransaction( + "slow", + transactionId, + () => read.promise, + undefined, + true, + ); + timer.now += observationLeaseDurationMs; + if (wake === "renew") + assert.deepEqual(observations.renew(["slow"]), ["slow"]); + if (wake === "resume") observations.invalidate(); + read.resolve(snapshot()); + await registered; + assert.deepEqual( + notifications.map((n) => n.type), + [NotificationType.ObservationEnded], + ); + assert.equal(timer.pending.size, 0); + await observations.registerTransaction("slow", transactionId, async () => + snapshot(), + ); + timer.advance(observationLeaseDurationMs); + assert.equal( + notifications.at(-1)?.type, + NotificationType.ObservationSnapshot, + ); + observations.shutdown(); + } +}); diff --git a/packages/taler-wallet-core/src/observations.ts b/packages/taler-wallet-core/src/observations.ts @@ -11,6 +11,7 @@ import { ErrorInfoSummary, getErrorDetailFromException, NotificationType, + observationLeaseDurationMs, ObservationType, ObservationSnapshotNotification, ScopeInfo, @@ -63,6 +64,8 @@ interface Observation { running: boolean; dirty: boolean; timer?: TimerHandle; + leaseExpiresAt?: number; + leaseTimer?: TimerHandle; } /** In-memory subscriptions, independent of the registering request's lifetime. */ @@ -73,6 +76,7 @@ export class WalletObservations { constructor( private timers: TimerGroup, private notify: (notification: WalletNotification) => void, + private now = Date.now, ) {} async registerTransaction( @@ -80,10 +84,12 @@ export class WalletObservations { transactionId: TransactionIdStr, read: () => Promise<TransactionSnapshot | null>, refreshAt?: () => number | undefined, + lease = false, ): Promise<void> { await this.register( observationId, ObservationType.Transaction, + lease, async () => ({ type: NotificationType.ObservationSnapshot, observationType: ObservationType.Transaction, @@ -99,10 +105,12 @@ export class WalletObservations { async registerUserAttention( observationId: string, read: () => Promise<UserAttentionSnapshot>, + lease = false, ) { await this.register( observationId, ObservationType.UserAttention, + lease, async () => ({ type: NotificationType.ObservationSnapshot, observationType: ObservationType.UserAttention, @@ -118,11 +126,13 @@ export class WalletObservations { scopeInfo: ScopeInfo, read: (token: CancellationToken) => Promise<WalletRefreshInfo | null>, refreshAt: () => number | undefined, + lease = false, ): Promise<void> { const source = CancellationToken.create(); await this.register( observationId, ObservationType.BalanceRefreshInfo, + lease, async () => ({ type: NotificationType.ObservationSnapshot, observationType: ObservationType.BalanceRefreshInfo, @@ -139,12 +149,14 @@ export class WalletObservations { private async register( observationId: string, observationType: ObservationType, + lease: boolean, read: Observation["read"], refreshAt?: Observation["refreshAt"], cancelRead?: () => void, ): Promise<void> { validateObservationId(observationId); - if (this.stopped || this.entries.has(observationId)) { + const previous = this.entries.get(observationId); + if (this.stopped || (previous && this.isActive(previous))) { throw TalerError.fromDetail( TalerErrorCode.WALLET_CORE_API_BAD_REQUEST, { parameter: "observationId" }, @@ -163,6 +175,7 @@ export class WalletObservations { }; // Install before reading: writes during the first read must mark it dirty. this.entries.set(observationId, entry); + if (lease) this.extendLease(entry); try { const snapshot = await read(); if (!this.isActive(entry)) return; @@ -218,6 +231,7 @@ export class WalletObservations { const entry = this.entries.get(observationId); if (!entry) return; entry.timer?.clear(); + entry.leaseTimer?.clear(); this.entries.delete(observationId); entry.cancelRead?.(); } @@ -228,7 +242,45 @@ export class WalletObservations { } private isActive(entry: Observation): boolean { - return this.entries.get(entry.observationId) === entry; + if (this.entries.get(entry.observationId) !== entry) return false; + if (entry.leaseExpiresAt === undefined || this.now() < entry.leaseExpiresAt) + return true; + this.expire(entry); + return false; + } + + private expire(entry: Observation): void { + if (this.entries.get(entry.observationId) !== entry) return; + this.stop(entry.observationId); + this.notify({ + type: NotificationType.ObservationEnded, + observationId: entry.observationId, + observationType: entry.observationType, + reason: "lease-expired", + }); + } + + renew(observationIds: string[]): string[] { + const ids = new Set(observationIds); + for (const id of ids) validateObservationId(id); + const missing: string[] = []; + for (const id of ids) { + const entry = this.entries.get(id); + if (entry?.leaseExpiresAt === undefined || !this.isActive(entry)) + missing.push(id); + else this.extendLease(entry); + } + return missing; + } + + private extendLease(entry: Observation): void { + entry.leaseExpiresAt = this.now() + observationLeaseDurationMs; + entry.leaseTimer?.clear(); + const alarm = this.timers.after(observationLeaseDurationMs, () => { + if (entry.leaseTimer === alarm) this.expire(entry); + }); + entry.leaseTimer = alarm; + alarm.unref(); } private schedule(entry: Observation): void { @@ -249,13 +301,13 @@ export class WalletObservations { if (this.isActive(entry)) this.publish(entry, snapshot); } catch (e) { if (this.isActive(entry)) { + this.stop(entry.observationId); this.notify({ type: NotificationType.ObservationError, observationType: entry.observationType, observationId: entry.observationId, error: summarizeObservationError(getErrorDetailFromException(e))!, }); - this.stop(entry.observationId); } } finally { entry.running = false; @@ -267,16 +319,14 @@ export class WalletObservations { entry: Observation, event: ObservationSnapshotNotification, ): void { + if (!event.snapshot) this.stop(entry.observationId); const value = canonicalJson(JSON.parse(JSON.stringify(event.snapshot))); if (value !== entry.lastValue) { entry.lastValue = value; event.revision = ++entry.revision; this.notify(event); } - if (!event.snapshot) { - this.stop(entry.observationId); - return; - } + if (!event.snapshot || !this.isActive(entry)) return; const info = event.observationType === ObservationType.Transaction && "info" in event.snapshot.transaction diff --git a/packages/taler-wallet-core/src/observe-transaction.test.ts b/packages/taler-wallet-core/src/observe-transaction.test.ts @@ -434,6 +434,7 @@ for (const makeRunner of runnerFactories) { await observeTransaction(f.wex, { transactionId: paymentId, observationId: "discount", + lease: true, }); assert.equal(await next, ChoiceSelectionDetailType.InsufficientBalance); await assert.rejects( diff --git a/packages/taler-wallet-core/src/observe-transaction.ts b/packages/taler-wallet-core/src/observe-transaction.ts @@ -435,6 +435,7 @@ export async function observeTransaction( return snapshot; }), () => deadline, + req.lease, ); return {}; } diff --git a/packages/taler-wallet-core/src/refreshBalance.test.ts b/packages/taler-wallet-core/src/refreshBalance.test.ts @@ -332,7 +332,9 @@ for (const makeRunner of runnerFactories) { await observeBalanceRefreshInfo(wex, { scopeInfo, observationId: "second", + lease: true, }); + assert.deepEqual(ws.observations.renew(["second", "cost"]), ["cost"]); await settle(); events.length = 0; ws.observations.stop("cost"); diff --git a/packages/taler-wallet-core/src/refreshBalance.ts b/packages/taler-wallet-core/src/refreshBalance.ts @@ -518,6 +518,7 @@ export async function observeBalanceRefreshInfo( return last.info; }, () => last?.nextCheck, + req.lease, ); return {}; } diff --git a/packages/taler-wallet-core/src/requests.ts b/packages/taler-wallet-core/src/requests.ts @@ -37,6 +37,7 @@ import { initializeAttention, scheduleAttentionExpirations, getUserAttention, + getUserAttentionInTx, markAllUserAttentionRead, clearReadUserAttention, updateAttention, @@ -266,6 +267,7 @@ import { codecForBalanceRefreshInfoRequest, codecForObserveBalanceRefreshInfoRequest, codecForObserveUserAttentionRequest, + codecForRenewObservationsRequest, codecForStopObservationRequest, codecForPreparePeerPushCreditRequest, codecForPrepareRefundRequest, @@ -3149,8 +3151,11 @@ const handlers: { [T in WalletApiOperation]: HandlerWithValidator<T> } = { [WalletApiOperation.ObserveUserAttention]: { codec: codecForObserveUserAttentionRequest(), handler: async (wex, req) => { - await wex.ws.observations.registerUserAttention(req.observationId, () => - getUserAttention(wex), + const ws = wex.ws; + await ws.observations.registerUserAttention( + req.observationId, + () => ws.runStandaloneWalletDbTx(getUserAttentionInTx), + req.lease, ); return {}; }, @@ -3185,6 +3190,12 @@ const handlers: { [T in WalletApiOperation]: HandlerWithValidator<T> } = { codec: codecForObserveTransactionRequest(), handler: observeTransaction, }, + [WalletApiOperation.RenewObservations]: { + codec: codecForRenewObservationsRequest(), + handler: async (wex, req) => ({ + missingObservationIds: wex.ws.observations.renew(req.observationIds), + }), + }, [WalletApiOperation.StopObservation]: { codec: codecForStopObservationRequest(), handler: stopObservation, diff --git a/packages/taler-wallet-core/src/user-attention.ts b/packages/taler-wallet-core/src/user-attention.ts @@ -69,18 +69,22 @@ async function save( export async function getUserAttention( wex: WalletExecutionContext, ): Promise<UserAttentionSnapshot> { - return wex.runWalletDbTx(async (tx) => { - const now = nowMs(); - const items = (await tx.listUserAttention()) - .filter((row) => active(row, now)) - .map((row) => row.item); - items.sort( - (a, b) => - stampMs(b.createdAt) - stampMs(a.createdAt) || - a.attentionId.localeCompare(b.attentionId), - ); - return { items, unreadCount: items.filter((item) => !item.readAt).length }; - }); + return wex.runWalletDbTx(getUserAttentionInTx); +} + +export async function getUserAttentionInTx( + tx: WalletDbTransaction, +): Promise<UserAttentionSnapshot> { + const now = nowMs(); + const items = (await tx.listUserAttention()) + .filter((row) => active(row, now)) + .map((row) => row.item); + items.sort( + (a, b) => + stampMs(b.createdAt) - stampMs(a.createdAt) || + a.attentionId.localeCompare(b.attentionId), + ); + return { items, unreadCount: items.filter((item) => !item.readAt).length }; } export async function updateAttention( diff --git a/packages/taler-wallet-core/src/wallet-api-types.ts b/packages/taler-wallet-core/src/wallet-api-types.ts @@ -176,6 +176,8 @@ import { BalanceRefreshInfoRequest, WalletRefreshInfo, ObserveUserAttentionRequest, + RenewObservationsRequest, + RenewObservationsResponse, StopObservationRequest, PreparePeerPushCreditRequest, PreparePeerPushCreditResponse, @@ -368,6 +370,7 @@ export enum WalletApiOperation { DismissUserAttention = "dismissUserAttention", GetRefreshBlocked = "getRefreshBlocked", SetRefreshBlocked = "setRefreshBlocked", + RenewObservations = "renewObservations", StopObservation = "stopObservation", PreparePeerPushCredit = "preparePeerPushCredit", CheckPeerPushDebit = "checkPeerPushDebit", @@ -1492,6 +1495,13 @@ export type SetRefreshBlockedOp = { response: EmptyObject; }; +/** Extend live leases. An empty list probes lease support. */ +export type RenewObservationsOp = { + op: WalletApiOperation.RenewObservations; + request: RenewObservationsRequest; + response: RenewObservationsResponse; +}; + /** End an observation. */ export type StopObservationOp = { op: WalletApiOperation.StopObservation; @@ -2104,6 +2114,9 @@ export const walletApiExpectedErrors = { [WalletApiOperation.SetExchangeTosAccepted]: [ TalerErrorCode.WALLET_CORE_API_BAD_REQUEST, ], + [WalletApiOperation.RenewObservations]: [ + TalerErrorCode.WALLET_CORE_API_BAD_REQUEST, + ], [WalletApiOperation.StopObservation]: [ TalerErrorCode.WALLET_CORE_API_BAD_REQUEST, ], @@ -2352,6 +2365,7 @@ export type WalletOperations = { [WalletApiOperation.DismissUserAttention]: DismissUserAttentionOp; [WalletApiOperation.GetRefreshBlocked]: GetRefreshBlockedOp; [WalletApiOperation.SetRefreshBlocked]: SetRefreshBlockedOp; + [WalletApiOperation.RenewObservations]: RenewObservationsOp; [WalletApiOperation.StopObservation]: StopObservationOp; [WalletApiOperation.PreparePeerPushCredit]: PreparePeerPushCreditOp; [WalletApiOperation.ConfirmPeerPushCredit]: ConfirmPeerPushCreditOp; diff --git a/packages/wallet-webui/src/api/notifications.ts b/packages/wallet-webui/src/api/notifications.ts @@ -82,6 +82,7 @@ export function notificationFamilies( case NotificationType.Idle: // Observations already carry their view; they must not trigger query reloads. case NotificationType.ObservationSnapshot: + case NotificationType.ObservationEnded: case NotificationType.ObservationError: case NotificationType.TaskObservabilityEvent: case NotificationType.RequestObservabilityEvent: diff --git a/packages/wallet-webui/src/testing/demo-wallet.ts b/packages/wallet-webui/src/testing/demo-wallet.ts @@ -5,6 +5,9 @@ import { ExchangeTosStatus, ExchangeUpdateStatus, NotificationType, + observationLeaseDurationMs, + timer, + type TimerHandle, ObservationType, type TransactionSnapshot, Paytos, @@ -459,6 +462,10 @@ export class DemoWalletConnection implements WalletConnection { string, { transactionId: string; revision: number; value?: string } >(); + private leases = new Map< + string, + { type: ObservationType; expiresAt: number; timer: TimerHandle } + >(); private readonly notifications = new Set<(n: WalletNotification) => void>(); private readonly statuses = new Set<(s: ConnectionStatus) => void>(); private state: DemoState; @@ -495,7 +502,43 @@ export class DemoWalletConnection implements WalletConnection { return `txn:${kind}:demo-${++this.state.sequence}` as TransactionIdStr; } + private stopObservation(id: string) { + this.leases.get(id)?.timer.clear(); + this.leases.delete(id); + this.attentionObservers.delete(id); + this.refreshObservers.delete(id); + this.observations.delete(id); + } + + private checkLease(id: string) { + const lease = this.leases.get(id); + if (lease && Date.now() >= lease.expiresAt) { + this.stopObservation(id); + this.emit({ + type: NotificationType.ObservationEnded, + reason: "lease-expired", + observationId: id, + observationType: lease.type, + }); + } + return this.leases.has(id); + } + + private extendLease(id: string, type: ObservationType) { + this.leases.get(id)?.timer.clear(); + const alarm = timer.after(observationLeaseDurationMs, () => + this.checkLease(id), + ); + alarm.unref(); + this.leases.set(id, { + type, + expiresAt: Date.now() + observationLeaseDurationMs, + timer: alarm, + }); + } + private requireUnusedObservationId(id: string): void { + this.checkLease(id); if ( this.observations.has(id) || this.refreshObservers.has(id) || @@ -508,7 +551,8 @@ export class DemoWalletConnection implements WalletConnection { for (const listener of this.notifications) listener(notification); if ( notification.type !== NotificationType.ObservationSnapshot && - notification.type !== NotificationType.ObservationError + notification.type !== NotificationType.ObservationError && + notification.type !== NotificationType.ObservationEnded ) this.publishObservations(); } @@ -530,6 +574,7 @@ export class DemoWalletConnection implements WalletConnection { return null; } private publishObservations() { + for (const id of this.leases.keys()) this.checkLease(id); for (const [id, entry] of this.refreshObservers) { const snapshot = this.refreshInfo(entry.scope); const value = JSON.stringify(snapshot); @@ -543,7 +588,7 @@ export class DemoWalletConnection implements WalletConnection { revision: ++entry.revision, snapshot, }); - if (!snapshot) this.refreshObservers.delete(id); + if (!snapshot) this.stopObservation(id); } for (const [observationId, entry] of this.observations) { const t = this.state.transactions.find( @@ -642,7 +687,7 @@ export class DemoWalletConnection implements WalletConnection { revision: ++entry.revision, snapshot, }); - if (!snapshot) this.observations.delete(observationId); + if (!snapshot) this.stopObservation(observationId); } } @@ -1268,6 +1313,7 @@ export class DemoWalletConnection implements WalletConnection { case WalletApiOperation.ObserveUserAttention: { const id = String(request.observationId); this.requireUnusedObservationId(id); + if (request.lease) this.extendLease(id, ObservationType.UserAttention); this.attentionObservers.add(id); this.emit({ type: NotificationType.ObservationSnapshot, @@ -1283,6 +1329,8 @@ export class DemoWalletConnection implements WalletConnection { case WalletApiOperation.ObserveBalanceRefreshInfo: { const id = String(request.observationId); this.requireUnusedObservationId(id); + if (request.lease) + this.extendLease(id, ObservationType.BalanceRefreshInfo); this.refreshObservers.set(id, { scope: request.scopeInfo as ScopeInfo, revision: 0, @@ -1295,6 +1343,7 @@ export class DemoWalletConnection implements WalletConnection { this.requireUnusedObservationId(id); const t = this.findTransaction(String(request.transactionId)); + if (request.lease) this.extendLease(id, ObservationType.Transaction); this.observations.set(id, { transactionId: t.transactionId, revision: 0, @@ -1302,10 +1351,17 @@ export class DemoWalletConnection implements WalletConnection { this.publishObservations(); return {} as never; } + case WalletApiOperation.RenewObservations: { + const missingObservationIds: string[] = []; + for (const id of new Set(request.observationIds as string[])) { + if (this.checkLease(id)) + this.extendLease(id, this.leases.get(id)!.type); + else missingObservationIds.push(id); + } + return { missingObservationIds } as never; + } case WalletApiOperation.StopObservation: - this.attentionObservers.delete(String(request.observationId)); - this.refreshObservers.delete(String(request.observationId)); - this.observations.delete(String(request.observationId)); + this.stopObservation(String(request.observationId)); return {} as never; case WalletApiOperation.PreparePeerPushCredit: { if (request.talerUri !== demoActionUris["peer-receive"]) @@ -1517,6 +1573,8 @@ export class DemoWalletConnection implements WalletConnection { } close(): void { + for (const id of this.leases.keys()) this.stopObservation(id); + this.attentionObservers.clear(); this.notifications.clear(); this.observations.clear(); this.refreshObservers.clear();