Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(redis_interface): redis-rs and fred-rs merge (#12162)
Shivansh Mathur545f0c3da7d1
diff --git a/.github/workflows/CI-pr.yml b/.github/workflows/CI-pr.ymlindex 60633ed05f..2c1033bcaa 100644--- a/.github/workflows/CI-pr.yml+++ b/.github/workflows/CI-pr.yml@@ -198,9 +198,17 @@ jobs:tool: justchecksum: true- - name: Run clippy+ - name: Run clippy (redis-rs backend)shell: bash- run: just clippy --jobs 3+ env:+ CARGO_BUILD_JOBS: 3+ run: just clippy++ - name: Run clippy (fred backend)+ shell: bash+ env:+ CARGO_BUILD_JOBS: 3+ run: just clippy fred- name: Check Cargo.lock changedif: ${{ (github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name) }}@@ -286,14 +294,26 @@ jobs:tool: justchecksum: true- - name: Run cargo clippy with v2 features enabled+ - name: Run cargo clippy with v2 features enabled (redis-rs backend)shell: bashenv:CARGO_BUILD_JOBS: 3run: just clippy_v2- - name: Run cargo check enabling only the release and v2 features+ - name: Run cargo clippy with v2 features enabled (fred backend)+ shell: bash+ env:+ CARGO_BUILD_JOBS: 3+ run: just clippy_v2 fred++ - name: Run cargo check enabling only the release and v2 features (redis-rs backend)+ shell: bash+ env:+ RUSTFLAGS: "-A warnings"+ run: cargo check --no-default-features --features "release,v2,redis-rs"++ - name: Run cargo check enabling only the release and v2 features (fred backend)shell: bashenv:RUSTFLAGS: "-A warnings"- run: cargo check --no-default-features --features "release,v2"+ run: cargo check --no-default-features --features "release,v2,fred"diff --git a/.github/workflows/CI-push.yml b/.github/workflows/CI-push.ymlindex 4af973e968..44b9ff707f 100644--- a/.github/workflows/CI-push.yml+++ b/.github/workflows/CI-push.yml@@ -219,10 +219,14 @@ jobs:with:save-if: ${{ github.event_name == 'push' }}- - name: Run clippy+ - name: Run clippy (redis-rs backend)shell: bashrun: just clippy+ - name: Run clippy (fred backend)+ shell: bash+ run: just clippy fred+- name: Cargo hackif: ${{ github.event_name == 'push' }}shell: bash@@ -292,6 +296,10 @@ jobs:- name: Install rust cacheuses: Swatinem/[email protected]- - name: Run cargo check enabling only the release and v2 features+ - name: Run cargo check enabling only the release and v2 features (redis-rs backend)+ shell: bash+ run: cargo check --no-default-features --features "release,v2,redis-rs"++ - name: Run cargo check enabling only the release and v2 features (fred backend)shell: bash- run: cargo check --no-default-features --features "release,v2"+ run: cargo check --no-default-features --features "release,v2,fred"diff --git a/Cargo.lock b/Cargo.lockindex 8c4d4aeaeb..9d8477f920 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -489,9 +489,18 @@ dependencies = [[[package]]name = "arc-swap"-version = "1.7.1"+version = "1.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a07d1f37ff60921c83bdfc7407723bdefe89b44b98a9b772f225c8f9d67141a6"+dependencies = [+ "rustversion",+]++[[package]]+name = "arcstr"+version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "69f7f8c3906b62b754cd5326047894316021dcfe5a194c8ea52bdd94934a3457"+checksum = "03918c3dbd7701a85c6b9887732e2921175f26c350b4563841d0958c21d57e6d"[[package]]name = "argon2"@@ -1393,6 +1402,15 @@ dependencies = ["tracing",]+[[package]]+name = "backon"+version = "1.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cffb0e931875b666fc4fcb20fee52e9bbd1ef836fd9e9e04ec21555f9f85f7ef"+dependencies = [+ "fastrand",+]+[[package]]name = "base16ct"version = "0.1.1"@@ -2099,6 +2117,20 @@ version = "1.0.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990"+[[package]]+name = "combine"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd"+dependencies = [+ "bytes 1.10.1",+ "futures-core",+ "memchr",+ "pin-project-lite",+ "tokio 1.48.0",+ "tokio-util",+]+[[package]]name = "common_enums"version = "0.1.0"@@ -7613,6 +7645,37 @@ dependencies = ["rand_core 0.3.1",]+[[package]]+name = "redis"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f44e94c96d8870a387d88ce3de3fdd608cbfc0705f03cb343cdde91509d3e49a"+dependencies = [+ "arc-swap",+ "arcstr",+ "async-lock",+ "backon",+ "bytes 1.10.1",+ "cfg-if 1.0.0",+ "combine",+ "crc16",+ "futures-channel",+ "futures-util",+ "itoa",+ "log 0.4.27",+ "num-bigint",+ "percent-encoding 2.3.1",+ "pin-project-lite",+ "rand 0.9.2",+ "ryu",+ "sha1_smol",+ "socket2 0.6.1",+ "tokio 1.48.0",+ "tokio-util",+ "url 2.5.4",+ "xxhash-rust",+]+[[package]]name = "redis-protocol"version = "4.1.0"@@ -7635,6 +7698,7 @@ dependencies = ["error-stack 0.4.1","fred","futures 0.3.31",+ "redis","serde","thiserror 1.0.69","tokio 1.48.0",@@ -8888,6 +8952,12 @@ dependencies = ["digest",]+[[package]]+name = "sha1_smol"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d"+[[package]]name = "sha2"version = "0.10.9"@@ -12318,6 +12388,12 @@ version = "0.13.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4"+[[package]]+name = "xxhash-rust"+version = "0.8.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fdd20c5420375476fbd4394763288da7eb0cc0b8c11deed431a91562af7335d3"+[[package]]name = "yaml-rust2"version = "0.8.1"diff --git a/config/config.example.toml b/config/config.example.tomlindex fc0f580e08..05523f5fe1 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -85,6 +85,7 @@ max_in_flight_commands = 5000 # The maximum number of in-flight commands (pedefault_command_timeout = 30 # An optional timeout to apply to all commands. In secondsunresponsive_timeout = 10 # An optional timeout for Unresponsive commands in seconds. This should be less than default_command_timeout.unresponsive_check_interval = 2 # The frequency at which the client checks for unresponsive connections. In seconds. This value should usually be less than half of `unresponsive_timeout` and always more than 1 ms.+max_failure_threshold_seconds = 5 # Max seconds Redis can be unreachable before server shutdown (min 5s)max_feed_count = 200 # The maximum number of frames that will be fed to a socket before flushing.# This section provides configs for currency conversion apidiff --git a/config/deployments/drainer.toml b/config/deployments/drainer.tomlindex f8bf282676..ac3b16d1c1 100644--- a/config/deployments/drainer.toml+++ b/config/deployments/drainer.toml@@ -45,5 +45,6 @@ pool_size = 5port = 6379reconnect_delay = 5reconnect_max_attempts = 5+max_failure_threshold_seconds = 5 # Max seconds Redis can be unreachable before server shutdownstream_read_count = 1use_legacy_version = falsediff --git a/config/development.toml b/config/development.tomlindex f4740b1a1b..0ab9025c57 100644--- a/config/development.toml+++ b/config/development.toml@@ -56,6 +56,7 @@ default_command_timeout = 30unresponsive_timeout = 10unresponsive_check_interval = 2max_feed_count = 200+max_failure_threshold_seconds = 5[trace_header]header_name = "x-request-id"diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.tomlindex f4cef04bb4..1d949216c7 100644--- a/crates/drainer/Cargo.toml+++ b/crates/drainer/Cargo.toml@@ -8,10 +8,13 @@ readme = "README.md"license.workspace = true[features]+default = ["redis-rs"]release = ["vergen", "external_services/aws_kms"]vergen = ["router_env/vergen"]v1 = ["diesel_models/v1", "hyperswitch_interfaces/v1", "common_utils/v1"]-v2 = ["diesel_models/v2", "hyperswitch_interfaces/v2", "common_utils/v2"]+v2 = ["diesel_models/v2", "hyperswitch_interfaces/v2", "common_utils/v2"]+fred = ["redis_interface/fred"]+redis-rs = ["redis_interface/redis-rs"][dependencies]actix-web = "4.11.0"@@ -36,7 +39,7 @@ diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_external_services = { version = "0.1.0", path = "../external_services" }hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" }hyperswitch_masking = "0.0.1"-redis_interface = { version = "0.1.0", path = "../redis_interface" }+redis_interface = { version = "0.1.0", path = "../redis_interface", default-features = false }router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }[build-dependencies]diff --git a/crates/drainer/src/health_check.rs b/crates/drainer/src/health_check.rsindex aaf455663f..27cc7c757e 100644--- a/crates/drainer/src/health_check.rs+++ b/crates/drainer/src/health_check.rs@@ -197,18 +197,19 @@ impl HealthCheckInterface for Store {logger::debug!("Stream append succeeded");let output = redis_conn- .stream_read_entries(TEST_STREAM_NAME, "0-0", Some(10))+ .stream_read_entries(+ &[TEST_STREAM_NAME.into()],+ vec!["0-0".to_string()],+ Some(10),+ ).await.change_context(HealthCheckRedisError::StreamReadFailed)?;logger::debug!("Stream read succeeded");- let (_, id_to_trim) = output+ let id_to_trim = output.get(&redis_conn.add_prefix(TEST_STREAM_NAME))- .and_then(|entries| {- entries- .last()- .map(|last_entry| (entries, last_entry.0.clone()))- })+ .and_then(|entries| entries.last())+ .map(|(entry_id, _fields)| entry_id.clone()).ok_or(error_stack::report!(HealthCheckRedisError::StreamReadFailed))?;@@ -217,10 +218,10 @@ impl HealthCheckInterface for Store {redis_conn.stream_trim_entries(&TEST_STREAM_NAME.into(),- (+ redis_interface::StreamTrimConfig::new(redis_interface::StreamCapKind::MinID,redis_interface::StreamCapTrim::Exact,- id_to_trim,+ &id_to_trim,),).awaitdiff --git a/crates/drainer/src/stream.rs b/crates/drainer/src/stream.rsindex 8939aa5527..fad80d96d3 100644--- a/crates/drainer/src/stream.rs+++ b/crates/drainer/src/stream.rs@@ -1,12 +1,10 @@-use std::collections::HashMap;-use redis_interface as redis;use router_env::{logger, tracing};use crate::{errors, metrics, Store};-pub type StreamEntries = Vec<(String, HashMap<String, String>)>;-pub type StreamReadResult = HashMap<String, StreamEntries>;+pub type StreamEntries = redis::StreamEntries;+pub type StreamReadResult = redis::StreamReadResult;impl Store {#[inline(always)]@@ -59,10 +57,10 @@ impl Store {max_read_count: u64,) -> errors::DrainerResult<StreamReadResult> {// "0-0" id gives first entry- let stream_id = "0-0";+ let stream_id = "0-0".to_string();let (output, execution_time) = common_utils::date_time::time_it(|| async {self.redis_conn- .stream_read_entries(stream_name, stream_id, Some(max_read_count))+ .stream_read_entries(&[stream_name.into()], vec![stream_id], Some(max_read_count)).await.map_err(errors::DrainerError::from)})@@ -80,21 +78,23 @@ impl Store {stream_name: &str,minimum_entry_id: &str,) -> errors::DrainerResult<usize> {- let trim_kind = redis::StreamCapKind::MinID;- let trim_type = redis::StreamCapTrim::Exact;- let trim_id = minimum_entry_id;+ let trim_config = redis::StreamTrimConfig::new(+ redis::StreamCapKind::MinID,+ redis::StreamCapTrim::Exact,+ minimum_entry_id,+ );let (trim_result, execution_time) =common_utils::date_time::time_it::<errors::DrainerResult<_>, _, _>(|| async {let trim_result = self.redis_conn- .stream_trim_entries(&stream_name.into(), (trim_kind, trim_type, trim_id))+ .stream_trim_entries(&stream_name.into(), trim_config.clone()).await.map_err(errors::DrainerError::from)?;// Since xtrim deletes entries below given id excluding the given id.// Hence, deleting the minimum entry idself.redis_conn- .stream_delete_entries(&stream_name.into(), minimum_entry_id)+ .stream_delete_entries(&stream_name.into(), vec![minimum_entry_id.to_string()]).await.map_err(errors::DrainerError::from)?;@@ -119,7 +119,7 @@ impl Store {let (_trim_result, execution_time) =common_utils::date_time::time_it::<errors::DrainerResult<_>, _, _>(|| async {self.redis_conn- .stream_delete_entries(&stream_name.into(), entry_id)+ .stream_delete_entries(&stream_name.into(), vec![entry_id.to_string()]).await.map_err(errors::DrainerError::from)?;Ok(())diff --git a/crates/drainer/src/types.rs b/crates/drainer/src/types.rsindex a61a0fd159..5c9fedf259 100644--- a/crates/drainer/src/types.rs+++ b/crates/drainer/src/types.rs@@ -21,13 +21,26 @@ pub struct StreamData {impl StreamData {pub fn from_hashmap(- hashmap: HashMap<String, String>,+ hashmap: HashMap<String, redis_interface::RedisValue>,) -> errors::CustomResult<Self, errors::ParsingError> {+ // Convert RedisValue to String, failing explicitly on non-convertible values+ // rather than silently dropping them. This catches data corruption early.+ let mut string_map = HashMap::with_capacity(hashmap.len());+ for (field_name, field_value) in hashmap {+ let string_value = field_value.as_string().ok_or_else(|| {+ error_stack::report!(errors::ParsingError::UnknownError).attach_printable(format!(+ "Field '{}' contains non-string Redis value that cannot be deserialized",+ field_name+ ))+ })?;+ string_map.insert(field_name, string_value);+ }+let iter = MapDeserializer::<'_,std::collections::hash_map::IntoIter<String, String>,serde_json::error::Error,- >::new(hashmap.into_iter());+ >::new(string_map.into_iter());Self::deserialize(iter).change_context(errors::ParsingError::StructParseFailure("StreamData"))diff --git a/crates/redis_interface/Cargo.toml b/crates/redis_interface/Cargo.tomlindex 13ff26589e..9d64aded98 100644--- a/crates/redis_interface/Cargo.toml+++ b/crates/redis_interface/Cargo.toml@@ -8,11 +8,13 @@ readme = "README.md"license.workspace = true[features]+default = ["redis-rs"]+fred = ["dep:fred"]+redis-rs = ["dep:redis"]multitenancy_fallback = [][dependencies]error-stack = "0.4.1"-fred = { version = "8.0.6", features = ["metrics", "partial-tracing", "subscriber-client"] }futures = "0.3"serde = { version = "1.0.219", features = ["derive"] }thiserror = "1.0.69"@@ -20,6 +22,14 @@ tokio = "1.48.0"tokio-stream = { version = "0.1.17", features = ["sync"] }tracing = { workspace = true }+# Exactly one backend must be active at compile time+redis = { version = "1.2.0", optional = true, features = [+ "tokio-comp", "cluster-async", "streams", "script", "connection-manager"+]}+fred = { version = "8.0.6", optional = true, features = [+ "metrics", "partial-tracing", "subscriber-client"+]}+# First party cratescommon_utils = { version = "0.1.0", path = "../common_utils", features = ["async_ext"] }diff --git a/crates/redis_interface/src/constant.rs b/crates/redis_interface/src/constant.rsnew file mode 100644index 0000000000..5176e9f0ff--- /dev/null+++ b/crates/redis_interface/src/constant.rs@@ -0,0 +1,26 @@+//! Shared constants for the redis_interface crate.+//!+//! Backend-specific command string constants live in each backend's module.++/// Redis commands used in redis::cmd() and pipe.cmd() calls (redis-rs backend)+#[cfg(feature = "redis-rs")]+pub mod redis_rs_commands {+ pub const REDIS_COMMAND_SET: &str = "SET";+ pub const REDIS_COMMAND_GET: &str = "GET";+ pub const REDIS_COMMAND_HSCAN: &str = "HSCAN";+ pub const REDIS_COMMAND_SCAN: &str = "SCAN";++ /// Redis arguments used in .arg() calls+ pub const REDIS_ARG_EX: &str = "EX";+ pub const REDIS_ARG_NX: &str = "NX";+ pub const REDIS_ARG_MATCH: &str = "MATCH";+ pub const REDIS_ARG_COUNT: &str = "COUNT";+ pub const REDIS_ARG_TYPE: &str = "TYPE";+ /// Default reconnect max attempts, matching RedisSettings::default().reconnect_max_attempts+ pub const DEFAULT_RECONNECT_MAX_ATTEMPTS: usize = 5;+ /// Minimum error check interval in seconds (used in `on_error`).+ pub const MIN_ERROR_CHECK_INTERVAL_SECS: u64 = 1;+ /// Safety limit for HSCAN/SCAN iterations to guard against a corrupted cursor+ /// that never returns to 0. 1000 iterations × default COUNT(100) = ~100K entries.+ pub const MAX_SCAN_ITERATIONS: u32 = 1000;+}diff --git a/crates/redis_interface/src/errors.rs b/crates/redis_interface/src/errors.rsindex 9e0fb4639a..9e2be1f5ce 100644--- a/crates/redis_interface/src/errors.rs+++ b/crates/redis_interface/src/errors.rs@@ -76,4 +76,6 @@ pub enum RedisError {PopListElementsFailed,#[error("Failed to increment hash field in Redis")]IncrementHashFieldFailed,+ #[error("Failed to evaluate Lua script in Redis")]+ ScriptExecutionFailed,}diff --git a/crates/redis_interface/src/lib.rs b/crates/redis_interface/src/lib.rsindex f9d3a6861e..db92a8bf2b 100644--- a/crates/redis_interface/src/lib.rs+++ b/crates/redis_interface/src/lib.rs@@ -1,264 +1,55 @@-//! Intermediate module for encapsulate all the redis related functionality+//! Redis interface — compile-time backend selection via Cargo feature.//!-//! Provides structs to represent redis connection and all functions that redis provides and-//! are used in the `router` crate. Abstractions for creating a new connection while also facilitating-//! redis connection pool and configuration based types.+//! By default the `redis-rs` crate is used. Enable the `fred` feature to switch.//!-//! # Examples+//! # Examples//! ```//! use redis_interface::{types::RedisSettings, RedisConnectionPool};//!//! #[tokio::main]//! async fn main() {//! let redis_conn = RedisConnectionPool::new(&RedisSettings::default()).await;-//! // ... redis_conn ready to use//! }//! ```-pub mod commands;-pub mod errors;-pub mod types;--use std::sync::{atomic, Arc};--use common_utils::errors::CustomResult;-use error_stack::ResultExt;-pub use fred::interfaces::{EventInterface, PubsubInterface};-use fred::{clients::Transaction, interfaces::ClientLike, prelude::TransactionInterface};+// Compile-time guards: exactly one backend must be active.+#[cfg(not(any(feature = "fred", feature = "redis-rs")))]+compile_error!("Either feature \"fred\" or \"redis-rs\" must be enabled for this crate.");-pub use self::types::*;--pub struct RedisConnectionPool {- pub pool: Arc<fred::prelude::RedisPool>,- pub key_prefix: String,- pub config: Arc<RedisConfig>,- pub subscriber: Arc<SubscriberClient>,- pub publisher: Arc<RedisClient>,- pub is_redis_available: Arc<atomic::AtomicBool>,-}--pub struct RedisClient {- inner: fred::prelude::RedisClient,-}+#[cfg(all(feature = "fred", feature = "redis-rs"))]+compile_error!("Features \"fred\" and \"redis-rs\" are mutually exclusive — enable only one.");-impl std::ops::Deref for RedisClient {- type Target = fred::prelude::RedisClient;- fn deref(&self) -> &Self::Target {- &self.inner- }-}--impl RedisClient {- pub async fn new(- config: fred::types::RedisConfig,- reconnect_policy: fred::types::ReconnectPolicy,- perf: fred::types::PerformanceConfig,- ) -> CustomResult<Self, errors::RedisError> {- let client =- fred::prelude::RedisClient::new(config, Some(perf), None, Some(reconnect_policy));- client.connect();- client- .wait_for_connect()- .await- .change_context(errors::RedisError::RedisConnectionError)?;- Ok(Self { inner: client })- }-}--pub struct SubscriberClient {- inner: fred::clients::SubscriberClient,- pub is_subscriber_handler_spawned: Arc<atomic::AtomicBool>,-}+pub mod constant;+pub mod errors;+pub mod types;-impl SubscriberClient {- pub async fn new(- config: fred::types::RedisConfig,- reconnect_policy: fred::types::ReconnectPolicy,- perf: fred::types::PerformanceConfig,- ) -> CustomResult<Self, errors::RedisError> {- let client =- fred::clients::SubscriberClient::new(config, Some(perf), None, Some(reconnect_policy));- client.connect();- client- .wait_for_connect()- .await- .change_context(errors::RedisError::RedisConnectionError)?;- Ok(Self {- inner: client,- is_subscriber_handler_spawned: Arc::new(atomic::AtomicBool::new(false)),- })- }+#[cfg(feature = "fred")]+mod module {+ pub mod fred;}-impl std::ops::Deref for SubscriberClient {- type Target = fred::clients::SubscriberClient;- fn deref(&self) -> &Self::Target {- &self.inner- }+#[cfg(feature = "redis-rs")]+mod module {+ pub mod redis_rs;}-impl RedisConnectionPool {- /// Create a new Redis connection- pub async fn new(conf: &RedisSettings) -> CustomResult<Self, errors::RedisError> {- let redis_connection_url = match conf.cluster_enabled {- // Fred relies on this format for specifying cluster where the host port is ignored & only query parameters are used for node addresses- // redis-cluster://username:password@host:port?node=bar.com:30002&node=baz.com:30003- true => format!(- "redis-cluster://{}:{}?{}",- conf.host,- conf.port,- conf.cluster_urls- .iter()- .flat_map(|url| vec!["&", url])- .skip(1)- .collect::<String>()- ),- false => format!(- "redis://{}:{}", //URI Schema- conf.host, conf.port,- ),- };- let mut config = fred::types::RedisConfig::from_url(&redis_connection_url)- .change_context(errors::RedisError::RedisConnectionError)?;-- let perf = fred::types::PerformanceConfig {- auto_pipeline: conf.auto_pipeline,- default_command_timeout: std::time::Duration::from_secs(conf.default_command_timeout),- max_feed_count: conf.max_feed_count,- backpressure: fred::types::BackpressureConfig {- disable_auto_backpressure: conf.disable_auto_backpressure,- max_in_flight_commands: conf.max_in_flight_commands,- policy: fred::types::BackpressurePolicy::Drain,- },- broadcast_channel_capacity: conf.broadcast_channel_capacity,- };-- let connection_config = fred::types::ConnectionConfig {- unresponsive: fred::types::UnresponsiveConfig {- max_timeout: Some(std::time::Duration::from_secs(conf.unresponsive_timeout)),- interval: std::time::Duration::from_secs(conf.unresponsive_check_interval),- },- ..fred::types::ConnectionConfig::default()- };+// Re-export the active backend's public types under unified names.+// All external code imports `redis_interface::RedisConnectionPool` etc.+// and is never aware of which backend is active.- if !conf.use_legacy_version {- config.version = fred::types::RespVersion::RESP3;- }- config.tracing = fred::types::TracingConfig::new(true);- config.blocking = fred::types::Blocking::Error;- let reconnect_policy = fred::types::ReconnectPolicy::new_constant(- conf.reconnect_max_attempts,- conf.reconnect_delay,- );-- let subscriber =- SubscriberClient::new(config.clone(), reconnect_policy.clone(), perf.clone()).await?;-- let publisher =- RedisClient::new(config.clone(), reconnect_policy.clone(), perf.clone()).await?;-- let pool = fred::prelude::RedisPool::new(- config,- Some(perf),- Some(connection_config),- Some(reconnect_policy),- conf.pool_size,- )- .change_context(errors::RedisError::RedisConnectionError)?;-- pool.connect();- pool.wait_for_connect()- .await- .change_context(errors::RedisError::RedisConnectionError)?;-- let config = RedisConfig::from(conf);-- Ok(Self {- pool: Arc::new(pool),- config: Arc::new(config),- is_redis_available: Arc::new(atomic::AtomicBool::new(true)),- subscriber: Arc::new(subscriber),- publisher: Arc::new(publisher),- key_prefix: String::default(),- })- }- pub fn clone(&self, key_prefix: &str) -> Self {- Self {- pool: Arc::clone(&self.pool),- key_prefix: key_prefix.to_string(),- config: Arc::clone(&self.config),- subscriber: Arc::clone(&self.subscriber),- publisher: Arc::clone(&self.publisher),- is_redis_available: Arc::clone(&self.is_redis_available),- }- }- pub async fn on_error(&self, tx: tokio::sync::oneshot::Sender<()>) {- use futures::StreamExt;- use tokio_stream::wrappers::BroadcastStream;-- let error_rxs: Vec<BroadcastStream<fred::error::RedisError>> = self- .pool- .clients()- .iter()- .map(|client| BroadcastStream::new(client.error_rx()))- .collect();-- let mut error_rx = futures::stream::select_all(error_rxs);- loop {- if let Some(Ok(error)) = error_rx.next().await {- tracing::error!(?error, "Redis protocol or connection error");- if self.pool.state() == fred::types::ClientState::Disconnected {- if tx.send(()).is_err() {- tracing::error!("The redis shutdown signal sender failed to signal");- }- self.is_redis_available- .store(false, atomic::Ordering::SeqCst);- break;- }- }- }- }-- pub async fn on_unresponsive(&self) {- let _ = self.pool.clients().iter().map(|client| {- client.on_unresponsive(|server| {- tracing::warn!(redis_server =?server.host, "Redis server is unresponsive");- Ok(())- })- });- }-- pub fn get_transaction(&self) -> Transaction {- self.pool.next().multi()- }-}--pub struct RedisConfig {- default_ttl: u32,- default_stream_read_count: u64,- default_hash_ttl: u32,- cluster_enabled: bool,-}+#[cfg(feature = "fred")]+pub use fred::interfaces::{EventInterface, PubsubInterface};+#[cfg(feature = "fred")]+pub use module::fred::{+ PubSubMessage, RedisClient, RedisConfig, RedisConnectionPool, SubscriberClient,+};+#[cfg(feature = "redis-rs")]+pub use module::redis_rs::{+ redis_value_to_option_string, PubSubMessage, PublisherClient, RedisConfig, RedisConn,+ RedisConnectionPool, SubscriberClient,+};-impl From<&RedisSettings> for RedisConfig {- fn from(config: &RedisSettings) -> Self {- Self {- default_ttl: config.default_ttl,- default_stream_read_count: config.stream_read_count,- default_hash_ttl: config.default_hash_ttl,- cluster_enabled: config.cluster_enabled,- }- }-}+pub use self::types::*;#[cfg(test)]-mod test {- use super::*;-- #[test]- fn test_redis_error() {- let x = errors::RedisError::ConsumerGroupClaimFailed.to_string();-- assert_eq!(x, "Failed to set Redis stream message owner".to_string())- }-}+mod test;diff --git a/crates/redis_interface/src/module/fred.rs b/crates/redis_interface/src/module/fred.rsnew file mode 100644index 0000000000..bf42337bdd--- /dev/null+++ b/crates/redis_interface/src/module/fred.rs@@ -0,0 +1,336 @@+//! Fred backend implementation for the redis_interface crate.+//!+//! This module contains the connection pool, subscriber, and publisher+//! implementations using the `fred` crate.++pub mod commands;+pub mod types;++use std::sync::{atomic, Arc};++use common_utils::errors::CustomResult;+use error_stack::ResultExt;+use fred::{+ clients::Transaction,+ interfaces::{ClientLike, EventInterface, PubsubInterface},+ prelude::TransactionInterface,+};+use tracing::Instrument;++use crate::types::RedisValue;++// ─── RedisClient (publisher) ────────────────────────────────────────────────++pub struct RedisClient {+ inner: fred::prelude::RedisClient,+}++impl RedisClient {+ pub async fn new(+ config: fred::types::RedisConfig,+ reconnect_policy: fred::types::ReconnectPolicy,+ perf: fred::types::PerformanceConfig,+ ) -> CustomResult<Self, crate::errors::RedisError> {+ let client =+ fred::prelude::RedisClient::new(config, Some(perf), None, Some(reconnect_policy));+ client.connect();+ client+ .wait_for_connect()+ .await+ .change_context(crate::errors::RedisError::RedisConnectionError)?;+ Ok(Self { inner: client })+ }++ pub async fn publish(+ &self,+ channel: &str,+ message: RedisValue,+ ) -> CustomResult<usize, crate::errors::RedisError> {+ self.inner+ .publish(channel, message.into_inner())+ .await+ .change_context(crate::errors::RedisError::PublishError)+ }+}++impl std::ops::Deref for RedisClient {+ type Target = fred::prelude::RedisClient;+ fn deref(&self) -> &Self::Target {+ &self.inner+ }+}++// ─── SubscriberClient ────────────────────────────────────────────────────────++/// Represents a message received from a pub/sub channel.+#[derive(Clone, Debug)]+pub struct PubSubMessage {+ pub channel: String,+ pub value: RedisValue,+}++pub struct SubscriberClient {+ inner: fred::clients::SubscriberClient,+ pub is_subscriber_handler_spawned: Arc<atomic::AtomicBool>,+ broadcast_sender: tokio::sync::broadcast::Sender<PubSubMessage>,+}++impl SubscriberClient {+ pub async fn new(+ config: fred::types::RedisConfig,+ reconnect_policy: fred::types::ReconnectPolicy,+ perf: fred::types::PerformanceConfig,+ broadcast_capacity: usize,+ ) -> CustomResult<Self, crate::errors::RedisError> {+ let client =+ fred::clients::SubscriberClient::new(config, Some(perf), None, Some(reconnect_policy));+ client.connect();+ client+ .wait_for_connect()+ .await+ .change_context(crate::errors::RedisError::RedisConnectionError)?;+ let (broadcast_sender, _) = tokio::sync::broadcast::channel(broadcast_capacity);++ // Auto-spawn the message forwarding task, just like the redis-rs backend.+ // This reads from fred's internal message broadcast and forwards to our+ // PubSubMessage broadcast channel, so callers can use `message_rx()`.+ let fred_rx = client.message_rx();+ let sender = broadcast_sender.clone();+ tokio::spawn(+ async move {+ Self::forward_messages(fred_rx, sender).await;+ }+ .in_current_span(),+ );++ Ok(Self {+ inner: client,+ is_subscriber_handler_spawned: Arc::new(atomic::AtomicBool::new(false)),+ broadcast_sender,+ })+ }++ /// Background task that reads from fred's internal message stream and+ /// forwards each message to our broadcast channel.+ async fn forward_messages(+ mut fred_rx: tokio::sync::broadcast::Receiver<fred::types::Message>,+ broadcast_sender: tokio::sync::broadcast::Sender<PubSubMessage>,+ ) {+ loop {+ match fred_rx.recv().await {+ Ok(msg) => {+ let channel = msg.channel.to_string();+ let value = RedisValue::new(msg.value);+ if let Err(e) = broadcast_sender.send(PubSubMessage { channel, value }) {+ tracing::warn!(error = ?e, "Failed to broadcast pub/sub message");+ }+ }+ Err(tokio::sync::broadcast::error::RecvError::Closed) => break,+ Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {+ tracing::warn!("fred pub/sub receiver lagged, {n} messages dropped");+ }+ }+ }+ }++ pub fn message_rx(&self) -> tokio::sync::broadcast::Receiver<PubSubMessage> {+ self.broadcast_sender.subscribe()+ }++ pub async fn subscribe(&self, channel: &str) -> CustomResult<(), crate::errors::RedisError> {+ // Spawns a task that will automatically re-subscribe to any channels+ // or channel patterns used by the client (fred-specific).+ self.inner.manage_subscriptions();++ self.inner+ .subscribe(channel)+ .await+ .change_context(crate::errors::RedisError::SubscribeError)+ }++ pub async fn unsubscribe(&self, channel: &str) -> CustomResult<(), crate::errors::RedisError> {+ self.inner+ .unsubscribe(channel)+ .await+ .change_context(crate::errors::RedisError::SubscribeError)+ }+}++impl std::ops::Deref for SubscriberClient {+ type Target = fred::clients::SubscriberClient;+ fn deref(&self) -> &Self::Target {+ &self.inner+ }+}++// ─── Connection pool ─────────────────────────────────────────────────────────++pub struct RedisConnectionPool {+ pub pool: Arc<fred::prelude::RedisPool>,+ pub key_prefix: String,+ pub config: Arc<RedisConfig>,+ pub subscriber: Arc<SubscriberClient>,+ pub publisher: Arc<RedisClient>,+ pub is_redis_available: Arc<atomic::AtomicBool>,+}++impl RedisConnectionPool {+ /// Create a new Redis connection+ pub async fn new(+ conf: &crate::types::RedisSettings,+ ) -> CustomResult<Self, crate::errors::RedisError> {+ let redis_connection_url = match conf.cluster_enabled {+ true => format!(+ "redis-cluster://{}:{}?{}",+ conf.host,+ conf.port,+ conf.cluster_urls+ .iter()+ .flat_map(|url| vec!["&", url])+ .skip(1)+ .collect::<String>()+ ),+ false => format!("redis://{}:{}", conf.host, conf.port,),+ };+ let mut config = fred::types::RedisConfig::from_url(&redis_connection_url)+ .change_context(crate::errors::RedisError::RedisConnectionError)?;++ let perf = fred::types::PerformanceConfig {+ auto_pipeline: conf.auto_pipeline,+ default_command_timeout: std::time::Duration::from_secs(conf.default_command_timeout),+ max_feed_count: conf.max_feed_count,+ backpressure: fred::types::BackpressureConfig {+ disable_auto_backpressure: conf.disable_auto_backpressure,+ max_in_flight_commands: u64::try_from(conf.max_in_flight_commands)+ .unwrap_or(u64::MAX),+ policy: fred::types::BackpressurePolicy::Drain,+ },+ broadcast_channel_capacity: conf.broadcast_channel_capacity,+ };++ let connection_config = fred::types::ConnectionConfig {+ unresponsive: fred::types::UnresponsiveConfig {+ max_timeout: Some(std::time::Duration::from_secs(conf.unresponsive_timeout)),+ interval: std::time::Duration::from_secs(conf.unresponsive_check_interval),+ },+ ..fred::types::ConnectionConfig::default()+ };++ if !conf.use_legacy_version {+ config.version = fred::types::RespVersion::RESP3;+ }+ config.tracing = fred::types::TracingConfig::new(true);+ config.blocking = fred::types::Blocking::Error;+ let reconnect_policy = fred::types::ReconnectPolicy::new_constant(+ conf.reconnect_max_attempts,+ conf.reconnect_delay,+ );++ let subscriber = SubscriberClient::new(+ config.clone(),+ reconnect_policy.clone(),+ perf.clone(),+ conf.broadcast_channel_capacity,+ )+ .await?;++ let publisher =+ RedisClient::new(config.clone(), reconnect_policy.clone(), perf.clone()).await?;++ let pool = fred::prelude::RedisPool::new(+ config,+ Some(perf),+ Some(connection_config),+ Some(reconnect_policy),+ conf.pool_size,+ )+ .change_context(crate::errors::RedisError::RedisConnectionError)?;++ pool.connect();+ pool.wait_for_connect()+ .await+ .change_context(crate::errors::RedisError::RedisConnectionError)?;++ let config = RedisConfig::from(conf);++ Ok(Self {+ pool: Arc::new(pool),+ config: Arc::new(config),+ is_redis_available: Arc::new(atomic::AtomicBool::new(true)),+ subscriber: Arc::new(subscriber),+ publisher: Arc::new(publisher),+ key_prefix: String::default(),+ })+ }++ pub fn clone(&self, key_prefix: &str) -> Self {+ Self {+ pool: Arc::clone(&self.pool),+ key_prefix: key_prefix.to_string(),+ config: Arc::clone(&self.config),+ subscriber: Arc::clone(&self.subscriber),+ publisher: Arc::clone(&self.publisher),+ is_redis_available: Arc::clone(&self.is_redis_available),+ }+ }++ pub async fn on_error(&self, tx: tokio::sync::oneshot::Sender<()>) {+ use futures::StreamExt;+ use tokio_stream::wrappers::BroadcastStream;++ let error_rxs: Vec<BroadcastStream<fred::error::RedisError>> = self+ .pool+ .clients()+ .iter()+ .map(|client| BroadcastStream::new(client.error_rx()))+ .collect();++ let mut error_rx = futures::stream::select_all(error_rxs);+ loop {+ if let Some(Ok(error)) = error_rx.next().await {+ tracing::error!(?error, "Redis protocol or connection error");+ if self.pool.state() == fred::types::ClientState::Disconnected {+ if tx.send(()).is_err() {+ tracing::error!("The redis shutdown signal sender failed to signal");+ }+ self.is_redis_available+ .store(false, atomic::Ordering::SeqCst);+ break;+ }+ }+ }+ }++ pub async fn on_unresponsive(&self) {+ let _ = self.pool.clients().iter().map(|client| {+ client.on_unresponsive(|server| {+ tracing::warn!(redis_server =?server.host, "Redis server is unresponsive");+ Ok(())+ })+ });+ }++ pub fn get_transaction(&self) -> Transaction {+ self.pool.next().multi()+ }+}++// ─── RedisConfig ─────────────────────────────────────────────────────────────++pub struct RedisConfig {+ pub(crate) default_ttl: u32,+ pub(crate) default_stream_read_count: u64,+ pub(crate) default_hash_ttl: u32,+ pub(crate) cluster_enabled: bool,+}++impl From<&crate::types::RedisSettings> for RedisConfig {+ fn from(config: &crate::types::RedisSettings) -> Self {+ Self {+ default_ttl: config.default_ttl,+ default_stream_read_count: config.stream_read_count,+ default_hash_ttl: config.default_hash_ttl,+ cluster_enabled: config.cluster_enabled,+ }+ }+}diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/module/fred/commands.rssimilarity index 62%rename from crates/redis_interface/src/commands.rsrename to crates/redis_interface/src/module/fred/commands.rsindex c54980a3c7..39d48c01c6 100644--- a/crates/redis_interface/src/commands.rs+++ b/crates/redis_interface/src/module/fred/commands.rs@@ -17,17 +17,16 @@ use fred::{prelude::{LuaInterface, RedisErrorKind},types::{Expiration, FromRedis, MultipleIDs, MultipleKeys, MultipleOrderedPairs, MultipleStrings,- MultipleValues, RedisMap, RedisValue, ScanType, Scanner, SetOptions, XCap, XReadResponse,+ MultipleValues, RedisMap, RedisValue, Scanner, SetOptions, XReadResponse,},};-use futures::StreamExt;use tracing::instrument;use crate::{errors,types::{DelReply, HsetnxReply, MsetnxReply, RedisEntryId, RedisKey, SaddReply, SetGetReply,- SetnxReply,+ SetnxReply, StreamEntries, StreamReadResult, StreamTrimConfig,},};@@ -79,16 +78,25 @@ impl super::RedisConnectionPool {.change_context(errors::RedisError::SetFailed)}- pub async fn set_multiple_keys_if_not_exist<V>(+ pub async fn set_multiple_keys_if_not_exist<K, V>(&self,- value: V,+ key_value_pairs: &[(K, V)],) -> CustomResult<MsetnxReply, errors::RedisError>where- V: TryInto<RedisMap> + Debug + Send + Sync,- V::Error: Into<fred::error::RedisError> + Send + Sync,+ K: Clone + Into<String> + Debug + Send + Sync,+ V: Clone + Into<String> + Debug + Send + Sync,{+ let pairs: Vec<(String, String)> = key_value_pairs+ .iter()+ .map(|(k, v)| (k.clone().into(), v.clone().into()))+ .collect();++ let map = RedisMap::try_from(pairs)+ .change_context(errors::RedisError::SetFailed)+ .attach_printable("Failed to convert key-value pairs to fred::types::RedisMap")?;+self.pool- .msetnx(value)+ .msetnx(map).await.change_context(errors::RedisError::SetFailed)}@@ -494,19 +502,28 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]- pub async fn set_hash_fields<V>(+ pub async fn set_hash_fields<F, V>(&self,key: &RedisKey,- values: V,+ field_value_pairs: Vec<(F, V)>,ttl: Option<i64>,) -> CustomResult<(), errors::RedisError>where- V: TryInto<RedisMap> + Debug + Send + Sync,- V::Error: Into<fred::error::RedisError> + Send + Sync,+ F: Into<String> + Debug + Send + Sync,+ V: Into<String> + Debug + Send + Sync,{+ let pairs: Vec<(String, String)> = field_value_pairs+ .into_iter()+ .map(|(f, v)| (f.into(), v.into()))+ .collect();++ let map = RedisMap::try_from(pairs)+ .change_context(errors::RedisError::SetHashFailed)+ .attach_printable("Failed to convert field pairs to fred::types::RedisMap")?;+let output: Result<(), _> = self.pool- .hset(key.tenant_aware_key(self), values)+ .hset(key.tenant_aware_key(self), map).await.change_context(errors::RedisError::SetHashFailed);// setting expiry for the key@@ -593,7 +610,7 @@ impl super::RedisConnectionPool {T: Debug + ToString,{let mut values_after_increment = Vec::with_capacity(fields_to_increment.len());- for (field, increment) in fields_to_increment.iter() {+ for (field, increment) in fields_to_increment {values_after_increment.push(self.pool.hincrby(key.tenant_aware_key(self), field.to_string(), *increment)@@ -612,6 +629,8 @@ impl super::RedisConnectionPool {pattern: &str,count: Option<u32>,) -> CustomResult<Vec<String>, errors::RedisError> {+ use futures::StreamExt;+Ok(self.pool.next()@@ -641,17 +660,20 @@ impl super::RedisConnectionPool {&self,pattern: &RedisKey,count: Option<u32>,- scan_type: Option<ScanType>,+ scan_type: Option<crate::types::RedisScanType>,) -> CustomResult<Vec<String>, errors::RedisError> {+ use futures::StreamExt;++ let fred_scan_type = scan_type.map(fred::types::ScanType::from);+Ok(self.pool.next()- .scan(pattern.tenant_aware_key(self), count, scan_type)+ .scan(pattern.tenant_aware_key(self), count, fred_scan_type).filter_map(|value| async move {match value {Ok(mut v) => {let v = v.take_results()?;-let v: Vec<String> =v.into_iter().filter_map(|val| val.into_string()).collect();Some(futures::stream::iter(v))@@ -787,47 +809,61 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]- pub async fn stream_append_entry<F>(+ pub async fn stream_append_entry<F, V>(&self,stream: &RedisKey,entry_id: &RedisEntryId,- fields: F,+ fields: Vec<(F, V)>,) -> CustomResult<(), errors::RedisError>where- F: TryInto<MultipleOrderedPairs> + Debug + Send + Sync,- F::Error: Into<fred::error::RedisError> + Send + Sync,+ F: Into<String> + Debug + Send + Sync,+ V: Into<String> + Debug + Send + Sync,{+ let pairs: Vec<(String, String)> = fields+ .into_iter()+ .map(|(f, v)| (f.into(), v.into()))+ .collect();++ let fred_fields = MultipleOrderedPairs::try_from(pairs)+ .change_context(errors::RedisError::StreamAppendFailed)+ .attach_printable(+ "Failed to convert field pairs to fred::types::MultipleOrderedPairs",+ )?;+self.pool- .xadd(stream.tenant_aware_key(self), false, None, entry_id, fields)+ .xadd(+ stream.tenant_aware_key(self),+ false,+ None,+ entry_id,+ fred_fields,+ ).await.change_context(errors::RedisError::StreamAppendFailed)}#[instrument(level = "DEBUG", skip(self))]- pub async fn stream_delete_entries<Ids>(+ pub async fn stream_delete_entries(&self,stream: &RedisKey,- ids: Ids,- ) -> CustomResult<usize, errors::RedisError>- where- Ids: Into<MultipleStrings> + Debug + Send + Sync,- {+ ids: Vec<String>,+ ) -> CustomResult<usize, errors::RedisError> {+ let fred_ids: MultipleStrings = ids.into();self.pool- .xdel(stream.tenant_aware_key(self), ids)+ .xdel(stream.tenant_aware_key(self), fred_ids).await.change_context(errors::RedisError::StreamDeleteFailed)}#[instrument(level = "DEBUG", skip(self))]- pub async fn stream_trim_entries<C>(+ pub async fn stream_trim_entries(&self,stream: &RedisKey,- xcap: C,- ) -> CustomResult<usize, errors::RedisError>- where- C: TryInto<XCap> + Debug + Send + Sync,- C::Error: Into<fred::error::RedisError> + Send + Sync,- {+ config: StreamTrimConfig,+ ) -> CustomResult<usize, errors::RedisError> {+ let xcap = fred::types::XCap::try_from(config)+ .change_context(errors::RedisError::StreamTrimFailed)+ .attach_printable("Failed to convert StreamTrimConfig to fred::types::XCap")?;self.pool.xtrim(stream.tenant_aware_key(self), xcap).await@@ -835,17 +871,15 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]- pub async fn stream_acknowledge_entries<Ids>(+ pub async fn stream_acknowledge_entries(&self,stream: &RedisKey,group: &str,- ids: Ids,- ) -> CustomResult<usize, errors::RedisError>- where- Ids: Into<MultipleIDs> + Debug + Send + Sync,- {+ ids: Vec<String>,+ ) -> CustomResult<usize, errors::RedisError> {+ let fred_ids: MultipleIDs = ids.into();self.pool- .xack(stream.tenant_aware_key(self), group, ids)+ .xack(stream.tenant_aware_key(self), group, fred_ids).await.change_context(errors::RedisError::StreamAcknowledgeFailed)}@@ -861,34 +895,22 @@ impl super::RedisConnectionPool {.change_context(errors::RedisError::GetLengthFailed)}- pub fn get_keys_with_prefix<K>(&self, keys: K) -> MultipleKeys- where- K: Into<MultipleKeys> + Debug + Send + Sync,- {- let multiple_keys: MultipleKeys = keys.into();- let res = multiple_keys- .inner()- .iter()- .filter_map(|key| key.as_str().map(RedisKey::from))- .map(|k: RedisKey| k.tenant_aware_key(self))- .collect::<Vec<_>>();-+ fn get_keys_with_prefix(&self, streams: &[RedisKey]) -> MultipleKeys {+ let res: Vec<String> = streams.iter().map(|k| k.tenant_aware_key(self)).collect();MultipleKeys::from(res)}#[instrument(level = "DEBUG", skip(self))]- pub async fn stream_read_entries<K, Ids>(+ pub async fn stream_read_entries(&self,- streams: K,- ids: Ids,+ streams: &[RedisKey],+ ids: Vec<String>,read_count: Option<u64>,- ) -> CustomResult<XReadResponse<String, String, String, String>, errors::RedisError>- where- K: Into<MultipleKeys> + Debug + Send + Sync,- Ids: Into<MultipleIDs> + Debug + Send + Sync,- {+ ) -> CustomResult<StreamReadResult, errors::RedisError> {let strms = self.get_keys_with_prefix(streams);- self.pool+ let ids: MultipleIDs = ids.into();+ let reply: XReadResponse<String, String, String, String> = self+ .pool.xread_map(Some(read_count.unwrap_or(self.config.default_stream_read_count)),None,@@ -901,48 +923,87 @@ impl super::RedisConnectionPool {report!(err).change_context(errors::RedisError::StreamEmptyOrNotAvailable)}_ => report!(err).change_context(errors::RedisError::StreamReadFailed),+ })?;++ Ok(reply+ .into_iter()+ .map(|(stream_key, stream_entries)| {+ let parsed_entries: StreamEntries = stream_entries+ .into_iter()+ .map(|(entry_id, field_pairs)| {+ // Convert raw fred field values into the common RedisValue wrapper type.+ // This preserves all data (strings, nulls, binary, etc.) in a backend-neutral form.+ let fields_by_redis_value: std::collections::HashMap<+ String,+ crate::RedisValue,+ > = field_pairs+ .into_iter()+ .map(|(field_name, field_value)| {+ (field_name, crate::RedisValue::new(field_value.into()))+ })+ .collect();+ (entry_id, fields_by_redis_value)+ })+ .collect();+ (stream_key, parsed_entries)})+ .collect())}#[instrument(level = "DEBUG", skip(self))]- pub async fn stream_read_with_options<K, Ids>(+ pub async fn stream_read_with_options(&self,- streams: K,- ids: Ids,+ streams: &[RedisKey],+ ids: Vec<String>,count: Option<u64>,- block: Option<u64>, // timeout in milliseconds- group: Option<(&str, &str)>, // (group_name, consumer_name)- ) -> CustomResult<XReadResponse<String, String, String, Option<String>>, errors::RedisError>- where- K: Into<MultipleKeys> + Debug + Send + Sync,- Ids: Into<MultipleIDs> + Debug + Send + Sync,- {- match group {+ block: Option<u64>,+ group: Option<(&str, &str)>,+ ) -> CustomResult<StreamReadResult, errors::RedisError> {+ let strms = self.get_keys_with_prefix(streams);+ let ids: MultipleIDs = ids.into();++ let reply: XReadResponse<String, String, String, Option<String>> = match group {Some((group_name, consumer_name)) => {self.pool- .xreadgroup_map(- group_name,- consumer_name,- count,- block,- false,- self.get_keys_with_prefix(streams),- ids,- )- .await- }- None => {- self.pool- .xread_map(count, block, self.get_keys_with_prefix(streams), ids)+ .xreadgroup_map(group_name, consumer_name, count, block, false, strms, ids).await}+ None => self.pool.xread_map(count, block, strms, ids).await,}.map_err(|err| match err.kind() {RedisErrorKind::NotFound | RedisErrorKind::Parse => {report!(err).change_context(errors::RedisError::StreamEmptyOrNotAvailable)}_ => report!(err).change_context(errors::RedisError::StreamReadFailed),- })+ })?;++ Ok(reply+ .into_iter()+ .map(|(stream_key, stream_entries)| {+ let parsed_entries: StreamEntries = stream_entries+ .into_iter()+ .map(|(entry_id, optional_field_pairs)| {+ // Wrap fred's field values (Option<String>) into RedisValue.+ // If the field has no value, we store Null to preserve the entry's presence.+ let fields_by_redis_value: std::collections::HashMap<+ String,+ crate::RedisValue,+ > = optional_field_pairs+ .into_iter()+ .map(|(field_name, maybe_field_value)| {+ let redis_value_inner = match maybe_field_value {+ Some(string_value) => RedisValue::String(string_value.into()),+ None => RedisValue::Null,+ };+ (field_name, crate::RedisValue::new(redis_value_inner))+ })+ .collect();+ (entry_id, fields_by_redis_value)+ })+ .collect();+ (stream_key, parsed_entries)+ })+ .collect())}#[instrument(level = "DEBUG", skip(self))]@@ -1022,11 +1083,13 @@ impl super::RedisConnectionPool {&self,stream: &RedisKey,group: &str,- ) -> CustomResult<usize, errors::RedisError> {- self.pool+ ) -> CustomResult<crate::types::ConsumerGroupDestroyReply, errors::RedisError> {+ let reply: crate::types::ConsumerGroupDestroyReply = self+ .pool.xgroup_destroy(stream.tenant_aware_key(self), group).await- .change_context(errors::RedisError::ConsumerGroupDestroyFailed)+ .change_context(errors::RedisError::ConsumerGroupDestroyFailed)?;+ Ok(reply)}// the number of pending messages that the consumer had before it was deleted@@ -1050,32 +1113,34 @@ impl super::RedisConnectionPool {group: &str,id: &RedisEntryId,) -> CustomResult<String, errors::RedisError> {+ let id_str = id.to_stream_id();self.pool- .xgroup_setid(stream.tenant_aware_key(self), group, id)+ .xgroup_setid::<(), _, _, _>(stream.tenant_aware_key(self), group, &id_str).await- .change_context(errors::RedisError::ConsumerGroupSetIdFailed)+ .change_context(errors::RedisError::ConsumerGroupSetIdFailed)?;+ Ok(id_str)}#[instrument(level = "DEBUG", skip(self))]- pub async fn consumer_group_set_message_owner<Ids, R>(+ pub async fn consumer_group_set_message_owner<R>(&self,stream: &RedisKey,group: &str,consumer: &str,min_idle_time: u64,- ids: Ids,+ ids: Vec<String>,) -> CustomResult<R, errors::RedisError>where- Ids: Into<MultipleIDs> + Debug + Send + Sync,R: FromRedis + Unpin + Send + 'static,{+ let fred_ids: MultipleIDs = ids.into();self.pool.xclaim(stream.tenant_aware_key(self),group,consumer,min_idle_time,- ids,+ fred_ids,None,None,None,@@ -1202,491 +1267,3 @@ impl super::RedisConnectionPool {}}}--#[cfg(test)]-mod tests {- use std::collections::HashMap;-- use crate::{errors::RedisError, RedisConnectionPool, RedisEntryId, RedisSettings};-- #[tokio::test]- async fn test_consumer_group_create() {- let is_invalid_redis_entry_error = tokio::task::spawn_blocking(move || {- futures::executor::block_on(async {- // Arrange- let redis_conn = RedisConnectionPool::new(&RedisSettings::default())- .await- .expect("failed to create redis connection pool");-- // Act- let result1 = redis_conn- .consumer_group_create(&"TEST1".into(), "GTEST", &RedisEntryId::AutoGeneratedID)- .await;-- let result2 = redis_conn- .consumer_group_create(- &"TEST3".into(),- "GTEST",- &RedisEntryId::UndeliveredEntryID,- )- .await;-- // Assert Setup- *result1.unwrap_err().current_context() == RedisError::InvalidRedisEntryId- && *result2.unwrap_err().current_context() == RedisError::InvalidRedisEntryId- })- })- .await- .expect("Spawn block failure");-- assert!(is_invalid_redis_entry_error);- }-- #[tokio::test]- async fn test_delete_existing_key_success() {- let is_success = tokio::task::spawn_blocking(move || {- futures::executor::block_on(async {- // Arrange- let pool = RedisConnectionPool::new(&RedisSettings::default())- .await- .expect("failed to create redis connection pool");- let _ = pool.set_key(&"key".into(), "value".to_string()).await;-- // Act- let result = pool.delete_key(&"key".into()).await;-- // Assert setup- result.is_ok()- })- })- .await- .expect("Spawn block failure");-- assert!(is_success);- }- #[tokio::test]- async fn test_delete_non_existing_key_success() {- let is_success = tokio::task::spawn_blocking(move || {- futures::executor::block_on(async {- // Arrange- let pool = RedisConnectionPool::new(&RedisSettings::default())- .await- .expect("failed to create redis connection pool");-- // Act- let result = pool.delete_key(&"key not exists".into()).await;-- // Assert Setup- result.is_ok()- })- })- .await- .expect("Spawn block failure");- assert!(is_success);- }-- #[tokio::test]- async fn test_setting_keys_using_scripts() {- let is_success = tokio::task::spawn_blocking(move || {- futures::executor::block_on(async {- // Arrange- let pool = RedisConnectionPool::new(&RedisSettings::default())- .await- .expect("failed to create redis connection pool");- let lua_script = r#"- for i = 1, #KEYS do- redis.call("INCRBY", KEYS[i], ARGV[i])- end- return- "#;- let mut keys_and_values = HashMap::new();- for i in 0..10 {- keys_and_values.insert(format!("key{i}"), i);- }-- let key = keys_and_values.keys().cloned().collect::<Vec<_>>();- let values = keys_and_values- .values()- .map(|val| val.to_string())- .collect::<Vec<String>>();-- // Act- let result = pool- .evaluate_redis_script::<_, ()>(lua_script, key, values)- .await;-- // Assert Setup- result.is_ok()- })- })- .await- .expect("Spawn block failure");-- assert!(is_success);- }- #[tokio::test]- async fn test_getting_keys_using_scripts() {- let is_success = tokio::task::spawn_blocking(move || {- futures::executor::block_on(async {- // Arrange- let pool = RedisConnectionPool::new(&RedisSettings::default())- .await- .expect("failed to create redis connection pool");-- // First set some keys- for i in 0..3 {- let key = format!("script_test_key{i}").into();- let _ = pool.set_key(&key, format!("value{i}")).await;- }-- let lua_script = r#"- local results = {}- for i = 1, #KEYS do- results[i] = redis.call("GET", KEYS[i])- end- return results- "#;-- let keys = vec![- "script_test_key0".to_string(),- "script_test_key1".to_string(),- "script_test_key2".to_string(),- ];-- // Act- let result = pool- .evaluate_redis_script::<_, Vec<String>>(lua_script, keys, vec![""])- .await;-- // Assert Setup- result.is_ok()- })- })- .await- .expect("Spawn block failure");-- assert!(is_success);- }-- #[tokio::test]- async fn test_set_key_if_not_exists_and_get_value_new_key() {- let is_success = tokio::task::spawn_blocking(move || {- futures::executor::block_on(async {- // Arrange- let pool = RedisConnectionPool::new(&RedisSettings::default())- .await- .expect("failed to create redis connection pool");- let key = "test_new_key_string".into();- let value = "test_value".to_string();-- // Act- let result = pool- .set_key_if_not_exists_and_get_value(&key, value.clone(), Some(30))- .await;-- // Assert- match result {- Ok(crate::types::SetGetReply::ValueSet(returned_value)) => {- returned_value == value- }- _ => false,- }- })- })- .await- .expect("Spawn block failure");-- assert!(is_success);- }-- #[tokio::test]- async fn test_set_key_if_not_exists_and_get_value_existing_key() {- let is_success = tokio::task::spawn_blocking(move || {- futures::executor::block_on(async {- // Arrange- let pool = RedisConnectionPool::new(&RedisSettings::default())- .await- .expect("failed to create redis connection pool");- let key = "test_existing_key_string".into();- let initial_value = "initial_value".to_string();- let new_value = "new_value".to_string();-- // First, set an initial value using regular set_key- let _ = pool.set_key(&key, initial_value.clone()).await;-- // Act - try to set a new value (should fail and return existing value)- let result = pool- .set_key_if_not_exists_and_get_value(&key, new_value, Some(30))- .await;-- // Assert- match result {- Ok(crate::types::SetGetReply::ValueExists(returned_value)) => {- returned_value == initial_value- }- _ => false,- }- })- })- .await- .expect("Spawn block failure");-- assert!(is_success);- }-- #[tokio::test]- async fn test_set_key_if_not_exists_and_get_value_with_default_ttl() {- let is_success = tokio::task::spawn_blocking(move || {- futures::executor::block_on(async {- // Arrange- let pool = RedisConnectionPool::new(&RedisSettings::default())- .await- .expect("failed to create redis connection pool");- let key = "test_default_ttl_key_string".into();- let value = "test_value".to_string();-- // Act - use None for TTL to test default behavior- let result = pool- .set_key_if_not_exists_and_get_value(&key, value.clone(), None)- .await;-- // Assert- match result {- Ok(crate::types::SetGetReply::ValueSet(returned_value)) => {- returned_value == value- }- _ => false,- }- })- })- .await- .expect("Spawn block failure");-- assert!(is_success);- }-- #[tokio::test]- async fn test_set_key_if_not_exists_and_get_value_concurrent_access() {- let is_success = tokio::task::spawn_blocking(move || {- futures::executor::block_on(async {- // Arrange- let pool = RedisConnectionPool::new(&RedisSettings::default())- .await- .expect("failed to create redis connection pool");- let key_name = "test_concurrent_key_string";- let value1 = "value1".to_string();- let value2 = "value2".to_string();-- // Act - simulate concurrent access- let pool1 = pool.clone("");- let pool2 = pool.clone("");- let key1 = key_name.into();- let key2 = key_name.into();-- let (result1, result2) = tokio::join!(- pool1.set_key_if_not_exists_and_get_value(&key1, value1, Some(30)),- pool2.set_key_if_not_exists_and_get_value(&key2, value2, Some(30))- );-- // Assert - one should succeed with ValueSet, one should fail with ValueExists- let result1_is_set = matches!(result1, Ok(crate::types::SetGetReply::ValueSet(_)));- let result2_is_set = matches!(result2, Ok(crate::types::SetGetReply::ValueSet(_)));- let result1_is_exists =- matches!(result1, Ok(crate::types::SetGetReply::ValueExists(_)));- let result2_is_exists =- matches!(result2, Ok(crate::types::SetGetReply::ValueExists(_)));-- // Exactly one should be ValueSet and one should be ValueExists- (result1_is_set && result2_is_exists) || (result1_is_exists && result2_is_set)- })- })- .await- .expect("Spawn block failure");-- assert!(is_success);- }-- #[tokio::test]- async fn test_get_multiple_keys_success() {- let is_success = tokio::task::spawn_blocking(move || {- futures::executor::block_on(async {- // Arrange- let pool = RedisConnectionPool::new(&RedisSettings::default())- .await- .expect("failed to create redis connection pool");-- // Set up test data- let keys = vec![- "multi_test_key1".into(),- "multi_test_key2".into(),- "multi_test_key3".into(),- ];- let values = ["value1", "value2", "value3"];-- // Set the keys- for (key, value) in keys.iter().zip(values.iter()) {- let _ = pool.set_key(key, value.to_string()).await;- }-- // Act- let result = pool.get_multiple_keys::<String>(&keys).await;-- // Assert- match result {- Ok(retrieved_values) => {- retrieved_values.len() == 3- && retrieved_values.first() == Some(&Some("value1".to_string()))- && retrieved_values.get(1) == Some(&Some("value2".to_string()))- && retrieved_values.get(2) == Some(&Some("value3".to_string()))- }- _ => false,- }- })- })- .await- .expect("Spawn block failure");-- assert!(is_success);- }-- #[tokio::test]- async fn test_get_multiple_keys_with_missing_keys() {- let is_success = tokio::task::spawn_blocking(move || {- futures::executor::block_on(async {- // Arrange- let pool = RedisConnectionPool::new(&RedisSettings::default())- .await- .expect("failed to create redis connection pool");-- let keys = vec![- "existing_key".into(),- "non_existing_key".into(),- "another_existing_key".into(),- ];-- // Set only some keys- let _ = pool- .set_key(- keys.first().expect("should not be none"),- "value1".to_string(),- )- .await;- let _ = pool- .set_key(- keys.get(2).expect("should not be none"),- "value3".to_string(),- )- .await;-- // Act- let result = pool.get_multiple_keys::<String>(&keys).await;-- // Assert- match result {- Ok(retrieved_values) => {- retrieved_values.len() == 3- && *retrieved_values.first().expect("should not be none")- == Some("value1".to_string())- && retrieved_values.get(1).is_some_and(|v| v.is_none())- && *retrieved_values.get(2).expect("should not be none")- == Some("value3".to_string())- }- _ => false,- }- })- })- .await- .expect("Spawn block failure");-- assert!(is_success);- }-- #[tokio::test]- async fn test_get_multiple_keys_empty_input() {- let is_success = tokio::task::spawn_blocking(move || {- futures::executor::block_on(async {- // Arrange- let pool = RedisConnectionPool::new(&RedisSettings::default())- .await- .expect("failed to create redis connection pool");-- let keys: Vec<crate::types::RedisKey> = vec![];-- // Act- let result = pool.get_multiple_keys::<String>(&keys).await;-- // Assert- match result {- Ok(retrieved_values) => retrieved_values.is_empty(),- _ => false,- }- })- })- .await- .expect("Spawn block failure");-- assert!(is_success);- }-- #[tokio::test]- async fn test_get_and_deserialize_multiple_keys() {- let is_success = tokio::task::spawn_blocking(move || {- futures::executor::block_on(async {- // Arrange- let pool = RedisConnectionPool::new(&RedisSettings::default())- .await- .expect("failed to create redis connection pool");-- #[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug, Clone)]- struct TestData {- id: u32,- name: String,- }-- let test_data = [- TestData {- id: 1,- name: "test1".to_string(),- },- TestData {- id: 2,- name: "test2".to_string(),- },- ];-- let keys = vec![- "serialize_test_key1".into(),- "serialize_test_key2".into(),- "non_existing_serialize_key".into(),- ];-- // Set serialized data for first two keys- for (i, data) in test_data.iter().enumerate() {- let _ = pool- .serialize_and_set_key(keys.get(i).expect("should not be none"), data)- .await;- }-- // Act- let result = pool- .get_and_deserialize_multiple_keys::<TestData>(&keys, "TestData")- .await;-- // Assert- match result {- Ok(retrieved_data) => {- retrieved_data.len() == 3- && retrieved_data.first() == Some(&Some(test_data[0].clone()))- && retrieved_data.get(1) == Some(&Some(test_data[1].clone()))- && retrieved_data.get(2) == Some(&None)- }- _ => false,- }- })- })- .await- .expect("Spawn block failure");-- assert!(is_success);- }-}diff --git a/crates/redis_interface/src/module/fred/types.rs b/crates/redis_interface/src/module/fred/types.rsnew file mode 100644index 0000000000..c3bea66645--- /dev/null+++ b/crates/redis_interface/src/module/fred/types.rs@@ -0,0 +1,223 @@+//! Fred-specific trait implementations for the shared types.+//!+//! These compile only when `redis-rs` is **not** active — i.e. when the+//! `fred-rs` feature is enabled instead. This file is the "else" branch:+//! redis-rs is the primary backend; fred is the fallback.++use crate::types::{+ ConsumerGroupDestroyReply, DelReply, HsetnxReply, MsetnxReply, RedisEntryId, RedisScanType,+ RedisValue, SaddReply, SetnxReply, StreamCapKind, StreamCapTrim, StreamTrimConfig,+};++// ─── RedisValue impls ────────────────────────────────────────────────────────++impl RedisValue {+ pub fn new(value: fred::types::RedisValue) -> Self {+ Self { inner: value }+ }++ pub fn from_bytes(val: Vec<u8>) -> Self {+ Self {+ inner: fred::types::RedisValue::Bytes(val.into()),+ }+ }++ pub fn from_string(value: String) -> Self {+ Self {+ inner: fred::types::RedisValue::String(value.into()),+ }+ }++ pub fn as_bytes(&self) -> Option<&[u8]> {+ match &self.inner {+ fred::types::RedisValue::Bytes(b) => Some(b.as_ref()),+ fred::types::RedisValue::String(s) => Some(s.as_bytes()),+ _ => None,+ }+ }++ pub fn as_string(&self) -> Option<String> {+ match &self.inner {+ fred::types::RedisValue::String(s) => Some(s.to_string()),+ fred::types::RedisValue::Bytes(b) => String::from_utf8(b.to_vec()).ok(),+ _ => None,+ }+ }++ pub(crate) fn into_inner(self) -> fred::types::RedisValue {+ self.inner+ }+}++impl std::ops::Deref for RedisValue {+ type Target = fred::types::RedisValue;+ fn deref(&self) -> &Self::Target {+ &self.inner+ }+}++impl From<RedisValue> for fred::types::RedisValue {+ fn from(v: RedisValue) -> Self {+ v.inner+ }+}++// ─── RedisEntryId → XID ──────────────────────────────────────────────────────++impl From<RedisEntryId> for fred::types::XID {+ fn from(id: RedisEntryId) -> Self {+ match id {+ RedisEntryId::UserSpecifiedID {+ milliseconds,+ sequence_number,+ } => Self::Manual(fred::bytes_utils::format_bytes!(+ "{milliseconds}-{sequence_number}"+ )),+ RedisEntryId::AutoGeneratedID => Self::Auto,+ RedisEntryId::AfterLastID => Self::Max,+ RedisEntryId::UndeliveredEntryID => Self::NewInGroup,+ }+ }+}++impl From<&RedisEntryId> for fred::types::XID {+ fn from(id: &RedisEntryId) -> Self {+ match id {+ RedisEntryId::UserSpecifiedID {+ milliseconds,+ sequence_number,+ } => Self::Manual(fred::bytes_utils::format_bytes!(+ "{milliseconds}-{sequence_number}"+ )),+ RedisEntryId::AutoGeneratedID => Self::Auto,+ RedisEntryId::AfterLastID => Self::Max,+ RedisEntryId::UndeliveredEntryID => Self::NewInGroup,+ }+ }+}++// ─── Reply type trait impls ──────────────────────────────────────────────────++impl fred::types::FromRedis for SetnxReply {+ fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> {+ match value {+ fred::types::RedisValue::String(_) => Ok(Self::KeySet),+ fred::types::RedisValue::Null => Ok(Self::KeyNotSet),+ _ => Err(fred::error::RedisError::new(+ fred::error::RedisErrorKind::Unknown,+ "Unexpected SETNX reply",+ )),+ }+ }+}++impl fred::types::FromRedis for HsetnxReply {+ fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> {+ match value {+ fred::types::RedisValue::Integer(1) => Ok(Self::KeySet),+ fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotSet),+ _ => Err(fred::error::RedisError::new(+ fred::error::RedisErrorKind::Unknown,+ "Unexpected HSETNX reply",+ )),+ }+ }+}++impl fred::types::FromRedis for MsetnxReply {+ fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> {+ match value {+ fred::types::RedisValue::Integer(1) => Ok(Self::KeysSet),+ fred::types::RedisValue::Integer(0) => Ok(Self::KeysNotSet),+ _ => Err(fred::error::RedisError::new(+ fred::error::RedisErrorKind::Unknown,+ "Unexpected MSETNX reply",+ )),+ }+ }+}++impl fred::types::FromRedis for DelReply {+ fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> {+ match value {+ fred::types::RedisValue::Integer(1) => Ok(Self::KeyDeleted),+ fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotDeleted),+ _ => Err(fred::error::RedisError::new(+ fred::error::RedisErrorKind::Unknown,+ "Unexpected DEL reply",+ )),+ }+ }+}++impl fred::types::FromRedis for SaddReply {+ fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> {+ match value {+ fred::types::RedisValue::Integer(1) => Ok(Self::KeySet),+ fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotSet),+ _ => Err(fred::error::RedisError::new(+ fred::error::RedisErrorKind::Unknown,+ "Unexpected SADD reply",+ )),+ }+ }+}++impl fred::types::FromRedis for ConsumerGroupDestroyReply {+ fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> {+ match value {+ // XGROUP DESTROY returns 1 if the group was destroyed, 0 if it didn't exist+ fred::types::RedisValue::Integer(1) => Ok(Self::Destroyed),+ fred::types::RedisValue::Integer(0) => Ok(Self::NotFound),+ _ => Err(fred::error::RedisError::new(+ fred::error::RedisErrorKind::Unknown,+ "Unexpected XGROUP DESTROY reply",+ )),+ }+ }+}++// ─── StreamCapKind / StreamCapTrim conversions ───────────────────────────────++impl From<StreamCapKind> for fred::types::XCapKind {+ fn from(item: StreamCapKind) -> Self {+ match item {+ StreamCapKind::MaxLen => Self::MaxLen,+ StreamCapKind::MinID => Self::MinID,+ }+ }+}++impl From<StreamCapTrim> for fred::types::XCapTrim {+ fn from(item: StreamCapTrim) -> Self {+ match item {+ StreamCapTrim::Exact => Self::Exact,+ StreamCapTrim::AlmostExact => Self::AlmostExact,+ }+ }+}++// ─── StreamTrimConfig → XCap ─────────────────────────────────────────────────++impl TryFrom<StreamTrimConfig> for fred::types::XCap {+ type Error = fred::error::RedisError;++ fn try_from(config: StreamTrimConfig) -> Result<Self, Self::Error> {+ (config.kind, config.trim, config.threshold).try_into()+ }+}++// ─── RedisScanType → fred ScanType ──────────────────────────────────────────++impl From<RedisScanType> for fred::types::ScanType {+ fn from(item: RedisScanType) -> Self {+ match item {+ RedisScanType::String => Self::String,+ RedisScanType::List => Self::List,+ RedisScanType::Set => Self::Set,+ RedisScanType::Zset => Self::ZSet,+ RedisScanType::Hash => Self::Hash,+ RedisScanType::Stream => Self::Stream,+ }+ }+}diff --git a/crates/redis_interface/src/module/redis_rs.rs b/crates/redis_interface/src/module/redis_rs.rsnew file mode 100644index 0000000000..dc1a2f7ecb--- /dev/null+++ b/crates/redis_interface/src/module/redis_rs.rs@@ -0,0 +1,677 @@+//! Redis-rs backend implementation for the redis_interface crate.+//!+//! This module contains the connection pool, subscriber, and publisher+//! implementations using the `redis` crate (redis-rs).++pub mod commands;+pub mod types;++use std::sync::{atomic, Arc};++use common_utils::errors::CustomResult;+use error_stack::ResultExt;+use redis::AsyncCommands;+use tracing::Instrument;+pub use types::redis_value_to_option_string;++// ─── Cluster abstraction ────────────────────────────────────────────────────++/// An abstraction over standalone and cluster Redis connections.+/// Both variants implement the same async command interface, so all+/// Redis operations work transparently on either.+#[derive(Clone)]+pub enum RedisConn {+ Standalone(redis::aio::ConnectionManager),+ Cluster(redis::cluster_async::ClusterConnection),+}++impl redis::aio::ConnectionLike for RedisConn {+ fn req_packed_command<'a>(+ &'a mut self,+ cmd: &'a redis::Cmd,+ ) -> redis::RedisFuture<'a, redis::Value> {+ match self {+ Self::Standalone(c) => c.req_packed_command(cmd),+ Self::Cluster(c) => c.req_packed_command(cmd),+ }+ }++ fn req_packed_commands<'a>(+ &'a mut self,+ cmd: &'a redis::Pipeline,+ offset: usize,+ count: usize,+ ) -> redis::RedisFuture<'a, Vec<redis::Value>> {+ match self {+ Self::Standalone(c) => c.req_packed_commands(cmd, offset, count),+ Self::Cluster(c) => c.req_packed_commands(cmd, offset, count),+ }+ }++ fn get_db(&self) -> i64 {+ match self {+ Self::Standalone(c) => c.get_db(),+ Self::Cluster(c) => c.get_db(),+ }+ }+}++// ─── Subscriber client with auto-resubscribe ────────────────────────────────++/// A pub/sub subscriber that uses RESP3 push messages for both standalone and cluster.+///+/// Subscribe/unsubscribe calls go directly to the Redis connection.+/// A background task reads push messages and forwards them to a broadcast channel.+pub struct SubscriberClient {+ connection: SubscriberBackend,+ broadcast_sender: tokio::sync::broadcast::Sender<PubSubMessage>,+ pub is_subscriber_handler_spawned: Arc<atomic::AtomicBool>,+}++enum SubscriberBackend {+ Standalone {+ connection: redis::aio::ConnectionManager,+ },+ Cluster {+ // Mutex required because ClusterConnection::subscribe/unsubscribe+ // needs &mut self, unlike ConnectionManager which can be cloned+ connection: tokio::sync::Mutex<redis::cluster_async::ClusterConnection>,+ },+}++/// Represents a message received from a pub/sub channel.+#[derive(Clone, Debug)]+pub struct PubSubMessage {+ pub channel: String,+ pub value: crate::types::RedisValue,+}++impl PubSubMessage {+ /// Attempts to extract a [`PubSubMessage`] from a RESP3 push info.+ ///+ /// Returns `None` if the push kind is not `Message`, or if the+ /// channel name or payload cannot be extracted from the data.+ fn from_push_info(push_info: &redis::PushInfo) -> Option<Self> {+ if push_info.kind != redis::PushKind::Message {+ return None;+ }++ // RESP3 pub/sub message format:+ // data[0] = channel name (string)+ // data[1] = message payload (any Value)+ let channel_value = push_info.data.first()?;+ let channel = match channel_value {+ redis::Value::BulkString(bytes) => String::from_utf8_lossy(bytes).into_owned(),+ redis::Value::SimpleString(string) => string.clone(),+ redis::Value::VerbatimString { text, .. } => text.clone(),+ // Non-string variants are not valid channel names in the RESP3+ // pub/sub protocol. Reject the message rather than fabricating+ // a default channel name.+ redis::Value::Nil+ | redis::Value::Int(_)+ | redis::Value::Okay+ | redis::Value::Double(_)+ | redis::Value::Boolean(_)+ | redis::Value::BigNumber(_)+ | redis::Value::Array(_)+ | redis::Value::Map(_)+ | redis::Value::Set(_)+ | redis::Value::Attribute { .. }+ | redis::Value::Push { .. }+ | redis::Value::ServerError(_) => {+ tracing::warn!(+ ?channel_value,+ "Pub/sub channel name is not a string variant — malformed push data"+ );+ return None;+ }+ // Catch-all for future variants added to the non-exhaustive enum+ _ => {+ tracing::warn!(+ ?channel_value,+ "Unknown Value variant in pub/sub channel name — malformed push data"+ );+ return None;+ }+ };++ if channel.is_empty() {+ tracing::warn!("Pub/sub channel name is empty — malformed push data");+ return None;+ }++ let payload = match push_info.data.get(1) {+ Some(value) => value.clone(),+ None => {+ tracing::warn!(+ ?push_info,+ "Pub/sub message has no payload — malformed push data"+ );+ return None;+ }+ };++ Some(Self {+ channel,+ value: crate::types::RedisValue::new(payload),+ })+ }+}++impl SubscriberClient {+ pub(crate) async fn new(+ conf: &crate::types::RedisSettings,+ ) -> CustomResult<Self, crate::errors::RedisError> {+ let (push_sender, push_receiver) =+ tokio::sync::broadcast::channel::<redis::PushInfo>(conf.broadcast_channel_capacity);++ let connection = match conf.cluster_enabled {+ true => Self::create_cluster_backend(conf, push_sender.clone()).await?,+ false => Self::create_standalone_backend(conf, push_sender.clone()).await?,+ };++ let (broadcast_sender, _) =+ tokio::sync::broadcast::channel(conf.broadcast_channel_capacity);++ tokio::spawn(Self::run(push_receiver, broadcast_sender.clone()).in_current_span());++ Ok(Self {+ connection,+ broadcast_sender,+ is_subscriber_handler_spawned: Arc::new(atomic::AtomicBool::new(false)),+ })+ }++ async fn create_standalone_backend(+ conf: &crate::types::RedisSettings,+ push_sender: tokio::sync::broadcast::Sender<redis::PushInfo>,+ ) -> CustomResult<SubscriberBackend, crate::errors::RedisError> {+ let connection_info = conf.build_standalone_connection_info()?;++ let redis_client = redis::Client::open(connection_info)+ .change_context(crate::errors::RedisError::RedisConnectionError)?;++ let config = conf+ .build_connection_manager_config()+ .set_push_sender(push_sender)+ .set_automatic_resubscription();++ let connection = redis::aio::ConnectionManager::new_with_config(redis_client, config)+ .await+ .change_context(crate::errors::RedisError::RedisConnectionError)+ .attach_printable_lazy(|| {+ format!(+ "Failed to create subscriber connection for {}:{}",+ conf.host, conf.port+ )+ })?;++ Ok(SubscriberBackend::Standalone { connection })+ }++ async fn create_cluster_backend(+ conf: &crate::types::RedisSettings,+ push_sender: tokio::sync::broadcast::Sender<redis::PushInfo>,+ ) -> CustomResult<SubscriberBackend, crate::errors::RedisError> {+ let nodes = conf.normalize_cluster_urls();++ let mut cluster_builder = conf+ .build_cluster_client_builder(nodes)+ .push_sender(push_sender);++ if conf.max_in_flight_commands > 0 {+ cluster_builder =+ cluster_builder.connection_concurrency_limit(conf.max_in_flight_commands);+ }++ let connection = cluster_builder+ .build()+ .change_context(crate::errors::RedisError::RedisConnectionError)?+ .get_async_connection()+ .await+ .change_context(crate::errors::RedisError::RedisConnectionError)?;++ Ok(SubscriberBackend::Cluster {+ connection: tokio::sync::Mutex::new(connection),+ })+ }++ pub async fn subscribe(&self, channel: &str) -> CustomResult<(), crate::errors::RedisError> {+ match &self.connection {+ SubscriberBackend::Standalone { connection } => connection+ .clone()+ .subscribe(channel)+ .await+ .change_context(crate::errors::RedisError::SubscribeError),+ SubscriberBackend::Cluster { connection } => connection+ .lock()+ .await+ .subscribe(channel)+ .await+ .change_context(crate::errors::RedisError::SubscribeError),+ }+ }++ pub async fn unsubscribe(&self, channel: &str) -> CustomResult<(), crate::errors::RedisError> {+ match &self.connection {+ SubscriberBackend::Standalone { connection } => connection+ .clone()+ .unsubscribe(channel)+ .await+ .change_context(crate::errors::RedisError::SubscribeError),+ SubscriberBackend::Cluster { connection } => connection+ .lock()+ .await+ .unsubscribe(channel)+ .await+ .change_context(crate::errors::RedisError::SubscribeError),+ }+ }++ pub fn message_rx(&self) -> tokio::sync::broadcast::Receiver<PubSubMessage> {+ self.broadcast_sender.subscribe()+ }++ /// Background task that reads RESP3 push messages from a broadcast receiver+ /// and forwards them as [`PubSubMessage`]s to an internal broadcast channel.+ ///+ /// The loop exits when the push channel is closed (i.e. the underlying+ /// Redis connection has dropped permanently). When that happens, the+ /// subscriber's `broadcast_sender` remains functional — callers invoking+ /// [`message_rx()`](Self::message_rx) will simply never receive new messages.+ async fn run(+ mut push_receiver: tokio::sync::broadcast::Receiver<redis::PushInfo>,+ broadcast_sender: tokio::sync::broadcast::Sender<PubSubMessage>,+ ) {+ loop {+ match push_receiver.recv().await {+ Ok(info) => Self::handle_push_info(&info, &broadcast_sender),+ Err(tokio::sync::broadcast::error::RecvError::Lagged(count)) => {+ tracing::warn!(count, "Push receiver lagged — dropped messages");+ }+ Err(tokio::sync::broadcast::error::RecvError::Closed) => {+ tracing::error!("Push channel closed — connection dropped permanently");+ break;+ }+ }+ }+ tracing::warn!("Subscriber handler task exiting — no further messages will be received");+ }++ /// Parses a single push message and, if it is a pub/sub `Message`,+ /// broadcasts it to all active receivers. Non-message push kinds+ /// (e.g. `Subscribe`, `Unsubscribe`) are logged at warn level and ignored.+ fn handle_push_info(+ push_info: &redis::PushInfo,+ broadcast_sender: &tokio::sync::broadcast::Sender<PubSubMessage>,+ ) {+ match PubSubMessage::from_push_info(push_info) {+ Some(msg) => {+ if let Err(error) = broadcast_sender.send(msg) {+ tracing::error!(+ ?error,+ "Failed to broadcast pub/sub message — no active receivers"+ );+ }+ }+ None => {+ tracing::warn!(+ kind = ?push_info.kind,+ "Ignoring non-message push kind"+ );+ }+ }+ }+}++// ─── Publisher client ────────────────────────────────────────────────────────++/// A wrapper around a connection used for publishing messages.+pub struct PublisherClient {+ inner: RedisConn,+}++impl PublisherClient {+ pub(crate) fn new(connection: RedisConn) -> Self {+ Self { inner: connection }+ }++ pub async fn publish(+ &self,+ channel: &str,+ message: crate::types::RedisValue,+ ) -> CustomResult<usize, crate::errors::RedisError> {+ let mut conn = self.inner.clone();+ conn.publish::<_, _, usize>(channel, message)+ .await+ .change_context(crate::errors::RedisError::PublishError)+ }+}++// ─── Connection pool ─────────────────────────────────────────────────────────++pub struct RedisConnectionPool {+ pub pool: RedisConn,+ pub key_prefix: String,+ pub config: Arc<RedisConfig>,+ pub subscriber: Arc<SubscriberClient>,+ pub publisher: Arc<PublisherClient>,+ pub is_redis_available: Arc<atomic::AtomicBool>,+}++impl RedisConnectionPool {+ /// Create a new Redis connection+ pub async fn new(+ conf: &crate::types::RedisSettings,+ ) -> CustomResult<Self, crate::errors::RedisError> {+ let (pool, subscriber, publisher) = match conf.cluster_enabled {+ true => {+ let nodes = conf.normalize_cluster_urls();++ let mut pool_builder = conf.build_cluster_client_builder(nodes.clone());++ if conf.max_in_flight_commands > 0 {+ pool_builder =+ pool_builder.connection_concurrency_limit(conf.max_in_flight_commands);+ }++ let pool_conn = pool_builder+ .build()+ .change_context(crate::errors::RedisError::RedisConnectionError)+ .attach_printable_lazy(|| {+ format!(+ "Failed to create Redis cluster client for {}:{}",+ conf.host, conf.port+ )+ })?+ .get_async_connection()+ .await+ .change_context(crate::errors::RedisError::RedisConnectionError)+ .attach_printable_lazy(|| {+ format!(+ "Failed to connect to Redis cluster at {}:{}",+ conf.host, conf.port+ )+ })?;++ let pool = RedisConn::Cluster(pool_conn);++ let publisher_builder = conf.build_cluster_client_builder(nodes);++ let publisher_conn = publisher_builder+ .build()+ .change_context(crate::errors::RedisError::RedisConnectionError)+ .attach_printable_lazy(|| {+ format!(+ "Failed to create Redis cluster pub/sub client for {}:{}",+ conf.host, conf.port+ )+ })?+ .get_async_connection()+ .await+ .change_context(crate::errors::RedisError::RedisConnectionError)+ .attach_printable_lazy(|| {+ format!(+ "Failed to connect Redis cluster pub/sub at {}:{}",+ conf.host, conf.port+ )+ })?;++ let publisher = Arc::new(PublisherClient::new(RedisConn::Cluster(publisher_conn)));++ let subscriber = Arc::new(SubscriberClient::new(conf).await?);++ (pool, subscriber, publisher)+ }+ false => {+ let connection_info = conf.build_standalone_connection_info()?;++ let client = redis::Client::open(connection_info)+ .change_context(crate::errors::RedisError::RedisConnectionError)+ .attach_printable_lazy(|| {+ format!(+ "Failed to open Redis client for {}:{}",+ conf.host, conf.port+ )+ })?;++ let mut pool_config = conf.build_connection_manager_config();++ if conf.max_in_flight_commands > 0 {+ pool_config = pool_config.set_pipeline_buffer_size(conf.max_in_flight_commands);+ }++ let conn = redis::aio::ConnectionManager::new_with_config(client, pool_config)+ .await+ .change_context(crate::errors::RedisError::RedisConnectionError)+ .attach_printable_lazy(|| {+ format!("Failed to connect to Redis at {}:{}", conf.host, conf.port)+ })?;++ let pool = RedisConn::Standalone(conn);++ let base_connection_info = conf.build_standalone_connection_info()?;++ let base_client = redis::Client::open(base_connection_info)+ .change_context(crate::errors::RedisError::RedisConnectionError)+ .attach_printable_lazy(|| {+ format!(+ "Failed to open Redis pub/sub client for {}:{}",+ conf.host, conf.port+ )+ })?;++ let subscriber = Arc::new(SubscriberClient::new(conf).await?);++ let publisher_conn = redis::aio::ConnectionManager::new(base_client)+ .await+ .change_context(crate::errors::RedisError::RedisConnectionError)+ .attach_printable_lazy(|| {+ format!(+ "Failed to create publisher connection for {}:{}",+ conf.host, conf.port+ )+ })?;+ let publisher =+ Arc::new(PublisherClient::new(RedisConn::Standalone(publisher_conn)));++ (pool, subscriber, publisher)+ }+ };++ let config = RedisConfig::from(conf);++ Ok(Self {+ pool,+ config: Arc::new(config),+ is_redis_available: Arc::new(atomic::AtomicBool::new(true)),+ subscriber,+ publisher,+ key_prefix: String::default(),+ })+ }++ pub fn clone(&self, key_prefix: &str) -> Self {+ Self {+ pool: self.pool.clone(),+ key_prefix: key_prefix.to_string(),+ config: Arc::clone(&self.config),+ subscriber: Arc::clone(&self.subscriber),+ publisher: Arc::clone(&self.publisher),+ is_redis_available: Arc::clone(&self.is_redis_available),+ }+ }++ /// Monitor for connection errors.+ /// When Redis is unreachable for longer than `max_failure_threshold_seconds` seconds,+ /// signals via the oneshot sender and marks redis as unavailable.+ pub async fn on_error(&self, tx: tokio::sync::oneshot::Sender<()>) {+ let check_interval = self+ .config+ .unresponsive_check_interval+ .max(crate::constant::redis_rs_commands::MIN_ERROR_CHECK_INTERVAL_SECS);+ let max_unreachable_secs = self.config.max_failure_threshold_seconds;+ let mut first_failure_at: Option<std::time::Instant> = None;++ loop {+ tokio::time::sleep(std::time::Duration::from_secs(check_interval)).await;+ let mut conn = self.pool.clone();++ // Timeout the ping so we can check threshold frequently,+ // even when ConnectionManager is retrying internally+ let result = tokio::time::timeout(+ std::time::Duration::from_secs(check_interval),+ conn.ping::<String>(),+ )+ .await;++ let ping_ok = matches!(result, Ok(Ok(_)));++ if ping_ok {+ if first_failure_at.is_some() {+ tracing::info!("Redis connection restored");+ }+ first_failure_at = None;+ } else {+ let now = std::time::Instant::now();+ let first_failure = *first_failure_at.get_or_insert(now);+ let unreachable_secs = now.duration_since(first_failure).as_secs();++ if unreachable_secs >= u64::from(max_unreachable_secs) {+ tracing::error!(+ "Redis has been unreachable for {}s (threshold: {}s), shutting down",+ unreachable_secs,+ max_unreachable_secs+ );+ if let Err(error) = tx.send(()) {+ tracing::warn!(+ ?error,+ "Failed to send shutdown signal — receiver already dropped"+ );+ }+ self.is_redis_available+ .store(false, atomic::Ordering::SeqCst);+ break;+ }++ tracing::warn!(+ "Redis unreachable for {}s (threshold: {}s), reconnecting",+ unreachable_secs,+ max_unreachable_secs+ );+ }+ }+ }+}++// ─── RedisSettings helpers (redis-rs backend only) ────────────────────────────++impl crate::types::RedisSettings {+ /// Normalize cluster URLs by prepending `"redis://"` if the scheme is missing.+ pub(crate) fn normalize_cluster_urls(&self) -> Vec<String> {+ self.cluster_urls+ .iter()+ .map(|url| {+ if url.starts_with("redis://") {+ url.clone()+ } else {+ format!("redis://{url}")+ }+ })+ .collect()+ }++ /// Convert `reconnect_max_attempts` to `usize`.+ ///+ /// Logs a warning and falls back to [`crate::constant::redis_rs_commands::DEFAULT_RECONNECT_MAX_ATTEMPTS`]+ /// when the value overflows.+ pub(crate) fn reconnect_max_attempts_as_usize(&self) -> usize {+ usize::try_from(self.reconnect_max_attempts).unwrap_or_else(|_| {+ tracing::warn!(+ "reconnect_max_attempts ({}) exceeds usize, using default ({})",+ self.reconnect_max_attempts,+ crate::constant::redis_rs_commands::DEFAULT_RECONNECT_MAX_ATTEMPTS+ );+ crate::constant::redis_rs_commands::DEFAULT_RECONNECT_MAX_ATTEMPTS+ })+ }++ /// Build standalone connection info with RESP3 protocol from host and port.+ pub(crate) fn build_standalone_connection_info(+ &self,+ ) -> CustomResult<redis::ConnectionInfo, crate::errors::RedisError> {+ use error_stack::ResultExt;+ use redis::IntoConnectionInfo;++ let connection_url = format!("redis://{}:{}", self.host, self.port);+ let mut connection_info = connection_url+ .as_str()+ .into_connection_info()+ .change_context(crate::errors::RedisError::RedisConnectionError)?;++ let redis_settings = connection_info+ .redis_settings()+ .clone()+ .set_protocol(redis::ProtocolVersion::RESP3);+ connection_info = connection_info.set_redis_settings(redis_settings);++ Ok(connection_info)+ }++ /// Build the connection manager configuration from these settings.+ ///+ /// Sets reconnection retries, minimum delay, and optional response timeout.+ pub(crate) fn build_connection_manager_config(&self) -> redis::aio::ConnectionManagerConfig {+ let mut config = redis::aio::ConnectionManagerConfig::new()+ .set_number_of_retries(self.reconnect_max_attempts_as_usize())+ .set_min_delay(std::time::Duration::from_millis(u64::from(+ self.reconnect_delay,+ )));++ if self.default_command_timeout > 0 {+ config = config.set_response_timeout(Some(std::time::Duration::from_secs(+ self.default_command_timeout,+ )));+ }++ config+ }++ /// Build a cluster client builder with common configuration.+ ///+ /// Sets retries, retry wait, response timeout, and RESP3 protocol.+ pub(crate) fn build_cluster_client_builder(+ &self,+ nodes: Vec<String>,+ ) -> redis::cluster::ClusterClientBuilder {+ redis::cluster::ClusterClient::builder(nodes)+ .retries(self.reconnect_max_attempts)+ .min_retry_wait(u64::from(self.reconnect_delay))+ .response_timeout(std::time::Duration::from_secs(+ self.default_command_timeout.max(1),+ ))+ .use_protocol(redis::ProtocolVersion::RESP3)+ }+}++pub struct RedisConfig {+ pub(crate) default_ttl: u32,+ pub(crate) default_stream_read_count: u64,+ pub(crate) default_hash_ttl: u32,+ pub(crate) cluster_enabled: bool,+ pub(crate) unresponsive_check_interval: u64,+ pub(crate) max_failure_threshold_seconds: u32,+}++impl From<&crate::types::RedisSettings> for RedisConfig {+ fn from(config: &crate::types::RedisSettings) -> Self {+ Self {+ default_ttl: config.default_ttl,+ default_stream_read_count: config.stream_read_count,+ default_hash_ttl: config.default_hash_ttl,+ cluster_enabled: config.cluster_enabled,+ unresponsive_check_interval: config.unresponsive_check_interval,+ max_failure_threshold_seconds: config.max_failure_threshold_seconds,+ }+ }+}diff --git a/crates/redis_interface/src/module/redis_rs/commands.rs b/crates/redis_interface/src/module/redis_rs/commands.rsnew file mode 100644index 0000000000..30a8c7ae80--- /dev/null+++ b/crates/redis_interface/src/module/redis_rs/commands.rs@@ -0,0 +1,1349 @@+//! An interface to abstract the `redis` commands+//!+//! The folder provides generic functions for providing serialization+//! and deserialization while calling redis.+//! It also includes instruments to provide tracing.++use std::fmt::Debug;++use common_utils::{+ errors::CustomResult,+ ext_traits::{ByteSliceExt, Encode, StringExt},+ fp_utils,+};+use error_stack::{report, ResultExt};+use redis::{+ streams::StreamReadOptions, AsyncCommands, ExistenceCheck, FromRedisValue, SetExpiry,+ SetOptions, ToSingleRedisArg,+};+use tracing::instrument;++use super::types::redis_value_to_option_string;+use crate::{+ constant::redis_rs_commands::{+ REDIS_ARG_COUNT, REDIS_ARG_EX, REDIS_ARG_MATCH, REDIS_ARG_NX, REDIS_ARG_TYPE,+ REDIS_COMMAND_GET, REDIS_COMMAND_HSCAN, REDIS_COMMAND_SCAN, REDIS_COMMAND_SET,+ },+ errors,+ types::{+ DelReply, HsetnxReply, MsetnxReply, RedisEntryId, RedisKey, SaddReply, SetGetReply,+ SetnxReply, StreamEntries, StreamReadResult, StreamTrimConfig,+ },+};++impl super::RedisConnectionPool {+ pub fn add_prefix(&self, key: &str) -> String {+ if self.key_prefix.is_empty() {+ key.to_string()+ } else {+ format!("{}:{}", self.key_prefix, key)+ }+ }++ // ─── Key Commands ────────────────────────────────────────────────────────++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn set_key<V>(&self, key: &RedisKey, value: V) -> CustomResult<(), errors::RedisError>+ where+ V: redis::ToRedisArgs + Debug + Send + Sync + ToSingleRedisArg,+ {+ let mut conn = self.pool.clone();+ let options = SetOptions::default()+ .with_expiration(SetExpiry::EX(u64::from(self.config.default_ttl)));+ let _: Option<String> = conn+ .set_options(key.tenant_aware_key(self), value, options)+ .await+ .change_context(errors::RedisError::SetFailed)?;+ Ok(())+ }++ pub async fn set_key_without_modifying_ttl<V>(+ &self,+ key: &RedisKey,+ value: V,+ ) -> CustomResult<(), errors::RedisError>+ where+ V: redis::ToRedisArgs + Debug + Send + Sync + ToSingleRedisArg,+ {+ let mut conn = self.pool.clone();+ let options = SetOptions::default().with_expiration(SetExpiry::KEEPTTL);+ let _: Option<String> = conn+ .set_options(key.tenant_aware_key(self), value, options)+ .await+ .change_context(errors::RedisError::SetFailed)?;+ Ok(())+ }++ pub async fn set_multiple_keys_if_not_exist<K, V>(+ &self,+ key_value_pairs: &[(K, V)],+ ) -> CustomResult<MsetnxReply, errors::RedisError>+ where+ K: redis::ToRedisArgs + Debug + Send + Sync,+ V: redis::ToRedisArgs + Debug + Send + Sync,+ {+ let mut conn = self.pool.clone();+ conn.mset_nx(key_value_pairs)+ .await+ .change_context(errors::RedisError::SetFailed)+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn serialize_and_set_key_if_not_exist<V>(+ &self,+ key: &RedisKey,+ value: V,+ ttl: Option<i64>,+ ) -> CustomResult<SetnxReply, errors::RedisError>+ where+ V: serde::Serialize + Debug,+ {+ let serialized = value+ .encode_to_vec()+ .change_context(errors::RedisError::JsonSerializationFailed)?;+ self.set_key_if_not_exists_with_expiry(key, serialized.as_slice(), ttl)+ .await+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn serialize_and_set_key<V>(+ &self,+ key: &RedisKey,+ value: V,+ ) -> CustomResult<(), errors::RedisError>+ where+ V: serde::Serialize + Debug,+ {+ let serialized = value+ .encode_to_vec()+ .change_context(errors::RedisError::JsonSerializationFailed)?;++ self.set_key(key, serialized.as_slice()).await+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn serialize_and_set_key_without_modifying_ttl<V>(+ &self,+ key: &RedisKey,+ value: V,+ ) -> CustomResult<(), errors::RedisError>+ where+ V: serde::Serialize + Debug,+ {+ let serialized = value+ .encode_to_vec()+ .change_context(errors::RedisError::JsonSerializationFailed)?;++ self.set_key_without_modifying_ttl(key, serialized.as_slice())+ .await+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn serialize_and_set_key_with_expiry<V>(+ &self,+ key: &RedisKey,+ value: V,+ seconds: i64,+ ) -> CustomResult<(), errors::RedisError>+ where+ V: serde::Serialize + Debug,+ {+ let serialized = value+ .encode_to_vec()+ .change_context(errors::RedisError::JsonSerializationFailed)?;++ let mut conn = self.pool.clone();+ let options = SetOptions::default().with_expiration(SetExpiry::EX(+ u64::try_from(seconds).change_context(errors::RedisError::SetExFailed)?,+ ));+ let _: Option<String> = conn+ .set_options(key.tenant_aware_key(self), serialized.as_slice(), options)+ .await+ .change_context(errors::RedisError::SetExFailed)?;+ Ok(())+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn get_key<V>(&self, key: &RedisKey) -> CustomResult<V, errors::RedisError>+ where+ V: FromRedisValue + Send + 'static,+ {+ let mut conn = self.pool.clone();+ match conn+ .get::<_, V>(key.tenant_aware_key(self))+ .await+ .change_context(errors::RedisError::GetFailed)+ {+ Ok(v) => Ok(v),+ Err(_err) => {+ #[cfg(not(feature = "multitenancy_fallback"))]+ {+ Err(_err)+ }++ #[cfg(feature = "multitenancy_fallback")]+ {+ conn.get::<_, V>(key.tenant_unaware_key(self))+ .await+ .change_context(errors::RedisError::GetFailed)+ }+ }+ }+ }++ #[instrument(level = "DEBUG", skip(self))]+ async fn get_multiple_keys_with_mget<V>(+ &self,+ keys: &[RedisKey],+ ) -> CustomResult<Vec<Option<V>>, errors::RedisError>+ where+ V: FromRedisValue + Send + 'static,+ {+ if keys.is_empty() {+ return Ok(Vec::new());+ }++ let tenant_aware_keys: Vec<String> =+ keys.iter().map(|key| key.tenant_aware_key(self)).collect();+ let mut conn = self.pool.clone();+ conn.mget(&tenant_aware_keys)+ .await+ .change_context(errors::RedisError::GetFailed)+ }++ #[instrument(level = "DEBUG", skip(self))]+ async fn get_multiple_keys_with_parallel_get<V>(+ &self,+ keys: &[RedisKey],+ ) -> CustomResult<Vec<Option<V>>, errors::RedisError>+ where+ V: FromRedisValue + Send + 'static,+ {+ if keys.is_empty() {+ return Ok(Vec::new());+ }+ let tenant_aware_keys: Vec<String> =+ keys.iter().map(|key| key.tenant_aware_key(self)).collect();++ let futures = tenant_aware_keys.iter().map(|redis_key| {+ let mut conn = self.pool.clone();+ let key = redis_key.clone();+ async move { conn.get::<_, Option<V>>(&key).await }+ });++ let results = futures::future::try_join_all(futures)+ .await+ .change_context(errors::RedisError::GetFailed)+ .attach_printable("Failed to get keys in cluster mode")?;++ Ok(results)+ }++ /// Helper method to encapsulate the logic for choosing between cluster and non-cluster modes+ #[instrument(level = "DEBUG", skip(self))]+ async fn get_keys_by_mode<V>(+ &self,+ keys: &[RedisKey],+ ) -> CustomResult<Vec<Option<V>>, errors::RedisError>+ where+ V: FromRedisValue + Send + 'static,+ {+ if self.config.cluster_enabled {+ // Use individual GET commands for cluster mode to avoid CROSSSLOT errors+ self.get_multiple_keys_with_parallel_get(keys).await+ } else {+ // Use MGET for non-cluster mode for better performance+ self.get_multiple_keys_with_mget(keys).await+ }+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn get_multiple_keys<V>(+ &self,+ keys: &[RedisKey],+ ) -> CustomResult<Vec<Option<V>>, errors::RedisError>+ where+ V: FromRedisValue + Send + 'static,+ {+ if keys.is_empty() {+ return Ok(Vec::new());+ }++ match self.get_keys_by_mode(keys).await {+ Ok(values) => Ok(values),+ Err(_err) => {+ #[cfg(not(feature = "multitenancy_fallback"))]+ {+ Err(_err)+ }++ #[cfg(feature = "multitenancy_fallback")]+ {+ let tenant_unaware_keys: Vec<RedisKey> = keys+ .iter()+ .map(|key| key.tenant_unaware_key(self).into())+ .collect();++ self.get_keys_by_mode(&tenant_unaware_keys).await+ }+ }+ }+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn exists<V>(&self, key: &RedisKey) -> CustomResult<bool, errors::RedisError>+ where+ V: Send + 'static,+ {+ let mut conn = self.pool.clone();+ match conn+ .exists::<_, bool>(key.tenant_aware_key(self))+ .await+ .change_context(errors::RedisError::GetFailed)+ {+ Ok(v) => Ok(v),+ Err(_err) => {+ #[cfg(not(feature = "multitenancy_fallback"))]+ {+ Err(_err)+ }++ #[cfg(feature = "multitenancy_fallback")]+ {+ conn.exists::<_, bool>(key.tenant_unaware_key(self))+ .await+ .change_context(errors::RedisError::GetFailed)+ }+ }+ }+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn get_and_deserialize_key<T>(+ &self,+ key: &RedisKey,+ type_name: &'static str,+ ) -> CustomResult<T, errors::RedisError>+ where+ T: serde::de::DeserializeOwned,+ {+ let value_bytes = self.get_key::<Vec<u8>>(key).await?;+ fp_utils::when(value_bytes.is_empty(), || Err(errors::RedisError::NotFound))?;+ value_bytes+ .parse_struct(type_name)+ .change_context(errors::RedisError::JsonDeserializationFailed)+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn get_and_deserialize_multiple_keys<T>(+ &self,+ keys: &[RedisKey],+ type_name: &'static str,+ ) -> CustomResult<Vec<Option<T>>, errors::RedisError>+ where+ T: serde::de::DeserializeOwned,+ {+ let value_bytes_vec = self.get_multiple_keys::<Vec<u8>>(keys).await?;++ let mut results = Vec::with_capacity(value_bytes_vec.len());+ for value_bytes_opt in value_bytes_vec {+ match value_bytes_opt {+ Some(value_bytes) => {+ if value_bytes.is_empty() {+ results.push(None);+ } else {+ let parsed = value_bytes+ .parse_struct(type_name)+ .change_context(errors::RedisError::JsonDeserializationFailed)?;+ results.push(Some(parsed));+ }+ }+ None => results.push(None),+ }+ }++ Ok(results)+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn delete_key(&self, key: &RedisKey) -> CustomResult<DelReply, errors::RedisError> {+ let mut conn = self.pool.clone();+ // Redis DEL returns the number of keys that were deleted.+ // 0 means the key did not exist (not an error).+ let deleted_count: usize = conn+ .del(key.tenant_aware_key(self))+ .await+ .change_context(errors::RedisError::DeleteFailed)?;++ let reply = if deleted_count > 0 {+ DelReply::KeyDeleted+ } else {+ // Key was not found in tenant-aware namespace.+ // With multitenancy_fallback, try the tenant-unaware namespace.+ // This mirrors the old behavior where a failed DEL in tenant-aware+ // namespace would fall back to tenant-unaware.+ #[cfg(not(feature = "multitenancy_fallback"))]+ {+ DelReply::KeyNotDeleted+ }++ #[cfg(feature = "multitenancy_fallback")]+ {+ let fallback_count: usize = conn+ .del(key.tenant_unaware_key(self))+ .await+ .change_context(errors::RedisError::DeleteFailed)?;+ if fallback_count > 0 {+ DelReply::KeyDeleted+ } else {+ DelReply::KeyNotDeleted+ }+ }+ };++ Ok(reply)+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn delete_multiple_keys(+ &self,+ keys: &[RedisKey],+ ) -> CustomResult<Vec<DelReply>, errors::RedisError> {+ let futures = keys.iter().map(|key| self.delete_key(key));++ let del_result = futures::future::try_join_all(futures)+ .await+ .change_context(errors::RedisError::DeleteFailed)?;++ Ok(del_result)+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn set_key_with_expiry<V>(+ &self,+ key: &RedisKey,+ value: V,+ seconds: i64,+ ) -> CustomResult<(), errors::RedisError>+ where+ V: redis::ToRedisArgs + Debug + Send + Sync + ToSingleRedisArg,+ {+ let mut conn = self.pool.clone();+ let options = SetOptions::default().with_expiration(SetExpiry::EX(+ u64::try_from(seconds).change_context(errors::RedisError::SetExFailed)?,+ ));+ let _: Option<String> = conn+ .set_options(key.tenant_aware_key(self), value, options)+ .await+ .change_context(errors::RedisError::SetExFailed)?;+ Ok(())+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn set_key_if_not_exists_with_expiry<V>(+ &self,+ key: &RedisKey,+ value: V,+ seconds: Option<i64>,+ ) -> CustomResult<SetnxReply, errors::RedisError>+ where+ V: redis::ToRedisArgs + Debug + Send + Sync + ToSingleRedisArg,+ {+ let ttl = seconds.unwrap_or(self.config.default_ttl.into());+ let mut conn = self.pool.clone();+ let options = SetOptions::default()+ .conditional_set(ExistenceCheck::NX)+ .with_expiration(SetExpiry::EX(+ u64::try_from(ttl).change_context(errors::RedisError::SetFailed)?,+ ));+ let result: Option<String> = conn+ .set_options(key.tenant_aware_key(self), value, options)+ .await+ .change_context(errors::RedisError::SetFailed)?;++ // SET NX returns OK on success, nil if key already exists+ let reply = if result.is_some() {+ SetnxReply::KeySet+ } else {+ SetnxReply::KeyNotSet+ };+ Ok(reply)+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn set_expiry(+ &self,+ key: &RedisKey,+ seconds: i64,+ ) -> CustomResult<(), errors::RedisError> {+ let mut conn = self.pool.clone();+ conn.expire::<_, ()>(key.tenant_aware_key(self), seconds)+ .await+ .change_context(errors::RedisError::SetExpiryFailed)+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn set_expire_at(+ &self,+ key: &RedisKey,+ timestamp: i64,+ ) -> CustomResult<(), errors::RedisError> {+ let mut conn = self.pool.clone();+ conn.expire_at::<_, ()>(key.tenant_aware_key(self), timestamp)+ .await+ .change_context(errors::RedisError::SetExpiryFailed)+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn get_ttl(&self, key: &RedisKey) -> CustomResult<i64, errors::RedisError> {+ let mut conn = self.pool.clone();+ conn.ttl::<_, i64>(key.tenant_aware_key(self))+ .await+ .change_context(errors::RedisError::GetFailed)+ }++ // ─── Hash Commands ───────────────────────────────────────────────────────++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn set_hash_fields<F, V>(+ &self,+ key: &RedisKey,+ field_value_pairs: Vec<(F, V)>,+ ttl: Option<i64>,+ ) -> CustomResult<(), errors::RedisError>+ where+ F: redis::ToRedisArgs + Debug + Send + Sync,+ V: redis::ToRedisArgs + Debug + Send + Sync,+ {+ let mut conn = self.pool.clone();+ let _: () = conn+ .hset_multiple(key.tenant_aware_key(self), &field_value_pairs)+ .await+ .change_context(errors::RedisError::SetHashFailed)?;++ // setting expiry for the key — reuse the same connection+ conn.expire::<_, ()>(+ key.tenant_aware_key(self),+ ttl.unwrap_or(self.config.default_hash_ttl.into()),+ )+ .await+ .change_context(errors::RedisError::SetExpiryFailed)+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn set_hash_field_if_not_exist<V>(+ &self,+ key: &RedisKey,+ field: &str,+ value: V,+ ttl: Option<u32>,+ ) -> CustomResult<HsetnxReply, errors::RedisError>+ where+ V: redis::ToRedisArgs + ToSingleRedisArg + Debug + Send + Sync,+ {+ let mut conn = self.pool.clone();+ let result: HsetnxReply = conn+ .hset_nx::<_, _, _, HsetnxReply>(key.tenant_aware_key(self), field, value)+ .await+ .change_context(errors::RedisError::SetHashFieldFailed)?;++ // Only set expiry if the field was actually set+ if matches!(result, HsetnxReply::KeySet) {+ conn.expire::<_, ()>(+ key.tenant_aware_key(self),+ ttl.unwrap_or(self.config.default_hash_ttl).into(),+ )+ .await+ .change_context(errors::RedisError::SetExpiryFailed)?;+ }++ Ok(result)+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn serialize_and_set_hash_field_if_not_exist<V>(+ &self,+ key: &RedisKey,+ field: &str,+ value: V,+ ttl: Option<u32>,+ ) -> CustomResult<HsetnxReply, errors::RedisError>+ where+ V: serde::Serialize + Debug,+ {+ let serialized = value+ .encode_to_vec()+ .change_context(errors::RedisError::JsonSerializationFailed)?;++ self.set_hash_field_if_not_exist(key, field, serialized.as_slice(), ttl)+ .await+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn serialize_and_set_multiple_hash_field_if_not_exist<V>(+ &self,+ kv: &[(&RedisKey, V)],+ field: &str,+ ttl: Option<u32>,+ ) -> CustomResult<Vec<HsetnxReply>, errors::RedisError>+ where+ V: serde::Serialize + Debug,+ {+ let mut hsetnx: Vec<HsetnxReply> = Vec::with_capacity(kv.len());+ for (key, val) in kv {+ hsetnx.push(+ self.serialize_and_set_hash_field_if_not_exist(key, field, val, ttl)+ .await?,+ );+ }+ Ok(hsetnx)+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn increment_fields_in_hash<T>(+ &self,+ key: &RedisKey,+ fields_to_increment: &[(T, i64)],+ ) -> CustomResult<Vec<usize>, errors::RedisError>+ where+ T: Debug + ToString,+ {+ let mut conn = self.pool.clone();+ let mut values_after_increment = Vec::with_capacity(fields_to_increment.len());+ for (field, increment) in fields_to_increment {+ values_after_increment.push(+ conn.hincr::<_, _, _, usize>(+ key.tenant_aware_key(self),+ field.to_string(),+ *increment,+ )+ .await+ .change_context(errors::RedisError::IncrementHashFieldFailed)?,+ )+ }++ Ok(values_after_increment)+ }++ /// Manually builds the HSCAN command because redis-rs's `hscan` / `hscan_match`+ /// helpers don't expose the `COUNT` argument. We need `MATCH` + `COUNT` together+ /// to bound per-iteration server work on large hashes.+ #[instrument(level = "DEBUG", skip(self))]+ pub async fn hscan(+ &self,+ key: &RedisKey,+ pattern: &str,+ count: Option<u32>,+ ) -> CustomResult<Vec<String>, errors::RedisError> {+ let mut conn = self.pool.clone();++ let mut results: Vec<String> = Vec::new();+ let mut cursor: u64 = 0;+ let mut iterations: u32 = 0;++ loop {+ // Guard against a corrupted cursor that never returns to 0+ iterations += 1;+ if iterations > crate::constant::redis_rs_commands::MAX_SCAN_ITERATIONS {+ tracing::warn!(key = ?key, iterations, "HSCAN exceeded max iterations — returning partial results");+ break;+ }++ // Build HSCAN command: HSCAN key cursor MATCH pattern [COUNT count]+ let mut command = redis::cmd(REDIS_COMMAND_HSCAN);+ command+ .arg(key.tenant_aware_key(self))+ .arg(cursor)+ .arg(REDIS_ARG_MATCH)+ .arg(pattern);++ if let Some(count_value) = count {+ command.arg(REDIS_ARG_COUNT).arg(count_value);+ }++ // HSCAN returns: [cursor, [field1, value1, field2, value2, ...]]+ let reply: (u64, Vec<redis::Value>) = command+ .query_async(&mut conn)+ .await+ .change_context(errors::RedisError::GetHashFieldFailed)?;++ cursor = reply.0;++ // Extract values (odd indices) from field/value pairs+ let pairs = reply.1;+ for (index, value) in pairs.into_iter().enumerate() {+ if index % 2 == 1 {+ if let Some(s) = redis_value_to_option_string(&value) {+ results.push(s);+ }+ }+ }++ // Cursor 0 means iteration is complete+ if cursor == 0 {+ break;+ }+ }++ Ok(results)+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn scan(+ &self,+ pattern: &RedisKey,+ count: Option<u32>,+ scan_type: Option<crate::types::RedisScanType>,+ ) -> CustomResult<Vec<String>, errors::RedisError> {+ let mut conn = self.pool.clone();++ let mut results: Vec<String> = Vec::new();+ let mut cursor: u64 = 0;+ let mut iterations: u32 = 0;++ loop {+ // Guard against a corrupted cursor that never returns to 0+ iterations += 1;+ if iterations > crate::constant::redis_rs_commands::MAX_SCAN_ITERATIONS {+ tracing::warn!(pattern = ?pattern, iterations, "SCAN exceeded max iterations — returning partial results");+ break;+ }++ let mut command = redis::cmd(REDIS_COMMAND_SCAN);+ command+ .arg(cursor)+ .arg(REDIS_ARG_MATCH)+ .arg(pattern.tenant_aware_key(self));++ if let Some(count_value) = count {+ command.arg(REDIS_ARG_COUNT).arg(count_value);+ }++ if let Some(scan_type_value) = scan_type {+ command.arg(REDIS_ARG_TYPE).arg(scan_type_value.as_ref());+ }++ let reply: (u64, Vec<String>) = command+ .query_async(&mut conn)+ .await+ .change_context(errors::RedisError::GetFailed)?;++ cursor = reply.0;+ results.extend(reply.1);++ if cursor == 0 {+ break;+ }+ }++ Ok(results)+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn hscan_and_deserialize<T>(+ &self,+ key: &RedisKey,+ pattern: &str,+ count: Option<u32>,+ ) -> CustomResult<Vec<T>, errors::RedisError>+ where+ T: serde::de::DeserializeOwned,+ {+ let redis_results = self.hscan(key, pattern, count).await?;+ Ok(redis_results+ .iter()+ .filter_map(|redis_value| {+ let r: T = redis_value.parse_struct(std::any::type_name::<T>()).ok()?;+ Some(r)+ })+ .collect())+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn get_hash_field<V>(+ &self,+ key: &RedisKey,+ field: &str,+ ) -> CustomResult<V, errors::RedisError>+ where+ V: FromRedisValue + Send + 'static,+ {+ let mut conn = self.pool.clone();+ match conn+ .hget::<_, _, V>(key.tenant_aware_key(self), field)+ .await+ .change_context(errors::RedisError::GetHashFieldFailed)+ {+ Ok(v) => Ok(v),+ Err(_err) => {+ #[cfg(feature = "multitenancy_fallback")]+ {+ conn.hget::<_, _, V>(key.tenant_unaware_key(self), field)+ .await+ .change_context(errors::RedisError::GetHashFieldFailed)+ }++ #[cfg(not(feature = "multitenancy_fallback"))]+ {+ Err(_err)+ }+ }+ }+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn get_hash_fields<V>(&self, key: &RedisKey) -> CustomResult<V, errors::RedisError>+ where+ V: FromRedisValue + Send + 'static,+ {+ let mut conn = self.pool.clone();+ match conn+ .hgetall::<_, V>(key.tenant_aware_key(self))+ .await+ .change_context(errors::RedisError::GetHashFieldFailed)+ {+ Ok(v) => Ok(v),+ Err(_err) => {+ #[cfg(feature = "multitenancy_fallback")]+ {+ conn.hgetall::<_, V>(key.tenant_unaware_key(self))+ .await+ .change_context(errors::RedisError::GetHashFieldFailed)+ }++ #[cfg(not(feature = "multitenancy_fallback"))]+ {+ Err(_err)+ }+ }+ }+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn get_hash_field_and_deserialize<V>(+ &self,+ key: &RedisKey,+ field: &str,+ type_name: &'static str,+ ) -> CustomResult<V, errors::RedisError>+ where+ V: serde::de::DeserializeOwned,+ {+ let value_bytes = self.get_hash_field::<Vec<u8>>(key, field).await?;++ if value_bytes.is_empty() {+ return Err(errors::RedisError::NotFound.into());+ }++ value_bytes+ .parse_struct(type_name)+ .change_context(errors::RedisError::JsonDeserializationFailed)+ }++ // ─── Set Commands ────────────────────────────────────────────────────────++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn sadd<V>(+ &self,+ key: &RedisKey,+ members: V,+ ) -> CustomResult<SaddReply, errors::RedisError>+ where+ V: redis::ToRedisArgs + Debug + Send + Sync,+ {+ let mut conn = self.pool.clone();+ conn.sadd::<_, _, SaddReply>(key.tenant_aware_key(self), members)+ .await+ .change_context(errors::RedisError::SetAddMembersFailed)+ }++ // ─── Stream Commands ─────────────────────────────────────────────────────++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn stream_append_entry<F, V>(+ &self,+ stream: &RedisKey,+ entry_id: &RedisEntryId,+ fields: Vec<(F, V)>,+ ) -> CustomResult<(), errors::RedisError>+ where+ F: Into<String> + Debug + Send + Sync,+ V: Into<String> + Debug + Send + Sync,+ {+ let pairs: Vec<(String, String)> = fields+ .into_iter()+ .map(|(f, v)| (f.into(), v.into()))+ .collect();++ let mut conn = self.pool.clone();+ let _: Option<String> = conn+ .xadd_map(+ stream.tenant_aware_key(self),+ entry_id.to_stream_id(),+ &pairs,+ )+ .await+ .change_context(errors::RedisError::StreamAppendFailed)?;+ Ok(())+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn stream_delete_entries(+ &self,+ stream: &RedisKey,+ ids: Vec<String>,+ ) -> CustomResult<usize, errors::RedisError> {+ let mut conn = self.pool.clone();+ conn.xdel(stream.tenant_aware_key(self), &ids)+ .await+ .change_context(errors::RedisError::StreamDeleteFailed)+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn stream_trim_entries(+ &self,+ stream: &RedisKey,+ config: StreamTrimConfig,+ ) -> CustomResult<usize, errors::RedisError> {+ let mut conn = self.pool.clone();++ let options = config+ .to_trim_options()+ .change_context(errors::RedisError::StreamTrimFailed)?;++ conn.xtrim_options(stream.tenant_aware_key(self), &options)+ .await+ .change_context(errors::RedisError::StreamTrimFailed)+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn stream_acknowledge_entries(+ &self,+ stream: &RedisKey,+ group: &str,+ ids: Vec<String>,+ ) -> CustomResult<usize, errors::RedisError> {+ let mut conn = self.pool.clone();+ conn.xack(stream.tenant_aware_key(self), group, &ids)+ .await+ .change_context(errors::RedisError::StreamAcknowledgeFailed)+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn stream_get_length(+ &self,+ stream: &RedisKey,+ ) -> CustomResult<usize, errors::RedisError> {+ let mut conn = self.pool.clone();+ conn.xlen(stream.tenant_aware_key(self))+ .await+ .change_context(errors::RedisError::GetLengthFailed)+ }++ /// Read entries from one or more streams using XREAD.+ /// Returns a [`StreamReadResult`] (stream key → list of `(entry_id, fields)`),+ /// so callers never need to parse backend-specific reply types.+ #[instrument(level = "DEBUG", skip(self))]+ pub async fn stream_read_entries(+ &self,+ streams: &[RedisKey],+ ids: Vec<String>,+ read_count: Option<u64>,+ ) -> CustomResult<StreamReadResult, errors::RedisError> {+ let mut conn = self.pool.clone();+ let stream_keys: Vec<String> = streams+ .iter()+ .map(|stream| stream.tenant_aware_key(self))+ .collect();++ let count = read_count.unwrap_or(self.config.default_stream_read_count);++ let options = StreamReadOptions::default()+ .count(usize::try_from(count).change_context(errors::RedisError::StreamReadFailed)?);++ let reply: redis::streams::StreamReadReply = conn+ .xread_options(&stream_keys, &ids, &options)+ .await+ .map_err(|err| {+ let kind = err.kind();+ match kind {+ redis::ErrorKind::UnexpectedReturnType | redis::ErrorKind::Parse => {+ report!(err).change_context(errors::RedisError::StreamEmptyOrNotAvailable)+ }+ _ => report!(err).change_context(errors::RedisError::StreamReadFailed),+ }+ })?;++ Ok(reply+ .keys+ .into_iter()+ .map(|stream_response| {+ let stream_entries: StreamEntries = stream_response+ .ids+ .into_iter()+ .map(|entry_response| {+ let fields_by_redis_value: std::collections::HashMap<+ String,+ crate::RedisValue,+ > = entry_response+ .map+ .into_iter()+ .map(|(field_name, raw_redis_value)| {+ (field_name, crate::RedisValue::new(raw_redis_value))+ })+ .collect();+ (entry_response.id, fields_by_redis_value)+ })+ .collect();+ (stream_response.key, stream_entries)+ })+ .collect())+ }++ /// Read stream entries and return them grouped by stream key with optional field values.+ /// Read entries from streams with options (XREAD / XREADGROUP)+ /// Returns a [`StreamReadResult`] (stream key → list of `(entry_id, fields)`),+ /// so callers never need to parse backend-specific reply types.+ #[instrument(level = "DEBUG", skip(self))]+ pub async fn stream_read_with_options(+ &self,+ streams: &[RedisKey],+ ids: Vec<String>,+ count: Option<u64>,+ block: Option<u64>,+ group: Option<(&str, &str)>,+ ) -> CustomResult<StreamReadResult, errors::RedisError> {+ let mut conn = self.pool.clone();+ let stream_keys: Vec<String> = streams+ .iter()+ .map(|stream| stream.tenant_aware_key(self))+ .collect();++ let mut options = StreamReadOptions::default();++ if let Some(count_val) = count {+ options = options.count(+ usize::try_from(count_val).change_context(errors::RedisError::StreamReadFailed)?,+ );+ }+ if let Some(block_ms) = block {+ options = options.block(+ usize::try_from(block_ms).change_context(errors::RedisError::StreamReadFailed)?,+ );+ }+ if let Some((group_name, consumer_name)) = group {+ options = options.group(group_name, consumer_name);+ }++ let reply: redis::streams::StreamReadReply = conn+ .xread_options(&stream_keys, &ids, &options)+ .await+ .map_err(|err| {+ let kind = err.kind();+ match kind {+ redis::ErrorKind::UnexpectedReturnType | redis::ErrorKind::Parse => {+ report!(err).change_context(errors::RedisError::StreamEmptyOrNotAvailable)+ }+ _ => report!(err).change_context(errors::RedisError::StreamReadFailed),+ }+ })?;++ Ok(reply+ .keys+ .into_iter()+ .map(|stream_response| {+ let stream_entries: StreamEntries = stream_response+ .ids+ .into_iter()+ .map(|entry_response| {+ let fields_by_redis_value: std::collections::HashMap<+ String,+ crate::RedisValue,+ > = entry_response+ .map+ .into_iter()+ .map(|(field_name, raw_redis_value)| {+ (field_name, crate::RedisValue::new(raw_redis_value))+ })+ .collect();+ (entry_response.id, fields_by_redis_value)+ })+ .collect();+ (stream_response.key, stream_entries)+ })+ .collect())+ }++ // ─── List Commands ───────────────────────────────────────────────────────++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn append_elements_to_list<V>(+ &self,+ key: &RedisKey,+ elements: V,+ ) -> CustomResult<(), errors::RedisError>+ where+ V: redis::ToRedisArgs + Debug + Send + Sync,+ {+ let mut conn = self.pool.clone();+ conn.rpush::<_, _, ()>(key.tenant_aware_key(self), elements)+ .await+ .change_context(errors::RedisError::AppendElementsToListFailed)+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn get_list_elements(+ &self,+ key: &RedisKey,+ start: i64,+ stop: i64,+ ) -> CustomResult<Vec<String>, errors::RedisError> {+ let mut conn = self.pool.clone();+ conn.lrange::<_, Vec<String>>(+ key.tenant_aware_key(self),+ isize::try_from(start).change_context(errors::RedisError::GetListElementsFailed)?,+ isize::try_from(stop).change_context(errors::RedisError::GetListElementsFailed)?,+ )+ .await+ .change_context(errors::RedisError::GetListElementsFailed)+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn get_list_length(&self, key: &RedisKey) -> CustomResult<usize, errors::RedisError> {+ let mut conn = self.pool.clone();+ conn.llen::<_, usize>(key.tenant_aware_key(self))+ .await+ .change_context(errors::RedisError::GetListLengthFailed)+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn lpop_list_elements(+ &self,+ key: &RedisKey,+ count: Option<usize>,+ ) -> CustomResult<Vec<String>, errors::RedisError> {+ let mut conn = self.pool.clone();+ let non_zero_count = count.and_then(std::num::NonZeroUsize::new);+ conn.lpop::<_, Vec<String>>(key.tenant_aware_key(self), non_zero_count)+ .await+ .change_context(errors::RedisError::PopListElementsFailed)+ }++ // Consumer Group API++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn consumer_group_create(+ &self,+ stream: &RedisKey,+ group: &str,+ id: &RedisEntryId,+ ) -> CustomResult<(), errors::RedisError> {+ if matches!(+ id,+ RedisEntryId::AutoGeneratedID | RedisEntryId::UndeliveredEntryID+ ) {+ Err(errors::RedisError::InvalidRedisEntryId)?;+ }++ let mut conn = self.pool.clone();+ let _: () = conn+ .xgroup_create_mkstream(stream.tenant_aware_key(self), group, id.to_stream_id())+ .await+ .change_context(errors::RedisError::ConsumerGroupCreateFailed)?;+ Ok(())+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn consumer_group_destroy(+ &self,+ stream: &RedisKey,+ group: &str,+ ) -> CustomResult<crate::types::ConsumerGroupDestroyReply, errors::RedisError> {+ let mut conn = self.pool.clone();+ let reply: crate::types::ConsumerGroupDestroyReply = conn+ .xgroup_destroy(stream.tenant_aware_key(self), group)+ .await+ .change_context(errors::RedisError::ConsumerGroupDestroyFailed)?;+ Ok(reply)+ }++ // the number of pending messages that the consumer had before it was deleted+ #[instrument(level = "DEBUG", skip(self))]+ pub async fn consumer_group_delete_consumer(+ &self,+ stream: &RedisKey,+ group: &str,+ consumer: &str,+ ) -> CustomResult<usize, errors::RedisError> {+ let mut conn = self.pool.clone();+ conn.xgroup_delconsumer(stream.tenant_aware_key(self), group, consumer)+ .await+ .change_context(errors::RedisError::ConsumerGroupRemoveConsumerFailed)+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn consumer_group_set_last_id(+ &self,+ stream: &RedisKey,+ group: &str,+ id: &RedisEntryId,+ ) -> CustomResult<String, errors::RedisError> {+ let mut conn = self.pool.clone();+ let _: () = conn+ .xgroup_setid(stream.tenant_aware_key(self), group, id.to_stream_id())+ .await+ .change_context(errors::RedisError::ConsumerGroupSetIdFailed)?;+ Ok(id.to_stream_id().to_string())+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn consumer_group_set_message_owner<R>(+ &self,+ stream: &RedisKey,+ group: &str,+ consumer: &str,+ min_idle_time: u64,+ ids: Vec<String>,+ ) -> CustomResult<R, errors::RedisError>+ where+ R: FromRedisValue + Send + 'static,+ {+ let mut conn = self.pool.clone();+ conn.xclaim(+ stream.tenant_aware_key(self),+ group,+ consumer,+ min_idle_time,+ &ids,+ )+ .await+ .change_context(errors::RedisError::ConsumerGroupClaimFailed)+ }++ // ─── Lua Scripting ───────────────────────────────────────────────────────++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn evaluate_redis_script<V, T>(+ &self,+ lua_script: &'static str,+ key: Vec<String>,+ values: V,+ ) -> CustomResult<T, errors::RedisError>+ where+ V: redis::ToRedisArgs + Debug + Send + Sync,+ T: serde::de::DeserializeOwned + FromRedisValue,+ {+ let mut conn = self.pool.clone();+ let script = redis::Script::new(lua_script);+ let mut invocation = script.prepare_invoke();++ for script_key in &key {+ invocation.key(script_key);+ }+ invocation.arg(values);++ let val: T = invocation+ .invoke_async(&mut conn)+ .await+ .change_context(errors::RedisError::ScriptExecutionFailed)?;+ Ok(val)+ }++ // ─── Transactions ────────────────────────────────────────────────────────++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn set_multiple_keys_if_not_exists_and_get_values<V>(+ &self,+ keys: &[(RedisKey, V)],+ ttl: Option<i64>,+ ) -> CustomResult<Vec<SetGetReply<V>>, errors::RedisError>+ where+ V: redis::ToRedisArgs+ + Debug+ + FromRedisValue+ + ToOwned<Owned = V>+ + Send+ + Sync+ + serde::de::DeserializeOwned,+ {+ let futures = keys.iter().map(|(key, value)| {+ self.set_key_if_not_exists_and_get_value(key, (*value).to_owned(), ttl)+ });++ let del_result = futures::future::try_join_all(futures)+ .await+ .change_context(errors::RedisError::SetFailed)?;++ Ok(del_result)+ }++ /// Sets a value in Redis if not already present, and returns the value (either existing or newly set).+ /// This operation is atomic using Redis transactions (MULTI/EXEC pipeline).+ #[instrument(level = "DEBUG", skip(self))]+ pub async fn set_key_if_not_exists_and_get_value<V>(+ &self,+ key: &RedisKey,+ value: V,+ ttl: Option<i64>,+ ) -> CustomResult<SetGetReply<V>, errors::RedisError>+ where+ V: redis::ToRedisArgs + Debug + FromRedisValue + Send + Sync + serde::de::DeserializeOwned,+ {+ let redis_key = key.tenant_aware_key(self);+ let ttl_seconds = ttl.unwrap_or(self.config.default_ttl.into());++ let mut conn = self.pool.clone();++ // Build an atomic pipeline (MULTI/EXEC)+ let mut pipe = redis::pipe();+ pipe.atomic();++ // SET key value EX ttl NX+ pipe.cmd(REDIS_COMMAND_SET)+ .arg(&redis_key)+ .arg(&value)+ .arg(REDIS_ARG_EX)+ .arg(ttl_seconds)+ .arg(REDIS_ARG_NX);++ pipe.cmd(REDIS_COMMAND_GET).arg(&redis_key);++ // Execute the transaction.+ // Redis MULTI/EXEC guarantees results are returned in the same order+ // as the commands were queued: [SET result, GET result].+ let results: Vec<redis::Value> = pipe+ .query_async(&mut conn)+ .await+ .change_context(errors::RedisError::SetFailed)+ .attach_printable("Failed to execute the redis transaction")?;++ let msg = "Got unexpected number of results from transaction";+ if results.len() < 2 {+ return Err(report!(errors::RedisError::SetFailed).attach_printable(msg));+ }++ let set_result = results+ .first()+ .cloned()+ .ok_or_else(|| report!(errors::RedisError::SetFailed).attach_printable(msg))?;+ let get_result = results+ .get(1)+ .cloned()+ .ok_or_else(|| report!(errors::RedisError::SetFailed).attach_printable(msg))?;++ // Parse the GET result to get the actual value+ let actual_value: V = FromRedisValue::from_redis_value(get_result)+ .change_context(errors::RedisError::SetFailed)+ .attach_printable("Failed to convert from redis value")?;++ // Check if SET NX succeeded or failed using the existing SetnxReply type+ let setnx_reply = SetnxReply::from_redis_value(set_result)+ .change_context(errors::RedisError::SetFailed)+ .attach_printable("Unexpected result from SET NX operation")?;++ Ok(match setnx_reply {+ SetnxReply::KeySet => SetGetReply::ValueSet(actual_value),+ SetnxReply::KeyNotSet => SetGetReply::ValueExists(actual_value),+ })+ }+}diff --git a/crates/redis_interface/src/module/redis_rs/types.rs b/crates/redis_interface/src/module/redis_rs/types.rsnew file mode 100644index 0000000000..c0cff1a255--- /dev/null+++ b/crates/redis_interface/src/module/redis_rs/types.rs@@ -0,0 +1,526 @@+//! Redis-rs–specific trait implementations for the shared types.++use crate::types::{+ ConsumerGroupDestroyReply, DelReply, HsetnxReply, MsetnxReply, RedisEntryId, RedisValue,+ SaddReply, SetnxReply,+};++// ─── RedisValue impls ────────────────────────────────────────────────────────++impl RedisValue {+ pub fn new(value: redis::Value) -> Self {+ Self { inner: value }+ }++ pub fn from_bytes(val: Vec<u8>) -> Self {+ Self {+ inner: redis::Value::BulkString(val),+ }+ }++ pub fn from_string(value: String) -> Self {+ Self {+ inner: redis::Value::SimpleString(value),+ }+ }++ /// Extract bytes from the underlying redis value.+ ///+ /// Returns `Some` for string-like variants (`BulkString`, `SimpleString`,+ /// `VerbatimString`) and `None` for all others.+ pub fn as_bytes(&self) -> Option<&[u8]> {+ match &self.inner {+ redis::Value::BulkString(bytes) => Some(bytes.as_slice()),+ redis::Value::SimpleString(string) => Some(string.as_bytes()),+ redis::Value::VerbatimString { text, .. } => Some(text.as_bytes()),+ other => {+ tracing::debug!(+ variant = value_variant_name(other),+ "as_bytes() called on non-string RedisValue variant, returning None"+ );+ None+ }+ }+ }++ /// Convert to string if the value has a meaningful string representation.+ ///+ /// Returns `Some` for string-like and scalar variants, `None` for aggregates+ /// and `Nil`.+ pub fn as_string(&self) -> Option<String> {+ match &self.inner {+ redis::Value::BulkString(bytes) => String::from_utf8(bytes.clone()).ok(),+ redis::Value::SimpleString(string) => Some(string.clone()),+ redis::Value::VerbatimString { text, .. } => Some(text.clone()),+ redis::Value::Int(integer) => Some(integer.to_string()),+ redis::Value::Double(double) => Some(double.to_string()),+ redis::Value::Boolean(boolean) => Some(boolean.to_string()),+ redis::Value::Okay => Some("OK".to_string()),+ redis::Value::BigNumber(ref big_number) => Some(big_number.to_string()),+ other => {+ tracing::debug!(+ variant = value_variant_name(other),+ "as_string() called on non-string RedisValue variant, returning None"+ );+ None+ }+ }+ }+}++impl std::ops::Deref for RedisValue {+ type Target = redis::Value;+ fn deref(&self) -> &Self::Target {+ &self.inner+ }+}++impl From<RedisValue> for redis::Value {+ fn from(v: RedisValue) -> Self {+ v.inner+ }+}++impl redis::ToRedisArgs for RedisValue {+ fn write_redis_args<W>(&self, out: &mut W)+ where+ W: ?Sized + redis::RedisWrite,+ {+ match &self.inner {+ redis::Value::BulkString(bytes) => bytes.write_redis_args(out),+ redis::Value::SimpleString(string) => string.write_redis_args(out),+ redis::Value::VerbatimString { text, .. } => text.write_redis_args(out),+ redis::Value::Int(integer) => integer.write_redis_args(out),+ redis::Value::Double(double) => double.to_string().write_redis_args(out),+ redis::Value::Boolean(boolean) => boolean.write_redis_args(out),+ redis::Value::Okay => "OK".write_redis_args(out),+ redis::Value::BigNumber(ref big_number) => big_number.to_string().write_redis_args(out),+ redis::Value::Nil => {+ // Nil cannot be meaningfully represented as a Redis command argument.+ // Writing empty bytes would turn "null" into "empty string", which+ // are semantically different. Skip the write so Redis sees a missing+ // argument rather than an empty one.+ tracing::warn!("Attempted to write Nil as a Redis command argument — skipping");+ }+ // Aggregate and error types cannot be serialized as a single Redis argument.+ // These variants are only expected in Redis *responses*, not as command+ // arguments. Writing empty bytes would silently corrupt data.+ redis::Value::Array(_)+ | redis::Value::Map(_)+ | redis::Value::Set(_)+ | redis::Value::Attribute { .. }+ | redis::Value::Push { .. }+ | redis::Value::ServerError(_) => {+ tracing::warn!(+ variant = ?self.inner,+ "Attempted to write an aggregate/error Redis value as a command argument — skipping. \+ Aggregate types (Array, Map, Set, etc.) should not be used as command arguments."+ );+ }+ // Catch-all for future variants added to the non-exhaustive enum+ _ => {+ tracing::warn!(+ variant = ?self.inner,+ "Attempted to write an unknown Redis value as a command argument — skipping"+ );+ }+ }+ }+}++impl redis::ToSingleRedisArg for RedisValue {}++// ─── RedisEntryId ────────────────────────────────────────────────────────────++impl redis::ToRedisArgs for RedisEntryId {+ fn write_redis_args<W>(&self, out: &mut W)+ where+ W: ?Sized + redis::RedisWrite,+ {+ self.to_stream_id().write_redis_args(out)+ }+}++// ─── Reply type trait impls ──────────────────────────────────────────────────++impl redis::FromRedisValue for SetnxReply {+ fn from_redis_value(v: redis::Value) -> Result<Self, redis::ParsingError> {+ match v {+ // SET NX returns Okay on success+ redis::Value::Okay => Ok(Self::KeySet),+ // Returns Nil if key already exists+ redis::Value::Nil => Ok(Self::KeyNotSet),+ _ => {+ tracing::error!(received = ?v, "Unexpected SETNX command reply from Redis");+ Err(redis::ParsingError::from(format!(+ "Unexpected SETNX command reply: {:?}",+ v+ )))+ }+ }+ }+}++impl redis::FromRedisValue for HsetnxReply {+ fn from_redis_value(v: redis::Value) -> Result<Self, redis::ParsingError> {+ match v {+ redis::Value::Int(1) => Ok(Self::KeySet),+ redis::Value::Int(0) => Ok(Self::KeyNotSet),+ _ => {+ tracing::error!(received = ?v, "Unexpected HSETNX command reply from Redis");+ Err(redis::ParsingError::from(format!(+ "Unexpected HSETNX command reply: {:?}",+ v+ )))+ }+ }+ }+}++impl redis::FromRedisValue for MsetnxReply {+ fn from_redis_value(v: redis::Value) -> Result<Self, redis::ParsingError> {+ match v {+ redis::Value::Int(1) => Ok(Self::KeysSet),+ redis::Value::Int(0) => Ok(Self::KeysNotSet),+ _ => {+ tracing::error!(received = ?v, "Unexpected MSETNX command reply from Redis");+ Err(redis::ParsingError::from(format!(+ "Unexpected MSETNX command reply: {:?}",+ v+ )))+ }+ }+ }+}++impl redis::FromRedisValue for DelReply {+ fn from_redis_value(v: redis::Value) -> Result<Self, redis::ParsingError> {+ match v {+ redis::Value::Int(1) => Ok(Self::KeyDeleted),+ redis::Value::Int(0) => Ok(Self::KeyNotDeleted),+ _ => {+ tracing::error!(received = ?v, "Unexpected DEL command reply from Redis");+ Err(redis::ParsingError::from(format!(+ "Unexpected DEL command reply: {:?}",+ v+ )))+ }+ }+ }+}++impl redis::FromRedisValue for SaddReply {+ fn from_redis_value(v: redis::Value) -> Result<Self, redis::ParsingError> {+ match v {+ redis::Value::Int(1) => Ok(Self::KeySet),+ redis::Value::Int(0) => Ok(Self::KeyNotSet),+ _ => {+ tracing::error!(received = ?v, "Unexpected SADD command reply from Redis");+ Err(redis::ParsingError::from(format!(+ "Unexpected SADD command reply: {:?}",+ v+ )))+ }+ }+ }+}++impl redis::FromRedisValue for ConsumerGroupDestroyReply {+ fn from_redis_value(value: redis::Value) -> Result<Self, redis::ParsingError> {+ match value {+ redis::Value::Int(1) => Ok(Self::Destroyed),+ redis::Value::Int(0) => Ok(Self::NotFound),+ _ => {+ tracing::error!(+ received = ?value,+ "Unexpected XGROUP DESTROY reply from Redis"+ );+ Err(redis::ParsingError::from(format!(+ "Unexpected XGROUP DESTROY reply: {:?}",+ value+ )))+ }+ }+ }+}++// ─── Redis-rs-specific helpers ───────────────────────────────────────────────++/// Returns the variant name of a `redis::Value` without any inner data.+/// Used for logging to avoid printing potentially large payloads.+pub(crate) fn value_variant_name(value: &redis::Value) -> &'static str {+ match value {+ redis::Value::Nil => "Nil",+ redis::Value::Int(_) => "Int",+ redis::Value::BulkString(_) => "BulkString",+ redis::Value::Array(_) => "Array",+ redis::Value::Push { .. } => "Push",+ redis::Value::Okay => "Okay",+ redis::Value::SimpleString(_) => "SimpleString",+ redis::Value::Map(_) => "Map",+ redis::Value::Attribute { .. } => "Attribute",+ redis::Value::Set(_) => "Set",+ redis::Value::Double(_) => "Double",+ redis::Value::Boolean(_) => "Boolean",+ redis::Value::VerbatimString { .. } => "VerbatimString",+ redis::Value::BigNumber(_) => "BigNumber",+ redis::Value::ServerError(_) => "ServerError",+ _ => "Unknown",+ }+}++/// Converts a `redis::Value` to `Option<String>`.+///+/// - String-like variants (`BulkString`, `SimpleString`, `VerbatimString`) → decoded string+/// - Scalar variants (`Int`, `Double`, `Boolean`, `Okay`, `BigNumber`) → string representation+/// - `Nil` and aggregate types (`Array`, `Map`, `Set`, `Attribute`, `Push`, `ServerError`) → `None`+pub fn redis_value_to_option_string(v: &redis::Value) -> Option<String> {+ match v {+ redis::Value::BulkString(bytes) => std::str::from_utf8(bytes)+ .ok()+ .map(|utf8_str| utf8_str.to_string()),+ redis::Value::SimpleString(string) => Some(string.clone()),+ redis::Value::VerbatimString { text, .. } => Some(text.clone()),+ redis::Value::Int(integer) => Some(integer.to_string()),+ redis::Value::Double(double) => Some(double.to_string()),+ redis::Value::Boolean(boolean) => Some(boolean.to_string()),+ redis::Value::Okay => Some("OK".to_string()),+ redis::Value::BigNumber(ref big_number) => Some(big_number.to_string()),+ // Nil and aggregate types have no meaningful single-string representation+ redis::Value::Nil+ | redis::Value::Array(_)+ | redis::Value::Map(_)+ | redis::Value::Set(_)+ | redis::Value::Attribute { .. }+ | redis::Value::Push { .. }+ | redis::Value::ServerError(_) => None,+ // Catch-all for future variants added to the non-exhaustive enum+ _ => None,+ }+}++// ─── Backend-specific tests ──────────────────────────────────────────────────++#[cfg(test)]+mod tests {+ use redis::FromRedisValue;++ use crate::types::{+ DelReply, HsetnxReply, MsetnxReply, RedisEntryId, RedisValue, SaddReply, SetnxReply,+ };++ /// Critical: Tests that serializing bulk string produces correct bytes+ #[test]+ fn test_redis_value_to_redis_args_bulk_string() {+ let value = RedisValue::from_bytes(b"hello".to_vec());+ let mut args = Vec::new();+ redis::ToRedisArgs::write_redis_args(&value, &mut args);+ assert_eq!(args, vec![b"hello".as_slice()]);+ }++ #[test]+ fn test_redis_value_to_redis_args_simple_string() {+ let value = RedisValue::from_string("world".to_string());+ let mut args = Vec::new();+ redis::ToRedisArgs::write_redis_args(&value, &mut args);+ assert_eq!(args, vec![b"world".as_slice()]);+ }++ #[test]+ fn test_redis_value_to_redis_args_int() {+ let value = RedisValue::new(redis::Value::Int(42));+ let mut args = Vec::new();+ redis::ToRedisArgs::write_redis_args(&value, &mut args);+ assert_eq!(args, vec![b"42".as_slice()]);+ }++ #[test]+ fn test_redis_value_to_redis_args_double() {+ let value = RedisValue::new(redis::Value::Double(1.5));+ let mut args = Vec::new();+ redis::ToRedisArgs::write_redis_args(&value, &mut args);+ assert_eq!(args, vec![b"1.5".as_slice()]);+ }++ #[test]+ fn test_redis_value_to_redis_args_boolean_true() {+ let value = RedisValue::new(redis::Value::Boolean(true));+ let mut args = Vec::new();+ redis::ToRedisArgs::write_redis_args(&value, &mut args);+ assert_eq!(args, vec![b"1".as_slice()]);+ }++ #[test]+ fn test_redis_value_to_redis_args_boolean_false() {+ let value = RedisValue::new(redis::Value::Boolean(false));+ let mut args = Vec::new();+ redis::ToRedisArgs::write_redis_args(&value, &mut args);+ assert_eq!(args, vec![b"0".as_slice()]);+ }++ #[test]+ fn test_redis_value_to_redis_args_verbatim_string() {+ let value = RedisValue::new(redis::Value::VerbatimString {+ format: redis::VerbatimFormat::Text,+ text: "verbatim".to_string(),+ });+ let mut args = Vec::new();+ redis::ToRedisArgs::write_redis_args(&value, &mut args);+ assert_eq!(args, vec![b"verbatim".as_slice()]);+ }++ #[test]+ fn test_redis_value_to_redis_args_okay() {+ let value = RedisValue::new(redis::Value::Okay);+ let mut args = Vec::new();+ redis::ToRedisArgs::write_redis_args(&value, &mut args);+ assert_eq!(args, vec![b"OK".as_slice()]);+ }++ #[test]+ fn test_redis_value_to_redis_args_nil_skips() {+ // Nil should not write any arguments (skip), not empty bytes+ let value = RedisValue::new(redis::Value::Nil);+ let mut args = Vec::new();+ redis::ToRedisArgs::write_redis_args(&value, &mut args);+ assert!(+ args.is_empty(),+ "Nil should produce no arguments, got {args:?}"+ );+ }++ #[test]+ fn test_redis_value_to_redis_args_array_skips() {+ // Aggregate types should not write any arguments (skip)+ let value = RedisValue::new(redis::Value::Array(vec![+ redis::Value::Int(1),+ redis::Value::Int(2),+ ]));+ let mut args = Vec::new();+ redis::ToRedisArgs::write_redis_args(&value, &mut args);+ assert!(+ args.is_empty(),+ "Array should produce no arguments, got {args:?}"+ );+ }++ #[test]+ fn test_entry_id_to_redis_args_user_specified() {+ let id = RedisEntryId::UserSpecifiedID {+ milliseconds: "1234567890".to_string(),+ sequence_number: "0".to_string(),+ };+ let mut args = Vec::new();+ redis::ToRedisArgs::write_redis_args(&id, &mut args);+ assert_eq!(args, vec![b"1234567890-0".as_slice()]);+ }++ #[test]+ fn test_entry_id_to_redis_args_auto_generated() {+ let id = RedisEntryId::AutoGeneratedID;+ let mut args = Vec::new();+ redis::ToRedisArgs::write_redis_args(&id, &mut args);+ assert_eq!(args, vec![b"*".as_slice()]);+ }++ #[test]+ fn test_entry_id_to_redis_args_after_last() {+ let id = RedisEntryId::AfterLastID;+ let mut args = Vec::new();+ redis::ToRedisArgs::write_redis_args(&id, &mut args);+ assert_eq!(args, vec![b"$".as_slice()]);+ }++ #[test]+ fn test_entry_id_to_redis_args_undelivered() {+ let id = RedisEntryId::UndeliveredEntryID;+ let mut args = Vec::new();+ redis::ToRedisArgs::write_redis_args(&id, &mut args);+ assert_eq!(args, vec![b">".as_slice()]);+ }++ #[test]+ fn test_setnx_reply_okay() {+ assert_eq!(+ SetnxReply::from_redis_value(redis::Value::Okay).unwrap(),+ SetnxReply::KeySet+ );+ }++ #[test]+ fn test_setnx_reply_nil() {+ assert_eq!(+ SetnxReply::from_redis_value(redis::Value::Nil).unwrap(),+ SetnxReply::KeyNotSet+ );+ }++ #[test]+ fn test_setnx_reply_unexpected() {+ assert!(SetnxReply::from_redis_value(redis::Value::Int(99)).is_err());+ }++ #[test]+ fn test_hsetnx_reply_key_set() {+ assert_eq!(+ HsetnxReply::from_redis_value(redis::Value::Int(1)).unwrap(),+ HsetnxReply::KeySet+ );+ }++ #[test]+ fn test_hsetnx_reply_key_not_set() {+ assert_eq!(+ HsetnxReply::from_redis_value(redis::Value::Int(0)).unwrap(),+ HsetnxReply::KeyNotSet+ );+ }++ #[test]+ fn test_msetnx_reply_keys_set() {+ assert_eq!(+ MsetnxReply::from_redis_value(redis::Value::Int(1)).unwrap(),+ MsetnxReply::KeysSet+ );+ }++ #[test]+ fn test_msetnx_reply_keys_not_set() {+ assert_eq!(+ MsetnxReply::from_redis_value(redis::Value::Int(0)).unwrap(),+ MsetnxReply::KeysNotSet+ );+ }++ #[test]+ fn test_del_reply_one() {+ assert_eq!(+ DelReply::from_redis_value(redis::Value::Int(1)).unwrap(),+ DelReply::KeyDeleted+ );+ }++ #[test]+ fn test_del_reply_zero() {+ assert_eq!(+ DelReply::from_redis_value(redis::Value::Int(0)).unwrap(),+ DelReply::KeyNotDeleted+ );+ }++ #[test]+ fn test_sadd_reply_key_set() {+ assert_eq!(+ SaddReply::from_redis_value(redis::Value::Int(1)).unwrap(),+ SaddReply::KeySet+ );+ }++ #[test]+ fn test_sadd_reply_key_not_set() {+ assert_eq!(+ SaddReply::from_redis_value(redis::Value::Int(0)).unwrap(),+ SaddReply::KeyNotSet+ );+ }+}diff --git a/crates/redis_interface/src/test.rs b/crates/redis_interface/src/test.rsnew file mode 100644index 0000000000..7456449a98--- /dev/null+++ b/crates/redis_interface/src/test.rs@@ -0,0 +1,2318 @@+//! Shared integration tests for the redis_interface crate.+//!+//! These tests exercise the **public API** only — `RedisConnectionPool`,+//! `RedisKey`, `RedisEntryId`, `RedisValue`, etc. — and therefore+//! validate both the `fred` and `redis-rs` module with the same+//! test suite.+//!+//! Run with redis-rs (default):+//! cargo test -p redis_interface+//!+//! Run with fred:+//! cargo test -p redis_interface --no-default-features --features fred++use std::collections::HashMap;++use crate::{+ ConsumerGroupDestroyReply, DelReply, HsetnxReply, MsetnxReply, RedisConnectionPool,+ RedisEntryId, RedisKey, RedisSettings, RedisValue, SaddReply, SetGetReply, SetnxReply,+ StreamCapKind, StreamCapTrim, StreamTrimConfig,+};++// ─── Helpers ──────────────────────────────────────────────────────────────────++/// Generate a unique ID for test key isolation.+/// Uses PID + nanoseconds + counter for global uniqueness across parallel runs.+fn unique_test_id() -> String {+ use std::sync::atomic::{AtomicU64, Ordering};+ static COUNTER: AtomicU64 = AtomicU64::new(0);+ let counter = COUNTER.fetch_add(1, Ordering::SeqCst);+ let pid = std::process::id();+ let millis = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_millis())+ .unwrap_or(0);+ format!("{pid}_{millis}_{counter}")+}++/// Convert a `RedisValue` to `Option<String>`.+/// Works for both module because `RedisValue::as_string()` is a shared method.+fn redis_value_to_option_string(v: &RedisValue) -> Option<String> {+ v.as_string()+}++/// Create a cluster `RedisConnectionPool` if `REDIS_CLUSTER_URLS` env var is set.+/// Returns `None` if no cluster is configured (test should skip, not fail).+async fn cluster_pool() -> Option<RedisConnectionPool> {+ let cluster_urls_str = std::env::var("REDIS_CLUSTER_URLS").ok()?;+ let cluster_urls: Vec<String> = cluster_urls_str+ .split(',')+ .map(|url| url.trim().to_string())+ .filter(|url| !url.is_empty())+ .collect();++ if cluster_urls.is_empty() {+ return None;+ }++ let first_url = cluster_urls.first()?;+ let (host, port) = if first_url.starts_with("redis://") {+ let without_scheme = first_url.trim_start_matches("redis://");+ let parts: Vec<&str> = without_scheme.split(':').collect();+ (+ parts.first()?.to_string(),+ parts.get(1)?.parse::<u16>().ok()?,+ )+ } else {+ let parts: Vec<&str> = first_url.split(':').collect();+ (+ parts.first()?.to_string(),+ parts.get(1)?.parse::<u16>().ok()?,+ )+ };++ let settings = RedisSettings {+ host,+ port,+ cluster_enabled: true,+ cluster_urls,+ ..RedisSettings::default()+ };++ RedisConnectionPool::new(&settings).await.ok()+}++/// Helper: get a cluster pool or skip the test.+async fn get_cluster_pool_or_skip() -> Option<RedisConnectionPool> {+ let pool = cluster_pool().await;+ if pool.is_none() {+ tracing::warn!(+ "SKIP: Cluster test skipped — set REDIS_CLUSTER_URLS to enable. \+ Example: REDIS_CLUSTER_URLS=redis://localhost:7000,redis://localhost:7001"+ );+ }+ pool+}++async fn get_cluster_pool_with_uid() -> Option<(RedisConnectionPool, String)> {+ let pool = get_cluster_pool_or_skip().await?;+ let unique_id = unique_test_id();+ Some((pool, unique_id))+}++// ─── Consumer Group Validation ────────────────────────────────────────────────++#[tokio::test]+async fn test_consumer_group_create() {+ let is_invalid_redis_entry_error = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let redis_conn = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");++ let result1 = redis_conn+ .consumer_group_create(&"TEST1".into(), "GTEST", &RedisEntryId::AutoGeneratedID)+ .await;++ let result2 = redis_conn+ .consumer_group_create(&"TEST3".into(), "GTEST", &RedisEntryId::UndeliveredEntryID)+ .await;++ *result1.unwrap_err().current_context()+ == crate::errors::RedisError::InvalidRedisEntryId+ && *result2.unwrap_err().current_context()+ == crate::errors::RedisError::InvalidRedisEntryId+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_invalid_redis_entry_error);+}++// ─── Key Commands ─────────────────────────────────────────────────────────────++#[tokio::test]+async fn test_delete_existing_key_success() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let _ = pool.set_key(&"key".into(), "value".to_string()).await;+ pool.delete_key(&"key".into()).await.is_ok()+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_delete_non_existing_key_success() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ pool.delete_key(&"key not exists".into()).await.is_ok()+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_delete_key_returns_correct_reply() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let existing_key: RedisKey = format!("test_del_exist_{uid}").into();+ let non_existing_key: RedisKey = format!("test_del_miss_{uid}").into();++ let _ = pool.set_key(&existing_key, "value".to_string()).await;++ let delete_existing = pool.delete_key(&existing_key).await;+ let delete_non_existing = pool.delete_key(&non_existing_key).await;++ matches!(delete_existing, Ok(DelReply::KeyDeleted))+ && matches!(delete_non_existing, Ok(DelReply::KeyNotDeleted))+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_delete_key_reply_semantics() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let existing_key: RedisKey = format!("test_del_existing_{uid}").into();+ let non_existing_key: RedisKey = format!("test_del_nonexisting_{uid}").into();++ let _ = pool.set_key(&existing_key, "value".to_string()).await;++ let delete_existing = pool.delete_key(&existing_key).await;+ let delete_non_existing = pool.delete_key(&non_existing_key).await;++ matches!(delete_existing, Ok(DelReply::KeyDeleted))+ && matches!(delete_non_existing, Ok(DelReply::KeyNotDeleted))+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_delete_multiple_keys() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let key1: RedisKey = format!("test_del_multi_a_{uid}").into();+ let key2: RedisKey = format!("test_del_multi_b_{uid}").into();+ let key3: RedisKey = format!("test_del_multi_c_{uid}").into();++ let _ = pool.set_key(&key1, "val1".to_string()).await;+ let _ = pool.set_key(&key2, "val2".to_string()).await;++ let result = pool.delete_multiple_keys(&[key1, key2, key3]).await;++ match result {+ Ok(replies) => {+ replies.len() == 3+ && replies.first() == Some(&DelReply::KeyDeleted)+ && replies.get(1) == Some(&DelReply::KeyDeleted)+ && replies.get(2) == Some(&DelReply::KeyNotDeleted)+ }+ Err(_) => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_exists_key() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let existing_key: RedisKey = format!("test_exists_yes_{uid}").into();+ let missing_key: RedisKey = format!("test_exists_no_{uid}").into();++ let _ = pool.set_key(&existing_key, "val".to_string()).await;++ let exists_result: Result<bool, _> = pool.exists::<()>(&existing_key).await;+ let missing_result: Result<bool, _> = pool.exists::<()>(&missing_key).await;++ matches!(exists_result, Ok(true)) && matches!(missing_result, Ok(false))+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_set_key_with_expiry() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let key: RedisKey = format!("test_set_expiry_{}", unique_test_id()).into();+ pool.set_key_with_expiry(&key, "test_value".to_string(), 60)+ .await+ .is_ok()+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_set_key_without_modifying_ttl() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let key: RedisKey = format!("test_keepttl_{}", unique_test_id()).into();+ let initial_value = "initial".to_string();+ let new_value = "new_value".to_string();++ let _ = pool.set_key_with_expiry(&key, initial_value, 60).await;++ pool.set_key_without_modifying_ttl(&key, new_value.clone())+ .await+ .is_ok()+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_set_key_if_not_exists_with_expiry_new_key() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let key: RedisKey = format!("test_setnx_new_{}", unique_test_id()).into();+ let value = "test_value".to_string();++ let result = pool+ .set_key_if_not_exists_with_expiry(&key, value.clone(), Some(60))+ .await;++ matches!(result, Ok(SetnxReply::KeySet))+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_set_key_if_not_exists_with_expiry_existing_key() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let key: RedisKey = format!("test_setnx_exist_{}", unique_test_id()).into();+ let initial_value = "initial".to_string();++ let _ = pool.set_key(&key, initial_value.clone()).await;++ let result = pool+ .set_key_if_not_exists_with_expiry(&key, "new_value".to_string(), Some(60))+ .await;++ matches!(result, Ok(SetnxReply::KeyNotSet))+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_set_key_if_not_exists_and_get_value_new_key() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let key: RedisKey = format!("test_new_key_string_{}", unique_test_id()).into();+ let value = "test_value".to_string();++ let result = pool+ .set_key_if_not_exists_and_get_value(&key, value.clone(), Some(30))+ .await;++ match result {+ Ok(SetGetReply::ValueSet(returned_value)) => returned_value == value,+ _ => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_set_key_if_not_exists_and_get_value_existing_key() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let key: RedisKey = format!("test_existing_key_string_{}", unique_test_id()).into();+ let initial_value = "initial_value".to_string();+ let new_value = "new_value".to_string();++ let _ = pool.set_key(&key, initial_value.clone()).await;++ let result = pool+ .set_key_if_not_exists_and_get_value(&key, new_value, Some(30))+ .await;++ match result {+ Ok(SetGetReply::ValueExists(returned_value)) => returned_value == initial_value,+ _ => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_set_key_if_not_exists_and_get_value_with_default_ttl() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let key: RedisKey = format!("test_default_ttl_key_string_{}", unique_test_id()).into();+ let value = "test_value".to_string();++ let result = pool+ .set_key_if_not_exists_and_get_value(&key, value.clone(), None)+ .await;++ match result {+ Ok(SetGetReply::ValueSet(returned_value)) => returned_value == value,+ _ => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_set_key_if_not_exists_and_get_value_concurrent_access() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let key_name = &format!("test_concurrent_key_string_{}", unique_test_id());+ let value1 = "value1".to_string();+ let value2 = "value2".to_string();++ let pool1 = pool.clone("");+ let pool2 = pool.clone("");+ let key1 = key_name.into();+ let key2 = key_name.into();++ let (result1, result2) = tokio::join!(+ pool1.set_key_if_not_exists_and_get_value(&key1, value1, Some(30)),+ pool2.set_key_if_not_exists_and_get_value(&key2, value2, Some(30))+ );++ let result1_is_set = matches!(result1, Ok(SetGetReply::ValueSet(_)));+ let result2_is_set = matches!(result2, Ok(SetGetReply::ValueSet(_)));+ let result1_is_exists = matches!(result1, Ok(SetGetReply::ValueExists(_)));+ let result2_is_exists = matches!(result2, Ok(SetGetReply::ValueExists(_)));++ (result1_is_set && result2_is_exists) || (result1_is_exists && result2_is_set)+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_resp3_set_and_get() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let key: RedisKey = format!("test_resp3_{}", unique_test_id()).into();+ let value = "resp3_value".to_string();+ let _ = pool.set_key(&key, value.clone()).await;+ let result: Result<String, _> = pool.get_key(&key).await;+ result.is_ok() && result.unwrap() == value+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_connection_with_custom_config() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let settings = RedisSettings {+ reconnect_max_attempts: 10,+ reconnect_delay: 100,+ default_command_timeout: 60,+ max_in_flight_commands: 10000,+ ..RedisSettings::default()+ };++ let pool = RedisConnectionPool::new(&settings)+ .await+ .expect("failed to create redis connection pool with custom config");++ let key: RedisKey = format!("test_config_{}", unique_test_id()).into();+ let value = "custom_config_value".to_string();+ let _ = pool.set_key(&key, value.clone()).await;+ let result: Result<String, _> = pool.get_key(&key).await;+ result.is_ok() && result.unwrap() == value+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++// ─── Get / Multiple Keys ──────────────────────────────────────────────────────++#[tokio::test]+async fn test_get_multiple_keys_success() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");++ let keys = vec![+ "multi_test_key1".into(),+ "multi_test_key2".into(),+ "multi_test_key3".into(),+ ];+ let values = ["value1", "value2", "value3"];++ for (key, value) in keys.iter().zip(values.iter()) {+ let _ = pool.set_key(key, value.to_string()).await;+ }++ let result = pool.get_multiple_keys::<String>(&keys).await;++ match result {+ Ok(retrieved_values) => {+ retrieved_values.len() == 3+ && retrieved_values.first() == Some(&Some("value1".to_string()))+ && retrieved_values.get(1) == Some(&Some("value2".to_string()))+ && retrieved_values.get(2) == Some(&Some("value3".to_string()))+ }+ _ => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_get_multiple_keys_with_missing_keys() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");++ let keys = vec![+ "existing_key".into(),+ "non_existing_key".into(),+ "another_existing_key".into(),+ ];++ let _ = pool+ .set_key(+ keys.first().expect("should not be none"),+ "value1".to_string(),+ )+ .await;+ let _ = pool+ .set_key(+ keys.get(2).expect("should not be none"),+ "value3".to_string(),+ )+ .await;++ let result = pool.get_multiple_keys::<String>(&keys).await;++ match result {+ Ok(retrieved_values) => {+ retrieved_values.len() == 3+ && *retrieved_values.first().expect("should not be none")+ == Some("value1".to_string())+ && retrieved_values.get(1).is_some_and(|v| v.is_none())+ && *retrieved_values.get(2).expect("should not be none")+ == Some("value3".to_string())+ }+ _ => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_get_multiple_keys_empty_input() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");++ let keys: Vec<RedisKey> = vec![];+ let result = pool.get_multiple_keys::<String>(&keys).await;++ match result {+ Ok(retrieved_values) => retrieved_values.is_empty(),+ _ => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_get_and_deserialize_key() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let key: RedisKey = format!("test_deser_single_{uid}").into();++ #[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug)]+ struct Data {+ x: i32,+ }++ let data = Data { x: 42 };+ let _ = pool.serialize_and_set_key(&key, &data).await;+ let result = pool.get_and_deserialize_key::<Data>(&key, "Data").await;++ match result {+ Ok(retrieved) => retrieved == data,+ Err(_) => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_get_and_deserialize_key_not_found() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let key: RedisKey = "nonexistent_deser_key".into();++ let result: Result<String, _> = pool.get_and_deserialize_key(&key, "String").await;+ result.is_err()+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_get_and_deserialize_multiple_keys() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");++ #[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug, Clone)]+ struct TestData {+ id: u32,+ name: String,+ }++ let test_data = [+ TestData {+ id: 1,+ name: "test1".to_string(),+ },+ TestData {+ id: 2,+ name: "test2".to_string(),+ },+ ];++ let keys = vec![+ "serialize_test_key1".into(),+ "serialize_test_key2".into(),+ "non_existing_serialize_key".into(),+ ];++ for (i, data) in test_data.iter().enumerate() {+ let _ = pool+ .serialize_and_set_key(keys.get(i).expect("should not be none"), data)+ .await;+ }++ let result = pool+ .get_and_deserialize_multiple_keys::<TestData>(&keys, "TestData")+ .await;++ match result {+ Ok(retrieved_data) => {+ retrieved_data.len() == 3+ && retrieved_data.first() == Some(&Some(test_data[0].clone()))+ && retrieved_data.get(1) == Some(&Some(test_data[1].clone()))+ && retrieved_data.get(2) == Some(&None)+ }+ _ => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++// ─── Serialization ────────────────────────────────────────────────────────────++#[tokio::test]+async fn test_serialize_and_set_key_if_not_exist() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let key: RedisKey = format!("test_ser_setnx_{uid}").into();++ #[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug)]+ struct Data {+ id: u32,+ }++ let data = Data { id: 99 };++ let set_result = pool+ .serialize_and_set_key_if_not_exist(&key, &data, Some(60))+ .await;++ let dup_result = pool+ .serialize_and_set_key_if_not_exist(&key, &Data { id: 100 }, Some(60))+ .await;++ matches!(+ (set_result, dup_result),+ (Ok(SetnxReply::KeySet), Ok(SetnxReply::KeyNotSet),)+ )+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_serialize_and_set_key_with_expiry() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let key: RedisKey = format!("test_ser_setex_{uid}").into();++ #[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug)]+ struct Data {+ name: String,+ }++ let data = Data {+ name: "test".to_string(),+ };++ let set_result = pool+ .serialize_and_set_key_with_expiry(&key, &data, 120)+ .await;++ let get_result = pool.get_and_deserialize_key::<Data>(&key, "Data").await;++ match (set_result, get_result) {+ (Ok(()), Ok(retrieved)) => retrieved == data,+ _ => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_serialize_and_set_key_without_modifying_ttl() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let key: RedisKey = format!("test_ser_keepttl_{uid}").into();++ #[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug)]+ struct Data {+ val: i32,+ }++ let _ = pool+ .serialize_and_set_key_with_expiry(&key, &Data { val: 1 }, 120)+ .await;++ let update_result = pool+ .serialize_and_set_key_without_modifying_ttl(&key, &Data { val: 2 })+ .await;++ let get_result = pool.get_and_deserialize_key::<Data>(&key, "Data").await;++ match (update_result, get_result) {+ (Ok(()), Ok(retrieved)) => retrieved.val == 2,+ _ => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++// ─── TTL ──────────────────────────────────────────────────────────────────────++#[tokio::test]+async fn test_set_expiry_and_get_ttl() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let key: RedisKey = format!("test_ttl_{uid}").into();++ let _ = pool.set_key(&key, "value".to_string()).await;++ let set_expiry_result = pool.set_expiry(&key, 120).await;+ let ttl_result = pool.get_ttl(&key).await;++ match (set_expiry_result, ttl_result) {+ (Ok(()), Ok(ttl)) => ttl > 0 && ttl <= 120,+ _ => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_set_expire_at_and_get_ttl() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let key: RedisKey = format!("test_expireat_{uid}").into();++ let _ = pool.set_key(&key, "value".to_string()).await;++ let future_ts = i64::try_from(+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_secs(),+ )+ .unwrap()+ + 120;+ let set_result = pool.set_expire_at(&key, future_ts).await;+ let ttl_result = pool.get_ttl(&key).await;++ match (set_result, ttl_result) {+ (Ok(()), Ok(ttl)) => ttl > 0 && ttl <= 120,+ _ => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++// ─── Hash Commands ────────────────────────────────────────────────────────────++#[tokio::test]+async fn test_set_hash_fields() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let key: RedisKey = format!("test_hash_{}", unique_test_id()).into();+ let fields: Vec<(&str, &str)> = vec![+ ("field1", "value1"),+ ("field2", "value2"),+ ("field3", "value3"),+ ];++ pool.set_hash_fields(&key, fields, Some(60)).await.is_ok()+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_set_hash_field_if_not_exist_and_get() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let key: RedisKey = format!("test_hsetnx_{uid}").into();++ let set_result = pool+ .set_hash_field_if_not_exist(&key, "field1", "value1", None)+ .await;++ let dup_result = pool+ .set_hash_field_if_not_exist(&key, "field1", "value2", None)+ .await;++ let get_result: Result<String, _> = pool.get_hash_field(&key, "field1").await;++ let all_fields: Result<HashMap<String, String>, _> = pool.get_hash_fields(&key).await;++ match (set_result, dup_result, get_result, all_fields) {+ (Ok(HsetnxReply::KeySet), Ok(HsetnxReply::KeyNotSet), Ok(val), Ok(map)) => {+ val == "value1" && map.get("field1") == Some(&"value1".to_string())+ }+ _ => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_increment_fields_in_hash() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let key: RedisKey = format!("test_hincr_{uid}").into();++ let fields: Vec<(&str, &str)> = vec![("counter", "10")];+ let _ = pool.set_hash_fields(&key, fields, Some(60)).await;++ let result = pool+ .increment_fields_in_hash(&key, &[("counter".to_string(), 5)])+ .await;++ match result {+ Ok(values) => values.len() == 1 && values.first() == Some(&15),+ Err(_) => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_hscan_returns_values() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let key: RedisKey = format!("test_hscan_{uid}").into();++ let fields: Vec<(&str, &str)> = vec![+ ("prefix_field1", "val1"),+ ("prefix_field2", "val2"),+ ("other_field", "val3"),+ ];+ let _ = pool.set_hash_fields(&key, fields, Some(60)).await;++ let scan_result = pool.hscan(&key, "prefix_*", None).await;++ match scan_result {+ Ok(values) => {+ values.contains(&"val1".to_string())+ && values.contains(&"val2".to_string())+ && !values.contains(&"val3".to_string())+ }+ Err(_) => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_hscan_and_deserialize() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let key: RedisKey = format!("test_hscan_deser_{uid}").into();++ let fields: Vec<(&str, &str)> = vec![+ ("item_a", "\"alpha\""),+ ("item_b", "\"beta\""),+ ("item_c", "\"gamma\""),+ ];+ let _ = pool.set_hash_fields(&key, fields, Some(60)).await;++ let result = pool+ .hscan_and_deserialize::<String>(&key, "item_*", None)+ .await;++ match result {+ Ok(values) => {+ values.contains(&"alpha".to_string())+ && values.contains(&"beta".to_string())+ && values.contains(&"gamma".to_string())+ }+ Err(_) => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_sadd_and_get_hash_field_and_deserialize() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let set_key: RedisKey = format!("test_sadd_{uid}").into();+ let hash_key: RedisKey = format!("test_hget_deser_{uid}").into();++ // SADD+ let sadd_result = pool.sadd(&set_key, "member1").await;+ let sadd_dup = pool.sadd(&set_key, "member1").await;++ // get_hash_field_and_deserialize+ #[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug)]+ struct TestData {+ id: u32,+ }+ let data = TestData { id: 42 };+ let _ = pool+ .serialize_and_set_hash_field_if_not_exist(&hash_key, "data", &data, None)+ .await;++ let deser_result = pool+ .get_hash_field_and_deserialize::<TestData>(&hash_key, "data", "TestData")+ .await;++ match (sadd_result, sadd_dup, deser_result) {+ (Ok(SaddReply::KeySet), Ok(SaddReply::KeyNotSet), Ok(deserialized)) => {+ deserialized == data+ }+ _ => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_serialize_and_set_multiple_hash_field_if_not_exist() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let key1: RedisKey = format!("test_ser_hsetnx_multi_a_{uid}").into();+ let key2: RedisKey = format!("test_ser_hsetnx_multi_b_{uid}").into();++ #[derive(serde::Serialize, Debug)]+ struct Data {+ id: u32,+ }++ let result = pool+ .serialize_and_set_multiple_hash_field_if_not_exist(+ &[(&key1, Data { id: 1 }), (&key2, Data { id: 2 })],+ "data",+ None,+ )+ .await;++ match result {+ Ok(replies) => {+ replies.len() == 2+ && replies.first() == Some(&HsetnxReply::KeySet)+ && replies.get(1) == Some(&HsetnxReply::KeySet)+ }+ Err(_) => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++// ─── MSETNX ───────────────────────────────────────────────────────────────────++#[tokio::test]+async fn test_set_multiple_keys_if_not_exist_msetnx() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let key1: RedisKey = format!("test_msetnx_a_{uid}").into();+ let key2: RedisKey = format!("test_msetnx_b_{uid}").into();++ let result = pool+ .set_multiple_keys_if_not_exist(&[+ (key1.tenant_aware_key(&pool), "val1"),+ (key2.tenant_aware_key(&pool), "val2"),+ ])+ .await;++ matches!(result, Ok(MsetnxReply::KeysSet))+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_set_multiple_keys_if_not_exist_with_existing_key() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let key1: RedisKey = format!("test_msetnx_exist_a_{uid}").into();+ let key2: RedisKey = format!("test_msetnx_exist_b_{uid}").into();++ let _ = pool.set_key(&key1, "existing".to_string()).await;++ let result = pool+ .set_multiple_keys_if_not_exist(&[+ (key1.tenant_aware_key(&pool), "new1"),+ (key2.tenant_aware_key(&pool), "new2"),+ ])+ .await;++ matches!(result, Ok(MsetnxReply::KeysNotSet))+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_set_multiple_keys_if_not_exists_and_get_values() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let key1: RedisKey = format!("test_setget_multi_a_{uid}").into();+ let key2: RedisKey = format!("test_setget_multi_b_{uid}").into();++ let result = pool+ .set_multiple_keys_if_not_exists_and_get_values(+ &[(key1, "val1".to_string()), (key2, "val2".to_string())],+ Some(30),+ )+ .await;++ match result {+ Ok(replies) => {+ replies.len() == 2+ && matches!(replies.first(), Some(SetGetReply::ValueSet(ref value)) if value == "val1")+ && matches!(replies.get(1), Some(SetGetReply::ValueSet(ref value)) if value == "val2")+ }+ Err(_) => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++// ─── Stream Commands ──────────────────────────────────────────────────────────++#[tokio::test]+async fn test_stream_append_and_get_length() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let stream: RedisKey = format!("test_stream_append_{}", unique_test_id()).into();+ let fields: Vec<(&str, &str)> = vec![("field1", "value1")];++ let append_result = pool+ .stream_append_entry(&stream, &RedisEntryId::AutoGeneratedID, fields)+ .await;++ let length_result = pool.stream_get_length(&stream).await;++ append_result.is_ok() && length_result.is_ok() && length_result.unwrap() >= 1+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_stream_read_entries_xread() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let stream: RedisKey = format!("test_stream_read_entries_{uid}").into();++ let fields1: Vec<(&str, &str)> = vec![("field1", "value1")];+ let fields2: Vec<(&str, &str)> = vec![("field2", "value2")];+ let _ = pool+ .stream_append_entry(&stream, &RedisEntryId::AutoGeneratedID, fields1)+ .await;+ let _ = pool+ .stream_append_entry(&stream, &RedisEntryId::AutoGeneratedID, fields2)+ .await;++ let result = pool+ .stream_read_entries(+ std::slice::from_ref(&stream),+ vec!["0-0".to_string()],+ Some(10),+ )+ .await;++ match result {+ Ok(grouped) => {+ let stream_key = pool.add_prefix(&format!("test_stream_read_entries_{uid}"));+ let entries = grouped.get(&stream_key);+ entries.is_some() && entries.unwrap().len() == 2+ }+ Err(_) => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_stream_read_entries() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let stream: RedisKey = format!("test_xread_{uid}").into();++ let fields: Vec<(&str, &str)> = vec![("f", "v")];+ let _ = pool+ .stream_append_entry(&stream, &RedisEntryId::AutoGeneratedID, fields)+ .await;++ let result = pool+ .stream_read_entries(+ std::slice::from_ref(&stream),+ vec!["0-0".to_string()],+ Some(10),+ )+ .await;++ match result {+ Ok(reply) => {+ reply.len() == 1+ && reply+ .values()+ .next()+ .is_some_and(|entries| !entries.is_empty())+ }+ Err(_) => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_stream_read_with_options_xreadgroup() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let stream: RedisKey = format!("test_xreadgroup_{uid}").into();+ let group = format!("test_grp_{uid}");+ let consumer = format!("test_consumer_{uid}");++ let fields: Vec<(&str, &str)> = vec![("task", "process_payment")];+ pool.stream_append_entry(&stream, &RedisEntryId::AutoGeneratedID, fields)+ .await+ .expect("failed to append");++ pool.consumer_group_create(+ &stream,+ &group,+ &RedisEntryId::UserSpecifiedID {+ milliseconds: "0".to_string(),+ sequence_number: "0".to_string(),+ },+ )+ .await+ .expect("failed to create group");++ let result = pool+ .stream_read_with_options(+ &[stream],+ vec![RedisEntryId::UndeliveredEntryID.to_stream_id()],+ Some(1),+ None,+ Some((&group, &consumer)),+ )+ .await;++ match result {+ Ok(reply) => {+ reply.len() == 1+ && reply+ .values()+ .next()+ .is_some_and(|entries| entries.len() == 1)+ && reply+ .values()+ .next()+ .and_then(|entries| entries.first())+ .is_some_and(|(_, fields)| fields.contains_key("task"))+ }+ Err(_) => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_stream_acknowledge_entries() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let stream: RedisKey = format!("test_stream_ack_{}", unique_test_id()).into();+ let group = "test_ack_group";+ let fields: Vec<(&str, &str)> = vec![("field1", "value1")];++ let _ = pool+ .stream_append_entry(&stream, &RedisEntryId::AutoGeneratedID, fields)+ .await;+ let _ = pool+ .consumer_group_create(+ &stream,+ group,+ &RedisEntryId::UserSpecifiedID {+ milliseconds: "0".to_string(),+ sequence_number: "0".to_string(),+ },+ )+ .await;++ let ack_result = pool+ .stream_acknowledge_entries(&stream, group, vec!["0-1".to_string()])+ .await;++ ack_result.is_ok()+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_stream_delete_entries() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let stream: RedisKey = format!("test_xdel_{uid}").into();++ let fields: Vec<(&str, &str)> = vec![("f", "v")];+ let _ = pool+ .stream_append_entry(&stream, &RedisEntryId::AutoGeneratedID, fields)+ .await;++ let read_result = pool+ .stream_read_entries(+ std::slice::from_ref(&stream),+ vec!["0-0".to_string()],+ Some(1),+ )+ .await+ .expect("failed to read");++ let stream_key = pool.add_prefix(&format!("test_xdel_{uid}"));+ let entries = read_result.get(&stream_key).expect("should have entries");+ if entries.is_empty() {+ return false;+ }+ let entry_id = entries.first().expect("checked non-empty").0.clone();++ let delete_result = pool.stream_delete_entries(&stream, vec![entry_id]).await;++ matches!(delete_result, Ok(count) if count >= 1)+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_stream_trim_entries() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let stream: RedisKey = format!("test_trim_{uid}").into();++ for i in 0..5 {+ let i_str = i.to_string();+ let fields: Vec<(&str, &str)> = vec![("idx", i_str.as_str())];+ let _ = pool+ .stream_append_entry(&stream, &RedisEntryId::AutoGeneratedID, fields)+ .await;+ }++ let len_before = pool.stream_get_length(&stream).await.unwrap();+ if len_before < 5 {+ return false;+ }++ let read_result = pool+ .stream_read_entries(+ std::slice::from_ref(&stream),+ vec!["0-0".to_string()],+ Some(10),+ )+ .await+ .expect("failed to read stream");++ let stream_key = pool.add_prefix(&format!("test_trim_{uid}"));+ let entries = read_result.get(&stream_key).expect("should have entries");++ if entries.len() >= 3 {+ let trim_id = &entries.get(1).expect("checked len >= 3").0;+ let trim_result = pool+ .stream_trim_entries(+ &stream,+ StreamTrimConfig::new(+ StreamCapKind::MinID,+ StreamCapTrim::Exact,+ trim_id.as_str(),+ ),+ )+ .await;++ match trim_result {+ Ok(trimmed_count) => trimmed_count >= 1,+ Err(e) => {+ eprintln!("trim returned error: {:?}", e);+ false+ }+ }+ } else {+ false+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++// ─── Consumer Group Commands ──────────────────────────────────────────────────++#[tokio::test]+async fn test_consumer_group_operations() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let stream: RedisKey = format!("test_stream_group_ops_{uid}").into();+ let group = format!("test_group_{uid}");+ let fields: Vec<(&str, &str)> = vec![("field1", "value1")];++ let _ = pool+ .stream_append_entry(&stream, &RedisEntryId::AutoGeneratedID, fields)+ .await;++ let create_result = pool+ .consumer_group_create(+ &stream,+ &group,+ &RedisEntryId::UserSpecifiedID {+ milliseconds: "0".to_string(),+ sequence_number: "0".to_string(),+ },+ )+ .await;++ create_result.is_ok()+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_consumer_group_destroy() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let stream: RedisKey = format!("test_grp_destroy_{uid}").into();+ let group = format!("test_destroy_grp_{uid}");++ let fields: Vec<(&str, &str)> = vec![("f", "v")];+ let _ = pool+ .stream_append_entry(&stream, &RedisEntryId::AutoGeneratedID, fields)+ .await;+ pool.consumer_group_create(+ &stream,+ &group,+ &RedisEntryId::UserSpecifiedID {+ milliseconds: "0".to_string(),+ sequence_number: "0".to_string(),+ },+ )+ .await+ .expect("failed to create group");++ let destroy_result = pool.consumer_group_destroy(&stream, &group).await;++ matches!(destroy_result, Ok(ConsumerGroupDestroyReply::Destroyed))+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_consumer_group_delete_consumer() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let stream: RedisKey = format!("test_xdelconsumer_{uid}").into();+ let group = format!("test_grp_{uid}");+ let consumer = format!("test_consumer_{uid}");++ let fields: Vec<(&str, &str)> = vec![("f", "v")];+ let _ = pool+ .stream_append_entry(&stream, &RedisEntryId::AutoGeneratedID, fields)+ .await;+ let _ = pool+ .consumer_group_create(+ &stream,+ &group,+ &RedisEntryId::UserSpecifiedID {+ milliseconds: "0".to_string(),+ sequence_number: "0".to_string(),+ },+ )+ .await;++ let _ = pool+ .stream_read_with_options(+ std::slice::from_ref(&stream),+ vec![RedisEntryId::UndeliveredEntryID.to_stream_id()],+ Some(1),+ None,+ Some((&group, &consumer)),+ )+ .await;++ let result = pool+ .consumer_group_delete_consumer(&stream, &group, &consumer)+ .await;++ result.is_ok()+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_consumer_group_set_last_id() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let stream: RedisKey = format!("test_xsetid_{uid}").into();+ let group = format!("test_grp_{uid}");++ let fields: Vec<(&str, &str)> = vec![("f", "v")];+ let _ = pool+ .stream_append_entry(&stream, &RedisEntryId::AutoGeneratedID, fields)+ .await;+ let _ = pool+ .consumer_group_create(+ &stream,+ &group,+ &RedisEntryId::UserSpecifiedID {+ milliseconds: "0".to_string(),+ sequence_number: "0".to_string(),+ },+ )+ .await;++ let result = pool+ .consumer_group_set_last_id(+ &stream,+ &group,+ &RedisEntryId::UserSpecifiedID {+ milliseconds: "0".to_string(),+ sequence_number: "1".to_string(),+ },+ )+ .await;++ matches!(result, Ok(id) if id == "0-1")+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++// ─── List Commands ────────────────────────────────────────────────────────────++#[tokio::test]+async fn test_list_operations() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let key: RedisKey = format!("test_list_{uid}").into();++ let append_result = pool.append_elements_to_list(&key, &["a", "b", "c"]).await;++ let length_result = pool.get_list_length(&key).await;++ let elements_result: Result<Vec<String>, _> = pool.get_list_elements(&key, 0, -1).await;++ let pop_result = pool.lpop_list_elements(&key, Some(1)).await;++ match (append_result, length_result, elements_result, pop_result) {+ (Ok(()), Ok(3), Ok(elems), Ok(popped)) => {+ elems == vec!["a".to_string(), "b".to_string(), "c".to_string()]+ && popped == vec!["a".to_string()]+ }+ _ => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++// ─── Lua Scripts ──────────────────────────────────────────────────────────────++#[tokio::test]+async fn test_setting_keys_using_scripts() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let lua_script = r#"+ for i = 1, #KEYS do+ redis.call("INCRBY", KEYS[i], ARGV[i])+ end+ return+ "#;+ let mut keys_and_values = HashMap::new();+ for i in 0..10 {+ keys_and_values.insert(format!("key{i}"), i);+ }++ let key = keys_and_values.keys().cloned().collect::<Vec<_>>();+ let values = keys_and_values+ .values()+ .map(|val| val.to_string())+ .collect::<Vec<String>>();++ pool.evaluate_redis_script::<_, ()>(lua_script, key, values)+ .await+ .is_ok()+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_getting_keys_using_scripts() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");++ for i in 0..3 {+ let key = format!("script_test_key{i}").into();+ let _ = pool.set_key(&key, format!("value{i}")).await;+ }++ let lua_script = r#"+ local results = {}+ for i = 1, #KEYS do+ results[i] = redis.call("GET", KEYS[i])+ end+ return results+ "#;++ let keys = vec![+ "script_test_key0".to_string(),+ "script_test_key1".to_string(),+ "script_test_key2".to_string(),+ ];++ pool.evaluate_redis_script::<_, Vec<String>>(lua_script, keys, vec![""])+ .await+ .is_ok()+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++// ─── SCAN ─────────────────────────────────────────────────────────────────────++#[tokio::test]+async fn test_scan_returns_matching_keys() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let key1: RedisKey = format!("test_scan_foo_{uid}").into();+ let key2: RedisKey = format!("test_scan_bar_{uid}").into();++ let _ = pool.set_key(&key1, "v1".to_string()).await;+ let _ = pool.set_key(&key2, "v2".to_string()).await;++ let scan_pattern: RedisKey = format!("*test_scan_foo_{uid}*").into();+ let result = pool.scan(&scan_pattern, None, None).await;++ match result {+ Ok(keys) => {+ let found_foo = keys+ .iter()+ .any(|k| k.contains(&format!("test_scan_foo_{uid}")));+ let found_bar = keys+ .iter()+ .any(|k| k.contains(&format!("test_scan_bar_{uid}")));+ found_foo && !found_bar+ }+ Err(_) => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++// ─── Pub/Sub ──────────────────────────────────────────────────────────────────++#[tokio::test]+async fn test_pubsub_standalone_publish_and_receive() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let channel = "test_pubsub_channel";+ let test_message = "test_message_value";++ pool.subscriber+ .subscribe(channel)+ .await+ .expect("failed to subscribe");++ let mut receiver = pool.subscriber.message_rx();++ tokio::time::sleep(std::time::Duration::from_millis(100)).await;++ pool.publisher+ .publish(channel, RedisValue::from_string(test_message.to_string()))+ .await+ .expect("failed to publish");++ let received =+ tokio::time::timeout(std::time::Duration::from_secs(5), receiver.recv()).await;++ match received {+ Ok(Ok(msg)) => {+ let value_str = redis_value_to_option_string(&msg.value);+ msg.channel == channel && value_str.as_deref() == Some(test_message)+ }+ _ => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_subscriber_unsubscribe() {+ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let channel = "test_unsub_channel";++ pool.subscriber+ .subscribe(channel)+ .await+ .expect("failed to subscribe");++ let unsub_result = pool.subscriber.unsubscribe(channel).await;++ matches!(unsub_result, Ok(()))+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++// ─── on_error / max_failure_threshold_seconds ─────────────────────────────────++#[tokio::test]+async fn test_on_error_triggers_shutdown_when_redis_unreachable() {+ let settings = RedisSettings {+ host: "192.0.2.1".to_string(), // RFC 5737 test address, guaranteed unreachable+ port: 1,+ unresponsive_check_interval: 1,+ max_failure_threshold_seconds: 2,+ reconnect_max_attempts: 1,+ default_command_timeout: 1,+ ..RedisSettings::default()+ };++ let pool = RedisConnectionPool::new(&settings).await;+ let pool = match pool {+ Ok(pool) => pool,+ Err(_) => return, // If connection fails entirely, skip+ };++ let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();++ tokio::spawn(async move {+ pool.on_error(shutdown_tx).await;+ });++ let result = tokio::time::timeout(std::time::Duration::from_secs(10), shutdown_rx).await;++ assert!(+ result.is_ok() && result.unwrap().is_ok(),+ "on_error should trigger shutdown signal when Redis is unreachable"+ );+}++#[tokio::test]+async fn test_on_error_keeps_redis_available_when_healthy() {+ let pool = RedisConnectionPool::new(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");++ let initial_state = pool+ .is_redis_available+ .load(std::sync::atomic::Ordering::SeqCst);++ let key: RedisKey = format!("test_health_{}", unique_test_id()).into();+ let set_result = pool.set_key(&key, "ok".to_string()).await;+ let get_result: Result<String, _> = pool.get_key(&key).await;++ if set_result.is_err() || get_result.is_err() {+ return;+ }++ assert!(initial_state, "Redis should be available when healthy");+}++#[tokio::test]+async fn test_on_error_marks_unavailable_after_threshold() {+ let settings = RedisSettings {+ host: "192.0.2.1".to_string(),+ port: 1,+ unresponsive_check_interval: 1,+ max_failure_threshold_seconds: 2,+ reconnect_max_attempts: 1,+ default_command_timeout: 1,+ ..RedisSettings::default()+ };++ let pool = RedisConnectionPool::new(&settings).await;+ let pool = match pool {+ Ok(pool) => pool,+ Err(_) => return,+ };++ let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();+ let is_available = pool.is_redis_available.clone();++ tokio::spawn(async move {+ pool.on_error(shutdown_tx).await;+ });++ let result = tokio::time::timeout(std::time::Duration::from_secs(10), shutdown_rx).await;++ if result.is_ok() && result.unwrap().is_ok() {+ assert!(+ !is_available.load(std::sync::atomic::Ordering::SeqCst),+ "is_redis_available should be false after on_error triggers shutdown"+ );+ }+}++// ─── Cluster-mode tests ──────────────────────────────────────────────────────+// These tests run only when `REDIS_CLUSTER_URLS` env var is set.++#[tokio::test]+async fn test_cluster_set_get_delete() {+ let (pool, uid) = match get_cluster_pool_with_uid().await {+ Some(result) => result,+ None => return,+ };++ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let key: RedisKey = format!("test_cluster_sgd_{uid}").into();+ let value = "cluster_value".to_string();++ let set_result = pool.set_key(&key, value.clone()).await;+ let get_result: Result<String, _> = pool.get_key(&key).await;+ let del_result = pool.delete_key(&key).await;++ matches!(set_result, Ok(()))+ && matches!(get_result, Ok(v) if v == value)+ && matches!(del_result, Ok(DelReply::KeyDeleted))+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_cluster_hash_operations() {+ let (pool, uid) = match get_cluster_pool_with_uid().await {+ Some(result) => result,+ None => return,+ };++ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let key: RedisKey = format!("test_cluster_hash_{uid}").into();++ let set_result = pool+ .set_hash_fields(&key, vec![("field1", "val1"), ("field2", "val2")], Some(60))+ .await;++ let hsetnx_new = pool+ .set_hash_field_if_not_exist(&key, "field3", "val3", None)+ .await;++ let hsetnx_dup = pool+ .set_hash_field_if_not_exist(&key, "field1", "new_val", None)+ .await;++ let hget_result: Result<String, _> = pool.get_hash_field(&key, "field1").await;++ let hgetall_result: Result<HashMap<String, String>, _> =+ pool.get_hash_fields(&key).await;++ match (+ set_result,+ hsetnx_new,+ hsetnx_dup,+ hget_result,+ hgetall_result,+ ) {+ (Ok(()), Ok(HsetnxReply::KeySet), Ok(HsetnxReply::KeyNotSet), Ok(val), Ok(map)) => {+ val == "val1" && map.contains_key("field1") && map.contains_key("field3")+ }+ _ => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_cluster_stream_operations() {+ let (pool, uid) = match get_cluster_pool_with_uid().await {+ Some(result) => result,+ None => return,+ };++ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let stream: RedisKey = format!("test_cluster_stream_{uid}").into();+ let group = format!("test_cluster_grp_{uid}");++ let append_result = pool+ .stream_append_entry(+ &stream,+ &RedisEntryId::AutoGeneratedID,+ vec![("task", "process")],+ )+ .await;++ let len_result = pool.stream_get_length(&stream).await;++ let group_result = pool+ .consumer_group_create(+ &stream,+ &group,+ &RedisEntryId::UserSpecifiedID {+ milliseconds: "0".to_string(),+ sequence_number: "0".to_string(),+ },+ )+ .await;++ let read_result = pool+ .stream_read_with_options(+ std::slice::from_ref(&stream),+ vec![RedisEntryId::UndeliveredEntryID.to_stream_id()],+ Some(1),+ None,+ Some((&group, &format!("consumer_{uid}"))),+ )+ .await;++ let destroy_result = pool.consumer_group_destroy(&stream, &group).await;++ match (+ append_result,+ len_result,+ group_result,+ read_result,+ destroy_result,+ ) {+ (Ok(()), Ok(len), Ok(()), Ok(reply), Ok(_)) => {+ len >= 1+ && reply.len() == 1+ && reply+ .values()+ .next()+ .is_some_and(|entries| !entries.is_empty())+ }+ _ => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_cluster_set_key_if_not_exists_and_get_value() {+ let (pool, uid) = match get_cluster_pool_with_uid().await {+ Some(result) => result,+ None => return,+ };++ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let key: RedisKey = format!("test_cluster_setnx_get_{uid}").into();++ let result_new = pool+ .set_key_if_not_exists_and_get_value(&key, "val1".to_string(), Some(30))+ .await;++ let result_exist = pool+ .set_key_if_not_exists_and_get_value(&key, "val2".to_string(), Some(30))+ .await;++ match (result_new, result_exist) {+ (Ok(SetGetReply::ValueSet(v1)), Ok(SetGetReply::ValueExists(v2))) => {+ v1 == "val1" && v2 == "val1"+ }+ _ => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_cluster_scan() {+ let (pool, uid) = match get_cluster_pool_with_uid().await {+ Some(result) => result,+ None => return,+ };++ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let key: RedisKey = format!("test_cluster_scan_{uid}").into();++ let _ = pool.set_key(&key, "v".to_string()).await;++ let pattern: RedisKey = format!("*test_cluster_scan_{uid}*").into();+ let result = pool.scan(&pattern, None, None).await;++ match result {+ Ok(keys) => keys+ .iter()+ .any(|k| k.contains(&format!("test_cluster_scan_{uid}"))),+ Err(_) => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}++#[tokio::test]+async fn test_cluster_pubsub() {+ let (pool, uid) = match get_cluster_pool_with_uid().await {+ Some(result) => result,+ None => return,+ };++ let is_success = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let channel = format!("test_cluster_pubsub_{uid}");+ let test_message = "cluster_message";++ pool.subscriber+ .subscribe(&channel)+ .await+ .expect("failed to subscribe on cluster");++ let mut receiver = pool.subscriber.message_rx();++ tokio::time::sleep(std::time::Duration::from_millis(100)).await;++ pool.publisher+ .publish(&channel, RedisValue::from_string(test_message.to_string()))+ .await+ .expect("failed to publish on cluster");++ let received =+ tokio::time::timeout(std::time::Duration::from_secs(5), receiver.recv()).await;++ match received {+ Ok(Ok(msg)) => {+ let value_str = redis_value_to_option_string(&msg.value);+ msg.channel == channel && value_str.as_deref() == Some(test_message)+ }+ _ => false,+ }+ })+ })+ .await+ .expect("Spawn block failure");++ assert!(is_success);+}diff --git a/crates/redis_interface/src/types.rs b/crates/redis_interface/src/types.rsindex 9ba19c210b..671fc64d82 100644--- a/crates/redis_interface/src/types.rs+++ b/crates/redis_interface/src/types.rs@@ -1,48 +1,29 @@-//! Data types and type conversions-//! from `fred`'s internal data-types to custom data-types+//! Shared data types — backend-neutral.+//!+//! All struct/enum *definitions* live here. Backend-specific trait+//! implementations (`FromRedisValue`, `FromRedis`, `ToRedisArgs`, `Deref`,+//! `From<RedisValue> for …`) live in each backend's `types.rs` instead.+//!+//! The one cfg-gated field that cannot be split is `RedisValue::inner`,+//! because Rust does not allow splitting a struct definition across files.use common_utils::errors::CustomResult;-use fred::types::RedisValue as FredRedisValue;-use crate::{errors, RedisConnectionPool};+use crate::errors;-pub struct RedisValue {- inner: FredRedisValue,-}--impl std::ops::Deref for RedisValue {- type Target = FredRedisValue;+// ─── RedisValue — wrapper whose inner type depends on the active backend ─────- fn deref(&self) -> &Self::Target {- &self.inner- }+#[derive(Clone, Debug)]+pub struct RedisValue {+ #[cfg(feature = "redis-rs")]+ pub(crate) inner: redis::Value,+ #[cfg(feature = "fred")]+ pub(crate) inner: fred::types::RedisValue,}-impl RedisValue {- pub fn new(value: FredRedisValue) -> Self {- Self { inner: value }- }- pub fn into_inner(self) -> FredRedisValue {- self.inner- }-- pub fn from_bytes(val: Vec<u8>) -> Self {- Self {- inner: FredRedisValue::Bytes(val.into()),- }- }- pub fn from_string(value: String) -> Self {- Self {- inner: FredRedisValue::String(value.into()),- }- }-}+// Method impls are in module/redis_rs/types.rs and module/fred/types.rs.-impl From<RedisValue> for FredRedisValue {- fn from(v: RedisValue) -> Self {- v.inner- }-}+// ─── Shared configuration types ─────────────────────────────────────────────#[derive(Debug, serde::Deserialize, Clone)]#[serde(default)]@@ -52,9 +33,11 @@ pub struct RedisSettings {pub cluster_enabled: bool,pub cluster_urls: Vec<String>,pub use_legacy_version: bool,+ /// Number of reconnection attempts before giving up (default: 5).pub pool_size: usize,+ /// Maximum number of connection retry attempts (default: 5).pub reconnect_max_attempts: u32,- /// Reconnect delay in milliseconds+ /// Initial delay in milliseconds between reconnection attempts (default: 5).pub reconnect_delay: u32,/// TTL in secondspub default_ttl: u32,@@ -63,12 +46,18 @@ pub struct RedisSettings {pub stream_read_count: u64,pub auto_pipeline: bool,pub disable_auto_backpressure: bool,- pub max_in_flight_commands: u64,+ /// Maximum number of in-flight commands before backpressure is applied.+ /// Set to 0 to disable.+ pub max_in_flight_commands: usize,+ /// Command timeout in seconds.pub default_command_timeout: u64,pub max_feed_count: u64,pub unresponsive_timeout: u64,pub unresponsive_check_interval: u64,+ /// Capacity of the broadcast channel used for pub/sub message distribution.pub broadcast_channel_capacity: usize,+ /// Maximum duration (in seconds) that Redis can be unreachable before the server shuts down.+ pub max_failure_threshold_seconds: u32,}impl RedisSettings {@@ -93,10 +82,21 @@ impl RedisSettings {|| {Err(errors::RedisError::InvalidConfiguration("Unresponsive timeout cannot be greater than the command timeout".into(),- )- .into())+ ))},- )+ )?;++ when(+ self.unresponsive_check_interval > self.max_failure_threshold_seconds.into(),+ || {+ Err(errors::RedisError::InvalidConfiguration(+ "Unresponsive check interval cannot be greater than the max failure threshold"+ .into(),+ ))+ },+ )?;++ Ok(())}}@@ -122,10 +122,13 @@ impl Default for RedisSettings {unresponsive_timeout: 10,unresponsive_check_interval: 2,broadcast_channel_capacity: 32,+ max_failure_threshold_seconds: 5,}}}+// ─── RedisEntryId ────────────────────────────────────────────────────────────+#[derive(Debug)]pub enum RedisEntryId {UserSpecifiedID {@@ -138,129 +141,44 @@ pub enum RedisEntryId {UndeliveredEntryID,}-impl From<RedisEntryId> for fred::types::XID {- fn from(id: RedisEntryId) -> Self {- match id {- RedisEntryId::UserSpecifiedID {+impl RedisEntryId {+ /// Convert to the string representation used by Redis stream commands+ pub fn to_stream_id(&self) -> String {+ match self {+ Self::UserSpecifiedID {milliseconds,sequence_number,- } => Self::Manual(fred::bytes_utils::format_bytes!(- "{milliseconds}-{sequence_number}"- )),- RedisEntryId::AutoGeneratedID => Self::Auto,- RedisEntryId::AfterLastID => Self::Max,- RedisEntryId::UndeliveredEntryID => Self::NewInGroup,+ } => format!("{milliseconds}-{sequence_number}"),+ Self::AutoGeneratedID => "*".to_string(),+ Self::AfterLastID => "$".to_string(),+ Self::UndeliveredEntryID => ">".to_string(),}}}-impl From<&RedisEntryId> for fred::types::XID {- fn from(id: &RedisEntryId) -> Self {- match id {- RedisEntryId::UserSpecifiedID {- milliseconds,- sequence_number,- } => Self::Manual(fred::bytes_utils::format_bytes!(- "{milliseconds}-{sequence_number}"- )),- RedisEntryId::AutoGeneratedID => Self::Auto,- RedisEntryId::AfterLastID => Self::Max,- RedisEntryId::UndeliveredEntryID => Self::NewInGroup,- }- }-}+// Trait impls live in module/redis_rs/types.rs and module/fred/types.rs.++// ─── Reply type enums ────────────────────────────────────────────────────────-#[derive(Eq, PartialEq)]+#[derive(Debug, Eq, PartialEq)]pub enum SetnxReply {KeySet,KeyNotSet, // Existing key}-impl fred::types::FromRedis for SetnxReply {- fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> {- match value {- // Returns String ( "OK" ) in case of success- fred::types::RedisValue::String(_) => Ok(Self::KeySet),- // Return Null in case of failure- fred::types::RedisValue::Null => Ok(Self::KeyNotSet),- // Unexpected behaviour- _ => Err(fred::error::RedisError::new(- fred::error::RedisErrorKind::Unknown,- "Unexpected SETNX command reply",- )),- }- }-}--#[derive(Eq, PartialEq)]+#[derive(Debug, Eq, PartialEq)]pub enum HsetnxReply {KeySet,KeyNotSet, // Existing key}-impl fred::types::FromRedis for HsetnxReply {- fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> {- match value {- fred::types::RedisValue::Integer(1) => Ok(Self::KeySet),- fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotSet),- _ => Err(fred::error::RedisError::new(- fred::error::RedisErrorKind::Unknown,- "Unexpected HSETNX command reply",- )),- }- }-}--#[derive(Eq, PartialEq)]+#[derive(Debug, Eq, PartialEq)]pub enum MsetnxReply {KeysSet,KeysNotSet, // At least one existing key}-impl fred::types::FromRedis for MsetnxReply {- fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> {- match value {- fred::types::RedisValue::Integer(1) => Ok(Self::KeysSet),- fred::types::RedisValue::Integer(0) => Ok(Self::KeysNotSet),- _ => Err(fred::error::RedisError::new(- fred::error::RedisErrorKind::Unknown,- "Unexpected MSETNX command reply",- )),- }- }-}--#[derive(Debug)]-pub enum StreamCapKind {- MinID,- MaxLen,-}--impl From<StreamCapKind> for fred::types::XCapKind {- fn from(item: StreamCapKind) -> Self {- match item {- StreamCapKind::MaxLen => Self::MaxLen,- StreamCapKind::MinID => Self::MinID,- }- }-}--#[derive(Debug)]-pub enum StreamCapTrim {- Exact,- AlmostExact,-}--impl From<StreamCapTrim> for fred::types::XCapTrim {- fn from(item: StreamCapTrim) -> Self {- match item {- StreamCapTrim::Exact => Self::Exact,- StreamCapTrim::AlmostExact => Self::AlmostExact,- }- }-}--#[derive(Debug)]+#[derive(Debug, Eq, PartialEq)]pub enum DelReply {KeyDeleted,KeyNotDeleted, // Key not found@@ -276,34 +194,39 @@ impl DelReply {}}-impl fred::types::FromRedis for DelReply {- fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> {- match value {- fred::types::RedisValue::Integer(1) => Ok(Self::KeyDeleted),- fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotDeleted),- _ => Err(fred::error::RedisError::new(- fred::error::RedisErrorKind::Unknown,- "Unexpected del command reply",- )),- }- }-}--#[derive(Debug)]+#[derive(Debug, Eq, PartialEq)]pub enum SaddReply {KeySet,KeyNotSet,}-impl fred::types::FromRedis for SaddReply {- fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> {- match value {- fred::types::RedisValue::Integer(1) => Ok(Self::KeySet),- fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotSet),- _ => Err(fred::error::RedisError::new(- fred::error::RedisErrorKind::Unknown,- "Unexpected sadd command reply",- )),+/// Reply from `XGROUP DESTROY`.+#[derive(Debug, Eq, PartialEq)]+pub enum ConsumerGroupDestroyReply {+ Destroyed,+ NotFound,+}++/// Redis key types used with the `TYPE` filter in `SCAN`.+#[derive(Debug, Clone, Copy, Eq, PartialEq)]+pub enum RedisScanType {+ String,+ List,+ Set,+ Zset,+ Hash,+ Stream,+}++impl AsRef<str> for RedisScanType {+ fn as_ref(&self) -> &str {+ match self {+ Self::String => "STRING",+ Self::List => "LIST",+ Self::Set => "SET",+ Self::Zset => "ZSET",+ Self::Hash => "HASH",+ Self::Stream => "STREAM",}}}@@ -323,15 +246,116 @@ impl<T> SetGetReply<T> {}}+// ─── Stream types ────────────────────────────────────────────────────────────++/// Entries within a single stream, as `(entry_id, fields)`.+pub type StreamEntries = Vec<(String, std::collections::HashMap<String, RedisValue>)>;++/// Grouped result of a stream read: stream key → list of `(entry_id, fields)`.+pub type StreamReadResult = std::collections::HashMap<String, StreamEntries>;++#[derive(Debug, Clone)]+pub enum StreamCapKind {+ MinID,+ MaxLen,+}++#[derive(Debug, Clone)]+pub enum StreamCapTrim {+ Exact,+ AlmostExact,+}++// Trait impls for StreamCapKind/StreamCapTrim live in module/fred/types.rs.++// ─── Stream trim types ────────────────────────────────────────────────────────++/// Configuration for trimming a Redis stream via `XTRIM`.+///+/// Encapsulates the kind (MaxLen or MinID), precision (Exact or AlmostExact),+/// and the numeric or ID threshold.+///+/// # Examples+///+/// ```+/// use redis_interface::types::{StreamCapKind, StreamCapTrim, StreamTrimConfig};+///+/// let config = StreamTrimConfig::new(StreamCapKind::MaxLen, StreamCapTrim::AlmostExact, "1000");+/// ```+#[derive(Debug, Clone)]+pub struct StreamTrimConfig {+ /// What to compare against — entry count or minimum ID.+ pub kind: StreamCapKind,+ /// How precisely to match the threshold.+ pub trim: StreamCapTrim,+ /// The threshold value: a numeric string for `MaxLen`, a stream ID for `MinID`.+ pub threshold: String,+}++impl StreamTrimConfig {+ /// Create a new trim configuration.+ pub fn new(kind: StreamCapKind, trim: StreamCapTrim, threshold: impl Into<String>) -> Self {+ Self {+ kind,+ trim,+ threshold: threshold.into(),+ }+ }++ /// Convert to the `redis` crate's `StreamTrimOptions` (redis-rs backend).+ ///+ /// Returns an error if `kind` is `MaxLen` and the threshold+ /// cannot be parsed as a `usize`.+ #[cfg(feature = "redis-rs")]+ pub fn to_trim_options(+ self,+ ) -> Result<redis::streams::StreamTrimOptions, StreamTrimThresholdError> {+ let trim_mode = match self.trim {+ StreamCapTrim::Exact => redis::streams::StreamTrimmingMode::Exact,+ StreamCapTrim::AlmostExact => redis::streams::StreamTrimmingMode::Approx,+ };++ match self.kind {+ StreamCapKind::MaxLen => {+ let max_len: usize = self+ .threshold+ .parse()+ .map_err(|_| StreamTrimThresholdError(self.threshold.clone()))?;+ Ok(redis::streams::StreamTrimOptions::maxlen(+ trim_mode, max_len,+ ))+ }+ StreamCapKind::MinID => Ok(redis::streams::StreamTrimOptions::minid(+ trim_mode,+ self.threshold,+ )),+ }+ }+}++/// Error returned when a `StreamTrimConfig` threshold cannot be parsed.#[derive(Debug)]+pub struct StreamTrimThresholdError(String);++impl std::fmt::Display for StreamTrimThresholdError {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(formatter, "Invalid stream trim threshold: {}", self.0)+ }+}++impl std::error::Error for StreamTrimThresholdError {}++// ─── RedisKey ────────────────────────────────────────────────────────────────++#[derive(Debug, Clone)]pub struct RedisKey(String);impl RedisKey {- pub fn tenant_aware_key(&self, pool: &RedisConnectionPool) -> String {+ pub fn tenant_aware_key(&self, pool: &crate::RedisConnectionPool) -> String {pool.add_prefix(&self.0)}- pub fn tenant_unaware_key(&self, _pool: &RedisConnectionPool) -> String {+ pub fn tenant_unaware_key(&self, _pool: &crate::RedisConnectionPool) -> String {self.0.clone()}}@@ -339,7 +363,94 @@ impl RedisKey {impl<T: AsRef<str>> From<T> for RedisKey {fn from(value: T) -> Self {let value = value.as_ref();-Self(value.to_string())}}++// ─── Tests (backend-neutral only) ────────────────────────────────────────────++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_entry_id_user_specified() {+ let id = RedisEntryId::UserSpecifiedID {+ milliseconds: "1234567890".to_string(),+ sequence_number: "0".to_string(),+ };+ assert_eq!(id.to_stream_id(), "1234567890-0");+ }++ #[test]+ fn test_entry_id_auto_generated() {+ assert_eq!(RedisEntryId::AutoGeneratedID.to_stream_id(), "*");+ }++ #[test]+ fn test_entry_id_after_last() {+ assert_eq!(RedisEntryId::AfterLastID.to_stream_id(), "$");+ }++ #[test]+ fn test_entry_id_undelivered() {+ assert_eq!(RedisEntryId::UndeliveredEntryID.to_stream_id(), ">");+ }++ #[test]+ fn test_redis_settings_validate_valid_defaults() {+ let settings = RedisSettings::default();+ assert!(settings.validate().is_ok());+ }++ #[test]+ fn test_redis_settings_validate_empty_host() {+ let settings = RedisSettings {+ host: String::new(),+ ..RedisSettings::default()+ };+ assert!(settings.validate().is_err());+ }++ #[test]+ fn test_redis_settings_validate_cluster_without_urls() {+ let settings = RedisSettings {+ cluster_enabled: true,+ cluster_urls: vec![],+ ..RedisSettings::default()+ };+ assert!(settings.validate().is_err());+ }++ #[test]+ fn test_redis_settings_validate_unresponsive_timeout_exceeds_command_timeout() {+ let settings = RedisSettings {+ unresponsive_timeout: 60,+ default_command_timeout: 30,+ ..RedisSettings::default()+ };+ assert!(settings.validate().is_err());+ }++ #[test]+ fn test_redis_settings_default_values() {+ let settings = RedisSettings::default();+ assert_eq!(settings.host, "127.0.0.1");+ assert_eq!(settings.port, 6379);+ assert!(!settings.cluster_enabled);+ assert!(settings.cluster_urls.is_empty());+ assert!(!settings.use_legacy_version);+ assert_eq!(settings.reconnect_max_attempts, 5);+ assert_eq!(settings.reconnect_delay, 5);+ assert_eq!(settings.default_ttl, 300);+ assert_eq!(settings.default_hash_ttl, 900);+ assert_eq!(settings.broadcast_channel_capacity, 32);+ assert_eq!(settings.max_failure_threshold_seconds, 5);+ }++ #[test]+ fn test_del_reply_is_key_deleted() {+ assert!(DelReply::KeyDeleted.is_key_deleted());+ assert!(!DelReply::KeyNotDeleted.is_key_deleted());+ }+}diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.tomlindex 9751fd1b1d..0f426cd539 100644--- a/crates/router/Cargo.toml+++ b/crates/router/Cargo.toml@@ -9,7 +9,7 @@ readme = "README.md"license.workspace = true[features]-default = ["common_default", "v1"]+default = ["common_default", "v1", "redis-rs"]common_default = ["kv_store", "stripe", "oltp", "olap", "accounts_cache", "dummy_connector", "payouts", "payout_retry", "retry", "frm", "tls", "partial-auth", "km_forward_x_request_id", "external_services/superposition"]olap = ["hyperswitch_domain_models/olap", "storage_impl/olap", "scheduler/olap", "api_models/olap", "dep:analytics"]tls = ["actix-web/rustls-0_22"]@@ -40,6 +40,8 @@ tokenization_v2 = ["api_models/tokenization_v2", "diesel_models/tokenization_v2"# The feature reduces the overhead of the router authenticating the merchant for every request, and trusts on `x-merchant-id` header to be present in the request.# This is named as partial-auth because the router will still try to authenticate if the `x-merchant-id` header is not present.partial-auth = []+fred = ["redis_interface/fred", "storage_impl/fred", "scheduler/fred"]+redis-rs = ["redis_interface/redis-rs", "storage_impl/redis-rs", "scheduler/redis-rs"][dependencies]actix-cors = "0.6.5"@@ -136,7 +138,7 @@ injector = { version = "0.1.0", path = "../injector", optional = true }kgraph_utils = { version = "0.1.0", path = "../kgraph_utils" }hyperswitch_masking = "0.0.1"pm_auth = { version = "0.1.0", path = "../pm_auth", package = "pm_auth" }-redis_interface = { version = "0.1.0", path = "../redis_interface" }+redis_interface = { version = "0.1.0", path = "../redis_interface", default-features = false }router_derive = { version = "0.1.0", path = "../router_derive" }router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }scheduler = { version = "0.1.0", path = "../scheduler", default-features = false }diff --git a/crates/router/src/core/api_locking.rs b/crates/router/src/core/api_locking.rsindex cc84e70e2c..0713fdf611 100644--- a/crates/router/src/core/api_locking.rs+++ b/crates/router/src/core/api_locking.rs@@ -67,7 +67,9 @@ impl LockAction {.iter().find_map(|input| input.override_lock_retries).unwrap_or(state.conf().lock_settings.lock_retries);- let request_id = state.get_request_id();+ let request_id = state+ .get_request_id()+ .ok_or(errors::ApiErrorResponse::InternalServerError)?;let redis_lock_expiry_seconds =state.conf().lock_settings.redis_lock_expiry_seconds;let redis_conn = state@@ -124,11 +126,14 @@ impl LockAction {let lock_retries = input.override_lock_retries.unwrap_or(state.conf().lock_settings.lock_retries);+ let request_id = state+ .get_request_id()+ .ok_or(errors::ApiErrorResponse::InternalServerError)?;for _retry in 0..lock_retries {let redis_lock_result = redis_conn.set_key_if_not_exists_with_expiry(&redis_locking_key.as_str().into(),- state.get_request_id(),+ request_id.clone(),Some(i64::from(redis_lock_expiry_seconds)),).await;diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rsindex 30773c930f..bfd2a5265c 100644--- a/crates/router/src/core/payment_methods/vault.rs+++ b/crates/router/src/core/payment_methods/vault.rs@@ -1683,7 +1683,7 @@ async fn create_tokenize(redis_conn.set_key_if_not_exists_with_expiry(&redis_key.as_str().into(),- bytes::Bytes::from(encrypted_payload),+ encrypted_payload.as_slice(),expiry_time.or(Some(i64::from(consts::LOCKER_REDIS_EXPIRY_SECONDS))),).awaitdiff --git a/crates/router/src/types/storage/revenue_recovery_redis_operation.rs b/crates/router/src/types/storage/revenue_recovery_redis_operation.rsindex 379c016dc2..b292ec6fd7 100644--- a/crates/router/src/types/storage/revenue_recovery_redis_operation.rs+++ b/crates/router/src/types/storage/revenue_recovery_redis_operation.rs@@ -379,13 +379,12 @@ impl RedisTokenManager {}let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;+ // Convert HashMap to Vec for hset_multiple+ let items: Vec<_> = serialized_payment_processor_tokens.into_iter().collect();+// Update or add tokensredis_conn- .set_hash_fields(- &tokens_key.into(),- serialized_payment_processor_tokens,- Some(*seconds),- )+ .set_hash_fields(&tokens_key.into(), items, Some(*seconds)).await.change_context(errors::StorageError::RedisError(errors::RedisError::SetHashFieldFailed.into(),diff --git a/crates/scheduler/Cargo.toml b/crates/scheduler/Cargo.tomlindex 8db32a3071..3cb0e981b9 100644--- a/crates/scheduler/Cargo.toml+++ b/crates/scheduler/Cargo.toml@@ -6,12 +6,14 @@ rust-version.workspace = truelicense.workspace = true[features]-default = ["kv_store", "olap"]+default = ["kv_store", "olap", "redis-rs"]olap = ["storage_impl/olap", "hyperswitch_domain_models/olap"]kv_store = []email = ["external_services/email"]v1 = ["diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "common_utils/v1", "common_types/v1"]v2 = ["diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "common_utils/v2", "common_types/v2"]+fred = ["redis_interface/fred", "storage_impl/fred"]+redis-rs = ["redis_interface/redis-rs", "storage_impl/redis-rs"][dependencies]# Third party crates@@ -34,7 +36,7 @@ common_types = { version = "0.1.0", path = "../common_types" }diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"], default-features = false }external_services = { version = "0.1.0", path = "../external_services" }hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }-redis_interface = { version = "0.1.0", path = "../redis_interface" }+redis_interface = { version = "0.1.0", path = "../redis_interface", default-features = false }router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false }diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rsindex c4e0ed2ad0..fd1baaff78 100644--- a/crates/scheduler/src/utils.rs+++ b/crates/scheduler/src/utils.rs@@ -200,8 +200,8 @@ pub async fn get_batches() -> CustomResult<Vec<ProcessTrackerBatch>, errors::ProcessTrackerError> {let response = match conn.stream_read_with_options(- stream_name,- RedisEntryId::UndeliveredEntryID,+ &[stream_name.into()],+ vec![RedisEntryId::UndeliveredEntryID.to_stream_id()],// Update logic for collecting to Vec and flattening, if count > 1 is providedSome(1),None,@@ -224,21 +224,26 @@ pub async fn get_batches(metrics::BATCHES_CONSUMED.add(1, &[]);- let (batches, entry_ids): (Vec<Vec<ProcessTrackerBatch>>, Vec<Vec<String>>) = response.into_values().map(|entries| {- entries.into_iter().try_fold(- (Vec::new(), Vec::new()),- |(mut batches, mut entry_ids), entry| {- // Redis entry ID- entry_ids.push(entry.0);- // Value HashMap- batches.push(ProcessTrackerBatch::from_redis_stream_entry(entry.1)?);-- Ok((batches, entry_ids))- },- )- }).collect::<CustomResult<Vec<(Vec<ProcessTrackerBatch>, Vec<String>)>, errors::ProcessTrackerError>>()?- .into_iter()- .unzip();+ // StreamReadResult: stream key → Vec<(entry_id, HashMap<String, RedisValue>)>+ let (batches, entry_ids): (Vec<Vec<ProcessTrackerBatch>>, Vec<Vec<String>>) = response+ .into_values()+ .map(|entries| {+ entries.into_iter().try_fold(+ (Vec::new(), Vec::new()),+ |(mut batches, mut entry_ids), (entry_id, fields)| {+ entry_ids.push(entry_id);+ let fields: std::collections::HashMap<String, Option<String>> = fields+ .into_iter()+ .map(|(k, v)| (k, v.as_string()))+ .collect();+ batches.push(ProcessTrackerBatch::from_redis_stream_entry(fields)?);+ Ok((batches, entry_ids))+ },+ )+ })+ .collect::<CustomResult<Vec<_>, errors::ProcessTrackerError>>()?+ .into_iter()+ .unzip();// Flattening the Vec's since the count provided above is 1. This needs to be updated if a// count greater than 1 is provided.let batches = batches.into_iter().flatten().collect::<Vec<_>>();@@ -250,7 +255,7 @@ pub async fn get_batches(logger::error!(?error, "Error acknowledging batch in stream");error.change_context(errors::ProcessTrackerError::BatchUpdateFailed)})?;- conn.stream_delete_entries(&stream_name.into(), entry_ids.clone())+ conn.stream_delete_entries(&stream_name.into(), entry_ids).await.map_err(|error| {logger::error!(?error, "Error deleting batch from stream");diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.tomlindex 700d587e2f..80ae2f4856 100644--- a/crates/storage_impl/Cargo.toml+++ b/crates/storage_impl/Cargo.toml@@ -8,7 +8,7 @@ readme = "README.md"license.workspace = true[features]-default = ["olap", "oltp", "accounts_cache"]+default = ["olap", "oltp", "accounts_cache", "redis-rs"]dynamic_routing = []oltp = []accounts_cache = []@@ -17,6 +17,8 @@ payouts = ["hyperswitch_domain_models/payouts"]v1 = ["api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "common_utils/v1"]v2 = ["api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "common_utils/v2"]tokenization_v2 = ["diesel_models/tokenization_v2", "api_models/tokenization_v2", "hyperswitch_domain_models/tokenization_v2"]+fred = ["redis_interface/fred"]+redis-rs = ["redis_interface/redis-rs"][dependencies]# First Party dependencies@@ -26,7 +28,7 @@ common_utils = { version = "0.1.0", path = "../common_utils" }diesel_models = { version = "0.1.0", path = "../diesel_models", default-features = false }hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }hyperswitch_masking = "0.0.1"-redis_interface = { version = "0.1.0", path = "../redis_interface" }+redis_interface = { version = "0.1.0", path = "../redis_interface", default-features = false }router_derive = { version = "0.1.0", path = "../router_derive" }router_env = { version = "0.1.0", path = "../router_env" }diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rsindex d190329a4b..6ee6f60af8 100644--- a/crates/storage_impl/src/redis/kv_store.rs+++ b/crates/storage_impl/src/redis/kv_store.rs@@ -190,7 +190,7 @@ wherelogger::debug!(kv_operation= %operation, value = ?value);redis_conn- .set_hash_fields(&key.into(), value, Some(ttl.into()))+ .set_hash_fields(&key.into(), vec![value], Some(ttl.into())).await?;storediff --git a/crates/storage_impl/src/redis/pub_sub.rs b/crates/storage_impl/src/redis/pub_sub.rsindex 5e7c20a4ad..0430b7caaf 100644--- a/crates/storage_impl/src/redis/pub_sub.rs+++ b/crates/storage_impl/src/redis/pub_sub.rs@@ -1,7 +1,7 @@use std::sync::atomic;use error_stack::ResultExt;-use redis_interface::{errors as redis_errors, EventInterface, PubsubInterface, RedisValue};+use redis_interface::{errors as redis_errors, RedisValue};use router_env::{logger, tracing::Instrument};use crate::redis::cache::{@@ -28,13 +28,7 @@ pub trait PubSubInterface {impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {#[inline]async fn subscribe(&self, channel: &str) -> error_stack::Result<(), redis_errors::RedisError> {- // Spawns a task that will automatically re-subscribe to any channels or channel patterns used by the client.- self.subscriber.manage_subscriptions();-- self.subscriber- .subscribe::<_>(channel)- .await- .change_context(redis_errors::RedisError::SubscribeError)?;+ self.subscriber.subscribe(channel).await?;// Spawn only one thread handling all the published messages to different channelsif self@@ -92,7 +86,7 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {match channel_name.as_str() {super::cache::IMC_INVALIDATION_CHANNEL => {- let message = match CacheRedact::try_from(RedisValue::new(message.value))+ let message = match CacheRedact::try_from(message.value).change_context(redis_errors::RedisError::OnMessageError){Ok(value) => value,diff --git a/justfile b/justfileindex e3ef449718..4bc74e0201 100644--- a/justfile+++ b/justfile@@ -16,7 +16,8 @@ alias c := check# Check compilation of Rust code and catch common mistakes# We cannot run --all-features because v1 and v2 are mutually exclusive features# Create a list of features by excluding certain features-clippy *FLAGS:+# redis_interface_backend: "redis-rs" (default) or "fred"+clippy redis_interface_backend="redis-rs" *FLAGS:#! /usr/bin/env bashset -euo pipefail@@ -24,15 +25,18 @@ clippy *FLAGS:jq -r '[ ( .workspace_members | sort ) as $package_ids # Store workspace crate package IDs in `package_ids` array| .packages[] | select( IN(.id; $package_ids[]) ) | .features | keys[] ] | unique # Select all unique features from all workspace crates- | del( .[] | select( any( . ; test("(([a-z_]+)_)?v2") ) ) ) # Exclude some features from features list+ | del( .[] | select( any( . ; test("(([a-z_]+)_)?v2") ) ) ) # Exclude v2 features+ | del( .[] | select( . == ("default", "fred", "redis-rs") ) ) # Exclude default and both backend flags| join(",") # Construct a comma-separated string of features for passing to `cargo`')"+ FEATURES="${FEATURES},{{ redis_interface_backend }}"set -x- cargo clippy {{ check_flags }} --features "${FEATURES}" {{ FLAGS }}+ cargo clippy {{ check_flags }} --no-default-features --features "${FEATURES}" {{ FLAGS }}set +x-clippy_v2 *FLAGS:+# redis_interface_backend: "redis-rs" (default) or "fred"+clippy_v2 redis_interface_backend="redis-rs" *FLAGS:#! /usr/bin/env bashset -euo pipefail@@ -40,15 +44,17 @@ clippy_v2 *FLAGS:jq -r '[ ( .workspace_members | sort ) as $package_ids # Store workspace crate package IDs in `package_ids` array| .packages[] | select( IN(.id; $package_ids[]) ) | .features | keys[] ] | unique # Select all unique features from all workspace crates- | del( .[] | select( . == ("default", "v1") ) ) # Exclude some features from features list+ | del( .[] | select( . == ("default", "v1", "fred", "redis-rs") ) ) # Exclude default, v1, and both backend flags| join(",") # Construct a comma-separated string of features for passing to `cargo`')"+ FEATURES="${FEATURES},{{ redis_interface_backend }}"set -xcargo clippy {{ check_flags }} --no-default-features --features "${FEATURES}" -- {{ v2_lints }} {{ FLAGS }}set +x-check_v2 *FLAGS:+# redis_interface_backend: "redis-rs" (default) or "fred"+check_v2 redis_interface_backend="redis-rs" *FLAGS:#! /usr/bin/env bashset -euo pipefail@@ -56,15 +62,17 @@ check_v2 *FLAGS:jq -r '[ ( .workspace_members | sort ) as $package_ids # Store workspace crate package IDs in `package_ids` array| .packages[] | select( IN(.id; $package_ids[]) ) | .features | keys[] ] | unique # Select all unique features from all workspace crates- | del( .[] | select( . == ("default", "v1") ) ) # Exclude some features from features list+ | del( .[] | select( . == ("default", "v1", "fred", "redis-rs") ) ) # Exclude default, v1, and both backend flags| join(",") # Construct a comma-separated string of features for passing to `cargo`')"+ FEATURES="${FEATURES},{{ redis_interface_backend }}"set -xcargo check {{ check_flags }} --no-default-features --features "${FEATURES}" -- {{ FLAGS }}set +x-build_v2 *FLAGS:+# redis_interface_backend: "redis-rs" (default) or "fred"+build_v2 redis_interface_backend="redis-rs" *FLAGS:#! /usr/bin/env bashset -euo pipefail@@ -74,13 +82,15 @@ build_v2 *FLAGS:| select( any( . ; test("(([a-z_]+)_)?v2") ) ) ] # Select v2 features| join(",") # Construct a comma-separated string of features for passing to `cargo`')"+ FEATURES="${FEATURES},{{ redis_interface_backend }}"set -xcargo build --package router --bin router --no-default-features --features "${FEATURES}" {{ FLAGS }}set +x-run_v2:+# redis_interface_backend: "redis-rs" (default) or "fred"+run_v2 redis_interface_backend="redis-rs":#! /usr/bin/env bashset -euo pipefail@@ -90,12 +100,14 @@ run_v2:| select( any( . ; test("(([a-z_]+)_)?v2") ) ) ] # Select v2 features| join(",") # Construct a comma-separated string of features for passing to `cargo`')"+ FEATURES="${FEATURES},{{ redis_interface_backend }}"set -xcargo run --package router --no-default-features --features "${FEATURES}"set +x-check *FLAGS:+# redis_interface_backend: "redis-rs" (default) or "fred"+check redis_interface_backend="redis-rs" *FLAGS:#! /usr/bin/env bashset -euo pipefail@@ -103,12 +115,14 @@ check *FLAGS:jq -r '[ ( .workspace_members | sort ) as $package_ids # Store workspace crate package IDs in `package_ids` array| .packages[] | select( IN(.id; $package_ids[]) ) | .features | keys[] ] | unique # Select all unique features from all workspace crates- | del( .[] | select( any( . ; test("(([a-z_]+)_)?v2") ) ) ) # Exclude some features from features list+ | del( .[] | select( any( . ; test("(([a-z_]+)_)?v2") ) ) ) # Exclude v2 features+ | del( .[] | select( . == ("default", "fred", "redis-rs") ) ) # Exclude default and both backend flags| join(",") # Construct a comma-separated string of features for passing to `cargo`')"+ FEATURES="${FEATURES},{{ redis_interface_backend }}"set -x- cargo check {{ check_flags }} --features "${FEATURES}" {{ FLAGS }}+ cargo check {{ check_flags }} --no-default-features --features "${FEATURES}" {{ FLAGS }}set +xalias cl := clippy