/
MessageMappingProcessorActor.java
278 lines (238 loc) · 11.9 KB
/
MessageMappingProcessorActor.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
/*
* Copyright (c) 2017 Bosch Software Innovations GmbH.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/epl-2.0/index.php
*
* Contributors:
* Bosch Software Innovations GmbH - initial contribution
*/
package org.eclipse.ditto.services.connectivity.messaging;
import java.util.Collections;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.eclipse.ditto.json.JsonCollectors;
import org.eclipse.ditto.json.JsonFactory;
import org.eclipse.ditto.model.base.auth.AuthorizationContext;
import org.eclipse.ditto.model.base.auth.AuthorizationSubject;
import org.eclipse.ditto.model.base.common.ConditionChecker;
import org.eclipse.ditto.model.base.common.HttpStatusCode;
import org.eclipse.ditto.model.base.exceptions.DittoRuntimeException;
import org.eclipse.ditto.model.base.headers.DittoHeaderDefinition;
import org.eclipse.ditto.model.base.headers.DittoHeaders;
import org.eclipse.ditto.model.connectivity.ExternalMessage;
import org.eclipse.ditto.services.utils.akka.LogUtil;
import org.eclipse.ditto.signals.base.Signal;
import org.eclipse.ditto.signals.commands.base.CommandResponse;
import org.eclipse.ditto.signals.commands.things.ThingErrorResponse;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.Status;
import akka.cluster.pubsub.DistributedPubSubMediator;
import akka.event.DiagnosticLoggingAdapter;
import akka.japi.Creator;
import akka.japi.pf.ReceiveBuilder;
import kamon.Kamon;
import kamon.trace.TraceContext;
import scala.Option;
/**
* This Actor processes incoming {@link Signal}s and dispatches them via {@link DistributedPubSubMediator} to a
* consumer actor.
*/
public final class MessageMappingProcessorActor extends AbstractActor {
/**
* The name of this Actor in the ActorSystem.
*/
public static final String ACTOR_NAME_PREFIX = "messageMappingProcessor-";
private final DiagnosticLoggingAdapter log = LogUtil.obtain(this);
private final ActorRef pubSubMediator;
private final String pubSubTargetPath;
private final ActorRef commandProducer;
private final AuthorizationContext authorizationContext;
private final Cache<String, TraceContext> traces;
private final MessageHeaderFilter headerFilter;
private final MessageMappingProcessor processor;
private MessageMappingProcessorActor(final ActorRef pubSubMediator, final String pubSubTargetPath,
final ActorRef commandProducer, final AuthorizationContext authorizationContext,
final MessageHeaderFilter headerFilter,
final MessageMappingProcessor processor) {
this.pubSubMediator = pubSubMediator;
this.pubSubTargetPath = pubSubTargetPath;
this.commandProducer = commandProducer;
this.authorizationContext = authorizationContext;
this.processor = processor;
this.headerFilter = headerFilter;
traces = CacheBuilder.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.removalListener((RemovalListener<String, TraceContext>) notification
-> log.debug("Trace for {} removed.", notification.getKey()))
.build();
log.info("Configured for processing messages with the following content types: {}",
processor.getSupportedContentTypes());
log.info("Interpreting messages with missing content type as '{}'", processor.getDefaultContentType());
}
/**
* Creates Akka configuration object for this actor.
*
* @param pubSubMediator the akka pubsub mediator actor
* @param pubSubTargetPath the target path where incoming messages are sent
* @param commandProducer actor that handles outgoing messages
* @param authorizationContext the authorization context (authorized subjects) that are set in command headers
* @param headerFilter the header filter used to apply on responses
* @param processor the MessageMappingProcessor to use
* @return the Akka configuration Props object
*/
public static Props props(final ActorRef pubSubMediator, final String pubSubTargetPath,
final ActorRef commandProducer,
final AuthorizationContext authorizationContext,
final MessageHeaderFilter headerFilter,
final MessageMappingProcessor processor) {
return Props.create(MessageMappingProcessorActor.class, new Creator<MessageMappingProcessorActor>() {
private static final long serialVersionUID = 1L;
@Override
public MessageMappingProcessorActor create() {
return new MessageMappingProcessorActor(pubSubMediator, pubSubTargetPath, commandProducer,
authorizationContext, headerFilter, processor);
}
});
}
/**
* Creates Akka configuration object for this actor.
*
* @param pubSubMediator the akka pubsub mediator actor
* @param pubSubTargetPath the target path where incoming messages are sent
* @param commandProducer actor that handles outgoing messages
* @param authorizationContext the authorization context (authorized subjects) that are set in command headers
* @param processor the MessageMappingProcessor to use
* @return the Akka configuration Props object
*/
public static Props props(final ActorRef pubSubMediator, final String pubSubTargetPath,
final ActorRef commandProducer,
final AuthorizationContext authorizationContext,
final MessageMappingProcessor processor) {
return props(pubSubMediator, pubSubTargetPath, commandProducer,
authorizationContext,
new MessageHeaderFilter(MessageHeaderFilter.Mode.EXCLUDE, Collections.emptyList()),
processor);
}
@Override
public Receive createReceive() {
return ReceiveBuilder.create()
.match(ExternalMessage.class, this::handle)
.match(CommandResponse.class, this::handleCommandResponse)
.match(Signal.class, this::handleSignal)
.match(DittoRuntimeException.class, this::handleDittoRuntimeException)
.match(Status.Failure.class, f -> log.warning("Got failure with cause {}: {}",
f.cause().getClass().getSimpleName(), f.cause().getMessage()))
.matchAny(m -> {
log.debug("Unknown message: {}", m);
unhandled(m);
}).build();
}
private void handle(final ExternalMessage m) {
ConditionChecker.checkNotNull(m);
final String correlationId = m.getHeaders().get(DittoHeaderDefinition.CORRELATION_ID.getKey());
LogUtil.enhanceLogWithCorrelationId(log, correlationId);
final String authSubjectsArray = authorizationContext.stream()
.map(AuthorizationSubject::getId)
.map(JsonFactory::newValue)
.collect(JsonCollectors.valuesToArray())
.toString();
final ExternalMessage messageWithAuthSubject =
m.withHeader(DittoHeaderDefinition.AUTHORIZATION_SUBJECTS.getKey(), authSubjectsArray);
try {
final Optional<Signal<?>> signalOpt = processor.process(messageWithAuthSubject);
signalOpt.ifPresent(signal -> {
final DittoHeaders adjustedHeaders = signal.getDittoHeaders().toBuilder()
.authorizationContext(authorizationContext)
.build();
// overwrite the auth-subjects to the configured ones after mapping in order to be sure that the mapping
// does not choose/change the auth-subjects itself:
final Signal<?> adjustedSignal = signal.setDittoHeaders(adjustedHeaders);
startTrace(adjustedSignal);
log.info("Publishing '{}' to '{}'", adjustedSignal.getType(), pubSubTargetPath);
pubSubMediator.tell(new DistributedPubSubMediator.Send(pubSubTargetPath, adjustedSignal, true),
getSelf());
});
} catch (final DittoRuntimeException e) {
handleDittoRuntimeException(e);
} catch (final Exception e) {
log.warning("Got <{}> when message was processed: <{}>", e.getClass().getSimpleName(), e.getMessage());
}
}
private void handleDittoRuntimeException(final DittoRuntimeException exception) {
final ThingErrorResponse errorResponse = ThingErrorResponse.of(exception);
LogUtil.enhanceLogWithCorrelationId(log, exception);
log.info( "Got DittoRuntimeException '{}' when command via AMQP was processed: {}",
exception.getErrorCode(), exception.getMessage());
handleCommandResponse(errorResponse);
}
private void handleCommandResponse(final CommandResponse<?> response) {
LogUtil.enhanceLogWithCorrelationId(log, response);
finishTrace(response);
if (response.getStatusCodeValue() < HttpStatusCode.BAD_REQUEST.toInt()) {
log.debug("Received response: {}", response);
} else {
log.info("Received error response: {}", response.toJsonString());
}
handleSignal(response);
}
private void handleSignal(final Signal<?> response) {
LogUtil.enhanceLogWithCorrelationId(log, response);
try {
final Optional<ExternalMessage> messageOpt = processor.process(response);
messageOpt.map(headerFilter).ifPresent(message -> commandProducer.forward(message, getContext()));
} catch (final DittoRuntimeException e) {
log.info("Got DittoRuntimeException during processing Signal: <{}>", e.getMessage());
} catch (final Exception e) {
log.warning("Got unexpected exception during processing Signal: <{}>", e.getMessage());
}
}
private void startTrace(final Signal<?> command) {
command.getDittoHeaders().getCorrelationId().ifPresent(correlationId ->
traces.put(correlationId, createRoundtripContext(correlationId, command.getType()))
);
}
private void finishTrace(final Signal<?> response) {
if (ThingErrorResponse.class.isAssignableFrom(response.getClass())) {
finishTrace(response, ((ThingErrorResponse) response).getDittoRuntimeException());
} else {
finishTrace(response, null);
}
}
private void finishTrace(final Signal<?> response, @Nullable final Throwable cause) {
response.getDittoHeaders().getCorrelationId().ifPresent(correlationId -> {
try {
finishTrace(correlationId, cause);
} catch (final IllegalArgumentException e) {
log.info("Trace missing for response: '{}'", response);
}
});
}
private void finishTrace(final String correlationId, @Nullable final Throwable cause) {
final TraceContext ctx = traces.getIfPresent(correlationId);
if (Objects.isNull(ctx)) {
throw new IllegalArgumentException("No trace found for correlationId: " + correlationId);
}
traces.invalidate(ctx);
if (Objects.isNull(cause)) {
ctx.finish();
} else {
ctx.finishWithError(cause);
}
}
private static TraceContext createRoundtripContext(final String correlationId, final String type) {
final Option<String> token = Option.apply(correlationId);
final TraceContext ctx = Kamon.tracer().newContext("roundtrip.amqp_" + type, token);
ctx.addMetadata("command", type);
return ctx;
}
}