Search in sources :

Example 11 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project pulsar by yahoo.

the class BatchMessageTest method testBatchAndNonBatchCumulativeAcks.

@Test
public void testBatchAndNonBatchCumulativeAcks() throws Exception {
    int numMsgs = 50;
    int numMsgsInBatch = numMsgs / 10;
    final String topicName = "persistent://prop/use/ns-abc/testBatchAndNonBatchCumulativeAcks";
    final String subscriptionName = "bnb-sub-1";
    Consumer consumer = pulsarClient.subscribe(topicName, subscriptionName);
    consumer.close();
    ProducerConfiguration producerConf = new ProducerConfiguration();
    producerConf.setBatchingMaxPublishDelay(5000, TimeUnit.MILLISECONDS);
    producerConf.setBatchingMaxMessages(numMsgsInBatch);
    producerConf.setBatchingEnabled(true);
    Producer producer = pulsarClient.createProducer(topicName, producerConf);
    // create producer to publish non batch messages
    Producer noBatchProducer = pulsarClient.createProducer(topicName);
    List<CompletableFuture<MessageId>> sendFutureList = Lists.newArrayList();
    for (int i = 0; i < numMsgs / 2; i++) {
        byte[] message = ("msg-" + i).getBytes();
        Message msg = MessageBuilder.create().setContent(message).build();
        sendFutureList.add(producer.sendAsync(msg));
        byte[] nobatchmsg = ("nobatch-" + i).getBytes();
        msg = MessageBuilder.create().setContent(nobatchmsg).build();
        sendFutureList.add(noBatchProducer.sendAsync(msg));
    }
    FutureUtil.waitForAll(sendFutureList).get();
    PersistentTopic topic = (PersistentTopic) pulsar.getBrokerService().getTopicReference(topicName);
    rolloverPerIntervalStats();
    assertTrue(topic.getProducers().values().iterator().next().getStats().msgRateIn > 0.0);
    assertEquals(topic.getPersistentSubscription(subscriptionName).getNumberOfEntriesInBacklog(), (numMsgs / 2) / numMsgsInBatch + numMsgs / 2);
    consumer = pulsarClient.subscribe(topicName, subscriptionName);
    Message lastunackedMsg = null;
    for (int i = 0; i < numMsgs; i++) {
        Message msg = consumer.receive(5, TimeUnit.SECONDS);
        assertNotNull(msg);
        LOG.info("[{}] got message position{} data {}", subscriptionName, msg.getMessageId(), String.valueOf(msg.getData()));
        if (i % 2 == 0) {
            lastunackedMsg = msg;
        } else {
            consumer.acknowledgeCumulative(msg);
            LOG.info("[{}] did cumulative ack on position{} ", subscriptionName, msg.getMessageId());
        }
    }
    if (lastunackedMsg != null) {
        consumer.acknowledgeCumulative(lastunackedMsg);
    }
    Thread.sleep(100);
    assertEquals(topic.getPersistentSubscription(subscriptionName).getNumberOfEntriesInBacklog(), 0);
    assertTrue(((ConsumerImpl) consumer).isBatchingAckTrackerEmpty());
    consumer.close();
    producer.close();
    noBatchProducer.close();
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) Consumer(com.yahoo.pulsar.client.api.Consumer) Producer(com.yahoo.pulsar.client.api.Producer) Message(com.yahoo.pulsar.client.api.Message) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) ProducerConfiguration(com.yahoo.pulsar.client.api.ProducerConfiguration) Test(org.testng.annotations.Test)

Example 12 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project pulsar by yahoo.

the class BatchMessageTest method testSimpleBatchProducerWithFixedBatchSize.

