-
Notifications
You must be signed in to change notification settings - Fork 215
/
ConnectionsRetrievalActor.java
227 lines (198 loc) · 10.4 KB
/
ConnectionsRetrievalActor.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
/*
* 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.gateway.service.endpoints.actors;
import static org.eclipse.ditto.base.model.common.ConditionChecker.checkNotNull;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.stream.Collectors;
import org.eclipse.ditto.base.model.exceptions.DittoRuntimeException;
import org.eclipse.ditto.base.model.headers.DittoHeaders;
import org.eclipse.ditto.base.model.headers.WithDittoHeaders;
import org.eclipse.ditto.base.model.signals.commands.Command;
import org.eclipse.ditto.base.model.signals.commands.ErrorResponse;
import org.eclipse.ditto.connectivity.model.ConnectionId;
import org.eclipse.ditto.connectivity.model.ConnectivityInternalErrorException;
import org.eclipse.ditto.connectivity.model.signals.commands.ConnectivityCommandResponse;
import org.eclipse.ditto.connectivity.model.signals.commands.ConnectivityErrorResponse;
import org.eclipse.ditto.connectivity.model.signals.commands.query.RetrieveAllConnectionIdsResponse;
import org.eclipse.ditto.connectivity.model.signals.commands.query.RetrieveConnection;
import org.eclipse.ditto.connectivity.model.signals.commands.query.RetrieveConnectionResponse;
import org.eclipse.ditto.connectivity.model.signals.commands.query.RetrieveConnections;
import org.eclipse.ditto.connectivity.model.signals.commands.query.RetrieveConnectionsResponse;
import org.eclipse.ditto.internal.utils.akka.logging.DittoLoggerFactory;
import org.eclipse.ditto.internal.utils.akka.logging.ThreadSafeDittoLogger;
import org.eclipse.ditto.json.JsonArray;
import org.eclipse.ditto.json.JsonCollectors;
import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.japi.pf.ReceiveBuilder;
import akka.pattern.Patterns;
/**
* Actor for retrieving multiple connections.
*/
public class ConnectionsRetrievalActor extends AbstractActor {
private static final ThreadSafeDittoLogger LOGGER =
DittoLoggerFactory.getThreadSafeLogger(ConnectionsRetrievalActor.class);
public static final String ACTOR_NAME = "connectionsRetrieval";
private static final String LOG_SEND_COMMAND = "Sending command <{}> to org.eclipse.ditto.connectivity.service.";
private final ActorRef edgeCommandForwarder;
private final ActorRef sender;
private final RetrieveConnections initialCommand;
@SuppressWarnings("unused")
private ConnectionsRetrievalActor(final RetrieveConnections initialCommand, final ActorRef edgeCommandForwarder,
final ActorRef sender) {
this.edgeCommandForwarder = edgeCommandForwarder;
this.initialCommand = initialCommand;
this.sender = sender;
}
/**
* Creates props for {@code ConnectionsRetrievalActor}.
*
* @param initialCommand the initial command.
* @param edgeCommandForwarder the edge command forwarder.
* @param sender the initial sender.
* @return the props.
*/
public static Props props(final RetrieveConnections initialCommand, final ActorRef edgeCommandForwarder,
final ActorRef sender) {
return Props.create(ConnectionsRetrievalActor.class, initialCommand, edgeCommandForwarder, sender);
}
@Override
public Receive createReceive() {
return ReceiveBuilder.create()
.match(RetrieveAllConnectionIdsResponse.class, this::retrieveConnectionsResponse)
.matchAny(msg -> LOGGER.warn("Unknown message: <{}>", msg))
.build();
}
private void retrieveConnectionsResponse(final RetrieveAllConnectionIdsResponse msg) {
if (initialCommand.getIdsOnly()) {
RetrieveConnectionsResponse response = RetrieveConnectionsResponse
.of(JsonArray.of(msg.getAllConnectionIds()), initialCommand.getDittoHeaders());
sender.tell(response, getSelf());
stop();
} else {
retrieveConnections(msg.getAllConnectionIds()
.stream()
// .limit(commandConfig.connectionsRetrieveLimit()) //TODO limit
.map(ConnectionId::of).collect(Collectors.toList()),
initialCommand.getDittoHeaders())
.thenAccept(retrieveConnectionsResponse -> {
sender.tell(retrieveConnectionsResponse, getSelf());
stop();
})
.exceptionally(t -> {
ConnectivityInternalErrorException exception =
ConnectivityInternalErrorException.newBuilder()
.dittoHeaders(initialCommand.getDittoHeaders())
.cause(t)
.build();
ConnectivityErrorResponse response =
ConnectivityErrorResponse.of(exception, initialCommand.getDittoHeaders());
sender.tell(response, getSelf());
stop();
return null;
});
}
}
private CompletionStage<RetrieveConnectionsResponse> retrieveConnections(
final Collection<ConnectionId> connectionIds, final DittoHeaders dittoHeaders) {
checkNotNull(connectionIds, "connectionIds");
checkNotNull(dittoHeaders, "dittoHeaders");
final List<CompletableFuture<RetrieveConnectionResponse>> completableFutures = connectionIds.parallelStream()
.map(connectionId -> retrieveConnection(RetrieveConnection.of(connectionId, dittoHeaders)))
.map(CompletionStage::toCompletableFuture)
.toList();
final List<ConnectionId> connectionIdList = new ArrayList<>(connectionIds);
// this comparator is used to support returning the connections in the same order they were requested
final Comparator<RetrieveConnectionResponse> sorter = (r1, r2) -> {
final ConnectionId r1ConnectionId = r1.getEntityId();
final ConnectionId r2ConnectionId = r2.getEntityId();
return Integer.compare(connectionIdList.indexOf(r1ConnectionId), connectionIdList.indexOf(r2ConnectionId));
};
return CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0]))
.thenApply(ignored -> completableFutures.stream()
.map(CompletableFuture::join)
.toList())
.thenApply(retrieveConnectionResponses -> {
final JsonArray connections = retrieveConnectionResponses.stream()
.sorted(sorter)
.map(RetrieveConnectionResponse::getEntity)
.collect(JsonCollectors.valuesToArray());
return RetrieveConnectionsResponse.of(connections, dittoHeaders);
});
}
private CompletionStage<RetrieveConnectionResponse> retrieveConnection(
final RetrieveConnection retrieveConnection) {
return askConnectivityCommandActor(retrieveConnection);
}
private <T extends ConnectivityCommandResponse<?>> CompletionStage<T> askConnectivityCommandActor(
final Command<?> command) {
LOGGER.withCorrelationId(command).debug(LOG_SEND_COMMAND, command);
final var commandWithCorrelationId = ensureCommandHasCorrelationId(command);
Duration askTimeout = initialCommand.getTimeout();
return Patterns.ask(edgeCommandForwarder, commandWithCorrelationId, askTimeout)
.thenApply(response -> {
LOGGER.withCorrelationId(command)
.debug("Received response <{}> from com.bosch.iot.things.connectivity.service.", response);
throwCauseIfErrorResponse(response);
throwCauseIfDittoRuntimeException(response);
final T mappedResponse = mapToType(response, (Class<T>) RetrieveConnectionResponse.class, command);
LOGGER.withCorrelationId(command)
.info("Received response of type <{}> from com.bosch.iot.things.connectivity.service.",
mappedResponse.getType());
return mappedResponse;
});
}
private static Command<?> ensureCommandHasCorrelationId(final Command<?> command) {
final DittoHeaders dittoHeaders = command.getDittoHeaders();
final Optional<String> correlationIdOptional = dittoHeaders.getCorrelationId();
if (correlationIdOptional.isPresent()) {
return command;
}
return command.setDittoHeaders(dittoHeaders.toBuilder().randomCorrelationId().build());
}
private static void throwCauseIfErrorResponse(final Object response) {
if (response instanceof ErrorResponse<?> errorResponse) {
throw (errorResponse).getDittoRuntimeException();
}
}
private static void throwCauseIfDittoRuntimeException(final Object response) {
if (response instanceof DittoRuntimeException dittoRuntimeException) {
throw dittoRuntimeException;
}
}
private static <T> T mapToType(final Object object, final Class<T> targetClass,
final WithDittoHeaders withDittoHeaders) {
final Class<?> actualClass = object.getClass();
if (targetClass.isAssignableFrom(actualClass)) {
return targetClass.cast(object);
}
final String message =
String.format("Expected <%s> response but got <%s>!", targetClass.getSimpleName(), actualClass);
final IllegalArgumentException exception = new IllegalArgumentException(message);
throw ConnectivityInternalErrorException.newBuilder()
.dittoHeaders(withDittoHeaders.getDittoHeaders())
.cause(exception)
.build();
}
private void stop() {
getContext().stop(getSelf());
}
}