-
Notifications
You must be signed in to change notification settings - Fork 215
/
ThingUpdater.java
505 lines (452 loc) · 25 KB
/
ThingUpdater.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
/*
* 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.thingsearch.service.updater.actors;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.time.Duration;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.bson.BsonDocument;
import org.bson.BsonInvalidOperationException;
import org.eclipse.ditto.base.model.acks.AcknowledgementRequest;
import org.eclipse.ditto.base.model.acks.DittoAcknowledgementLabel;
import org.eclipse.ditto.base.service.actors.ShutdownBehaviour;
import org.eclipse.ditto.internal.models.streaming.IdentifiableStreamingMessage;
import org.eclipse.ditto.internal.utils.akka.actors.AbstractActorWithStashWithTimers;
import org.eclipse.ditto.internal.utils.akka.logging.DittoDiagnosticLoggingAdapter;
import org.eclipse.ditto.internal.utils.akka.logging.DittoLogger;
import org.eclipse.ditto.internal.utils.akka.logging.DittoLoggerFactory;
import org.eclipse.ditto.internal.utils.akka.streaming.StreamAck;
import org.eclipse.ditto.internal.utils.config.DefaultScopedConfig;
import org.eclipse.ditto.internal.utils.metrics.DittoMetrics;
import org.eclipse.ditto.internal.utils.metrics.instruments.counter.Counter;
import org.eclipse.ditto.internal.utils.metrics.instruments.timer.StartedTimer;
import org.eclipse.ditto.internal.utils.tracing.DittoTracing;
import org.eclipse.ditto.policies.api.PolicyReferenceTag;
import org.eclipse.ditto.policies.model.PolicyId;
import org.eclipse.ditto.things.model.ThingId;
import org.eclipse.ditto.things.model.signals.events.ThingDeleted;
import org.eclipse.ditto.things.model.signals.events.ThingEvent;
import org.eclipse.ditto.thingsearch.api.UpdateReason;
import org.eclipse.ditto.thingsearch.api.commands.sudo.UpdateThing;
import org.eclipse.ditto.thingsearch.api.commands.sudo.UpdateThingResponse;
import org.eclipse.ditto.thingsearch.service.common.config.DittoSearchConfig;
import org.eclipse.ditto.thingsearch.service.common.config.UpdaterConfig;
import org.eclipse.ditto.thingsearch.service.persistence.BulkWriteComplete;
import org.eclipse.ditto.thingsearch.service.persistence.read.MongoThingsSearchPersistence;
import org.eclipse.ditto.thingsearch.service.persistence.write.mapping.BsonDiff;
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.eclipse.ditto.thingsearch.service.persistence.write.streaming.ConsistencyLag;
import org.eclipse.ditto.thingsearch.service.persistence.write.streaming.SearchUpdaterStream;
import org.eclipse.ditto.thingsearch.service.starter.actors.MongoClientExtension;
import com.mongodb.client.model.UpdateOneModel;
import com.mongodb.client.model.WriteModel;
import akka.Done;
import akka.actor.ActorRef;
import akka.actor.PoisonPill;
import akka.actor.Props;
import akka.actor.ReceiveTimeout;
import akka.cluster.sharding.ShardRegion;
import akka.japi.pf.ReceiveBuilder;
import akka.pattern.Patterns;
import akka.stream.javadsl.Sink;
/**
* This Actor initiates persistence updates related to 1 thing.
*/
final class ThingUpdater extends AbstractActorWithStashWithTimers {
private static final String FORCE_UPDATE = "force-update";
private static final AcknowledgementRequest SEARCH_PERSISTED_REQUEST =
AcknowledgementRequest.of(DittoAcknowledgementLabel.SEARCH_PERSISTED);
static final String FORCE_UPDATE_AFTER_START = "FORCE_UPDATE_AFTER_START";
static final String BULK_RESULT_AWAITING_TIMEOUT = "BULK_RESULT_AWAITING_TIMEOUT";
private static final Duration BULK_RESULT_AWAITING_TIMEOUT_DURATION = Duration.ofMinutes(2);
private static final Counter INCORRECT_PATCH_UPDATE_COUNT = DittoMetrics.counter("search_incorrect_patch_updates");
private static final Counter UPDATE_FAILURE_COUNT = DittoMetrics.counter("search_update_failures");
private static final Counter PATCH_UPDATE_COUNT = DittoMetrics.counter("search_patch_updates");
private static final Counter PATCH_SKIP_COUNT = DittoMetrics.counter("search_patch_skips");
private static final Counter FULL_UPDATE_COUNT = DittoMetrics.counter("search_full_updates");
private static final Duration THING_DELETION_TIMEOUT = Duration.ofMinutes(5);
private static final DittoLogger LOGGER = DittoLoggerFactory.getLogger(ThingUpdater.class);
// logger for "trace" statements
private final DittoDiagnosticLoggingAdapter log;
private final ThingId thingId;
private final ShutdownBehaviour shutdownBehaviour;
private final ActorRef changeQueueActor;
private final double forceUpdateProbability;
private final MongoClientExtension mongoClientExtension;
private final Consumer<AbstractWriteModel> recoveryCompleteConsumer;
// state of Thing and Policy
private long thingRevision = -1L;
@Nullable private PolicyId policyId = null;
private long policyRevision = -1L;
// cache last update document for incremental updates
@Nullable AbstractWriteModel lastWriteModel = null;
private boolean forceNextUpdate = false;
@SuppressWarnings("unused") //It is used via reflection. See props method.
private ThingUpdater(final ActorRef pubSubMediator,
final ActorRef changeQueueActor,
final double forceUpdateProbability,
final Duration forceUpdateAfterStartTimeout,
final double forceUpdateAfterStartRandomFactor) {
this(pubSubMediator, changeQueueActor, forceUpdateProbability, forceUpdateAfterStartTimeout,
forceUpdateAfterStartRandomFactor, null, true, true,
writeModel -> {});
}
ThingUpdater(final ActorRef pubSubMediator,
final ActorRef changeQueueActor,
final double forceUpdateProbability,
final Duration forceUpdateAfterStartTimeout,
final double forceUpdateAfterStartRandomFactor,
@Nullable final MongoClientExtension mongoClientExtension,
final boolean loadPreviousState,
final boolean awaitRecovery,
final Consumer<AbstractWriteModel> recoveryCompleteConsumer) {
log = DittoLoggerFactory.getDiagnosticLoggingAdapter(this);
final var dittoSearchConfig = DittoSearchConfig.of(
DefaultScopedConfig.dittoScoped(getContext().getSystem().settings().config())
);
thingId = tryToGetThingId();
shutdownBehaviour = ShutdownBehaviour.fromId(thingId, pubSubMediator, getSelf());
this.changeQueueActor = changeQueueActor;
this.forceUpdateProbability = forceUpdateProbability;
this.mongoClientExtension = Objects.requireNonNullElseGet(mongoClientExtension,
() -> MongoClientExtension.get(getContext().getSystem()));
this.recoveryCompleteConsumer = recoveryCompleteConsumer;
getContext().setReceiveTimeout(dittoSearchConfig.getUpdaterConfig().getMaxIdleTime());
if (loadPreviousState) {
recoverLastWriteModel(thingId);
} else if (!awaitRecovery) {
// Not loading the previous model is equivalent to initializing via a delete-one model.
final var noLastModel = ThingDeleteModel.of(Metadata.of(thingId, -1L, null, null, null));
getSelf().tell(noLastModel, getSelf());
}
if (forceUpdateAfterStartTimeout.negated().isNegative()) {
getTimers().startSingleTimer(FORCE_UPDATE_AFTER_START, FORCE_UPDATE_AFTER_START,
randomizeTimeout(forceUpdateAfterStartTimeout, forceUpdateAfterStartRandomFactor));
}
}
/**
* Creates Akka configuration object for this actor.
*
* @param pubSubMediator Akka pub-sub mediator.
* @param changeQueueActor reference of the change queue actor.
* @param updaterConfig the updater config.
* @return the Akka configuration Props object
*/
static Props props(final ActorRef pubSubMediator, final ActorRef changeQueueActor,
final UpdaterConfig updaterConfig) {
// Use duration 0 to disable force-update-after-start-timeout.
final var effectiveForceUpdateAfterStartTimeout = updaterConfig.isForceUpdateAfterStartEnabled()
? updaterConfig.getForceUpdateAfterStartTimeout()
: Duration.ZERO;
return Props.create(ThingUpdater.class, pubSubMediator, changeQueueActor,
updaterConfig.getForceUpdateProbability(),
effectiveForceUpdateAfterStartTimeout,
updaterConfig.getForceUpdateAfterStartRandomFactor());
}
@Override
public Receive createReceive() {
return shutdownBehaviour.createReceive()
.match(AbstractWriteModel.class, this::recoveryComplete)
.match(ReceiveTimeout.class, this::stopThisActor)
.matchAny(this::matchAnyDuringRecovery)
.build();
}
private void recoveryComplete(final AbstractWriteModel writeModel) {
log.debug("Recovered: <{}>", writeModel.getClass().getSimpleName());
LOGGER.trace("Recovered: <{}>", writeModel);
thingRevision = writeModel.getMetadata().getThingRevision();
writeModel.getMetadata().getPolicyRevision().ifPresent(rev -> this.policyRevision = rev);
lastWriteModel = writeModel;
getContext().become(recoveredBehavior(), true);
unstashAll();
recoveryCompleteConsumer.accept(writeModel);
}
private Receive recoveredBehavior() {
return recoveredBehavior("recoveredBehavior");
}
private Receive recoveredBehavior(final String currentBehaviorHintForLogging) {
return shutdownBehaviour.createReceive()
.match(ThingEvent.class, this::processThingEvent)
.match(AbstractWriteModel.class, this::onNextWriteModel)
.match(PolicyReferenceTag.class, this::processPolicyReferenceTag)
.match(UpdateThing.class, this::updateThing)
.match(UpdateThingResponse.class, this::processUpdateThingResponse)
.match(ReceiveTimeout.class, this::stopThisActor)
.matchEquals(FORCE_UPDATE_AFTER_START, this::forceUpdateAfterStart)
.matchAny(m -> {
log.warning("Unknown message in '{}': {}", currentBehaviorHintForLogging, m);
unhandled(m);
})
.build();
}
private Receive recoveredAwaitingBulkWriteResultBehavior() {
getTimers().startSingleTimer(BULK_RESULT_AWAITING_TIMEOUT, BULK_RESULT_AWAITING_TIMEOUT,
BULK_RESULT_AWAITING_TIMEOUT_DURATION);
return ReceiveBuilder.create()
.match(AbstractWriteModel.class, writeModel -> {
log.info("Stashing received writeModel while being in " +
"'recoveredAwaitingBulkWriteResultBehavior': <{}> with revision: <{}>",
writeModel.getClass().getSimpleName(), writeModel.getMetadata().getThingRevision());
stash();
})
.match(BulkWriteComplete.class, bulkWriteComplete -> {
log.withCorrelationId(bulkWriteComplete.getBulkWriteCorrelationId().orElse(null))
.debug("Got confirmation bulkWrite was performed - switching to 'recoveredBehavior'");
getTimers().cancel(BULK_RESULT_AWAITING_TIMEOUT);
getContext().become(recoveredBehavior(), true);
unstashAll();
})
.matchEquals(BULK_RESULT_AWAITING_TIMEOUT, bra -> {
log.warning("Encountered timeout being in 'recoveredAwaitingBulkWriteResultBehavior' - " +
"switching back to 'recoveredBehavior'");
getTimers().cancel(BULK_RESULT_AWAITING_TIMEOUT);
getContext().become(recoveredBehavior(), true);
unstashAll();
})
.build()
.orElse(recoveredBehavior("recoveredAwaitingBulkWriteResultBehavior"));
}
private void matchAnyDuringRecovery(final Object message) {
log.debug("Stashing during initialization: <{}>", message);
stash();
}
private void forceUpdateAfterStart(final String trigger) {
log.debug("Forcing the next update to be a full 'forceUpdate'");
forceNextUpdate = true;
enqueueMetadata(UpdateReason.FORCE_UPDATE_AFTER_START);
}
private void onNextWriteModel(final AbstractWriteModel nextWriteModel) {
final WriteModel<BsonDocument> mongoWriteModel;
final boolean forceUpdate = (forceUpdateProbability > 0 && Math.random() < forceUpdateProbability) ||
forceNextUpdate;
if (!forceUpdate && lastWriteModel instanceof ThingWriteModel && nextWriteModel instanceof ThingWriteModel) {
final var last = (ThingWriteModel) lastWriteModel;
final var next = (ThingWriteModel) nextWriteModel;
final Optional<BsonDiff> diff = tryComputeDiff(next.getThingDocument(), last.getThingDocument());
if (diff.isPresent() && diff.get().isDiffSmaller()) {
final var aggregationPipeline = diff.get().consumeAndExport();
if (aggregationPipeline.isEmpty()) {
log.debug("Skipping update due to empty diff <{}>", nextWriteModel.getClass().getSimpleName());
LOGGER.trace("Skipping update due to empty diff <{}>", nextWriteModel);
getSender().tell(Done.getInstance(), getSelf());
PATCH_SKIP_COUNT.increment();
return;
}
final var filter = ((ThingWriteModel) nextWriteModel)
.asPatchUpdate(lastWriteModel.getMetadata().getThingRevision())
.getFilter();
mongoWriteModel = new UpdateOneModel<>(filter, aggregationPipeline);
log.debug("Using incremental update <{}>", mongoWriteModel.getClass().getSimpleName());
LOGGER.trace("Using incremental update <{}>", mongoWriteModel);
PATCH_UPDATE_COUNT.increment();
} else {
mongoWriteModel = nextWriteModel.toMongo();
log.debug("Using replacement because diff is bigger or nonexistent: <{}>",
mongoWriteModel.getClass().getSimpleName());
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Using replacement because diff is bigger or nonexistent. Diff=<{}>",
diff.map(BsonDiff::consumeAndExport));
}
FULL_UPDATE_COUNT.increment();
}
} else {
mongoWriteModel = nextWriteModel.toMongo();
if (forceUpdate) {
log.debug("Using replacement (forceUpdate) <{}> - forceNextUpdate was: <{}>",
mongoWriteModel.getClass().getSimpleName(), forceNextUpdate);
LOGGER.trace("Using replacement (forceUpdate) <{}> - forceNextUpdate was: <{}>", mongoWriteModel,
forceNextUpdate);
forceNextUpdate = false;
} else {
log.debug("Using replacement <{}>", mongoWriteModel.getClass().getSimpleName());
LOGGER.trace("Using replacement <{}>", mongoWriteModel);
}
FULL_UPDATE_COUNT.increment();
}
getSender().tell(mongoWriteModel, getSelf());
lastWriteModel = nextWriteModel;
log.debug("Responded with mongoWriteModel - switching to 'recoveredAwaitingBulkWriteResultBehavior'");
getContext().become(recoveredAwaitingBulkWriteResultBehavior(), true);
}
private Optional<BsonDiff> tryComputeDiff(final BsonDocument minuend, final BsonDocument subtrahend) {
try {
return Optional.of(BsonDiff.minusThingDocs(minuend, subtrahend));
} catch (final BsonInvalidOperationException e) {
log.error(e, "Failed to compute BSON diff between <{}> and <{}>", minuend, subtrahend);
return Optional.empty();
}
}
private void stopThisActor(final Object reason) {
log.debug("stopping ThingUpdater <{}> due to <{}>", thingId, reason);
getContext().getParent().tell(new ShardRegion.Passivate(PoisonPill.getInstance()), getSelf());
}
/**
* Export the metadata of this updater.
*
* @param timer an optional timer measuring the search updater's consistency lag.
*/
private Metadata exportMetadata(@Nullable final ThingEvent<?> event, @Nullable final StartedTimer timer) {
return Metadata.of(thingId, thingRevision, policyId, policyRevision,
event == null ? List.of() : List.of(event), timer, null);
}
private Metadata exportMetadataWithSender(final boolean shouldAcknowledge,
final ThingEvent<?> event,
final ActorRef sender,
final StartedTimer consistencyLagTimer) {
if (shouldAcknowledge) {
return Metadata.of(thingId, thingRevision, policyId, policyRevision, List.of(event), consistencyLagTimer,
sender);
} else {
return exportMetadata(event, consistencyLagTimer);
}
}
/**
* Push metadata of this updater to the queue of thing-changes to be streamed into the persistence.
*
* @param updateReason the reason why the search index is updated.
*/
private void enqueueMetadata(final UpdateReason updateReason) {
enqueueMetadata(exportMetadata(null, null).withUpdateReason(updateReason));
}
private void enqueueMetadata(final Metadata metadata) {
changeQueueActor.tell(metadata.withOrigin(getSelf()), getSelf());
}
private void updateThing(final UpdateThing updateThing) {
log.withCorrelationId(updateThing)
.info("Requested to update search index <{}> by <{}>", updateThing, getSender());
if (updateThing.getDittoHeaders().containsKey(FORCE_UPDATE)) {
lastWriteModel = null;
forceNextUpdate = true;
}
final Metadata metadata = exportMetadata(null, null)
.invalidateCaches(updateThing.shouldInvalidateThing(), updateThing.shouldInvalidatePolicy())
.withUpdateReason(updateThing.getUpdateReason());
if (updateThing.getDittoHeaders().getAcknowledgementRequests().contains(SEARCH_PERSISTED_REQUEST)) {
enqueueMetadata(metadata.withSender(getSender()));
} else {
enqueueMetadata(metadata);
}
}
private void processUpdateThingResponse(final UpdateThingResponse response) {
final var isFailure = !response.isSuccess();
final var isIncorrectPatch =
response.getDittoHeaders().containsKey(SearchUpdaterStream.FORCE_UPDATE_INCORRECT_PATCH);
if (isFailure || isIncorrectPatch) {
// discard last write model: index document is not known
lastWriteModel = null;
final Metadata metadata =
exportMetadata(null, null).invalidateCaches(true, true);
final String warningTemplate;
// check first for incorrect patch update otherwise the else branch is never triggered.
if (isIncorrectPatch) {
warningTemplate = "Inconsistent patch update detected for <{}>; updating to <{}>.";
INCORRECT_PATCH_UPDATE_COUNT.increment();
} else {
warningTemplate = "Got negative acknowledgement for <{}>; updating to <{}>.";
UPDATE_FAILURE_COUNT.increment();
}
log.withCorrelationId(response)
.warning(warningTemplate, Metadata.fromResponse(response), metadata);
enqueueMetadata(metadata.withUpdateReason(UpdateReason.RETRY));
}
}
private void processPolicyReferenceTag(final PolicyReferenceTag policyReferenceTag) {
if (log.isDebugEnabled()) {
log.debug("Received new Policy-Reference-Tag for thing <{}> with revision <{}>, policy-id <{}> and " +
"policy-revision <{}>: <{}>.",
thingId, thingRevision, policyId, policyRevision, policyReferenceTag.asIdentifierString());
}
final var policyTag = policyReferenceTag.getPolicyTag();
final var policyIdOfTag = policyTag.getEntityId();
if (!Objects.equals(policyId, policyIdOfTag) || policyRevision < policyTag.getRevision()) {
this.policyId = policyIdOfTag;
policyRevision = policyTag.getRevision();
enqueueMetadata(UpdateReason.POLICY_UPDATE);
} else {
log.debug("Dropping <{}> because my policyId=<{}> and policyRevision=<{}>",
policyReferenceTag, policyId, policyRevision);
}
acknowledge(policyReferenceTag);
}
private void processThingEvent(final ThingEvent<?> thingEvent) {
final DittoDiagnosticLoggingAdapter l = log.withCorrelationId(thingEvent);
l.debug("Received new thing event for thing id <{}> with revision <{}>.", thingId, thingEvent.getRevision());
final boolean shouldAcknowledge =
thingEvent.getDittoHeaders().getAcknowledgementRequests().contains(SEARCH_PERSISTED_REQUEST);
// check if the revision is valid (thingEvent.revision = 1 + sequenceNumber)
if (thingEvent.getRevision() <= thingRevision && !shouldAcknowledge) {
l.debug("Dropped thing event for thing id <{}> with revision <{}> because it was older than or "
+ "equal to the current sequence number <{}> of the update actor.", thingId,
thingEvent.getRevision(), thingRevision);
} else {
l.debug("Applying thing event <{}>.", thingEvent);
thingRevision = thingEvent.getRevision();
final StartedTimer timer = DittoMetrics.timer(ConsistencyLag.TIMER_NAME)
.tag(ConsistencyLag.TAG_SHOULD_ACK, Boolean.toString(shouldAcknowledge))
.onExpiration(startedTimer ->
l.warning("Timer measuring consistency lag timed out for event <{}>", thingEvent))
.start();
DittoTracing.wrapTimer(DittoTracing.extractTraceContext(thingEvent), timer);
ConsistencyLag.startS0InUpdater(timer);
enqueueMetadata(
exportMetadataWithSender(shouldAcknowledge, thingEvent, getSender(), timer).withUpdateReason(
UpdateReason.THING_UPDATE));
}
if (thingEvent instanceof ThingDeleted) {
// will stop this actor after 5 minutes (finishing up updating the index):
// this time should be longer than the consistency lag, otherwise the actor will be stopped before the
// actual "delete" is applied to the search index:
getContext().setReceiveTimeout(THING_DELETION_TIMEOUT);
}
}
private ThingId tryToGetThingId() {
final Charset utf8 = StandardCharsets.UTF_8;
try {
return getThingId(utf8);
} catch (final UnsupportedEncodingException e) {
throw new IllegalStateException(MessageFormat.format("Charset <{0}> is unsupported!", utf8.name()), e);
}
}
private ThingId getThingId(final Charset charset) throws UnsupportedEncodingException {
final String actorName = self().path().name();
return ThingId.of(URLDecoder.decode(actorName, charset.name()));
}
private void acknowledge(final IdentifiableStreamingMessage message) {
final ActorRef sender = getSender();
if (!getContext().system().deadLetters().equals(sender)) {
getSender().tell(StreamAck.success(message.asIdentifierString()), getSelf());
}
}
private void recoverLastWriteModel(final ThingId thingId) {
final var actorSystem = getContext().getSystem();
// using search client instead of updater client for READ to ensure consistency in case of shard migration
final var client = mongoClientExtension.getSearchClient();
final var searchPersistence = new MongoThingsSearchPersistence(client, actorSystem);
final var writeModelFuture = searchPersistence.recoverLastWriteModel(thingId).runWith(Sink.head(), actorSystem);
Patterns.pipe(writeModelFuture, getContext().getDispatcher()).to(getSelf());
}
private static Duration randomizeTimeout(final Duration minTimeout, final double randomFactor) {
final long randomDelayMillis = (long) (Math.random() * randomFactor * minTimeout.toMillis());
return minTimeout.plus(Duration.ofMillis(randomDelayMillis));
}
}