-
Notifications
You must be signed in to change notification settings - Fork 214
/
PersistenceCleanupActorTest.java
351 lines (312 loc) · 15.3 KB
/
PersistenceCleanupActorTest.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
/*
* 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.internal.utils.persistentactors.cleanup;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.ditto.base.api.common.ModifyConfig;
import org.eclipse.ditto.base.api.common.ModifyConfigResponse;
import org.eclipse.ditto.base.api.common.RetrieveConfig;
import org.eclipse.ditto.base.api.common.RetrieveConfigResponse;
import org.eclipse.ditto.base.model.headers.DittoHeaders;
import org.eclipse.ditto.internal.utils.health.RetrieveHealth;
import org.eclipse.ditto.internal.utils.health.RetrieveHealthResponse;
import org.eclipse.ditto.internal.utils.health.StatusDetailMessage;
import org.eclipse.ditto.internal.utils.health.StatusInfo;
import org.eclipse.ditto.internal.utils.persistence.mongo.streaming.MongoReadJournal;
import org.eclipse.ditto.json.JsonFactory;
import org.eclipse.ditto.json.JsonObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.mongodb.client.result.DeleteResult;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigRenderOptions;
import org.apache.pekko.Done;
import org.apache.pekko.NotUsed;
import org.apache.pekko.actor.ActorRef;
import org.apache.pekko.actor.ActorSystem;
import org.apache.pekko.actor.FSM;
import org.apache.pekko.actor.Props;
import org.apache.pekko.event.Logging;
import org.apache.pekko.japi.Pair;
import org.apache.pekko.stream.Attributes;
import org.apache.pekko.stream.KillSwitches;
import org.apache.pekko.stream.javadsl.Keep;
import org.apache.pekko.stream.javadsl.Source;
import org.apache.pekko.stream.testkit.javadsl.TestSource;
import org.apache.pekko.testkit.javadsl.TestKit;
/**
* Tests {@link PersistenceCleanupActor}.
*/
public final class PersistenceCleanupActorTest {
private final ActorSystem actorSystem = ActorSystem.create("test",
ConfigFactory.load("test.conf"));
private final AtomicReference<Source<Source<CleanupResult, NotUsed>, NotUsed>> sourceBox =
new AtomicReference<>(Source.empty());
private Cleanup cleanup;
private Credits credits;
@Before
public void init() {
cleanup = mock(Cleanup.class);
credits = mock(Credits.class);
doAnswer(inv -> Source.empty()).when(cleanup).getCleanupStream(any());
doAnswer(inv -> sourceBox.get()).when(credits).regulate(any(), any());
}
@After
public void cleanUp() {
TestKit.shutdownActorSystem(actorSystem);
}
@Test
public void emptyStream() {
new TestKit(actorSystem) {{
final ActorRef underTest = childActorOf(testProps());
final var retrieveHealth = RetrieveHealth.newInstance();
final var probeSource =
TestSource.<Source<CleanupResult, NotUsed>>probe(actorSystem);
final var probeSourcePair = probeSource.preMaterialize(actorSystem);
final var probe = probeSourcePair.first();
sourceBox.set(probeSourcePair.second());
underTest.tell(retrieveHealth, getRef());
expectMsg(retrieveHealthResponse("IN_QUIET_PERIOD", ""));
underTest.tell(FSM.StateTimeout$.MODULE$, ActorRef.noSender());
probe.expectRequest();
underTest.tell(retrieveHealth, getRef());
expectMsg(retrieveHealthResponse("RUNNING", ""));
probe.sendComplete();
waitForResponse(this, underTest, retrieveHealthResponse("IN_QUIET_PERIOD", ""), probe::expectNoMsg);
}};
}
@Test
public void successfulStream() {
new TestKit(actorSystem) {{
final ActorRef underTest = childActorOf(testProps());
final var retrieveHealth = RetrieveHealth.newInstance();
final var probeSource =
TestSource.<Source<CleanupResult, NotUsed>>probe(actorSystem);
final var probeSourcePair = probeSource.preMaterialize(actorSystem);
final var probe = probeSourcePair.first();
sourceBox.set(probeSourcePair.second());
underTest.tell(FSM.StateTimeout$.MODULE$, ActorRef.noSender());
probe.expectRequest();
probe.sendNext(Source.single(new CleanupResult(
CleanupResult.Type.SNAPSHOTS,
new SnapshotRevision("thing:p:id", 1234, true),
DeleteResult.acknowledged(4)
)));
waitForResponse(this, underTest, retrieveHealthResponse("RUNNING", "thing:p:id"), probe::expectNoMsg);
// WHEN stream completes successfully
probe.sendComplete();
waitForResponse(this, underTest, retrieveHealthResponse("IN_QUIET_PERIOD", ""), probe::expectNoMsg);
// THEN the starting PID is reset
final var killSwitchPair = Source.<Source<CleanupResult, NotUsed>>never()
.viaMat(KillSwitches.single(), Keep.right())
.preMaterialize(actorSystem);
sourceBox.set(killSwitchPair.second());
underTest.tell(FSM.StateTimeout$.MODULE$, ActorRef.noSender());
underTest.tell(retrieveHealth, getRef());
expectMsg(retrieveHealthResponse("RUNNING", ""));
verify(cleanup, timeout(5000L).times(2)).getCleanupStream(eq(""));
killSwitchPair.first().shutdown();
}};
}
@Test
public void failedStream() {
new TestKit(actorSystem) {{
// uncomment to un-suppress error log
actorSystem.eventStream().setLogLevel(Attributes.logLevelOff());
final ActorRef underTest = childActorOf(testProps());
final var retrieveHealth = RetrieveHealth.newInstance();
final var probeSource =
TestSource.<Source<CleanupResult, NotUsed>>probe(actorSystem);
final var probeSourcePair = probeSource.preMaterialize(actorSystem);
final var probe = probeSourcePair.first();
sourceBox.set(probeSourcePair.second());
underTest.tell(FSM.StateTimeout$.MODULE$, ActorRef.noSender());
probe.expectRequest();
final var pid = "thing:p:id";
probe.sendNext(Source.single(new CleanupResult(
CleanupResult.Type.SNAPSHOTS,
new SnapshotRevision(pid, 1234, true),
DeleteResult.acknowledged(4)
)));
waitForResponse(this, underTest, retrieveHealthResponse("RUNNING", pid), probe::expectNoMsg);
// WHEN stream fails
probe.sendError(new IllegalStateException("Expected error"));
waitForResponse(this, underTest, retrieveHealthResponse("IN_QUIET_PERIOD", pid), probe::expectNoMsg);
// THEN the starting PID is set to the last successful pid
final var killSwitchPair = Source.<Source<CleanupResult, NotUsed>>never()
.viaMat(KillSwitches.single(), Keep.right())
.preMaterialize(actorSystem);
sourceBox.set(killSwitchPair.second());
underTest.tell(FSM.StateTimeout$.MODULE$, ActorRef.noSender());
underTest.tell(retrieveHealth, getRef());
expectMsg(retrieveHealthResponse("RUNNING", pid));
verify(cleanup, timeout(5000L)).getCleanupStream(eq(pid));
killSwitchPair.first().shutdown();
}};
}
@Test
public void retrieveConfig() {
new TestKit(actorSystem) {{
final ActorRef underTest = childActorOf(testProps());
final var retrieveConfig = RetrieveConfig.of();
underTest.tell(retrieveConfig, getRef());
final var retrieveConfigResponse = expectMsgClass(RetrieveConfigResponse.class);
final String expectedConfigJson =
CleanupConfig.of(ConfigFactory.empty()).render().root().render(ConfigRenderOptions.concise());
assertThat(retrieveConfigResponse.getConfig()).isEqualTo(JsonFactory.readFrom(expectedConfigJson));
}};
}
@Test
public void modifyConfigInQuietPeriod() {
new TestKit(actorSystem) {{
final ActorRef underTest = childActorOf(testProps());
final var modifyConfig =
ModifyConfig.of(JsonObject.newBuilder().set("enabled", false).build(), DittoHeaders.empty());
underTest.tell(modifyConfig, getRef());
final var response = expectMsgClass(ModifyConfigResponse.class);
final var expectedConfig = CleanupConfig.of(ConfigFactory.parseMap(Map.of("cleanup.enabled", false)));
assertThat(response.getConfig()).containsExactlyInAnyOrderElementsOf(
JsonObject.of(expectedConfig.render().root().render(ConfigRenderOptions.concise())));
}};
}
@Test
public void modifyConfigWhenRunning() {
new TestKit(actorSystem) {{
final ActorRef underTest = childActorOf(testProps());
// GIVEN a cleanup stream is running
final var retrieveHealth = RetrieveHealth.newInstance();
sourceBox.set(Source.never());
underTest.tell(FSM.StateTimeout$.MODULE$, ActorRef.noSender());
underTest.tell(retrieveHealth, getRef());
expectMsg(retrieveHealthResponse("RUNNING", ""));
// WHEN config is modified
final var modifyConfig = ModifyConfig.of(JsonObject.newBuilder()
.set("enabled", false)
.set("last-pid", "thing:last:pid")
.build(),
DittoHeaders.empty());
underTest.tell(modifyConfig, getRef());
final var response = expectMsgClass(ModifyConfigResponse.class);
final var expectedConfig = CleanupConfig.of(ConfigFactory.parseMap(Map.of("cleanup.enabled", false)));
assertThat(response.getConfig()).containsExactlyInAnyOrderElementsOf(
JsonObject.of(expectedConfig.render().root().render(ConfigRenderOptions.concise())));
// THEN the running stream is shutdown
waitForResponse(this, underTest, retrieveHealthResponse("IN_QUIET_PERIOD", "thing:last:pid"), () -> {
try {
Thread.sleep(300L);
} catch (final Exception e) {
throw new AssertionError(e);
}
});
}};
}
@Test
public void shutdownInQuietPeriod() {
new TestKit(actorSystem) {{
final ActorRef underTest = childActorOf(testProps());
underTest.tell(PersistenceCleanupActor.Control.SERVICE_REQUESTS_DONE, getRef());
expectMsg(Done.getInstance());
}};
}
@Test
public void shutdownWhenRunning() {
new TestKit(actorSystem) {{
final ActorRef underTest = childActorOf(testProps());
// GIVEN a cleanup stream is running
final var retrieveHealth = RetrieveHealth.newInstance();
final var probeSource =
TestSource.<Source<CleanupResult, NotUsed>>probe(actorSystem);
final var probeSourcePair = probeSource.preMaterialize(actorSystem);
final var probe = probeSourcePair.first();
sourceBox.set(probeSourcePair.second());
underTest.tell(FSM.StateTimeout$.MODULE$, ActorRef.noSender());
underTest.tell(retrieveHealth, getRef());
expectMsg(retrieveHealthResponse("RUNNING", ""));
// WHEN graceful shutdown is initiated
underTest.tell(PersistenceCleanupActor.Control.SERVICE_REQUESTS_DONE, getRef());
// THEN expect cancellation and Done
probe.expectCancellation();
expectMsg(Done.getInstance());
}};
}
@Test
public void shutdownWhenStreamCompleted() throws InterruptedException {
new TestKit(actorSystem) {{
final ActorRef underTest = childActorOf(testProps());
final var retrieveHealth = RetrieveHealth.newInstance();
final var probeSource =
TestSource.<Source<CleanupResult, NotUsed>>probe(actorSystem);
final var probeSourcePair = probeSource.preMaterialize(actorSystem);
final var probe = probeSourcePair.first();
sourceBox.set(probeSourcePair.second());
underTest.tell(FSM.StateTimeout$.MODULE$, ActorRef.noSender());
probe.expectRequest();
probe.sendNext(Source.single(new CleanupResult(
CleanupResult.Type.SNAPSHOTS,
new SnapshotRevision("thing:p:id", 1234, true),
DeleteResult.acknowledged(4)
)));
waitForResponse(this, underTest, retrieveHealthResponse("RUNNING", "thing:p:id"), probe::expectNoMsg);
// WHEN stream completes successfully and graceful shutdown is initiated
probe.sendComplete();
waitForResponse(this, underTest, retrieveHealthResponse("IN_QUIET_PERIOD", ""), probe::expectNoMsg);
underTest.tell(PersistenceCleanupActor.Control.SERVICE_REQUESTS_DONE, getRef());
// THEN expect Done
expectMsg(Done.getInstance());
}};
}
private void waitForResponse(final TestKit testKit,
final ActorRef underTest,
final RetrieveHealthResponse expectedResponse,
final Runnable wait) {
final var retries = 30;
Object lastResponse = null;
for (int i = 1; i <= retries; ++i) {
underTest.tell(RetrieveHealth.newInstance(), testKit.getRef());
final var response = testKit.expectMsgClass(Duration.of(30, ChronoUnit.SECONDS), RetrieveHealthResponse.class);
if (response.equals(expectedResponse)) {
return;
}
lastResponse = response;
Logging.getLogger(actorSystem, this).info("Waiting {}/{}", i, retries);
wait.run();
}
throw new AssertionError(
"Did not receive expected response: " + expectedResponse + "\nlastResponse=" + lastResponse);
}
private Props testProps() {
return Props.create(PersistenceCleanupActor.class,
() -> new PersistenceCleanupActor(cleanup, credits, mock(MongoReadJournal.class),
() -> Pair.create(0, 1)));
}
private static RetrieveHealthResponse retrieveHealthResponse(final String stateName, final String lastPid) {
return RetrieveHealthResponse.of(
StatusInfo.fromDetail(StatusDetailMessage.of(StatusDetailMessage.Level.INFO, JsonObject.newBuilder()
.set("state", stateName)
.set("pid", lastPid)
.build())
),
DittoHeaders.empty()
);
}
}