-
Notifications
You must be signed in to change notification settings - Fork 629
/
WebsocketServerOperations.java
279 lines (248 loc) · 10.1 KB
/
WebsocketServerOperations.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
/*
* Copyright (c) 2011-2022 VMware, Inc. or its affiliates, All Rights Reserved.
*
* 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 reactor.netty5.http.server;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import io.netty5.buffer.Buffer;
import io.netty5.channel.Channel;
import io.netty5.channel.ChannelFutureListeners;
import io.netty5.channel.ChannelHandlerContext;
import io.netty5.handler.codec.http.DefaultFullHttpRequest;
import io.netty5.handler.codec.http.EmptyLastHttpContent;
import io.netty5.handler.codec.http.HttpHeaderNames;
import io.netty5.handler.codec.http.headers.HttpHeaders;
import io.netty5.handler.codec.http.FullHttpRequest;
import io.netty5.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty5.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty5.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty5.handler.codec.http.websocketx.WebSocketCloseStatus;
import io.netty5.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty5.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty5.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty5.util.concurrent.Future;
import io.netty5.util.concurrent.FutureListener;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;
import reactor.netty5.NettyOutbound;
import reactor.netty5.NettyPipeline;
import reactor.netty5.ReactorNetty;
import reactor.netty5.http.HttpOperations;
import reactor.netty5.http.websocket.WebsocketInbound;
import reactor.netty5.http.websocket.WebsocketOutbound;
import reactor.util.annotation.Nullable;
import static reactor.netty5.ReactorNetty.format;
/**
* Conversion between Netty types and Reactor types ({@link HttpOperations}
*
* @author Stephane Maldini
* @author Simon Baslé
*/
final class WebsocketServerOperations extends HttpServerOperations
implements WebsocketInbound, WebsocketOutbound {
final WebSocketServerHandshaker handshaker;
final Future<Void> handshakerResult;
final Sinks.One<WebSocketCloseStatus> onCloseState;
final boolean proxyPing;
volatile int closeSent;
WebsocketServerOperations(String wsUrl, WebsocketServerSpec websocketServerSpec, HttpServerOperations replaced) {
super(replaced);
this.proxyPing = websocketServerSpec.handlePing();
Channel channel = replaced.channel();
onCloseState = Sinks.unsafe().one();
// Handshake
WebSocketServerHandshakerFactory wsFactory =
new WebSocketServerHandshakerFactory(wsUrl, websocketServerSpec.protocols(), true, websocketServerSpec.maxFramePayloadLength());
handshaker = wsFactory.newHandshaker(replaced.nettyRequest);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(channel);
handshakerResult = null;
}
else {
removeHandler(NettyPipeline.HttpTrafficHandler);
removeHandler(NettyPipeline.AccessLogHandler);
removeHandler(NettyPipeline.HttpMetricsHandler);
FullHttpRequest request = new DefaultFullHttpRequest(replaced.version(), replaced.method(), replaced.uri(),
channel.bufferAllocator().allocate(0));
request.headers()
.set(replaced.nettyRequest.headers());
if (websocketServerSpec.compress()) {
removeHandler(NettyPipeline.CompressionHandler);
WebSocketServerCompressionHandler wsServerCompressionHandler =
new WebSocketServerCompressionHandler();
try {
wsServerCompressionHandler.channelRead(channel.pipeline()
.context(NettyPipeline.ReactiveBridge),
request);
addHandlerFirst(NettyPipeline.WsCompressionHandler, wsServerCompressionHandler);
}
catch (Throwable e) {
log.error(format(channel(), ""), e);
}
}
HttpHeaders responseHeaders = replaced.responseHeaders();
responseHeaders.remove(HttpHeaderNames.TRANSFER_ENCODING);
handshakerResult =
handshaker.handshake(channel,
request,
responseHeaders)
.addListener(f -> {
request.close();
if (replaced.rebind(this)) {
markPersistent(false);
// This change is needed after the Netty change https://github.com/netty/netty/pull/11966
channel.read();
}
else {
log.debug(format(channel, "Cannot bind WebsocketServerOperations after the handshake."));
}
});
}
}
@Override
public NettyOutbound send(Publisher<? extends Buffer> dataStream) {
return sendObject(Flux.from(dataStream).map(bytebufToWebsocketFrame));
}
@Override
public HttpHeaders headers() {
return requestHeaders();
}
@Override
public void onInboundNext(ChannelHandlerContext ctx, Object frame) {
if (frame instanceof CloseWebSocketFrame closeWebSocketFrame && closeWebSocketFrame.isFinalFragment()) {
if (log.isDebugEnabled()) {
log.debug(format(channel(), "CloseWebSocketFrame detected. Closing Websocket"));
}
CloseWebSocketFrame closeFrame = new CloseWebSocketFrame(true, closeWebSocketFrame.rsv(),
closeWebSocketFrame.binaryData());
if (closeFrame.statusCode() != -1) {
// terminate() will invoke onInboundComplete()
sendCloseNow(closeFrame, f -> terminate());
}
else {
// terminate() will invoke onInboundComplete()
sendCloseNow(closeFrame, WebSocketCloseStatus.EMPTY, f -> terminate());
}
return;
}
if (!this.proxyPing && frame instanceof PingWebSocketFrame pingWebSocketFrame) {
ctx.writeAndFlush(new PongWebSocketFrame(pingWebSocketFrame.binaryData()));
ctx.read();
return;
}
if (!(frame instanceof EmptyLastHttpContent)) {
super.onInboundNext(ctx, frame);
}
}
@Override
protected void onOutboundComplete() {
}
@Override
protected void onOutboundError(Throwable err) {
if (channel().isActive()) {
if (log.isDebugEnabled()) {
log.debug(format(channel(), "Outbound error happened"), err);
}
sendCloseNow(new CloseWebSocketFrame(channel().bufferAllocator(), WebSocketCloseStatus.PROTOCOL_ERROR),
f -> terminate());
}
}
@Override
protected void onInboundCancel() {
if (log.isDebugEnabled()) {
log.debug(format(channel(), "Cancelling Websocket inbound. Closing Websocket"));
}
sendCloseNow(new CloseWebSocketFrame(true, 0, channel().bufferAllocator().allocate(0)),
WebSocketCloseStatus.ABNORMAL_CLOSURE, f -> terminate());
}
@Override
public Mono<Void> sendClose() {
return sendClose(new CloseWebSocketFrame(true, 0, channel().bufferAllocator().allocate(0)));
}
@Override
public Mono<Void> sendClose(int rsv) {
return sendClose(new CloseWebSocketFrame(channel().bufferAllocator(), true, rsv));
}
@Override
public Mono<Void> sendClose(int statusCode, @Nullable String reasonText) {
return sendClose(new CloseWebSocketFrame(channel().bufferAllocator(), statusCode, reasonText));
}
@Override
public Mono<Void> sendClose(int rsv, int statusCode, @Nullable String reasonText) {
return sendClose(new CloseWebSocketFrame(channel().bufferAllocator(), true, rsv, statusCode, reasonText));
}
@Override
@SuppressWarnings("unchecked")
public Mono<WebSocketCloseStatus> receiveCloseStatus() {
return onCloseState.asMono().or((Mono) onTerminate());
}
Mono<Void> sendClose(CloseWebSocketFrame frame) {
if (CLOSE_SENT.get(this) == 0) {
//commented for now as we assume the close is always scheduled (deferFuture runs)
//onTerminate().subscribe(null, null, () -> ReactorNetty.safeRelease(frame));
return Mono.fromCompletionStage(() -> {
if (CLOSE_SENT.getAndSet(this, 1) == 0) {
discard();
// EmitResult is ignored as CLOSE_SENT guarantees that there will be only one emission
// Whether there are subscribers or the subscriber cancels is not of interest
// Evaluated EmitResult: FAIL_TERMINATED, FAIL_OVERFLOW, FAIL_CANCELLED, FAIL_NON_SERIALIZED
// FAIL_ZERO_SUBSCRIBER
onCloseState.tryEmitValue(new WebSocketCloseStatus(frame.statusCode(), frame.reasonText()));
return channel().writeAndFlush(frame)
.addListener(channel(), ChannelFutureListeners.CLOSE)
.asStage();
}
frame.close();
return channel().newSucceededFuture().asStage();
}).doOnCancel(() -> ReactorNetty.safeRelease(frame));
}
frame.close();
return Mono.empty();
}
void sendCloseNow(CloseWebSocketFrame frame, FutureListener<Void> listener) {
sendCloseNow(frame, new WebSocketCloseStatus(frame.statusCode(), frame.reasonText()), listener);
}
void sendCloseNow(CloseWebSocketFrame frame, WebSocketCloseStatus closeStatus, FutureListener<Void> listener) {
if (!frame.isFinalFragment()) {
channel().writeAndFlush(frame);
return;
}
if (CLOSE_SENT.getAndSet(this, 1) == 0) {
// EmitResult is ignored as CLOSE_SENT guarantees that there will be only one emission
// Whether there are subscribers or the subscriber cancels is not of interest
// Evaluated EmitResult: FAIL_TERMINATED, FAIL_OVERFLOW, FAIL_CANCELLED, FAIL_NON_SERIALIZED
// FAIL_ZERO_SUBSCRIBER
onCloseState.tryEmitValue(closeStatus);
channel().writeAndFlush(frame)
.addListener(listener);
}
else {
frame.close();
}
}
@Override
public boolean isWebsocket() {
return true;
}
@Override
@Nullable
public String selectedSubprotocol() {
return handshaker.selectedSubprotocol();
}
static final AtomicIntegerFieldUpdater<WebsocketServerOperations> CLOSE_SENT =
AtomicIntegerFieldUpdater.newUpdater(WebsocketServerOperations.class,
"closeSent");
}