-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathHttp2Handler.java
More file actions
317 lines (279 loc) · 13.8 KB
/
Http2Handler.java
File metadata and controls
317 lines (279 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
/*
* Copyright (c) 2014-2026 AsyncHttpClient Project. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.asynchttpclient.netty.handler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2GoAwayFrame;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.handler.codec.http2.Http2ResetFrame;
import io.netty.handler.codec.http2.Http2StreamChannel;
import org.asynchttpclient.AsyncHandler;
import org.asynchttpclient.AsyncHandler.State;
import org.asynchttpclient.AsyncHttpClientConfig;
import org.asynchttpclient.HttpResponseBodyPart;
import org.asynchttpclient.netty.NettyResponseFuture;
import org.asynchttpclient.netty.NettyResponseStatus;
import org.asynchttpclient.netty.channel.ChannelManager;
import org.asynchttpclient.netty.channel.Http2ConnectionState;
import org.asynchttpclient.netty.request.NettyRequestSender;
import java.io.IOException;
/**
* HTTP/2 channel handler for stream child channels created by {@link io.netty.handler.codec.http2.Http2MultiplexHandler}.
* <p>
* Each HTTP/2 stream is represented as a child channel. This handler is attached to each stream child channel
* and processes {@link Http2HeadersFrame} (response status + headers) and {@link Http2DataFrame} (response body)
* frames directly for maximum performance — no HTTP/1.1 object conversion overhead.
* <p>
* Follows the same structure as {@link HttpHandler} and reuses the same interceptor chain,
* body part factory, and lifecycle methods from {@link AsyncHttpClientHandler}.
*/
@Sharable
public final class Http2Handler extends AsyncHttpClientHandler {
private static final HttpVersion HTTP_2 = new HttpVersion("HTTP", 2, 0, true);
public Http2Handler(AsyncHttpClientConfig config, ChannelManager channelManager, NettyRequestSender requestSender) {
super(config, channelManager, requestSender);
}
/**
* Handles incoming frames on the HTTP/2 stream child channel.
* Dispatches to the appropriate handler based on frame type.
*/
@Override
public void handleRead(final Channel channel, final NettyResponseFuture<?> future, final Object e) throws Exception {
if (future.isDone()) {
channelManager.closeChannel(channel);
return;
}
AsyncHandler<?> handler = future.getAsyncHandler();
try {
if (e instanceof Http2HeadersFrame) {
Http2HeadersFrame headersFrame = (Http2HeadersFrame) e;
if (headersFrame.headers().status() != null) {
handleHttp2HeadersFrame(headersFrame, channel, future, handler);
} else {
handleHttp2TrailingHeadersFrame(headersFrame, channel, future, handler);
}
} else if (e instanceof Http2DataFrame) {
handleHttp2DataFrame((Http2DataFrame) e, channel, future, handler);
} else if (e instanceof Http2ResetFrame) {
handleHttp2ResetFrame((Http2ResetFrame) e, channel, future);
} else if (e instanceof Http2GoAwayFrame) {
handleHttp2GoAwayFrame((Http2GoAwayFrame) e, channel, future);
}
} catch (Exception t) {
if (hasIOExceptionFilters && t instanceof IOException
&& requestSender.applyIoExceptionFiltersAndReplayRequest(future, (IOException) t, channel)) {
return;
}
readFailed(channel, future, t);
throw t;
}
}
/**
* Processes an HTTP/2 HEADERS frame, which carries the response status and headers.
* Builds a synthetic {@link HttpResponse} from the HTTP/2 pseudo-headers so the existing
* interceptor chain can be reused without modification.
*/
private void handleHttp2HeadersFrame(Http2HeadersFrame headersFrame, Channel channel,
NettyResponseFuture<?> future, AsyncHandler<?> handler) throws Exception {
Http2Headers h2Headers = headersFrame.headers();
// Extract :status pseudo-header and convert to HTTP status
CharSequence statusValue = h2Headers.status();
int statusCode = statusValue != null ? Integer.parseInt(statusValue.toString()) : 200;
HttpResponseStatus nettyStatus = HttpResponseStatus.valueOf(statusCode);
// Build HTTP/1.1-style headers, skipping HTTP/2 pseudo-headers (start with ':')
HttpHeaders responseHeaders = new DefaultHttpHeaders();
h2Headers.forEach(entry -> {
CharSequence name = entry.getKey();
if (name.length() > 0 && name.charAt(0) != ':') {
responseHeaders.add(name, entry.getValue());
}
});
// Build a synthetic HttpResponse so the existing interceptor chain can be reused unchanged
HttpResponse syntheticResponse = new DefaultHttpResponse(HTTP_2, nettyStatus, responseHeaders);
// Respect user's keepAlive config; only multiplex/pool if keepAlive is enabled
future.setKeepAlive(config.isKeepAlive());
NettyResponseStatus status = new NettyResponseStatus(future.getUri(), syntheticResponse, channel);
if (!interceptors.exitAfterIntercept(channel, future, handler, syntheticResponse, status, responseHeaders)) {
boolean abort = handler.onStatusReceived(status) == State.ABORT;
if (!abort) {
abort = handler.onHeadersReceived(responseHeaders) == State.ABORT;
}
if (abort) {
finishUpdate(future, channel, false);
return;
}
}
// If headers frame also ends the stream (no body), finish the response
if (headersFrame.isEndStream()) {
finishUpdate(future, channel, false);
}
}
/**
* Processes an HTTP/2 DATA frame, which carries response body bytes.
* Passes body content directly to {@link AsyncHandler#onBodyPartReceived} using the
* configured {@link org.asynchttpclient.ResponseBodyPartFactory} — same as HTTP/1.1.
*/
private void handleHttp2DataFrame(Http2DataFrame dataFrame, Channel channel,
NettyResponseFuture<?> future, AsyncHandler<?> handler) throws Exception {
boolean last = dataFrame.isEndStream();
ByteBuf data = dataFrame.content();
if (data.isReadable() || last) {
HttpResponseBodyPart bodyPart = config.getResponseBodyPartFactory().newResponseBodyPart(data, last);
boolean abort = handler.onBodyPartReceived(bodyPart) == State.ABORT;
if (abort || last) {
finishUpdate(future, channel, false);
}
}
}
/**
* Processes trailing HTTP/2 HEADERS frame (no :status pseudo-header), which carries trailer headers
* sent after the DATA frames. Delegates to {@link AsyncHandler#onTrailingHeadersReceived}.
*/
private void handleHttp2TrailingHeadersFrame(Http2HeadersFrame headersFrame, Channel channel,
NettyResponseFuture<?> future, AsyncHandler<?> handler) throws Exception {
Http2Headers h2Headers = headersFrame.headers();
HttpHeaders trailingHeaders = new DefaultHttpHeaders();
h2Headers.forEach(entry -> {
CharSequence name = entry.getKey();
if (name.length() > 0 && name.charAt(0) != ':') {
trailingHeaders.add(name, entry.getValue());
}
});
boolean abort = false;
if (!trailingHeaders.isEmpty()) {
abort = handler.onTrailingHeadersReceived(trailingHeaders) == State.ABORT;
}
if (abort || headersFrame.isEndStream()) {
finishUpdate(future, channel, false);
}
}
/**
* Processes an HTTP/2 RST_STREAM frame, which indicates the server aborted the stream.
*/
private void handleHttp2ResetFrame(Http2ResetFrame resetFrame, Channel channel, NettyResponseFuture<?> future) {
long errorCode = resetFrame.errorCode();
readFailed(channel, future, new IOException("HTTP/2 stream reset by server, error code: " + errorCode));
}
/**
* Processes an HTTP/2 GOAWAY frame, which indicates the server is shutting down the connection.
* The parent connection is removed from the pool to prevent new streams from being created on it.
* The current stream's future is failed so the request can be retried on a new connection.
*/
private void handleHttp2GoAwayFrame(Http2GoAwayFrame goAwayFrame, Channel channel, NettyResponseFuture<?> future) {
long errorCode = goAwayFrame.errorCode();
int lastStreamId = goAwayFrame.lastStreamId();
// Remove the parent connection from the HTTP/2 registry so no new streams are opened on it
Channel parentChannel = (channel instanceof Http2StreamChannel)
? ((Http2StreamChannel) channel).parent()
: channel;
// Mark the connection as draining and remove from registry
Http2ConnectionState state = parentChannel.attr(Http2ConnectionState.HTTP2_STATE_KEY).get();
if (state != null) {
state.setDraining(lastStreamId);
Object partitionKey = state.getPartitionKey();
if (partitionKey != null) {
channelManager.removeHttp2Connection(partitionKey, parentChannel);
}
}
// Check if this stream's ID is within the allowed range
if (channel instanceof Http2StreamChannel) {
int streamId = ((Http2StreamChannel) channel).stream().id();
if (streamId <= lastStreamId) {
// This stream is allowed to complete — don't fail it
return;
}
}
readFailed(channel, future, new IOException("HTTP/2 connection GOAWAY received, error code: " + errorCode
+ ", lastStreamId: " + lastStreamId));
}
/**
* Overrides the base {@link AsyncHttpClientHandler#finishUpdate} to correctly handle HTTP/2
* connection pooling. HTTP/2 stream channels are single-use — after the stream completes,
* it must be closed. The reusable resource is the parent TCP connection channel, which is
* offered back to the pool so future requests can open new streams on the same connection.
*
* @param future the completed request future
* @param streamChannel the stream child channel (single-use, will be closed)
* @param close if {@code true}, close the parent connection entirely rather than pooling it
*/
@Override
void finishUpdate(NettyResponseFuture<?> future, Channel streamChannel, boolean close) {
future.cancelTimeouts();
// Stream channels are single-use in HTTP/2 — close the stream
streamChannel.close();
// The parent HTTP/2 connection stays in the HTTP/2 registry (not the regular pool)
// to allow concurrent multiplexed requests. We only need to release the stream count.
Channel parentChannel = (streamChannel instanceof Http2StreamChannel)
? ((Http2StreamChannel) streamChannel).parent()
: null;
if (parentChannel != null) {
Http2ConnectionState state = parentChannel.attr(Http2ConnectionState.HTTP2_STATE_KEY).get();
if (state != null) {
state.releaseStream();
// If connection is draining and no more active streams, close it
if (state.isDraining() && state.getActiveStreams() <= 0) {
channelManager.closeChannel(parentChannel);
}
}
// Fire onConnectionOffer to maintain event lifecycle contract
try {
future.getAsyncHandler().onConnectionOffer(parentChannel);
} catch (Exception e) {
logger.error("onConnectionOffer crashed", e);
}
}
// If close was requested, close the parent connection entirely
if (close && parentChannel != null) {
channelManager.closeChannel(parentChannel);
}
try {
future.done();
} catch (Exception t) {
logger.debug(t.getMessage(), t);
}
}
private void readFailed(Channel channel, NettyResponseFuture<?> future, Throwable t) {
try {
requestSender.abort(channel, future, t);
} catch (Exception abortException) {
logger.debug("Abort failed", abortException);
} finally {
finishUpdate(future, channel, true);
}
}
@Override
public void handleException(NettyResponseFuture<?> future, Throwable error) {
if (!future.isDone()) {
readFailed(future.channel(), future, error);
}
}
@Override
public void handleChannelInactive(NettyResponseFuture<?> future) {
if (!future.isDone()) {
readFailed(future.channel(), future,
new IOException("HTTP/2 stream channel closed unexpectedly"));
}
}
}