Skip to content

Commit f5ce61a

Browse files
authored
fix(node-http-handler): begin socket timeout countdown before socket event (#4804)
1 parent d8317fe commit f5ce61a

File tree

2 files changed

+14
-16
lines changed

2 files changed

+14
-16
lines changed

packages/node-http-handler/src/set-connection-timeout.spec.ts

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ describe("setConnectionTimeout", () => {
3434
});
3535

3636
afterEach(() => {
37+
jest.advanceTimersByTime(10000);
3738
jest.useRealTimers();
3839
});
3940

@@ -48,7 +49,7 @@ describe("setConnectionTimeout", () => {
4849
connecting: false,
4950
});
5051
expect(mockSocket.on).not.toHaveBeenCalled();
51-
expect(setTimeout).not.toHaveBeenCalled();
52+
expect(setTimeout).toHaveBeenCalled();
5253
expect(reject).not.toHaveBeenCalled();
5354
});
5455

@@ -74,8 +75,6 @@ describe("setConnectionTimeout", () => {
7475
});
7576

7677
it("clears timeout if socket gets connected", () => {
77-
const mockTimeoutId = 42;
78-
(setTimeout as unknown as jest.Mock).mockReturnValueOnce(mockTimeoutId);
7978
clientRequest.on.mock.calls[0][1](mockSocket);
8079

8180
expect(clientRequest.destroy).not.toHaveBeenCalled();
@@ -87,7 +86,6 @@ describe("setConnectionTimeout", () => {
8786
mockSocket.on.mock.calls[0][1]();
8887

8988
expect(clearTimeout).toHaveBeenCalled();
90-
expect(clearTimeout).toHaveBeenCalledWith(mockTimeoutId);
9189

9290
// Fast-forward until timer has been executed.
9391
jest.runAllTimers();

packages/node-http-handler/src/set-connection-timeout.ts

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,23 @@ export const setConnectionTimeout = (request: ClientRequest, reject: (err: Error
66
return;
77
}
88

9+
// Throw a connecting timeout error unless a connection is made within time.
10+
const timeoutId = setTimeout(() => {
11+
request.destroy();
12+
reject(
13+
Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), {
14+
name: "TimeoutError",
15+
})
16+
);
17+
}, timeoutInMs);
18+
919
request.on("socket", (socket: Socket) => {
1020
if (socket.connecting) {
11-
// Throw a connecting timeout error unless a connection is made within x time.
12-
const timeoutId = setTimeout(() => {
13-
// destroy the request.
14-
request.destroy();
15-
reject(
16-
Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), {
17-
name: "TimeoutError",
18-
})
19-
);
20-
}, timeoutInMs);
21-
22-
// if the connection was established, cancel the timeout.
2321
socket.on("connect", () => {
2422
clearTimeout(timeoutId);
2523
});
24+
} else {
25+
clearTimeout(timeoutId);
2626
}
2727
});
2828
};

0 commit comments

Comments
 (0)