/
CommandProcessorActor.java
261 lines (224 loc) · 10.7 KB
/
CommandProcessorActor.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
/*
* 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.amqpbridge.messaging;
import static org.eclipse.ditto.services.models.amqpbridge.AmqpBridgeMessagingConstants.GATEWAY_PROXY_ACTOR_PATH;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.eclipse.ditto.json.JsonFactory;
import org.eclipse.ditto.model.amqpbridge.ExternalMessage;
import org.eclipse.ditto.model.amqpbridge.MappingContext;
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.services.utils.akka.LogUtil;
import org.eclipse.ditto.signals.commands.base.Command;
import org.eclipse.ditto.signals.commands.base.CommandResponse;
import org.eclipse.ditto.signals.commands.things.ThingErrorResponse;
import org.eclipse.ditto.signals.events.base.Event;
import org.eclipse.ditto.signals.events.things.ThingEvent;
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.DynamicAccess;
import akka.actor.ExtendedActorSystem;
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 Command}s and dispatches them via {@link DistributedPubSubMediator} to a
* consumer actor.
*/
public final class CommandProcessorActor extends AbstractActor {
/**
* The name of this Actor in the ActorSystem.
*/
public static final String ACTOR_NAME_PREFIX = "amqpCommandProcessor-";
private final DiagnosticLoggingAdapter log = LogUtil.obtain(this);
private final ActorRef pubSubMediator;
private final ActorRef commandProducer;
private final AuthorizationSubject authorizationSubject;
private final Cache<String, TraceContext> traces;
private final CommandProcessor processor;
private CommandProcessorActor(final ActorRef pubSubMediator, final ActorRef commandProducer,
final AuthorizationSubject authorizationSubject,
final List<MappingContext> mappingContexts) {
this.pubSubMediator = pubSubMediator;
this.commandProducer = commandProducer;
this.authorizationSubject = authorizationSubject;
traces = CacheBuilder.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.removalListener((RemovalListener<String, TraceContext>) notification
-> log.debug("Trace for {} removed.", notification.getKey()))
.build();
this.processor = CommandProcessor.of(mappingContexts, getDynamicAccess(), log);
log.info("Configured for processing messages with the following content types: {}",
processor.getSupportedContentTypes());
final Optional<String> defaultContentType = processor.getDefaultContentType();
if (defaultContentType.isPresent()) {
log.info("Interpreting messages with missing content type as '{}'", defaultContentType.get());
} else {
log.warning("No default config type configured!");
}
}
/**
* Creates Akka configuration object for this actor.
*
* @param pubSubMediator the akka pubsub mediator actor.
* @param commandProducer actor that handles outgoing messages
* @param authorizationSubject the authorized subject that are set in command headers.
* @param mappingContexts the mapping contexts to apply for different content-types.
* @return the Akka configuration Props object
*/
static Props props(final ActorRef pubSubMediator, final ActorRef commandProducer,
final AuthorizationSubject authorizationSubject,
final List<MappingContext> mappingContexts) {
return Props.create(CommandProcessorActor.class, new Creator<CommandProcessorActor>() {
private static final long serialVersionUID = 1L;
@Override
public CommandProcessorActor create() {
return new CommandProcessorActor(pubSubMediator, commandProducer, authorizationSubject,
mappingContexts);
}
});
}
@Override
public Receive createReceive() {
return ReceiveBuilder.create()
.match(ExternalMessage.class, this::handle)
.match(CommandResponse.class, this::handleCommandResponse)
.match(ThingEvent.class, this::handleThingEvent)
.match(DittoRuntimeException.class, this::handleDittoRuntimeException)
.match(Status.Failure.class, f -> log.error(f.cause(), "Got an unexpected failure."))
.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 =
JsonFactory.newArrayBuilder().add(authorizationSubject.getId()).build().toString();
final ExternalMessage messageWithAuthSubject =
m.withHeader(DittoHeaderDefinition.AUTHORIZATION_SUBJECTS.getKey(), authSubjectsArray);
try {
final Command<?> command = processor.process(messageWithAuthSubject);
startTrace(command);
log.info("Publishing '{}' to '{}'", command.getType(), GATEWAY_PROXY_ACTOR_PATH);
pubSubMediator.tell(new DistributedPubSubMediator.Send(GATEWAY_PROXY_ACTOR_PATH, command, 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);
logDittoRuntimeException(exception);
handleCommandResponse(errorResponse);
}
private void logDittoRuntimeException(final DittoRuntimeException exception) {
LogUtil.enhanceLogWithCorrelationId(log, exception);
log.info( "Got DittoRuntimeException '{}' when command via AMQP was processed: {}",
exception.getErrorCode(), exception.getMessage());
}
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);
}
try {
final ExternalMessage message = processor.process(response);
commandProducer.forward(message, context());
} catch (final DittoRuntimeException e) {
log.info("Got DittoRuntimeException during processing CommandResponse: <{}>", e.getMessage());
} catch (final Exception e) {
log.warning("Got unexpected exception during processing CommandResponse: <{}>", e.getMessage());
}
}
private void handleThingEvent(final Event<?> event) {
LogUtil.enhanceLogWithCorrelationId(log, event);
try {
final ExternalMessage message = processor.process(event);
commandProducer.forward(message, context());
} catch (final DittoRuntimeException e) {
log.info("Got DittoRuntimeException during processing Event: <{}>", e.getMessage());
} catch (final Exception e) {
log.warning("Got unexpected exception during processing Event: <{}>", e.getMessage());
}
}
/**
* Shortcut to the dynamic access object
*
* @return the dynamic access object
*/
private DynamicAccess getDynamicAccess() {
return ((ExtendedActorSystem) getContext().getSystem()).dynamicAccess();
}
private void startTrace(final Command<?> command) {
command.getDittoHeaders().getCorrelationId().ifPresent(correlationId ->
traces.put(correlationId, createRoundtripContext(correlationId, command.getType()))
);
}
private void finishTrace(final CommandResponse<?> response) {
if (ThingErrorResponse.class.isAssignableFrom(response.getClass())) {
finishTrace(response, ((ThingErrorResponse) response).getDittoRuntimeException());
} else {
finishTrace(response, null);
}
}
private void finishTrace(final CommandResponse<?> 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;
}
}