From 87dc6c54e9c554daded2d82b07b2a6075a8af651 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts <49400901+pavel-ptashyts@users.noreply.github.com> Date: Tue, 1 Dec 2026 08:22:02 +0100 Subject: [PATCH 1/3] Delete the body file from the client in replay tests FailedReplayHttp2Test and FailedReplayTest had their server delete the request body file as soon as it had read the body. The client closes the file only when its last write of the body completes, and the server can read that body before the client's write listener runs. Windows refuses to delete a file that is still open, so the server's delete failed now and then: over HTTP/2 the stream was reset and the request failed with that IOException, over HTTP/1.1 Jetty answered 500. This made FailedReplayHttp2Test fail on windows-latest in every Build PR run on main since #2415. A response filter now deletes the file on the client when the 307 arrives. It runs on the event loop that wrote the body, after that write has closed the file, so the delete no longer races it. The tests still prove that a replay that cannot be built fails the request with the IllegalArgumentException of the build, after one replay, and that the client serves requests afterwards. Claude Code on behalf of Pavel Ptashyts Co-Authored-By: Claude Opus 5.5 --- .../filter/FailedReplayHttp2Test.java | 27 +++++++++++++++---- .../filter/FailedReplayTest.java | 20 ++++++++++++-- 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/client/src/test/java/org/asynchttpclient/filter/FailedReplayHttp2Test.java b/client/src/test/java/org/asynchttpclient/filter/FailedReplayHttp2Test.java index 754ce6219..39923b7a1 100644 --- a/client/src/test/java/org/asynchttpclient/filter/FailedReplayHttp2Test.java +++ b/client/src/test/java/org/asynchttpclient/filter/FailedReplayHttp2Test.java @@ -41,12 +41,14 @@ import io.netty.pkitesting.X509Bundle; import io.netty.util.ReferenceCountUtil; import org.asynchttpclient.AsyncHttpClient; +import org.asynchttpclient.exception.FilterException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import java.io.File; +import java.io.IOException; import java.net.InetSocketAddress; import java.nio.file.Files; import java.util.concurrent.ExecutionException; @@ -72,7 +74,7 @@ public class FailedReplayHttp2Test { private Channel serverChannel; private SslContext serverSslCtx; private int serverPort; - // The server deletes it once it has received the request body, before it answers with a 307. + // The client deletes it once the 307 arrives. private volatile File body; @BeforeEach @@ -101,7 +103,7 @@ protected void initChannel(Channel ch) { .addLast(new Http2MultiplexHandler(new ChannelInitializer() { @Override protected void initChannel(Http2StreamChannel streamCh) { - streamCh.pipeline().addLast(new DeletingRedirectHandler()); + streamCh.pipeline().addLast(new RedirectHandler()); } })); } @@ -137,11 +139,27 @@ public FilterContext filter(FilterContext ctx) { : ctx; } }; + // The server could see the end of the body before the client closed the file, which Windows refuses to + // delete while it is open. Response filters run after the last write of the body has closed it. + ResponseFilter deleteBodyOnRedirect = new ResponseFilter() { + @Override + public FilterContext filter(FilterContext ctx) throws FilterException { + if (ctx.getResponseStatus() != null && ctx.getResponseStatus().getStatusCode() == 307) { + try { + Files.delete(body.toPath()); + } catch (IOException e) { + throw new FilterException("Could not delete the request body", e); + } + } + return ctx; + } + }; try (AsyncHttpClient client = asyncHttpClient(config() .setUseInsecureTrustManager(true) .setHttp2Enabled(true) .setFollowRedirect(true) + .addResponseFilter(deleteBodyOnRedirect) .addIOExceptionFilter(replayOnce))) { String base = "https://localhost:" + serverPort; // The redirect refuses to resend the missing file with an IOException, which the filter replays. @@ -155,8 +173,8 @@ public FilterContext filter(FilterContext ctx) { } } - /** Deletes the body file once a request on /redirect has ended, then answers with a 307. Answers 200 otherwise. */ - private final class DeletingRedirectHandler extends SimpleChannelInboundHandler { + /** Answers a request on /redirect with a 307 once it has ended, and 200 otherwise. */ + private final class RedirectHandler extends SimpleChannelInboundHandler { private boolean redirect; @@ -176,7 +194,6 @@ protected void channelRead0(ChannelHandlerContext ctx, Http2StreamFrame frame) t return; } if (redirect) { - Files.delete(body.toPath()); ctx.write(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers().status("307").set("location", "/target"), false)); ctx.writeAndFlush(new DefaultHttp2DataFrame(Unpooled.copiedBuffer("moved", US_ASCII), true)); diff --git a/client/src/test/java/org/asynchttpclient/filter/FailedReplayTest.java b/client/src/test/java/org/asynchttpclient/filter/FailedReplayTest.java index 8b55d64a8..7760351d3 100644 --- a/client/src/test/java/org/asynchttpclient/filter/FailedReplayTest.java +++ b/client/src/test/java/org/asynchttpclient/filter/FailedReplayTest.java @@ -22,6 +22,7 @@ import org.asynchttpclient.AsyncHttpClient; import org.asynchttpclient.ListenableFuture; import org.asynchttpclient.Response; +import org.asynchttpclient.exception.FilterException; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; @@ -53,7 +54,7 @@ */ public class FailedReplayTest extends AbstractBasicTest { - // The handler deletes it once it has read the request body, before it answers with a 307. + // The client deletes it once the 307 arrives. private volatile File body; @Override @@ -88,7 +89,6 @@ public void handle(String target, Request baseRequest, HttpServletRequest reques baseRequest.setHandled(true); request.getInputStream().readAllBytes(); if ("/redirect".equals(target)) { - Files.delete(body.toPath()); response.setStatus(307); response.setHeader("Location", "/target"); } else { @@ -111,12 +111,28 @@ public FilterContext filter(FilterContext ctx) { : ctx; } }; + // The server could see the end of the body before the client closed the file, which Windows refuses to + // delete while it is open. Response filters run after the last write of the body has closed it. + ResponseFilter deleteBodyOnRedirect = new ResponseFilter() { + @Override + public FilterContext filter(FilterContext ctx) throws FilterException { + if (ctx.getResponseStatus() != null && ctx.getResponseStatus().getStatusCode() == 307) { + try { + Files.delete(body.toPath()); + } catch (IOException e) { + throw new FilterException("Could not delete the request body", e); + } + } + return ctx; + } + }; // One connection: the request sent from onThrowable needs the permit of the one the replay came from. try (AsyncHttpClient client = asyncHttpClient(config() .setUseInsecureTrustManager(true) .setFollowRedirect(true) .setMaxConnections(1) + .addResponseFilter(deleteBodyOnRedirect) .addIOExceptionFilter(replayOnce))) { String base = "https://localhost:" + port1; CompletableFuture> next = new CompletableFuture<>(); From 9ac585d55c1524584f68f5a2657fbc3937580301 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts <49400901+pavel-ptashyts@users.noreply.github.com> Date: Tue, 1 Dec 2026 10:02:55 +0100 Subject: [PATCH 2/3] Close an HTTP/2 body source before failing When reading the next chunk of an HTTP/2 request body failed, for example because a file body got shorter than its announced length, Http2BodyWriter failed the request future first and closed the body source only afterwards. A caller woken by that failure could then find the file still open: on Windows, deleting it failed with "The process cannot access the file because it is being used by another process". Http2StreamingBodyFlowControlTest hit this in its cleanup on windows-latest. The source is now closed before the future fails. The future still fails with the source's error before the stream is closed, so it is neither replaced by the closed stream nor replayed. Claude Code on behalf of Pavel Ptashyts Co-Authored-By: Claude Opus 5.5 --- .../netty/request/body/Http2BodyWriter.java | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/client/src/main/java/org/asynchttpclient/netty/request/body/Http2BodyWriter.java b/client/src/main/java/org/asynchttpclient/netty/request/body/Http2BodyWriter.java index e54b6df62..fc0972da8 100644 --- a/client/src/main/java/org/asynchttpclient/netty/request/body/Http2BodyWriter.java +++ b/client/src/main/java/org/asynchttpclient/netty/request/body/Http2BodyWriter.java @@ -126,6 +126,7 @@ default void onResume(Runnable resume) { // writer until written; released by finish() if still set when the pump ends. private ByteBuf pending; private boolean done; + private boolean sourceClosed; // flush() can synchronously fire channelWritabilityChanged. Prevent that callback from re-entering the // pump, and remember permanently once the terminal frame has been emitted so later callbacks cannot write @@ -254,6 +255,8 @@ private void pump() { // First iteration (toWrite == null): nothing written yet, loop to read the second chunk. } } catch (Throwable t) { + // Released before the request fails, so that whoever learns of the failure can delete a file body. + closeSource(); future.abort(t); finish(t); } finally { @@ -313,11 +316,7 @@ private void finish(Throwable cause) { resumeHandler = null; } - try { - source.close(); - } catch (Throwable t) { - LOGGER.warn("Failed to close HTTP/2 request body source", t); - } + closeSource(); if (cause != null) { LOGGER.debug("HTTP/2 request body streaming failed; closing stream", cause); @@ -328,6 +327,18 @@ private void finish(Throwable cause) { } } + private void closeSource() { + if (sourceClosed) { + return; + } + sourceClosed = true; + try { + source.close(); + } catch (Throwable t) { + LOGGER.warn("Failed to close HTTP/2 request body source", t); + } + } + /** * Resumes the parked pump when the stream channel becomes writable again. */ From 6a117b5988d56555e139f7d61e601bd92ba3e531 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts <49400901+pavel-ptashyts@users.noreply.github.com> Date: Tue, 1 Dec 2026 10:02:55 +0100 Subject: [PATCH 3/3] Wait for the server to close after a 1009 When a WebSocket message went over the buffer or inflate limit, the client sent a 1009 close frame and closed the connection at once. What the server was still sending stayed unread, so closing reset the connection, and the server could lose the close frame and report 1006. WebSocketMessageTooBigTest failed this way on windows-latest. The handler also sent a second close frame, 1000, after the 1009. The client now sends the 1009 alone and, as RFC 6455 section 7.1.1 asks of a client, leaves closing the connection to the server. It discards what the server still sends meanwhile, and closes the connection itself if the server has not done so within 10 seconds. The listener still gets onError, then onClose once the connection is gone. Claude Code on behalf of Pavel Ptashyts Co-Authored-By: Claude Opus 5.5 --- .../netty/handler/WebSocketHandler.java | 50 ++++++++++++++++++- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/client/src/main/java/org/asynchttpclient/netty/handler/WebSocketHandler.java b/client/src/main/java/org/asynchttpclient/netty/handler/WebSocketHandler.java index bffca101e..baca849c0 100755 --- a/client/src/main/java/org/asynchttpclient/netty/handler/WebSocketHandler.java +++ b/client/src/main/java/org/asynchttpclient/netty/handler/WebSocketHandler.java @@ -18,6 +18,7 @@ import io.netty.channel.Channel; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.TooLongFrameException; import io.netty.handler.codec.compression.DecompressionException; import io.netty.handler.codec.http.HttpHeaderValues; @@ -28,6 +29,8 @@ import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketCloseStatus; import io.netty.handler.codec.http.websocketx.WebSocketFrame; +import io.netty.util.ReferenceCountUtil; +import io.netty.util.concurrent.ScheduledFuture; import org.asynchttpclient.AsyncHandler.State; import org.asynchttpclient.AsyncHttpClientConfig; import org.asynchttpclient.HttpResponseStatus; @@ -40,6 +43,7 @@ import org.asynchttpclient.ws.WebSocketUpgradeHandler; import java.io.IOException; +import java.util.concurrent.TimeUnit; import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION; import static io.netty.handler.codec.http.HttpHeaderNames.SEC_WEBSOCKET_ACCEPT; @@ -54,6 +58,9 @@ @Sharable public final class WebSocketHandler extends AsyncHttpClientHandler { + // How long the server gets to close the connection after a 1009, before the client closes it itself. + private static final long CLOSE_HANDSHAKE_TIMEOUT_SECONDS = 10; + public WebSocketHandler(AsyncHttpClientConfig config, ChannelManager channelManager, NettyRequestSender requestSender) { super(config, channelManager, requestSender); } @@ -164,15 +171,54 @@ public void handleRead(Channel channel, NettyResponseFuture future, Object e) @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { // RFC 6455 section 7.4.1: 1009 for a message too big to process, whether the aggregator refused it or the - // inflater did. Queued before the close below. + // inflater did. Throwable cause = getCause(e); if ((cause instanceof TooLongFrameException && ctx.pipeline().get(WS_FRAME_AGGREGATOR) != null) || (cause instanceof DecompressionException && ctx.pipeline().get(WS_DECODER_HANDLER) != null)) { - ctx.writeAndFlush(new CloseWebSocketFrame(WebSocketCloseStatus.MESSAGE_TOO_BIG)); + closeWithMessageTooBig(ctx, e); + return; } super.exceptionCaught(ctx, e); } + /** + * Sends the 1009 and leaves closing the connection to the server, as RFC 6455 section 7.1.1 asks of a client, + * discarding what the server still sends until then. Closing it here instead would leave that input unread, so + * the connection would be reset, and the server could lose the close frame and report 1006. + */ + private void closeWithMessageTooBig(ChannelHandlerContext ctx, Throwable e) { + if (ctx.pipeline().get(DiscardInbound.class) != null) { + // What the decoder still held when the close began. + return; + } + ctx.pipeline().addBefore(WS_DECODER_HANDLER, null, new DiscardInbound()); + Channel channel = ctx.channel(); + ctx.writeAndFlush(new CloseWebSocketFrame(WebSocketCloseStatus.MESSAGE_TOO_BIG)); + ScheduledFuture forceClose = ctx.executor().schedule(() -> Channels.silentlyCloseChannel(channel), + CLOSE_HANDSHAKE_TIMEOUT_SECONDS, TimeUnit.SECONDS); + channel.closeFuture().addListener(f -> forceClose.cancel(false)); + + Object attribute = Channels.getAttribute(channel); + if (attribute instanceof NettyResponseFuture) { + logger.warn("onError", e); + try { + NettyWebSocket webSocket = getNettyWebSocket((NettyResponseFuture) attribute); + if (webSocket != null) { + webSocket.onError(e); + } + } catch (Throwable t) { + logger.error("onError", t); + } + } + } + + private static final class DiscardInbound extends ChannelInboundHandlerAdapter { + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) { + ReferenceCountUtil.release(msg); + } + } + @Override public void handleException(NettyResponseFuture future, Throwable e) { logger.warn("onError", e);