commit 57aad93720a39cc56d45217c98c5c293310f62ae
parent 253e639558d811b3d6e62f737dc5046c88f7e128
Author: Florian Dold <dold@taler.net>
Date: Tue, 17 Nov 2026 23:19:27 +0100
wallet-core: skip duplicate exchange notifications
Repeated updates made clients reload unchanged exchange data. Keep those
wakeups internal, but tell clients when a retry error changes or clears.
Diffstat:
4 files changed, 176 insertions(+), 70 deletions(-)
diff --git a/packages/taler-wallet-core/src/exchanges.ts b/packages/taler-wallet-core/src/exchanges.ts
@@ -22,6 +22,10 @@
*/
import {
+ canonicalJson,
+ type ExchangeStateTransitionNotification,
+} from "@gnu-taler/taler-util";
+import {
evaluateAutoRefresh,
autoRefreshDeadline,
refreshLifetime,
@@ -978,13 +982,33 @@ export async function requireExchangeCoinUseConfirmedOrThrow(
);
}
+function notifyExchangeUpdate(
+ wex: WalletExecutionContext,
+ tx: WalletDbTransaction,
+ event: ExchangeStateTransitionNotification,
+ detailsChanged = false,
+) {
+ if (
+ detailsChanged ||
+ canonicalJson(event.oldExchangeState ?? null) !==
+ canonicalJson(event.newExchangeState ?? null)
+ )
+ tx.notify(event);
+ else tx.scheduleOnCommit(() => wex.ws.notifyInternal(event));
+}
+
export async function acceptExchangeTermsOfService(
wex: WalletExecutionContext,
exchangeBaseUrl: string,
): Promise<void> {
await wex.runWalletDbTx(async (tx) => {
const exch = await tx.getExchange(exchangeBaseUrl);
- if (exch && exch.tosCurrentEtag) {
+ if (
+ exch &&
+ exch.tosCurrentEtag &&
+ (exch.tosCurrentEtag !== exch.tosAcceptedEtag ||
+ !exch.tosAcceptedTimestamp)
+ ) {
const oldExchangeState = getExchangeState(exch);
exch.tosAcceptedEtag = exch.tosCurrentEtag;
exch.tosAcceptedTimestamp = timestampPreciseToDb(
@@ -1013,7 +1037,7 @@ export async function forgetExchangeTermsOfService(
): Promise<void> {
await wex.runWalletDbTx(async (tx) => {
const exch = await tx.getExchange(exchangeBaseUrl);
- if (!exch) {
+ if (!exch || (!exch.tosAcceptedEtag && !exch.tosAcceptedTimestamp)) {
return;
}
const oldExchangeState = getExchangeState(exch);
@@ -1773,7 +1797,7 @@ export async function startUpdateExchangeEntry(
wex.ws.exchangeCache.clear();
await tx.upsertExchange(r);
const newExchangeState = getExchangeState(r);
- tx.notify({
+ notifyExchangeUpdate(wex, tx, {
type: NotificationType.ExchangeStateTransition,
exchangeBaseUrl,
causeHint: "update-started",
@@ -2337,6 +2361,7 @@ async function handleExchageUpdateIncompatible(
return;
}
const oldExchangeState = getExchangeState(r);
+ const previousReason = r.unavailableReason;
r.updateStatus = ExchangeEntryDbUpdateStatus.UnavailableUpdate;
r.unavailableReason = makeTalerErrorDetail(
TalerErrorCode.WALLET_EXCHANGE_PROTOCOL_VERSION_INCOMPATIBLE,
@@ -2347,13 +2372,19 @@ async function handleExchageUpdateIncompatible(
);
const newExchangeState = getExchangeState(r);
await tx.upsertExchange(r);
- tx.notify({
- type: NotificationType.ExchangeStateTransition,
- exchangeBaseUrl,
- causeHint: "update-incompatible",
- newExchangeState,
- oldExchangeState,
- });
+ notifyExchangeUpdate(
+ wex,
+ tx,
+ {
+ type: NotificationType.ExchangeStateTransition,
+ exchangeBaseUrl,
+ causeHint: "update-incompatible",
+ newExchangeState,
+ oldExchangeState,
+ },
+ canonicalJson(previousReason ?? null) !==
+ canonicalJson(r.unavailableReason),
+ );
});
return TaskRunResult.backoff();
}
@@ -2715,6 +2746,27 @@ export async function updateExchangeFromUrlHandler(
}
const oldExchangeState = getExchangeState(r);
+ const entryMetadata = () =>
+ canonicalJson([
+ r.noFees ?? false,
+ r.peerPaymentsDisabled ?? false,
+ r.directDepositDisabled ?? false,
+ r.tosCurrentEtag ?? null,
+ r.supersededKeySet ?? null,
+ r.unavailableReason ?? null,
+ ]);
+ const currencyScope = {
+ type: ScopeType.Exchange as const,
+ currency: keysInfo.currency,
+ url: exchangeBaseUrl,
+ };
+ const currencySpecChanged =
+ !!keysInfo.currency_specification &&
+ canonicalJson(
+ (await tx.getCurrencyInfo(currencyScope))?.currencySpec ?? null,
+ ) !== canonicalJson(keysInfo.currency_specification);
+ const oldMetadata = entryMetadata();
+ let denominationsChanged = false;
const existingDetails = await getExchangeRecordsInternal(tx, r.baseUrl);
let detailsPointerChanged = false;
if (!existingDetails) {
@@ -3061,9 +3113,11 @@ export async function updateExchangeFromUrlHandler(
changed = true;
}
if (changed) {
+ denominationsChanged = true;
await tx.upsertDenomination(oldDenom);
}
} else {
+ denominationsChanged = true;
await tx.upsertDenomination(denomRec);
}
}
@@ -3100,12 +3154,14 @@ export async function updateExchangeFromUrlHandler(
logger.info(
`setting denomination ${x.denomPubHash} to offered=false`,
);
+ denominationsChanged = true;
await tx.upsertDenomination(x);
}
} else {
if (!x.isOffered) {
x.isOffered = true;
logger.info(`setting denomination ${x.denomPubHash} to offered=true`);
+ denominationsChanged = true;
await tx.upsertDenomination(x);
}
}
@@ -3140,13 +3196,21 @@ export async function updateExchangeFromUrlHandler(
const newExchangeState = getExchangeState(r);
- tx.notify({
- type: NotificationType.ExchangeStateTransition,
- exchangeBaseUrl,
- causeHint: "update-from-response",
- newExchangeState,
- oldExchangeState,
- });
+ notifyExchangeUpdate(
+ wex,
+ tx,
+ {
+ type: NotificationType.ExchangeStateTransition,
+ exchangeBaseUrl,
+ causeHint: "update-from-response",
+ newExchangeState,
+ oldExchangeState,
+ },
+ currencySpecChanged ||
+ denominationsChanged ||
+ oldMetadata !== entryMetadata() ||
+ canonicalJson(existingDetails ?? null) !== canonicalJson(newDetails),
+ );
return TaskRunResult.progress();
});
diff --git a/packages/taler-wallet-core/src/shepherd-longpoll.test.ts b/packages/taler-wallet-core/src/shepherd-longpoll.test.ts
@@ -37,7 +37,6 @@ const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
function fixture(t: TestContext) {
const groups = new Map<string, WalletWithdrawalGroup>();
- const completed: string[] = [];
const errors: unknown[] = [];
const delays: number[] = [];
const requests: { url: URL; finish: () => void }[] = [];
@@ -46,9 +45,7 @@ function fixture(t: TestContext) {
const tx = {
getWithdrawalGroup: async (id: string) => groups.get(id),
getOperationRetry: async () => undefined,
- deleteOperationRetry: async (id: string) => {
- completed.push(id);
- },
+ deleteOperationRetry: async () => {},
upsertOperationRetry: async (record: unknown) => {
errors.push(record);
},
@@ -112,7 +109,7 @@ function fixture(t: TestContext) {
scheduler.startShepherdTask(taskId);
return taskId;
}
- return { start, completed, errors, delays, requests };
+ return { start, scheduler, errors, delays, requests };
}
test("scheduler leaves capacity for foreground work while 32 withdrawals long-poll", async (t) => {
@@ -121,9 +118,10 @@ test("scheduler leaves capacity for foreground work while 32 withdrawals long-po
await tick();
assert.equal(f.requests.length, 3);
const foreground = f.start("foreground", WithdrawalGroupStatus.Done);
+ assert.ok(f.scheduler.getActiveTasks().includes(foreground));
await tick();
assert.ok(
- f.completed.includes(foreground),
+ !f.scheduler.getActiveTasks().includes(foreground),
"foreground task must finish before any poll is released",
);
assert.equal(f.requests.length, 3);
diff --git a/packages/taler-wallet-core/src/shepherd.ts b/packages/taler-wallet-core/src/shepherd.ts
@@ -416,22 +416,7 @@ export class TaskSchedulerImpl implements TaskScheduler {
}
async resetTask(taskId: TaskIdStr): Promise<void> {
- await this.ws.runStandaloneWalletDbTx(async (tx) => {
- logger.trace(`storing task [reset] for ${taskId}`);
- const hadError = (await tx.getOperationRetry(taskId))?.lastError;
- await tx.deleteOperationRetry(taskId);
- if (hadError) {
- const notif = await taskToRetryNotification(
- this.ws,
- tx,
- taskId,
- undefined,
- );
- if (notif) {
- tx.notify(notif);
- }
- }
- });
+ await clearTaskRetry(this.ws, taskId);
this.stopShepherdTask(taskId);
this.startShepherdTask(taskId);
}
@@ -641,7 +626,7 @@ export class TaskSchedulerImpl implements TaskScheduler {
break;
}
case TaskRunResultType.Progress: {
- await storeTaskProgress(this.ws, taskId);
+ await clearTaskRetry(this.ws, taskId);
break;
}
case TaskRunResultType.ScheduleLater: {
@@ -657,7 +642,7 @@ export class TaskSchedulerImpl implements TaskScheduler {
break;
}
case TaskRunResultType.Finished:
- await storePendingTaskFinished(this.ws, taskId);
+ await clearTaskRetry(this.ws, taskId);
if (info.rerunRequested) {
// A wakeup arrived while we were finishing.
// Re-run instead of terminating, otherwise the
@@ -669,7 +654,7 @@ export class TaskSchedulerImpl implements TaskScheduler {
}
return;
case TaskRunResultType.LongpollReturnedPending: {
- await storeTaskProgress(this.ws, taskId);
+ await clearTaskRetry(this.ws, taskId);
// Also back off when no poll completed, to avoid a busy retry loop.
if (!wex.longpollWaited) {
logger.info(
@@ -730,14 +715,19 @@ async function capAutoRefreshRetry(
);
}
-async function storePendingTaskError(
+export async function storePendingTaskError(
ws: InternalWalletState,
pendingTaskId: string,
e: TalerErrorDetail,
): Promise<WalletOperationRetry> {
logger.trace(`storing task [pending] with ERROR for ${pendingTaskId}`);
- const res = await ws.runStandaloneWalletDbTx(async (tx) => {
+ return ws.runStandaloneWalletDbTx(async (tx) => {
let retryRecord = await tx.getOperationRetry(pendingTaskId);
+ const sameExchangeError =
+ parseTaskIdentifier(pendingTaskId).tag ===
+ PendingTaskType.ExchangeUpdate &&
+ retryRecord?.lastError?.code === e.code &&
+ retryRecord.lastError.hint === e.hint;
if (!retryRecord) {
retryRecord = {
id: pendingTaskId,
@@ -750,27 +740,39 @@ async function storePendingTaskError(
}
await capAutoRefreshRetry(tx, retryRecord);
await tx.upsertOperationRetry(retryRecord);
- return {
- notification: await taskToRetryNotification(ws, tx, pendingTaskId, e),
- retryRecord,
- };
+ const notification = await taskToRetryNotification(
+ ws,
+ tx,
+ pendingTaskId,
+ e,
+ );
+ if (notification) {
+ if (sameExchangeError)
+ tx.scheduleOnCommit(() => ws.notifyInternal(notification));
+ else tx.notify(notification);
+ }
+ return retryRecord;
});
- if (res?.notification) {
- ws.notify(res.notification);
- }
- return res.retryRecord;
}
-/**
- * Task made progress, clear error.
- */
-async function storeTaskProgress(
+/** Publish recovery in the same commit that removes the displayed error. */
+export async function clearTaskRetry(
ws: InternalWalletState,
- pendingTaskId: string,
+ taskId: string,
): Promise<void> {
- logger.trace(`storing task [progress] for ${pendingTaskId}`);
await ws.runStandaloneWalletDbTx(async (tx) => {
- await tx.deleteOperationRetry(pendingTaskId);
+ const retry = await tx.getOperationRetry(taskId);
+ if (!retry) return;
+ await tx.deleteOperationRetry(taskId);
+ if (retry.lastError) {
+ const notification = await taskToRetryNotification(
+ ws,
+ tx,
+ taskId,
+ undefined,
+ );
+ if (notification) tx.notify(notification);
+ }
});
}
@@ -824,16 +826,6 @@ async function storePendingTaskPending(
return res.retryRecord;
}
-async function storePendingTaskFinished(
- ws: InternalWalletState,
- pendingTaskId: string,
-): Promise<void> {
- logger.trace(`storing task [finished] for ${pendingTaskId}`);
- await ws.runStandaloneWalletDbTx(async (tx) => {
- await tx.deleteOperationRetry(pendingTaskId);
- });
-}
-
function getWalletExecutionContextForTask(
ws: InternalWalletState,
taskId: TaskIdStr,
diff --git a/packages/taler-wallet-core/src/wallet-notifications.test.ts b/packages/taler-wallet-core/src/wallet-notifications.test.ts
@@ -53,7 +53,11 @@ import { runnerFactories } from "./db/testing/runners.js";
import { doExchangeAutoRefresh, waitReadyExchange } from "./exchanges.js";
import { preparePayForUriV2, processPurchase } from "./pay-merchant.js";
import { processRefreshBalance } from "./refreshBalance.js";
-import { TaskSchedulerImpl } from "./shepherd.js";
+import {
+ clearTaskRetry,
+ storePendingTaskError,
+ TaskSchedulerImpl,
+} from "./shepherd.js";
import {
applyRunConfigDefaults,
getNormalWalletExecutionContext,
@@ -262,6 +266,54 @@ async function fixture(makeRunner: (typeof runnerFactories)[number]) {
}
for (const makeRunner of runnerFactories) {
+ test(`${makeRunner.name}: exchange retry publishes changed errors and their removal`, async () => {
+ const f = await fixture(makeRunner);
+ try {
+ const id = TaskIdentifiers.forExchangeUpdateFromUrl(exchangeUrl);
+ const error = {
+ code: TalerErrorCode.WALLET_NETWORK_ERROR,
+ hint: "offline",
+ };
+ const internal: WalletNotification[] = [];
+ f.ws.addNotificationListener((n) => internal.push(n));
+ await storePendingTaskError(f.ws, id, {
+ ...error,
+ when: AbsoluteTime.fromMilliseconds(1),
+ });
+ await storePendingTaskError(f.ws, id, {
+ ...error,
+ when: AbsoluteTime.fromMilliseconds(2),
+ });
+ await storePendingTaskError(f.ws, id, { ...error, hint: "timeout" });
+ await clearTaskRetry(f.ws, id);
+ await clearTaskRetry(f.ws, id);
+ await tick();
+ const exchangeErrors = (events: WalletNotification[]) =>
+ events.flatMap((n) =>
+ n.type === NotificationType.ExchangeStateTransition
+ ? [n.errorInfo?.hint]
+ : [],
+ );
+ assert.deepEqual(exchangeErrors(f.notifications), [
+ "offline",
+ "timeout",
+ undefined,
+ ]);
+ assert.deepEqual(exchangeErrors(internal), [
+ "offline",
+ "offline",
+ "timeout",
+ undefined,
+ ]);
+ assert.equal(
+ await f.db.runReadWriteTx((tx) => tx.getOperationRetry(id)),
+ undefined,
+ );
+ } finally {
+ await f.close();
+ }
+ });
+
test(
`${makeRunner.name}: auto-refresh wakes internal waiters without frontend reloads`,
{ timeout: 5000 },