-
Notifications
You must be signed in to change notification settings - Fork 526
/
ConnectionHandler.java
405 lines (342 loc) · 11.7 KB
/
ConnectionHandler.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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/*
* Copyright 2021 Red Hat, Inc.
*
* Red Hat licenses this file to you 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:
*
* http://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.vertx.ext.web.handler.graphql.impl.ws;
import graphql.ExecutionInput;
import graphql.ExecutionResult;
import graphql.execution.preparsed.persisted.PersistedQuerySupport;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Promise;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.ServerWebSocket;
import io.vertx.core.impl.ContextInternal;
import io.vertx.core.impl.logging.Logger;
import io.vertx.core.impl.logging.LoggerFactory;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.graphql.ExecutionInputBuilderWithContext;
import io.vertx.ext.web.handler.graphql.impl.GraphQLQuery;
import io.vertx.ext.web.handler.graphql.ws.ConnectionInitEvent;
import io.vertx.ext.web.handler.graphql.ws.Message;
import io.vertx.ext.web.handler.graphql.ws.MessageType;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscription;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import static io.vertx.ext.web.handler.graphql.impl.ErrorUtil.toJsonObject;
import static io.vertx.ext.web.handler.graphql.ws.MessageType.*;
public class ConnectionHandler {
private static final Logger log = LoggerFactory.getLogger(ConnectionHandler.class);
private final GraphQLWSHandlerImpl graphQLWSHandler;
private final ContextInternal context;
private final ServerWebSocket socket;
private final RoutingContext routingContext;
private ConnectionState state;
public ConnectionHandler(GraphQLWSHandlerImpl graphQLWSHandler, ContextInternal context, ServerWebSocket socket, RoutingContext routingContext) {
this.graphQLWSHandler = graphQLWSHandler;
this.context = context;
this.socket = socket;
this.routingContext = routingContext;
state = new InitialState();
}
public void handleConnection() {
socket.closeHandler(this::close)
.binaryMessageHandler(this::handleBinaryMessage)
.textMessageHandler(this::handleTextMessage);
}
private void handleBinaryMessage(Buffer buffer) {
handleMessage(new JsonObject(buffer));
}
private void handleTextMessage(String text) {
handleMessage(new JsonObject(text));
}
private void handleMessage(JsonObject json) {
String typeStr = json.getString("type");
MessageType type = from(typeStr);
if (type == null) {
socket.close((short) 4400, "Unknown message type: " + typeStr);
return;
}
MessageImpl message = state.createMessage(type, json);
Handler<Message> mh = graphQLWSHandler.getMessageHandler();
if (mh != null) {
mh.handle(message);
}
state.handleMessage(message);
}
private void sendPong(MessageImpl msg) {
sendMessage(null, PONG, msg.message().getJsonObject("payload"));
}
private void sendMessage(String id, MessageType type, Object payload) {
JsonObject message = new JsonObject();
if (id != null) {
message.put("id", id);
}
message.put("type", type.getText());
if (payload != null) {
message.put("payload", payload);
}
socket.writeTextMessage(message.encode());
}
private void close(Void unused) {
state.close();
}
private interface ConnectionState {
MessageImpl createMessage(MessageType type, JsonObject message);
void handleMessage(MessageImpl msg);
void close();
}
private class InitialState implements ConnectionState, Handler<Long> {
final long timerId;
InitialState() {
timerId = context.setTimer(graphQLWSHandler.getConnectionInitWaitTimeout(), this);
}
@Override
public void handle(Long unused) {
socket.close((short) 4408, "Connection initialisation timeout");
}
@Override
public MessageImpl createMessage(MessageType type, JsonObject message) {
return new MessageImpl(socket, type, message);
}
@Override
public void handleMessage(MessageImpl msg) {
ServerWebSocket socket = msg.socket();
switch (msg.type()) {
case CONNECTION_INIT:
connectionInit(msg);
break;
case PING:
sendPong(msg);
break;
case PONG:
break;
default:
socket.close((short) 4401, "Unauthorized");
break;
}
}
void connectionInit(MessageImpl msg) {
context.owner().cancelTimer(timerId);
Handler<ConnectionInitEvent> connectionInitHandler = graphQLWSHandler.getConnectionInitHandler();
if (connectionInitHandler != null) {
Promise<Object> connectionPromise = context.promise();
state = new InitializingState(connectionPromise.future());
connectionInitHandler.handle(new ConnectionInitEventImpl(msg, connectionPromise));
} else {
sendMessage(null, CONNECTION_ACK, null);
state = new ReadyState(null);
}
}
@Override
public void close() {
context.owner().cancelTimer(timerId);
}
}
private class InitializingState implements ConnectionState, Handler<AsyncResult<Object>> {
InitializingState(Future<Object> connectionFuture) {
connectionFuture.onComplete(this);
}
@Override
public void handle(AsyncResult<Object> ar) {
if (ar.succeeded()) {
connect(ar.result());
} else {
log.trace("Failed to initialize GraphQLWS socket", ar.cause());
socket.close((short) 4401, "Unauthorized");
}
}
void connect(Object connectionParams) {
sendMessage(null, CONNECTION_ACK, null);
state = new ReadyState(connectionParams);
}
@Override
public MessageImpl createMessage(MessageType type, JsonObject message) {
return new MessageImpl(socket, type, message);
}
@Override
public void handleMessage(MessageImpl msg) {
switch (msg.type()) {
case CONNECTION_INIT:
socket.close((short) 4429, "Too many initialisation requests");
break;
case PING:
sendPong(msg);
break;
case PONG:
break;
default:
socket.close((short) 4401, "Unauthorized");
break;
}
}
@Override
public void close() {
}
}
private static final Subscription TRANSIENT_SUBSCRIPTION = new Subscription() {
@Override
public void request(long l) {
throw new IllegalStateException();
}
@Override
public void cancel() {
}
};
private class ReadyState implements ConnectionState {
final Object connectionParams;
final Executor executor;
final ConcurrentMap<String, Subscription> subscriptions;
class Subscriber implements org.reactivestreams.Subscriber<ExecutionResult> {
final String id;
volatile Subscription subscription;
Subscriber(String id) {
this.id = id;
}
@Override
public void onSubscribe(Subscription s) {
subscription = s;
if (!subscriptions.replace(id, TRANSIENT_SUBSCRIPTION, s)) {
s.cancel();
} else {
s.request(1);
}
}
@Override
public void onNext(ExecutionResult er) {
sendMessage(id, NEXT, new JsonObject(er.toSpecification()));
subscription.request(1);
}
@Override
public void onError(Throwable t) {
sendMessage(id, ERROR, new JsonArray().add(toJsonObject(t)));
subscriptions.remove(id);
}
@Override
public void onComplete() {
sendMessage(id, COMPLETE, null);
subscriptions.remove(id);
}
}
ReadyState(Object connectionParams) {
this.connectionParams = connectionParams;
executor = task -> context.runOnContext(v -> task.run());
subscriptions = new ConcurrentHashMap<>();
}
@Override
public MessageImpl createMessage(MessageType type, JsonObject message) {
return new MessageImpl(socket, type, message, connectionParams);
}
@Override
public void handleMessage(MessageImpl msg) {
switch (msg.type()) {
case PING:
sendPong(msg);
break;
case PONG:
break;
case SUBSCRIBE:
subscribe(msg);
break;
case COMPLETE:
unsubscribe(msg);
break;
default:
socket.close((short) 4400, "Unexpected message type: " + msg.type());
break;
}
}
void subscribe(MessageImpl msg) {
String id = msg.id();
if (id == null) {
socket.close((short) 4400, "Subscribe message must have an ID");
return;
}
if (subscriptions.putIfAbsent(id, TRANSIENT_SUBSCRIPTION) != null) {
socket.close((short) 4409, "Subscriber for " + id + " already exists");
return;
}
GraphQLQuery payload = new GraphQLQuery(msg.message().getJsonObject("payload"));
ExecutionInput.Builder builder = ExecutionInput.newExecutionInput();
String operationName = payload.getOperationName();
if (operationName != null) {
builder.operationName(operationName);
}
Map<String, Object> variables = payload.getVariables();
if (variables != null) {
builder.variables(variables);
}
Object initialValue = payload.getInitialValue();
if (initialValue != null) {
builder.root(initialValue);
}
Map<String, Object> extensions = payload.getExtensions();
if (extensions != null) {
builder.extensions(extensions);
}
String query = payload.getQuery();
if (query != null) {
builder.query(query);
} else if (extensions != null && extensions.containsKey("persistedQuery")) {
builder.query(PersistedQuerySupport.PERSISTED_QUERY_MARKER);
}
builder.graphQLContext(Collections.singletonMap(RoutingContext.class, routingContext));
Handler<ExecutionInputBuilderWithContext<Message>> beforeExecute = graphQLWSHandler.getBeforeExecute();
if (beforeExecute != null) {
beforeExecute.handle(new ExecutionInputBuilderWithContext<Message>() {
@Override
public Message context() {
return msg;
}
@Override
public ExecutionInput.Builder builder() {
return builder;
}
});
}
graphQLWSHandler.getGraphQL().executeAsync(builder).whenCompleteAsync((executionResult, throwable) -> {
if (throwable == null) {
if (executionResult.getData() instanceof Publisher) {
Publisher<ExecutionResult> data = executionResult.getData();
data.subscribe(new Subscriber(id));
} else {
subscriptions.remove(id);
sendMessage(id, NEXT, new JsonObject(executionResult.toSpecification()));
sendMessage(id, COMPLETE, null);
}
} else {
subscriptions.remove(id);
sendMessage(id, ERROR, new JsonArray().add(toJsonObject(throwable)));
}
}, executor);
}
void unsubscribe(MessageImpl msg) {
Subscription s = subscriptions.remove(msg.id());
if (s != null) {
s.cancel();
}
}
@Override
public void close() {
subscriptions.values().forEach(Subscription::cancel);
}
}
}