Search in sources :

Example 1 with ConfirmationHandler

use of com.rabbitmq.stream.ConfirmationHandler in project rabbitmq-stream-java-client by rabbitmq.

the class StreamProducerTest method producerShouldBeClosedWhenStreamIsDeleted.

@ParameterizedTest
@ValueSource(ints = { 1, 7 })
void producerShouldBeClosedWhenStreamIsDeleted(int subEntrySize, TestInfo info) throws Exception {
    Level initialLogLevel = TestUtils.newLoggerLevel(ProducersCoordinator.class, Level.DEBUG);
    try {
        String s = streamName(info);
        environment.streamCreator().stream(s).create();
        StreamProducer producer = (StreamProducer) environment.producerBuilder().subEntrySize(subEntrySize).stream(s).build();
        AtomicInteger published = new AtomicInteger(0);
        AtomicInteger confirmed = new AtomicInteger(0);
        AtomicInteger errored = new AtomicInteger(0);
        Set<Number> errorCodes = ConcurrentHashMap.newKeySet();
        AtomicBoolean continuePublishing = new AtomicBoolean(true);
        Thread publishThread = new Thread(() -> {
            ConfirmationHandler confirmationHandler = confirmationStatus -> {
                if (confirmationStatus.isConfirmed()) {
                    confirmed.incrementAndGet();
                } else {
                    errored.incrementAndGet();
                    errorCodes.add(confirmationStatus.getCode());
                }
            };
            while (continuePublishing.get()) {
                try {
                    producer.send(producer.messageBuilder().addData("".getBytes(StandardCharsets.UTF_8)).build(), confirmationHandler);
                    published.incrementAndGet();
                } catch (StreamException e) {
                // OK
                }
            }
        });
        publishThread.start();
        Thread.sleep(1000L);
        assertThat(producer.isOpen()).isTrue();
        environment.deleteStream(s);
        waitAtMost(() -> !producer.isOpen());
        continuePublishing.set(false);
        waitAtMost(() -> !errorCodes.isEmpty(), () -> "The producer should have received negative publish confirms");
    } finally {
        TestUtils.newLoggerLevel(ProducersCoordinator.class, initialLogLevel);
    }
}
Also used : IntStream(java.util.stream.IntStream) BeforeEach(org.junit.jupiter.api.BeforeEach) SortedSet(java.util.SortedSet) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) IntConsumer(java.util.function.IntConsumer) TestUtils.latchAssert(com.rabbitmq.stream.impl.TestUtils.latchAssert) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicReference(java.util.concurrent.atomic.AtomicReference) TestUtils.streamName(com.rabbitmq.stream.impl.TestUtils.streamName) TreeSet(java.util.TreeSet) ConfirmationHandler(com.rabbitmq.stream.ConfirmationHandler) StreamException(com.rabbitmq.stream.StreamException) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ProducerInfo(com.rabbitmq.stream.impl.MonitoringTestUtils.ProducerInfo) Duration(java.time.Duration) Map(java.util.Map) ExecutorService(java.util.concurrent.ExecutorService) Host(com.rabbitmq.stream.Host) ValueSource(org.junit.jupiter.params.provider.ValueSource) TestUtils.waitAtMost(com.rabbitmq.stream.impl.TestUtils.waitAtMost) Status(com.rabbitmq.stream.impl.StreamProducer.Status) EventLoopGroup(io.netty.channel.EventLoopGroup) Environment(com.rabbitmq.stream.Environment) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) UUID(java.util.UUID) Compression(com.rabbitmq.stream.compression.Compression) Producer(com.rabbitmq.stream.Producer) Collectors(java.util.stream.Collectors) EnvironmentBuilder(com.rabbitmq.stream.EnvironmentBuilder) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) TestInfo(org.junit.jupiter.api.TestInfo) BackOffDelayPolicy(com.rabbitmq.stream.BackOffDelayPolicy) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) Level(ch.qos.logback.classic.Level) List(java.util.List) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) ConfirmationStatus(com.rabbitmq.stream.ConfirmationStatus) Constants(com.rabbitmq.stream.Constants) OffsetSpecification(com.rabbitmq.stream.OffsetSpecification) TestUtils.localhost(com.rabbitmq.stream.impl.TestUtils.localhost) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ConfirmationHandler(com.rabbitmq.stream.ConfirmationHandler) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Level(ch.qos.logback.classic.Level) StreamException(com.rabbitmq.stream.StreamException) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 2 with ConfirmationHandler

