Search in sources :

Example 21 with MessageIdImpl

use of org.apache.pulsar.client.impl.MessageIdImpl in project incubator-pulsar by apache.

the class JavaInstanceRunnableProcessTest method testAtMostOnceProcessing.

@Test
public void testAtMostOnceProcessing() throws Exception {
    FunctionConfig newFnConfig = FunctionConfig.newBuilder(fnConfig).setProcessingGuarantees(ProcessingGuarantees.ATMOST_ONCE).build();
    config.setFunctionConfig(newFnConfig);
    @Cleanup("shutdown") ExecutorService executorService = Executors.newSingleThreadExecutor();
    try (JavaInstanceRunnable runnable = new JavaInstanceRunnable(config, fnCache, "test-jar-file", mockClient, null)) {
        executorService.submit(runnable);
        Pair<String, String> consumerId = Pair.of(newFnConfig.getInputs(0), FunctionConfigUtils.getFullyQualifiedName(newFnConfig));
        ConsumerInstance consumerInstance = mockConsumers.get(consumerId);
        while (null == consumerInstance) {
            TimeUnit.MILLISECONDS.sleep(20);
            consumerInstance = mockConsumers.get(consumerId);
        }
        ProducerInstance producerInstance = mockProducers.values().iterator().next();
        // once we get consumer id, simulate receiving 10 messages from consumer
        for (int i = 0; i < 10; i++) {
            Message msg = mock(Message.class);
            when(msg.getData()).thenReturn(("message-" + i).getBytes(UTF_8));
            when(msg.getMessageId()).thenReturn(new MessageIdImpl(1L, i, 0));
            consumerInstance.addMessage(msg);
            consumerInstance.getConf().getMessageListener().received(consumerInstance.getConsumer(), msg);
        }
        // wait until all the messages are published
        for (int i = 0; i < 10; i++) {
            Message msg = producerInstance.msgQueue.take();
            assertEquals("message-" + i + "!", new String(msg.getData(), UTF_8));
            // sequence id is not set for AT_MOST_ONCE processing
            assertEquals(0L, msg.getSequenceId());
        }
        // verify acknowledge before send completes
        verify(consumerInstance.getConsumer(), times(10)).acknowledgeAsync(any(Message.class));
        assertEquals(0, consumerInstance.getNumMessages());
        // complete all the publishes
        synchronized (producerInstance) {
            for (CompletableFuture<MessageId> future : producerInstance.sendFutures) {
                future.complete(mock(MessageId.class));
            }
        }
        // acknowledges count should remain same
        verify(consumerInstance.getConsumer(), times(10)).acknowledgeAsync(any(Message.class));
    }
}
Also used : FunctionConfig(org.apache.pulsar.functions.proto.Function.FunctionConfig) Message(org.apache.pulsar.client.api.Message) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) Matchers.anyString(org.mockito.Matchers.anyString) Cleanup(lombok.Cleanup) ExecutorService(java.util.concurrent.ExecutorService) MessageId(org.apache.pulsar.client.api.MessageId) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 22 with MessageIdImpl

use of org.apache.pulsar.client.impl.MessageIdImpl in project incubator-pulsar by apache.

the class UtilsTest method testGetSequenceId.

@Test
public void testGetSequenceId() {
    long lid = 12345L;
    long eid = 34566L;
    MessageIdImpl id = mock(MessageIdImpl.class);
    when(id.getLedgerId()).thenReturn(lid);
    when(id.getEntryId()).thenReturn(eid);
    assertEquals((lid << 28) | eid, Utils.getSequenceId(id));
}
Also used : MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) Test(org.testng.annotations.Test)

Example 23 with MessageIdImpl

use of org.apache.pulsar.client.impl.MessageIdImpl in project incubator-pulsar by apache.

the class UtilsTest method testGetMessageId.

@Test
public void testGetMessageId() {
    long lid = 12345L;
    long eid = 34566L;
    long sequenceId = (lid << 28) | eid;
    MessageIdImpl id = (MessageIdImpl) Utils.getMessageId(sequenceId);
    assertEquals(lid, id.getLedgerId());
    assertEquals(eid, id.getEntryId());
}
Also used : MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) Test(org.testng.annotations.Test)

Example 24 with MessageIdImpl

use of org.apache.pulsar.client.impl.MessageIdImpl in project incubator-pulsar by apache.

the class PulsarKafkaConsumer method poll.

