-
Notifications
You must be signed in to change notification settings - Fork 1k
/
NettyWebSocketClientHandler.java
264 lines (239 loc) · 11 KB
/
NettyWebSocketClientHandler.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
/*
* Copyright 2017-2020 original 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 io.micronaut.http.client.netty.websocket;
import io.micronaut.core.annotation.Internal;
import io.micronaut.core.bind.BoundExecutable;
import io.micronaut.core.bind.DefaultExecutableBinder;
import io.micronaut.core.bind.ExecutableBinder;
import io.micronaut.core.convert.value.ConvertibleValues;
import io.micronaut.core.type.Argument;
import io.micronaut.http.MutableHttpRequest;
import io.micronaut.http.bind.RequestBinderRegistry;
import io.micronaut.http.codec.MediaTypeCodecRegistry;
import io.micronaut.http.netty.websocket.AbstractNettyWebSocketHandler;
import io.micronaut.http.netty.websocket.NettyWebSocketSession;
import io.micronaut.http.uri.UriMatchInfo;
import io.micronaut.http.uri.UriMatchTemplate;
import io.micronaut.websocket.CloseReason;
import io.micronaut.websocket.WebSocketPongMessage;
import io.micronaut.websocket.annotation.ClientWebSocket;
import io.micronaut.websocket.bind.WebSocketState;
import io.micronaut.websocket.context.WebSocketBean;
import io.micronaut.websocket.exceptions.WebSocketClientException;
import io.micronaut.websocket.exceptions.WebSocketSessionException;
import io.micronaut.websocket.interceptor.WebSocketSessionAware;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;
import java.util.Collections;
import java.util.List;
/**
* Handler for WebSocket clients.
*
* @param <T> The type emitted.
* @author graemerocher
* @since 1.0
*/
@Internal
public class NettyWebSocketClientHandler<T> extends AbstractNettyWebSocketHandler {
private final WebSocketClientHandshaker handshaker;
/**
* Generic version of {@link #webSocketBean}.
*/
private final WebSocketBean<T> genericWebSocketBean;
private final Sinks.One<T> completion = Sinks.one();
private final UriMatchInfo matchInfo;
private final MediaTypeCodecRegistry codecRegistry;
private NettyWebSocketSession clientSession;
private FullHttpResponse handshakeResponse;
private Argument<?> clientBodyArgument;
private Argument<?> clientPongArgument;
/**
* Default constructor.
* @param request The originating request that created the WebSocket.
* @param webSocketBean The WebSocket client bean.
* @param handshaker The handshaker
* @param requestBinderRegistry The request binder registry
* @param mediaTypeCodecRegistry The media type codec registry
*/
public NettyWebSocketClientHandler(
MutableHttpRequest<?> request,
WebSocketBean<T> webSocketBean,
final WebSocketClientHandshaker handshaker,
RequestBinderRegistry requestBinderRegistry,
MediaTypeCodecRegistry mediaTypeCodecRegistry) {
super(null, requestBinderRegistry, mediaTypeCodecRegistry, webSocketBean, request, Collections.emptyMap(), handshaker.version(), handshaker.actualSubprotocol(), null);
this.codecRegistry = mediaTypeCodecRegistry;
this.handshaker = handshaker;
this.genericWebSocketBean = webSocketBean;
String clientPath = webSocketBean.getBeanDefinition().stringValue(ClientWebSocket.class).orElse("");
UriMatchTemplate matchTemplate = UriMatchTemplate.of(clientPath);
this.matchInfo = matchTemplate.match(request.getPath()).orElse(null);
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
if (idleStateEvent.state() == IdleState.ALL_IDLE && clientSession != null && clientSession.isOpen()) {
// close the connection if it is idle for too long
clientSession.close(CloseReason.NORMAL);
}
} else {
super.userEventTriggered(ctx, evt);
}
}
@Override
public Argument<?> getBodyArgument() {
return clientBodyArgument;
}
@Override
public Argument<?> getPongArgument() {
return clientPongArgument;
}
@Override
public NettyWebSocketSession getSession() {
return clientSession;
}
@Override
public void channelActive(final ChannelHandlerContext ctx) {
handshaker.handshake(ctx.channel()).addListener(future -> {
if (future.isSuccess()) {
ctx.channel().config().setAutoRead(true);
ctx.read();
} else {
completion.tryEmitError(future.cause());
}
});
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
final Channel ch = ctx.channel();
if (!handshaker.isHandshakeComplete()) {
// web socket client connected
FullHttpResponse res = (FullHttpResponse) msg;
this.handshakeResponse = res;
try {
handshaker.finishHandshake(ch, res);
} catch (Exception e) {
try {
completion.tryEmitError(new WebSocketClientException("Error finishing WebSocket handshake: " + e.getMessage(), e));
} finally {
// clientSession isn't set yet, so we do the close manually instead of through session.close
ch.writeAndFlush(new CloseWebSocketFrame(CloseReason.INTERNAL_ERROR.getCode(), CloseReason.INTERNAL_ERROR.getReason()));
ch.close();
}
return;
}
this.clientSession = createWebSocketSession(ctx);
T targetBean = genericWebSocketBean.getTarget();
if (targetBean instanceof WebSocketSessionAware) {
((WebSocketSessionAware) targetBean).setWebSocketSession(clientSession);
}
ExecutableBinder<WebSocketState> binder = new DefaultExecutableBinder<>();
BoundExecutable<?, ?> bound = binder.tryBind(messageHandler.getExecutableMethod(), webSocketBinder, new WebSocketState(clientSession, originatingRequest));
List<Argument<?>> unboundArguments = bound.getUnboundArguments();
if (unboundArguments.size() == 1) {
this.clientBodyArgument = unboundArguments.iterator().next();
} else {
this.clientBodyArgument = null;
try {
completion.tryEmitError(new WebSocketClientException("WebSocket @OnMessage method " + targetBean.getClass().getSimpleName() + "." + messageHandler.getExecutableMethod() + " should define exactly 1 message parameter, but found 2 possible candidates: " + unboundArguments));
} finally {
if (getSession().isOpen()) {
getSession().close(CloseReason.INTERNAL_ERROR);
}
}
return;
}
if (pongHandler != null) {
BoundExecutable<?, ?> boundPong = binder.tryBind(pongHandler.getExecutableMethod(), webSocketBinder, new WebSocketState(clientSession, originatingRequest));
List<Argument<?>> unboundPongArguments = boundPong.getUnboundArguments();
if (unboundPongArguments.size() == 1 && unboundPongArguments.get(0).isAssignableFrom(WebSocketPongMessage.class)) {
this.clientPongArgument = unboundPongArguments.get(0);
} else {
this.clientPongArgument = null;
try {
completion.tryEmitError(new WebSocketClientException("WebSocket @OnMessage pong handler method " + targetBean.getClass().getSimpleName() + "." + messageHandler.getExecutableMethod() + " should define exactly 1 pong message parameter, but found: " + unboundArguments));
} finally {
if (getSession().isOpen()) {
getSession().close(CloseReason.INTERNAL_ERROR);
}
}
return;
}
}
Flux.from(callOpenMethod(ctx)).subscribe(
o -> { },
error -> completion.tryEmitError(new WebSocketSessionException("Error opening WebSocket client session: " + error.getMessage(), error)),
() -> completion.tryEmitValue(targetBean)
);
return;
}
if (msg instanceof WebSocketFrame) {
handleWebSocketFrame(ctx, (WebSocketFrame) msg);
} else {
ctx.fireChannelRead(msg);
}
}
@Override
protected NettyWebSocketSession createWebSocketSession(ChannelHandlerContext ctx) {
if (ctx != null) {
return new NettyWebSocketSession(
handshakeResponse.headers().get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT),
ctx.channel(),
originatingRequest,
codecRegistry,
handshaker.version().toHttpHeaderValue(),
ctx.pipeline().get(SslHandler.class) != null
) {
@Override
public ConvertibleValues<Object> getUriVariables() {
if (matchInfo != null) {
return ConvertibleValues.of(matchInfo.getVariableValues());
}
return ConvertibleValues.empty();
}
};
}
return null;
}
@Override
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
completion.tryEmitError(cause);
super.exceptionCaught(ctx, cause);
}
public final Mono<T> getHandshakeCompletedMono() {
return completion.asMono();
}
@Override
protected void handleCloseReason(ChannelHandlerContext ctx, CloseReason cr, boolean writeCloseReason) {
if (!handshaker.isHandshakeComplete()) {
completion.tryEmitError(new WebSocketClientException("Error opening WebSocket client session: " + cr.getReason()));
return;
}
super.handleCloseReason(ctx, cr, writeCloseReason);
}
}