Skip to content

Commit

Permalink
fix: enable keepAlive for HTTP requests
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-fenster committed Jan 11, 2024
1 parent 8d96291 commit 4a07184
Showing 1 changed file with 30 additions and 3 deletions.
33 changes: 30 additions & 3 deletions gax/src/fallbackServiceStub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,42 @@
/* global AbortController */

import nodeFetch from 'node-fetch';
import {Response as NodeFetchResponse} from 'node-fetch';
import {Response as NodeFetchResponse, RequestInit} from 'node-fetch';
import {AbortController as NodeAbortController} from 'abort-controller';

import {hasWindowFetch, hasAbortController} from './featureDetection';
import {hasWindowFetch, hasAbortController, isNodeJS} from './featureDetection';
import {AuthClient} from './fallback';
import {StreamArrayParser} from './streamArrayParser';
import {pipeline, PipelineSource} from 'stream';
import type {Agent as HttpAgent} from 'http';
import type {Agent as HttpsAgent} from 'https';

interface NodeFetchType {
(url: RequestInfo, init?: RequestInit): Promise<Response>;
}

// Node.js before v19 does not enable keepalive by default.
// We'll try to enable it very carefully to make sure we don't break possible non-Node use cases.
// TODO: remove this after Node 18 is EOL.
// More info: https://github.com/node-fetch/node-fetch#custom-agent
let agentOption:
| ((parsedUrl: {protocol: string}) => HttpAgent | HttpsAgent)
| null = null;
let httpAgent: HttpAgent | null = null;
let httpsAgent: HttpsAgent | null = null;
if (isNodeJS()) {
const http = require('http');
httpAgent = new http.Agent({keepAlive: true});
const https = require('https');
httpsAgent = new https.Agent({keepAlive: true});
agentOption = (parsedUrl: {protocol: string}) => {
if (parsedUrl.protocol === 'http:') {
return httpAgent!;
}
return httpsAgent!;
};
}

export interface FallbackServiceStub {
// Compatible with gRPC service stub
[method: string]: (
Expand Down Expand Up @@ -141,13 +165,16 @@ export function generateServiceStub(
method: fetchParameters.method,
signal: cancelSignal,
};
if (agentOption) {
fetchRequest.agent = agentOption;
}
if (
fetchParameters.method === 'GET' ||
fetchParameters.method === 'DELETE'
) {
delete fetchRequest['body'];
}
return fetch(url, fetchRequest);
return fetch(url, fetchRequest as {});
})
.then((response: Response | NodeFetchResponse) => {
if (response.ok && rpc.responseStream) {
Expand Down

0 comments on commit 4a07184

Please sign in to comment.