Search in sources :

Example 1 with RawMessage

use of org.apache.pulsar.client.api.RawMessage in project incubator-pulsar by apache.

the class RawReaderTest method testFlowControl.

/**
 * Try to fill the receiver queue, and drain it multiple times
 */
@Test
public void testFlowControl() throws Exception {
    int numMessages = RawReaderImpl.DEFAULT_RECEIVER_QUEUE_SIZE * 5;
    String topic = "persistent://my-property/use/my-ns/my-raw-topic";
    publishMessages(topic, numMessages);
    RawReader reader = RawReader.create(pulsarClient, topic, subscription).get();
    List<Future<RawMessage>> futures = new ArrayList<>();
    Set<String> keys = new HashSet<>();
    // +1 to make sure we read past the end
    for (int i = 0; i < numMessages + 1; i++) {
        futures.add(reader.readNextAsync());
    }
    int timeouts = 0;
    for (Future<RawMessage> f : futures) {
        try (RawMessage m = f.get(1, TimeUnit.SECONDS)) {
            // Assert each key is unique
            Assert.assertTrue(keys.add(extractKey(m)));
        } catch (TimeoutException te) {
            timeouts++;
        }
    }
    Assert.assertEquals(timeouts, 1);
    Assert.assertEquals(keys.size(), numMessages);
}
Also used : RawReader(org.apache.pulsar.client.api.RawReader) ArrayList(java.util.ArrayList) Future(java.util.concurrent.Future) RawMessage(org.apache.pulsar.client.api.RawMessage) HashSet(java.util.HashSet) TimeoutException(java.util.concurrent.TimeoutException) Test(org.testng.annotations.Test) MockedPulsarServiceBaseTest(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest)

Example 2 with RawMessage

use of org.apache.pulsar.client.api.RawMessage in project incubator-pulsar by apache.

the class RawReaderTest method testBatchingExtractKeysAndIds.

@Test
public void testBatchingExtractKeysAndIds() throws Exception {
    String topic = "persistent://my-property/use/my-ns/my-raw-topic";
    try (Producer producer = pulsarClient.newProducer().topic(topic).maxPendingMessages(3).enableBatching(true).batchingMaxMessages(3).batchingMaxPublishDelay(1, TimeUnit.HOURS).create()) {
        producer.sendAsync(MessageBuilder.create().setKey("key1").setContent("my-content-1".getBytes()).build());
        producer.sendAsync(MessageBuilder.create().setKey("key2").setContent("my-content-2".getBytes()).build());
        producer.sendAsync(MessageBuilder.create().setKey("key3").setContent("my-content-3".getBytes()).build()).get();
    }
    RawReader reader = RawReader.create(pulsarClient, topic, subscription).get();
    try (RawMessage m = reader.readNextAsync().get()) {
        List<ImmutablePair<MessageId, String>> idsAndKeys = RawBatchConverter.extractIdsAndKeys(m);
        Assert.assertEquals(idsAndKeys.size(), 3);
        // assert message ids are in correct order
        Assert.assertTrue(idsAndKeys.get(0).getLeft().compareTo(idsAndKeys.get(1).getLeft()) < 0);
        Assert.assertTrue(idsAndKeys.get(1).getLeft().compareTo(idsAndKeys.get(2).getLeft()) < 0);
        // assert keys are as expected
        Assert.assertEquals(idsAndKeys.get(0).getRight(), "key1");
        Assert.assertEquals(idsAndKeys.get(1).getRight(), "key2");
        Assert.assertEquals(idsAndKeys.get(2).getRight(), "key3");
    } finally {
        reader.closeAsync().get();
    }
}
Also used : Producer(org.apache.pulsar.client.api.Producer) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) RawReader(org.apache.pulsar.client.api.RawReader) RawMessage(org.apache.pulsar.client.api.RawMessage) Test(org.testng.annotations.Test) MockedPulsarServiceBaseTest(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest)

Example 3 with RawMessage

