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 — Batch decompressed buffers in HttpContentDecoder to reduce channelRea… · netty/netty@8e79ccd

File tree

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

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

Copy file name to clipboardExpand all lines: codec-http/src/main/java/io/netty/handler/codec/http/HttpContentDecoder.java
+60-1Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import io.netty.handler.codec.MessageToMessageDecoder;
2525
import io.netty.util.ReferenceCountUtil;
2626

27+
import java.util.ArrayDeque;
2728
import java.util.List;
2829

2930
/**
@@ -49,14 +50,35 @@ public abstract class HttpContentDecoder extends MessageToMessageDecoder<HttpObj
4950

5051
static final String IDENTITY = HttpHeaderValues.IDENTITY.toString();
5152

53+
/**
54+
* Default maximum number of decompressed bytes to accumulate before flushing downstream.
55+
* Balances pipeline efficiency (fewer channelRead events) with zip bomb protection (bounded memory).
56+
*/
57+
static final int DEFAULT_MAX_BATCH_BYTES = 16 * 1024;
58+
5259
protected ChannelHandlerContext ctx;
5360
private EmbeddedChannel decoder;
5461
private boolean continueResponse;
5562
private boolean needRead = true;
5663
private ByteBufForwarder forwarder;
64+
private final int maxBatchBytes;
5765

5866
public HttpContentDecoder() {
67+
this(DEFAULT_MAX_BATCH_BYTES);
68+
}
69+
70+
/**
71+
* @param maxBatchBytes maximum number of decompressed bytes to accumulate before flushing
72+
* downstream as a single {@link HttpContent}. Smaller values provide
73+
* better protection against zip bombs but produce more {@code channelRead}
74+
* events. Must be &gt; 0.
75+
*/
76+
public HttpContentDecoder(int maxBatchBytes) {
5977
super(HttpObject.class);
78+
if (maxBatchBytes <= 0) {
79+
throw new IllegalArgumentException("maxBatchBytes must be > 0: " + maxBatchBytes);
80+
}
81+
this.maxBatchBytes = maxBatchBytes;
6082
}
6183

