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 7a4113d42137 CAMEL-27430: camel-support - FileIdempotentRepository
must not lose the stored keys when the file store is rewritten (#30791)
7a4113d42137 is described below
commit 7a4113d42137b663b647e35016b048c53e653890
Author: Claus Ibsen <[email protected]>
AuthorDate: Wed Nov 25 15:04:25 2026 +0100
CAMEL-27430: camel-support - FileIdempotentRepository must not lose the
stored keys when the file store is rewritten (#30791)
A remove and dropping the oldest keys rewrote the file store in place: it
was
truncated first and then written key by key, so a JVM stop or an I/O error
during the rewrite lost the keys not written yet, and their messages were
processed again after a restart. The keys are now written to a temporary
file
(with the permissions of the store, next to the real file of a symlinked
store), synced, and moved over the store, as FileStateRepository does since
CAMEL-25213. When the temporary file cannot be created or cannot replace the
store (such as a single file mounted into a container), the store is
rewritten
in place as before, with a WARN.
A failure to drop the oldest keys no longer fails the add of a key that is
already stored, and a key is appended with its delimiter in one write.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Claus Ibsen <[email protected]>
---
.../idempotent/FileIdempotentRepository.java | 158 ++++++++++++---
.../FileIdempotentRepositoryRewriteTest.java | 214 +++++++++++++++++++++
2 files changed, 344 insertions(+), 28 deletions(-)
diff --git
a/core/camel-support/src/main/java/org/apache/camel/support/processor/idempotent/FileIdempotentRepository.java
b/core/camel-support/src/main/java/org/apache/camel/support/processor/idempotent/FileIdempotentRepository.java
index 36ad3d142f69..454203d1d481 100644
---
a/core/camel-support/src/main/java/org/apache/camel/support/processor/idempotent/FileIdempotentRepository.java
+++
b/core/camel-support/src/main/java/org/apache/camel/support/processor/idempotent/FileIdempotentRepository.java
@@ -16,12 +16,22 @@
*/
package org.apache.camel.support.processor.idempotent;
+import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.file.AtomicMoveNotSupportedException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.attribute.PosixFileAttributeView;
+import java.nio.file.attribute.PosixFilePermission;
+import java.nio.file.attribute.PosixFilePermissions;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@@ -83,6 +93,7 @@ public class FileIdempotentRepository extends ServiceSupport
implements Idempote
+ " space to allow room for new entries.",
defaultValue = "1000")
private long dropOldestFileStore = 1000;
+ private boolean rewriteInPlaceLogged;
public FileIdempotentRepository() {
}
@@ -213,7 +224,15 @@ public class FileIdempotentRepository extends
ServiceSupport implements Idempote
LOG.warn(
"Maximum capacity of file store: {} hit at {}
bytes. Dropping {} oldest entries from the file store",
fileStore, maxFileStoreSize, dropOldestFileStore);
- trunkStore();
+ try {
+ trunkStore();
+ } catch (RuntimeException e) {
+ // the key is stored, so the add succeeded (failing it
would take the retry of the message
+ // for a duplicate): the oldest entries are dropped on
the next add instead
+ LOG.warn(
+ "Cannot drop the oldest entries from the file
store: {} due to: {}. Trying again on the next add.",
+ fileStore, e.getMessage(), e);
+ }
}
return true;
@@ -440,10 +459,9 @@ public class FileIdempotentRepository extends
ServiceSupport implements Idempote
if (!fileStore.exists()) {
FileUtil.createNewFile(fileStore);
}
- // append to store
+ // append to store (as a single write, so the key is not split
from its delimiter)
fos = new FileOutputStream(fileStore, true);
- fos.write(key.getBytes());
- fos.write(STORE_DELIMITER.getBytes());
+ fos.write((key + STORE_DELIMITER).getBytes());
} catch (IOException e) {
throw RuntimeCamelException.wrapRuntimeCamelException(e);
} finally {
@@ -478,18 +496,7 @@ public class FileIdempotentRepository extends
ServiceSupport implements Idempote
if (found) {
// rewrite file
LOG.debug("Rewriting idempotent filestore: {} due to key: {}
removed", fileStore, key);
- FileOutputStream fos = null;
- try {
- fos = new FileOutputStream(fileStore);
- for (String line : lines) {
- fos.write(line.getBytes());
- fos.write(STORE_DELIMITER.getBytes());
- }
- } catch (IOException e) {
- throw RuntimeCamelException.wrapRuntimeCamelException(e);
- } finally {
- IOHelper.close(fos, "Rewriting file idempotent
repository", LOG);
- }
+ rewriteStore(lines);
}
} finally {
lock.unlock();
@@ -541,18 +548,7 @@ public class FileIdempotentRepository extends
ServiceSupport implements Idempote
if (!lines.isEmpty()) {
// rewrite file
LOG.debug("Rewriting idempotent filestore: {} with {}
entries:", fileStore, lines.size());
- FileOutputStream fos = null;
- try {
- fos = new FileOutputStream(fileStore);
- for (String line : lines) {
- fos.write(line.getBytes());
- fos.write(STORE_DELIMITER.getBytes());
- }
- } catch (IOException e) {
- throw RuntimeCamelException.wrapRuntimeCamelException(e);
- } finally {
- IOHelper.close(fos, "Rewriting file idempotent
repository", LOG);
- }
+ rewriteStore(lines);
} else {
// its a small file so recreate the file
LOG.debug("Clearing idempotent filestore: {}", fileStore);
@@ -563,6 +559,112 @@ public class FileIdempotentRepository extends
ServiceSupport implements Idempote
}
}
+ /**
+ * Rewrites the file store with the given keys. The keys are written to a
temporary file which then replaces the
+ * file store, so the file store is never left truncated or half written
(such as when writing fails, or the JVM
+ * stops while writing). When the temporary file cannot be created or
cannot replace the file store (such as a file
+ * store that is a single file mounted into a container), the file store
is rewritten in place instead.
+ */
+ private void rewriteStore(List<String> keys) {
+ Path target = fileStore.toPath();
+ Path tmp;
+ try {
+ if (Files.exists(target)) {
+ // replace the real file of a symlinked store (so the link is
kept, and the temporary file is on the
+ // same file system as the store)
+ target = target.toRealPath();
+ }
+ tmp = createTemporaryStore(target);
+ } catch (IOException e) {
+ rewriteStoreInPlace(target, keys, "a temporary file cannot be
created next to it", e);
+ return;
+ }
+
+ boolean written = false;
+ try {
+ writeStore(tmp, keys);
+ written = true;
+ } finally {
+ if (!written) {
+ // the file store is unchanged
+ FileUtil.deleteFile(tmp.toFile());
+ }
+ }
+
+ try {
+ try {
+ Files.move(tmp, target, StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.ATOMIC_MOVE);
+ } catch (AtomicMoveNotSupportedException e) {
+ Files.move(tmp, target, StandardCopyOption.REPLACE_EXISTING);
+ }
+ } catch (IOException e) {
+ // a failed move leaves the file store unchanged
+ FileUtil.deleteFile(tmp.toFile());
+ rewriteStoreInPlace(target, keys, "a temporary file cannot replace
it", e);
+ }
+ }
+
+ /**
+ * Creates the temporary file next to the file store, with the permissions
of the file store (before the keys are
+ * written to it, so the keys are never readable with wider permissions
than the file store)
+ */
+ private static Path createTemporaryStore(Path target) throws IOException {
+ Path tmp = target.resolveSibling(target.getFileName() + ".tmp");
+ Files.deleteIfExists(tmp);
+ boolean created = false;
+ try {
+ if (Files.exists(target) && Files.getFileAttributeView(target,
PosixFileAttributeView.class) != null) {
+ Set<PosixFilePermission> permissions =
Files.getPosixFilePermissions(target);
+ Files.createFile(tmp,
PosixFilePermissions.asFileAttribute(permissions));
+ created = true;
+ // the umask may have removed some of them
+ Files.setPosixFilePermissions(tmp, permissions);
+ } else {
+ Files.createFile(tmp);
+ created = true;
+ }
+ return tmp;
+ } catch (IOException e) {
+ if (created) {
+ FileUtil.deleteFile(tmp.toFile());
+ }
+ throw e;
+ }
+ }
+
+ private void rewriteStoreInPlace(Path target, List<String> keys, String
reason, IOException cause) {
+ if (!rewriteInPlaceLogged) {
+ rewriteInPlaceLogged = true;
+ LOG.warn("Rewriting idempotent filestore: {} in place, as {} due
to: {}. A JVM stop or an I/O error while"
+ + " rewriting can lose entries of the filestore.",
+ fileStore, reason, cause.getMessage(), cause);
+ } else {
+ LOG.debug("Rewriting idempotent filestore: {} in place, as {} due
to: {}", fileStore, reason,
+ cause.getMessage());
+ }
+ writeStore(target, keys);
+ }
+
+ private void writeStore(Path file, List<String> keys) {
+ try (FileOutputStream fos = new FileOutputStream(file.toFile());
+ OutputStream out = new BufferedOutputStream(fos)) {
+ writeKeys(out, keys);
+ out.flush();
+ fos.getFD().sync();
+ } catch (IOException e) {
+ throw RuntimeCamelException.wrapRuntimeCamelException(e);
+ }
+ }
+
+ /**
+ * Writes the keys, each followed by the delimiter, when the file store is
rewritten
+ */
+ void writeKeys(OutputStream out, List<String> keys) throws IOException {
+ for (String key : keys) {
+ out.write((key + STORE_DELIMITER).getBytes());
+ }
+ }
+
/**
* Cleanup the 1st-level cache.
*/
diff --git
a/core/camel-support/src/test/java/org/apache/camel/support/processor/idempotent/FileIdempotentRepositoryRewriteTest.java
b/core/camel-support/src/test/java/org/apache/camel/support/processor/idempotent/FileIdempotentRepositoryRewriteTest.java
new file mode 100644
index 000000000000..9f8a9e1e7c0e
--- /dev/null
+++
b/core/camel-support/src/test/java/org/apache/camel/support/processor/idempotent/FileIdempotentRepositoryRewriteTest.java
@@ -0,0 +1,214 @@
+/*
+ * 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.support.processor.idempotent;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.attribute.PosixFilePermission;
+import java.nio.file.attribute.PosixFilePermissions;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.DisabledOnOs;
+import org.junit.jupiter.api.condition.OS;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
+
+/**
+ * The file store is rewritten when a key is removed and when the oldest keys
are dropped: a rewrite that fails must
+ * leave the file store unchanged, instead of truncated or half written
(CAMEL-27430).
+ */
+class FileIdempotentRepositoryRewriteTest {
+
+ @TempDir
+ Path dir;
+
+ private FileIdempotentRepository repository;
+
+ @AfterEach
+ void stop() {
+ if (repository != null) {
+ repository.stop();
+ }
+ }
+
+ @Test
+ void removeKeepsTheStoreWhenTheRewriteFails() throws Exception {
+ Path store = dir.resolve("store.dat");
+ AtomicBoolean diskFull = new AtomicBoolean();
+ repository = new FailingRewriteRepository(store, diskFull);
+ repository.start();
+ repository.add("A");
+ repository.add("B");
+ repository.add("C");
+
+ diskFull.set(true);
+ assertThatThrownBy(() ->
repository.remove("B")).hasMessageContaining("No space left on device");
+
+ assertThat(Files.readString(store)).isEqualTo("A\nB\nC\n");
+ assertThat(dir.resolve("store.dat.tmp")).doesNotExist();
+ assertThat(repository.contains("B")).as("the key that could not be
removed is still stored").isTrue();
+
+ diskFull.set(false);
+ repository.remove("B");
+ assertThat(Files.readString(store)).isEqualTo("A\nC\n");
+ }
+
+ @Test
+ void addSucceedsAndKeepsTheStoreWhenDroppingTheOldestKeysFails() throws
Exception {
+ Path store = dir.resolve("store.dat");
+ AtomicBoolean diskFull = new AtomicBoolean();
+ repository = new FailingRewriteRepository(store, diskFull);
+ repository.setMaxFileStoreSize(6);
+ repository.setDropOldestFileStore(1);
+ repository.start();
+ repository.add("A");
+ repository.add("B");
+ repository.add("C");
+ assertThat(Files.readString(store)).isEqualTo("A\nB\nC\n");
+
+ // the key is stored, so the add succeeds although the oldest keys
cannot be dropped
+ diskFull.set(true);
+ assertThat(repository.add("D")).isTrue();
+ assertThat(Files.readString(store)).isEqualTo("A\nB\nC\nD\n");
+ assertThat(repository.add("D")).as("a duplicate").isFalse();
+
+ // the next add drops the oldest key
+ diskFull.set(false);
+ assertThat(repository.add("E")).isTrue();
+ assertThat(Files.readString(store)).isEqualTo("B\nC\nD\nE\n");
+ }
+
+ @Test
+ void removeRewritesTheStoreInPlaceWhenNoTemporaryFileCanBeCreated() throws
Exception {
+ Path store = dir.resolve("store.dat");
+ repository = new FileIdempotentRepository(store.toFile(), new
HashMap<>());
+ repository.start();
+ repository.add("A");
+ repository.add("B");
+ repository.add("C");
+
+ // the temporary file cannot be created (here: a directory that is not
empty took its place)
+ Path tmp = Files.createDirectory(dir.resolve("store.dat.tmp"));
+ Files.writeString(tmp.resolve("other"), "other");
+
+ assertThat(repository.remove("B")).isTrue();
+ assertThat(Files.readString(store)).isEqualTo("A\nC\n");
+ assertThat(tmp.resolve("other")).exists();
+ }
+
+ @Test
+ void removeReplacesTheStore() throws Exception {
+ Path store = dir.resolve("store.dat");
+ repository = new FileIdempotentRepository(store.toFile(), new
HashMap<>());
+ repository.start();
+ repository.add("A");
+ repository.add("B");
+ repository.add("C");
+
+ assertThat(repository.remove("B")).isTrue();
+
+ assertThat(Files.readString(store)).isEqualTo("A\nC\n");
+ assertThat(dir.resolve("store.dat.tmp")).doesNotExist();
+ }
+
+ @Test
+ @DisabledOnOs(OS.WINDOWS)
+ void removeKeepsTheSymlinkedStore() throws Exception {
+ // a store which is a symbolic link to a file in another directory
+ Path realStore =
Files.createDirectory(dir.resolve("real")).resolve("store.dat");
+ Files.writeString(realStore, "A\nB\nC\n");
+ Path link = dir.resolve("store.dat");
+ try {
+ Files.createSymbolicLink(link, realStore);
+ } catch (UnsupportedOperationException | IOException e) {
+ assumeTrue(false, "Symbolic links are not supported: " +
e.getMessage());
+ }
+ repository = new FileIdempotentRepository(link.toFile(), new
HashMap<>());
+ repository.start();
+
+ assertThat(repository.remove("B")).isTrue();
+
+ assertThat(Files.isSymbolicLink(link)).isTrue();
+ assertThat(Files.readSymbolicLink(link)).isEqualTo(realStore);
+ assertThat(Files.readString(realStore)).isEqualTo("A\nC\n");
+ assertThat(Path.of(realStore + ".tmp")).doesNotExist();
+ assertThat(Files.exists(Path.of(link + ".tmp"),
LinkOption.NOFOLLOW_LINKS)).isFalse();
+ }
+
+ @Test
+ void removeKeepsThePermissionsOfTheStore() throws Exception {
+
assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix"),
+ "POSIX file permissions are not supported");
+
+ // a store that only its owner can read
+ Path store = dir.resolve("store.dat");
+ Files.writeString(store, "A\nB\nC\n");
+ Set<PosixFilePermission> permissions =
PosixFilePermissions.fromString("rw-------");
+ Files.setPosixFilePermissions(store, permissions);
+ AtomicBoolean checked = new AtomicBoolean();
+ repository = new FileIdempotentRepository(store.toFile(), new
HashMap<>()) {
+ @Override
+ void writeKeys(OutputStream out, List<String> keys) throws
IOException {
+ // the temporary file has the permissions of the store before
the keys are written to it
+ assertThat(Files.getPosixFilePermissions(Path.of(store +
".tmp"))).isEqualTo(permissions);
+ checked.set(true);
+ super.writeKeys(out, keys);
+ }
+ };
+ repository.start();
+
+ assertThat(repository.remove("B")).isTrue();
+
+ assertThat(checked).isTrue();
+
assertThat(Files.getPosixFilePermissions(store)).isEqualTo(permissions);
+ assertThat(Files.readString(store)).isEqualTo("A\nC\n");
+ }
+
+ /**
+ * A repository whose rewrite of the file store fails after the first key,
as when the disk is full
+ */
+ private static final class FailingRewriteRepository extends
FileIdempotentRepository {
+ private final AtomicBoolean diskFull;
+
+ FailingRewriteRepository(Path store, AtomicBoolean diskFull) {
+ super(store.toFile(), new HashMap<>());
+ this.diskFull = diskFull;
+ }
+
+ @Override
+ void writeKeys(OutputStream out, List<String> keys) throws IOException
{
+ if (diskFull.get()) {
+ out.write((keys.get(0) + "\n").getBytes());
+ out.flush();
+ throw new IOException("No space left on device");
+ }
+ super.writeKeys(out, keys);
+ }
+ }
+}