-
Notifications
You must be signed in to change notification settings - Fork 214
/
KafkaPublisherActor.java
460 lines (392 loc) · 20.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
/*
* 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.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
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.auth.AuthorizationContext;
import org.eclipse.ditto.base.model.common.ByteBufferUtils;
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.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.GenericTarget;
import org.eclipse.ditto.connectivity.model.MessageSendingFailedException;
import org.eclipse.ditto.connectivity.model.Target;
import org.eclipse.ditto.connectivity.service.config.ConnectivityConfig;
import org.eclipse.ditto.connectivity.service.config.KafkaProducerConfig;
import org.eclipse.ditto.connectivity.service.messaging.BasePublisherActor;
import org.eclipse.ditto.connectivity.service.messaging.ConnectivityStatusResolver;
import org.eclipse.ditto.connectivity.service.messaging.ExceptionToAcknowledgementConverter;
import org.eclipse.ditto.connectivity.service.messaging.SendResult;
import org.eclipse.ditto.connectivity.service.messaging.internal.ConnectionFailure;
import org.eclipse.ditto.json.JsonField;
import org.eclipse.ditto.json.JsonObject;
import org.eclipse.ditto.json.JsonObjectBuilder;
import org.apache.pekko.Done;
import org.apache.pekko.NotUsed;
import org.apache.pekko.actor.Props;
import org.apache.pekko.actor.Status;
import org.apache.pekko.japi.Pair;
import org.apache.pekko.japi.pf.ReceiveBuilder;
import org.apache.pekko.kafka.ProducerMessage;
import org.apache.pekko.kafka.javadsl.SendProducer;
import org.apache.pekko.stream.KillSwitch;
import org.apache.pekko.stream.KillSwitches;
import org.apache.pekko.stream.Materializer;
import org.apache.pekko.stream.OverflowStrategy;
import org.apache.pekko.stream.QueueOfferResult;
import org.apache.pekko.stream.RestartSettings;
import org.apache.pekko.stream.javadsl.Flow;
import org.apache.pekko.stream.javadsl.Keep;
import org.apache.pekko.stream.javadsl.RestartFlow;
import org.apache.pekko.stream.javadsl.Sink;
import org.apache.pekko.stream.javadsl.Source;
import org.apache.pekko.stream.javadsl.SourceQueueWithComplete;
/**
* Responsible for publishing {@link org.eclipse.ditto.connectivity.api.ExternalMessage}s into a Kafka broker.
*/
final class KafkaPublisherActor extends BasePublisherActor<KafkaPublishTarget> {
static final String ACTOR_NAME = "kafkaPublisher";
private final boolean dryRun;
private final KafkaProducerStream producerStream;
@SuppressWarnings("unused")
private KafkaPublisherActor(final Connection connection,
final SendProducerFactory producerFactory,
final boolean dryRun,
final ConnectivityStatusResolver connectivityStatusResolver,
final ConnectivityConfig connectivityConfig) {
super(connection, connectivityStatusResolver, connectivityConfig);
this.dryRun = dryRun;
final var connectionConfig = connectivityConfig.getConnectionConfig();
final var kafkaConfig = connectionConfig.getKafkaConfig();
producerStream = new KafkaProducerStream(kafkaConfig.getProducerConfig(),
Materializer.createMaterializer(this::getContext),
producerFactory);
}
/**
* Creates Akka configuration object {@link pekko.actor.Props} for this {@code BasePublisherActor}.
*
* @param connection the connection this publisher belongs to.
* @param producerFactory factory to create kafka SendProducer.
* @param dryRun whether this publisher is only created for a test or not.
* @param connectivityStatusResolver connectivity status resolver to resolve occurred exceptions to a connectivity
* status.
* @param connectivityConfig the config of the connectivity service with potential overwrites.
* @return the Akka configuration Props object.
*/
static Props props(final Connection connection,
final SendProducerFactory producerFactory,
final boolean dryRun,
final ConnectivityStatusResolver connectivityStatusResolver,
final ConnectivityConfig connectivityConfig) {
return Props.create(KafkaPublisherActor.class,
connection,
producerFactory,
dryRun,
connectivityStatusResolver,
connectivityConfig);
}
@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
public void preStart() throws Exception {
super.preStart();
reportInitialConnectionState();
}
@Override
protected void postEnhancement(final ReceiveBuilder receiveBuilder) {
// noop
}
@Override
protected KafkaPublishTarget toPublishTarget(final GenericTarget target) {
return KafkaPublishTarget.fromTargetAddress(target.getAddress());
}
@Override
protected CompletionStage<SendResult> publishMessage(final Signal<?> signal,
@Nullable final Target autoAckTarget,
final KafkaPublishTarget publishTarget,
final ExternalMessage message,
final int maxTotalMessageSize,
final int ackSizeQuota,
@Nullable final AuthorizationContext targetAuthorizationContext) {
@Nullable final AcknowledgementLabel autoAckLabel = getAcknowledgementLabel(autoAckTarget).orElse(null);
final Function<RecordMetadata, SendResult> callback =
new ProducerCallback(signal, autoAckLabel, ackSizeQuota, connection);
final ExternalMessage messageWithConnectionIdHeader =
message.withHeader("ditto-connection-id", connection.getId().toString());
return producerStream.publish(publishTarget, messageWithConnectionIdHeader).thenApply(callback);
}
@Override
public void postStop() throws Exception {
super.postStop();
producerStream.shutdown();
}
private boolean isDryRun() {
return dryRun;
}
private void reportInitialConnectionState() {
logger.info("Publisher ready.");
getContext().getParent().tell(new Status.Success(Done.done()), getSelf());
}
private void stopGracefully() {
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() {}
@Override
protected HttpStatus getHttpStatusForGenericException(final Throwable 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;
}
}
final class KafkaProducerStream {
private static final String TOO_MANY_IN_FLIGHT_MESSAGE_DESCRIPTION = """
This can have the following reasons:
a) The Kafka consumer does not consume the messages fast enough.
b) The client count of this connection is not configured high enough.""";
private final KillSwitch killSwitch;
private final SourceQueueWithComplete<ProducerMessage.Envelope<String, ByteBuffer, CompletableFuture<RecordMetadata>>>
sourceQueue;
private final AtomicReference<SendProducer<String, ByteBuffer>> sendProducer = new AtomicReference<>();
private KafkaProducerStream(final KafkaProducerConfig config, final Materializer materializer,
final SendProducerFactory producerFactory) {
final RestartSettings restartSettings =
RestartSettings.create(config.getMinBackoff(), config.getMaxBackoff(), config.getRandomFactor())
.withMaxRestarts(config.getMaxRestartsCount(), config.getMaxRestartsWithin());
final Pair<SourceQueueWithComplete<ProducerMessage.Envelope<String, ByteBuffer, CompletableFuture<RecordMetadata>>>, Source<ProducerMessage.Envelope<String, ByteBuffer, CompletableFuture<RecordMetadata>>, NotUsed>>
sourcePair =
Source.<ProducerMessage.Envelope<String, ByteBuffer, CompletableFuture<RecordMetadata>>>
queue(config.getQueueSize(), OverflowStrategy.dropNew()).preMaterialize(materializer);
sourceQueue = sourcePair.first();
killSwitch = sourcePair.second()
.via(RestartFlow.onFailuresWithBackoff(restartSettings, () -> {
logger.debug("Creating new kafka publish flow.");
Optional.ofNullable(sendProducer.getAndSet(producerFactory.newSendProducer()))
.ifPresent(SendProducer::close);
return Flow.fromFunction(envelope -> sendProducer.get()
.sendEnvelope(envelope)
.whenComplete((results, exception) -> handleSendResult(results,
exception,
envelope.passThrough())));
}))
.viaMat(KillSwitches.single(), Keep.right())
.toMat(Sink.ignore(), Keep.left())
.run(materializer);
}
private void handleSendResult(
@Nullable final ProducerMessage.Results<String, ByteBuffer, CompletableFuture<RecordMetadata>> results,
@Nullable final Throwable exception, final CompletableFuture<RecordMetadata> resultFuture) {
if (exception == null) {
if (results instanceof ProducerMessage.Result) {
final ProducerMessage.Result<String, ByteBuffer, CompletableFuture<RecordMetadata>> result =
(ProducerMessage.Result<String, ByteBuffer, CompletableFuture<RecordMetadata>>) results;
resultFuture.complete(result.metadata());
} else {
// should never happen, we provide only ProducerMessage.single to the source
logger.warning("Received multipart result, ignoring: {}", results);
resultFuture.completeExceptionally(
new IllegalArgumentException("Received unexpected multipart result."));
}
} else {
logger.debug("Failed to send kafka record: [{}] {}", exception.getClass().getName(),
exception.getMessage());
resultFuture.completeExceptionally(exception);
escalate(exception, ConnectionFailure.determineFailureDescription(Instant.now(),
exception, "Broker may not be available."));
}
}
private CompletableFuture<RecordMetadata> publish(final KafkaPublishTarget publishTarget,
final ExternalMessage externalMessage) {
final CompletableFuture<RecordMetadata> resultFuture = new CompletableFuture<>();
final ProducerRecord<String, ByteBuffer> producerRecord = getProducerRecord(publishTarget, externalMessage);
final ProducerMessage.Envelope<String, ByteBuffer, CompletableFuture<RecordMetadata>> envelope =
ProducerMessage.single(producerRecord, resultFuture);
if (null != sourceQueue) {
sourceQueue.offer(envelope).whenComplete(handleQueueOfferResult(externalMessage, resultFuture));
} else {
final IllegalStateException ex = new IllegalStateException("Publisher not initialized");
logger.error(ex, ex.getMessage());
resultFuture.completeExceptionally(ex);
}
return resultFuture;
}
private ProducerRecord<String, ByteBuffer> getProducerRecord(final KafkaPublishTarget publishTarget,
final ExternalMessage externalMessage) {
final ByteBuffer 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 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 ByteBuffer mapExternalMessagePayload(final ExternalMessage externalMessage) {
if (externalMessage.isBytesMessage()) {
return externalMessage.getBytePayload()
.orElseGet(ByteBufferUtils::empty);
} else if (externalMessage.isTextMessage()) {
final Charset charset = getCharsetFromMessage(externalMessage);
return externalMessage.getTextPayload()
.map(text -> text.getBytes(charset))
.map(ByteBuffer::wrap)
.orElseGet(ByteBufferUtils::empty);
} else {
return ByteBufferUtils.empty();
}
}
// Async callback. Must be thread-safe.
private BiConsumer<QueueOfferResult, Throwable> handleQueueOfferResult(final ExternalMessage message,
final CompletableFuture<?> resultFuture) {
return (queueOfferResult, error) -> {
if (error != null) {
final String errorDescription = "Source queue failure";
logger.error(error, errorDescription);
resultFuture.completeExceptionally(error);
escalate(error, errorDescription);
} else if (Objects.equals(queueOfferResult, QueueOfferResult.dropped())) {
resultFuture.completeExceptionally(MessageSendingFailedException.newBuilder()
.message("Outgoing Kafka message dropped: There are too many uncommitted messages.")
.description(TOO_MANY_IN_FLIGHT_MESSAGE_DESCRIPTION)
.dittoHeaders(message.getInternalHeaders())
.build());
}
};
}
private void shutdown() {
Optional.ofNullable(sendProducer.get()).ifPresent(SendProducer::close);
killSwitch.shutdown();
}
}
}