From 6748b25d0bdd77b174f8106426b9a08b3b4343bd Mon Sep 17 00:00:00 2001 From: Krishna Yadav <963gurudev@gmail.com> Date: Sat, 3 Oct 2026 16:38:28 +0530 Subject: [PATCH] Fix promise hanging until timeout when connection drops mid-response --- src/utils.ts | 18 +++++++++++++++ tests/utils_test.ts | 56 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) diff --git a/src/utils.ts b/src/utils.ts index 082434c..549fad5 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -107,6 +107,24 @@ export function execute( if (timer) clearTimeout(timer); } }); + + // when the connection breaks mid-response + const onAborted = () => { + if (timer) clearTimeout(timer); + reject( + new Error( + "The connection was closed before the full response arrived", + ), + ); + }; + resp.on("aborted", onAborted); + resp.on("error", (error) => { + if (timer) clearTimeout(timer); + reject(error); + }); + resp.on("close", () => { + if (!resp.complete) onAborted(); + }); }; const handleError = (err: Error) => { diff --git a/tests/utils_test.ts b/tests/utils_test.ts index 46f444d..8ae3ba0 100644 --- a/tests/utils_test.ts +++ b/tests/utils_test.ts @@ -1,4 +1,5 @@ import http from "node:http"; +import https from "node:https"; import qs from "node:querystring"; import { loadSync } from "@std/dotenv"; import { afterAll, beforeAll, describe, it } from "@std/testing/bdd"; @@ -235,3 +236,58 @@ describe( }); }, ); + +describe( + "execute with a dropped connection", + { + sanitizeOps: false, + sanitizeResources: false, + }, + () => { + let server: http.Server; + let urlStub: Stub; + let getStub: Stub; + + beforeAll(async () => { + // A server that promises 1000 bytes, sends a few, then kills the socket. + server = http.createServer((req, res) => { + res.writeHead(200, { "Content-Length": 1000 }); + res.write('{"organic_results":['); + setTimeout(() => req.socket.destroy(), 100); + }); + await new Promise((resolve) => + server.listen(0, "127.0.0.1", resolve) + ); + const { port } = server.address() as { port: number }; + + // Talk plain HTTP to the local server instead of HTTPS to serpapi.com. + urlStub = stub( + _internals, + "getHostnameAndPort", + () => ({ hostname: "127.0.0.1", port }), + ); + getStub = stub(https, "get", http.get as typeof https.get); + }); + + afterAll(() => { + getStub.restore(); + urlStub.restore(); + server.close(); + }); + + it("rejects quickly instead of waiting for the timeout", async () => { + const start = Date.now(); + let error: unknown; + try { + await execute("/search", { q: "coffee" }, 3000); + } catch (e) { + error = e; + } + const elapsed = Date.now() - start; + + assertInstanceOf(error, Error); + assertEquals(error instanceof RequestTimeoutError, false); + assertEquals(elapsed < 1500, true); + }); + }, +);