commit ab5a6551dcffcb0923a5b294c655d014a696b3a4
parent 23e2873dcbd48f34816fb7f7b9effdd6fbeda9db
Author: Florian Dold <dold@taler.net>
Date: Sun, 8 Nov 2026 20:22:10 +0100
taler-util: limit long polls to 3 per host and 20 overall
Shorten timeouts as host demand grows. Remove queued requests when
cancelled or past their deadline.
Diffstat:
2 files changed, 371 insertions(+), 55 deletions(-)
diff --git a/packages/taler-util/src/longpoll-queue.test.ts b/packages/taler-util/src/longpoll-queue.test.ts
@@ -0,0 +1,234 @@
+/*
+ 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 { LongpollQueue } from "./longpoll-queue.js";
+import { openPromise } from "./promises.js";
+
+const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
+
+function poll(
+ queue: LongpollQueue,
+ host = "a.example",
+ token = CancellationToken.CONTINUE,
+) {
+ const started = openPromise<number>();
+ const finish = openPromise<void>();
+ let calls = 0;
+ const done = queue.run(
+ new URL(host.includes("://") ? host : "https://" + host + "/"),
+ token,
+ (timeout) => {
+ calls++;
+ started.resolve(timeout);
+ return finish.promise;
+ },
+ );
+ return { started: started.promise, finish, done, calls: () => calls };
+}
+
+test("three polls per hostname, FIFO, and no blocking of other hosts", async () => {
+ const queue = new LongpollQueue();
+ const active = [
+ poll(queue, "https://a.example/one"),
+ poll(queue, "http://a.example:8080/two"),
+ poll(queue, "https://A.EXAMPLE:444/three"),
+ ];
+ await Promise.all(active.map((p) => p.started));
+ const fourth = poll(queue);
+ const fifth = poll(queue);
+ const other = poll(queue, "b.example");
+ assert.equal(await other.started, 30000);
+ assert.equal(fourth.calls(), 0);
+ assert.equal(fifth.calls(), 0);
+ active[0].finish.resolve();
+ await fourth.started;
+ assert.equal(fifth.calls(), 0);
+ active[1].finish.resolve();
+ await fifth.started;
+ for (const p of [...active, fourth, fifth, other]) p.finish.resolve();
+ await Promise.all([...active, fourth, fifth, other].map((p) => p.done));
+});
+
+test("twenty overall, oldest eligible request gets released capacity", async () => {
+ const queue = new LongpollQueue();
+ const active = Array.from({ length: 20 }, (_, i) =>
+ poll(queue, "host" + Math.floor(i / 3) + ".example"),
+ );
+ await Promise.all(active.map((p) => p.started));
+ const blocked = poll(queue, "host0.example");
+ const eligible = poll(queue, "new.example");
+ const newer = poll(queue, "newer.example");
+ await tick();
+ assert.equal(eligible.calls(), 0);
+ active[19].finish.resolve();
+ await eligible.started;
+ assert.equal(blocked.calls(), 0);
+ assert.equal(newer.calls(), 0);
+ active[0].finish.resolve();
+ await blocked.started;
+ assert.equal(newer.calls(), 0);
+ active[1].finish.resolve();
+ await newer.started;
+ const all = [...active, blocked, eligible, newer];
+ for (const p of all) p.finish.resolve();
+ await Promise.all(all.map((p) => p.done));
+});
+
+test("timeouts reflect host demand and recover when demand clears", async () => {
+ const queue = new LongpollQueue();
+ const first = poll(queue);
+ assert.equal(await first.started, 30000);
+ const second = poll(queue);
+ assert.equal(await second.started, 15000);
+ const third = poll(queue);
+ assert.equal(await third.started, 10000);
+ const waiting = poll(queue);
+ const other = poll(queue, "b.example");
+ assert.equal(await other.started, 30000);
+ first.finish.resolve();
+ assert.equal(await waiting.started, 10000);
+ const all = [first, second, third, waiting, other];
+ for (const p of all) p.finish.resolve();
+ await Promise.all(all.map((p) => p.done));
+ const fresh = poll(queue);
+ assert.equal(await fresh.started, 30000);
+ fresh.finish.resolve();
+ await fresh.done;
+});
+
+test("queued demand counts when starting after global saturation", async () => {
+ const queue = new LongpollQueue();
+ const active = Array.from({ length: 20 }, (_, i) =>
+ poll(queue, "host" + i + ".example"),
+ );
+ await Promise.all(active.map((p) => p.started));
+ const first = poll(queue, "waiting.example");
+ const second = poll(queue, "waiting.example");
+ active[0].finish.resolve();
+ assert.equal(await first.started, 15000);
+ assert.equal(second.calls(), 0);
+ second.finish.resolve();
+ for (const p of active) p.finish.resolve();
+ first.finish.resolve();
+ await Promise.all([...active, first, second].map((p) => p.done));
+});
+
+test("cancelled queued and admitted polls never execute or leak capacity", async () => {
+ const queue = new LongpollQueue();
+ const cancelled = poll(queue, "a.example", CancellationToken.CANCELLED);
+ await assert.rejects(cancelled.done, CancellationToken.CancellationError);
+ assert.equal(cancelled.calls(), 0);
+
+ const source = CancellationToken.create();
+ const admitted = poll(queue, "a.example", source.token);
+ const rejected = assert.rejects(
+ admitted.done,
+ CancellationToken.CancellationError,
+ );
+ source.cancel();
+ await rejected;
+ assert.equal(admitted.calls(), 0);
+
+ const active = Array.from({ length: 3 }, () => poll(queue));
+ await Promise.all(active.map((p) => p.started));
+ const queuedSource = CancellationToken.create();
+ const queued = poll(queue, "a.example", queuedSource.token);
+ const queuedRejected = assert.rejects(
+ queued.done,
+ CancellationToken.CancellationError,
+ );
+ const next = poll(queue);
+ queuedSource.cancel();
+ await queuedRejected;
+ active[0].finish.resolve();
+ await next.started;
+ assert.equal(queued.calls(), 0);
+ for (const p of [...active, next]) p.finish.resolve();
+ await Promise.all([...active, next].map((p) => p.done));
+});
+
+test("cancellation during handoff releases both permits", async () => {
+ const queue = new LongpollQueue();
+ const active = Array.from({ length: 3 }, () => poll(queue));
+ await Promise.all(active.map((p) => p.started));
+ const source = CancellationToken.create();
+ const waiting = poll(queue, "a.example", source.token);
+ const rejected = assert.rejects(
+ waiting.done,
+ CancellationToken.CancellationError,
+ );
+ const next = poll(queue);
+ active[0].finish.resolve();
+ // The running callback's continuation admits waiting before this microtask;
+ // waiting's continuation must still check cancellation before executing.
+ queueMicrotask(() => source.cancel());
+ await rejected;
+ await next.started;
+ assert.equal(waiting.calls(), 0);
+ for (const p of [...active, next]) p.finish.resolve();
+ await Promise.all([...active, next].map((p) => p.done));
+});
+
+test("running cancellation retains capacity until the callback settles", async () => {
+ const queue = new LongpollQueue();
+ const source = CancellationToken.create();
+ const running = poll(queue, "a.example", source.token);
+ const others = [poll(queue), poll(queue)];
+ await Promise.all([running, ...others].map((p) => p.started));
+ const next = poll(queue);
+ source.cancel();
+ await tick();
+ assert.equal(next.calls(), 0);
+ running.finish.resolve();
+ await next.started;
+ for (const p of [...others, next]) p.finish.resolve();
+ await Promise.all([running, ...others, next].map((p) => p.done));
+});
+
+test("callback throws and rejections release permits and preserve results", async () => {
+ const queue = new LongpollQueue();
+ const error = new Error("request failed");
+ for (let i = 0; i < 25; i++) {
+ await assert.rejects(
+ queue.run(
+ new URL("https://a.example"),
+ CancellationToken.CONTINUE,
+ () => {
+ if (i % 2) throw error;
+ return Promise.reject(error);
+ },
+ ),
+ (e) => e === error,
+ );
+ }
+ const active = Array.from({ length: 20 }, (_, i) =>
+ poll(queue, "host" + Math.floor(i / 3) + ".example"),
+ );
+ await Promise.all(active.map((p) => p.started));
+ for (const p of active) p.finish.resolve();
+ await Promise.all(active.map((p) => p.done));
+ assert.equal(
+ await queue.run(
+ new URL("https://a.example"),
+ CancellationToken.CONTINUE,
+ async () => 42,
+ ),
+ 42,
+ );
+});
diff --git a/packages/taler-util/src/longpoll-queue.ts b/packages/taler-util/src/longpoll-queue.ts
@@ -18,80 +18,162 @@
import { CancellationToken } from "./CancellationToken.js";
import { Logger } from "./logging.js";
+import { AbsoluteTime, Duration } from "./time.js";
+import { performanceNow, performanceDelta } from "./timer.js";
import { openPromise } from "./promises.js";
const logger = new Logger("longpoll-queue.ts");
-const PERMITS: number = 20;
+const MAX_ACTIVE = 20;
+const MAX_ACTIVE_PER_HOST = 3;
type LongpollRunFn<T> = (timeoutMs: number) => Promise<T>;
+export type LongpollAdmission =
+ | { status: "deadline-expired" }
+ | { status: "admitted"; timeoutMs: number; release: () => void };
+
+interface QueueEntry {
+ hostname: string;
+ admit: () => void;
+}
+
+/**
+ * Bound long polls independently of the transport's request limits, leaving
+ * room for ordinary requests even on transports with small per-host pools.
+ */
export class LongpollQueue {
- private idCounter: number = 0;
- private queue: (() => void)[] = [];
- private permits: number = PERMITS;
+ private idCounter = 0;
+ private queue: QueueEntry[] = [];
+ private active = 0;
+ private activeByHost = new Map<string, number>();
- async run<T>(
+ private drain(): void {
+ let idx = 0;
+ // Scan in queue order, skipping hosts at capacity. Admission cannot free
+ // capacity, so earlier blocked hosts need not be reconsidered in this pass.
+ while (this.active < MAX_ACTIVE && idx < this.queue.length) {
+ const entry = this.queue[idx];
+ const nextActiveForHost =
+ (this.activeByHost.get(entry.hostname) ?? 0) + 1;
+ if (nextActiveForHost > MAX_ACTIVE_PER_HOST) {
+ idx++;
+ continue;
+ }
+ // The next entry moves into this index when we remove the admitted one.
+ this.queue.splice(idx, 1);
+ this.active++;
+ this.activeByHost.set(entry.hostname, nextActiveForHost);
+ entry.admit();
+ }
+ }
+
+ /**
+ * Wait for capacity, or return when the caller's deadline expires.
+ * The caller must release an admitted permit in a finally block.
+ */
+ async acquire(
url: URL,
cancellationToken: CancellationToken,
- f: LongpollRunFn<T>,
- ): Promise<T> {
+ deadline?: AbsoluteTime,
+ ): Promise<LongpollAdmission> {
+ cancellationToken.throwIfCancelled();
+ if (deadline && AbsoluteTime.isExpired(deadline)) {
+ return { status: "deadline-expired" };
+ }
const hostname = url.hostname;
const rid = this.idCounter++;
-
- const triggerNextLongpoll = () => {
- logger.trace(`cleaning up after long-poll ${rid} to ${hostname}`);
- // Run pending task
- const next = this.queue.shift();
- if (next != null) {
- next();
+ const queuedAt = performanceNow();
+ const admission = openPromise<"admitted" | "deadline-expired">();
+ let admitted = false;
+ let released = false;
+ const release = () => {
+ if (released) return;
+ released = true;
+ this.active--;
+ const remaining = this.activeByHost.get(hostname)! - 1;
+ if (remaining === 0) this.activeByHost.delete(hostname);
+ else this.activeByHost.set(hostname, remaining);
+ this.drain();
+ };
+ const entry: QueueEntry = {
+ hostname,
+ admit: () => {
+ admitted = true;
+ admission.resolve("admitted");
+ },
+ };
+ // Only a waiting entry can be removed. After admission the caller owns
+ // the permit, even if cancellation or the deadline races with resumption.
+ const removeWaiter = () => {
+ const idx = this.queue.indexOf(entry);
+ if (idx < 0) return false;
+ this.queue.splice(idx, 1);
+ this.drain();
+ return true;
+ };
+ this.queue.push(entry);
+ const unregister = cancellationToken.onCancelled(() => {
+ if (removeWaiter()) {
+ admission.reject(
+ new CancellationToken.CancellationError(cancellationToken.reason),
+ );
+ }
+ });
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const checkDeadline = () => {
+ if (admitted || !deadline || AbsoluteTime.isNever(deadline)) return;
+ const remaining = Duration.toMilliseconds(
+ AbsoluteTime.remaining(deadline),
+ );
+ if (remaining <= 0) {
+ if (removeWaiter()) admission.resolve("deadline-expired");
} else {
- // Else release permit
- this.permits++;
+ // Long deadlines must not overflow the platform's timer range.
+ timer = setTimeout(checkDeadline, Math.min(remaining, 0x7fffffff));
}
};
-
- const doRunLongpoll: () => Promise<T> = async () => {
- const numWaiting = this.queue.length;
- const numConcurrent = PERMITS - this.permits;
+ try {
+ checkDeadline();
+ this.drain();
+ const status = await admission.promise;
+ cancellationToken.throwIfCancelled();
+ if (status === "deadline-expired") return { status };
+ const demand =
+ this.activeByHost.get(hostname)! +
+ this.queue.filter((pending) => pending.hostname === hostname).length;
+ const timeoutMs = Math.round(Math.max(10000, 30000 / demand));
logger.info(
- `running long-poll ${rid} to ${hostname} with ${numWaiting} waiting and ${numConcurrent} running`,
+ `running long-poll ${rid} to ${hostname}, timeout ${timeoutMs}ms`,
);
- try {
- const timeoutMs = Math.round(Math.max(10000, 30000 / (numWaiting + 1)));
- return await f(timeoutMs);
- } finally {
- triggerNextLongpoll();
+ return { status: "admitted", timeoutMs, release };
+ } catch (e) {
+ if (admitted) release();
+ throw e;
+ } finally {
+ clearTimeout(timer);
+ unregister();
+ if (!admitted) {
+ logger.info(
+ `long-poll ${rid} to ${hostname} left queue after ${performanceDelta(queuedAt, performanceNow())}ms (${cancellationToken.isCancelled ? "cancelled" : "deadline expired"})`,
+ );
}
- };
+ }
+ }
- if (this.permits > 0) {
- this.permits--;
- return doRunLongpoll();
- } else {
- logger.info(`long-poll ${rid} to ${hostname} queued`);
- const promcap = openPromise<void>();
- const entry = promcap.resolve;
- this.queue.push(entry);
- try {
- await cancellationToken.racePromise(promcap.promise);
- } catch (e) {
- // The wait was interrupted (cancelled/errored) rather than woken
- // normally. If our entry is still queued we were never handed a
- // slot, so just remove ourselves without releasing a permit. If it
- // was already dequeued (a departing task handed us a slot before the
- // cancellation won the race), release that slot so it isn't leaked.
- const idx = this.queue.indexOf(entry);
- if (idx >= 0) {
- this.queue.splice(idx, 1);
- } else {
- triggerNextLongpoll();
- }
- logger.info(`long-poll ${rid} to ${hostname} cancelled while queued`);
- throw e;
- }
- // Woken normally: a departing task dequeued our entry and handed its
- // slot to us. doRunLongpoll() is the sole releaser of that slot.
- return doRunLongpoll();
+ /** Run a callback while holding a long-poll permit. */
+ async run<T>(
+ url: URL,
+ cancellationToken: CancellationToken,
+ f: LongpollRunFn<T>,
+ ): Promise<T> {
+ const admission = await this.acquire(url, cancellationToken);
+ if (admission.status !== "admitted")
+ throw Error("unexpected queue deadline");
+ try {
+ cancellationToken.throwIfCancelled();
+ return await f(admission.timeoutMs);
+ } finally {
+ admission.release();
}
}
}