Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions docs/asciidoc/websocket.adoc
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
== Web Sockets

Jooby supports https://developer.mozilla.org/es/docs/Web/API/WebSockets_API[WebSockets].
A javadoc:WebSocket[] is registered like any other handler:
Adding a javadoc:WebSocket[]:

.WebSocket
[source,java,role="primary"]
Expand Down Expand Up @@ -170,7 +169,9 @@ import io.jooby.json.JacksonModule;
Structure messages depends/requires a javadoc:MessageDecoder[] and jadoc:MessageEncoder[]. In this
example both are provided by the JacksonModule.

=== Connection Timeouts
=== Options

==== Connection Timeouts
By default Jooby will timeout idle connections that have no activity after 5 minutes. You can
control this behaviour by setting the `websocket.idleTimeout` property:

Expand All @@ -181,3 +182,15 @@ websocket.idleTimeout = 1h
----

See https://github.com/lightbend/config/blob/master/HOCON.md#duration-format[duration format]

==== Max size

Max size is set to `128K` you can override it like:

.application.conf
[source, properties]
----
websocket.maxSize = 128K
----

See https://github.com/lightbend/config/blob/master/HOCON.md#size-in-bytes-format[sizes in bytes]
2 changes: 1 addition & 1 deletion jooby/src/main/java/io/jooby/WebSocket.java
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ interface OnError {
void onError(@Nonnull WebSocket ws, @Nonnull Throwable cause);
}

