You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by GitBox <gi...@apache.org> on 2022/11/03 04:11:47 UTC

[GitHub] [pulsar] Pomelongan opened a new pull request, #18312: [improve][broker]optimize the logic of internalCreatePartitionedTopic

Pomelongan opened a new pull request, #18312:
URL: https://github.com/apache/pulsar/pull/18312

   ### Motivation
   In `org.apache.pulsar.broker.admin.AdminResource#internalCreatePartitionedTopic`:
   
   - some logical order can be optimized. For example, can first execute `validateNamespaceOperation` for permission verification.
   - some log printing can be merged.see line 613,622,655
   
   https://github.com/apache/pulsar/blob/2bed5ff3ab9dbb8c57c0d4d29a5a6775a610d326/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/AdminResource.java#L613-L623
   
   https://github.com/apache/pulsar/blob/2bed5ff3ab9dbb8c57c0d4d29a5a6775a610d326/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/AdminResource.java#L654-L656
   
   ### Modifications
   Optimize the logical order and log printing of  `org.apache.pulsar.broker.admin.AdminResource#internalCreatePartitionedTopic`.
   
   
   ### Verifying this change
   
   - [x] Make sure that the change passes the CI checks.
   
   This change is a trivial rework / code cleanup without any test coverage.
   
   ### Does this pull request potentially affect one of the following parts:
   
   *If the box was checked, please highlight the changes*
   
   - [ ] Dependencies (add or upgrade a dependency)
   - [ ] The public API
   - [ ] The schema
   - [ ] The default values of configurations
   - [ ] The binary protocol
   - [ ] The REST endpoints
   - [ ] The admin CLI options
   - [ ] Anything that affects deployment
   
   ### Documentation
   
   <!-- DO NOT REMOVE THIS SECTION. CHECK THE PROPER BOX ONLY. -->
   
   - [ ] `doc` <!-- Your PR contains doc changes -->
   - [ ] `doc-required` <!-- Your PR changes impact docs and you will update later -->
   - [x] `doc-not-needed` <!-- Your PR changes do not impact docs -->
   - [ ] `doc-complete` <!-- Docs have been already added -->
   
   ### Matching PR in forked repository
   
   PR in forked repository: https://github.com/Pomelongan/pulsar/pull/12


-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] AnonHxy commented on a diff in pull request #18312: [improve][broker]optimize the logic of internalCreatePartitionedTopic

Posted by GitBox <gi...@apache.org>.
AnonHxy commented on code in PR #18312:
URL: https://github.com/apache/pulsar/pull/18312#discussion_r1012924553


