lhotari commented on code in PR #17254:
URL: https://github.com/apache/pulsar/pull/17254#discussion_r954460316


##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/namespace/NamespaceService.java:
##########
@@ -644,6 +646,25 @@ private CompletableFuture<Optional<CandidateBrokerResult>> 
getCandidateBrokerRes
 
     }
 
+    private CompletableFuture<Optional<LeaderBroker>> 
getOrWaitForLeader(AtomicInteger retries) {
+        return pulsar.getLeaderElectionService().readCurrentLeader()
+                .handle((leaderBroker, t) -> {
+                    CompletableFuture<Optional<LeaderBroker>> retval;
+                    if ((t != null || !leaderBroker.isPresent()) && 
retries.getAndIncrement() < 3) {
+                        // retry after a delay of 5 seconds
+                        retval =
+                                CompletableFuture.supplyAsync(() -> null,
+                                                
CompletableFuture.delayedExecutor(5, SECONDS))
+                                        .thenCompose(__ -> 
getOrWaitForLeader(retries));
+                    } else {
+                        retval = CompletableFuture.completedFuture(
+                                leaderBroker != null ? leaderBroker : 
Optional.empty());
+                    }
+                    return retval;
+                })
+                .thenCompose(Function.identity());

Review Comment:
   when using `.handle` that returns a CompletableFuture, it's necessary to 
"flatten" it with `.thenCompose(Function.identity())`. 
   This is a known gap in CompletableFuture API that there is no 
`handleCompose` method directly. (an [stackoverflow answer explaining 
details](https://stackoverflow.com/a/60602429), contains links to other 
answers) . Java 12+ contains `.exceptionallyCompose`, but no `.handleCompose` 
which is unfortunate.



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