-
Notifications
You must be signed in to change notification settings - Fork 215
/
Subscriber.java
217 lines (192 loc) · 9.67 KB
/
Subscriber.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
/*
* Copyright (c) 2019 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.internal.utils.pubsub.actors;
import java.time.Duration;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.eclipse.ditto.base.model.acks.AcknowledgementLabel;
import org.eclipse.ditto.base.model.headers.DittoHeaderDefinition;
import org.eclipse.ditto.base.model.signals.SignalWithEntityId;
import org.eclipse.ditto.base.model.signals.acks.Acknowledgements;
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.counter.Counter;
import org.eclipse.ditto.internal.utils.pubsub.DistributedAcks;
import org.eclipse.ditto.internal.utils.pubsub.api.LocalAcksChanged;
import org.eclipse.ditto.internal.utils.pubsub.api.PublishSignal;
import org.eclipse.ditto.internal.utils.pubsub.config.PubSubConfig;
import org.eclipse.ditto.internal.utils.pubsub.ddata.SubscriptionsReader;
import org.eclipse.ditto.internal.utils.pubsub.ddata.ack.GroupedSnapshot;
import org.eclipse.ditto.internal.utils.pubsub.extractors.AckExtractor;
import org.eclipse.ditto.internal.utils.pubsub.extractors.PubSubTopicExtractor;
import akka.actor.AbstractActorWithTimers;
import akka.actor.ActorRef;
import akka.actor.ActorSelection;
import akka.actor.Props;
import akka.actor.Terminated;
import akka.cluster.Cluster;
import akka.japi.Pair;
import akka.japi.pf.ReceiveBuilder;
/**
* Actor that distributes messages to local subscribers
*
* @param <T> type of messages.
*/
public final class Subscriber<T extends SignalWithEntityId<?>> extends AbstractActorWithTimers {
/**
* Prefix of this actor's name.
*/
public static final String ACTOR_NAME_PREFIX = "subscriber";
private final Class<T> messageClass;
private final PubSubTopicExtractor<T> topicExtractor;
private final AckExtractor<T> ackExtractor;
private final DistributedAcks distributedAcks;
private final Counter truePositiveCounter = DittoMetrics.counter("pubsub-true-positive");
private final Counter falsePositiveCounter = DittoMetrics.counter("pubsub-false-positive");
private final Counter receivedMessagesCounter = DittoMetrics.counter("pubsub-received-messages");
private final DittoDiagnosticLoggingAdapter logger = DittoLoggerFactory.getDiagnosticLoggingAdapter(this);
private PublisherIndex<String> publisherIndex = PublisherIndex.empty();
private GroupedSnapshot<ActorRef, String> declaredAcks = GroupedSnapshot.empty();
@Nullable private ActorRef ackUpdater = null;
@Nullable private ActorRef subUpdater = null;
@SuppressWarnings("unused")
private Subscriber(final Class<T> messageClass,
final PubSubTopicExtractor<T> topicExtractor,
final AckExtractor<T> ackExtractor,
final DistributedAcks distributedAcks) {
this.messageClass = messageClass;
this.topicExtractor = topicExtractor;
this.ackExtractor = ackExtractor;
this.distributedAcks = distributedAcks;
distributedAcks.receiveLocalDeclaredAcks(getSelf());
}
/**
* Create Props object for this actor.
*
* @param <T> type of messages.
* @param messageClass class of message distributed by the pub-sub.
* @param topicExtractor extractor of topics from messages.
* @param ackExtractor extractor of acknowledgement-related information from a message.
* @param distributedAcks access to the distributed data of declared acknowledgement labels.
* @return the Props object.
*/
public static <T> Props props(final Class<T> messageClass, final PubSubTopicExtractor<T> topicExtractor,
final AckExtractor<T> ackExtractor, final DistributedAcks distributedAcks) {
return Props.create(Subscriber.class, messageClass, topicExtractor, ackExtractor, distributedAcks);
}
@Override
public Receive createReceive() {
return ReceiveBuilder.create()
.match(PublishSignal.class, this::broadcastToLocalSubscribers)
.match(SubscriptionsReader.class, this::updateLocalSubscriptions)
.match(LocalAcksChanged.class, this::updateLocalAcks)
.match(Terminated.class, this::terminated)
.matchEquals(ActorEvent.ACK_UPDATER_NOT_AVAILABLE, this::scheduleReceiveLocalDeclaredAcks)
.matchEquals(Control.RECEIVE_LOCAL_DECLARED_ACKS, this::receiveLocalDeclaredAcks)
.build();
}
private void scheduleReceiveLocalDeclaredAcks(final ActorEvent ackUpdaterNotAvailable) {
if (!timers().isTimerActive(Control.RECEIVE_LOCAL_DECLARED_ACKS)) {
timers().startSingleTimer(Control.RECEIVE_LOCAL_DECLARED_ACKS, Control.RECEIVE_LOCAL_DECLARED_ACKS,
getRestartDelayWithBuffer());
}
}
private void receiveLocalDeclaredAcks(final Control receiveLocalDeclaredAcks) {
distributedAcks.receiveLocalDeclaredAcks(getSelf());
}
private void terminated(final Terminated terminated) {
if (Cluster.get(getContext().getSystem()).isTerminated()) {
logger.info("This cluster instance was terminated - no action required ..");
} else if (terminated.getActor().equals(ackUpdater)) {
logger.error("Notifying SubUpdater <{}> of AckUpdater termination: <{}>", subUpdater, terminated);
if (subUpdater != null) {
subUpdater.tell(ActorEvent.PUBSUB_TERMINATED, getSelf());
}
scheduleReceiveLocalDeclaredAcks(ActorEvent.ACK_UPDATER_NOT_AVAILABLE);
}
}
private void broadcastToLocalSubscribers(final PublishSignal command) {
receivedMessagesCounter.increment();
final T message = messageClass.cast(command.getSignal());
final Collection<String> topics = topicExtractor.getTopics(message);
final Set<ActorRef> localSubscribers =
publisherIndex.assignGroupsToSubscribers(message, topics, command.getGroups())
.stream()
.map(Pair::first)
.collect(Collectors.toSet());
if (localSubscribers.isEmpty()) {
falsePositiveCounter.increment();
} else {
truePositiveCounter.increment();
for (final ActorRef localSubscriber : localSubscribers) {
localSubscriber.tell(message, getSender());
}
}
replyWeakAck(message, command, localSubscribers);
}
private void replyWeakAck(final T message, final PublishSignal command, final Set<ActorRef> localSubscribers) {
final Set<String> responsibleAcks = declaredAcks.getValues(command.getGroups().keySet());
final Collection<AcknowledgementLabel> declaredCustomAcks =
ackExtractor.getDeclaredCustomAcksRequestedBy(message, responsibleAcks::contains);
final Collection<AcknowledgementLabel> declaredCustomAcksWithoutSubscribers = declaredCustomAcks.stream()
.filter(label -> disjoint(localSubscribers, declaredAcks.getKeys(label.toString())))
.toList();
if (!declaredCustomAcksWithoutSubscribers.isEmpty()) {
final Acknowledgements acknowledgements =
ackExtractor.toWeakAcknowledgements(message, declaredCustomAcksWithoutSubscribers);
final String ackregatorAddress = acknowledgements.getDittoHeaders()
.get(DittoHeaderDefinition.DITTO_ACKREGATOR_ADDRESS.getKey());
if (null != ackregatorAddress) {
final ActorSelection acknowledgementRequester = getContext().actorSelection(ackregatorAddress);
acknowledgementRequester.tell(acknowledgements, ActorRef.noSender());
} else {
logger.withCorrelationId(acknowledgements)
.error("Received Acknowledgements did not contain header of Ackgregator address: {}",
acknowledgements.getDittoHeaders());
}
}
}
private void updateLocalSubscriptions(final SubscriptionsReader subscriptionsReader) {
this.publisherIndex = PublisherIndex.fromSubscriptionsReader(subscriptionsReader);
// no need to watch the subUpdater -- the supervisor takes care of restarting on termination.
subUpdater = getSender();
}
private void updateLocalAcks(final LocalAcksChanged localAcksChanged) {
declaredAcks = localAcksChanged.getSnapshot();
ackUpdater = getSender();
getContext().watch(ackUpdater);
}
private Duration getRestartDelayWithBuffer() {
final long bufferFactor = 4;
final Duration configuredRestartDelay = PubSubConfig.of(getContext().getSystem()).getRestartDelay();
return configuredRestartDelay.plus(configuredRestartDelay.dividedBy(bufferFactor));
}
private static <T> boolean disjoint(final Set<T> set1, final Set<T> set2) {
final Set<T> smaller;
final Set<T> bigger;
if (set1.size() < set2.size()) {
smaller = set1;
bigger = set2;
} else {
smaller = set2;
bigger = set1;
}
return smaller.stream().noneMatch(bigger::contains);
}
private enum Control {
RECEIVE_LOCAL_DECLARED_ACKS
}
}