This is an automated email from the ASF dual-hosted git repository. davsclaus pushed a commit to branch CAMEL-27542-saga-stop-fails-finalization in repository https://gitbox.apache.org/repos/asf/camel.git
commit 788321c05dadc1834f1b360d7ab5739fcc0cd8bb Author: Claus Ibsen <[email protected]> AuthorDate: Fri Nov 27 10:12:11 2026 +0100 CAMEL-27542: camel-core - when the InMemorySagaService stops, fail the saga finalizations that are still running When the in-memory saga service stopped while a compensation or completion was still running, its pending retry was dropped by the shutdown of the executor, so the caller that started the finalization and the callers waiting for its outcome never got an answer (or a waiter that came later got a success). The service now fails the outcome of each finalization still running with a RejectedExecutionException after its executor is shut down. The winner's compensate()/complete() follows that outcome, and a waiter fails with the exception when the status is still COMPENSATING or COMPLETING. A scheduled retry that throws now fails its attempt instead of leaving it open. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Claus Ibsen <[email protected]> --- .../processor/SagaStopDuringFinalizationTest.java | 117 +++++++++++++++++++++ .../apache/camel/saga/InMemorySagaCoordinator.java | 49 ++++++--- .../org/apache/camel/saga/InMemorySagaService.java | 10 +- .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 4 + 4 files changed, 165 insertions(+), 15 deletions(-) diff --git a/core/camel-core/src/test/java/org/apache/camel/processor/SagaStopDuringFinalizationTest.java b/core/camel-core/src/test/java/org/apache/camel/processor/SagaStopDuringFinalizationTest.java new file mode 100644 index 000000000000..2f5a37328ac4 --- /dev/null +++ b/core/camel-core/src/test/java/org/apache/camel/processor/SagaStopDuringFinalizationTest.java @@ -0,0 +1,117 @@ +/* + * 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.RejectedExecutionException; +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.Test; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * When the in-memory saga service stops while a compensation still waits for a retry, the caller that started the + * compensation and the caller that waits for its outcome both fail, instead of waiting for a retry that never runs. + */ +class SagaStopDuringFinalizationTest extends ContextTestSupport { + + private final CountDownLatch compensationFailed = new CountDownLatch(1); + private final AtomicReference<CamelSagaCoordinator> coordinator = new AtomicReference<>(); + private InMemorySagaService sagaService; + + @Test + void stopWhileTheRetryIsScheduledFailsTheCompensation() throws Exception { + // the retry is still scheduled when the shutdown of the executor gives up waiting and drops it + sagaService.setMaxRetryAttempts(3); + sagaService.setRetryDelayInMilliseconds(60000); + context.getExecutorServiceManager().setShutdownAwaitTermination(500); + + assertCallersFailWhenTheServiceStops(); + } + + @Test + void stopBeforeTheRetryRunsFailsTheCompensation() throws Exception { + // the retry runs while the executor shuts down, and the executor drops the attempt it submits + sagaService.setMaxRetryAttempts(100); + sagaService.setRetryDelayInMilliseconds(1000); + context.getExecutorServiceManager().setShutdownAwaitTermination(20000); + + assertCallersFailWhenTheServiceStops(); + } + + private void assertCallersFailWhenTheServiceStops() throws Exception { + template.sendBody("direct:manual", "hello"); + CamelSagaCoordinator saga = coordinator.get(); + assertNotNull(saga); + + CompletableFuture<Void> first = saga.compensate(context.getEndpoint("direct:first").createExchange()); + assertTrue(compensationFailed.await(10, TimeUnit.SECONDS), "the first attempt of the compensation failed"); + CompletableFuture<Void> second = saga.compensate(context.getEndpoint("direct:second").createExchange()); + await().during(300, TimeUnit.MILLISECONDS) + .atMost(5, TimeUnit.SECONDS).until(() -> !first.isDone() && !second.isDone()); + + sagaService.stop(); + + // before, both waited until the retry, which never runs + await().atMost(20, TimeUnit.SECONDS).until(() -> first.isDone() && second.isDone()); + ExecutionException ex = assertThrows(ExecutionException.class, () -> first.get(1, TimeUnit.SECONDS)); + assertInstanceOf(RejectedExecutionException.class, ex.getCause()); + ex = assertThrows(ExecutionException.class, () -> second.get(1, TimeUnit.SECONDS)); + assertInstanceOf(RejectedExecutionException.class, ex.getCause()); + assertTrue(ex.getCause().getMessage().contains(saga.getId()), ex.getCause().getMessage()); + } + + @Override + protected RouteBuilder createRouteBuilder() { + return new RouteBuilder() { + @Override + public void configure() throws Exception { + sagaService = new InMemorySagaService(); + context.addService(sagaService); + + from("direct:manual") + .saga().completionMode(SagaCompletionMode.MANUAL) + .compensation("direct:compensation-fails") + .process(e -> captureCoordinator(e)); + + from("direct:compensation-fails") + .process(e -> { + compensationFailed.countDown(); + throw new IllegalStateException("compensation failure"); + }); + } + }; + } + + 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 34d9caaeee22..c111b88927bb 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 @@ -197,12 +197,15 @@ public class InMemorySagaCoordinator implements CamelSagaCoordinator { 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) { + if (current == null || current.kind() != running || 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)); + // the status is set to the final one before the outcome is completed (see doCompensate and doComplete), so a + // failed outcome with the status still running is a finalization aborted by the stop of the saga service + return current.outcome().handle((res, ex) -> ex) + .thenCompose(ex -> ex != null && currentStatus.get() == running + ? CompletableFuture.<Void> failedFuture(ex) + : statusAnswer(running, succeeded, action)); } private CompletableFuture<Void> statusAnswer(Status running, Status succeeded, String action) { @@ -214,7 +217,8 @@ public class InMemorySagaCoordinator implements CamelSagaCoordinator { } /** - * Completes the outcome of the finalization that ended the saga with the result of the compensation or completion. + * Completes the outcome of the finalization that ended the saga with the result of the compensation or completion, + * and returns the outcome, which {@link #abortFinalization(Throwable)} may complete first. */ private CompletableFuture<Boolean> finish(CompletableFuture<Boolean> result) { CompletableFuture<Boolean> outcome = finalization.outcome(); @@ -225,7 +229,20 @@ public class InMemorySagaCoordinator implements CamelSagaCoordinator { outcome.complete(res); } }); - return result; + return outcome; + } + + /** + * Fails the outcome of the compensation or completion that is still running when the saga service stops: its + * retries no longer run, so the callers that wait for it would otherwise never get an answer. A finalization that + * ends afterwards no longer changes the outcome. A finalization that already set its final status is not failed, as + * its outcome is about to be completed with its result. + */ + void abortFinalization(Throwable cause) { + Finalization current = finalization; + if (current != null && currentStatus.get() == current.kind()) { + current.outcome().completeExceptionally(cause); + } } /** @@ -329,13 +346,19 @@ public class InMemorySagaCoordinator implements CamelSagaCoordinator { } else { CompletableFuture<Boolean> future = new CompletableFuture<>(); sagaService.getExecutorService().schedule(() -> { - doFinalize(target, endpoint, enlistment, currentAttempt, description).whenComplete((res, ex) -> { - if (ex != null) { - future.completeExceptionally(ex); - } else { - future.complete(res); - } - }); + try { + doFinalize(target, endpoint, enlistment, currentAttempt, description).whenComplete((res, ex) -> { + if (ex != null) { + future.completeExceptionally(ex); + } else { + future.complete(res); + } + }); + } catch (Exception e) { + // such as the executor of the saga service rejecting the attempt: the scheduled task would + // swallow the exception, and the attempt would never end + future.completeExceptionally(e); + } }, sagaService.getRetryDelayInMilliseconds(), TimeUnit.MILLISECONDS); return future; } diff --git a/core/camel-support/src/main/java/org/apache/camel/saga/InMemorySagaService.java b/core/camel-support/src/main/java/org/apache/camel/saga/InMemorySagaService.java index 63cf81f158c9..f8d7ac1a0f92 100644 --- a/core/camel-support/src/main/java/org/apache/camel/saga/InMemorySagaService.java +++ b/core/camel-support/src/main/java/org/apache/camel/saga/InMemorySagaService.java @@ -19,6 +19,7 @@ package org.apache.camel.saga; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import org.apache.camel.CamelContext; @@ -43,7 +44,7 @@ public class InMemorySagaService extends ServiceSupport implements CamelSagaServ private CamelContext camelContext; - private final Map<String, CamelSagaCoordinator> coordinators = new ConcurrentHashMap<>(); + private final Map<String, InMemorySagaCoordinator> coordinators = new ConcurrentHashMap<>(); private ScheduledExecutorService executorService; @@ -58,7 +59,7 @@ public class InMemorySagaService extends ServiceSupport implements CamelSagaServ ObjectHelper.notNull(camelContext, "camelContext"); String uuid = camelContext.getUuidGenerator().generateUuid(); - CamelSagaCoordinator coordinator = new InMemorySagaCoordinator(camelContext, this, uuid); + InMemorySagaCoordinator coordinator = new InMemorySagaCoordinator(camelContext, this, uuid); coordinators.put(uuid, coordinator); return CompletableFuture.completedFuture(coordinator); @@ -105,6 +106,11 @@ public class InMemorySagaService extends ServiceSupport implements CamelSagaServ camelContext.getExecutorServiceManager().shutdownGraceful(this.executorService); this.executorService = null; } + // the compensations and completions still running will not end: fail them, so their callers do not wait + for (Map.Entry<String, InMemorySagaCoordinator> entry : coordinators.entrySet()) { + entry.getValue().abortFinalization(new RejectedExecutionException( + "The in-memory saga service stopped before the saga " + entry.getKey() + " was finalized")); + } } @Override 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 4d6f339655cd..b5951843110d 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 @@ -2026,6 +2026,10 @@ failed. The exchanges that compensate or complete a step carry the exchange prop 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. +When the in-memory saga service stops while a compensation or completion is still running (for example waiting for a +retry), the caller that started it and the callers that wait for its outcome now fail with a +`RejectedExecutionException`. Before, they waited for a retry that no longer runs. + === 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.
