allthingssecurity commented on code in PR #27341:
URL: https://github.com/apache/camel/pull/27341#discussion_r4181333354


##########
core/camel-core-processor/src/main/java/org/apache/camel/processor/TotalRequestsThrottler.java:
##########
@@ -247,8 +262,50 @@ public ThrottlePermit take() throws InterruptedException {
             return delayQueue.take();
         }
 
+        /**
+         * Removes this state if all its permits are returned (no exchange 
took a permit it has not returned yet). Only
+         * this state is removed, and not a state that has already replaced it.
+         */
         public void clean() {
-            states.remove(key);
+            states.computeIfPresent(key, (k, s) -> s == this && 
markRemovedIfUnused() ? null : s);
+        }
+
+        private boolean markRemovedIfUnused() {
+            removedLock.lock();
+            try {
+                if (delayQueue.size() >= throttleRate) {
+                    removed = true;
+                }
+                return removed;
+            } finally {
+                removedLock.unlock();
+            }
+        }
+
+        /**
+         * Whether this state was removed by {@link #clean()} after the 
exchange looked it up, in which case a permit
+         * taken from it does not count, and must be taken from the state that 
replaced it instead.
+         */
+        private boolean isRemoved() {

Review Comment:
   Not measured before; I did now. Reasoning first: `removedLock` belongs to 
one `ThrottlingState` (one correlation key),
   and an exchange holds it only to read one boolean. The only other user is 
the clean, which runs at most once per 10
   periods and holds it for a `size()` check. So it is uncontended apart from 
the exchanges on the same key, which already
   go through more serializing points on every permit: the state's `lock` in 
`calculateAndSetMaxRequestsPerPeriod`, the
   `DelayQueue`'s internal lock on `poll()` and again on the `put()` that 
returns the permit, and the scheduler queue when
   the clean task is rescheduled.
   
   Quick measurement (scratch test, not committed): N threads calling 
`TotalRequestsThrottler.process()` directly on one
   key, `throttle(1_000_000).timePeriodMillis(1)` so a permit is always 
available, 5 rounds of 1 s after warm-up, medians,
   JDK 21 on an Apple Silicon laptop. Same test with this PR's throttler and 
with main's (the main-code diff reversed):
   
   | threads | main | this PR |
   |---|---|---|
   | 1 | 0.69 M exchanges/s | 0.70 M |
   | 2 | 0.52 M | 0.51 M |
   | 4 | 0.52 M | 0.51 M |
   | 8 | 0.50 M | 0.51 M |
   | 16 | 0.49 M | 0.51 M |
   
   The difference is within the noise. Throughput levels off at 2 threads in 
both versions, because of the existing
   per-exchange locks listed above, not because of `removedLock`.
   
   _Claude Code on behalf of allthingssecurity_
   



##########
core/camel-core/src/test/java/org/apache/camel/processor/throttle/requests/TotalRequestsThrottlerCleanTest.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.processor.throttle.requests;
+
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.CamelExecutionException;
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.processor.ThrottlerRejectedExecutionException;
+import org.apache.camel.processor.TotalRequestsThrottler;
+import org.apache.camel.support.ExpressionAdapter;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * The throttler cleans up its state some time after a permit was last 
returned. An exchange that looked up the state
+ * before the clean must not take a permit from the removed state, as the next 
exchanges get the permits of the state
+ * that replaces it, and more exchanges than allowed would pass in the time 
period.
+ */
+public class TotalRequestsThrottlerCleanTest extends ContextTestSupport {
+
+    private final CapturingExecutor executor = new CapturingExecutor();
+
+    @AfterEach
+    public void shutdownExecutor() {
+        executor.shutdownNow();
+    }
+
+    @Test
+    public void testCleanAfterExchangeLookedUpState() throws Exception {
+        getMockEndpoint("mock:result").expectedBodiesReceived("first", "race", 
"second");
+
+        // takes a permit, which schedules the clean
+        template.sendBody("direct:start", "first");
+        // the clean runs (as if 10 periods had passed) after race looked up 
the state, but before it takes a permit
+        template.sendBody("direct:start", "race");
+
+        // race took the first permit of the state that replaced the cleaned 
one, so one more permit is left

Review Comment:
   You are right, thanks. Reworded in 7504be388e85: the comment now says that 
`race` took its permit from the replacement state,
   so that state hands out only one more permit and not a second full set next 
to the permit `race` took. It also says
   that the clean runs here while `first`'s permit is still delayed (in 
practice 10 periods later), so `first`, `race` and
   `second` all pass, and that the test is about the replacement state's 
permits, not the per-period limit. I also dropped
   "as if 10 periods had passed" from the comment above it. The PR text no 
longer says "only 2 exchanges pass in the
   period"; it now describes what the test shows, in the same terms.
   
   _Claude Code on behalf of allthingssecurity_
   



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