Skip to content

Commit

Permalink
Use undici upstream fetch, and disable pipling
Browse files Browse the repository at this point in the history
  • Loading branch information
Half-Shot committed Feb 21, 2024
1 parent 29c04e1 commit c4f0fbc
Showing 1 changed file with 24 additions and 12 deletions.
36 changes: 24 additions & 12 deletions src/Request.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { setRequestFn } from "matrix-bot-sdk";
import type { OptionsWithUri, RequestResponse } from "request";
import { Agent } from "undici";
import { Agent, fetch as undiciFetch } from "undici";

let installed = false;

Expand All @@ -13,23 +13,35 @@ export function installRequestFunction() {
return;
}
// Keep connections alive for long enough to be reused.
const dispatcher = new Agent({ allowH2: true, keepAliveTimeout: 10000, pipelining: 8 });
const dispatcher = new Agent({ allowH2: true });
const fn = async (params: OptionsWithUri): Promise<{response: RequestResponse, rBody: Buffer|unknown}> => {
let url = params.uri.toString();
if (params.qs) {
url += `?${new URLSearchParams(params.qs).toString()}`
}
const abort = new AbortController();
const tOut = params.timeout !== undefined ? setTimeout(() => abort.abort("Timed out"), params.timeout): undefined;
const res = await fetch(url, {
method: params.method ?? 'GET',
body: params.body,
headers: params.headers,
keepalive: true,
dispatcher,
signal: tOut ? abort.signal : undefined,
} satisfies Partial<RequestInit>);
clearTimeout(tOut);
let res;
try {
console.log(params.method ?? "GET", url);

Check failure on line 26 in src/Request.ts

View workflow job for this annotation

GitHub Actions / lint-node

Unexpected console statement
res = await undiciFetch(url, {
method: params.method ?? 'GET',
body: params.body,
headers: params.headers,
keepalive: true,
dispatcher,
signal: tOut ? abort.signal : undefined,
} satisfies Partial<RequestInit>);
console.log("response");

Check failure on line 35 in src/Request.ts

View workflow job for this annotation

GitHub Actions / lint-node

Unexpected console statement
} catch (ex) {
if (ex instanceof Error && ex.cause) {
throw ex.cause;
}
throw ex;
} finally {
clearTimeout(tOut);
}

let rBody: Buffer|unknown;
if (res.headers.get('Content-Type') === 'application/json') {
rBody = await res.json();
Expand All @@ -44,7 +56,7 @@ export function installRequestFunction() {
headers: Object.fromEntries(res.headers.entries()),
statusCode: res.status,
statusMessage: res.statusText,
} as Partial<RequestResponse> as any};
} satisfies Partial<RequestResponse> as any};
};
setRequestFn(
(params: OptionsWithUri, callback: (err: Error|null, response?: any, rBody?: any) => void) =>
Expand Down

0 comments on commit c4f0fbc

Please sign in to comment.