Search in sources :

Example 16 with MessageIdData

use of org.apache.pulsar.common.api.proto.MessageIdData in project pulsar by apache.

the class Consumer method individualAckNormal.

// this method is for individual ack not carry the transaction
private CompletableFuture<Void> individualAckNormal(CommandAck ack, Map<String, Long> properties) {
    List<Position> positionsAcked = new ArrayList<>();
    for (int i = 0; i < ack.getMessageIdsCount(); i++) {
        MessageIdData msgId = ack.getMessageIdAt(i);
        PositionImpl position;
        long ackedCount = 0;
        long batchSize = getBatchSize(msgId);
        Consumer ackOwnerConsumer = getAckOwnerConsumer(msgId.getLedgerId(), msgId.getEntryId());
        if (msgId.getAckSetsCount() > 0) {
            long[] ackSets = new long[msgId.getAckSetsCount()];
            for (int j = 0; j < msgId.getAckSetsCount(); j++) {
                ackSets[j] = msgId.getAckSetAt(j);
            }
            position = PositionImpl.get(msgId.getLedgerId(), msgId.getEntryId(), ackSets);
            ackedCount = getAckedCountForBatchIndexLevelEnabled(position, batchSize, ackSets);
            if (isTransactionEnabled()) {
                // sync the batch position bit set point, in order to delete the position in pending acks
                if (Subscription.isIndividualAckMode(subType)) {
                    ((PersistentSubscription) subscription).syncBatchPositionBitSetForPendingAck(position);
                }
            }
        } else {
            position = PositionImpl.get(msgId.getLedgerId(), msgId.getEntryId());
            ackedCount = getAckedCountForMsgIdNoAckSets(batchSize, position);
        }
        addAndGetUnAckedMsgs(ackOwnerConsumer, -(int) ackedCount);
        positionsAcked.add(position);
        checkCanRemovePendingAcksAndHandle(position, msgId);
        checkAckValidationError(ack, position);
    }
    subscription.acknowledgeMessage(positionsAcked, AckType.Individual, properties);
    CompletableFuture<Void> completableFuture = new CompletableFuture<>();
    completableFuture.complete(null);
    if (isTransactionEnabled() && Subscription.isIndividualAckMode(subType)) {
        completableFuture.whenComplete((v, e) -> positionsAcked.forEach(position -> {
            // the bit set is empty in pending ack handle.
            if (((PositionImpl) position).getAckSet() != null) {
                if (((PersistentSubscription) subscription).checkIsCanDeleteConsumerPendingAck((PositionImpl) position)) {
                    removePendingAcks((PositionImpl) position);
                }
            }
        }));
    }
    return completableFuture;
}
Also used : LongAdder(java.util.concurrent.atomic.LongAdder) AtomicIntegerFieldUpdater(java.util.concurrent.atomic.AtomicIntegerFieldUpdater) Setter(lombok.Setter) MutableInt(org.apache.commons.lang3.mutable.MutableInt) TopicName(org.apache.pulsar.common.naming.TopicName) LongPair(org.apache.pulsar.common.util.collections.ConcurrentLongLongPairHashMap.LongPair) Getter(lombok.Getter) AckType(org.apache.pulsar.common.api.proto.CommandAck.AckType) MessageIdData(org.apache.pulsar.common.api.proto.MessageIdData) Entry(org.apache.bookkeeper.mledger.Entry) LoggerFactory(org.slf4j.LoggerFactory) CompletableFuture(java.util.concurrent.CompletableFuture) KeySharedMeta(org.apache.pulsar.common.api.proto.KeySharedMeta) ArrayList(java.util.ArrayList) Commands(org.apache.pulsar.common.protocol.Commands) SubType(org.apache.pulsar.common.api.proto.CommandSubscribe.SubType) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) TxnID(org.apache.pulsar.client.api.transaction.TxnID) Lists(com.google.common.collect.Lists) KeyLongValue(org.apache.pulsar.common.api.proto.KeyLongValue) DateFormatter(org.apache.pulsar.common.util.DateFormatter) MutablePair(org.apache.commons.lang3.tuple.MutablePair) Map(java.util.Map) ConsumerStatsImpl(org.apache.pulsar.common.policies.data.stats.ConsumerStatsImpl) CommandAck(org.apache.pulsar.common.api.proto.CommandAck) PositionImpl(org.apache.bookkeeper.mledger.impl.PositionImpl) DEFAULT_CONSUMER_EPOCH(org.apache.pulsar.common.protocol.Commands.DEFAULT_CONSUMER_EPOCH) Logger(org.slf4j.Logger) Promise(io.netty.util.concurrent.Promise) InitialPosition(org.apache.pulsar.common.api.proto.CommandSubscribe.InitialPosition) TransactionConflictException(org.apache.pulsar.transaction.common.exception.TransactionConflictException) BitSetRecyclable(org.apache.pulsar.common.util.collections.BitSetRecyclable) MoreObjects(com.google.common.base.MoreObjects) Position(org.apache.bookkeeper.mledger.Position) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) FutureUtil(org.apache.pulsar.common.util.FutureUtil) MessageId(org.apache.pulsar.client.api.MessageId) PersistentSubscription(org.apache.pulsar.broker.service.persistent.PersistentSubscription) ConcurrentLongLongPairHashMap(org.apache.pulsar.common.util.collections.ConcurrentLongLongPairHashMap) BitSet(java.util.BitSet) Future(io.netty.util.concurrent.Future) Collections(java.util.Collections) Rate(org.apache.pulsar.common.stats.Rate) InitialPosition(org.apache.pulsar.common.api.proto.CommandSubscribe.InitialPosition) Position(org.apache.bookkeeper.mledger.Position) MessageIdData(org.apache.pulsar.common.api.proto.MessageIdData) PositionImpl(org.apache.bookkeeper.mledger.impl.PositionImpl) ArrayList(java.util.ArrayList) PersistentSubscription(org.apache.pulsar.broker.service.persistent.PersistentSubscription) CompletableFuture(java.util.concurrent.CompletableFuture)

