Search in sources :

Example 11 with SequencedMessage

use of com.google.cloud.pubsublite.SequencedMessage in project java-pubsublite by googleapis.

the class SubscriberImplTest method reinitialize_handlesIgnoredReset.

@Test
public void reinitialize_handlesIgnoredReset() throws Exception {
    subscriber.allowFlow(FlowControlRequest.newBuilder().setAllowedBytes(100).setAllowedMessages(100).build());
    ImmutableList<SequencedMessage> messages = ImmutableList.of(SequencedMessage.of(Message.builder().build(), Timestamps.EPOCH, Offset.of(0), 10), SequencedMessage.of(Message.builder().build(), Timestamps.EPOCH, Offset.of(1), 10));
    CountDownLatch messagesReceived = countdownMessageBatches(1);
    leakedResponseObserver.onResponse(messages);
    assertThat(messagesReceived.await(10, SECONDS)).isTrue();
    verify(mockMessageConsumer).accept(messages);
    final SubscribeRequest nextOffsetRequest = SubscribeRequest.newBuilder().setInitial(BASE_INITIAL_SUBSCRIBE_REQUEST.toBuilder().setInitialLocation(SeekRequest.newBuilder().setCursor(Cursor.newBuilder().setOffset(2)))).build();
    doAnswer(args -> {
        leakedResponseObserver = args.getArgument(1);
        return mockConnectedSubscriber2;
    }).when(mockSubscriberFactory).New(any(), any(), eq(nextOffsetRequest));
    // If the RESET signal is received and subscriber reset is ignored, the subscriber should read
    // from the next offset upon reconnect.
    when(mockResetHandler.handleReset()).thenReturn(false);
    subscriber.triggerReinitialize(TestResetSignal.newCheckedException());
    verify(mockSubscriberFactory, times(1)).New(any(), any(), eq(initialRequest()));
    verify(mockSubscriberFactory, times(1)).New(any(), any(), eq(nextOffsetRequest));
    verify(mockConnectedSubscriber2).allowFlow(FlowControlRequest.newBuilder().setAllowedBytes(80).setAllowedMessages(98).build());
}
Also used : SubscribeRequest(com.google.cloud.pubsublite.proto.SubscribeRequest) InitialSubscribeRequest(com.google.cloud.pubsublite.proto.InitialSubscribeRequest) SequencedMessage(com.google.cloud.pubsublite.SequencedMessage) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 12 with SequencedMessage

use of com.google.cloud.pubsublite.SequencedMessage in project java-pubsublite by googleapis.

the class SubscriberImplTest method reinitialize_reconnectsToNextOffset.

@Test
public void reinitialize_reconnectsToNextOffset() throws Exception {
    subscriber.allowFlow(FlowControlRequest.newBuilder().setAllowedBytes(100).setAllowedMessages(100).build());
    ImmutableList<SequencedMessage> messages = ImmutableList.of(SequencedMessage.of(Message.builder().build(), Timestamps.EPOCH, Offset.of(0), 10), SequencedMessage.of(Message.builder().build(), Timestamps.EPOCH, Offset.of(1), 10));
    CountDownLatch messagesReceived = countdownMessageBatches(1);
    leakedResponseObserver.onResponse(messages);
    assertThat(messagesReceived.await(10, SECONDS)).isTrue();
    verify(mockMessageConsumer).accept(messages);
    final SubscribeRequest nextOffsetRequest = SubscribeRequest.newBuilder().setInitial(BASE_INITIAL_SUBSCRIBE_REQUEST.toBuilder().setInitialLocation(SeekRequest.newBuilder().setCursor(Cursor.newBuilder().setOffset(2)))).build();
    doAnswer(args -> {
        leakedResponseObserver = args.getArgument(1);
        return mockConnectedSubscriber2;
    }).when(mockSubscriberFactory).New(any(), any(), eq(nextOffsetRequest));
    subscriber.triggerReinitialize(new CheckedApiException(Code.ABORTED));
    verify(mockSubscriberFactory, times(1)).New(any(), any(), eq(initialRequest()));
    verify(mockSubscriberFactory, times(1)).New(any(), any(), eq(nextOffsetRequest));
    verify(mockConnectedSubscriber2).allowFlow(FlowControlRequest.newBuilder().setAllowedBytes(80).setAllowedMessages(98).build());
}
Also used : SubscribeRequest(com.google.cloud.pubsublite.proto.SubscribeRequest) InitialSubscribeRequest(com.google.cloud.pubsublite.proto.InitialSubscribeRequest) SequencedMessage(com.google.cloud.pubsublite.SequencedMessage) CheckedApiException(com.google.cloud.pubsublite.internal.CheckedApiException) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 13 with SequencedMessage

