/
Publisher.java
248 lines (211 loc) · 10.1 KB
/
Publisher.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
/*
* 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.services.utils.pubsub.actors;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.eclipse.ditto.json.JsonValue;
import org.eclipse.ditto.model.base.acks.AcknowledgementLabel;
import org.eclipse.ditto.model.base.acks.AcknowledgementRequest;
import org.eclipse.ditto.model.base.acks.DittoAcknowledgementLabel;
import org.eclipse.ditto.model.base.entity.id.EntityIdWithType;
import org.eclipse.ditto.model.base.headers.DittoHeaders;
import org.eclipse.ditto.services.utils.akka.logging.DittoLoggerFactory;
import org.eclipse.ditto.services.utils.akka.logging.ThreadSafeDittoLoggingAdapter;
import org.eclipse.ditto.services.utils.metrics.DittoMetrics;
import org.eclipse.ditto.services.utils.metrics.instruments.counter.Counter;
import org.eclipse.ditto.services.utils.pubsub.DistributedAcks;
import org.eclipse.ditto.services.utils.pubsub.ddata.DDataReader;
import org.eclipse.ditto.signals.acks.base.Acknowledgement;
import org.eclipse.ditto.signals.acks.base.Acknowledgements;
import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.Address;
import akka.actor.Props;
import akka.cluster.ddata.Replicator;
import akka.japi.pf.ReceiveBuilder;
import scala.collection.immutable.Set;
import scala.collection.immutable.Set$;
import scala.jdk.javaapi.CollectionConverters;
/**
* Publishes messages according to topic Bloom filters.
*
* @param <T> representation of topics in the distributed data.
*/
public final class Publisher<T> extends AbstractActor {
/**
* Prefix of this actor's name.
*/
public static final String ACTOR_NAME_PREFIX = "publisher";
private static final List<AcknowledgementLabel> BUILT_IN_LABELS = List.of(DittoAcknowledgementLabel.values());
private static final Set<String> EMPTY_SET = Set$.MODULE$.empty();
private final ThreadSafeDittoLoggingAdapter log = DittoLoggerFactory.getThreadSafeDittoLoggingAdapter(this);
private final DDataReader<ActorRef, T> ddataReader;
private final Counter messageCounter = DittoMetrics.counter("pubsub-published-messages");
private final Counter topicCounter = DittoMetrics.counter("pubsub-published-topics");
private Map<ActorRef, Set<T>> topicSubscribers = Map.of();
private Map<Address, Set<String>> declaredAcks = Map.of();
private java.util.Set<String> allDeclaredAcks = java.util.Set.of();
@SuppressWarnings("unused")
private Publisher(final DDataReader<ActorRef, T> ddataReader, final DistributedAcks distributedAcks) {
this.ddataReader = ddataReader;
ddataReader.receiveChanges(getSelf());
distributedAcks.receiveDistributedDeclaredAcks(getSelf());
}
/**
* Create Props for this actor.
*
* @param <T> representation of topics in the distributed data.
* @param ddataReader reader of remote subscriptions.
* @param distributedAcks access to the declared ack labels ddata.
* @return a Props object.
*/
public static <T> Props props(final DDataReader<ActorRef, T> ddataReader, final DistributedAcks distributedAcks) {
return Props.create(Publisher.class, ddataReader, distributedAcks);
}
/**
* Create a publish message for the publisher.
*
* @param topics the topics to publish at.
* @param message the message to publish.
* @return a publish message.
*/
public static Request publish(final Collection<String> topics, final Object message) {
return new Publish(topics, message);
}
/**
* Create a publish message with requested acknowledgements.
*
* @param topics the topics to publish at.
* @param message the message to publish.
* @param ackRequests acknowledgement requests of the message.
* @param entityId entity ID of the message.
* @param dittoHeaders the Ditto headers of any weak acknowledgements to send back.
* @param sender the sender of the message and the receiver of acknowledgements.
* @return the request.
*/
public static Request publishWithAck(final Collection<String> topics,
final Object message,
final java.util.Set<AcknowledgementRequest> ackRequests,
final EntityIdWithType entityId,
final DittoHeaders dittoHeaders,
final ActorRef sender) {
return new PublishWithAck(topics, message, ackRequests, entityId, dittoHeaders, sender);
}
@Override
public Receive createReceive() {
return ReceiveBuilder.create()
.match(Publish.class, this::publish)
.match(PublishWithAck.class, this::publishWithAck)
.match(AcksUpdater.DDataChanged.class, this::declaredAcksChanged)
.match(Replicator.Changed.class, this::topicSubscribersChanged)
.matchAny(this::logUnhandled)
.build();
}
private void publish(final Publish publish) {
doPublish(publish.topics, publish.message);
}
private void publishWithAck(final PublishWithAck publishWithAck) {
final Collection<ActorRef> subscribers = doPublish(publishWithAck.topics, publishWithAck.message);
final java.util.Set<String> subscriberDeclaredAcks = subscribers.stream()
.map(subscriber -> declaredAcks.getOrDefault(subscriber.path().address(), EMPTY_SET))
.flatMap(set -> CollectionConverters.asJava(set).stream())
.collect(Collectors.toSet());
final Collection<AcknowledgementLabel> requestedCustomAcks =
getRequestedAndDeclaredCustomAcks(publishWithAck.ackRequests, allDeclaredAcks);
final List<AcknowledgementLabel> labelsWithoutAuthorizedSubscribers = requestedCustomAcks.stream()
.filter(label -> !subscriberDeclaredAcks.contains(label.toString()))
.collect(Collectors.toList());
if (!labelsWithoutAuthorizedSubscribers.isEmpty()) {
publishWithAck.sender.tell(publishWithAck.toAcks(labelsWithoutAuthorizedSubscribers), ActorRef.noSender());
}
}
private Collection<ActorRef> doPublish(final Collection<String> topics, final Object message) {
messageCounter.increment();
topicCounter.increment(topics.size());
final List<T> hashes = topics.stream().map(ddataReader::approximate).collect(Collectors.toList());
final ActorRef sender = getSender();
final Collection<ActorRef> subscribers = ddataReader.getSubscribers(topicSubscribers, hashes);
subscribers.forEach(subscriber -> subscriber.tell(message, sender));
return subscribers;
}
private void declaredAcksChanged(final AcksUpdater.DDataChanged ddataChanged) {
declaredAcks = ddataChanged.getMultiMap();
allDeclaredAcks = declaredAcks.values().stream()
.flatMap(set -> CollectionConverters.asJava(set).stream())
.collect(Collectors.toSet());
}
private void topicSubscribersChanged(final Replicator.Changed<?> event) {
topicSubscribers = CollectionConverters.asJava(event.get(ddataReader.getKey()).entries());
}
private void logUnhandled(final Object message) {
log.warning("Unhandled: <{}>", message);
}
private static Collection<AcknowledgementLabel> getRequestedAndDeclaredCustomAcks(
final java.util.Set<AcknowledgementRequest> requestedAcks,
final java.util.Set<String> allDeclaredAcks) {
return requestedAcks.stream()
.map(AcknowledgementRequest::getLabel)
.filter(label -> !BUILT_IN_LABELS.contains(label) && allDeclaredAcks.contains(label.toString()))
.collect(Collectors.toList());
}
/**
* Requests to a publisher actor.
*/
public interface Request {}
/**
* Request for the publisher to publish a message.
* Only the message is sent across the cluster.
*/
private static final class Publish implements Request {
private final Collection<String> topics;
private final Object message;
private Publish(final Collection<String> topics, final Object message) {
this.topics = topics;
this.message = message;
}
}
/**
* Request for the publisher to publish a message with attention to acknowledgement requests.
*/
private static final class PublishWithAck implements Request {
private static final JsonValue WEAK_ACK_PAYLOAD =
JsonValue.of("Acknowledgement was issued automatically, because the subscriber " +
"is not authorized to receive the signal.");
private final Collection<String> topics;
private final Object message;
private final java.util.Set<AcknowledgementRequest> ackRequests;
private final EntityIdWithType entityId;
private final DittoHeaders dittoHeaders;
private final ActorRef sender;
private PublishWithAck(final Collection<String> topics, final Object message,
final java.util.Set<AcknowledgementRequest> ackRequests,
final EntityIdWithType entityId,
final DittoHeaders dittoHeaders, final ActorRef sender) {
this.topics = topics;
this.message = message;
this.ackRequests = ackRequests;
this.entityId = entityId;
this.dittoHeaders = dittoHeaders;
this.sender = sender;
}
private Acknowledgements toAcks(final Collection<AcknowledgementLabel> ackLabels) {
return Acknowledgements.of(ackLabels.stream()
.map(ackLabel -> Acknowledgement.weak(ackLabel, entityId, dittoHeaders, WEAK_ACK_PAYLOAD))
.collect(Collectors.toList()),
dittoHeaders
);
}
}
}