Skip to content

Commit e97e357

Browse files
TysonAndretrivikr
andauthored
fix(node-http-handler): handle NodeHttp2Handler session failure (#2289)
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?) Co-authored-by: Trivikram Kamat <[email protected]>
1 parent 3dd31c4 commit e97e357

File tree

2 files changed

+162
-7
lines changed

2 files changed

+162
-7
lines changed

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

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import { HttpRequest } from "@aws-sdk/protocol-http";
2+
import { rejects } from "assert";
3+
import { constants, Http2Stream } from "http2";
24

35
import { NodeHttp2Handler } from "./node-http2-handler";
46
import { createMockHttp2Server, createResponseFunction } from "./server.mock";
@@ -100,6 +102,113 @@ describe("NodeHttp2Handler", () => {
100102
mockH2Server2.close();
101103
});
102104

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

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

Lines changed: 53 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,20 @@ 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
110+
// http2stream.rstCode property. If the code is any value other than NGHTTP2_NO_ERROR (0),
111+
// an 'error' event will have also been emitted.
112+
req.on("close", () => {
113+
if (!fulfilled) {
114+
reject(new Error("Unexpected error: http2 request did not get a response"));
115+
}
116+
});
99117
writeRequestBody(req, request);
100118
});
101119
}
@@ -107,14 +125,42 @@ export class NodeHttp2Handler implements HttpHandler {
107125

108126
const newSession = connect(authority);
109127
connectionPool.set(authority, newSession);
128+
const destroySessionCb = () => {
129+
this.destroySession(authority, newSession);
130+
};
131+
newSession.on("goaway", destroySessionCb);
132+
newSession.on("error", destroySessionCb);
133+
newSession.on("frameError", destroySessionCb);
110134

111135
const sessionTimeout = this.sessionTimeout;
112136
if (sessionTimeout) {
113137
newSession.setTimeout(sessionTimeout, () => {
114-
newSession.close();
115-
connectionPool.delete(authority);
138+
if (connectionPool.get(authority) === newSession) {
139+
newSession.close();
140+
connectionPool.delete(authority);
141+
}
116142
});
117143
}
118144
return newSession;
119145
}
146+
147+
/**
148+
* Destroy a session immediately and remove it from the http2 pool.
149+
*
150+
* This check ensures that the session is only closed once
151+
* and that an event on one session does not close a different session.
152+
*/
153+
private destroySession(authority: string, session: ClientHttp2Session): void {
154+
if (this.connectionPool.get(authority) !== session) {
155+
// Already closed?
156+
return;
157+
}
158+
this.connectionPool.delete(authority);
159+
session.removeAllListeners("goaway");
160+
session.removeAllListeners("error");
161+
session.removeAllListeners("frameError");
162+
if (!session.destroyed) {
163+
session.destroy();
164+
}
165+
}
120166
}

0 commit comments

Comments
 (0)