use of com.rabbitmq.stream.ConfirmationHandler in project rabbitmq-stream-java-client by rabbitmq.

the class StreamProducerTest method subEntryBatchesSentCompressedShouldBeConsumedProperly.

@Test
void subEntryBatchesSentCompressedShouldBeConsumedProperly() {
    int messagePerProducer = 10000;
    int messageCount = Compression.values().length * messagePerProducer;
    CountDownLatch publishLatch = new CountDownLatch(messageCount);
    ConfirmationHandler confirmationHandler = confirmationStatus -> publishLatch.countDown();
    AtomicInteger messageIndex = new AtomicInteger(0);
    Set<String> publishedBodies = ConcurrentHashMap.newKeySet(messageCount);
    for (Compression compression : Compression.values()) {
        Producer producer = environment.producerBuilder().stream(stream).subEntrySize(100).compression(compression).build();
        IntStream.range(0, messagePerProducer).forEach(i -> {
            String body = "compression " + compression.name() + " message " + messageIndex.getAndIncrement();
            producer.send(producer.messageBuilder().addData(body.getBytes(StandardCharsets.UTF_8)).build(), confirmationHandler);
            publishedBodies.add(body);
        });
    }
    assertThat(latchAssert(publishLatch)).completes();
    Set<String> consumedBodies = ConcurrentHashMap.newKeySet(messageCount);
    CountDownLatch consumeLatch = new CountDownLatch(messageCount);
    environment.consumerBuilder().stream(stream).offset(OffsetSpecification.first()).messageHandler((context, message) -> {
        consumedBodies.add(new String(message.getBodyAsBinary(), StandardCharsets.UTF_8));
        consumeLatch.countDown();
    }).build();
    assertThat(latchAssert(consumeLatch)).completes();
    assertThat(consumedBodies).isNotEmpty().hasSameSizeAs(publishedBodies);
    publishedBodies.forEach(publishBody -> assertThat(consumedBodies.contains(publishBody)).isTrue());
}
Also used : IntStream(java.util.stream.IntStream) BeforeEach(org.junit.jupiter.api.BeforeEach) SortedSet(java.util.SortedSet) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) IntConsumer(java.util.function.IntConsumer) TestUtils.latchAssert(com.rabbitmq.stream.impl.TestUtils.latchAssert) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicReference(java.util.concurrent.atomic.AtomicReference) TestUtils.streamName(com.rabbitmq.stream.impl.TestUtils.streamName) TreeSet(java.util.TreeSet) ConfirmationHandler(com.rabbitmq.stream.ConfirmationHandler) StreamException(com.rabbitmq.stream.StreamException) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ProducerInfo(com.rabbitmq.stream.impl.MonitoringTestUtils.ProducerInfo) Duration(java.time.Duration) Map(java.util.Map) ExecutorService(java.util.concurrent.ExecutorService) Host(com.rabbitmq.stream.Host) ValueSource(org.junit.jupiter.params.provider.ValueSource) TestUtils.waitAtMost(com.rabbitmq.stream.impl.TestUtils.waitAtMost) Status(com.rabbitmq.stream.impl.StreamProducer.Status) EventLoopGroup(io.netty.channel.EventLoopGroup) Environment(com.rabbitmq.stream.Environment) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) UUID(java.util.UUID) Compression(com.rabbitmq.stream.compression.Compression) Producer(com.rabbitmq.stream.Producer) Collectors(java.util.stream.Collectors) EnvironmentBuilder(com.rabbitmq.stream.EnvironmentBuilder) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) TestInfo(org.junit.jupiter.api.TestInfo) BackOffDelayPolicy(com.rabbitmq.stream.BackOffDelayPolicy) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) Level(ch.qos.logback.classic.Level) List(java.util.List) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) ConfirmationStatus(com.rabbitmq.stream.ConfirmationStatus) Constants(com.rabbitmq.stream.Constants) OffsetSpecification(com.rabbitmq.stream.OffsetSpecification) TestUtils.localhost(com.rabbitmq.stream.impl.TestUtils.localhost) Compression(com.rabbitmq.stream.compression.Compression) ConfirmationHandler(com.rabbitmq.stream.ConfirmationHandler) Producer(com.rabbitmq.stream.Producer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 3 with ConfirmationHandler

use of com.rabbitmq.stream.ConfirmationHandler in project rabbitmq-stream-java-client by rabbitmq.

the class StreamProducerTest method shouldRecoverAfterConnectionIsKilled.

@ParameterizedTest
@ValueSource(ints = { 1, 10 })
@TestUtils.DisabledIfRabbitMqCtlNotSet
void shouldRecoverAfterConnectionIsKilled(int subEntrySize) throws Exception {
    Producer producer = environment.producerBuilder().subEntrySize(subEntrySize).stream(stream).build();
    AtomicInteger published = new AtomicInteger(0);
    AtomicInteger confirmed = new AtomicInteger(0);
    AtomicInteger errored = new AtomicInteger(0);
    AtomicBoolean canPublish = new AtomicBoolean(true);
    Thread publishThread = new Thread(() -> {
        ConfirmationHandler confirmationHandler = confirmationStatus -> {
            if (confirmationStatus.isConfirmed()) {
                confirmed.incrementAndGet();
            } else {
                errored.incrementAndGet();
            }
        };
        while (true) {
            try {
                if (canPublish.get()) {
                    producer.send(producer.messageBuilder().addData("".getBytes(StandardCharsets.UTF_8)).build(), confirmationHandler);
                    published.incrementAndGet();
                } else {
                    Thread.sleep(500);
                }
            } catch (InterruptedException | StreamException e) {
            // OK
            }
        }
    });
    publishThread.start();
    Thread.sleep(1000L);
    Host.killConnection("rabbitmq-stream-producer-0");
    waitAtMost(10, () -> ((StreamProducer) producer).status() == Status.NOT_AVAILABLE);
    canPublish.set(false);
    assertThat(confirmed.get()).isPositive();
    waitAtMost(5, () -> confirmed.get() + errored.get() == published.get(), () -> String.format("confirmed %d / errored %d / published %d, %d + %d = %d != %d, difference %d", confirmed.get(), errored.get(), published.get(), confirmed.get(), errored.get(), (confirmed.get() + errored.get()), published.get(), (published.get() - (confirmed.get() + errored.get()))));
    assertThat(confirmed.get() + errored.get()).isEqualTo(published.get());
    waitAtMost(10, () -> ((StreamProducer) producer).status() == StreamProducer.Status.RUNNING);
    int confirmedAfterUnavailability = confirmed.get();
    int errorAfterUnavailability = errored.get();
    canPublish.set(true);
    waitAtMost(10, () -> confirmed.get() > confirmedAfterUnavailability * 2);
    assertThat(errored.get()).isEqualTo(errorAfterUnavailability);
    canPublish.set(false);
    publishThread.interrupt();
    waitAtMost(10, () -> confirmed.get() + errored.get() == published.get());
    CountDownLatch consumeLatch = new CountDownLatch(confirmed.get());
    environment.consumerBuilder().stream(stream).offset(OffsetSpecification.first()).messageHandler((offset, message) -> {
        consumeLatch.countDown();
    }).build();
    assertThat(consumeLatch.await(10, TimeUnit.SECONDS)).isTrue();
}
Also used : IntStream(java.util.stream.IntStream) BeforeEach(org.junit.jupiter.api.BeforeEach) SortedSet(java.util.SortedSet) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) IntConsumer(java.util.function.IntConsumer) TestUtils.latchAssert(com.rabbitmq.stream.impl.TestUtils.latchAssert) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicReference(java.util.concurrent.atomic.AtomicReference) TestUtils.streamName(com.rabbitmq.stream.impl.TestUtils.streamName) TreeSet(java.util.TreeSet) ConfirmationHandler(com.rabbitmq.stream.ConfirmationHandler) StreamException(com.rabbitmq.stream.StreamException) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ProducerInfo(com.rabbitmq.stream.impl.MonitoringTestUtils.ProducerInfo) Duration(java.time.Duration) Map(java.util.Map) ExecutorService(java.util.concurrent.ExecutorService) Host(com.rabbitmq.stream.Host) ValueSource(org.junit.jupiter.params.provider.ValueSource) TestUtils.waitAtMost(com.rabbitmq.stream.impl.TestUtils.waitAtMost) Status(com.rabbitmq.stream.impl.StreamProducer.Status) EventLoopGroup(io.netty.channel.EventLoopGroup) Environment(com.rabbitmq.stream.Environment) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) UUID(java.util.UUID) Compression(com.rabbitmq.stream.compression.Compression) Producer(com.rabbitmq.stream.Producer) Collectors(java.util.stream.Collectors) EnvironmentBuilder(com.rabbitmq.stream.EnvironmentBuilder) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) TestInfo(org.junit.jupiter.api.TestInfo) BackOffDelayPolicy(com.rabbitmq.stream.BackOffDelayPolicy) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) Level(ch.qos.logback.classic.Level) List(java.util.List) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) ConfirmationStatus(com.rabbitmq.stream.ConfirmationStatus) Constants(com.rabbitmq.stream.Constants) OffsetSpecification(com.rabbitmq.stream.OffsetSpecification) TestUtils.localhost(com.rabbitmq.stream.impl.TestUtils.localhost) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Producer(com.rabbitmq.stream.Producer) ConfirmationHandler(com.rabbitmq.stream.ConfirmationHandler) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CountDownLatch(java.util.concurrent.CountDownLatch) StreamException(com.rabbitmq.stream.StreamException) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 4 with ConfirmationHandler

