This is an automated email from the ASF dual-hosted git repository.
pvillard31 pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/nifi.git
The following commit(s) were added to refs/heads/main by this push:
new 39ed1fb5ba8 NIFI-16582 Support Redis Enterprise and Cloud atomic map
cache operations (#11919)
39ed1fb5ba8 is described below
commit 39ed1fb5ba861d852d7fa4e238d3d52c06541dff
Author: Albert T. Wong <[email protected]>
AuthorDate: Mon Nov 23 01:39:48 2026 -0800
NIFI-16582 Support Redis Enterprise and Cloud atomic map cache operations
(#11919)
* NIFI-16582 Support Redis Enterprise and Cloud atomic map cache operations
Replace transaction-based conditional operations with single-key Lua
scripts, support Cluster connections, and document managed database endpoint
configuration. Add authenticated standalone and Cluster API regression coverage.
---
.../RedisDistributedMapCacheClientService.java | 137 +++++++---------
.../additionalDetails.md | 72 ++++++++
...disClusterDistributedMapCacheClientService.java | 31 ++++
.../ITRedisDistributedMapCacheClientService.java | 182 +++++++++++++++++++--
.../TestRedisDistributedMapCacheClientService.java | 47 ++++++
.../org/apache/nifi/redis/util/RedisUtils.java | 7 +-
6 files changed, 388 insertions(+), 88 deletions(-)
diff --git
a/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-extensions/src/main/java/org/apache/nifi/redis/service/RedisDistributedMapCacheClientService.java
b/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-extensions/src/main/java/org/apache/nifi/redis/service/RedisDistributedMapCacheClientService.java
index ca59728574d..8260e8e3739 100644
---
a/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-extensions/src/main/java/org/apache/nifi/redis/service/RedisDistributedMapCacheClientService.java
+++
b/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-extensions/src/main/java/org/apache/nifi/redis/service/RedisDistributedMapCacheClientService.java
@@ -18,49 +18,73 @@ package org.apache.nifi.redis.service;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.Tags;
-import org.apache.nifi.components.ValidationContext;
-import org.apache.nifi.components.ValidationResult;
import org.apache.nifi.distributed.cache.client.AtomicCacheEntry;
import
org.apache.nifi.distributed.cache.client.AtomicDistributedMapCacheClient;
import org.apache.nifi.distributed.cache.client.Deserializer;
import org.apache.nifi.distributed.cache.client.Serializer;
-import org.apache.nifi.redis.RedisConnectionPool;
-import org.apache.nifi.redis.RedisType;
+import org.apache.nifi.util.Tuple;
+import org.springframework.data.redis.connection.ReturnType;
+import org.springframework.data.redis.connection.SetCondition;
+import org.springframework.data.redis.core.types.Expiration;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-
-import static org.apache.nifi.redis.util.RedisUtils.REDIS_CONNECTION_POOL;
+import java.nio.charset.StandardCharsets;
@Tags({ "redis", "distributed", "cache", "map" })
-@CapabilityDescription("An implementation of DistributedMapCacheClient that
uses Redis as the backing cache. This service relies on " +
- "the WATCH, MULTI, and EXEC commands in Redis, which are not fully
supported when Redis is clustered. As a result, this service " +
- "can only be used with a Redis Connection Pool that is configured for
standalone or sentinel mode. Sentinel mode can be used to " +
- "provide high-availability configurations.")
+@CapabilityDescription("An implementation of AtomicDistributedMapCacheClient
that uses Redis as the backing cache, including " +
+ "Redis Enterprise Software and Redis Cloud. Atomic operations use
single-key Lua scripts and require permission to execute EVAL. " +
+ "Use standalone mode for a Redis Enterprise or Redis Cloud database
endpoint, or cluster mode for an endpoint with the Redis Cluster API enabled. "
+
+ "Atomicity applies to the Redis endpoint and does not provide
coordination across Active-Active regions.")
public class RedisDistributedMapCacheClientService extends
SimpleRedisDistributedMapCacheClientService implements
AtomicDistributedMapCacheClient<byte[]> {
- @Override
- protected Collection<ValidationResult> customValidate(ValidationContext
validationContext) {
- final List<ValidationResult> results = new ArrayList<>();
+ private static final byte[] GET_AND_PUT_IF_ABSENT_SCRIPT = """
+ local current = redis.call('GET', KEYS[1])
+ if current then
+ return current
+ end
+ if tonumber(ARGV[2]) > 0 then
+ redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[2])
+ else
+ redis.call('SET', KEYS[1], ARGV[1])
+ end
+ return false
+ """.getBytes(StandardCharsets.UTF_8);
+
+ private static final byte[] REPLACE_SCRIPT = """
+ local current = redis.call('GET', KEYS[1])
+ if ARGV[1] == '0' then
+ if current then
+ return 0
+ end
+ elseif current ~= ARGV[2] then
+ return 0
+ end
+ if tonumber(ARGV[4]) > 0 then
+ redis.call('SET', KEYS[1], ARGV[3], 'EX', ARGV[4])
+ else
+ redis.call('SET', KEYS[1], ARGV[3])
+ end
+ return 1
+ """.getBytes(StandardCharsets.UTF_8);
- final RedisConnectionPool redisConnectionPool =
validationContext.getProperty(REDIS_CONNECTION_POOL).asControllerService(RedisConnectionPool.class);
- if (redisConnectionPool != null) {
- final RedisType redisType = redisConnectionPool.getRedisType();
- if (redisType != null && redisType == RedisType.CLUSTER) {
- results.add(new ValidationResult.Builder()
- .subject(REDIS_CONNECTION_POOL.getDisplayName())
- .valid(false)
- .explanation(REDIS_CONNECTION_POOL.getDisplayName()
- + " is configured in clustered mode, and this
service requires a non-clustered Redis")
- .build());
- }
- }
+ @Override
+ public <K, V> boolean putIfAbsent(final K key, final V value, final
Serializer<K> keySerializer, final Serializer<V> valueSerializer) throws
IOException {
+ return withConnection(redisConnection -> {
+ final Tuple<byte[], byte[]> kv = serialize(key, value,
keySerializer, valueSerializer);
+ return
Boolean.TRUE.equals(redisConnection.stringCommands().set(kv.getKey(),
kv.getValue(),
+ SetCondition.ifAbsent(), Expiration.seconds(getTtl())));
+ });
+ }
- return results;
+ @Override
+ public <K, V> V getAndPutIfAbsent(final K key, final V value, final
Serializer<K> keySerializer,
+ final Serializer<V> valueSerializer,
final Deserializer<V> valueDeserializer) throws IOException {
+ return withConnection(redisConnection -> {
+ final Tuple<byte[], byte[]> kv = serialize(key, value,
keySerializer, valueSerializer);
+ final byte[] previous =
redisConnection.scriptingCommands().eval(GET_AND_PUT_IF_ABSENT_SCRIPT,
ReturnType.VALUE, 1,
+ kv.getKey(), kv.getValue(),
getTtl().toString().getBytes(StandardCharsets.UTF_8));
+ return previous == null ? null :
valueDeserializer.deserialize(previous);
+ });
}
@Override
@@ -81,50 +105,13 @@ public class RedisDistributedMapCacheClientService extends
SimpleRedisDistribute
@Override
public <K, V> boolean replace(final AtomicCacheEntry<K, V, byte[]> entry,
final Serializer<K> keySerializer, final Serializer<V> valueSerializer) throws
IOException {
return withConnection(redisConnection -> {
- final ByteArrayOutputStream out = new ByteArrayOutputStream();
-
- keySerializer.serialize(entry.getKey(), out);
- final byte[] k = out.toByteArray();
- out.reset();
-
- valueSerializer.serialize(entry.getValue(), out);
- final byte[] newVal = out.toByteArray();
-
- // the revision of the cache entry holds the value of the key from
a previous fetch
- final byte[] prevVal = entry.getRevision().orElse(null);
-
- boolean replaced = false;
-
- // start a watch on the key and retrieve the current value
- redisConnection.watch(k);
- final byte[] currValue = redisConnection.stringCommands().get(k);
-
- // start a transaction
- redisConnection.multi();
-
- // compare-and-set
- if (Arrays.equals(prevVal, currValue)) {
- // if we use set(k, newVal) then the results list will always
have size == 0 b/c when convertPipelineAndTxResults is set to true,
- // status responses like "OK" are skipped over, so by using
getSet we can rely on the results list to know if the transaction succeeded
- redisConnection.stringCommands().getSet(k, newVal);
-
- // set the TTL if specified
- final long ttl = getTtl();
- if (ttl != -1L) {
- redisConnection.keyCommands().expire(k, ttl);
- }
- }
-
- // execute the transaction
- final List<Object> results = redisConnection.exec();
-
- // if we have a result then the replace succeeded
- if (results != null && !results.isEmpty()) {
- replaced = true;
- }
-
- return replaced;
+ final Tuple<byte[], byte[]> kv = serialize(entry.getKey(),
entry.getValue(), keySerializer, valueSerializer);
+ // Keep the existing raw-value revision format, including the
distinction between an absent key and an empty value.
+ final byte[] previous = entry.getRevision().orElse(null);
+ final Long result =
redisConnection.scriptingCommands().eval(REPLACE_SCRIPT, ReturnType.INTEGER, 1,
+ kv.getKey(), (previous == null ? "0" :
"1").getBytes(StandardCharsets.UTF_8),
+ previous == null ? new byte[0] : previous, kv.getValue(),
getTtl().toString().getBytes(StandardCharsets.UTF_8));
+ return Long.valueOf(1).equals(result);
});
}
-
}
diff --git
a/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-extensions/src/main/resources/docs/org.apache.nifi.redis.service.RedisDistributedMapCacheClientService/additionalDetails.md
b/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-extensions/src/main/resources/docs/org.apache.nifi.redis.service.RedisDistributedMapCacheClientService/additionalDetails.md
new file mode 100644
index 00000000000..98da5128962
--- /dev/null
+++
b/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-extensions/src/main/resources/docs/org.apache.nifi.redis.service.RedisDistributedMapCacheClientService/additionalDetails.md
@@ -0,0 +1,72 @@
+<!--
+ 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.
+-->
+
+# RedisDistributedMapCacheClientService
+
+## Redis Enterprise Software and Redis Cloud
+
+Configure a `RedisConnectionPoolService` and select it as the **Redis
Connection Pool** for this service.
+
+| Connection pool property | Value |
+|---|---|
+| **Redis Mode** | `Standalone` for a database endpoint that routes commands
through the Redis proxy, including sharded databases. Select `Cluster` only if
the endpoint exposes the Redis Cluster API and its advertised nodes are
reachable from NiFi. |
+| **Connection String** | The database endpoint as `hostname:port`. Use the
database endpoint, not a management console or REST API endpoint. Do not
include a `redis://` or `rediss://` scheme. |
+| **Database Index** | `0`. Redis Enterprise Software and Redis Cloud identify
databases by endpoint. |
+| **Username** | The database ACL user, or `default` when using the default
user. |
+| **Password** | The database user's password, supplied through a sensitive
parameter. |
+| **SSL Context Service** | Configure this when the database endpoint requires
TLS. Trust the database CA, and supply a client certificate and private key
when mutual TLS is required. |
+
+`Standalone` describes the client connection topology. It does not require an
unsharded Redis server and does not
+disable the availability or sharding provided by the Redis database endpoint.
In `Standalone` mode, NiFi connects to
+the database proxy, and the proxy routes each command to the shard that owns
the key, across nodes when the database
+spans several. See [proxy
policies](https://redis.io/docs/latest/operate/rs/databases/configure/proxy-policy/)
and
+[Redis Cloud
clustering](https://redis.io/docs/latest/operate/rc/databases/configuration/clustering/).
+
+`Cluster` mode uses the [OSS Cluster
API](https://redis.io/docs/latest/operate/rs/clusters/optimize/oss-cluster-api/):
+the client discovers the hash slot topology, connects to the node that owns
each key, and follows redirects. It can
+reduce forwarding inside the database, but it is optional and is not required
to use a sharded or multi-node database.
+
+## Atomic Operations and Permissions
+
+Conditional insert and replace operations act on one key at a time. The
get-and-insert and compare-and-set operations
+use `EVAL` with a single explicitly declared key, keeping the read,
conditional write, and TTL update together on the
+server. `WATCH`, `MULTI`, and `EXEC` are not required. Scripts and values are
binary safe. Existing keys, values, and
+raw-value revisions retain their format.
+
+The Redis user needs permission for `EVAL` and the commands executed by these
scripts (`GET` and `SET`), as well as
+commands used by the cache operations the flow calls (including `EXISTS`,
`DEL`, `MSET`, and `EXPIRE`). Configure key
+permissions for the serialized cache keys. A server configured to prohibit
scripting cannot use this atomic cache
+service.
+
+TTL is applied when an entry is inserted or successfully replaced. A failed
comparison or an insert against an
+existing key leaves the value and its expiration unchanged. A TTL of `0 secs`
creates entries without expiration.
+
+## Upgrading from Earlier Versions
+
+Earlier versions implemented `getAndPutIfAbsent` and `replace` with `WATCH`,
`MULTI`, and `EXEC`. Those operations
+now run as Lua scripts. Before upgrading, grant the Redis user permission for
`EVAL`, `GET`, and `SET` on the
+serialized cache keys. A user that is allowed `WATCH`, `MULTI`, and `EXEC` but
not `EVAL` fails these operations with
+a `NOPERM` error, and the cache entry is left unchanged.
+
+## Deployment Considerations
+
+Single-key atomicity applies at the endpoint executing the operation. Redis
Active-Active replication does not provide
+a globally serialized compare-and-set across regions. Flows that require
global coordination, such as duplicate
+detection or Wait/Notify, should use one authoritative database rather than
independent writable Active-Active
+regions.
+
+Bulk `putAll` retains its existing `MSET` behavior; it does not promise a
transaction across multiple hash slots.
+Follow the database's multi-key command restrictions and use a common hash tag
when a deployment requires keys in one
+slot.
diff --git
a/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-extensions/src/test/java/org/apache/nifi/redis/service/ITRedisClusterDistributedMapCacheClientService.java
b/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-extensions/src/test/java/org/apache/nifi/redis/service/ITRedisClusterDistributedMapCacheClientService.java
new file mode 100644
index 00000000000..a0156a67f88
--- /dev/null
+++
b/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-extensions/src/test/java/org/apache/nifi/redis/service/ITRedisClusterDistributedMapCacheClientService.java
@@ -0,0 +1,31 @@
+/*
+ * 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.nifi.redis.service;
+
+/**
+ * Runs the atomic cache contract against the Redis Cluster API, with all hash
slots assigned to one node.
+ * This exercises cluster command routing without requiring fixed Docker host
ports or a multi-node network.
+ * Because one node owns every slot, the client never receives MOVED or ASK
redirects, so this test does not cover
+ * redirect handling or slot migration between nodes.
+ */
+public class ITRedisClusterDistributedMapCacheClientService extends
ITRedisDistributedMapCacheClientService {
+
+ @Override
+ protected String getRedisMode() {
+ return "Cluster";
+ }
+}
diff --git
a/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-extensions/src/test/java/org/apache/nifi/redis/service/ITRedisDistributedMapCacheClientService.java
b/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-extensions/src/test/java/org/apache/nifi/redis/service/ITRedisDistributedMapCacheClientService.java
index d91ba052416..28f4b79c678 100644
---
a/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-extensions/src/test/java/org/apache/nifi/redis/service/ITRedisDistributedMapCacheClientService.java
+++
b/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-extensions/src/test/java/org/apache/nifi/redis/service/ITRedisDistributedMapCacheClientService.java
@@ -31,12 +31,21 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+import org.springframework.data.redis.connection.RedisConnection;
import org.testcontainers.containers.Container;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
-
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
@@ -46,26 +55,53 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
* Integration test for {@link RedisDistributedMapCacheClientService} against
a real Redis, covering the atomic
* operations {@code getAndPutIfAbsent} (used by DetectDuplicate) and {@code
replace} (used by Wait/Notify).
* A non-zero TTL is configured so the tests exercise the
value-plus-expiration paths.
+ * The endpoint requires ACL credentials and prohibits WATCH, MULTI, and EXEC.
*/
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class ITRedisDistributedMapCacheClientService {
private static final Serializer<String> STRING_SERIALIZER = new
StringSerializer();
private static final Deserializer<String> STRING_DESERIALIZER = new
StringDeserializer();
- public static final RedisContainer REDIS_CONTAINER = new
RedisContainer(RedisContainer.DEFAULT_IMAGE_NAME).withExposedPorts(6379);
+ public final RedisContainer redisContainer = new
RedisContainer(RedisContainer.DEFAULT_IMAGE_NAME).withExposedPorts(6379);
private TestRunner testRunner;
private RedisConnectionPoolService redisConnectionPool;
private RedisDistributedMapCacheClientService cacheClient;
@BeforeAll
- public static void startContainer() {
- REDIS_CONTAINER.start();
+ public void startContainer() throws IOException, InterruptedException {
+ redisContainer.addConfigurationOption("user default off");
+ redisContainer.addConfigurationOption("user nifi on >test-password ~*
+@all -watch -multi -exec");
+ if ("Cluster".equals(getRedisMode())) {
+ redisContainer.addConfigurationOption("cluster-enabled yes");
+ }
+ redisContainer.start();
+ if ("Cluster".equals(getRedisMode())) {
+ redisContainer.execInContainer("redis-cli", "--user", "nifi",
"-a", "test-password", "CONFIG", "SET",
+ "cluster-announce-ip", redisContainer.getHost(),
"cluster-announce-port", redisContainer.getFirstMappedPort().toString());
+ redisContainer.execInContainer("redis-cli", "--user", "nifi",
"-a", "test-password", "CLUSTER", "ADDSLOTSRANGE", "0", "16383");
+ final long deadline = System.nanoTime() +
java.util.concurrent.TimeUnit.SECONDS.toNanos(10);
+ boolean ready = false;
+ while (System.nanoTime() < deadline) {
+ if (redisContainer.execInContainer("redis-cli", "--user",
"nifi", "-a", "test-password", "CLUSTER", "INFO")
+ .getStdout().contains("cluster_state:ok")) {
+ ready = true;
+ break;
+ }
+ Thread.sleep(50);
+ }
+ assertTrue(ready, "Redis Cluster must own all slots and be ready
before connecting");
+ }
+ }
+
+ protected String getRedisMode() {
+ return "Standalone";
}
@AfterAll
- public static void stopContainer() {
- REDIS_CONTAINER.stop();
+ public void stopContainer() {
+ redisContainer.stop();
}
@BeforeEach
@@ -76,9 +112,11 @@ public class ITRedisDistributedMapCacheClientService {
redisConnectionPool = new RedisConnectionPoolService();
testRunner.addControllerService("redis-pool", redisConnectionPool);
- testRunner.setProperty(redisConnectionPool, RedisUtils.REDIS_MODE,
"Standalone");
+ testRunner.setProperty(redisConnectionPool, RedisUtils.REDIS_MODE,
getRedisMode());
testRunner.setProperty(redisConnectionPool,
RedisUtils.CONNECTION_STRING,
- REDIS_CONTAINER.getHost() + ":" +
REDIS_CONTAINER.getFirstMappedPort());
+ redisContainer.getHost() + ":" +
redisContainer.getFirstMappedPort());
+ testRunner.setProperty(redisConnectionPool, RedisUtils.USERNAME,
"nifi");
+ testRunner.setProperty(redisConnectionPool, RedisUtils.PASSWORD,
"test-password");
testRunner.enableControllerService(redisConnectionPool);
cacheClient = new RedisDistributedMapCacheClientService();
@@ -173,9 +211,133 @@ public class ITRedisDistributedMapCacheClientService {
assertEquals("v1", cacheClient.get(key, STRING_SERIALIZER,
STRING_DESERIALIZER));
}
- private static void flushDatabase() {
+ @Test
+ public void
testPutIfAbsentSetsExpirationWithoutChangingExistingExpiration() throws
IOException {
+ assertTrue(cacheClient.putIfAbsent("ttl", "v1", STRING_SERIALIZER,
STRING_SERIALIZER));
+ try (RedisConnection connection = redisConnectionPool.getConnection())
{
+ final byte[] key = "ttl".getBytes(StandardCharsets.UTF_8);
+ final long ttl = connection.keyCommands().ttl(key);
+ assertTrue(ttl > 0 && ttl <= 60);
+ connection.keyCommands().expire(key, 20);
+ assertFalse(cacheClient.putIfAbsent("ttl", "v2",
STRING_SERIALIZER, STRING_SERIALIZER));
+ assertTrue(connection.keyCommands().ttl(key) <= 20);
+ }
+ assertEquals("v1", cacheClient.get("ttl", STRING_SERIALIZER,
STRING_DESERIALIZER));
+ }
+
+ @Test
+ public void testGetAndPutIfAbsentDoesNotRefreshExistingExpiration() throws
IOException {
+ assertNull(cacheClient.getAndPutIfAbsent("ttl", "v1",
STRING_SERIALIZER, STRING_SERIALIZER, STRING_DESERIALIZER));
+ try (RedisConnection connection = redisConnectionPool.getConnection())
{
+ final byte[] key = "ttl".getBytes(StandardCharsets.UTF_8);
+ assertTrue(connection.keyCommands().ttl(key) > 0);
+ connection.keyCommands().expire(key, 20);
+ assertEquals("v1", cacheClient.getAndPutIfAbsent("ttl", "v2",
STRING_SERIALIZER, STRING_SERIALIZER, STRING_DESERIALIZER));
+ assertTrue(connection.keyCommands().ttl(key) <= 20);
+ }
+ }
+
+ @Test
+ public void
testReplacePreservesExpirationOnConflictAndRefreshesOnSuccess() throws
IOException {
+ cacheClient.put("ttl", "v1", STRING_SERIALIZER, STRING_SERIALIZER);
+ final AtomicCacheEntry<String, String, byte[]> entry =
cacheClient.fetch("ttl", STRING_SERIALIZER, STRING_DESERIALIZER);
+ try (RedisConnection connection = redisConnectionPool.getConnection())
{
+ final byte[] key = "ttl".getBytes(StandardCharsets.UTF_8);
+ connection.keyCommands().expire(key, 20);
+ assertFalse(cacheClient.replace(new AtomicCacheEntry<>("ttl",
"v2", new byte[0]), STRING_SERIALIZER, STRING_SERIALIZER));
+ assertTrue(connection.keyCommands().ttl(key) <= 20);
+ entry.setValue("v2");
+ assertTrue(cacheClient.replace(entry, STRING_SERIALIZER,
STRING_SERIALIZER));
+ assertTrue(connection.keyCommands().ttl(key) > 20);
+ }
+ }
+
+ @Test
+ public void testBinaryAndEmptyValuesAreDistinctFromMissingKeys() throws
IOException {
+ final Serializer<byte[]> serializer = (value, output) ->
output.write(value);
+ final Deserializer<byte[]> deserializer = value -> value;
+ final byte[] key = {0, (byte) 255, 1};
+ final byte[] empty = new byte[0];
+ final byte[] binary = {0, (byte) 255, 2};
+ assertNull(cacheClient.getAndPutIfAbsent(key, empty, serializer,
serializer, deserializer));
+ assertArrayEquals(empty, cacheClient.getAndPutIfAbsent(key, binary,
serializer, serializer, deserializer));
+ assertFalse(cacheClient.replace(new AtomicCacheEntry<>(key, binary,
null), serializer, serializer));
+ assertTrue(cacheClient.replace(new AtomicCacheEntry<>(key, binary,
empty), serializer, serializer));
+ assertArrayEquals(binary, cacheClient.fetch(key, serializer,
deserializer).getRevision().orElseThrow());
+ assertFalse(cacheClient.replace(new AtomicCacheEntry<>(new byte[]{3},
binary, empty), serializer, serializer));
+ }
+
+ @Test
+ public void testZeroTtlCreatesPersistentEntries() throws IOException {
+ testRunner.disableControllerService(cacheClient);
+ testRunner.setProperty(cacheClient, RedisUtils.TTL, "0 secs");
+ testRunner.enableControllerService(cacheClient);
+ assertTrue(cacheClient.putIfAbsent("put", "v1", STRING_SERIALIZER,
STRING_SERIALIZER));
+ assertNull(cacheClient.getAndPutIfAbsent("get", "v1",
STRING_SERIALIZER, STRING_SERIALIZER, STRING_DESERIALIZER));
+ assertTrue(cacheClient.replace(new AtomicCacheEntry<>("replace", "v1",
null), STRING_SERIALIZER, STRING_SERIALIZER));
+ try (RedisConnection connection = redisConnectionPool.getConnection())
{
+ for (String key : List.of("put", "get", "replace")) {
+ assertEquals(-1L,
connection.keyCommands().ttl(key.getBytes(StandardCharsets.UTF_8)));
+ }
+ // A successful replacement with TTL disabled removes any existing
expiration.
+
connection.keyCommands().expire("replace".getBytes(StandardCharsets.UTF_8), 20);
+ assertTrue(cacheClient.replace(new AtomicCacheEntry<>("replace",
"v2", "v1".getBytes(StandardCharsets.UTF_8)),
+ STRING_SERIALIZER, STRING_SERIALIZER));
+ assertEquals(-1L,
connection.keyCommands().ttl("replace".getBytes(StandardCharsets.UTF_8)));
+ }
+ }
+
+ @Test
+ public void testConcurrentInsertsHaveOneWinner() throws Exception {
+ try (ExecutorService executor = Executors.newFixedThreadPool(8)) {
+ final List<Callable<String>> tasks = new ArrayList<>();
+ for (int i = 0; i < 32; i++) {
+ final String value = "value-" + i;
+ tasks.add(() -> cacheClient.getAndPutIfAbsent("concurrent",
value,
+ STRING_SERIALIZER, STRING_SERIALIZER,
STRING_DESERIALIZER));
+ }
+ int winners = 0;
+ final String[] previousValues = new String[tasks.size()];
+ final List<Future<String>> results = executor.invokeAll(tasks);
+ for (int i = 0; i < results.size(); i++) {
+ previousValues[i] = results.get(i).get();
+ if (previousValues[i] == null) {
+ winners++;
+ }
+ }
+ assertEquals(1, winners);
+ final String stored = cacheClient.get("concurrent",
STRING_SERIALIZER, STRING_DESERIALIZER);
+ for (String previous : previousValues) {
+ if (previous != null) {
+ assertEquals(stored, previous);
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testConcurrentReplacementsHaveOneWinner() throws Exception {
+ cacheClient.put("concurrent", "initial", STRING_SERIALIZER,
STRING_SERIALIZER);
+ try (ExecutorService executor = Executors.newFixedThreadPool(8)) {
+ final List<Callable<Boolean>> tasks = new ArrayList<>();
+ for (int i = 0; i < 32; i++) {
+ final String value = "value-" + i;
+ tasks.add(() -> cacheClient.replace(new
AtomicCacheEntry<>("concurrent", value,
"initial".getBytes(StandardCharsets.UTF_8)),
+ STRING_SERIALIZER, STRING_SERIALIZER));
+ }
+ int winners = 0;
+ for (Future<Boolean> result : executor.invokeAll(tasks)) {
+ if (result.get()) {
+ winners++;
+ }
+ }
+ assertEquals(1, winners);
+ }
+ }
+
+ private void flushDatabase() {
try {
- final Container.ExecResult execResult =
REDIS_CONTAINER.execInContainer("redis-cli", "flushall");
+ final Container.ExecResult execResult =
redisContainer.execInContainer("redis-cli", "--user", "nifi", "-a",
"test-password", "flushall");
if (execResult.getExitCode() != 0) {
throw new IllegalStateException(String.format("Failed to flush
Redis container: %s%s",
execResult.getStdout(), execResult.getStderr()));
diff --git
a/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-extensions/src/test/java/org/apache/nifi/redis/service/TestRedisDistributedMapCacheClientService.java
b/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-extensions/src/test/java/org/apache/nifi/redis/service/TestRedisDistributedMapCacheClientService.java
new file mode 100644
index 00000000000..40184fc7f69
--- /dev/null
+++
b/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-extensions/src/test/java/org/apache/nifi/redis/service/TestRedisDistributedMapCacheClientService.java
@@ -0,0 +1,47 @@
+/*
+ * 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.nifi.redis.service;
+
+import org.apache.nifi.redis.RedisConnectionPool;
+import org.apache.nifi.redis.RedisType;
+import org.apache.nifi.redis.util.RedisUtils;
+import org.apache.nifi.reporting.InitializationException;
+import org.apache.nifi.util.TestRunner;
+import org.apache.nifi.util.TestRunners;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class TestRedisDistributedMapCacheClientService {
+
+ @ParameterizedTest
+ @EnumSource(RedisType.class)
+ public void testAcceptsConnectionTopologies(final RedisType redisType)
throws InitializationException {
+ final TestRunner runner = TestRunners.newTestRunner(new
FakeRedisProcessor());
+ final RedisConnectionPool pool = mock(RedisConnectionPool.class);
+ when(pool.getIdentifier()).thenReturn("pool");
+ when(pool.getRedisType()).thenReturn(redisType);
+ runner.addControllerService("pool", pool);
+ runner.enableControllerService(pool);
+ final RedisDistributedMapCacheClientService cache = new
RedisDistributedMapCacheClientService();
+ runner.addControllerService("cache", cache);
+ runner.setProperty(cache, RedisUtils.REDIS_CONNECTION_POOL, "pool");
+ runner.assertValid(cache);
+ }
+}
diff --git
a/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-utils/src/main/java/org/apache/nifi/redis/util/RedisUtils.java
b/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-utils/src/main/java/org/apache/nifi/redis/util/RedisUtils.java
index 1ff170ff21e..5c8ef991969 100644
---
a/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-utils/src/main/java/org/apache/nifi/redis/util/RedisUtils.java
+++
b/nifi-extension-bundles/nifi-redis-bundle/nifi-redis-utils/src/main/java/org/apache/nifi/redis/util/RedisUtils.java
@@ -84,7 +84,8 @@ public class RedisUtils {
public static final PropertyDescriptor REDIS_MODE = new
PropertyDescriptor.Builder()
.name("Redis Mode")
- .description("The type of Redis being communicated with -
standalone, sentinel, or clustered.")
+ .description("The Redis connection topology: standalone, sentinel,
or clustered. Use standalone for a Redis Enterprise Software or Redis Cloud
database endpoint. " +
+ "Use clustered only when the endpoint exposes the Redis
Cluster API.")
.allowableValues(REDIS_MODE_STANDALONE, REDIS_MODE_SENTINEL,
REDIS_MODE_CLUSTER)
.defaultValue(REDIS_MODE_STANDALONE.getValue())
.addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
@@ -136,14 +137,14 @@ public class RedisUtils {
public static final PropertyDescriptor USERNAME = new
PropertyDescriptor.Builder()
.name("Username")
- .description("The username used to authenticate to the Redis
server.")
+ .description("The Redis ACL username used to authenticate to the
Redis server, including Redis Enterprise Software and Redis Cloud.")
.addValidator(StandardValidators.NON_BLANK_VALIDATOR)
.expressionLanguageSupported(ExpressionLanguageScope.ENVIRONMENT)
.build();
public static final PropertyDescriptor PASSWORD = new
PropertyDescriptor.Builder()
.name("Password")
- .description("The password used to authenticate to the Redis
server. See the 'requirepass' property in redis.conf.")
+ .description("The database password used to authenticate to the
Redis server, including Redis Enterprise Software and Redis Cloud.")
.addValidator(StandardValidators.NON_BLANK_VALIDATOR)
.expressionLanguageSupported(ExpressionLanguageScope.ENVIRONMENT)
.sensitive(true)