@Test(dataProvider = "codec")
public void testSimpleBatchProducerWithFixedBatchSize(CompressionType compressionType) throws Exception {
    int numMsgs = 50;
    int numMsgsInBatch = numMsgs / 2;
    final String topicName = "persistent://prop/use/ns-abc/testSimpleBatchProducerWithFixedBatchSize";
    final String subscriptionName = "sub-1" + compressionType.toString();
    Consumer consumer = pulsarClient.subscribe(topicName, subscriptionName);
    consumer.close();
    ProducerConfiguration producerConf = new ProducerConfiguration();
    producerConf.setCompressionType(compressionType);
    producerConf.setBatchingMaxPublishDelay(5000, TimeUnit.MILLISECONDS);
    producerConf.setBatchingMaxMessages(numMsgsInBatch);
    producerConf.setBatchingEnabled(true);
    Producer producer = pulsarClient.createProducer(topicName, producerConf);
    List<CompletableFuture<MessageId>> sendFutureList = Lists.newArrayList();
    for (int i = 0; i < numMsgs; i++) {
        byte[] message = ("my-message-" + i).getBytes();
        Message msg = MessageBuilder.create().setContent(message).build();
        sendFutureList.add(producer.sendAsync(msg));
    }
    FutureUtil.waitForAll(sendFutureList).get();
    PersistentTopic topic = (PersistentTopic) pulsar.getBrokerService().getTopicReference(topicName);
    rolloverPerIntervalStats();
    assertTrue(topic.getProducers().values().iterator().next().getStats().msgRateIn > 0.0);
    // we expect 2 messages in the backlog since we sent 50 messages with the batch size set to 25. We have set the
    // batch time high enough for it to not affect the number of messages in the batch
    assertEquals(topic.getPersistentSubscription(subscriptionName).getNumberOfEntriesInBacklog(), 2);
    consumer = pulsarClient.subscribe(topicName, subscriptionName);
    for (int i = 0; i < numMsgs; i++) {
        Message msg = consumer.receive(5, TimeUnit.SECONDS);
        assertNotNull(msg);
        String receivedMessage = new String(msg.getData());
        String expectedMessage = "my-message-" + i;
        Assert.assertEquals(receivedMessage, expectedMessage, "Received message " + receivedMessage + " did not match the expected message " + expectedMessage);
    }
    consumer.close();
    producer.close();
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) Consumer(com.yahoo.pulsar.client.api.Consumer) Producer(com.yahoo.pulsar.client.api.Producer) Message(com.yahoo.pulsar.client.api.Message) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) ProducerConfiguration(com.yahoo.pulsar.client.api.ProducerConfiguration) Test(org.testng.annotations.Test)

Example 13 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project pulsar by yahoo.

the class PersistentTopicTest method setupMLAsyncCallbackMocks.