use of com.google.cloud.pubsublite.SequencedMessage in project java-pubsublite-kafka by googleapis.

the class SingleSubscriptionConsumerImpl method doPoll.

private Map<Partition, Queue<SequencedMessage>> doPoll(Duration duration) {
    try {
        ImmutableList.Builder<ApiFuture<Void>> stopSleepingSignals = ImmutableList.builder();
        try (CloseableMonitor.Hold h = monitor.enter()) {
            stopSleepingSignals.add(wakeupTriggered);
            stopSleepingSignals.add(assignmentChanged);
            partitions.values().forEach(subscriber -> stopSleepingSignals.add(subscriber.onData()));
        }
        try {
            ApiFuturesExtensions.whenFirstDone(stopSleepingSignals.build()).get(duration.toMillis(), MILLISECONDS);
        } catch (TimeoutException e) {
            return ImmutableMap.of();
        }
        try (CloseableMonitor.Hold h = monitor.enter()) {
            if (wakeupTriggered.isDone())
                throw new WakeupException();
            Map<Partition, Queue<SequencedMessage>> partitionQueues = new HashMap<>();
            partitions.forEach(ExtractStatus.rethrowAsRuntime((partition, subscriber) -> partitionQueues.put(partition, subscriber.getMessages())));
            return partitionQueues;
        }
    } catch (Throwable t) {
        throw toKafka(t);
    }
}
Also used : MoreExecutors(com.google.common.util.concurrent.MoreExecutors) TimeoutException(java.util.concurrent.TimeoutException) KafkaException(org.apache.kafka.common.KafkaException) HashMap(java.util.HashMap) SequencedMessage(com.google.cloud.pubsublite.SequencedMessage) ConsumerRecords(org.apache.kafka.clients.consumer.ConsumerRecords) TopicPath(com.google.cloud.pubsublite.TopicPath) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) ExtractStatus(com.google.cloud.pubsublite.internal.ExtractStatus) Duration(java.time.Duration) Map(java.util.Map) SimpleEntry(java.util.AbstractMap.SimpleEntry) NamedTarget(com.google.cloud.pubsublite.proto.SeekRequest.NamedTarget) ApiServiceUtils.blockingShutdown(com.google.cloud.pubsublite.internal.wire.ApiServiceUtils.blockingShutdown) TopicPartition(org.apache.kafka.common.TopicPartition) ImmutableSet(com.google.common.collect.ImmutableSet) ApiFutures(com.google.api.core.ApiFutures) Partition(com.google.cloud.pubsublite.Partition) ImmutableMap(com.google.common.collect.ImmutableMap) Offset(com.google.cloud.pubsublite.Offset) SeekRequest(com.google.cloud.pubsublite.proto.SeekRequest) WakeupException(org.apache.kafka.common.errors.WakeupException) GuardedBy(com.google.errorprone.annotations.concurrent.GuardedBy) Set(java.util.Set) ApiFutureCallback(com.google.api.core.ApiFutureCallback) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) CloseableMonitor(com.google.cloud.pubsublite.internal.CloseableMonitor) KafkaExceptionUtils.toKafka(com.google.cloud.pubsublite.kafka.KafkaExceptionUtils.toKafka) GoogleLogger(com.google.common.flogger.GoogleLogger) Collectors(java.util.stream.Collectors) ApiFuture(com.google.api.core.ApiFuture) SettableApiFuture(com.google.api.core.SettableApiFuture) List(java.util.List) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord) Optional(java.util.Optional) CommitFailedException(org.apache.kafka.clients.consumer.CommitFailedException) Queue(java.util.Queue) TopicPartition(org.apache.kafka.common.TopicPartition) Partition(com.google.cloud.pubsublite.Partition) HashMap(java.util.HashMap) ImmutableList(com.google.common.collect.ImmutableList) WakeupException(org.apache.kafka.common.errors.WakeupException) ApiFuture(com.google.api.core.ApiFuture) SettableApiFuture(com.google.api.core.SettableApiFuture) CloseableMonitor(com.google.cloud.pubsublite.internal.CloseableMonitor) Queue(java.util.Queue) TimeoutException(java.util.concurrent.TimeoutException)

