-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
ContextImpl.java
825 lines (718 loc) · 29.9 KB
/
ContextImpl.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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.functions.instance;
import static com.google.common.base.Preconditions.checkState;
import static org.apache.pulsar.functions.instance.stats.FunctionStatsManager.USER_METRIC_PREFIX;
import com.google.common.annotations.VisibleForTesting;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import io.prometheus.client.Summary;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.api.BatcherBuilder;
import org.apache.pulsar.client.api.ClientBuilder;
import org.apache.pulsar.client.api.CompressionType;
import org.apache.pulsar.client.api.Consumer;
import org.apache.pulsar.client.api.ConsumerBuilder;
import org.apache.pulsar.client.api.HashingScheme;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.api.MessageRoutingMode;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.Schema;
import org.apache.pulsar.client.api.SubscriptionType;
import org.apache.pulsar.client.api.TypedMessageBuilder;
import org.apache.pulsar.client.impl.MultiTopicsConsumerImpl;
import org.apache.pulsar.client.impl.ProducerBuilderImpl;
import org.apache.pulsar.common.io.SinkConfig;
import org.apache.pulsar.common.io.SourceConfig;
import org.apache.pulsar.common.naming.TopicName;
import org.apache.pulsar.common.util.FutureUtil;
import org.apache.pulsar.functions.api.Context;
import org.apache.pulsar.functions.api.Record;
import org.apache.pulsar.functions.api.StateStore;
import org.apache.pulsar.functions.api.utils.FunctionRecord;
import org.apache.pulsar.functions.instance.state.DefaultStateStore;
import org.apache.pulsar.functions.instance.state.StateManager;
import org.apache.pulsar.functions.instance.stats.ComponentStatsManager;
import org.apache.pulsar.functions.instance.stats.FunctionCollectorRegistry;
import org.apache.pulsar.functions.instance.stats.FunctionStatsManager;
import org.apache.pulsar.functions.instance.stats.SinkStatsManager;
import org.apache.pulsar.functions.instance.stats.SourceStatsManager;
import org.apache.pulsar.functions.proto.Function;
import org.apache.pulsar.functions.proto.Function.SinkSpec;
import org.apache.pulsar.functions.secretsprovider.SecretsProvider;
import org.apache.pulsar.functions.source.PulsarFunctionRecord;
import org.apache.pulsar.functions.source.TopicSchema;
import org.apache.pulsar.functions.utils.FunctionCommon;
import org.apache.pulsar.functions.utils.SinkConfigUtils;
import org.apache.pulsar.functions.utils.SourceConfigUtils;
import org.apache.pulsar.io.core.SinkContext;
import org.apache.pulsar.io.core.SourceContext;
import org.slf4j.Logger;
/**
* This class implements the Context interface exposed to the user.
*/
@ToString(exclude = {"pulsarAdmin"})
class ContextImpl implements Context, SinkContext, SourceContext, AutoCloseable {
private InstanceConfig config;
private Logger logger;
// Per Message related
private Record<?> record;
private final ClientBuilder clientBuilder;
private final PulsarClient client;
private final PulsarAdmin pulsarAdmin;
private Map<String, Producer<?>> publishProducers;
private ThreadLocal<Map<String, Producer<?>>> tlPublishProducers;
private ProducerBuilderImpl<?> producerBuilder;
private final TopicSchema topicSchema;
private final SecretsProvider secretsProvider;
private final Map<String, Object> secretsMap;
@VisibleForTesting
StateManager stateManager;
@VisibleForTesting
DefaultStateStore defaultStateStore;
private Map<String, Object> userConfigs;
private ComponentStatsManager statsManager;
Map<String, String[]> userMetricsLabels = new HashMap<>();
private final String[] metricsLabels;
private final Summary userMetricsSummary;
private final SubscriptionType subscriptionType;
private static final String[] userMetricsLabelNames;
private boolean exposePulsarAdminClientEnabled;
private List<Consumer<?>> inputConsumers;
private final Map<TopicName, Consumer> topicConsumers = new ConcurrentHashMap<>();
static {
// add label to indicate user metric
userMetricsLabelNames = Arrays.copyOf(ComponentStatsManager.METRICS_LABEL_NAMES,
ComponentStatsManager.METRICS_LABEL_NAMES.length + 1);
userMetricsLabelNames[ComponentStatsManager.METRICS_LABEL_NAMES.length] = "metric";
}
private final Function.FunctionDetails.ComponentType componentType;
public ContextImpl(InstanceConfig config, Logger logger, PulsarClient client,
SecretsProvider secretsProvider, FunctionCollectorRegistry collectorRegistry,
String[] metricsLabels,
Function.FunctionDetails.ComponentType componentType, ComponentStatsManager statsManager,
StateManager stateManager, PulsarAdmin pulsarAdmin, ClientBuilder clientBuilder)
throws PulsarClientException {
this.config = config;
this.logger = logger;
this.clientBuilder = clientBuilder;
this.client = client;
this.pulsarAdmin = pulsarAdmin;
this.topicSchema = new TopicSchema(client, Thread.currentThread().getContextClassLoader());
this.statsManager = statsManager;
this.producerBuilder = (ProducerBuilderImpl<?>) client.newProducer().blockIfQueueFull(true).enableBatching(true)
.batchingMaxPublishDelay(1, TimeUnit.MILLISECONDS);
boolean useThreadLocalProducers = false;
Function.ProducerSpec producerSpec = config.getFunctionDetails().getSink().getProducerSpec();
if (producerSpec != null) {
if (producerSpec.getMaxPendingMessages() != 0) {
this.producerBuilder.maxPendingMessages(producerSpec.getMaxPendingMessages());
}
if (producerSpec.getMaxPendingMessagesAcrossPartitions() != 0) {
this.producerBuilder
.maxPendingMessagesAcrossPartitions(producerSpec.getMaxPendingMessagesAcrossPartitions());
}
if (producerSpec.getBatchBuilder() != null) {
if (producerSpec.getBatchBuilder().equals("KEY_BASED")) {
this.producerBuilder.batcherBuilder(BatcherBuilder.KEY_BASED);
} else {
this.producerBuilder.batcherBuilder(BatcherBuilder.DEFAULT);
}
}
useThreadLocalProducers = producerSpec.getUseThreadLocalProducers();
}
if (useThreadLocalProducers) {
tlPublishProducers = new ThreadLocal<>();
} else {
publishProducers = new ConcurrentHashMap<>();
}
if (config.getFunctionDetails().getUserConfig().isEmpty()) {
userConfigs = new HashMap<>();
} else {
userConfigs = new Gson().fromJson(config.getFunctionDetails().getUserConfig(),
new TypeToken<Map<String, Object>>() {
}.getType());
}
this.secretsProvider = secretsProvider;
if (!StringUtils.isEmpty(config.getFunctionDetails().getSecretsMap())) {
secretsMap = new Gson().fromJson(config.getFunctionDetails().getSecretsMap(),
new TypeToken<Map<String, Object>>() {
}.getType());
} else {
secretsMap = new HashMap<>();
}
this.metricsLabels = metricsLabels;
String prefix;
switch (componentType) {
case FUNCTION:
prefix = FunctionStatsManager.PULSAR_FUNCTION_METRICS_PREFIX;
break;
case SINK:
prefix = SinkStatsManager.PULSAR_SINK_METRICS_PREFIX;
break;
case SOURCE:
prefix = SourceStatsManager.PULSAR_SOURCE_METRICS_PREFIX;
break;
default:
throw new RuntimeException("Unknown component type: " + componentType);
}
this.userMetricsSummary = collectorRegistry.registerIfNotExist(
prefix + ComponentStatsManager.USER_METRIC_PREFIX,
Summary.build()
.name(prefix + ComponentStatsManager.USER_METRIC_PREFIX)
.help("User defined metric.")
.labelNames(userMetricsLabelNames)
.quantile(0.5, 0.01)
.quantile(0.9, 0.01)
.quantile(0.99, 0.01)
.quantile(0.999, 0.01)
.create());
this.componentType = componentType;
this.stateManager = stateManager;
this.defaultStateStore = (DefaultStateStore) stateManager.getStore(
config.getFunctionDetails().getTenant(),
config.getFunctionDetails().getNamespace(),
config.getFunctionDetails().getName()
);
this.exposePulsarAdminClientEnabled = config.isExposePulsarAdminClientEnabled();
Function.SourceSpec sourceSpec = config.getFunctionDetails().getSource();
switch (sourceSpec.getSubscriptionType()) {
case FAILOVER:
subscriptionType = SubscriptionType.Failover;
break;
case KEY_SHARED:
subscriptionType = SubscriptionType.Key_Shared;
break;
default:
subscriptionType = SubscriptionType.Shared;
break;
}
}
public void setCurrentMessageContext(Record<?> record) {
this.record = record;
}
@Override
public Record<?> getCurrentRecord() {
return new PulsarFunctionRecord(record, config.getFunctionDetails());
}
@Override
public Collection<String> getInputTopics() {
return config.getFunctionDetails().getSource().getInputSpecsMap().keySet();
}
@Override
public SinkConfig getSinkConfig() {
return SinkConfigUtils.convertFromDetails(config.getFunctionDetails());
}
@Override
public String getOutputTopic() {
return config.getFunctionDetails().getSink().getTopic();
}
@Override
public SourceConfig getSourceConfig() {
return SourceConfigUtils.convertFromDetails(config.getFunctionDetails());
}
@Override
public String getOutputSchemaType() {
SinkSpec sink = config.getFunctionDetails().getSink();
if (!StringUtils.isEmpty(sink.getSchemaType())) {
return sink.getSchemaType();
} else {
return sink.getSerDeClassName();
}
}
@Override
public String getTenant() {
return config.getFunctionDetails().getTenant();
}
@Override
public String getNamespace() {
return config.getFunctionDetails().getNamespace();
}
@Override
public String getSinkName() {
return config.getFunctionDetails().getName();
}
@Override
public String getSourceName() {
return config.getFunctionDetails().getName();
}
@Override
public String getFunctionName() {
return config.getFunctionDetails().getName();
}
@Override
public String getFunctionId() {
return config.getFunctionId();
}
@Override
public int getInstanceId() {
return config.getInstanceId();
}
@Override
public int getNumInstances() {
return config.getFunctionDetails().getParallelism();
}
@Override
public String getFunctionVersion() {
return config.getFunctionVersion();
}
@Override
public Logger getLogger() {
return logger;
}
@Override
public Optional<Object> getUserConfigValue(String key) {
Object value = userConfigs.getOrDefault(key, null);
if (value instanceof String && ((String) value).startsWith("$")) {
// any string starts with '$' is considered as system env symbol and will be
// replaced with the actual env value
try {
String actualValue = System.getenv(((String) value).substring(1));
return Optional.ofNullable(actualValue);
} catch (SecurityException ex) {
throw new RuntimeException("Access to environment variable " + value + " is not allowed.", ex);
}
} else {
return Optional.ofNullable(value);
}
}
@Override
public Object getUserConfigValueOrDefault(String key, Object defaultValue) {
return getUserConfigValue(key).orElse(defaultValue);
}
@Override
public Map<String, Object> getUserConfigMap() {
return userConfigs;
}
@Override
public String getSecret(String secretName) {
if (secretsMap.containsKey(secretName)) {
return secretsProvider.provideSecret(secretName, secretsMap.get(secretName));
} else {
return null;
}
}
@Override
public PulsarAdmin getPulsarAdmin() {
if (exposePulsarAdminClientEnabled) {
return pulsarAdmin;
} else {
throw new IllegalStateException("PulsarAdmin is not enabled in function worker");
}
}
@Override
public <T extends StateStore> T getStateStore(String name) {
return getStateStore(
config.getFunctionDetails().getTenant(),
config.getFunctionDetails().getNamespace(),
name);
}
@Override
public <T extends StateStore> T getStateStore(String tenant, String ns, String name) {
return (T) stateManager.getStore(tenant, ns, name);
}
private void ensureStateEnabled() {
checkState(null != defaultStateStore, "State %s/%s/%s is not enabled.",
config.getFunctionDetails().getTenant(),
config.getFunctionDetails().getNamespace(),
config.getFunctionDetails().getName());
}
@Override
public CompletableFuture<Void> incrCounterAsync(String key, long amount) {
ensureStateEnabled();
return defaultStateStore.incrCounterAsync(key, amount);
}
@Override
public void incrCounter(String key, long amount) {
ensureStateEnabled();
defaultStateStore.incrCounter(key, amount);
}
@Override
public CompletableFuture<Long> getCounterAsync(String key) {
ensureStateEnabled();
return defaultStateStore.getCounterAsync(key);
}
@Override
public long getCounter(String key) {
ensureStateEnabled();
return defaultStateStore.getCounter(key);
}
@Override
public CompletableFuture<Void> putStateAsync(String key, ByteBuffer value) {
ensureStateEnabled();
return defaultStateStore.putAsync(key, value);
}
@Override
public void putState(String key, ByteBuffer value) {
ensureStateEnabled();
defaultStateStore.put(key, value);
}
@Override
public CompletableFuture<Void> deleteStateAsync(String key) {
ensureStateEnabled();
return defaultStateStore.deleteAsync(key);
}
@Override
public void deleteState(String key) {
ensureStateEnabled();
defaultStateStore.delete(key);
}
@Override
public CompletableFuture<ByteBuffer> getStateAsync(String key) {
ensureStateEnabled();
return defaultStateStore.getAsync(key);
}
@Override
public ByteBuffer getState(String key) {
ensureStateEnabled();
return defaultStateStore.get(key);
}
@Override
public <T> CompletableFuture<Void> publish(String topicName, T object) {
return publish(topicName, object, "");
}
@SuppressWarnings("unchecked")
@Override
public <T> CompletableFuture<Void> publish(String topicName, T object, String schemaOrSerdeClassName) {
return publish(topicName, object,
(Schema<T>) topicSchema.getSchema(topicName, object, schemaOrSerdeClassName, false));
}
@Override
public <T> TypedMessageBuilder<T> newOutputMessage(String topicName, Schema<T> schema)
throws PulsarClientException {
MessageBuilderImpl<T> messageBuilder = new MessageBuilderImpl<>();
TypedMessageBuilder<T> typedMessageBuilder;
Producer<T> producer = getProducer(topicName, schema);
if (schema != null) {
typedMessageBuilder = producer.newMessage(schema);
} else {
typedMessageBuilder = producer.newMessage();
}
messageBuilder.setUnderlyingBuilder(typedMessageBuilder);
return messageBuilder;
}
@Override
public <T> ConsumerBuilder<T> newConsumerBuilder(Schema<T> schema) throws PulsarClientException {
return this.client.newConsumer(schema);
}
@Override
public <X> FunctionRecord.FunctionRecordBuilder<X> newOutputRecordBuilder(Schema<X> schema) {
return FunctionRecord.from(this, schema);
}
@Override
public SubscriptionType getSubscriptionType() {
return subscriptionType;
}
public <T> CompletableFuture<Void> publish(String topicName, T object, Schema<T> schema) {
try {
return newOutputMessage(topicName, schema).value(object).sendAsync().thenApply(msgId -> null);
} catch (PulsarClientException e) {
logger.error("Failed to create Producer while doing user publish", e);
return FutureUtil.failedFuture(e);
}
}
@Override
public void recordMetric(String metricName, double value) {
String[] userMetricLabels = userMetricsLabels.get(metricName);
if (userMetricLabels == null) {
userMetricLabels = Arrays.copyOf(metricsLabels, metricsLabels.length + 1);
userMetricLabels[userMetricLabels.length - 1] = metricName;
// set label for metrics before putting into userMetricsLabels map to
// prevent race condition with getMetrics calls
userMetricsSummary.labels(userMetricLabels).observe(value);
userMetricsLabels.put(metricName, userMetricLabels);
} else {
userMetricsSummary.labels(userMetricLabels).observe(value);
}
}
@Override
public PulsarClient getPulsarClient() {
return client;
}
@Override
public ClientBuilder getPulsarClientBuilder() {
return clientBuilder;
}
private <T> Producer<T> getProducer(String topicName, Schema<T> schema) throws PulsarClientException {
Producer<T> producer;
if (tlPublishProducers != null) {
Map<String, Producer<?>> producerMap = tlPublishProducers.get();
if (producerMap == null) {
producerMap = new HashMap<>();
tlPublishProducers.set(producerMap);
}
producer = (Producer<T>) producerMap.get(topicName);
} else {
producer = (Producer<T>) publishProducers.get(topicName);
}
if (producer == null) {
Producer<T> newProducer = ((ProducerBuilderImpl<T>) producerBuilder.clone())
.schema(schema)
.blockIfQueueFull(true)
.enableBatching(true)
.batchingMaxPublishDelay(10, TimeUnit.MILLISECONDS)
.compressionType(CompressionType.LZ4)
.hashingScheme(HashingScheme.Murmur3_32Hash) //
.messageRoutingMode(MessageRoutingMode.CustomPartition)
.messageRouter(FunctionResultRouter.of())
// set send timeout to be infinity to prevent potential deadlock with consumer
// that might happen when consumer is blocked due to unacked messages
.sendTimeout(0, TimeUnit.SECONDS)
.topic(topicName)
.properties(InstanceUtils.getProperties(componentType,
FunctionCommon.getFullyQualifiedName(
this.config.getFunctionDetails().getTenant(),
this.config.getFunctionDetails().getNamespace(),
this.config.getFunctionDetails().getName()),
this.config.getInstanceId()))
.create();
if (tlPublishProducers != null) {
tlPublishProducers.get().put(topicName, newProducer);
} else {
Producer<T> existingProducer = (Producer<T>) publishProducers.putIfAbsent(topicName, newProducer);
if (existingProducer != null) {
// The value in the map was not updated after the concurrent put
newProducer.close();
producer = existingProducer;
} else {
producer = newProducer;
}
}
}
return producer;
}
public Map<String, Double> getAndResetMetrics() {
Map<String, Double> retval = getMetrics();
resetMetrics();
return retval;
}
public void resetMetrics() {
userMetricsSummary.clear();
}
public Map<String, Double> getMetrics() {
Map<String, Double> metricsMap = new HashMap<>();
for (Map.Entry<String, String[]> userMetricsLabelsEntry : userMetricsLabels.entrySet()) {
String metricName = userMetricsLabelsEntry.getKey();
String[] labels = userMetricsLabelsEntry.getValue();
Summary.Child.Value summary = userMetricsSummary.labels(labels).get();
String prefix = USER_METRIC_PREFIX + metricName + "_";
metricsMap.put(prefix + "sum", summary.sum);
metricsMap.put(prefix + "count", summary.count);
for (Map.Entry<Double, Double> entry : summary.quantiles.entrySet()) {
Double quantile = entry.getKey();
Double value = entry.getValue();
metricsMap.put(prefix + quantile, value);
}
}
return metricsMap;
}
class MessageBuilderImpl<T> implements TypedMessageBuilder<T> {
private TypedMessageBuilder<T> underlyingBuilder;
@Override
public MessageId send() throws PulsarClientException {
try {
return sendAsync().get();
} catch (Exception e) {
throw PulsarClientException.unwrap(e);
}
}
@Override
public CompletableFuture<MessageId> sendAsync() {
return underlyingBuilder.sendAsync()
.whenComplete((result, cause) -> {
if (null != cause) {
statsManager.incrSysExceptions(cause);
logger.error("Failed to publish to topic with error", cause);
}
});
}
@Override
public TypedMessageBuilder<T> key(String key) {
underlyingBuilder.key(key);
return this;
}
@Override
public TypedMessageBuilder<T> keyBytes(byte[] key) {
underlyingBuilder.keyBytes(key);
return this;
}
@Override
public TypedMessageBuilder<T> orderingKey(byte[] orderingKey) {
underlyingBuilder.orderingKey(orderingKey);
return this;
}
@Override
public TypedMessageBuilder<T> value(T value) {
underlyingBuilder.value(value);
return this;
}
@Override
public TypedMessageBuilder<T> property(String name, String value) {
underlyingBuilder.property(name, value);
return this;
}
@Override
public TypedMessageBuilder<T> properties(Map<String, String> properties) {
underlyingBuilder.properties(properties);
return this;
}
@Override
public TypedMessageBuilder<T> eventTime(long timestamp) {
underlyingBuilder.eventTime(timestamp);
return this;
}
@Override
public TypedMessageBuilder<T> sequenceId(long sequenceId) {
underlyingBuilder.sequenceId(sequenceId);
return this;
}
@Override
public TypedMessageBuilder<T> replicationClusters(List<String> clusters) {
underlyingBuilder.replicationClusters(clusters);
return this;
}
@Override
public TypedMessageBuilder<T> disableReplication() {
underlyingBuilder.disableReplication();
return this;
}
@Override
public TypedMessageBuilder<T> loadConf(Map<String, Object> config) {
underlyingBuilder.loadConf(config);
return this;
}
@Override
public TypedMessageBuilder<T> deliverAfter(long delay, TimeUnit unit) {
underlyingBuilder.deliverAfter(delay, unit);
return this;
}
@Override
public TypedMessageBuilder<T> deliverAt(long timestamp) {
underlyingBuilder.deliverAt(timestamp);
return this;
}
public void setUnderlyingBuilder(TypedMessageBuilder<T> underlyingBuilder) {
this.underlyingBuilder = underlyingBuilder;
}
}
@Override
public void close() {
List<CompletableFuture> futures = new LinkedList<>();
if (publishProducers != null) {
for (Producer<?> producer : publishProducers.values()) {
futures.add(producer.closeAsync());
}
}
if (tlPublishProducers != null) {
for (Producer<?> producer : tlPublishProducers.get().values()) {
futures.add(producer.closeAsync());
}
}
if (pulsarAdmin != null) {
pulsarAdmin.close();
}
try {
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get();
} catch (InterruptedException | ExecutionException e) {
logger.warn("Failed to close producers", e);
}
}
@Override
public void seek(String topic, int partition, MessageId messageId) throws PulsarClientException {
Consumer<?> consumer = getConsumer(topic, partition);
consumer.seek(messageId);
}
@Override
public void pause(String topic, int partition) throws PulsarClientException {
getConsumer(topic, partition).pause();
}
@Override
public void resume(String topic, int partition) throws PulsarClientException {
getConsumer(topic, partition).resume();
}
public void setInputConsumers(List<Consumer<?>> inputConsumers) {
this.inputConsumers = inputConsumers;
inputConsumers.stream()
.flatMap(consumer ->
consumer instanceof MultiTopicsConsumerImpl
? ((MultiTopicsConsumerImpl<?>) consumer).getConsumers().stream()
: Stream.of(consumer))
.forEach(consumer -> topicConsumers.putIfAbsent(TopicName.get(consumer.getTopic()), consumer));
}
private void reloadConsumersFromMultiTopicsConsumers() {
// MultiTopicsConsumer in the list of inputConsumers could change its nested consumers
// if ne partition was created or a new topic added that matches subscription pattern.
// Let's update topicConsumers map to match.
inputConsumers
.stream()
.flatMap(c ->
c instanceof MultiTopicsConsumerImpl
? ((MultiTopicsConsumerImpl<?>) c).getConsumers().stream()
: Stream.empty() // no changes expected in regular consumers
).forEach(c -> topicConsumers.putIfAbsent(TopicName.get(c.getTopic()), c));
}
// returns null if consumer not found
private Consumer<?> tryGetConsumer(String topic, int partition) {
if (partition == 0) {
// maybe a non-partitioned topic
Consumer<?> consumer = topicConsumers.get(TopicName.get(topic));
if (consumer != null) {
return consumer;
}
}
// maybe partitioned topic
return topicConsumers.get(TopicName.get(topic).getPartition(partition));
}
@VisibleForTesting
Consumer<?> getConsumer(String topic, int partition) throws PulsarClientException {
if (inputConsumers == null) {
throw new PulsarClientException("Getting consumer is not supported");
}
Consumer<?> consumer = tryGetConsumer(topic, partition);
if (consumer == null) {
// MultiTopicsConsumer's list of consumers could change
// if partitions changed or pattern(s) used to subscribe.
// Reload and try one more time.
reloadConsumersFromMultiTopicsConsumers();
consumer = tryGetConsumer(topic, partition);
}
if (consumer != null) {
return consumer;
}
throw new PulsarClientException("Consumer for topic " + topic
+ " partition " + partition + " is not found");
}
}