Search in sources :

Example 6 with MessageId

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

the class PulsarKafkaConsumer method seek.

@Override
public void seek(TopicPartition partition, long offset) {
    MessageId msgId = MessageIdUtils.getMessageId(offset);
    org.apache.pulsar.client.api.Consumer<byte[]> c = consumers.get(partition);
    if (c == null) {
        throw new IllegalArgumentException("Cannot seek on a partition where we are not subscribed");
    }
    try {
        c.seek(msgId);
    } catch (PulsarClientException e) {
        throw new RuntimeException(e);
    }
}
Also used : PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) MessageId(org.apache.pulsar.client.api.MessageId)

Example 7 with MessageId

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

the class ServiceRequestManagerTest method testSubmitRequest.

@Test
public void testSubmitRequest() throws Exception {
    ServiceRequest request = ServiceRequest.newBuilder().build();
    MessageId msgId = mock(MessageId.class);
    when(producer.sendAsync(any(byte[].class))).thenReturn(CompletableFuture.completedFuture(msgId));
    CompletableFuture<MessageId> submitFuture = reqMgr.submitRequest(request);
    assertSame(msgId, submitFuture.get());
    verify(producer, times(1)).sendAsync(any(byte[].class));
}
Also used : ServiceRequest(org.apache.pulsar.functions.proto.Request.ServiceRequest) MessageId(org.apache.pulsar.client.api.MessageId) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 8 with MessageId

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

the class FunctionMetaDataManager method submit.

@VisibleForTesting
CompletableFuture<RequestResult> submit(Request.ServiceRequest serviceRequest) {
    ServiceRequestInfo serviceRequestInfo = ServiceRequestInfo.of(serviceRequest);
    CompletableFuture<MessageId> messageIdCompletableFuture = this.serviceRequestManager.submitRequest(serviceRequest);
    serviceRequestInfo.setCompletableFutureRequestMessageId(messageIdCompletableFuture);
    CompletableFuture<RequestResult> requestResultCompletableFuture = new CompletableFuture<>();
    serviceRequestInfo.setRequestResultCompletableFuture(requestResultCompletableFuture);
    this.pendingServiceRequests.put(serviceRequestInfo.getServiceRequest().getRequestId(), serviceRequestInfo);
    return requestResultCompletableFuture;
}
Also used : RequestResult(org.apache.pulsar.functions.worker.request.RequestResult) CompletableFuture(java.util.concurrent.CompletableFuture) ServiceRequestInfo(org.apache.pulsar.functions.worker.request.ServiceRequestInfo) MessageId(org.apache.pulsar.client.api.MessageId) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 9 with MessageId

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

the class FunctionsImpl method triggerFunction.

