Copilot commented on code in PR #24833:
URL: https://github.com/apache/pulsar/pull/24833#discussion_r2421601390


##########
pulsar-broker-common/src/main/java/org/apache/pulsar/broker/topiclistlimit/TopicListMemoryLimiter.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.topiclistlimit;
+
+import io.opentelemetry.api.metrics.DoubleGauge;
+import io.opentelemetry.api.metrics.DoubleHistogram;
+import io.opentelemetry.api.metrics.LongCounter;
+import io.opentelemetry.api.metrics.LongGauge;
+import io.opentelemetry.api.metrics.Meter;
+import io.opentelemetry.api.metrics.ObservableDoubleGauge;
+import io.opentelemetry.api.metrics.ObservableLongUpDownCounter;
+import io.prometheus.client.Collector;
+import io.prometheus.client.CollectorRegistry;
+import io.prometheus.client.Counter;
+import io.prometheus.client.Gauge;
+import io.prometheus.client.Summary;
+import java.util.concurrent.TimeUnit;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.pulsar.common.semaphore.AsyncDualMemoryLimiterImpl;
+import org.apache.pulsar.common.semaphore.AsyncSemaphore;
+
+/**
+ * Topic list memory limiter that exposes both Prometheus metrics and 
OpenTelemetry metrics.
+ */
+@Slf4j
+public class TopicListMemoryLimiter extends AsyncDualMemoryLimiterImpl {
+    private final CollectorRegistry collectorRegistry;
+    private final Gauge heapMemoryUsedBytes;
+    private final Gauge heapMemoryLimitBytes;
+    private final Gauge directMemoryUsedBytes;
+    private final Gauge directMemoryLimitBytes;
+    private final Gauge heapQueueSize;
+    private final Gauge heapQueueMaxSize;
+    private final Gauge directQueueSize;
+    private final Gauge directQueueMaxSize;
+    private final Summary heapWaitTimeMs;
+    private final Summary directWaitTimeMs;
+    private final Counter heapTimeoutTotal;
+    private final Counter directTimeoutTotal;
+    private final ObservableDoubleGauge otelHeapMemoryUsedGauge;
+    private final DoubleGauge otelHeapMemoryLimitGauge;
+    private final ObservableDoubleGauge otelDirectMemoryUsedGauge;
+    private final DoubleGauge otelDirectMemoryLimitGauge;
+    private final ObservableLongUpDownCounter otelHeapQueueSize;
+    private final ObservableLongUpDownCounter otelDirectQueueSize;
+    private final DoubleHistogram otelHeapWaitTime;
+    private final DoubleHistogram otelDirectWaitTime;
+    private final LongCounter otelHeapTimeoutTotal;
+    private final LongCounter otelDirectTimeoutTotal;
+
+    public TopicListMemoryLimiter(CollectorRegistry collectorRegistry, String 
prometheusPrefix,
+                                  Meter openTelemetryMeter,
+                                  long maxHeapMemory, int maxHeapQueueSize,
+                                  long heapTimeoutMillis, long 
maxDirectMemory, int maxDirectQueueSize,
+                                  long directTimeoutMillis) {
+        super(maxHeapMemory, maxHeapQueueSize, heapTimeoutMillis, 
maxDirectMemory, maxDirectQueueSize,
+                directTimeoutMillis);
+        this.collectorRegistry = collectorRegistry;
+
+        AsyncSemaphore heapMemoryLimiter = getLimiter(LimitType.HEAP_MEMORY);
+        AsyncSemaphore directMemoryLimiter = 
getLimiter(LimitType.DIRECT_MEMORY);
+
+        this.heapMemoryUsedBytes = register(Gauge.build(prometheusPrefix + 
"topic_list_heap_memory_used_bytes",
+                        "Current heap memory used by topic listings")
+                .create()
+                .setChild(new Gauge.Child() {
+                    @Override
+                    public double get() {
+                        return heapMemoryLimiter.getAcquiredPermits();
+                    }
+                }));
+        this.otelHeapMemoryUsedGauge = 
openTelemetryMeter.gaugeBuilder("topic.list.heap.memory.used")
+                .setUnit("By")
+                .setDescription("Current heap memory used by topic listings")
+                .buildWithCallback(observableDoubleMeasurement -> {
+                    
observableDoubleMeasurement.record(heapMemoryLimiter.getAcquiredPermits());
+                });
+
+        this.heapMemoryLimitBytes = register(Gauge.build(prometheusPrefix + 
"topic_list_heap_memory_limit_bytes",
+                        "Configured heap memory limit")
+                .create());
+        this.heapMemoryLimitBytes.set(maxHeapMemory);
+        this.otelHeapMemoryLimitGauge = 
openTelemetryMeter.gaugeBuilder("topic.list.heap.memory.limit")
+                .setUnit("By")
+                .setDescription("Configured heap memory limit")
+                .build();
+        this.otelHeapMemoryLimitGauge.set(maxHeapMemory);
+
+        this.directMemoryUsedBytes = register(Gauge.build(prometheusPrefix + 
"topic_list_direct_memory_used_bytes",
+                        "Current direct memory used by topic listings")
+                .create()
+                .setChild(new Gauge.Child() {
+                    @Override
+                    public double get() {
+                        return directMemoryLimiter.getAcquiredPermits();
+                    }
+                }));
+        this.otelDirectMemoryUsedGauge = 
openTelemetryMeter.gaugeBuilder("topic.list.direct.memory.used")
+                .setUnit("By")
+                .setDescription("Current direct memory used by topic listings")
+                .buildWithCallback(observableDoubleMeasurement -> {
+                    
observableDoubleMeasurement.record(directMemoryLimiter.getAcquiredPermits());
+                });
+
+        this.directMemoryLimitBytes = register(Gauge.build(prometheusPrefix + 
"topic_list_direct_memory_limit_bytes",
+                        "Configured direct memory limit")
+                .create());
+        this.directMemoryLimitBytes.set(maxDirectMemory);
+        this.otelDirectMemoryLimitGauge = 
openTelemetryMeter.gaugeBuilder("topic.list.direct.memory.limit")
+                .setUnit("By")
+                .setDescription("Configured direct memory limit")
+                .build();
+        this.otelDirectMemoryLimitGauge.set(maxHeapMemory);

Review Comment:
   The direct memory limit gauge is being set with the heap memory value 
instead of the direct memory value. This should be `maxDirectMemory`.
   ```suggestion
           this.otelDirectMemoryLimitGauge.set(maxDirectMemory);
   ```



##########
pulsar-common/src/test/java/org/apache/pulsar/common/semaphore/AsyncDualMemoryLimiterImplTest.java:
##########
@@ -0,0 +1,722 @@
+

Review Comment:
   The file starts with an empty line before the license header. Remove the 
empty line to maintain consistency with the project's file format.
   ```suggestion
   
   ```



##########
pulsar-common/src/test/java/org/apache/pulsar/common/semaphore/AsyncDualMemoryLimiterUtilTest.java:
##########
@@ -0,0 +1,497 @@
+

Review Comment:
   The file starts with an empty line before the license header. Remove the 
empty line to maintain consistency with the project's file format.
   ```suggestion
   
   ```



##########
pulsar-common/src/main/java/org/apache/pulsar/common/semaphore/AsyncDualMemoryLimiterUtil.java:
##########
@@ -0,0 +1,111 @@
+/*
+ * 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.common.semaphore;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelHandlerContext;
+import java.util.concurrent.CompletableFuture;
+import java.util.function.BooleanSupplier;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import lombok.experimental.UtilityClass;
+import org.apache.commons.lang3.tuple.Pair;
+import org.apache.pulsar.common.api.proto.BaseCommand;
+import org.apache.pulsar.common.protocol.Commands;
+import 
org.apache.pulsar.common.semaphore.AsyncDualMemoryLimiter.AsyncDualMemoryLimiterPermit;
+
+@UtilityClass
+public class AsyncDualMemoryLimiterUtil {
+
+    public static <T> CompletableFuture<T> withPermitsFuture(
+            CompletableFuture<AsyncDualMemoryLimiterPermit>
+                    permitsFuture,
+            Function<AsyncDualMemoryLimiterPermit,
+                    CompletableFuture<T>> function,
+            Function<Throwable, CompletableFuture<T>>
+                    permitAcquireErrorHandler,
+            Consumer<AsyncDualMemoryLimiterPermit> releaser) {
+        return permitsFuture
+                // combine the permits and error into a single pair so that it 
can be used in thenCompose
+                .handle((permits, permitAcquireError) ->
+                        Pair.of(permits, permitAcquireError))
+                .thenCompose(permitsAndError -> {
+                    if (permitsAndError.getRight() != null) {
+                        // permits weren't acquired
+                        return 
permitAcquireErrorHandler.apply(permitsAndError.getRight());
+                    } else {
+                        // permits were acquired
+                        AsyncDualMemoryLimiterPermit permits = 
permitsAndError.getLeft();
+                        try {
+                            return function.apply(permits)
+                                    .whenComplete((__, ___) ->
+                                            // release the permits
+                                            releaser.accept(permits));
+                        } catch (Throwable t) {
+                            // release the permits if an exception occurs 
before the function returns
+                            releaser.accept(permits);
+                            throw t;
+                        }
+                    }
+                });
+    }
+
+    /**
+     * Acquire permits and write the command as the response to the channel.
+     * Releases the permits after the response has been written to the socket 
or the write fails.
+     *
+     * @param ctx               the channel handler context.
+     * @param dualMemoryLimiter the memory limiter to acquire permits from.
+     * @param command           the command to write to the channel.
+     * @return a future that completes when the command has been written to 
the channel's outbound buffer.
+     */
+    public static CompletableFuture<Void> 
acquireDirectMemoryPermitsAndWriteAndFlush(ChannelHandlerContext ctx,
+                                                                               
      AsyncDualMemoryLimiter
+                                                                               
              dualMemoryLimiter,
+                                                                               
      BooleanSupplier isCancelled,
+                                                                               
      BaseCommand command,
+                                                                               
      Consumer<Throwable>
+                                                                               
              permitAcquireErrorHandler
+                                                                               
      ) {
+        // Calculate serialized size before acquiring permits
+        int serializedSize = command.getSerializedSize();
+        // Acquire permits
+        return dualMemoryLimiter.acquire(serializedSize, 
AsyncDualMemoryLimiter.LimitType.DIRECT_MEMORY, isCancelled)
+                .whenComplete((permits, t) -> {
+                    if (t != null) {
+                        permitAcquireErrorHandler.accept(t);
+                        return;
+                    }
+                    try {
+                        // Serialize the response
+                        ByteBuf outBuf = 
Commands.serializeWithPrecalculatedSerializedSize(command, serializedSize);
+                        // Write the response
+                        ctx.writeAndFlush(outBuf).addListener(future -> {
+                            // Release permits after the response has been 
written to the socket
+                            dualMemoryLimiter.release(permits);
+                        });
+                    } catch (Exception e) {
+                        // Return permits if an exception occurs before 
writeAndFlush is called successfully
+                        dualMemoryLimiter.release(permits);
+                        throw e;
+                    }
+                }).thenAccept(__ -> {

Review Comment:
   The empty lambda body `thenAccept(__ -> {})` is unnecessary. Consider 
returning the CompletableFuture directly or using a more meaningful operation.
   ```suggestion
   
   ```



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