/** Max message size for websocket (13k). */
/** Max message size for websocket (128K). */
int MAX_BUFFER_SIZE = 131072;

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
package io.jooby.exception;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Parameter;
Expand All @@ -24,9 +26,9 @@ public class ProvisioningException extends BadRequestException {
* Creates a provisioning exception.
*
* @param parameter Failing parameter.
* @param cause Cause.
* @param cause Cause. Nullable.
*/
public ProvisioningException(@Nonnull Parameter parameter, @Nonnull Throwable cause) {
public ProvisioningException(@Nonnull Parameter parameter, @Nullable Throwable cause) {
this("Unable to provision parameter: '" + toString(parameter) + "', require by: " + toString(
parameter.getDeclaringExecutable()), cause);
}
Expand All @@ -37,7 +39,7 @@ public ProvisioningException(@Nonnull Parameter parameter, @Nonnull Throwable ca
* @param message Error message.
* @param cause Cause.
*/
public ProvisioningException(@Nonnull String message, @Nonnull Throwable cause) {
public ProvisioningException(@Nonnull String message, @Nullable Throwable cause) {
super(message, cause);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,6 @@
*/
package io.jooby.internal.jetty;

import io.jooby.Context;
import io.jooby.Server;
import io.jooby.SneakyThrows;
import io.jooby.WebSocket;
import io.jooby.WebSocketCloseStatus;
import io.jooby.WebSocketConfigurer;
import io.jooby.WebSocketMessage;
import org.eclipse.jetty.websocket.api.CloseException;
import org.eclipse.jetty.websocket.api.RemoteEndpoint;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketListener;
import org.eclipse.jetty.websocket.api.WriteCallback;

import javax.annotation.Nonnull;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
Expand All @@ -27,6 +13,24 @@
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

import javax.annotation.Nonnull;

import org.eclipse.jetty.websocket.api.CloseException;
import org.eclipse.jetty.websocket.api.RemoteEndpoint;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketListener;
import org.eclipse.jetty.websocket.api.WriteCallback;

import io.jooby.Context;
import io.jooby.Server;
import io.jooby.SneakyThrows;
import io.jooby.WebSocket;
import io.jooby.WebSocketCloseStatus;
import io.jooby.WebSocketConfigurer;
import io.jooby.WebSocketMessage;

public class JettyWebSocket implements WebSocketListener, WebSocketConfigurer, WebSocket,
WriteCallback {
Expand All @@ -41,8 +45,9 @@ public class JettyWebSocket implements WebSocketListener, WebSocketConfigurer, W
private Session session;
private WebSocket.OnConnect onConnectCallback;
private WebSocket.OnMessage onMessageCallback;
private WebSocket.OnClose onCloseCallback;
private AtomicReference<WebSocket.OnClose> onCloseCallback = new AtomicReference<>();
private WebSocket.OnError onErrorCallback;
private AtomicBoolean open = new AtomicBoolean(false);

public JettyWebSocket(JettyContext ctx) {
this.ctx = ctx;
Expand Down Expand Up @@ -73,6 +78,7 @@ public JettyWebSocket(JettyContext ctx) {

@Override public void onWebSocketConnect(Session session) {
try {
open.set(true);
this.session = session;
addSession(this);
if (onConnectCallback != null) {
Expand All @@ -86,7 +92,7 @@ public JettyWebSocket(JettyContext ctx) {
@Override public void onWebSocketError(Throwable x) {
// should close?
if (!isTimeout(x)) {
if (Server.connectionLost(x) || SneakyThrows.isFatal(x)) {
if (isOpen() && (Server.connectionLost(x) || SneakyThrows.isFatal(x))) {
handleClose(WebSocketCloseStatus.SERVER_ERROR);
}

Expand Down Expand Up @@ -131,7 +137,7 @@ private boolean isTimeout(Throwable x) {
}

@Nonnull @Override public WebSocketConfigurer onClose(@Nonnull WebSocket.OnClose callback) {
onCloseCallback = callback;
onCloseCallback.set(callback);
return this;
}

Expand All @@ -150,7 +156,7 @@ private boolean isTimeout(Throwable x) {
}

@Override public boolean isOpen() {
return session.isOpen();
return open.get() && session.isOpen();
}

@Nonnull @Override public WebSocket send(@Nonnull String message, boolean broadcast) {
Expand All @@ -167,7 +173,8 @@ private boolean isTimeout(Throwable x) {
onWebSocketError(x);
}
} else {
onWebSocketError(new IllegalStateException("Attempt to send a message on closed web socket"));
onWebSocketError(
new IllegalStateException("Attempt to send a message on closed web socket"));
}
}
return this;
Expand Down Expand Up @@ -209,14 +216,34 @@ private boolean isTimeout(Throwable x) {
}

private void handleClose(WebSocketCloseStatus closeStatus) {
WebSocket.OnClose callback = this.onCloseCallback.getAndSet(null);
Throwable cause = null;
// 1. close socket
try {
if (onCloseCallback != null) {
onCloseCallback.onClose(this, closeStatus);
if (isOpen()) {
session.close(closeStatus.getCode(), closeStatus.getReason());
}
} catch (Throwable x) {
onWebSocketError(x);
} finally {
removeSession(this);
cause = x;
}
open.set(false);
// fire callback:
if (callback != null) {
try {
callback.onClose(this, closeStatus);
} catch (Throwable x) {
if (cause != null) {
x.addSuppressed(cause);
}
cause = x;
}
}
// clear from active sessions:
removeSession(this);

if (cause != null) {
// fire error:
onWebSocketError(cause);
}
}

Expand Down
9 changes: 6 additions & 3 deletions modules/jooby-jetty/src/main/java/io/jooby/jetty/Jetty.java
Original file line number Diff line number Diff line change
Expand Up @@ -186,11 +186,14 @@ public class Jetty extends io.jooby.Server.Base {
context.setHandler(handler);
}
/* ********************************* WebSocket *************************************/
Config conf = application.getConfig();
int maxSize = conf.hasPath("websocket.maxSize")
? conf.getBytes("websocket.maxSize").intValue()
: WebSocket.MAX_BUFFER_SIZE;
context.setAttribute(DecoratedObjectFactory.ATTR, new DecoratedObjectFactory());
WebSocketPolicy policy = new WebSocketPolicy(WebSocketBehavior.SERVER);
policy.setMaxTextMessageBufferSize(WebSocket.MAX_BUFFER_SIZE);
policy.setMaxTextMessageSize(WebSocket.MAX_BUFFER_SIZE);
Config conf = application.getConfig();
policy.setMaxTextMessageBufferSize(maxSize);
policy.setMaxTextMessageSize(maxSize);
long timeout = conf.hasPath("websocket.idleTimeout")
? conf.getDuration("websocket.idleTimeout", TimeUnit.MILLISECONDS)
: TimeUnit.MINUTES.toMillis(5);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -373,12 +373,16 @@ boolean isHttpGet() {
@Nonnull @Override public Context upgrade(WebSocket.Initializer handler) {
try {
responseStarted = true;
Config conf = getRouter().getConfig();
int maxSize = conf.hasPath("websocket.maxSize")
? conf.getBytes("websocket.maxSize").intValue()
: WebSocket.MAX_BUFFER_SIZE;
String webSocketURL = getProtocol() + "://" + req.headers().get(HttpHeaderNames.HOST) + path;
WebSocketDecoderConfig config = WebSocketDecoderConfig.newBuilder()
.allowExtensions(true)
.allowMaskMismatch(false)
.withUTF8Validator(false)
.maxFramePayloadLength(WebSocket.MAX_BUFFER_SIZE)
.maxFramePayloadLength(maxSize)
.build();
webSocket = new NettyWebSocket(this);
handler.init(Context.readOnly(this), webSocket);
Expand All @@ -389,7 +393,6 @@ boolean isHttpGet() {
WebSocketServerHandshaker handshaker = factory.newHandshaker(webSocketRequest);
handshaker.handshake(ctx.channel(), webSocketRequest);
webSocket.fireConnect();
Config conf = getRouter().getConfig();
long timeout = conf.hasPath("websocket.idleTimeout")
? conf.getDuration("websocket.idleTimeout", MILLISECONDS)
: MINUTES.toMillis(5);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

import javax.annotation.Nonnull;

Expand Down Expand Up @@ -48,9 +50,10 @@ public class NettyWebSocket implements WebSocketConfigurer, WebSocket, ChannelFu
private ByteBuf buffer;
private WebSocket.OnConnect connectCallback;
private WebSocket.OnMessage messageCallback;
private OnClose onCloseCallback;
private AtomicReference<OnClose> onCloseCallback = new AtomicReference<>();
private OnError onErrorCallback;
private CountDownLatch ready = new CountDownLatch(1);
private AtomicBoolean open = new AtomicBoolean(false);

public NettyWebSocket(NettyContext ctx) {
this.netty = ctx;
Expand Down Expand Up @@ -112,7 +115,7 @@ private WebSocket send(ByteBuf buffer, boolean broadcast) {
}

public boolean isOpen() {
return netty.ctx.channel().isOpen();
return open.get() && netty.ctx.channel().isOpen();
}

@Override public WebSocketConfigurer onConnect(WebSocket.OnConnect callback) {
Expand All @@ -126,7 +129,7 @@ public boolean isOpen() {
}

@Override public WebSocketConfigurer onClose(WebSocket.OnClose callback) {
onCloseCallback = callback;
onCloseCallback.set(callback);
return this;
}

Expand Down Expand Up @@ -179,23 +182,22 @@ private void handleMessage(WebSocketFrame frame) {
}

private void handleClose(WebSocketCloseStatus closeStatus) {
OnClose callback = onCloseCallback.getAndSet(null);
if (isOpen()) {
// close socket:
netty.ctx.channel()
.writeAndFlush(
new CloseWebSocketFrame(closeStatus.getCode(), closeStatus.getReason()))
.addListener(ChannelFutureListener.CLOSE);
}
open.set(false);
try {
if (isOpen()) {
if (onCloseCallback != null) {
Runnable closeCallback = () -> {
try {
webSocketTask(() -> onCloseCallback.onClose(this, closeStatus), false).run();
} finally {
netty.ctx.channel()
.writeAndFlush(
new CloseWebSocketFrame(closeStatus.getCode(), closeStatus.getReason()))
.addListener(ChannelFutureListener.CLOSE);
}
};
fireCallback(closeCallback);
}
if (callback != null) {
// fire callback:
fireCallback(webSocketTask(() -> callback.onClose(this, closeStatus), false));
}
} finally {
// clear from active sessions:
this.netty.ctx.channel().attr(WS).set(null);
removeSession(this);
}
Expand Down Expand Up @@ -291,6 +293,7 @@ private Runnable webSocketTask(Runnable runnable, boolean isInit) {
private void waitForConnect() {
try {
ready.await();
open.set(true);
} catch (InterruptedException x) {
Thread.currentThread().interrupt();
}
Expand Down
7 changes: 7 additions & 0 deletions modules/jooby-utow/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@
</dependency>

<!-- utow -->
<dependency>
<!-- remove xnio once we upgrade to 2.2.18 + There is a Invalida Path on Windows-->
<groupId> org.jboss.xnio</groupId>
<artifactId>xnio-api</artifactId>
<version>3.8.7.Final</version>
</dependency>

<dependency>
<groupId>io.undertow</groupId>
<artifactId>undertow-core</artifactId>
Expand Down
Loading