6284
@Override
@@ -171,11 +193,13 @@ protected void decode(ChannelHandlerContext ctx, HttpObject msg, List<Object> ou
171193
} else {
172194
// call retain here as it will call release after its written to the channel
173195
decoder.writeInbound(c.content().retain());
196+
forwarder.flushDecompressed();
174197

175198
if (c instanceof LastHttpContent) {
176199
boolean notEmpty = decoder.finish();
177200
decoder = null;
178201
assert !notEmpty;
202+
forwarder.flushDecompressed();
179203
LastHttpContent last = (LastHttpContent) c;
180204
// Generate an additional chunk if the decoder produced
181205
// the last product on closure,
@@ -255,6 +279,9 @@ private void cleanup() {
255279
decoder = null;
256280
assert !nonEmpty;
257281
}
282+
if (forwarder != null) {
283+
forwarder.flushDecompressed();
284+
}
258285
}
259286

260287
private void cleanupSafely(ChannelHandlerContext ctx) {
@@ -270,6 +297,8 @@ private void cleanupSafely(ChannelHandlerContext ctx) {
270297
private final class ByteBufForwarder extends ChannelInboundHandlerAdapter {
271298

272299
private final ChannelHandlerContext targetCtx;
300+
private ArrayDeque<ByteBuf> pending;
301+
private int unflushedBytes;
273302

274303
ByteBufForwarder(ChannelHandlerContext targetCtx) {
275304
this.targetCtx = targetCtx;
@@ -289,8 +318,38 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) {
289318
buf.release();
290319
return;
291320
}
321+
int readableBytes = buf.readableBytes();
322+
if (unflushedBytes > 0 && unflushedBytes + readableBytes > maxBatchBytes) {
323+
flushDecompressed();
324+
}
325+
if (pending == null) {
326+
pending = new ArrayDeque<>(16);
327+
}
328+
pending.add(buf);
329+
unflushedBytes += readableBytes;
330+
}
331+
332+
void flushDecompressed() {
333+
if (pending == null || pending.isEmpty()) {
334+
return;
335+
}
292336
needRead = false;
293-
targetCtx.fireChannelRead(new DefaultHttpContent(buf));
337+
if (pending.size() == 1) {
338+
targetCtx.fireChannelRead(new DefaultHttpContent(pending.poll()));
339+
} else {
340+
ByteBuf last = pending.peekLast();
341+
ByteBuf merged = last.isDirect()
342+
? targetCtx.alloc().directBuffer(unflushedBytes)
343+
: targetCtx.alloc().heapBuffer(unflushedBytes);
344+
ByteBuf buf;
345+
while ((buf = pending.poll()) != null) {
346+
merged.writeBytes(buf);
347+
buf.release();
348+
}
349+
targetCtx.fireChannelRead(new DefaultHttpContent(merged));
350+
}
351+
unflushedBytes = 0;
294352
}
353+
295354
}
296355
}
Collapse file

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

Copy file name to clipboardExpand all lines: codec-http/src/main/java/io/netty/handler/codec/http/HttpContentDecompressor.java
+18Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,24 @@ public HttpContentDecompressor(boolean strict, int maxAllocation) {
8989
this.maxAllocation = checkPositiveOrZero(maxAllocation, "maxAllocation");
9090
}
9191

92+
/**
93+
* Create a new {@link HttpContentDecompressor}.
94+
*
95+
* @param strict if {@code true} use strict handling of deflate if used, otherwise handle it in a
96+
* more lenient fashion.
97+
* @param maxAllocation
98+
* Maximum size of the decompression buffer. Must be &gt;= 0. If zero, maximum size is not limited.
99+
* @param maxBatchBytes
100+
* Maximum number of decompressed bytes to accumulate before flushing downstream. Smaller values
101+
* provide better protection against zip bombs but produce more {@code channelRead} events.
102+
* Must be &gt; 0.
103+
*/
104+
public HttpContentDecompressor(boolean strict, int maxAllocation, int maxBatchBytes) {
105+
super(maxBatchBytes);
106+
this.strict = strict;
107+
this.maxAllocation = checkPositiveOrZero(maxAllocation, "maxAllocation");
108+
}
109+
92110
@Override
93111
protected EmbeddedChannel newContentDecoder(String contentEncoding) throws Exception {
94112
Channel channel = ctx.channel();
Collapse file

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

Copy file name to clipboard
+137Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
/*
2+
* Copyright 2026 The Netty Project
3+
*
4+
* The Netty Project licenses this file to you under the Apache License,
5+
* version 2.0 (the "License"); you may not use this file except in compliance
6+
* with the License. You may obtain a copy of the License at:
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations
14+
* under the License.
15+
*/
16+
package io.netty.handler.codec.http;
17+
18+
import io.netty.buffer.ByteBuf;
19+
import io.netty.channel.ChannelHandlerContext;
20+
import io.netty.channel.ChannelInboundHandlerAdapter;
21+
import io.netty.channel.embedded.EmbeddedChannel;
22+
import io.netty.util.ReferenceCountUtil;
23+
import org.junit.jupiter.api.Test;
24+
25+
import java.nio.charset.StandardCharsets;
26+
import java.util.concurrent.atomic.AtomicInteger;
27+
28+
import static org.junit.jupiter.api.Assertions.assertEquals;
29+
import static org.junit.jupiter.api.Assertions.assertNotNull;
30+
import static org.junit.jupiter.api.Assertions.assertTrue;
31+
32+
/**
33+
* Demonstrates that decompressing a single compressed HTTP content chunk produces an excessive
34+
* number of channelRead events due to ByteBufForwarder firing each decompressed buffer
35+
* individually through the pipeline instead of batching them.
36+
*
37+
* See https://github.com/netty/netty/issues/15852
38+
*/
39+
public class ExcessiveChunksTest {
40+
41+
@Test
42+
public void testDecompressionChunkCount() {
43+
// Step 1: Generate a large compressible payload (~150KB uncompressed)
44+
StringBuilder sb = new StringBuilder();
45+
sb.append("{\"items\":[");
46+
for (int i = 0; i < 1000; i++) {
47+
if (i > 0) {
48+
sb.append(',');
49+
}
50+
sb.append("{\"id\":").append(i)
51+
.append(",\"name\":\"Item ").append(i).append('"')
52+
.append(",\"description\":\"This is a sample description for item number ").append(i)
53+
.append(" which contains some text to make the response larger and more compressible.")
54+
.append(" The quick brown fox jumps over the lazy dog. Lorem ipsum dolor sit amet.\"")
55+
.append(",\"value\":").append(i * 1.5)
56+
.append(",\"active\":").append(i % 2 == 0)
57+
.append('}');
58+
}
59+
sb.append("]}");
60+
byte[] payload = sb.toString().getBytes(StandardCharsets.UTF_8);
61+
62+
// Step 2: Compress the payload using HttpContentCompressor (server-side)
63+
EmbeddedChannel compressionChannel = new EmbeddedChannel(new HttpContentCompressor());
64+
DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
65+
req.headers().set(HttpHeaderNames.ACCEPT_ENCODING, "gzip");
66+
compressionChannel.writeInbound(req);
67+
68+
ByteBuf payloadBuf = compressionChannel.alloc().buffer(payload.length);
69+
payloadBuf.writeBytes(payload);
70+
DefaultFullHttpResponse fullResponse = new DefaultFullHttpResponse(
71+
HttpVersion.HTTP_1_1, HttpResponseStatus.OK, payloadBuf);
72+
fullResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json");
73+
fullResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, payload.length);
74+
compressionChannel.writeOutbound(fullResponse);
75+
compressionChannel.finish();
76+
compressionChannel.releaseInbound();
77+
78+
// Read compressed output: headers + all content merged into a single buffer
79+
HttpMessage compressedMessage = null;
80+
ByteBuf compressedBody = compressionChannel.alloc().buffer();
81+
boolean lastSeen = false;
82+
while (true) {
83+
HttpObject obj = compressionChannel.readOutbound();
84+
if (obj == null) {
85+
break;
86+
}
87+
if (obj instanceof HttpMessage) {
88+
compressedMessage = (HttpMessage) obj;
89+
}
90+
if (obj instanceof HttpContent) {
91+
HttpContent content = (HttpContent) obj;
92+
compressedBody.writeBytes(content.content());
93+
if (obj instanceof LastHttpContent) {
94+
lastSeen = true;
95+
}
96+
content.release();
97+
}
98+
}
99+
assertNotNull(compressedMessage);
100+
assertTrue(lastSeen);
101+
assertTrue(compressedBody.isReadable(), "Compressed body should not be empty");
102+
103+
// Step 3: Decompress and count channelRead events on the downstream handler
104+
final AtomicInteger channelReadCount = new AtomicInteger();
105+
long[] totalBytes = {0};
106+
107+
EmbeddedChannel decompressChannel = new EmbeddedChannel(
108+
new HttpContentDecompressor(0),
109+
new ChannelInboundHandlerAdapter() {
110+
@Override
111+
public void channelRead(ChannelHandlerContext ctx, Object msg) {
112+
if (msg instanceof HttpContent) {
113+
channelReadCount.incrementAndGet();
114+
totalBytes[0] += ((HttpContent) msg).content().readableBytes();
115+
}
116+
ReferenceCountUtil.release(msg);
117+
}
118+
});
119+
120+
// Feed the compressed response as: headers + single content chunk
121+
decompressChannel.writeInbound(compressedMessage);
122+
decompressChannel.writeInbound(new DefaultLastHttpContent(compressedBody));
123+
decompressChannel.finish();
124+
125+
// Verify all data was decompressed correctly
126+
assertEquals(payload.length, totalBytes[0],
127+
"Total decompressed bytes should match original payload size");
128+
129+
// With batching (default 16KB), a ~271KB payload should produce significantly fewer content chunks
130+
// than the 74 that the unbatched ByteBufForwarder produced.
131+
// See https://github.com/netty/netty/issues/15852
132+
assertTrue(channelReadCount.get() <= 25,
133+
"Decompression should batch output to reduce channelRead events. Got " +
134+
channelReadCount.get() + " content chunks for a ~" + (payload.length / 1024) +
135+
"KB payload (expected <= 25 with default 16KB batch size).");
136+
}
137+
}

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.