-
Notifications
You must be signed in to change notification settings - Fork 215
/
BaseConsumerActor.java
335 lines (298 loc) · 16.3 KB
/
BaseConsumerActor.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
/*
* 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.connectivity.service.messaging;
import static org.eclipse.ditto.base.model.common.ConditionChecker.checkNotNull;
import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.eclipse.ditto.base.model.common.HttpStatus;
import org.eclipse.ditto.base.model.exceptions.DittoRuntimeException;
import org.eclipse.ditto.base.model.headers.DittoHeaders;
import org.eclipse.ditto.base.model.signals.acks.Acknowledgements;
import org.eclipse.ditto.base.model.signals.commands.CommandResponse;
import org.eclipse.ditto.connectivity.api.ExternalMessage;
import org.eclipse.ditto.connectivity.api.ExternalMessageBuilder;
import org.eclipse.ditto.connectivity.api.ExternalMessageFactory;
import org.eclipse.ditto.connectivity.model.Connection;
import org.eclipse.ditto.connectivity.model.ConnectionId;
import org.eclipse.ditto.connectivity.model.ConnectionType;
import org.eclipse.ditto.connectivity.model.ConnectivityModelFactory;
import org.eclipse.ditto.connectivity.model.ConnectivityStatus;
import org.eclipse.ditto.connectivity.model.ResourceStatus;
import org.eclipse.ditto.connectivity.model.Source;
import org.eclipse.ditto.connectivity.service.config.ConnectivityConfig;
import org.eclipse.ditto.connectivity.service.messaging.InboundMappingSink.ExternalMessageWithSender;
import org.eclipse.ditto.connectivity.service.messaging.monitoring.ConnectionMonitor;
import org.eclipse.ditto.connectivity.service.messaging.monitoring.DefaultConnectionMonitorRegistry;
import org.eclipse.ditto.internal.models.acks.config.AcknowledgementConfig;
import org.eclipse.ditto.internal.utils.akka.logging.ThreadSafeDittoLoggingAdapter;
import org.eclipse.ditto.internal.utils.config.InstanceIdentifierSupplier;
import org.eclipse.ditto.internal.utils.metrics.DittoMetrics;
import org.eclipse.ditto.internal.utils.metrics.instruments.timer.StartedTimer;
import org.eclipse.ditto.internal.utils.tracing.DittoTracing;
import org.eclipse.ditto.internal.utils.tracing.TracingTags;
import akka.NotUsed;
import akka.actor.AbstractActorWithTimers;
import akka.actor.ActorRef;
import akka.pattern.Patterns;
import akka.stream.javadsl.Flow;
import akka.stream.javadsl.Sink;
import kamon.context.Context;
/**
* Base class for consumer actors that holds common fields and handles the address status.
*/
public abstract class BaseConsumerActor extends AbstractActorWithTimers {
private static final String TIMER_ACK_HANDLING = "connectivity_ack_handling";
private static final String COUNTER_ACK_HANDLING = "connectivity_ack_handling_counter";
protected final String sourceAddress;
protected final Source source;
private final ConnectionType connectionType;
protected final ConnectionMonitor inboundMonitor;
protected final ConnectionMonitor inboundAcknowledgedMonitor;
protected final ConnectionId connectionId;
protected final ConnectivityStatusResolver connectivityStatusResolver;
private final Sink<Object, ?> inboundMappingSink;
private final AcknowledgementConfig acknowledgementConfig;
@Nullable private ResourceStatus resourceStatus;
protected BaseConsumerActor(final Connection connection,
final String sourceAddress,
final Sink<Object, ?> inboundMappingSink,
final Source source,
final ConnectivityStatusResolver connectivityStatusResolver,
final ConnectivityConfig connectivityConfig) {
connectionId = checkNotNull(connection, "connection").getId();
this.sourceAddress = checkNotNull(sourceAddress, "sourceAddress");
this.inboundMappingSink = checkNotNull(inboundMappingSink, "inboundMappingSink");
this.source = checkNotNull(source, "source");
connectionType = connection.getConnectionType();
this.connectivityStatusResolver = checkNotNull(connectivityStatusResolver, "connectivityStatusResolver");
resetResourceStatus();
acknowledgementConfig = connectivityConfig.getAcknowledgementConfig();
inboundMonitor = DefaultConnectionMonitorRegistry.fromConfig(connectivityConfig)
.forInboundConsumed(connection, sourceAddress);
inboundAcknowledgedMonitor =
DefaultConnectionMonitorRegistry.fromConfig(connectivityConfig)
.forInboundAcknowledged(connection, sourceAddress);
}
/**
* @return the logging adapter of this actor.
*/
protected abstract ThreadSafeDittoLoggingAdapter log();
protected final Sink<AcknowledgeableMessage, NotUsed> getMessageMappingSink() {
return Flow.fromFunction(this::withSender)
.map(Object.class::cast)
.to(inboundMappingSink);
}
private ExternalMessageWithSender withSender(final AcknowledgeableMessage acknowledgeableMessage) {
// Start per-inbound-signal actor to collect acks of all thing-modify-commands mapped from incoming signal
final Duration collectorLifetime = acknowledgementConfig.getCollectorFallbackLifetime();
final ActorRef responseCollector = getContext().actorOf(ResponseCollectorActor.props(collectorLifetime));
prepareResponseHandler(acknowledgeableMessage, responseCollector);
final ExternalMessage messageWithSourceAndReplyTarget =
addSourceAndReplyTarget(acknowledgeableMessage.getMessage());
log().debug("Forwarding incoming message for mapping. ResponseCollector=<{}>", responseCollector);
return new ExternalMessageWithSender(messageWithSourceAndReplyTarget, responseCollector);
}
private void prepareResponseHandler(final AcknowledgeableMessage acknowledgeableMessage,
final ActorRef responseCollector) {
final StartedTimer ackTimer = DittoMetrics.timer(TIMER_ACK_HANDLING)
.tag(TracingTags.CONNECTION_ID, connectionId.toString())
.tag(TracingTags.CONNECTION_TYPE, connectionType.getName())
.start();
final var ackCounter = DittoMetrics.gauge(COUNTER_ACK_HANDLING)
.tag(TracingTags.CONNECTION_ID, connectionId.toString())
.tag(TracingTags.CONNECTION_TYPE, connectionType.toString())
.increment();
final Context traceContext = DittoTracing.extractTraceContext(acknowledgeableMessage.getMessage().getHeaders());
DittoTracing.wrapTimer(traceContext, ackTimer);
final Duration askTimeout = acknowledgementConfig.getCollectorFallbackAskTimeout();
// Ask response collector actor to get the collected responses in a future
Patterns.ask(responseCollector, ResponseCollectorActor.query(), askTimeout).thenCompose(output -> {
if (output instanceof ResponseCollectorActor.Output) {
return CompletableFuture.completedFuture((ResponseCollectorActor.Output) output);
} else if (output instanceof Throwable) {
log().debug("Patterns.ask failed. ResponseCollector=<{}>", responseCollector);
return CompletableFuture.failedFuture((Throwable) output);
} else {
log().error("Expect ResponseCollectorActor.Output, got: <{}>. ResponseCollector=<{}>", output,
responseCollector);
return CompletableFuture.failedFuture(new ClassCastException("Unexpected acknowledgement type."));
}
}).handle((output, error) -> {
log().debug("Result from ResponseCollector=<{}>: output=<{}> error=<{}>",
responseCollector, output, error);
if (output != null) {
final List<CommandResponse<?>> failedResponses = output.getFailedResponses();
if (output.allExpectedResponsesArrived() && failedResponses.isEmpty()) {
ackTimer.tag(TracingTags.ACK_SUCCESS, true).stop();
ackCounter.decrement();
acknowledgeableMessage.settle();
} else {
// empty failed responses indicate that SetCount was missing
final boolean shouldRedeliver = failedResponses.isEmpty() ||
someFailedResponseRequiresRedelivery(failedResponses);
log().debug("Rejecting [redeliver={}] due to failed responses <{}>. " +
"ResponseCollector=<{}>", shouldRedeliver, failedResponses, responseCollector);
ackTimer.tag(TracingTags.ACK_SUCCESS, false)
.tag(TracingTags.ACK_REDELIVER, shouldRedeliver)
.stop();
ackCounter.decrement();
acknowledgeableMessage.reject(shouldRedeliver);
}
} else {
// don't count this as "failure" in the "source consumed" metric as the consumption
// itself was successful
final DittoRuntimeException dittoRuntimeException =
DittoRuntimeException.asDittoRuntimeException(error, rootCause -> {
// Redeliver and pray this unexpected error goes away
log().debug("Rejecting [redeliver=true] due to error <{}>. " +
"ResponseCollector=<{}>", rootCause, responseCollector);
ackTimer.tag(TracingTags.ACK_SUCCESS, false)
.tag(TracingTags.ACK_REDELIVER, true)
.stop();
ackCounter.decrement();
acknowledgeableMessage.reject(true);
return null;
});
if (dittoRuntimeException != null) {
if (isConsideredSuccess(dittoRuntimeException)) {
ackTimer.tag(TracingTags.ACK_SUCCESS, true).stop();
ackCounter.tag(TracingTags.ACK_SUCCESS, true).decrement();
acknowledgeableMessage.settle();
} else {
final var shouldRedeliver = requiresRedelivery(dittoRuntimeException.getHttpStatus());
log().debug("Rejecting [redeliver={}] due to error <{}>. ResponseCollector=<{}>",
shouldRedeliver, dittoRuntimeException, responseCollector);
ackTimer.tag(TracingTags.ACK_SUCCESS, false)
.tag(TracingTags.ACK_REDELIVER, shouldRedeliver)
.stop();
ackCounter.decrement();
acknowledgeableMessage.reject(shouldRedeliver);
}
}
}
return null;
}).exceptionally(e -> {
log().error(e, "Unexpected error during manual acknowledgement. ResponseCollector=<{}>",
responseCollector);
return null;
});
}
/**
* Send an error to the mapping sink to be published in the reply-target.
*/
protected final Sink<DittoRuntimeException, ?> getDittoRuntimeExceptionSink() {
return Flow.<DittoRuntimeException, DittoRuntimeException>fromFunction(
message -> message.setDittoHeaders(enrichHeadersWithReplyInformation(message.getDittoHeaders())))
.via(Flow.<DittoRuntimeException, Object>fromFunction(value -> {
inboundMonitor.failure(value.getDittoHeaders(), value);
return value;
}))
.to(inboundMappingSink);
}
protected void resetResourceStatus() {
resourceStatus = ConnectivityModelFactory.newSourceStatus(getInstanceIdentifier(),
ConnectivityStatus.OPEN, sourceAddress, "Consumer started.", Instant.now());
}
protected ResourceStatus getCurrentSourceStatus() {
final Optional<ResourceStatus> statusOptional = Optional.ofNullable(resourceStatus);
return ConnectivityModelFactory.newSourceStatus(getInstanceIdentifier(),
statusOptional.map(ResourceStatus::getStatus).orElse(ConnectivityStatus.UNKNOWN),
sourceAddress,
statusOptional.flatMap(ResourceStatus::getStatusDetails).orElse(null),
statusOptional.flatMap(ResourceStatus::getInStateSince).orElse(null));
}
protected void handleAddressStatus(final ResourceStatus resourceStatus) {
if (resourceStatus.getResourceType() == ResourceStatus.ResourceType.UNKNOWN) {
this.resourceStatus = ConnectivityModelFactory.newSourceStatus(getInstanceIdentifier(),
resourceStatus.getStatus(), sourceAddress,
resourceStatus.getStatusDetails().orElse(null),
resourceStatus.getInStateSince().orElse(Instant.now()));
} else {
this.resourceStatus = resourceStatus;
}
}
private ExternalMessage addSourceAndReplyTarget(final ExternalMessage message) {
final ExternalMessageBuilder externalMessageBuilder =
ExternalMessageFactory.newExternalMessageBuilder(message)
.withSource(source);
externalMessageBuilder.withInternalHeaders(enrichHeadersWithReplyInformation(message.getInternalHeaders()));
return externalMessageBuilder.build();
}
private DittoHeaders enrichHeadersWithReplyInformation(final DittoHeaders headers) {
return source.getReplyTarget()
.<DittoHeaders>map(replyTarget -> headers.toBuilder()
.replyTarget(source.getIndex())
.expectedResponseTypes(replyTarget.getExpectedResponseTypes())
.build())
.orElse(headers);
}
private static String getInstanceIdentifier() {
return InstanceIdentifierSupplier.getInstance().get();
}
private static boolean someFailedResponseRequiresRedelivery(final Collection<CommandResponse<?>> failedResponses) {
return failedResponses.stream()
.flatMap(BaseConsumerActor::extractAggregatedResponses)
.map(CommandResponse::getHttpStatus)
.anyMatch(BaseConsumerActor::requiresRedelivery);
}
private static Stream<? extends CommandResponse<?>> extractAggregatedResponses(final CommandResponse<?> response) {
if (response instanceof Acknowledgements) {
return ((Acknowledgements) response).stream();
} else {
return Stream.of(response);
}
}
/**
* Decide whether an Acknowledgement or DittoRuntimeException requires redelivery based on the status.
* Client errors excluding 408 request-timeout and 424 failed-dependency are considered unrecoverable and no
* redelivery will be attempted.
*
* @param status HTTP status of the Acknowledgement or DittoRuntimeException.
* @return whether it requires redelivery.
*/
private static boolean requiresRedelivery(final HttpStatus status) {
if (HttpStatus.REQUEST_TIMEOUT.equals(status) || HttpStatus.FAILED_DEPENDENCY.equals(status)) {
return true;
}
return status.isServerError();
}
/**
* Decide whether a DittoRuntimeException is considered successful processing.
* This happens with ThingPreconditionFailedException and PolicyPreconditionFailedException.
* All DittoRuntimeException with status 412 Precondition Failed are considered success.
*
* @param dittoRuntimeException the DittoRuntimeException.
* @return whether it is considered successful processing.
*/
private static boolean isConsideredSuccess(final DittoRuntimeException dittoRuntimeException) {
return HttpStatus.PRECONDITION_FAILED.equals(dittoRuntimeException.getHttpStatus());
}
/**
* Reject an incoming message.
*/
@FunctionalInterface
public interface Reject {
/**
* Reject a message.
*
* @param shouldRedeliver whether the broker should redeliver.
*/
void reject(boolean shouldRedeliver);
}
}