void setupMLAsyncCallbackMocks() {
    ledgerMock = mock(ManagedLedger.class);
    cursorMock = mock(ManagedCursor.class);
    final CompletableFuture<Void> closeFuture = new CompletableFuture<>();
    doReturn(new ArrayList<Object>()).when(ledgerMock).getCursors();
    doReturn("mockCursor").when(cursorMock).getName();
    // doNothing().when(cursorMock).asyncClose(new CloseCallback() {
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            // return closeFuture.get();
            return closeFuture.complete(null);
        }
    }).when(cursorMock).asyncClose(new CloseCallback() {

        @Override
        public void closeComplete(Object ctx) {
            log.info("[{}] Successfully closed cursor ledger", "mockCursor");
            closeFuture.complete(null);
        }

        @Override
        public void closeFailed(ManagedLedgerException exception, Object ctx) {
            // isFenced.set(false);
            log.error("Error closing cursor for subscription", exception);
            closeFuture.completeExceptionally(new BrokerServiceException.PersistenceException(exception));
        }
    }, null);
    // call openLedgerComplete with ledgerMock on ML factory asyncOpen
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((OpenLedgerCallback) invocationOnMock.getArguments()[2]).openLedgerComplete(ledgerMock, null);
            return null;
        }
    }).when(mlFactoryMock).asyncOpen(matches(".*success.*"), any(ManagedLedgerConfig.class), any(OpenLedgerCallback.class), anyObject());
    // call openLedgerFailed on ML factory asyncOpen
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((OpenLedgerCallback) invocationOnMock.getArguments()[2]).openLedgerFailed(new ManagedLedgerException("Managed ledger failure"), null);
            return null;
        }
    }).when(mlFactoryMock).asyncOpen(matches(".*fail.*"), any(ManagedLedgerConfig.class), any(OpenLedgerCallback.class), anyObject());
    // call addComplete on ledger asyncAddEntry
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((AddEntryCallback) invocationOnMock.getArguments()[1]).addComplete(new PositionImpl(1, 1), invocationOnMock.getArguments()[2]);
            return null;
        }
    }).when(ledgerMock).asyncAddEntry(any(ByteBuf.class), any(AddEntryCallback.class), anyObject());
    // call openCursorComplete on cursor asyncOpen
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((OpenCursorCallback) invocationOnMock.getArguments()[1]).openCursorComplete(cursorMock, null);
            return null;
        }
    }).when(ledgerMock).asyncOpenCursor(matches(".*success.*"), any(OpenCursorCallback.class), anyObject());
    // call deleteLedgerComplete on ledger asyncDelete
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((DeleteLedgerCallback) invocationOnMock.getArguments()[0]).deleteLedgerComplete(null);
            return null;
        }
    }).when(ledgerMock).asyncDelete(any(DeleteLedgerCallback.class), anyObject());
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((DeleteCursorCallback) invocationOnMock.getArguments()[1]).deleteCursorComplete(null);
            return null;
        }
    }).when(ledgerMock).asyncDeleteCursor(matches(".*success.*"), any(DeleteCursorCallback.class), anyObject());
}
Also used : ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) CloseCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.CloseCallback) PositionImpl(org.apache.bookkeeper.mledger.impl.PositionImpl) ByteBuf(io.netty.buffer.ByteBuf) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Answer(org.mockito.stubbing.Answer) CompletableFuture(java.util.concurrent.CompletableFuture) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) OpenCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenCursorCallback) DeleteLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteLedgerCallback) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Matchers.anyObject(org.mockito.Matchers.anyObject) DeleteCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteCursorCallback) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback) AddEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback)

Example 14 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project pulsar by yahoo.

the class PersistentTopicTest method testCreateTopic.