@SuppressWarnings("unchecked")
@Override
public ConsumerRecords<K, V> poll(long timeoutMillis) {
    try {
        QueueItem item = receivedMessages.poll(timeoutMillis, TimeUnit.MILLISECONDS);
        if (item == null) {
            return (ConsumerRecords<K, V>) ConsumerRecords.EMPTY;
        }
        Map<TopicPartition, List<ConsumerRecord<K, V>>> records = new HashMap<>();
        int numberOfRecords = 0;
        while (item != null && ++numberOfRecords < MAX_RECORDS_IN_SINGLE_POLL) {
            TopicName topicName = TopicName.get(item.consumer.getTopic());
            String topic = topicName.getPartitionedTopicName();
            int partition = topicName.isPartitioned() ? topicName.getPartitionIndex() : 0;
            Message<byte[]> msg = item.message;
            MessageIdImpl msgId = (MessageIdImpl) msg.getMessageId();
            long offset = MessageIdUtils.getOffset(msgId);
            TopicPartition tp = new TopicPartition(topic, partition);
            K key = getKey(topic, msg);
            V value = valueDeserializer.deserialize(topic, msg.getData());
            TimestampType timestampType = TimestampType.LOG_APPEND_TIME;
            long timestamp = msg.getPublishTime();
            if (msg.getEventTime() > 0) {
                // If we have Event time, use that in preference
                timestamp = msg.getEventTime();
                timestampType = TimestampType.CREATE_TIME;
            }
            ConsumerRecord<K, V> consumerRecord = new ConsumerRecord<>(topic, partition, offset, timestamp, timestampType, -1, msg.hasKey() ? msg.getKey().length() : 0, msg.getData().length, key, value);
            records.computeIfAbsent(tp, k -> new ArrayList<>()).add(consumerRecord);
            // Update last offset seen by application
            lastReceivedOffset.put(tp, offset);
            // Check if we have an item already available
            item = receivedMessages.poll(0, TimeUnit.MILLISECONDS);
        }
        if (isAutoCommit) {
            // Commit the offset of previously dequeued messages
            commitAsync();
        }
        return new ConsumerRecords<>(records);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}
Also used : TopicName(org.apache.pulsar.common.naming.TopicName) PulsarClientImpl(org.apache.pulsar.client.impl.PulsarClientImpl) TimeoutException(java.util.concurrent.TimeoutException) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) ConsumerBuilder(org.apache.pulsar.client.api.ConsumerBuilder) PulsarConsumerKafkaConfig(org.apache.pulsar.client.kafka.compat.PulsarConsumerKafkaConfig) Message(org.apache.pulsar.client.api.Message) PulsarClientKafkaConfig(org.apache.pulsar.client.kafka.compat.PulsarClientKafkaConfig) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) ConsumerName(org.apache.pulsar.client.util.ConsumerName) StringDeserializer(org.apache.kafka.common.serialization.StringDeserializer) Map(java.util.Map) Metric(org.apache.kafka.common.Metric) MetricName(org.apache.kafka.common.MetricName) Deserializer(org.apache.kafka.common.serialization.Deserializer) PulsarClient(org.apache.pulsar.client.api.PulsarClient) ProducerConfig(org.apache.kafka.clients.producer.ProducerConfig) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) TimestampType(org.apache.kafka.common.record.TimestampType) TopicPartition(org.apache.kafka.common.TopicPartition) Properties(java.util.Properties) MessageIdUtils(org.apache.pulsar.client.kafka.compat.MessageIdUtils) Collection(java.util.Collection) MessageListener(org.apache.pulsar.client.api.MessageListener) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) BlockingQueue(java.util.concurrent.BlockingQueue) PartitionInfo(org.apache.kafka.common.PartitionInfo) SubscriptionType(org.apache.pulsar.client.api.SubscriptionType) Collectors(java.util.stream.Collectors) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) Base64(java.util.Base64) List(java.util.List) FutureUtil(org.apache.pulsar.common.util.FutureUtil) MessageId(org.apache.pulsar.client.api.MessageId) ClientBuilder(org.apache.pulsar.client.api.ClientBuilder) Pattern(java.util.regex.Pattern) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ArrayList(java.util.ArrayList) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) TopicName(org.apache.pulsar.common.naming.TopicName) TopicPartition(org.apache.kafka.common.TopicPartition) TimestampType(org.apache.kafka.common.record.TimestampType) ArrayList(java.util.ArrayList) List(java.util.List)

Example 25 with MessageIdImpl

use of org.apache.pulsar.client.impl.MessageIdImpl in project incubator-pulsar by apache.

the class MessageIdUtils method getOffset.

public static final long getOffset(MessageId messageId) {
    MessageIdImpl msgId = (MessageIdImpl) messageId;
    long ledgerId = msgId.getLedgerId();
    long entryId = msgId.getEntryId();
    // Combine ledger id and entry id to form offset
    // Use less than 32 bits to represent entry id since it will get
    // rolled over way before overflowing the max int range
    long offset = (ledgerId << 28) | entryId;
    return offset;
}
Also used : MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl)

Aggregations

MessageIdImpl (org.apache.pulsar.client.impl.MessageIdImpl)27 Test (org.testng.annotations.Test)18 MessageId (org.apache.pulsar.client.api.MessageId)15 Message (org.apache.pulsar.client.api.Message)11 CompletableFuture (java.util.concurrent.CompletableFuture)9 ExecutorService (java.util.concurrent.ExecutorService)9 TopicName (org.apache.pulsar.common.naming.TopicName)8 List (java.util.List)6 TimeUnit (java.util.concurrent.TimeUnit)6 Cleanup (lombok.Cleanup)6 FunctionConfig (org.apache.pulsar.functions.proto.Function.FunctionConfig)6 Matchers.anyString (org.mockito.Matchers.anyString)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 Map (java.util.Map)5 Set (java.util.Set)5 PersistentTopic (org.apache.pulsar.broker.service.persistent.PersistentTopic)5 Lists (com.google.common.collect.Lists)4 Collectors (java.util.stream.Collectors)4 ManagedLedgerImpl (org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl)4 FutureUtil (org.apache.pulsar.common.util.FutureUtil)4