Add response body flow control - #2318
Merged
hyperxpro merged 12 commits intoAug 31, 2026
Merged
Conversation
hyperxpro
requested changes
Aug 26, 2026
Expose a thread-safe response body control after final response headers so handlers can suspend, resume, or cancel transport reads without coupling AHC to a streaming API. Integrate the control with HTTP/1.1 and HTTP/2, pause network read timeouts while reads are intentionally suspended, and keep request timeouts active. Make completion, cancellation, callback aborts, and channel teardown restore transport state exactly once. Cover backpressure, cancellation, timeout, callback failures, and connection reuse for both protocols. OpenAI Codex on behalf of Matthias Kurz. Co-Authored-By: OpenAI Codex <codex@openai.com>
Return connection-level receive credit as DATA frames arrive while preserving per-stream flow control for application backpressure. This prevents one suspended response from starving siblings on the same multiplexed connection. Document that aggregate queued data can scale with the number of suspended streams and point users to the initial-window and concurrent-stream controls. Preserve Netty's client shutdown behavior in the custom frame-codec builder. Cover sibling progress, repeated cancellation, and the retained per-stream window bound. OpenAI Codex on behalf of Matthias Kurz. Co-Authored-By: OpenAI Codex <codex@openai.com>
Store each response body control on its response future instead of its transport channel. Replays can then replace the control without leaving a suspended channel behind, and calls on a stale control become harmless. Keep recoverable exception paths alive until their replay decision is made, avoid the control lookup on the normal auto-read path, and tolerate event loop shutdown racing with late control calls. Cover replay replacement, old-channel draining, stale controls, and calls made after client shutdown. OpenAI Codex on behalf of Matthias Kurz. Co-Authored-By: OpenAI Codex <codex@openai.com>
Record when HTTP/1.1 has received the terminal content before invoking trailer or body callbacks. Cancellation from either terminal callback can then finish normally and reuse a keep-alive connection instead of closing it as unread. Check for inline cancellation after trailers so no later terminal body callback is delivered. Remove duplicate control completion from callback-abort paths and leave finishUpdate as the single completion owner. Cover cancellation from terminal body and trailer callbacks, single handler completion, skipped callbacks, and HTTP/1.1 connection reuse. OpenAI Codex on behalf of Matthias Kurz. Co-Authored-By: OpenAI Codex <codex@openai.com>
Document that onResponseBodyStart is invoked even when final headers end the response, but suspension cannot defer completion in that case. The control is inactive once the callback returns and later calls are harmless. Cover that behavior explicitly for HTTP/1.1 and HTTP/2, including completion without resume, late control calls, and connection reuse. OpenAI Codex on behalf of Matthias Kurz. Co-Authored-By: OpenAI Codex <codex@openai.com>
Treat HTTP/1.1 informational responses as interim rather than delivering them to the response handler or creating a response body control. Ignore Netty's synthetic LastHttpContent for each interim response while preserving the special terminator used to release a deferred 100-continue request body. Cover a 103 Early Hints followed by a final response, callback counts, body delivery, completion, and connection reuse. Retain the existing deferred 100-continue behavior. OpenAI Codex on behalf of Matthias Kurz. Co-Authored-By: OpenAI Codex <codex@openai.com>
Log once when a response remains suspended for a read-timeout interval while its request timeout is disabled. Such an exchange otherwise has no configured deadline and retains its handler and transport resources until application code resumes or cancels it. Keep the timeout path lock-free using the race-safe arming logic already on main, and cover warning severity, wording, and one-shot behavior. OpenAI Codex on behalf of Matthias Kurz. Co-Authored-By: OpenAI Codex <codex@openai.com>
Preserve the normal connection-level receive-window bound until a handler actually suspends a response. While any response on the connection is suspended, return shared credit without returning its per-stream credit so unrelated streams can continue. Track credit returned early until application consumption catches up. This avoids returning connection credit twice when suspension ends and normal accounting resumes. OpenAI Codex on behalf of Matthias Kurz. Co-Authored-By: OpenAI Codex <codex@openai.com>
Use the existing last-content callback, tied to the response future, to consume Netty's synthetic terminator after an HTTP/1.1 interim response. This prevents a channel marker from surviving into a later exchange. Explain how the unchanged channel attribute identifies an unsolicited 100 response after the continue interceptor runs. OpenAI Codex on behalf of Matthias Kurz. Co-Authored-By: OpenAI Codex <codex@openai.com>
Record that the package-private controller is adapted from Netty 4.2.17.Final and must be compared with upstream when Netty is upgraded for correctness and security fixes. Identify a runtime auto-refill API in Netty as the exit path that would let AHC remove the maintained adaptation. OpenAI Codex on behalf of Matthias Kurz. Co-Authored-By: OpenAI Codex <codex@openai.com>
mkurz
force-pushed
the
feature/response-body-control
branch
from
August 28, 2026 20:45
00ada81 to
08be4ab
Compare
Contributor
Author
|
@hyperxpro if you have time to look at this PR that would be really great, so I know how to move on in play-ws. Thanks! |
hyperxpro
requested changes
Aug 31, 2026
…ionAwareHttp2LocalFlowController.java
External cancellation and timeout paths mark the channel as discarded before channelInactive runs, so channel cleanup cannot recover the response future. A suspended HTTP/2 control can then leave connection auto-refill enabled and remain callable from onThrowable. Make the future's terminal transitions deactivate the control before user callbacks, while retaining channel-close cleanup for replay paths. Cover both abort and explicit cancellation. OpenAI Codex on behalf of Matthias Kurz. Co-Authored-By: OpenAI Codex <codex@openai.com>
hyperxpro
approved these changes
Aug 31, 2026
Member
|
Thanks a lot! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
ResponseBodyControlcallback after final response headers.Motivation
AHC 3 removed
StreamedAsyncHandlerand its Reactive Streams integration in pull request #1843. That removal avoids coupling AHC to a particular streaming library, butAsyncHandlerby itself has no way to stop transport reads while a downstream consumer has no demand.Play WS is the driving consumer for this change. Play WS needs transport backpressure to preserve its existing Pekko Streams and Reactive Streams response APIs while upgrading to AHC 3. A working adapter on a currently local Play WS development branch turns this control into a single-subscriber Reactive Streams publisher and has been tested against this AHC branch.
This pull request adds only the transport primitive. Streaming-library policy and dependencies remain in Play WS, so AHC does not regain a dependency on Reactive Streams or JDK Flow.
Semantics
AsyncHandler.onResponseBodyStartruns after final headers and before body parts, including for a response with no body.suspend()stops requesting new transport data, although body parts already read may still be delivered.resume()permits transport reads again.State.ABORTis the synchronous callback-time way to stop processing. A handler can retain the control and callcancel()when an asynchronous decision is made after the callback returns.HTTP/2 flow control
Connections with no actively suspended response retain Netty's normal connection-level receive-window accounting. The default 65,535-byte connection window therefore continues to cap unconsumed flow-controlled DATA across all streams for users that never call
suspend().When the first response on a connection is suspended, AHC returns connection-level credit that has already accumulated and continues returning that shared credit as DATA arrives. This prevents the suspended stream from exhausting the connection window and starving sibling streams. Per-stream credit remains consumption-driven at all times, so each suspended stream is still bounded by its own receive window. Multiple simultaneous suspensions are counted, and normal connection accounting resumes after the last one ends. Credit already returned and data already queued cannot be revoked, and the controller tracks credit returned early so later application consumption does not return it twice.
During an active suspension, aggregate buffering can still scale with the number of concurrent streams; the relevant controls are
http2InitialWindowSize,http2MaxConcurrentStreams, and the connection limits. The defaults do not impose a hard client-side aggregate bound during that interval: the initial per-stream window is 16 MiB andhttp2MaxConcurrentStreams = -1leaves concurrency server-controlled. A rough upper-bound estimate is connection count times effective concurrent streams times the initial window, excluding network and decoder overhead. Applications requiring a finite policy must configure these values together. A hard aggregate byte budget is a separate design and is outside this pull request.Netty's connection auto-refill state is private and fixed when
DefaultHttp2LocalFlowControlleris constructed, so it cannot be enabled only for the lifetime of a suspension through composition or subclassing. The package-privateSuspensionAwareHttp2LocalFlowControllertherefore adaptsDefaultHttp2LocalFlowControllerfrom Netty 4.2.17.Final, preserving its normal behavior while making connection refill suspension-scoped.This adaptation has a maintenance cost: AHC owns the copied flow-control logic and every Netty upgrade must compare it with the corresponding upstream implementation for correctness and security fixes. The exact source version and that obligation are recorded in the class Javadoc. An upstream Netty API that permits connection auto-refill to be changed at runtime would provide the exit path and allow AHC to remove the adaptation; no such API exists in Netty 4.2.17.Final.
The auto-refill mode requires a custom
Http2Connection. Netty's builder treatsserver()andconnection()as mutually exclusive, soClientHttp2FrameCodecBuildersupplies the connection through the protected builder API and overridesisServer()to retain client mode.The explicit
gracefulShutdownTimeoutMillis(0)is not a new shutdown policy.Http2FrameCodecBuilder.forClient()selects zero through its package-private client constructor; the subclass must use the protected no-argument constructor, so it sets zero explicitly to preserve the existing client-factory behavior.Scope and commit structure
The API/lifecycle work and the HTTP/2 independence work are kept as separate logical commits, but they belong in one pull request. Without the HTTP/2 work, a suspended response can consume the shared connection window and block unrelated sibling streams, so the public control would not have correct multiplexed behavior. Follow-up review fixes are also split into focused commits covering exchange ownership, terminal cleanup, terminal HTTP/1.1 cancellation, bodyless responses, interim responses, indefinite-suspension diagnostics, and suspension-scoped HTTP/2 refill.
History checked
AsyncHandlerbackpressure, and pull request #963 addressed it by adding Reactive Streams support.StreamedAsyncHandlerfor AHC 3.Compatibility
AsyncHandler.onResponseBodyStartis a new Javadefaultmethod, so existing handler implementations remain source- and binary-compatible and retain their previous behavior unless they override it.ResponseBodyControlis a new public interface.NettyResponseBodyControlis public only to support AHC's cross-package transport integration and is marked@ApiStatus.Internal; consumers should depend onResponseBodyControlinstead.onStatusReceivedoronHeadersReceived; this matches the existing HTTP/2 behavior and prevents a 103 Early Hints response from completing the exchange before the final response. Existing 100 Continue handling and 101 protocol switching are preserved.LastHttpContenthas already been received; it previously closed that fully read connection.AI disclosure
OpenAI Codex on behalf of Matthias Kurz. The commits include
Co-Authored-By: OpenAI Codex <codex@openai.com>perAGENTS.md.Test plan
ResponseBodyControlTest,Http2ResponseBodyControlTest,NettyResponseFutureTest,TimeoutTimerTaskTest,SuspensionAwareHttp2LocalFlowControllerTest, andContinue100InterceptorTestsuites pass 38 tests: 12 HTTP/1.1 control tests, 6 HTTP/2 integration tests, 9 future-lifecycle tests, 4 timeout-task tests, 5 flow-controller accounting tests, and 2 HTTP/1.1 Continue tests.JAVA_HOME=<jdk-11> ./mvnw clean verify: BUILD SUCCESS for the full reactor, including tests, Javadocs, coverage, and Revapi.