commit 35235b3467bb200b43721edc9221925c5261a650
parent ab5a6551dcffcb0923a5b294c655d014a696b3a4
Author: Florian Dold <dold@taler.net>
Date: Mon, 9 Nov 2026 15:28:44 +0100
taler-util: report long-poll waits through an observer
Apply admitted timeouts and report HTTP duration separately from queue
waits. Keep scheduling metadata out of HTTP request options.
Diffstat:
8 files changed, 526 insertions(+), 28 deletions(-)
diff --git a/packages/libeufin-bank-webui/src/pages/BankFrame.tsx b/packages/libeufin-bank-webui/src/pages/BankFrame.tsx
@@ -643,6 +643,7 @@ function AppActivity(): VNode {
/**
* all of these are ignored
*/
+ case ObservabilityEventType.LongpollFinished:
case ObservabilityEventType.DbQueryStart:
case ObservabilityEventType.DbQueryFinishSuccess:
case ObservabilityEventType.DbQueryFinishError:
diff --git a/packages/taler-util/src/index.ts b/packages/taler-util/src/index.ts
@@ -45,6 +45,7 @@ export * from "./merchant-identifiers.js";
export * from "./merchant-pos.js";
export * from "./merchant-payout.js";
export * from "./longpoll-queue.js";
+export * from "./longpoll-http.js";
export {
xsalsa20Poly1305Decrypt,
xsalsa20Poly1305Encrypt,
diff --git a/packages/taler-util/src/longpoll-http.test.ts b/packages/taler-util/src/longpoll-http.test.ts
@@ -0,0 +1,379 @@
+/*
+ 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 } from "./CancellationToken.js";
+import {
+ HeadersImpl,
+ HttpRequestLibrary,
+ HttpRequestOptions,
+} from "./http-common.js";
+import { AbsoluteTime } from "./time.js";
+import { LongpollQueue } from "./longpoll-queue.js";
+import { fetchLongpoll, LongpollResult } from "./longpoll-http.js";
+import { openPromise } from "./promises.js";
+
+const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
+function fixture() {
+ const requests: {
+ url: URL;
+ options?: HttpRequestOptions;
+ finish: () => void;
+ }[] = [];
+ const http: HttpRequestLibrary = {
+ async fetch(url, options) {
+ const gate = openPromise<void>();
+ requests.push({
+ url: new URL(url),
+ options,
+ finish: () => gate.resolve(),
+ });
+ await gate.promise;
+ const headers = new HeadersImpl();
+ headers.set("content-type", "application/json");
+ return {
+ requestUrl: url,
+ requestMethod: "GET",
+ status: 404,
+ headers,
+ json: async () => ({ code: 1 }),
+ text: async () => "",
+ bytes: async () => new Uint8Array(),
+ };
+ },
+ };
+ return { http, requests };
+}
+
+test("deadline expiry removes a waiter and performs one immediate check", async (t) => {
+ t.mock.timers.enable({ apis: ["Date", "setTimeout"], now: 100000 });
+ const { http, requests } = fixture();
+ const queue = new LongpollQueue();
+ const url = new URL("https://same.example/status");
+ const active = Array.from({ length: 3 }, () =>
+ fetchLongpoll(queue, http, url, {}),
+ );
+ await tick();
+ const events: LongpollResult[] = [];
+ const final = fetchLongpoll(queue, http, url, {
+ maxTimeoutMs: 30000,
+ deadline: AbsoluteTime.fromMilliseconds(105000),
+ onLongpoll: (event) => events.push(event),
+ });
+ await tick();
+ assert.equal(requests.length, 3);
+ t.mock.timers.tick(5000);
+ await tick();
+ assert.equal(requests.length, 4);
+ assert.equal(requests[3].url.searchParams.get("timeout_ms"), "0");
+ requests[3].finish();
+ await final;
+ assert.deepEqual(events, [], "deadline fallback is not a poll");
+ for (const r of requests) r.finish();
+ await Promise.all(active);
+ await tick();
+ assert.equal(requests.length, 4);
+ assert.deepEqual(events, []);
+});
+
+test("deadline and caller timeout bound the adaptive timeout at admission", async (t) => {
+ t.mock.timers.enable({ apis: ["Date", "setTimeout"], now: 100000 });
+ const { http, requests } = fixture();
+ const queue = new LongpollQueue();
+ const url = new URL("https://same.example/status");
+ const active = Array.from({ length: 3 }, () =>
+ fetchLongpoll(queue, http, url, {}),
+ );
+ await tick();
+ const next = fetchLongpoll(queue, http, url, {
+ maxTimeoutMs: 4000,
+ deadline: AbsoluteTime.fromMilliseconds(105000),
+ });
+ t.mock.timers.tick(3000);
+ requests[0].finish();
+ await tick();
+ assert.equal(requests[3].url.searchParams.get("timeout_ms"), "2000");
+ // The queue deadline timer must not cancel an already admitted HTTP request.
+ t.mock.timers.tick(10000);
+ assert.equal(requests.length, 4);
+ for (const r of requests) r.finish();
+ await Promise.all([...active, next]);
+});
+
+test("cancellation takes precedence over queued deadline expiry", async (t) => {
+ t.mock.timers.enable({ apis: ["Date", "setTimeout"], now: 100000 });
+ const { http, requests } = fixture();
+ const queue = new LongpollQueue();
+ const url = new URL("https://same.example/status");
+ const active = Array.from({ length: 3 }, () =>
+ fetchLongpoll(queue, http, url, {}),
+ );
+ await tick();
+ const source = CancellationToken.create();
+ const waiting = fetchLongpoll(queue, http, url, {
+ cancellationToken: source.token,
+ maxTimeoutMs: 30000,
+ deadline: AbsoluteTime.fromMilliseconds(101000),
+ });
+ const rejected = assert.rejects(waiting, CancellationToken.CancellationError);
+ t.mock.timers.tick(1000);
+ source.cancel();
+ await rejected;
+ assert.equal(requests.length, 3);
+ for (const r of requests) r.finish();
+ await Promise.all(active);
+});
+
+test("expired deadlines and zero timeouts bypass admission", async (t) => {
+ t.mock.timers.enable({ apis: ["Date", "setTimeout"], now: 100000 });
+ const { http, requests } = fixture();
+ const url = new URL("https://same.example/status");
+ const work = [
+ fetchLongpoll(new LongpollQueue(), http, url, { maxTimeoutMs: 0 }),
+ fetchLongpoll(new LongpollQueue(), http, url, {
+ maxTimeoutMs: 30000,
+ deadline: AbsoluteTime.fromMilliseconds(99999),
+ }),
+ ];
+ await tick();
+ assert.deepEqual(
+ requests.map((r) => r.url.searchParams.get("timeout_ms")),
+ ["0", "0"],
+ );
+ for (const r of requests) r.finish();
+ await Promise.all(work);
+});
+
+test("long-poll measurements stay out of HTTP options", async () => {
+ const { http, requests } = fixture();
+ const events: LongpollResult[] = [];
+ const work = fetchLongpoll(
+ new LongpollQueue(),
+ http,
+ new URL("https://same.example/status"),
+ {
+ maxTimeoutMs: 500,
+ onLongpoll: (event) => events.push(event),
+ },
+ );
+ await tick();
+ assert.equal(events.length, 0);
+ for (const key of [
+ "longPolling",
+ "longPollTimeoutMs",
+ "queueWaitMs",
+ "maxTimeoutMs",
+ "deadline",
+ "onLongpoll",
+ ]) {
+ assert.equal(key in requests[0].options!, false);
+ }
+ requests[0].finish();
+ await work;
+ assert.equal(events.length, 1);
+ assert.equal(events[0].timeoutMs, 500);
+ assert.equal(events[0].outcome, "success");
+ assert.ok(events[0].queueWaitMs >= 0);
+ assert.ok(events[0].durationMs >= 0);
+});
+
+test("distant deadlines do not overflow the platform timer", async (t) => {
+ t.mock.timers.enable({ apis: ["Date", "setTimeout"], now: 100000 });
+ const { http, requests } = fixture();
+ const queue = new LongpollQueue();
+ const url = new URL("https://same.example/status");
+ const active = Array.from({ length: 3 }, () =>
+ fetchLongpoll(queue, http, url, {}),
+ );
+ await tick();
+ const next = fetchLongpoll(queue, http, url, {
+ maxTimeoutMs: 30000,
+ deadline: AbsoluteTime.fromMilliseconds(100000 + 0x80000000),
+ });
+ t.mock.timers.tick(1);
+ await tick();
+ assert.equal(requests.length, 3);
+ requests[0].finish();
+ await tick();
+ assert.equal(requests[3].url.searchParams.get("timeout_ms"), "10000");
+ for (const r of requests) r.finish();
+ await Promise.all([...active, next]);
+});
+test("a deadline crossed between admission and execution triggers a snapshot", async (t) => {
+ t.mock.timers.enable({ apis: ["Date", "setTimeout"], now: 100000 });
+ const { http, requests } = fixture();
+ const work = fetchLongpoll(
+ new LongpollQueue(),
+ http,
+ new URL("https://same.example/status"),
+ { maxTimeoutMs: 30000, deadline: AbsoluteTime.fromMilliseconds(100001) },
+ );
+ t.mock.timers.tick(1);
+ await tick();
+ assert.equal(requests.length, 1);
+ assert.equal(requests[0].url.searchParams.get("timeout_ms"), "0");
+ requests[0].finish();
+ await work;
+});
+
+test("HTTP throws and rejections release admission permits", async () => {
+ const queue = new LongpollQueue();
+ const url = new URL("https://same.example/status");
+ const error = new Error("request failed");
+ for (let i = 0; i < 25; i++) {
+ const http: HttpRequestLibrary = {
+ fetch() {
+ if (i % 2) throw error;
+ return Promise.reject(error);
+ },
+ };
+ await assert.rejects(fetchLongpoll(queue, http, url), (e) => e === error);
+ }
+ const { http, requests } = fixture();
+ const active = Array.from({ length: 20 }, (_, i) =>
+ fetchLongpoll(
+ queue,
+ http,
+ new URL("https://host" + Math.floor(i / 3) + ".example/status"),
+ ),
+ );
+ await tick();
+ assert.equal(
+ requests.length,
+ 20,
+ "failed requests must release global capacity",
+ );
+ for (const request of requests) request.finish();
+ const responses = await Promise.all(active);
+ assert.ok(responses.every((response) => response.status === 404));
+ const sameHost = fetchLongpoll(queue, http, url);
+ await tick();
+ assert.equal(
+ requests.length,
+ 21,
+ "failed requests must release host capacity",
+ );
+ requests[20].finish();
+ assert.equal((await sameHost).requestUrl.startsWith(url.href), true);
+});
+
+test("a never deadline waits for capacity without scheduling an expiry timer", async (t) => {
+ const timer = t.mock.method(globalThis, "setTimeout");
+ const queue = new LongpollQueue();
+ const { http, requests } = fixture();
+ const url = new URL("https://same.example/status");
+ const work = Array.from({ length: 4 }, () =>
+ fetchLongpoll(queue, http, url, { deadline: AbsoluteTime.never() }),
+ );
+ await tick();
+ assert.equal(requests.length, 3);
+ assert.equal(timer.mock.callCount(), 0);
+ requests[0].finish();
+ await tick();
+ assert.equal(requests.length, 4);
+ assert.ok(
+ requests.every(
+ (request) => Number(request.url.searchParams.get("timeout_ms")) > 0,
+ ),
+ );
+ for (const request of requests) request.finish();
+ await Promise.all(work);
+});
+
+test("observers report failures and cancellation without affecting transport outcomes", async (t) => {
+ let now = 0n;
+ t.mock.method(process.hrtime, "bigint", () => now);
+ const queue = new LongpollQueue();
+ const events: LongpollResult[] = [];
+ const failure = new Error("transport failed");
+ const url = new URL("https://example/status");
+ for (const cancelled of [false, true]) {
+ const source = CancellationToken.create();
+ const work = fetchLongpoll(
+ queue,
+ {
+ async fetch() {
+ now += 1000000000n;
+ if (cancelled) source.cancel();
+ throw failure;
+ },
+ },
+ url,
+ {
+ cancellationToken: source.token,
+ onLongpoll: (event) => events.push(event),
+ },
+ );
+ await assert.rejects(work, (e) => e === failure);
+ }
+ assert.deepEqual(
+ events.map((e) => e.outcome),
+ ["error", "cancelled"],
+ );
+ assert.ok(
+ events.every((e) => e.durationMs === 1000 && e.timeoutMs === 30000),
+ );
+ const { http, requests } = fixture();
+ const work = fetchLongpoll(queue, http, url, {
+ onLongpoll() {
+ throw Error("observer failed");
+ },
+ });
+ await tick();
+ requests[0].finish();
+ await work;
+ const next = fetchLongpoll(queue, http, url);
+ await tick();
+ requests[1].finish();
+ await next;
+});
+
+test("snapshots and cancellation before admission do not report a long poll", async () => {
+ const { http, requests } = fixture();
+ const queue = new LongpollQueue();
+ const url = new URL("https://same.example/status");
+ const events: LongpollResult[] = [];
+ const onLongpoll = (event: LongpollResult) => events.push(event);
+ const snapshot = fetchLongpoll(queue, http, url, {
+ maxTimeoutMs: 0,
+ onLongpoll,
+ });
+ await tick();
+ requests[0].finish();
+ await snapshot;
+ assert.deepEqual(events, [], "snapshot must not notify the observer");
+ const active = Array.from({ length: 3 }, () =>
+ fetchLongpoll(queue, http, url),
+ );
+ await tick();
+ const source = CancellationToken.create();
+ const waiting = fetchLongpoll(queue, http, url, {
+ cancellationToken: source.token,
+ onLongpoll,
+ });
+ const rejected = assert.rejects(waiting, CancellationToken.CancellationError);
+ source.cancel();
+ await rejected;
+ assert.deepEqual(
+ events,
+ [],
+ "cancelled queue entry must not notify the observer",
+ );
+ for (const request of requests) request.finish();
+ await Promise.all(active);
+ assert.deepEqual(events, []);
+});
diff --git a/packages/taler-util/src/longpoll-http.ts b/packages/taler-util/src/longpoll-http.ts
@@ -0,0 +1,129 @@
+/*
+ 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 { Logger } from "./logging.js";
+import { CancellationToken } from "./CancellationToken.js";
+import {
+ HttpRequestLibrary,
+ HttpRequestOptions,
+ HttpResponse,
+} from "./http-common.js";
+import { LongpollQueue } from "./longpoll-queue.js";
+import { AbsoluteTime, Duration } from "./time.js";
+import { performanceNow, performanceDelta } from "./timer.js";
+
+/** Measurements for one admitted long poll, excluding queue time from duration. */
+export interface LongpollResult {
+ url: string;
+ queueWaitMs: number;
+ timeoutMs: number;
+ durationMs: number;
+ outcome: "success" | "error" | "cancelled";
+}
+
+export type LongpollObserver = (result: LongpollResult) => void;
+
+const logger = new Logger("longpoll-http.ts");
+
+export interface LongpollRequestOptions extends HttpRequestOptions {
+ /** Reports actual long polls only, not snapshots or cancelled queue entries. */
+ onLongpoll?: LongpollObserver;
+ /** Maximum server wait in milliseconds, excluding queue time (default: 30000). */
+ maxTimeoutMs?: number;
+ /**
+ * Absolute business deadline. An absent or never deadline has no expiry.
+ * Queue time counts toward it. If it expires before the HTTP request starts,
+ * perform one immediate status request (timeout_ms=0) instead of rejecting.
+ * At admission, the remaining time caps the requested server wait.
+ * Expiry does not abort an HTTP request already in progress; the separate
+ * transport timeout and cancellation token still apply. Caller cancellation
+ * also prevents the immediate fallback request.
+ */
+ deadline?: AbsoluteTime;
+}
+
+/**
+ * Perform HTTP under the supplied queue's concurrency budget. The queue owns
+ * all scheduling state; this function applies the admitted timeout and always
+ * releases the permit. The transport stays task-local for timing and tracing.
+ */
+export async function fetchLongpoll(
+ queue: LongpollQueue,
+ http: HttpRequestLibrary,
+ url: URL,
+ {
+ maxTimeoutMs = 30000,
+ deadline,
+ onLongpoll,
+ ...options
+ }: LongpollRequestOptions = {},
+): Promise<HttpResponse> {
+ const cancellation = options.cancellationToken ?? CancellationToken.CONTINUE;
+ const remaining = () =>
+ deadline
+ ? Duration.toMilliseconds(AbsoluteTime.remaining(deadline))
+ : Infinity;
+ const immediate = () => {
+ cancellation.throwIfCancelled();
+ const target = new URL(url);
+ target.searchParams.set("timeout_ms", "0");
+ return http.fetch(target.href, options);
+ };
+
+ cancellation.throwIfCancelled();
+ if (maxTimeoutMs <= 0 || remaining() <= 0) return immediate();
+ const queuedAt = performanceNow();
+ const admission = await queue.acquire(url, cancellation, deadline);
+ if (admission.status === "deadline-expired") return immediate();
+ try {
+ cancellation.throwIfCancelled();
+ const timeoutMs = Math.max(
+ 0,
+ Math.floor(Math.min(admission.timeoutMs, maxTimeoutMs, remaining())),
+ );
+ // A deadline can pass between admission and this continuation. Release
+ // the long-poll slot before making the final non-polling request.
+ if (timeoutMs === 0) {
+ admission.release();
+ return immediate();
+ }
+ const target = new URL(url);
+ target.searchParams.set("timeout_ms", String(timeoutMs));
+ const started = performanceNow();
+ let outcome: LongpollResult["outcome"] = "error";
+ try {
+ const response = await http.fetch(target.href, options);
+ outcome = "success";
+ return response;
+ } finally {
+ const result: LongpollResult = {
+ url: target.href,
+ queueWaitMs: performanceDelta(queuedAt, started),
+ timeoutMs,
+ durationMs: performanceDelta(started, performanceNow()),
+ outcome: cancellation.isCancelled ? "cancelled" : outcome,
+ };
+ // Diagnostics must not replace a response or hide a transport failure.
+ try {
+ onLongpoll?.(result);
+ } catch (e) {
+ logger.warn(`long-poll observer failed: ${e}`);
+ }
+ }
+ } finally {
+ admission.release();
+ }
+}
diff --git a/packages/taler-util/src/notifications.ts b/packages/taler-util/src/notifications.ts
@@ -22,6 +22,7 @@
/**
* Imports.
*/
+import type { LongpollResult } from "./longpoll-http.js";
import { AbsoluteTime, TalerProtocolDuration } from "./time.js";
import { TransactionState } from "./types-taler-wallet-transactions.js";
import {
@@ -250,6 +251,7 @@ export interface RequestProgressPhaseNotification {
}
export enum ObservabilityEventType {
+ LongpollFinished = "longpoll-finished",
HttpFetchStart = "http-fetch-start",
HttpFetchFinishError = "http-fetch-finish-error",
HttpFetchFinishSuccess = "http-fetch-finish-success",
@@ -277,12 +279,15 @@ export enum ObservabilityEventType {
}
export type ObservabilityEvent =
+ | ({
+ type: ObservabilityEventType.LongpollFinished;
+ when: AbsoluteTime;
+ } & LongpollResult)
| {
id: string;
when: AbsoluteTime;
type: ObservabilityEventType.HttpFetchStart;
url: string;
- longPolling: boolean;
}
| {
id: string;
@@ -291,7 +296,6 @@ export type ObservabilityEvent =
url: string;
status: number;
durationMs: number;
- longPolling: boolean;
}
| {
id: string;
@@ -300,7 +304,6 @@ export type ObservabilityEvent =
url: string;
error: TalerErrorDetail;
durationMs: number;
- longPolling: boolean;
}
| {
type: ObservabilityEventType.DbQueryStart;
diff --git a/packages/taler-util/src/observability.test.ts b/packages/taler-util/src/observability.test.ts
@@ -53,28 +53,20 @@ test("ObservableHttpClientLibrary releases the caller's cancellation callback",
assert.strictEqual(callbacks().size, 0);
});
-test("ObservableHttpClientLibrary reports long polling consistently", async (t) => {
+test("HTTP observability reports transport events without scheduling metadata", async () => {
const events: any[] = [];
- const inner: HttpRequestLibrary = {
- fetch: async (url) => stubResponse(url),
- };
+ const inner: HttpRequestLibrary = { fetch: async (url) => stubResponse(url) };
const client = new ObservableHttpClientLibrary(inner, {
observe: (evt) => events.push(evt),
});
const source = CancellationToken.create();
-
const opts = { cancellationToken: source.token };
await client.fetch("http://example.com/", opts);
- await client.fetch("http://example.com/plain");
-
- // A request the caller supplied a cancellation token for is the long poll;
- // the start and the finish event of one request must agree.
- const [pollStart, pollEnd, plainStart, plainEnd] = events;
- assert.strictEqual(pollStart.longPolling, true);
- assert.strictEqual(pollEnd.longPolling, true);
- assert.strictEqual(plainStart.longPolling, false);
- assert.strictEqual(plainEnd.longPolling, false);
-
- // The caller's options object must not be rewritten.
+ assert.equal(events.length, 2);
+ for (const event of events) {
+ assert.equal("longPolling" in event, false);
+ assert.equal("queueWaitMs" in event, false);
+ assert.equal("longPollTimeoutMs" in event, false);
+ }
assert.strictEqual(opts.cancellationToken, source.token);
});
diff --git a/packages/taler-util/src/observability.ts b/packages/taler-util/src/observability.ts
@@ -57,9 +57,6 @@ export class ObservableHttpClientLibrary implements HttpRequestLibrary {
const cancelator = CancellationToken.create();
let unregisterCancel: (() => void) | undefined = undefined;
- // Long-polling requests are the ones the caller can cancel, so a
- // cancellation token is what distinguishes them here.
- const longPolling = !!opt?.cancellationToken;
if (opt?.cancellationToken) {
unregisterCancel = opt.cancellationToken.onCancelled(cancelator.cancel);
}
@@ -70,7 +67,6 @@ export class ObservableHttpClientLibrary implements HttpRequestLibrary {
when: AbsoluteTime.now(),
type: ObservabilityEventType.HttpFetchStart,
url: url,
- longPolling,
});
const optsWithCancel = { ...opt, cancellationToken: cancelator.token };
@@ -85,7 +81,6 @@ export class ObservableHttpClientLibrary implements HttpRequestLibrary {
url,
status: res.status,
durationMs: performanceDelta(start, end),
- longPolling,
};
this.oc.observe(event);
return res;
@@ -98,7 +93,6 @@ export class ObservableHttpClientLibrary implements HttpRequestLibrary {
url,
error: getErrorDetailFromException(e),
durationMs: performanceDelta(start, end),
- longPolling,
});
throw e;
} finally {
diff --git a/packages/taler-util/src/performance.ts b/packages/taler-util/src/performance.ts
@@ -86,9 +86,8 @@ export namespace PerformanceStat {
evt: ObservabilityEvent & { durationMs: number },
): PerformanceStat | undefined {
if (
- (evt.type === ObservabilityEventType.HttpFetchFinishSuccess ||
- evt.type === ObservabilityEventType.HttpFetchFinishError) &&
- !evt.longPolling
+ evt.type === ObservabilityEventType.HttpFetchFinishSuccess ||
+ evt.type === ObservabilityEventType.HttpFetchFinishError
) {
return {
type: PerformanceStatType.HttpFetch,