/
WebSocketMessagingProvider.java
497 lines (445 loc) · 20.7 KB
/
WebSocketMessagingProvider.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
/*
* Copyright (c) 2019 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.ditto.client.messaging.internal;
import static org.eclipse.ditto.model.base.common.ConditionChecker.checkNotNull;
import java.io.IOException;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import org.eclipse.ditto.client.configuration.AuthenticationConfiguration;
import org.eclipse.ditto.client.configuration.MessagingConfiguration;
import org.eclipse.ditto.client.internal.DefaultThreadFactory;
import org.eclipse.ditto.client.internal.VersionReader;
import org.eclipse.ditto.client.internal.bus.AdaptableBus;
import org.eclipse.ditto.client.internal.bus.BusFactory;
import org.eclipse.ditto.client.messaging.AuthenticationException;
import org.eclipse.ditto.client.messaging.AuthenticationProvider;
import org.eclipse.ditto.client.messaging.MessagingException;
import org.eclipse.ditto.client.messaging.MessagingProvider;
import org.eclipse.ditto.json.JsonCollectors;
import org.eclipse.ditto.json.JsonValue;
import org.eclipse.ditto.model.base.acks.AcknowledgementLabel;
import org.eclipse.ditto.model.base.common.HttpStatusCode;
import org.eclipse.ditto.model.base.headers.DittoHeaderDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.neovisionaries.ws.client.OpeningHandshakeException;
import com.neovisionaries.ws.client.StatusLine;
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketAdapter;
import com.neovisionaries.ws.client.WebSocketError;
import com.neovisionaries.ws.client.WebSocketException;
import com.neovisionaries.ws.client.WebSocketFactory;
import com.neovisionaries.ws.client.WebSocketFrame;
/**
* Messaging Provider providing messaging access to Ditto WebSocket which is directly provided by Eclipse Ditto
* Gateway.
*
* @since 1.0.0
*/
public final class WebSocketMessagingProvider extends WebSocketAdapter implements MessagingProvider {
private static final String DITTO_CLIENT_USER_AGENT = "DittoClient/" + VersionReader.determineClientVersion();
private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketMessagingProvider.class);
private static final int CONNECTION_TIMEOUT_MS = 5000;
private static final int RECONNECTION_TIMEOUT_SECONDS = 5;
private final AdaptableBus adaptableBus;
private final MessagingConfiguration messagingConfiguration;
private final AuthenticationProvider<WebSocket> authenticationProvider;
private final ExecutorService callbackExecutor;
private final String sessionId;
private final ScheduledExecutorService connectExecutor;
private final Map<Object, String> subscriptionMessages;
private final AtomicBoolean reconnecting = new AtomicBoolean(false);
private final AtomicBoolean initializing = new AtomicBoolean(false);
private final CompletableFuture<WebSocket> initializationFuture = new CompletableFuture<>();
private final AtomicReference<WebSocket> webSocket;
/**
* Constructs a new {@code WsMessagingProvider}.
*
* @param adaptableBus the bus to publish all messages to.
* @param messagingConfiguration the specific configuration to apply.
* @param authenticationProvider provider for the authentication method with which to open the websocket.
* @param callbackExecutor the executor service to run callbacks with.
*/
private WebSocketMessagingProvider(final AdaptableBus adaptableBus,
final MessagingConfiguration messagingConfiguration,
final AuthenticationProvider<WebSocket> authenticationProvider,
final ExecutorService callbackExecutor) {
this.adaptableBus = adaptableBus;
this.messagingConfiguration = messagingConfiguration;
this.authenticationProvider = authenticationProvider;
this.callbackExecutor = callbackExecutor;
sessionId = authenticationProvider.getConfiguration().getSessionId();
connectExecutor = createConnectExecutor();
subscriptionMessages = new ConcurrentHashMap<>();
webSocket = new AtomicReference<>();
}
private static ScheduledExecutorService createConnectExecutor() {
return Executors.newScheduledThreadPool(1, new DefaultThreadFactory("ditto-client-reconnect"));
}
/**
* Returns a new {@code WebSocketMessagingProvider}.
*
* @param messagingConfiguration configuration of messaging.
* @param authenticationProvider provides authentication.
* @param callbackExecutor the executor for messages.
* @return the provider.
*/
public static WebSocketMessagingProvider newInstance(final MessagingConfiguration messagingConfiguration,
final AuthenticationProvider<WebSocket> authenticationProvider,
final ExecutorService callbackExecutor) {
checkNotNull(messagingConfiguration, "messagingConfiguration");
checkNotNull(authenticationProvider, "authenticationProvider");
checkNotNull(callbackExecutor, "callbackExecutor");
final AdaptableBus adaptableBus = BusFactory.createAdaptableBus();
return new WebSocketMessagingProvider(adaptableBus, messagingConfiguration, authenticationProvider,
callbackExecutor);
}
@Override
public AuthenticationConfiguration getAuthenticationConfiguration() {
return authenticationProvider.getConfiguration();
}
@Override
public MessagingConfiguration getMessagingConfiguration() {
return messagingConfiguration;
}
@Override
public ExecutorService getExecutorService() {
return callbackExecutor;
}
/**
* Return the executor for reconnection.
*
* @return the reconnect executor.
*/
public ScheduledExecutorService getConnectExecutor() {
return connectExecutor;
}
@Override
public AdaptableBus getAdaptableBus() {
return adaptableBus;
}
@Override
public MessagingProvider registerSubscriptionMessage(final Object key, final String message) {
subscriptionMessages.put(key, message);
return this;
}
@Override
public MessagingProvider unregisterSubscriptionMessage(final Object key) {
subscriptionMessages.remove(key);
return this;
}
@Override
public CompletionStage<?> initializeAsync() {
// this method may be called multiple times.
if (!initializing.getAndSet(true)) {
if (webSocket.get() == null) {
return connectWithPotentialRetries(this::createWebsocket, initializationFuture)
.thenApply(ws -> {
setWebSocket(ws);
return this;
});
}
}
// no need to set flags for subsequent calls of this method
return initializationFuture.thenApply(ws -> this);
}
private WebSocket createWebsocket() {
final WebSocketFactory webSocketFactory = WebSocketFactoryFactory.newWebSocketFactory(messagingConfiguration);
final WebSocket ws;
try {
final String declaredAcksJsonArrayString = messagingConfiguration.getDeclaredAcknowledgements()
.stream()
.map(AcknowledgementLabel::toString)
.map(JsonValue::of)
.collect(JsonCollectors.valuesToArray())
.toString();
ws = webSocketFactory.createSocket(messagingConfiguration.getEndpointUri())
.addHeader(DittoHeaderDefinition.DECLARED_ACKS.getKey(), declaredAcksJsonArrayString);
} catch (final IOException e) {
throw MessagingException.connectFailed(sessionId, e);
}
return ws;
}
/**
* Initiates the connection to the web socket by using the provided {@code ws} and applying the passed {@code
* webSocketListener} for web socket handling and incoming messages.
*
* @param ws the WebSocket instance to use for connecting.
* @return The connected websocket.
* be empty.
* @throws NullPointerException if any argument is {@code null}.
*/
private CompletionStage<WebSocket> initiateConnection(final WebSocket ws) {
checkNotNull(ws, "ws");
// TODO: make these configurable?
ws.addHeader("User-Agent", DITTO_CLIENT_USER_AGENT);
ws.setMaxPayloadSize(256 * 1024); // 256 KiB
ws.setMissingCloseFrameAllowed(true);
ws.setFrameQueueSize(0);
ws.setPingInterval(CONNECTION_TIMEOUT_MS);
authenticationProvider.prepareAuthentication(ws);
ws.addListener(this);
LOGGER.info("Connecting WebSocket on endpoint <{}>.", ws.getURI());
final Callable<WebSocket> connectCallable = ws.connectable();
return CompletableFuture.supplyAsync(() -> {
try {
return connectCallable.call();
} catch (final Throwable e) {
throw mapConnectError(e);
}
}, connectExecutor);
}
@Override
public void emit(final String message) {
sendToWebsocket(message);
}
private void sendToWebsocket(final String stringMessage) {
final WebSocket ws = webSocket.get();
if (ws != null && ws.isOpen()) {
LOGGER.debug("Client <{}>: Sending: {}", sessionId, stringMessage);
ws.sendText(stringMessage);
} else {
LOGGER.error("Client <{}>: WebSocket is not connected - going to discard message '{}'",
sessionId, stringMessage);
}
}
@Override
public void close() {
try {
LOGGER.debug("Client <{}>: Closing WebSocket client of endpoint <{}>.", sessionId,
messagingConfiguration.getEndpointUri());
// Scheduled tasks obtained from "shutdownNow" are useless because they overrides Runnable.run()
// to NOT run when the parent executor was shut down.
connectExecutor.shutdownNow();
authenticationProvider.destroy();
adaptableBus.shutdownExecutor();
final WebSocket ws = webSocket.get();
if (ws != null) {
ws.disconnect();
}
LOGGER.info("Client <{}>: WebSocket destroyed.", sessionId);
initializationFuture.completeExceptionally(MessagingException.connectFailed(sessionId,
new IllegalStateException("The client was destroyed.")));
} catch (final Exception e) {
LOGGER.info("Client <{}>: Exception occurred while trying to shutdown http client.", sessionId, e);
initializationFuture.completeExceptionally(MessagingException.connectFailed(sessionId, e));
}
}
@Override
public void onConnected(final WebSocket websocket, final Map<String, List<String>> headers) {
callbackExecutor.execute(() -> {
LOGGER.info("Client <{}>: WebSocket connection is established", sessionId);
if (!subscriptionMessages.isEmpty()) {
LOGGER.info("Client <{}>: Subscribing again for messages from backend after reconnection",
sessionId);
subscriptionMessages.values().forEach(this::emit);
}
});
}
@Override
public void onDisconnected(final WebSocket websocket, final WebSocketFrame serverCloseFrame,
final WebSocketFrame clientCloseFrame,
final boolean closedByServer) {
callbackExecutor.execute(() -> {
if (closedByServer) {
LOGGER.info(
"Client <{}>: WebSocket connection to endpoint <{}> was closed by Server with code <{}> and " +
"reason <{}>.", sessionId, messagingConfiguration.getEndpointUri(),
serverCloseFrame.getCloseCode(),
serverCloseFrame.getCloseReason());
handleReconnectionIfEnabled();
} else {
LOGGER.info("Client <{}>: WebSocket connection to endpoint <{}> was closed by client",
sessionId, messagingConfiguration.getEndpointUri());
}
});
}
@Override
public void onError(final WebSocket websocket, final WebSocketException cause) {
callbackExecutor.execute(() -> {
final String msgPattern = "Client <{}>: Error in WebSocket: {}";
final String errorMsg; // avoids cluttering the log
if (null != cause) {
errorMsg = cause.getClass().getSimpleName() + ": " + cause.getMessage();
} else {
errorMsg = "-";
}
LOGGER.error(msgPattern, sessionId, errorMsg);
handleReconnectionIfEnabled();
});
}
private CompletableFuture<WebSocket> connectWithPotentialRetries(final Supplier<WebSocket> webSocket,
final CompletableFuture<WebSocket> future) {
try {
if (messagingConfiguration.isInitialConnectRetryEnabled()) {
return Retry.retryTo("initialize WebSocket connection",
() -> initiateConnection(webSocket.get()))
.inClientSession(sessionId)
.withExecutors(connectExecutor, callbackExecutor)
.notifyOnError(messagingConfiguration.getConnectionErrorHandler().orElse(null))
.isRecoverable(WebSocketMessagingProvider::isRecoverable)
.completeFutureEventually(future);
} else {
LOGGER.info("Client <{}>: Initializing WebSocket connection without retrying", sessionId);
initiateConnection(webSocket.get()).whenComplete((result, error) -> {
if (error == null) {
future.complete(result);
} else {
future.completeExceptionally(error);
}
});
return future;
}
} catch (final Exception exception) {
future.completeExceptionally(exception);
return future;
}
}
private void handleReconnectionIfEnabled() {
if (messagingConfiguration.isReconnectEnabled()) {
// reconnect in a while if client was initially connected and we are not reconnecting already
if (reconnecting.compareAndSet(false, true)) {
LOGGER.info("Client <{}>: Reconnection is enabled. Reconnecting in <{}> seconds ...",
sessionId, RECONNECTION_TIMEOUT_SECONDS);
connectExecutor.schedule(this::reconnectWithRetries, RECONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
} else {
LOGGER.info("Client <{}>: Reconnection is NOT enabled. Closing client ...", sessionId);
close();
}
}
private void reconnectWithRetries() {
this.connectWithPotentialRetries(this::recreateWebSocket, new CompletableFuture<>())
.thenAccept(reconnectedWebSocket -> {
setWebSocket(reconnectedWebSocket);
reconnecting.set(false);
});
}
private void setWebSocket(final WebSocket webSocket) {
synchronized (this.webSocket) {
final WebSocket oldWebSocket = this.webSocket.get();
this.webSocket.set(webSocket);
try {
if (oldWebSocket != null && oldWebSocket != webSocket) {
oldWebSocket.disconnect();
}
} catch (final Exception exception) {
LOGGER.error("Client <{}>: Error disconnecting a previous websocket", sessionId, exception);
}
}
}
private WebSocket recreateWebSocket() {
LOGGER.info("Recreating Websocket..");
final WebSocket ws = webSocket.get();
if (ws == null) {
LOGGER.error("Client <{}>: attempt to recreate a null websocket", sessionId);
throw new IllegalStateException("Cannot recreate a null websocket. This method should not have been " +
"called without having created a WebSocket before.");
}
ws.clearHeaders();
ws.clearListeners();
try {
final String declaredAcksJsonArrayString = messagingConfiguration.getDeclaredAcknowledgements()
.stream()
.map(AcknowledgementLabel::toString)
.map(JsonValue::of)
.collect(JsonCollectors.valuesToArray())
.toString();
return ws.recreate(CONNECTION_TIMEOUT_MS)
.addHeader(DittoHeaderDefinition.DECLARED_ACKS.getKey(), declaredAcksJsonArrayString);
} catch (IOException e) {
throw MessagingException.recreateFailed(sessionId, e);
}
}
@Override
public void onBinaryMessage(final WebSocket websocket, final byte[] binary) {
callbackExecutor.execute(() -> {
final String stringMessage = new String(binary, StandardCharsets.UTF_8);
LOGGER.debug(
"Client <{}>: Received WebSocket byte array message <{}>, as string <{}> - don't know what to do" +
" with it!.", sessionId, binary, stringMessage);
});
}
@Override
public void onTextMessage(final WebSocket websocket, final String text) {
callbackExecutor.execute(() -> {
LOGGER.debug("Client <{}>: Received WebSocket string message <{}>", sessionId, text);
handleIncomingMessage(text);
});
}
private void handleIncomingMessage(final String message) {
adaptableBus.publish(message);
}
private RuntimeException mapConnectError(final Throwable e) {
final Throwable cause = getRootCause(e);
if (cause instanceof WebSocketException) {
LOGGER.error("Got exception: {}", cause.getMessage());
if (cause instanceof OpeningHandshakeException) {
final StatusLine statusLine = ((OpeningHandshakeException) cause).getStatusLine();
final HttpStatusCode httpStatusCode = HttpStatusCode.forInt(statusLine.getStatusCode())
.orElse(HttpStatusCode.INTERNAL_SERVER_ERROR);
if (httpStatusCode.isClientError()) {
switch (httpStatusCode) {
case UNAUTHORIZED:
return AuthenticationException.unauthorized(sessionId, cause);
case FORBIDDEN:
return AuthenticationException.forbidden(sessionId, cause);
default:
return AuthenticationException.withStatus(sessionId, cause, statusLine.getStatusCode(),
statusLine.getReasonPhrase() + ": " +
new String(((OpeningHandshakeException) cause).getBody()));
}
}
} else if (((WebSocketException) cause).getError() == WebSocketError.SOCKET_CONNECT_ERROR &&
cause.getCause() instanceof UnknownHostException) {
return MessagingException.connectFailed(sessionId, cause.getCause());
}
}
return MessagingException.connectFailed(sessionId, cause);
}
/**
* Test whether an exception to be delivered to error consumer can be recovered from.
* Reconnection will be attempted only if it is.
*
* @param error the error to deliver to any configured error consumer.
* @return whether the error can be recovered from.
* @see this#mapConnectError(Throwable)
*/
private static boolean isRecoverable(final Throwable error) {
// every exception should be recoverable
return true;
}
private static Throwable getRootCause(final Throwable e) {
if (e.getCause() == null) {
return e;
}
return (e instanceof CompletionException || e instanceof ExecutionException)
? getRootCause(e.getCause())
: e;
}
}