@POST
@Path("/{tenant}/{namespace}/{functionName}/trigger")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response triggerFunction(@PathParam("tenant") final String tenant, @PathParam("namespace") final String namespace, @PathParam("name") final String functionName, @FormDataParam("data") final String input, @FormDataParam("dataStream") final InputStream uploadedInputStream) {
    FunctionConfig functionConfig;
    // validate parameters
    try {
        validateTriggerRequestParams(tenant, namespace, functionName, input, uploadedInputStream);
    } catch (IllegalArgumentException e) {
        log.error("Invalid trigger function request @ /{}/{}/{}", tenant, namespace, functionName, e);
        return Response.status(Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON).entity(new ErrorData(e.getMessage())).build();
    }
    FunctionMetaDataManager functionMetaDataManager = worker().getFunctionMetaDataManager();
    if (!functionMetaDataManager.containsFunction(tenant, namespace, functionName)) {
        log.error("Function in getFunction does not exist @ /{}/{}/{}", tenant, namespace, functionName);
        return Response.status(Status.NOT_FOUND).type(MediaType.APPLICATION_JSON).entity(new ErrorData(String.format("Function %s doesn't exist", functionName))).build();
    }
    FunctionMetaData functionMetaData = functionMetaDataManager.getFunctionMetaData(tenant, namespace, functionName);
    String inputTopicToWrite;
    if (functionMetaData.getFunctionConfig().getInputsList().size() > 0) {
        inputTopicToWrite = functionMetaData.getFunctionConfig().getInputsList().get(0);
    } else {
        inputTopicToWrite = functionMetaData.getFunctionConfig().getCustomSerdeInputs().entrySet().iterator().next().getKey();
    }
    String outputTopic = functionMetaData.getFunctionConfig().getOutput();
    Reader reader = null;
    Producer producer = null;
    try {
        if (outputTopic != null && !outputTopic.isEmpty()) {
            reader = worker().getClient().newReader().topic(outputTopic).startMessageId(MessageId.latest).create();
        }
        producer = worker().getClient().newProducer().topic(inputTopicToWrite).create();
        byte[] targetArray;
        if (uploadedInputStream != null) {
            targetArray = new byte[uploadedInputStream.available()];
            uploadedInputStream.read(targetArray);
        } else {
            targetArray = input.getBytes();
        }
        MessageId msgId = producer.send(targetArray);
        if (reader == null) {
            return Response.status(Status.OK).build();
        }
        long curTime = System.currentTimeMillis();
        long maxTime = curTime + 1000;
        while (curTime < maxTime) {
            Message msg = reader.readNext(10000, TimeUnit.MILLISECONDS);
            if (msg == null)
                break;
            if (msg.getProperties().containsKey("__pfn_input_msg_id__") && msg.getProperties().containsKey("__pfn_input_topic__")) {
                MessageId newMsgId = MessageId.fromByteArray(Base64.getDecoder().decode((String) msg.getProperties().get("__pfn_input_msg_id__")));
                if (msgId.equals(newMsgId) && msg.getProperties().get("__pfn_input_topic__").equals(inputTopicToWrite)) {
                    return Response.status(Status.OK).entity(msg.getData()).build();
                }
            }
            curTime = System.currentTimeMillis();
        }
        return Response.status(Status.REQUEST_TIMEOUT).build();
    } catch (Exception e) {
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    } finally {
        if (reader != null) {
            reader.closeAsync();
        }
        if (producer != null) {
            producer.closeAsync();
        }
    }
}
Also used : FunctionConfig(org.apache.pulsar.functions.proto.Function.FunctionConfig) FunctionMetaData(org.apache.pulsar.functions.proto.Function.FunctionMetaData) Message(org.apache.pulsar.client.api.Message) Reader(org.apache.pulsar.client.api.Reader) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) Producer(org.apache.pulsar.client.api.Producer) FunctionMetaDataManager(org.apache.pulsar.functions.worker.FunctionMetaDataManager) ErrorData(org.apache.pulsar.common.policies.data.ErrorData) MessageId(org.apache.pulsar.client.api.MessageId) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 10 with MessageId

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

the class ConsumerImpl method internalGetLastMessageIdAsync.

