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


##########
pulsar-common/src/main/java/org/apache/pulsar/common/semaphore/AsyncSemaphoreImpl.java:
##########
@@ -0,0 +1,286 @@
+/*
+ * 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.util.concurrent.DefaultThreadFactory;
+import java.util.Queue;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicLongFieldUpdater;
+import java.util.function.BooleanSupplier;
+import java.util.function.LongConsumer;
+import org.apache.pulsar.common.util.Runnables;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Implementation of AsyncSemaphore with timeout and queue size limits.
+ */
+public class AsyncSemaphoreImpl implements AsyncSemaphore, AutoCloseable {
+    private static final Logger log = 
LoggerFactory.getLogger(AsyncSemaphoreImpl.class);
+
+    private final AtomicLong availablePermits;
+    private final Queue<PendingRequest> queue;
+    private final long maxPermits;
+    private final long timeoutMillis;
+    private final ScheduledExecutorService executor;
+    private final boolean shutdownExecutor;
+    private final LongConsumer queueLatencyRecorder;
+    private final AtomicBoolean closed = new AtomicBoolean(false);
+    private final Runnable processQueueRunnable = 
Runnables.catchingAndLoggingThrowables(this::internalProcessQueue);
+
+    public AsyncSemaphoreImpl(long maxPermits, int maxQueueSize, long 
timeoutMillis) {
+        this(maxPermits, maxQueueSize, timeoutMillis, createExecutor(), true, 
null);
+    }
+
+    public AsyncSemaphoreImpl(long maxPermits, int maxQueueSize, long 
timeoutMillis,
+                              ScheduledExecutorService executor, LongConsumer 
queueLatencyRecorder) {
+        this(maxPermits, maxQueueSize, timeoutMillis, executor, false, 
queueLatencyRecorder);
+    }
+
+    AsyncSemaphoreImpl(long maxPermits, int maxQueueSize, long timeoutMillis, 
ScheduledExecutorService executor,
+                       boolean shutdownExecutor, LongConsumer 
queueLatencyRecorder) {
+        this.availablePermits = new AtomicLong(maxPermits);
+        this.maxPermits = maxPermits;
+        this.queue = new ArrayBlockingQueue<>(maxQueueSize);
+        this.timeoutMillis = timeoutMillis;
+        this.executor = executor;
+        this.shutdownExecutor = shutdownExecutor;
+        this.queueLatencyRecorder = queueLatencyRecorder;
+    }
+
+    private static ScheduledExecutorService createExecutor() {
+        return Executors.newSingleThreadScheduledExecutor(
+                new DefaultThreadFactory("async-semaphore-executor"));
+    }
+
+    @Override
+    public CompletableFuture<AsyncSemaphorePermit> acquire(long permits, 
BooleanSupplier isCancelled) {
+        return internalAcquire(permits, permits, isCancelled);
+    }
+
+    private CompletableFuture<AsyncSemaphorePermit> internalAcquire(long 
permits, long acquirePermits,
+                                                                    
BooleanSupplier isCancelled) {
+        if (permits < 0) {
+            throw new IllegalArgumentException("Invalid permits value: " + 
permits);
+        }
+
+        CompletableFuture<AsyncSemaphorePermit> future = new 
CompletableFuture<>();
+
+        if (closed.get()) {
+            future.completeExceptionally(new 
PermitAcquireAlreadyClosedException("Semaphore is closed"));
+            return future;
+        }
+
+        PendingRequest request = new PendingRequest(permits, acquirePermits, 
future, isCancelled);
+        if (!queue.offer(request)) {
+            future.completeExceptionally(new PermitAcquireQueueFullException(
+                    "Semaphore queue is full"));
+            return future;
+        }
+        // Schedule timeout
+        ScheduledFuture<?> timeoutTask = executor.schedule(() -> {
+            if (!request.future.isDone() && queue.remove(request)) {
+                // timeout is recorded with Long.MAX_VALUE as the age
+                recordQueueLatency(Long.MAX_VALUE);
+                // also record the time in the queue
+                recordQueueLatency(request.getAgeNanos());
+                future.completeExceptionally(new PermitAcquireTimeoutException(
+                        "Permit acquisition timed out"));
+                // the next request might have smaller permits and that might 
be processed
+                processQueue();
+            }
+        }, timeoutMillis, TimeUnit.MILLISECONDS);
+        request.setTimeoutTask(timeoutTask);
+
+        processQueue();
+        return future;
+    }
+
+    private void recordQueueLatency(long ageNanos) {
+        if (queueLatencyRecorder != null) {
+            queueLatencyRecorder.accept(ageNanos);
+        }
+    }
+
+    @Override
+    public CompletableFuture<AsyncSemaphorePermit> update(AsyncSemaphorePermit 
permit, long newPermits,
+                                                          BooleanSupplier 
isCancelled) {
+        if (newPermits < 0) {
+            throw new IllegalArgumentException("Invalid permits value: " + 
newPermits);
+        }
+        long oldPermits = permit.getPermits();
+        long additionalPermits = newPermits - oldPermits;
+        // mark the old permits as released without adding the permits to 
availablePermits
+        castToImplementation(permit).releasePermits();
+        if (additionalPermits > 0) {
+            return internalAcquire(newPermits, additionalPermits, isCancelled);
+        } else {
+            // new permits are less than the old ones, so we return the 
difference
+            availablePermits.addAndGet(-additionalPermits);
+            processQueue();
+            // return the new permits immediately
+            return CompletableFuture.completedFuture(new 
SemaphorePermit(newPermits));
+        }
+    }
+
+    @Override
+    public void release(AsyncSemaphorePermit permit) {
+        
availablePermits.addAndGet(castToImplementation(permit).releasePermits());
+        processQueue();
+    }
+
+    @Override
+    public long getAvailablePermits() {
+        return availablePermits.get();
+    }
+
+    @Override
+    public long getAcquiredPermits() {
+        return maxPermits - availablePermits.get();
+    }
+
+    @Override
+    public int getQueueSize() {
+        return queue.size();
+    }
+
+    private SemaphorePermit castToImplementation(AsyncSemaphorePermit permit) {
+        if (permit instanceof SemaphorePermit semaphorePermit) {
+            return semaphorePermit;
+        } else {
+            throw new IllegalArgumentException("Invalid permit type");
+        }
+    }
+
+    private void processQueue() {
+        if (closed.get()) {
+            return;
+        }
+        executor.execute(processQueueRunnable);
+    }
+
+    private void internalProcessQueue() {

Review Comment:
   Oh! I understand. This does indeed need to be recorded.



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