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 — Port 4.1: Arm force-close timeout when an inbound CLOSE frame is echo… · netty/netty@e7de11e

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • codec-http/src
    • main/java/io/netty/handler/codec/http/websocketx
      • WebSocketClientProtocolConfig.java
      • WebSocketProtocolHandler.java
      • WebSocketServerProtocolConfig.java
      • WebSocketServerProtocolHandler.java
    • test/java/io/netty/handler/codec/http/websocketx
      • WebSocketProtocolHandlerTest.java
      • WebSocketServerProtocolHandlerTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

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

Copy file name to clipboardExpand all lines: codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientProtocolConfig.java
+2-1Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222

2323
import java.net.URI;
2424

25+
import static io.netty.handler.codec.http.websocketx.WebSocketServerProtocolConfig.DEFAULT_FORCE_CLOSE_TIMEOUT_MILLIS;
2526
import static io.netty.handler.codec.http.websocketx.WebSocketServerProtocolConfig.DEFAULT_HANDSHAKE_TIMEOUT_MILLIS;
2627
import static io.netty.util.internal.ObjectUtil.checkPositive;
2728

@@ -193,7 +194,7 @@ public static Builder newBuilder() {
193194
WebSocketCloseStatus.NORMAL_CLOSURE,
194195
DEFAULT_DROP_PONG_FRAMES,
195196
DEFAULT_HANDSHAKE_TIMEOUT_MILLIS,
196-
-1,
197+
DEFAULT_FORCE_CLOSE_TIMEOUT_MILLIS,
197198
false,
198199
DEFAULT_GENERATE_ORIGIN_HEADER,
199200
DEFAULT_WITH_UTF8_VALIDATOR);
Collapse file

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

Copy file name to clipboardExpand all lines: codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketProtocolHandler.java
+33-9Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ abstract class WebSocketProtocolHandler extends MessageToMessageDecoder<WebSocke
3838
private final WebSocketCloseStatus closeStatus;
3939
private final long forceCloseTimeoutMillis;
4040
private ChannelPromise closeSent;
41+
private Future<?> forceCloseTimeoutTask;
4142

4243
/**
4344
* Creates a new {@link WebSocketProtocolHandler} that will <i>drop</i> {@link PongWebSocketFrame}s.
@@ -54,7 +55,7 @@ abstract class WebSocketProtocolHandler extends MessageToMessageDecoder<WebSocke
5455
* {@code true} if {@link PongWebSocketFrame}s should be dropped
5556
*/
5657
WebSocketProtocolHandler(boolean dropPongFrames) {
57-
this(dropPongFrames, null, 0L);
58+
this(dropPongFrames, null, WebSocketServerProtocolConfig.DEFAULT_FORCE_CLOSE_TIMEOUT_MILLIS);
5859
}
5960

