Search in sources :

Example 11 with MessageMetadata

use of org.apache.pulsar.common.api.proto.PulsarApi.MessageMetadata in project incubator-pulsar by apache.

the class ServerCnxTest method testSendFailureOnEncryptionRequiredTopic.

@Test(timeOut = 30000)
public void testSendFailureOnEncryptionRequiredTopic() throws Exception {
    resetChannel();
    setChannelConnected();
    // Set encryption_required to true
    ZooKeeperDataCache<Policies> zkDataCache = mock(ZooKeeperDataCache.class);
    Policies policies = mock(Policies.class);
    policies.encryption_required = true;
    policies.clusterDispatchRate = Maps.newHashMap();
    doReturn(Optional.of(policies)).when(zkDataCache).get(AdminResource.path(POLICIES, TopicName.get(encryptionRequiredTopicName).getNamespace()));
    doReturn(CompletableFuture.completedFuture(Optional.of(policies))).when(zkDataCache).getAsync(AdminResource.path(POLICIES, TopicName.get(encryptionRequiredTopicName).getNamespace()));
    doReturn(zkDataCache).when(configCacheService).policiesCache();
    ByteBuf clientCommand = Commands.newProducer(encryptionRequiredTopicName, 1, /* producer id */
    1, /* request id */
    "prod-name", true, null);
    channel.writeInbound(clientCommand);
    assertTrue(getResponse() instanceof CommandProducerSuccess);
    // test failure case: unencrypted messages cannot be published
    MessageMetadata messageMetadata = MessageMetadata.newBuilder().setPublishTime(System.currentTimeMillis()).setProducerName("prod-name").setSequenceId(0).build();
    ByteBuf data = Unpooled.buffer(1024);
    clientCommand = ByteBufPair.coalesce(Commands.newSend(1, 0, 1, ChecksumType.None, messageMetadata, data));
    channel.writeInbound(Unpooled.copiedBuffer(clientCommand));
    clientCommand.release();
    assertTrue(getResponse() instanceof CommandSendError);
    channel.finish();
}
Also used : MessageMetadata(org.apache.pulsar.common.api.proto.PulsarApi.MessageMetadata) Policies(org.apache.pulsar.common.policies.data.Policies) CommandProducerSuccess(org.apache.pulsar.common.api.proto.PulsarApi.CommandProducerSuccess) ByteBuf(io.netty.buffer.ByteBuf) CommandSendError(org.apache.pulsar.common.api.proto.PulsarApi.CommandSendError) Test(org.testng.annotations.Test)

Example 12 with MessageMetadata

use of org.apache.pulsar.common.api.proto.PulsarApi.MessageMetadata in project incubator-pulsar by apache.

the class PersistentTopicTest method testPublishMessageMLFailure.

@Test
public void testPublishMessageMLFailure() throws Exception {
    final String successTopicName = "persistent://prop/use/ns-abc/successTopic";
    final ManagedLedger ledgerMock = mock(ManagedLedger.class);
    doReturn(new ArrayList<Object>()).when(ledgerMock).getCursors();
    PersistentTopic topic = new PersistentTopic(successTopicName, ledgerMock, brokerService);
    MessageMetadata.Builder messageMetadata = MessageMetadata.newBuilder();
    messageMetadata.setPublishTime(System.currentTimeMillis());
    messageMetadata.setProducerName("prod-name");
    messageMetadata.setSequenceId(1);
    ByteBuf payload = Unpooled.wrappedBuffer("content".getBytes());
    final CountDownLatch latch = new CountDownLatch(1);
    // override asyncAddEntry callback to return error
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((AddEntryCallback) invocationOnMock.getArguments()[1]).addFailed(new ManagedLedgerException("Managed ledger failure"), invocationOnMock.getArguments()[2]);
            return null;
        }
    }).when(ledgerMock).asyncAddEntry(any(ByteBuf.class), any(AddEntryCallback.class), anyObject());
    topic.publishMessage(payload, (exception, ledgerId, entryId) -> {
        if (exception == null) {
            fail("publish should have failed");
        } else {
            latch.countDown();
        }
    });
    assertTrue(latch.await(1, TimeUnit.SECONDS));
}
Also used : ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) Matchers.anyString(org.mockito.Matchers.anyString) ByteBuf(io.netty.buffer.ByteBuf) CountDownLatch(java.util.concurrent.CountDownLatch) MessageMetadata(org.apache.pulsar.common.api.proto.PulsarApi.MessageMetadata) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) InvocationOnMock(org.mockito.invocation.InvocationOnMock) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) Matchers.anyObject(org.mockito.Matchers.anyObject) AddEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback) Test(org.testng.annotations.Test)

Example 13 with MessageMetadata

use of org.apache.pulsar.common.api.proto.PulsarApi.MessageMetadata in project incubator-pulsar by apache.

the class RawBatchConverter method rebatchMessage.

/**
 * Take a batched message and a filter, and returns a message with the only the submessages
 * which match the filter. Returns an empty optional if no messages match.
 *
 * This takes ownership of the passes in message, and if the returned optional is not empty,
 * the ownership of that message is returned also.
 */