Example 17 with MessageIdData

use of org.apache.pulsar.common.api.proto.MessageIdData in project pulsar by apache.

the class Consumer method redeliverUnacknowledgedMessages.

public void redeliverUnacknowledgedMessages(List<MessageIdData> messageIds) {
    int totalRedeliveryMessages = 0;
    List<PositionImpl> pendingPositions = Lists.newArrayList();
    for (MessageIdData msg : messageIds) {
        PositionImpl position = PositionImpl.get(msg.getLedgerId(), msg.getEntryId());
        LongPair longPair = pendingAcks.get(position.getLedgerId(), position.getEntryId());
        if (longPair != null) {
            int unAckedCount = (int) getUnAckedCountForBatchIndexLevelEnabled(position, longPair.first);
            pendingAcks.remove(position.getLedgerId(), position.getEntryId());
            totalRedeliveryMessages += unAckedCount;
            pendingPositions.add(position);
        }
    }
    addAndGetUnAckedMsgs(this, -totalRedeliveryMessages);
    blockedConsumerOnUnackedMsgs = false;
    if (log.isDebugEnabled()) {
        log.debug("[{}-{}] consumer {} received {} msg-redelivery {}", topicName, subscription, consumerId, totalRedeliveryMessages, pendingPositions.size());
    }
    subscription.redeliverUnacknowledgedMessages(this, pendingPositions);
    msgRedeliver.recordMultipleEvents(totalRedeliveryMessages, totalRedeliveryMessages);
    int numberOfBlockedPermits = PERMITS_RECEIVED_WHILE_CONSUMER_BLOCKED_UPDATER.getAndSet(this, 0);
    // if permitsReceivedWhileConsumerBlocked has been accumulated then pass it to Dispatcher to flow messages
    if (numberOfBlockedPermits > 0) {
        MESSAGE_PERMITS_UPDATER.getAndAdd(this, numberOfBlockedPermits);
        if (log.isDebugEnabled()) {
            log.debug("[{}-{}] Added {} blockedPermits to broker.service.Consumer's messagePermits for consumer {}", topicName, subscription, numberOfBlockedPermits, consumerId);
        }
        subscription.consumerFlow(this, numberOfBlockedPermits);
    }
}
Also used : MessageIdData(org.apache.pulsar.common.api.proto.MessageIdData) LongPair(org.apache.pulsar.common.util.collections.ConcurrentLongLongPairHashMap.LongPair) PositionImpl(org.apache.bookkeeper.mledger.impl.PositionImpl)