use of com.rabbitmq.stream.ConfirmationHandler in project rabbitmq-stream-java-client by rabbitmq.

the class StreamProducerUnitTest method confirmTimeoutTaskShouldFailMessagesAfterTimeout.

@ParameterizedTest
@CsvSource({ "500,1000,1", "0,1000,1", "500,1000,7", "0,1000,7" })
void confirmTimeoutTaskShouldFailMessagesAfterTimeout(long confirmTimeoutMs, long waitTimeMs, int subEntrySize) throws Exception {
    Duration confirmTimeout = Duration.ofMillis(confirmTimeoutMs);
    Duration waitTime = Duration.ofMillis(waitTimeMs);
    clock.refresh();
    int messageCount = 500;
    int confirmedPart = messageCount / 10;
    int expectedConfirmed = confirmedPart - confirmedPart % subEntrySize;
    AtomicInteger confirmedCount = new AtomicInteger();
    AtomicInteger erroredCount = new AtomicInteger();
    Set<Short> responseCodes = ConcurrentHashMap.newKeySet();
    CountDownLatch confirmLatch = new CountDownLatch(confirmedPart);
    ConfirmationHandler confirmationHandler = status -> {
        if (status.isConfirmed()) {
            confirmedCount.incrementAndGet();
            confirmLatch.countDown();
        } else {
            erroredCount.incrementAndGet();
            responseCodes.add(status.getCode());
        }
    };
    clock.refresh();
    StreamProducer producer = new StreamProducer(null, "stream", subEntrySize, 10, Compression.NONE, Duration.ofMillis(100), messageCount * 10, confirmTimeout, Duration.ofSeconds(10), env);
    IntStream.range(0, messageCount).forEach(i -> producer.send(producer.messageBuilder().addData("".getBytes()).build(), confirmationHandler));
    IntStream.range(0, confirmedPart).forEach(publishingId -> producer.confirm(publishingId));
    assertThat(confirmedCount.get()).isEqualTo(expectedConfirmed);
    assertThat(erroredCount.get()).isZero();
    executorService.scheduleAtFixedRate(() -> clock.refresh(), 100, 100, TimeUnit.MILLISECONDS);
    Thread.sleep(waitTime.toMillis());
    assertThat(confirmedCount.get()).isEqualTo(expectedConfirmed);
    if (confirmTimeout.isZero()) {
        assertThat(erroredCount.get()).isZero();
        assertThat(responseCodes).isEmpty();
    } else {
        waitAtMost(waitTime.multipliedBy(2), () -> erroredCount.get() == (messageCount - expectedConfirmed));
        assertThat(responseCodes).hasSize(1).contains(Constants.CODE_PUBLISH_CONFIRM_TIMEOUT);
    }
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) IntStream(java.util.stream.IntStream) BeforeEach(org.junit.jupiter.api.BeforeEach) CsvSource(org.junit.jupiter.params.provider.CsvSource) ArgumentMatchers.nullable(org.mockito.ArgumentMatchers.nullable) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) Mock(org.mockito.Mock) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SimpleCodec(com.rabbitmq.stream.codec.SimpleCodec) OutboundEntityWriteCallback(com.rabbitmq.stream.impl.Client.OutboundEntityWriteCallback) ConfirmationHandler(com.rabbitmq.stream.ConfirmationHandler) MockitoAnnotations(org.mockito.MockitoAnnotations) Answer(org.mockito.stubbing.Answer) ThrowingCallable(org.assertj.core.api.ThrowableAssert.ThrowingCallable) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) StreamException(com.rabbitmq.stream.StreamException) ByteBuf(io.netty.buffer.ByteBuf) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Duration(java.time.Duration) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ToLongFunction(java.util.function.ToLongFunction) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) ValueSource(org.junit.jupiter.params.provider.ValueSource) TestUtils.waitAtMost(com.rabbitmq.stream.impl.TestUtils.waitAtMost) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) Mockito.when(org.mockito.Mockito.when) ArgumentMatchers.anyList(org.mockito.ArgumentMatchers.anyList) Compression(com.rabbitmq.stream.compression.Compression) Executors(java.util.concurrent.Executors) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) Mockito(org.mockito.Mockito) ArgumentMatchers.anyByte(org.mockito.ArgumentMatchers.anyByte) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Constants(com.rabbitmq.stream.Constants) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ConfirmationHandler(com.rabbitmq.stream.ConfirmationHandler) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) CountDownLatch(java.util.concurrent.CountDownLatch) CsvSource(org.junit.jupiter.params.provider.CsvSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 5 with ConfirmationHandler

use of com.rabbitmq.stream.ConfirmationHandler in project rabbitmq-stream-java-client by rabbitmq.

the class StreamConsumerTest method manualTrackingConsumerShouldRestartWhereItLeftOff.

@Test
void manualTrackingConsumerShouldRestartWhereItLeftOff() throws Exception {
    Producer producer = environment.producerBuilder().stream(stream).build();
    int messageCountFirstWave = 10_000;
    int messageCountSecondWave = 5_000;
    int messageCount = messageCountFirstWave + messageCountSecondWave;
    CountDownLatch latchConfirmFirstWave = new CountDownLatch(messageCountFirstWave);
    CountDownLatch latchConfirmSecondWave = new CountDownLatch(messageCount);
    ConfirmationHandler confirmationHandler = confirmationStatus -> {
        latchConfirmFirstWave.countDown();
        latchConfirmSecondWave.countDown();
    };
    AtomicLong messageIdSequence = new AtomicLong();
    java.util.function.Consumer<Integer> messageSending = messageCountToSend -> {
        IntStream.range(0, messageCountToSend).forEach(i -> producer.send(producer.messageBuilder().addData("".getBytes()).properties().messageId(messageIdSequence.getAndIncrement()).messageBuilder().build(), confirmationHandler));
    };
    messageSending.accept(messageCountFirstWave);
    assertThat(latchAssert(latchConfirmFirstWave)).completes();
    int storeEvery = 100;
    AtomicInteger consumedMessageCount = new AtomicInteger();
    AtomicReference<Consumer> consumerReference = new AtomicReference<>();
    AtomicLong lastStoredOffset = new AtomicLong(0);
    AtomicLong lastProcessedMessage = new AtomicLong(0);
    AtomicInteger storeCount = new AtomicInteger(0);
    Consumer consumer = environment.consumerBuilder().stream(stream).offset(OffsetSpecification.first()).name("application-1").manualTrackingStrategy().checkInterval(Duration.ZERO).builder().messageHandler((context, message) -> {
        consumedMessageCount.incrementAndGet();
        lastProcessedMessage.set(message.getProperties().getMessageIdAsLong());
        if (consumedMessageCount.get() % storeEvery == 0) {
            context.storeOffset();
            lastStoredOffset.set(context.offset());
            storeCount.incrementAndGet();
        }
    }).build();
    ConsumerInfo consumerInfo = MonitoringTestUtils.extract(consumer);
    assertThat(consumerInfo.getId()).isGreaterThanOrEqualTo(0);
    assertThat(consumerInfo.getStream()).isEqualTo(stream);
    assertThat(consumerInfo.getSubscriptionClient()).contains(" -> localhost:5552");
    assertThat(consumerInfo.getTrackingClient()).contains(" -> localhost:5552");
    consumerReference.set(consumer);
    waitAtMost(10, () -> consumedMessageCount.get() == messageCountFirstWave);
    assertThat(lastStoredOffset.get()).isPositive();
    consumer.close();
    messageSending.accept(messageCountSecondWave);
    assertThat(latchAssert(latchConfirmSecondWave)).completes();
    AtomicLong firstOffset = new AtomicLong(0);
    consumer = environment.consumerBuilder().stream(stream).name("application-1").manualTrackingStrategy().checkInterval(Duration.ZERO).builder().messageHandler((context, message) -> {
        firstOffset.compareAndSet(0, context.offset());
        if (message.getProperties().getMessageIdAsLong() > lastProcessedMessage.get()) {
            consumedMessageCount.incrementAndGet();
        }
    }).build();
    waitAtMost(3, () -> consumedMessageCount.get() == messageCount, () -> "Expected " + consumedMessageCount.get() + " to reach " + messageCount);
    // there will be the tracking records after the first wave of messages,
    // messages offset won't be contiguous, so it's not an exact match
    assertThat(firstOffset.get()).isGreaterThanOrEqualTo(lastStoredOffset.get());
    consumer.close();
}
Also used : IntStream(java.util.stream.IntStream) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) StreamDoesNotExistException(com.rabbitmq.stream.StreamDoesNotExistException) IntConsumer(java.util.function.IntConsumer) TestUtils.latchAssert(com.rabbitmq.stream.impl.TestUtils.latchAssert) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) UnaryOperator(java.util.function.UnaryOperator) AtomicReference(java.util.concurrent.atomic.AtomicReference) TestUtils.b(com.rabbitmq.stream.impl.TestUtils.b) TestUtils.streamName(com.rabbitmq.stream.impl.TestUtils.streamName) ConfirmationHandler(com.rabbitmq.stream.ConfirmationHandler) DisabledIfRabbitMqCtlNotSet(com.rabbitmq.stream.impl.TestUtils.DisabledIfRabbitMqCtlNotSet) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConsumerBuilder(com.rabbitmq.stream.ConsumerBuilder) Duration(java.time.Duration) MethodSource(org.junit.jupiter.params.provider.MethodSource) Host(com.rabbitmq.stream.Host) TestUtils.waitAtMost(com.rabbitmq.stream.impl.TestUtils.waitAtMost) EventLoopGroup(io.netty.channel.EventLoopGroup) Environment(com.rabbitmq.stream.Environment) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) UUID(java.util.UUID) Consumer(com.rabbitmq.stream.Consumer) Producer(com.rabbitmq.stream.Producer) String.format(java.lang.String.format) EnvironmentBuilder(com.rabbitmq.stream.EnvironmentBuilder) ConsumerInfo(com.rabbitmq.stream.impl.MonitoringTestUtils.ConsumerInfo) TestInfo(org.junit.jupiter.api.TestInfo) BackOffDelayPolicy(com.rabbitmq.stream.BackOffDelayPolicy) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Stream(java.util.stream.Stream) Collections(java.util.Collections) OffsetSpecification(com.rabbitmq.stream.OffsetSpecification) TestUtils.localhost(com.rabbitmq.stream.impl.TestUtils.localhost) ConsumerInfo(com.rabbitmq.stream.impl.MonitoringTestUtils.ConsumerInfo) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicLong(java.util.concurrent.atomic.AtomicLong) Producer(com.rabbitmq.stream.Producer) ConfirmationHandler(com.rabbitmq.stream.ConfirmationHandler) IntConsumer(java.util.function.IntConsumer) Consumer(com.rabbitmq.stream.Consumer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Aggregations

ConfirmationHandler (com.rabbitmq.stream.ConfirmationHandler)13 CountDownLatch (java.util.concurrent.CountDownLatch)13 Environment (com.rabbitmq.stream.Environment)12 OffsetSpecification (com.rabbitmq.stream.OffsetSpecification)12 Producer (com.rabbitmq.stream.Producer)12 StreamException (com.rabbitmq.stream.StreamException)12 Duration (java.time.Duration)12 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)12 BeforeEach (org.junit.jupiter.api.BeforeEach)12 Constants (com.rabbitmq.stream.Constants)11 EnvironmentBuilder (com.rabbitmq.stream.EnvironmentBuilder)11 TestUtils.latchAssert (com.rabbitmq.stream.impl.TestUtils.latchAssert)11 AfterEach (org.junit.jupiter.api.AfterEach)11 Test (org.junit.jupiter.api.Test)11 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)11 TestUtils.localhost (com.rabbitmq.stream.impl.TestUtils.localhost)10 EventLoopGroup (io.netty.channel.EventLoopGroup)10 IntStream (java.util.stream.IntStream)10 AtomicReference (java.util.concurrent.atomic.AtomicReference)9 Host (com.rabbitmq.stream.Host)8