/
KafkaPublisherActor.java
347 lines (294 loc) · 13.3 KB
/
KafkaPublisherActor.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
/*
* 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.connectivity.service.messaging.kafka;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.errors.RetriableException;
import org.apache.kafka.common.header.Header;
import org.apache.kafka.common.header.internals.RecordHeader;
import org.eclipse.ditto.base.model.acks.AcknowledgementLabel;
import org.eclipse.ditto.base.model.common.HttpStatus;
import org.eclipse.ditto.base.model.entity.id.EntityId;
import org.eclipse.ditto.base.model.entity.id.WithEntityId;
import org.eclipse.ditto.base.model.headers.DittoHeaderDefinition;
import org.eclipse.ditto.base.model.headers.DittoHeaders;
import org.eclipse.ditto.base.model.signals.Signal;
import org.eclipse.ditto.base.model.signals.acks.Acknowledgement;
import org.eclipse.ditto.connectivity.api.ExternalMessage;
import org.eclipse.ditto.connectivity.api.OutboundSignal;
import org.eclipse.ditto.connectivity.model.Connection;
import org.eclipse.ditto.connectivity.model.MessageSendingFailedException;
import org.eclipse.ditto.connectivity.model.Target;
import org.eclipse.ditto.connectivity.service.messaging.BasePublisherActor;
import org.eclipse.ditto.connectivity.service.messaging.ExceptionToAcknowledgementConverter;
import org.eclipse.ditto.connectivity.service.messaging.SendResult;
import org.eclipse.ditto.json.JsonField;
import org.eclipse.ditto.json.JsonObject;
import org.eclipse.ditto.json.JsonObjectBuilder;
import akka.Done;
import akka.actor.Props;
import akka.actor.Status;
import akka.japi.pf.ReceiveBuilder;
import akka.kafka.javadsl.SendProducer;
import akka.util.ByteString;
/**
* Responsible for publishing {@link org.eclipse.ditto.connectivity.api.ExternalMessage}s into an Kafka
* broker.
*/
final class KafkaPublisherActor extends BasePublisherActor<KafkaPublishTarget> {
static final String ACTOR_NAME = "kafkaPublisher";
private final KafkaProducerFactory producerFactory;
private final boolean dryRun;
private SendProducer<String, String> producer;
@SuppressWarnings("unused")
private KafkaPublisherActor(final Connection connection, final KafkaProducerFactory factory,
final boolean dryRun, final String clientId) {
super(connection, clientId);
this.dryRun = dryRun;
producerFactory = factory;
startInternalKafkaProducer();
reportInitialConnectionState();
}
/**
* Creates Akka configuration object {@link akka.actor.Props} for this {@code BasePublisherActor}.
*
* @param connection the connection this publisher belongs to.
* @param factory the factory to create Kafka connections with.
* @param dryRun whether this publisher is only created for a test or not.
* @param clientId identifier of the client actor.
* @return the Akka configuration Props object.
*/
static Props props(final Connection connection, final KafkaProducerFactory factory, final boolean dryRun,
final String clientId) {
return Props.create(KafkaPublisherActor.class, connection, factory, dryRun, clientId);
}
@Override
public void postStop() throws Exception {
closeProducer();
super.postStop();
}
@Override
protected ExceptionToAcknowledgementConverter getExceptionConverter() {
return KafkaExceptionConverter.INSTANCE;
}
@Override
protected void preEnhancement(final ReceiveBuilder receiveBuilder) {
receiveBuilder.match(OutboundSignal.Mapped.class, this::isDryRun,
outbound -> logger.withCorrelationId(outbound.getSource())
.info("Message dropped in dry run mode: {}", outbound))
.matchEquals(GracefulStop.INSTANCE, unused -> this.stopGracefully());
}
@Override
protected void postEnhancement(final ReceiveBuilder receiveBuilder) {
// noop
}
@Override
protected KafkaPublishTarget toPublishTarget(final String address) {
return KafkaPublishTarget.fromTargetAddress(address);
}
@Override
protected CompletionStage<SendResult> publishMessage(final Signal<?> signal,
@Nullable final Target autoAckTarget,
final KafkaPublishTarget publishTarget,
final ExternalMessage message,
final int maxTotalMessageSize,
final int ackSizeQuota) {
if (producer == null) {
final MessageSendingFailedException error = MessageSendingFailedException.newBuilder()
.message("Kafka producer is not available.")
.dittoHeaders(signal.getDittoHeaders())
.build();
escalate(error, "Requested to send Kafka message without producer; this is a bug.");
return CompletableFuture.failedFuture(error);
} else {
final ExternalMessage messageWithConnectionIdHeader = message
.withHeader("ditto-connection-id", connection.getId().toString());
final ProducerRecord<String, String> record = producerRecord(publishTarget, messageWithConnectionIdHeader);
@Nullable final AcknowledgementLabel autoAckLabel = getAcknowledgementLabel(autoAckTarget).orElse(null);
final Function<RecordMetadata, SendResult> callBack =
new ProducerCallBack(signal, autoAckLabel, ackSizeQuota, connection);
return producer.send(record)
.thenApply(callBack)
.whenComplete((metadata, throwable) -> {
if (throwable != null) {
escalateIfNotRetryable(throwable);
}
});
}
}
/**
* Check a send exception.
* Escalate to parent if it cannot be recovered from.
* Called by ProducerCallBack; must be thread-safe.
*
* @param throwable the exception.
*/
private void escalateIfNotRetryable(final Throwable throwable) {
if (!(throwable instanceof RetriableException)) {
escalate(throwable, "Got non-retryable exception");
}
}
private boolean isDryRun() {
return dryRun;
}
private static ProducerRecord<String, String> producerRecord(final KafkaPublishTarget publishTarget,
final ExternalMessage externalMessage) {
final String payload = mapExternalMessagePayload(externalMessage);
final Iterable<Header> headers = mapExternalMessageHeaders(externalMessage);
return new ProducerRecord<>(publishTarget.getTopic(),
publishTarget.getPartition().orElse(null),
publishTarget.getKey().orElse(null),
payload, headers);
}
private static Iterable<Header> mapExternalMessageHeaders(final ExternalMessage externalMessage) {
return externalMessage.getHeaders()
.entrySet()
.stream()
.map(header -> new RecordHeader(header.getKey(), header.getValue().getBytes(StandardCharsets.UTF_8)))
.collect(Collectors.toList());
}
private static String mapExternalMessagePayload(final ExternalMessage externalMessage) {
if (externalMessage.isTextMessage()) {
return externalMessage.getTextPayload().orElse("");
} else if (externalMessage.isBytesMessage()) {
return externalMessage.getBytePayload()
.map(ByteString::fromByteBuffer)
.map(ByteString::utf8String)
.orElse("");
} else {
return "";
}
}
private void startInternalKafkaProducer() {
logger.info("Starting internal Kafka producer.");
closeProducer();
producer = producerFactory.newProducer();
}
private void closeProducer() {
if (producer != null) {
producer.close();
}
}
private void stopInternalKafkaProducer() {
logger.info("Stopping internal Kafka producer.");
closeProducer();
}
private void reportInitialConnectionState() {
logger.info("Publisher ready.");
getContext().getParent().tell(new Status.Success(Done.done()), getSelf());
}
private void stopGracefully() {
stopInternalKafkaProducer();
logger.debug("Stopping myself.");
getContext().stop(getSelf());
}
/**
* Message that allows gracefully stopping the publisher actor.
*/
static final class GracefulStop {
static final GracefulStop INSTANCE = new GracefulStop();
private GracefulStop() {
// intentionally empty
}
}
private static final class ProducerCallBack implements Function<RecordMetadata, SendResult> {
private final Signal<?> signal;
private final int ackSizeQuota;
private int currentQuota;
private final Connection connection;
@Nullable private final AcknowledgementLabel autoAckLabel;
private ProducerCallBack(final Signal<?> signal,
@Nullable final AcknowledgementLabel autoAckLabel,
final int ackSizeQuota,
final Connection connection) {
this.signal = signal;
this.autoAckLabel = autoAckLabel;
this.ackSizeQuota = ackSizeQuota;
this.connection = connection;
}
@Override
public SendResult apply(final RecordMetadata recordMetadata) {
return buildResponseFromMetadata(recordMetadata);
}
private SendResult buildResponseFromMetadata(@Nullable final RecordMetadata metadata) {
final DittoHeaders dittoHeaders = signal.getDittoHeaders();
final boolean verbose = isDebugEnabled() && metadata != null;
final JsonObject ackPayload = verbose ? toPayload(metadata) : null;
final HttpStatus httpStatus = verbose ? HttpStatus.OK : HttpStatus.NO_CONTENT;
final Optional<EntityId> entityIdOptional =
WithEntityId.getEntityIdOfType(EntityId.class, signal);
@Nullable final Acknowledgement issuedAck;
if (entityIdOptional.isPresent() && null != autoAckLabel) {
issuedAck = Acknowledgement.of(autoAckLabel,
entityIdOptional.get(),
httpStatus,
dittoHeaders,
ackPayload);
} else {
issuedAck = null;
}
return new SendResult(issuedAck, dittoHeaders);
}
private JsonObject toPayload(final RecordMetadata metadata) {
final JsonObjectBuilder builder = JsonObject.newBuilder();
currentQuota = ackSizeQuota;
if (metadata.hasTimestamp()) {
builder.set("timestamp", metadata.timestamp(), this::isQuotaSufficient);
}
builder.set("serializedKeySize", metadata.serializedKeySize(), this::isQuotaSufficient);
builder.set("serializedValueSize", metadata.serializedValueSize(), this::isQuotaSufficient);
builder.set("topic", metadata.topic(), this::isQuotaSufficient);
builder.set("partition", metadata.partition(), this::isQuotaSufficient);
if (metadata.hasOffset()) {
builder.set("offset", metadata.offset(), this::isQuotaSufficient);
}
return builder.build();
}
private boolean isQuotaSufficient(final JsonField field) {
final int fieldSize = field.getKey().length() +
(field.getValue().isString() ? field.getValue().asString().length() : 8);
if (fieldSize <= currentQuota) {
currentQuota -= fieldSize;
return true;
} else {
return false;
}
}
private boolean isDebugEnabled() {
final Map<String, String> specificConfig = connection.getSpecificConfig();
return Boolean.parseBoolean(specificConfig.getOrDefault("debugEnabled", Boolean.FALSE.toString()));
}
}
private static final class KafkaExceptionConverter extends ExceptionToAcknowledgementConverter {
static final ExceptionToAcknowledgementConverter INSTANCE = new KafkaExceptionConverter();
private KafkaExceptionConverter() {
super();
}
@Override
protected HttpStatus getHttpStatusForGenericException(final Exception exception) {
// return 500 for retryable exceptions -> sender will retry
// return 400 for non-retryable exceptions -> sender will give up
return exception instanceof RetriableException
? HttpStatus.INTERNAL_SERVER_ERROR
: HttpStatus.BAD_REQUEST;
}
}
}