Example 18 with MessageIdData

use of org.apache.pulsar.common.api.proto.MessageIdData in project pulsar by apache.

the class CompactedOutBatchMessageTest method testCompactedOutMessages.

@Test
public void testCompactedOutMessages() throws Exception {
    final String topic1 = "persistent://my-property/my-ns/my-topic";
    BrokerEntryMetadata brokerEntryMetadata = new BrokerEntryMetadata().setBrokerTimestamp(1).setBrokerTimestamp(1);
    MessageMetadata metadata = new MessageMetadata().setProducerName("foobar").setSequenceId(1).setPublishTime(1).setNumMessagesInBatch(3);
    // build a buffer with 4 messages, first and last compacted out
    ByteBuf batchBuffer = Unpooled.buffer(1000);
    Commands.serializeSingleMessageInBatchWithPayload(new SingleMessageMetadata().setCompactedOut(true).setPartitionKey("key1"), Unpooled.EMPTY_BUFFER, batchBuffer);
    Commands.serializeSingleMessageInBatchWithPayload(new SingleMessageMetadata().setCompactedOut(true).setPartitionKey("key2"), Unpooled.EMPTY_BUFFER, batchBuffer);
    Commands.serializeSingleMessageInBatchWithPayload(new SingleMessageMetadata().setCompactedOut(false).setPartitionKey("key3"), Unpooled.EMPTY_BUFFER, batchBuffer);
    Commands.serializeSingleMessageInBatchWithPayload(new SingleMessageMetadata().setCompactedOut(true).setPartitionKey("key4"), Unpooled.EMPTY_BUFFER, batchBuffer);
    try (ConsumerImpl<byte[]> consumer = (ConsumerImpl<byte[]>) pulsarClient.newConsumer().topic(topic1).subscriptionName("my-subscriber-name").subscribe()) {
        // shove it in the sideways
        consumer.receiveIndividualMessagesFromBatch(brokerEntryMetadata, metadata, 0, null, batchBuffer, new MessageIdData().setLedgerId(1234).setEntryId(567), consumer.cnx(), DEFAULT_CONSUMER_EPOCH);
        Message<?> m = consumer.receive();
        assertEquals(((BatchMessageIdImpl) m.getMessageId()).getLedgerId(), 1234);
        assertEquals(((BatchMessageIdImpl) m.getMessageId()).getEntryId(), 567);
        assertEquals(((BatchMessageIdImpl) m.getMessageId()).getBatchIndex(), 2);
        assertEquals(m.getKey(), "key3");
        assertEquals(consumer.numMessagesInQueue(), 0);
    }
}
Also used : MessageMetadata(org.apache.pulsar.common.api.proto.MessageMetadata) SingleMessageMetadata(org.apache.pulsar.common.api.proto.SingleMessageMetadata) SingleMessageMetadata(org.apache.pulsar.common.api.proto.SingleMessageMetadata) MessageIdData(org.apache.pulsar.common.api.proto.MessageIdData) BrokerEntryMetadata(org.apache.pulsar.common.api.proto.BrokerEntryMetadata) ByteBuf(io.netty.buffer.ByteBuf) Test(org.testng.annotations.Test)

Example 19 with MessageIdData

use of org.apache.pulsar.common.api.proto.MessageIdData in project pulsar by apache.

the class RawMessageSerDeserTest method testSerializationAndDeserialization.