Example 14 with SequencedMessage

use of com.google.cloud.pubsublite.SequencedMessage in project java-pubsublite-kafka by googleapis.

the class SingleSubscriptionConsumerImpl method poll.

@Override
public ConsumerRecords<byte[], byte[]> poll(Duration duration) {
    if (autocommit) {
        ApiFuture<?> future = commitAll();
        ApiFutures.addCallback(future, new ApiFutureCallback<Object>() {

            @Override
            public void onFailure(Throwable throwable) {
                logger.atWarning().withCause(throwable).log("Failed to commit offsets.");
            }

            @Override
            public void onSuccess(Object result) {
            }
        }, MoreExecutors.directExecutor());
    }
    Map<Partition, Queue<SequencedMessage>> partitionQueues = doPoll(duration);
    Map<TopicPartition, List<ConsumerRecord<byte[], byte[]>>> records = new HashMap<>();
    partitionQueues.forEach((partition, queue) -> {
        if (queue.isEmpty())
            return;
        List<ConsumerRecord<byte[], byte[]>> partitionRecords = queue.stream().map(message -> RecordTransforms.fromMessage(message, topic, partition)).collect(Collectors.toList());
        records.put(new TopicPartition(topic.toString(), (int) partition.value()), partitionRecords);
    });
    return new ConsumerRecords<>(records);
}
Also used : MoreExecutors(com.google.common.util.concurrent.MoreExecutors) TimeoutException(java.util.concurrent.TimeoutException) KafkaException(org.apache.kafka.common.KafkaException) HashMap(java.util.HashMap) SequencedMessage(com.google.cloud.pubsublite.SequencedMessage) ConsumerRecords(org.apache.kafka.clients.consumer.ConsumerRecords) TopicPath(com.google.cloud.pubsublite.TopicPath) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) ExtractStatus(com.google.cloud.pubsublite.internal.ExtractStatus) Duration(java.time.Duration) Map(java.util.Map) SimpleEntry(java.util.AbstractMap.SimpleEntry) NamedTarget(com.google.cloud.pubsublite.proto.SeekRequest.NamedTarget) ApiServiceUtils.blockingShutdown(com.google.cloud.pubsublite.internal.wire.ApiServiceUtils.blockingShutdown) TopicPartition(org.apache.kafka.common.TopicPartition) ImmutableSet(com.google.common.collect.ImmutableSet) ApiFutures(com.google.api.core.ApiFutures) Partition(com.google.cloud.pubsublite.Partition) ImmutableMap(com.google.common.collect.ImmutableMap) Offset(com.google.cloud.pubsublite.Offset) SeekRequest(com.google.cloud.pubsublite.proto.SeekRequest) WakeupException(org.apache.kafka.common.errors.WakeupException) GuardedBy(com.google.errorprone.annotations.concurrent.GuardedBy) Set(java.util.Set) ApiFutureCallback(com.google.api.core.ApiFutureCallback) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) CloseableMonitor(com.google.cloud.pubsublite.internal.CloseableMonitor) KafkaExceptionUtils.toKafka(com.google.cloud.pubsublite.kafka.KafkaExceptionUtils.toKafka) GoogleLogger(com.google.common.flogger.GoogleLogger) Collectors(java.util.stream.Collectors) ApiFuture(com.google.api.core.ApiFuture) SettableApiFuture(com.google.api.core.SettableApiFuture) List(java.util.List) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord) Optional(java.util.Optional) CommitFailedException(org.apache.kafka.clients.consumer.CommitFailedException) Queue(java.util.Queue) TopicPartition(org.apache.kafka.common.TopicPartition) Partition(com.google.cloud.pubsublite.Partition) HashMap(java.util.HashMap) ConsumerRecords(org.apache.kafka.clients.consumer.ConsumerRecords) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord) TopicPartition(org.apache.kafka.common.TopicPartition) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) Queue(java.util.Queue)

