-
Notifications
You must be signed in to change notification settings - Fork 215
/
EnforcementFlowTest.java
690 lines (592 loc) · 35.2 KB
/
EnforcementFlowTest.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
/*
* Copyright (c) 2021 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.thingsearch.service.persistence.write.streaming;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.eclipse.ditto.base.model.headers.DittoHeaders;
import org.eclipse.ditto.base.model.json.FieldType;
import org.eclipse.ditto.json.JsonObject;
import org.eclipse.ditto.json.JsonPointer;
import org.eclipse.ditto.json.JsonValue;
import org.eclipse.ditto.policies.api.commands.sudo.SudoRetrievePolicy;
import org.eclipse.ditto.policies.api.commands.sudo.SudoRetrievePolicyResponse;
import org.eclipse.ditto.policies.model.Policy;
import org.eclipse.ditto.policies.model.PolicyId;
import org.eclipse.ditto.things.api.commands.sudo.SudoRetrieveThing;
import org.eclipse.ditto.things.api.commands.sudo.SudoRetrieveThingResponse;
import org.eclipse.ditto.things.model.Thing;
import org.eclipse.ditto.things.model.ThingId;
import org.eclipse.ditto.things.model.signals.events.AttributeDeleted;
import org.eclipse.ditto.things.model.signals.events.AttributeModified;
import org.eclipse.ditto.things.model.signals.events.ThingCreated;
import org.eclipse.ditto.things.model.signals.events.ThingDeleted;
import org.eclipse.ditto.things.model.signals.events.ThingEvent;
import org.eclipse.ditto.things.model.signals.events.ThingMerged;
import org.eclipse.ditto.things.model.signals.events.ThingModified;
import org.eclipse.ditto.thingsearch.service.common.config.DefaultStreamConfig;
import org.eclipse.ditto.thingsearch.service.common.config.StreamConfig;
import org.eclipse.ditto.thingsearch.service.persistence.write.model.AbstractWriteModel;
import org.eclipse.ditto.thingsearch.service.persistence.write.model.Metadata;
import org.eclipse.ditto.thingsearch.service.persistence.write.model.ThingDeleteModel;
import org.eclipse.ditto.thingsearch.service.persistence.write.model.ThingWriteModel;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import com.typesafe.config.ConfigFactory;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.stream.KillSwitches;
import akka.stream.UniqueKillSwitch;
import akka.stream.javadsl.Keep;
import akka.stream.testkit.TestPublisher;
import akka.stream.testkit.TestSubscriber;
import akka.stream.testkit.javadsl.TestSink;
import akka.stream.testkit.javadsl.TestSource;
import akka.testkit.TestActor;
import akka.testkit.TestProbe;
import akka.testkit.javadsl.TestKit;
import scala.concurrent.duration.Duration;
import scala.concurrent.duration.FiniteDuration;
/**
* Unit tests for {@link EnforcementFlow}. Contains fix method order to allow for longer setup during first test.
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public final class EnforcementFlowTest {
private ActorSystem system;
private TestPublisher.Probe<Map<ThingId, Metadata>> sourceProbe;
private TestSubscriber.Probe<List<AbstractWriteModel>> sinkProbe;
private UniqueKillSwitch killSwitch;
@Before
public void init() {
system = ActorSystem.create("test", ConfigFactory.load("actors-test.conf"));
}
@After
public void cleanup() {
if (system != null) {
TestKit.shutdownActorSystem(system);
}
}
@Test
public void updateThingAndPolicyRevisions() {
new TestKit(system) {{
// GIVEN: enqueued metadata is out of date
final long thingRev1 = 1L;
final long thingRev2 = 99L;
final long policyRev1 = 2L;
final long policyRev2 = 98L;
final ThingId thingId = ThingId.of("thing:id");
final PolicyId policyId = PolicyId.of("policy:id");
final Metadata metadata = Metadata.of(thingId, thingRev1, policyId, policyRev1, null);
final Map<ThingId, Metadata> inputMap = Map.of(thingId, metadata);
final TestProbe thingsProbe = TestProbe.apply(system);
final TestProbe policiesProbe = TestProbe.apply(system);
final StreamConfig streamConfig = DefaultStreamConfig.of(ConfigFactory.empty());
final EnforcementFlow underTest =
EnforcementFlow.of(system, streamConfig, thingsProbe.ref(), policiesProbe.ref(),
system.getScheduler());
materializeTestProbes(underTest);
sinkProbe.ensureSubscription();
sourceProbe.ensureSubscription();
sinkProbe.request(1);
assertThat(sourceProbe.expectRequest()).isEqualTo(16);
sourceProbe.sendNext(inputMap);
sourceProbe.sendComplete();
// WHEN: thing and policy are retrieved with up-to-date revisions
thingsProbe.expectMsgClass(FiniteDuration.apply(10, TimeUnit.SECONDS), SudoRetrieveThing.class);
final var thing = Thing.newBuilder().setId(thingId).setPolicyId(policyId).setRevision(thingRev2).build();
final var thingJson = thing.toJson(FieldType.regularOrSpecial());
assertThat(thingJson.getValue(Thing.JsonFields.REVISION)).contains(thingRev2);
thingsProbe.reply(SudoRetrieveThingResponse.of(thingJson, DittoHeaders.empty()));
policiesProbe.expectMsgClass(SudoRetrievePolicy.class);
final var policy = Policy.newBuilder(policyId).setRevision(policyRev2).build();
policiesProbe.reply(SudoRetrievePolicyResponse.of(policyId, policy, DittoHeaders.empty()));
// THEN: the write model contains up-to-date revisions
final AbstractWriteModel writeModel = sinkProbe.expectNext().get(0);
sinkProbe.expectComplete();
assertThat(writeModel).isInstanceOf(ThingWriteModel.class);
final var document = JsonObject.of(((ThingWriteModel) writeModel).getThingDocument().toJson());
assertThat(document.getValue("_id")).contains(JsonValue.of(thingId));
assertThat(document.getValue("policyId")).contains(JsonValue.of(policyId));
assertThat(document.getValue("_revision")).contains(JsonValue.of(thingRev2));
assertThat(document.getValue("__policyRev")).contains(JsonValue.of(policyRev2));
}};
}
@Test
public void ignoreCacheWhenRequestedToUpdate() {
// GIVEN: the enqueued metadata is out-of-date
final long thingRev1 = 1L;
final long thingRev2 = 99L;
final long policyRev1 = 2L;
final long policyRev2 = 98L;
final ThingId thingId = ThingId.of("thing:id");
final PolicyId policyId = PolicyId.of("policy:id");
final Metadata metadata1 = Metadata.of(thingId, thingRev1, policyId, policyRev1, null);
final TestProbe thingsProbe = TestProbe.apply(system);
final TestProbe policiesProbe = TestProbe.apply(system);
final StreamConfig streamConfig = DefaultStreamConfig.of(ConfigFactory.empty());
final EnforcementFlow underTest =
EnforcementFlow.of(system, streamConfig, thingsProbe.ref(), policiesProbe.ref(),
system.getScheduler());
materializeTestProbes(underTest);
sinkProbe.ensureSubscription();
sourceProbe.ensureSubscription();
sinkProbe.request(2);
sourceProbe.sendNext(Map.of(thingId, metadata1));
thingsProbe.expectMsgClass(SudoRetrieveThing.class);
final var thing = Thing.newBuilder().setId(thingId).setPolicyId(policyId).setRevision(thingRev2).build();
final var thingJson = thing.toJson(FieldType.regularOrSpecial());
thingsProbe.reply(SudoRetrieveThingResponse.of(thingJson, DittoHeaders.empty()));
// GIVEN: enforcer cache is loaded with out-of-date policy
policiesProbe.expectMsgClass(SudoRetrievePolicy.class);
final var policy1 = Policy.newBuilder(policyId).setRevision(policyRev1).build();
policiesProbe.reply(SudoRetrievePolicyResponse.of(policyId, policy1, DittoHeaders.empty()));
final AbstractWriteModel writeModel1 = sinkProbe.expectNext().get(0);
assertThat(writeModel1).isInstanceOf(ThingWriteModel.class);
final var document1 = JsonObject.of(((ThingWriteModel) writeModel1).getThingDocument().toJson());
assertThat(document1.getValue("_revision")).contains(JsonValue.of(thingRev2));
assertThat(document1.getValue("__policyRev")).contains(JsonValue.of(policyRev1));
// WHEN: a metadata with 'invalidateCache' flag is enqueued
final Metadata metadata2 = metadata1.invalidateCaches(true, true);
sourceProbe.sendNext(Map.of(thingId, metadata2));
sourceProbe.sendComplete();
thingsProbe.expectMsgClass(SudoRetrieveThing.class);
thingsProbe.reply(SudoRetrieveThingResponse.of(thingJson, DittoHeaders.empty()));
// THEN: policy cache is reloaded
policiesProbe.expectMsgClass(SudoRetrievePolicy.class);
final var policy2 = Policy.newBuilder(policyId).setRevision(policyRev2).build();
policiesProbe.reply(SudoRetrievePolicyResponse.of(policyId, policy2, DittoHeaders.empty()));
// THEN: write model contains up-to-date policy revisions.
final AbstractWriteModel writeModel2 = sinkProbe.expectNext().get(0);
sinkProbe.expectComplete();
assertThat(writeModel2).isInstanceOf(ThingWriteModel.class);
final var document2 = JsonObject.of(((ThingWriteModel) writeModel2).getThingDocument().toJson());
assertThat(document2.getValue("_revision")).contains(JsonValue.of(thingRev2));
assertThat(document2.getValue("__policyRev")).contains(JsonValue.of(policyRev2));
}
@Test
public void computeThingCacheValueFromThingEvents() {
new TestKit(system) {{
// GIVEN: enqueued metadata contains events sufficient to determine the thing state
final DittoHeaders headers = DittoHeaders.empty();
final ThingId thingId = ThingId.of("thing:id");
final PolicyId policyId = PolicyId.of("policy:id");
final Thing thing = Thing.newBuilder().setId(thingId).setPolicyId(policyId).build();
final List<ThingEvent<?>> events = List.of(
ThingModified.of(thing, 1, null, headers, null),
ThingDeleted.of(thingId, 2, null, headers, null),
ThingCreated.of(thing.toBuilder()
.setAttribute(JsonPointer.of("w"), JsonValue.of(4))
.setAttribute(JsonPointer.of("x"), JsonValue.of(5))
.build(), 3,
null, headers, null),
ThingMerged.of(thingId, JsonPointer.of("attributes/y"), JsonValue.of(6), 4, null, headers, null),
AttributeModified.of(thingId, JsonPointer.of("z"), JsonValue.of(7), 5, null, headers, null),
AttributeDeleted.of(thingId, JsonPointer.of("w"), 6, null, headers, null)
);
final Metadata metadata = Metadata.of(thingId, 5L, policyId, 1L, events, null, null);
final Map<ThingId, Metadata> inputMap = Map.of(thingId, metadata);
final TestProbe thingsProbe = TestProbe.apply(system);
final TestProbe policiesProbe = TestProbe.apply(system);
final StreamConfig streamConfig = DefaultStreamConfig.of(ConfigFactory.empty());
final EnforcementFlow underTest =
EnforcementFlow.of(system, streamConfig, thingsProbe.ref(), policiesProbe.ref(),
system.getScheduler());
materializeTestProbes(underTest);
sinkProbe.ensureSubscription();
sourceProbe.ensureSubscription();
sinkProbe.request(1);
assertThat(sourceProbe.expectRequest()).isEqualTo(16);
sourceProbe.sendNext(inputMap);
sourceProbe.sendComplete();
// WHEN: policy is retrieved with up-to-date revisions
policiesProbe.expectMsgClass(Duration.apply(30, TimeUnit.SECONDS), SudoRetrievePolicy.class);
final var policy = Policy.newBuilder(policyId).setRevision(1).build();
policiesProbe.reply(SudoRetrievePolicyResponse.of(policyId, policy, DittoHeaders.empty()));
// THEN: the write model contains up-to-date revisions
final AbstractWriteModel writeModel = sinkProbe.expectNext().get(0);
sinkProbe.expectComplete();
assertThat(writeModel).isInstanceOf(ThingWriteModel.class);
final var document = JsonObject.of(((ThingWriteModel) writeModel).getThingDocument().toJson());
assertThat(document.getValue("_id")).contains(JsonValue.of(thingId));
assertThat(document.getValue("policyId")).contains(JsonValue.of(policyId));
assertThat(document.getValue("_revision")).contains(JsonValue.of(6));
assertThat(document.getValue("__policyRev")).contains(JsonValue.of(1));
assertThat(document.getValue("s/attributes")).contains(JsonObject.of("{\"x\":5,\"y\":6,\"z\":7}"));
// THEN: thing is computed in the cache
thingsProbe.expectNoMessage(FiniteDuration.Zero());
}};
}
@Test
public void computeThingCacheValueFromThingEventsWhenLastEventWasDeleted() {
new TestKit(system) {{
// GIVEN: enqueued metadata contains events sufficient to determine the thing state
final DittoHeaders headers = DittoHeaders.empty();
final ThingId thingId = ThingId.of("thing:id");
final PolicyId policyId = PolicyId.of("policy:id");
final Thing thing = Thing.newBuilder().setId(thingId).setPolicyId(policyId).build();
final Instant deletedTime = Instant.now();
final List<ThingEvent<?>> events = List.of(
ThingModified.of(thing, 1, deletedTime.minusSeconds(1), headers, null),
ThingDeleted.of(thingId, 2, deletedTime, headers, null),
ThingCreated.of(thing.toBuilder()
.setAttribute(JsonPointer.of("w"), JsonValue.of(4))
.setAttribute(JsonPointer.of("x"), JsonValue.of(5))
.build(), 3,
deletedTime.minusSeconds(5), headers, null),
ThingMerged.of(thingId, JsonPointer.of("attributes/y"), JsonValue.of(6), 4,
deletedTime.minusSeconds(4), headers, null),
AttributeModified.of(thingId, JsonPointer.of("z"), JsonValue.of(7), 5, deletedTime.minusSeconds(3),
headers, null),
AttributeDeleted.of(thingId, JsonPointer.of("w"), 6, deletedTime.minusSeconds(2), headers, null)
);
final Metadata metadata = Metadata.of(thingId, 5L, policyId, 1L, events, null, null);
final Map<ThingId, Metadata> inputMap = Map.of(thingId, metadata);
final TestProbe thingsProbe = TestProbe.apply(system);
final TestProbe policiesProbe = TestProbe.apply(system);
final StreamConfig streamConfig = DefaultStreamConfig.of(ConfigFactory.empty());
final EnforcementFlow underTest =
EnforcementFlow.of(system, streamConfig, thingsProbe.ref(), policiesProbe.ref(),
system.getScheduler());
materializeTestProbes(underTest);
sinkProbe.ensureSubscription();
sourceProbe.ensureSubscription();
sinkProbe.request(1);
assertThat(sourceProbe.expectRequest()).isEqualTo(16);
sourceProbe.sendNext(inputMap);
sourceProbe.sendComplete();
// THEN: the write model contains up-to-date revisions
final AbstractWriteModel deleteModel = sinkProbe.expectNext().get(0);
sinkProbe.expectComplete();
assertThat(deleteModel).isInstanceOf(ThingDeleteModel.class);
final var modelMetadata = deleteModel.getMetadata();
assertThat(modelMetadata.getThingId().toString()).isEqualTo(thingId.toString());
// THEN: thing is computed in the cache
thingsProbe.expectNoMessage(FiniteDuration.Zero());
}};
}
@Test
public void forceRetrieveThing() {
new TestKit(system) {{
final DittoHeaders headers = DittoHeaders.empty();
final ThingId thingId = ThingId.of("thing:id");
final PolicyId policyId = PolicyId.of("policy:id");
final Thing thing = Thing.newBuilder().setId(thingId).setPolicyId(policyId).build();
final List<ThingEvent<?>> events = List.of(
ThingModified.of(thing, 1, null, headers, null),
ThingDeleted.of(thingId, 2, null, headers, null),
ThingCreated.of(thing.toBuilder()
.setAttribute(JsonPointer.of("w"), JsonValue.of(4))
.setAttribute(JsonPointer.of("x"), JsonValue.of(5))
.build(), 3,
null, headers, null),
ThingMerged.of(thingId, JsonPointer.of("attributes/y"), JsonValue.of(6), 4, null, headers, null),
AttributeModified.of(thingId, JsonPointer.of("z"), JsonValue.of(7), 5, null, headers, null),
AttributeDeleted.of(thingId, JsonPointer.of("w"), 6, null, headers, null)
);
final Metadata metadata = Metadata.of(thingId, 6L, policyId, 1L, events, null, null)
.invalidateCaches(true, true);
final Map<ThingId, Metadata> inputMap = Map.of(thingId, metadata);
final TestProbe thingsProbe = TestProbe.apply(system);
final TestProbe policiesProbe = TestProbe.apply(system);
final StreamConfig streamConfig = DefaultStreamConfig.of(ConfigFactory.empty());
final EnforcementFlow underTest =
EnforcementFlow.of(system, streamConfig, thingsProbe.ref(), policiesProbe.ref(),
system.getScheduler());
materializeTestProbes(underTest);
sinkProbe.ensureSubscription();
sourceProbe.ensureSubscription();
sinkProbe.request(1);
assertThat(sourceProbe.expectRequest()).isEqualTo(16);
sourceProbe.sendNext(inputMap);
sourceProbe.sendComplete();
assertThat((CharSequence) thingsProbe.expectMsgClass(SudoRetrieveThing.class).getEntityId())
.isEqualTo(thingId);
}};
}
@Test
public void eventSequenceNumberTooLow() {
new TestKit(system) {{
final DittoHeaders headers = DittoHeaders.empty();
final ThingId thingId = ThingId.of("thing:id");
final PolicyId policyId = PolicyId.of("policy:id");
final Thing thing = Thing.newBuilder().setId(thingId).setPolicyId(policyId).build();
final List<ThingEvent<?>> events = List.of(
ThingModified.of(thing, 1, null, headers, null),
ThingDeleted.of(thingId, 2, null, headers, null),
ThingCreated.of(thing.toBuilder()
.setAttribute(JsonPointer.of("w"), JsonValue.of(4))
.setAttribute(JsonPointer.of("x"), JsonValue.of(5))
.build(), 3,
null, headers, null),
ThingMerged.of(thingId, JsonPointer.of("attributes/y"), JsonValue.of(6), 4, null, headers, null),
AttributeModified.of(thingId, JsonPointer.of("z"), JsonValue.of(7), 5, null, headers, null),
AttributeDeleted.of(thingId, JsonPointer.of("w"), 6, null, headers, null)
);
final Metadata metadata = Metadata.of(thingId, 7L, policyId, 1L, events, null, null);
final Map<ThingId, Metadata> inputMap = Map.of(thingId, metadata);
final TestProbe thingsProbe = TestProbe.apply(system);
final TestProbe policiesProbe = TestProbe.apply(system);
final StreamConfig streamConfig = DefaultStreamConfig.of(ConfigFactory.empty());
final EnforcementFlow underTest =
EnforcementFlow.of(system, streamConfig, thingsProbe.ref(), policiesProbe.ref(),
system.getScheduler());
materializeTestProbes(underTest);
sinkProbe.ensureSubscription();
sourceProbe.ensureSubscription();
sinkProbe.request(1);
assertThat(sourceProbe.expectRequest()).isEqualTo(16);
sourceProbe.sendNext(inputMap);
sourceProbe.sendComplete();
assertThat((CharSequence) thingsProbe.expectMsgClass(SudoRetrieveThing.class).getEntityId())
.isEqualTo(thingId);
}};
}
@Test
public void eventMissed() {
new TestKit(system) {{
final DittoHeaders headers = DittoHeaders.empty();
final ThingId thingId = ThingId.of("thing:id");
final PolicyId policyId = PolicyId.of("policy:id");
final Thing thing = Thing.newBuilder().setId(thingId).setPolicyId(policyId).build();
final List<ThingEvent<?>> events = List.of(
ThingModified.of(thing, 1, null, headers, null),
ThingDeleted.of(thingId, 2, null, headers, null),
ThingCreated.of(thing.toBuilder()
.setAttribute(JsonPointer.of("w"), JsonValue.of(4))
.setAttribute(JsonPointer.of("x"), JsonValue.of(5))
.build(), 3,
null, headers, null),
AttributeModified.of(thingId, JsonPointer.of("z"), JsonValue.of(7), 5, null, headers, null),
AttributeDeleted.of(thingId, JsonPointer.of("w"), 6, null, headers, null)
);
final Metadata metadata = Metadata.of(thingId, 6L, policyId, 1L, events, null, null);
final Map<ThingId, Metadata> inputMap = Map.of(thingId, metadata);
final TestProbe thingsProbe = TestProbe.apply(system);
final TestProbe policiesProbe = TestProbe.apply(system);
final StreamConfig streamConfig = DefaultStreamConfig.of(ConfigFactory.empty());
final EnforcementFlow underTest =
EnforcementFlow.of(system, streamConfig, thingsProbe.ref(), policiesProbe.ref(),
system.getScheduler());
materializeTestProbes(underTest);
sinkProbe.ensureSubscription();
sourceProbe.ensureSubscription();
sinkProbe.request(1);
assertThat(sourceProbe.expectRequest()).isEqualTo(16);
sourceProbe.sendNext(inputMap);
sourceProbe.sendComplete();
assertThat((CharSequence) thingsProbe.expectMsgClass(SudoRetrieveThing.class).getEntityId())
.isEqualTo(thingId);
}};
}
@Test
public void noInitialCreatedOrDeletedEvent() {
new TestKit(system) {{
final DittoHeaders headers = DittoHeaders.empty();
final ThingId thingId = ThingId.of("thing:id");
final PolicyId policyId = PolicyId.of("policy:id");
final Thing thing = Thing.newBuilder().setId(thingId).setPolicyId(policyId).build();
final List<ThingEvent<?>> events = List.of(
ThingModified.of(thing.toBuilder()
.setAttribute(JsonPointer.of("w"), JsonValue.of(4))
.setAttribute(JsonPointer.of("x"), JsonValue.of(5))
.build(), 3,
null, headers, null),
ThingMerged.of(thingId, JsonPointer.of("attributes/y"), JsonValue.of(6), 4, null, headers, null),
AttributeModified.of(thingId, JsonPointer.of("z"), JsonValue.of(7), 5, null, headers, null),
AttributeDeleted.of(thingId, JsonPointer.of("w"), 6, null, headers, null)
);
final Metadata metadata = Metadata.of(thingId, 6L, policyId, 1L, events, null, null);
final Map<ThingId, Metadata> inputMap = Map.of(thingId, metadata);
final TestProbe thingsProbe = TestProbe.apply(system);
final TestProbe policiesProbe = TestProbe.apply(system);
final StreamConfig streamConfig = DefaultStreamConfig.of(ConfigFactory.empty());
final EnforcementFlow underTest =
EnforcementFlow.of(system, streamConfig, thingsProbe.ref(), policiesProbe.ref(),
system.getScheduler());
materializeTestProbes(underTest);
sinkProbe.ensureSubscription();
sourceProbe.ensureSubscription();
sinkProbe.request(1);
assertThat(sourceProbe.expectRequest()).isEqualTo(16);
sourceProbe.sendNext(inputMap);
sourceProbe.sendComplete();
// WHEN: thing and policy caches are loaded
final var sudoRetrieveThing = thingsProbe.expectMsgClass(SudoRetrieveThing.class);
thingsProbe.reply(SudoRetrieveThingResponse.of(
thing.toBuilder().setRevision(2).build().toJson(FieldType.all()),
sudoRetrieveThing.getDittoHeaders()));
policiesProbe.expectMsgClass(SudoRetrievePolicy.class);
final var policy = Policy.newBuilder(policyId).setRevision(1).build();
policiesProbe.reply(SudoRetrievePolicyResponse.of(policyId, policy, DittoHeaders.empty()));
// THEN: the write model contains up-to-date revisions
final AbstractWriteModel writeModel = sinkProbe.expectNext().get(0);
sinkProbe.expectComplete();
assertThat(writeModel).isInstanceOf(ThingWriteModel.class);
final var document = JsonObject.of(((ThingWriteModel) writeModel).getThingDocument().toJson());
assertThat(document.getValue("_id")).contains(JsonValue.of(thingId));
assertThat(document.getValue("policyId")).contains(JsonValue.of(policyId));
assertThat(document.getValue("_revision")).contains(JsonValue.of(6));
assertThat(document.getValue("__policyRev")).contains(JsonValue.of(1));
assertThat(document.getValue("s/attributes")).contains(JsonObject.of("{\"x\":5,\"y\":6,\"z\":7}"));
// THEN: thing is computed in the cache
thingsProbe.expectNoMessage(FiniteDuration.Zero());
}};
}
@Test
public void onlyApplyRelevantEvents() {
new TestKit(system) {{
final DittoHeaders headers = DittoHeaders.empty();
final ThingId thingId = ThingId.of("thing:id");
final PolicyId policyId = PolicyId.of("policy:id");
final Thing thing = Thing.newBuilder().setId(thingId).setPolicyId(policyId).build();
final List<ThingEvent<?>> events = List.of(
// this event should be skipped because cache loader returns revision 2
ThingMerged.of(thingId, JsonPointer.of("attributes/v"), JsonValue.of(3), 2, null, headers, null),
// these events should be applied
ThingModified.of(thing.toBuilder()
.setAttribute(JsonPointer.of("w"), JsonValue.of(4))
.setAttribute(JsonPointer.of("x"), JsonValue.of(5))
.build(), 3,
null, headers, null),
ThingMerged.of(thingId, JsonPointer.of("attributes/y"), JsonValue.of(6), 4, null, headers, null),
AttributeModified.of(thingId, JsonPointer.of("z"), JsonValue.of(7), 5, null, headers, null),
AttributeDeleted.of(thingId, JsonPointer.of("w"), 6, null, headers, null)
);
final Metadata metadata = Metadata.of(thingId, 6L, policyId, 1L, events, null, null);
final Map<ThingId, Metadata> inputMap = Map.of(thingId, metadata);
final TestProbe thingsProbe = TestProbe.apply(system);
final TestProbe policiesProbe = TestProbe.apply(system);
final StreamConfig streamConfig = DefaultStreamConfig.of(ConfigFactory.empty());
final EnforcementFlow underTest =
EnforcementFlow.of(system, streamConfig, thingsProbe.ref(), policiesProbe.ref(),
system.getScheduler());
materializeTestProbes(underTest);
sinkProbe.ensureSubscription();
sourceProbe.ensureSubscription();
sinkProbe.request(1);
assertThat(sourceProbe.expectRequest()).isEqualTo(16);
sourceProbe.sendNext(inputMap);
sourceProbe.sendComplete();
// WHEN: thing and policy caches are loaded
final var sudoRetrieveThing = thingsProbe.expectMsgClass(SudoRetrieveThing.class);
thingsProbe.reply(SudoRetrieveThingResponse.of(
thing.toBuilder().setRevision(2).build().toJson(FieldType.all()),
sudoRetrieveThing.getDittoHeaders()));
policiesProbe.expectMsgClass(SudoRetrievePolicy.class);
final var policy = Policy.newBuilder(policyId).setRevision(1).build();
policiesProbe.reply(SudoRetrievePolicyResponse.of(policyId, policy, DittoHeaders.empty()));
// THEN: the write model contains up-to-date revisions
final AbstractWriteModel writeModel = sinkProbe.expectNext().get(0);
sinkProbe.expectComplete();
assertThat(writeModel).isInstanceOf(ThingWriteModel.class);
final var document = JsonObject.of(((ThingWriteModel) writeModel).getThingDocument().toJson());
assertThat(document.getValue("_id")).contains(JsonValue.of(thingId));
assertThat(document.getValue("policyId")).contains(JsonValue.of(policyId));
assertThat(document.getValue("_revision")).contains(JsonValue.of(6));
assertThat(document.getValue("__policyRev")).contains(JsonValue.of(1));
assertThat(document.getValue("s/attributes")).contains(JsonObject.of("{\"x\":5,\"y\":6,\"z\":7}"));
// THEN: thing is computed in the cache
thingsProbe.expectNoMessage(FiniteDuration.Zero());
}};
}
@Test
public void updatesDoNotGetReordered() {
Assume.assumeThat(System.getProperty("build.environment"), Matchers.not(Matchers.equalTo("Github")));
new TestKit(system) {{
final DittoHeaders headers = DittoHeaders.empty();
final PolicyId policyId = PolicyId.of("policy:id");
final Thing thing = Thing.newBuilder().setPolicyId(policyId).build();
final var policy = Policy.newBuilder(policyId).setRevision(1).build();
final List<Map<ThingId, Metadata>> changeMaps = IntStream.range(1, 5).mapToObj(i -> {
final ThingId thingId = ThingId.of("thing:" + i);
final Thing ithThing = thing.toBuilder().setId(thingId).setRevision(i).build();
final List<ThingEvent<?>> events = List.of(ThingModified.of(ithThing, i, null, headers, null));
final Metadata metadata = Metadata.of(thingId, i, policyId, 1L, events, null, null);
return Map.of(thingId, metadata);
}).toList();
final TestProbe thingsProbe = TestProbe.apply(system);
final TestProbe policiesProbe = TestProbe.apply(system);
final StreamConfig streamConfig = DefaultStreamConfig.of(ConfigFactory.parseString(
"stream.ask-with-retry.ask-timeout=30s"));
final EnforcementFlow underTest = EnforcementFlow.of(system, streamConfig, thingsProbe.ref(),
policiesProbe.ref(), system.getScheduler());
materializeTestProbes(underTest);
sinkProbe.ensureSubscription();
sourceProbe.ensureSubscription();
sinkProbe.request(4);
assertThat(sourceProbe.expectRequest()).isEqualTo(16);
changeMaps.forEach(sourceProbe::sendNext);
sourceProbe.sendComplete();
final var sudoRetrievePolicyResponse =
SudoRetrievePolicyResponse.of(policyId, policy, DittoHeaders.empty());
policiesProbe.setAutoPilot(new TestActor.AutoPilot() {
@Override
public TestActor.AutoPilot run(final ActorRef sender, final Object msg) {
sender.tell(sudoRetrievePolicyResponse, policiesProbe.ref());
return keepRunning();
}
});
thingsProbe.setAutoPilot(new TestActor.AutoPilot() {
@Override
public TestActor.AutoPilot run(final ActorRef sender, final Object msg) {
if (msg instanceof final SudoRetrieveThing command) {
final var thingId = (ThingId) command.getEntityId();
final int i = Integer.parseInt(thingId.getName());
final var response = SudoRetrieveThingResponse.of(
thing.toBuilder()
.setId(thingId)
.setRevision(i)
.setAttribute(JsonPointer.of("x"), JsonValue.of(i))
.build()
.toJson(FieldType.all()),
command.getDittoHeaders()
);
final var future = new CompletableFuture<Integer>();
future.completeOnTimeout(i, 4 - i, TimeUnit.SECONDS);
future.whenComplete((j, error) -> sender.tell(response, getRef()));
}
return keepRunning();
}
});
for (final var changeMap : changeMaps) {
final var expectedMetadata = changeMap.values().iterator().next();
final var list = sinkProbe.expectNext(FiniteDuration.apply(60, "s"));
final AbstractWriteModel writeModel = list.get(0);
assertThat(writeModel.getMetadata()).isEqualTo(expectedMetadata);
}
sinkProbe.expectComplete();
}};
}
private void materializeTestProbes(final EnforcementFlow enforcementFlow) {
final var source = TestSource.<Map<ThingId, Metadata>>probe(system);
final var sink = TestSink.<List<AbstractWriteModel>>probe(system);
final var runnableGraph = enforcementFlow.create(source, 16, 1, system)
.mapConcat(x -> x)
.map(List::of)
.mergeSubstreams()
.viaMat(KillSwitches.single(), Keep.both())
.toMat(sink, Keep.both());
final var materializedValue = runnableGraph.run(() -> system);
sourceProbe = materializedValue.first().first();
sinkProbe = materializedValue.second();
}
}