@Test
public void testSerializationAndDeserialization() {
    int payload = 0xbeefcafe;
    ByteBuf headersAndPayload = Unpooled.buffer(4);
    headersAndPayload.writeInt(payload);
    MessageIdData id = new MessageIdData().setLedgerId(0xf00).setEntryId(0xbaa).setPartition(10).setBatchIndex(20);
    @Cleanup RawMessage m = new RawMessageImpl(id, headersAndPayload);
    ByteBuf serialized = m.serialize();
    byte[] bytes = new byte[serialized.readableBytes()];
    serialized.readBytes(bytes);
    RawMessage m2 = RawMessageImpl.deserializeFrom(Unpooled.wrappedBuffer(bytes));
    Assert.assertEquals(m2.getMessageIdData().getLedgerId(), m.getMessageIdData().getLedgerId());
    Assert.assertEquals(m2.getMessageIdData().getEntryId(), m.getMessageIdData().getEntryId());
    Assert.assertEquals(m2.getMessageIdData().getPartition(), m.getMessageIdData().getPartition());
    Assert.assertEquals(m2.getMessageIdData().getBatchIndex(), m.getMessageIdData().getBatchIndex());
    Assert.assertEquals(m2.getHeadersAndPayload(), m.getHeadersAndPayload());
}
Also used : MessageIdData(org.apache.pulsar.common.api.proto.MessageIdData) ByteBuf(io.netty.buffer.ByteBuf) RawMessage(org.apache.pulsar.client.api.RawMessage) Cleanup(lombok.Cleanup) Test(org.testng.annotations.Test)

Example 20 with MessageIdData

use of org.apache.pulsar.common.api.proto.MessageIdData in project pulsar by apache.

the class CompactedTopicTest method buildCompactedLedger.

/**
 * Build a compacted ledger, and return the id of the ledger, the position of the different
 * entries in the ledger, and a list of gaps, and the entry which should be returned after the gap.
 */
