/
PolicyPersistenceActor.java
executable file
·292 lines (251 loc) · 11.8 KB
/
PolicyPersistenceActor.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
/*
* Copyright (c) 2017 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.ditto.services.policies.persistence.actors;
import java.time.Duration;
import java.time.Instant;
import java.util.Comparator;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.StreamSupport;
import javax.annotation.Nullable;
import org.eclipse.ditto.model.base.exceptions.DittoRuntimeExceptionBuilder;
import org.eclipse.ditto.model.base.headers.DittoHeaderDefinition;
import org.eclipse.ditto.model.base.headers.DittoHeaders;
import org.eclipse.ditto.model.base.json.JsonSchemaVersion;
import org.eclipse.ditto.model.policies.Label;
import org.eclipse.ditto.model.policies.Policy;
import org.eclipse.ditto.model.policies.PolicyEntry;
import org.eclipse.ditto.model.policies.PolicyId;
import org.eclipse.ditto.model.policies.PolicyLifecycle;
import org.eclipse.ditto.model.policies.Subject;
import org.eclipse.ditto.model.policies.SubjectExpiry;
import org.eclipse.ditto.model.policies.Subjects;
import org.eclipse.ditto.services.models.policies.PolicyTag;
import org.eclipse.ditto.services.policies.common.config.DittoPoliciesConfig;
import org.eclipse.ditto.services.policies.common.config.PolicyConfig;
import org.eclipse.ditto.services.policies.persistence.actors.strategies.commands.PolicyCommandStrategies;
import org.eclipse.ditto.services.policies.persistence.actors.strategies.events.PolicyEventStrategies;
import org.eclipse.ditto.services.utils.cluster.DistPubSubAccess;
import org.eclipse.ditto.services.utils.config.DefaultScopedConfig;
import org.eclipse.ditto.services.utils.persistence.SnapshotAdapter;
import org.eclipse.ditto.services.utils.persistence.mongo.config.ActivityCheckConfig;
import org.eclipse.ditto.services.utils.persistence.mongo.config.SnapshotConfig;
import org.eclipse.ditto.services.utils.persistentactors.AbstractShardedPersistenceActor;
import org.eclipse.ditto.services.utils.persistentactors.commands.CommandStrategy;
import org.eclipse.ditto.services.utils.persistentactors.commands.DefaultContext;
import org.eclipse.ditto.services.utils.persistentactors.events.EventStrategy;
import org.eclipse.ditto.services.utils.persistentactors.results.Result;
import org.eclipse.ditto.signals.commands.base.Command;
import org.eclipse.ditto.signals.commands.policies.exceptions.PolicyNotAccessibleException;
import org.eclipse.ditto.signals.events.policies.PolicyEvent;
import org.eclipse.ditto.signals.events.policies.SubjectDeleted;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.japi.Pair;
import akka.japi.pf.ReceiveBuilder;
import akka.persistence.RecoveryCompleted;
/**
* PersistentActor which "knows" the state of a single {@link Policy}.
*/
public final class PolicyPersistenceActor
extends AbstractShardedPersistenceActor<Command, Policy, PolicyId, PolicyId, PolicyEvent> {
/**
* The prefix of the persistenceId for Policies.
*/
public static final String PERSISTENCE_ID_PREFIX = "policy:";
/**
* The ID of the journal plugin this persistence actor uses.
*/
static final String JOURNAL_PLUGIN_ID = "akka-contrib-mongodb-persistence-policies-journal";
/**
* The ID of the snapshot plugin this persistence actor uses.
*/
static final String SNAPSHOT_PLUGIN_ID = "akka-contrib-mongodb-persistence-policies-snapshots";
private static final String NEXT_SUBJECT_EXPIRY_TIMER = "next-subject-expiry-timer";
private final ActorRef pubSubMediator;
private final PolicyConfig policyConfig;
PolicyPersistenceActor(final PolicyId policyId,
final SnapshotAdapter<Policy> snapshotAdapter,
final ActorRef pubSubMediator) {
super(policyId, snapshotAdapter);
this.pubSubMediator = pubSubMediator;
final DittoPoliciesConfig policiesConfig = DittoPoliciesConfig.of(
DefaultScopedConfig.dittoScoped(getContext().getSystem().settings().config())
);
this.policyConfig = policiesConfig.getPolicyConfig();
}
/**
* Creates Akka configuration object {@link Props} for this PolicyPersistenceActor.
*
* @param policyId the ID of the Policy this Actor manages.
* @param snapshotAdapter the adapter to serialize Policy snapshots.
* @param pubSubMediator the PubSub mediator actor.
* @return the Akka configuration Props object
*/
public static Props props(final PolicyId policyId,
final SnapshotAdapter<Policy> snapshotAdapter,
final ActorRef pubSubMediator) {
return Props.create(PolicyPersistenceActor.class, policyId, snapshotAdapter, pubSubMediator);
}
@Override
public String persistenceId() {
return PERSISTENCE_ID_PREFIX + entityId;
}
@Override
public String journalPluginId() {
return JOURNAL_PLUGIN_ID;
}
@Override
public String snapshotPluginId() {
return SNAPSHOT_PLUGIN_ID;
}
@Override
protected Class<PolicyEvent> getEventClass() {
return PolicyEvent.class;
}
@Override
protected CommandStrategy.Context<PolicyId> getStrategyContext() {
return DefaultContext.getInstance(entityId, log);
}
@Override
protected PolicyCommandStrategies getCreatedStrategy() {
return PolicyCommandStrategies.getInstance(policyConfig);
}
@Override
protected CommandStrategy<? extends Command, Policy, PolicyId, Result<PolicyEvent>> getDeletedStrategy() {
return PolicyCommandStrategies.getCreatePolicyStrategy(policyConfig);
}
@Override
protected EventStrategy<PolicyEvent, Policy> getEventStrategy() {
return PolicyEventStrategies.getInstance();
}
@Override
protected ActivityCheckConfig getActivityCheckConfig() {
return policyConfig.getActivityCheckConfig();
}
@Override
protected SnapshotConfig getSnapshotConfig() {
return policyConfig.getSnapshotConfig();
}
@Override
protected boolean entityExistsAsDeleted() {
return null != entity && entity.hasLifecycle(PolicyLifecycle.DELETED);
}
@Override
protected DittoRuntimeExceptionBuilder newNotAccessibleExceptionBuilder() {
return PolicyNotAccessibleException.newBuilder(entityId);
}
@Override
protected void publishEvent(final PolicyEvent event) {
pubSubMediator.tell(DistPubSubAccess.publishViaGroup(PolicyEvent.TYPE_PREFIX, event), getSender());
final boolean policyEnforcerInvalidatedPreemptively = Boolean.parseBoolean(event.getDittoHeaders()
.getOrDefault(DittoHeaderDefinition.POLICY_ENFORCER_INVALIDATED_PREEMPTIVELY.getKey(),
Boolean.FALSE.toString()));
if (!policyEnforcerInvalidatedPreemptively) {
final PolicyTag policyTag = PolicyTag.of(entityId, event.getRevision());
pubSubMediator.tell(DistPubSubAccess.publish(PolicyTag.PUB_SUB_TOPIC_INVALIDATE_ENFORCERS, policyTag),
getSender());
}
}
@Override
protected JsonSchemaVersion getEntitySchemaVersion(final Policy entity) {
return entity.getImplementedSchemaVersion();
}
@Override
protected Receive matchAnyAfterInitialization() {
return ReceiveBuilder.create()
.matchEquals(DeleteOldestExpiredSubject.INSTANCE, this::handleDeleteExpiredSubjects)
.matchAny(message -> log.warning("Unknown message: {}", message))
.build();
}
@Override
protected void recoveryCompleted(final RecoveryCompleted event) {
if (entity != null) {
onEntityModified();
becomeCreatedOrDeletedHandler();
}
}
@Override
protected void onEntityModified() {
findEarliestSubjectExpiryTimestamp(entity).ifPresent(earliestSubjectExpiryTimestamp -> {
timers().cancel(NEXT_SUBJECT_EXPIRY_TIMER);
final Instant earliestExpiry = earliestSubjectExpiryTimestamp.getTimestamp();
final Duration durationBetweenNowAndEarliestExpiry = Duration.between(Instant.now(), earliestExpiry);
if (durationBetweenNowAndEarliestExpiry.isNegative()) {
// there are currently expired subjects, so delete the oldest right away:
getSelf().tell(DeleteOldestExpiredSubject.INSTANCE, getSelf());
} else {
log.info("Scheduling message for deleting next expired subject in: <{}> - at: <{}>",
durationBetweenNowAndEarliestExpiry, earliestExpiry);
timers().startSingleTimer(NEXT_SUBJECT_EXPIRY_TIMER, DeleteOldestExpiredSubject.INSTANCE,
durationBetweenNowAndEarliestExpiry);
}
});
}
private void handleDeleteExpiredSubjects(final DeleteOldestExpiredSubject deleteOldestExpiredSubject) {
log.debug("Calculating whether subjects did expire and need to be deleted..");
calculateSubjectDeletedEventOfOldestExpiredSubject(entityId, entity)
.ifPresent(subjectDeleted ->
persistAndApplyEvent(subjectDeleted, (persistedEvent, resultingEntity) ->
log.withCorrelationId(persistedEvent)
.info("Deleted expired subject <{}> of label <{}>",
subjectDeleted.getSubjectId(), subjectDeleted.getLabel())
)
);
}
private Optional<SubjectDeleted> calculateSubjectDeletedEventOfOldestExpiredSubject(final PolicyId policyId,
@Nullable final Iterable<PolicyEntry> policyEntries) {
if (null == policyEntries) {
return Optional.empty();
}
final Instant eventTimestamp = Instant.now();
final DittoHeaders eventDittoHeaders = DittoHeaders.newBuilder()
.correlationId(UUID.randomUUID().toString())
.build();
return StreamSupport.stream(policyEntries.spliterator(), false)
.flatMap(entry -> entry.getSubjects().stream()
.map(subject -> Pair.create(entry.getLabel(), subject))
)
.filter(PolicyPersistenceActor::keepExpiredSubjects)
.min(Comparator.comparing(pair -> pair.second().getExpiry().orElseThrow()))
.map(pair ->
SubjectDeleted.of(policyId,
pair.first(),
pair.second().getId(),
getRevisionNumber(),
eventTimestamp,
eventDittoHeaders
)
);
}
private static boolean keepExpiredSubjects(final Pair<Label, Subject> pair) {
return pair.second().getExpiry()
.map(SubjectExpiry::isExpired)
.orElse(false);
}
private static Optional<SubjectExpiry> findEarliestSubjectExpiryTimestamp(
@Nullable final Iterable<PolicyEntry> policyEntries) {
if (null == policyEntries) {
return Optional.empty();
}
return StreamSupport.stream(policyEntries.spliterator(), false)
.map(PolicyEntry::getSubjects)
.flatMap(Subjects::stream)
.map(Subject::getExpiry)
.flatMap(Optional::stream)
.min(Comparator.comparing(SubjectExpiry::getTimestamp));
}
private static final class DeleteOldestExpiredSubject {
private static final DeleteOldestExpiredSubject INSTANCE = new DeleteOldestExpiredSubject();
}
}