/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.pulsar.client.impl;

import com.google.common.collect.Sets;
import io.netty.channel.EventLoopGroup;
import io.netty.util.concurrent.DefaultThreadFactory;
import org.apache.pulsar.client.api.Consumer;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.Messages;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.Schema;
import org.apache.pulsar.client.impl.conf.ClientConfigurationData;
import org.apache.pulsar.client.impl.conf.ConsumerConfigurationData;
import org.apache.pulsar.client.util.ExecutorProvider;
import org.apache.pulsar.common.partition.PartitionedTopicMetadata;
import org.apache.pulsar.common.util.netty.EventLoopUtil;
import org.testng.annotations.Test;

import java.util.Arrays;
import java.util.HashSet;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static org.apache.pulsar.client.impl.ClientTestFixtures.createDelayedCompletedFuture;
import static org.apache.pulsar.client.impl.ClientTestFixtures.createExceptionFuture;
import static org.apache.pulsar.client.impl.ClientTestFixtures.createPulsarClientMockWithMockedClientCnx;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.expectThrows;

/**
 * Unit Tests of {@link MultiTopicsConsumerImpl}.
 */
public class MultiTopicsConsumerImplTest {

    @Test
    public void testGetStats() throws Exception {
        String topicName = "test-stats";
        ClientConfigurationData conf = new ClientConfigurationData();
        conf.setServiceUrl("pulsar://localhost:6650");
        conf.setStatsIntervalSeconds(100);

        ThreadFactory threadFactory = new DefaultThreadFactory("client-test-stats", Thread.currentThread().isDaemon());
        EventLoopGroup eventLoopGroup = EventLoopUtil.newEventLoopGroup(conf.getNumIoThreads(), threadFactory);
        ExecutorProvider executorProvider = new ExecutorProvider(1, threadFactory);

        PulsarClientImpl clientImpl = new PulsarClientImpl(conf, eventLoopGroup);

        ConsumerConfigurationData consumerConfData = new ConsumerConfigurationData();
        consumerConfData.setTopicNames(Sets.newHashSet(topicName));

        assertEquals(Long.parseLong("100"), clientImpl.getConfiguration().getStatsIntervalSeconds());

        MultiTopicsConsumerImpl impl = new MultiTopicsConsumerImpl(
            clientImpl, consumerConfData,
            executorProvider, null, null, null, true);

        impl.getStats();
    }

    // Test uses a mocked PulsarClientImpl which will complete the getPartitionedTopicMetadata() internal async call
    // after a delay longer than the interval between the two subscribeAsync() calls in the test method body.
    //
    // Code under tests is using CompletableFutures. Theses may hang indefinitely if code is broken.
    // That's why a test timeout is defined.
    @Test(timeOut = 5000)
    public void testParallelSubscribeAsync() throws Exception {
        String topicName = "parallel-subscribe-async-topic";
        MultiTopicsConsumerImpl<byte[]> impl = createMultiTopicsConsumer();

        CompletableFuture<Void> firstInvocation = impl.subscribeAsync(topicName, true);
        Thread.sleep(5); // less than completionDelayMillis
        CompletableFuture<Void> secondInvocation = impl.subscribeAsync(topicName, true);

        firstInvocation.get(); // does not throw
        Throwable t = expectThrows(ExecutionException.class, secondInvocation::get);
        Throwable cause = t.getCause();
        assertEquals(cause.getClass(), PulsarClientException.class);
        assertTrue(cause.getMessage().endsWith("Topic is already being subscribed for in other thread."));
    }

    private MultiTopicsConsumerImpl<byte[]> createMultiTopicsConsumer() {
        ExecutorProvider executorProvider = mock(ExecutorProvider.class);
        ConsumerConfigurationData<byte[]> consumerConfData = new ConsumerConfigurationData<>();
        consumerConfData.setSubscriptionName("subscriptionName");
        int completionDelayMillis = 100;
        Schema<byte[]> schema = Schema.BYTES;
        PulsarClientImpl clientMock = createPulsarClientMockWithMockedClientCnx();
        when(clientMock.getPartitionedTopicMetadata(any())).thenAnswer(invocation -> createDelayedCompletedFuture(
                new PartitionedTopicMetadata(), completionDelayMillis));
        when(clientMock.<byte[]>preProcessSchemaBeforeSubscribe(any(), any(), any()))
                .thenReturn(CompletableFuture.completedFuture(schema));
        MultiTopicsConsumerImpl<byte[]> impl = new MultiTopicsConsumerImpl<byte[]>(clientMock, consumerConfData, executorProvider,
            new CompletableFuture<>(), schema, null, true);
        return impl;
    }

    @Test
    public void testReceiveAsyncCanBeCancelled() {
        // given
        MultiTopicsConsumerImpl<byte[]> consumer = createMultiTopicsConsumer();
        CompletableFuture<Message<byte[]>> future = consumer.receiveAsync();
        assertEquals(consumer.peekPendingReceive(), future);
        // when
        future.cancel(true);
        // then
        assertTrue(consumer.pendingReceives.isEmpty());
    }

    @Test
    public void testBatchReceiveAsyncCanBeCancelled() {
        // given
        MultiTopicsConsumerImpl<byte[]> consumer = createMultiTopicsConsumer();
        CompletableFuture<Messages<byte[]>> future = consumer.batchReceiveAsync();
        assertTrue(consumer.hasPendingBatchReceive());
        // when
        future.cancel(true);
        // then
        assertFalse(consumer.hasPendingBatchReceive());
    }

    @Test
    public void testConsumerCleanupOnSubscribeFailure() throws InterruptedException, TimeoutException, ExecutionException {
        ExecutorProvider executorProvider = mock(ExecutorProvider.class);
        ConsumerConfigurationData<byte[]> consumerConfData = new ConsumerConfigurationData<>();
        consumerConfData.setSubscriptionName("subscriptionName");
        consumerConfData.setTopicNames(new HashSet<>(Arrays.asList("a", "b", "c")));
        int completionDelayMillis = 10;
        Schema<byte[]> schema = Schema.BYTES;
        PulsarClientImpl clientMock = createPulsarClientMockWithMockedClientCnx();
        when(clientMock.getPartitionedTopicMetadata(any())).thenAnswer(invocation -> createExceptionFuture(
                new PulsarClientException.InvalidConfigurationException("a mock exception"), completionDelayMillis));
        CompletableFuture<Consumer<byte[]>> completeFuture = new CompletableFuture<>();
        MultiTopicsConsumerImpl<byte[]> impl = new MultiTopicsConsumerImpl<byte[]>(clientMock, consumerConfData, executorProvider,
                completeFuture, schema, null, true);
        // assert that we don't start in closed, then we move to closed and get an exception
        // indicating that closeAsync was called
        assertEquals(impl.getState(), HandlerState.State.Uninitialized);
        try {
            completeFuture.get(15, TimeUnit.MILLISECONDS);
        } catch (Throwable ex) {
            // just ignore the exception
        }
        assertTrue(completeFuture.isCompletedExceptionally());
        assertEquals(impl.getConsumers().size(), 0);
        assertEquals(impl.getState(), HandlerState.State.Closed);
        verify(clientMock, times(1)).cleanupConsumer(any());
    }

}

@@ -8102,10 +8102,9 @@
 get(
-15
+2
 , Ti
@@ -8114,13 +8114,8 @@
 nit.
-MILLI
 SECO
@@ -8147,18 +8147,22 @@
 rowable 
+ignor
 e
-x
 ) %7B%0A    

Fix flaky test MultiTopicsConsumerImplTest#testConsumerCleanupOnSubscribeFailure (#9705)