Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
56 changes: 56 additions & 0 deletions tests/utils_test.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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<void>((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);
});
},
);