use of org.apache.pulsar.client.api.Message in project incubator-pulsar by apache.
the class FunctionMetaDataTopicTailerTest method testUpdate.
@Test
public void testUpdate() throws Exception {
ServiceRequest request = ServiceRequestUtils.getUpdateRequest(TEST_NAME, FunctionMetaData.newBuilder().build());
Message msg = mock(Message.class);
when(msg.getData()).thenReturn(request.toByteArray());
CompletableFuture<Message> receiveFuture = CompletableFuture.completedFuture(msg);
when(reader.readNextAsync()).thenReturn(receiveFuture).thenReturn(new CompletableFuture<>());
fsc.start();
// wait for receive future to complete
receiveFuture.thenApply(Function.identity()).get();
verify(reader, times(2)).readNextAsync();
verify(fsm, times(1)).processRequest(any(MessageId.class), any(ServiceRequest.class));
}
use of org.apache.pulsar.client.api.Message 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();
}
}
}
use of org.apache.pulsar.client.api.Message 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);
}
}
use of org.apache.pulsar.client.api.Message in project incubator-pulsar by apache.
the class ProducerImpl method connectionOpened.
@Override
public void connectionOpened(final ClientCnx cnx) {
// we set the cnx reference before registering the producer on the cnx, so if the cnx breaks before creating the
// producer, it will try to grab a new cnx
connectionHandler.setClientCnx(cnx);
cnx.registerProducer(producerId, this);
log.info("[{}] [{}] Creating producer on cnx {}", topic, producerName, cnx.ctx().channel());
long requestId = client.newRequestId();
cnx.sendRequestWithId(Commands.newProducer(topic, producerId, requestId, producerName, conf.isEncryptionEnabled(), metadata), requestId).thenAccept(pair -> {
String producerName = pair.getLeft();
long lastSequenceId = pair.getRight();
// set the cnx pointer so that new messages will be sent immediately
synchronized (ProducerImpl.this) {
if (getState() == State.Closing || getState() == State.Closed) {
// Producer was closed while reconnecting, close the connection to make sure the broker
// drops the producer on its side
cnx.removeProducer(producerId);
cnx.channel().close();
return;
}
resetBackoff();
log.info("[{}] [{}] Created producer on cnx {}", topic, producerName, cnx.ctx().channel());
connectionId = cnx.ctx().channel().toString();
connectedSince = DateFormatter.now();
if (this.producerName == null) {
this.producerName = producerName;
}
if (this.lastSequenceIdPublished == -1 && conf.getInitialSequenceId() == null) {
this.lastSequenceIdPublished = lastSequenceId;
this.msgIdGenerator = lastSequenceId + 1;
}
if (!producerCreatedFuture.isDone() && isBatchMessagingEnabled()) {
// schedule the first batch message task
client.timer().newTimeout(batchMessageAndSendTask, conf.getBatchingMaxPublishDelayMicros(), TimeUnit.MICROSECONDS);
}
resendMessages(cnx);
}
}).exceptionally((e) -> {
Throwable cause = e.getCause();
cnx.removeProducer(producerId);
if (getState() == State.Closing || getState() == State.Closed) {
// Producer was closed while reconnecting, close the connection to make sure the broker
// drops the producer on its side
cnx.channel().close();
return null;
}
log.error("[{}] [{}] Failed to create producer: {}", topic, producerName, cause.getMessage());
if (cause instanceof PulsarClientException.ProducerBlockedQuotaExceededException) {
synchronized (this) {
log.warn("[{}] [{}] Topic backlog quota exceeded. Throwing Exception on producer.", topic, producerName);
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Pending messages: {}", topic, producerName, pendingMessages.size());
}
PulsarClientException bqe = new PulsarClientException.ProducerBlockedQuotaExceededException("Could not send pending messages as backlog exceeded");
failPendingMessages(cnx(), bqe);
}
} else if (cause instanceof PulsarClientException.ProducerBlockedQuotaExceededError) {
log.warn("[{}] [{}] Producer is blocked on creation because backlog exceeded on topic.", producerName, topic);
}
if (cause instanceof PulsarClientException.TopicTerminatedException) {
setState(State.Terminated);
failPendingMessages(cnx(), (PulsarClientException) cause);
producerCreatedFuture.completeExceptionally(cause);
client.cleanupProducer(this);
} else if (//
producerCreatedFuture.isDone() || (cause instanceof PulsarClientException && connectionHandler.isRetriableError((PulsarClientException) cause) && System.currentTimeMillis() < createProducerTimeout)) {
// Either we had already created the producer once (producerCreatedFuture.isDone()) or we are
// still within the initial timeout budget and we are dealing with a retriable error
reconnectLater(cause);
} else {
setState(State.Failed);
producerCreatedFuture.completeExceptionally(cause);
client.cleanupProducer(this);
}
return null;
});
}
use of org.apache.pulsar.client.api.Message in project incubator-pulsar by apache.
the class PulsarBoltTest method testMetrics.
@Test
public void testMetrics() throws Exception {
bolt.resetMetrics();
String msgContent = "hello world";
Tuple tuple = getMockTuple(msgContent);
for (int i = 0; i < 10; i++) {
bolt.execute(tuple);
}
for (int i = 0; i < NO_OF_RETRIES; i++) {
Thread.sleep(1000);
if (mockCollector.getNumTuplesAcked() == 10) {
break;
}
}
@SuppressWarnings("rawtypes") Map metrics = (Map) bolt.getValueAndReset();
Assert.assertEquals(((Long) metrics.get(PulsarBolt.NO_OF_MESSAGES_SENT)).longValue(), 10);
Assert.assertEquals(((Double) metrics.get(PulsarBolt.PRODUCER_RATE)).doubleValue(), 10.0 / pulsarBoltConf.getMetricsTimeIntervalInSecs());
Assert.assertEquals(((Double) metrics.get(PulsarBolt.PRODUCER_THROUGHPUT_BYTES)).doubleValue(), ((double) msgContent.getBytes().length * 10) / pulsarBoltConf.getMetricsTimeIntervalInSecs());
metrics = bolt.getMetrics();
Assert.assertEquals(((Long) metrics.get(PulsarBolt.NO_OF_MESSAGES_SENT)).longValue(), 0);
for (int i = 0; i < 10; i++) {
Message msg = consumer.receive(5, TimeUnit.SECONDS);
consumer.acknowledge(msg);
}
}
Aggregations