From 60738acd176a7cecef61bb75c45a1b111216cb3c Mon Sep 17 00:00:00 2001 From: Chris Eager Date: Wed, 30 Sep 2026 16:52:52 +0000 Subject: [PATCH] Update to Lettuce 7.8.0 Also, adapt to Lettuce 7.7.0 behavior change (redis/lettuce#3782) with respect to command rejection in pending connections by eagerly connecting to upstreams in `FaultTolerantRedisClusterClient` construction. --- .github/dependabot.yml | 4 - pom.xml | 2 +- .../FaultTolerantRedisClusterClient.java | 54 +++++++++++ .../FaultTolerantRedisClusterClientTest.java | 96 ++++++++++++++++++- 4 files changed, 149 insertions(+), 7 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index b700996c1..822c63ae0 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -32,10 +32,6 @@ updates: - dependency-name: "org.eclipse.jetty.ee10:*" versions: ["<=12.1.12"] - # Temporary exclusions, pending adaptation to upstream changes - - dependency-name: "io.lettuce:lettuce-core" - versions: [">=7.7.0.RELEASE"] - # Dependency convergence sentinels, pinned to specific versions - dependency-name: "tools.jackson.core:jackson-databind" - dependency-name: "com.squareup.okio:okio-jvm" diff --git a/pom.xml b/pom.xml index f3ae5ad89..09fc072cc 100644 --- a/pom.xml +++ b/pom.xml @@ -71,7 +71,7 @@ 1.5.38 2.0.15 - 7.6.0.RELEASE + 7.8.0.RELEASE 9.0.38 9.0 2.26.1 diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/redis/FaultTolerantRedisClusterClient.java b/service/src/main/java/org/whispersystems/textsecuregcm/redis/FaultTolerantRedisClusterClient.java index ae277b6cf..409e37163 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/redis/FaultTolerantRedisClusterClient.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/redis/FaultTolerantRedisClusterClient.java @@ -18,6 +18,8 @@ import io.lettuce.core.cluster.ClusterTopologyRefreshOptions; import io.lettuce.core.cluster.RedisClusterClient; import io.lettuce.core.cluster.api.StatefulRedisClusterConnection; import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent; +import io.lettuce.core.cluster.models.partitions.Partitions; +import io.lettuce.core.cluster.models.partitions.RedisClusterNode; import io.lettuce.core.cluster.pubsub.StatefulRedisClusterPubSubConnection; import io.lettuce.core.codec.ByteArrayCodec; import io.lettuce.core.resource.ClientResources; @@ -25,9 +27,16 @@ import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import javax.annotation.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.whispersystems.textsecuregcm.configuration.RedisClusterConfiguration; import reactor.core.scheduler.Schedulers; @@ -40,6 +49,8 @@ public class FaultTolerantRedisClusterClient { private final String name; + private final Duration upstreamConnectionTimeout; + private final RedisClusterClient clusterClient; private final StatefulRedisClusterConnection stringConnection; @@ -49,6 +60,8 @@ public class FaultTolerantRedisClusterClient { private final Retry topologyChangedEventRetry; + private static final Logger logger = LoggerFactory.getLogger(FaultTolerantRedisClusterClient.class); + public FaultTolerantRedisClusterClient(final String name, final RedisClusterConfiguration clusterConfiguration, @@ -69,6 +82,7 @@ public class FaultTolerantRedisClusterClient { @Nullable final String circuitBreakerConfigurationName) { this.name = name; + this.upstreamConnectionTimeout = commandTimeout; final LettuceShardCircuitBreaker lettuceShardCircuitBreaker = new LettuceShardCircuitBreaker(name, circuitBreakerConfigurationName); @@ -98,6 +112,12 @@ public class FaultTolerantRedisClusterClient { this.stringConnection = clusterClient.connect(); this.binaryConnection = clusterClient.connect(ByteArrayCodec.INSTANCE); + // Eagerly initialize connections. Otherwise, the first several calls will fail immediately, rather than being queued + // while the connection is pending. See https://github.com/redis/lettuce/pull/378. + awaitUpstreamConnections( + connectToAllUpstreams(stringConnection.getPartitions(), stringConnection::getConnectionAsync), + connectToAllUpstreams(binaryConnection.getPartitions(), binaryConnection::getConnectionAsync)); + // create a synthetic topology changed event to notify shard circuit breakers of initial upstreams clusterClient.getResources().eventBus().publish( new ClusterTopologyChangedEvent(Collections.emptyList(), clusterClient.getPartitions().getPartitions())); @@ -172,6 +192,9 @@ public class FaultTolerantRedisClusterClient { final StatefulRedisClusterPubSubConnection pubSubConnection = clusterClient.connectPubSub(); pubSubConnections.add(pubSubConnection); + awaitUpstreamConnections( + connectToAllUpstreams(pubSubConnection.getPartitions(), pubSubConnection::getConnectionAsync)); + return new FaultTolerantPubSubClusterConnection<>(name, pubSubConnection, topologyChangedEventRetry, Schedulers.newSingle(name + "-redisPubSubEvents", true)); } @@ -180,7 +203,38 @@ public class FaultTolerantRedisClusterClient { final StatefulRedisClusterPubSubConnection pubSubConnection = clusterClient.connectPubSub(ByteArrayCodec.INSTANCE); pubSubConnections.add(pubSubConnection); + awaitUpstreamConnections( + connectToAllUpstreams(pubSubConnection.getPartitions(), pubSubConnection::getConnectionAsync)); + return new FaultTolerantPubSubClusterConnection<>(name, pubSubConnection, topologyChangedEventRetry, Schedulers.newSingle(name + "-redisPubSubEvents", true)); } + + /// Initiates connections to all upstream nodes in the cluster + /// + /// @return a future that completes when all connection attempts have either succeeded or failed. This future will never fail. + private CompletableFuture connectToAllUpstreams(final Partitions partitions, + final BiFunction> connectionFunction) { + + return CompletableFuture.allOf(partitions.stream() + .filter(node -> node.is(RedisClusterNode.NodeFlag.UPSTREAM)) + .map(node -> connectionFunction.apply(node.getUri().getHost(), node.getUri().getPort()) + .exceptionally(throwable -> { + logger.warn("Failed to connect to upstream {} for {}", node.getUri(), name, throwable); + return null; + })) + .toArray(CompletableFuture[]::new)); + } + + /// Awaits the futures until {@link FaultTolerantRedisClusterClient#upstreamConnectionTimeout} is reached + void awaitUpstreamConnections(final CompletableFuture... connectionFutures) { + try { + CompletableFuture.allOf(connectionFutures).get(upstreamConnectionTimeout.toMillis(), TimeUnit.MILLISECONDS); + } catch (final TimeoutException | InterruptedException e) { + logger.warn("Upstream connection to {} timed out or interrupted; continuing", this.name, e); + } catch (final ExecutionException e) { + throw new IllegalStateException("Unexpected: connection attempt futures always complete successfully", e); + } + } + } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/redis/FaultTolerantRedisClusterClientTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/redis/FaultTolerantRedisClusterClientTest.java index 8b97f100f..00f2e2b52 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/redis/FaultTolerantRedisClusterClientTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/redis/FaultTolerantRedisClusterClientTest.java @@ -5,6 +5,7 @@ package org.whispersystems.textsecuregcm.redis; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -20,12 +21,14 @@ import io.lettuce.core.cluster.models.partitions.RedisClusterNode; import io.lettuce.core.cluster.pubsub.RedisClusterPubSubAdapter; import io.lettuce.core.event.EventBus; import io.lettuce.core.event.EventPublisherOptions; +import io.lettuce.core.internal.HostAndPort; import io.lettuce.core.metrics.CommandLatencyCollectorOptions; import io.lettuce.core.metrics.CommandLatencyRecorder; import io.lettuce.core.resource.ClientResources; import io.lettuce.core.resource.Delay; -import io.lettuce.core.resource.DnsResolver; +import io.lettuce.core.resource.DnsResolvers; import io.lettuce.core.resource.EventLoopGroupProvider; +import io.lettuce.core.resource.MappingSocketAddressResolver; import io.lettuce.core.resource.NettyCustomizer; import io.lettuce.core.resource.SocketAddressResolver; import io.lettuce.core.resource.ThreadFactoryProvider; @@ -41,6 +44,7 @@ import io.netty.util.Timer; import io.netty.util.concurrent.EventExecutorGroup; import java.net.InetSocketAddress; import java.net.SocketAddress; +import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.ArrayList; import java.util.HashSet; @@ -50,6 +54,7 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; @@ -60,9 +65,9 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.extension.RegisterExtension; import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration; -import org.whispersystems.textsecuregcm.util.ResilienceUtil; import org.whispersystems.textsecuregcm.util.Pair; import org.whispersystems.textsecuregcm.util.RedisClusterUtil; +import org.whispersystems.textsecuregcm.util.ResilienceUtil; // ThreadMode.SEPARATE_THREAD protects against hangs in the remote Redis calls, as this mode allows the test code to be // preempted by the timeout check @@ -106,6 +111,93 @@ class FaultTolerantRedisClusterClientTest { cluster.shutdown(); } + @Test + void testConnectedToAllUpstreamsAtStartup() { + cluster = buildCluster("testConnectedToAllUpstreams", null, ClientResources.builder()); + + final List keysByUpstream = cluster.withCluster(connection -> connection.getPartitions().stream() + .filter(node -> node.is(RedisClusterNode.NodeFlag.UPSTREAM)) + .map(node -> "key::{%s}".formatted(RedisClusterUtil.getMinimalHashTag(node.getSlots().getFirst()))) + .toList()); + + assertTrue(keysByUpstream.size() >= 2, "we should have at least two upstream nodes in a cluster"); + + for (final String key : keysByUpstream) { + cluster.useCluster(connection -> connection.sync().set(key, "value")); + assertEquals("value", cluster.withBinaryCluster(connection -> + new String(connection.sync().get(key.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8))); + } + + final FaultTolerantPubSubClusterConnection pubSubConnection = cluster.createPubSubConnection(); + final FaultTolerantPubSubClusterConnection binaryPubSubConnection = + cluster.createBinaryPubSubConnection(); + + for (final String key : keysByUpstream) { + pubSubConnection.usePubSubConnection(connection -> connection.sync().ssubscribe(key)); + binaryPubSubConnection.usePubSubConnection(connection -> + connection.sync().ssubscribe(key.getBytes(StandardCharsets.UTF_8))); + } + } + + @Test + void testUnreachableUpstream() { + final RedisClusterNode unreachableNode = getFirstUpstream(); + final AtomicBoolean nodeUnreachable = new AtomicBoolean(false); + + cluster = new FaultTolerantRedisClusterClient("testUnreachableUpstream", + ClientResources.builder() + .socketAddressResolver(buildUnreachableNodeSocketAddressResolver(unreachableNode, nodeUnreachable)), + RedisClusterExtension.getRedisURIs(), + TIMEOUT, + null); + + // The node becomes unreachable only after constructing the client, so that the client's topology discovery and + // initial connections succeed + nodeUnreachable.set(true); + + final FaultTolerantPubSubClusterConnection pubSubConnection = cluster.createPubSubConnection(); + + final List upstreams = cluster.withCluster(connection -> connection.getPartitions().stream() + .filter(node -> node.is(RedisClusterNode.NodeFlag.UPSTREAM)) + .toList()); + + for (final RedisClusterNode upstream : upstreams) { + final String channel = "channel::{%s}".formatted(RedisClusterUtil.getMinimalHashTag(upstream.getSlots().getFirst())); + + if (upstream.getNodeId().equals(unreachableNode.getNodeId())) { + assertThrows(RedisException.class, + () -> pubSubConnection.usePubSubConnection(connection -> connection.sync().ssubscribe(channel))); + } else { + assertDoesNotThrow( + () -> pubSubConnection.usePubSubConnection(connection -> connection.sync().ssubscribe(channel))); + } + } + } + + private static RedisClusterNode getFirstUpstream() { + return REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(connection -> connection.getPartitions().stream() + .filter(node -> node.is(RedisClusterNode.NodeFlag.UPSTREAM)) + .findFirst() + .orElseThrow()); + } + + private static SocketAddressResolver buildUnreachableNodeSocketAddressResolver(final RedisClusterNode unreachableNode, + final AtomicBoolean nodeUnreachable) { + + final HostAndPort unreachableHostAndPort = HostAndPort.of(unreachableNode.getUri().getHost(), unreachableNode.getUri().getPort()); + + return MappingSocketAddressResolver.create(DnsResolvers.UNRESOLVED, hostAndPort -> { + if (nodeUnreachable.get() && hostAndPort.equals(unreachableHostAndPort)) { + // IP in TEST-NET-1 (https://www.rfc-editor.org/info/rfc5737/#section-3); should not be routable + return HostAndPort.of("192.0.2.1", hostAndPort.getPort()); + } + + final RedisURI exposedUri = REDIS_CLUSTER_EXTENSION.getExposedRedisURI(RedisURI.create(hostAndPort.getHostText(), hostAndPort.getPort())); + + return HostAndPort.of(exposedUri.getHost(), exposedUri.getPort()); + }); + } + @Test void testTimeout() { cluster = buildCluster("testTimeout", null, ClientResources.builder());