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

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-8Lines changed: 33 additions & 8 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 Promise<Void> 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,
@@ -115,12 +116,36 @@ public void write(final ChannelHandlerContext ctx, Object msg, CompletionHandler
115116
}
116117
}
117118

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

122-
private void applyCloseSentTimeout(ChannelHandlerContext ctx) {
123-
if (closeSent.isDone() || forceCloseTimeoutMillis < 0) {
147+
void applyCloseSentTimeout(ChannelHandlerContext ctx) {
148+
if (forceCloseTimeoutTask != null || closeSent.isDone() || forceCloseTimeoutMillis < 0) {
124149
return;
125150
}
126151

@@ -129,9 +154,14 @@ private void applyCloseSentTimeout(ChannelHandlerContext ctx) {
129154
public void run() {
130155
if (!closeSent.isDone()) {
131156
closeSent.tryFailure(buildHandshakeException("send close frame timed out"));
157+
// Do not rely on some other listener eventually closing the channel once closeSent
158+
// completes (e.g. write(CloseWebSocketFrame) without a subsequent close() call attaches
159+
// none): close it here so the deadline is enforced unconditionally.
160+
ctx.close();
132161
}
133162
}
134163
}, forceCloseTimeoutMillis, TimeUnit.MILLISECONDS);
164+
forceCloseTimeoutTask = timeoutTask;
135165

136166
closeSent.addListener(future -> timeoutTask.cancel(false));
137167
}
@@ -176,11 +206,6 @@ public void read(ChannelHandlerContext ctx) {
176206
ctx.read();
177207
}
178208

179-
@Override
180-
public void flush(ChannelHandlerContext ctx) {
181-
ctx.flush();
182-
}
183-
184209
@Override
185210
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
186211
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
@@ -240,6 +240,11 @@ protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Obje
240240
Promise<Void> promise = ctx.newPromise();
241241
closeSent(promise);
242242
handshaker.close(ctx, (CloseWebSocketFrame) frame, promise);
243+
// handshaker.close() bypasses this handler's own write()/flush() overrides (it writes
244+
// directly on ctx), so the force-close timeout must be armed explicitly here. Doing so
245+
// after the close0() write-and-flush attempt above mirrors close()'s ordering and avoids
246+
// racing a write that completes synchronously.
247+
applyCloseSentTimeout(ctx);
243248
} else {
244249
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(f -> ctx.close());
245250
}
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
+56Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,20 @@
1818

1919
import io.netty.buffer.ByteBuf;
2020
import io.netty.buffer.Unpooled;
21+
import io.netty.channel.ChannelHandlerContext;
22+
import io.netty.channel.ChannelOutboundHandler;
2123
import io.netty.channel.embedded.EmbeddedChannel;
2224
import io.netty.handler.flow.FlowControlHandler;
25+
import io.netty.util.ReferenceCountUtil;
26+
import io.netty.util.concurrent.CompletionHandler;
27+
import io.netty.util.concurrent.Future;
2328
import org.junit.jupiter.api.Test;
2429

30+
2531
import static io.netty.util.CharsetUtil.UTF_8;
2632
import static org.junit.jupiter.api.Assertions.assertEquals;
2733
import static org.junit.jupiter.api.Assertions.assertFalse;
34+
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
2835
import static org.junit.jupiter.api.Assertions.assertNull;
2936
import static org.junit.jupiter.api.Assertions.assertTrue;
3037

@@ -142,6 +149,55 @@ public void testTextFrame() throws Exception {
142149
assertFalse(channel.finish());
143150
}
144151

152+
@Test
153+
public void testTimeout() throws Exception {
154+
WebSocketProtocolHandler handler = new WebSocketProtocolHandler(
155+
false, WebSocketCloseStatus.NORMAL_CLOSURE, 1) { };
156+
EmbeddedChannel channel = new EmbeddedChannel(new ChannelOutboundHandler() {
157+
@Override
158+
public void write(ChannelHandlerContext ctx, Object msg, CompletionHandler<Void> handler) {
159+
ReferenceCountUtil.release(msg);
160+
}
161+
}, handler);
162+
163+
ChannelHandlerContext ctx = channel.pipeline().context(WebSocketProtocolHandler.class);
164+
Future<Void> future = channel.writeAndFlush(new CloseWebSocketFrame());
165+
handler.close(ctx, ctx.newPromise());
166+
167+
do {
168+
Thread.sleep(10);
169+
channel.runPendingTasks();
170+
} while (!future.isDone());
171+
172+
assertInstanceOf(WebSocketHandshakeException.class, future.cause());
173+
assertFalse(channel.finish());
174+
}
175+
176+
@Test
177+
public void testTimeoutWithoutExplicitClose() throws Exception {
178+
// A bare write(CloseWebSocketFrame) is not followed by any close() call: the force-close
179+
// timeout itself must be the thing that closes the channel once it fires.
180+
WebSocketProtocolHandler handler = new WebSocketProtocolHandler(
181+
false, WebSocketCloseStatus.NORMAL_CLOSURE, 1) { };
182+
EmbeddedChannel channel = new EmbeddedChannel(new ChannelOutboundHandler() {
183+
@Override
184+
public void write(ChannelHandlerContext ctx, Object msg, CompletionHandler<Void> handler) {
185+
// Simulate a stalled write: never complete the handler.
186+
ReferenceCountUtil.release(msg);
187+
}
188+
}, handler);
189+
190+
channel.writeAndFlush(new CloseWebSocketFrame());
191+
192+
while (channel.isOpen()) {
193+
Thread.sleep(10);
194+
channel.runPendingTasks();
195+
}
196+
197+
assertFalse(channel.isOpen());
198+
assertFalse(channel.finish());
199+
}
200+
145201
/**
146202
* Asserts that a message was propagated inbound through the channel.
147203
*/
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
+106Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,14 @@
3939
import io.netty.util.CharsetUtil;
4040
import io.netty.util.ReferenceCountUtil;
4141
import io.netty.util.concurrent.CompletionHandler;
42+
import io.netty.util.concurrent.Promise;
4243
import org.junit.jupiter.api.BeforeEach;
4344
import org.junit.jupiter.api.Test;
4445

4546
import java.util.ArrayDeque;
47+
import java.util.ArrayList;
4648
import java.util.Queue;
49+
import java.util.concurrent.TimeUnit;
4750

4851
import static io.netty.handler.codec.http.HttpResponseStatus.*;
4952
import static io.netty.handler.codec.http.HttpVersion.*;
@@ -458,6 +461,109 @@ public void write(ChannelHandlerContext ctx, Object msg, CompletionHandler<Void>
458461
assertFalse(server.finishAndReleaseAll());
459462
}
460463

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