wallet-core/packages/taler-wallet-core/src/headless/NodeHttpLib.ts

184 lines
5.2 KiB
TypeScript
Raw Normal View History

2019-12-15 17:48:22 +01:00
/*
This file is part of GNU Taler
(C) 2019 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/>
SPDX-License-Identifier: AGPL3.0-or-later
*/
2020-04-07 10:28:55 +02:00
/**
* Imports.
*/
2020-03-30 12:39:32 +02:00
import {
DEFAULT_REQUEST_TIMEOUT_MS,
2020-03-30 12:39:32 +02:00
Headers,
HttpRequestLibrary,
HttpRequestOptions,
HttpResponse,
} from "../util/http.js";
import { RequestThrottler } from "@gnu-taler/taler-util";
2020-09-06 15:02:05 +02:00
import Axios, { AxiosResponse } from "axios";
import { TalerError } from "../errors.js";
import { Logger, bytesToString } from "@gnu-taler/taler-util";
import { TalerErrorCode, URL } from "@gnu-taler/taler-util";
const logger = new Logger("NodeHttpLib.ts");
2019-12-15 17:48:22 +01:00
/**
* Implementation of the HTTP request library interface for node.
*/
export class NodeHttpLib implements HttpRequestLibrary {
private throttle = new RequestThrottler();
private throttlingEnabled = true;
/**
* Set whether requests should be throttled.
*/
2020-04-07 10:28:55 +02:00
setThrottling(enabled: boolean): void {
2019-12-15 17:48:22 +01:00
this.throttlingEnabled = enabled;
}
2020-12-02 14:55:04 +01:00
async fetch(url: string, opt?: HttpRequestOptions): Promise<HttpResponse> {
const method = opt?.method ?? "GET";
let body = opt?.body;
2021-08-12 21:01:40 +02:00
logger.trace(`Requesting ${method} ${url}`);
const parsedUrl = new URL(url);
2019-12-15 17:48:22 +01:00
if (this.throttlingEnabled && this.throttle.applyThrottle(url)) {
throw TalerError.fromDetail(
TalerErrorCode.WALLET_HTTP_REQUEST_THROTTLED,
{
requestMethod: method,
requestUrl: url,
throttleStats: this.throttle.getThrottleStats(url),
2020-09-01 15:37:14 +02:00
},
`request to origin ${parsedUrl.origin} was throttled`,
2020-09-01 15:37:14 +02:00
);
}
let timeoutMs: number | undefined;
if (typeof opt?.timeout?.d_ms === "number") {
timeoutMs = opt.timeout.d_ms;
} else {
timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS;
2019-12-15 17:48:22 +01:00
}
// FIXME: Use AbortController / etc. to handle cancellation
2020-09-06 15:02:05 +02:00
let resp: AxiosResponse;
try {
let respPromise = Axios({
2020-09-06 15:02:05 +02:00
method,
url: url,
2020-12-02 14:55:04 +01:00
responseType: "arraybuffer",
2020-09-06 15:02:05 +02:00
headers: opt?.headers,
validateStatus: () => true,
transformResponse: (x) => x,
data: body,
timeout: timeoutMs,
2021-08-12 21:01:40 +02:00
maxRedirects: 0,
2020-09-06 15:02:05 +02:00
});
if (opt?.cancellationToken) {
respPromise = opt.cancellationToken.racePromise(respPromise);
}
resp = await respPromise;
} catch (e: any) {
throw TalerError.fromDetail(
2020-09-06 15:02:05 +02:00
TalerErrorCode.WALLET_NETWORK_ERROR,
{
requestUrl: url,
requestMethod: method,
},
`${e.message}`,
2020-09-06 15:02:05 +02:00
);
}
2020-04-07 10:28:55 +02:00
2020-12-14 16:45:15 +01:00
const makeText = async (): Promise<string> => {
opt?.cancellationToken?.throwIfCancelled();
2020-12-02 14:55:04 +01:00
const respText = new Uint8Array(resp.data);
return bytesToString(respText);
2020-12-14 16:45:15 +01:00
};
2020-12-02 14:55:04 +01:00
2020-04-07 10:28:55 +02:00
const makeJson = async (): Promise<any> => {
opt?.cancellationToken?.throwIfCancelled();
2019-12-15 17:48:22 +01:00
let responseJson;
2020-12-02 14:55:04 +01:00
const respText = await makeText();
2019-12-15 17:48:22 +01:00
try {
responseJson = JSON.parse(respText);
} catch (e) {
2020-12-02 14:55:04 +01:00
logger.trace(`invalid json: '${resp.data}'`);
throw TalerError.fromDetail(
TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE,
{
httpStatusCode: resp.status,
requestUrl: url,
requestMethod: method,
},
"Could not parse response body as JSON",
);
2019-12-15 17:48:22 +01:00
}
if (responseJson === null || typeof responseJson !== "object") {
logger.trace(`invalid json (not an object): '${respText}'`);
throw TalerError.fromDetail(
TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE,
{
httpStatusCode: resp.status,
requestUrl: url,
requestMethod: method,
},
`invalid JSON`,
);
2019-12-15 17:48:22 +01:00
}
return responseJson;
};
2020-12-02 14:55:04 +01:00
const makeBytes = async () => {
opt?.cancellationToken?.throwIfCancelled();
2021-01-07 19:50:53 +01:00
if (typeof resp.data.byteLength !== "number") {
2020-12-02 14:55:04 +01:00
throw Error("expected array buffer");
}
const buf = resp.data;
return buf;
};
2019-12-15 17:48:22 +01:00
const headers = new Headers();
for (const hn of Object.keys(resp.headers)) {
headers.set(hn, resp.headers[hn]);
}
return {
requestUrl: url,
requestMethod: method,
2019-12-15 17:48:22 +01:00
headers,
status: resp.status,
2020-12-02 14:55:04 +01:00
text: makeText,
2019-12-15 17:48:22 +01:00
json: makeJson,
2020-12-02 14:55:04 +01:00
bytes: makeBytes,
2019-12-15 17:48:22 +01:00
};
2020-12-02 14:55:04 +01:00
}
2020-03-30 12:39:32 +02:00
async get(url: string, opt?: HttpRequestOptions): Promise<HttpResponse> {
2020-12-02 14:55:04 +01:00
return this.fetch(url, {
method: "GET",
...opt,
});
2019-12-15 17:48:22 +01:00
}
async postJson(
url: string,
body: any,
opt?: HttpRequestOptions,
): Promise<HttpResponse> {
2020-12-02 14:55:04 +01:00
return this.fetch(url, {
method: "POST",
body,
...opt,
});
2019-12-15 17:48:22 +01:00
}
2020-03-30 12:39:32 +02:00
}