This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new fb713a6077f7 CAMEL-26965: camel-core - interceptSendToEndpoint: 
process returns the value its callback is called with (#30129)
fb713a6077f7 is described below

commit fb713a6077f7c0cf9c895396a27952822b29c972
Author: allthingssecurity <[email protected]>
AuthorDate: Mon Nov 16 18:58:59 2026 +0530

    CAMEL-26965: camel-core - interceptSendToEndpoint: process returns the 
value its callback is called with (#30129)
    
    [CAMEL-26965](https://issues.apache.org/jira/browse/CAMEL-26965). Found by 
rule R3 of the exchange sanitizer 
([CAMEL-26630](https://issues.apache.org/jira/browse/CAMEL-26630)), whose first 
part (the `AsyncProcessor` contract: `process` returns the value its callback 
is called with) is the next sanitizer PR. That PR is meant to merge after this 
one.
    
    `InterceptSendToEndpointProcessor` returned the value of the `before` of 
the interceptor and called the callback with the value of what ran after it, 
the producer of the original endpoint or the `after` processor (`afterBefore`: 
`callback.done(doneSync1)`, and the return of the rest of the chain was 
dropped):
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../InterceptSendToEndpointProcessor.java          |  32 +++-
 .../InterceptSendToEndpointDoneSyncTest.java       | 204 +++++++++++++++++++++
 2 files changed, 228 insertions(+), 8 deletions(-)

diff --git 
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/InterceptSendToEndpointProcessor.java
 
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/InterceptSendToEndpointProcessor.java
index 635183ed5072..0f10039758f3 100644
--- 
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/InterceptSendToEndpointProcessor.java
+++ 
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/InterceptSendToEndpointProcessor.java
@@ -154,17 +154,28 @@ public class InterceptSendToEndpointProcessor extends 
DefaultAsyncProducer {
             
exchange.removeProperty(ExchangePropertyKey.INTERCEPT_SEND_TO_ENDPOINT_WHEN_MATCHED);
         }
         AsyncProcessor before = 
AsyncProcessorConverterHelper.convert(current.before());
-        return before.process(exchange, doneSync -> afterBefore(exchange, 
chain, index, current, callback, doneSync));
+        // what the rest of the chain returned: read only when the before was 
done on this thread, before it returned
+        boolean[] rest = { true };
+        boolean sync = before.process(exchange, doneSync -> {
+            rest[0] = afterBefore(exchange, chain, index, current, callback, 
doneSync);
+        });
+        // the value the callback is called with: false when the before or the 
rest of the chain went asynchronous
+        return sync && rest[0];
     }
 
-    private void afterBefore(
+    /**
+     * Goes on after the before processor of the interceptor, and returns 
whether the rest was done synchronously. The
+     * callback is called with false when the before or anything after it was 
asynchronous, so it gets the value that
+     * {@link #process(Exchange, AsyncCallback)} returns (the contract of 
{@link AsyncProcessor}).
+     */
+    private boolean afterBefore(
             Exchange exchange, List<Interceptor> chain, int index, Interceptor 
current, AsyncCallback callback,
             boolean doneSync) {
         // Decide whether to continue or not; similar logic to the Pipeline
         // check for error if so we should break out
         if (!continueProcessing(exchange, "skip sending to original intended 
destination: " + getEndpoint(), LOG)) {
             callback.done(doneSync);
-            return;
+            return doneSync;
         }
 
         // if the interceptor has predicate, then we should only skip if 
matched
@@ -176,24 +187,29 @@ public class InterceptSendToEndpointProcessor extends 
DefaultAsyncProducer {
                         getEndpoint(), exchange);
             }
             callback.done(doneSync);
-            return;
+            return doneSync;
         }
 
         ExchangeHelper.prepareOutToIn(exchange);
 
         AsyncCallback ac1 = doneSync1 -> {
             
exchange.removeProperty(ExchangePropertyKey.INTERCEPT_SEND_TO_ENDPOINT_WHEN_MATCHED);
-            callback.done(doneSync1);
+            callback.done(doneSync && doneSync1);
         };
-        AsyncCallback ac2 = null;
+        AsyncCallback next = ac1;
+        // what the after processor returned: read only when the rest of the 
chain was done on this thread
+        boolean[] afterSync = { true };
         if (current.after() != null && matched) {
             AsyncProcessor after = 
AsyncProcessorConverterHelper.convert(current.after());
-            ac2 = doneSync2 -> after.process(exchange, ac1);
+            next = doneSync2 -> {
+                afterSync[0] = after.process(exchange, doneSync3 -> 
ac1.done(doneSync2 && doneSync3));
+            };
         }
 
         // route to the next interceptor (or the original destination) and 
when done, then
         // optional route to the after processor
-        process(exchange, chain, index + 1, ac2 != null ? ac2 : ac1);
+        boolean sync = process(exchange, chain, index + 1, next);
+        return doneSync && sync && afterSync[0];
     }
 
     @Override
diff --git 
a/core/camel-core/src/test/java/org/apache/camel/processor/intercept/InterceptSendToEndpointDoneSyncTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/processor/intercept/InterceptSendToEndpointDoneSyncTest.java
new file mode 100644
index 000000000000..5d48b0bf33aa
--- /dev/null
+++ 
b/core/camel-core/src/test/java/org/apache/camel/processor/intercept/InterceptSendToEndpointDoneSyncTest.java
@@ -0,0 +1,204 @@
+/*
+ * 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.intercept;
+
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.AsyncCallback;
+import org.apache.camel.AsyncProducer;
+import org.apache.camel.CamelContext;
+import org.apache.camel.Consumer;
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Endpoint;
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.Producer;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.spi.InterceptSendToEndpoint;
+import org.apache.camel.spi.SendHook;
+import org.apache.camel.support.DefaultAsyncProducer;
+import org.apache.camel.support.DefaultComponent;
+import org.apache.camel.support.DefaultEndpoint;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.support.DefaultInterceptSendToEndpoint;
+import org.apache.camel.support.service.ServiceHelper;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+
+/**
+ * The producer of an intercepted endpoint keeps the contract of 
AsyncProcessor: process returns the value its callback
+ * is called with, also when the before of the interceptor and the producer of 
the original endpoint differ (one
+ * synchronous, the other not).
+ */
+class InterceptSendToEndpointDoneSyncTest extends ContextTestSupport {
+
+    @Override
+    protected CamelContext createCamelContext() throws Exception {
+        CamelContext context = super.createCamelContext();
+        // a component, so its endpoints are created when used, and the mock 
endpoints strategy wraps them
+        context.addComponent("async", new DefaultComponent() {
+            @Override
+            protected Endpoint createEndpoint(String uri, String remaining, 
Map<String, Object> parameters) {
+                return new AsyncEndpoint(uri, getCamelContext());
+            }
+        });
+        return context;
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() {
+                // the before of this interceptor is a route of its own, which 
goes on through the reactive executor
+                interceptSendToEndpoint("mock:result").to("mock:detour");
+
+                from("direct:start").to("mock:result");
+                // the routing slip goes on with its next step through the 
return value of the send, or through the
+                // callback when the send returned false
+                
from("direct:slip").routingSlip(constant("mock:result,mock:next"));
+            }
+        };
+    }
+
+    @Test
+    void anAsynchronousBeforeAndASynchronousProducer() throws Exception {
+        getMockEndpoint("mock:detour").expectedMessageCount(1);
+        getMockEndpoint("mock:result").expectedMessageCount(1);
+
+        Endpoint endpoint = context.getEndpoint("mock:result");
+        assertInstanceOf(InterceptSendToEndpoint.class, endpoint);
+        assertDoneSyncIsTheReturnedValue(endpoint);
+
+        assertMockEndpointsSatisfied();
+    }
+
+    @Test
+    void aSynchronousBeforeAndAnAsynchronousProducer() throws Exception {
+        getMockEndpoint("mock:before").expectedMessageCount(1);
+
+        // as advice with mockEndpoints() wraps an endpoint: the before is the 
producer of a mock, which is synchronous
+        DefaultInterceptSendToEndpoint endpoint
+                = new 
DefaultInterceptSendToEndpoint(context.getEndpoint("async:x"), false);
+        Producer before = context.getEndpoint("mock:before").createProducer();
+        endpoint.setBefore(before);
+        try {
+            endpoint.start();
+            boolean returned = assertDoneSyncIsTheReturnedValue(endpoint);
+
+            // the producer of async:x calls back on its own thread
+            assertFalse(returned);
+            assertMockEndpointsSatisfied();
+        } finally {
+            ServiceHelper.stopService(endpoint, before);
+        }
+    }
+
+    @Test
+    void aSendTwiceHookSendsTwiceToAnInterceptedEndpoint() throws Exception {
+        // as the duplicate fault of camel-chaos: when the first send returns 
false, SendHelper makes the second send in
+        // the callback of the first, so that callback must get false too
+        context.getCamelContextExtension().addSendHook(new SendHook() {
+            @Override
+            public long beforeSend(Exchange exchange, Endpoint endpoint) {
+                return "mock://result".equals(endpoint.getEndpointUri()) ? 
SEND_TWICE : PROCEED;
+            }
+
+            @Override
+            public void afterSend(Exchange exchange, Endpoint endpoint) {
+                // nothing to do
+            }
+        });
+        getMockEndpoint("mock:detour").expectedBodiesReceived("Hello", 
"Hello");
+        getMockEndpoint("mock:result").expectedBodiesReceived("Hello", 
"Hello");
+
+        Future<Object> sent = template.asyncSendBody("direct:start", "Hello");
+
+        assertMockEndpointsSatisfied();
+        // the exchange completes
+        sent.get(10, TimeUnit.SECONDS);
+    }
+
+    @Test
+    void aRoutingSlipGoesOnAfterAnInterceptedEndpoint() throws Exception {
+        getMockEndpoint("mock:detour").expectedBodiesReceived("Hello");
+        getMockEndpoint("mock:result").expectedBodiesReceived("Hello");
+        getMockEndpoint("mock:next").expectedBodiesReceived("Hello");
+
+        template.asyncSendBody("direct:slip", "Hello");
+
+        assertMockEndpointsSatisfied();
+    }
+
+    @Test
+    void theRoutesStillWork() throws Exception {
+        getMockEndpoint("mock:detour").expectedBodiesReceived("Hello");
+        getMockEndpoint("mock:result").expectedBodiesReceived("Hello");
+
+        template.sendBody("direct:start", "Hello");
+
+        assertMockEndpointsSatisfied();
+    }
+
+    private boolean assertDoneSyncIsTheReturnedValue(Endpoint endpoint) throws 
Exception {
+        AsyncProducer producer = endpoint.createAsyncProducer();
+        ServiceHelper.startService(producer);
+        try {
+            Exchange exchange = new DefaultExchange(context);
+            exchange.getMessage().setBody("Hello");
+            CompletableFuture<Boolean> callback = new CompletableFuture<>();
+            boolean returned = producer.process(exchange, callback::complete);
+            assertEquals(returned, callback.get(10, TimeUnit.SECONDS), "the 
value of the callback");
+            return returned;
+        } finally {
+            ServiceHelper.stopService(producer);
+        }
+    }
+
+    /**
+     * An endpoint whose producer calls its callback on a thread of its own.
+     */
+    private static final class AsyncEndpoint extends DefaultEndpoint {
+
+        AsyncEndpoint(String uri, CamelContext camelContext) {
+            super(uri, null);
+            setCamelContext(camelContext);
+        }
+
+        @Override
+        public Producer createProducer() {
+            return new DefaultAsyncProducer(this) {
+                @Override
+                public boolean process(Exchange exchange, AsyncCallback 
callback) {
+                    new Thread(() -> callback.done(false), 
"async-producer").start();
+                    return false;
+                }
+            };
+        }
+
+        @Override
+        public Consumer createConsumer(Processor processor) {
+            throw new UnsupportedOperationException("producer only");
+        }
+    }
+}

Reply via email to