-
Notifications
You must be signed in to change notification settings - Fork 215
/
ConnectionPersistenceActorRecoveryTest.java
326 lines (275 loc) · 12.7 KB
/
ConnectionPersistenceActorRecoveryTest.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
/*
* Copyright (c) 2019 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.ditto.connectivity.service.messaging;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.eclipse.ditto.base.model.headers.DittoHeaders;
import org.eclipse.ditto.connectivity.model.Connection;
import org.eclipse.ditto.connectivity.model.ConnectionConfigurationInvalidException;
import org.eclipse.ditto.connectivity.model.ConnectionId;
import org.eclipse.ditto.connectivity.model.ConnectionLifecycle;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.OpenConnection;
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.ConnectivityEvent;
import org.eclipse.ditto.connectivity.service.messaging.persistence.ConnectionMongoSnapshotAdapter;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigValueFactory;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.cluster.pubsub.DistributedPubSub;
import akka.japi.Creator;
import akka.persistence.AbstractPersistentActor;
import akka.persistence.RecoveryCompleted;
import akka.persistence.SnapshotMetadata;
import akka.persistence.SnapshotOffer;
import akka.testkit.javadsl.TestKit;
/**
* Unit test for {@link org.eclipse.ditto.connectivity.service.messaging.persistence.ConnectionPersistenceActor}.
*/
public final class ConnectionPersistenceActorRecoveryTest extends WithMockServers {
private static final String PERSISTENCE_ID_PREFIX = "connection:";
private static final String JOURNAL_PLUGIN_ID = "akka-contrib-mongodb-persistence-connection-journal";
private static final String SNAPSHOT_PLUGIN_ID = "akka-contrib-mongodb-persistence-connection-snapshots";
private static ActorSystem actorSystem;
private static ActorRef pubSubMediator;
private static ActorRef proxyActor;
private ConnectionId connectionId;
private ConnectionCreated connectionCreated;
private ConnectionDeleted connectionDeleted;
private static final ConnectionMongoSnapshotAdapter SNAPSHOT_ADAPTER = new ConnectionMongoSnapshotAdapter();
@BeforeClass
public static void setUp() {
actorSystem = ActorSystem.create("AkkaTestSystem",
ConfigFactory.parseMap(Map.of("pre-enforcer-provider","org.eclipse.ditto.policies.enforcement." +
"DefaultPreEnforcerProvider")).withFallback(TestConstants.CONFIG));
pubSubMediator = DistributedPubSub.get(actorSystem).mediator();
proxyActor = actorSystem.actorOf(TestConstants.ProxyActorMock.props());
}
@AfterClass
public static void tearDown() {
TestKit.shutdownActorSystem(actorSystem, scala.concurrent.duration.Duration.apply(5, TimeUnit.SECONDS), false);
}
@Before
public void init() {
connectionId = TestConstants.createRandomConnectionId();
final Connection connection = TestConstants.createConnection(connectionId);
connectionCreated = ConnectionCreated.of(connection, 1L, TestConstants.INSTANT, DittoHeaders.empty(), null);
connectionDeleted = ConnectionDeleted.of(connectionId, 2L, TestConstants.INSTANT, DittoHeaders.empty(), null);
}
/**
* This tests the behavior for connections that were deleted without saving a snapshot i.e the last stored event
* is a ConnectionDeleted event.
*/
@Test
public void testRecoveryOfDeletedConnectionsWithoutSnapshot() {
new TestKit(actorSystem) {{
final Queue<ConnectivityEvent<?>> existingEvents
= new LinkedList<>(Arrays.asList(connectionCreated, connectionDeleted));
final Props fakeProps = FakePersistenceActor.props(connectionId, getRef(), existingEvents);
actorSystem.actorOf(fakeProps);
expectMsgEquals("persisted");
final ActorRef underTest = TestConstants.createConnectionSupervisorActor(connectionId, actorSystem,
pubSubMediator, proxyActor);
watch(underTest);
// expect termination because it was deleted (last event was ConnectionDeleted)
expectTerminated(underTest);
// verify snapshot was saved with DELETED lifecycle
final SnapshotOffer snapshot = getSnapshotOffer(null, 2); // created + deleted = 2
final Queue<Object> expected = new LinkedList<>(Arrays.asList(snapshot, RecoveryCompleted.getInstance()));
actorSystem.actorOf(RecoverActor.props(connectionId, getRef(), expected));
expectMsgEquals("recovered");
}};
}
@Test
public void testRecoveryOfConnectionWithBlockedHost() {
final ActorSystem akkaTestSystem =
ActorSystem.create("AkkaTestSystem", TestConstants.CONFIG.withValue("ditto.connectivity.connection" +
".blocked-hostnames", ConfigValueFactory.fromAnyRef("127.0.0.1"))
.withValue("pre-enforcer-provider",ConfigValueFactory.fromAnyRef(
"org.eclipse.ditto.policies.enforcement.DefaultPreEnforcerProvider")));
final ActorRef mediator = DistributedPubSub.get(akkaTestSystem).mediator();
final ActorRef proxyActor = actorSystem.actorOf(TestConstants.ProxyActorMock.props());
try {
new TestKit(akkaTestSystem) {{
final Queue<ConnectivityEvent<?>> existingEvents = new LinkedList<>(List.of(connectionCreated));
final Props fakeProps = FakePersistenceActor.props(connectionId, getRef(), existingEvents);
akkaTestSystem.actorOf(fakeProps);
expectMsgEquals("persisted");
final ActorRef underTest = TestConstants.createConnectionSupervisorActor(connectionId, akkaTestSystem,
mediator, proxyActor);
underTest.tell(OpenConnection.of(connectionId, DittoHeaders.empty()), getRef());
final ConnectionConfigurationInvalidException exception =
expectMsgClass(ConnectionConfigurationInvalidException.class);
assertThat(exception)
.hasMessageContaining("The configured host '127.0.0.1' may not be used for the connection");
}};
} finally {
TestKit.shutdownActorSystem(akkaTestSystem);
}
}
private Connection setLifecycleDeleted(final Connection connection) {
return connection
.toBuilder()
.lifecycle(ConnectionLifecycle.DELETED)
.build();
}
private SnapshotOffer getSnapshotOffer(@Nullable final Object deletedConnection, final int sequenceNr) {
final SnapshotMetadata metadata = new SnapshotMetadata(PERSISTENCE_ID_PREFIX + connectionId, sequenceNr, 0);
return new SnapshotOffer(metadata, deletedConnection);
}
/**
* This actor verifies recovery of a persistence actor by checking if the events received during recovery matches
* the expected events.
*/
static class RecoverActor extends AbstractPersistentActor {
private final ConnectionId connectionId;
private final ActorRef ref;
private final Queue<Object> expected;
private RecoverActor(final ConnectionId connectionId, final ActorRef ref,
final Queue<Object> expected) {
this.connectionId = connectionId;
this.ref = ref;
this.expected = expected;
}
static Props props(final ConnectionId connectionId, final ActorRef probe,
final Queue<Object> expected) {
return Props.create(RecoverActor.class, new Creator<>() {
private static final long serialVersionUID = 1L;
@Override
public RecoverActor create() {
return new RecoverActor(connectionId, probe, expected);
}
});
}
@Override
public Receive createReceiveRecover() {
return receiveBuilder()
.match(SnapshotOffer.class, this::checkSnapshotOffer)
.matchAny(this::check)
.build();
}
private void check(final Object recovered) {
final Object next = expected.poll();
if (recovered.equals(next)) {
if (expected.isEmpty()) {
ref.tell("recovered", getSelf());
}
} else {
fail("expected: " + next + " but got: " + recovered);
}
}
private void checkSnapshotOffer(final SnapshotOffer snapshotOffer) {
final Object next = expected.poll();
if (next instanceof SnapshotOffer) {
final SnapshotOffer expected = (SnapshotOffer) next;
if (expected.metadata().sequenceNr() != snapshotOffer.metadata().sequenceNr()) {
fail("expected sequence nr: " + expected.metadata().sequenceNr() + " but got: " +
snapshotOffer.metadata().sequenceNr());
}
if (!Objects.equals(expected.snapshot(), SNAPSHOT_ADAPTER.fromSnapshotStore(snapshotOffer))) {
fail("expected: " + expected.snapshot() + " but got: " + snapshotOffer.snapshot());
}
} else {
fail("expected snapshot offer");
}
}
private void fail(final String reason) {
ref.tell(reason, getSelf());
getContext().stop(getSelf());
}
@Override
public Receive createReceive() {
return receiveBuilder()
.matchAny(m -> ref.forward(m, context())).build();
}
@Override
public String persistenceId() {
return PERSISTENCE_ID_PREFIX + connectionId;
}
@Override
public String journalPluginId() {
return JOURNAL_PLUGIN_ID;
}
@Override
public String snapshotPluginId() {
return SNAPSHOT_PLUGIN_ID;
}
}
/**
* This actor prepares the (in-memory) persistence with the given events.
*/
static class FakePersistenceActor extends AbstractPersistentActor {
private final ConnectionId connectionId;
private final ActorRef probe;
private final Queue<ConnectivityEvent<?>> events;
private FakePersistenceActor(final ConnectionId connectionId, final ActorRef probe,
final Queue<ConnectivityEvent<?>> events) {
this.connectionId = connectionId;
this.probe = probe;
this.events = events;
}
static Props props(final ConnectionId connectionId, final ActorRef probe,
final Queue<ConnectivityEvent<?>> events) {
return Props.create(FakePersistenceActor.class,
(Creator<FakePersistenceActor>) () -> new FakePersistenceActor(connectionId, probe, events));
}
@Override
public Receive createReceiveRecover() {
return receiveBuilder().build();
}
@Override
public Receive createReceive() {
return receiveBuilder()
.match(ConnectivityEvent.class, e -> persist(e, persisted -> persistNextEvent()))
.build();
}
private void persistNextEvent() {
final ConnectivityEvent<?> next = events.poll();
if (next != null) {
getSelf().tell(next, getSelf());
} else {
probe.tell("persisted", getSelf());
getContext().stop(getSelf());
}
}
@Override
public void preStart() {
persistNextEvent();
}
@Override
public String persistenceId() {
return PERSISTENCE_ID_PREFIX + connectionId;
}
@Override
public String journalPluginId() {
return JOURNAL_PLUGIN_ID;
}
@Override
public String snapshotPluginId() {
return SNAPSHOT_PLUGIN_ID;
}
}
}