-
Notifications
You must be signed in to change notification settings - Fork 215
/
ConnectionPersistenceActor.java
1223 lines (1088 loc) · 58.2 KB
/
ConnectionPersistenceActor.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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2017 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.connectivity.service.messaging.persistence;
import static org.eclipse.ditto.base.model.common.ConditionChecker.checkNotNull;
import static org.eclipse.ditto.connectivity.api.ConnectivityMessagingConstants.CLUSTER_ROLE;
import java.text.MessageFormat;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.stream.StreamSupport;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.eclipse.ditto.base.model.exceptions.DittoRuntimeException;
import org.eclipse.ditto.base.model.exceptions.DittoRuntimeExceptionBuilder;
import org.eclipse.ditto.base.model.headers.DittoHeaders;
import org.eclipse.ditto.base.model.headers.WithDittoHeaders;
import org.eclipse.ditto.base.model.json.JsonSchemaVersion;
import org.eclipse.ditto.base.model.signals.SignalWithEntityId;
import org.eclipse.ditto.base.model.signals.commands.Command;
import org.eclipse.ditto.connectivity.api.BaseClientState;
import org.eclipse.ditto.connectivity.api.messaging.monitoring.logs.AddConnectionLogEntry;
import org.eclipse.ditto.connectivity.model.Connection;
import org.eclipse.ditto.connectivity.model.ConnectionId;
import org.eclipse.ditto.connectivity.model.ConnectionLifecycle;
import org.eclipse.ditto.connectivity.model.ConnectionMetrics;
import org.eclipse.ditto.connectivity.model.ConnectivityModelFactory;
import org.eclipse.ditto.connectivity.model.ConnectivityStatus;
import org.eclipse.ditto.connectivity.model.LogEntry;
import org.eclipse.ditto.connectivity.model.signals.commands.ConnectivityCommand;
import org.eclipse.ditto.connectivity.model.signals.commands.ConnectivityCommandInterceptor;
import org.eclipse.ditto.connectivity.model.signals.commands.exceptions.ConnectionFailedException;
import org.eclipse.ditto.connectivity.model.signals.commands.exceptions.ConnectionNotAccessibleException;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.CheckConnectionLogsActive;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.CloseConnection;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.EnableConnectionLogs;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.OpenConnection;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.TestConnection;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.TestConnectionResponse;
import org.eclipse.ditto.connectivity.model.signals.commands.query.ConnectivityQueryCommand;
import org.eclipse.ditto.connectivity.model.signals.commands.query.RetrieveConnectionLogs;
import org.eclipse.ditto.connectivity.model.signals.commands.query.RetrieveConnectionLogsResponse;
import org.eclipse.ditto.connectivity.model.signals.commands.query.RetrieveConnectionMetrics;
import org.eclipse.ditto.connectivity.model.signals.commands.query.RetrieveConnectionMetricsResponse;
import org.eclipse.ditto.connectivity.model.signals.commands.query.RetrieveConnectionStatus;
import org.eclipse.ditto.connectivity.model.signals.commands.query.RetrieveConnectionStatusResponse;
import org.eclipse.ditto.connectivity.model.signals.events.ConnectionClosed;
import org.eclipse.ditto.connectivity.model.signals.events.ConnectionCreated;
import org.eclipse.ditto.connectivity.model.signals.events.ConnectionDeleted;
import org.eclipse.ditto.connectivity.model.signals.events.ConnectionModified;
import org.eclipse.ditto.connectivity.model.signals.events.ConnectionOpened;
import org.eclipse.ditto.connectivity.model.signals.events.ConnectivityEvent;
import org.eclipse.ditto.connectivity.service.config.ConnectionConfig;
import org.eclipse.ditto.connectivity.service.config.ConnectivityConfig;
import org.eclipse.ditto.connectivity.service.config.MonitoringConfig;
import org.eclipse.ditto.connectivity.service.config.MqttConfig;
import org.eclipse.ditto.connectivity.service.messaging.ClientActorPropsFactory;
import org.eclipse.ditto.connectivity.service.messaging.ClientActorRefs;
import org.eclipse.ditto.connectivity.service.messaging.amqp.AmqpValidator;
import org.eclipse.ditto.connectivity.service.messaging.httppush.HttpPushValidator;
import org.eclipse.ditto.connectivity.service.messaging.kafka.KafkaValidator;
import org.eclipse.ditto.connectivity.service.messaging.monitoring.logs.ConnectionLogger;
import org.eclipse.ditto.connectivity.service.messaging.monitoring.logs.ConnectionLoggerRegistry;
import org.eclipse.ditto.connectivity.service.messaging.monitoring.logs.InfoProviderFactory;
import org.eclipse.ditto.connectivity.service.messaging.monitoring.logs.RetrieveConnectionLogsAggregatorActor;
import org.eclipse.ditto.connectivity.service.messaging.monitoring.metrics.RetrieveConnectionMetricsAggregatorActor;
import org.eclipse.ditto.connectivity.service.messaging.monitoring.metrics.RetrieveConnectionStatusAggregatorActor;
import org.eclipse.ditto.connectivity.service.messaging.mqtt.Mqtt3Validator;
import org.eclipse.ditto.connectivity.service.messaging.mqtt.Mqtt5Validator;
import org.eclipse.ditto.connectivity.service.messaging.persistence.stages.ConnectionAction;
import org.eclipse.ditto.connectivity.service.messaging.persistence.stages.ConnectionState;
import org.eclipse.ditto.connectivity.service.messaging.persistence.stages.StagedCommand;
import org.eclipse.ditto.connectivity.service.messaging.persistence.strategies.commands.ConnectionCreatedStrategies;
import org.eclipse.ditto.connectivity.service.messaging.persistence.strategies.commands.ConnectionDeletedStrategies;
import org.eclipse.ditto.connectivity.service.messaging.persistence.strategies.events.ConnectionEventStrategies;
import org.eclipse.ditto.connectivity.service.messaging.rabbitmq.RabbitMQValidator;
import org.eclipse.ditto.connectivity.service.messaging.validation.CompoundConnectivityCommandInterceptor;
import org.eclipse.ditto.connectivity.service.messaging.validation.ConnectionValidator;
import org.eclipse.ditto.connectivity.service.messaging.validation.DittoConnectivityCommandValidator;
import org.eclipse.ditto.connectivity.service.util.ConnectivityMdcEntryKey;
import org.eclipse.ditto.internal.utils.akka.PingCommand;
import org.eclipse.ditto.internal.utils.akka.logging.CommonMdcEntryKey;
import org.eclipse.ditto.internal.utils.akka.logging.DittoDiagnosticLoggingAdapter;
import org.eclipse.ditto.internal.utils.akka.logging.DittoLoggerFactory;
import org.eclipse.ditto.internal.utils.cluster.DistPubSubAccess;
import org.eclipse.ditto.internal.utils.config.InstanceIdentifierSupplier;
import org.eclipse.ditto.internal.utils.metrics.DittoMetrics;
import org.eclipse.ditto.internal.utils.persistence.mongo.config.ActivityCheckConfig;
import org.eclipse.ditto.internal.utils.persistence.mongo.config.SnapshotConfig;
import org.eclipse.ditto.internal.utils.persistence.mongo.streaming.MongoReadJournal;
import org.eclipse.ditto.internal.utils.persistentactors.AbstractShardedPersistenceActor;
import org.eclipse.ditto.internal.utils.persistentactors.EmptyEvent;
import org.eclipse.ditto.internal.utils.persistentactors.commands.CommandStrategy;
import org.eclipse.ditto.internal.utils.persistentactors.commands.DefaultContext;
import org.eclipse.ditto.internal.utils.persistentactors.events.EventStrategy;
import org.eclipse.ditto.json.JsonValue;
import org.eclipse.ditto.thingsearch.model.signals.commands.subscription.CreateSubscription;
import com.typesafe.config.Config;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.Status;
import akka.actor.SupervisorStrategy;
import akka.actor.Terminated;
import akka.cluster.Cluster;
import akka.cluster.routing.ClusterRouterPool;
import akka.cluster.routing.ClusterRouterPoolSettings;
import akka.japi.pf.ReceiveBuilder;
import akka.pattern.Patterns;
import akka.persistence.RecoveryCompleted;
import akka.routing.Broadcast;
import akka.routing.ConsistentHashingPool;
import akka.routing.ConsistentHashingRouter;
import akka.routing.Pool;
/**
* Handles {@code *Connection} commands and manages the persistence of connection. The actual connection handling to the
* remote server is delegated to a child actor that uses a specific client (AMQP 1.0 or 0.9.1).
*/
public final class ConnectionPersistenceActor
extends AbstractShardedPersistenceActor<ConnectivityCommand<?>, Connection, ConnectionId, ConnectionState,
ConnectivityEvent<?>> {
/**
* Prefix to prepend to the connection ID to construct the persistence ID.
*/
public static final String PERSISTENCE_ID_PREFIX = "connection:";
/**
* The ID of the journal plugin this persistence actor uses.
*/
public static final String JOURNAL_PLUGIN_ID = "akka-contrib-mongodb-persistence-connection-journal";
/**
* The ID of the snapshot plugin this persistence actor uses.
*/
public static final String SNAPSHOT_PLUGIN_ID = "akka-contrib-mongodb-persistence-connection-snapshots";
private static final Duration DEFAULT_RETRIEVE_STATUS_TIMEOUT = Duration.ofMillis(500L);
private static final Duration GRACE_PERIOD_NOT_RETRIEVING_CONNECTION_STATUS_AFTER_RECOVERY = Duration.ofSeconds(10);
private static final Duration SELF_RETRIEVE_CONNECTION_STATUS_TIMEOUT = Duration.ofSeconds(30);
// never retry, just escalate. ConnectionSupervisorActor will handle restarting this actor
private static final SupervisorStrategy ESCALATE_ALWAYS_STRATEGY = OneForOneEscalateStrategy.escalateStrategy();
private final Cluster cluster;
private final ActorRef proxyActor;
private final ClientActorPropsFactory propsFactory;
private final ActorRef pubSubMediator;
private final boolean allClientActorsOnOneNode;
private final ConnectionLoggerRegistry connectionLoggerRegistry;
private final ConnectionLogger connectionLogger;
private final Duration clientActorAskTimeout;
private final Duration checkLoggingActiveInterval;
private final Duration loggingEnabledDuration;
private final ConnectivityConfig connectivityConfig;
private final Config connectivityConfigOverwrites;
private final ClientActorRefs clientActorRefs = ClientActorRefs.empty();
private final ConnectionPriorityProvider connectionPriorityProvider;
private final ConnectivityCommandInterceptor commandValidator;
private int subscriptionCounter = 0;
private Instant connectionClosedAt = Instant.now();
@Nullable private Instant loggingEnabledUntil;
@Nullable private ActorRef clientActorRouter;
@Nullable private ActorRef clientActorRefsAggregationActor;
@Nullable private Integer priority;
@Nullable private Instant recoveredAt;
ConnectionPersistenceActor(final ConnectionId connectionId,
final ActorRef proxyActor,
final ActorRef pubSubMediator,
final ClientActorPropsFactory propsFactory,
@Nullable final ConnectivityCommandInterceptor customCommandValidator,
final ConnectionPriorityProviderFactory connectionPriorityProviderFactory,
final Trilean allClientActorsOnOneNode,
final Config connectivityConfigOverwrites) {
super(connectionId, new ConnectionMongoSnapshotAdapter());
this.cluster = Cluster.get(getContext().getSystem());
this.proxyActor = proxyActor;
this.propsFactory = propsFactory;
this.pubSubMediator = pubSubMediator;
this.connectivityConfigOverwrites = connectivityConfigOverwrites;
connectivityConfig = getConnectivityConfigWithOverwrites(connectivityConfigOverwrites);
this.commandValidator = getCommandValidator(customCommandValidator);
final ConnectionConfig connectionConfig = this.connectivityConfig.getConnectionConfig();
this.allClientActorsOnOneNode = allClientActorsOnOneNode.orElse(connectionConfig.areAllClientActorsOnOneNode());
connectionPriorityProvider = connectionPriorityProviderFactory.newProvider(self(), log);
clientActorAskTimeout = connectionConfig.getClientActorAskTimeout();
final MonitoringConfig monitoringConfig = connectivityConfig.getMonitoringConfig();
connectionLoggerRegistry = ConnectionLoggerRegistry.fromConfig(monitoringConfig.logger());
connectionLogger = connectionLoggerRegistry.forConnection(connectionId);
loggingEnabledDuration = monitoringConfig.logger().logDuration();
checkLoggingActiveInterval = monitoringConfig.logger().loggingActiveCheckInterval();
// Make duration fuzzy to avoid all connections getting updated at once.
final Duration fuzzyPriorityUpdateInterval =
makeFuzzy(connectivityConfig.getConnectionConfig().getPriorityUpdateInterval());
startUpdatePriorityPeriodically(fuzzyPriorityUpdateInterval);
}
private ConnectivityConfig getConnectivityConfigWithOverwrites(final Config connectivityConfigOverwrites) {
final Config defaultConfig = getContext().getSystem().settings().config();
final Config withOverwrites = connectivityConfigOverwrites.withFallback(defaultConfig);
return ConnectivityConfig.of(withOverwrites);
}
/**
* Makes the duration fuzzy. By returning a duration which is something between 5% shorter or 5% longer.
*
* @param duration the duration to make fuzzy.
* @return the fuzzy duration.
*/
private static Duration makeFuzzy(final Duration duration) {
final long millis = duration.toMillis();
final double fuzzyFactor =
new Random().doubles(0.95, 1.05).findAny().orElse(0.0);
final double fuzzedMillis = millis * fuzzyFactor;
return Duration.ofMillis((long) fuzzedMillis);
}
@Override
protected DittoDiagnosticLoggingAdapter createLogger() {
return DittoLoggerFactory.getDiagnosticLoggingAdapter(this)
.withMdcEntry(ConnectivityMdcEntryKey.CONNECTION_ID.toString(), entityId);
}
/**
* Creates Akka configuration object for this actor.
*
* @param connectionId the connection ID.
* @param proxyActor the actor used to send signals into the ditto cluster..
* @param propsFactory factory of props of client actors for various protocols.
* @param commandValidator validator for commands that should throw an exception if a command is invalid.
* @param connectionPriorityProviderFactory Creates a new connection priority provider.
* @param connectivityConfigOverwrites the overwrites for the connectivity config for the given connection.
* @return the Akka configuration Props object.
*/
public static Props props(final ConnectionId connectionId,
final ActorRef proxyActor,
final ActorRef pubSubMediator,
final ClientActorPropsFactory propsFactory,
@Nullable final ConnectivityCommandInterceptor commandValidator,
final ConnectionPriorityProviderFactory connectionPriorityProviderFactory,
final Config connectivityConfigOverwrites
) {
return Props.create(ConnectionPersistenceActor.class, connectionId, proxyActor, pubSubMediator, propsFactory,
commandValidator, connectionPriorityProviderFactory, Trilean.UNKNOWN, connectivityConfigOverwrites);
}
/**
* Compute the length of the subscription ID prefix to identify the client actor owning a search session.
*
* @param clientCount the client count of the connection.
* @return the length of the subscription prefix.
*/
public static int getSubscriptionPrefixLength(final int clientCount) {
return Integer.toHexString(clientCount).length();
}
@Override
public String persistenceId() {
return PERSISTENCE_ID_PREFIX + entityId;
}
@Override
public String journalPluginId() {
return JOURNAL_PLUGIN_ID;
}
@Override
public String snapshotPluginId() {
return SNAPSHOT_PLUGIN_ID;
}
@Override
protected Class<?> getEventClass() {
return ConnectivityEvent.class;
}
@Override
protected CommandStrategy.Context<ConnectionState> getStrategyContext() {
return DefaultContext.getInstance(ConnectionState.of(entityId, connectionLogger, commandValidator), log);
}
@Override
protected ConnectionCreatedStrategies getCreatedStrategy() {
return ConnectionCreatedStrategies.getInstance();
}
@Override
protected ConnectionDeletedStrategies getDeletedStrategy() {
return ConnectionDeletedStrategies.getInstance();
}
@Override
protected EventStrategy<ConnectivityEvent<?>, Connection> getEventStrategy() {
return ConnectionEventStrategies.getInstance();
}
@Override
protected ActivityCheckConfig getActivityCheckConfig() {
return connectivityConfig.getConnectionConfig().getActivityCheckConfig();
}
@Override
protected SnapshotConfig getSnapshotConfig() {
return connectivityConfig.getConnectionConfig().getSnapshotConfig();
}
@Override
protected boolean entityExistsAsDeleted() {
return entity != null &&
entity.getLifecycle().orElse(ConnectionLifecycle.ACTIVE) == ConnectionLifecycle.DELETED;
}
@Override
protected DittoRuntimeExceptionBuilder<?> newNotAccessibleExceptionBuilder() {
return ConnectionNotAccessibleException.newBuilder(entityId);
}
@Override
protected void publishEvent(final ConnectivityEvent<?> event) {
if (event instanceof ConnectionDeleted) {
pubSubMediator.tell(DistPubSubAccess.publish(ConnectionDeleted.TYPE, event), getSelf());
}
// no other events are emitted
}
@Override
protected JsonSchemaVersion getEntitySchemaVersion(final Connection entity) {
return entity.getImplementedSchemaVersion();
}
@Override
protected boolean shouldSendResponse(final DittoHeaders dittoHeaders) {
return dittoHeaders.isResponseRequired();
}
@Override
protected boolean isEntityAlwaysAlive() {
return isDesiredStateOpen();
}
@Override
public void postStop() throws Exception {
log.info("stopped connection <{}>", entityId);
super.postStop();
}
@Override
protected void recoveryCompleted(final RecoveryCompleted event) {
log.info("Connection <{}> was recovered: {}", entityId, entity);
recoveredAt = Instant.now();
if (entity != null && entity.getLifecycle().isEmpty()) {
entity = entity.toBuilder().lifecycle(ConnectionLifecycle.ACTIVE).build();
}
if (isDesiredStateOpen()) {
log.debug("Opening connection <{}> after recovery.", entityId);
restoreOpenConnection();
}
super.recoveryCompleted(event);
}
@Override
protected ConnectivityEvent<?> modifyEventBeforePersist(final ConnectivityEvent<?> event) {
final ConnectivityEvent<?> superEvent = super.modifyEventBeforePersist(event);
final ConnectivityStatus targetConnectionStatus;
if (event instanceof ConnectionCreated connectionCreated) {
targetConnectionStatus = connectionCreated.getConnection().getConnectionStatus();
} else if (event instanceof ConnectionModified connectionModified) {
targetConnectionStatus = connectionModified.getConnection().getConnectionStatus();
} else if (event instanceof ConnectionDeleted) {
targetConnectionStatus = ConnectivityStatus.CLOSED;
} else if (event instanceof ConnectionOpened) {
targetConnectionStatus = ConnectivityStatus.OPEN;
} else if (event instanceof ConnectionClosed) {
targetConnectionStatus = ConnectivityStatus.CLOSED;
} else if (null != entity) {
targetConnectionStatus = entity.getConnectionStatus();
} else {
targetConnectionStatus = ConnectivityStatus.UNKNOWN;
}
final var alwaysAlive = (targetConnectionStatus == ConnectivityStatus.OPEN);
if (alwaysAlive) {
final DittoHeaders headersWithJournalTags = superEvent.getDittoHeaders().toBuilder()
.journalTags(journalTags())
.build();
return superEvent.setDittoHeaders(headersWithJournalTags);
}
return superEvent;
}
private Set<String> journalTags() {
return Set.of(JOURNAL_TAG_ALWAYS_ALIVE,
MongoReadJournal.PRIORITY_TAG_PREFIX + Optional.ofNullable(priority).orElse(0));
}
@Override
protected void processPingCommand(final PingCommand ping) {
super.processPingCommand(ping);
final String journalTag = ping.getPayload()
.filter(JsonValue::isString)
.map(JsonValue::asString)
.orElse(null);
if (journalTag != null && journalTag.isEmpty() && isDesiredStateOpen()) {
// persistence actor was sent a "ping" with empty journal tag:
// build in adding the "always-alive" tag here by persisting an "empty" event which is just tagged to be
// "always alive". Stop persisting the empty event once every open connection has a tagged event, when
// the persistence ping actor will have a non-empty journal tag configured.
final EmptyEvent
emptyEvent = new EmptyEvent(EmptyEvent.EFFECT_ALWAYS_ALIVE, getRevisionNumber() + 1,
DittoHeaders.newBuilder()
.correlationId(ping.getCorrelationId().orElse(null))
.journalTags(journalTags())
.build());
getSelf().tell(new PersistEmptyEvent(emptyEvent), ActorRef.noSender());
}
if (null != recoveredAt && recoveredAt.plus(GRACE_PERIOD_NOT_RETRIEVING_CONNECTION_STATUS_AFTER_RECOVERY)
.isBefore(Instant.now())) {
// only ask for connection status after initial recovery was completed + some grace period
askSelfForRetrieveConnectionStatus(ping.getCorrelationId().orElse(null));
}
}
private void askSelfForRetrieveConnectionStatus(@Nullable final CharSequence correlationId) {
final var retrieveConnectionStatus = RetrieveConnectionStatus.of(entityId,
DittoHeaders.newBuilder().correlationId(correlationId).build());
Patterns.ask(getSelf(), retrieveConnectionStatus, SELF_RETRIEVE_CONNECTION_STATUS_TIMEOUT)
.whenComplete((response, throwable) -> {
if (response instanceof RetrieveConnectionStatusResponse rcsResp) {
final ConnectivityStatus liveStatus = rcsResp.getLiveStatus();
final String connectionType = Optional.ofNullable(entity)
.map(Connection::getConnectionType).map(Object::toString).orElse("?");
DittoMetrics.counter("connection_live_status_reported")
.tag("connectionId", String.valueOf(entityId))
.tag("connectionType", connectionType)
.tag("status", liveStatus.getName())
.increment();
final DittoDiagnosticLoggingAdapter l = log
.withMdcEntries(
ConnectivityMdcEntryKey.CONNECTION_ID, entityId,
ConnectivityMdcEntryKey.CONNECTION_TYPE, connectionType,
CommonMdcEntryKey.DITTO_LOG_TAG,
"connection-live-status-" + liveStatus.getName()
)
.withCorrelationId(rcsResp);
final String template = "Calculated <{}> live ConnectionStatus: <{}>";
if (liveStatus == ConnectivityStatus.FAILED) {
l.error(template, liveStatus, rcsResp);
} else if (liveStatus == ConnectivityStatus.MISCONFIGURED) {
l.info(template, liveStatus, rcsResp);
} else {
l.info(template, liveStatus, rcsResp);
}
} else if (null != throwable) {
log.withCorrelationId(correlationId)
.warning("Received throwable while waiting for RetrieveConnectionStatusResponse: " +
"<{}: {}>", throwable.getClass().getSimpleName(), throwable.getMessage());
} else if (null != response) {
log.withCorrelationId(correlationId)
.warning("Unknown response while waiting for RetrieveConnectionStatusResponse: " +
"<{}: {}>", response.getClass().getSimpleName(), response);
}
});
}
@Override
public void onMutation(final Command<?> command, final ConnectivityEvent<?> event,
final WithDittoHeaders response, final boolean becomeCreated, final boolean becomeDeleted) {
if (command instanceof StagedCommand stagedCommand) {
interpretStagedCommand(stagedCommand.withSenderUnlessDefined(getSender()));
} else {
super.onMutation(command, event, response, becomeCreated, becomeDeleted);
}
}
@Override
protected void checkForActivity(final CheckForActivity trigger) {
if (isDesiredStateOpen()) {
// stay in memory forever if desired state is open. check again later in case connection becomes closed.
scheduleCheckForActivity(getActivityCheckConfig().getInactiveInterval());
} else {
super.checkForActivity(trigger);
}
}
/**
* Carry out the actions in a staged command. Synchronous actions are performed immediately followed by recursion
* onto the next action. Asynchronous action are scheduled with the sending of the next staged command at the end.
* Failures abort all asynchronous actions except OPEN_CONNECTION_IGNORE_ERRORS.
*
* @param command the staged command.
*/
private void interpretStagedCommand(final StagedCommand command) {
if (!command.hasNext()) {
// execution complete
return;
}
switch (command.nextAction()) {
case TEST_CONNECTION:
testConnection(command.next());
break;
case APPLY_EVENT:
command.getEvent()
.ifPresentOrElse(event -> {
entity = getEventStrategy().handle(event, entity, getRevisionNumber());
interpretStagedCommand(command.next());
},
() -> log.error(
"Failed to handle staged command because required event wasn't present: <{}>",
command));
break;
case PERSIST_AND_APPLY_EVENT:
command.getEvent().ifPresentOrElse(
event -> persistAndApplyEvent(event,
(unusedEvent, connection) -> interpretStagedCommand(command.next())),
() -> log.error("Failed to handle staged command because required event wasn't present: <{}>",
command));
break;
case SEND_RESPONSE:
command.getSender().tell(command.getResponse(), getSelf());
interpretStagedCommand(command.next());
break;
case PASSIVATE:
// This actor will stop. Subsequent actions are ignored.
passivate();
break;
case OPEN_CONNECTION:
openConnection(command.next(), false);
break;
case OPEN_CONNECTION_IGNORE_ERRORS:
openConnection(command.next(), true);
break;
case CLOSE_CONNECTION:
closeConnection(command.next());
break;
case STOP_CLIENT_ACTORS:
stopClientActors();
interpretStagedCommand(command.next());
break;
case BECOME_CREATED:
becomeCreatedHandler();
interpretStagedCommand(command.next());
break;
case BECOME_DELETED:
becomeDeletedHandler();
interpretStagedCommand(command.next());
break;
case UPDATE_SUBSCRIPTIONS:
prepareForSignalForwarding(command.next());
break;
case BROADCAST_TO_CLIENT_ACTORS_IF_STARTED:
broadcastToClientActorsIfStarted(command.getCommand(), getSelf());
interpretStagedCommand(command.next());
break;
case RETRIEVE_CONNECTION_LOGS:
retrieveConnectionLogs((RetrieveConnectionLogs) command.getCommand(), command.getSender());
interpretStagedCommand(command.next());
break;
case RETRIEVE_CONNECTION_STATUS:
retrieveConnectionStatus((RetrieveConnectionStatus) command.getCommand(), command.getSender());
interpretStagedCommand(command.next());
break;
case RETRIEVE_CONNECTION_METRICS:
retrieveConnectionMetrics((RetrieveConnectionMetrics) command.getCommand(), command.getSender());
interpretStagedCommand(command.next());
break;
case ENABLE_LOGGING:
loggingEnabled();
interpretStagedCommand(command.next());
break;
case DISABLE_LOGGING:
loggingDisabled();
interpretStagedCommand(command.next());
break;
default:
log.error("Failed to handle staged command: <{}>", command);
}
}
@Override
protected Receive matchAnyAfterInitialization() {
return ReceiveBuilder.create()
.match(CreateSubscription.class, this::startThingSearchSession)
.matchEquals(Control.CHECK_LOGGING_ACTIVE, this::checkLoggingEnabled)
.matchEquals(Control.TRIGGER_UPDATE_PRIORITY, this::triggerUpdatePriority)
.match(UpdatePriority.class, this::updatePriority)
// maintain client actor refs
.match(ClientActorRefs.class, this::syncClientActorRefs)
.match(ActorRef.class, this::addClientActor)
.match(Terminated.class, this::removeClientActor)
.match(AddConnectionLogEntry.class, this::handleAddConnectionLogEntry)
.build()
.orElse(super.matchAnyAfterInitialization());
}
private void handleAddConnectionLogEntry(final AddConnectionLogEntry addConnectionLogEntry) {
final var logEntry = addConnectionLogEntry.getLogEntry();
log.withCorrelationId(logEntry.getCorrelationId()).debug("Handling <{}>.", addConnectionLogEntry);
final var logger = getAppropriateLogger(addConnectionLogEntry.getEntityId(), logEntry);
logger.logEntry(logEntry);
}
private ConnectionLogger getAppropriateLogger(final ConnectionId connectionId, final LogEntry logEntry) {
return connectionLoggerRegistry.getLogger(connectionId,
logEntry.getLogCategory(),
logEntry.getLogType(),
logEntry.getAddress().orElse(null));
}
@Override
protected void becomeDeletedHandler() {
this.cancelPeriodicPriorityUpdate();
super.becomeDeletedHandler();
}
/**
* Route search commands according to subscription ID prefix. This is necessary so that for connections with
* client count > 1, all commands related to 1 search session are routed to the same client actor. This is achieved
* by using a prefix of fixed length of subscription IDs as the hash key of search commands. The length of the
* prefix depends on the client count configured in the connection; it is 1 for connections with client count <= 15.
* <p>
* For the search protocol, all incoming messages are commands (ThingSearchCommand) and all outgoing messages are
* events (SubscriptionEvent).
* <p>
* Message path for incoming search commands:
* <pre>
* ConsumerActor -> MessageMappingProcessorActor -> ConnectionPersistenceActor -> ClientActor -> SubscriptionManager
* </pre>
* Message path for outgoing search events:
* <pre>
* SubscriptionActor -> MessageMappingProcessorActor -> PublisherActor
* </pre>
*
* @param command the command to route.
*/
private void startThingSearchSession(final CreateSubscription command) {
if (clientActorRouter == null) {
logDroppedSignal(command, command.getType(), "Client actor not ready.");
return;
}
if (entity == null) {
logDroppedSignal(command, command.getType(), "No Connection configuration available.");
return;
}
log.debug("Forwarding <{}> to client actors.", command);
// compute the next prefix according to subscriptionCounter and the currently configured client actor count
// ignore any "prefix" field from the command
augmentWithPrefixAndForward(command, entity.getClientCount(), clientActorRouter);
}
private void augmentWithPrefixAndForward(final CreateSubscription createSubscription,
final int clientCount,
final ActorRef clientActorRouter) {
subscriptionCounter = (subscriptionCounter + 1) % Math.max(1, clientCount);
final var prefix = getPrefix(getSubscriptionPrefixLength(clientCount), subscriptionCounter);
final var receiver = clientActorRefs.get(subscriptionCounter);
final var commandWithPrefix = createSubscription.setPrefix(prefix);
if (clientCount == 1) {
clientActorRouter.tell(consistentHashableEnvelope(commandWithPrefix, prefix), ActorRef.noSender());
} else if (receiver.isPresent()) {
receiver.get().tell(commandWithPrefix, ActorRef.noSender());
} else {
logDroppedSignal(createSubscription, createSubscription.getType(), "Client actor not ready.");
}
}
private static String getPrefix(final int prefixLength, final int subscriptionCounter) {
final var prefixPattern = MessageFormat.format("%0{0,number}X", prefixLength);
return String.format(prefixPattern, subscriptionCounter);
}
private void checkLoggingEnabled(final Control message) {
final CheckConnectionLogsActive checkLoggingActive = CheckConnectionLogsActive.of(entityId, Instant.now());
broadcastToClientActorsIfStarted(checkLoggingActive, getSelf());
}
private void triggerUpdatePriority(final Control message) {
if (entity != null) {
final String correlationId = UUID.randomUUID().toString();
connectionPriorityProvider.getPriorityFor(entityId, correlationId)
.whenComplete((desiredPriority, error) -> {
if (error != null) {
log.withCorrelationId(correlationId)
.warning("Got error when trying to get the desired priority for connection <{}>.",
entityId);
} else {
final DittoHeaders headers = DittoHeaders.newBuilder().correlationId(correlationId).build();
self().tell(new UpdatePriority(desiredPriority, headers), ActorRef.noSender());
}
});
}
}
private void updatePriority(final UpdatePriority updatePriority) {
final Integer desiredPriority = updatePriority.getDesiredPriority();
if (!desiredPriority.equals(priority)) {
log.withCorrelationId(updatePriority)
.info("Updating priority of connection <{}> from <{}> to <{}>", entityId, priority,
desiredPriority);
this.priority = desiredPriority;
final DittoHeaders headersWithJournalTags =
updatePriority.getDittoHeaders().toBuilder().journalTags(journalTags()).build();
final EmptyEvent emptyEvent = new EmptyEvent(EmptyEvent.EFFECT_PRIORITY_UPDATE, getRevisionNumber() + 1,
headersWithJournalTags);
getSelf().tell(new PersistEmptyEvent(emptyEvent), ActorRef.noSender());
}
}
private void prepareForSignalForwarding(final StagedCommand command) {
if (isDesiredStateOpen()) {
startEnabledLoggingChecker();
updateLoggingIfEnabled();
}
interpretStagedCommand(command);
}
private void testConnection(final StagedCommand command) {
final ActorRef origin = command.getSender();
final ActorRef self = getSelf();
final DittoHeaders headersWithDryRun = command.getDittoHeaders()
.toBuilder()
.dryRun(true)
.build();
final TestConnection testConnection = (TestConnection) command.getCommand().setDittoHeaders(headersWithDryRun);
if (clientActorRouter != null) {
// client actor is already running, so either another TestConnection command is currently executed or the
// connection has been created in the meantime. In either case reject the new TestConnection command to
// prevent strange behavior.
origin.tell(TestConnectionResponse.alreadyCreated(entityId, command.getDittoHeaders()), self);
} else {
// no need to start more than 1 client for tests
// set connection status to CLOSED so that client actors will not try to connect on startup
setConnectionStatusClosedForTestConnection();
startAndAskClientActors(testConnection, 1)
.thenAccept(response -> self.tell(
command.withResponse(TestConnectionResponse.success(testConnection.getEntityId(),
response.toString(), command.getDittoHeaders())),
ActorRef.noSender()))
.exceptionally(error -> {
self.tell(
command.withResponse(
toDittoRuntimeException(error, entityId, command.getDittoHeaders())),
ActorRef.noSender());
return null;
});
}
}
private void setConnectionStatusClosedForTestConnection() {
if (entity != null) {
entity = entity.toBuilder().connectionStatus(ConnectivityStatus.CLOSED).build();
}
}
private void openConnection(final StagedCommand command, final boolean ignoreErrors) {
final OpenConnection openConnection = OpenConnection.of(entityId, command.getDittoHeaders());
final Consumer<Object> successConsumer = response -> getSelf().tell(command, ActorRef.noSender());
startAndAskClientActors(openConnection, getClientCount())
.thenAccept(successConsumer)
.exceptionally(error -> {
if (ignoreErrors) {
// log the exception and proceed
handleException("open-connection", command.getSender(), error, false);
successConsumer.accept(error);
return null;
} else {
return handleException("open-connection", command.getSender(), error);
}
});
}
private void closeConnection(final StagedCommand command) {
final CloseConnection closeConnection = CloseConnection.of(entityId, command.getDittoHeaders());
broadcastToClientActorsIfStarted(closeConnection)
.thenAccept(response -> getSelf().tell(command, ActorRef.noSender()))
.exceptionally(error -> {
// stop client actors anyway --- the closed status is already persisted.
stopClientActors();
return handleException("disconnect", command.getSender(), error);
});
}
private void logDroppedSignal(final WithDittoHeaders withDittoHeaders, final String type, final String reason) {
log.withCorrelationId(withDittoHeaders).debug("Signal ({}) dropped: {}", type, reason);
}
private void retrieveConnectionLogs(final RetrieveConnectionLogs command, final ActorRef sender) {
this.updateLoggingIfEnabled();
broadcastCommandWithDifferentSender(command,
(existingConnection, timeout) -> RetrieveConnectionLogsAggregatorActor.props(
existingConnection, sender, command.getDittoHeaders(), timeout,
connectivityConfig.getMonitoringConfig().logger().maxLogSizeInBytes()),
() -> respondWithEmptyLogs(command, sender));
}
private boolean isLoggingEnabled() {
return loggingEnabledUntil != null && Instant.now().isBefore(loggingEnabledUntil);
}
private void loggingEnabled() {
// start check logging scheduler
startEnabledLoggingChecker();
loggingEnabledUntil = Instant.now().plus(this.loggingEnabledDuration);
}
private void updateLoggingIfEnabled() {
if (isLoggingEnabled()) {
loggingEnabledUntil = Instant.now().plus(loggingEnabledDuration);
broadcastToClientActorsIfStarted(EnableConnectionLogs.of(entityId, DittoHeaders.empty()),
ActorRef.noSender());
}
}
private void loggingDisabled() {
loggingEnabledUntil = null;
cancelEnabledLoggingChecker();
}
private void cancelEnabledLoggingChecker() {
timers().cancel(Control.CHECK_LOGGING_ACTIVE);
}
private void startEnabledLoggingChecker() {
timers().startTimerWithFixedDelay(Control.CHECK_LOGGING_ACTIVE, Control.CHECK_LOGGING_ACTIVE,
checkLoggingActiveInterval);
}
private void startUpdatePriorityPeriodically(final Duration priorityUpdateInterval) {
log.info("Schedule update of priority periodically in an interval of <{}>", priorityUpdateInterval);
timers().startTimerWithFixedDelay(Control.TRIGGER_UPDATE_PRIORITY, Control.TRIGGER_UPDATE_PRIORITY,
priorityUpdateInterval);
}
private void cancelPeriodicPriorityUpdate() {
timers().cancel(Control.TRIGGER_UPDATE_PRIORITY);
}
private void respondWithEmptyLogs(final WithDittoHeaders command, final ActorRef origin) {
log.debug("ClientActor not started, responding with empty connection logs.");
final RetrieveConnectionLogsResponse logsResponse = RetrieveConnectionLogsResponse.of(
entityId,
Collections.emptyList(),
null,
null,
command.getDittoHeaders()
);
origin.tell(logsResponse, getSelf());
}
private CompletionStage<Object> startAndAskClientActors(final SignalWithEntityId<?> cmd, final int clientCount) {
startClientActorsIfRequired(clientCount, cmd.getDittoHeaders());
final Object msg = consistentHashableEnvelope(cmd, cmd.getEntityId().toString());
return processClientAskResult(Patterns.ask(clientActorRouter, msg, clientActorAskTimeout));
}
private static Object consistentHashableEnvelope(final Object message, final String hashKey) {
return new ConsistentHashingRouter.ConsistentHashableEnvelope(message, hashKey);
}
private void broadcastToClientActorsIfStarted(final Command<?> cmd, final ActorRef sender) {
if (clientActorRouter != null && entity != null) {
clientActorRouter.tell(new Broadcast(cmd), sender);
}
}
/*
* NOT thread-safe.
*/
private CompletionStage<Object> broadcastToClientActorsIfStarted(final Command<?> cmd) {
if (clientActorRouter != null && entity != null) {
// wrap in Broadcast message because these management messages must be delivered to each client actor
final Broadcast broadcast = new Broadcast(cmd);
return processClientAskResult(Patterns.ask(clientActorRouter, broadcast, clientActorAskTimeout));
} else {
return CompletableFuture.completedFuture(null);
}
}
private void broadcastCommandWithDifferentSender(final ConnectivityQueryCommand<?> command,
final BiFunction<Connection, Duration, Props> senderPropsForConnectionWithTimeout,
final Runnable onClientActorNotStarted) {
if (clientActorRouter != null && entity != null) {
// timeout before sending the (partial) response
final Duration timeout = extractTimeoutFromCommand(command.getDittoHeaders());
final ActorRef aggregator =
getContext().actorOf(senderPropsForConnectionWithTimeout.apply(entity, timeout));
// forward command to all client actors with aggregator as sender
clientActorRouter.tell(new Broadcast(command), aggregator);
} else {
onClientActorNotStarted.run();
}
}
private void forwardToClientActors(final Props aggregatorProps, final Command<?> cmd,
final Runnable onClientActorNotStarted) {
if (clientActorRouter != null && entity != null) {
final ActorRef metricsAggregator = getContext().actorOf(aggregatorProps);
// forward command to all client actors with aggregator as sender
clientActorRouter.tell(new Broadcast(cmd), metricsAggregator);
} else {
onClientActorNotStarted.run();
}
}
/*
* Thread-safe because Actor.getSelf() is thread-safe.
*/
private Void handleException(final String action, @Nullable final ActorRef origin, final Throwable exception) {
return handleException(action, origin, exception, true);
}
private Void handleException(final String action,
@Nullable final ActorRef origin,
final Throwable error,
final boolean sendExceptionResponse) {
final DittoRuntimeException dre = toDittoRuntimeException(error, entityId, DittoHeaders.empty());
if (sendExceptionResponse && origin != null) {
origin.tell(dre, getSelf());
}
connectionLogger.failure(InfoProviderFactory.forHeaders(dre.getDittoHeaders()),
"Operation {0} failed due to {1}", action, dre.getMessage());
log.warning("Operation <{}> on connection <{}> failed due to {}: {}.", action, entityId,
dre.getClass().getSimpleName(), dre.getMessage());
return null;
}
private void retrieveConnectionStatus(final RetrieveConnectionStatus command, final ActorRef sender) {
checkNotNull(entity, "Connection");
// timeout before sending the (partial) response
final Duration timeout = extractTimeoutFromCommand(command.getDittoHeaders());
final long availableConnectivityInstances =
StreamSupport.stream(cluster.state().getMembers().spliterator(), false)
.filter(member -> member.getRoles().contains(CLUSTER_ROLE))
.count();
final Props props = RetrieveConnectionStatusAggregatorActor.props(entity, sender,
command.getDittoHeaders(), timeout, availableConnectivityInstances);
forwardToClientActors(props, command, () -> respondWithEmptyStatus(command, sender));
}
private static Duration extractTimeoutFromCommand(final DittoHeaders headers) {
return Duration.ofMillis(
(long) (headers.getTimeout().orElse(DEFAULT_RETRIEVE_STATUS_TIMEOUT).toMillis() * 0.75)
);
}
private void retrieveConnectionMetrics(final RetrieveConnectionMetrics command, final ActorRef sender) {
broadcastCommandWithDifferentSender(command,
(existingConnection, timeout) -> RetrieveConnectionMetricsAggregatorActor.props(
existingConnection, sender, command.getDittoHeaders(), timeout),
() -> respondWithEmptyMetrics(command, sender));
}
private void respondWithEmptyMetrics(final WithDittoHeaders command, final ActorRef origin) {
log.debug("ClientActor not started, responding with empty connection metrics with status closed.");
final ConnectionMetrics metrics =