From cc24c51bdbf46c5ad1b181b8fad7f87ab569cde9 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Fri, 27 May 2022 12:06:01 -0400 Subject: [PATCH] Use a keep-alive agent for got when sending to Hydro (#28051) --- lib/hydro.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/lib/hydro.js b/lib/hydro.js index 8cc995baf47f..06cd8067c679 100644 --- a/lib/hydro.js +++ b/lib/hydro.js @@ -1,5 +1,8 @@ import crypto from 'crypto' +import { Agent } from 'https' + import got from 'got' + import statsd from '../lib/statsd.js' import FailBot from '../lib/failbot.js' @@ -12,6 +15,21 @@ const TIME_OUT_TEXT = 'ms has passed since batch creation' // linger within the thread. const POST_TIMEOUT_MS = 3000 +let _agent +function getHttpsAgent() { + if (!_agent) { + const agentOptions = { + // The most important option. This is false by default. + keepAlive: true, + // 32 because it's what's recommended here + // https://docs.microsoft.com/en-us/azure/app-service/app-service-web-nodejs-best-practices-and-troubleshoot-guide#my-node-application-is-making-excessive-outbound-calls + maxSockets: 32, + } + _agent = new Agent(agentOptions) + } + return _agent +} + export default class Hydro { constructor({ secret, endpoint } = {}) { this.secret = secret || process.env.HYDRO_SECRET @@ -51,6 +69,8 @@ export default class Hydro { }) const token = this.generatePayloadHmac(body) + const agent = getHttpsAgent() + const doPost = () => got(this.endpoint, { method: 'POST', @@ -64,6 +84,11 @@ export default class Hydro { throwHttpErrors: false, // The default is no timeout. timeout: POST_TIMEOUT_MS, + agent: { + // Deliberately not setting up a `http` or `http2` agent + // because it won't be used for this particular `got` request. + https: agent, + }, }) const res = await statsd.asyncTimer(doPost, 'hydro.response_time')()