adikou commented on code in PR #24199:
URL: https://github.com/apache/kafka/pull/24199#discussion_r4565817827


##########
clients/src/test/java/org/apache/kafka/clients/consumer/KafkaConsumerTest.java:
##########
@@ -3305,6 +3305,21 @@ public void 
onPartitionsAssigned(Collection<TopicPartition> partitions, Rebalanc
         };
     }
 
+    /**
+     * Counts the callbacks like {@link MockRebalanceListener} and 
additionally seeks every newly
+     * assigned partition to 0, which both avoids an offset lookup and leaves 
an observable trace
+     * of the callback having run.
+     */
+    private static class SeekToZeroRebalanceListener extends 
MockRebalanceListener {

Review Comment:
   This is more of a CountingSeekToZeroRebalanceListener



##########
clients/clients-integration-tests/src/test/java/org/apache/kafka/clients/consumer/PlaintextConsumerCallbackTest.java:
##########
@@ -537,6 +537,83 @@ public void onPartitionsRevoked(Collection<TopicPartition> 
partitions, Rebalance
         assertEquals(2, revokedCount.get(), "close() should invoke 
onPartitionsRevoked");
     }
 
+    @ClusterTest
+    public void testClassicConsumerRebalanceListenerRemovedByNull() throws 
InterruptedException {
+        testRebalanceListenerRemovedByNull(CLASSIC);
+    }
+
+    @ClusterTest
+    public void testAsyncConsumerRebalanceListenerRemovedByNull() throws 
InterruptedException {
+        testRebalanceListenerRemovedByNull(CONSUMER);
+    }
+
+    private void testRebalanceListenerRemovedByNull(GroupProtocol 
groupProtocol) throws InterruptedException {
+        var assignedCount = new AtomicInteger(0);
+        var revokedCount = new AtomicInteger(0);
+        var totalRecords = 10;
+        var consumer = createConsumer(groupProtocol);
+        try {
+            consumer.setRebalanceListener(new RebalanceListener() {
+                @Override
+                public void onPartitionsAssigned(Collection<TopicPartition> 
partitions, RebalanceConsumer rc) {
+                    if (partitions.contains(tp)) {
+                        assignedCount.incrementAndGet();
+                    }
+                }
+
+                @Override
+                public void onPartitionsRevoked(Collection<TopicPartition> 
partitions, RebalanceConsumer rc) {
+                    if (partitions.contains(tp)) {
+                        revokedCount.incrementAndGet();
+                    }
+                }
+            });
+            consumer.subscribe(List.of(topic));
+            ClientsTestUtils.pollUntilTrue(
+                    consumer,
+                    () -> assignedCount.get() == 1,
+                    "Timed out before expected rebalance completed"
+            );
+
+            // positive control: while the listener is set, unsubscribe() 
invokes onPartitionsRevoked
+            // without a poll, so the silence asserted further down is a real 
change of behaviour
+            consumer.unsubscribe();
+            assertEquals(1, revokedCount.get(), "unsubscribe() should invoke 
the listener while it is set");
+
+            consumer.subscribe(List.of(topic));
+            ClientsTestUtils.pollUntilTrue(
+                    consumer,
+                    () -> assignedCount.get() == 2,
+                    "Timed out before the listener was invoked again"
+            );
+
+            consumer.setRebalanceListener(null);
+
+            // the very same call that invoked onPartitionsRevoked above is 
now silent
+            consumer.unsubscribe();
+            assertEquals(1, revokedCount.get(), "unsubscribe() should not 
invoke the removed listener");
+
+            // consuming every record proves the new assignment is fully 
usable without the callback,
+            // not merely present in assignment()
+            consumer.subscribe(List.of(topic));
+            ClientsTestUtils.pollUntilTrue(
+                    consumer,
+                    () -> consumer.assignment().contains(tp),
+                    "Timed out before the partition was assigned again"
+            );
+            sendRecords(cluster, tp, totalRecords, 0L);
+            consumeAndVerifyRecords(consumer, tp, totalRecords, 0);
+            assertEquals(2, assignedCount.get(), "re-subscribing should not 
invoke the removed listener");
+            assertEquals(1, revokedCount.get());
+        } finally {
+            consumer.close();

Review Comment:
   Why revert from the AutoCloseable above?



##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/ConsumerRebalanceListenerInvokerTest.java:
##########
@@ -0,0 +1,198 @@
+/*
+ * 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.kafka.clients.consumer.internals;
+
+import 
org.apache.kafka.clients.consumer.internals.metrics.RebalanceCallbackMetricsManager;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.InterruptException;
+import org.apache.kafka.common.errors.WakeupException;
+import org.apache.kafka.common.utils.MockTime;
+import org.apache.kafka.common.utils.internals.LogContext;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
+
+import java.util.HashSet;
+import java.util.SortedSet;
+import java.util.TreeSet;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+/**
+ * Tests the two things this invoker adds on top of the dispatch: it skips the 
dispatch entirely
+ * when no rebalance listener is registered, which is the case after
+ * {@link org.apache.kafka.clients.consumer.Consumer#setRebalanceListener(
+ * org.apache.kafka.clients.consumer.RebalanceListener)} is passed null, and 
it turns a failing
+ * listener into a returned exception while letting {@link WakeupException} and
+ * {@link InterruptException} through. The subscription state is mocked rather 
than real on purpose:
+ * a real one silently drops the callbacks itself, so it would hide whether 
the invoker checked at all.
+ */
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.STRICT_STUBS)
+public class ConsumerRebalanceListenerInvokerTest {
+
+    private final SortedSet<TopicPartition> partitions = new TreeSet<>(new 
Utils.TopicPartitionComparator());
+
+    @Mock
+    private ConsumerSubscriptionState subscriptions;
+
+    @Mock
+    private RebalanceCallbackMetricsManager metricsManager;
+
+    private ConsumerRebalanceListenerInvoker invoker;
+
+    @BeforeEach
+    public void setup() {
+        partitions.add(new TopicPartition("topic", 0));
+        invoker = new ConsumerRebalanceListenerInvoker(
+            new LogContext(), subscriptions, new MockTime(), metricsManager);
+    }
+
+    @Test
+    public void 
testInvokePartitionsAssignedWithoutRebalanceListenerSkipsDispatch() {
+        when(subscriptions.hasRebalanceListener()).thenReturn(false);
+
+        assertNull(invoker.invokePartitionsAssigned(partitions));
+
+        verify(subscriptions, never()).onPartitionsAssigned(any());
+        verifyNoInteractions(metricsManager);
+    }
+
+    @Test
+    public void 
testInvokePartitionsRevokedWithoutRebalanceListenerSkipsDispatch() {
+        when(subscriptions.hasRebalanceListener()).thenReturn(false);
+        when(subscriptions.pausedPartitions()).thenReturn(new HashSet<>());
+
+        assertNull(invoker.invokePartitionsRevoked(partitions));
+
+        verify(subscriptions, never()).onPartitionsRevoked(any());
+        verifyNoInteractions(metricsManager);
+    }
+
+    @Test
+    public void 
testInvokePartitionsLostWithoutRebalanceListenerSkipsDispatch() {
+        when(subscriptions.hasRebalanceListener()).thenReturn(false);
+        when(subscriptions.pausedPartitions()).thenReturn(new HashSet<>());
+
+        assertNull(invoker.invokePartitionsLost(partitions));
+
+        verify(subscriptions, never()).onPartitionsLost(any());
+        verifyNoInteractions(metricsManager);
+    }
+
+    @Test
+    public void testInvokeCallbacksWithRebalanceListenerDispatches() {
+        when(subscriptions.hasRebalanceListener()).thenReturn(true);
+        when(subscriptions.pausedPartitions()).thenReturn(new HashSet<>());
+
+        assertNull(invoker.invokePartitionsAssigned(partitions));
+        assertNull(invoker.invokePartitionsRevoked(partitions));
+        assertNull(invoker.invokePartitionsLost(partitions));
+
+        verify(subscriptions).onPartitionsAssigned(partitions);
+        verify(subscriptions).onPartitionsRevoked(partitions);
+        verify(subscriptions).onPartitionsLost(partitions);
+        verify(metricsManager).recordPartitionsAssignedLatency(anyLong());
+        verify(metricsManager).recordPartitionsRevokedLatency(anyLong());
+        verify(metricsManager).recordPartitionsLostLatency(anyLong());
+    }
+
+    @Test
+    public void testInvokePartitionsAssignedReturnsListenerException() {
+        RuntimeException exception = new RuntimeException("Test exception");
+        when(subscriptions.hasRebalanceListener()).thenReturn(true);
+        
doThrow(exception).when(subscriptions).onPartitionsAssigned(partitions);
+
+        assertSame(exception, invoker.invokePartitionsAssigned(partitions));
+        verifyNoInteractions(metricsManager);
+    }
+
+    @Test
+    public void testInvokePartitionsRevokedReturnsListenerException() {
+        RuntimeException exception = new RuntimeException("Test exception");
+        when(subscriptions.hasRebalanceListener()).thenReturn(true);
+        when(subscriptions.pausedPartitions()).thenReturn(new HashSet<>());
+        doThrow(exception).when(subscriptions).onPartitionsRevoked(partitions);
+
+        assertSame(exception, invoker.invokePartitionsRevoked(partitions));
+        verifyNoInteractions(metricsManager);
+    }
+
+    @Test
+    public void testInvokePartitionsLostReturnsListenerException() {
+        RuntimeException exception = new RuntimeException("Test exception");
+        when(subscriptions.hasRebalanceListener()).thenReturn(true);
+        when(subscriptions.pausedPartitions()).thenReturn(new HashSet<>());
+        doThrow(exception).when(subscriptions).onPartitionsLost(partitions);
+
+        assertSame(exception, invoker.invokePartitionsLost(partitions));
+        verifyNoInteractions(metricsManager);
+    }
+
+    @ParameterizedTest
+    @MethodSource("rethrownExceptions")
+    public void testInvokePartitionsAssignedRethrows(RuntimeException 
exception) {
+        when(subscriptions.hasRebalanceListener()).thenReturn(true);
+        
doThrow(exception).when(subscriptions).onPartitionsAssigned(partitions);
+
+        assertSame(exception, assertThrows(RuntimeException.class, () -> 
invoker.invokePartitionsAssigned(partitions)));
+        verifyNoInteractions(metricsManager);
+    }
+
+    @ParameterizedTest
+    @MethodSource("rethrownExceptions")
+    public void testInvokePartitionsRevokedRethrows(RuntimeException 
exception) {
+        when(subscriptions.hasRebalanceListener()).thenReturn(true);
+        when(subscriptions.pausedPartitions()).thenReturn(new HashSet<>());
+        doThrow(exception).when(subscriptions).onPartitionsRevoked(partitions);
+
+        assertSame(exception, assertThrows(RuntimeException.class, () -> 
invoker.invokePartitionsRevoked(partitions)));
+        verifyNoInteractions(metricsManager);
+    }
+
+    @ParameterizedTest
+    @MethodSource("rethrownExceptions")
+    public void testInvokePartitionsLostRethrows(RuntimeException exception) {
+        when(subscriptions.hasRebalanceListener()).thenReturn(true);
+        when(subscriptions.pausedPartitions()).thenReturn(new HashSet<>());
+        doThrow(exception).when(subscriptions).onPartitionsLost(partitions);
+
+        assertSame(exception, assertThrows(RuntimeException.class, () -> 
invoker.invokePartitionsLost(partitions)));
+        verifyNoInteractions(metricsManager);
+    }
+
+    private static Stream<RuntimeException> rethrownExceptions() {
+        return Stream.of(new WakeupException(), new InterruptException("Test 
interrupt"));

Review Comment:
   Why only these two? Why not some custom user exception? Is it swallowed by 
subscriptionstate ?



##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/ConsumerRebalanceListenerInvokerTest.java:
##########
@@ -0,0 +1,198 @@
+/*
+ * 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.kafka.clients.consumer.internals;
+
+import 
org.apache.kafka.clients.consumer.internals.metrics.RebalanceCallbackMetricsManager;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.InterruptException;
+import org.apache.kafka.common.errors.WakeupException;
+import org.apache.kafka.common.utils.MockTime;
+import org.apache.kafka.common.utils.internals.LogContext;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
+
+import java.util.HashSet;
+import java.util.SortedSet;
+import java.util.TreeSet;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+/**
+ * Tests the two things this invoker adds on top of the dispatch: it skips the 
dispatch entirely
+ * when no rebalance listener is registered, which is the case after
+ * {@link org.apache.kafka.clients.consumer.Consumer#setRebalanceListener(
+ * org.apache.kafka.clients.consumer.RebalanceListener)} is passed null, and 
it turns a failing
+ * listener into a returned exception while letting {@link WakeupException} and
+ * {@link InterruptException} through. The subscription state is mocked rather 
than real on purpose:
+ * a real one silently drops the callbacks itself, so it would hide whether 
the invoker checked at all.
+ */
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.STRICT_STUBS)
+public class ConsumerRebalanceListenerInvokerTest {
+
+    private final SortedSet<TopicPartition> partitions = new TreeSet<>(new 
Utils.TopicPartitionComparator());

Review Comment:
   AbstractMembershipManager.TOPIC_PARTITION_COMPARATOR ? I see that's the one 
being used in the async consumer test. Perhaps this is a better one -- might be 
good to pick one over the other in tests. I think this utils comparator is 
good, might be better to switch the other class



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to