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 7560b308e6f5 CAMEL-27417: camel-core - in-memory saga: a compensate or
complete during a running compensation or completion gets its outcome (#30760)
7560b308e6f5 is described below
commit 7560b308e6f5e15497561243f3854492d2cdcfa7
Author: allthingssecurity <[email protected]>
AuthorDate: Wed Nov 25 16:46:03 2026 +0530
CAMEL-27417: camel-core - in-memory saga: a compensate or complete during a
running compensation or completion gets its outcome (#30760)
When compensate() lost the race to start the compensation (to the
timeout of a step, or to another caller such as saga:compensate), it read
the status once and returned a successful future while the status was
COMPENSATING. The running compensation could still use up its retries
and end the saga FAILED, so the caller was told the saga was compensated,
and the Saga EIP in AUTO mode returned the exchange without the
compensation failure. complete() did the same while COMPLETING.
The coordinator now keeps the outcome of the compensation or completion
that ended the saga, set together with that change of status. A caller
that finds the saga being finalized the way it asks waits for that
outcome, and then answers from the final status as before (success when
COMPENSATED or COMPLETED, otherwise "Cannot compensate: status is
FAILED"). The exchanges that compensate or complete a step carry the
property CamelInMemorySagaFinalizing with the id of their saga, and a call
from such an exchange for its own saga is answered at once, as before, so
a compensation route that calls saga:compensate does not wait for itself.
Found with a TLA+ model.
Also in this change:
- CAMEL-27417: camel-core - review follow-up: a compensation route that
removes the properties does not wait for itself
- CAMEL-27417: camel-core - review follow-up: test the exchange property
guard with a thread hop
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../org/apache/camel/catalog/docs/saga-eip.adoc | 2 +
.../src/main/docs/modules/eips/pages/saga-eip.adoc | 2 +
.../processor/SagaFinalizationInProgressTest.java | 287 +++++++++++++++++++++
.../apache/camel/saga/InMemorySagaCoordinator.java | 98 +++++--
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 10 +
5 files changed, 382 insertions(+), 17 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/saga-eip.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/saga-eip.adoc
index 0406f552a3e4..5611175f570e 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/saga-eip.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/saga-eip.adoc
@@ -393,6 +393,8 @@ so it should take into account that it may be triggered
multiple times and shoul
If compensation cannot be done after all retries, a manual intervention
process should be triggered.
The in-memory Saga service logs a warning, marks the Saga as failed, and keeps
the exception that caused the compensation
on the exchange, with the compensation failure added to it as a suppressed
exception.
+A compensation or completion asked for while the in-memory Saga service
already compensates or completes the Saga
+(because of the timeout of a step, or another caller such as
`saga:compensate`) waits for it and gets its outcome.
[NOTE]
====
diff --git
a/core/camel-core-engine/src/main/docs/modules/eips/pages/saga-eip.adoc
b/core/camel-core-engine/src/main/docs/modules/eips/pages/saga-eip.adoc
index 0406f552a3e4..5611175f570e 100644
--- a/core/camel-core-engine/src/main/docs/modules/eips/pages/saga-eip.adoc
+++ b/core/camel-core-engine/src/main/docs/modules/eips/pages/saga-eip.adoc
@@ -393,6 +393,8 @@ so it should take into account that it may be triggered
multiple times and shoul
If compensation cannot be done after all retries, a manual intervention
process should be triggered.
The in-memory Saga service logs a warning, marks the Saga as failed, and keeps
the exception that caused the compensation
on the exchange, with the compensation failure added to it as a suppressed
exception.
+A compensation or completion asked for while the in-memory Saga service
already compensates or completes the Saga
+(because of the timeout of a step, or another caller such as
`saga:compensate`) waits for it and gets its outcome.
[NOTE]
====
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/SagaFinalizationInProgressTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/SagaFinalizationInProgressTest.java
new file mode 100644
index 000000000000..897870deaebf
--- /dev/null
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/SagaFinalizationInProgressTest.java
@@ -0,0 +1,287 @@
+/*
+ * 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.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.model.SagaCompletionMode;
+import org.apache.camel.saga.CamelSagaCoordinator;
+import org.apache.camel.saga.InMemorySagaService;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A compensate() or complete() of the in-memory saga that finds the saga
already being compensated or completed (by a
+ * step timeout or another caller) gets the outcome of that compensation or
completion, not a success before it is
+ * known.
+ */
+class SagaFinalizationInProgressTest extends ContextTestSupport {
+
+ private final CountDownLatch finalizationStarted = new CountDownLatch(1);
+ private final CountDownLatch releaseFinalization = new CountDownLatch(1);
+ private final AtomicReference<CamelSagaCoordinator> coordinator = new
AtomicReference<>();
+ private final AtomicReference<Exchange> ownCompensateAnswered = new
AtomicReference<>();
+ private final AtomicReference<Thread> compensationThread = new
AtomicReference<>();
+ private final AtomicReference<Thread> ownCompensateThread = new
AtomicReference<>();
+ private InMemorySagaService sagaService;
+
+ @Override
+ @AfterEach
+ public void tearDown() throws Exception {
+ releaseFinalization.countDown();
+ super.tearDown();
+ }
+
+ @Test
+ void ownerThatLosesToTheTimeoutCompensationGetsItsFailure() throws
Exception {
+ CompletableFuture<Exchange> owner =
template.asyncSend("direct:fails-after-timeout",
+ e -> e.getMessage().setBody("hello"));
+ assertTrue(finalizationStarted.await(10, TimeUnit.SECONDS), "the
timeout started the compensation");
+
+ // on main the exchange returned at once, as if the saga had been
compensated
+ await().during(300, TimeUnit.MILLISECONDS)
+ .atMost(5, TimeUnit.SECONDS).until(() -> !owner.isDone());
+ releaseFinalization.countDown();
+
+ Exchange result = owner.get(10, TimeUnit.SECONDS);
+ Exception ex = result.getException();
+ assertInstanceOf(IllegalArgumentException.class, ex);
+ assertEquals(1, ex.getSuppressed().length, "the compensation failure
should be attached to the exchange");
+ assertInstanceOf(IllegalStateException.class, ex.getSuppressed()[0]);
+ assertTrue(ex.getSuppressed()[0].getMessage().contains("status is
FAILED"), ex.getSuppressed()[0].getMessage());
+ }
+
+ @Test
+ void compensateWhileTheTimeoutCompensationRunsGetsItsFailure() throws
Exception {
+ template.sendBody("direct:manual-with-timeout", "hello");
+ assertTrue(finalizationStarted.await(10, TimeUnit.SECONDS), "the
timeout started the compensation");
+ CamelSagaCoordinator saga = coordinator.get();
+ assertNotNull(saga);
+
+ // a second caller, as the saga:compensate endpoint
+ CompletableFuture<Void> second =
saga.compensate(context.getEndpoint("direct:other").createExchange());
+ // on main it completed at once, successfully
+ await().during(300, TimeUnit.MILLISECONDS)
+ .atMost(5, TimeUnit.SECONDS).until(() -> !second.isDone());
+ releaseFinalization.countDown();
+
+ ExecutionException ex = assertThrows(ExecutionException.class, () ->
second.get(10, TimeUnit.SECONDS));
+ assertInstanceOf(IllegalStateException.class, ex.getCause());
+ assertTrue(ex.getCause().getMessage().contains("status is FAILED"),
ex.getCause().getMessage());
+ }
+
+ @Test
+ void completeWhileAnotherCompletionRunsGetsItsFailure() throws Exception {
+ template.sendBody("direct:manual-completion-fails", "hello");
+ CamelSagaCoordinator saga = coordinator.get();
+ assertNotNull(saga);
+
+ CompletableFuture<Void> first =
saga.complete(context.getEndpoint("direct:first").createExchange());
+ assertTrue(finalizationStarted.await(10, TimeUnit.SECONDS), "the first
call started the completion");
+ CompletableFuture<Void> second =
saga.complete(context.getEndpoint("direct:second").createExchange());
+ // on main it completed at once, successfully
+ await().during(300, TimeUnit.MILLISECONDS)
+ .atMost(5, TimeUnit.SECONDS).until(() -> !second.isDone());
+ releaseFinalization.countDown();
+
+ assertThrows(ExecutionException.class, () -> first.get(10,
TimeUnit.SECONDS));
+ ExecutionException ex = assertThrows(ExecutionException.class, () ->
second.get(10, TimeUnit.SECONDS));
+ assertInstanceOf(IllegalStateException.class, ex.getCause());
+ assertTrue(ex.getCause().getMessage().contains("status is FAILED"),
ex.getCause().getMessage());
+ }
+
+ @Test
+ void compensateWhileTheCompensationRunsGetsItsSuccess() throws Exception {
+ template.sendBody("direct:manual-compensation-succeeds", "hello");
+ CamelSagaCoordinator saga = coordinator.get();
+ assertNotNull(saga);
+
+ CompletableFuture<Void> first =
saga.compensate(context.getEndpoint("direct:first").createExchange());
+ assertTrue(finalizationStarted.await(10, TimeUnit.SECONDS), "the first
call started the compensation");
+ CompletableFuture<Void> second =
saga.compensate(context.getEndpoint("direct:second").createExchange());
+ releaseFinalization.countDown();
+
+ assertNull(first.get(10, TimeUnit.SECONDS));
+ assertNull(second.get(10, TimeUnit.SECONDS));
+ }
+
+ @Test
+ void compensationThatCompensatesItsOwnSagaDoesNotWaitForItself() throws
Exception {
+ // control, as on main: the compensation route asks to compensate the
saga it compensates, and waits for the
+ // answer; it is answered at once instead of waiting for the
compensation it is part of
+ Exchange result =
template.send("direct:compensation-compensates-its-saga", e ->
e.getMessage().setBody("hello"));
+
+ Exception ex = result.getException();
+ assertInstanceOf(IllegalArgumentException.class, ex);
+ assertEquals(0, ex.getSuppressed().length, "the compensation
succeeded");
+ CamelSagaCoordinator saga = coordinator.get();
+ assertNull(saga.compensate(result).get(10, TimeUnit.SECONDS));
+ assertNull(sagaService.getSaga(saga.getId()).get(), "the saga ended");
+ }
+
+ @Test
+ void
compensationThatRemovesThePropertiesAndCompensatesItsOwnSagaDoesNotWaitForItself()
throws Exception {
+ // the compensation route removes all the exchange properties and then
calls saga:compensate: the saga id is
+ // still on the exchange, and the call must be answered at once, not
wait for the compensation it is part of
+ CompletableFuture<Exchange> owner =
template.asyncSend("direct:compensation-removes-properties",
+ e -> e.getMessage().setBody("hello"));
+
+ Exchange result = owner.get(10, TimeUnit.SECONDS);
+ Exception ex = result.getException();
+ assertInstanceOf(IllegalArgumentException.class, ex);
+ assertEquals(0, ex.getSuppressed().length, "the compensation
succeeded");
+ Exchange answered = ownCompensateAnswered.get();
+ assertNotNull(answered, "saga:compensate answered the compensation
route");
+ assertNull(answered.getException());
+ assertNull(sagaService.getSaga(coordinator.get().getId()).get(), "the
saga ended");
+ }
+
+ @Test
+ void
compensationThatCompensatesItsOwnSagaFromAnotherThreadDoesNotWaitForItself()
throws Exception {
+ // the compensation route goes on in another thread and then calls
saga:compensate: that thread is not the one
+ // that called the compensation endpoint, so only the exchange
property tells that the call is part of the
+ // compensation of the same saga, and the call must be answered at once
+ CompletableFuture<Exchange> owner =
template.asyncSend("direct:compensation-changes-thread",
+ e -> e.getMessage().setBody("hello"));
+
+ Exchange result = owner.get(10, TimeUnit.SECONDS);
+ Exception ex = result.getException();
+ assertInstanceOf(IllegalArgumentException.class, ex);
+ assertEquals(0, ex.getSuppressed().length, "the compensation
succeeded");
+ Exchange answered = ownCompensateAnswered.get();
+ assertNotNull(answered, "saga:compensate answered the compensation
route");
+ assertNull(answered.getException());
+ assertNotNull(compensationThread.get());
+ assertNotSame(compensationThread.get(), ownCompensateThread.get(),
+ "saga:compensate was called from another thread than the
compensation endpoint");
+ assertNull(sagaService.getSaga(coordinator.get().getId()).get(), "the
saga ended");
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+ sagaService = new InMemorySagaService();
+ sagaService.setMaxRetryAttempts(1);
+ context.addService(sagaService);
+
+ // the body outlives the timeout of the step, waits until the
compensation runs, and then fails
+ from("direct:fails-after-timeout")
+ .saga().timeout(200,
TimeUnit.MILLISECONDS).compensation("direct:blocks-then-fails")
+ .process(e -> {
+ waitFor(finalizationStarted, "the timeout started
the compensation");
+ throw new IllegalArgumentException("business
failure");
+ });
+
+ from("direct:manual-with-timeout")
+ .saga().completionMode(SagaCompletionMode.MANUAL)
+ .timeout(200,
TimeUnit.MILLISECONDS).compensation("direct:blocks-then-fails")
+ .process(e -> captureCoordinator(e));
+
+ from("direct:manual-completion-fails")
+ .saga().completionMode(SagaCompletionMode.MANUAL)
+ .completion("direct:blocks-then-fails")
+ .process(e -> captureCoordinator(e));
+
+ from("direct:manual-compensation-succeeds")
+ .saga().completionMode(SagaCompletionMode.MANUAL)
+ .compensation("direct:blocks-then-succeeds")
+ .process(e -> captureCoordinator(e));
+
+ from("direct:compensation-compensates-its-saga")
+ .saga().compensation("direct:compensates-its-saga")
+ .process(e -> captureCoordinator(e))
+ .process(e -> {
+ throw new IllegalArgumentException("business
failure");
+ });
+
+ from("direct:blocks-then-fails")
+ .process(e -> {
+ finalizationStarted.countDown();
+ waitFor(releaseFinalization, "the test released
the finalization");
+ throw new IllegalStateException("finalization
failure");
+ });
+
+ from("direct:blocks-then-succeeds")
+ .process(e -> {
+ finalizationStarted.countDown();
+ waitFor(releaseFinalization, "the test released
the finalization");
+ });
+
+ from("direct:compensates-its-saga")
+ .process(e -> coordinator.get().compensate(e).get(5,
TimeUnit.SECONDS));
+
+ from("direct:compensation-removes-properties")
+
.saga().compensation("direct:removes-properties-then-compensates")
+ .process(e -> captureCoordinator(e))
+ .process(e -> {
+ throw new IllegalArgumentException("business
failure");
+ });
+
+ from("direct:removes-properties-then-compensates")
+ .removeProperties("*")
+ .to("saga:compensate")
+ .process(ownCompensateAnswered::set);
+
+ from("direct:compensation-changes-thread")
+
.saga().compensation("direct:changes-thread-then-compensates")
+ .process(e -> captureCoordinator(e))
+ .process(e -> {
+ throw new IllegalArgumentException("business
failure");
+ });
+
+ from("direct:changes-thread-then-compensates")
+ .process(e ->
compensationThread.set(Thread.currentThread()))
+ .threads()
+ .process(e ->
ownCompensateThread.set(Thread.currentThread()))
+ .to("saga:compensate")
+ .process(ownCompensateAnswered::set);
+ }
+ };
+ }
+
+ /**
+ * Waits in a route for the test thread: if it does not come, the exchange
fails with this message instead of a
+ * failed assertion that would show up later as an unrelated one.
+ */
+ private static void waitFor(CountDownLatch latch, String what) throws
InterruptedException {
+ if (!latch.await(10, TimeUnit.SECONDS)) {
+ throw new IllegalStateException("Test route gave up after 10
seconds waiting until " + what);
+ }
+ }
+
+ private void captureCoordinator(Exchange exchange) throws Exception {
+
coordinator.set(sagaService.getSaga(exchange.getExchangeExtension().getSagaLongRunningAction()).get());
+ }
+}
diff --git
a/core/camel-support/src/main/java/org/apache/camel/saga/InMemorySagaCoordinator.java
b/core/camel-support/src/main/java/org/apache/camel/saga/InMemorySagaCoordinator.java
index 1e04dc749f2a..34d9caaeee22 100644
---
a/core/camel-support/src/main/java/org/apache/camel/saga/InMemorySagaCoordinator.java
+++
b/core/camel-support/src/main/java/org/apache/camel/saga/InMemorySagaCoordinator.java
@@ -57,6 +57,11 @@ public class InMemorySagaCoordinator implements
CamelSagaCoordinator {
}
private static final Logger LOG =
LoggerFactory.getLogger(InMemorySagaCoordinator.class);
+ // set on the exchanges that compensate or complete a step, to the id of
their saga
+ private static final String FINALIZING_SAGA =
"CamelInMemorySagaFinalizing";
+ // the id of the saga whose compensation or completion endpoint the
current thread is calling: unlike the exchange
+ // property, a route cannot remove it (removeProperties("*")), so it
covers the synchronous part of that route
+ private static final ThreadLocal<String> FINALIZING_ON_THREAD = new
ThreadLocal<>();
private final CamelContext camelContext;
private final InMemorySagaService sagaService;
@@ -66,6 +71,9 @@ public class InMemorySagaCoordinator implements
CamelSagaCoordinator {
private final AtomicReference<Status> currentStatus;
// makes the status check and the enlistment of a step atomic with the
change of status that ends the saga
private final Lock lock = new ReentrantLock();
+ // the compensation or completion that ended the saga, set with that
change of status: a caller that finds the saga
+ // already being compensated or completed gets its outcome, instead of a
success before it is known
+ private volatile Finalization finalization;
public InMemorySagaCoordinator(CamelContext camelContext,
InMemorySagaService sagaService, String sagaId) {
this.camelContext = ObjectHelper.notNull(camelContext, "camelContext");
@@ -125,7 +133,7 @@ public class InMemorySagaCoordinator implements
CamelSagaCoordinator {
ScheduledFuture<?> timeoutFuture =
sagaService.getExecutorService().schedule(() -> {
List<StepEnlistment> steps = end(Status.COMPENSATING);
if (steps != null) {
- doCompensate(exchange, steps);
+ finish(doCompensate(exchange, steps));
}
}, step.getTimeoutInMilliseconds().get(),
TimeUnit.MILLISECONDS);
timeoutFutures.add(timeoutFuture);
@@ -143,7 +151,7 @@ public class InMemorySagaCoordinator implements
CamelSagaCoordinator {
if (steps != null) {
cancelTimeouts();
- return doCompensate(exchange, steps).thenApply(res -> {
+ return finish(doCompensate(exchange, steps)).thenApply(res -> {
if (!res) {
throw new RuntimeCamelException(
"Unable to compensate all required steps of the
saga " + sagaId);
@@ -152,14 +160,7 @@ public class InMemorySagaCoordinator implements
CamelSagaCoordinator {
});
}
- Status status = currentStatus.get();
- if (status != Status.COMPENSATING && status != Status.COMPENSATED) {
- CompletableFuture<Void> res = new CompletableFuture<>();
- res.completeExceptionally(new IllegalStateException("Cannot
compensate: status is " + status));
- return res;
- }
-
- return CompletableFuture.completedFuture(null);
+ return afterFinalization(exchange, Status.COMPENSATING,
Status.COMPENSATED, "compensate");
}
@Override
@@ -168,7 +169,7 @@ public class InMemorySagaCoordinator implements
CamelSagaCoordinator {
if (steps != null) {
cancelTimeouts();
- return doComplete(exchange, steps).thenApply(res -> {
+ return finish(doComplete(exchange, steps)).thenApply(res -> {
if (!res) {
throw new RuntimeCamelException(
"Unable to complete all required steps of the saga
" + sagaId);
@@ -177,16 +178,56 @@ public class InMemorySagaCoordinator implements
CamelSagaCoordinator {
});
}
- Status status = currentStatus.get();
- if (status != Status.COMPLETING && status != Status.COMPLETED) {
- CompletableFuture<Void> res = new CompletableFuture<>();
- res.completeExceptionally(new IllegalStateException("Cannot
complete: status is " + status));
- return res;
+ return afterFinalization(exchange, Status.COMPLETING,
Status.COMPLETED, "complete");
+ }
+
+ /**
+ * The answer to a {@code compensate()} or {@code complete()} that found
the saga no longer running: once the
+ * compensation or completion that ended the saga is done, success if it
is of the kind asked for and succeeded,
+ * otherwise an {@link IllegalStateException} with the status.
+ * <p>
+ * A call from the compensation or completion of this saga itself (its
route calls {@code saga:compensate}, say) is
+ * answered at once, as before: it would otherwise wait for the very
finalization it is part of. Such a call is
+ * recognized by the thread that calls the compensation or completion
endpoint, which covers the route even when it
+ * removes the exchange properties, or by the exchange property, which
covers copies of the exchange that go on in
+ * other threads.
+ */
+ private CompletableFuture<Void> afterFinalization(
+ Exchange exchange, Status running, Status succeeded, String
action) {
+ Finalization current = finalization;
+ boolean finalizing = sagaId.equals(FINALIZING_ON_THREAD.get())
+ || exchange != null &&
sagaId.equals(exchange.getProperty(FINALIZING_SAGA, String.class));
+ if (current == null || current.kind() != running ||
current.outcome().isDone() || finalizing) {
+ return statusAnswer(running, succeeded, action);
}
+ // the status is set to the final one before the outcome is completed
(see doCompensate and doComplete)
+ return current.outcome().handle((res, ex) -> null)
+ .thenCompose(ignored -> statusAnswer(running, succeeded,
action));
+ }
+ private CompletableFuture<Void> statusAnswer(Status running, Status
succeeded, String action) {
+ Status status = currentStatus.get();
+ if (status != running && status != succeeded) {
+ return CompletableFuture.failedFuture(new
IllegalStateException("Cannot " + action + ": status is " + status));
+ }
return CompletableFuture.completedFuture(null);
}
+ /**
+ * Completes the outcome of the finalization that ended the saga with the
result of the compensation or completion.
+ */
+ private CompletableFuture<Boolean> finish(CompletableFuture<Boolean>
result) {
+ CompletableFuture<Boolean> outcome = finalization.outcome();
+ result.whenComplete((res, ex) -> {
+ if (ex != null) {
+ outcome.completeExceptionally(ex);
+ } else {
+ outcome.complete(res);
+ }
+ });
+ return result;
+ }
+
/**
* Changes the status from RUNNING to the given status, and returns the
steps enlisted at that time, or
* <code>null</code> if the saga is not running. This holds the lock that
beginStep holds while it checks the status
@@ -196,6 +237,7 @@ public class InMemorySagaCoordinator implements
CamelSagaCoordinator {
lock.lock();
try {
if (currentStatus.compareAndSet(Status.RUNNING, status)) {
+ finalization = new Finalization(status, new
CompletableFuture<>());
return new ArrayList<>(enlistments);
}
return null;
@@ -268,7 +310,7 @@ public class InMemorySagaCoordinator implements
CamelSagaCoordinator {
Exchange target = createExchange(exchange, endpoint, enlistment);
return CompletableFuture.supplyAsync(() -> {
- Exchange res = sagaService.getProducerTemplate().send(endpoint,
target);
+ Exchange res = sendFinalizing(endpoint, target);
Exception ex = res.getException();
if (ex != null) {
throw new RuntimeCamelException(res.getException());
@@ -300,11 +342,30 @@ public class InMemorySagaCoordinator implements
CamelSagaCoordinator {
});
}
+ /**
+ * Sends the exchange to the compensation or completion endpoint, with the
current thread marked as finalizing this
+ * saga while it does. The previous mark is restored, so the thread of the
pool keeps no mark afterwards.
+ */
+ private Exchange sendFinalizing(Endpoint endpoint, Exchange target) {
+ String previous = FINALIZING_ON_THREAD.get();
+ FINALIZING_ON_THREAD.set(sagaId);
+ try {
+ return sagaService.getProducerTemplate().send(endpoint, target);
+ } finally {
+ if (previous == null) {
+ FINALIZING_ON_THREAD.remove();
+ } else {
+ FINALIZING_ON_THREAD.set(previous);
+ }
+ }
+ }
+
@SuppressWarnings("deprecation")
private Exchange createExchange(Exchange parent, Endpoint endpoint,
StepEnlistment enlistment) {
Exchange answer = endpoint.createExchange();
answer.getMessage().setHeader(Exchange.SAGA_LONG_RUNNING_ACTION,
getId());
answer.getExchangeExtension().setSagaLongRunningAction(getId());
+ answer.setProperty(FINALIZING_SAGA, getId());
// preserve span from parent, so we can link this new exchange to the
parent span for distributed tracing
Object span = parent != null ?
parent.getProperty(ExchangePropertyKey.OTEL_ACTIVE_SPAN) : null;
@@ -331,6 +392,9 @@ public class InMemorySagaCoordinator implements
CamelSagaCoordinator {
return reversed;
}
+ private record Finalization(Status kind, CompletableFuture<Boolean>
outcome) {
+ }
+
private static class StepEnlistment {
final CamelSagaStep step;
final Map<String, Object> optionValues;
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 28a12b52fbbb..8447dee2cce3 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
@@ -1810,6 +1810,16 @@ or payload from the body after a timed out `pollEnrich`
must keep it before the
with the same message id, headers and attachments, so after a timeout it is no
longer of the message type of the
consumer (such as `GenericFileMessage` or `JmsMessage`).
+=== camel-core - the in-memory saga answers a compensate or complete during a
running finalization with its outcome
+
+With the in-memory saga service (`InMemorySagaService`), a `compensate()` or
`complete()` that finds the saga already
+being compensated or completed (by the timeout of a step, or by another caller
such as `saga:compensate`,
+`saga:complete` or the Saga EIP in `AUTO` mode) now waits for that
compensation or completion, and fails when it
+fails (`Cannot compensate: status is FAILED`). Before, it reported success at
once, also when the compensation then
+failed. The exchanges that compensate or complete a step carry the exchange
property `CamelInMemorySagaFinalizing`
+with the id of their saga; a call for its own saga from such an exchange, or
from the thread that calls the
+compensation or completion endpoint (also after `removeProperties("*")`), is
answered at once, as before.
+
=== camel-core - Loop EIP breakOnShutdown
The Loop EIP with `breakOnShutdown` now only breaks out when the route (or
Camel) is stopped, and no longer on suspend.