-
Notifications
You must be signed in to change notification settings - Fork 215
/
EdgeCommandForwarderActor.java
232 lines (204 loc) · 11.5 KB
/
EdgeCommandForwarderActor.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
/*
* Copyright (c) 2022 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.edge.service.dispatching;
import org.eclipse.ditto.base.model.entity.id.WithEntityId;
import org.eclipse.ditto.base.model.signals.Signal;
import org.eclipse.ditto.base.model.signals.commands.Command;
import org.eclipse.ditto.connectivity.model.signals.commands.ConnectivityCommand;
import org.eclipse.ditto.internal.utils.akka.logging.DittoDiagnosticLoggingAdapter;
import org.eclipse.ditto.internal.utils.akka.logging.DittoLoggerFactory;
import org.eclipse.ditto.internal.utils.cacheloaders.config.AskWithRetryConfig;
import org.eclipse.ditto.internal.utils.cacheloaders.config.DefaultAskWithRetryConfig;
import org.eclipse.ditto.internal.utils.cluster.DistPubSubAccess;
import org.eclipse.ditto.internal.utils.config.DefaultScopedConfig;
import org.eclipse.ditto.messages.model.signals.commands.MessageCommand;
import org.eclipse.ditto.policies.model.signals.commands.PolicyCommand;
import org.eclipse.ditto.things.api.ThingsMessagingConstants;
import org.eclipse.ditto.things.api.commands.sudo.SudoRetrieveThings;
import org.eclipse.ditto.things.model.signals.commands.ThingCommand;
import org.eclipse.ditto.things.model.signals.commands.query.RetrieveThings;
import org.eclipse.ditto.things.model.signals.events.ThingEvent;
import org.eclipse.ditto.thingsearch.api.ThingsSearchConstants;
import org.eclipse.ditto.thingsearch.api.commands.sudo.ThingSearchSudoCommand;
import org.eclipse.ditto.thingsearch.model.signals.commands.ThingSearchCommand;
import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.cluster.pubsub.DistributedPubSubMediator;
import akka.japi.pf.ReceiveBuilder;
/**
* Actor which acts as a client used at the Ditto edges (gateway and connectivity) in order to forward messages
* directly to the shard regions of the services the commands are targeted to.
* For "thing search" commands, it sends them via pub/sub to the SearchActor.
*/
public class EdgeCommandForwarderActor extends AbstractActor {
/**
* Name of this actor.
*/
public static final String ACTOR_NAME = "edgeCommandForwarder";
private final DittoDiagnosticLoggingAdapter log = DittoLoggerFactory.getDiagnosticLoggingAdapter(this);
private final ActorRef pubSubMediator;
private final ShardRegions shardRegions;
private final SignalTransformer signalTransformer;
private final AskWithRetryCommandForwarder askWithRetryCommandForwarder;
@SuppressWarnings("unused")
private EdgeCommandForwarderActor(final ActorRef pubSubMediator, final ShardRegions shardRegions,
final SignalTransformer signalTransformer) {
this.pubSubMediator = pubSubMediator;
this.shardRegions = shardRegions;
this.signalTransformer = signalTransformer;
final AskWithRetryConfig askWithRetryConfig = DefaultAskWithRetryConfig.of(
DefaultScopedConfig.dittoScoped(getContext().getSystem().settings().config()),
"ask-with-retry");
final ActorSystem actorSystem = getContext().getSystem();
askWithRetryCommandForwarder = AskWithRetryCommandForwarder.get(actorSystem);
}
/**
* Creates Akka configuration object Props for this actor.
*
* @param pubSubMediator the PubSub mediator Actor.
* @param shardRegions shard regions to use in order to dispatch different entity Signals to.
* @param signalTransformer Used to transform signals before forwarding them to the responsible service.
* @return the Akka configuration Props object.
*/
public static Props props(final ActorRef pubSubMediator, final ShardRegions shardRegions,
final SignalTransformer signalTransformer) {
return Props.create(EdgeCommandForwarderActor.class, pubSubMediator, shardRegions, signalTransformer);
}
@Override
public Receive createReceive() {
final Receive receiveExtension = EdgeCommandForwarderExtension.get(context().system())
.getReceiveExtension(getContext());
final Receive forwardingReceive = ReceiveBuilder.create()
.match(MessageCommand.class, this::forwardToThings)
.match(ThingCommand.class, this::forwardToThings)
.match(ThingEvent.class, Signal::isChannelLive, this::forwardToThings)
.match(RetrieveThings.class, this::forwardToThingsAggregator)
.match(SudoRetrieveThings.class, this::forwardToThingsAggregator)
.match(PolicyCommand.class, this::forwardToPolicies)
.match(ConnectivityCommand.class, this::forwardToConnectivity)
.match(ThingSearchCommand.class, this::forwardToThingSearch)
.match(ThingSearchSudoCommand.class, this::forwardToThingSearch)
.match(Signal.class, this::handleUnknownSignal)
.match(DistributedPubSubMediator.SubscribeAck.class, subscribeAck ->
log.debug("Successfully subscribed to distributed pub/sub on topic '{}'",
subscribeAck.subscribe().topic())
)
.matchAny(m -> log.warning("Got unknown message: {}", m))
.build();
return receiveExtension.orElse(forwardingReceive);
}
private void forwardToThings(final MessageCommand<?, ?> messageCommand) {
final ActorRef sender = getSender();
signalTransformer.apply(messageCommand)
.thenAccept(transformed -> {
final MessageCommand<?, ?> transformedMessageCommand = (MessageCommand<?, ?>) transformed;
log.withCorrelationId(transformedMessageCommand)
.info("Forwarding message command with ID <{}> and type <{}> to 'things' shard region",
transformedMessageCommand.getEntityId(), transformedMessageCommand.getType());
// don't send message commands with retries - we cannot assure idempotency!
shardRegions.things().tell(transformedMessageCommand, sender);
});
}
private void forwardToThings(final Signal<?> thingSignal) {
final ActorRef sender = getSender();
signalTransformer.apply(thingSignal)
.thenAccept(transformed -> {
log.withCorrelationId(transformed)
.info("Forwarding thing signal with ID <{}> and type <{}> to 'things' shard region",
transformed instanceof WithEntityId withEntityId ? withEntityId.getEntityId() : null,
transformed.getType());
if (!Signal.isChannelLive(transformed) &&
!Signal.isChannelSmart(transformed) &&
transformed instanceof Command<?> command &&
isIdempotent(command)) {
askWithRetryCommandForwarder.forwardCommand(command,
shardRegions.things(),
sender);
} else {
shardRegions.things().tell(transformed, sender);
}
});
}
private void forwardToThingsAggregator(final Command<?> command) {
final ActorRef sender = getSender();
final DistributedPubSubMediator.Send pubSubMsg =
DistPubSubAccess.send(ThingsMessagingConstants.THINGS_AGGREGATOR_ACTOR_PATH, command);
askWithRetryCommandForwarder.forwardCommandViaPubSub(command, pubSubMsg, pubSubMediator, sender);
}
private void forwardToPolicies(final PolicyCommand<?> policyCommand) {
final ActorRef sender = getSender();
signalTransformer.apply(policyCommand)
.thenAccept(transformed -> {
final PolicyCommand<?> transformedPolicyCommand = (PolicyCommand<?>) transformed;
log.withCorrelationId(transformedPolicyCommand)
.info("Forwarding policy command with ID <{}> and type <{}> to 'policies' shard region",
transformedPolicyCommand.getEntityId(), transformedPolicyCommand.getType());
if (isIdempotent(transformedPolicyCommand)) {
askWithRetryCommandForwarder.forwardCommand(transformedPolicyCommand,
shardRegions.policies(),
sender);
} else {
shardRegions.policies().tell(transformedPolicyCommand, sender);
}
});
}
private void forwardToConnectivity(final ConnectivityCommand<?> connectivityCommand) {
if (connectivityCommand instanceof WithEntityId withEntityId) {
final ActorRef sender = getSender();
signalTransformer.apply(connectivityCommand)
.thenAccept(transformed -> {
final ConnectivityCommand<?> transformedConnectivityCommand =
(ConnectivityCommand<?>) transformed;
log.withCorrelationId(transformedConnectivityCommand)
.info("Forwarding connectivity command with ID <{}> and type <{}> to 'connections' " +
"shard region", withEntityId.getEntityId(),
transformedConnectivityCommand.getType());
if (isIdempotent(transformedConnectivityCommand)) {
askWithRetryCommandForwarder.forwardCommand(transformedConnectivityCommand,
shardRegions.connections(),
sender);
} else {
shardRegions.connections().tell(transformedConnectivityCommand, sender);
}
});
} else {
log.withCorrelationId(connectivityCommand)
.error("Could not forward ConnectivityCommand not implementing WithEntityId to 'connections' " +
"shard region");
}
}
private void forwardToThingSearch(final Command<?> command) {
// don't use "ask with retry" as the search could take some time and we don't want to stress the search
// by retrying a query several times if it took long
pubSubMediator.tell(
DistPubSubAccess.send(ThingsSearchConstants.SEARCH_ACTOR_PATH, command),
getSender());
}
private static boolean isIdempotent(final Command<?> command) {
return switch (command.getCategory()) {
case QUERY, MERGE, MODIFY, DELETE -> true;
default -> false;
};
}
private void handleUnknownSignal(final Signal<?> signal) {
signalTransformer.apply(signal)
.thenAccept(transformedSignal -> {
final String signalType = transformedSignal.getType();
final DittoDiagnosticLoggingAdapter l = log.withCorrelationId(transformedSignal);
l.error("Received signal <{}> which is not known how to be handled: {}",
signalType, transformedSignal);
});
}
}