Skip to content

Commit 27aefd9

Browse files
committed
fix(node-http-handler): handle NodeHttp2Handler session failure
fix: detect errors on the NodeHttp2Handler, immediately destroy connections on unexpected error mode, and reconnect. Prior to this PR, if the server sent the client a GOAWAY frame, the session would not be removed from the connection pool and requests would fail indefinitely. This tries to avoid keeping streams(requests) on the Http2Session (tcp connection) from being stuck in an open state waiting for a gentle close even if there were unexpected protocol or connection errors during the request, assuming http2 errors are rare. (if a server or load balancer or network is misbehaving, close() might get stuck waiting for requests to finish, especially if requests and sessions don't have timeouts?) I'm only slightly familiar with http/2 client implementations from working on clients for Apple Push Notification Service. - In those, the client could rely on a session and request timeout existing, so close() would finish. In aws-sdk-js-v3, timeouts are optional. - I've seen some strange race conditions prior to node 12 in different client implementations for close and/or destroying Fixes #1525
1 parent 3788909 commit 27aefd9

File tree

2 files changed

+145
-7
lines changed

2 files changed

+145
-7
lines changed

packages/node-http-handler/src/node-http2-handler.spec.ts

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
import { HttpRequest } from "@aws-sdk/protocol-http";
2+
import { IncomingMessage, ServerResponse } from "http";
3+
import * as assert from "assert"
4+
import { Http2Stream, Http2Session, constants } from "http2";
25

36
import { NodeHttp2Handler } from "./node-http2-handler";
47
import { createMockHttp2Server, createResponseFunction } from "./server.mock";
@@ -100,6 +103,97 @@ describe("NodeHttp2Handler", () => {
100103
mockH2Server2.close();
101104
});
102105

106+
const UNEXPECTEDLY_CLOSED_REGEX = /closed|destroy|cancel|did not get a response/i;
107+
it("handles goaway frames", async () => {
108+
const port3 = port + 2;
109+
const mockH2Server3 = createMockHttp2Server().listen(port3);
110+
let establishedConnections = 0;
111+
let numRequests = 0;
112+
let shouldSendGoAway = true;
113+
114+
mockH2Server3.on("stream", (request: Http2Stream) => {
115+
// transmit goaway frame without shutting down the connection
116+
// to simulate an unlikely error mode.
117+
numRequests += 1;
118+
if (shouldSendGoAway) {
119+
request.session.goaway(constants.NGHTTP2_PROTOCOL_ERROR);
120+
}
121+
});
122+
mockH2Server3.on("connection", () => {
123+
establishedConnections += 1;
124+
});
125+
try {
126+
// should throw
127+
const req = new HttpRequest({ ...getMockReqOptions(), port: port3 });
128+
expect(establishedConnections).toBe(0);
129+
expect(numRequests).toBe(0);
130+
await assert.rejects(nodeH2Handler.handle(req, {}), UNEXPECTEDLY_CLOSED_REGEX, "should be rejected promptly due to goaway frame");
131+
expect(establishedConnections).toBe(1);
132+
expect(numRequests).toBe(1);
133+
await assert.rejects(nodeH2Handler.handle(req, {}), UNEXPECTEDLY_CLOSED_REGEX, "should be rejected promptly due to goaway frame");
134+
expect(establishedConnections).toBe(2);
135+
expect(numRequests).toBe(2);
136+
await assert.rejects(nodeH2Handler.handle(req, {}), UNEXPECTEDLY_CLOSED_REGEX, "should be rejected promptly due to goaway frame");
137+
expect(establishedConnections).toBe(3);
138+
expect(numRequests).toBe(3);
139+
140+
// should be able to recover from goaway after reconnecting to a server
141+
// that doesn't send goaway, and reuse the TCP connection (Http2Session)
142+
shouldSendGoAway = false;
143+
mockH2Server3.on("request", createResponseFunction(mockResponse));
144+
await nodeH2Handler.handle(req, {})
145+
const result = await nodeH2Handler.handle(req, {})
146+
const resultReader = result.response.body;
147+
148+
// ...and validate that the mocked response is received
149+
const responseBody = await new Promise((resolve) => {
150+
const buffers = [];
151+
resultReader.on('data', (chunk) => buffers.push(chunk));
152+
resultReader.on('end', () => {
153+
resolve(Buffer.concat(buffers).toString('utf8'));
154+
});
155+
});
156+
expect(responseBody).toBe('test');
157+
expect(establishedConnections).toBe(4);
158+
expect(numRequests).toBe(5);
159+
} finally {
160+
mockH2Server3.close();
161+
}
162+
});
163+
164+
it("handles connections destroyed by servers", async () => {
165+
const port3 = port + 2;
166+
const mockH2Server3 = createMockHttp2Server().listen(port3);
167+
let establishedConnections = 0;
168+
let numRequests = 0;
169+
170+
mockH2Server3.on("stream", (request: Http2Stream) => {
171+
// transmit goaway frame and then shut down the connection.
172+
numRequests += 1;
173+
request.session.destroy();
174+
});
175+
mockH2Server3.on("connection", () => {
176+
establishedConnections += 1;
177+
});
178+
try {
179+
// should throw
180+
const req = new HttpRequest({ ...getMockReqOptions(), port: port3 });
181+
expect(establishedConnections).toBe(0);
182+
expect(numRequests).toBe(0);
183+
await assert.rejects(nodeH2Handler.handle(req, {}), UNEXPECTEDLY_CLOSED_REGEX, "should be rejected promptly due to goaway frame or destroyed connection");
184+
expect(establishedConnections).toBe(1);
185+
expect(numRequests).toBe(1);
186+
await assert.rejects(nodeH2Handler.handle(req, {}), UNEXPECTEDLY_CLOSED_REGEX, "should be rejected promptly due to goaway frame or destroyed connection");
187+
expect(establishedConnections).toBe(2);
188+
expect(numRequests).toBe(2);
189+
await assert.rejects(nodeH2Handler.handle(req, {}), UNEXPECTEDLY_CLOSED_REGEX, "should be rejected promptly due to goaway frame or destroyed connection");
190+
expect(establishedConnections).toBe(3);
191+
expect(numRequests).toBe(3);
192+
} finally {
193+
mockH2Server3.close();
194+
}
195+
});
196+
103197
it("closes and removes session on sessionTimeout", async (done) => {
104198
const sessionTimeout = 500;
105199
nodeH2Handler = new NodeHttp2Handler({ sessionTimeout });

packages/node-http-handler/src/node-http2-handler.ts

Lines changed: 51 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,14 @@ export class NodeHttp2Handler implements HttpHandler {
4545
}
4646

4747
handle(request: HttpRequest, { abortSignal }: HttpHandlerOptions = {}): Promise<{ response: HttpResponse }> {
48-
return new Promise((resolve, reject) => {
48+
return new Promise((resolve, rejectOriginal) => {
49+
// It's redundant to track fulfilled because promises use the first resolution/rejection
50+
// but avoids generating unnecessary stack traces in the "close" event handler.
51+
let fulfilled = false;
52+
const reject = (err: Error) => {
53+
fulfilled = true;
54+
rejectOriginal(err);
55+
};
4956
// if the request was already aborted, prevent doing extra work
5057
if (abortSignal?.aborted) {
5158
const abortError = new Error("Request aborted");
@@ -70,13 +77,10 @@ export class NodeHttp2Handler implements HttpHandler {
7077
headers: getTransformedHeaders(headers),
7178
body: req,
7279
});
80+
fulfilled = true;
7381
resolve({ response: httpResponse });
7482
});
7583

76-
req.on("error", reject);
77-
req.on("frameError", reject);
78-
req.on("aborted", reject);
79-
8084
const requestTimeout = this.requestTimeout;
8185
if (requestTimeout) {
8286
req.setTimeout(requestTimeout, () => {
@@ -96,6 +100,18 @@ export class NodeHttp2Handler implements HttpHandler {
96100
};
97101
}
98102

103+
// Set up handlers for errors
104+
req.on("frameError", reject);
105+
req.on("error", reject);
106+
req.on("goaway", reject);
107+
req.on("aborted", reject);
108+
109+
// The HTTP/2 error code used when closing the stream can be retrieved using the http2stream.rstCode property. If the code is any value other than NGHTTP2_NO_ERROR (0), an 'error' event will have also been emitted.
110+
req.on("close", () => {
111+
if (!fulfilled) {
112+
reject(new Error("Unexpected error: http2 request did not get a response"));
113+
}
114+
});
99115
writeRequestBody(req, request);
100116
});
101117
}
@@ -107,14 +123,42 @@ export class NodeHttp2Handler implements HttpHandler {
107123

108124
const newSession = connect(authority);
109125
connectionPool.set(authority, newSession);
126+
const destroySessionCb = () => {
127+
this.destroySession(authority, newSession);
128+
};
129+
newSession.on("goaway", destroySessionCb);
130+
newSession.on("error", destroySessionCb);
131+
newSession.on("frameError", destroySessionCb);
110132

111133
const sessionTimeout = this.sessionTimeout;
112134
if (sessionTimeout) {
113135
newSession.setTimeout(sessionTimeout, () => {
114-
newSession.close();
115-
connectionPool.delete(authority);
136+
if (connectionPool.get(authority) === newSession) {
137+
newSession.close();
138+
connectionPool.delete(authority);
139+
}
116140
});
117141
}
118142
return newSession;
119143
}
144+
145+
/**
146+
* Destroy a session immediately and remove it from the http2 pool.
147+
*
148+
* This check ensures that the session is only closed once
149+
* and that an event on one session does not close a different session.
150+
*/
151+
private destroySession(authority: string, session: ClientHttp2Session): void {
152+
if (this.connectionPool.get(authority) !== session) {
153+
// Already closed?
154+
return;
155+
}
156+
this.connectionPool.delete(authority);
157+
session.removeAllListeners("goaway");
158+
session.removeAllListeners("error");
159+
session.removeAllListeners("frameError");
160+
if (!session.destroyed) {
161+
session.destroy();
162+
}
163+
}
120164
}

0 commit comments

Comments
 (0)