##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/AdminResource.java:
##########
@@ -576,124 +576,80 @@ protected void internalCreatePartitionedTopic(AsyncResponse asyncResponse, int n
 
     protected void internalCreatePartitionedTopic(AsyncResponse asyncResponse, int numPartitions,
                                                   boolean createLocalTopicOnly, Map<String, String> properties) {
-        Integer maxTopicsPerNamespace = null;
-
-        try {
-            Policies policies = getNamespacePolicies(namespaceName);
-            maxTopicsPerNamespace = policies.max_topics_per_namespace;
-        } catch (RestException e) {
-            if (e.getResponse().getStatus() != Status.NOT_FOUND.getStatusCode()) {
-                log.error("[{}] Failed to create partitioned topic {}", clientAppId(), namespaceName, e);
-                resumeAsyncResponseExceptionally(asyncResponse, e);
-                return;
-            }
-        }
-
-        try {
-            if (maxTopicsPerNamespace == null) {
-                maxTopicsPerNamespace = pulsar().getConfig().getMaxTopicsPerNamespace();
-            }
-
-            // new create check
-            if (maxTopicsPerNamespace > 0 && !pulsar().getBrokerService().isSystemTopic(topicName)) {
-                List<String> partitionedTopics = getTopicPartitionList(TopicDomain.persistent);
-                // exclude created system topic
-                long topicsCount =
-                        partitionedTopics.stream().filter(t ->
-                                        !pulsar().getBrokerService().isSystemTopic(TopicName.get(t))).count();
-                if (topicsCount + numPartitions > maxTopicsPerNamespace) {
-                    log.error("[{}] Failed to create partitioned topic {}, "
-                            + "exceed maximum number of topics in namespace", clientAppId(), topicName);
-                    resumeAsyncResponseExceptionally(asyncResponse, new RestException(Status.PRECONDITION_FAILED,
-                            "Exceed maximum number of topics in namespace."));
-                    return;
-                }
-            }
-        } catch (Exception e) {
-            log.error("[{}] Failed to create partitioned topic {}", clientAppId(), namespaceName, e);
-            resumeAsyncResponseExceptionally(asyncResponse, e);
-            return;
-        }
-
-        final int maxPartitions = pulsar().getConfig().getMaxNumPartitionsPerPartitionedTopic();
-        try {
-            validateNamespaceOperation(topicName.getNamespaceObject(), NamespaceOperation.CREATE_TOPIC);
-        } catch (Exception e) {
-            log.error("[{}] Failed to create partitioned topic {}", clientAppId(), topicName, e);
-            resumeAsyncResponseExceptionally(asyncResponse, e);
-            return;
-        }
-        if (numPartitions <= 0) {
-            asyncResponse.resume(new RestException(Status.NOT_ACCEPTABLE,
-                    "Number of partitions should be more than 0"));
-            return;
-        }
-        if (maxPartitions > 0 && numPartitions > maxPartitions) {
-            asyncResponse.resume(new RestException(Status.NOT_ACCEPTABLE,
-                    "Number of partitions should be less than or equal to " + maxPartitions));
-            return;
-        }
+        validateNamespaceOperationAsync(topicName.getNamespaceObject(), NamespaceOperation.CREATE_TOPIC)
+                .thenCompose(__ -> getNamespacePoliciesAsync(namespaceName))
+                .handle((policies, ex) -> {
+                    if (ex != null
+                            && (!(ex.getCause() instanceof RestException)
+                            || ((RestException) ex.getCause()).getResponse().getStatus()
+                            != Status.NOT_FOUND.getStatusCode())) {
+                        throw new RestException(ex);
+                    }
 
-        CompletableFuture<Void> createLocalFuture = new CompletableFuture<>();
-        checkTopicExistsAsync(topicName).thenAccept(exists -> {
-            if (exists) {
-                log.warn("[{}] Failed to create already existing topic {}", clientAppId(), topicName);
-                asyncResponse.resume(new RestException(Status.CONFLICT, "This topic already exists"));
-                return;
-            }
+                    if (numPartitions <= 0) {
+                        throw new RestException(Status.NOT_ACCEPTABLE, "Number of partitions should be more than 0.");
+                    }
+                    int maxTopicsPerNamespace = policies != null && policies.max_topics_per_namespace != null
+                            ? policies.max_topics_per_namespace : pulsar().getConfig().getMaxTopicsPerNamespace();
+                    if (maxTopicsPerNamespace > 0 && !pulsar().getBrokerService().isSystemTopic(topicName)) {
+                        List<String> partitionedTopics = getTopicPartitionList(TopicDomain.persistent);
+                        // exclude created system topic
+                        long topicsCount = partitionedTopics.stream().filter(t ->
+                                !pulsar().getBrokerService().isSystemTopic(TopicName.get(t))).count();
+                        if (topicsCount + numPartitions > maxTopicsPerNamespace) {
+                            throw new RestException(Status.PRECONDITION_FAILED,
+                                    "Exceed maximum number of topics in namespace.");
+                        }
+                    }
 
-            provisionPartitionedTopicPath(numPartitions, createLocalTopicOnly, properties)
-                    .thenCompose(ignored -> tryCreatePartitionsAsync(numPartitions))
-                    .whenComplete((ignored, ex) -> {
-                        if (ex != null) {
-                            createLocalFuture.completeExceptionally(ex);
-                            return;
+                    int maxPartitions = pulsar().getConfig().getMaxNumPartitionsPerPartitionedTopic();
+                    if (maxPartitions > 0 && numPartitions > maxPartitions) {
+                        throw new RestException(Status.NOT_ACCEPTABLE,
+                                "Number of partitions should be less than or equal to " + maxPartitions);
+                    }
+                    return checkTopicExistsAsync(topicName).thenAccept(exists -> {

Review Comment:
   We should not return `CompleteFutrure` in  `handle` method



##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/AdminResource.java:
##########
@@ -576,124 +576,80 @@ protected void internalCreatePartitionedTopic(AsyncResponse asyncResponse, int n
 
     protected void internalCreatePartitionedTopic(AsyncResponse asyncResponse, int numPartitions,
                                                   boolean createLocalTopicOnly, Map<String, String> properties) {
-        Integer maxTopicsPerNamespace = null;
-
-        try {
-            Policies policies = getNamespacePolicies(namespaceName);
-            maxTopicsPerNamespace = policies.max_topics_per_namespace;
-        } catch (RestException e) {
-            if (e.getResponse().getStatus() != Status.NOT_FOUND.getStatusCode()) {
-                log.error("[{}] Failed to create partitioned topic {}", clientAppId(), namespaceName, e);
-                resumeAsyncResponseExceptionally(asyncResponse, e);
-                return;
-            }
-        }
-
-        try {
-            if (maxTopicsPerNamespace == null) {
-                maxTopicsPerNamespace = pulsar().getConfig().getMaxTopicsPerNamespace();
-            }
-
-            // new create check
-            if (maxTopicsPerNamespace > 0 && !pulsar().getBrokerService().isSystemTopic(topicName)) {
-                List<String> partitionedTopics = getTopicPartitionList(TopicDomain.persistent);
-                // exclude created system topic
-                long topicsCount =
-                        partitionedTopics.stream().filter(t ->
-                                        !pulsar().getBrokerService().isSystemTopic(TopicName.get(t))).count();
-                if (topicsCount + numPartitions > maxTopicsPerNamespace) {
-                    log.error("[{}] Failed to create partitioned topic {}, "
-                            + "exceed maximum number of topics in namespace", clientAppId(), topicName);
-                    resumeAsyncResponseExceptionally(asyncResponse, new RestException(Status.PRECONDITION_FAILED,
-                            "Exceed maximum number of topics in namespace."));
-                    return;
-                }
-            }
-        } catch (Exception e) {
-            log.error("[{}] Failed to create partitioned topic {}", clientAppId(), namespaceName, e);
-            resumeAsyncResponseExceptionally(asyncResponse, e);
-            return;
-        }
-
-        final int maxPartitions = pulsar().getConfig().getMaxNumPartitionsPerPartitionedTopic();
-        try {
-            validateNamespaceOperation(topicName.getNamespaceObject(), NamespaceOperation.CREATE_TOPIC);
-        } catch (Exception e) {
-            log.error("[{}] Failed to create partitioned topic {}", clientAppId(), topicName, e);
-            resumeAsyncResponseExceptionally(asyncResponse, e);
-            return;
-        }
-        if (numPartitions <= 0) {
-            asyncResponse.resume(new RestException(Status.NOT_ACCEPTABLE,
-                    "Number of partitions should be more than 0"));
-            return;
-        }
-        if (maxPartitions > 0 && numPartitions > maxPartitions) {
-            asyncResponse.resume(new RestException(Status.NOT_ACCEPTABLE,
-                    "Number of partitions should be less than or equal to " + maxPartitions));
-            return;
-        }
+        validateNamespaceOperationAsync(topicName.getNamespaceObject(), NamespaceOperation.CREATE_TOPIC)
+                .thenCompose(__ -> getNamespacePoliciesAsync(namespaceName))
+                .handle((policies, ex) -> {
+                    if (ex != null
+                            && (!(ex.getCause() instanceof RestException)
+                            || ((RestException) ex.getCause()).getResponse().getStatus()
+                            != Status.NOT_FOUND.getStatusCode())) {
+                        throw new RestException(ex);
+                    }
 
-        CompletableFuture<Void> createLocalFuture = new CompletableFuture<>();
-        checkTopicExistsAsync(topicName).thenAccept(exists -> {
-            if (exists) {
-                log.warn("[{}] Failed to create already existing topic {}", clientAppId(), topicName);
-                asyncResponse.resume(new RestException(Status.CONFLICT, "This topic already exists"));
-                return;
-            }
+                    if (numPartitions <= 0) {

Review Comment:
   How about verify this in the very first line?



##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/AdminResource.java:
##########
@@ -576,124 +576,80 @@ protected void internalCreatePartitionedTopic(AsyncResponse asyncResponse, int n
 
     protected void internalCreatePartitionedTopic(AsyncResponse asyncResponse, int numPartitions,
                                                   boolean createLocalTopicOnly, Map<String, String> properties) {
-        Integer maxTopicsPerNamespace = null;
-
-        try {
-            Policies policies = getNamespacePolicies(namespaceName);
-            maxTopicsPerNamespace = policies.max_topics_per_namespace;
-        } catch (RestException e) {
-            if (e.getResponse().getStatus() != Status.NOT_FOUND.getStatusCode()) {
-                log.error("[{}] Failed to create partitioned topic {}", clientAppId(), namespaceName, e);
-                resumeAsyncResponseExceptionally(asyncResponse, e);
-                return;
-            }
-        }
-
-        try {
-            if (maxTopicsPerNamespace == null) {
-                maxTopicsPerNamespace = pulsar().getConfig().getMaxTopicsPerNamespace();
-            }
-
-            // new create check
-            if (maxTopicsPerNamespace > 0 && !pulsar().getBrokerService().isSystemTopic(topicName)) {
-                List<String> partitionedTopics = getTopicPartitionList(TopicDomain.persistent);
-                // exclude created system topic
-                long topicsCount =
-                        partitionedTopics.stream().filter(t ->
-                                        !pulsar().getBrokerService().isSystemTopic(TopicName.get(t))).count();
-                if (topicsCount + numPartitions > maxTopicsPerNamespace) {
-                    log.error("[{}] Failed to create partitioned topic {}, "
-                            + "exceed maximum number of topics in namespace", clientAppId(), topicName);
-                    resumeAsyncResponseExceptionally(asyncResponse, new RestException(Status.PRECONDITION_FAILED,
-                            "Exceed maximum number of topics in namespace."));
-                    return;
-                }
-            }
-        } catch (Exception e) {
-            log.error("[{}] Failed to create partitioned topic {}", clientAppId(), namespaceName, e);
-            resumeAsyncResponseExceptionally(asyncResponse, e);
-            return;
-        }
-
-        final int maxPartitions = pulsar().getConfig().getMaxNumPartitionsPerPartitionedTopic();
-        try {
-            validateNamespaceOperation(topicName.getNamespaceObject(), NamespaceOperation.CREATE_TOPIC);
-        } catch (Exception e) {
-            log.error("[{}] Failed to create partitioned topic {}", clientAppId(), topicName, e);
-            resumeAsyncResponseExceptionally(asyncResponse, e);
-            return;
-        }
-        if (numPartitions <= 0) {
-            asyncResponse.resume(new RestException(Status.NOT_ACCEPTABLE,
-                    "Number of partitions should be more than 0"));
-            return;
-        }
-        if (maxPartitions > 0 && numPartitions > maxPartitions) {
-            asyncResponse.resume(new RestException(Status.NOT_ACCEPTABLE,
-                    "Number of partitions should be less than or equal to " + maxPartitions));
-            return;
-        }
+        validateNamespaceOperationAsync(topicName.getNamespaceObject(), NamespaceOperation.CREATE_TOPIC)
+                .thenCompose(__ -> getNamespacePoliciesAsync(namespaceName))
+                .handle((policies, ex) -> {
+                    if (ex != null
+                            && (!(ex.getCause() instanceof RestException)
+                            || ((RestException) ex.getCause()).getResponse().getStatus()
+                            != Status.NOT_FOUND.getStatusCode())) {
+                        throw new RestException(ex);
+                    }
 
-        CompletableFuture<Void> createLocalFuture = new CompletableFuture<>();
-        checkTopicExistsAsync(topicName).thenAccept(exists -> {
-            if (exists) {
-                log.warn("[{}] Failed to create already existing topic {}", clientAppId(), topicName);
-                asyncResponse.resume(new RestException(Status.CONFLICT, "This topic already exists"));
-                return;
-            }
+                    if (numPartitions <= 0) {
+                        throw new RestException(Status.NOT_ACCEPTABLE, "Number of partitions should be more than 0.");
+                    }
+                    int maxTopicsPerNamespace = policies != null && policies.max_topics_per_namespace != null
+                            ? policies.max_topics_per_namespace : pulsar().getConfig().getMaxTopicsPerNamespace();
+                    if (maxTopicsPerNamespace > 0 && !pulsar().getBrokerService().isSystemTopic(topicName)) {
+                        List<String> partitionedTopics = getTopicPartitionList(TopicDomain.persistent);
+                        // exclude created system topic
+                        long topicsCount = partitionedTopics.stream().filter(t ->
+                                !pulsar().getBrokerService().isSystemTopic(TopicName.get(t))).count();
+                        if (topicsCount + numPartitions > maxTopicsPerNamespace) {
+                            throw new RestException(Status.PRECONDITION_FAILED,
+                                    "Exceed maximum number of topics in namespace.");
+                        }
+                    }
 
-            provisionPartitionedTopicPath(numPartitions, createLocalTopicOnly, properties)
-                    .thenCompose(ignored -> tryCreatePartitionsAsync(numPartitions))
-                    .whenComplete((ignored, ex) -> {
-                        if (ex != null) {
-                            createLocalFuture.completeExceptionally(ex);
-                            return;
+                    int maxPartitions = pulsar().getConfig().getMaxNumPartitionsPerPartitionedTopic();
+                    if (maxPartitions > 0 && numPartitions > maxPartitions) {
+                        throw new RestException(Status.NOT_ACCEPTABLE,
+                                "Number of partitions should be less than or equal to " + maxPartitions);
+                    }
+                    return checkTopicExistsAsync(topicName).thenAccept(exists -> {
+                        if (exists) {
+                            log.warn("[{}] Failed to create already existing topic {}", clientAppId(), topicName);
+                            throw new RestException(Status.CONFLICT, "This topic already exists");
                         }
-                        createLocalFuture.complete(null);
                     });
-        }).exceptionally(ex -> {
-            log.error("[{}] Failed to create partitioned topic {}", clientAppId(), topicName, ex);
-            resumeAsyncResponseExceptionally(asyncResponse, ex);
-            return null;
-        });
-
-        List<String> replicatedClusters = new ArrayList<>();
-        if (!createLocalTopicOnly && topicName.isGlobal() && isNamespaceReplicated(namespaceName)) {
-            getNamespaceReplicatedClusters(namespaceName)
-                    .stream().filter(cluster -> !cluster.equals(pulsar().getConfiguration().getClusterName()))
-                    .forEach(replicatedClusters::add);
-        }
-        createLocalFuture.whenComplete((ignored, ex) -> {
-            if (ex != null) {
-                log.error("[{}] Failed to create partitions for topic {}", clientAppId(), topicName, ex.getCause());
-                if (ex.getCause() instanceof RestException) {
-                    asyncResponse.resume(ex.getCause());
-                } else {
-                    resumeAsyncResponseExceptionally(asyncResponse, ex.getCause());
-                }
-                return;
-            }
-
-            if (!replicatedClusters.isEmpty()) {
-                replicatedClusters.forEach(cluster -> {
-                    pulsar().getPulsarResources().getClusterResources().getClusterAsync(cluster)
-                            .thenAccept(clusterDataOp -> {
-                                ((TopicsImpl) pulsar().getBrokerService()
-                                        .getClusterPulsarAdmin(cluster, clusterDataOp).topics())
-                                        .createPartitionedTopicAsync(
-                                                topicName.getPartitionedTopicName(), numPartitions, true, null);
-                            })
-                            .exceptionally(throwable -> {
-                                log.error("Failed to create partition topic in cluster {}.", cluster, throwable);
-                                return null;
-                            });
+                })
+                .thenCompose(__ -> provisionPartitionedTopicPath(numPartitions, createLocalTopicOnly, properties))
+                .thenCompose(__ -> tryCreatePartitionsAsync(numPartitions))
+                .thenAccept(__ -> {

Review Comment:
   `thenRun` is better 



-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] Pomelongan closed pull request #18312: [improve][admin] Optimize the logic of internalCreatePartitionedTopic

Posted by GitBox <gi...@apache.org>.
Pomelongan closed pull request #18312: [improve][admin] Optimize the logic of internalCreatePartitionedTopic
URL: https://github.com/apache/pulsar/pull/18312


-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] Pomelongan commented on a diff in pull request #18312: [improve][admin] Optimize the logic of internalCreatePartitionedTopic

Posted by GitBox <gi...@apache.org>.
Pomelongan commented on code in PR #18312:
URL: https://github.com/apache/pulsar/pull/18312#discussion_r1013697270


##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/AdminResource.java:
##########
@@ -576,124 +576,80 @@ protected void internalCreatePartitionedTopic(AsyncResponse asyncResponse, int n
 
     protected void internalCreatePartitionedTopic(AsyncResponse asyncResponse, int numPartitions,
                                                   boolean createLocalTopicOnly, Map<String, String> properties) {
-        Integer maxTopicsPerNamespace = null;
-
-        try {
-            Policies policies = getNamespacePolicies(namespaceName);
-            maxTopicsPerNamespace = policies.max_topics_per_namespace;
-        } catch (RestException e) {
-            if (e.getResponse().getStatus() != Status.NOT_FOUND.getStatusCode()) {
-                log.error("[{}] Failed to create partitioned topic {}", clientAppId(), namespaceName, e);
-                resumeAsyncResponseExceptionally(asyncResponse, e);
-                return;
-            }
-        }
-
-        try {
-            if (maxTopicsPerNamespace == null) {
-                maxTopicsPerNamespace = pulsar().getConfig().getMaxTopicsPerNamespace();
-            }
-
-            // new create check
-            if (maxTopicsPerNamespace > 0 && !pulsar().getBrokerService().isSystemTopic(topicName)) {
-                List<String> partitionedTopics = getTopicPartitionList(TopicDomain.persistent);
-                // exclude created system topic
-                long topicsCount =
-                        partitionedTopics.stream().filter(t ->
-                                        !pulsar().getBrokerService().isSystemTopic(TopicName.get(t))).count();
-                if (topicsCount + numPartitions > maxTopicsPerNamespace) {
-                    log.error("[{}] Failed to create partitioned topic {}, "
-                            + "exceed maximum number of topics in namespace", clientAppId(), topicName);
-                    resumeAsyncResponseExceptionally(asyncResponse, new RestException(Status.PRECONDITION_FAILED,
-                            "Exceed maximum number of topics in namespace."));
-                    return;
-                }
-            }
-        } catch (Exception e) {
-            log.error("[{}] Failed to create partitioned topic {}", clientAppId(), namespaceName, e);
-            resumeAsyncResponseExceptionally(asyncResponse, e);
-            return;
-        }
-
-        final int maxPartitions = pulsar().getConfig().getMaxNumPartitionsPerPartitionedTopic();
-        try {
-            validateNamespaceOperation(topicName.getNamespaceObject(), NamespaceOperation.CREATE_TOPIC);
-        } catch (Exception e) {
-            log.error("[{}] Failed to create partitioned topic {}", clientAppId(), topicName, e);
-            resumeAsyncResponseExceptionally(asyncResponse, e);
-            return;
-        }
-        if (numPartitions <= 0) {
-            asyncResponse.resume(new RestException(Status.NOT_ACCEPTABLE,
-                    "Number of partitions should be more than 0"));
-            return;
-        }
-        if (maxPartitions > 0 && numPartitions > maxPartitions) {
-            asyncResponse.resume(new RestException(Status.NOT_ACCEPTABLE,
-                    "Number of partitions should be less than or equal to " + maxPartitions));
-            return;
-        }
+        validateNamespaceOperationAsync(topicName.getNamespaceObject(), NamespaceOperation.CREATE_TOPIC)
+                .thenCompose(__ -> getNamespacePoliciesAsync(namespaceName))
+                .handle((policies, ex) -> {
+                    if (ex != null
+                            && (!(ex.getCause() instanceof RestException)
+                            || ((RestException) ex.getCause()).getResponse().getStatus()
+                            != Status.NOT_FOUND.getStatusCode())) {
+                        throw new RestException(ex);
+                    }
 
-        CompletableFuture<Void> createLocalFuture = new CompletableFuture<>();
-        checkTopicExistsAsync(topicName).thenAccept(exists -> {
-            if (exists) {
-                log.warn("[{}] Failed to create already existing topic {}", clientAppId(), topicName);
-                asyncResponse.resume(new RestException(Status.CONFLICT, "This topic already exists"));
-                return;
-            }
+                    if (numPartitions <= 0) {
+                        throw new RestException(Status.NOT_ACCEPTABLE, "Number of partitions should be more than 0.");
+                    }
+                    int maxTopicsPerNamespace = policies != null && policies.max_topics_per_namespace != null
+                            ? policies.max_topics_per_namespace : pulsar().getConfig().getMaxTopicsPerNamespace();
+                    if (maxTopicsPerNamespace > 0 && !pulsar().getBrokerService().isSystemTopic(topicName)) {
+                        List<String> partitionedTopics = getTopicPartitionList(TopicDomain.persistent);
+                        // exclude created system topic
+                        long topicsCount = partitionedTopics.stream().filter(t ->
+                                !pulsar().getBrokerService().isSystemTopic(TopicName.get(t))).count();
+                        if (topicsCount + numPartitions > maxTopicsPerNamespace) {
+                            throw new RestException(Status.PRECONDITION_FAILED,
+                                    "Exceed maximum number of topics in namespace.");
+                        }
+                    }
 
-            provisionPartitionedTopicPath(numPartitions, createLocalTopicOnly, properties)
-                    .thenCompose(ignored -> tryCreatePartitionsAsync(numPartitions))
-                    .whenComplete((ignored, ex) -> {
-                        if (ex != null) {
-                            createLocalFuture.completeExceptionally(ex);
-                            return;
+                    int maxPartitions = pulsar().getConfig().getMaxNumPartitionsPerPartitionedTopic();
+                    if (maxPartitions > 0 && numPartitions > maxPartitions) {
+                        throw new RestException(Status.NOT_ACCEPTABLE,
+                                "Number of partitions should be less than or equal to " + maxPartitions);
+                    }
+                    return checkTopicExistsAsync(topicName).thenAccept(exists -> {
+                        if (exists) {
+                            log.warn("[{}] Failed to create already existing topic {}", clientAppId(), topicName);
+                            throw new RestException(Status.CONFLICT, "This topic already exists");
                         }
-                        createLocalFuture.complete(null);
                     });
-        }).exceptionally(ex -> {
-            log.error("[{}] Failed to create partitioned topic {}", clientAppId(), topicName, ex);
-            resumeAsyncResponseExceptionally(asyncResponse, ex);
-            return null;
-        });
-
-        List<String> replicatedClusters = new ArrayList<>();
-        if (!createLocalTopicOnly && topicName.isGlobal() && isNamespaceReplicated(namespaceName)) {
-            getNamespaceReplicatedClusters(namespaceName)
-                    .stream().filter(cluster -> !cluster.equals(pulsar().getConfiguration().getClusterName()))
-                    .forEach(replicatedClusters::add);
-        }
-        createLocalFuture.whenComplete((ignored, ex) -> {
-            if (ex != null) {
-                log.error("[{}] Failed to create partitions for topic {}", clientAppId(), topicName, ex.getCause());
-                if (ex.getCause() instanceof RestException) {
-                    asyncResponse.resume(ex.getCause());
-                } else {
-                    resumeAsyncResponseExceptionally(asyncResponse, ex.getCause());
-                }
-                return;
-            }
-
-            if (!replicatedClusters.isEmpty()) {
-                replicatedClusters.forEach(cluster -> {
-                    pulsar().getPulsarResources().getClusterResources().getClusterAsync(cluster)
-                            .thenAccept(clusterDataOp -> {
-                                ((TopicsImpl) pulsar().getBrokerService()
-                                        .getClusterPulsarAdmin(cluster, clusterDataOp).topics())
-                                        .createPartitionedTopicAsync(
-                                                topicName.getPartitionedTopicName(), numPartitions, true, null);
-                            })
-                            .exceptionally(throwable -> {
-                                log.error("Failed to create partition topic in cluster {}.", cluster, throwable);
-                                return null;
-                            });
+                })
+                .thenCompose(__ -> provisionPartitionedTopicPath(numPartitions, createLocalTopicOnly, properties))
+                .thenCompose(__ -> tryCreatePartitionsAsync(numPartitions))
+                .thenAccept(__ -> {

Review Comment:
   @AnonHxy I have updated, PTAL.



-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] AnonHxy commented on a diff in pull request #18312: [improve][broker]optimize the logic of internalCreatePartitionedTopic

Posted by GitBox <gi...@apache.org>.
AnonHxy commented on code in PR #18312:
URL: https://github.com/apache/pulsar/pull/18312#discussion_r1012952519


##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/AdminResource.java:
##########
@@ -576,124 +576,80 @@ protected void internalCreatePartitionedTopic(AsyncResponse asyncResponse, int n
 
     protected void internalCreatePartitionedTopic(AsyncResponse asyncResponse, int numPartitions,
                                                   boolean createLocalTopicOnly, Map<String, String> properties) {
-        Integer maxTopicsPerNamespace = null;
-
-        try {
-            Policies policies = getNamespacePolicies(namespaceName);
-            maxTopicsPerNamespace = policies.max_topics_per_namespace;
-        } catch (RestException e) {
-            if (e.getResponse().getStatus() != Status.NOT_FOUND.getStatusCode()) {
-                log.error("[{}] Failed to create partitioned topic {}", clientAppId(), namespaceName, e);
-                resumeAsyncResponseExceptionally(asyncResponse, e);
-                return;
-            }
-        }
-
-        try {
-            if (maxTopicsPerNamespace == null) {
-                maxTopicsPerNamespace = pulsar().getConfig().getMaxTopicsPerNamespace();
-            }
-
-            // new create check
-            if (maxTopicsPerNamespace > 0 && !pulsar().getBrokerService().isSystemTopic(topicName)) {
-                List<String> partitionedTopics = getTopicPartitionList(TopicDomain.persistent);
-                // exclude created system topic
-                long topicsCount =
-                        partitionedTopics.stream().filter(t ->
-                                        !pulsar().getBrokerService().isSystemTopic(TopicName.get(t))).count();
-                if (topicsCount + numPartitions > maxTopicsPerNamespace) {
-                    log.error("[{}] Failed to create partitioned topic {}, "
-                            + "exceed maximum number of topics in namespace", clientAppId(), topicName);
-                    resumeAsyncResponseExceptionally(asyncResponse, new RestException(Status.PRECONDITION_FAILED,
-                            "Exceed maximum number of topics in namespace."));
-                    return;
-                }
-            }
-        } catch (Exception e) {
-            log.error("[{}] Failed to create partitioned topic {}", clientAppId(), namespaceName, e);
-            resumeAsyncResponseExceptionally(asyncResponse, e);
-            return;
-        }
-
-        final int maxPartitions = pulsar().getConfig().getMaxNumPartitionsPerPartitionedTopic();
-        try {
-            validateNamespaceOperation(topicName.getNamespaceObject(), NamespaceOperation.CREATE_TOPIC);
-        } catch (Exception e) {
-            log.error("[{}] Failed to create partitioned topic {}", clientAppId(), topicName, e);
-            resumeAsyncResponseExceptionally(asyncResponse, e);
-            return;
-        }
-        if (numPartitions <= 0) {
-            asyncResponse.resume(new RestException(Status.NOT_ACCEPTABLE,
-                    "Number of partitions should be more than 0"));
-            return;
-        }
-        if (maxPartitions > 0 && numPartitions > maxPartitions) {
-            asyncResponse.resume(new RestException(Status.NOT_ACCEPTABLE,
-                    "Number of partitions should be less than or equal to " + maxPartitions));
-            return;
-        }
+        validateNamespaceOperationAsync(topicName.getNamespaceObject(), NamespaceOperation.CREATE_TOPIC)
+                .thenCompose(__ -> getNamespacePoliciesAsync(namespaceName))
+                .handle((policies, ex) -> {
+                    if (ex != null
+                            && (!(ex.getCause() instanceof RestException)
+                            || ((RestException) ex.getCause()).getResponse().getStatus()
+                            != Status.NOT_FOUND.getStatusCode())) {
+                        throw new RestException(ex);
+                    }
 
-        CompletableFuture<Void> createLocalFuture = new CompletableFuture<>();
-        checkTopicExistsAsync(topicName).thenAccept(exists -> {
-            if (exists) {
-                log.warn("[{}] Failed to create already existing topic {}", clientAppId(), topicName);
-                asyncResponse.resume(new RestException(Status.CONFLICT, "This topic already exists"));
-                return;
-            }
+                    if (numPartitions <= 0) {
+                        throw new RestException(Status.NOT_ACCEPTABLE, "Number of partitions should be more than 0.");
+                    }
+                    int maxTopicsPerNamespace = policies != null && policies.max_topics_per_namespace != null
+                            ? policies.max_topics_per_namespace : pulsar().getConfig().getMaxTopicsPerNamespace();
+                    if (maxTopicsPerNamespace > 0 && !pulsar().getBrokerService().isSystemTopic(topicName)) {
+                        List<String> partitionedTopics = getTopicPartitionList(TopicDomain.persistent);
+                        // exclude created system topic
+                        long topicsCount = partitionedTopics.stream().filter(t ->
+                                !pulsar().getBrokerService().isSystemTopic(TopicName.get(t))).count();
+                        if (topicsCount + numPartitions > maxTopicsPerNamespace) {
+                            throw new RestException(Status.PRECONDITION_FAILED,
+                                    "Exceed maximum number of topics in namespace.");
+                        }
+                    }
 
-            provisionPartitionedTopicPath(numPartitions, createLocalTopicOnly, properties)
-                    .thenCompose(ignored -> tryCreatePartitionsAsync(numPartitions))
-                    .whenComplete((ignored, ex) -> {
-                        if (ex != null) {
-                            createLocalFuture.completeExceptionally(ex);
-                            return;
+                    int maxPartitions = pulsar().getConfig().getMaxNumPartitionsPerPartitionedTopic();
+                    if (maxPartitions > 0 && numPartitions > maxPartitions) {
+                        throw new RestException(Status.NOT_ACCEPTABLE,
+                                "Number of partitions should be less than or equal to " + maxPartitions);
+                    }
+                    return checkTopicExistsAsync(topicName).thenAccept(exists -> {
+                        if (exists) {
+                            log.warn("[{}] Failed to create already existing topic {}", clientAppId(), topicName);
+                            throw new RestException(Status.CONFLICT, "This topic already exists");
                         }
-                        createLocalFuture.complete(null);
                     });
-        }).exceptionally(ex -> {
-            log.error("[{}] Failed to create partitioned topic {}", clientAppId(), topicName, ex);
-            resumeAsyncResponseExceptionally(asyncResponse, ex);
-            return null;
-        });
-
-        List<String> replicatedClusters = new ArrayList<>();
-        if (!createLocalTopicOnly && topicName.isGlobal() && isNamespaceReplicated(namespaceName)) {
-            getNamespaceReplicatedClusters(namespaceName)
-                    .stream().filter(cluster -> !cluster.equals(pulsar().getConfiguration().getClusterName()))
-                    .forEach(replicatedClusters::add);
-        }
-        createLocalFuture.whenComplete((ignored, ex) -> {
-            if (ex != null) {
-                log.error("[{}] Failed to create partitions for topic {}", clientAppId(), topicName, ex.getCause());
-                if (ex.getCause() instanceof RestException) {
-                    asyncResponse.resume(ex.getCause());
-                } else {
-                    resumeAsyncResponseExceptionally(asyncResponse, ex.getCause());
-                }
-                return;
-            }
-
-            if (!replicatedClusters.isEmpty()) {
-                replicatedClusters.forEach(cluster -> {
-                    pulsar().getPulsarResources().getClusterResources().getClusterAsync(cluster)
-                            .thenAccept(clusterDataOp -> {
-                                ((TopicsImpl) pulsar().getBrokerService()
-                                        .getClusterPulsarAdmin(cluster, clusterDataOp).topics())
-                                        .createPartitionedTopicAsync(
-                                                topicName.getPartitionedTopicName(), numPartitions, true, null);
-                            })
-                            .exceptionally(throwable -> {
-                                log.error("Failed to create partition topic in cluster {}.", cluster, throwable);
-                                return null;
-                            });
+                })
+                .thenCompose(__ -> provisionPartitionedTopicPath(numPartitions, createLocalTopicOnly, properties))
+                .thenCompose(__ -> tryCreatePartitionsAsync(numPartitions))
+                .thenAccept(__ -> {
+                    List<String> replicatedClusters = new ArrayList<>();
+                    if (!createLocalTopicOnly && topicName.isGlobal() && isNamespaceReplicated(namespaceName)) {
+                        getNamespaceReplicatedClusters(namespaceName)
+                                .stream()
+                                .filter(cluster -> !cluster.equals(pulsar().getConfiguration().getClusterName()))
+                                .forEach(replicatedClusters::add);
+                    }
+                    replicatedClusters.forEach(cluster -> {
+                        pulsar().getPulsarResources().getClusterResources().getClusterAsync(cluster)
+                                .thenAccept(clusterDataOp ->
+                                        ((TopicsImpl) pulsar().getBrokerService()
+                                                .getClusterPulsarAdmin(cluster, clusterDataOp).topics())
+                                                .createPartitionedTopicAsync(
+                                                        topicName.getPartitionedTopicName(), numPartitions,
+                                                        true, null))
+                                        .exceptionally(ex -> {
+                                            log.error("Failed to create partition topic in cluster {}.", cluster, ex);
+                                            return null;
+                                        });
+                    });
+                    log.info("[{}] Successfully created partitions for topic {} in cluster {}",
+                            clientAppId(), topicName, pulsar().getConfiguration().getClusterName());
+                    asyncResponse.resume(Response.noContent().build());
+                })
+                .exceptionally(ex -> {
+                    log.error("[{}] Failed to create partitions for topic {}", clientAppId(), topicName, ex);
+                    if (ex instanceof RestException) {
+                        asyncResponse.resume(ex);
+                    } else {

Review Comment:
   There is no need for line646 to line 648 I think, because `resumeAsyncResponseExceptionally` has covered this



-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] Pomelongan commented on a diff in pull request #18312: [improve][admin] Optimize the logic of internalCreatePartitionedTopic

Posted by GitBox <gi...@apache.org>.
Pomelongan commented on code in PR #18312:
URL: https://github.com/apache/pulsar/pull/18312#discussion_r1013697024


##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/AdminResource.java:
##########
@@ -576,124 +576,80 @@ protected void internalCreatePartitionedTopic(AsyncResponse asyncResponse, int n
 
     protected void internalCreatePartitionedTopic(AsyncResponse asyncResponse, int numPartitions,
                                                   boolean createLocalTopicOnly, Map<String, String> properties) {
-        Integer maxTopicsPerNamespace = null;
-
-        try {
-            Policies policies = getNamespacePolicies(namespaceName);
-            maxTopicsPerNamespace = policies.max_topics_per_namespace;
-        } catch (RestException e) {
-            if (e.getResponse().getStatus() != Status.NOT_FOUND.getStatusCode()) {
-                log.error("[{}] Failed to create partitioned topic {}", clientAppId(), namespaceName, e);
-                resumeAsyncResponseExceptionally(asyncResponse, e);
-                return;
-            }
-        }
-
-        try {
-            if (maxTopicsPerNamespace == null) {
-                maxTopicsPerNamespace = pulsar().getConfig().getMaxTopicsPerNamespace();
-            }
-
-            // new create check
-            if (maxTopicsPerNamespace > 0 && !pulsar().getBrokerService().isSystemTopic(topicName)) {
-                List<String> partitionedTopics = getTopicPartitionList(TopicDomain.persistent);
-                // exclude created system topic
-                long topicsCount =
-                        partitionedTopics.stream().filter(t ->
-                                        !pulsar().getBrokerService().isSystemTopic(TopicName.get(t))).count();
-                if (topicsCount + numPartitions > maxTopicsPerNamespace) {
-                    log.error("[{}] Failed to create partitioned topic {}, "
-                            + "exceed maximum number of topics in namespace", clientAppId(), topicName);
-                    resumeAsyncResponseExceptionally(asyncResponse, new RestException(Status.PRECONDITION_FAILED,
-                            "Exceed maximum number of topics in namespace."));
-                    return;
-                }
-            }
-        } catch (Exception e) {
-            log.error("[{}] Failed to create partitioned topic {}", clientAppId(), namespaceName, e);
-            resumeAsyncResponseExceptionally(asyncResponse, e);
-            return;
-        }
-
-        final int maxPartitions = pulsar().getConfig().getMaxNumPartitionsPerPartitionedTopic();
-        try {
-            validateNamespaceOperation(topicName.getNamespaceObject(), NamespaceOperation.CREATE_TOPIC);
-        } catch (Exception e) {
-            log.error("[{}] Failed to create partitioned topic {}", clientAppId(), topicName, e);
-            resumeAsyncResponseExceptionally(asyncResponse, e);
-            return;
-        }
-        if (numPartitions <= 0) {
-            asyncResponse.resume(new RestException(Status.NOT_ACCEPTABLE,
-                    "Number of partitions should be more than 0"));
-            return;
-        }
-        if (maxPartitions > 0 && numPartitions > maxPartitions) {
-            asyncResponse.resume(new RestException(Status.NOT_ACCEPTABLE,
-                    "Number of partitions should be less than or equal to " + maxPartitions));
-            return;
-        }
+        validateNamespaceOperationAsync(topicName.getNamespaceObject(), NamespaceOperation.CREATE_TOPIC)
+                .thenCompose(__ -> getNamespacePoliciesAsync(namespaceName))
+                .handle((policies, ex) -> {
+                    if (ex != null
+                            && (!(ex.getCause() instanceof RestException)
+                            || ((RestException) ex.getCause()).getResponse().getStatus()
+                            != Status.NOT_FOUND.getStatusCode())) {
+                        throw new RestException(ex);
+                    }
 
-        CompletableFuture<Void> createLocalFuture = new CompletableFuture<>();
-        checkTopicExistsAsync(topicName).thenAccept(exists -> {
-            if (exists) {
-                log.warn("[{}] Failed to create already existing topic {}", clientAppId(), topicName);
-                asyncResponse.resume(new RestException(Status.CONFLICT, "This topic already exists"));
-                return;
-            }
+                    if (numPartitions <= 0) {

Review Comment:
   Good idea~ 



-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org