Example 15 with SequencedMessage

use of com.google.cloud.pubsublite.SequencedMessage in project java-pubsublite-spark by googleapis.

the class PslMicroBatchInputPartitionReaderTest method testPartitionReader.

@Test
public void testPartitionReader() throws Exception {
    long endOffset = 14L;
    createReader(endOffset);
    SequencedMessage message1 = newMessage(10L);
    SequencedMessage message2 = newMessage(endOffset);
    // Multiple get w/o next will return same msg.
    when(subscriber.onData()).thenReturn(ApiFutures.immediateFuture(null));
    when(subscriber.messageIfAvailable()).thenReturn(Optional.of(message1));
    assertThat(reader.next()).isTrue();
    verifyInternalRow(reader.get(), 10L);
    verifyInternalRow(reader.get(), 10L);
    // Next will advance to next msg which is also the last msg in the batch.
    when(subscriber.onData()).thenReturn(ApiFutures.immediateFuture(null));
    when(subscriber.messageIfAvailable()).thenReturn(Optional.of(message2));
    assertThat(reader.next()).isTrue();
    verifyInternalRow(reader.get(), 14L);
    // Now it already reached the end of the batch
    assertThat(reader.next()).isFalse();
}
Also used : SequencedMessage(com.google.cloud.pubsublite.SequencedMessage) Test(org.junit.Test)

Aggregations

SequencedMessage (com.google.cloud.pubsublite.SequencedMessage)24 Test (org.junit.Test)20 Partition (com.google.cloud.pubsublite.Partition)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 Offset (com.google.cloud.pubsublite.Offset)4 PubsubMessage (com.google.pubsub.v1.PubsubMessage)4 TopicPath (com.google.cloud.pubsublite.TopicPath)3 FlowControlRequest (com.google.cloud.pubsublite.proto.FlowControlRequest)3 ArrayList (java.util.ArrayList)3 ApiFuture (com.google.api.core.ApiFuture)2 ApiFutureCallback (com.google.api.core.ApiFutureCallback)2 ApiFutures (com.google.api.core.ApiFutures)2 SettableApiFuture (com.google.api.core.SettableApiFuture)2 CheckedApiException (com.google.cloud.pubsublite.internal.CheckedApiException)2 CloseableMonitor (com.google.cloud.pubsublite.internal.CloseableMonitor)2 ExtractStatus (com.google.cloud.pubsublite.internal.ExtractStatus)2 ApiServiceUtils.blockingShutdown (com.google.cloud.pubsublite.internal.wire.ApiServiceUtils.blockingShutdown)2 KafkaExceptionUtils.toKafka (com.google.cloud.pubsublite.kafka.KafkaExceptionUtils.toKafka)2 InitialSubscribeRequest (com.google.cloud.pubsublite.proto.InitialSubscribeRequest)2 SeekRequest (com.google.cloud.pubsublite.proto.SeekRequest)2