From d21e959b2692927e001c16e877e518ce61233f6b Mon Sep 17 00:00:00 2001 From: hex Date: Thu, 30 Jul 2026 08:18:09 -0600 Subject: [PATCH 1/2] Add Redis Cluster support --- Cargo.toml | 7 +- README.md | 23 ++++- examples/cluster.rs | 23 +++++ src/lock.rs | 238 ++++++++++++++++++++++++++++++++++++++++---- 4 files changed, 270 insertions(+), 21 deletions(-) create mode 100644 examples/cluster.rs diff --git a/Cargo.toml b/Cargo.toml index f586c9d..557d10b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rslock" -version = "0.8.0" +version = "0.9.0" authors = [ "Jan-Erik Rediger ", "Romain Boces ", @@ -21,6 +21,7 @@ edition = "2021" [features] async-std-comp = ["redis/smol-rustls-comp"] tokio-comp = ["redis/tokio-rustls-comp"] +cluster = ["redis/cluster-async"] default = ["async-std-comp"] [dependencies] @@ -36,3 +37,7 @@ testcontainers = "0.27.3" anyhow = "1.0.104" tokio = { version = "1.53.1", features = ["macros", "rt-multi-thread"] } tokio-test = "0.4.5" + +[[example]] +name = "cluster" +required-features = ["cluster"] diff --git a/README.md b/README.md index b8ffcc7..0f5d311 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ This is an implementation of Redlock, the [distributed locking mechanism](http:/ - Lock extending - Async runtime support (async-std and tokio) - Async redis +- Redis Cluster support ## Install @@ -18,7 +19,7 @@ This is an implementation of Redlock, the [distributed locking mechanism](http:/ ```bash # It is recommended to pin the version to a minor release, as breaking changes may be introduced between minor versions before 1.0.0. -cargo add rslock --vers "~0.7.2" +cargo add rslock --vers "~0.9.0" ``` > [!NOTE] @@ -73,6 +74,25 @@ async fn main() { } ``` +### Redis Cluster + +Enable the `cluster` feature and pass one or more seed-node URIs for the same cluster: + +```bash +cargo add rslock --vers "~0.9.0" --features cluster +``` + +```rust +let manager = LockManager::new_cluster(vec![ + "redis://127.0.0.1:7000/", + "redis://127.0.0.1:7001/", + "redis://127.0.0.1:7002/", +])?; +``` + +For authentication, TLS, address mapping, and other advanced configuration, build a +`redis::cluster::ClusterClient` and pass it to `LockManager::from_cluster_client`. + ## Extending Locks Extending a lock effectively renews its duration instead of adding extra time to it. For instance, if a 1000ms lock is extended by 1000ms after 500ms pass, it will only last for a total of 1500ms, not 2000ms. This approach is consistent with the [Node.js Redlock implementation](https://www.npmjs.com/package/redlock). See the [extend script](https://github.com/hexcowboy/rslock/blob/main/src/lock.rs#L22-L30). @@ -99,6 +119,7 @@ Run the examples: cargo run --example basic cargo run --example shared_lock cargo run --example from_clients +cargo run --example cluster --features cluster ``` Stop the redis servers: diff --git a/examples/cluster.rs b/examples/cluster.rs new file mode 100644 index 0000000..d3aff5b --- /dev/null +++ b/examples/cluster.rs @@ -0,0 +1,23 @@ +use rslock::LockManager; +use std::time::Duration; + +#[tokio::main] +async fn main() -> Result<(), Box> { + // These are seed nodes for one logical Redis Cluster, not independent Redlock servers. + // The cluster client discovers the rest of the topology automatically. + let manager = LockManager::new_cluster(vec![ + "redis://127.0.0.1:7000/", + "redis://127.0.0.1:7001/", + "redis://127.0.0.1:7002/", + ])?; + + let lock = manager + .lock("cluster-example", Duration::from_secs(10)) + .await?; + + println!("Lock acquired"); + manager.unlock(&lock).await; + println!("Lock released"); + + Ok(()) +} diff --git a/src/lock.rs b/src/lock.rs index af6f591..d1a6fd1 100644 --- a/src/lock.rs +++ b/src/lock.rs @@ -1,12 +1,19 @@ +use std::fmt; use std::io; use std::sync::Arc; use std::time::{Duration, Instant}; use futures::future::join_all; use rand::{rng, Rng, RngExt}; -use redis::aio::MultiplexedConnection; +use redis::aio::{ConnectionLike, MultiplexedConnection}; +#[cfg(feature = "cluster")] +use redis::cluster::ClusterClient; +#[cfg(feature = "cluster")] +use redis::cluster_async::ClusterConnection; use redis::Value::Okay; -use redis::{Client, IntoConnectionInfo, RedisError, RedisResult, Value}; +use redis::{ + Client, Cmd, IntoConnectionInfo, Pipeline, RedisError, RedisFuture, RedisResult, Value, +}; use crate::resource::{LockResource, ToLockResource}; @@ -91,29 +98,46 @@ impl LockManagerInner { } } -#[derive(Debug, Clone)] +#[derive(Clone)] struct RestorableConnection { - client: Client, - con: Arc>>, + client: RedisClient, + con: Arc>>, } impl RestorableConnection { pub fn new(client: Client) -> Self { Self { - client, + client: RedisClient::Standalone(client), + con: Arc::new(tokio::sync::Mutex::new(None)), + } + } + + #[cfg(feature = "cluster")] + pub fn new_cluster(client: ClusterClient) -> Self { + Self { + client: RedisClient::Cluster(client), con: Arc::new(tokio::sync::Mutex::new(None)), } } - pub async fn get_connection(&mut self) -> Result { + async fn connect(&self) -> RedisResult { + match &self.client { + RedisClient::Standalone(client) => client + .get_multiplexed_async_connection() + .await + .map(RedisConnection::Standalone), + #[cfg(feature = "cluster")] + RedisClient::Cluster(client) => client + .get_async_connection() + .await + .map(RedisConnection::Cluster), + } + } + + pub async fn get_connection(&mut self) -> Result { let mut lock = self.con.lock().await; if lock.is_none() { - *lock = Some( - self.client - .get_multiplexed_async_connection() - .await - .map_err(LockError::Redis)?, - ); + *lock = Some(self.connect().await.map_err(LockError::Redis)?); } match (*lock).clone() { Some(conn) => Ok(conn), @@ -127,17 +151,87 @@ impl RestorableConnection { Ok(()) } else { let mut lock = self.con.lock().await; - *lock = Some( - self.client - .get_multiplexed_async_connection() - .await - .map_err(LockError::Redis)?, - ); + *lock = Some(self.connect().await.map_err(LockError::Redis)?); Ok(()) } } } +#[derive(Clone)] +enum RedisClient { + Standalone(Client), + #[cfg(feature = "cluster")] + Cluster(ClusterClient), +} + +impl fmt::Debug for RedisClient { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Standalone(_) => formatter.write_str("Standalone"), + #[cfg(feature = "cluster")] + Self::Cluster(_) => formatter.write_str("Cluster"), + } + } +} + +#[derive(Clone)] +enum RedisConnection { + Standalone(MultiplexedConnection), + #[cfg(feature = "cluster")] + Cluster(ClusterConnection), +} + +impl fmt::Debug for RedisConnection { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Standalone(_) => formatter.write_str("Standalone"), + #[cfg(feature = "cluster")] + Self::Cluster(_) => formatter.write_str("Cluster"), + } + } +} + +impl ConnectionLike for RedisConnection { + fn req_packed_command<'a>(&'a mut self, cmd: &'a Cmd) -> RedisFuture<'a, Value> { + match self { + Self::Standalone(connection) => connection.req_packed_command(cmd), + #[cfg(feature = "cluster")] + Self::Cluster(connection) => connection.req_packed_command(cmd), + } + } + + fn req_packed_commands<'a>( + &'a mut self, + pipeline: &'a Pipeline, + offset: usize, + count: usize, + ) -> RedisFuture<'a, Vec> { + match self { + Self::Standalone(connection) => connection.req_packed_commands(pipeline, offset, count), + #[cfg(feature = "cluster")] + Self::Cluster(connection) => connection.req_packed_commands(pipeline, offset, count), + } + } + + fn get_db(&self) -> i64 { + match self { + Self::Standalone(connection) => connection.get_db(), + #[cfg(feature = "cluster")] + Self::Cluster(connection) => connection.get_db(), + } + } +} + +impl fmt::Debug for RestorableConnection { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("RestorableConnection") + .field("client", &self.client) + .field("con", &self.con) + .finish() + } +} + impl RestorableConnection { async fn lock(&mut self, resource: &LockResource<'_>, val: &[u8], ttl: usize) -> bool { let mut con = match self.get_connection().await { @@ -289,6 +383,30 @@ impl LockManager { } } + /// Create a lock manager backed by one Redis Cluster. + /// + /// The URIs are seed nodes for the same logical cluster, so the cluster counts as one server + /// when calculating quorum. Enable the `cluster` crate feature to use this constructor. + #[cfg(feature = "cluster")] + pub fn new_cluster(uris: Vec) -> RedisResult { + ClusterClient::new(uris).map(Self::from_cluster_client) + } + + /// Create a lock manager from a configured Redis Cluster client. + /// + /// Use this constructor when the cluster needs authentication, TLS, address remapping, or + /// other options exposed by [`redis::cluster::ClusterClientBuilder`]. + #[cfg(feature = "cluster")] + pub fn from_cluster_client(client: ClusterClient) -> LockManager { + LockManager { + lock_manager_inner: Arc::new(Mutex::new(LockManagerInner { + servers: vec![RestorableConnection::new_cluster(client)], + })), + retry_count: DEFAULT_RETRY_COUNT, + retry_delay: DEFAULT_RETRY_DELAY, + } + } + /// Get 20 random bytes from the pseudorandom interface. pub fn get_unique_lock_id(&self) -> io::Result> { let mut buf = [0u8; 20]; @@ -552,6 +670,12 @@ impl LockManager { #[cfg(test)] mod tests { use anyhow::Result; + #[cfg(feature = "cluster")] + use redis::cluster::{ClusterClientBuilder, NodeAddress}; + #[cfg(feature = "cluster")] + use std::collections::HashMap; + #[cfg(feature = "cluster")] + use testcontainers::ImageExt; use testcontainers::{ core::{IntoContainerPort, WaitFor}, runners::AsyncRunner, @@ -646,6 +770,82 @@ mod tests { is_normal::(); } + #[cfg(feature = "cluster")] + #[test] + fn test_new_cluster_validates_seed_nodes() { + assert!(LockManager::new_cluster(vec!["not-a-redis-uri"]).is_err()); + } + + #[cfg(feature = "cluster")] + #[tokio::test] + async fn test_cluster_lock_lifecycle() -> Result<()> { + const CLUSTER_PORTS: [u16; 6] = [7000, 7001, 7002, 7003, 7004, 7005]; + + let mut image = + GenericImage::new("grokzen/redis-cluster", "7.2.5").with_wait_for(WaitFor::seconds(10)); + + for port in CLUSTER_PORTS { + image = image.with_exposed_port(port.tcp()); + } + + let container = image + .with_env_var("IP", "127.0.0.1") + .with_env_var("LANG", "C.UTF-8") + .with_env_var("LC_ALL", "C.UTF-8") + .start() + .await + .expect("Failed to start Redis Cluster container"); + let host = container.get_host().await?.to_string(); + let mut address_map = HashMap::new(); + + for port in CLUSTER_PORTS { + address_map.insert( + NodeAddress::new("127.0.0.1", port), + NodeAddress::new(host.clone(), container.get_host_port_ipv4(port).await?), + ); + } + + let seed_port = container.get_host_port_ipv4(CLUSTER_PORTS[0]).await?; + let seed = format!("redis://{host}:{seed_port}/"); + let client = ClusterClientBuilder::new([seed]) + .node_address_map(address_map) + .build()?; + let manager = LockManager::from_cluster_client(client); + let mut inner = manager.lock_inner().await; + if let Err(error) = inner.servers[0].get_connection().await { + eprintln!( + "Redis Cluster stdout:\n{}", + String::from_utf8_lossy(&container.stdout_to_vec().await?) + ); + eprintln!( + "Redis Cluster stderr:\n{}", + String::from_utf8_lossy(&container.stderr_to_vec().await?) + ); + return Err(error.into()); + } + drop(inner); + + let lock = manager + .lock("cluster-lock-lifecycle", Duration::from_secs(10)) + .await?; + assert_eq!( + manager.query_redis_for_key_value(&lock.resource).await?, + Some(lock.val.clone()) + ); + + let extended = manager.extend(&lock, Duration::from_secs(10)).await?; + assert!(extended.validity_time > 0); + + manager.unlock(&extended).await; + assert_eq!( + manager.query_redis_for_key_value(&lock.resource).await?, + None + ); + + drop(container); + Ok(()) + } + #[tokio::test] async fn test_lock_get_unique_id() -> Result<()> { let rl = LockManager::new(Vec::::new()); From 4fe77e47efb63a3a0170460ec7ed7eda420d24de Mon Sep 17 00:00:00 2001 From: hex Date: Thu, 30 Jul 2026 08:28:36 -0600 Subject: [PATCH 2/2] Fix cluster-only feature build --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 557d10b..9b41371 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ edition = "2021" [features] async-std-comp = ["redis/smol-rustls-comp"] tokio-comp = ["redis/tokio-rustls-comp"] -cluster = ["redis/cluster-async"] +cluster = ["async-std-comp", "redis/cluster-async"] default = ["async-std-comp"] [dependencies]