@Test
public void testCreateTopic() throws Exception {
    final ManagedLedger ledgerMock = mock(ManagedLedger.class);
    doReturn(new ArrayList<Object>()).when(ledgerMock).getCursors();
    final String topicName = "persistent://prop/use/ns-abc/topic1";
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((OpenLedgerCallback) invocationOnMock.getArguments()[2]).openLedgerComplete(ledgerMock, null);
            return null;
        }
    }).when(mlFactoryMock).asyncOpen(anyString(), any(ManagedLedgerConfig.class), any(OpenLedgerCallback.class), anyObject());
    CompletableFuture<Void> future = brokerService.getTopic(topicName).thenAccept(topic -> {
        assertTrue(topic.toString().contains(topicName));
    }).exceptionally((t) -> {
        fail("should not fail");
        return null;
    });
    // wait for completion
    try {
        future.get(1, TimeUnit.SECONDS);
    } catch (Exception e) {
        fail("Should not fail or time out");
    }
}
Also used : SubType(com.yahoo.pulsar.common.api.proto.PulsarApi.CommandSubscribe.SubType) PersistentDispatcherMultipleConsumers(com.yahoo.pulsar.broker.service.persistent.PersistentDispatcherMultipleConsumers) NamespaceService(com.yahoo.pulsar.broker.namespace.NamespaceService) URL(java.net.URL) CloseCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.CloseCallback) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) Test(org.testng.annotations.Test) Policies(com.yahoo.pulsar.common.policies.data.Policies) AfterMethod(org.testng.annotations.AfterMethod) Unpooled(io.netty.buffer.Unpooled) Future(java.util.concurrent.Future) OpenCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenCursorCallback) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Mockito.atLeast(org.mockito.Mockito.atLeast) DeleteCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteCursorCallback) PulsarService(com.yahoo.pulsar.broker.PulsarService) PulsarClientImpl(com.yahoo.pulsar.client.impl.PulsarClientImpl) PulsarClient(com.yahoo.pulsar.client.api.PulsarClient) Mockito.doReturn(org.mockito.Mockito.doReturn) Assert.assertFalse(org.testng.Assert.assertFalse) Method(java.lang.reflect.Method) PositionImpl(org.apache.bookkeeper.mledger.impl.PositionImpl) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) ZooKeeper(org.apache.zookeeper.ZooKeeper) CyclicBarrier(java.util.concurrent.CyclicBarrier) PersistentSubscription(com.yahoo.pulsar.broker.service.persistent.PersistentSubscription) BeforeMethod(org.testng.annotations.BeforeMethod) Mockito.doNothing(org.mockito.Mockito.doNothing) InetSocketAddress(java.net.InetSocketAddress) Executors(java.util.concurrent.Executors) AddEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback) Matchers.any(org.mockito.Matchers.any) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) VerificationMode(org.mockito.verification.VerificationMode) CountDownLatch(java.util.concurrent.CountDownLatch) ManagedCursorImpl(org.apache.bookkeeper.mledger.impl.ManagedCursorImpl) AdminResource(com.yahoo.pulsar.broker.admin.AdminResource) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) Optional(java.util.Optional) CommandSubscribe(com.yahoo.pulsar.common.api.proto.PulsarApi.CommandSubscribe) Mockito.mock(org.mockito.Mockito.mock) DeleteLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteLedgerCallback) Assert.assertNull(org.testng.Assert.assertNull) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) Assert.assertEquals(org.testng.Assert.assertEquals) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) ConfigurationCacheService(com.yahoo.pulsar.broker.cache.ConfigurationCacheService) Mockito.spy(org.mockito.Mockito.spy) Matchers.anyString(org.mockito.Matchers.anyString) ProducerConfiguration(com.yahoo.pulsar.client.api.ProducerConfiguration) ArrayList(java.util.ArrayList) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ArgumentCaptor(org.mockito.ArgumentCaptor) Assert(org.testng.Assert) ByteBuf(io.netty.buffer.ByteBuf) Matchers.anyObject(org.mockito.Matchers.anyObject) ConcurrentOpenHashMap(com.yahoo.pulsar.common.util.collections.ConcurrentOpenHashMap) PowerMockito(org.powermock.api.mockito.PowerMockito) ExecutorService(java.util.concurrent.ExecutorService) NamespaceBundle(com.yahoo.pulsar.common.naming.NamespaceBundle) PersistentReplicator(com.yahoo.pulsar.broker.service.persistent.PersistentReplicator) Logger(org.slf4j.Logger) ZooKeeperDataCache(com.yahoo.pulsar.zookeeper.ZooKeeperDataCache) Matchers.matches(org.mockito.Matchers.matches) Assert.fail(org.testng.Assert.fail) PersistentDispatcherSingleActiveConsumer(com.yahoo.pulsar.broker.service.persistent.PersistentDispatcherSingleActiveConsumer) Mockito.when(org.mockito.Mockito.when) Field(java.lang.reflect.Field) Mockito.verify(org.mockito.Mockito.verify) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) MessageMetadata(com.yahoo.pulsar.common.api.proto.PulsarApi.MessageMetadata) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback) ServiceConfiguration(com.yahoo.pulsar.broker.ServiceConfiguration) Assert.assertTrue(org.testng.Assert.assertTrue) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) Matchers.anyString(org.mockito.Matchers.anyString) TimeoutException(java.util.concurrent.TimeoutException) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) ExecutionException(java.util.concurrent.ExecutionException) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Matchers.anyObject(org.mockito.Matchers.anyObject) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback) Test(org.testng.annotations.Test)