public static Optional<RawMessage> rebatchMessage(RawMessage msg, BiPredicate<String, MessageId> filter) throws IOException {
    checkArgument(msg.getMessageIdData().getBatchIndex() == -1);
    ByteBuf payload = msg.getHeadersAndPayload();
    MessageMetadata metadata = Commands.parseMessageMetadata(payload);
    ByteBuf batchBuffer = PooledByteBufAllocator.DEFAULT.buffer(payload.capacity());
    try {
        int batchSize = metadata.getNumMessagesInBatch();
        int messagesRetained = 0;
        SingleMessageMetadata.Builder emptyMetadataBuilder = SingleMessageMetadata.newBuilder().setCompactedOut(true);
        for (int i = 0; i < batchSize; i++) {
            SingleMessageMetadata.Builder singleMessageMetadataBuilder = SingleMessageMetadata.newBuilder();
            ByteBuf singleMessagePayload = Commands.deSerializeSingleMessageInBatch(payload, singleMessageMetadataBuilder, 0, batchSize);
            String key = singleMessageMetadataBuilder.getPartitionKey();
            MessageId id = new BatchMessageIdImpl(msg.getMessageIdData().getLedgerId(), msg.getMessageIdData().getEntryId(), msg.getMessageIdData().getPartition(), i);
            if (filter.test(key, id)) {
                messagesRetained++;
                Commands.serializeSingleMessageInBatchWithPayload(singleMessageMetadataBuilder, singleMessagePayload, batchBuffer);
            } else {
                Commands.serializeSingleMessageInBatchWithPayload(emptyMetadataBuilder, Unpooled.EMPTY_BUFFER, batchBuffer);
            }
            singleMessageMetadataBuilder.recycle();
            singleMessagePayload.release();
        }
        emptyMetadataBuilder.recycle();
        if (messagesRetained > 0) {
            ByteBuf metadataAndPayload = Commands.serializeMetadataAndPayload(Commands.ChecksumType.Crc32c, metadata, batchBuffer);
            return Optional.of(new RawMessageImpl(msg.getMessageIdData(), metadataAndPayload));
        } else {
            return Optional.empty();
        }
    } finally {
        batchBuffer.release();
        metadata.recycle();
        msg.close();
    }
}
Also used : SingleMessageMetadata(org.apache.pulsar.common.api.proto.PulsarApi.SingleMessageMetadata) MessageMetadata(org.apache.pulsar.common.api.proto.PulsarApi.MessageMetadata) SingleMessageMetadata(org.apache.pulsar.common.api.proto.PulsarApi.SingleMessageMetadata) BatchMessageIdImpl(org.apache.pulsar.client.impl.BatchMessageIdImpl) ByteBuf(io.netty.buffer.ByteBuf) MessageId(org.apache.pulsar.client.api.MessageId)

Example 14 with MessageMetadata

use of org.apache.pulsar.common.api.proto.PulsarApi.MessageMetadata in project incubator-pulsar by apache.

the class RawBatchConverter method isBatch.

public static boolean isBatch(RawMessage msg) {
    ByteBuf payload = msg.getHeadersAndPayload();
    MessageMetadata metadata = Commands.parseMessageMetadata(payload);
    int batchSize = metadata.getNumMessagesInBatch();
    return batchSize > 1;
}
Also used : SingleMessageMetadata(org.apache.pulsar.common.api.proto.PulsarApi.SingleMessageMetadata) MessageMetadata(org.apache.pulsar.common.api.proto.PulsarApi.MessageMetadata) ByteBuf(io.netty.buffer.ByteBuf)

Example 15 with MessageMetadata

use of org.apache.pulsar.common.api.proto.PulsarApi.MessageMetadata in project incubator-pulsar by apache.

the class TwoPhaseCompactor method extractKey.

private static String extractKey(RawMessage m) {
    ByteBuf headersAndPayload = m.getHeadersAndPayload();
    MessageMetadata msgMetadata = Commands.parseMessageMetadata(headersAndPayload);
    return msgMetadata.getPartitionKey();
}
Also used : MessageMetadata(org.apache.pulsar.common.api.proto.PulsarApi.MessageMetadata) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

MessageMetadata (org.apache.pulsar.common.api.proto.PulsarApi.MessageMetadata)21 ByteBuf (io.netty.buffer.ByteBuf)15 Test (org.testng.annotations.Test)7 SingleMessageMetadata (org.apache.pulsar.common.api.proto.PulsarApi.SingleMessageMetadata)4 ManagedLedgerException (org.apache.bookkeeper.mledger.ManagedLedgerException)3 MessageId (org.apache.pulsar.client.api.MessageId)3 PulsarClientException (org.apache.pulsar.client.api.PulsarClientException)3 CommandProducerSuccess (org.apache.pulsar.common.api.proto.PulsarApi.CommandProducerSuccess)3 IOException (java.io.IOException)2 Entry (org.apache.bookkeeper.mledger.Entry)2 PersistentTopic (org.apache.pulsar.broker.service.persistent.PersistentTopic)2 PulsarAdminException (org.apache.pulsar.client.admin.PulsarAdminException)2 ByteBufPair (org.apache.pulsar.common.api.ByteBufPair)2 OutputStream (java.io.OutputStream)1 Field (java.lang.reflect.Field)1 ArrayList (java.util.ArrayList)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 ExecutionException (java.util.concurrent.ExecutionException)1 WebApplicationException (javax.ws.rs.WebApplicationException)1 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)1