use of org.apache.pulsar.client.api.RawMessage in project incubator-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<MessageIdData>();
        if (r.nextInt(10) == 1) {
            long delta = r.nextInt(10) + 1;
            idsInGap.add(MessageIdData.newBuilder().setLedgerId(ledgerIds.get()).setEntryId(entryIds.get() + 1).build());
            ledgerIds.addAndGet(delta);
            entryIds.set(0);
        }
        long delta = r.nextInt(5);
        if (delta != 0) {
            idsInGap.add(MessageIdData.newBuilder().setLedgerId(ledgerIds.get()).setEntryId(entryIds.get() + 1).build());
        }
        MessageIdData id = MessageIdData.newBuilder().setLedgerId(ledgerIds.get()).setEntryId(entryIds.addAndGet(delta + 1)).build();
        @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);
        buffer.release();
        return f;
    }).toArray(CompletableFuture[]::new)).get();
    lh.close();
    return Triple.of(lh.getId(), positions, idsInGaps);
}
Also used : IntStream(java.util.stream.IntStream) RawMessageImpl(org.apache.pulsar.client.impl.RawMessageImpl) RawMessage(org.apache.pulsar.client.api.RawMessage) Cleanup(lombok.Cleanup) Random(java.util.Random) CompletableFuture(java.util.concurrent.CompletableFuture) Test(org.testng.annotations.Test) ClusterData(org.apache.pulsar.common.policies.data.ClusterData) AfterMethod(org.testng.annotations.AfterMethod) ArrayList(java.util.ArrayList) Unpooled(io.netty.buffer.Unpooled) Lists(com.google.common.collect.Lists) Pair(org.apache.commons.lang3.tuple.Pair) Assert(org.testng.Assert) ByteBuf(io.netty.buffer.ByteBuf) Triple(org.apache.commons.lang3.tuple.Triple) LedgerHandle(org.apache.bookkeeper.client.LedgerHandle) PositionImpl(org.apache.bookkeeper.mledger.impl.PositionImpl) PropertyAdmin(org.apache.pulsar.common.policies.data.PropertyAdmin) BeforeMethod(org.testng.annotations.BeforeMethod) BookKeeper(org.apache.bookkeeper.client.BookKeeper) BKException(org.apache.bookkeeper.client.BKException) Sets(com.google.common.collect.Sets) AtomicLong(java.util.concurrent.atomic.AtomicLong) MockedPulsarServiceBaseTest(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest) List(java.util.List) AsyncLoadingCache(com.github.benmanes.caffeine.cache.AsyncLoadingCache) MessageIdData(org.apache.pulsar.common.api.proto.PulsarApi.MessageIdData) Collections(java.util.Collections) RawMessageImpl(org.apache.pulsar.client.impl.RawMessageImpl) LedgerHandle(org.apache.bookkeeper.client.LedgerHandle) MessageIdData(org.apache.pulsar.common.api.proto.PulsarApi.MessageIdData) ArrayList(java.util.ArrayList) ByteBuf(io.netty.buffer.ByteBuf) AtomicLong(java.util.concurrent.atomic.AtomicLong) CompletableFuture(java.util.concurrent.CompletableFuture) ArrayList(java.util.ArrayList) List(java.util.List) RawMessage(org.apache.pulsar.client.api.RawMessage) Pair(org.apache.commons.lang3.tuple.Pair)

Example 4 with RawMessage

use of org.apache.pulsar.client.api.RawMessage in project incubator-pulsar by apache.

the class ChecksumTest method verifyChecksumSentToConsumer.

@Test
public void verifyChecksumSentToConsumer() throws Exception {
    final String topicName = "persistent://prop/use/ns-abc/topic-1";
    Producer<byte[]> producer = pulsarClient.newProducer().topic(topicName).create();
    RawReader reader = RawReader.create(pulsarClient, topicName, "sub").get();
    producer.send("Hello".getBytes());
    RawMessage msg = reader.readNextAsync().get();
    ByteBuf b = msg.getHeadersAndPayload();
    assertTrue(Commands.hasChecksum(b));
    int parsedChecksum = Commands.readChecksum(b);
    int computedChecksum = Crc32cIntChecksum.computeChecksum(b);
    assertEquals(parsedChecksum, computedChecksum);
    producer.close();
    reader.closeAsync().get();
}
Also used : RawReader(org.apache.pulsar.client.api.RawReader) RawMessage(org.apache.pulsar.client.api.RawMessage) ByteBuf(io.netty.buffer.ByteBuf) Test(org.testng.annotations.Test)

Example 5 with RawMessage

use of org.apache.pulsar.client.api.RawMessage in project incubator-pulsar by apache.

the class CompactedTopicImpl method readOneMessageId.

private static CompletableFuture<MessageIdData> readOneMessageId(LedgerHandle lh, long entryId) {
    CompletableFuture<MessageIdData> promise = new CompletableFuture<>();
    lh.asyncReadEntries(entryId, entryId, (rc, _lh, seq, ctx) -> {
        if (rc != BKException.Code.OK) {
            promise.completeExceptionally(BKException.create(rc));
        } else {
            try (RawMessage m = RawMessageImpl.deserializeFrom(seq.nextElement().getEntryBuffer())) {
                promise.complete(m.getMessageIdData());
            } catch (NoSuchElementException e) {
                log.error("No such entry {} in ledger {}", entryId, lh.getId());
                promise.completeExceptionally(e);
            }
        }
    }, null);
    return promise;
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) MessageIdData(org.apache.pulsar.common.api.proto.PulsarApi.MessageIdData) RawMessage(org.apache.pulsar.client.api.RawMessage) NoSuchElementException(java.util.NoSuchElementException)

Aggregations

RawMessage (org.apache.pulsar.client.api.RawMessage)16 Test (org.testng.annotations.Test)11 RawReader (org.apache.pulsar.client.api.RawReader)10 ByteBuf (io.netty.buffer.ByteBuf)8 MockedPulsarServiceBaseTest (org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest)8 MessageId (org.apache.pulsar.client.api.MessageId)7 ArrayList (java.util.ArrayList)6 HashSet (java.util.HashSet)4 CompletableFuture (java.util.concurrent.CompletableFuture)4 HashMap (java.util.HashMap)3 List (java.util.List)3 Future (java.util.concurrent.Future)3 TimeoutException (java.util.concurrent.TimeoutException)3 BookKeeper (org.apache.bookkeeper.client.BookKeeper)3 LedgerHandle (org.apache.bookkeeper.client.LedgerHandle)3 MessageIdData (org.apache.pulsar.common.api.proto.PulsarApi.MessageIdData)3 Lists (com.google.common.collect.Lists)2 Sets (com.google.common.collect.Sets)2 IOException (java.io.IOException)2 Collections (java.util.Collections)2