diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/hazelcast-topic-component.adoc b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/hazelcast-topic-component.adoc index 6ec4f4ac860e0..9812e82595c35 100644 --- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/hazelcast-topic-component.adoc +++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/hazelcast-topic-component.adoc @@ -79,6 +79,11 @@ component is supposed to support multiple consumption as it's expected when it comes to topics, so you are free to have as many consumers as you need on the same hazelcast topic. +With `reliable=true`, the consumer listens on a Hazelcast reliable topic, which keeps its messages in a ringbuffer of +limited capacity (and time to live). A consumer that falls behind by more than that loses the messages that were +overwritten or expired: it logs a WARN with their number and goes on with the oldest message still in the +ringbuffer. + [tabs] ==== Java:: diff --git a/components/camel-hazelcast/src/main/docs/hazelcast-topic-component.adoc b/components/camel-hazelcast/src/main/docs/hazelcast-topic-component.adoc index 6ec4f4ac860e0..9812e82595c35 100644 --- a/components/camel-hazelcast/src/main/docs/hazelcast-topic-component.adoc +++ b/components/camel-hazelcast/src/main/docs/hazelcast-topic-component.adoc @@ -79,6 +79,11 @@ component is supposed to support multiple consumption as it's expected when it comes to topics, so you are free to have as many consumers as you need on the same hazelcast topic. +With `reliable=true`, the consumer listens on a Hazelcast reliable topic, which keeps its messages in a ringbuffer of +limited capacity (and time to live). A consumer that falls behind by more than that loses the messages that were +overwritten or expired: it logs a WARN with their number and goes on with the oldest message still in the +ringbuffer. + [tabs] ==== Java:: diff --git a/components/camel-hazelcast/src/main/java/org/apache/camel/component/hazelcast/listener/CamelReliableMessageListener.java b/components/camel-hazelcast/src/main/java/org/apache/camel/component/hazelcast/listener/CamelReliableMessageListener.java new file mode 100644 index 0000000000000..d50b19e27235c --- /dev/null +++ b/components/camel-hazelcast/src/main/java/org/apache/camel/component/hazelcast/listener/CamelReliableMessageListener.java @@ -0,0 +1,99 @@ +/* + * 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.component.hazelcast.listener; + +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.topic.ReliableMessageListener; +import org.apache.camel.component.hazelcast.HazelcastDefaultConsumer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The listener of a reliable topic consumer. A reliable topic keeps its messages in a ringbuffer: a listener that falls + * behind by more than its capacity (or its time to live) loses the messages that were overwritten (or expired). + * Hazelcast removes a listener that is not loss tolerant at that point, for good, which would leave the consumer + * started without receiving anything again. This listener reports the loss and goes on with the oldest message still in + * the ringbuffer. + */ +public class CamelReliableMessageListener extends CamelMessageListener implements ReliableMessageListener { + + private static final Logger LOG = LoggerFactory.getLogger(CamelReliableMessageListener.class); + + private final String cacheName; + private final HazelcastInstance hazelcastInstance; + // the sequence of the last message received, -1 before the first one + private long lastSequence = -1; + + public CamelReliableMessageListener(HazelcastDefaultConsumer consumer, String cacheName, + HazelcastInstance hazelcastInstance) { + super(consumer, cacheName); + this.cacheName = cacheName; + this.hazelcastInstance = hazelcastInstance; + } + + @Override + public long retrieveInitialSequence() { + // the messages published from now on, as with a plain message listener + return -1; + } + + @Override + public void storeSequence(long sequence) { + // called by one thread at a time, for each message in order + if (lastSequence >= 0 && sequence > lastSequence + 1) { + LOG.warn("The consumer of the reliable topic {} lost {} messages: they were overwritten or expired in the" + + " ringbuffer before they were received", + cacheName, sequence - lastSequence - 1); + } + lastSequence = sequence; + } + + @Override + public boolean isLossTolerant() { + return true; + } + + @Override + public boolean isTerminal(Throwable failure) { + // the route's failures are handled by the consumer's exception handler and do not reach Hazelcast + return false; + } + + @Override + public void onCancel() { + // Hazelcast cancels the listener when the consumer removes it as it stops, and when it gives up on it: an error + // reading the ringbuffer, such as a destroyed topic or a Hazelcast instance that is no longer active. Then the + // consumer receives nothing more, so report it, unless the consumer is stopping + if (!getConsumer().isStarted()) { + return; + } + // or unless it is an ordinary shutdown: Hazelcast's JVM shutdown hook runs at the same time as Camel's, so the + // instance can stop while the route is still started (the runner then fails with + // HazelcastInstanceNotActiveException) + if (!hazelcastInstance.getLifecycleService().isRunning() + || getConsumer().getEndpoint().getCamelContext().isStopping()) { + LOG.debug("The listener of the reliable topic {} was cancelled while Hazelcast or Camel is shutting down", + cacheName); + } else { + getConsumer().getExceptionHandler().handleException( + "The consumer of the reliable topic " + cacheName + " no longer receives messages", + new IllegalStateException( + "Hazelcast cancelled the listener of the reliable topic " + cacheName + + ". Restart the route to receive messages again.")); + } + } +} diff --git a/components/camel-hazelcast/src/main/java/org/apache/camel/component/hazelcast/topic/HazelcastTopicConsumer.java b/components/camel-hazelcast/src/main/java/org/apache/camel/component/hazelcast/topic/HazelcastTopicConsumer.java index b3354f46980fd..9696adeeb192c 100644 --- a/components/camel-hazelcast/src/main/java/org/apache/camel/component/hazelcast/topic/HazelcastTopicConsumer.java +++ b/components/camel-hazelcast/src/main/java/org/apache/camel/component/hazelcast/topic/HazelcastTopicConsumer.java @@ -24,9 +24,11 @@ import org.apache.camel.Processor; import org.apache.camel.component.hazelcast.HazelcastDefaultConsumer; import org.apache.camel.component.hazelcast.listener.CamelMessageListener; +import org.apache.camel.component.hazelcast.listener.CamelReliableMessageListener; public class HazelcastTopicConsumer extends HazelcastDefaultConsumer { + private final boolean reliable; private ITopic topic; private UUID listener; @@ -34,6 +36,7 @@ public class HazelcastTopicConsumer extends HazelcastDefaultConsumer { public HazelcastTopicConsumer(HazelcastInstance hazelcastInstance, Endpoint endpoint, Processor processor, String cacheName, boolean reliable) { super(hazelcastInstance, endpoint, processor, cacheName); + this.reliable = reliable; if (!reliable) { topic = hazelcastInstance.getTopic(cacheName); } else { @@ -45,7 +48,10 @@ public HazelcastTopicConsumer(HazelcastInstance hazelcastInstance, Endpoint endp protected void doStart() throws Exception { super.doStart(); - listener = topic.addMessageListener(new CamelMessageListener(this, cacheName)); + // a reliable topic removes a listener that lost messages, unless it is loss tolerant + listener = topic.addMessageListener(reliable + ? new CamelReliableMessageListener(this, cacheName, hazelcastInstance) + : new CamelMessageListener(this, cacheName)); } @Override diff --git a/components/camel-hazelcast/src/test/java/org/apache/camel/component/hazelcast/HazelcastReliableTopicConsumerLossTest.java b/components/camel-hazelcast/src/test/java/org/apache/camel/component/hazelcast/HazelcastReliableTopicConsumerLossTest.java new file mode 100644 index 0000000000000..de8fc0fcc267b --- /dev/null +++ b/components/camel-hazelcast/src/test/java/org/apache/camel/component/hazelcast/HazelcastReliableTopicConsumerLossTest.java @@ -0,0 +1,171 @@ +/* + * 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.component.hazelcast; + +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import com.hazelcast.config.Config; +import com.hazelcast.config.RingbufferConfig; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.topic.ITopic; +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.spi.ExceptionHandler; +import org.apache.camel.test.junit6.CamelTestSupport; +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.assertTrue; + +/** + * A reliable topic keeps its messages in a ringbuffer of limited capacity. A consumer that falls behind by more than + * that capacity loses the messages that were overwritten; it must go on with the messages published afterwards. + */ +class HazelcastReliableTopicConsumerLossTest extends CamelTestSupport { + + private static final int CAPACITY = 10; + + private final CountDownLatch slowMessageStarted = new CountDownLatch(1); + private final CountDownLatch releaseSlowMessage = new CountDownLatch(1); + private HazelcastInstance member; + // what the consumer reported to its exception handler + private final List reported = new CopyOnWriteArrayList<>(); + + @Override + protected CamelContext createCamelContext() throws Exception { + Config config = new Config(); + config.setClusterName("reliable-topic-loss-" + UUID.randomUUID()); + config.getMetricsConfig().setEnabled(false); + config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); + config.getNetworkConfig().getJoin().getAutoDetectionConfig().setEnabled(false); + config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false); + // the ringbuffer of the reliable topic (only one in this member) + config.addRingBufferConfig(new RingbufferConfig("default").setCapacity(CAPACITY)); + member = Hazelcast.newHazelcastInstance(config); + + CamelContext context = super.createCamelContext(); + context.getRegistry().bind("hazelcastInstance", member); + context.getRegistry().bind("exceptionHandler", new ExceptionHandler() { + @Override + public void handleException(Throwable exception) { + handleException(null, null, exception); + } + + @Override + public void handleException(String message, Throwable exception) { + handleException(message, null, exception); + } + + @Override + public void handleException(String message, Exchange exchange, Throwable exception) { + reported.add(message + ": " + exception.getMessage()); + } + }); + return context; + } + + @AfterEach + void shutdownMember() { + releaseSlowMessage.countDown(); + // stop the route before the member, so its listener does not read from a member that is shut down + context.stop(); + if (member != null) { + member.shutdown(); + } + } + + @Test + void consumerGoesOnAfterFallingBehindTheRingbuffer() throws Exception { + ITopic topic = member.getReliableTopic("news"); + MockEndpoint mock = getMockEndpoint("mock:news"); + + topic.publish("slow"); + assertTrue(slowMessageStarted.await(10, TimeUnit.SECONDS), "The first message was not consumed"); + + // while the route is busy with the first message, more messages than the ringbuffer holds are published + for (int i = 0; i < 3 * CAPACITY; i++) { + topic.publish("burst-" + i); + } + releaseSlowMessage.countDown(); + + // the overwritten messages are lost, but the consumer must receive the messages published afterwards + mock.expectedBodiesReceived("after"); + mock.setResultWaitTime(15000); + topic.publish("after"); + mock.assertIsSatisfied(); + } + + @Test + void listenerCancelledByHazelcastIsReported() throws Exception { + // Hazelcast cancels the listener when the topic is destroyed: the consumer receives nothing more + member.getReliableTopic("news").destroy(); + + await().atMost(10, TimeUnit.SECONDS).until(() -> !reported.isEmpty()); + assertEquals(1, reported.size(), "Reported: " + reported); + assertTrue(reported.get(0).contains("Hazelcast cancelled the listener of the reliable topic news"), + "Reported: " + reported); + } + + @Test + void listenerRemovedWhenTheConsumerStopsIsNotReported() throws Exception { + // removing the listener when the route stops cancels it too + context.getRouteController().stopRoute("news"); + + assertEquals(List.of(), reported); + } + + @Test + void listenerCancelledWhenTheMemberShutsDownIsNotReported() throws Exception { + // an ordinary shutdown where the member stops before the route (Hazelcast's shutdown hook runs at the same time + // as Camel's): the runner fails with HazelcastInstanceNotActiveException and Hazelcast cancels the listener + member.shutdown(); + + await().during(1, TimeUnit.SECONDS).atMost(5, TimeUnit.SECONDS) + .untilAsserted(() -> assertEquals(List.of(), reported)); + } + + @Override + protected RouteBuilder createRouteBuilder() { + return new RouteBuilder() { + @Override + public void configure() { + from("hazelcast-topic:news?reliable=true&hazelcastInstance=#hazelcastInstance" + + "&exceptionHandler=#exceptionHandler").routeId("news") + .choice() + // the body is the Hazelcast message + .when(simple("${body.messageObject} == 'slow'")) + .process(exchange -> { + slowMessageStarted.countDown(); + releaseSlowMessage.await(10, TimeUnit.SECONDS); + }) + .when(simple("${body.messageObject} == 'after'")) + .setBody(simple("${body.messageObject}")) + .to("mock:news") + .end(); + } + }; + } +} 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 46379cf15944b..80c1c71d4cca9 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 @@ -1008,6 +1008,16 @@ transaction timeout (2 minutes by default, `TransactionOptions`): when it takes `TransactionTimedOutException`, which is logged at ERROR, the transaction is rolled back and the message is consumed again, also when the route succeeded. +=== camel-hazelcast - the reliable topic consumer goes on after it lost messages + +A `hazelcast-topic` consumer with `reliable=true` that fell behind the ringbuffer of the reliable topic (messages +overwritten, or expired by its time to live, before the consumer read them) stopped receiving messages for good, +while the route stayed started: Hazelcast removed its listener. The consumer now skips the lost messages, logs a WARN +with their number, and goes on with the oldest message still in the ringbuffer. When Hazelcast cancels the listener +for another reason, such as a destroyed topic, the consumer reports it to its exception handler (logged at WARN by +default); restart the route to receive messages again. A listener cancelled because the Hazelcast instance or the +CamelContext is shutting down is only logged at DEBUG. + === camel-sql, camel-mybatis, camel-jooq - an exchange marked rollback only last is not consumed either The SQL, MyBatis and jOOQ consumers already left a message unconsumed when the route marked the exchange rollback