This is an automated email from the ASF dual-hosted git repository. apupier pushed a commit to branch main in repository https://gitbox.apache.org/repos/asf/camel.git
commit afd887a1123418eaf3233146821a96e268d38654 Author: Aurélien Pupier <[email protected]> AuthorDate: Wed Nov 25 10:01:18 2026 +0100 CAMEL-26486: camel-cassandraql - CassandraKeyValueRepository writes with lightweight transactions only put() and delete(key) used plain INSERT/DELETE while putIfAbsent(), replace() and delete(key, expectedValue) use lightweight transactions. The timestamp of a plain write is generated by the client and the one of a lightweight transaction by the server, so a plain write could hide a replace() or delete(key, expected) that had returned true. This made CassandraKeyValueRepositoryIT flaky. - put() and delete(key) now use lightweight transactions (retried when another client wins a race), and return the value they actually replaced or removed - a row whose value expired (TTL) but that is still there is considered absent by contains(), keys(), size() and putIfAbsent() - add tests for put then replace/delete, delete then put, TTL expiry through put/replace, and concurrent puts on the same key - document the change in the 4.24 upgrade guide Co-authored-by: IBM Bob <[email protected]> --- .../cassandra/CassandraKeyValueRepository.java | 205 ++++++++++++--------- .../cassandra/CassandraKeyValueRepositoryIT.java | 118 ++++++++++++ .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 14 ++ 3 files changed, 251 insertions(+), 86 deletions(-) diff --git a/components/camel-cassandraql/src/main/java/org/apache/camel/processor/keyvalue/cassandra/CassandraKeyValueRepository.java b/components/camel-cassandraql/src/main/java/org/apache/camel/processor/keyvalue/cassandra/CassandraKeyValueRepository.java index 0e4089591ba7..0971f28c5b9a 100644 --- a/components/camel-cassandraql/src/main/java/org/apache/camel/processor/keyvalue/cassandra/CassandraKeyValueRepository.java +++ b/components/camel-cassandraql/src/main/java/org/apache/camel/processor/keyvalue/cassandra/CassandraKeyValueRepository.java @@ -48,6 +48,7 @@ import org.slf4j.LoggerFactory; import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.bindMarker; import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.insertInto; +import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.selectFrom; import static org.apache.camel.utils.cassandra.CassandraUtils.applyConsistencyLevel; import static org.apache.camel.utils.cassandra.CassandraUtils.generateDelete; import static org.apache.camel.utils.cassandra.CassandraUtils.generateSelect; @@ -60,13 +61,25 @@ import static org.apache.camel.utils.cassandra.CassandraUtils.generateTruncate; * stored as {@code TEXT}. Time-to-live is handled natively by Cassandra's {@code USING TTL} clause on {@code INSERT} * statements, so expired entries are removed automatically by Cassandra without any client-side eviction logic. * <p/> - * The CAS (compare-and-swap) methods are implemented atomically using Cassandra's lightweight transactions (LWT): + * All the write operations are implemented using Cassandra's lightweight transactions (LWT), so that they are ordered + * with each other: * <ul> * <li>{@link #putIfAbsent(String, Object, Duration)} uses {@code INSERT ... IF NOT EXISTS}</li> + * <li>{@link #put(String, Object, Duration)} uses {@code INSERT ... IF NOT EXISTS}, and when the key already exists + * {@code UPDATE ... SET value = ? WHERE key = ? IF value = ?} with the value that has just been read, retried until it + * succeeds</li> * <li>{@link #replace(String, Object, Object, Duration)} uses * {@code UPDATE ... SET value = ? WHERE key = ? IF value = ?}</li> * <li>{@link #delete(String, Object)} uses {@code DELETE FROM ... WHERE key = ? IF value = ?}</li> + * <li>{@link #delete(String)} uses {@code DELETE FROM ... WHERE key = ? IF value = ?} with the value that has just been + * read, retried until it succeeds</li> * </ul> + * Mixing lightweight transactions with plain writes on the same row is not safe: the timestamp of a plain write is + * generated by the client while the one of a lightweight transaction is generated by the server, so a plain write can + * hide a lightweight transaction that has been applied. This is why a plain {@code INSERT} or {@code DELETE} is not + * used. {@link #clear()} is not a lightweight transaction. + * <p/> + * An entry whose value expired (TTL) can leave its row behind without a value. Such a row is considered as absent. * <p/> * Advice: use LeveledCompaction for the backing table and tune read/write consistency levels for your use case. * @@ -84,6 +97,11 @@ public class CassandraKeyValueRepository extends ServiceSupport implements KeyVa private static final String KEY_COLUMN = "key"; private static final String VALUE_COLUMN = "value"; + private static final String WRITE_TIME_ALIAS = "value_write_time"; + /** + * Maximum number of attempts of a lightweight transaction loop, which only loops when another client wins a race + */ + private static final int MAX_ATTEMPTS = 50; @Metadata(description = "Cassandra session", required = true) private CassandraSessionHolder session; @@ -103,10 +121,7 @@ public class CassandraKeyValueRepository extends ServiceSupport implements KeyVa + " this pattern when storing instances of your own classes in the repository.") private String deserializationFilter; - private PreparedStatement insertStatement; - private PreparedStatement insertWithTtlStatement; private PreparedStatement selectStatement; - private PreparedStatement deleteStatement; private PreparedStatement selectAllKeysStatement; private PreparedStatement truncateStatement; private PreparedStatement insertIfNotExistsStatement; @@ -143,10 +158,7 @@ public class CassandraKeyValueRepository extends ServiceSupport implements KeyVa protected void doStart() throws Exception { ObjectHelper.notNull(session, "session", this); session.start(); - initInsertStatement(); - initInsertWithTtlStatement(); initSelectStatement(); - initDeleteStatement(); initSelectAllKeysStatement(); initClearStatement(); initInsertIfNotExistsStatement(); @@ -166,29 +178,6 @@ public class CassandraKeyValueRepository extends ServiceSupport implements KeyVa // ------------------------------------------------------------------------- // Prepared statement initialization - protected void initInsertStatement() { - SimpleStatement statement = applyConsistencyLevel( - insertInto(table) - .value(KEY_COLUMN, bindMarker()) - .value(VALUE_COLUMN, bindMarker()) - .build(), - writeConsistencyLevel); - LOGGER.debug("Generated Insert {}", statement); - insertStatement = getSession().prepare(statement); - } - - protected void initInsertWithTtlStatement() { - SimpleStatement statement = applyConsistencyLevel( - insertInto(table) - .value(KEY_COLUMN, bindMarker()) - .value(VALUE_COLUMN, bindMarker()) - .usingTtl(bindMarker()) - .build(), - writeConsistencyLevel); - LOGGER.debug("Generated Insert with TTL {}", statement); - insertWithTtlStatement = getSession().prepare(statement); - } - protected void initSelectStatement() { Select select = generateSelect(table, new String[] { VALUE_COLUMN }, new String[] { KEY_COLUMN }); SimpleStatement statement = applyConsistencyLevel(select.build(), readConsistencyLevel); @@ -196,15 +185,9 @@ public class CassandraKeyValueRepository extends ServiceSupport implements KeyVa selectStatement = getSession().prepare(statement); } - protected void initDeleteStatement() { - Delete delete = generateDelete(table, new String[] { KEY_COLUMN }, true); - SimpleStatement statement = applyConsistencyLevel(delete.build(), writeConsistencyLevel); - LOGGER.debug("Generated Delete {}", statement); - deleteStatement = getSession().prepare(statement); - } - protected void initSelectAllKeysStatement() { - Select select = generateSelect(table, new String[] { KEY_COLUMN }, null); + // the write time is null when the row has no value anymore (the value expired but not the row) + Select select = selectFrom(table).column(KEY_COLUMN).writeTime(VALUE_COLUMN).as(WRITE_TIME_ALIAS); SimpleStatement statement = applyConsistencyLevel(select.build(), readConsistencyLevel); LOGGER.debug("Generated Select all keys {}", statement); selectAllKeysStatement = getSession().prepare(statement); @@ -281,54 +264,62 @@ public class CassandraKeyValueRepository extends ServiceSupport implements KeyVa @ManagedOperation(description = "Get value by key") public Object get(String key) { LOGGER.debug("Getting key {}", key); - ResultSet rs = getSession().execute(selectStatement.bind(key)); - Row row = rs.one(); - if (row == null) { - return null; - } - ByteBuffer buffer = row.getByteBuffer(VALUE_COLUMN); - return buffer != null ? KeyValueRepositoryHelper.deserialize(buffer, deserializationFilter) : null; + return deserialize(readValue(key)); } /** * Stores a value with optional TTL. * <p/> - * <b>Note:</b> The previous value is read in a separate query before the upsert. This is not atomic — another - * client could modify the entry between the read and the write. The stored value is always correct, but the - * returned previous value may be stale. Cassandra does not provide a native {@code getAndSet} equivalent. + * The value is stored with lightweight transactions, so that it is ordered with the other write operations, and the + * returned previous value is the one that has actually been replaced. */ @Override @ManagedOperation(description = "Put a key-value pair with optional TTL") public Object put(String key, Object value, Duration ttl) { LOGGER.debug("Putting key {} with TTL {}", key, ttl); - // Read the previous value before upserting - Object oldValue = get(key); ByteBuffer serializedValue = KeyValueRepositoryHelper.serializeToByteBuffer(value); int ttlSeconds = toTtlSeconds(ttl); - if (ttlSeconds > 0) { - getSession().execute(insertWithTtlStatement.bind(key, serializedValue, ttlSeconds)); - } else { - getSession().execute(insertStatement.bind(key, serializedValue)); + for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++) { + Row existing = insertIfNotExists(key, serializedValue, ttlSeconds); + if (existing == null) { + return null; + } + ByteBuffer previous = existing.getByteBuffer(VALUE_COLUMN); + if (updateIfValue(key, serializedValue, previous, ttlSeconds)) { + return deserialize(previous); + } + // another client changed the entry in between, try again } - return oldValue; + throw new IllegalStateException("Unable to put the key " + key + " after " + MAX_ATTEMPTS + " attempts"); } + /** + * Removes an entry. + * <p/> + * The entry is removed with a lightweight transaction, so that it is ordered with the other write operations, and + * the returned previous value is the one that has actually been removed. + */ @Override @ManagedOperation(description = "Delete a key") public Object delete(String key) { LOGGER.debug("Deleting key {}", key); - // Read the previous value before deleting - Object oldValue = get(key); - getSession().execute(deleteStatement.bind(key)); - return oldValue; + ByteBuffer previous = readValue(key); + for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++) { + Row row = getSession().execute(deleteIfValueStatement.bind(key, previous)).one(); + if (row == null || row.getBoolean("[applied]")) { + return deserialize(previous); + } + // another client changed the entry in between, try again with the value it has now + previous = row.getByteBuffer(VALUE_COLUMN); + } + throw new IllegalStateException("Unable to delete the key " + key + " after " + MAX_ATTEMPTS + " attempts"); } @Override @ManagedOperation(description = "Check if key exists") public boolean contains(String key) { LOGGER.debug("Checking key {}", key); - ResultSet rs = getSession().execute(selectStatement.bind(key)); - return rs.one() != null; + return readValue(key) != null; } @Override @@ -337,7 +328,9 @@ public class CassandraKeyValueRepository extends ServiceSupport implements KeyVa ResultSet rs = getSession().execute(selectAllKeysStatement.bind()); Set<String> result = new LinkedHashSet<>(); for (Row row : rs) { - result.add(row.getString(KEY_COLUMN)); + if (!row.isNull(WRITE_TIME_ALIAS)) { + result.add(row.getString(KEY_COLUMN)); + } } return Collections.unmodifiableSet(result); } @@ -362,20 +355,23 @@ public class CassandraKeyValueRepository extends ServiceSupport implements KeyVa public Object putIfAbsent(String key, Object value, Duration ttl) { LOGGER.debug("Putting key {} if absent with TTL {}", key, ttl); ByteBuffer serializedValue = KeyValueRepositoryHelper.serializeToByteBuffer(value); - ResultSet rs; int ttlSeconds = toTtlSeconds(ttl); - if (ttlSeconds > 0) { - rs = getSession().execute(insertIfNotExistsWithTtlStatement.bind(key, serializedValue, ttlSeconds)); - } else { - rs = getSession().execute(insertIfNotExistsStatement.bind(key, serializedValue)); - } - Row row = rs.one(); - if (row == null || row.getBoolean("[applied]")) { - return null; + for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++) { + Row existing = insertIfNotExists(key, serializedValue, ttlSeconds); + if (existing == null) { + return null; + } + ByteBuffer existingValue = existing.getByteBuffer(VALUE_COLUMN); + if (existingValue != null) { + return deserialize(existingValue); + } + // the row exists without a value, which is the same as absent: set the value if it is still not set + if (updateIfValue(key, serializedValue, null, ttlSeconds)) { + return null; + } + // another client set the value in between, try again } - // Insert was not applied; return the existing value from the result row - ByteBuffer existingBuffer = row.getByteBuffer(VALUE_COLUMN); - return existingBuffer != null ? KeyValueRepositoryHelper.deserialize(existingBuffer, deserializationFilter) : null; + throw new IllegalStateException("Unable to put the key " + key + " after " + MAX_ATTEMPTS + " attempts"); } /** @@ -398,18 +394,7 @@ public class CassandraKeyValueRepository extends ServiceSupport implements KeyVa LOGGER.debug("Replacing key {} if value matches, TTL {}", key, ttl); ByteBuffer serializedNewValue = KeyValueRepositoryHelper.serializeToByteBuffer(newValue); ByteBuffer serializedExpectedValue = KeyValueRepositoryHelper.serializeToByteBuffer(expectedOldValue); - ResultSet rs; - int ttlSeconds = toTtlSeconds(ttl); - if (ttlSeconds > 0) { - // bind order: TTL, newValue (SET), key (WHERE), expectedValue (IF) - rs = getSession().execute( - updateIfValueWithTtlStatement.bind(ttlSeconds, serializedNewValue, key, serializedExpectedValue)); - } else { - // bind order: newValue (SET), key (WHERE), expectedValue (IF) - rs = getSession().execute( - updateIfValueStatement.bind(serializedNewValue, key, serializedExpectedValue)); - } - return isApplied(rs); + return updateIfValue(key, serializedNewValue, serializedExpectedValue, toTtlSeconds(ttl)); } /** @@ -442,6 +427,54 @@ public class CassandraKeyValueRepository extends ServiceSupport implements KeyVa return keys().size(); } + /** + * Reads the serialized value of the key. + * + * @return the serialized value, or {@code null} if the key is absent or has no value anymore + */ + private ByteBuffer readValue(String key) { + Row row = getSession().execute(selectStatement.bind(key)).one(); + return row != null ? row.getByteBuffer(VALUE_COLUMN) : null; + } + + private Object deserialize(ByteBuffer buffer) { + return buffer != null ? KeyValueRepositoryHelper.deserialize(buffer, deserializationFilter) : null; + } + + /** + * Inserts the entry if the key does not exist. + * + * @return {@code null} if the entry has been inserted, otherwise the existing row, whose value is {@code null} if + * the row has no value + */ + private Row insertIfNotExists(String key, ByteBuffer serializedValue, int ttlSeconds) { + ResultSet rs; + if (ttlSeconds > 0) { + rs = getSession().execute(insertIfNotExistsWithTtlStatement.bind(key, serializedValue, ttlSeconds)); + } else { + rs = getSession().execute(insertIfNotExistsStatement.bind(key, serializedValue)); + } + Row row = rs.one(); + return row == null || row.getBoolean("[applied]") ? null : row; + } + + /** + * Sets the value if the current one equals the expected one, where a {@code null} expected value matches a key + * without a value. + */ + private boolean updateIfValue(String key, ByteBuffer serializedNewValue, ByteBuffer expectedValue, int ttlSeconds) { + ResultSet rs; + if (ttlSeconds > 0) { + // bind order: TTL, newValue (SET), key (WHERE), expectedValue (IF) + rs = getSession().execute( + updateIfValueWithTtlStatement.bind(ttlSeconds, serializedNewValue, key, expectedValue)); + } else { + // bind order: newValue (SET), key (WHERE), expectedValue (IF) + rs = getSession().execute(updateIfValueStatement.bind(serializedNewValue, key, expectedValue)); + } + return isApplied(rs); + } + private static int toTtlSeconds(Duration ttl) { if (ttl == null || ttl.isZero() || ttl.isNegative()) { return 0; diff --git a/components/camel-cassandraql/src/test/java/org/apache/camel/processor/keyvalue/cassandra/CassandraKeyValueRepositoryIT.java b/components/camel-cassandraql/src/test/java/org/apache/camel/processor/keyvalue/cassandra/CassandraKeyValueRepositoryIT.java index 1498a7e611d8..0f5fb18fb9d7 100644 --- a/components/camel-cassandraql/src/test/java/org/apache/camel/processor/keyvalue/cassandra/CassandraKeyValueRepositoryIT.java +++ b/components/camel-cassandraql/src/test/java/org/apache/camel/processor/keyvalue/cassandra/CassandraKeyValueRepositoryIT.java @@ -19,8 +19,12 @@ package org.apache.camel.processor.keyvalue.cassandra; import java.time.Duration; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.Set; import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.apache.camel.builder.RouteBuilder; @@ -286,6 +290,120 @@ public class CassandraKeyValueRepositoryIT extends BaseCassandra { assertEquals("value1", repository.get(key("key1"))); } + @Test + public void testPutThenReplaceIsNotLost() { + // a plain write could hide the lightweight transaction of the replace, which is then applied but without effect + for (int i = 0; i < 100; i++) { + String key = key("replace" + i); + repository.put(key, "value1", null); + assertTrue(repository.replace(key, "value1", "value2", null), key); + assertEquals("value2", repository.get(key), key); + } + } + + @Test + public void testPutThenDeleteIsNotLost() { + for (int i = 0; i < 100; i++) { + String key = key("delete" + i); + repository.put(key, "value1", null); + assertTrue(repository.delete(key, "value1"), key); + assertNull(repository.get(key), key); + } + } + + @Test + public void testDeleteThenPut() { + for (int i = 0; i < 100; i++) { + String key = key("deleteput" + i); + repository.put(key, "value1", null); + assertEquals("value1", repository.delete(key), key); + assertNull(repository.put(key, "value2", null), key); + assertEquals("value2", repository.get(key), key); + } + } + + @Test + public void testPutWithTtlOverwritingExistingKeyExpiresTheEntry() { + repository.put(key("key1"), "value1", null); + assertEquals("value1", repository.put(key("key1"), "value2", Duration.ofSeconds(2))); + assertEquals("value2", repository.get(key("key1"))); + assertTrue(repository.contains(key("key1"))); + + // the whole entry must expire, not only its value + await().atMost(10, TimeUnit.SECONDS) + .untilAsserted(() -> assertFalse(repository.contains(key("key1")))); + assertNull(repository.get(key("key1"))); + } + + @Test + public void testReplaceWithTtlExpiresTheEntry() { + repository.put(key("key1"), "value1", null); + assertTrue(repository.replace(key("key1"), "value1", "value2", Duration.ofSeconds(2))); + + await().atMost(10, TimeUnit.SECONDS) + .untilAsserted(() -> assertFalse(repository.contains(key("key1")))); + } + + @Test + public void testKeysAndSizeIgnoreExpiredEntries() { + CassandraKeyValueRepository isolated = createIsolatedRepository(); + isolated.put(key("key1"), "value1", null); + isolated.put(key("key1"), "value2", Duration.ofSeconds(2)); + isolated.put(key("key2"), "value3", null); + + await().atMost(10, TimeUnit.SECONDS) + .untilAsserted(() -> assertEquals(Set.of(key("key2")), isolated.keys())); + assertEquals(1, isolated.size()); + } + + @Test + public void testPutIfAbsentAfterExpiration() { + repository.put(key("key1"), "value1", null); + repository.put(key("key1"), "value2", Duration.ofSeconds(2)); + await().atMost(10, TimeUnit.SECONDS) + .untilAsserted(() -> assertFalse(repository.contains(key("key1")))); + + assertNull(repository.putIfAbsent(key("key1"), "value3", null)); + assertEquals("value3", repository.get(key("key1"))); + } + + @Test + public void testConcurrentPutOnSameKeyReturnsEachPreviousValueOnce() throws Exception { + int threads = 8; + int puts = 20; + String key = key("contended"); + ExecutorService executor = Executors.newFixedThreadPool(threads); + try { + List<Future<List<Object>>> futures = new ArrayList<>(); + for (int t = 0; t < threads; t++) { + int id = t; + futures.add(executor.submit(() -> { + List<Object> previous = new ArrayList<>(); + for (int i = 0; i < puts; i++) { + previous.add(repository.put(key, "t" + id + "-" + i, null)); + } + return previous; + })); + } + + List<Object> previousValues = new ArrayList<>(); + for (Future<List<Object>> future : futures) { + previousValues.addAll(future.get(60, TimeUnit.SECONDS)); + } + + // every put replaces the value stored by another put, apart from the very first one: the values returned + // plus the final value are the values stored, each one exactly once + List<Object> all = new ArrayList<>(previousValues); + all.remove(null); + all.add(repository.get(key)); + assertEquals(threads * puts, all.size()); + assertEquals(threads * puts, Set.copyOf(all).size()); + assertEquals(1, previousValues.stream().filter(Objects::isNull).count()); + } finally { + executor.shutdownNow(); + } + } + @Override protected RouteBuilder createRouteBuilder() { return null; 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 749cd1f0142f..dfede46e80fa 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 @@ -931,6 +931,20 @@ A cql endpoint no longer closes a session given with `session` or `beanRef` when uses it is removed. It still closes a session it creates from its `hosts`, and creates a new one when it is started again. The application closes a session it gives to the endpoint, such as with a destroy method of its bean. +=== camel-cassandraql - the key value repository writes with lightweight transactions only + +`CassandraKeyValueRepository` (and its `Named` variant) now stores and removes entries with Cassandra lightweight +transactions only. Before, `put` and `delete(key)` used a plain `INSERT` and `DELETE` while `putIfAbsent`, `replace` and +`delete(key, expectedValue)` used lightweight transactions. The timestamp of a plain write is generated by the client and +the one of a lightweight transaction by the server, so a plain write could hide a `replace` or a `delete(key, +expectedValue)` that had returned `true`. Now `put` and `delete(key)` return the value they have actually replaced or +removed, also when another client writes the same key at the same time. As a lightweight transaction costs more than a +plain write, `put` and `delete(key)` are slower, and Cassandra's `SERIAL` consistency applies to them. + +Also, when the value of an entry expires (TTL) Cassandra can leave the row behind without a value, which happened for an +entry stored with a TTL that replaces an existing entry or that is stored by `replace`. Such a row is now considered +absent: `contains`, `keys` and `size` no longer report it, and `putIfAbsent` can store a value for it. + === camel-mongodb - the change streams consumer stores the post batch resume token While no change of its collection arrives, the change streams consumer now takes the post batch resume token of the
