davsclaus commented on code in PR #27510: URL: https://github.com/apache/camel/pull/27510#discussion_r4210387862
########## core/camel-core/src/test/java/org/apache/camel/processor/SagaCompensationFailureTest.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.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import org.apache.camel.ContextTestSupport; +import org.apache.camel.Exchange; +import org.apache.camel.RuntimeCamelException; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.log.ConsumingAppender; +import org.apache.camel.model.SagaCompletionMode; +import org.apache.camel.saga.CamelSagaCoordinator; +import org.apache.camel.saga.InMemorySagaService; +import org.apache.camel.spi.Registry; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.core.LoggerContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * CAMEL-25419: what the saga EIP reports when a compensation cannot be done, and what the in-memory saga service logs + * when it stops while a compensation is still being retried. + */ +public class SagaCompensationFailureTest extends ContextTestSupport { + + private static final String SAGA_SERVICE_LOGGER = InMemorySagaService.class.getName(); + + private final AtomicReference<CamelSagaCoordinator> coordinator = new AtomicReference<>(); + private final AtomicReference<String> timeoutSagaId = new AtomicReference<>(); + private final AtomicInteger flakyCompensationCalls = new AtomicInteger(); + private final List<String> sagaServiceWarnings = new CopyOnWriteArrayList<>(); + + @Test + public void testFailedCompensationKeepsTheOriginalException() { + Exchange result = template.send("direct:saga-fails", e -> e.getMessage().setBody("hello")); + + // the exception that caused the compensation stays on the exchange + Exception ex = result.getException(); + assertInstanceOf(IllegalArgumentException.class, ex); + assertEquals("business failure", ex.getMessage()); + + // and the compensation failure is attached to it + Throwable[] suppressed = ex.getSuppressed(); + assertEquals(1, suppressed.length, "the compensation failure should be attached as a suppressed exception"); + assertInstanceOf(RuntimeCamelException.class, suppressed[0]); + assertTrue(suppressed[0].getMessage().contains("Unable to compensate all required steps of the saga"), + suppressed[0].getMessage()); + } + + @Test + public void testFailedCompensationIsNotReportedAsCompensated() throws Exception { + Exchange result = template.send("direct:saga-fails", e -> e.getMessage().setBody("hello")); + assertNotNull(result.getException()); + + CamelSagaCoordinator saga = coordinator.get(); + assertNotNull(saga); + // the compensation could not be done: compensating the saga again must not report success + ExecutionException ex = assertThrows(ExecutionException.class, + () -> saga.compensate(result).get(5, TimeUnit.SECONDS), + "a saga whose compensation failed is reported as successfully compensated"); + assertInstanceOf(IllegalStateException.class, ex.getCause()); + assertTrue(ex.getCause().getMessage().contains("status is FAILED"), ex.getCause().getMessage()); + } + + @Test + public void testCompensationRetryPendingWhenContextStopsIsLogged() throws Exception { + // the saga times out, the first compensation attempt fails, and a retry is scheduled + template.sendBody("direct:saga-timeout", "hello"); + await().atMost(5, TimeUnit.SECONDS).until(() -> flakyCompensationCalls.get() == 1); + + // the in-memory service does not persist sagas: stopping while the retry is pending abandons the saga, + // which must be logged + context.stop(); Review Comment: Possible flakiness: the retry is scheduled 500 ms after the first failed attempt (line 135). If CI is slow enough that the retry fires between this `await` and `context.stop()`, the second attempt succeeds, the saga is removed, no warning is logged, and the `assertEquals(1, ...)` fails. A longer retry delay for the timeout scenario would make the window much safer, for example a second `InMemorySagaService` or a larger delay with `maxRetryAttempts` kept low for the first two tests. ########## core/camel-core-processor/src/main/java/org/apache/camel/processor/saga/SagaProcessor.java: ########## @@ -110,10 +111,19 @@ protected void handleSagaCompletion( if (this.completionMode == SagaCompletionMode.AUTO) { if (exchange.getException() != null) { if (coordinator != null) { - coordinator.compensate(exchange).whenComplete((done, ex) -> ifNotException(ex, exchange, callback, () -> { - setCurrentSagaCoordinator(exchange, previousCoordinator); - callback.done(false); - })); + final Exception cause = exchange.getException(); + coordinator.compensate(exchange).whenComplete((done, ex) -> { + if (ex != null) { + // keep the exception that caused the compensation, and attach the compensation failure to it + cause.addSuppressed( + ex instanceof CompletionException && ex.getCause() != null ? ex.getCause() : ex); Review Comment: Small thing to consider: `addSuppressed` mutates the user's exception instance. If a route throws a shared or cached exception instance, the suppressed list grows on every failed compensation. That's an edge case and probably acceptable, but worth a short note in the comment above. -- 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]
