Savonitar commented on code in PR #287:
URL: 
https://github.com/apache/flink-connector-kafka/pull/287#discussion_r3737612561


##########
flink-connector-kafka/src/main/java/org/apache/flink/connector/kafka/source/enumerator/metadata/TopicIntegrityProvider.java:
##########
@@ -0,0 +1,174 @@
+/*
+ * 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.flink.connector.kafka.source.enumerator.metadata;
+
+import org.apache.flink.connector.kafka.util.AdminUtils;
+import org.apache.flink.util.ExceptionUtils;
+
+import org.apache.kafka.clients.admin.AdminClient;
+import org.apache.kafka.clients.admin.TopicDescription;
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.errors.UnknownTopicOrPartitionException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+/**
+ * Provider of topic integrity related functionalities for {@link
+ * org.apache.flink.connector.kafka.source.enumerator.KafkaSourceEnumerator}.
+ */
+public class TopicIntegrityProvider implements TopicMetadataProvider {

Review Comment:
   Should we wrap these new classes by Internal/PublicEvolving annotations?



##########
flink-connector-kafka/src/main/java/org/apache/flink/connector/kafka/source/enumerator/metadata/TopicIntegrityProvider.java:
##########
@@ -0,0 +1,174 @@
+/*
+ * 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.flink.connector.kafka.source.enumerator.metadata;
+
+import org.apache.flink.connector.kafka.util.AdminUtils;
+import org.apache.flink.util.ExceptionUtils;
+
+import org.apache.kafka.clients.admin.AdminClient;
+import org.apache.kafka.clients.admin.TopicDescription;
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.errors.UnknownTopicOrPartitionException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+/**
+ * Provider of topic integrity related functionalities for {@link
+ * org.apache.flink.connector.kafka.source.enumerator.KafkaSourceEnumerator}.
+ */
+public class TopicIntegrityProvider implements TopicMetadataProvider {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(TopicIntegrityProvider.class);
+    private final Map<String, String> trackedTopicIdsByName;
+
+    public TopicIntegrityProvider(Map<String, String> 
trackedTopicIdsByNameFromContext) {
+        trackedTopicIdsByName = new 
ConcurrentHashMap<>(trackedTopicIdsByNameFromContext);
+    }
+
+    @Override
+    public Map<String, TopicDescription> getTopicMetadata(
+            AdminClient adminClient, Pattern pattern) {
+        final Collection<String> topicsToVerifyInPatternMode =
+                trackedTopicIdsByName.keySet().stream()
+                        .filter(pattern.asPredicate())

Review Comment:
   If checkpointed state has `payments` and `payments-dql ` tracked, then we 
restore with a new pattern payments (no dql), will it still match 
`payments-dql` as a substring and as a result stay tracker forever even it is 
already out of scope for the new subscription and if it will be deleted, we 
will have a crash loop? 
   
   IIRC in FLIP discussion: topics no longer part of the subscription get 
dropped from tracked state and shouldn't fail the job). Should this match 
AdminUtils 
https://github.com/Efrat19/flink-connector-kafka/blob/cff2fbdebd80d3ef00d5f5fcfbf53db3fcf6155d/flink-connector-kafka/src/main/java/org/apache/flink/connector/kafka/util/AdminUtils.java#L62
 ? 



##########
flink-connector-kafka/src/test/java/org/apache/flink/connector/kafka/testutils/KafkaSourceTestEnv.java:
##########
@@ -274,4 +272,59 @@ public static void setupTopic(
             setupCommittedOffsets(topic);
         }
     }
+
+    public static String getTopicId(String topicName)
+            throws InterruptedException, ExecutionException {
+        return getAdminClient()
+                .listTopics()
+                .namesToListings()
+                .get()
+                .get(topicName)
+                .topicId()
+                .toString();
+    }
+
+    // Helper method to count records in a topic
+    private static long getRecordCountInTopic(String topicName) {
+        try (Consumer<String, Integer> consumer = getConsumer()) {
+            List<TopicPartition> partitions =
+                    consumer.partitionsFor(topicName).stream()
+                            .map(info -> new TopicPartition(topicName, 
info.partition()))
+                            .collect(Collectors.toList());
+
+            consumer.assign(partitions);
+            consumer.seekToBeginning(partitions);
+
+            long totalRecords = 0;
+            ConsumerRecords<String, Integer> records;
+            do {
+                records = consumer.poll(Duration.ofSeconds(1));
+                totalRecords += records.count();
+            } while (!records.isEmpty());
+
+            return totalRecords;
+        }
+    }
+
+    // Helper method to wait for specific number of records in a topic

Review Comment:
   do we need this comment if it almost repeats method name?



##########
flink-connector-kafka/src/test/java/org/apache/flink/connector/kafka/source/enumerator/KafkaSourceEnumeratorTest.java:
##########
@@ -62,6 +62,7 @@
 
 import static 
org.apache.flink.connector.kafka.source.split.KafkaPartitionSplit.MIGRATED;
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;

Review Comment:
   Sorry, I know many people are used to Junit assertions, however, [Flink 
guidelines](https://flink.apache.org/how-to-contribute/code-style-and-quality-common/#tooling)
 ask to use AssertJ: e.g. assertThat 



##########
flink-connector-kafka/src/test/java/org/apache/flink/connector/kafka/testutils/KafkaSourceTestEnv.java:
##########
@@ -274,4 +272,59 @@ public static void setupTopic(
             setupCommittedOffsets(topic);
         }
     }
+
+    public static String getTopicId(String topicName)
+            throws InterruptedException, ExecutionException {
+        return getAdminClient()
+                .listTopics()
+                .namesToListings()
+                .get()
+                .get(topicName)
+                .topicId()
+                .toString();
+    }
+
+    // Helper method to count records in a topic

Review Comment:
   do we need this comment if it almost repeats method name?



##########
flink-connector-kafka/src/test/java/org/apache/flink/connector/kafka/source/enumerator/TopicIntegrityProviderTest.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.flink.connector.kafka.source.enumerator;
+
+import 
org.apache.flink.connector.kafka.source.enumerator.metadata.TopicIntegrityException;
+import 
org.apache.flink.connector.kafka.source.enumerator.metadata.TopicIntegrityProvider;
+
+import org.apache.kafka.clients.admin.MockAdminClient;
+import org.apache.kafka.clients.admin.TopicDescription;
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.errors.UnknownTopicOrPartitionException;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Pattern;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.assertj.core.api.Assertions.entry;
+
+/** Unit tests for {@link TopicIntegrityProvider}. */
+class TopicIntegrityProviderTest {
+
+    private static final String TOPIC1 = "topic1";
+    private static final String TOPIC2 = "topic2";
+    private static MockAdminClient mockAdmin;
+
+    @BeforeEach
+    public void setup() {
+        mockAdmin = new MockAdminClient();
+    }
+
+    @Test
+    void testReturnsVerifiedTopics() throws Exception {
+        String id = addTopic(TOPIC1);
+
+        TopicIntegrityProvider provider = new 
TopicIntegrityProvider(Map.of(TOPIC1, id));
+
+        Map<String, TopicDescription> result =
+                provider.getTopicMetadata(mockAdmin, 
Collections.singletonList(TOPIC1));
+
+        assertThat(result).containsOnlyKeys(TOPIC1);
+        assertThat(result.get(TOPIC1).topicId().toString()).isEqualTo(id);
+    }
+
+    @Test
+    void testAddsNewlySubscribedTopicWithoutFailingIntegrityCheck() throws 
Exception {
+        String id = addTopic(TOPIC1);
+
+        TopicIntegrityProvider provider = new TopicIntegrityProvider(new 
HashMap<>());
+
+        provider.getTopicMetadata(mockAdmin, 
Collections.singletonList(TOPIC1));
+
+        
assertThat(provider.getTrackedTopicIdsByName()).containsExactly(entry(TOPIC1, 
id));
+    }
+
+    @Test
+    void testFailsIfTopicIsMissing() {
+        TopicIntegrityProvider provider =
+                new TopicIntegrityProvider(Map.of(TOPIC1, 
Uuid.randomUuid().toString()));
+
+        assertThatThrownBy(
+                        () ->
+                                provider.getTopicMetadata(
+                                        mockAdmin, 
Collections.singletonList(TOPIC1)))
+                .isInstanceOf(TopicIntegrityException.class)
+                .hasMessageContaining("Topic " + TOPIC1 + " is missing");
+    }
+
+    @Test
+    void testFailsIfTopicWasRecreated() throws Exception {
+        String originalId = addTopic(TOPIC1);
+
+        TopicIntegrityProvider provider = new 
TopicIntegrityProvider(Map.of(TOPIC1, originalId));
+
+        // Simulate recreation: delete and re-add under the same name, 
yielding a new id.
+        mockAdmin.deleteTopics(Collections.singletonList(TOPIC1)).all().get();
+        addTopic(TOPIC1);
+
+        assertThatThrownBy(
+                        () ->
+                                provider.getTopicMetadata(
+                                        mockAdmin, 
Collections.singletonList(TOPIC1)))
+                .isInstanceOf(TopicIntegrityException.class)
+                .hasMessageContaining("Topic " + TOPIC1 + " was recreated");
+    }
+
+    @Test
+    void 
testThrowsOriginalErrorWhenUnknownTopicExceptionIsNotDueToMissingTopic() throws 
Exception {
+        String id = addTopic(TOPIC1);
+        mockAdmin.markTopicForDeletion(TOPIC1);
+
+        TopicIntegrityProvider provider = new 
TopicIntegrityProvider(Map.of(TOPIC1, id));
+
+        assertThatThrownBy(
+                        () ->
+                                provider.getTopicMetadata(
+                                        mockAdmin, 
Collections.singletonList(TOPIC1)))
+                .isNotInstanceOf(TopicIntegrityException.class)
+                
.hasRootCauseInstanceOf(UnknownTopicOrPartitionException.class);
+    }
+
+    @Test
+    void testThrowsOriginalErrorForUnrelatedException() throws Exception {
+        String id = addTopic(TOPIC1);
+        mockAdmin.timeoutNextRequest(1);
+
+        TopicIntegrityProvider provider = new 
TopicIntegrityProvider(Map.of(TOPIC1, id));
+
+        assertThatThrownBy(
+                        () ->
+                                provider.getTopicMetadata(
+                                        mockAdmin, 
Collections.singletonList(TOPIC1)))
+                .isNotInstanceOf(TopicIntegrityException.class)
+                .hasRootCauseInstanceOf(TimeoutException.class);
+    }
+
+    @Test
+    void testRemovesOutdatedTopicFromMapping() throws Exception {
+        String id1 = addTopic(TOPIC1);
+
+        Map<String, String> tracked = new HashMap<>();
+        tracked.put(TOPIC1, id1);
+        tracked.put(TOPIC2, Uuid.randomUuid().toString());
+        TopicIntegrityProvider provider = new TopicIntegrityProvider(tracked);
+
+        // Only TOPIC1 is subscribed to anymore; TOPIC2 must be dropped from 
the tracked mapping.
+        provider.getTopicMetadata(mockAdmin, 
Collections.singletonList(TOPIC1));
+
+        
assertThat(provider.getTrackedTopicIdsByName()).containsExactly(entry(TOPIC1, 
id1));
+    }
+
+    @Test
+    void testPatternModeStillChecksTopicsThatDisappearedFromLiveMatch() {
+        TopicIntegrityProvider provider =
+                new TopicIntegrityProvider(Map.of(TOPIC1, 
Uuid.randomUuid().toString()));
+
+        assertThatThrownBy(() -> provider.getTopicMetadata(mockAdmin, 
Pattern.compile(".*")))
+                .isInstanceOf(TopicIntegrityException.class)
+                .hasMessageContaining("Topic " + TOPIC1 + " is missing");
+    }
+
+    @Test
+    void testGetTrackedTopicIdsByNameReturnsDefensiveCopy() {
+        TopicIntegrityProvider provider =
+                new TopicIntegrityProvider(Map.of(TOPIC1, 
Uuid.randomUuid().toString()));
+
+        Map<String, String> mapping = provider.getTrackedTopicIdsByName();
+        mapping.put(TOPIC2, Uuid.randomUuid().toString());
+
+        
assertThat(provider.getTrackedTopicIdsByName()).doesNotContainKey(TOPIC2);
+    }
+
+    @Test
+    void testEmptySubscriptionReturnsEmptyMetadataWithoutError() {
+        TopicIntegrityProvider provider = new TopicIntegrityProvider(new 
HashMap<>());
+
+        Map<String, TopicDescription> result =
+                provider.getTopicMetadata(mockAdmin, Collections.emptyList());
+
+        assertThat(result).isEmpty();
+        assertThat(provider.getTrackedTopicIdsByName()).isEmpty();
+    }
+
+    private static final String addTopic(String name) throws Exception {

Review Comment:
   nit: final is redundant here (the method is private and static)



##########
flink-connector-kafka/src/main/java/org/apache/flink/connector/kafka/source/enumerator/metadata/TopicIntegrityProvider.java:
##########
@@ -0,0 +1,164 @@
+/*
+ * 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.flink.connector.kafka.source.enumerator.metadata;
+
+import org.apache.flink.connector.kafka.util.AdminUtils;
+import org.apache.flink.util.ExceptionUtils;
+
+import org.apache.kafka.clients.admin.AdminClient;
+import org.apache.kafka.clients.admin.TopicDescription;
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.errors.UnknownTopicOrPartitionException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+/**
+ * Provider of topic integrity related functionalities for {@link
+ * org.apache.flink.connector.kafka.source.enumerator.KafkaSourceEnumerator}.
+ */
+public class TopicIntegrityProvider implements TopicMetadataProvider {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(TopicIntegrityProvider.class);
+    private final Map<String, String> trackedTopicIdsByName;
+
+    public TopicIntegrityProvider(Map<String, String> 
trackedTopicIdsByNameFromContext) {
+        trackedTopicIdsByName = new 
ConcurrentHashMap<>(trackedTopicIdsByNameFromContext);
+    }
+
+    @Override
+    public Map<String, TopicDescription> getTopicMetadata(
+            AdminClient adminClient, Pattern pattern) {
+        final Collection<String> topicsToVerifyInPatternMode =
+                trackedTopicIdsByName.keySet().stream()
+                        .filter(pattern.asPredicate())
+                        .collect(Collectors.toCollection(HashSet::new));
+        
topicsToVerifyInPatternMode.addAll(AdminUtils.getTopicsByPattern(adminClient, 
pattern));
+        return getTopicMetadata(adminClient, topicsToVerifyInPatternMode);
+    }
+
+    @Override
+    public Map<String, TopicDescription> getTopicMetadata(
+            AdminClient adminClient, Collection<String> subscribedTopicNames) {
+        Map<String, TopicDescription> topicMetadata;
+        try {
+            topicMetadata = AdminUtils.getTopicMetadata(adminClient, 
subscribedTopicNames);
+            failIfRecreated(subscribedTopicNames, topicMetadata);
+        } catch (RuntimeException original) {
+            if (ExceptionUtils.findThrowable(original, 
UnknownTopicOrPartitionException.class)
+                    .isPresent()) {
+                // UnknownTopicOrPartitionException can be transient due to 
broker timeout
+                // or permanent due to topic/partition loss.
+                // Determine if the exception is caused by a missing topic
+                // and if yes, trigger a TopicIntegrity failure instead
+                try {
+                    failIfMissing(subscribedTopicNames, 
adminClient.listTopics().names().get());
+                } catch (TopicIntegrityException missingTopicException) {
+                    throw missingTopicException;
+                } catch (Exception ignored) {
+                    // ignored so we fallback to the original error

Review Comment:
   Thanks for restoring the interrupt flag. nit: Btw, a dedicated `catch 
(InterruptedException ie)` before the `catch (Exception)` would do the same 
thing without the `instanceof`. 
   Not blocking. 



-- 
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