Copilot commented on code in PR #25707: URL: https://github.com/apache/pulsar/pull/25707#discussion_r3199083067
########## pulsar-broker/src/main/java/org/apache/pulsar/broker/service/LegacyAwareTopicPoliciesService.java: ########## @@ -0,0 +1,137 @@ +/* + * 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.broker.service; + +import com.github.benmanes.caffeine.cache.AsyncCacheLoader; +import com.github.benmanes.caffeine.cache.AsyncLoadingCache; +import com.github.benmanes.caffeine.cache.Caffeine; +import com.google.common.annotations.VisibleForTesting; +import java.time.Duration; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import java.util.function.Consumer; +import lombok.CustomLog; +import org.apache.pulsar.broker.PulsarService; +import org.apache.pulsar.broker.systopic.NamespaceEventsSystemTopicFactory; +import org.apache.pulsar.common.events.EventType; +import org.apache.pulsar.common.naming.NamespaceName; +import org.apache.pulsar.common.naming.TopicName; +import org.apache.pulsar.common.policies.data.TopicPolicies; +import org.jspecify.annotations.NonNull; + +/** + * Routes topic policy operations to the legacy system-topic backend when a namespace already has + * a topic-policy {@code __change_events} system topic, and otherwise to the configured backend. + */ +@CustomLog +public class LegacyAwareTopicPoliciesService implements TopicPoliciesService { + + // Generally, we only need to check if the __change_events topic exists once because the __change_events topic + // should only be created by broker before the upgrade, where `SystemTopicBasedTopicPoliciesService` is configured + // as the topic policies service. + private final AsyncLoadingCache<NamespaceName, Boolean> isLegacyNamespace = Caffeine.newBuilder() + .expireAfterWrite(Duration.ofHours(1)) + .buildAsync(new AsyncCacheLoader<>() { + @NonNull + @Override + public CompletableFuture<? extends Boolean> asyncLoad(NamespaceName key, Executor executor) { + return NamespaceEventsSystemTopicFactory.checkSystemTopicExists(key, EventType.TOPIC_POLICY, + pulsar); + } + }); + private final PulsarService pulsar; Review Comment: `isLegacyNamespace` is initialized in a field initializer but its loader captures `pulsar`, which is assigned in the constructor. In Java, instance field initializers run before the constructor, so this will fail to compile (or risks using an uninitialized field). Initialize `isLegacyNamespace` in the constructor after assigning `this.pulsar`, or refactor the loader to avoid referencing `pulsar` during field initialization. ########## pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/TopicPoliciesTest.java: ########## @@ -2756,10 +2780,8 @@ public void testRemoveSubscribeRate() throws Exception { @Test public void testPublishRateInDifferentLevelPolicy() throws Exception { - cleanup(); - conf.setMaxPublishRatePerTopicInMessages(5); - conf.setMaxPublishRatePerTopicInBytes(50L); - setup(); + admin.brokers().updateDynamicConfiguration("maxPublishRatePerTopicInMessages", "5"); + admin.brokers().updateDynamicConfiguration("maxPublishRatePerTopicInBytes", "50"); Review Comment: With the suite now using a shared `@BeforeClass` broker, per-test dynamic config changes must be reliably reverted even when assertions fail. These updates are restored later in the test, but not in a `finally`/`@AfterMethod`, so a failure can leak config into subsequent tests and cause cascading/flaky failures. Wrap config mutation in `try/finally` (or centralize restoration in `@AfterMethod`) for this and similar patterns in this file (e.g., allowAutoTopicCreation, subscriptionTypesEnabled, restartBroker-based config changes). ########## pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/TopicPoliciesTest.java: ########## @@ -156,17 +159,38 @@ protected void setup() throws Exception { admin.namespaces().createNamespace(testTenant + "/" + testNamespace, Set.of("test")); admin.namespaces().createNamespace(myNamespaceV1); admin.topics().createPartitionedTopic(testTopic, testTopicPartitions); - Producer<?> producer = pulsarClient.newProducer().topic(testTopic).create(); - producer.close(); - waitForZooKeeperWatchers(); } - @AfterMethod(alwaysRun = true) + @AfterClass(alwaysRun = true) @Override public void cleanup() throws Exception { super.internalCleanup(); } + @BeforeMethod + void setupTestTopic() throws Exception { + // Recreate namespace to clear any policies set by previous tests + try { + admin.topics().deletePartitionedTopic(testTopic, true); + } catch (PulsarAdminException.NotFoundException e) { + // topic may already be deleted + } + admin.namespaces().deleteNamespace(myNamespace, true); + admin.namespaces().deleteNamespace(myNamespaceV1, true); Review Comment: Namespace deletion isn’t guarded the same way as topic deletion. If any test deletes `myNamespace`/`myNamespaceV1` (or fails mid-way), `deleteNamespace(...)` can throw and fail unrelated tests during `@BeforeMethod`. Consider handling `NotFoundException` (or checking existence) for the namespace deletions too to make the test fixture robust and reduce cascading failures. ########## pulsar-broker/src/test/java/org/apache/pulsar/broker/service/TopicPolicyTestUtils.java: ########## @@ -72,6 +72,13 @@ public static TopicPolicies getGlobalTopicPolicies(TopicPoliciesService topicPol public static Optional<TopicPolicies> getTopicPoliciesBypassCache(TopicPoliciesService topicPoliciesService, TopicName topicName, boolean isGlobal) throws Exception { + if (topicPoliciesService instanceof LegacyAwareTopicPoliciesService legacyService) { + TopicPoliciesService resolved = legacyService.resolveService(topicName.getNamespaceObject()).get(); + return getTopicPoliciesBypassCache(resolved, topicName, isGlobal); + } + if (topicPoliciesService instanceof MetadataStoreTopicPoliciesService metadataStoreService) { + return metadataStoreService.getTopicPoliciesDirectFromStore(topicName, isGlobal).get(); + } Review Comment: These `CompletableFuture.get()` calls have no timeout, which can hang the test suite indefinitely if the future never completes. Prefer a bounded wait (e.g., `get(timeout, unit)` with a clear failure) or use Awaitility to enforce a maximum time and produce better diagnostics on timeout. ########## pulsar-broker/src/main/java/org/apache/pulsar/broker/service/LegacyAwareTopicPoliciesService.java: ########## @@ -0,0 +1,137 @@ +/* + * 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.broker.service; + +import com.github.benmanes.caffeine.cache.AsyncCacheLoader; +import com.github.benmanes.caffeine.cache.AsyncLoadingCache; +import com.github.benmanes.caffeine.cache.Caffeine; +import com.google.common.annotations.VisibleForTesting; +import java.time.Duration; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import java.util.function.Consumer; +import lombok.CustomLog; +import org.apache.pulsar.broker.PulsarService; +import org.apache.pulsar.broker.systopic.NamespaceEventsSystemTopicFactory; +import org.apache.pulsar.common.events.EventType; +import org.apache.pulsar.common.naming.NamespaceName; +import org.apache.pulsar.common.naming.TopicName; +import org.apache.pulsar.common.policies.data.TopicPolicies; +import org.jspecify.annotations.NonNull; + +/** + * Routes topic policy operations to the legacy system-topic backend when a namespace already has + * a topic-policy {@code __change_events} system topic, and otherwise to the configured backend. + */ +@CustomLog +public class LegacyAwareTopicPoliciesService implements TopicPoliciesService { + + // Generally, we only need to check if the __change_events topic exists once because the __change_events topic + // should only be created by broker before the upgrade, where `SystemTopicBasedTopicPoliciesService` is configured + // as the topic policies service. + private final AsyncLoadingCache<NamespaceName, Boolean> isLegacyNamespace = Caffeine.newBuilder() + .expireAfterWrite(Duration.ofHours(1)) + .buildAsync(new AsyncCacheLoader<>() { + @NonNull + @Override + public CompletableFuture<? extends Boolean> asyncLoad(NamespaceName key, Executor executor) { + return NamespaceEventsSystemTopicFactory.checkSystemTopicExists(key, EventType.TOPIC_POLICY, + pulsar); + } + }); + private final PulsarService pulsar; + private final SystemTopicBasedTopicPoliciesService systemTopicService; + private final TopicPoliciesService configuredService; + + public LegacyAwareTopicPoliciesService(PulsarService pulsar, + SystemTopicBasedTopicPoliciesService systemTopicService, + TopicPoliciesService configuredService) { + this.pulsar = pulsar; + this.systemTopicService = systemTopicService; + this.configuredService = configuredService; + if (configuredService instanceof SystemTopicBasedTopicPoliciesService) { + throw new IllegalArgumentException( + "configuredService should not be an instance of SystemTopicBasedTopicPoliciesService"); + } + } + + @Override + public void start(PulsarService pulsarService) { + configuredService.start(pulsarService); Review Comment: `LegacyAwareTopicPoliciesService` can route requests to `systemTopicService`, but `start()` only starts `configuredService`. If `SystemTopicBasedTopicPoliciesService.start()` performs required initialization (caches/listeners/etc.), legacy namespaces may break at runtime. Start both services here (and consider ordering/exception handling), so whichever backend is selected is guaranteed initialized. ########## pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/TopicPoliciesTest.java: ########## @@ -4657,4 +4701,9 @@ public void testGetAppliedOffloadPoliciesWithLegacyNamespacePolicies() throws Ex assertEquals(offloadPolicies.getManagedLedgerOffloadThresholdInBytes(), (Long) (1024 * 1024 * 10L), "Should inherit offload threshold from legacy namespace policy"); } + + private void initEventsTopicAndPartitions() throws Exception { + Producer<?> producer = pulsarClient.newProducer().topic(testTopic).create(); + producer.close(); Review Comment: Resource cleanup should be exception-safe: if `create()` throws, `producer.close()` won’t run. Prefer try-with-resources or Lombok `@Cleanup` here to ensure the producer is always closed. -- 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]
