taler-typescript-core

Wallet core logic and WebUIs for various components
Log | Files | Refs | Submodules | README | LICENSE

commit ffaf4dbba034f2fef42aa048decf9d68a7372a4d
parent 2f657b0baa918a3cd31d735b2b2eae5a2d149282
Author: Florian Dold <dold@taler.net>
Date:   Tue, 17 Nov 2026 10:03:55 +0100

browser HTTP: preserve body timeouts and cancellation

Diffstat:
Apackages/taler-util/src/http-browser.test.ts | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Apackages/taler-util/src/http-browser.ts | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/taler-util/src/http-common.ts | 24+++++++++++++++++-------
Mpackages/taler-util/src/http.ts | 2++
Mpackages/taler-util/src/operation.ts | 2++
Mpackages/wallet-webui/src/platform/browser-http.ts | 70+++++++++++++---------------------------------------------------------
Mpackages/web-util/src/utils/http-impl.browser.ts | 88++-----------------------------------------------------------------------------
7 files changed, 261 insertions(+), 150 deletions(-)

diff --git a/packages/taler-util/src/http-browser.test.ts b/packages/taler-util/src/http-browser.test.ts @@ -0,0 +1,120 @@ +/* + 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, type TestContext } from "node:test"; +import { browserRawHttp } from "./http-browser.js"; +import { HttpLib } from "./http-common.js"; +import { CancellationToken } from "./CancellationToken.js"; +import { TalerErrorCode } from "./taler-error-codes.js"; + +function fixture(t: TestContext) { + let finish!: () => void; + let reads = 0; + let aborted = false; + t.mock.method(globalThis, "fetch", async (_url: string, options: any) => { + const body = new Promise<ArrayBuffer>((resolve, reject) => { + finish = () => resolve(new TextEncoder().encode('{"ok":true}').buffer); + options.signal.addEventListener("abort", () => { + aborted = true; + reject(new Error("aborted")); + }); + }); + return { + status: 200, + headers: { forEach() {} }, + arrayBuffer() { + reads++; + return body; + }, + }; + }); + return { + http: new HttpLib(browserRawHttp), + finish: () => finish(), + reads: () => reads, + aborted: () => aborted, + }; +} + +test("headers return before body, with one shared body read", async (t) => { + const f = fixture(t); + const response = await f.http.fetch("https://example.com/"); + assert.equal(response.status, 200); + const json = response.json(), + text = response.text(); + f.finish(); + assert.deepEqual(await json, { ok: true }); + assert.equal(await text, '{"ok":true}'); + assert.equal(f.reads(), 1); + response.dispose?.(); + assert.equal(f.aborted(), false); +}); + +test("body timeout retains the wallet timeout code, including delayed reads", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 1000 }); + const f = fixture(t); + const response = await f.http.fetch("https://example.com/", { + timeout: { d_ms: 100 }, + }); + t.mock.timers.tick(101); + await assert.rejects( + response.json(), + (e: any) => + e.errorDetail.code === TalerErrorCode.WALLET_HTTP_REQUEST_GENERIC_TIMEOUT, + ); + assert.equal(f.aborted(), true); +}); + +test("cancellation after headers still aborts an unlimited response", async (t) => { + const f = fixture(t), + cts = CancellationToken.create(); + const response = await f.http.fetch("https://example.com/", { + timeout: { d_ms: "forever" }, + cancellationToken: cts.token, + }); + cts.cancel(); + await assert.rejects( + response.bytes(), + (e: any) => + e.errorDetail.code === TalerErrorCode.WALLET_CORE_REQUEST_CANCELLED, + ); +}); + +test("disposing an unread unlimited body aborts it without unhandled rejections", async (t) => { + const f = fixture(t); + const response = await f.http.fetch("https://example.com/", { + timeout: { d_ms: "forever" }, + }); + response.dispose?.(); + response.dispose?.(); + assert.equal(f.aborted(), true); + await new Promise((resolve) => setImmediate(resolve)); +}); + +test("wall clock deadline is checked even before the timeout callback runs", async (t) => { + t.mock.timers.enable({ apis: ["Date"], now: 1000 }); + const f = fixture(t); + const response = await f.http.fetch("https://example.com/", { + timeout: { d_ms: 1000 }, + }); + t.mock.timers.setTime(3000); + f.finish(); + await assert.rejects( + response.bytes(), + (e: any) => + e.errorDetail.code === TalerErrorCode.WALLET_HTTP_REQUEST_GENERIC_TIMEOUT, + ); +}); diff --git a/packages/taler-util/src/http-browser.ts b/packages/taler-util/src/http-browser.ts @@ -0,0 +1,105 @@ +/* + This file is part of GNU Taler + (C) 2022-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 { + HeadersImpl, + type HttpRawLib, + RequestCancelledError, + RequestTimeoutError, +} from "./http-common.js"; + +/** Fetch resolves at headers; ownership of cancellation lasts through the body. */ +export const browserRawHttp: HttpRawLib = { + async fetch(url, options) { + const controller = new AbortController(); + const deadline = + options.timeoutMs === undefined + ? undefined + : Date.now() + options.timeoutMs; + let failure: Error | undefined; + let finished = false; + let timeout: ReturnType<typeof setTimeout> | undefined; + let unregister: (() => void) | undefined; + const cleanup = () => { + if (timeout !== undefined) clearTimeout(timeout); + unregister?.(); + unregister = undefined; + }; + const abort = (error: Error) => { + if (finished || failure) return; + failure = error; + controller.abort(); + cleanup(); + }; + const check = () => { + if (!finished && deadline !== undefined && Date.now() >= deadline) + abort(new RequestTimeoutError()); + if (failure) throw failure; + }; + if (options.timeoutMs !== undefined) + timeout = setTimeout( + () => abort(new RequestTimeoutError()), + options.timeoutMs, + ); + unregister = options.cancellationToken?.onCancelled(() => + abort(new RequestCancelledError()), + ); + if (failure) cleanup(); + try { + check(); + const response = (await globalThis.fetch(url, { + method: options.method, + headers: options.headers, + body: options.body == null ? undefined : new Uint8Array(options.body), + redirect: options.redirect, + signal: controller.signal, + })) as unknown as { + status: number; + headers: { forEach(f: (value: string, key: string) => void): void }; + arrayBuffer(): Promise<ArrayBuffer>; + }; + check(); + const headers = new HeadersImpl(); + response.headers.forEach((value, key) => headers.set(key, value)); + // Drain in the background, retaining headers-first behavior. This also + // releases resources when callers inspect only status on a finite body. + const body = (async () => { + try { + const bytes = new Uint8Array(await response.arrayBuffer()); + check(); + return bytes; + } catch (error) { + throw failure ?? error; + } finally { + finished = true; + cleanup(); + } + })(); + // A caller may deliberately ignore the body or read it much later. + void body.catch(() => {}); + return { + status: response.status, + headers, + bytes: () => body, + dispose: () => abort(new RequestCancelledError()), + }; + } catch (error) { + cleanup(); + controller.abort(); + throw failure ?? error; + } + }, +}; diff --git a/packages/taler-util/src/http-common.ts b/packages/taler-util/src/http-common.ts @@ -43,6 +43,8 @@ export interface HttpResponse { json(): Promise<any>; text(): Promise<string>; bytes(): Promise<Uint8Array>; + /** Release an unread response body. Idempotent. */ + dispose?(): void; } export const DEFAULT_REQUEST_TIMEOUT_MS = 60000; @@ -527,6 +529,8 @@ export interface HttpRawResponse { status: number; headers: Headers; bytes(): Promise<Uint8Array>; + /** Release an unread response body. Idempotent. */ + dispose?(): void; } /** @@ -732,13 +736,17 @@ export class HttpLib implements HttpRequestLibrary { // The response body gets read more than once in a few places (an error // path that reports the raw text after JSON parsing failed, for one), so // the bytes are pulled from the platform exactly once and kept. - let cachedBytes: Uint8Array | undefined; - const readBytes = async (): Promise<Uint8Array> => { - if (cachedBytes === undefined) { - cachedBytes = await resp.bytes(); - } - return cachedBytes; - }; + let cachedBytes: Promise<Uint8Array> | undefined; + const readBytes = (): Promise<Uint8Array> => + (cachedBytes ??= resp.bytes().catch((cause) => { + throw this.mapRequestError( + cause, + rid, + requestUrl, + requestMethod, + timeoutMs, + ); + })); const decodeText = async (): Promise<string> => { const bytes = await readBytes(); @@ -800,6 +808,7 @@ export class HttpLib implements HttpRequestLibrary { bytes: readBytes, text: readText, json: readJson, + dispose: () => resp.dispose?.(), }; } @@ -842,6 +851,7 @@ export class HttpLib implements HttpRequestLibrary { ) { return response; } + response.dispose?.(); if (redirects >= 21) throw Error("too many HTTP redirects"); const next = new URL(location, url); // URL credentials must not silently become credentials for a new host. diff --git a/packages/taler-util/src/http.ts b/packages/taler-util/src/http.ts @@ -35,3 +35,5 @@ export function createPlatformHttpLib( ): common.HttpRequestLibrary { return new common.HttpLib(impl.rawLib, args); } + +export { browserRawHttp } from "./http-browser.js"; diff --git a/packages/taler-util/src/operation.ts b/packages/taler-util/src/operation.ts @@ -112,10 +112,12 @@ export async function opSuccessFromHttp<T>( * to the client. */ export function opFixedSuccess<T>(resp: HttpResponse, body: T): OperationOk<T> { + resp.dispose?.(); return { type: "ok" as const, response: resp, case: "ok", body }; } export function opEmptySuccess(resp: HttpResponse): OperationOk<undefined> { + resp.dispose?.(); return { type: "ok" as const, response: resp, case: "ok", body: undefined }; } diff --git a/packages/wallet-webui/src/platform/browser-http.ts b/packages/wallet-webui/src/platform/browser-http.ts @@ -1,68 +1,24 @@ -import { - HeadersImpl, - HttpLib, - type HttpRawLib, - type HttpRawRequestOptions, - type HttpRawResponse, - RequestCancelledError, - RequestTimeoutError, -} from "@gnu-taler/taler-util/http"; +import { HttpLib, browserRawHttp } from "@gnu-taler/taler-util/http"; -const browserRawHttp: HttpRawLib = { - async fetch( - url: string, - options: HttpRawRequestOptions, - ): Promise<HttpRawResponse> { - const controller = new AbortController(); - let timedOut = false; - let cancelled = false; - let timeout: ReturnType<typeof setTimeout> | undefined; - const unregister = options.cancellationToken?.onCancelled(() => { - cancelled = true; - controller.abort(); - }); - if (options.timeoutMs !== undefined) { - timeout = setTimeout(() => { - timedOut = true; - controller.abort(); - }, options.timeoutMs); - } - try { - const response = await fetch(url, { - method: options.method, - headers: options.headers, - body: options.body == null ? undefined : new Uint8Array(options.body), - redirect: options.redirect, - signal: controller.signal, - }); - const headers = new HeadersImpl(); - response.headers.forEach((value, key) => headers.set(key, value)); - return { - status: response.status, - headers, - bytes: async () => new Uint8Array(await response.arrayBuffer()), - }; - } catch (error) { - if (timedOut) throw new RequestTimeoutError(); - if (cancelled) throw new RequestCancelledError(); - throw error; - } finally { - if (timeout !== undefined) clearTimeout(timeout); - unregister?.(); - } - }, - async compress(algorithm, bytes) { +const browserRawHttpWithCompression = { + ...browserRawHttp, + async compress(algorithm: "gzip" | "deflate" | undefined, bytes: Uint8Array) { if (!algorithm) return bytes; const stream = new CompressionStream(algorithm); const writer = stream.writable.getWriter(); - await writer.write(new Uint8Array(bytes)); - await writer.close(); - return new Uint8Array(await new Response(stream.readable).arrayBuffer()); + const writing = writer.write(new Uint8Array(bytes)); + const closing = writer.close(); + const result = new Uint8Array( + await new Response(stream.readable).arrayBuffer(), + ); + await writing; + await closing; + return result; }, }; export class BrowserHttpLibrary extends HttpLib { constructor() { - super(browserRawHttp); + super(browserRawHttpWithCompression); } } diff --git a/packages/web-util/src/utils/http-impl.browser.ts b/packages/web-util/src/utils/http-impl.browser.ts @@ -17,93 +17,9 @@ /** * Imports. */ -import { - HeadersImpl, - HttpRawLib, - HttpRawRequestOptions, - HttpRawResponse, - RequestCancelledError, - RequestTimeoutError, -} from "@gnu-taler/taler-util/http"; +import { browserRawHttp, type HttpRawLib } from "@gnu-taler/taler-util/http"; -/** - * Implementation of the raw HTTP layer for the browser, using the fetch API. - */ -export const browserRawLib: HttpRawLib = { - compress, - - async fetch( - url: string, - opt: HttpRawRequestOptions, - ): Promise<HttpRawResponse> { - const controller = new AbortController(); - let timedOut = false; - let cancelled = false; - let timeoutId: ReturnType<typeof setTimeout> | undefined; - let unregisterCancel: (() => void) | undefined; - - const cleanup = (): void => { - if (timeoutId !== undefined) { - clearTimeout(timeoutId); - timeoutId = undefined; - } - if (unregisterCancel !== undefined) { - unregisterCancel(); - unregisterCancel = undefined; - } - }; - - if (opt.timeoutMs !== undefined) { - timeoutId = setTimeout(() => { - timedOut = true; - controller.abort(); - }, opt.timeoutMs); - } - if (opt.cancellationToken) { - unregisterCancel = opt.cancellationToken.onCancelled(() => { - cancelled = true; - controller.abort(); - }); - } - - let response: Response; - try { - response = await globalThis.fetch(url, { - headers: opt.headers, - body: opt.body != null ? new Uint8Array(opt.body) : undefined, - method: opt.method, - signal: controller.signal, - redirect: opt.redirect, - }); - } catch (e) { - // The abort reason is tracked separately: an AbortError does not say - // whether we timed out or the caller cancelled. - if (timedOut) { - throw new RequestTimeoutError(); - } - if (cancelled) { - throw new RequestCancelledError(); - } - throw e; - } finally { - cleanup(); - } - - const headers = new HeadersImpl(); - response.headers.forEach((value, key) => { - headers.set(key, value); - }); - - return { - status: response.status, - headers, - async bytes() { - const buf = await response.arrayBuffer(); - return new Uint8Array(buf); - }, - }; - }, -}; +export const browserRawLib: HttpRawLib = { ...browserRawHttp, compress }; export async function compress( alg: "gzip" | "deflate" | undefined,