GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Auto-port 5.0: Avoid ArrayQueue allocation in HttpServerCodec (#16648) · netty/netty@3e84c5a

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • codec-http/src
    • main/java/io/netty/handler/codec/http
      • HttpServerCodec.java
    • test/java/io/netty/handler/codec/http
      • HttpServerCodecTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎codec-http/src/main/java/io/netty/handler/codec/http/HttpServerCodec.java‎

Copy file name to clipboardExpand all lines: codec-http/src/main/java/io/netty/handler/codec/http/HttpServerCodec.java
+75-9Lines changed: 75 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@
2626
import static io.netty.handler.codec.http.HttpObjectDecoder.DEFAULT_MAX_CHUNK_SIZE;
2727
import static io.netty.handler.codec.http.HttpObjectDecoder.DEFAULT_MAX_HEADER_SIZE;
2828
import static io.netty.handler.codec.http.HttpObjectDecoder.DEFAULT_MAX_INITIAL_LINE_LENGTH;
29-
import static io.netty.handler.codec.http.HttpObjectDecoder.DEFAULT_VALIDATE_HEADERS;
3029

3130
/**
3231
* A combination of {@link HttpRequestDecoder} and {@link HttpResponseEncoder}
@@ -49,8 +48,27 @@
4948
public final class HttpServerCodec extends CombinedChannelDuplexHandler<HttpRequestDecoder, HttpResponseEncoder>
5049
implements HttpServerUpgradeHandler.SourceCodec {
5150

52-
/** A queue that is used for correlating a request and a response. */
53-
private final Queue<HttpMethod> queue = new ArrayDeque<HttpMethod>();
51+
private static final byte METHOD_FLAG_HEAD = 1;
52+
private static final byte METHOD_FLAG_CONNECT = 2;
53+
private static final byte METHOD_FLAG_OTHER = 3;
54+
55+
// We only need 2 bits per request because we distinguish:
56+
// 01 = HEAD, 10 = CONNECT, 11 = other
57+
private static final int METHOD_FLAG_BITS = 2;
58+
private static final int INLINE_QUEUE_CAPACITY = Long.SIZE / METHOD_FLAG_BITS; // 32
59+
60+
/**
61+
* FIFO of request method flags.
62+
*
63+
* The oldest entry is stored in the least-significant bits so poll is just a mask + unsigned shift.
64+
* This avoids allocation for the common case of <= 32 outstanding requests.
65+
*
66+
* Once more than {@link #INLINE_QUEUE_CAPACITY} requests are queued, additional entries are appended
67+
* to {@link #methodOverflowQueue}. Order is preserved by always draining the inline queue first.
68+
*/
69+
private long methodQueue;
70+
private int methodQueueSize;
71+
private Queue<Byte> methodOverflowQueue;
5472

5573
/**
5674
* Creates a new instance with the default decoder options
@@ -156,6 +174,54 @@ public void upgradeFrom(ChannelHandlerContext ctx) {
156174
ctx.pipeline().remove(this);
157175
}
158176

177+
private void enqueueMethod(HttpMethod method) {
178+
final byte flag;
179+
if (HttpMethod.HEAD.equals(method)) {
180+
flag = METHOD_FLAG_HEAD;
181+
} else if (HttpMethod.CONNECT.equals(method)) {
182+
flag = METHOD_FLAG_CONNECT;
183+
} else {
184+
flag = METHOD_FLAG_OTHER;
185+
}
186+
187+
// Once we have overflow, always append there until it drains completely.
188+
Queue<Byte> overflowQueue = methodOverflowQueue;
189+
if (overflowQueue != null) {
190+
overflowQueue.add(flag);
191+
return;
192+
}
193+
194+
if (methodQueueSize < INLINE_QUEUE_CAPACITY) {
195+
methodQueue |= (long) flag << (methodQueueSize << 1);
196+
methodQueueSize++;
197+
} else {
198+
overflowQueue = new ArrayDeque<>(4);
199+
overflowQueue.add(flag);
200+
methodOverflowQueue = overflowQueue;
201+
}
202+
}
203+
204+
private byte pollMethod() {
205+
if (methodQueueSize != 0) {
206+
//(methodQueue & ((1L << METHOD_FLAG_BITS) - 1))
207+
byte flag = (byte) (methodQueue & 0x3L);
208+
methodQueue >>>= METHOD_FLAG_BITS;
209+
methodQueueSize--;
210+
return flag;
211+
}
212+
213+
Queue<Byte> overflowQueue = methodOverflowQueue;
214+
if (overflowQueue != null) {
215+
Byte flag = overflowQueue.poll();
216+
if (overflowQueue.isEmpty()) {
217+
methodOverflowQueue = null;
218+
}
219+
return flag != null ? flag : METHOD_FLAG_OTHER;
220+
}
221+
222+
return METHOD_FLAG_OTHER;
223+
}
224+
159225
private final class HttpServerRequestDecoder extends HttpRequestDecoder {
160226
HttpServerRequestDecoder(HttpDecoderConfig config) {
161227
super(config);
@@ -169,19 +235,19 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> ou
169235
for (int i = oldSize; i < size; i++) {
170236
Object obj = out.get(i);
171237
if (obj instanceof HttpRequest) {
172-
queue.add(((HttpRequest) obj).method());
238+
enqueueMethod(((HttpRequest) obj).method());
173239
}
174240
}
175241
}
176242
}
177243

178244
private final class HttpServerResponseEncoder extends HttpResponseEncoder {
179245

180-
private HttpMethod method;
246+
private byte methodFlag;
181247

182248
@Override
183249
protected void sanitizeHeadersBeforeEncode(HttpResponse msg, boolean isAlwaysEmpty) {
184-
if (!isAlwaysEmpty && HttpMethod.CONNECT.equals(method)
250+
if (!isAlwaysEmpty && methodFlag == METHOD_FLAG_CONNECT
185251
&& msg.status().codeClass() == HttpStatusClass.SUCCESS) {
186252
// Stripping Transfer-Encoding:
187253
// See https://tools.ietf.org/html/rfc7230#section-3.3.1
@@ -193,9 +259,9 @@ protected void sanitizeHeadersBeforeEncode(HttpResponse msg, boolean isAlwaysEmp
193259
}
194260

195261
@Override
196-
protected boolean isContentAlwaysEmpty(@SuppressWarnings("unused") HttpResponse msg) {
197-
method = queue.poll();
198-
return HttpMethod.HEAD.equals(method) || super.isContentAlwaysEmpty(msg);
262+
protected boolean isContentAlwaysEmpty(HttpResponse msg) {
263+
methodFlag = pollMethod();
264+
return methodFlag == METHOD_FLAG_HEAD || super.isContentAlwaysEmpty(msg);
199265
}
200266
}
201267
}
Collapse file

‎codec-http/src/test/java/io/netty/handler/codec/http/HttpServerCodecTest.java‎

Copy file name to clipboardExpand all lines: codec-http/src/test/java/io/netty/handler/codec/http/HttpServerCodecTest.java
+234-1Lines changed: 234 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import io.netty.util.CharsetUtil;
2222
import org.junit.jupiter.api.Test;
2323

24+
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
2425
import static org.junit.jupiter.api.Assertions.assertEquals;
2526
import static org.junit.jupiter.api.Assertions.assertFalse;
2627
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -138,7 +139,8 @@ public void testChunkedHeadResponse() throws Exception {
138139
assertTrue(ch.finish());
139140

140141
ByteBuf buf = ch.readOutbound();
141-
assertEquals("HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n", buf.toString(CharsetUtil.US_ASCII));
142+
assertEquals("HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n",
143+
buf.toString(CharsetUtil.US_ASCII));
142144
buf.release();
143145

144146
buf = ch.readOutbound();
@@ -174,6 +176,237 @@ public void testChunkedHeadFullHttpResponse() throws Exception {
174176
assertFalse(ch.finishAndReleaseAll());
175177
}
176178

179+
@Test
180+
public void testInterleavedRequestResponseAcrossOverflow() throws Exception {
181+
// Test interleaved enqueue/dequeue that crosses the inline-to-overflow boundary.
182+
// Send some requests, process some responses, then send more requests to trigger overflow.
183+
EmbeddedChannel ch = new EmbeddedChannel(new HttpServerCodec());
184+
185+
// Send 30 GET requests (not yet filling the 32-slot inline queue).
186+
StringBuilder requests = new StringBuilder();
187+
for (int i = 0; i < 30; i++) {
188+
requests.append("GET /").append(i).append(" HTTP/1.1\r\nHost: a\r\n\r\n");
189+
}
190+
assertTrue(ch.writeInbound(Unpooled.copiedBuffer(requests.toString(), CharsetUtil.UTF_8)));
191+
192+
// Drain inbound.
193+
for (;;) {
194+
Object msg = ch.readInbound();
195+
if (msg == null) {
196+
break;
197+
}
198+
if (msg instanceof HttpContent) {
199+
((HttpContent) msg).release();
200+
}
201+
}
202+
203+
// Respond to 10 of them (draining 10 from the queue, leaving 20).
204+
for (int i = 0; i < 10; i++) {
205+
FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
206+
Unpooled.copiedBuffer("ok", CharsetUtil.UTF_8));
207+
resp.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 2);
208+
assertTrue(ch.writeOutbound(resp));
209+
ByteBuf buf = ch.readOutbound();
210+
buf.release();
211+
}
212+
213+
// Now send 15 more requests (20 remaining + 15 = 35 total, exceeding inline capacity of 32).
214+
// Put a HEAD request as the last one to verify overflow ordering.
215+
requests = new StringBuilder();
216+
for (int i = 30; i < 44; i++) {
217+
requests.append("GET /").append(i).append(" HTTP/1.1\r\nHost: a\r\n\r\n");
218+
}
219+
requests.append("HEAD /44 HTTP/1.1\r\nHost: a\r\n\r\n");
220+
assertTrue(ch.writeInbound(Unpooled.copiedBuffer(requests.toString(), CharsetUtil.UTF_8)));
221+
222+
// Drain inbound.
223+
for (;;) {
224+
Object msg = ch.readInbound();
225+
if (msg == null) {
226+
break;
227+
}
228+
if (msg instanceof HttpContent) {
229+
((HttpContent) msg).release();
230+
}
231+
}
232+
233+
// Respond to remaining 20 GET requests (inline queue).
234+
for (int i = 10; i < 30; i++) {
235+
FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
236+
Unpooled.copiedBuffer("ok", CharsetUtil.UTF_8));
237+
resp.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 2);
238+
assertTrue(ch.writeOutbound(resp));
239+
ByteBuf buf = ch.readOutbound();
240+
buf.release();
241+
}
242+
243+
// Respond to the 14 GET requests that were added.
244+
for (int i = 30; i < 44; i++) {
245+
FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
246+
Unpooled.copiedBuffer("ok", CharsetUtil.UTF_8));
247+
resp.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 2);
248+
assertTrue(ch.writeOutbound(resp));
249+
ByteBuf buf = ch.readOutbound();
250+
String encoded = buf.toString(CharsetUtil.US_ASCII);
251+
assertTrue(encoded.contains("ok"), "GET response at position " + i + " should contain body");
252+
buf.release();
253+
}
254+
255+
// Respond to the HEAD request at position 44 — must be content-always-empty.
256+
HttpResponse headResp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
257+
headResp.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 999);
258+
assertTrue(ch.writeOutbound(headResp));
259+
assertTrue(ch.writeOutbound(LastHttpContent.EMPTY_LAST_CONTENT));
260+
261+
ByteBuf buf = ch.readOutbound();
262+
String encoded = buf.toString(CharsetUtil.US_ASCII);
263+
assertTrue(encoded.contains("HTTP/1.1 200 OK"), "HEAD response should be 200 OK");
264+
buf.release();
265+
266+
buf = ch.readOutbound();
267+
assertFalse(buf.isReadable(), "HEAD response body should be empty in overflow scenario");
268+
buf.release();
269+
270+
assertFalse(ch.finishAndReleaseAll());
271+
}
272+
273+
@Test
274+
public void testGetMethodHasNormalBody() throws Exception {
275+
// Verify a simple GET request is treated as METHOD_FLAG_NONE and body is included.
276+
EmbeddedChannel ch = new EmbeddedChannel(new HttpServerCodec());
277+
278+
assertTrue(ch.writeInbound(Unpooled.copiedBuffer(
279+
"GET / HTTP/1.1\r\nHost: a\r\n\r\n", CharsetUtil.UTF_8)));
280+
281+
HttpRequest request = ch.readInbound();
282+
assertEquals(HttpMethod.GET, request.method());
283+
LastHttpContent content = ch.readInbound();
284+
content.release();
285+
286+
FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
287+
Unpooled.copiedBuffer("hello", CharsetUtil.UTF_8));
288+
resp.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 5);
289+
assertTrue(ch.writeOutbound(resp));
290+
291+
ByteBuf buf = ch.readOutbound();
292+
String encoded = buf.toString(CharsetUtil.US_ASCII);
293+
assertTrue(encoded.contains("hello"), "GET response should contain body");
294+
assertTrue(encoded.contains("content-length: 5"));
295+
buf.release();
296+
297+
assertFalse(ch.finishAndReleaseAll());
298+
}
299+
300+
@Test
301+
public void testPostMethodHasNormalBody() throws Exception {
302+
// POST should also be METHOD_FLAG_NONE.
303+
EmbeddedChannel ch = new EmbeddedChannel(new HttpServerCodec());
304+
305+
assertTrue(ch.writeInbound(Unpooled.copiedBuffer(
306+
"POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 0\r\n\r\n", CharsetUtil.UTF_8)));
307+
308+
for (;;) {
309+
Object msg = ch.readInbound();
310+
if (msg == null) {
311+
break;
312+
}
313+
if (msg instanceof HttpContent) {
314+
((HttpContent) msg).release();
315+
}
316+
}
317+
318+
FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
319+
Unpooled.copiedBuffer("result", CharsetUtil.UTF_8));
320+
resp.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 6);
321+
assertTrue(ch.writeOutbound(resp));
322+
323+
ByteBuf buf = ch.readOutbound();
324+
String encoded = buf.toString(CharsetUtil.US_ASCII);
325+
assertTrue(encoded.contains("result"), "POST response should contain body");
326+
buf.release();
327+
328+
assertFalse(ch.finishAndReleaseAll());
329+
}
330+
331+
@Test
332+
public void testOverflowDrainsBeforeInlineRefill() throws Exception {
333+
// Verify that once overflow is activated, subsequent enqueues also go to overflow
334+
// until the overflow drains, keeping FIFO order correct.
335+
EmbeddedChannel ch = new EmbeddedChannel(new HttpServerCodec());
336+
337+
int totalRequests = 34; // 32 inline + 2 overflow
338+
339+
// Send 34 pipelined requests: position 33 (overflow) is HEAD.
340+
StringBuilder requests = new StringBuilder();
341+
for (int i = 0; i < totalRequests; i++) {
342+
if (i == 33) {
343+
requests.append("HEAD /").append(i).append(" HTTP/1.1\r\nHost: a\r\n\r\n");
344+
} else {
345+
requests.append("GET /").append(i).append(" HTTP/1.1\r\nHost: a\r\n\r\n");
346+
}
347+
}
348+
assertTrue(ch.writeInbound(Unpooled.copiedBuffer(requests.toString(), CharsetUtil.UTF_8)));
349+
350+
// Drain inbound.
351+
for (;;) {
352+
Object msg = ch.readInbound();
353+
if (msg == null) {
354+
break;
355+
}
356+
if (msg instanceof HttpContent) {
357+
((HttpContent) msg).release();
358+
}
359+
}
360+
361+
// Send responses for first 33 (all GET).
362+
for (int i = 0; i < 33; i++) {
363+
FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
364+
Unpooled.copiedBuffer("ok", CharsetUtil.UTF_8));
365+
resp.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 2);
366+
assertTrue(ch.writeOutbound(resp));
367+
ByteBuf buf = ch.readOutbound();
368+
String encoded = buf.toString(CharsetUtil.US_ASCII);
369+
assertTrue(encoded.contains("ok"), "GET response at position " + i + " should contain body");
370+
buf.release();
371+
}
372+
373+
// Response for position 33 — HEAD from overflow queue.
374+
HttpResponse headResp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
375+
headResp.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 42);
376+
assertTrue(ch.writeOutbound(headResp));
377+
assertTrue(ch.writeOutbound(LastHttpContent.EMPTY_LAST_CONTENT));
378+
379+
ByteBuf buf = ch.readOutbound();
380+
buf.release();
381+
382+
buf = ch.readOutbound();
383+
assertFalse(buf.isReadable(), "HEAD response from overflow queue body should be empty");
384+
buf.release();
385+
386+
assertFalse(ch.finishAndReleaseAll());
387+
}
388+
389+
@Test
390+
public void testPollFromEmptyQueueReturnsNone() throws Exception {
391+
// If a response is written without a matching request (unusual but defensive),
392+
// pollMethod should return METHOD_FLAG_NONE, so body is treated normally.
393+
EmbeddedChannel ch = new EmbeddedChannel(new HttpServerCodec());
394+
395+
// Write a response without any prior request.
396+
FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
397+
Unpooled.copiedBuffer("data", CharsetUtil.UTF_8));
398+
resp.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 4);
399+
assertDoesNotThrow(() -> ch.writeOutbound(resp));
400+
401+
ByteBuf buf = ch.readOutbound();
402+
assertNotNull(buf);
403+
String encoded = buf.toString(CharsetUtil.US_ASCII);
404+
assertTrue(encoded.contains("data"), "Response body should be present even without prior request");
405+
buf.release();
406+
407+
ch.finishAndReleaseAll();
408+
}
409+
177410
private static ByteBuf prepareDataChunk(int size) {
178411
StringBuilder sb = new StringBuilder();
179412
for (int i = 0; i < size; ++i) {

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.