/
ThingPersistenceActor.java
executable file
·2471 lines (2112 loc) · 107 KB
/
ThingPersistenceActor.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 Bosch Software Innovations GmbH.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/epl-2.0/index.php
*
* Contributors:
* Bosch Software Innovations GmbH - initial contribution
*/
package org.eclipse.ditto.services.things.persistence.actors;
import java.text.MessageFormat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Supplier;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.NotThreadSafe;
import org.eclipse.ditto.json.JsonFieldSelector;
import org.eclipse.ditto.json.JsonObject;
import org.eclipse.ditto.json.JsonPointer;
import org.eclipse.ditto.json.JsonValue;
import org.eclipse.ditto.model.base.auth.AuthorizationContext;
import org.eclipse.ditto.model.base.auth.AuthorizationSubject;
import org.eclipse.ditto.model.base.common.Validator;
import org.eclipse.ditto.model.base.exceptions.DittoRuntimeException;
import org.eclipse.ditto.model.base.headers.DittoHeaders;
import org.eclipse.ditto.model.base.headers.WithDittoHeaders;
import org.eclipse.ditto.model.base.json.FieldType;
import org.eclipse.ditto.model.base.json.JsonSchemaVersion;
import org.eclipse.ditto.model.things.AccessControlList;
import org.eclipse.ditto.model.things.AclEntry;
import org.eclipse.ditto.model.things.AclInvalidException;
import org.eclipse.ditto.model.things.AclNotAllowedException;
import org.eclipse.ditto.model.things.AclValidator;
import org.eclipse.ditto.model.things.Attributes;
import org.eclipse.ditto.model.things.Feature;
import org.eclipse.ditto.model.things.FeatureDefinition;
import org.eclipse.ditto.model.things.FeatureProperties;
import org.eclipse.ditto.model.things.Features;
import org.eclipse.ditto.model.things.PolicyIdMissingException;
import org.eclipse.ditto.model.things.Thing;
import org.eclipse.ditto.model.things.ThingBuilder;
import org.eclipse.ditto.model.things.ThingLifecycle;
import org.eclipse.ditto.model.things.ThingsModelFactory;
import org.eclipse.ditto.services.models.things.ThingsMessagingConstants;
import org.eclipse.ditto.services.models.things.commands.sudo.SudoRetrieveThing;
import org.eclipse.ditto.services.models.things.commands.sudo.SudoRetrieveThingResponse;
import org.eclipse.ditto.services.things.persistence.actors.strategies.AbstractReceiveStrategy;
import org.eclipse.ditto.services.things.persistence.actors.strategies.AbstractThingCommandStrategy;
import org.eclipse.ditto.services.things.persistence.actors.strategies.ModifyAttributesStrategy;
import org.eclipse.ditto.services.things.persistence.actors.strategies.ReceiveStrategy;
import org.eclipse.ditto.services.things.persistence.snapshotting.DittoThingSnapshotter;
import org.eclipse.ditto.services.things.persistence.snapshotting.ThingSnapshotter;
import org.eclipse.ditto.services.things.starter.util.ConfigKeys;
import org.eclipse.ditto.services.utils.akka.LogUtil;
import org.eclipse.ditto.signals.base.WithThingId;
import org.eclipse.ditto.signals.base.WithType;
import org.eclipse.ditto.signals.commands.base.Command;
import org.eclipse.ditto.signals.commands.things.exceptions.AclModificationInvalidException;
import org.eclipse.ditto.signals.commands.things.exceptions.AclNotAccessibleException;
import org.eclipse.ditto.signals.commands.things.exceptions.AttributeNotAccessibleException;
import org.eclipse.ditto.signals.commands.things.exceptions.AttributesNotAccessibleException;
import org.eclipse.ditto.signals.commands.things.exceptions.FeatureDefinitionNotAccessibleException;
import org.eclipse.ditto.signals.commands.things.exceptions.FeatureNotAccessibleException;
import org.eclipse.ditto.signals.commands.things.exceptions.FeaturePropertiesNotAccessibleException;
import org.eclipse.ditto.signals.commands.things.exceptions.FeaturePropertyNotAccessibleException;
import org.eclipse.ditto.signals.commands.things.exceptions.FeaturesNotAccessibleException;
import org.eclipse.ditto.signals.commands.things.exceptions.PolicyIdNotAccessibleException;
import org.eclipse.ditto.signals.commands.things.exceptions.ThingConflictException;
import org.eclipse.ditto.signals.commands.things.exceptions.ThingNotAccessibleException;
import org.eclipse.ditto.signals.commands.things.modify.CreateThing;
import org.eclipse.ditto.signals.commands.things.modify.CreateThingResponse;
import org.eclipse.ditto.signals.commands.things.modify.DeleteAclEntry;
import org.eclipse.ditto.signals.commands.things.modify.DeleteAclEntryResponse;
import org.eclipse.ditto.signals.commands.things.modify.DeleteAttribute;
import org.eclipse.ditto.signals.commands.things.modify.DeleteAttributeResponse;
import org.eclipse.ditto.signals.commands.things.modify.DeleteAttributes;
import org.eclipse.ditto.signals.commands.things.modify.DeleteAttributesResponse;
import org.eclipse.ditto.signals.commands.things.modify.DeleteFeature;
import org.eclipse.ditto.signals.commands.things.modify.DeleteFeatureDefinition;
import org.eclipse.ditto.signals.commands.things.modify.DeleteFeatureDefinitionResponse;
import org.eclipse.ditto.signals.commands.things.modify.DeleteFeatureProperties;
import org.eclipse.ditto.signals.commands.things.modify.DeleteFeaturePropertiesResponse;
import org.eclipse.ditto.signals.commands.things.modify.DeleteFeatureProperty;
import org.eclipse.ditto.signals.commands.things.modify.DeleteFeaturePropertyResponse;
import org.eclipse.ditto.signals.commands.things.modify.DeleteFeatureResponse;
import org.eclipse.ditto.signals.commands.things.modify.DeleteFeatures;
import org.eclipse.ditto.signals.commands.things.modify.DeleteFeaturesResponse;
import org.eclipse.ditto.signals.commands.things.modify.DeleteThing;
import org.eclipse.ditto.signals.commands.things.modify.DeleteThingResponse;
import org.eclipse.ditto.signals.commands.things.modify.ModifyAcl;
import org.eclipse.ditto.signals.commands.things.modify.ModifyAclEntry;
import org.eclipse.ditto.signals.commands.things.modify.ModifyAclEntryResponse;
import org.eclipse.ditto.signals.commands.things.modify.ModifyAclResponse;
import org.eclipse.ditto.signals.commands.things.modify.ModifyAttribute;
import org.eclipse.ditto.signals.commands.things.modify.ModifyAttributeResponse;
import org.eclipse.ditto.signals.commands.things.modify.ModifyAttributes;
import org.eclipse.ditto.signals.commands.things.modify.ModifyFeature;
import org.eclipse.ditto.signals.commands.things.modify.ModifyFeatureDefinition;
import org.eclipse.ditto.signals.commands.things.modify.ModifyFeatureDefinitionResponse;
import org.eclipse.ditto.signals.commands.things.modify.ModifyFeatureProperties;
import org.eclipse.ditto.signals.commands.things.modify.ModifyFeaturePropertiesResponse;
import org.eclipse.ditto.signals.commands.things.modify.ModifyFeatureProperty;
import org.eclipse.ditto.signals.commands.things.modify.ModifyFeaturePropertyResponse;
import org.eclipse.ditto.signals.commands.things.modify.ModifyFeatureResponse;
import org.eclipse.ditto.signals.commands.things.modify.ModifyFeatures;
import org.eclipse.ditto.signals.commands.things.modify.ModifyFeaturesResponse;
import org.eclipse.ditto.signals.commands.things.modify.ModifyPolicyId;
import org.eclipse.ditto.signals.commands.things.modify.ModifyPolicyIdResponse;
import org.eclipse.ditto.signals.commands.things.modify.ModifyThing;
import org.eclipse.ditto.signals.commands.things.modify.ModifyThingResponse;
import org.eclipse.ditto.signals.commands.things.modify.ThingModifyCommandResponse;
import org.eclipse.ditto.signals.commands.things.query.RetrieveAcl;
import org.eclipse.ditto.signals.commands.things.query.RetrieveAclEntry;
import org.eclipse.ditto.signals.commands.things.query.RetrieveAclEntryResponse;
import org.eclipse.ditto.signals.commands.things.query.RetrieveAclResponse;
import org.eclipse.ditto.signals.commands.things.query.RetrieveAttribute;
import org.eclipse.ditto.signals.commands.things.query.RetrieveAttributeResponse;
import org.eclipse.ditto.signals.commands.things.query.RetrieveAttributes;
import org.eclipse.ditto.signals.commands.things.query.RetrieveAttributesResponse;
import org.eclipse.ditto.signals.commands.things.query.RetrieveFeature;
import org.eclipse.ditto.signals.commands.things.query.RetrieveFeatureDefinition;
import org.eclipse.ditto.signals.commands.things.query.RetrieveFeatureDefinitionResponse;
import org.eclipse.ditto.signals.commands.things.query.RetrieveFeatureProperties;
import org.eclipse.ditto.signals.commands.things.query.RetrieveFeaturePropertiesResponse;
import org.eclipse.ditto.signals.commands.things.query.RetrieveFeatureProperty;
import org.eclipse.ditto.signals.commands.things.query.RetrieveFeaturePropertyResponse;
import org.eclipse.ditto.signals.commands.things.query.RetrieveFeatureResponse;
import org.eclipse.ditto.signals.commands.things.query.RetrieveFeatures;
import org.eclipse.ditto.signals.commands.things.query.RetrieveFeaturesResponse;
import org.eclipse.ditto.signals.commands.things.query.RetrievePolicyId;
import org.eclipse.ditto.signals.commands.things.query.RetrievePolicyIdResponse;
import org.eclipse.ditto.signals.commands.things.query.RetrieveThing;
import org.eclipse.ditto.signals.commands.things.query.RetrieveThingResponse;
import org.eclipse.ditto.signals.events.things.AclEntryCreated;
import org.eclipse.ditto.signals.events.things.AclEntryDeleted;
import org.eclipse.ditto.signals.events.things.AclEntryModified;
import org.eclipse.ditto.signals.events.things.AclModified;
import org.eclipse.ditto.signals.events.things.AttributeCreated;
import org.eclipse.ditto.signals.events.things.AttributeDeleted;
import org.eclipse.ditto.signals.events.things.AttributeModified;
import org.eclipse.ditto.signals.events.things.AttributesDeleted;
import org.eclipse.ditto.signals.events.things.FeatureCreated;
import org.eclipse.ditto.signals.events.things.FeatureDefinitionCreated;
import org.eclipse.ditto.signals.events.things.FeatureDefinitionDeleted;
import org.eclipse.ditto.signals.events.things.FeatureDefinitionModified;
import org.eclipse.ditto.signals.events.things.FeatureDeleted;
import org.eclipse.ditto.signals.events.things.FeatureModified;
import org.eclipse.ditto.signals.events.things.FeaturePropertiesCreated;
import org.eclipse.ditto.signals.events.things.FeaturePropertiesDeleted;
import org.eclipse.ditto.signals.events.things.FeaturePropertiesModified;
import org.eclipse.ditto.signals.events.things.FeaturePropertyCreated;
import org.eclipse.ditto.signals.events.things.FeaturePropertyDeleted;
import org.eclipse.ditto.signals.events.things.FeaturePropertyModified;
import org.eclipse.ditto.signals.events.things.FeaturesCreated;
import org.eclipse.ditto.signals.events.things.FeaturesDeleted;
import org.eclipse.ditto.signals.events.things.FeaturesModified;
import org.eclipse.ditto.signals.events.things.PolicyIdCreated;
import org.eclipse.ditto.signals.events.things.PolicyIdModified;
import org.eclipse.ditto.signals.events.things.ThingCreated;
import org.eclipse.ditto.signals.events.things.ThingDeleted;
import org.eclipse.ditto.signals.events.things.ThingEvent;
import org.eclipse.ditto.signals.events.things.ThingModified;
import org.eclipse.ditto.signals.events.things.ThingModifiedEvent;
import com.typesafe.config.Config;
import akka.ConfigurationException;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Cancellable;
import akka.actor.PoisonPill;
import akka.actor.Props;
import akka.cluster.pubsub.DistributedPubSubMediator;
import akka.cluster.sharding.ClusterSharding;
import akka.event.DiagnosticLoggingAdapter;
import akka.japi.Creator;
import akka.japi.pf.FI;
import akka.japi.pf.ReceiveBuilder;
import akka.persistence.AbstractPersistentActor;
import akka.persistence.RecoveryCompleted;
import akka.persistence.SnapshotOffer;
import scala.concurrent.duration.Duration;
/**
* PersistentActor which "knows" the state of a single {@link Thing}.
*/
public final class ThingPersistenceActor extends AbstractPersistentActor implements ThingPersistenceActorInterface {
/**
* The prefix of the persistenceId for Things.
*/
public static final String PERSISTENCE_ID_PREFIX = "thing:";
/**
* The ID of the journal plugin this persistence actor uses.
*/
public static final String JOURNAL_PLUGIN_ID = "akka-contrib-mongodb-persistence-things-journal";
/**
* The ID of the snapshot plugin this persistence actor uses.
*/
public static final String SNAPSHOT_PLUGIN_ID = "akka-contrib-mongodb-persistence-things-snapshots";
private static final String UNHANDLED_MESSAGE_TEMPLATE =
"This Thing Actor did not handle the requested Thing with ID <{0}>!";
private final DiagnosticLoggingAdapter log = LogUtil.obtain(this);
private static final ThingEventHandlers thingEventHandlers = new ThingEventHandlers();
private final String thingId;
private final ActorRef pubSubMediator;
private final java.time.Duration activityCheckInterval;
private final java.time.Duration activityCheckDeletedInterval;
private final Receive handleThingEvents;
private final ThingSnapshotter<?, ?> thingSnapshotter;
private final long snapshotThreshold;
private long accessCounter;
private Cancellable activityChecker;
private final AtomicReference<Thing> thing = new AtomicReference<>();
ThingPersistenceActor(final String thingId,
final ActorRef pubSubMediator,
final ThingSnapshotter.Create thingSnapshotterCreate) {
this.thingId = thingId;
this.pubSubMediator = pubSubMediator;
final Config config = getContext().system().settings().config();
activityCheckInterval = config.getDuration(ConfigKeys.Thing.ACTIVITY_CHECK_INTERVAL);
activityCheckDeletedInterval = config.getDuration(ConfigKeys.Thing.ACTIVITY_CHECK_DELETED_INTERVAL);
// Activity checking
final long configuredSnapshotThreshold = config.getLong(ConfigKeys.Thing.SNAPSHOT_THRESHOLD);
if (configuredSnapshotThreshold < 0) {
throw new ConfigurationException(String.format("Config setting '%s' must be positive, but is: %d.",
ConfigKeys.Thing.SNAPSHOT_THRESHOLD, configuredSnapshotThreshold));
}
snapshotThreshold = configuredSnapshotThreshold;
// Snapshotting
final java.time.Duration snapshotInterval = config.getDuration(ConfigKeys.Thing.SNAPSHOT_INTERVAL);
final boolean snapshotDeleteOld = config.getBoolean(ConfigKeys.Thing.SNAPSHOT_DELETE_OLD);
final boolean eventsDeleteOld = config.getBoolean(ConfigKeys.Thing.EVENTS_DELETE_OLD);
thingSnapshotter =
thingSnapshotterCreate.apply(this, pubSubMediator, snapshotDeleteOld, eventsDeleteOld, log,
snapshotInterval);
handleThingEvents = ReceiveBuilder.create().matchAny(event -> {
final Thing modified = thingEventHandlers.handle(event, thing(), getRevisionNumber());
if (modified != null) {
thing.set(modified);
}
}).build();
}
private Thing thing() {
return thing.get();
}
private void setThing(final Thing thing) {
this.thing.set(thing);
}
/**
* Creates Akka configuration object {@link Props} for this ThingPersistenceActor.
*
* @param thingId the Thing ID this Actor manages.
* @param pubSubMediator the PubSub mediator actor.
* @param thingSnapshotterCreate creator of {@code ThingSnapshotter} objects.
* @return the Akka configuration Props object
*/
public static Props props(final String thingId,
final ActorRef pubSubMediator,
final ThingSnapshotter.Create thingSnapshotterCreate) {
return Props.create(ThingPersistenceActor.class, new Creator<ThingPersistenceActor>() {
private static final long serialVersionUID = 1L;
@Override
public ThingPersistenceActor create() {
return new ThingPersistenceActor(thingId, pubSubMediator, thingSnapshotterCreate);
}
});
}
/**
* Creates a default Akka configuration object {@link Props} for this ThingPersistenceActor using sudo commands
* for external snapshot requests.
*
* @param thingId the Thing ID this Actor manages.
* @param pubSubMediator the PubSub mediator actor.
* @return the Akka configuration Props object
*/
public static Props props(final String thingId, final ActorRef pubSubMediator) {
return Props.create(ThingPersistenceActor.class, new Creator<ThingPersistenceActor>() {
private static final long serialVersionUID = 1L;
@Override
public ThingPersistenceActor create() {
return new ThingPersistenceActor(thingId, pubSubMediator, DittoThingSnapshotter::getInstance);
}
});
}
/**
* Retrieves the ShardRegion of "Things". ThingCommands can be sent to this region which handles dispatching them
* in the cluster (onto the cluster node containing the shard).
*
* @param system the ActorSystem in which to lookup the ShardRegion.
* @return the ActorRef to the ShardRegion.
*/
public static ActorRef getShardRegion(final ActorSystem system) {
return ClusterSharding.get(system).shardRegion(ThingsMessagingConstants.SHARD_REGION);
}
private static Instant eventTimestamp() {
return Instant.now();
}
private static Thing enhanceThingWithLifecycle(final Thing thing) {
final ThingBuilder.FromCopy thingBuilder = ThingsModelFactory.newThingBuilder(thing);
if (!thing.getLifecycle().isPresent()) {
thingBuilder.setLifecycle(ThingLifecycle.ACTIVE);
}
return thingBuilder.build();
}
private long getRevisionNumber() {
return lastSequenceNr();
}
@Nonnull
@Override
public Thing getThing() {
return thing();
}
@Nonnull
@Override
public String getThingId() {
return thingId;
}
private void scheduleCheckForThingActivity(final long intervalInSeconds) {
log.debug("Scheduling for Activity Check in <{}> seconds.", intervalInSeconds);
// if there is a previous activity checker, cancel it
if (activityChecker != null) {
activityChecker.cancel();
}
// send a message to ourselves:
activityChecker = getContext()
.system()
.scheduler()
.scheduleOnce(Duration.apply(intervalInSeconds, TimeUnit.SECONDS), getSelf(),
new CheckForActivity(getRevisionNumber(), accessCounter), getContext().dispatcher(), null);
}
@Override
public String persistenceId() {
return PERSISTENCE_ID_PREFIX + thingId;
}
@Override
public String journalPluginId() {
return JOURNAL_PLUGIN_ID;
}
@Override
public String snapshotPluginId() {
return SNAPSHOT_PLUGIN_ID;
}
@Override
public void postStop() {
super.postStop();
thingSnapshotter.postStop();
if (activityChecker != null) {
activityChecker.cancel();
}
}
@Override
public Receive createReceive() {
/*
* First no Thing for the ID exists at all. Thus the only command this Actor reacts to is CreateThing.
* This behaviour changes as soon as a Thing was created.
*/
return new StrategyAwareReceiveBuilder()
.match(new CreateThingStrategy())
.matchAny(new MatchAnyDuringInitializeStrategy())
.setPeekConsumer(getIncomingMessagesLoggerOrNull())
.build();
}
@Override
public Receive createReceiveRecover() {
// defines how state is updated during recovery
return ReceiveBuilder.create()
// # Snapshot handling
.match(SnapshotOffer.class, ss -> {
log.debug("Got SnapshotOffer: {}", ss);
setThing(thingSnapshotter.recoverThingFromSnapshotOffer(ss));
})
// # Recovery handling
.match(RecoveryCompleted.class, rc -> {
if (thing() != null) {
setThing(enhanceThingWithLifecycle(thing()));
log.debug("Thing <{}> was recovered.", thingId);
if (isThingActive()) {
becomeThingCreatedHandler();
} else {
// expect life cycle to be DELETED. if it's not, then act as if this thing is deleted.
if (!isThingDeleted()) {
// life cycle isn't known, act as
log.error("Unknown lifecycle state <{}> for Thing <{}>.", thing().getLifecycle(),
thingId);
}
becomeThingDeletedHandler();
}
}
})
// // # Handle unknown
// .matchAny(m -> log.warning("Unknown recover message: {}", m))
.build().orElse(handleThingEvents);
}
/*
* Now as the {@code thing} reference is not {@code null} the strategies which act on this reference can
* be activated. In return the strategy for the CreateThing command is not needed anymore.
*/
private void becomeThingCreatedHandler() {
// final Collection<ReceiveStrategy<?>> thingCreatedStrategies = initThingCreatedStrategies();
// final Receive receive = new StrategyAwareReceiveBuilder()
// .matchEach(thingCreatedStrategies)
// .matchAny(new MatchAnyAfterInitializeStrategy())
// .setPeekConsumer(getIncomingMessagesLoggerOrNull())
// .build();
final LazyStrategyLoader lazyStrategyLoader = new LazyStrategyLoader();
final Receive receive = ReceiveBuilder.create().matchAny(lazyStrategyLoader::apply).build();
getContext().become(receive, true);
getContext().getParent().tell(ThingSupervisorActor.ManualReset.INSTANCE, getSelf());
scheduleCheckForThingActivity(activityCheckInterval.getSeconds());
thingSnapshotter.startMaintenanceSnapshots();
}
private void becomeThingDeletedHandler() {
final Collection<ReceiveStrategy<?>> thingDeletedStrategies = initThingDeletedStrategies();
final Receive receive = new StrategyAwareReceiveBuilder()
.matchEach(thingDeletedStrategies)
.matchAny(new ThingNotFoundStrategy())
.setPeekConsumer(getIncomingMessagesLoggerOrNull())
.build();
getContext().become(receive, true);
getContext().getParent().tell(ThingSupervisorActor.ManualReset.INSTANCE, getSelf());
/* check in the next X minutes and therefore
* - stay in-memory for a short amount of minutes after deletion
* - get a Snapshot when removed from memory
*/
scheduleCheckForThingActivity(activityCheckDeletedInterval.getSeconds());
thingSnapshotter.stopMaintenanceSnapshots();
}
private Collection<ReceiveStrategy<?>> initThingDeletedStrategies() {
final Collection<ReceiveStrategy<?>> result = new ArrayList<>();
result.add(new CreateThingStrategy());
// TakeSnapshot
result.addAll(thingSnapshotter.strategies());
// Persistence specific
result.add(new CheckForActivityStrategy());
return result;
}
private <A extends ThingModifiedEvent> void persistAndApplyEvent(final A event, final Consumer<A> handler) {
final A modifiedEvent;
if (thing() != null) {
// set version of event to the version of the thing
final DittoHeaders newHeaders = event.getDittoHeaders().toBuilder()
.schemaVersion(thing().getImplementedSchemaVersion())
.build();
modifiedEvent = (A) event.setDittoHeaders(newHeaders);
} else {
modifiedEvent = event;
}
if (modifiedEvent.getDittoHeaders().isDryRun()) {
handler.accept(modifiedEvent);
} else {
persistEvent(modifiedEvent, persistedEvent -> {
// after the event was persisted, apply the event on the current actor state
applyEvent(persistedEvent);
handler.accept(persistedEvent);
});
}
}
private <A extends ThingModifiedEvent> void persistEvent(final A event, final Consumer<A> handler) {
LogUtil.enhanceLogWithCorrelationId(log, event.getDittoHeaders().getCorrelationId());
log.debug("About to persist Event <{}>", event.getType());
persist(event, persistedEvent -> {
LogUtil.enhanceLogWithCorrelationId(log, event.getDittoHeaders().getCorrelationId());
log.info("Successfully persisted Event <{}>", event.getType());
/* the event has to be applied before creating the snapshot, otherwise a snapshot with new
sequence no (e.g. 2), but old thing revision no (e.g. 1) will be created -> can lead to serious
aftereffects.
*/
handler.accept(persistedEvent);
// save a snapshot if there were too many changes since the last snapshot
if (snapshotThresholdPassed()) {
thingSnapshotter.takeSnapshotInternal();
}
});
}
private boolean snapshotThresholdPassed() {
if (thingSnapshotter.getLatestSnapshotSequenceNr() > 0) {
return (getRevisionNumber() - thingSnapshotter.getLatestSnapshotSequenceNr()) > snapshotThreshold;
} else {
// there is no snapshot; count the sequence numbers from 0.
return (getRevisionNumber() + 1) > snapshotThreshold;
}
}
private <A extends ThingModifiedEvent> void applyEvent(final A event) {
handleThingEvents.onMessage().apply(event);
notifySubscribers(event);
}
private long nextRevision() {
return getRevisionNumber() + 1;
}
/**
* @return Whether the lifecycle of the Thing is active.
*/
public boolean isThingActive() {
return thing().hasLifecycle(ThingLifecycle.ACTIVE);
}
@Override
public boolean isThingDeleted() {
return null == thing() || thing().hasLifecycle(ThingLifecycle.DELETED);
}
private void notifySubscribers(final ThingEvent event) {
// publish the event in the cluster
// publish via cluster pubSub (as we cannot expect that Websocket sessions interested in this event
// are running on the same cluster node):
pubSubMediator.tell(new DistributedPubSubMediator.Publish(ThingEvent.TYPE_PREFIX, event, true), getSelf());
}
private void attributesNotFound(final DittoHeaders dittoHeaders) {
notifySender(AttributesNotAccessibleException.newBuilder(thingId).dittoHeaders(dittoHeaders).build());
}
private void attributeNotFound(final JsonPointer attributeKey, final DittoHeaders dittoHeaders) {
notifySender(AttributeNotAccessibleException.newBuilder(thingId, attributeKey)
.dittoHeaders(dittoHeaders)
.build());
}
private void featureNotFound(final String featureId, final DittoHeaders dittoHeaders) {
final FeatureNotAccessibleException featureNotAccessibleException =
FeatureNotAccessibleException.newBuilder(thingId, featureId).dittoHeaders(dittoHeaders).build();
notifySender(getSender(), featureNotAccessibleException);
}
private void featuresNotFound(final DittoHeaders dittoHeaders) {
notifySender(getSender(), FeaturesNotAccessibleException.newBuilder(thingId)
.dittoHeaders(dittoHeaders)
.build());
}
private void notifySender(final WithDittoHeaders message) {
notifySender(getSender(), message);
}
private void notifySender(final ActorRef sender, final WithDittoHeaders message) {
accessCounter++;
sender.tell(message, getSelf());
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private void aclInvalid(final Optional<String> message, final AuthorizationContext authContext,
final DittoHeaders dittoHeaders) {
log.debug("ACL could not be modified by Authorization Context <{}> due to: {}", authContext,
message.orElse(null));
notifySender(getSender(), AclModificationInvalidException.newBuilder(thingId)
.description(message.orElse(null))
.dittoHeaders(dittoHeaders)
.build());
}
private void aclEntryNotFound(final AuthorizationSubject authorizationSubject, final DittoHeaders dittoHeaders) {
notifySender(getSender(), AclNotAccessibleException.newBuilder(thingId, authorizationSubject)
.dittoHeaders(dittoHeaders)
.build());
}
private void featureDefinitionNotFound(final String featureId, final DittoHeaders dittoHeaders) {
notifySender(getSender(), FeatureDefinitionNotAccessibleException.newBuilder(thingId, featureId)
.dittoHeaders(dittoHeaders)
.build());
}
private void featurePropertiesNotFound(final String featureId, final DittoHeaders dittoHeaders) {
notifySender(getSender(), FeaturePropertiesNotAccessibleException.newBuilder(thingId, featureId)
.dittoHeaders(dittoHeaders)
.build());
}
private void featurePropertyNotFound(final String featureId, final JsonPointer jsonPointer,
final DittoHeaders dittoHeaders) {
notifySender(getSender(), FeaturePropertyNotAccessibleException.newBuilder(thingId, featureId, jsonPointer)
.dittoHeaders(dittoHeaders)
.build());
}
private Consumer<Object> getIncomingMessagesLoggerOrNull() {
if (isLogIncomingMessages()) {
return new LogIncomingMessagesConsumer();
}
return null;
}
/**
* Indicates whether the logging of incoming messages is enabled by config or not.
*
* @return {@code true} if information about incoming messages should be logged, {@code false} else.
*/
private boolean isLogIncomingMessages() {
final ActorSystem actorSystem = getContext().getSystem();
final Config config = actorSystem.settings().config();
return config.hasPath(ConfigKeys.THINGS_LOG_INCOMING_MESSAGES) &&
config.getBoolean(ConfigKeys.THINGS_LOG_INCOMING_MESSAGES);
}
/**
* Message the ThingPersistenceActor can send to itself to check for activity of the Actor and terminate itself
* if there was no activity since the last check.
*/
static final class CheckForActivity {
private final long currentSequenceNr;
private final long currentAccessCounter;
/**
* Constructs a new {@code CheckForActivity} message containing the current "lastSequenceNo" of the
* ThingPersistenceActor.
*
* @param currentSequenceNr the current {@code lastSequenceNr()} of the ThingPersistenceActor.
* @param currentAccessCounter the current {@code accessCounter} of the ThingPersistenceActor.
*/
public CheckForActivity(final long currentSequenceNr, final long currentAccessCounter) {
this.currentSequenceNr = currentSequenceNr;
this.currentAccessCounter = currentAccessCounter;
}
/**
* Returns the current {@code ThingsModelFactory.lastSequenceNr()} of the ThingPersistenceActor.
*
* @return the current {@code ThingsModelFactory.lastSequenceNr()} of the ThingPersistenceActor.
*/
public long getCurrentSequenceNr() {
return currentSequenceNr;
}
/**
* Returns the current {@code accessCounter} of the ThingPersistenceActor.
*
* @return the current {@code accessCounter} of the ThingPersistenceActor.
*/
public long getCurrentAccessCounter() {
return currentAccessCounter;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final CheckForActivity that = (CheckForActivity) o;
return Objects.equals(currentSequenceNr, that.currentSequenceNr) &&
Objects.equals(currentAccessCounter, that.currentAccessCounter);
}
@Override
public int hashCode() {
return Objects.hash(currentSequenceNr, currentAccessCounter);
}
@Override
public String toString() {
return getClass().getSimpleName() + " [" + "currentSequenceNr=" + currentSequenceNr +
", currentAccessCounter=" + currentAccessCounter + "]";
}
}
private final class LazyStrategyLoader {
final Map<Class, Supplier<ReceiveStrategy>> supplier = new HashMap<>();
final Map<Class, ReceiveStrategy> strategies = new HashMap<>();
final ReceiveStrategy unhandledStrategy = new MatchAnyAfterInitializeStrategy();
private LazyStrategyLoader() {
// Thing level
supplier.put(CreateThing.class, () -> new ThingConflictStrategy());
supplier.put(ModifyThing.class, () -> new ModifyThingStrategy());
supplier.put(RetrieveThing.class, () -> new RetrieveThingStrategy());
supplier.put(DeleteThing.class, () -> new DeleteThingStrategy());
// Policy ID
supplier.put(RetrievePolicyId.class, () -> new RetrievePolicyIdStrategy());
supplier.put(ModifyPolicyId.class, () -> new ModifyPolicyIdStrategy());
// ACL
supplier.put(ModifyAcl.class, () -> new ModifyAclStrategy());
supplier.put(RetrieveAcl.class, () -> new RetrieveAclStrategy());
supplier.put(ModifyAclEntry.class, () -> new ModifyAclEntryStrategy());
supplier.put(RetrieveAclEntry.class, () -> new RetrieveAclEntryStrategy());
supplier.put(DeleteAclEntry.class, () -> new DeleteAclEntryStrategy());
// Attributes
supplier.put(ModifyAttributes.class, () -> new ModifyAttributesStrategy());
supplier.put(ModifyAttribute.class, () -> new ModifyAttributeStrategy());
supplier.put(RetrieveAttributes.class, () -> new RetrieveAttributesStrategy());
supplier.put(RetrieveAttribute.class, () -> new RetrieveAttributeStrategy());
supplier.put(DeleteAttributes.class, () -> new DeleteAttributesStrategy());
supplier.put(DeleteAttribute.class, () -> new DeleteAttributeStrategy());
// Features
supplier.put(ModifyFeatures.class, () -> new ModifyFeaturesStrategy());
supplier.put(ModifyFeature.class, () -> new ModifyFeatureStrategy());
supplier.put(RetrieveFeatures.class, () -> new RetrieveFeaturesStrategy());
supplier.put(RetrieveFeature.class, () -> new RetrieveFeatureStrategy());
supplier.put(DeleteFeatures.class, () -> new DeleteFeaturesStrategy());
supplier.put(DeleteFeature.class, () -> new DeleteFeatureStrategy());
// Feature Definition
supplier.put(ModifyFeatureDefinition.class, () -> new ModifyFeatureDefinitionStrategy());
supplier.put(RetrieveFeatureDefinition.class, () -> new RetrieveFeatureDefinitionStrategy());
supplier.put(DeleteFeatureDefinition.class, () -> new DeleteFeatureDefinitionStrategy());
// Feature Properties
supplier.put(ModifyFeatureProperties.class, () -> new ModifyFeaturePropertiesStrategy());
supplier.put(ModifyFeatureProperty.class, () -> new ModifyFeaturePropertyStrategy());
supplier.put(RetrieveFeatureProperties.class, () -> new RetrieveFeaturePropertiesStrategy());
supplier.put(RetrieveFeatureProperty.class, () -> new RetrieveFeaturePropertyStrategy());
supplier.put(DeleteFeatureProperties.class, () -> new DeleteFeaturePropertiesStrategy());
supplier.put(DeleteFeatureProperty.class, () -> new DeleteFeaturePropertyStrategy());
// sudo
supplier.put(SudoRetrieveThing.class, () -> new SudoRetrieveThingStrategy());
// Persistence specific
supplier.put(CheckForActivity.class, () -> new CheckForActivityStrategy());
// TakeSnapshot, pre load
thingSnapshotter.strategies().forEach(s -> strategies.put(s.getMatchingClass(), s));
}
protected void apply(final Object message) throws Exception {
log.info("Loading strategy for class: {}", message.getClass());
final ReceiveStrategy strategy = strategies.computeIfAbsent(message.getClass(), cls -> {
final Supplier<ReceiveStrategy> receiveStrategySupplier = supplier.get(message.getClass());
if (receiveStrategySupplier != null) {
log.info("Strategy for {} does not exists, creating.", cls);
return receiveStrategySupplier.get();
} else {
log.info("Message of type {} cannot be handled.", message.getClass());
return null;
}
});
if (strategy != null) {
if (strategy.getPredicate().defined(message)) {
strategy.getApplyFunction().apply(message);
} else {
strategy.getUnhandledFunction().apply(message);
}
} else {
unhandledStrategy.getApplyFunction().apply(message);
}
}
}
/**
* This strategy handles the {@link CreateThing} command.
*/
@NotThreadSafe
private final class CreateThingStrategy extends AbstractReceiveStrategy<CreateThing> {
/**
* Constructs a new {@code CreateThingStrategy} object.
*/
public CreateThingStrategy() {
super(CreateThing.class, log);
}
@Override
public FI.TypedPredicate<CreateThing> getPredicate() {
return command -> Objects.equals(thingId, command.getId());
}
@Override
protected void doApply(final CreateThing command) {
final DittoHeaders commandHeaders = command.getDittoHeaders();
// Thing not yet created - do so ..
final Thing newThing;
try {
newThing =
handleCommandVersion(command.getImplementedSchemaVersion(), command.getThing(), commandHeaders);
} catch (final DittoRuntimeException e) {
notifySender(e);
return;
}
// before persisting, check if the Thing is valid and reject if not:
if (!isValidThing(command.getImplementedSchemaVersion(), newThing, commandHeaders)) {
return;
}
final ThingCreated thingCreated;
if (JsonSchemaVersion.V_1.equals(command.getImplementedSchemaVersion())) {
thingCreated = ThingCreated.of(newThing, nextRevision(), eventTimestamp(), commandHeaders);
}
// default case handle as v2 and upwards:
else {
thingCreated =
ThingCreated.of(newThing.setPolicyId(newThing.getPolicyId().orElse(thingId)), nextRevision(),
eventTimestamp(), commandHeaders);
}
persistAndApplyEvent(thingCreated, event -> {
notifySender(CreateThingResponse.of(thing(), thingCreated.getDittoHeaders()));
log.debug("Created new Thing with ID <{}>.", thingId);
becomeThingCreatedHandler();
});
}
private Thing handleCommandVersion(final JsonSchemaVersion version, final Thing thing,
final DittoHeaders dittoHeaders) {
if (JsonSchemaVersion.V_1.equals(version)) {
return enhanceNewThingWithFallbackAcl(enhanceThingWithLifecycle(thing),
dittoHeaders.getAuthorizationContext());
}
// default case handle as v2 and upwards:
else {
//acl is not allowed to be set in v2
if (thing.getAccessControlList().isPresent()) {
throw AclNotAllowedException.newBuilder(thingId).dittoHeaders(dittoHeaders).build();
}
// policyId is required for v2
if (!thing.getPolicyId().isPresent()) {
throw PolicyIdMissingException.fromThingIdOnCreate(thingId, dittoHeaders);
}
return enhanceThingWithLifecycle(thing);
}
}
/**
* Retrieves the Thing with first authorization subjects as fallback for the ACL of the Thing if the passed
* {@code newThing} has no ACL set.
*
* @param newThing the new Thing to take as a "base" and to check for presence of ACL inside.
* @param authContext the AuthorizationContext to take the first AuthorizationSubject as fallback from.
* @return the really new Thing with guaranteed ACL.
*/
private Thing enhanceNewThingWithFallbackAcl(final Thing newThing, final AuthorizationContext authContext) {
final ThingBuilder.FromCopy newThingBuilder = ThingsModelFactory.newThingBuilder(newThing);
final Boolean isAclEmpty = newThing.getAccessControlList()
.map(AccessControlList::isEmpty)
.orElse(true);
if (isAclEmpty) {
// do the fallback and use the first authorized subject and give all permissions to it:
final AuthorizationSubject authorizationSubject = authContext.getFirstAuthorizationSubject()
.orElseThrow(() -> new NullPointerException("AuthorizationContext does not contain an " +
"AuthorizationSubject!"));
newThingBuilder.setPermissions(authorizationSubject, Thing.MIN_REQUIRED_PERMISSIONS);
}
return newThingBuilder.build();
}
private boolean isValidThing(final JsonSchemaVersion version, final Thing thing, final DittoHeaders headers) {
final Optional<AccessControlList> accessControlList = thing.getAccessControlList();
if (JsonSchemaVersion.V_1.equals(version)) {
if (accessControlList.isPresent()) {
final Validator aclValidator =
AclValidator.newInstance(accessControlList.get(), Thing.MIN_REQUIRED_PERMISSIONS);
// before persisting, check if the ACL is valid and reject if not:
if (!aclValidator.isValid()) {
notifySender(getSender(), AclInvalidException.newBuilder(thing.getId().orElse(thingId))
.dittoHeaders(headers)
.build());
return false;
}
} else {
return false;
}
}
return true;
}
@Override
public FI.UnitApply<CreateThing> getUnhandledFunction() {
return command -> {
throw new IllegalArgumentException(MessageFormat.format(UNHANDLED_MESSAGE_TEMPLATE, command.getId()));
};
}
}
/**
* This strategy handles the {@link CreateThing} command for an already existing Thing.
*/
@NotThreadSafe
private final class ThingConflictStrategy extends AbstractReceiveStrategy<CreateThing> {
/**
* Constructs a new {@code ThingConflictStrategy} object.
*/
public ThingConflictStrategy() {
super(CreateThing.class, log);
}
@Override
public FI.TypedPredicate<CreateThing> getPredicate() {
return command -> Objects.equals(thingId, command.getId());
}
@Override
protected void doApply(final CreateThing command) {
notifySender(ThingConflictException.newBuilder(command.getId())
.dittoHeaders(command.getDittoHeaders())
.build());
}
@Override
public FI.UnitApply<CreateThing> getUnhandledFunction() {
return command -> {
throw new IllegalArgumentException(MessageFormat.format(UNHANDLED_MESSAGE_TEMPLATE, command.getId()));
};
}
}
/**
* This strategy handles the {@link ModifyThing} command for an already existing Thing.
*/
@NotThreadSafe
private final class ModifyThingStrategy extends AbstractThingCommandStrategy<ModifyThing> {
/**
* Constructs a new {@code ModifyThingStrategy} object.