Repository navigation
New decompressor API - #15667
New decompressor API#15667yawkat wants to merge 298 commits into
Conversation
|
@normanmaurer I've added new logic that allows a number of buffers to be forwarded before a readComplete, and a test. I hope that works for you. The logic is getting complicated though. PTAL. I've also changed the handler API to create the decompressor lazily, in handlerAdded. This looks a bit odd (you pass the decompressor builder, not the decompressor, to the handler) but I think it works as an API and it's safer. |
|
I've added a HttpContentDecoder and -decompressor replacement, based on the BackpressureDecompressionHandler. I've also deprecated all the old decoders. I still need to migrate DelegatingDecompressorFrameListener. It is a bit more difficult because it uses a different flow control mechanism. Probably it needs an independent Decompressor-based implementation, not based on BackpressureDecompressionHandler. Finally, I changed the decompressor API a little bit so that the alloc is required by the .build call, not when creating the builder. This complements the change in 9279fc0. Now, the BackpressureDecompressionHandler will use the alloc from the context, and you don't need to manually pass in the alloc at all before that. |
|
Okay, I rebuilt the decompression codecs again. HTTP/1.1 pipelining has a lot of edge cases to handle. I decided to build a central I've also built a Http2FrameListener based on the new decompressors. It appears to be a lot simpler than the ChannelHandler approach, unless I missed some edge cases. I'm going on vacation for a few days so I might be slow to answer now. |
|
Hey folks, do you think this will get merged anytime soon? |
|
There's also merge conflicts that need to be fixed. Please ping me when I should take a look again. |
|
@chrisvest updated |
There was a problem hiding this comment.
Pull request overview
This PR introduces a new backpressure-aware decompression API (Decompressor) and integrates it into new handlers for HTTP/1.1 and HTTP/2, aiming to reduce overhead (no EmbeddedChannel indirection) and improve zip-bomb/backpressure behavior.
Changes:
- Added
DecompressorAPI plus a shared backpressure-aware handler base (AbstractBackpressureDecompressionHandler) and concrete handler (BackpressureDecompressionHandler). - Implemented new
Decompressorimplementations for multiple codecs (zlib/jzlib/jdkzlib, brotli, zstd, snappy, lzf, lz4, fastlz, bzip2) and deprecated the older decoder counterparts. - Added HTTP/1.1
HttpDecompressionHandler, HTTP/2DecompressingFrameListener, and expanded tests/fixtures to cover the new behavior.
Reviewed changes
Copilot reviewed 68 out of 69 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
| testsuite-common/src/main/java/io/netty/util/test/LeakPresenceExtension.java | Adjusts leak-scope lifecycle to prevent JUnit auto-closing scopes. |
| pom.xml | Updates JUnit version property. |
| codec-http2/src/main/java/io/netty/handler/codec/http2/DecompressingFrameListener.java | Adds a new HTTP/2 frame listener that decompresses DATA frames using Decompressor with backpressure. |
| codec-http2/src/test/java/io/netty/handler/codec/http2/DecompressingFrameListenerTest.java | Adds unit tests for HTTP/2 decompression/backpressure listener behavior. |
| codec-http2/src/test/java/io/netty/handler/codec/http2/DataCompressionHttp2Test.java | Refactors test hook to allow swapping decompression frame listener implementations. |
| codec-http2/src/test/java/io/netty/handler/codec/http2/DataCompressionBackpressureHttp2Test.java | Adds variant test using the new DecompressingFrameListener. |
| codec-http/src/main/java/io/netty/handler/codec/http/HttpDecompressionHandler.java | Introduces HTTP/1.1 decompression handler built on backpressure-aware decompression base. |
| codec-http/src/test/java/io/netty/handler/codec/http/HttpDecompressionHandlerTest.java | Adds HTTP/1.1 decompression/backpressure tests for the new handler. |
| codec-http/src/test/java/io/netty/handler/codec/http/HttpContentDecompressorTest.java | Refactors tests to allow injecting a decompressor implementation (old/new). |
| codec-http/src/test/java/io/netty/handler/codec/http/HttpContentDecoderTest.java | Refactors tests to allow injecting a decompressor implementation (old/new). |
| codec-http/src/main/java/io/netty/handler/codec/http/HttpContentDecompressor.java | Marks old decompressor deprecated in favor of HttpDecompressionHandler. |
| codec-http/src/main/resources/META-INF/native-image/io.netty/netty-codec-http/generated/handlers/reflect-config.json | Adds native-image reflect config for HttpDecompressionHandler. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/Decompressor.java | Adds core decompressor contract and builder type. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/DefensiveDecompressor.java | Adds contract-enforcing wrapper for decompressor implementations. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/InputBufferingDecompressor.java | Adds common input-cumulation base for incremental decompressors. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/BackpressureGauge.java | Adds shared accounting/configuration for backpressure limits. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/AbstractBackpressureDecompressionHandler.java | Adds shared backpressure-aware handler logic for decompressing pipelines. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/BackpressureDecompressionHandler.java | Adds concrete channel handler wrapping a Decompressor into a pipeline element. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/ZlibCodecFactory.java | Adds ZlibDecompressorBuilder to produce new decompressor instances. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/ZlibDecompressor.java | Adds zlib decompressor base/builder config shared by implementations. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/JdkZlibDecompressor.java | Adds new JDK inflater-based Decompressor. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/JZlibDecompressor.java | Adds new JZlib-based Decompressor. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/BrotliDecompressor.java | Adds new brotli Decompressor. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/ZstdDecompressor.java | Adds new zstd Decompressor. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/SnappyFrameDecompressor.java | Adds new snappy framing Decompressor. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/LzfDecompressor.java | Adds new lzf Decompressor. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/Lz4FrameDecompressor.java | Adds new lz4 frame Decompressor. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/FastLzFrameDecompressor.java | Adds new fastlz frame Decompressor. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/Bzip2Decompressor.java | Adds new bzip2 Decompressor. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/BrotliEncoder.java | Adjusts brotli encoder finishing/closure future handling. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/BrotliDecoder.java | Deprecates old decoder in favor of new decompressor + handler. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/ZstdDecoder.java | Deprecates old decoder in favor of new decompressor + handler. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/SnappyFrameDecoder.java | Deprecates old decoder in favor of new decompressor + handler. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/LzfDecoder.java | Deprecates old decoder in favor of new decompressor + handler. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/Lz4FrameDecoder.java | Deprecates old decoder in favor of new decompressor + handler. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/FastLzFrameDecoder.java | Deprecates old decoder in favor of new decompressor + handler. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/Bzip2Decoder.java | Deprecates old decoder in favor of new decompressor + handler. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/JdkZlibDecoder.java | Deprecates old decoder in favor of new decompressor + handler. |
| codec-compression/src/main/java/io/netty/handler/codec/compression/JZlibDecoder.java | Deprecates old decoder in favor of new decompressor + handler. |
| codec-compression/src/test/java/io/netty/handler/codec/compression/AbstractDecompressorTest.java | Adds shared decompressor test base for builder-based decompressor implementations. |
| codec-compression/src/test/java/io/netty/handler/codec/compression/BackpressureDecompressionHandlerTest.java | Adds tests for the new backpressure-aware decompression handler. |
| codec-compression/src/test/java/io/netty/handler/codec/compression/*DecompressorTest.java | Adds decompressor tests for newly introduced decompressor implementations. |
| codec-compression/src/test/java/io/netty/handler/codec/compression/DecompressorHandlerTest.java | Adds tests/integration tests for BackpressureDecompressionHandler wired with each decompressor. |
| codec-compression/src/test/java/io/netty/handler/codec/compression/*DecoderTest.java | Refactors decoder tests to support handler-based decompression variants where applicable. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
I found one likely regression in the new HTTP/2 decompression path: In For padded DATA frames, those padding bytes never seem to get returned to the upstream flow controller. Under enough padded traffic, that would permanently shrink the local receive window and can stall the stream/connection. I think this needs to preserve padding in the accounting path, and it would be good to add a test that exercises non-zero padding, since the new |
Introduce the core Decompressor contract, defensive state validation, and input-buffering helper. Add a FastLZ implementation as the first decompressor to exercise the new API without introducing the backpressure handler yet. The new API is marked unstable and links to the decompression migration tracking issue until the follow-up PRs land. Co-Authored-By: multicode <[email protected]>
Document that decompressor callers need to observe the status before invoking status-specific operations. Tighten InputBufferingDecompressor resource handling when status checks fail after output is produced, clear cumulation on close, and add tests for these cases. Co-Authored-By: multicode <[email protected]>
Motivation: AutoScalingEventExecutorChooserFactory suspends idle executors and resets their busy/idle cycle counters once a scale-down decision is made, so they need a fresh patience period before triggering another scaling decision. The scale-up path had no equivalent reset: once an executor's busy-cycle counter crossed scalingPatienceCycles, it kept incrementing on every following cycle it remained busy, so the same executor could keep triggering further scale-ups on its own without any additional executor becoming busy. This causes the group to overshoot the number of active executors that the actual load justifies, and is the cause of intermittent CI failures in AutoScalingEventExecutorChooserFactoryTest.testScaleUp (e.g. expected 2 active executors but found 3). Modifications: - Track the executors that are consistently busy in a list, mirroring the existing consistentlyIdleChildren list, instead of only counting them. - After using that list to decide on a scale-up, reset the busy and idle cycle counters of the contributing executors so each one needs another full patience period of sustained load before it can justify a further scale-up. Result: A single sustained busy executor scales the group up exactly once per patience period instead of repeatedly ramping up on its own.
…kiness (#17540) Motivation: We saw sporadic CI failures in Http2ConnectionRoundtripTest where a CountDownLatch.await(...) timed out even though the connection was behaving correctly. Each test method spins up two MultiThreadIoEventLoopGroups with the default thread count (2 * available processors), even though the test only exercises LocalChannel and never needs more than one thread per group. Combined with this module running JUnit5 tests concurrently, this can create significant thread oversubscription and starve the event loop long enough to blow the 15 second timeout under load. This was reproduced locally by running many instances of the test concurrently while the machine was under heavy CPU load, which reliably reproduced the same kind of timeout failure seen on CI. Modifications: - Pin the client and server MultiThreadIoEventLoopGroups in bootstrapEnv(...) to a single thread each instead of the default, since LocalChannel does not benefit from extra threads. - Increase DEFAULT_AWAIT_TIMEOUT_SECONDS from 15 to 30 seconds to give more headroom under CI load. Result: Less flaky Http2ConnectionRoundtripTest.
…prefix is incomplete (#17550) Motivation: Since #14050 two incomplete length prefix cases are no longer treated as "need more data" by `ProtobufVarint32FrameDecoder`: - If only 3 bytes are readable and all of them have the continuation bit set, `readRawVarint24` returned the partial value and left the readerIndex advanced. `decode()` then used the low 21 bits of the real length. When these bits are 0, i.e. the message length is an exact multiple of 2 MiB, an empty frame was emitted, the prefix bytes were consumed and the rest of the stream was decoded from the wrong position. A single 2 MiB message split after the third prefix byte was delivered as about 2 million bogus frames without any exception. - If exactly 4 bytes are readable and all of them have the continuation bit set, `readRawVarint40` threw a `CorruptedFrameException` although the fifth byte may simply not have been received yet. Before #14050 both cases reset the readerIndex and returned 0. Modifications: - `readRawVarint24` resets the readerIndex and returns 0 when the third byte still has the continuation bit set. - `readRawVarint40` returns 0 without moving the readerIndex when only 4 bytes are readable, and only throws when the fifth byte is malformed. - Add tests that split 1 to 5 byte length prefixes at every position, including lengths that are exact multiples of 2 MiB. Result: `ProtobufVarint32FrameDecoder` produces the same frames regardless of how the length prefix is fragmented across reads. Fixes #17549.
… disabled (#17537) Motivation: QpackEncoder.sectionAcknowledgment(...) only had an assert to guard against streamSectionTrackers being null, which is a no-op unless the JVM runs with -ea. When a peer negotiates SETTINGS_QPACK_MAX_TABLE_CAPACITY=0 (the RFC 9204 default), configureDynamicTable(...) never allocates streamSectionTrackers. A peer can then send a single Section Acknowledgment instruction (0x80) on its QPACK decoder stream and trigger a NullPointerException, which escapes the QpackException catch in QpackDecoderHandler and tears down the connection. Modification: Replace the assert with an explicit null check that throws the existing INVALID_SECTION_ACKNOWLEDGMENT QpackException, matching the pattern already used by the sibling streamCancellation(...) method. Result: A Section Acknowledgment received while the dynamic table is disabled is now reported as a QpackException instead of crashing the connection with an unchecked NullPointerException.
Motivation: decode() only checked for 3 readable bytes before parsing, but it unconditionally consumes a 3-byte code plus a 4th separator byte. A line consisting of only a 3-digit code (e.g. "250\r\n") passed the guard and then threw a raw IndexOutOfBoundsException from readByte() instead of the intended DecoderException. Modifications: Require 4 readable bytes and add a regression test. Result: No more IOOBE
…ion (#17532) Motivation: AbstractSniHandler.extractSniHostname() reads the session_id, cipher_suites and compression_methods lengths from a ClientHello and advances the parse offset by each of these attacker-controlled values, without re-checking the offset against the buffer bounds before the next read. A single crafted, non-fragmented ClientHello with an oversized session_id length (e.g. 0xFF) pushes the offset past the end of the buffer and triggers an IndexOutOfBoundsException. Modification: Re-validate the offset against the end of the buffer before each of the three interior reads, symmetric to the bounds checks already used by the extensions loop further down. Result: Malformed ClientHello messages no longer trigger an IndexOutOfBoundsException while parsing the SNI extension.
…rameCodec (#17523) Motivation: decodeFrame() and decodeSettings() checked that the buffer held at least the frame's declared payload length, but the length of the variable-length integer(s) inside that payload is derived from the integer's own first byte, independent of the declared payload length. A CANCEL_PUSH/GO_AWAY/MAX_PUSH_ID/PUSH_PROMISE frame (or a SETTINGS key/value) whose declared length was shorter than what its own prefix bits require caused readVariableLengthInteger() to call readLong()/readInt()/etc. past what was verified available, throwing a raw IndexOutOfBoundsException instead of failing the connection with H3_FRAME_ERROR. Modifications: Validate the integer's encoded length against the declared payload length before reading it, and add regression tests for each affected frame type plus both SETTINGS key and value lengths. Result: Correctly handle varint lenght parsing
Motivation: QuicHeaderParser read the destination/source connection-id length bytes of a long-header QUIC packet without first verifying enough bytes were readable, unlike every other read in the class. A truncated datagram could trigger a raw IndexOutOfBoundsException instead of the expected QuicException, or silently read stale bytes from an over-allocated buffer. Modifications: Add the missing checkReadable() guards and a regression test. Result: No more risk of IOOBE
…17495) Motivation: In DefaultHttp2ConnectionDecoder.onPushPromiseRead(), the promised stream was only reserved via reservePushStream() after the Http2PromisedRequestVerifier checks (isAuthoritative/isCacheable/ isSafe) passed. If the verifier rejected the promised request, the method threw before the stream was ever reserved, so the connection lost all bookkeeping of that stream ID's existence. Modification: - Move the reservePushStream() call ahead of the verifier checks in onPushPromiseRead(), so the promised stream is reserved as soon as the parent stream state is validated, and any subsequent verifier rejection fails an already-reserved stream instead of leaving no record of it. - Add a unit test that rejects a push promise via a custom verifier and asserts the stream was still reserved. Result: The promised stream ID's existence is always tracked once a PUSH_PROMISE is otherwise valid enough to reach verification.
Motivation: This is an additional fix for PR #17523. The check added with PR #17523 reads the first byte of the variable length integer, a frame with a declared zero length doesn't have such byte. Modification: - Add a payload length check - Add junit tests Result: Frames with zero length payloads fail with H3_FRAME_ERROR
…ng netty.io over the network (#17566) Motivation: testSharedDNSCacheAcrossEventLoops resolved the real netty.io hostname over the network to verify that DnsAddressResolverGroup shares its DNS cache across EventLoops. netty.io is fronted by Cloudflare, and live queries can return different edge IPs on different lookups, which made the assertSame check flaky regardless of whether the cache was actually shared. Modification: Use a TestDnsServer (as already done in DnsNameResolverTest) backed by a RecordStore that always returns a single, fixed A record for netty.io, and point the resolver's nameServerProvider at it. This makes both resolutions deterministic so the assertion only depends on the cache-sharing behavior under test. Result: testSharedDNSCacheAcrossEventLoops no longer depends on the live DNS answer for netty.io and is no longer flaky due to external network behavior.
…17570) Motivation: We should construct the LocalAddress by passing in a Class. This way we are sure the LocalAddress is really unique and so we don't get into any clashes when running parallel tests. Modifications: Change usage of new LocalAddress(String) to new LocalAddress(Class). Result: More stable CI
…7569) ### Motivation `notifyConnect()` completes the acquire `Promise` with `trySuccess(...)` and releases the `Channel` if already completed. `notifyHealthCheck()`, the reuse path, still uses `setSuccess(...)`. `doHealthCheck` runs via `loop.execute(...)` when `acquire()` is called off its event loop, so a cancel can land while that task is queued, even with the stock `ACTIVE` checker. `setSuccess(...)` then throws into `closeAndFail(...)`: a healthy pooled `Channel` is closed and its `channelAcquired(...)` gets no `channelReleased(...)`. #17287 gave `FixedChannelPool` this guard. ### Modification `notifyHealthCheck()` mirrors `notifyConnect()`, plus a regression test on a hand-completed health check. ### Result Reverting just the source hunk fails that test on `releasedCount()`, 2 expected, 1 seen. With it, 34/34.
Motivation: When IORING_RECVSEND_BUNDLE is enabled, a single completion can report a byte count spanning multiple buffer-ring entries. useBuffer(...) sliced the ring entry using that raw total instead of clamping it to the entry's own writable capacity, so retainedSlice(...) threw an IndexOutOfBoundsException on the io_uring event-loop thread. The exception propagated out before the buffer-ring bookkeeping (freeing the bid, releasing the buffer, decrementing usableBuffers) ran, leaking a direct buffer and leaving the channel's multishot receive armed to repeat the fault on every subsequent oversized burst. Modifications: Clamp the slice length and writerIndex advance in useBuffer(...) to byteBuf.writableBytes(), matching the method's documented contract that callers loop over the remainder via nextBid(...). Add a regression test exercising useBuffer(...) directly with a read larger than a single entry's capacity, and switch the test class to AssertJ assumptions. Result: useBuffer(...) no longer throws when a bundle completion spans more than one ring entry.
…seudoHeaders is enabled (#17460) Motivation: RFC 9113, 8.4.1 requires a PUSH_PROMISE field block to carry a complete set of request pseudo-header fields, and mandates a PROTOCOL_ERROR on the promised stream if it does not. DefaultHttp2ConnectionDecoder never performed this check, so even with validateRequiredPseudoHeaders enabled an empty/incomplete promised request was accepted and the promised stream reserved. Modifications: - Validate push promise headers when enabled - Add unit tests Result: Fixes #17439
#17571) Motivation: Http3FrameCodec.enforceExactIdLength() (added in #17523) rejects CANCEL_PUSH, GO_AWAY and MAX_PUSH_ID frames whose declared payload length does not exactly match the encoded width of their single push-id/stream-id varint. That fix already covers a declared length shorter than the varint's width, but there was no test asserting the opposite direction: a declared length longer than the varint's width, which would otherwise leave unread trailing bytes in the buffer to be mis-parsed as the type/length/payload of a bogus subsequent frame, desynchronizing the control stream. Modifications: Add parameterized tests for all three frame types that send a payload declared as the maximum 8 bytes but containing only a 1-byte varint followed by 7 trailing bytes shaped like a HEADERS frame header. Assert the connection is closed with H3_FRAME_ERROR and that no frame, legitimate or smuggled, is produced from the trailing bytes. Result: Explicit regression coverage for the control-stream desynchronization scenario. This is a followup to #17523
Motivation: We create a lot of EventLoopGroups with very short life-time when running our tests. By default these use 2 * cpu's EventLoops. This is quite wasteful on shared infrastructure that runs our CI. Modifications: Use 2 EventLoops per EventLoopGroup by default if not manual specified Result: Less resource usage while running our CI builds
…AndTrailingHeaders (#17590) Motivation: HttpToHttp2ConnectionHandlerTest.testChunkedRequestWithBodyAndTrailingHeaders writes two HttpContent chunks for the same stream and asserted that exactly one onDataRead(...) call was observed on the server side with the two payloads concatenated into a single DATA frame. Whether the two writeData(...) calls get merged into one physical DATA frame by DefaultHttp2RemoteFlowController's pending-write-queue coalescing is a timing-dependent internal optimization, not a guarantee of the codec. When the merge does not happen in time, two separate DATA frames are delivered instead, which is spec-compliant but failed the test's strict Mockito verify(times(1)) expectation. Modifications: - Verify onDataRead(...) is invoked atLeastOnce() instead of exactly once - Assert the concatenation of all received buffers matches the sent payload instead of assuming a single buffer Result: The test no longer depends on the timing of the flow controller's DATA frame coalescing and reliably passes regardless of whether the two chunks are delivered as one or two DATA frames.
…teStreamException (#17470) Motivation: RFC 9113, Section 5.4 states that implementations SHOULD report at most one stream and one connection error as a result of processing a single condition, even if multiple errors are discovered. When DefaultHttp2LocalFlowController accumulates per-stream failures (e.g. while applying a new SETTINGS initial window size) into a single CompositeStreamException, Http2ConnectionHandler.onError iterated all contained StreamExceptions and wrote an RST_STREAM for each one, exceeding the recommended limit of one stream error per result. Modifications: - Http2ConnectionHandler.onError only reports the first StreamException contained in a CompositeStreamException for a specific stream instead of iterating and reporting every one of them. - Add unit tests Result: Only one RST_STREAM is written per CompositeStreamException, in line with the RFC 9113 recommendation.
…17597) Motivation: testSslException and testFireChannelReadAfterHandshakeSuccess only released the server/client SslContext on the happy path, after latch.await() returned successfully. If an exception was thrown earlier (for example while binding or connecting), the SslContext and the native OpenSSL key material it holds were never released explicitly, and cleanup would only happen once the JVM finalizer ran. This races with the leak presence detector's afterAll check and can be reported as a flaky memory leak in this test class. Modifications: - Release the SslContext instances in a finally block so they are always released, even if an exception is thrown. Result: Fix possible SslContext leak in unit tests.
…ventLoop (#17481) Motivation: The unification done in #13991/#14557 replaced the per-transport ioRatio scheduling with a fixed maxTaskProcessingQuantumMs cap on task processing before returning to IO. Under sustained load the task queue is never empty, so the event loop can spend up to the full quantum on tasks every iteration regardless of how little time was just spent on IO, delaying IO servicing (and so response completion) for a minority of requests. This was observed as an elevated mean (but not median) round-trip latency after upgrading from 4.1 to 4.2, which went away on rollback. Modifications: - Add back a volatile ioRatio field and functional getIoRatio()/ setIoRatio(int) on SingleThreadIoEventLoop, configurable via the new io.netty.eventLoop.ioRatio system property (default 100, which preserves the current fixed-quantum behaviour unchanged). - When ioRatio < 100, size each iteration's task budget as ioTime * (100 - ioRatio) / ioRatio, capped by maxTaskProcessingQuantumNs, matching the pre-4.2 NioEventLoop formula while keeping the existing quantum as a safety upper bound. - Add setter / getter to MultiThreadIoEventLoopGroup so it is supported globally Result: Users hitting the 4.2 scheduling regression can restore proportional IO/task balancing with a single setIoRatio(50) call (or the new system property), with no change in behaviour for anyone who doesn't opt in.
…nnection (#17594) Motivation: Http2Connection.PropertyKey instances could only be created via Http2Connection.newKey(), which ties every key to the specific connection instance that created it. This makes it impossible to share a key, e.g. as a static field, across multiple Http2Connection instances, or to create a key before an Http2Connection instance is even available. Modifications: - Add a static factory method that returns a key which is not associated with any particular Http2Connection and so can be used with the streams of any connection - Let DefaultStream dispatch on the concrete key type - Add tests covering both key kinds, including cross-connection rejection of connection-bound keys and sharing of static keys across connections Result: It is now possible to create an Http2Connection.PropertyKey without having access to an Http2Connection instance, while keys created via Http2Connection.newKey() keep their existing fast-path performance characteristics.
…an initialBytesToStrip (#17606) Motivation: When the adjusted frame length is less than `initialBytesToStrip`, `LengthFieldBasedFrameDecoder` throws a `CorruptedFrameException` without resetting `frameLengthInt`. Every following `decode(...)` call then skips reading the length field of the next frame, sees the same short frame length again, and throws again. `frameLength` is `0` in those calls, so no bytes are skipped either. One malformed frame therefore makes every later frame on the connection fail (`Adjusted frame length (0) is less than initialBytesToStrip: ...`). The same happens on the first malformed frame if its length field and its content arrive in separate reads. All the other error paths of the decoder reset their state and go on with the next frame. This regressed in #12173, which cached the frame length in `frameLengthInt` but only reset it on the success path. Modification: - Reset `frameLengthInt` before failing, and skip the frame using `frameLengthInt` instead of the local `frameLength`, which is `0` when the length field was read by an earlier call. - Add two tests: the malformed frame in one read, and its length field and content in separate reads. Both fail without the change (with the exception above on the following valid frame) and pass with it. Result: The decoder fails the malformed frame and then decodes the following frames again. `codec-base` tests: 352, 0 failures.
…d cancellation … (#17601) Auto-port of #17589 to 4.2 Cherry-picked commit: bcc636d --- …of scheduled tasks Motivation: Cancelling a scheduled task removes it by resubmitting it via scheduleRemoveScheduled(), which can land in the task queue in the narrow window between run() deciding it can suspend and doStartThread() re-checking canSuspend() afterwards. doStartThread() only knew how to recover from a task racing in once the state had already reached ST_SUSPENDED; if the re-check simply saw canSuspend() return false while the state was still ST_SUSPENDING/ST_SUSPENDED, it fell through and treated the situation as if run() had returned without confirming shutdown, forcing the executor into a real shutdown even though nobody requested one. Once terminated, trySuspend() can never succeed again, so a caller looping on trySuspend() (as recommended when removal of a cancelled scheduled task may be lazy) spins until it times out. Modifications: - doStartThread() now goes around the loop again instead of shutting down when canSuspend() is false but the state is still ST_SUSPENDING/ST_SUSPENDED, letting run() pick up whatever raced in. - Add SingleThreadEventExecutorTest.testSuspendDoesNotRaceWithCancelledScheduledTask, which repeats the schedule/suspend/cancel sequence many times to make the race reproducible. Result: Cancelling a scheduled task while an executor is suspending no longer risks a spurious shutdown. Co-authored-by: Norman Maurer <[email protected]>
…'s own internal NIO buffer (#17618) ### Motivation: `ByteBuf.setBytes(int, ByteBuffer)` may be called with the buffer's own internal NIO buffer as the source, which callers can obtain through `ByteBuf.internalNioBuffer(int, int)`: Implementations obtain their destination through `internalNioBuffer()`, which calls `clear()` on the cached instance. When the source is that cached instance, the call resets the caller's position and limit before they are read, so the copy is done with the wrong offsets. `UnpooledDirectByteBuf` already gets this right — it duplicates before calling internalNioBuffer(...), we should align with it: https://github.com/netty/netty/blob/cd967a41cc8b930c21286348a526196e8e10a7e1/buffer/src/main/java/io/netty/buffer/UnpooledDirectByteBuf.java#L610-L612 ### Modification: * `PooledDirectByteBuf.setBytes(int, ByteBuffer)`: move the `src == tmpNioBuf` check before `internalNioBuffer()`. * `AdaptiveByteBuf.setBytes(int, ByteBuffer)`: add the same check, before `internalNioBuffer()`. ### Result: `setBytes(int, ByteBuffer)` copies the requested range for every allocator, whether or not the source is the buffer's own internal NIO buffer. The new test fails before this change on `AdaptiveByteBufAllocatorTest` and on `PooledByteBufAllocatorTest` when run with `-Dio.netty.noUnsafe=true`; it passes on both afterwards.
…ariants (#17620) Motivation: `AdaptiveByteBuf.getBytes(int, GatheringByteChannel, int)` and `AdaptiveByteBuf.getBytes(int, FileChannel, long, int)` do not call `checkIndex(index, length)`, unlike other `ByteBuf` implementations. These methods write from the cached `tmpNioBuf`, whose limit is `maxFastCapacity` (the size of the underlying segment) rather than `capacity()`. An out-of-bounds request that still fits within the segment is therefore not rejected: instead of throwing `IndexOutOfBoundsException`, the buffer silently writes bytes located beyond its own capacity to the channel. Modification: Add the missing `checkIndex(index, length)` to both methods, and add tests covering both channel variants. Result: `AdaptiveByteBuf` no longer reads past its capacity, and throws `IndexOutOfBoundsException` like the other `ByteBuf` implementations.
Motivation: Most of this PR has been split out and merged to 4.2 (#16745, #17145-#17155), and the backpressure handler is under review in #17161. The split versions received review fixes that this branch does not have, which left the PR conflicting with 4.2 in every decompressor. Modification: * Take the merged 4.2 decompressor implementations and the #17161 version of the backpressure handler infrastructure. * Re-apply the remaining unmerged parts of this PR on top: HTTP/1.1 HttpDecompressionHandler, HTTP/2 DecompressingFrameListener, their tests, and deprecation of the legacy decoders. * Drop JZlib support (JZlibDecompressor, ZlibDecompressor base class, ZlibCodecFactory decompressor builder). HttpDecompressionHandler uses JdkZlibDecompressor directly. * Restore BackpressureGauge.relieveBackpressure(long), which #17161 removed but DecompressingFrameListener needs for HTTP/2 flow-control credit. Result: The PR applies cleanly on 4.2 again and only carries the unmerged parts of #16743. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… the rebuilt tree)
🚨 TestLens detected 2 failed tests 🚨Here is what you can do:
Test SummaryBuild PR / linux-x86_64-java24 build > Netty/Common
Build PR / macos-x86_64-java11-boringssl build > Netty/Transport/Native/KQueue
🏷️ Commit: 9d6a5c7 Test FailuresSingleThreadEventExecutorTest > testSuspendDoesNotRaceWithCancelledScheduledTask() (Netty/Common in Build PR / linux-x86_64-java24 build)
KQueueDatagramUnicastIPv6MappedTest > testSimpleSendWithConnect(TestInfo) (Netty/Transport/Native/KQueue in Build PR / macos-x86_64-java11-boringssl build)Rerun ControlsSelect tests to mute in this pull request:
Reuse successful test results:
Click the checkbox to trigger a rerun:
Learn more about TestLens at testlens.app/docs. |
Motivation:
The current decompression decoders have a few issues:
Modification:
DecompressorAPI not based onChannelHandler. It is similar in design to the brotli API, with separate operations for adding input and removing output.BackpressureDecompressionHandlerthat uses the newDecompressorAPI.Result:
Lower overhead, better backpressure handling.
Work yet to be done:
BackpressureDecompressionHandlerHttpContentDecoderbased on the new decompressors