commit 70340843124f74f05eb5e76573dca7ff9300d75a parent 9a732caca330d4c509a18d189b34bf0aa4e19113 Author: Florian Dold <dold@taler.net> Date: Mon, 9 Nov 2026 15:30:32 +0100 wallet-core: release task slots during long polls Suspend network waits as one phase and process results after resumption. Use completed poll observations to back off early replies. Diffstat:
14 files changed, 789 insertions(+), 176 deletions(-)
diff --git a/packages/taler-wallet-core/src/deposits.ts b/packages/taler-wallet-core/src/deposits.ts @@ -162,6 +162,7 @@ import { parseTransactionIdentifier, } from "./transactions.js"; import { + suspendForLongpoll, denomRefKey, getDenomInfos, WalletExecutionContext, @@ -2671,14 +2672,19 @@ async function trackDeposit( }); const exchangeClient = walletExchangeClient(exchangeUrl, wex); // wait for a 202 state where kyc_ok is false or a 200 OK response - const trackResp = await exchangeClient.trackDeposit({ - wireHash, - merchantPub: depositGroup.merchantPub, - contractTermsHash: depositGroup.contractTermsHash, - coinPub, - merchantSig: sigResp.sig, + const trackResp = await suspendForLongpoll( + wex, + () => + exchangeClient.trackDeposit({ + wireHash, + merchantPub: depositGroup.merchantPub, + contractTermsHash: depositGroup.contractTermsHash, + coinPub, + merchantSig: sigResp.sig, + longpoll, + }), longpoll, - }); + ); logger.trace(`deposits response status: ${trackResp.response.status}`); switch (trackResp.case) { case HttpStatusCode.Accepted: { diff --git a/packages/taler-wallet-core/src/exchanges.ts b/packages/taler-wallet-core/src/exchanges.ts @@ -206,6 +206,7 @@ import { } from "./transactions.js"; import { WALLET_EXCHANGE_PROTOCOL_VERSION } from "./versions.js"; import { + suspendForLongpoll, denomRefKey, InternalWalletState, WalletExecutionContext, @@ -5412,13 +5413,15 @@ async function handleExchangeKycPendingLegitimization( // Long-poll for target 3 <-> KYC status to be OK. logger.info(`long-polling wallet KYC status for ${paytoHash}`); const exchangeClient = walletExchangeClient(exchange.baseUrl, wex); - const resp = await exchangeClient.checkKycStatus({ - paytoHash, - accountPub: reserve.reservePub, - accountSig: sigResp.sig, - longpoll: true, - lpt: 3, - }); + const resp = await suspendForLongpoll(wex, () => + exchangeClient.checkKycStatus({ + paytoHash, + accountPub: reserve.reservePub, + accountSig: sigResp.sig, + longpoll: true, + lpt: 3, + }), + ); logger.info(`kyc-check (long-poll) response status ${resp.response.status}`); diff --git a/packages/taler-wallet-core/src/kyc.ts b/packages/taler-wallet-core/src/kyc.ts @@ -40,7 +40,7 @@ import { timestampPreciseToDb, } from "./db/records.js"; import { ReadyExchangeSummary } from "./exchanges.js"; -import { WalletExecutionContext } from "./wallet.js"; +import { suspendForLongpoll, WalletExecutionContext } from "./wallet.js"; import { walletExchangeClient } from "./wallet.js"; /** @@ -588,14 +588,19 @@ export async function runKycCheckAlgo( ); const exchangeClient = walletExchangeClient(st.exchangeBaseUrl, wex); - const kycRes = await exchangeClient.checkKycStatus({ - paytoHash: st.paytoHash, - accountPub: st.accountPub, - accountSig: sigResp.sig, - longpoll: doLongpoll, - lpt, - minRule, - }); + const kycRes = await suspendForLongpoll( + wex, + () => + exchangeClient.checkKycStatus({ + paytoHash: st.paytoHash, + accountPub: st.accountPub, + accountSig: sigResp.sig, + longpoll: doLongpoll, + lpt, + minRule, + }), + doLongpoll, + ); const status = kycRes.response.status; logger.trace( diff --git a/packages/taler-wallet-core/src/longpoll-tracking.test.ts b/packages/taler-wallet-core/src/longpoll-tracking.test.ts @@ -0,0 +1,167 @@ +/* + This file is part of GNU Taler + (C) 2026 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +import assert from "node:assert/strict"; +import test from "node:test"; +import { + CancellationToken, + ObservabilityEvent, + ObservabilityEventType, + LongpollQueue, + fetchLongpoll, + openPromise, +} from "@gnu-taler/taler-util"; +import { + dummyHttpResponse, + HttpRequestLibrary, +} from "@gnu-taler/taler-util/http"; +import { + getNormalWalletExecutionContext, + InternalWalletState, +} from "./wallet.js"; + +function taskContext( + http: HttpRequestLibrary, + events: ObservabilityEvent[] = [], +) { + return getNormalWalletExecutionContext( + { initCalled: true, http } as InternalWalletState, + CancellationToken.CONTINUE, + undefined, + { + observe(event) { + events.push(event); + }, + }, + ); +} + +test("task retry state remembers any successful poll that waited long enough", async (t) => { + let now = 0n; + t.mock.method(process.hrtime, "bigint", () => now); + for (const timeoutMs of [500, 10000, 15000, 30000]) { + let durationNs = 0n; + const http = { + async fetch() { + now += durationNs; + return dummyHttpResponse; + }, + }; + const task = taskContext(http); + const queue = new LongpollQueue(); + const poll = () => + fetchLongpoll(queue, task.http, new URL("https://example/poll"), { + maxTimeoutMs: timeoutMs, + onLongpoll: task.onLongpoll, + }); + assert.ok(!task.longpollWaited); + durationNs = BigInt(timeoutMs) * 500000n; + assert.equal(await poll(), dummyHttpResponse); + assert.ok(!task.longpollWaited); + durationNs = BigInt(Math.ceil((timeoutMs * 2) / 3)) * 1000000n; + await poll(); + assert.equal(task.longpollWaited, true); + durationNs = 0n; + await poll(); + assert.equal(task.longpollWaited, true); + } +}); + +test("snapshots, failures and cancellation do not satisfy the task wait", async (t) => { + let now = 0n; + t.mock.method(process.hrtime, "bigint", () => now); + const source = CancellationToken.create(); + const failure = new Error("network failure"); + const http = { + async fetch(url: string) { + now += 30000000000n; + if (url.includes("/error")) throw failure; + if (url.includes("/cancelled")) source.cancel(); + return dummyHttpResponse; + }, + }; + const first = taskContext(http); + const second = taskContext(http); + const queue = new LongpollQueue(); + const poll = (path: string, options = {}) => + fetchLongpoll(queue, http, new URL("https://example/" + path), { + maxTimeoutMs: 500, + onLongpoll: first.onLongpoll, + ...options, + }); + await poll("snapshot", { maxTimeoutMs: 0 }); + await assert.rejects(poll("error"), failure); + await poll("cancelled", { cancellationToken: source.token }); + assert.ok(!first.longpollWaited); + await fetchLongpoll(queue, http, new URL("https://example/poll"), { + onLongpoll: second.onLongpoll, + }); + assert.equal(second.longpollWaited, true); + assert.ok(!first.longpollWaited); +}); + +test("one queue shares capacity across task transports without counting queue delay", async (t) => { + let now = 0n; + t.mock.method(process.hrtime, "bigint", () => now * 1000000n); + const queue = new LongpollQueue(); + const url = new URL("https://same.example/status"); + const gates = Array.from({ length: 3 }, () => openPromise<void>()); + const busy = gates.map((gate) => + fetchLongpoll( + queue, + { + async fetch() { + await gate.promise; + return dummyHttpResponse; + }, + }, + url, + ), + ); + await new Promise<void>((resolve) => setImmediate(resolve)); + let started = false; + const events: ObservabilityEvent[] = []; + const task = taskContext( + { + async fetch() { + started = true; + now += 1000n; + return dummyHttpResponse; + }, + }, + events, + ); + const waiting = fetchLongpoll(queue, task.http, url, { + maxTimeoutMs: 10000, + onLongpoll: task.onLongpoll, + }); + await new Promise<void>((resolve) => setImmediate(resolve)); + assert.equal(started, false); + now += 100000n; + gates[0].resolve(); + await waiting; + assert.ok(!task.longpollWaited); + assert.equal(events.length, 1); + const event = events[0]; + assert.equal(event.type, ObservabilityEventType.LongpollFinished); + if (event.type !== ObservabilityEventType.LongpollFinished) assert.fail(); + assert.equal(event.queueWaitMs, 100000); + assert.equal(event.durationMs, 1000); + assert.equal(event.timeoutMs, 10000); + assert.equal(event.outcome, "success"); + gates.forEach((gate) => gate.resolve()); + await Promise.all(busy); +}); diff --git a/packages/taler-wallet-core/src/pay-merchant.ts b/packages/taler-wallet-core/src/pay-merchant.ts @@ -198,6 +198,7 @@ import { parseTransactionIdentifier, } from "./transactions.js"; import { + suspendForLongpoll, denomRefKey, EXCHANGE_COINS_LOCK, getDenomInfos, @@ -5269,11 +5270,13 @@ async function processPurchaseDialogShared( contractTerms.merchant_base_url, wex, ); - const resp = await merchantClient.getPaymentStatus(contractTerms.order_id, { - contractTermHash: download.contractTermsHash, - sessionId: rec.lastSessionId ?? undefined, - timeout: MERCHANT_ORDER_STATUS_LONGPOLL_MS, - }); + const resp = await suspendForLongpoll(wex, () => + merchantClient.getPaymentStatus(contractTerms.order_id, { + contractTermHash: download.contractTermsHash, + sessionId: rec.lastSessionId ?? undefined, + timeout: MERCHANT_ORDER_STATUS_LONGPOLL_MS, + }), + ); if (isOrderUnknown(resp)) { // The merchant deleted the order, so no other wallet can pay it anymore @@ -5367,13 +5370,12 @@ async function processPurchaseDialogUnclaimed( txRes.download.contractTerms.merchant_base_url, wex, ); - let response = await merchantClient.getPaymentStatus( - txRes.download.contractTerms.order_id, - { + let response = await suspendForLongpoll(wex, () => + merchantClient.getPaymentStatus(txRes.download.contractTerms.order_id, { claimToken: txRes.rec.claimToken, sessionId: txRes.rec.lastSessionId ?? undefined, timeout: MERCHANT_ORDER_STATUS_LONGPOLL_MS, - }, + }), ); // The claim token keeps the long-poll authorized while the order is @@ -5517,9 +5519,8 @@ async function processPurchaseAutoRefund( download.contractTerms.merchant_base_url, wex, ); - const resp = await merchantClient.getPaymentStatus( - download.contractTerms.order_id, - { + const resp = await suspendForLongpoll(wex, () => + merchantClient.getPaymentStatus(download.contractTerms.order_id, { contractTermHash: download.contractTermsHash, refund: Amounts.stringify(totalKnownRefund), // After resuming past the deadline, still ask the merchant once. A @@ -5527,7 +5528,7 @@ async function processPurchaseAutoRefund( // earlier long polls by the deadline so completion is not delayed. timeout: MERCHANT_ORDER_STATUS_LONGPOLL_MS, deadline, - }, + }), ); if (isOrderUnknown(resp)) { diff --git a/packages/taler-wallet-core/src/pay-peer-pull-credit.ts b/packages/taler-wallet-core/src/pay-peer-pull-credit.ts @@ -118,7 +118,11 @@ import { constructTransactionIdentifier, isUnsuccessfulTransaction, } from "./transactions.js"; -import { WalletExecutionContext, walletExchangeClient } from "./wallet.js"; +import { + suspendForLongpoll, + WalletExecutionContext, + walletExchangeClient, +} from "./wallet.js"; import { WithdrawTransactionContext, getExchangeWithdrawalInfo, @@ -758,9 +762,8 @@ async function processPendingReady( ): Promise<TaskRunResult> { const ctx = new PeerPullCreditTransactionContext(wex, pullIni.pursePub); const exchangeClient = walletExchangeClient(pullIni.exchangeBaseUrl, wex); - const resp = await exchangeClient.getPurseStatusAtDeposit( - pullIni.pursePub, - true, + const resp = await suspendForLongpoll(wex, () => + exchangeClient.getPurseStatusAtDeposit(pullIni.pursePub, true), ); switch (resp.case) { diff --git a/packages/taler-wallet-core/src/pay-peer-pull-debit.ts b/packages/taler-wallet-core/src/pay-peer-pull-debit.ts @@ -115,7 +115,11 @@ import { makeTransactionNotFoundError, parseTransactionIdentifier, } from "./transactions.js"; -import { WalletExecutionContext, walletExchangeClient } from "./wallet.js"; +import { + suspendForLongpoll, + WalletExecutionContext, + walletExchangeClient, +} from "./wallet.js"; import { WalletDbTransaction } from "./db/transaction.js"; import { requireValidExchangePurseDepositConfirmation, @@ -1054,9 +1058,8 @@ async function processPeerPullDebitDialogProposed( ): Promise<TaskRunResult> { const ctx = new PeerPullDebitTransactionContext(wex, pullIni.peerPullDebitId); const exchangeClient = walletExchangeClient(pullIni.exchangeBaseUrl, wex); - const resp = await exchangeClient.getPurseStatusAtDeposit( - pullIni.pursePub, - true, + const resp = await suspendForLongpoll(wex, () => + exchangeClient.getPurseStatusAtDeposit(pullIni.pursePub, true), ); switch (resp.case) { @@ -1157,9 +1160,8 @@ async function processPeerPullDebitPendingDeposit( isPurseGoneByExpiration(contractTerms.contractTermsRaw.purse_expiration) ) { const exchangeClient = walletExchangeClient(exchangeBaseUrl, wex); - const statusResp = await exchangeClient.getPurseStatusAtMerge( - pursePub, - true, + const statusResp = await suspendForLongpoll(wex, () => + exchangeClient.getPurseStatusAtMerge(pursePub, true), ); switch (statusResp.case) { case "ok": diff --git a/packages/taler-wallet-core/src/pay-peer-push-credit.ts b/packages/taler-wallet-core/src/pay-peer-push-credit.ts @@ -117,7 +117,11 @@ import { makeTransactionNotFoundError, parseTransactionIdentifier, } from "./transactions.js"; -import { WalletExecutionContext, walletExchangeClient } from "./wallet.js"; +import { + suspendForLongpoll, + WalletExecutionContext, + walletExchangeClient, +} from "./wallet.js"; import { WithdrawTransactionContext, getExchangeWithdrawalInfo, @@ -933,9 +937,8 @@ async function processPeerPushCreditKycHardLimitRecovery( contractTerms: PeerContractTerms, ): Promise<TaskRunResult> { const exchangeClient = walletExchangeClient(peerInc.exchangeBaseUrl, wex); - const statusResp = await exchangeClient.getPurseStatusAtMerge( - peerInc.pursePub, - true, + const statusResp = await suspendForLongpoll(wex, () => + exchangeClient.getPurseStatusAtMerge(peerInc.pursePub, true), ); let nextStatus: PeerPushCreditStatus | undefined; switch (statusResp.case) { @@ -1186,9 +1189,8 @@ async function reconcileExpiredPeerPushCredit( contractTerms: PeerContractTerms, ): Promise<TaskRunResult> { const exchangeClient = walletExchangeClient(peerInc.exchangeBaseUrl, wex); - const statusResp = await exchangeClient.getPurseStatusAtMerge( - peerInc.pursePub, - true, + const statusResp = await suspendForLongpoll(wex, () => + exchangeClient.getPurseStatusAtMerge(peerInc.pursePub, true), ); switch (statusResp.case) { case "ok": @@ -1241,10 +1243,12 @@ async function processAbortingPeerPushCredit( peerInc: WalletPeerPushCredit, contractTerms: PeerContractTerms, ): Promise<TaskRunResult> { - const statusResp = await walletExchangeClient( - peerInc.exchangeBaseUrl, - wex, - ).getPurseStatusAtMerge(peerInc.pursePub, true); + const statusResp = await suspendForLongpoll(wex, () => + walletExchangeClient(peerInc.exchangeBaseUrl, wex).getPurseStatusAtMerge( + peerInc.pursePub, + true, + ), + ); switch (statusResp.case) { case "ok": await requireValidExchangePurseStatus( @@ -1627,9 +1631,8 @@ async function processPeerPushDebitDialogProposed( pullIni.peerPushCreditId, ); const exchangeClient = walletExchangeClient(pullIni.exchangeBaseUrl, wex); - const resp = await exchangeClient.getPurseStatusAtMerge( - pullIni.pursePub, - true, + const resp = await suspendForLongpoll(wex, () => + exchangeClient.getPurseStatusAtMerge(pullIni.pursePub, true), ); switch (resp.case) { diff --git a/packages/taler-wallet-core/src/pay-peer-push-debit.ts b/packages/taler-wallet-core/src/pay-peer-push-debit.ts @@ -117,7 +117,11 @@ import { constructTransactionIdentifier, isUnsuccessfulTransaction, } from "./transactions.js"; -import { WalletExecutionContext, walletExchangeClient } from "./wallet.js"; +import { + suspendForLongpoll, + WalletExecutionContext, + walletExchangeClient, +} from "./wallet.js"; import { updateWithdrawalDenomsForCurrency } from "./withdraw.js"; import { reconcilePurgedPurseDeposits } from "./purse-deposit-reconciliation.js"; @@ -1305,7 +1309,9 @@ async function processPeerPushDebitReady( peerPushInitiation.exchangeBaseUrl, wex, ); - const resp = await exchangeClient.getPurseStatusAtMerge(pursePub, true); + const resp = await suspendForLongpoll(wex, () => + exchangeClient.getPurseStatusAtMerge(pursePub, true), + ); switch (resp.case) { case "ok": { diff --git a/packages/taler-wallet-core/src/shepherd-longpoll.test.ts b/packages/taler-wallet-core/src/shepherd-longpoll.test.ts @@ -0,0 +1,173 @@ +/* + This file is part of GNU Taler + (C) 2026 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +import assert from "node:assert/strict"; +import { test, TestContext } from "node:test"; +import { + CancellationToken, + Duration, + LongpollQueue, + openPromise, +} from "@gnu-taler/taler-util"; +import { + dummyHttpResponse, + HeadersImpl, + HttpRequestLibrary, +} from "@gnu-taler/taler-util/http"; +import { TaskIdentifiers } from "./common.js"; +import { WalletWithdrawalGroup, WithdrawalGroupStatus } from "./db/records.js"; +import { WalletDbTransaction } from "./db/transaction.js"; +import { TaskSchedulerImpl } from "./shepherd.js"; +import { InternalWalletState } from "./wallet.js"; + +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 }[] = []; + // Only storage and the network are faked. The real scheduler constructs + // execution contexts and invokes the real withdrawal handler and clients. + const tx = { + getWithdrawalGroup: async (id: string) => groups.get(id), + getOperationRetry: async () => undefined, + deleteOperationRetry: async (id: string) => { + completed.push(id); + }, + upsertOperationRetry: async (record: unknown) => { + errors.push(record); + }, + } as unknown as WalletDbTransaction; + const http: HttpRequestLibrary = { + async fetch(url, options) { + const gate = openPromise<void>(); + requests.push({ url: new URL(url), finish: () => gate.resolve() }); + await ( + options?.cancellationToken ?? CancellationToken.CONTINUE + ).racePromise(gate.promise); + const headers = new HeadersImpl(); + headers.set("content-type", "application/json"); + return { + ...dummyHttpResponse, + requestUrl: url, + status: 404, + headers, + json: async () => ({ code: 1 }), + }; + }, + }; + const runTx = <T>(f: (tx: WalletDbTransaction) => Promise<T>) => f(tx); + const ws = { + initCalled: true, + stopped: false, + networkAvailable: true, + http, + longpollQueue: new LongpollQueue(), + config: { testing: { emitObservabilityEvents: false } }, + db: { runReadWriteTx: runTx }, + runStandaloneWalletDbTx: runTx, + timerGroup: { + resolveAfter(delay: Duration) { + const ms = Duration.toMilliseconds(delay); + delays.push(ms); + return new Promise<void>((resolve) => setTimeout(resolve, ms)); + }, + }, + } as unknown as InternalWalletState; + const scheduler = new TaskSchedulerImpl(ws); + ws.taskScheduler = scheduler; + // Start only the tasks named by the test, without database discovery. + t.mock.method(scheduler, "ensureRunning", async () => {}); + t.after(async () => { + ws.stopped = true; + await scheduler.shutdown(); + }); + function start( + id: string, + status = WithdrawalGroupStatus.PendingQueryingStatus, + ) { + const group = { + withdrawalGroupId: id, + status, + reservePub: id, + exchangeBaseUrl: "https://exchange.example/", + } as WalletWithdrawalGroup; + groups.set(id, group); + const taskId = TaskIdentifiers.forWithdrawal(group); + scheduler.startShepherdTask(taskId); + return taskId; + } + return { start, completed, errors, delays, requests }; +} + +test("scheduler leaves capacity for foreground work while 32 withdrawals long-poll", async (t) => { + const f = fixture(t); + for (let i = 0; i < 32; i++) f.start("poll-" + i); + await tick(); + assert.equal(f.requests.length, 3); + const foreground = f.start("foreground", WithdrawalGroupStatus.Done); + await tick(); + assert.ok( + f.completed.includes(foreground), + "foreground task must finish before any poll is released", + ); + assert.equal(f.requests.length, 3); + assert.deepEqual(f.errors, []); +}); + +for (const scenario of [ + { name: "early reply", durationMs: 1000, backoff: true }, + { name: "full wait", durationMs: 30000, backoff: false }, +]) { + test(`scheduler retry delay follows actual long-poll completion: ${scenario.name}`, async (t) => { + t.mock.timers.enable({ apis: ["Date", "setTimeout"], now: 100000 }); + t.mock.method( + process.hrtime, + "bigint", + () => BigInt(Date.now()) * 1000000n, + ); + const f = fixture(t); + f.start("poll"); + await tick(); + assert.equal(f.requests.length, 1); + assert.equal(f.requests[0].url.searchParams.get("timeout_ms"), "30000"); + t.mock.timers.tick(scenario.durationMs); + f.requests[0].finish(); + await tick(); + if (scenario.backoff) { + assert.equal(f.requests.length, 1); + assert.deepEqual(f.delays, [10000]); + t.mock.timers.tick(9999); + await tick(); + assert.equal(f.requests.length, 1); + t.mock.timers.tick(1); + await tick(); + } else { + assert.deepEqual(f.delays, []); + } + assert.equal(f.requests.length, 2, "retry must start at the expected time"); + // The next run must get fresh tracking state, even after a full wait. + const previousDelays = f.delays.length; + t.mock.timers.tick(1000); + f.requests[1].finish(); + await tick(); + assert.equal(f.requests.length, 2); + assert.deepEqual(f.delays.slice(previousDelays), [10000]); + assert.deepEqual(f.errors, []); + }); +} diff --git a/packages/taler-wallet-core/src/shepherd.ts b/packages/taler-wallet-core/src/shepherd.ts @@ -563,12 +563,13 @@ export class TaskSchedulerImpl implements TaskScheduler { taskId, parseTaskIdentifier(taskId).tag === PendingTaskType.Refresh, info.cts.token, - async () => { + async (lease) => { const wex = getWalletExecutionContextForTask( this.ws, taskId, info.cts.token, ); + wex.taskExecution = lease; const startTime = AbsoluteTime.now(); // Reset immediately before running the handler so that a wakeup // while queued is satisfied by this run, while a wakeup during @@ -669,12 +670,10 @@ export class TaskSchedulerImpl implements TaskScheduler { return; case TaskRunResultType.LongpollReturnedPending: { await storeTaskProgress(this.ws, taskId); - // Make sure that we are waiting a bit if long-polling returned too early. - if ( - Duration.cmp(taskDuration, Duration.fromSpec({ seconds: 20 })) < 0 - ) { + // Also back off when no poll completed, to avoid a busy retry loop. + if (!wex.longpollWaited) { logger.info( - `long-poller for ${taskId} returned unexpectedly early (${taskDuration.d_ms} ms), waiting 10 seconds`, + `long-poller for ${taskId} returned before two-thirds of the requested HTTP wait, waiting 10 seconds`, ); await this.wait(taskId, info, Duration.fromSpec({ seconds: 10 })); } else { @@ -869,6 +868,7 @@ function getWalletExecutionContextForTask( }; wex = getNormalWalletExecutionContext(ws, cancellationToken, undefined, oc); } + wex.longpollWaited = false; return wex; } diff --git a/packages/taler-wallet-core/src/wallet.ts b/packages/taler-wallet-core/src/wallet.ts @@ -23,7 +23,12 @@ /** * Imports. */ -import { LongpollObserver } from "@gnu-taler/taler-util"; +import { + AbsoluteTime, + LongpollObserver, + LongpollResult, +} from "@gnu-taler/taler-util"; +import { TaskExecutionLease } from "./task-run-limiter.js"; import { TaskIdentifiers, PendingTaskType, @@ -146,6 +151,9 @@ const logger = new Logger("wallet.ts"); * request handler or for a shepherded task. */ export interface WalletExecutionContext { + taskExecution?: TaskExecutionLease; + /** A completed long poll waited long enough to retry without backoff. */ + longpollWaited?: boolean; onLongpoll?: LongpollObserver; /** * Start a database transaction. @@ -363,6 +371,20 @@ export class AdmittedWalletDbHandle implements WalletDbHandle { } } +/** + * Run a network-only phase under the TaskExecutionLease.suspend contract. + * Non-task callers, and immediate checks with enabled=false, run directly. + */ +export function suspendForLongpoll<T>( + wex: WalletExecutionContext, + wait: () => Promise<T>, + enabled = true, +): Promise<T> { + return enabled && wex.taskExecution + ? wex.taskExecution.suspend(wait) + : wait(); +} + /** Per-operation overrides; transport and long-poll ownership stay with the wallet. */ export interface WalletClientOptions { timeout?: Duration; @@ -803,6 +825,23 @@ async function getClientFromWalletState( return client; } +function recordLongpoll( + wex: WalletExecutionContext, + result: LongpollResult, +): void { + if ( + result.outcome === "success" && + result.durationMs >= (result.timeoutMs * 2) / 3 + ) { + wex.longpollWaited = true; + } + wex.oc.observe({ + ...result, + type: ObservabilityEventType.LongpollFinished, + when: AbsoluteTime.now(), + }); +} + export function getObservedWalletExecutionContext( ws: InternalWalletState, cancellationToken: CancellationToken, @@ -817,6 +856,7 @@ export function getObservedWalletExecutionContext( cancellationToken, cts, cryptoApi: observeTalerCrypto(ws.cryptoApi, oc), + onLongpoll: (result) => recordLongpoll(wex, result), dbRetryState: { retriedExchangeUpdate: new Set(), }, @@ -982,6 +1022,7 @@ export function getNormalWalletExecutionContext( cancellationToken, cts, cryptoApi: ws.cryptoApi, + onLongpoll: (result) => recordLongpoll(wex, result), dbRetryState: { retriedExchangeUpdate: new Set(), }, diff --git a/packages/taler-wallet-core/src/withdraw-longpoll.test.ts b/packages/taler-wallet-core/src/withdraw-longpoll.test.ts @@ -0,0 +1,196 @@ +/* + This file is part of GNU Taler + (C) 2026 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + CancellationToken, + LongpollQueue, + openPromise, +} from "@gnu-taler/taler-util"; +import { HeadersImpl, HttpRequestLibrary } from "@gnu-taler/taler-util/http"; +import { WalletWithdrawalGroup, WithdrawalGroupStatus } from "./db/records.js"; +import { WalletExecutionContext } from "./wallet.js"; +import { processWithdrawalGroup } from "./withdraw.js"; +import { TaskRunLimiter } from "./task-run-limiter.js"; + +const tick = () => new Promise<void>((resolve) => setImmediate(resolve)); + +for (const scenario of [ + "pending", + "confirmed", + "bank-error", + "funded-after-abort", + "funded-after-bank-error", +] as const) { + test( + "bank/reserve polling resumes task capacity before processing: " + scenario, + async () => { + const limiter = new TaskRunLimiter({ + maxConcurrentTasks: 1, + maxConcurrentRefreshTasks: 1, + }); + const queue = new LongpollQueue(); + const requests: { + reserve: boolean; + gate: ReturnType<typeof openPromise<{ status: number; body: object }>>; + token: CancellationToken; + }[] = []; + const networkError = new Error("bank unavailable"); + const fundedProcessing = new Error("entered funded reserve processing"); + let waiting = false; + let phases = 0; + let dbReads = 0; + const http: HttpRequestLibrary = { + async fetch(url, options) { + assert.equal(waiting, true); + const gate = openPromise<{ status: number; body: object }>(); + const token = + options?.cancellationToken ?? CancellationToken.CONTINUE; + requests.push({ reserve: url.includes("/reserves/"), gate, token }); + const reply = await token.racePromise(gate.promise); + const headers = new HeadersImpl(); + headers.set("content-type", "application/json"); + return { + requestUrl: url, + requestMethod: "GET", + status: reply.status, + headers, + json: async () => reply.body, + text: async () => "", + bytes: async () => new Uint8Array(), + }; + }, + }; + const group = { + withdrawalGroupId: "test", + status: WithdrawalGroupStatus.PendingWaitConfirmBank, + reservePub: "reserve", + exchangeBaseUrl: "https://same.example/exchange/", + instructedAmount: "TESTKUDOS:1", + denomsSel: { + selectedDenoms: [], + totalCoinValue: "TESTKUDOS:1", + totalWithdrawCost: "TESTKUDOS:1", + }, + wgInfo: { + withdrawalType: "bank-integrated", + bankInfo: { + talerWithdrawUri: "taler://withdraw/same.example/operation", + }, + }, + } as unknown as WalletWithdrawalGroup; + const wex = { + ws: { networkAvailable: true, longpollQueue: queue }, + http, + cancellationToken: CancellationToken.CONTINUE, + async runWalletDbTx(fn: (tx: unknown) => Promise<unknown>) { + assert.equal( + waiting, + false, + "DB processing must not run during suspension", + ); + dbReads++; + // On confirmed responses, simulate a concurrently deleted transaction. + return fn({ + getWithdrawalGroup: async () => (dbReads <= 2 ? group : undefined), + getExchange: async () => { + throw fundedProcessing; + }, + }); + }, + } as unknown as WalletExecutionContext; + const result = limiter.run( + "withdraw", + false, + CancellationToken.CONTINUE, + async (lease) => { + wex.taskExecution = { + suspend: (wait) => + lease.suspend(async () => { + assert.equal(waiting, false); + waiting = true; + phases++; + try { + return await wait(); + } finally { + waiting = false; + } + }), + }; + return processWithdrawalGroup(wex, "test"); + }, + ); + // Attach rejection handling before resolving any fake network operations. + const observed = result.then( + (value) => ({ value }), + (error) => ({ error }), + ); + await tick(); + assert.equal(requests.length, 2); + assert.equal(phases, 1); + const block = openPromise<void>(); + const foreground = limiter.run( + "payment", + false, + CancellationToken.CONTINUE, + () => block.promise, + ); + await tick(); + const bank = requests.find((r) => !r.reserve)!; + const reserve = requests.find((r) => r.reserve)!; + if (scenario === "bank-error" || scenario === "funded-after-bank-error") + bank.gate.reject(networkError); + else + bank.gate.resolve({ + status: 200, + body: { + status: + scenario === "funded-after-abort" + ? "aborted" + : scenario === "confirmed" + ? "confirmed" + : "selected", + wire_types: [], + }, + }); + if (scenario !== "confirmed") { + reserve.gate.resolve( + scenario.startsWith("funded") + ? { status: 200, body: { balance: "TESTKUDOS:1" } } + : { status: 404, body: { code: 1 } }, + ); + } + await tick(); + assert.equal(dbReads, 2, "result processing must wait for a task slot"); + if (scenario === "confirmed") + assert.equal(reserve.token.isCancelled, true); + block.resolve(); + const outcome = await observed; + await foreground; + if (scenario === "bank-error") + assert.ok("error" in outcome && outcome.error === networkError); + else if (scenario.startsWith("funded")) + assert.ok("error" in outcome && outcome.error === fundedProcessing); + else + assert.equal( + "value" in outcome ? outcome.value.type : undefined, + scenario === "pending" ? "longpoll-returned-pending" : "finished", + ); + assert.equal(phases, 1); + }, + ); +} diff --git a/packages/taler-wallet-core/src/withdraw.ts b/packages/taler-wallet-core/src/withdraw.ts @@ -212,6 +212,7 @@ import { getWithdrawalVolumeKycStatus, } from "./withdrawal-kyc.js"; import { + suspendForLongpoll, denomRefKey, WalletExecutionContext, getDenomInfo, @@ -1310,10 +1311,12 @@ async function processWithdrawalGroupDialogProposed( ctx.wex, ); - const resp = await bankClient.getWithdrawalOperationById(wopid, { - old_state: "pending", - timeoutMs: 30000, - }); + const resp = await suspendForLongpoll(ctx.wex, () => + bankClient.getWithdrawalOperationById(wopid, { + old_state: "pending", + timeoutMs: 30000, + }), + ); switch (resp.case) { case HttpStatusCode.NotFound: { @@ -2466,7 +2469,9 @@ async function processQueryReserve( withdrawalGroup.exchangeBaseUrl !== undefined, "can't get funding uri from uninitialized wg", ); - const resp = await queryReserveStatus(wex, withdrawalGroup); + const resp = await suspendForLongpoll(wex, () => + queryReserveStatus(wex, withdrawalGroup), + ); if (resp.case === HttpStatusCode.NotFound) { logger.trace(`got reserve status error (not found)`); @@ -4127,120 +4132,122 @@ async function processReserveBankStatus( wex.cancellationToken, pollCts.token, ); - const bankClient = walletBankIntegrationClient( - uriResult.bankIntegrationApiBaseUrl, - wex, - { - cancellationToken: pollCancellation, - timeout: getReserveRequestTimeout(withdrawalGroup), - }, - ); - - // Both endpoints describe the same transfer from opposite sides. A - // confirmed bank transfer is enough to make progress without waiting for - // the exchange. For every other bank outcome we still wait for the reserve, - // since arrived funds are authoritative even if the bank reports an abort - // or an outage. - const bankPromise = bankClient.getWithdrawalOperationById( - uriResult.withdrawalOperationId, - { - old_state: "selected", - timeoutMs: 30000, - }, - ); - const reservePromise = queryReserveStatus( - wex, - withdrawalGroup, - pollCancellation, - ); - try { - const firstPoll = await Promise.race([ - bankPromise.then( - (value) => ({ source: "bank" as const, value }), - (reason) => ({ source: "bank-error" as const, reason }), - ), - reservePromise.then( - (value) => ({ source: "reserve" as const, value }), - (reason) => ({ source: "reserve-error" as const, reason }), - ), - ]); - - if ( - firstPoll.source === "bank" && - firstPoll.value.case === "ok" && - firstPoll.value.body.status === "confirmed" - ) { - return await processConfirmedBankWithdrawal( - wex, - ctx, - withdrawalGroup, - firstPoll.value.body, + const outcome = await suspendForLongpoll(wex, async () => { + const bankClient = walletBankIntegrationClient( + uriResult.bankIntegrationApiBaseUrl, + wex, + { + timeout: getReserveRequestTimeout(withdrawalGroup), + cancellationToken: pollCancellation, + }, + ); + try { + // Both endpoints describe the same transfer from opposite sides. A + // confirmed bank transfer is enough to make progress without waiting for + // the exchange. For every other bank outcome we still wait for the reserve, + // since arrived funds are authoritative even if the bank reports an abort + // or an outage. + const bankPromise = bankClient.getWithdrawalOperationById( + uriResult.withdrawalOperationId, + { + old_state: "selected", + timeoutMs: 30000, + }, ); - } - const [bankPoll, reservePoll] = await Promise.allSettled([ - bankPromise, - reservePromise, - ]); - - const bankStatus = - bankPoll.status === "fulfilled" && bankPoll.value.case === "ok" - ? bankPoll.value.body - : undefined; - - // A funded reserve is definitive. Prefer it even if the bank request - // failed or reports an abort: the wallet controls the reserve key and must - // recover the value that reached the exchange. - if (reservePoll.status === "fulfilled" && reservePoll.value.case === "ok") { - return await processFundedReserve( + const reservePromise = queryReserveStatus( wex, withdrawalGroup, - reservePoll.value.body, - bankStatus?.status === "confirmed" - ? { amount: bankStatus.amount } - : undefined, + pollCancellation, ); - } + const firstPoll = await Promise.race([ + bankPromise.then( + (value) => ({ source: "bank" as const, value }), + (reason) => ({ source: "bank-error" as const, reason }), + ), + reservePromise.then( + (value) => ({ source: "reserve" as const, value }), + (reason) => ({ source: "reserve-error" as const, reason }), + ), + ]); - if ( - reservePoll.status === "rejected" && - !wex.cancellationToken.isCancelled - ) { - // Until the bank confirms the transfer, exchange failures are secondary: - // keep them out of the transaction's single user-visible retry record. - logger.warn( - `reserve long-poll failed while waiting for bank confirmation: ${j2s( - getErrorDetailFromException(reservePoll.reason), - )}`, - ); + if ( + firstPoll.source === "bank" && + firstPoll.value.case === "ok" && + firstPoll.value.body.status === "confirmed" + ) { + return { type: "confirmed" as const, status: firstPoll.value.body }; + } + const [bankPoll, reservePoll] = await Promise.allSettled([ + bankPromise, + reservePromise, + ]); + return { type: "both" as const, bankPoll, reservePoll }; + } finally { + pollCts.cancel("reserve/bank status polling finished"); } + }); + if (outcome.type === "confirmed") { + return processConfirmedBankWithdrawal( + wex, + ctx, + withdrawalGroup, + outcome.status, + ); + } + const { bankPoll, reservePoll } = outcome; + const bankStatus = + bankPoll.status === "fulfilled" && bankPoll.value.case === "ok" + ? bankPoll.value.body + : undefined; - if (bankPoll.status === "rejected") { - throw bankPoll.reason; - } + // A funded reserve is definitive. Prefer it even if the bank request + // failed or reports an abort: the wallet controls the reserve key and must + // recover the value that reached the exchange. + if (reservePoll.status === "fulfilled" && reservePoll.value.case === "ok") { + return await processFundedReserve( + wex, + withdrawalGroup, + reservePoll.value.body, + bankStatus?.status === "confirmed" + ? { amount: bankStatus.amount } + : undefined, + ); + } - const status = succeedOrThrow(bankPoll.value); + if (reservePoll.status === "rejected" && !wex.cancellationToken.isCancelled) { + // Until the bank confirms the transfer, exchange failures are secondary: + // keep them out of the transaction's single user-visible retry record. + logger.warn( + `reserve long-poll failed while waiting for bank confirmation: ${j2s( + getErrorDetailFromException(reservePoll.reason), + )}`, + ); + } - if (logger.shouldLogTrace()) { - logger.trace(`response body: ${j2s(status)}`); - } + if (bankPoll.status === "rejected") { + throw bankPoll.reason; + } - if (status.status === "aborted") { - return transitionBankAborted(ctx); - } + const status = succeedOrThrow(bankPoll.value); - if (status.status != "confirmed") { - return TaskRunResult.longpollReturnedPending(); - } + if (logger.shouldLogTrace()) { + logger.trace(`response body: ${j2s(status)}`); + } - return await processConfirmedBankWithdrawal( - wex, - ctx, - withdrawalGroup, - status, - ); - } finally { - pollCts.cancel("reserve/bank status polling finished"); + if (status.status === "aborted") { + return transitionBankAborted(ctx); + } + + if (status.status != "confirmed") { + return TaskRunResult.longpollReturnedPending(); } + + return await processConfirmedBankWithdrawal( + wex, + ctx, + withdrawalGroup, + status, + ); } export interface PrepareCreateWithdrawalGroupResult {