Skip to content

Commit a5de377

Browse files
committed
[grid] shutdown the websocket on unexpected failures
1 parent 21e3a92 commit a5de377

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

java/src/org/openqa/selenium/netty/server/WebSocketUpgradeHandler.java

+28-1
Original file line numberDiff line numberDiff line change
@@ -44,10 +44,15 @@
4444
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
4545
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
4646
import io.netty.util.AttributeKey;
47+
import java.util.Arrays;
48+
import java.util.Objects;
4749
import java.util.Optional;
4850
import java.util.function.BiFunction;
4951
import java.util.function.Consumer;
52+
import java.util.logging.Level;
53+
import java.util.logging.Logger;
5054
import org.openqa.selenium.internal.Require;
55+
import org.openqa.selenium.remote.http.CloseMessage;
5156
import org.openqa.selenium.remote.http.Message;
5257

5358
// Plenty of code in this class is taken from Netty's own
@@ -56,6 +61,7 @@
5661

5762
class WebSocketUpgradeHandler extends ChannelInboundHandlerAdapter {
5863

64+
private static final Logger LOG = Logger.getLogger(WebSocketUpgradeHandler.class.getName());
5965
private final AttributeKey<Consumer<Message>> key;
6066
private final BiFunction<String, Consumer<Message>, Optional<Consumer<Message>>> factory;
6167
private WebSocketServerHandshaker handshaker;
@@ -180,6 +186,27 @@ private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame fram
180186

181187
@Override
182188
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
183-
ctx.close();
189+
try {
190+
Consumer<Message> consumer = ctx.channel().attr(key).get();
191+
192+
if (consumer != null) {
193+
byte[] reason = Objects.toString(cause).getBytes(UTF_8);
194+
195+
// the spec defines it as max 123 bytes encoded in UTF_8
196+
if (reason.length > 123) {
197+
reason = Arrays.copyOf(reason, 123);
198+
Arrays.fill(reason, 120, 123, (byte) '.');
199+
}
200+
201+
try {
202+
consumer.accept(new CloseMessage(1011, new String(reason, UTF_8)));
203+
} catch (Exception ex) {
204+
LOG.log(Level.FINE, "failed to send the close message", ex);
205+
}
206+
}
207+
} finally {
208+
LOG.log(Level.FINE, "exception caught, close the context", cause);
209+
ctx.close();
210+
}
184211
}
185212
}

0 commit comments

Comments
 (0)