6061
WebSocketProtocolHandler(boolean dropPongFrames,
@@ -96,7 +97,6 @@ public void close(final ChannelHandlerContext ctx, final ChannelPromise promise)
9697
write(ctx, new CloseWebSocketFrame(closeStatus), ctx.newPromise());
9798
}
9899
flush(ctx);
99-
applyCloseSentTimeout(ctx);
100100
closeSent.addListener(new ChannelFutureListener() {
101101
@Override
102102
public void operationComplete(ChannelFuture future) {
@@ -119,12 +119,36 @@ public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise pr
119119
}
120120
}
121121

122+
@Override
123+
public void flush(ChannelHandlerContext ctx) throws Exception {
124+
ctx.flush();
125+
// Give the flush a chance to complete synchronously before arming the deadline, so a write that
126+
// finishes immediately (e.g. EmbeddedChannel, or a fast socket) never races the force-close timer.
127+
if (closeSent != null) {
128+
applyCloseSentTimeout(ctx);
129+
}
130+
}
131+
132+
/**
133+
* Records the {@link ChannelPromise} used to write the outgoing close frame. Every code path that initiates
134+
* the close handshake must call this, and must subsequently give
135+
* {@link #applyCloseSentTimeout(ChannelHandlerContext)} a chance to run (directly, or indirectly via
136+
* {@link #flush(ChannelHandlerContext)}) so the channel is guaranteed to close even if the outbound write
137+
* never completes (e.g. the peer stops reading and the socket send buffer fills up).
138+
*/
122139
void closeSent(ChannelPromise promise) {
140+
if (closeSent != null) {
141+
// Already sending (or already sent) a close frame, e.g. a peer that sends more than one CLOSE
142+
// frame. Keep the original promise (and the deadline already armed for it) authoritative, and
143+
// just cascade its outcome onto the new one instead of losing track of the original.
144+
closeSent.addListener(new PromiseNotifier<Void, ChannelFuture>(false, promise));
145+
return;
146+
}
123147
closeSent = promise;
124148
}
125149

126-
private void applyCloseSentTimeout(ChannelHandlerContext ctx) {
127-
if (closeSent.isDone() || forceCloseTimeoutMillis < 0) {
150+
void applyCloseSentTimeout(final ChannelHandlerContext ctx) {
151+
if (forceCloseTimeoutTask != null || closeSent.isDone() || forceCloseTimeoutMillis < 0) {
128152
return;
129153
}
130154

@@ -133,9 +157,14 @@ private void applyCloseSentTimeout(ChannelHandlerContext ctx) {
133157
public void run() {
134158
if (!closeSent.isDone()) {
135159
closeSent.tryFailure(buildHandshakeException("send close frame timed out"));
160+
// Do not rely on some other listener eventually closing the channel once closeSent
161+
// completes (e.g. write(CloseWebSocketFrame) without a subsequent close() call attaches
162+
// none): close it here so the deadline is enforced unconditionally.
163+
ctx.close();
136164
}
137165
}
138166
}, forceCloseTimeoutMillis, TimeUnit.MILLISECONDS);
167+
forceCloseTimeoutTask = timeoutTask;
139168

140169
closeSent.addListener(new ChannelFutureListener() {
141170
@Override
@@ -181,11 +210,6 @@ public void read(ChannelHandlerContext ctx) throws Exception {
181210
ctx.read();
182211
}
183212

184-
@Override
185-
public void flush(ChannelHandlerContext ctx) throws Exception {
186-
ctx.flush();
187-
}
188-
189213
@Override
190214
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
191215
ctx.fireExceptionCaught(cause);
Collapse file

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

Copy file name to clipboardExpand all lines: codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolConfig.java
+4-2Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
public final class WebSocketServerProtocolConfig {
2727

2828
static final long DEFAULT_HANDSHAKE_TIMEOUT_MILLIS = 10000L;
29+
static final long DEFAULT_FORCE_CLOSE_TIMEOUT_MILLIS = 10000L;
2930

3031
private final String websocketPath;
3132
private final String subprotocols;
@@ -115,8 +116,9 @@ public Builder toBuilder() {
115116
}
116117

117118
public static Builder newBuilder() {
118-
return new Builder("/", null, false, DEFAULT_HANDSHAKE_TIMEOUT_MILLIS, 0L,
119-
true, WebSocketCloseStatus.NORMAL_CLOSURE, true, WebSocketDecoderConfig.DEFAULT);
119+
return new Builder("/", null, false, DEFAULT_HANDSHAKE_TIMEOUT_MILLIS,
120+
DEFAULT_FORCE_CLOSE_TIMEOUT_MILLIS, true, WebSocketCloseStatus.NORMAL_CLOSURE, true,
121+
WebSocketDecoderConfig.DEFAULT);
120122
}
121123

122124
public static final class Builder {
Collapse file

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

Copy file name to clipboardExpand all lines: codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandler.java
+5Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,11 @@ protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Obje
241241
ChannelPromise promise = ctx.newPromise();
242242
closeSent(promise);
243243
handshaker.close(ctx, (CloseWebSocketFrame) frame, promise);
244+
// handshaker.close() bypasses this handler's own write()/flush() overrides (it writes
245+
// directly on ctx), so the force-close timeout must be armed explicitly here. Doing so
246+
// after the close0() write-and-flush attempt above mirrors close()'s ordering and avoids
247+
// racing a write that completes synchronously.
248+
applyCloseSentTimeout(ctx);
244249
} else {
245250
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
246251
}
Collapse file

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

Copy file name to clipboardExpand all lines: codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketProtocolHandlerTest.java
+26-1Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,8 +163,8 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
163163
}
164164
}, handler);
165165

166-
ChannelFuture future = channel.writeAndFlush(new CloseWebSocketFrame());
167166
ChannelHandlerContext ctx = channel.pipeline().context(WebSocketProtocolHandler.class);
167+
ChannelFuture future = channel.writeAndFlush(new CloseWebSocketFrame());
168168
handler.close(ctx, ctx.newPromise());
169169

170170
do {
@@ -177,6 +177,31 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
177177
assertFalse(channel.finish());
178178
}
179179

180+
@Test
181+
public void testTimeoutWithoutExplicitClose() throws Exception {
182+
// A bare write(CloseWebSocketFrame) is not followed by any close() call: the force-close
183+
// timeout itself must be the thing that closes the channel once it fires.
184+
WebSocketProtocolHandler handler = new WebSocketProtocolHandler(
185+
false, WebSocketCloseStatus.NORMAL_CLOSURE, 1) { };
186+
EmbeddedChannel channel = new EmbeddedChannel(new ChannelOutboundHandlerAdapter() {
187+
@Override
188+
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
189+
// Simulate a stalled write: never complete the promise.
190+
ReferenceCountUtil.release(msg);
191+
}
192+
}, handler);
193+
194+
channel.writeAndFlush(new CloseWebSocketFrame());
195+
196+
while (channel.isOpen()) {
197+
Thread.sleep(10);
198+
channel.runPendingTasks();
199+
}
200+
201+
assertFalse(channel.isOpen());
202+
assertFalse(channel.finish());
203+
}
204+
180205
/**
181206
* Asserts that a message was propagated inbound through the channel.
182207
*/
Collapse file

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

Copy file name to clipboardExpand all lines: codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandlerTest.java
+105Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,9 @@
4343
import org.junit.jupiter.api.Test;
4444

4545
import java.util.ArrayDeque;
46+
import java.util.ArrayList;
4647
import java.util.Queue;
48+
import java.util.concurrent.TimeUnit;
4749

4850
import static io.netty.handler.codec.http.HttpResponseStatus.*;
4951
import static io.netty.handler.codec.http.HttpVersion.*;
@@ -456,6 +458,109 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
456458
assertFalse(server.finishAndReleaseAll());
457459
}
458460

461+
@Test
462+
public void testForceCloseTimeoutAppliedToInboundCloseFrame() throws Exception {
463+
final long forceCloseTimeoutMillis = 100;
464+
final Queue<ChannelPromise> stalledWrites = new ArrayDeque<ChannelPromise>();
465+
EmbeddedChannel client = createClient();
466+
EmbeddedChannel server = createStallingServer(forceCloseTimeoutMillis, stalledWrites);
467+
468+
assertFalse(server.writeInbound(client.<ByteBuf>readOutbound()));
469+
assertFalse(client.writeInbound(server.<ByteBuf>readOutbound()));
470+
471+
// The peer initiates the close handshake.
472+
assertTrue(client.writeOutbound(new CloseWebSocketFrame(WebSocketCloseStatus.NORMAL_CLOSURE)));
473+
assertFalse(server.writeInbound(client.<ByteBuf>readOutbound()));
474+
475+
// The server's echo write is stalled, simulating a peer that stopped draining its socket
476+
// receive buffer. The channel must not stay open indefinitely waiting on that write.
477+
assertEquals(1, stalledWrites.size());
478+
assertTrue(server.isOpen());
479+
480+
server.advanceTimeBy(forceCloseTimeoutMillis * 2, TimeUnit.MILLISECONDS);
481+
server.runScheduledPendingTasks();
482+
483+
assertFalse(server.isOpen());
484+
485+
client.close();
486+
assertFalse(client.finishAndReleaseAll());
487+
assertFalse(server.finishAndReleaseAll());
488+
}
489+
490+
@Test
491+
public void testSimultaneousCloseDoesNotLeakOriginalPromise() throws Exception {
492+
// The application initiates an outbound close (e.g. via ctx.close()) while the peer's own CLOSE
493+
// frame is concurrently in flight. Both paths call closeSent(): the second call must not silently
494+
// overwrite (and orphan) the promise the first call already armed a deadline for.
495+
final long forceCloseTimeoutMillis = 100;
496+
final Queue<ChannelPromise> stalledWrites = new ArrayDeque<ChannelPromise>();
497+
EmbeddedChannel client = createClient();
498+
EmbeddedChannel server = createStallingServer(forceCloseTimeoutMillis, stalledWrites);
499+
500+
assertFalse(server.writeInbound(client.<ByteBuf>readOutbound()));
501+
assertFalse(client.writeInbound(server.<ByteBuf>readOutbound()));
502+
503+
// The application decides to close first.
504+
ChannelHandlerContext serverCtx = server.pipeline().context(WebSocketServerProtocolHandler.class);
505+
ChannelPromise applicationClosePromise = serverCtx.newPromise();
506+
((WebSocketServerProtocolHandler) serverCtx.handler()).close(serverCtx, applicationClosePromise);
507+
508+
// Before that echo completes, the peer's own CLOSE frame arrives too.
509+
assertTrue(client.writeOutbound(new CloseWebSocketFrame(WebSocketCloseStatus.NORMAL_CLOSURE)));
510+
assertFalse(server.writeInbound(client.<ByteBuf>readOutbound()));
511+
512+
// Both echo writes are stalled, but only a single deadline should govern the close handshake.
513+
assertEquals(2, stalledWrites.size());
514+
// The second echo (triggered by the peer's inbound frame) is the one whose promise was cascaded
515+
// from the original closeSent instead of overwriting it.
516+
ChannelPromise peerEchoWrite = new ArrayList<ChannelPromise>(stalledWrites).get(1);
517+
assertTrue(server.isOpen());
518+
519+
server.advanceTimeBy(forceCloseTimeoutMillis * 2, TimeUnit.MILLISECONDS);
520+
server.runScheduledPendingTasks();
521+
522+
assertFalse(server.isOpen());
523+
// Neither promise is left hanging forever: the application's own close promise completes, and so
524+
// does the promise cascaded from it for the peer's own (redundant) close frame.
525+
assertTrue(applicationClosePromise.isDone());
526+
assertTrue(peerEchoWrite.isDone());
527+
528+
client.close();
529+
assertFalse(client.finishAndReleaseAll());
530+
assertFalse(server.finishAndReleaseAll());
531+
}
532+
533+
private static EmbeddedChannel createStallingServer(
534+
long forceCloseTimeoutMillis, final Queue<ChannelPromise> stalledWrites) throws Exception {
535+
WebSocketServerProtocolConfig serverConfig = WebSocketServerProtocolConfig.newBuilder()
536+
.websocketPath("/test")
537+
.dropPongFrames(false)
538+
.forceCloseTimeoutMillis(forceCloseTimeoutMillis)
539+
.build();
540+
EmbeddedChannel ch = new EmbeddedChannel(false, false,
541+
new ChannelOutboundHandlerAdapter() {
542+
private boolean handshakeResponseSent;
543+
544+
@Override
545+
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
546+
if (msg instanceof ByteBuf && handshakeResponseSent) {
547+
// Simulate a peer that stopped draining its socket receive buffer: the
548+
// close-frame echo write never completes on its own.
549+
ReferenceCountUtil.release(msg);
550+
stalledWrites.add(promise);
551+
return;
552+
}
553+
handshakeResponseSent = true;
554+
ctx.write(msg, promise);
555+
}
556+
},
557+
new HttpServerCodec(),
558+
new HttpObjectAggregator(8192),
559+
new WebSocketServerProtocolHandler(serverConfig));
560+
ch.register();
561+
return ch;
562+
}
563+
459564
private EmbeddedChannel createClient(ChannelHandler... handlers) throws Exception {
460565
WebSocketClientProtocolConfig clientConfig = WebSocketClientProtocolConfig.newBuilder()
461566
.webSocketUri("http://test/test")

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.