/
EnforcementFlow.java
294 lines (261 loc) · 13.7 KB
/
EnforcementFlow.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
/*
* 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.thingsearch.service.persistence.write.streaming;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import javax.annotation.Nullable;
import org.eclipse.ditto.base.model.headers.DittoHeaders;
import org.eclipse.ditto.internal.utils.cache.Cache;
import org.eclipse.ditto.internal.utils.cache.CacheFactory;
import org.eclipse.ditto.internal.utils.cache.CacheKey;
import org.eclipse.ditto.internal.utils.cache.entry.Entry;
import org.eclipse.ditto.internal.utils.cacheloaders.PolicyEnforcer;
import org.eclipse.ditto.internal.utils.cacheloaders.PolicyEnforcerCacheLoader;
import org.eclipse.ditto.json.JsonObject;
import org.eclipse.ditto.json.JsonRuntimeException;
import org.eclipse.ditto.policies.model.PolicyId;
import org.eclipse.ditto.policies.model.PolicyIdInvalidException;
import org.eclipse.ditto.policies.model.enforcers.Enforcer;
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.commands.exceptions.ThingNotAccessibleException;
import org.eclipse.ditto.thingsearch.service.common.config.StreamCacheConfig;
import org.eclipse.ditto.thingsearch.service.common.config.StreamConfig;
import org.eclipse.ditto.thingsearch.service.persistence.write.mapping.EnforcedThingMapper;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.benmanes.caffeine.cache.AsyncCacheLoader;
import akka.NotUsed;
import akka.actor.ActorRef;
import akka.dispatch.MessageDispatcher;
import akka.pattern.Patterns;
import akka.stream.Attributes;
import akka.stream.javadsl.Flow;
import akka.stream.javadsl.Keep;
import akka.stream.javadsl.Source;
/**
* Converts Thing changes into write models by retrieving data and applying enforcement via an enforcer cache.
*/
final class EnforcementFlow {
private static final Source<Entry<Enforcer>, NotUsed> ENFORCER_NONEXISTENT = Source.single(Entry.nonexistent());
private final Logger log = LoggerFactory.getLogger(getClass());
private final ActorRef thingsShardRegion;
private final Cache<CacheKey, Entry<Enforcer>> policyEnforcerCache;
private final Duration thingsTimeout;
private final Duration cacheRetryDelay;
private final int maxArraySize;
private EnforcementFlow(final ActorRef thingsShardRegion,
final Cache<CacheKey, Entry<Enforcer>> policyEnforcerCache,
final Duration thingsTimeout,
final Duration cacheRetryDelay,
final int maxArraySize) {
this.thingsShardRegion = thingsShardRegion;
this.policyEnforcerCache = policyEnforcerCache;
this.thingsTimeout = thingsTimeout;
this.cacheRetryDelay = cacheRetryDelay;
this.maxArraySize = maxArraySize;
}
/**
* Create an EnforcementFlow object.
*
* @param updaterStreamConfig configuration of the updater stream.
* @param thingsShardRegion the shard region to retrieve things from.
* @param policiesShardRegion the shard region to retrieve policies from.
* @param cacheDispatcher dispatcher for the enforcer cache.
* @return an EnforcementFlow object.
*/
public static EnforcementFlow of(final StreamConfig updaterStreamConfig,
final ActorRef thingsShardRegion,
final ActorRef policiesShardRegion,
final MessageDispatcher cacheDispatcher) {
final Duration askTimeout = updaterStreamConfig.getAskTimeout();
final StreamCacheConfig streamCacheConfig = updaterStreamConfig.getCacheConfig();
final AsyncCacheLoader<CacheKey, Entry<PolicyEnforcer>> policyEnforcerCacheLoader =
new PolicyEnforcerCacheLoader(askTimeout, policiesShardRegion);
final Cache<CacheKey, Entry<Enforcer>> policyEnforcerCache =
CacheFactory.createCache(policyEnforcerCacheLoader, streamCacheConfig,
EnforcementFlow.class.getCanonicalName() + ".cache", cacheDispatcher)
.projectValues(PolicyEnforcer::project, PolicyEnforcer::embed);
return new EnforcementFlow(thingsShardRegion, policyEnforcerCache, askTimeout,
streamCacheConfig.getRetryDelay(), updaterStreamConfig.getMaxArraySize());
}
private static CacheKey getPolicyCacheKey(final PolicyId policyId) {
return CacheKey.of(policyId);
}
/**
* Extract Thing ID from SudoRetrieveThingResponse.
* This is needed because SudoRetrieveThingResponse#id() is always the empty string.
*
* @param response the SudoRetrieveThingResponse.
* @return the extracted Thing ID.
*/
private static ThingId getThingId(final SudoRetrieveThingResponse response) {
final String thingId = response.getEntity().asObject().getValueOrThrow(Thing.JsonFields.ID);
return ThingId.of(thingId);
}
/**
* Decide whether to reload an enforcer entry.
* An entry should be reload if it is out-of-date, nonexistent, or corresponds to a nonexistent entity.
*
* @param entry the enforcer cache entry
* @param metadata the metadata
* @param iteration how many times cache read was attempted
* @return whether to reload the cache
*/
private static boolean shouldReloadCache(@Nullable final Entry<?> entry, final Metadata metadata,
final int iteration) {
if (iteration <= 0) {
return metadata.shouldInvalidateCache() || entry == null || !entry.exists() ||
entry.getRevision() < metadata.getPolicyRevision().orElse(Long.MAX_VALUE);
} else {
// never attempt to reload cache more than once
return false;
}
}
/**
* Create a flow from Thing changes to write models by retrieving data from Things shard region and enforcer cache.
*
* @param shouldAcknowledge defines whether for the created flow the requested ack
* {@link org.eclipse.ditto.base.model.acks.DittoAcknowledgementLabel#SEARCH_PERSISTED} was required or not.
* @param parallelism how many SudoRetrieveThing commands to send in parallel.
* @return the flow.
*/
public Flow<Map<ThingId, Metadata>, Source<AbstractWriteModel, NotUsed>, NotUsed> create(
final boolean shouldAcknowledge, final int parallelism) {
return Flow.<Map<ThingId, Metadata>>create()
.map(changeMap -> {
log.info("Updating search index with <shouldAcknowledge={}> of <{}> things", shouldAcknowledge,
changeMap.size());
return sudoRetrieveThingJsons(parallelism, changeMap).flatMapConcat(responseMap ->
Source.fromIterator(changeMap.values()::iterator)
.flatMapMerge(parallelism, metadataRef ->
computeWriteModel(metadataRef, responseMap.get(metadataRef.getThingId()))
.async(MongoSearchUpdaterFlow.DISPATCHER_NAME, parallelism)
)
.withAttributes(Attributes.inputBuffer(parallelism, parallelism))
);
})
.withAttributes(Attributes.inputBuffer(1, 1));
}
private Source<Map<ThingId, SudoRetrieveThingResponse>, NotUsed> sudoRetrieveThingJsons(
final int parallelism, final Map<ThingId, Metadata> changeMap) {
return Source.fromIterator(changeMap.entrySet()::iterator)
.flatMapMerge(parallelism, entry -> sudoRetrieveThing(entry)
.async(MongoSearchUpdaterFlow.DISPATCHER_NAME, parallelism))
.withAttributes(Attributes.inputBuffer(parallelism, parallelism))
.<Map<ThingId, SudoRetrieveThingResponse>>fold(new HashMap<>(), (map, response) -> {
map.put(getThingId(response), response);
return map;
})
.map(result -> {
log.info("Got SudoRetrieveThingResponse <{}> times", result.size());
return result;
});
}
private Source<SudoRetrieveThingResponse, NotUsed> sudoRetrieveThing(final Map.Entry<ThingId, Metadata> entry) {
final ThingId thingId = entry.getKey();
ConsistencyLag.startS3RetrieveThing(entry.getValue());
final SudoRetrieveThing command =
SudoRetrieveThing.withOriginalSchemaVersion(thingId, DittoHeaders.empty());
final CompletionStage<Source<SudoRetrieveThingResponse, NotUsed>> responseFuture =
// using default thread-pool for asking Things shard region
Patterns.ask(thingsShardRegion, command, thingsTimeout)
.handle((response, error) -> {
if (response instanceof SudoRetrieveThingResponse) {
return Source.single((SudoRetrieveThingResponse) response);
} else {
if (error != null) {
log.error("Failed command <{}>", command, error);
} else if (!(response instanceof ThingNotAccessibleException)) {
log.error("Unexpected response for <{}>: <{}>", command, response);
}
return Source.empty();
}
});
return Source.completionStageSource(responseFuture)
.viaMat(Flow.create(), Keep.none());
}
private Source<AbstractWriteModel, NotUsed> computeWriteModel(final Metadata metadata,
@Nullable final SudoRetrieveThingResponse sudoRetrieveThingResponse) {
ConsistencyLag.startS4GetEnforcer(metadata);
if (sudoRetrieveThingResponse == null) {
return Source.single(ThingDeleteModel.of(metadata));
} else {
final JsonObject thing = sudoRetrieveThingResponse.getEntity().asObject();
return getEnforcer(metadata, thing)
.map(entry -> {
if (entry.exists()) {
try {
return EnforcedThingMapper.toWriteModel(thing, entry.getValueOrThrow(),
entry.getRevision(),
maxArraySize,
metadata);
} catch (final JsonRuntimeException e) {
log.error(e.getMessage(), e);
return ThingDeleteModel.of(metadata);
}
} else {
// no enforcer; delete thing from search index
return ThingDeleteModel.of(metadata);
}
});
}
}
/**
* Get the enforcer of a thing or an empty source if it does not exist.
*
* @param metadata metadata of the thing.
* @param thing the thing
* @return source of an enforcer or an empty source.
*/
private Source<Entry<Enforcer>, NotUsed> getEnforcer(final Metadata metadata, final JsonObject thing) {
try {
return thing.getValue(Thing.JsonFields.POLICY_ID)
.map(PolicyId::of)
.map(policyId -> readCachedEnforcer(metadata, getPolicyCacheKey(policyId), 0))
.orElse(ENFORCER_NONEXISTENT);
} catch (PolicyIdInvalidException e) {
return ENFORCER_NONEXISTENT;
}
}
private Source<Entry<Enforcer>, NotUsed> readCachedEnforcer(final Metadata metadata,
final CacheKey policyId, final int iteration) {
final Source<Entry<Enforcer>, ?> lazySource = Source.lazySource(() -> {
final CompletionStage<Source<Entry<Enforcer>, NotUsed>> enforcerFuture = policyEnforcerCache.get(policyId)
.thenApply(optionalEnforcerEntry -> {
if (shouldReloadCache(optionalEnforcerEntry.orElse(null), metadata, iteration)) {
// invalid entry; invalidate and retry after delay
policyEnforcerCache.invalidate(policyId);
return readCachedEnforcer(metadata, policyId, iteration + 1)
.initialDelay(cacheRetryDelay);
} else {
return optionalEnforcerEntry.map(Source::single)
.orElse(ENFORCER_NONEXISTENT);
}
})
.exceptionally(error -> {
log.error("Failed to read policyEnforcerCache", error);
return ENFORCER_NONEXISTENT;
});
return Source.completionStageSource(enforcerFuture);
});
return lazySource.viaMat(Flow.create(), Keep.none());
}
}