private void internalGetLastMessageIdAsync(final Backoff backoff, final AtomicLong remainingTime, CompletableFuture<MessageId> future) {
    ClientCnx cnx = cnx();
    if (isConnected() && cnx != null) {
        if (!Commands.peerSupportsGetLastMessageId(cnx.getRemoteEndpointProtocolVersion())) {
            future.completeExceptionally(new PulsarClientException.NotSupportedException("GetLastMessageId Not supported for ProtocolVersion: " + cnx.getRemoteEndpointProtocolVersion()));
        }
        long requestId = client.newRequestId();
        ByteBuf getLastIdCmd = Commands.newGetLastMessageId(consumerId, requestId);
        log.info("[{}][{}] Get topic last message Id", topic, subscription);
        cnx.sendGetLastMessageId(getLastIdCmd, requestId).thenAccept((result) -> {
            log.info("[{}][{}] Successfully getLastMessageId {}:{}", topic, subscription, result.getLedgerId(), result.getEntryId());
            future.complete(new MessageIdImpl(result.getLedgerId(), result.getEntryId(), result.getPartition()));
        }).exceptionally(e -> {
            log.error("[{}][{}] Failed getLastMessageId command", topic, subscription);
            future.completeExceptionally(e.getCause());
            return null;
        });
    } else {
        long nextDelay = Math.min(backoff.next(), remainingTime.get());
        if (nextDelay <= 0) {
            future.completeExceptionally(new PulsarClientException.TimeoutException("Could not getLastMessageId within configured timeout."));
            return;
        }
        ((ScheduledExecutorService) listenerExecutor).schedule(() -> {
            log.warn("[{}] [{}] Could not get connection while getLastMessageId -- Will try again in {} ms", topic, getHandlerName(), nextDelay);
            remainingTime.addAndGet(-nextDelay);
            internalGetLastMessageIdAsync(backoff, remainingTime, future);
        }, nextDelay, TimeUnit.MILLISECONDS);
    }
}
Also used : PulsarApi(org.apache.pulsar.common.api.proto.PulsarApi) Commands.hasChecksum(org.apache.pulsar.common.api.Commands.hasChecksum) LoggerFactory(org.slf4j.LoggerFactory) AckType(org.apache.pulsar.common.api.proto.PulsarApi.CommandAck.AckType) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Map(java.util.Map) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) Crc32cIntChecksum.computeChecksum(com.scurrilous.circe.checksum.Crc32cIntChecksum.computeChecksum) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) PulsarDecoder(org.apache.pulsar.common.api.PulsarDecoder) Commands(org.apache.pulsar.common.api.Commands) Set(java.util.Set) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) Objects(java.util.Objects) Consumer(org.apache.pulsar.client.api.Consumer) List(java.util.List) FutureUtil(org.apache.pulsar.common.util.FutureUtil) MessageIdData(org.apache.pulsar.common.api.proto.PulsarApi.MessageIdData) CompressionCodec(org.apache.pulsar.common.compression.CompressionCodec) AtomicIntegerFieldUpdater(java.util.concurrent.atomic.AtomicIntegerFieldUpdater) ConsumerCryptoFailureAction(org.apache.pulsar.client.api.ConsumerCryptoFailureAction) Iterables(com.google.common.collect.Iterables) ConsumerConfigurationData(org.apache.pulsar.client.impl.conf.ConsumerConfigurationData) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) ProtocolVersion(org.apache.pulsar.common.api.proto.PulsarApi.ProtocolVersion) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) Message(org.apache.pulsar.client.api.Message) SubscriptionInitialPosition(org.apache.pulsar.client.api.SubscriptionInitialPosition) ArrayList(java.util.ArrayList) ConsumerStats(org.apache.pulsar.client.api.ConsumerStats) ByteBuf(io.netty.buffer.ByteBuf) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) CompressionCodecProvider(org.apache.pulsar.common.compression.CompressionCodecProvider) MessageMetadata(org.apache.pulsar.common.api.proto.PulsarApi.MessageMetadata) ExecutorService(java.util.concurrent.ExecutorService) Timeout(io.netty.util.Timeout) Logger(org.slf4j.Logger) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) IOException(java.io.IOException) SubscriptionType(org.apache.pulsar.client.api.SubscriptionType) Schema(org.apache.pulsar.client.api.Schema) Commands.readChecksum(org.apache.pulsar.common.api.Commands.readChecksum) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) ValidationError(org.apache.pulsar.common.api.proto.PulsarApi.CommandAck.ValidationError) AtomicLong(java.util.concurrent.atomic.AtomicLong) MessageId(org.apache.pulsar.client.api.MessageId) CompressionType(org.apache.pulsar.common.api.proto.PulsarApi.CompressionType) InitialPosition(org.apache.pulsar.common.api.proto.PulsarApi.CommandSubscribe.InitialPosition) Future(io.netty.util.concurrent.Future) Collections(java.util.Collections) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

MessageId (org.apache.pulsar.client.api.MessageId)65 Test (org.testng.annotations.Test)42 CompletableFuture (java.util.concurrent.CompletableFuture)25 Message (org.apache.pulsar.client.api.Message)22 PulsarClientException (org.apache.pulsar.client.api.PulsarClientException)16 List (java.util.List)14 TimeUnit (java.util.concurrent.TimeUnit)14 Producer (org.apache.pulsar.client.api.Producer)14 Future (java.util.concurrent.Future)13 Consumer (org.apache.pulsar.client.api.Consumer)13 MessageIdImpl (org.apache.pulsar.client.impl.MessageIdImpl)13 ExecutorService (java.util.concurrent.ExecutorService)11 Logger (org.slf4j.Logger)11 LoggerFactory (org.slf4j.LoggerFactory)11 ByteBuf (io.netty.buffer.ByteBuf)10 HashSet (java.util.HashSet)10 Map (java.util.Map)10 Lists (com.google.common.collect.Lists)8 IOException (java.io.IOException)8 ArrayList (java.util.ArrayList)8