gnodet-bot commented on code in PR #31289:
URL: https://github.com/apache/camel/pull/31289#discussion_r4773121228


##########
components/camel-ai/camel-ai-guardrail/src/main/java/org/apache/camel/component/ai/guardrail/AiGuardrailConsumer.java:
##########
@@ -0,0 +1,308 @@
+/*
+ * 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.camel.component.ai.guardrail;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Processor;
+import org.apache.camel.ShutdownRunningTask;
+import org.apache.camel.StartupListener;
+import org.apache.camel.spi.ShutdownAware;
+import org.apache.camel.spi.ThreadPoolProfile;
+import org.apache.camel.support.DefaultConsumer;
+import org.apache.camel.util.concurrent.ThreadPoolRejectedPolicy;
+
+/**
+ * Registers the guardrail route in the {@link AiGuardrailRegistry} under its 
tags, and owns the bounded pool the route
+ * calls run on.
+ * <p>
+ * The route is registered from its creation until its shutdown: while it is 
not started (also
+ * {@code autoStartup=false}), stopped or suspended, a call to its tags is 
fatal instead of silently skipping it. Only a
+ * shutdown (the route is removed, or the context stops) deregisters it.
+ * <p>
+ * The bounds are enforced by semaphores, not by the pool, which is unbounded: 
with virtual threads
+ * ({@code camel.threads.virtual.enabled}) a bounded Camel pool is one thread 
per task that blocks a caller beyond its
+ * bound, outside of the timeout of the call. A call holds its slot until the 
route really ends, also after its caller
+ * gave up, and a queued call until the pool drops it from its queue, so the 
queue never grows beyond the bound.
+ * <p>
+ * A graceful shutdown defers the stop of the consumer, so the calls already 
admitted finish within the shutdown
+ * timeout. A new call during a route stop is fatal; during a context stop it 
is admitted, as it can come from an
+ * exchange still in flight. A stop that times out and is aborted leaves the 
route running, and the route accepts calls
+ * again.
+ *
+ * @since 4.25
+ */
+public class AiGuardrailConsumer extends DefaultConsumer implements 
ShutdownAware, StartupListener {
+
+    private volatile Pool pool;
+    private volatile boolean shuttingDown;
+    private AiGuardrailSpec spec;
+    private final List<String> registeredTags = new ArrayList<>();
+
+    public AiGuardrailConsumer(AiGuardrailEndpoint endpoint, Processor 
processor) {
+        super(endpoint, processor);
+    }
+
+    @Override
+    public AiGuardrailEndpoint getEndpoint() {
+        return (AiGuardrailEndpoint) super.getEndpoint();
+    }
+
+    Pool getPool() {
+        return pool;
+    }
+
+    /**
+     * Whether a graceful stop of the route has begun: new calls are fatal, 
the admitted ones finish.
+     */
+    boolean isShuttingDown() {
+        return shuttingDown;
+    }
+
+    @Override
+    public boolean deferShutdown(ShutdownRunningTask shutdownRunningTask) {
+        // keep the pool running while the shutdown waits for the admitted 
calls. A route stop refuses new calls, a
+        // context stop admits them: they can come from exchanges still in 
flight, which the context waits for too
+        shuttingDown = !getEndpoint().getCamelContext().isStopping();
+        return true;
+    }
+
+    @Override
+    public int getPendingExchangesSize() {
+        // the admitted calls, running or queued: a queued call is not in the 
inflight repository yet
+        Pool p = pool;
+        return p != null ? p.capacity() - p.slots().availablePermits() : 0;
+    }
+
+    @Override
+    public void prepareShutdown(boolean suspendOnly, boolean forced) {
+        // noop
+    }
+
+    /**
+     * Registers the route under its tags once the route sets its id, right 
after it creates the consumer. This also
+     * registers a route with {@code autoStartup=false}, whose consumer is not 
initialized before its start: until it
+     * starts, its tags are fatal. The route id tells a restarted route (a new 
consumer) from a duplicate name.
+     */
+    @Override
+    public void setRouteId(String routeId) {
+        super.setRouteId(routeId);
+        if (spec == null && routeId != null) {
+            register();
+        }
+    }
+
+    private void register() {
+        AiGuardrailEndpoint endpoint = getEndpoint();
+        String name = endpoint.getName();
+        List<String> tags = endpoint.parseTags();
+        if (endpoint.getType() == null) {
+            throw new IllegalArgumentException("Guardrail '" + name + "' needs 
type=input or type=output");
+        }
+        if (tags.isEmpty()) {
+            throw new IllegalArgumentException("Guardrail '" + name + "' needs 
at least one tag");
+        }
+        int concurrency = endpoint.getConcurrency();
+        int queueCapacity = endpoint.getQueueCapacity();
+        if (endpoint.getTimeout() <= 0 || concurrency < 1 || queueCapacity < 
1) {
+            throw new IllegalArgumentException(
+                    "Guardrail '" + name + "': timeout, concurrency and 
queueCapacity must be positive");
+        }
+        if ((long) concurrency + queueCapacity > Integer.MAX_VALUE) {
+            throw new IllegalArgumentException(
+                    "Guardrail '" + name + "': concurrency + queueCapacity 
must not exceed " + Integer.MAX_VALUE);
+        }
+        spec = new AiGuardrailSpec(name, endpoint.getType(), 
endpoint.getOrder(), tags, this);
+        AiGuardrailRegistry registry = 
AiGuardrailRegistry.getOrCreate(endpoint.getCamelContext());
+        try {
+            for (String tag : tags) {
+                registry.put(tag, spec);
+                registeredTags.add(tag);
+            }
+        } catch (RuntimeException e) {
+            deregister();
+            throw e;
+        }
+    }
+
+    /**
+     * Called each time the route starts this consumer on a started context, 
also when a stop that timed out was
+     * aborted: the route starts the consumer again, which is still started, 
so {@link #doStart()} is not called. It
+     * fires for every later route start (the consumer stays a listener of the 
context), never during a graceful stop:
+     * stopping and starting a route share the lock of the context.
+     */
+    @Override
+    public void onCamelContextStarted(CamelContext context, boolean 
alreadyStarted) {
+        shuttingDown = false;
+    }
+
+    @Override
+    protected void doStart() throws Exception {
+        super.doStart();
+        // on a context start, onCamelContextStarted is called only once all 
routes started
+        shuttingDown = false;
+        AiGuardrailEndpoint endpoint = getEndpoint();
+        String name = endpoint.getName();
+        int concurrency = endpoint.getConcurrency();
+        ThreadPoolProfile profile = new ThreadPoolProfile(name);
+        profile.setPoolSize(concurrency);
+        profile.setMaxPoolSize(concurrency);
+        // the semaphores bound the calls: the pool is unbounded (with virtual 
threads a bound it never reaches), so it
+        // never makes an admitted call wait or rejects it
+        profile.setMaxQueueSize(Integer.MAX_VALUE);
+        // never caller-runs: a call to a stopped pool is rejected, not run on 
the caller's thread
+        profile.setRejectedPolicy(ThreadPoolRejectedPolicy.Abort);
+        pool = new Pool(
+                endpoint.getCamelContext().getExecutorServiceManager()
+                        .newThreadPool(this, "AiGuardrail[" + name + "]", 
profile),
+                concurrency + endpoint.getQueueCapacity(), new 
Semaphore(concurrency + endpoint.getQueueCapacity()),
+                new Semaphore(concurrency));
+    }
+
+    @Override
+    protected void doStop() throws Exception {
+        // after a graceful shutdown the admitted calls are done: shutdownNow 
only cuts calls on a forced stop or timeout
+        // a stopped route stays registered: calls to its tags are fatal until 
it starts again or is removed
+        shutdownPool();
+        super.doStop();
+    }
+
+    @Override
+    protected void doShutdown() throws Exception {
+        deregister();
+        shutdownPool();
+        super.doShutdown();
+    }
+
+    private void deregister() {
+        AiGuardrailRegistry registry = 
AiGuardrailRegistry.getOrCreate(getEndpoint().getCamelContext());
+        for (String tag : registeredTags) {
+            registry.remove(tag, spec);
+        }
+        registeredTags.clear();
+        spec = null;
+    }
+
+    private void shutdownPool() {
+        Pool p = pool;
+        pool = null;
+        if (p != null) {
+            // interrupts the running calls, and with virtual threads the 
calls waiting for their turn
+            List<Runnable> queued = 
getEndpoint().getCamelContext().getExecutorServiceManager().shutdownNow(p.executor());
+            if (queued != null) {
+                // complete the queued calls, so their callers fail closed now 
instead of after the timeout
+                for (Runnable task : queued) {
+                    if (task instanceof Future<?> future) {
+                        future.cancel(false);
+                    }
+                }
+            }
+        }
+    }
+
+    /**
+     * The pool of the route and its bounds. slots: admission, held by a call 
from its submission until the route ends,
+     * also after its caller gave up, or until the pool drops it from its 
queue when it was cancelled before it ran.
+     * running: held while the route runs; with platform threads the pool size 
already bounds it, with virtual threads a
+     * call waits for it on its own thread, which is the queue.
+     */
+    record Pool(ExecutorService executor, int capacity, Semaphore slots, 
Semaphore running) {
+
+        boolean isShutdown() {
+            return executor.isShutdown();
+        }
+
+        /**
+         * Submits the task, rejected at once when no slot is free. A call 
that does not reach the route by the deadline
+         * ({@link System#nanoTime()}) fails with a {@link TimeoutException}.
+         */
+        <T> Future<T> submit(Callable<T> task, long deadline) {
+            if (!slots.tryAcquire()) {
+                throw new RejectedExecutionException("no free slot");
+            }
+            // set when the call ran: it released its slot before its caller 
sees the result
+            AtomicBoolean ran = new AtomicBoolean();
+            FutureTask<T> future = new FutureTask<>(() -> {
+                ran.set(true);
+                try {
+                    return runInTurn(task, deadline);
+                } finally {
+                    slots.release();
+                }
+            }) {
+                @Override
+                public void run() {
+                    // a call cancelled while queued does not run: its slot is 
released when the pool takes it from its
+                    // queue, so the queue never grows beyond the bound while 
the routes hold all threads
+                    try {
+                        super.run();
+                    } finally {
+                        if (!ran.get()) {
+                            slots.release();
+                        }
+                    }
+                }
+            };
+            try {
+                executor.execute(future);
+            } catch (Throwable e) {

Review Comment:
   💡 `catch (Throwable e)` is intentional here — catching `Error` (e.g. 
`OutOfMemoryError`) ensures the slot is always released even on JVM-level 
failures before `run()` starts. Worth a brief comment to prevent a future 
"broad catch" refactor from silently introducing a slot leak:
   
   ```suggestion
               } catch (Throwable e) { // includes Error — slot must be 
released even on OOM
   ```



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