private Triple<Long, List<Pair<MessageIdData, Long>>, List<Pair<MessageIdData, Long>>> buildCompactedLedger(BookKeeper bk, int count) throws Exception {
    LedgerHandle lh = bk.createLedger(1, 1, Compactor.COMPACTED_TOPIC_LEDGER_DIGEST_TYPE, Compactor.COMPACTED_TOPIC_LEDGER_PASSWORD);
    List<Pair<MessageIdData, Long>> positions = new ArrayList<>();
    List<Pair<MessageIdData, Long>> idsInGaps = new ArrayList<>();
    AtomicLong ledgerIds = new AtomicLong(10L);
    AtomicLong entryIds = new AtomicLong(0L);
    CompletableFuture.allOf(IntStream.range(0, count).mapToObj((i) -> {
        List<MessageIdData> idsInGap = new ArrayList<>();
        if (r.nextInt(10) == 1) {
            long delta = r.nextInt(10) + 1;
            idsInGap.add(new MessageIdData().setLedgerId(ledgerIds.get()).setEntryId(entryIds.get() + 1));
            ledgerIds.addAndGet(delta);
            entryIds.set(0);
        }
        long delta = r.nextInt(5);
        if (delta != 0) {
            idsInGap.add(new MessageIdData().setLedgerId(ledgerIds.get()).setEntryId(entryIds.get() + 1));
        }
        MessageIdData id = new MessageIdData().setLedgerId(ledgerIds.get()).setEntryId(entryIds.addAndGet(delta + 1));
        @Cleanup RawMessage m = new RawMessageImpl(id, Unpooled.EMPTY_BUFFER);
        CompletableFuture<Void> f = new CompletableFuture<>();
        ByteBuf buffer = m.serialize();
        lh.asyncAddEntry(buffer, (rc, ledger, eid, ctx) -> {
            if (rc != BKException.Code.OK) {
                f.completeExceptionally(BKException.create(rc));
            } else {
                positions.add(Pair.of(id, eid));
                idsInGap.forEach((gid) -> idsInGaps.add(Pair.of(gid, eid)));
                f.complete(null);
            }
        }, null);
        return f;
    }).toArray(CompletableFuture[]::new)).get();
    lh.close();
    return Triple.of(lh.getId(), positions, idsInGaps);
}
Also used : COMPACTION_SUBSCRIPTION(org.apache.pulsar.compaction.Compactor.COMPACTION_SUBSCRIPTION) Topic(org.apache.pulsar.broker.service.Topic) RawMessage(org.apache.pulsar.client.api.RawMessage) MessageIdData(org.apache.pulsar.common.api.proto.MessageIdData) Producer(org.apache.pulsar.client.api.Producer) Cleanup(lombok.Cleanup) Random(java.util.Random) Test(org.testng.annotations.Test) ClusterData(org.apache.pulsar.common.policies.data.ClusterData) AfterMethod(org.testng.annotations.AfterMethod) ReaderImpl(org.apache.pulsar.client.impl.ReaderImpl) Unpooled(io.netty.buffer.Unpooled) Pair(org.apache.commons.lang3.tuple.Pair) Triple(org.apache.commons.lang3.tuple.Triple) LedgerHandle(org.apache.bookkeeper.client.LedgerHandle) PositionImpl(org.apache.bookkeeper.mledger.impl.PositionImpl) BeforeMethod(org.testng.annotations.BeforeMethod) UUID(java.util.UUID) BookKeeper(org.apache.bookkeeper.client.BookKeeper) Sets(com.google.common.collect.Sets) BKException(org.apache.bookkeeper.client.BKException) MockedPulsarServiceBaseTest(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest) List(java.util.List) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) FutureUtil(org.apache.pulsar.common.util.FutureUtil) Optional(java.util.Optional) PersistentTopicInternalStats(org.apache.pulsar.common.policies.data.PersistentTopicInternalStats) TenantInfoImpl(org.apache.pulsar.common.policies.data.TenantInfoImpl) Awaitility(org.awaitility.Awaitility) IntStream(java.util.stream.IntStream) RawMessageImpl(org.apache.pulsar.client.impl.RawMessageImpl) DataProvider(org.testng.annotations.DataProvider) CompletableFuture(java.util.concurrent.CompletableFuture) Message(org.apache.pulsar.client.api.Message) ArrayList(java.util.ArrayList) ProducerBuilder(org.apache.pulsar.client.api.ProducerBuilder) ByteBuf(io.netty.buffer.ByteBuf) Charset(java.nio.charset.Charset) Assert(org.testng.Assert) LongRunningProcessStatus(org.apache.pulsar.client.admin.LongRunningProcessStatus) ManagedLedgerImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl) PulsarAdminException(org.apache.pulsar.client.admin.PulsarAdminException) Reader(org.apache.pulsar.client.api.Reader) Schema(org.apache.pulsar.client.api.Schema) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) AsyncLoadingCache(com.github.benmanes.caffeine.cache.AsyncLoadingCache) MessageId(org.apache.pulsar.client.api.MessageId) Collections(java.util.Collections) RawMessageImpl(org.apache.pulsar.client.impl.RawMessageImpl) LedgerHandle(org.apache.bookkeeper.client.LedgerHandle) MessageIdData(org.apache.pulsar.common.api.proto.MessageIdData) ArrayList(java.util.ArrayList) ByteBuf(io.netty.buffer.ByteBuf) AtomicLong(java.util.concurrent.atomic.AtomicLong) CompletableFuture(java.util.concurrent.CompletableFuture) List(java.util.List) ArrayList(java.util.ArrayList) RawMessage(org.apache.pulsar.client.api.RawMessage) Pair(org.apache.commons.lang3.tuple.Pair)

Aggregations

MessageIdData (org.apache.pulsar.common.api.proto.MessageIdData)24 ByteBuf (io.netty.buffer.ByteBuf)12 CompletableFuture (java.util.concurrent.CompletableFuture)8 PositionImpl (org.apache.bookkeeper.mledger.impl.PositionImpl)8 ArrayList (java.util.ArrayList)7 Collections (java.util.Collections)6 List (java.util.List)6 MessageId (org.apache.pulsar.client.api.MessageId)6 FutureUtil (org.apache.pulsar.common.util.FutureUtil)6 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)5 Map (java.util.Map)5 Objects (java.util.Objects)5 AtomicLong (java.util.concurrent.atomic.AtomicLong)5 Collectors (java.util.stream.Collectors)5 PersistentTopic (org.apache.pulsar.broker.service.persistent.PersistentTopic)5 PulsarClientException (org.apache.pulsar.client.api.PulsarClientException)5 CommandAck (org.apache.pulsar.common.api.proto.CommandAck)5 InitialPosition (org.apache.pulsar.common.api.proto.CommandSubscribe.InitialPosition)5 MessageMetadata (org.apache.pulsar.common.api.proto.MessageMetadata)5 IOException (java.io.IOException)4