handler request timeout

This commit is contained in:
Sebastian 2022-12-20 13:44:42 -03:00
parent 15d76cf77c
commit 46607dc260
No known key found for this signature in database
GPG Key ID: BE4FF68352439FC1

View File

@ -17,7 +17,11 @@
/** /**
* Imports. * Imports.
*/ */
import { RequestThrottler, TalerErrorCode } from "@gnu-taler/taler-util"; import {
Logger,
RequestThrottler,
TalerErrorCode,
} from "@gnu-taler/taler-util";
import { import {
Headers, Headers,
HttpRequestLibrary, HttpRequestLibrary,
@ -41,6 +45,7 @@ export class ServiceWorkerHttpLib implements HttpRequestLibrary {
const requestMethod = options?.method ?? "GET"; const requestMethod = options?.method ?? "GET";
const requestBody = options?.body; const requestBody = options?.body;
const requestHeader = options?.headers; const requestHeader = options?.headers;
const requestTimeout = options?.timeout ?? { d_ms: 2 * 1000 };
if (this.throttlingEnabled && this.throttle.applyThrottle(requestUrl)) { if (this.throttlingEnabled && this.throttle.applyThrottle(requestUrl)) {
const parsedUrl = new URL(requestUrl); const parsedUrl = new URL(requestUrl);
@ -70,13 +75,26 @@ export class ServiceWorkerHttpLib implements HttpRequestLibrary {
} }
} }
const controller = new AbortController();
let timeoutId: any | undefined;
if (requestTimeout.d_ms !== "forever") {
timeoutId = setTimeout(() => {
controller.abort(TalerErrorCode.WALLET_HTTP_REQUEST_GENERIC_TIMEOUT);
}, requestTimeout.d_ms);
}
try {
const response = await fetch(requestUrl, { const response = await fetch(requestUrl, {
headers: requestHeader, headers: requestHeader,
body: myBody, body: myBody,
method: requestMethod, method: requestMethod,
// timeout: options?.timeout signal: controller.signal,
}); });
if (timeoutId) {
clearTimeout(timeoutId);
}
const headerMap = new Headers(); const headerMap = new Headers();
response.headers.forEach((value, key) => { response.headers.forEach((value, key) => {
headerMap.set(key, value); headerMap.set(key, value);
@ -90,6 +108,16 @@ export class ServiceWorkerHttpLib implements HttpRequestLibrary {
text: makeTextHandler(response, requestUrl), text: makeTextHandler(response, requestUrl),
bytes: async () => (await response.blob()).arrayBuffer(), bytes: async () => (await response.blob()).arrayBuffer(),
}; };
} catch (e) {
if (controller.signal) {
throw TalerError.fromDetail(
controller.signal.reason,
{},
`request to ${requestUrl} timed out`,
);
}
throw e;
}
} }
get(url: string, opt?: HttpRequestOptions): Promise<HttpResponse> { get(url: string, opt?: HttpRequestOptions): Promise<HttpResponse> {