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 5f62a26f8079 CAMEL-27039: camel-core - EventNotifierProducer: a 
producer that calls the callback and then throws completes the exchange once 
(#30245)
5f62a26f8079 is described below

commit 5f62a26f80798da71e80c7f09ef7bc060c423301
Author: allthingssecurity <[email protected]>
AuthorDate: Tue Nov 17 14:29:48 2026 +0530

    CAMEL-27039: camel-core - EventNotifierProducer: a producer that calls the 
callback and then throws completes the exchange once (#30245)
    
    …s the callback and then throws completes the exchange once
    
    EventNotifierProducer, the producer that @EndpointInject and @Produce inject
    (and the producer of the @Produce proxies), caught an exception of the
    producer by setting it on the exchange and calling the callback. When the
    producer had called the callback before it threw, the exchange was completed
    twice, and the completed exchange carried the exception.
    
    As SendProcessor does since CAMEL-26953, the producer now gets a callback 
per
    send that records that it was called: a throw after it is logged at WARN and
    not set on the exchange, and the doneSync the producer passed is returned. A
    throw before it fails the exchange as before, and an Error is thrown on as
    before.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../camel/processor/EventNotifierProducer.java     |  38 ++++-
 .../EventNotifierProducerProducerThrowsTest.java   | 173 +++++++++++++++++++++
 .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc    |   7 +
 3 files changed, 217 insertions(+), 1 deletion(-)

diff --git 
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/EventNotifierProducer.java
 
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/EventNotifierProducer.java
index bb2f32abc739..0d5eebea47e1 100644
--- 
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/EventNotifierProducer.java
+++ 
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/EventNotifierProducer.java
@@ -16,6 +16,8 @@
  */
 package org.apache.camel.processor;
 
+import java.util.concurrent.atomic.AtomicBoolean;
+
 import org.apache.camel.AsyncCallback;
 import org.apache.camel.AsyncProducer;
 import org.apache.camel.Endpoint;
@@ -55,11 +57,19 @@ public final class EventNotifierProducer extends 
DefaultAsyncProducer {
             return true;
         }
 
+        SendCallback send = new SendCallback(callback);
         try {
             LOG.debug(">>>> {} {}", getEndpoint(), exchange);
             // emit the sending and sent events around the send (and run the 
send hook if any)
-            return SendHelper.send(exchange, getEndpoint(), producer, 
callback);
+            return SendHelper.send(exchange, getEndpoint(), producer, send);
         } catch (Exception throwable) {
+            if (!send.compareAndSet(false, true)) {
+                // the producer called the callback and then threw: the 
exchange is already continued (maybe on another
+                // thread), so it is not completed a second time and the 
exception is not set on it
+                LOG.warn("The producer of {} threw an exception after it 
completed the exchange. This exception is ignored.",
+                        getEndpoint(), throwable);
+                return send.doneSync;
+            }
             exchange.setException(throwable);
             callback.done(true);
         }
@@ -67,6 +77,32 @@ public final class EventNotifierProducer extends 
DefaultAsyncProducer {
         return true;
     }
 
+    /**
+     * The callback of one send: calls the callback of the caller, and records 
that it did, so that an exception the
+     * producer throws after it called the callback does not complete the 
exchange a second time. A further call of the
+     * callback by the producer is passed on as before.
+     */
+    private final class SendCallback extends AtomicBoolean implements 
AsyncCallback {
+        private final AsyncCallback callback;
+        private volatile boolean doneSync;
+
+        private SendCallback(AsyncCallback callback) {
+            this.callback = callback;
+        }
+
+        @Override
+        public void done(boolean doneSync) {
+            if (compareAndSet(false, true)) {
+                this.doneSync = doneSync;
+            } else {
+                LOG.warn("The producer of {} completed the exchange after the 
send was completed (more than once, or after"
+                         + " it threw).",
+                        getEndpoint());
+            }
+            callback.done(doneSync);
+        }
+    }
+
     @Override
     public Endpoint getEndpoint() {
         return producer.getEndpoint();
diff --git 
a/core/camel-core/src/test/java/org/apache/camel/processor/EventNotifierProducerProducerThrowsTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/processor/EventNotifierProducerProducerThrowsTest.java
new file mode 100644
index 000000000000..b666d301af87
--- /dev/null
+++ 
b/core/camel-core/src/test/java/org/apache/camel/processor/EventNotifierProducerProducerThrowsTest.java
@@ -0,0 +1,173 @@
+/*
+ * 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;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.AsyncCallback;
+import org.apache.camel.Consumer;
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.Producer;
+import org.apache.camel.spi.CamelEvent;
+import org.apache.camel.support.DefaultAsyncProducer;
+import org.apache.camel.support.DefaultEndpoint;
+import org.apache.camel.support.EventNotifierSupport;
+import org.apache.camel.support.PluginHelper;
+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.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * An AsyncProducer that breaks the async contract by throwing from process, 
before or after it called the callback,
+ * called through the {@link EventNotifierProducer}, as the producers injected 
with {@code @EndpointInject} and the
+ * {@code @Produce} proxies are (DefaultDeferServiceFactory).
+ */
+class EventNotifierProducerProducerThrowsTest extends ContextTestSupport {
+
+    @Test
+    void testCallbackThenThrowCompletesOnce() throws Exception {
+        EventNotifierProducer producer = new EventNotifierProducer(new 
ThrowingEndpoint().createProducer());
+        ServiceHelper.startService(producer);
+        try {
+            Exchange exchange = 
context.getEndpoint("direct:start").createExchange();
+            exchange.getMessage().setHeader("mode", "after");
+            AtomicInteger done = new AtomicInteger();
+
+            boolean sync = producer.process(exchange, doneSync -> 
done.incrementAndGet());
+
+            // the exchange is completed once, without the exception the 
producer threw after it completed
+            assertEquals(1, done.get());
+            assertTrue(sync);
+            assertNull(exchange.getException());
+            assertEquals("Done", exchange.getMessage().getBody());
+        } finally {
+            ServiceHelper.stopService(producer);
+        }
+    }
+
+    @Test
+    void testThrowBeforeCallbackFailsTheExchange() throws Exception {
+        EventNotifierProducer producer = new EventNotifierProducer(new 
ThrowingEndpoint().createProducer());
+        ServiceHelper.startService(producer);
+        try {
+            Exchange exchange = 
context.getEndpoint("direct:start").createExchange();
+            exchange.getMessage().setHeader("mode", "before");
+            AtomicInteger done = new AtomicInteger();
+
+            boolean sync = producer.process(exchange, doneSync -> 
done.incrementAndGet());
+
+            assertEquals(1, done.get());
+            assertTrue(sync);
+            assertInstanceOf(IllegalStateException.class, 
exchange.getException());
+        } finally {
+            ServiceHelper.stopService(producer);
+        }
+    }
+
+    @Test
+    void testCallbackThenThrowWithEventsCompletesOnce() throws Exception {
+        List<CamelEvent> events = new ArrayList<>();
+        EventNotifierSupport notifier = new EventNotifierSupport() {
+            @Override
+            public void notify(CamelEvent event) {
+                events.add(event);
+            }
+
+            @Override
+            public boolean isEnabled(CamelEvent event) {
+                return event instanceof CamelEvent.ExchangeSendingEvent || 
event instanceof CamelEvent.ExchangeSentEvent;
+            }
+        };
+        context.getManagementStrategy().addEventNotifier(notifier);
+        ServiceHelper.startService(notifier);
+        EventNotifierProducer producer = new EventNotifierProducer(new 
ThrowingEndpoint().createProducer());
+        ServiceHelper.startService(producer);
+        try {
+            Exchange exchange = 
context.getEndpoint("direct:start").createExchange();
+            exchange.getMessage().setHeader("mode", "after");
+            AtomicInteger done = new AtomicInteger();
+
+            producer.process(exchange, doneSync -> done.incrementAndGet());
+
+            assertEquals(1, done.get());
+            assertNull(exchange.getException());
+            // one sending and one sent event
+            assertEquals(2, events.size(), "Events: " + events);
+            assertInstanceOf(CamelEvent.ExchangeSendingEvent.class, 
events.get(0));
+            assertInstanceOf(CamelEvent.ExchangeSentEvent.class, 
events.get(1));
+        } finally {
+            ServiceHelper.stopService(producer);
+            context.getManagementStrategy().removeEventNotifier(notifier);
+        }
+    }
+
+    @Test
+    void testInjectedProducerCallbackThenThrowSucceeds() throws Exception {
+        // the producer that @EndpointInject injects
+        context.addEndpoint("throwing:producer", new ThrowingEndpoint());
+        Producer producer
+                = 
PluginHelper.getDeferServiceFactory(context).createProducer(context.getEndpoint("throwing:producer"));
+        ServiceHelper.startService(producer);
+        try {
+            Exchange exchange = 
context.getEndpoint("direct:start").createExchange();
+            exchange.getMessage().setHeader("mode", "after");
+
+            producer.process(exchange);
+
+            // the producer completed the exchange: the exception it threw 
afterwards does not fail it
+            assertNull(exchange.getException());
+            assertEquals("Done", exchange.getMessage().getBody());
+        } finally {
+            ServiceHelper.stopService(producer);
+        }
+    }
+
+    private final class ThrowingEndpoint extends DefaultEndpoint {
+
+        ThrowingEndpoint() {
+            super("throwing:producer", null);
+            setCamelContext(context);
+        }
+
+        @Override
+        public Producer createProducer() {
+            return new DefaultAsyncProducer(this) {
+                @Override
+                public boolean process(Exchange exchange, AsyncCallback 
callback) {
+                    if 
("after".equals(exchange.getMessage().getHeader("mode"))) {
+                        exchange.getMessage().setBody("Done");
+                        callback.done(true);
+                    }
+                    throw new IllegalStateException("Simulated producer that 
throws");
+                }
+            };
+        }
+
+        @Override
+        public Consumer createConsumer(Processor processor) {
+            throw new UnsupportedOperationException();
+        }
+    }
+}
diff --git 
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 2aa30d446426..edcf9cdd8574 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -8604,6 +8604,13 @@ The asynchronous sends of the `ProducerTemplate` now 
fire one `ExchangeSendingEv
 send; before, each event was fired twice. Tracing (camel-tracing, 
camel-telemetry), which builds its spans from these
 events, now sees one sending/sent pair per asynchronous send of the 
`ProducerTemplate` instead of two.
 
+=== camel-core - an injected producer whose producer calls the callback and 
then throws
+
+The same now applies to the producers that `@EndpointInject` and `@Produce` 
inject (`Producer` fields and the
+`@Produce` proxies, made by the `DeferServiceFactory`): when the producer of 
the endpoint calls the callback and then
+throws, the exception is logged at WARN and no longer set on the exchange, and 
the callback is called once. Before, the
+exchange failed with that exception after the producer completed it, and the 
callback was called a second time.
+
 === camel-core - a hook before each step of a route
 
 A new SPI `org.apache.camel.spi.StepHook`, added with 
`ExtendedCamelContext.addStepHook`, can fail or delay each step of

Reply via email to