Example 15 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project pulsar by yahoo.

the class BatchMessageTest method testSimpleBatchProducerConsumer.

@Test(dataProvider = "codec")
public void testSimpleBatchProducerConsumer(CompressionType compressionType) throws Exception {
    int numMsgs = 500;
    int numMsgsInBatch = numMsgs / 20;
    final String topicName = "persistent://prop/use/ns-abc/testSimpleBatchProducerConsumer";
    final String subscriptionName = "pc-sub-1" + compressionType.toString();
    Consumer consumer = pulsarClient.subscribe(topicName, subscriptionName);
    consumer.close();
    ProducerConfiguration producerConf = new ProducerConfiguration();
    producerConf.setCompressionType(compressionType);
    producerConf.setBatchingMaxPublishDelay(5000, TimeUnit.MILLISECONDS);
    producerConf.setBatchingMaxMessages(numMsgsInBatch);
    producerConf.setBatchingEnabled(true);
    Producer producer = pulsarClient.createProducer(topicName, producerConf);
    List<CompletableFuture<MessageId>> sendFutureList = Lists.newArrayList();
    for (int i = 0; i < numMsgs; i++) {
        byte[] message = ("msg-" + i).getBytes();
        Message msg = MessageBuilder.create().setContent(message).build();
        sendFutureList.add(producer.sendAsync(msg));
    }
    FutureUtil.waitForAll(sendFutureList).get();
    PersistentTopic topic = (PersistentTopic) pulsar.getBrokerService().getTopicReference(topicName);
    rolloverPerIntervalStats();
    assertTrue(topic.getProducers().values().iterator().next().getStats().msgRateIn > 0.0);
    assertEquals(topic.getPersistentSubscription(subscriptionName).getNumberOfEntriesInBacklog(), numMsgs / numMsgsInBatch);
    consumer = pulsarClient.subscribe(topicName, subscriptionName);
    Message lastunackedMsg = null;
    for (int i = 0; i < numMsgs; i++) {
        Message msg = consumer.receive(5, TimeUnit.SECONDS);
        assertNotNull(msg);
        if (i % 2 == 0) {
            consumer.acknowledgeCumulative(msg);
        } else {
            lastunackedMsg = msg;
        }
    }
    if (lastunackedMsg != null) {
        consumer.acknowledgeCumulative(lastunackedMsg);
    }
    Thread.sleep(100);
    assertEquals(topic.getPersistentSubscription(subscriptionName).getNumberOfEntriesInBacklog(), 0);
    consumer.close();
    producer.close();
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) Consumer(com.yahoo.pulsar.client.api.Consumer) Producer(com.yahoo.pulsar.client.api.Producer) Message(com.yahoo.pulsar.client.api.Message) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) ProducerConfiguration(com.yahoo.pulsar.client.api.ProducerConfiguration) Test(org.testng.annotations.Test)

Aggregations

CompletableFuture (java.util.concurrent.CompletableFuture)490 Test (org.junit.Test)152 ArrayList (java.util.ArrayList)88 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)77 List (java.util.List)75 UUID (java.util.UUID)62 Futures (io.pravega.common.concurrent.Futures)60 Map (java.util.Map)59 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)57 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)53 HashMap (java.util.HashMap)52 TimeUnit (java.util.concurrent.TimeUnit)52 Cleanup (lombok.Cleanup)49 Exceptions (io.pravega.common.Exceptions)48 Collectors (java.util.stream.Collectors)48 lombok.val (lombok.val)47 IOException (java.io.IOException)46 Duration (java.time.Duration)46 Slf4j (lombok.extern.slf4j.Slf4j)46 AtomicReference (java.util.concurrent.atomic.AtomicReference)45