commit 904af3e931aa882e51086de7982cc572ca017d22
parent ba921fe8445228dff5f244d1d9b33cd4f5251d3d
Author: Florian Dold <dold@taler.net>
Date: Mon, 23 Nov 2026 23:18:16 +0100
wallet-core: refresh observations from committed notifications
Use wallet events to schedule snapshot reads and drop the proxy that
matched database writes by method name. Database replacement, resume,
and expiry deadlines can still schedule reads directly.
Diffstat:
4 files changed, 69 insertions(+), 86 deletions(-)
diff --git a/packages/taler-wallet-core/src/dev-experiments.ts b/packages/taler-wallet-core/src/dev-experiments.ts
@@ -185,7 +185,6 @@ export async function setRefreshScenario(
override ? override === "risk" : !!first?.hasExpirationRisk;
tx.scheduleOnCommit(() => {
wex.ws.devExperimentState.refreshScenario = scenario;
- wex.ws.observations.invalidate();
});
tx.notify({ type: NotificationType.BalanceRefreshInfoChanged });
if (first && visibleRisk(previous) !== visibleRisk(scenario))
diff --git a/packages/taler-wallet-core/src/observations.ts b/packages/taler-wallet-core/src/observations.ts
@@ -25,7 +25,6 @@ import {
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(
@@ -189,6 +188,24 @@ export class WalletObservations {
}
}
+ handleNotification(n: WalletNotification): void {
+ switch (n.type) {
+ case NotificationType.TransactionStateTransition:
+ case NotificationType.ExchangeStateTransition:
+ case NotificationType.BalanceChange:
+ case NotificationType.DonauConfigChanged:
+ // For example, a withdrawal can change its parent credit's snapshot.
+ this.invalidate(ObservationType.Transaction);
+ break;
+ case NotificationType.BalanceRefreshInfoChanged:
+ this.invalidate(ObservationType.BalanceRefreshInfo);
+ break;
+ case NotificationType.UserAttentionChanged:
+ this.invalidate(ObservationType.UserAttention);
+ break;
+ }
+ }
+
invalidate(type?: ObservationType): void {
for (const entry of this.entries.values()) {
if (type !== undefined && entry.observationType !== type) continue;
@@ -290,59 +307,3 @@ export class WalletObservations {
}
}
}
-
-/** All persistent inputs read by transaction snapshots, including amount recovery. */
-const observationInputWrites = new Set<string>([
- ...[
- "PeerPushCredit",
- "PeerPullCredit",
- "PeerPullDebit",
- "PeerPushDebit",
- "Purchase",
- "RefundGroup",
- "RefundItem",
- "RefreshGroup",
- "DepositGroup",
- "RecoupGroup",
- "DenomLossEvent",
- "Token",
- "Config",
- "WithdrawalGroup",
- "OperationRetry",
- "Exchange",
- "ExchangeDetails",
- "Reserve",
- "ContractTerms",
- "TransactionMeta",
- "GlobalCurrencyExchange",
- "GlobalCurrencyAuditor",
- "CurrencyInfo",
- "CurrencyInfoEntry",
- "Coin",
- "CoinAvailability",
- "CoinHistory",
- "Slate",
- "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/observe-transaction.test.ts b/packages/taler-wallet-core/src/observe-transaction.test.ts
@@ -34,6 +34,7 @@ import {
} from "@gnu-taler/taler-util";
import { HeadersImpl, HttpRequestLibrary } from "@gnu-taler/taler-util/http";
import {
+ getExchangeState,
TaskIdentifiers,
constructTaskIdentifier,
PendingTaskType,
@@ -62,8 +63,11 @@ import { PeerPushCreditTransactionContext } from "./pay-peer-push-credit.js";
import { dispatchRequestInternal } from "./requests.js";
import { handleSetDonau } from "./donau.js";
import { WalletDbTransaction } from "./db/transaction.js";
+import {
+ PayMerchantTransactionContext,
+ RefundTransactionContext,
+} from "./pay-merchant.js";
import { WithdrawTransactionContext } from "./withdraw.js";
-import { RefundTransactionContext } from "./pay-merchant.js";
import {
clearTaskRetry,
storePendingTaskError,
@@ -261,6 +265,16 @@ async function fixture(makeRunner: (typeof runnerFactories)[number]) {
detailsChanged: true,
});
}
+ async function notifyExchangeUpdate(tx: WalletDbTransaction) {
+ const exchange = await tx.getExchange(exchangeUrl);
+ assert.ok(exchange);
+ tx.notify({
+ type: NotificationType.ExchangeStateTransition,
+ exchangeBaseUrl: exchangeUrl,
+ causeHint: "update-from-response",
+ newExchangeState: getExchangeState(exchange),
+ });
+ }
return {
db,
ws,
@@ -273,6 +287,7 @@ async function fixture(makeRunner: (typeof runnerFactories)[number]) {
nextSnapshot,
updateCredit,
updateWithdrawal,
+ notifyExchangeUpdate,
observe,
settle,
};
@@ -293,6 +308,7 @@ for (const makeRunner of runnerFactories) {
assert.ok(contract);
contract.contractTermsRaw.purse_expiration = { t_s: 1 };
await tx.upsertContractTerms(contract);
+ await f.updateCredit(tx, f.credit);
});
const expired = await next;
assert.equal(
@@ -479,6 +495,7 @@ for (const makeRunner of runnerFactories) {
},
],
});
+ await f.notifyExchangeUpdate(tx);
});
const n = await next;
assert.equal(n.snapshot?.exchanges[0]?.kycHardLimit, "TESTKUDOS:4");
@@ -578,7 +595,10 @@ for (const makeRunner of runnerFactories) {
f.cts.cancel();
const next = f.nextSnapshot("two");
await f.ws.runStandaloneWalletDbTx((tx) =>
- tx.deletePeerPushCredit("incoming"),
+ new PeerPushCreditTransactionContext(
+ f.wex,
+ "incoming",
+ ).deleteTransactionInTx(tx),
);
const n = await next;
assert.equal(n.snapshot, null);
@@ -907,13 +927,14 @@ for (const makeRunner of runnerFactories) {
...reserve!,
status: ReserveRecordStatus.Done,
});
+ await f.notifyExchangeUpdate(tx);
}),
);
assert.equal(t.kycUrl, undefined);
assert.equal(t.kycAmlReview, undefined);
t = await change(() =>
f.wex.runWalletDbTx((tx) =>
- tx.upsertPeerPushCredit({
+ f.updateCredit(tx, {
...credit,
status: PeerPushCreditStatus.Done,
}),
@@ -1120,11 +1141,12 @@ for (const makeRunner of runnerFactories) {
assert.ok(!wire.includes(key), key);
}
assert.deepEqual(await f.ws.db.exportDatabase(), before);
+ const paymentCtx = new PayMerchantTransactionContext(f.wex, "payment");
let nextPayment = f.nextSnapshot("txn:payment:payment");
// Downloaded payment choices and configuration must update without a public state transition.
const now = Math.floor(Date.now() / 1000);
await f.wex.runWalletDbTx(async (tx) => {
- const purchase = await tx.getPurchase("payment");
+ const [purchase, handle] = await paymentCtx.getRecordHandle(tx);
assert.ok(purchase);
purchase.download = {
contractTermsHash: master,
@@ -1154,7 +1176,7 @@ for (const makeRunner of runnerFactories) {
exchanges: [],
},
});
- await tx.upsertPurchase(purchase);
+ await handle.update(purchase, "download");
});
await f.settle();
await nextPayment;
@@ -1201,6 +1223,10 @@ for (const makeRunner of runnerFactories) {
assert.ok(ct);
ct.contractTermsRaw.pay_deadline = { t_s: 1 };
await tx.upsertContractTerms(ct);
+ const [record, handle] = await paymentCtx.getRecordHandle(tx);
+ await handle.update(record, "contract-update", undefined, {
+ detailsChanged: true,
+ });
});
await f.settle();
await nextPayment;
@@ -1244,6 +1270,7 @@ for (const makeRunner of runnerFactories) {
},
};
await tx.upsertExchangeDetails(details);
+ await f.notifyExchangeUpdate(tx);
});
await nextPayment;
const unpaid = latestPayment().snapshot;
@@ -1338,6 +1365,7 @@ for (const makeRunner of runnerFactories) {
t_s: depositExpiry,
});
await tx.upsertDenomination(denomination);
+ await f.notifyExchangeUpdate(tx);
});
await f.settle();
nextPayment = f.nextSnapshot("txn:payment:payment");
@@ -1379,6 +1407,7 @@ for (const makeRunner of runnerFactories) {
},
];
await tx.upsertExchangeDetails(details);
+ await f.notifyExchangeUpdate(tx);
});
await f.settle();
nextPayment = f.nextSnapshot("txn:payment:payment");
@@ -1426,6 +1455,7 @@ for (const makeRunner of runnerFactories) {
assert.ok(details);
details.wireInfo.feesForType.iban[0].startStamp = { t_s: wireStart };
await tx.upsertExchangeDetails(details);
+ await f.notifyExchangeUpdate(tx);
});
await new Promise((resolve) =>
setTimeout(resolve, Math.max(0, wireStart * 1000 - Date.now()) + 50),
@@ -1444,6 +1474,10 @@ for (const makeRunner of runnerFactories) {
assert.ok(contract);
contract.contractTermsRaw.pay_deadline = { t_s: payDeadline };
await tx.upsertContractTerms(contract);
+ const [record, handle] = await paymentCtx.getRecordHandle(tx);
+ await handle.update(record, "contract-update", undefined, {
+ detailsChanged: true,
+ });
});
await f.settle();
nextPayment = f.nextSnapshot("txn:payment:payment");
@@ -1460,10 +1494,10 @@ for (const makeRunner of runnerFactories) {
nextPayment = f.nextSnapshot("txn:payment:payment");
await f.wex.runWalletDbTx(async (tx) => {
- const p = await tx.getPurchase("payment");
+ const [p, handle] = await paymentCtx.getRecordHandle(tx);
assert.ok(p);
p.purchaseStatus = R.PurchaseStatus.DialogUnclaimed;
- await tx.upsertPurchase(p);
+ await handle.update(p, "claim");
});
await nextPayment;
const handedOff = latestPayment().snapshot;
@@ -1536,7 +1570,7 @@ for (const makeRunner of runnerFactories) {
undefined,
true,
);
- await f.wex.runWalletDbTx((tx) => tx.deletePurchase("payment"));
+ await paymentCtx.userDeleteTransaction();
assert.equal((await deletedPayment).snapshot, null);
} finally {
await f.ws.shutdown();
diff --git a/packages/taler-wallet-core/src/wallet.ts b/packages/taler-wallet-core/src/wallet.ts
@@ -52,7 +52,6 @@ import {
Logger,
LongpollQueue,
NotificationType,
- ObservationType,
ObservabilityContext,
ObservabilityEventType,
ObservableHttpClientLibrary,
@@ -143,7 +142,7 @@ import {
} from "./wallet-api-types.js";
import { updateWithdrawalDenomsForExchange } from "./withdraw.js";
import { MaintenanceNotificationThrottler } from "./maintenance-notifications.js";
-import { WalletObservations, watchObservationInputs } from "./observations.js";
+import { WalletObservations } from "./observations.js";
const logger = new Logger("wallet.ts");
@@ -323,7 +322,7 @@ export class AdmittedWalletDbHandle implements WalletDbHandle {
throw Error("current database backend cannot import a foreign dump");
}
await fn.apply(db, args);
- this.onObservationInputsChanged();
+ this.onDatabaseReplaced();
}, args[2]?.cancellationToken);
}
@@ -335,22 +334,11 @@ export class AdmittedWalletDbHandle implements WalletDbHandle {
constructor(
private current: () => WalletDbHandle,
private gate: DbOperationGate,
- private onObservationInputsChanged: () => void = () => {},
+ private onDatabaseReplaced: () => void = () => {},
) {}
runReadWriteTx<T>(f: (tx: WalletDbTransaction) => Promise<T>): Promise<T> {
- 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;
- });
+ return this.gate.runShared(() => this.current().runReadWriteTx(f));
}
exportDatabase(): Promise<any> {
return this.gate.runShared(() => this.current().exportDatabase());
@@ -362,13 +350,13 @@ export class AdmittedWalletDbHandle implements WalletDbHandle {
): Promise<void> {
return this.gate.runExclusive(async () => {
await this.current().importDatabase(dump, finalize, options);
- this.onObservationInputsChanged();
+ this.onDatabaseReplaced();
}, options?.cancellationToken);
}
clearDatabase(): Promise<void> {
return this.gate.runExclusive(async () => {
await this.current().clearDatabase();
- this.onObservationInputsChanged();
+ this.onDatabaseReplaced();
});
}
getAccessStats() {
@@ -1649,6 +1637,9 @@ export class InternalWalletState {
this.observations = new WalletObservations(this.timerGroup, (n) =>
this.notify(n),
);
+ this.addNotificationListener((n) =>
+ this.observations.handleNotification(n),
+ );
this.maintenanceNotifications = new MaintenanceNotificationThrottler(
timer,
(n) => this.deliverNotificationSynchronously(n),
@@ -1888,8 +1879,6 @@ export class InternalWalletState {
notify(n: WalletNotification): void {
logger.trace(`Notification: ${j2s(n)}`);
- if (n.type === NotificationType.UserAttentionChanged)
- this.observations.invalidate(ObservationType.UserAttention);
if (n.type === NotificationType.BalanceChange) {
for (const id of this.taskScheduler.getActiveTasks()) {
if (id.startsWith(`${PendingTaskType.ExchangeAutoRefresh}:`))