dajac commented on code in PR #21103: URL: https://github.com/apache/kafka/pull/21103#discussion_r2607117151
########## group-coordinator/src/main/java/org/apache/kafka/coordinator/group/modern/consumer/TopicRegexResolver.java: ########## @@ -0,0 +1,166 @@ +/* + * 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.coordinator.group.modern.consumer; + +import org.apache.kafka.common.internals.Plugin; +import org.apache.kafka.common.resource.ResourcePattern; +import org.apache.kafka.common.utils.Time; +import org.apache.kafka.coordinator.common.runtime.CoordinatorMetadataImage; +import org.apache.kafka.coordinator.group.Utils; +import org.apache.kafka.server.authorizer.Action; +import org.apache.kafka.server.authorizer.AuthorizableRequestContext; +import org.apache.kafka.server.authorizer.AuthorizationResult; +import org.apache.kafka.server.authorizer.Authorizer; + +import com.google.re2j.Pattern; +import com.google.re2j.PatternSyntaxException; + +import org.slf4j.Logger; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.apache.kafka.common.acl.AclOperation.DESCRIBE; +import static org.apache.kafka.common.resource.PatternType.LITERAL; +import static org.apache.kafka.common.resource.ResourceType.TOPIC; + +public class TopicRegexResolver { + + private final Supplier<Optional<Plugin<Authorizer>>> authorizerPluginSupplier; + private final Time time; + + public TopicRegexResolver( + Supplier<Optional<Plugin<Authorizer>>> authorizerPluginSupplier, + Time time + ) { + this.authorizerPluginSupplier = authorizerPluginSupplier; + this.time = time; + } + + /** + * Resolves the provided regular expressions. + * + * @param context The request context. + * @param groupId The group id. + * @param log The logger to use. + * @param metadataImage The metadata image to use for the resolution. + * @param regexes The list of regular expressions that must be resolved. + * @return The list of resolved regular expressions. + * + * public for benchmarks. + */ + public Map<String, ResolvedRegularExpression> resolveRegularExpressions( + AuthorizableRequestContext context, + String groupId, + Logger log, + CoordinatorMetadataImage metadataImage, + Set<String> regexes + ) { + long startTimeMs = time.milliseconds(); + log.debug("[GroupId {}] Refreshing regular expressions: {}", groupId, regexes); + + Map<String, Set<String>> resolvedRegexes = new HashMap<>(regexes.size()); + List<Pattern> compiledRegexes = new ArrayList<>(regexes.size()); + for (String regex : regexes) { + resolvedRegexes.put(regex, new HashSet<>()); + try { + compiledRegexes.add(Pattern.compile(regex)); + } catch (PatternSyntaxException ex) { + // This should not happen because the regular expressions are validated + // when received from the members. If for some reason, it would + // happen, we log it and ignore it. + log.error("[GroupId {}] Couldn't parse regular expression '{}' due to `{}`. Ignoring it.", + groupId, regex, ex.getDescription()); + } + } + + for (String topicName : metadataImage.topicNames()) { + for (Pattern regex : compiledRegexes) { + if (regex.matcher(topicName).matches()) { + resolvedRegexes.get(regex.pattern()).add(topicName); + } + } + } + + filterTopicDescribeAuthorizedTopics( + context, + resolvedRegexes + ); + + long version = metadataImage.version(); + Map<String, ResolvedRegularExpression> result = new HashMap<>(resolvedRegexes.size()); + for (Map.Entry<String, Set<String>> resolvedRegex : resolvedRegexes.entrySet()) { + result.put( + resolvedRegex.getKey(), + new ResolvedRegularExpression(resolvedRegex.getValue(), version, startTimeMs) + ); + } + + log.info("[GroupId {}] Scanned {} topics to refresh regular expressions {} in {}ms.", + groupId, metadataImage.topicNames().size(), resolvedRegexes.keySet(), + time.milliseconds() - startTimeMs); + + return result; + } + + /** + * This method filters the topics in the resolved regexes + * that the member is authorized to describe. + * + * @param context The request context. + * @param resolvedRegexes The map of the regex pattern and its set of matched topics. + */ + private void filterTopicDescribeAuthorizedTopics( + AuthorizableRequestContext context, + Map<String, Set<String>> resolvedRegexes Review Comment: nit: Indentation is off. ########## group-coordinator/src/test/java/org/apache/kafka/coordinator/group/modern/consumer/TopicRegexResolverTest.java: ########## @@ -0,0 +1,144 @@ +/* + * 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.coordinator.group.modern.consumer; + +import org.apache.kafka.common.Uuid; +import org.apache.kafka.common.internals.Plugin; +import org.apache.kafka.common.metadata.TopicRecord; +import org.apache.kafka.common.utils.MockTime; +import org.apache.kafka.common.utils.Time; +import org.apache.kafka.coordinator.common.runtime.CoordinatorMetadataImage; +import org.apache.kafka.coordinator.common.runtime.KRaftCoordinatorMetadataImage; +import org.apache.kafka.image.MetadataDelta; +import org.apache.kafka.image.MetadataImage; +import org.apache.kafka.image.MetadataProvenance; +import org.apache.kafka.server.authorizer.Action; +import org.apache.kafka.server.authorizer.AuthorizationResult; +import org.apache.kafka.server.authorizer.Authorizer; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class TopicRegexResolverTest { + + private final Logger log = LoggerFactory.getLogger(TopicRegexResolverTest.class); + + private static CoordinatorMetadataImage imageWithTopics(String... topicNames) { + MetadataDelta delta = new MetadataDelta(MetadataImage.EMPTY); + for (String topic : topicNames) { + delta.replay(new TopicRecord() + .setName(topic) + .setTopicId(Uuid.randomUuid())); + } + MetadataImage image = delta.apply(MetadataProvenance.EMPTY); + return new KRaftCoordinatorMetadataImage(image); + } + + @Test + public void testBasicMatching() { + CoordinatorMetadataImage image = imageWithTopics("foo", "bar", "baz", "qux"); + Time time = new MockTime(0L, 0L, 0L); + + TopicRegexResolver resolver = new TopicRegexResolver(Optional::empty, time); + + Map<String, ResolvedRegularExpression> result = resolver.resolveRegularExpressions( + null, + "group-1", + log, + image, + Set.of("ba.*") + ); + + ResolvedRegularExpression resolved = result.get("ba.*"); + assertEquals(Set.of("bar", "baz"), resolved.topics()); + assertEquals(image.version(), resolved.version()); + assertEquals(0L, resolved.timestamp()); + } + + @Test + public void testInvalidRegexIgnored() { + CoordinatorMetadataImage image = imageWithTopics("foo", "bar"); + Time time = new MockTime(5L, 0L, 0L); + + TopicRegexResolver resolver = new TopicRegexResolver(Optional::empty, time); + + Map<String, ResolvedRegularExpression> result = resolver.resolveRegularExpressions( + null, + "group-2", + log, + image, + Set.of("a.*") + ); + + ResolvedRegularExpression resolved = result.get("a.*"); + assertTrue(resolved.topics().isEmpty()); + assertEquals(image.version(), resolved.version()); + assertEquals(5L, resolved.timestamp()); + } + + @Test + public void testAuthorizationFiltering() { + CoordinatorMetadataImage image = imageWithTopics("allow1", "deny1", "allow2"); + Time time = new MockTime(10L, 0L, 0L); + + Authorizer authorizer = mock(Authorizer.class); + when(authorizer.authorize(any(), any())).thenAnswer(invocation -> { + List<Action> actions = invocation.getArgument(1); + List<AuthorizationResult> results = new ArrayList<>(actions.size()); + for (Action action : actions) { + String topic = action.resourcePattern().name(); + results.add("deny1".equals(topic) ? AuthorizationResult.DENIED : AuthorizationResult.ALLOWED); + } + return results; + }); + + Plugin<Authorizer> plugin = Plugin.wrapInstance(authorizer, null, "authorizer.class.name"); + + TopicRegexResolver resolver = new TopicRegexResolver(() -> Optional.of(plugin), time); + + Map<String, ResolvedRegularExpression> result = resolver.resolveRegularExpressions( Review Comment: nit: We could use `var` in many place to simplify the code. ########## group-coordinator/src/test/java/org/apache/kafka/coordinator/group/modern/consumer/TopicRegexResolverTest.java: ########## @@ -0,0 +1,144 @@ +/* + * 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.coordinator.group.modern.consumer; + +import org.apache.kafka.common.Uuid; +import org.apache.kafka.common.internals.Plugin; +import org.apache.kafka.common.metadata.TopicRecord; +import org.apache.kafka.common.utils.MockTime; +import org.apache.kafka.common.utils.Time; +import org.apache.kafka.coordinator.common.runtime.CoordinatorMetadataImage; +import org.apache.kafka.coordinator.common.runtime.KRaftCoordinatorMetadataImage; +import org.apache.kafka.image.MetadataDelta; +import org.apache.kafka.image.MetadataImage; +import org.apache.kafka.image.MetadataProvenance; +import org.apache.kafka.server.authorizer.Action; +import org.apache.kafka.server.authorizer.AuthorizationResult; +import org.apache.kafka.server.authorizer.Authorizer; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class TopicRegexResolverTest { + + private final Logger log = LoggerFactory.getLogger(TopicRegexResolverTest.class); + + private static CoordinatorMetadataImage imageWithTopics(String... topicNames) { + MetadataDelta delta = new MetadataDelta(MetadataImage.EMPTY); + for (String topic : topicNames) { + delta.replay(new TopicRecord() + .setName(topic) + .setTopicId(Uuid.randomUuid())); + } + MetadataImage image = delta.apply(MetadataProvenance.EMPTY); + return new KRaftCoordinatorMetadataImage(image); + } + + @Test + public void testBasicMatching() { + CoordinatorMetadataImage image = imageWithTopics("foo", "bar", "baz", "qux"); Review Comment: nit: Could we reuse the `MetadataImageBuilder` that we use in other group coordinator tests? -- 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]
