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 64c3a5b62e08 CAMEL-27529: camel-mail - consumers sharing an idempotent
repository do not route a mail twice (#30832)
64c3a5b62e08 is described below
commit 64c3a5b62e08a44afe05f34c5f5954371126ec5c
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 13:32:37 2026 +0530
CAMEL-27529: camel-mail - consumers sharing an idempotent repository do not
route a mail twice (#30832)
Consumer B can search the unseen mails before consumer A marks a mail SEEN,
and
add its key after A removed it (idempotentRepositoryRemoveOnCommit=true, the
default): the add succeeds and B routed the mail again.
After the key of a mail was added, the consumer now asks the server whether
the
mail is SEEN (a SEARCH restricted to that mail, one round trip per mail
whose key
was added), and if so skips the mail and removes the key again. The flags
of the
mail object cannot be used: IMAPMessage fetches them once per object, and
with
closeFolder=false the next poll gets the objects of the earlier poll back,
with
the flags loaded then. The check applies with IMAP, the unseen search
(unseen=true, no custom searchTerm) and peek=true; setPeek is now applied
before
the key is generated, so a mailUidGenerator that reads the mail does not
flag it
SEEN. The component page says that other set-ups (POP3, a custom searchTerm,
unseen=false or peek=false) need idempotentRepositoryRemoveOnCommit=false.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../apache/camel/catalog/docs/mail-component.adoc | 12 ++
.../camel-mail/src/main/docs/mail-component.adoc | 12 ++
.../apache/camel/component/mail/MailConsumer.java | 49 ++++++-
...lSharedIdempotentRepositoryCachedFlagsTest.java | 145 +++++++++++++++++++++
.../mail/MailSharedIdempotentRepositoryTest.java | 121 +++++++++++++++++
5 files changed, 335 insertions(+), 4 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mail-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mail-component.adoc
index a7c423fbab02..2d070dc1ca3f 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mail-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mail-component.adoc
@@ -443,6 +443,18 @@ These parameters should help to prevent bad performance
when working with folder
In previous versions, these parameters have been evaluated too late, so that
big mailboxes could still cause performance problems.
With Camel 3.1, these parameters are evaluated earlier during the poll to
avoid these problems.
+=== Consuming one mailbox with several consumers
+
+Several consumers (in one or more applications) can consume the same mailbox
when they share an
+`idempotentRepository`: a consumer routes a mail only when it could add the
key of the mail to the repository. Once
+the mail is routed, it is marked as SEEN (or deleted), and by default its key
is removed from the repository
+(`idempotentRepositoryRemoveOnCommit=true`). Another consumer may have found
the mail in its search before that, and
+add the key after it was removed. With IMAP, the default `unseen=true` and no
custom `searchTerm`, and with `peek=true`,
+that consumer asks the server whether the mail is SEEN now (one request for
each mail whose key it added), and does not
+route it again. Otherwise (POP3, which has no SEEN flag, a
+custom `searchTerm`, `unseen=false` or `peek=false`), set
`idempotentRepositoryRemoveOnCommit=false` so the key of a
+consumed mail stays in the repository, and use a repository that keeps the
keys long enough.
+
== Examples
We start with a simple route that sends the messages received from a JMS
diff --git a/components/camel-mail/src/main/docs/mail-component.adoc
b/components/camel-mail/src/main/docs/mail-component.adoc
index a7c423fbab02..2d070dc1ca3f 100644
--- a/components/camel-mail/src/main/docs/mail-component.adoc
+++ b/components/camel-mail/src/main/docs/mail-component.adoc
@@ -443,6 +443,18 @@ These parameters should help to prevent bad performance
when working with folder
In previous versions, these parameters have been evaluated too late, so that
big mailboxes could still cause performance problems.
With Camel 3.1, these parameters are evaluated earlier during the poll to
avoid these problems.
+=== Consuming one mailbox with several consumers
+
+Several consumers (in one or more applications) can consume the same mailbox
when they share an
+`idempotentRepository`: a consumer routes a mail only when it could add the
key of the mail to the repository. Once
+the mail is routed, it is marked as SEEN (or deleted), and by default its key
is removed from the repository
+(`idempotentRepositoryRemoveOnCommit=true`). Another consumer may have found
the mail in its search before that, and
+add the key after it was removed. With IMAP, the default `unseen=true` and no
custom `searchTerm`, and with `peek=true`,
+that consumer asks the server whether the mail is SEEN now (one request for
each mail whose key it added), and does not
+route it again. Otherwise (POP3, which has no SEEN flag, a
+custom `searchTerm`, `unseen=false` or `peek=false`), set
`idempotentRepositoryRemoveOnCommit=false` so the key of a
+consumed mail stays in the repository, and use a repository that keeps the
keys long enough.
+
== Examples
We start with a simple route that sends the messages received from a JMS
diff --git
a/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailConsumer.java
b/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailConsumer.java
index 61c7ccb5b557..fe48fdc82ba7 100644
---
a/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailConsumer.java
+++
b/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailConsumer.java
@@ -36,6 +36,7 @@ import jakarta.mail.MessagingException;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Store;
import jakarta.mail.UIDFolder;
+import jakarta.mail.search.FlagTerm;
import jakarta.mail.search.SearchTerm;
import org.apache.camel.Exchange;
@@ -496,13 +497,25 @@ public class MailConsumer extends
ScheduledBatchPollingConsumer {
// the key of this mail once it has been added to the idempotent
repository
String addedKey = null;
try {
+ // need to call setPeek on java-mail to avoid the message
being flagged eagerly as SEEN on the server in
+ // case we process the message and rollback due an exception;
before the key is generated, so a
+ // mailUidGenerator that reads the mail does not flag it SEEN
either
+ if (getEndpoint().getConfiguration().isPeek()) {
+ peekMessage(message);
+ }
String key =
getEndpoint().getMailUidGenerator().generateUuid(getEndpoint(), message);
if (isValidMessage(key, message)) {
addedKey = key;
- // need to call setPeek on java-mail to avoid the message
being flagged eagerly as SEEN on the server in case
- // we process the message and rollback due an exception
- if (getEndpoint().getConfiguration().isPeek()) {
- peekMessage(message);
+ if (isSeenSinceSearched(message)) {
+ // another consumer sharing the idempotent repository
consumed the mail after this poll
+ // searched the unseen mails: it marked the mail SEEN,
then removed its key
+ // (idempotentRepositoryRemoveOnCommit), so the key
could be added again. The mail is not routed
+ // again, and the key is removed again
+ LOG.debug(
+ "Skipping message with key: {} as it was
flagged as SEEN after the unseen mails were searched",
+ key);
+ removeIdempotentKey(key);
+ continue;
}
Exchange exchange = createExchange(new
KeyValueHolder<>(key, message));
if (exchange != null) {
@@ -564,6 +577,34 @@ public class MailConsumer extends
ScheduledBatchPollingConsumer {
return answer;
}
+ /**
+ * Whether a mail that the unseen search of this poll found is flagged
SEEN once its key was added to the idempotent
+ * repository. Consumers sharing the repository can search the same mail;
the one that consumes it marks it SEEN,
+ * then removes its key (by default), so another one can add the key
afterwards and would route the mail again.
+ * <p/>
+ * Only for IMAP, when the consumer searches the unseen mails (unseen=true
and no custom searchTerm), and with
+ * peek=true, so the consumer itself did not flag the mail SEEN by reading
it. The server is asked, with a SEARCH
+ * restricted to this one mail (one round trip, only for a mail whose key
was just added): the flags of the mail
+ * object can be cached, as IMAPMessage.getFlags() fetches them only once
per mail object, and with
+ * closeFolder=false the folder stays open, so the search of this poll
returns the mail objects of earlier polls.
+ */
+ private boolean isSeenSinceSearched(Message mail) {
+ MailConfiguration config = getEndpoint().getConfiguration();
+ if (getEndpoint().getIdempotentRepository() == null ||
getEndpoint().getSearchTerm() != null || !config.isUnseen()
+ || !config.isPeek() ||
config.getProtocol().startsWith("pop3")) {
+ return false;
+ }
+ try {
+ Message[] seen = folder.search(new FlagTerm(new
Flags(Flags.Flag.SEEN), true), new Message[] { mail });
+ return seen != null && seen.length > 0;
+ } catch (MessagingException e) {
+ // the mail is handled as not SEEN: the DELETED check of
createExchange reads its flags, and handles a
+ // failure as for any mail (skipFailedMessage, handleFailedMessage)
+ LOG.trace("Cannot search whether the mail with the key just added
is SEEN. This exception is ignored here.", e);
+ return false;
+ }
+ }
+
/**
* @return Search term from endpoint (including "seen" check) or null if
there is no search term
*/
diff --git
a/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailSharedIdempotentRepositoryCachedFlagsTest.java
b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailSharedIdempotentRepositoryCachedFlagsTest.java
new file mode 100644
index 000000000000..d67716449924
--- /dev/null
+++
b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailSharedIdempotentRepositoryCachedFlagsTest.java
@@ -0,0 +1,145 @@
+/*
+ * 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.mail;
+
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
+import jakarta.mail.Folder;
+import jakarta.mail.Message;
+import jakarta.mail.Store;
+import jakarta.mail.internet.MimeMessage;
+
+import org.apache.camel.BindToRegistry;
+import org.apache.camel.Exchange;
+import org.apache.camel.component.mail.Mailbox.MailboxUser;
+import org.apache.camel.component.mail.Mailbox.Protocol;
+import org.apache.camel.support.KeyValueIdempotentRepository;
+import org.apache.camel.support.UnitOfWorkHelper;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Two consumers share an idempotent repository. Consumer B routed the mail
once and its exchange failed (the key is
+ * removed, the mail stays unseen), so B's mail object has loaded the flags of
the mail (not SEEN). In B's next poll,
+ * after B searched the unseen mails, consumer A consumes the mail: it marks
it SEEN and removes its key. B then adds
+ * the key, which succeeds. B must ask the server whether the mail is SEEN:
with closeFolder=false B's folder stays open
+ * and the search returns the mail object of the first poll, whose flags are
cached. A runs inside B's mailUidGenerator,
+ * between B's search and B's add, so the test needs no threads.
+ */
+class MailSharedIdempotentRepositoryCachedFlagsTest extends CamelTestSupport {
+ private static final MailboxUser kim =
Mailbox.getOrCreateUser("MailSharedIdempotentRepositoryCachedFlagsTest-kim",
+ "secret");
+
+ @BindToRegistry("repo")
+ private final KeyValueIdempotentRepository repo = new
KeyValueIdempotentRepository();
+
+ private final Queue<Exchange> queuedA = new ConcurrentLinkedQueue<>();
+ private final Queue<Exchange> queuedB = new ConcurrentLinkedQueue<>();
+ private final AtomicBoolean consumeByA = new AtomicBoolean();
+ private final AtomicReference<MailConsumer> consumerA = new
AtomicReference<>();
+
+ @BindToRegistry("gateB")
+ private final MailUidGenerator gateB = (endpoint, message) -> {
+ String key = new DefaultMailUidGenerator().generateUuid(endpoint,
message);
+ if (consumeByA.compareAndSet(true, false)) {
+ try {
+ assertEquals(1, consumerA.get().poll());
+ complete(queuedA.poll());
+ } catch (Exception e) {
+ throw new IllegalStateException(e);
+ }
+ assertEquals(0, kim.getInbox().getNewMessageCount(), "A marked the
mail SEEN");
+ assertFalse(repo.contains(key), "A removed the key of the mail");
+ }
+ return key;
+ };
+
+ @Override
+ public void setupResources() throws Exception {
+ Mailbox.clearAll(kim);
+ JavaMailSender sender = new DefaultJavaMailSender();
+ Store store = sender.getSession().getStore("imap");
+ store.connect("localhost", Mailbox.getPort(Protocol.imap),
kim.getLogin(), kim.getPassword());
+ Folder folder = store.getFolder("INBOX");
+ folder.open(Folder.READ_WRITE);
+ Message message = new MimeMessage(sender.getSession());
+ message.setSubject("Mail 0");
+ message.setText("Message 0");
+ folder.appendMessages(new Message[] { message });
+ folder.close(true);
+ store.close();
+ }
+
+ @Test
+ void folderKeptOpen() throws Exception {
+ mailConsumedByAnotherConsumerIsNotRoutedAgain("&closeFolder=false");
+ }
+
+ @Test
+ void folderClosedAfterEachPoll() throws Exception {
+ mailConsumedByAnotherConsumerIsNotRoutedAgain("");
+ }
+
+ private void mailConsumedByAnotherConsumerIsNotRoutedAgain(String options)
throws Exception {
+ consumerA.set(createConsumer("&idempotentRepository=#repo", queuedA));
+ MailConsumer consumerB =
createConsumer("&idempotentRepository=#repo&mailUidGenerator=#gateB" + options,
queuedB);
+ try {
+ // B routes the mail, and the exchange fails: the key is removed,
the mail stays unseen
+ assertEquals(1, consumerB.poll());
+ Exchange first = queuedB.poll();
+ assertNotNull(first);
+ first.setException(new IllegalStateException("Forced"));
+ complete(first);
+ assertEquals(1, kim.getInbox().getNewMessageCount());
+
+ // B polls again; A consumes the mail between B's search and B's
add
+ consumeByA.set(true);
+ assertEquals(0, consumerB.poll(), "B does not route the mail that
A consumed");
+ assertFalse(consumeByA.get(), "A consumed the mail during B's
poll");
+ assertTrue(queuedB.isEmpty());
+ } finally {
+ consumerB.stop();
+ consumerA.get().stop();
+ }
+ }
+
+ /**
+ * A consumer whose processor only queues the exchange, as the polling
consumer of pollEnrich and ConsumerTemplate
+ * does: the exchange completes later, on the test thread.
+ */
+ private MailConsumer createConsumer(String options, Queue<Exchange> queue)
throws Exception {
+ MailEndpoint endpoint =
context.getEndpoint(kim.uriPrefix(Protocol.imap) + options, MailEndpoint.class);
+ JavaMailSender sender =
endpoint.getConfiguration().createJavaMailSender(context);
+ endpoint.getConfiguration().configureJavaMailSender(context, sender);
+ MailConsumer consumer = new MailConsumer(endpoint, queue::add, sender);
+ consumer.setStartScheduler(false);
+ consumer.start();
+ return consumer;
+ }
+
+ private static void complete(Exchange exchange) {
+ UnitOfWorkHelper.doneSynchronizations(exchange,
exchange.getExchangeExtension().handoverCompletions());
+ }
+}
diff --git
a/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailSharedIdempotentRepositoryTest.java
b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailSharedIdempotentRepositoryTest.java
new file mode 100644
index 000000000000..f925b116fb94
--- /dev/null
+++
b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailSharedIdempotentRepositoryTest.java
@@ -0,0 +1,121 @@
+/*
+ * 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.mail;
+
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+import jakarta.mail.Folder;
+import jakarta.mail.Message;
+import jakarta.mail.Store;
+import jakarta.mail.internet.MimeMessage;
+
+import org.apache.camel.BindToRegistry;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mail.Mailbox.MailboxUser;
+import org.apache.camel.component.mail.Mailbox.Protocol;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.support.KeyValueIdempotentRepository;
+import org.apache.camel.test.junit6.CamelTestSupport;
+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.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Two consumers share an idempotent repository to consume one mailbox.
Consumer B searches the unseen mails, then
+ * consumer A consumes the mail, marks it SEEN and removes its key
(idempotentRepositoryRemoveOnCommit=true, the
+ * default); then B adds the key, which succeeds. B must not route the mail
again. The gate is B's mailUidGenerator,
+ * which runs between the search and the add.
+ */
+class MailSharedIdempotentRepositoryTest extends CamelTestSupport {
+ private static final MailboxUser lee =
Mailbox.getOrCreateUser("MailSharedIdempotentRepositoryTest-lee", "secret");
+
+ private final CountDownLatch bSearched = new CountDownLatch(1);
+ private final CountDownLatch bPolled = new CountDownLatch(1);
+ private final AtomicReference<String> keyOfB = new AtomicReference<>();
+
+ @BindToRegistry("repo")
+ private final KeyValueIdempotentRepository repo = new
KeyValueIdempotentRepository();
+
+ @BindToRegistry("gateB")
+ private final MailUidGenerator gateB = (endpoint, message) -> {
+ String key = new DefaultMailUidGenerator().generateUuid(endpoint,
message);
+ keyOfB.set(key);
+ bSearched.countDown();
+ // wait until A routed the mail, marked it SEEN and removed its key
+ await().atMost(20, TimeUnit.SECONDS)
+ .until(() -> !repo.contains(key) &&
lee.getInbox().getNewMessageCount() == 0
+ && getMockEndpoint("mock:result").getReceivedCounter()
== 1);
+ return key;
+ };
+
+ // called by B at the end of its poll, after its batch was routed
+ @BindToRegistry("afterPollB")
+ private final MailBoxPostProcessAction afterPollB = folder ->
bPolled.countDown();
+
+ @Override
+ public void setupResources() throws Exception {
+ Mailbox.clearAll(lee);
+ JavaMailSender sender = new DefaultJavaMailSender();
+ Store store = sender.getSession().getStore("imap");
+ store.connect("localhost", Mailbox.getPort(Protocol.imap),
lee.getLogin(), lee.getPassword());
+ Folder folder = store.getFolder("INBOX");
+ folder.open(Folder.READ_WRITE);
+ Message message = new MimeMessage(sender.getSession());
+ message.setText("Only mail");
+ folder.appendMessages(new Message[] { message });
+ folder.close(true);
+ store.close();
+ }
+
+ @Test
+ void mailConsumedByAnotherConsumerAfterTheSearchIsNotRoutedAgain() throws
Exception {
+ MockEndpoint mock = getMockEndpoint("mock:result");
+ mock.expectedMessageCount(1);
+
+ context.getRouteController().startRoute("B");
+ assertTrue(bSearched.await(20, TimeUnit.SECONDS));
+ // B searched the unseen mails and waits before it adds the key; A
consumes the mail now
+ context.getRouteController().startRoute("A");
+ assertTrue(bPolled.await(20, TimeUnit.SECONDS));
+
+ MockEndpoint.assertIsSatisfied(context);
+ List<Object> consumers = mock.getExchanges().stream().map(e ->
e.getIn().getHeader("consumer")).toList();
+ assertEquals(List.of("A"), consumers, "only A routes the mail");
+ assertFalse(repo.contains(keyOfB.get()), "B removed the key it added
again");
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ public void configure() {
+ String base = lee.uriPrefix(Protocol.imap) +
"&idempotentRepository=#repo&initialDelay=0&delay=60000";
+ from(base).routeId("A").autoStartup(false)
+ .setHeader("consumer", constant("A"))
+ .to("mock:result");
+ from(base +
"&mailUidGenerator=#gateB&postProcessAction=#afterPollB").routeId("B").autoStartup(false)
+ .setHeader("consumer", constant("B"))
+ .to("mock:result");
+ }
+ };
+ }
+}