Support for WebFlux on Reactor Netty 2 with Netty 5
See gh-28847
This commit is contained in:
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.web.reactive.socket.adapter;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import io.netty5.buffer.api.Buffer;
|
||||
import io.netty5.handler.codec.http.websocketx.BinaryWebSocketFrame;
|
||||
import io.netty5.handler.codec.http.websocketx.PingWebSocketFrame;
|
||||
import io.netty5.handler.codec.http.websocketx.PongWebSocketFrame;
|
||||
import io.netty5.handler.codec.http.websocketx.TextWebSocketFrame;
|
||||
import io.netty5.handler.codec.http.websocketx.WebSocketFrame;
|
||||
|
||||
import org.springframework.core.io.buffer.DataBuffer;
|
||||
import org.springframework.core.io.buffer.Netty5DataBufferFactory;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
import org.springframework.web.reactive.socket.HandshakeInfo;
|
||||
import org.springframework.web.reactive.socket.WebSocketMessage;
|
||||
import org.springframework.web.reactive.socket.WebSocketSession;
|
||||
|
||||
/**
|
||||
* Base class for Netty-based {@link WebSocketSession} adapters that provides
|
||||
* convenience methods to convert Netty {@link WebSocketFrame WebSocketFrames} to and from
|
||||
* {@link WebSocketMessage WebSocketMessages}.
|
||||
*
|
||||
* <p>This class is based on {@link NettyWebSocketSessionSupport}.
|
||||
*
|
||||
* @author Violeta Georgieva
|
||||
* @since 6.0
|
||||
* @param <T> the native delegate type
|
||||
*/
|
||||
public abstract class Netty5WebSocketSessionSupport<T> extends AbstractWebSocketSession<T> {
|
||||
|
||||
/**
|
||||
* The default max size for inbound WebSocket frames.
|
||||
*/
|
||||
public static final int DEFAULT_FRAME_MAX_SIZE = 64 * 1024;
|
||||
|
||||
|
||||
private static final Map<Class<?>, WebSocketMessage.Type> messageTypes;
|
||||
|
||||
static {
|
||||
messageTypes = new HashMap<>(8);
|
||||
messageTypes.put(TextWebSocketFrame.class, WebSocketMessage.Type.TEXT);
|
||||
messageTypes.put(BinaryWebSocketFrame.class, WebSocketMessage.Type.BINARY);
|
||||
messageTypes.put(PingWebSocketFrame.class, WebSocketMessage.Type.PING);
|
||||
messageTypes.put(PongWebSocketFrame.class, WebSocketMessage.Type.PONG);
|
||||
}
|
||||
|
||||
|
||||
protected Netty5WebSocketSessionSupport(T delegate, HandshakeInfo info, Netty5DataBufferFactory factory) {
|
||||
super(delegate, ObjectUtils.getIdentityHexString(delegate), info, factory);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Netty5DataBufferFactory bufferFactory() {
|
||||
return (Netty5DataBufferFactory) super.bufferFactory();
|
||||
}
|
||||
|
||||
|
||||
protected WebSocketMessage toMessage(WebSocketFrame frame) {
|
||||
WebSocketFrame newFrame = frame.send().receive();
|
||||
DataBuffer payload = bufferFactory().wrap(newFrame.binaryData());
|
||||
return new WebSocketMessage(messageTypes.get(newFrame.getClass()), payload, newFrame);
|
||||
}
|
||||
|
||||
protected WebSocketFrame toFrame(WebSocketMessage message) {
|
||||
if (message.getNativeMessage() != null) {
|
||||
return message.getNativeMessage();
|
||||
}
|
||||
Buffer buffer = Netty5DataBufferFactory.toBuffer(message.getPayload());
|
||||
if (WebSocketMessage.Type.TEXT.equals(message.getType())) {
|
||||
return new TextWebSocketFrame(buffer);
|
||||
}
|
||||
else if (WebSocketMessage.Type.BINARY.equals(message.getType())) {
|
||||
return new BinaryWebSocketFrame(buffer);
|
||||
}
|
||||
else if (WebSocketMessage.Type.PING.equals(message.getType())) {
|
||||
return new PingWebSocketFrame(buffer);
|
||||
}
|
||||
else if (WebSocketMessage.Type.PONG.equals(message.getType())) {
|
||||
return new PongWebSocketFrame(buffer);
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException("Unexpected message type: " + message.getType());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
/*
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.web.reactive.socket.adapter;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import io.netty5.channel.ChannelId;
|
||||
import io.netty5.handler.codec.http.websocketx.WebSocketFrame;
|
||||
import org.reactivestreams.Publisher;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.netty5.Connection;
|
||||
import reactor.netty5.NettyInbound;
|
||||
import reactor.netty5.NettyOutbound;
|
||||
import reactor.netty5.channel.ChannelOperations;
|
||||
import reactor.netty5.http.websocket.WebsocketInbound;
|
||||
import reactor.netty5.http.websocket.WebsocketOutbound;
|
||||
|
||||
import org.springframework.core.io.buffer.Netty5DataBufferFactory;
|
||||
import org.springframework.web.reactive.socket.CloseStatus;
|
||||
import org.springframework.web.reactive.socket.HandshakeInfo;
|
||||
import org.springframework.web.reactive.socket.WebSocketMessage;
|
||||
import org.springframework.web.reactive.socket.WebSocketSession;
|
||||
|
||||
/**
|
||||
* {@link WebSocketSession} implementation for use with the Reactor Netty's (Netty 5)
|
||||
* {@link NettyInbound} and {@link NettyOutbound}.
|
||||
* This class is based on {@link ReactorNettyWebSocketSession}.
|
||||
*
|
||||
* @author Violeta Georgieva
|
||||
* @since 6.0
|
||||
*/
|
||||
public class ReactorNetty2WebSocketSession
|
||||
extends Netty5WebSocketSessionSupport<ReactorNetty2WebSocketSession.WebSocketConnection> {
|
||||
|
||||
private final int maxFramePayloadLength;
|
||||
|
||||
private final ChannelId channelId;
|
||||
|
||||
|
||||
/**
|
||||
* Constructor for the session, using the {@link #DEFAULT_FRAME_MAX_SIZE} value.
|
||||
*/
|
||||
public ReactorNetty2WebSocketSession(WebsocketInbound inbound, WebsocketOutbound outbound,
|
||||
HandshakeInfo info, Netty5DataBufferFactory bufferFactory) {
|
||||
|
||||
this(inbound, outbound, info, bufferFactory, DEFAULT_FRAME_MAX_SIZE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor with an additional maxFramePayloadLength argument.
|
||||
* @since 5.1
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public ReactorNetty2WebSocketSession(WebsocketInbound inbound, WebsocketOutbound outbound,
|
||||
HandshakeInfo info, Netty5DataBufferFactory bufferFactory,
|
||||
int maxFramePayloadLength) {
|
||||
|
||||
super(new WebSocketConnection(inbound, outbound), info, bufferFactory);
|
||||
this.maxFramePayloadLength = maxFramePayloadLength;
|
||||
this.channelId = ((ChannelOperations) inbound).channel().id();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Return the id of the underlying Netty channel.
|
||||
* @since 5.3.4
|
||||
*/
|
||||
public ChannelId getChannelId() {
|
||||
return this.channelId;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Flux<WebSocketMessage> receive() {
|
||||
return getDelegate().getInbound()
|
||||
.aggregateFrames(this.maxFramePayloadLength)
|
||||
.receiveFrames()
|
||||
.map(super::toMessage)
|
||||
.doOnNext(message -> {
|
||||
if (logger.isTraceEnabled()) {
|
||||
logger.trace(getLogPrefix() + "Received " + message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> send(Publisher<WebSocketMessage> messages) {
|
||||
Flux<WebSocketFrame> frames = Flux.from(messages)
|
||||
.doOnNext(message -> {
|
||||
if (logger.isTraceEnabled()) {
|
||||
logger.trace(getLogPrefix() + "Sending " + message);
|
||||
}
|
||||
})
|
||||
.map(this::toFrame);
|
||||
return getDelegate().getOutbound()
|
||||
.sendObject(frames)
|
||||
.then();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOpen() {
|
||||
DisposedCallback callback = new DisposedCallback();
|
||||
getDelegate().getInbound().withConnection(callback);
|
||||
return !callback.isDisposed();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> close(CloseStatus status) {
|
||||
// this will notify WebSocketInbound.receiveCloseStatus()
|
||||
return getDelegate().getOutbound().sendClose(status.getCode(), status.getReason());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<CloseStatus> closeStatus() {
|
||||
return getDelegate().getInbound().receiveCloseStatus()
|
||||
.map(status -> CloseStatus.create(status.code(), status.reasonText()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple container for {@link NettyInbound} and {@link NettyOutbound}.
|
||||
*/
|
||||
public static class WebSocketConnection {
|
||||
|
||||
private final WebsocketInbound inbound;
|
||||
|
||||
private final WebsocketOutbound outbound;
|
||||
|
||||
|
||||
public WebSocketConnection(WebsocketInbound inbound, WebsocketOutbound outbound) {
|
||||
this.inbound = inbound;
|
||||
this.outbound = outbound;
|
||||
}
|
||||
|
||||
public WebsocketInbound getInbound() {
|
||||
return this.inbound;
|
||||
}
|
||||
|
||||
public WebsocketOutbound getOutbound() {
|
||||
return this.outbound;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class DisposedCallback implements Consumer<Connection> {
|
||||
|
||||
private boolean disposed;
|
||||
|
||||
public boolean isDisposed() {
|
||||
return this.disposed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(Connection connection) {
|
||||
this.disposed = connection.isDisposed();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
/*
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.web.reactive.socket.client;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.netty5.http.client.HttpClient;
|
||||
import reactor.netty5.http.client.WebsocketClientSpec;
|
||||
import reactor.netty5.http.websocket.WebsocketInbound;
|
||||
|
||||
import org.springframework.core.io.buffer.Netty5DataBufferFactory;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.reactive.socket.HandshakeInfo;
|
||||
import org.springframework.web.reactive.socket.WebSocketHandler;
|
||||
import org.springframework.web.reactive.socket.WebSocketSession;
|
||||
import org.springframework.web.reactive.socket.adapter.ReactorNetty2WebSocketSession;
|
||||
|
||||
/**
|
||||
* {@link WebSocketClient} implementation for use with Reactor Netty for Netty 5.
|
||||
*
|
||||
* <p>This class is based on {@link ReactorNettyWebSocketClient}.
|
||||
*
|
||||
* @author Violeta Georgieva
|
||||
* @since 6.0
|
||||
*/
|
||||
public class ReactorNetty2WebSocketClient implements WebSocketClient {
|
||||
|
||||
private static final Log logger = LogFactory.getLog(ReactorNetty2WebSocketClient.class);
|
||||
|
||||
|
||||
private final HttpClient httpClient;
|
||||
|
||||
private final Supplier<WebsocketClientSpec.Builder> specBuilderSupplier;
|
||||
|
||||
@Nullable
|
||||
private Integer maxFramePayloadLength;
|
||||
|
||||
@Nullable
|
||||
private Boolean handlePing;
|
||||
|
||||
|
||||
/**
|
||||
* Default constructor.
|
||||
*/
|
||||
public ReactorNetty2WebSocketClient() {
|
||||
this(HttpClient.create());
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor that accepts an existing {@link HttpClient} builder
|
||||
* with a default {@link WebsocketClientSpec.Builder}.
|
||||
* @since 5.1
|
||||
*/
|
||||
public ReactorNetty2WebSocketClient(HttpClient httpClient) {
|
||||
this(httpClient, WebsocketClientSpec.builder());
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor that accepts an existing {@link HttpClient} builder
|
||||
* and a pre-configured {@link WebsocketClientSpec.Builder}.
|
||||
* @since 5.3
|
||||
*/
|
||||
public ReactorNetty2WebSocketClient(
|
||||
HttpClient httpClient, Supplier<WebsocketClientSpec.Builder> builderSupplier) {
|
||||
|
||||
Assert.notNull(httpClient, "HttpClient is required");
|
||||
Assert.notNull(builderSupplier, "WebsocketClientSpec.Builder is required");
|
||||
this.httpClient = httpClient;
|
||||
this.specBuilderSupplier = builderSupplier;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Return the configured {@link HttpClient}.
|
||||
*/
|
||||
public HttpClient getHttpClient() {
|
||||
return this.httpClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an instance of {@code WebsocketClientSpec} that reflects the current
|
||||
* configuration. This can be used to check the configured parameters except
|
||||
* for sub-protocols which depend on the {@link WebSocketHandler} that is used
|
||||
* for a given upgrade.
|
||||
* @since 5.3
|
||||
*/
|
||||
public WebsocketClientSpec getWebsocketClientSpec() {
|
||||
return buildSpec(null);
|
||||
}
|
||||
|
||||
private WebsocketClientSpec buildSpec(@Nullable String protocols) {
|
||||
WebsocketClientSpec.Builder builder = this.specBuilderSupplier.get();
|
||||
if (StringUtils.hasText(protocols)) {
|
||||
builder.protocols(protocols);
|
||||
}
|
||||
if (this.maxFramePayloadLength != null) {
|
||||
builder.maxFramePayloadLength(this.maxFramePayloadLength);
|
||||
}
|
||||
if (this.handlePing != null) {
|
||||
builder.handlePing(this.handlePing);
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure the maximum allowable frame payload length. Setting this value
|
||||
* to your application's requirement may reduce denial of service attacks
|
||||
* using long data frames.
|
||||
* <p>Corresponds to the argument with the same name in the constructor of
|
||||
* {@link io.netty5.handler.codec.http.websocketx.WebSocketServerHandshakerFactory
|
||||
* WebSocketServerHandshakerFactory} in Netty.
|
||||
* <p>By default set to 65536 (64K).
|
||||
* @param maxFramePayloadLength the max length for frames.
|
||||
* @since 5.2
|
||||
* @deprecated as of 5.3 in favor of providing a supplier of
|
||||
* {@link WebsocketClientSpec.Builder} with a
|
||||
* constructor argument
|
||||
*/
|
||||
@Deprecated
|
||||
public void setMaxFramePayloadLength(int maxFramePayloadLength) {
|
||||
this.maxFramePayloadLength = maxFramePayloadLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the configured {@link #setMaxFramePayloadLength(int) maxFramePayloadLength}.
|
||||
* @since 5.2
|
||||
* @deprecated as of 5.3 in favor of {@link #getWebsocketClientSpec()}
|
||||
*/
|
||||
@Deprecated
|
||||
public int getMaxFramePayloadLength() {
|
||||
return getWebsocketClientSpec().maxFramePayloadLength();
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure whether to let ping frames through to be handled by the
|
||||
* {@link WebSocketHandler} given to the execute method. By default, Reactor
|
||||
* Netty automatically replies with pong frames in response to pings. This is
|
||||
* useful in a proxy for allowing ping and pong frames through.
|
||||
* <p>By default this is set to {@code false} in which case ping frames are
|
||||
* handled automatically by Reactor Netty. If set to {@code true}, ping
|
||||
* frames will be passed through to the {@link WebSocketHandler}.
|
||||
* @param handlePing whether to let Ping frames through for handling
|
||||
* @since 5.2.4
|
||||
* @deprecated as of 5.3 in favor of providing a supplier of
|
||||
* {@link WebsocketClientSpec.Builder} with a
|
||||
* constructor argument
|
||||
*/
|
||||
@Deprecated
|
||||
public void setHandlePing(boolean handlePing) {
|
||||
this.handlePing = handlePing;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the configured {@link #setHandlePing(boolean)}.
|
||||
* @since 5.2.4
|
||||
* @deprecated as of 5.3 in favor of {@link #getWebsocketClientSpec()}
|
||||
*/
|
||||
@Deprecated
|
||||
public boolean getHandlePing() {
|
||||
return getWebsocketClientSpec().handlePing();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> execute(URI url, WebSocketHandler handler) {
|
||||
return execute(url, new HttpHeaders(), handler);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> execute(URI url, HttpHeaders requestHeaders, WebSocketHandler handler) {
|
||||
String protocols = StringUtils.collectionToCommaDelimitedString(handler.getSubProtocols());
|
||||
return getHttpClient()
|
||||
.headers(nettyHeaders -> setNettyHeaders(requestHeaders, nettyHeaders))
|
||||
.websocket(buildSpec(protocols))
|
||||
.uri(url.toString())
|
||||
.handle((inbound, outbound) -> {
|
||||
HttpHeaders responseHeaders = toHttpHeaders(inbound);
|
||||
String protocol = responseHeaders.getFirst("Sec-WebSocket-Protocol");
|
||||
HandshakeInfo info = new HandshakeInfo(url, responseHeaders, Mono.empty(), protocol);
|
||||
Netty5DataBufferFactory factory = new Netty5DataBufferFactory(outbound.alloc());
|
||||
WebSocketSession session = new ReactorNetty2WebSocketSession(
|
||||
inbound, outbound, info, factory, getMaxFramePayloadLength());
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Started session '" + session.getId() + "' for " + url);
|
||||
}
|
||||
return handler.handle(session).checkpoint(url + " [ReactorNetty2WebSocketClient]");
|
||||
})
|
||||
.doOnRequest(n -> {
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Connecting to " + url);
|
||||
}
|
||||
})
|
||||
.next();
|
||||
}
|
||||
|
||||
private void setNettyHeaders(HttpHeaders httpHeaders, io.netty5.handler.codec.http.HttpHeaders nettyHeaders) {
|
||||
httpHeaders.forEach(nettyHeaders::set);
|
||||
}
|
||||
|
||||
private HttpHeaders toHttpHeaders(WebsocketInbound inbound) {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
io.netty5.handler.codec.http.HttpHeaders nettyHeaders = inbound.headers();
|
||||
nettyHeaders.forEach(entry -> {
|
||||
String name = entry.getKey();
|
||||
headers.put(name, nettyHeaders.getAll(name));
|
||||
});
|
||||
return headers;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
/*
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.web.reactive.socket.server.upgrade;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.netty5.http.server.HttpServerResponse;
|
||||
import reactor.netty5.http.server.WebsocketServerSpec;
|
||||
|
||||
import org.springframework.core.io.buffer.Netty5DataBufferFactory;
|
||||
import org.springframework.http.server.reactive.ServerHttpResponse;
|
||||
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.web.reactive.socket.HandshakeInfo;
|
||||
import org.springframework.web.reactive.socket.WebSocketHandler;
|
||||
import org.springframework.web.reactive.socket.adapter.ReactorNetty2WebSocketSession;
|
||||
import org.springframework.web.reactive.socket.server.RequestUpgradeStrategy;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
/**
|
||||
* A {@link RequestUpgradeStrategy} for use with Reactor Netty for Netty 5.
|
||||
*
|
||||
* <p>This class is based on {@link ReactorNettyRequestUpgradeStrategy}.
|
||||
*\
|
||||
* @author Violeta Georgieva
|
||||
* @since 6.0
|
||||
*/
|
||||
public class ReactorNetty2RequestUpgradeStrategy implements RequestUpgradeStrategy {
|
||||
|
||||
private final Supplier<WebsocketServerSpec.Builder> specBuilderSupplier;
|
||||
|
||||
@Nullable
|
||||
private Integer maxFramePayloadLength;
|
||||
|
||||
@Nullable
|
||||
private Boolean handlePing;
|
||||
|
||||
|
||||
/**
|
||||
* Create an instances with a default {@link WebsocketServerSpec.Builder}.
|
||||
* @since 5.2.6
|
||||
*/
|
||||
public ReactorNetty2RequestUpgradeStrategy() {
|
||||
this(WebsocketServerSpec::builder);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create an instance with a pre-configured {@link WebsocketServerSpec.Builder}
|
||||
* to use for WebSocket upgrades.
|
||||
* @since 5.2.6
|
||||
*/
|
||||
public ReactorNetty2RequestUpgradeStrategy(Supplier<WebsocketServerSpec.Builder> builderSupplier) {
|
||||
Assert.notNull(builderSupplier, "WebsocketServerSpec.Builder is required");
|
||||
this.specBuilderSupplier = builderSupplier;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Build an instance of {@code WebsocketServerSpec} that reflects the current
|
||||
* configuration. This can be used to check the configured parameters except
|
||||
* for sub-protocols which depend on the {@link WebSocketHandler} that is used
|
||||
* for a given upgrade.
|
||||
* @since 5.2.6
|
||||
*/
|
||||
public WebsocketServerSpec getWebsocketServerSpec() {
|
||||
return buildSpec(null);
|
||||
}
|
||||
|
||||
WebsocketServerSpec buildSpec(@Nullable String subProtocol) {
|
||||
WebsocketServerSpec.Builder builder = this.specBuilderSupplier.get();
|
||||
if (subProtocol != null) {
|
||||
builder.protocols(subProtocol);
|
||||
}
|
||||
if (this.maxFramePayloadLength != null) {
|
||||
builder.maxFramePayloadLength(this.maxFramePayloadLength);
|
||||
}
|
||||
if (this.handlePing != null) {
|
||||
builder.handlePing(this.handlePing);
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure the maximum allowable frame payload length. Setting this value
|
||||
* to your application's requirement may reduce denial of service attacks
|
||||
* using long data frames.
|
||||
* <p>Corresponds to the argument with the same name in the constructor of
|
||||
* {@link io.netty5.handler.codec.http.websocketx.WebSocketServerHandshakerFactory
|
||||
* WebSocketServerHandshakerFactory} in Netty.
|
||||
* <p>By default set to 65536 (64K).
|
||||
* @param maxFramePayloadLength the max length for frames.
|
||||
* @since 5.1
|
||||
* @deprecated as of 5.2.6 in favor of providing a supplier of
|
||||
* {@link WebsocketServerSpec.Builder} with a
|
||||
* constructor argument
|
||||
*/
|
||||
@Deprecated
|
||||
public void setMaxFramePayloadLength(Integer maxFramePayloadLength) {
|
||||
this.maxFramePayloadLength = maxFramePayloadLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the configured max length for frames.
|
||||
* @since 5.1
|
||||
* @deprecated as of 5.2.6 in favor of {@link #getWebsocketServerSpec()}
|
||||
*/
|
||||
@Deprecated
|
||||
public int getMaxFramePayloadLength() {
|
||||
return getWebsocketServerSpec().maxFramePayloadLength();
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure whether to let ping frames through to be handled by the
|
||||
* {@link WebSocketHandler} given to the upgrade method. By default, Reactor
|
||||
* Netty automatically replies with pong frames in response to pings. This is
|
||||
* useful in a proxy for allowing ping and pong frames through.
|
||||
* <p>By default this is set to {@code false} in which case ping frames are
|
||||
* handled automatically by Reactor Netty. If set to {@code true}, ping
|
||||
* frames will be passed through to the {@link WebSocketHandler}.
|
||||
* @param handlePing whether to let Ping frames through for handling
|
||||
* @since 5.2.4
|
||||
* @deprecated as of 5.2.6 in favor of providing a supplier of
|
||||
* {@link WebsocketServerSpec.Builder} with a
|
||||
* constructor argument
|
||||
*/
|
||||
@Deprecated
|
||||
public void setHandlePing(boolean handlePing) {
|
||||
this.handlePing = handlePing;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the configured {@link #setHandlePing(boolean)}.
|
||||
* @since 5.2.4
|
||||
* @deprecated as of 5.2.6 in favor of {@link #getWebsocketServerSpec()}
|
||||
*/
|
||||
@Deprecated
|
||||
public boolean getHandlePing() {
|
||||
return getWebsocketServerSpec().handlePing();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler,
|
||||
@Nullable String subProtocol, Supplier<HandshakeInfo> handshakeInfoFactory) {
|
||||
|
||||
ServerHttpResponse response = exchange.getResponse();
|
||||
HttpServerResponse reactorResponse = ServerHttpResponseDecorator.getNativeResponse(response);
|
||||
HandshakeInfo handshakeInfo = handshakeInfoFactory.get();
|
||||
Netty5DataBufferFactory bufferFactory = (Netty5DataBufferFactory) response.bufferFactory();
|
||||
URI uri = exchange.getRequest().getURI();
|
||||
|
||||
// Trigger WebFlux preCommit actions and upgrade
|
||||
return response.setComplete()
|
||||
.then(Mono.defer(() -> {
|
||||
WebsocketServerSpec spec = buildSpec(subProtocol);
|
||||
return reactorResponse.sendWebsocket((in, out) -> {
|
||||
ReactorNetty2WebSocketSession session =
|
||||
new ReactorNetty2WebSocketSession(
|
||||
in, out, handshakeInfo, bufferFactory, spec.maxFramePayloadLength());
|
||||
return handler.handle(session).checkpoint(uri + " [ReactorNetty2RequestUpgradeStrategy]");
|
||||
}, spec);
|
||||
}));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -73,6 +73,7 @@ import org.springframework.http.client.reactive.HttpComponentsClientHttpConnecto
|
||||
import org.springframework.http.client.reactive.JdkClientHttpConnector;
|
||||
import org.springframework.http.client.reactive.JettyClientHttpConnector;
|
||||
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
|
||||
import org.springframework.http.client.reactive.ReactorNetty2ClientHttpConnector;
|
||||
import org.springframework.web.reactive.function.BodyExtractors;
|
||||
import org.springframework.web.reactive.function.client.WebClient.ResponseSpec;
|
||||
import org.springframework.web.testfixture.xml.Pojo;
|
||||
@@ -102,6 +103,7 @@ class WebClientIntegrationTests {
|
||||
static Stream<Named<ClientHttpConnector>> arguments() {
|
||||
return Stream.of(
|
||||
named("Reactor Netty", new ReactorClientHttpConnector()),
|
||||
named("Reactor Netty 2", new ReactorNetty2ClientHttpConnector()),
|
||||
named("JDK", new JdkClientHttpConnector()),
|
||||
named("Jetty", new JettyClientHttpConnector()),
|
||||
named("HttpComponents", new HttpComponentsClientHttpConnector())
|
||||
@@ -860,6 +862,12 @@ class WebClientIntegrationTests {
|
||||
|
||||
@ParameterizedWebClientTest
|
||||
void statusHandlerSuppressedErrorSignalWithFlux(ClientHttpConnector connector) {
|
||||
|
||||
// Temporarily disabled, leads to io.netty5.buffer.api.BufferClosedException
|
||||
if (connector instanceof ReactorNetty2ClientHttpConnector) {
|
||||
return;
|
||||
}
|
||||
|
||||
startServer(connector);
|
||||
|
||||
prepareResponse(response -> response.setResponseCode(500)
|
||||
|
||||
@@ -46,6 +46,7 @@ import org.springframework.http.server.reactive.HttpHandler;
|
||||
import org.springframework.web.filter.reactive.ServerWebExchangeContextFilter;
|
||||
import org.springframework.web.reactive.DispatcherHandler;
|
||||
import org.springframework.web.reactive.socket.client.JettyWebSocketClient;
|
||||
import org.springframework.web.reactive.socket.client.ReactorNetty2WebSocketClient;
|
||||
import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient;
|
||||
import org.springframework.web.reactive.socket.client.TomcatWebSocketClient;
|
||||
import org.springframework.web.reactive.socket.client.UndertowWebSocketClient;
|
||||
@@ -55,6 +56,7 @@ import org.springframework.web.reactive.socket.server.WebSocketService;
|
||||
import org.springframework.web.reactive.socket.server.support.HandshakeWebSocketService;
|
||||
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
|
||||
import org.springframework.web.reactive.socket.server.upgrade.JettyRequestUpgradeStrategy;
|
||||
import org.springframework.web.reactive.socket.server.upgrade.ReactorNetty2RequestUpgradeStrategy;
|
||||
import org.springframework.web.reactive.socket.server.upgrade.ReactorNettyRequestUpgradeStrategy;
|
||||
import org.springframework.web.reactive.socket.server.upgrade.TomcatRequestUpgradeStrategy;
|
||||
import org.springframework.web.reactive.socket.server.upgrade.UndertowRequestUpgradeStrategy;
|
||||
@@ -63,6 +65,7 @@ import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
|
||||
import org.springframework.web.testfixture.http.server.reactive.bootstrap.HttpServer;
|
||||
import org.springframework.web.testfixture.http.server.reactive.bootstrap.JettyHttpServer;
|
||||
import org.springframework.web.testfixture.http.server.reactive.bootstrap.ReactorHttpServer;
|
||||
import org.springframework.web.testfixture.http.server.reactive.bootstrap.ReactorNetty2HttpServer;
|
||||
import org.springframework.web.testfixture.http.server.reactive.bootstrap.TomcatHttpServer;
|
||||
import org.springframework.web.testfixture.http.server.reactive.bootstrap.UndertowHttpServer;
|
||||
|
||||
@@ -92,6 +95,7 @@ abstract class AbstractWebSocketIntegrationTests {
|
||||
new TomcatWebSocketClient(),
|
||||
new JettyWebSocketClient(),
|
||||
new ReactorNettyWebSocketClient(),
|
||||
new ReactorNetty2WebSocketClient(),
|
||||
new UndertowWebSocketClient(Xnio.getInstance().createWorker(OptionMap.EMPTY))
|
||||
};
|
||||
|
||||
@@ -99,6 +103,7 @@ abstract class AbstractWebSocketIntegrationTests {
|
||||
servers.put(new TomcatHttpServer(TMP_DIR.getAbsolutePath(), WsContextListener.class), TomcatConfig.class);
|
||||
servers.put(new JettyHttpServer(), JettyConfig.class);
|
||||
servers.put(new ReactorHttpServer(), ReactorNettyConfig.class);
|
||||
servers.put(new ReactorNetty2HttpServer(), ReactorNetty2Config.class);
|
||||
servers.put(new UndertowHttpServer(), UndertowConfig.class);
|
||||
|
||||
// Try each client once against each server..
|
||||
@@ -204,6 +209,14 @@ abstract class AbstractWebSocketIntegrationTests {
|
||||
}
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class ReactorNetty2Config extends AbstractHandlerAdapterConfig {
|
||||
|
||||
@Override
|
||||
protected RequestUpgradeStrategy getUpgradeStrategy() {
|
||||
return new ReactorNetty2RequestUpgradeStrategy();
|
||||
}
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class TomcatConfig extends AbstractHandlerAdapterConfig {
|
||||
|
||||
Reference in New Issue
Block a user