Skip to content

Commit

Permalink
fix: enable keepAlive for HTTP requests (#1534)
Browse files Browse the repository at this point in the history
* fix: enable keepAlive for HTTP requests

* fix: make it more straightforward

---------

Co-authored-by: sofisl <55454395+sofisl@users.noreply.github.com>
  • Loading branch information
alexander-fenster and sofisl authored Feb 5, 2025
1 parent 9cd9902 commit a706d5a
Showing 1 changed file with 28 additions and 3 deletions.
31 changes: 28 additions & 3 deletions gax/src/fallbackServiceStub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,40 @@
/* 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;
if (isNodeJS()) {
const http = require('http');
const https = require('https');
const httpAgent = new http.Agent({keepAlive: true});
const 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 +163,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 a706d5a

Please sign in to comment.