-
Notifications
You must be signed in to change notification settings - Fork 215
/
StreamingActor.java
executable file
·207 lines (181 loc) · 8.83 KB
/
StreamingActor.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
/*
* 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.gateway.service.streaming.actors;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.stream.StreamSupport;
import org.eclipse.ditto.base.model.headers.translator.HeaderTranslator;
import org.eclipse.ditto.gateway.service.security.authentication.jwt.JwtAuthenticationResultProvider;
import org.eclipse.ditto.gateway.service.security.authentication.jwt.JwtValidator;
import org.eclipse.ditto.gateway.service.streaming.Connect;
import org.eclipse.ditto.gateway.service.util.config.streaming.DefaultStreamingConfig;
import org.eclipse.ditto.gateway.service.util.config.streaming.StreamingConfig;
import org.eclipse.ditto.internal.utils.akka.actors.ModifyConfigBehavior;
import org.eclipse.ditto.internal.utils.akka.actors.RetrieveConfigBehavior;
import org.eclipse.ditto.internal.utils.akka.logging.DittoDiagnosticLoggingAdapter;
import org.eclipse.ditto.internal.utils.akka.logging.DittoLoggerFactory;
import org.eclipse.ditto.internal.utils.metrics.DittoMetrics;
import org.eclipse.ditto.internal.utils.metrics.instruments.gauge.Gauge;
import org.eclipse.ditto.internal.utils.pubsub.DittoProtocolSub;
import org.eclipse.ditto.internal.utils.search.SubscriptionManager;
import com.typesafe.config.Config;
import akka.actor.AbstractActorWithTimers;
import akka.actor.ActorRef;
import akka.actor.ActorSelection;
import akka.actor.OneForOneStrategy;
import akka.actor.Props;
import akka.actor.SupervisorStrategy;
import akka.japi.pf.DeciderBuilder;
import akka.japi.pf.ReceiveBuilder;
import akka.stream.Materializer;
/**
* Parent Actor for {@link StreamingSessionActor}s delegating most of the messages to a specific session.
* Manages WebSocket configuration.
*/
public final class StreamingActor extends AbstractActorWithTimers implements RetrieveConfigBehavior,
ModifyConfigBehavior {
/**
* The name of this Actor.
*/
public static final String ACTOR_NAME = "streaming";
private final DittoProtocolSub dittoProtocolSub;
private final ActorRef commandRouter;
private final Gauge streamingSessionsCounter;
private final JwtValidator jwtValidator;
private final JwtAuthenticationResultProvider jwtAuthenticationResultProvider;
private final Props subscriptionManagerProps;
private final DittoDiagnosticLoggingAdapter logger = DittoLoggerFactory.getDiagnosticLoggingAdapter(this);
private final HeaderTranslator headerTranslator;
private int childCounter = -1;
private StreamingConfig streamingConfig;
private final SupervisorStrategy strategy = new OneForOneStrategy(true, DeciderBuilder
.match(Throwable.class, e -> {
logger.error(e, "Escalating above actor!");
return (SupervisorStrategy.Directive) SupervisorStrategy.escalate();
}).matchAny(e -> {
logger.error("Unknown message:'{}'! Escalating above actor!", e);
return (SupervisorStrategy.Directive) SupervisorStrategy.escalate();
}).build());
@SuppressWarnings("unused")
private StreamingActor(final DittoProtocolSub dittoProtocolSub,
final ActorRef commandRouter,
final JwtValidator jwtValidator,
final JwtAuthenticationResultProvider jwtAuthenticationResultProvider,
final StreamingConfig streamingConfig,
final HeaderTranslator headerTranslator,
final ActorRef pubSubMediator,
final ActorRef conciergeForwarder) {
this.dittoProtocolSub = dittoProtocolSub;
this.commandRouter = commandRouter;
this.jwtValidator = jwtValidator;
this.jwtAuthenticationResultProvider = jwtAuthenticationResultProvider;
this.streamingConfig = streamingConfig;
this.headerTranslator = headerTranslator;
streamingSessionsCounter = DittoMetrics.gauge("streaming_sessions_count");
final ActorSelection conciergeForwarderSelection = ActorSelection.apply(conciergeForwarder, "");
subscriptionManagerProps =
SubscriptionManager.props(streamingConfig.getSearchIdleTimeout(), pubSubMediator,
conciergeForwarderSelection, Materializer.createMaterializer(getContext()));
scheduleScrapeStreamSessionsCounter();
}
/**
* Creates Akka configuration object Props for this StreamingActor.
*
* @param dittoProtocolSub the Ditto protocol sub access.
* @param commandRouter the command router used to send signals into the cluster.
* @param streamingConfig the streaming config.
* @param headerTranslator translates headers from external sources or to external sources.
* @return the Akka configuration Props object.
*/
public static Props props(final DittoProtocolSub dittoProtocolSub,
final ActorRef commandRouter,
final JwtValidator jwtValidator,
final JwtAuthenticationResultProvider jwtAuthenticationResultProvider,
final StreamingConfig streamingConfig,
final HeaderTranslator headerTranslator,
final ActorRef pubSubMediator,
final ActorRef conciergeForwarder) {
return Props.create(StreamingActor.class, dittoProtocolSub, commandRouter, jwtValidator,
jwtAuthenticationResultProvider, streamingConfig, headerTranslator, pubSubMediator, conciergeForwarder);
}
@Override
public SupervisorStrategy supervisorStrategy() {
return strategy;
}
@Override
public Receive createReceive() {
return retrieveConfigBehavior()
.orElse(modifyConfigBehavior())
.orElse(createConnectAndMetricsBehavior())
.orElse(ReceiveBuilder.create()
.matchAny(any -> logger.warning("Got unknown message: '{}'", any))
.build());
}
private Receive createConnectAndMetricsBehavior() {
return ReceiveBuilder.create()
.match(Connect.class, connect -> {
final String sessionActorName = getUniqueChildActorName(connect.getConnectionCorrelationId());
final ActorRef streamingSessionActor = getContext().actorOf(
StreamingSessionActor.props(connect, dittoProtocolSub,
commandRouter, streamingConfig.getAcknowledgementConfig(), headerTranslator,
subscriptionManagerProps, jwtValidator, jwtAuthenticationResultProvider),
sessionActorName);
getSender().tell(streamingSessionActor, ActorRef.noSender());
})
.matchEquals(Control.RETRIEVE_WEBSOCKET_CONFIG, this::replyWebSocketConfig)
.matchEquals(Control.SCRAPE_STREAM_COUNTER, this::updateStreamingSessionsCounter)
.build();
}
@Override
public Config getConfig() {
return streamingConfig.render().getConfig(StreamingConfig.CONFIG_PATH);
}
@Override
public Config setConfig(final Config config) {
streamingConfig = DefaultStreamingConfig.of(
config.atKey(StreamingConfig.CONFIG_PATH).withFallback(streamingConfig.render()));
// reschedule scrapes: interval may have changed.
scheduleScrapeStreamSessionsCounter();
return streamingConfig.render();
}
private String getUniqueChildActorName(final String suffix) {
final int counter = ++childCounter;
return String.format("%x-%s", counter, URLEncoder.encode(suffix, StandardCharsets.UTF_8));
}
private void scheduleScrapeStreamSessionsCounter() {
getTimers().startPeriodicTimer(Control.SCRAPE_STREAM_COUNTER, Control.SCRAPE_STREAM_COUNTER,
streamingConfig.getSessionCounterScrapeInterval());
}
private void replyWebSocketConfig(final Control trigger) {
getSender().tell(streamingConfig.getWebsocketConfig(), getSelf());
}
private void updateStreamingSessionsCounter(final Control trigger) {
if (getContext() != null) {
streamingSessionsCounter.set(
StreamSupport.stream(getContext().getChildren().spliterator(), false).count());
}
}
/**
* Control messages to send in the same actor system.
*/
public enum Control {
/**
* Tell streaming actor to set the stream counter to its current number of child actors.
*/
SCRAPE_STREAM_COUNTER,
/**
* Request the current WebSocket config.
*/
RETRIEVE_WEBSOCKET_CONFIG
}
}