Skip to content

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

feat(redis_interface): instrument Redis commands with external service call event emission (#13091)

spritianeja0381b9d86af8ce
diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs
index 8cd8809251..997889da91 100644
--- a/crates/common_utils/src/lib.rs
+++ b/crates/common_utils/src/lib.rs
@@ -29,6 +29,7 @@ pub mod payout_method_utils;
pub mod pii;
#[allow(missing_docs)] // Todo: add docs
pub mod request;
+pub mod request_context;
#[cfg(feature = "signals")]
pub mod signals;
pub mod transformers;
@@ -101,6 +102,11 @@ pub mod date_time {
OffsetDateTime::now_utc().unix_timestamp()
}
+ /// Return the UNIX timestamp in nanoseconds of the current date and time in UTC
+ pub fn now_unix_timestamp_nanos() -> i128 {
+ OffsetDateTime::now_utc().unix_timestamp_nanos()
+ }
+
/// Calculate execution time for a async block in milliseconds
#[cfg(feature = "async_ext")]
pub async fn time_it<T, Fut: futures::Future<Output = T>, F: FnOnce() -> Fut>(
diff --git a/crates/common_utils/src/request_context.rs b/crates/common_utils/src/request_context.rs
new file mode 100644
index 0000000000..d306b49fe2
--- /dev/null
+++ b/crates/common_utils/src/request_context.rs
@@ -0,0 +1,10 @@
+//! Request correlation context shared by infrastructure clients.
+
+/// Minimal request correlation context for infrastructure calls.
+///
+/// This intentionally avoids the name `Context` to prevent confusion with
+/// `error_stack::Context`, and carries the request ID only.
+pub trait RequestContext: Send + Sync {
+ /// Return the request ID associated with the current execution, if any.
+ fn request_id(&self) -> Option<&str>;
+}
diff --git a/crates/drainer/src/connection.rs b/crates/drainer/src/connection.rs
index ec3bc44973..0baef50aba 100644
--- a/crates/drainer/src/connection.rs
+++ b/crates/drainer/src/connection.rs
@@ -8,7 +8,7 @@ pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>;
#[allow(clippy::expect_used)]
pub async fn redis_connection(conf: &Settings) -> redis_interface::RedisConnectionPool {
- redis_interface::RedisConnectionPool::new(&conf.redis)
+ redis_interface::RedisConnectionPool::new_without_event_emitter(&conf.redis)
.await
.expect("Failed to create Redis connection Pool")
}
diff --git a/crates/drainer/src/handler.rs b/crates/drainer/src/handler.rs
index db7889cbb5..b00c35dc1e 100644
--- a/crates/drainer/src/handler.rs
+++ b/crates/drainer/src/handler.rs
@@ -129,7 +129,7 @@ impl Handler {
.stores
.values()
.next()
- .map(|store| store.redis_conn.clone());
+ .map(|store| store.get_redis_conn().redis_conn.clone());
match redis_conn_clone {
None => {
logger::error!("No redis connection found");
@@ -231,7 +231,7 @@ async fn drainer(
// parse_stream_entries returns error if no entries is found, handle it
let entries = utils::parse_stream_entries(
&stream_read,
- store.redis_conn.add_prefix(stream_name).as_str(),
+ store.get_redis_conn().add_prefix(stream_name).as_str(),
)?;
let read_count = entries.len();
diff --git a/crates/drainer/src/health_check.rs b/crates/drainer/src/health_check.rs
index 27cc7c757e..a114502a88 100644
--- a/crates/drainer/src/health_check.rs
+++ b/crates/drainer/src/health_check.rs
@@ -162,7 +162,7 @@ impl HealthCheckInterface for Store {
&self,
_conf: &Settings,
) -> CustomResult<(), HealthCheckRedisError> {
- let redis_conn = self.redis_conn.clone();
+ let redis_conn = self.get_redis_conn();
redis_conn
.serialize_and_set_key_with_expiry(&"test_key".into(), "test_value", 30)
diff --git a/crates/drainer/src/services.rs b/crates/drainer/src/services.rs
index 14bef1bf23..0030d740ba 100644
--- a/crates/drainer/src/services.rs
+++ b/crates/drainer/src/services.rs
@@ -1,6 +1,7 @@
use std::sync::Arc;
use actix_web::{body, HttpResponse, ResponseError};
+use common_utils::request_context::RequestContext;
use error_stack::Report;
use redis_interface::RedisConnectionPool;
@@ -13,11 +14,17 @@ use crate::{
#[derive(Clone)]
pub struct Store {
pub master_pool: PgPool,
- pub redis_conn: Arc<RedisConnectionPool>,
+ redis_conn: Arc<RedisConnectionPool>,
pub config: StoreConfig,
pub request_id: Option<String>,
}
+impl RequestContext for Store {
+ fn request_id(&self) -> Option<&str> {
+ self.request_id.as_deref()
+ }
+}
+
#[derive(Clone)]
pub struct StoreConfig {
pub drainer_stream_name: String,
@@ -55,6 +62,10 @@ impl Store {
pub fn use_legacy_version(&self) -> bool {
self.config.use_legacy_version
}
+
+ pub fn get_redis_conn(&self) -> redis_interface::RedisConnectionWithContext {
+ redis_interface::RedisConnectionWithContext::new(self.redis_conn.clone(), self)
+ }
}
pub fn log_and_return_error_response<T>(error: Report<T>) -> HttpResponse
diff --git a/crates/drainer/src/stream.rs b/crates/drainer/src/stream.rs
index fad80d96d3..898b437b03 100644
--- a/crates/drainer/src/stream.rs
+++ b/crates/drainer/src/stream.rs
@@ -28,7 +28,7 @@ impl Store {
let stream_key_flag = self.get_stream_key_flag(stream_index);
match self
- .redis_conn
+ .get_redis_conn()
.set_key_if_not_exists_with_expiry(&stream_key_flag.as_str().into(), true, None)
.await
{
@@ -41,7 +41,11 @@ impl Store {
}
pub async fn make_stream_available(&self, stream_name_flag: &str) -> errors::DrainerResult<()> {
- match self.redis_conn.delete_key(&stream_name_flag.into()).await {
+ match self
+ .get_redis_conn()
+ .delete_key(&stream_name_flag.into())
+ .await
+ {
Ok(redis::DelReply::KeyDeleted) => Ok(()),
Ok(redis::DelReply::KeyNotDeleted) => {
logger::error!("Tried to unlock a stream which is already unlocked");
@@ -59,7 +63,7 @@ impl Store {
// "0-0" id gives first entry
let stream_id = "0-0".to_string();
let (output, execution_time) = common_utils::date_time::time_it(|| async {
- self.redis_conn
+ self.get_redis_conn()
.stream_read_entries(&[stream_name.into()], vec![stream_id], Some(max_read_count))
.await
.map_err(errors::DrainerError::from)
@@ -86,14 +90,14 @@ impl Store {
let (trim_result, execution_time) =
common_utils::date_time::time_it::<errors::DrainerResult<_>, _, _>(|| async {
let trim_result = self
- .redis_conn
+ .get_redis_conn()
.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 id
- self.redis_conn
+ self.get_redis_conn()
.stream_delete_entries(&stream_name.into(), vec![minimum_entry_id.to_string()])
.await
.map_err(errors::DrainerError::from)?;
@@ -118,7 +122,7 @@ impl Store {
) -> errors::DrainerResult<()> {
let (_trim_result, execution_time) =
common_utils::date_time::time_it::<errors::DrainerResult<_>, _, _>(|| async {
- self.redis_conn
+ self.get_redis_conn()
.stream_delete_entries(&stream_name.into(), vec![entry_id.to_string()])
.await
.map_err(errors::DrainerError::from)?;
diff --git a/crates/redis_interface/src/lib.rs b/crates/redis_interface/src/lib.rs
index 3b3bb9c7f8..10c7918ed8 100644
--- a/crates/redis_interface/src/lib.rs
+++ b/crates/redis_interface/src/lib.rs
@@ -3,12 +3,15 @@
//! By default the `redis-rs` crate is used. Enable the `fred` feature to switch.
//!
//! # Examples
-//! ```
+//! ```ignore
+//! use std::sync::Arc;
+//! use common_utils::external_service::NoOpEventEmitter;
//! use redis_interface::{types::RedisSettings, RedisConnectionPool};
//!
//! #[tokio::main]
//! async fn main() {
-//! let redis_conn = RedisConnectionPool::new(&RedisSettings::default()).await;
+//! let emitter = Arc::new(NoOpEventEmitter);
+//! let redis_conn = RedisConnectionPool::new(&RedisSettings::default(), emitter).await;
//! }
//! ```
@@ -42,12 +45,13 @@ mod module {
pub use fred::interfaces::{EventInterface, PubsubInterface};
#[cfg(feature = "fred")]
pub use module::fred::{
- PubSubMessage, RedisClient, RedisConfig, RedisConnectionPool, SubscriberClient,
+ PubSubMessage, RedisClient, RedisConfig, RedisConnectionPool, RedisConnectionWithContext,
+ SubscriberClient,
};
#[cfg(feature = "redis-rs")]
pub use module::redis_rs::{
redis_value_to_option_string, PubSubMessage, PublisherClient, RedisConfig, RedisConn,
- RedisConnectionPool, SubscriberClient,
+ RedisConnectionPool, RedisConnectionWithContext, SubscriberClient,
};
pub use self::types::*;
diff --git a/crates/redis_interface/src/metrics.rs b/crates/redis_interface/src/metrics.rs
index f4f37c2da1..44ed3a0530 100644
--- a/crates/redis_interface/src/metrics.rs
+++ b/crates/redis_interface/src/metrics.rs
@@ -1,5 +1,17 @@
-//! OpenTelemetry metrics for Redis operations, gated behind the `metrics` feature.
+//! OpenTelemetry metrics and per-roundtrip event emission for Redis operations.
+//!
+//! `track_redis_call` wraps every raw Redis client future — i.e. every actual
+//! network roundtrip. It records the OTel latency histogram (gated behind the
+//! `metrics` feature) and, independently, emits one `ExternalServiceCall` event
+//! per roundtrip reflecting that exact command's latency and outcome.
+//!
+//! Emitting at the roundtrip layer (rather than once per logical command
+//! method) means multi-roundtrip methods — multitenancy-fallback retries,
+//! `HSET` + `EXPIRE`, cluster parallel `GET`, `SCAN`/`HSCAN` cursor pages —
+//! each produce one event per real roundtrip with correct wall-clock latency,
+//! instead of a single event whose latency sums or hides the constituent calls.
+use common_utils::external_service::{ExternalServiceCall, ExternalServiceEventEmitter};
#[cfg(feature = "metrics")]
use router_env::{global_meter, histogram_metric_f64};
@@ -9,7 +21,8 @@ global_meter!(GLOBAL_METER, "REDIS");
#[cfg(feature = "metrics")]
histogram_metric_f64!(REDIS_CALL_TIME, GLOBAL_METER);
-/// The Redis operation being performed, used as the `operation` metric label.
+/// The Redis operation being performed. Used both as the `operation` metric
+/// label and as the `endpoint` field on the emitted `ExternalServiceCall`.
#[derive(Debug)]
pub(crate) enum RedisOperation {
SetKey,
@@ -55,11 +68,55 @@ pub(crate) enum RedisOperation {
EvaluateRedisScript,
}
-/// Times a Redis future and records its latency, tagged by operation.
+/// Extracts whether a completed Redis roundtrip succeeded, so the emitted
+/// `ExternalServiceCall` can carry `success`/`status_code`.
+///
+/// Most `track_redis_call` call sites pass a future whose output is a `Result`
+/// (the raw `RedisResult`/`FredResult`, or an already-`change_context`ed
+/// `CustomResult`), so the blanket impl below covers those.
+pub(crate) trait RedisCallStatus {
+ fn is_success(&self) -> bool;
+}
+
+impl<T, E> RedisCallStatus for Result<T, E> {
+ fn is_success(&self) -> bool {
+ self.is_ok()
+ }
+}
+
+/// Output of the `SCAN`/`HSCAN` streaming helpers, which collect successful
+/// pages into a `Vec<String>` after logging and dropping page-level errors. At
+/// this layer no error signal remains, so completion is treated as success for
+/// event emission.
+///
+/// Only the `fred` backend streams pages this way; `redis-rs` loops per-page
+/// `track_redis_call`s that already return a `Result`, so it never needs this type.
+#[cfg(feature = "fred")]
+pub(crate) struct ScanOutcome(pub Vec<String>);
+
+#[cfg(feature = "fred")]
+impl RedisCallStatus for ScanOutcome {
+ fn is_success(&self) -> bool {
+ true
+ }
+}
+
+/// Times a single Redis roundtrip, records its latency metric, and emits one
+/// `ExternalServiceCall` event reflecting this exact roundtrip.
+///
+/// When `request_id` is absent (background work, drainer, scheduler) no event is
+/// emitted: the correlator joins on `request_id` and cannot place request-less
+/// rows.
#[inline]
-pub(crate) async fn track_redis_call<Fut, U>(operation: RedisOperation, future: Fut) -> U
+pub(crate) async fn track_redis_call<Fut, U>(
+ request_id: Option<&str>,
+ event_emitter: &dyn ExternalServiceEventEmitter,
+ operation: RedisOperation,
+ future: Fut,
+) -> U
where
Fut: std::future::Future<Output = U>,
+ U: RedisCallStatus,
{
let start = std::time::Instant::now();
let output = future.await;
@@ -77,5 +134,19 @@ where
REDIS_CALL_TIME.record(time_elapsed.as_secs_f64(), attributes);
}
+ if let Some(request_id) = request_id {
+ let success = output.is_success();
+ event_emitter.emit_external_service_call(ExternalServiceCall {
+ service_name: "redis".to_string(),
+ endpoint: format!("{operation:?}"),
+ method: "Redis".to_string(),
+ request_id: request_id.to_string(),
+ status_code: if success { 200 } else { 500 },
+ success,
+ latency_ms: time_elapsed.as_millis(),
+ created_at_timestamp: common_utils::date_time::now_unix_timestamp_nanos(),
+ });
+ }
+
output
}
diff --git a/crates/redis_interface/src/module/fred.rs b/crates/redis_interface/src/module/fred.rs
index bf42337bdd..dd2709cee0 100644
--- a/crates/redis_interface/src/module/fred.rs
+++ b/crates/redis_interface/src/module/fred.rs
@@ -8,7 +8,11 @@ pub mod types;
use std::sync::{atomic, Arc};
-use common_utils::errors::CustomResult;
+use common_utils::{
+ errors::CustomResult,
+ external_service::{ExternalServiceEventEmitter, NoOpEventEmitter},
+ request_context::RequestContext,
+};
use error_stack::ResultExt;
use fred::{
clients::Transaction,
@@ -172,12 +176,51 @@ pub struct RedisConnectionPool {
pub subscriber: Arc<SubscriberClient>,
pub publisher: Arc<RedisClient>,
pub is_redis_available: Arc<atomic::AtomicBool>,
+ pub event_emitter: Arc<dyn ExternalServiceEventEmitter>,
+}
+
+/// A request-scoped Redis handle.
+///
+/// Wraps the shared [`RedisConnectionPool`] and carries the request ID of the
+/// execution that created it, so per-roundtrip events can be correlated back to
+/// the originating API request.
+#[derive(Clone)]
+pub struct RedisConnectionWithContext {
+ pub redis_conn: Arc<RedisConnectionPool>,
+ pub request_id: Option<String>,
+}
+
+impl RedisConnectionWithContext {
+ pub fn new(pool: Arc<RedisConnectionPool>, context: &dyn RequestContext) -> Self {
+ Self {
+ redis_conn: pool,
+ request_id: context.request_id().map(str::to_owned),
+ }
+ }
+
+ pub fn new_without_context(pool: Arc<RedisConnectionPool>) -> Self {
+ Self {
+ redis_conn: pool,
+ request_id: None,
+ }
+ }
+
+ pub fn get_transaction(&self) -> Transaction {
+ self.redis_conn.pool.next().multi()
+ }
}
impl RedisConnectionPool {
/// Create a new Redis connection
+ pub async fn new_without_event_emitter(
+ conf: &crate::types::RedisSettings,
+ ) -> CustomResult<Self, crate::errors::RedisError> {
+ Self::new(conf, Arc::new(NoOpEventEmitter)).await
+ }
+
pub async fn new(
conf: &crate::types::RedisSettings,
+ event_emitter: Arc<dyn ExternalServiceEventEmitter>,
) -> CustomResult<Self, crate::errors::RedisError> {
let redis_connection_url = match conf.cluster_enabled {
true => format!(
@@ -260,6 +303,7 @@ impl RedisConnectionPool {
subscriber: Arc::new(subscriber),
publisher: Arc::new(publisher),
key_prefix: String::default(),
+ event_emitter,
})
}
@@ -271,9 +315,32 @@ impl RedisConnectionPool {
subscriber: Arc::clone(&self.subscriber),
publisher: Arc::clone(&self.publisher),
is_redis_available: Arc::clone(&self.is_redis_available),
+ event_emitter: Arc::clone(&self.event_emitter),
}
}
+ /// Prefix `key` with this pool's tenant key prefix.
+ pub fn add_prefix(&self, key: &str) -> String {
+ let physical = if self.key_prefix.is_empty() {
+ key.to_string()
+ } else {
+ format!("{}:{}", self.key_prefix, key)
+ };
+ // Deja replay isolation: during REPLAY, namespace every physical key
+ // by the active correlation so each test case's store is isolated — no
+ // cross-case collisions and no read-modify-write double-apply, which is
+ // what makes it safe to Execute stateful redis ops against the seeded
+ // store. The harness seeds each correlation under the same
+ // `{correlation}:{physical}` namespace. Inert during record and when no
+ // correlation is in scope, so recorded keys and normal operation are
+ // unchanged (and for Substitute ops the real command never runs anyway).
+ #[cfg(feature = "deja")]
+ if let Some(corr) = deja::replay_key_namespace() {
+ return format!("{corr}:{physical}");
+ }
+ physical
+ }
+
pub async fn on_error(&self, tx: tokio::sync::oneshot::Sender<()>) {
use futures::StreamExt;
use tokio_stream::wrappers::BroadcastStream;
@@ -309,10 +376,6 @@ impl RedisConnectionPool {
})
});
}
-
- pub fn get_transaction(&self) -> Transaction {
- self.pool.next().multi()
- }
}
// ─── RedisConfig ─────────────────────────────────────────────────────────────
diff --git a/crates/redis_interface/src/module/fred/commands.rs b/crates/redis_interface/src/module/fred/commands.rs
index 15a248756b..eb23d7df44 100644
--- a/crates/redis_interface/src/module/fred/commands.rs
+++ b/crates/redis_interface/src/module/fred/commands.rs
@@ -101,26 +101,10 @@ impl TryFrom<DejaRedisValue> for RedisValue {
}
}
-impl super::RedisConnectionPool {
+impl super::RedisConnectionWithContext {
+ /// Prefix `key` with the tenant key prefix of the underlying pool.
pub fn add_prefix(&self, key: &str) -> String {
- let physical = if self.key_prefix.is_empty() {
- key.to_string()
- } else {
- format!("{}:{}", self.key_prefix, key)
- };
- // Deja replay isolation: during REPLAY, namespace every physical key
- // by the active correlation so each test case's store is isolated — no
- // cross-case collisions and no read-modify-write double-apply, which is
- // what makes it safe to Execute stateful redis ops against the seeded
- // store. The harness seeds each correlation under the same
- // `{correlation}:{physical}` namespace. Inert during record and when no
- // correlation is in scope, so recorded keys and normal operation are
- // unchanged (and for Substitute ops the real command never runs anyway).
- #[cfg(feature = "deja")]
- if let Some(corr) = deja::replay_key_namespace() {
- return format!("{corr}:{physical}");
- }
- physical
+ self.redis_conn.add_prefix(key)
}
#[cfg_attr(
@@ -144,11 +128,13 @@ impl super::RedisConnectionPool {
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetKey,
- self.pool.set(
- key.tenant_aware_key(self),
+ self.redis_conn.pool.set(
+ key.tenant_aware_key(&self.redis_conn),
value,
- Some(Expiration::EX(self.config.default_ttl.into())),
+ Some(Expiration::EX(self.redis_conn.config.default_ttl.into())),
None,
false,
),
@@ -180,9 +166,11 @@ impl super::RedisConnectionPool {
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetKeyWithoutModifyingTtl,
- self.pool.set(
- key.tenant_aware_key(self),
+ self.redis_conn.pool.set(
+ key.tenant_aware_key(&self.redis_conn),
value,
Some(Expiration::KEEPTTL),
None,
@@ -223,8 +211,10 @@ impl super::RedisConnectionPool {
.attach_printable("Failed to convert key-value pairs to fred::types::RedisMap")?;
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetMultipleKeysIfNotExist,
- self.pool.msetnx(map),
+ self.redis_conn.pool.msetnx(map),
)
.await
.change_context(errors::RedisError::SetFailed)
@@ -303,9 +293,11 @@ impl super::RedisConnectionPool {
#[cfg(not(feature = "deja"))]
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SerializeAndSetKeyWithExpiry,
- self.pool.set(
- key.tenant_aware_key(self),
+ self.redis_conn.pool.set(
+ key.tenant_aware_key(&self.redis_conn),
serialized.as_slice(),
Some(Expiration::EX(seconds)),
None,
@@ -329,7 +321,7 @@ impl super::RedisConnectionPool {
#[deja::redis(
operation = "get_key",
codec = deja::codec::ResultCodec::<DejaRedisValue, errors::RedisError>,
- state_read = key.tenant_aware_key(self),
+ state_read = key.tenant_aware_key(&self.redis_conn),
args = {
serde_json::json!({
"key": key.as_str(),
@@ -342,8 +334,12 @@ impl super::RedisConnectionPool {
key: &RedisKey,
) -> CustomResult<DejaRedisValue, errors::RedisError> {
match track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetKey,
- self.pool.get::<RedisValue, _>(key.tenant_aware_key(self)),
+ self.redis_conn
+ .pool
+ .get::<RedisValue, _>(key.tenant_aware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetFailed)
@@ -358,8 +354,12 @@ impl super::RedisConnectionPool {
#[cfg(feature = "multitenancy_fallback")]
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetKey,
- self.pool.get::<RedisValue, _>(key.tenant_unaware_key(self)),
+ self.redis_conn
+ .pool
+ .get::<RedisValue, _>(key.tenant_unaware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetFailed)
@@ -386,8 +386,12 @@ impl super::RedisConnectionPool {
#[cfg(not(feature = "deja"))]
{
match track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetKey,
- self.pool.get(key.tenant_aware_key(self)),
+ self.redis_conn
+ .pool
+ .get(key.tenant_aware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetFailed)
@@ -402,8 +406,12 @@ impl super::RedisConnectionPool {
#[cfg(feature = "multitenancy_fallback")]
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetKey,
- self.pool.get(key.tenant_unaware_key(self)),
+ self.redis_conn
+ .pool
+ .get(key.tenant_unaware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetFailed)
@@ -425,11 +433,15 @@ impl super::RedisConnectionPool {
return Ok(Vec::new());
}
- let tenant_aware_keys: Vec<String> =
- keys.iter().map(|key| key.tenant_aware_key(self)).collect();
+ let tenant_aware_keys: Vec<String> = keys
+ .iter()
+ .map(|key| key.tenant_aware_key(&self.redis_conn))
+ .collect();
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetMultipleKeys,
- self.pool.mget(tenant_aware_keys),
+ self.redis_conn.pool.mget(tenant_aware_keys),
)
.await
.change_context(errors::RedisError::GetFailed)
@@ -446,13 +458,17 @@ impl super::RedisConnectionPool {
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 tenant_aware_keys: Vec<String> = keys
+ .iter()
+ .map(|key| key.tenant_aware_key(&self.redis_conn))
+ .collect();
let futures = tenant_aware_keys.iter().map(|redis_key| {
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetKey,
- self.pool.get::<Option<V>, _>(redis_key),
+ self.redis_conn.pool.get::<Option<V>, _>(redis_key),
)
});
@@ -473,7 +489,7 @@ impl super::RedisConnectionPool {
where
V: FromRedis + Unpin + Send + 'static,
{
- if self.config.cluster_enabled {
+ if self.redis_conn.config.cluster_enabled {
// Use individual GET commands for cluster mode to avoid CROSSSLOT errors
self.get_multiple_keys_with_parallel_get(keys).await
} else {
@@ -486,7 +502,7 @@ impl super::RedisConnectionPool {
feature = "deja",
deja::redis(
operation = "get_multiple_keys",
- read_set = keys.iter().map(|key| key.tenant_aware_key(self)).collect::<Vec<_>>(),
+ read_set = keys.iter().map(|key| key.tenant_aware_key(&self.redis_conn)).collect::<Vec<_>>(),
args = {
serde_json::json!({
"key_count": keys.len(),
@@ -529,7 +545,7 @@ impl super::RedisConnectionPool {
{
let tenant_unaware_keys: Vec<RedisKey> = keys
.iter()
- .map(|key| key.tenant_unaware_key(self).into())
+ .map(|key| key.tenant_unaware_key(&self.redis_conn).into())
.collect();
self.get_keys_by_mode(&tenant_unaware_keys).await
@@ -557,8 +573,12 @@ impl super::RedisConnectionPool {
V: Into<MultipleKeys> + Unpin + Send + 'static,
{
match track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::Exists,
- self.pool.exists(key.tenant_aware_key(self)),
+ self.redis_conn
+ .pool
+ .exists(key.tenant_aware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetFailed)
@@ -573,8 +593,12 @@ impl super::RedisConnectionPool {
#[cfg(feature = "multitenancy_fallback")]
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::Exists,
- self.pool.exists(key.tenant_unaware_key(self)),
+ self.redis_conn
+ .pool
+ .exists(key.tenant_unaware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetFailed)
@@ -648,8 +672,12 @@ impl super::RedisConnectionPool {
#[instrument(level = "DEBUG", skip(self))]
pub async fn delete_key(&self, key: &RedisKey) -> CustomResult<DelReply, errors::RedisError> {
match track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::DeleteKey,
- self.pool.del(key.tenant_aware_key(self)),
+ self.redis_conn
+ .pool
+ .del(key.tenant_aware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::DeleteFailed)
@@ -664,8 +692,12 @@ impl super::RedisConnectionPool {
#[cfg(feature = "multitenancy_fallback")]
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::DeleteKey,
- self.pool.del(key.tenant_unaware_key(self)),
+ self.redis_conn
+ .pool
+ .del(key.tenant_unaware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::DeleteFailed)
@@ -716,9 +748,11 @@ impl super::RedisConnectionPool {
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetKeyWithExpiry,
- self.pool.set(
- key.tenant_aware_key(self),
+ self.redis_conn.pool.set(
+ key.tenant_aware_key(&self.redis_conn),
value,
Some(Expiration::EX(seconds)),
None,
@@ -738,7 +772,7 @@ impl super::RedisConnectionPool {
// later read-back of it (e.g. the lock GET after this SETNX). Without
// this the read-back is seeded as "present", and the replayed Execute
// SETNX then sees the lock held → never acquires → retry storm.
- state_write = key.tenant_aware_key(self),
+ state_write = key.tenant_aware_key(&self.redis_conn),
args = {
serde_json::json!({
"key": key.as_str(),
@@ -760,12 +794,14 @@ impl super::RedisConnectionPool {
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetKeyIfNotExistsWithExpiry,
- self.pool.set(
- key.tenant_aware_key(self),
+ self.redis_conn.pool.set(
+ key.tenant_aware_key(&self.redis_conn),
value,
Some(Expiration::EX(
- seconds.unwrap_or(self.config.default_ttl.into()),
+ seconds.unwrap_or(self.redis_conn.config.default_ttl.into()),
)),
Some(SetOptions::NX),
false,
@@ -796,8 +832,12 @@ impl super::RedisConnectionPool {
seconds: i64,
) -> CustomResult<(), errors::RedisError> {
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetExpiry,
- self.pool.expire(key.tenant_aware_key(self), seconds),
+ self.redis_conn
+ .pool
+ .expire(key.tenant_aware_key(&self.redis_conn), seconds),
)
.await
.change_context(errors::RedisError::SetExpiryFailed)
@@ -824,8 +864,12 @@ impl super::RedisConnectionPool {
timestamp: i64,
) -> CustomResult<(), errors::RedisError> {
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetExpireAt,
- self.pool.expire_at(key.tenant_aware_key(self), timestamp),
+ self.redis_conn
+ .pool
+ .expire_at(key.tenant_aware_key(&self.redis_conn), timestamp),
)
.await
.change_context(errors::RedisError::SetExpiryFailed)
@@ -847,8 +891,12 @@ impl super::RedisConnectionPool {
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_ttl(&self, key: &RedisKey) -> CustomResult<i64, errors::RedisError> {
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetTtl,
- self.pool.ttl(key.tenant_aware_key(self)),
+ self.redis_conn
+ .pool
+ .ttl(key.tenant_aware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetFailed)
@@ -889,8 +937,12 @@ impl super::RedisConnectionPool {
.attach_printable("Failed to convert field pairs to fred::types::RedisMap")?;
let output: Result<(), _> = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetHashFields,
- self.pool.hset(key.tenant_aware_key(self), map),
+ self.redis_conn
+ .pool
+ .hset(key.tenant_aware_key(&self.redis_conn), map),
)
.await
.change_context(errors::RedisError::SetHashFailed);
@@ -899,7 +951,10 @@ impl super::RedisConnectionPool {
{
output
.async_and_then(|_| {
- self.set_expiry(key, ttl.unwrap_or(self.config.default_hash_ttl.into()))
+ self.set_expiry(
+ key,
+ ttl.unwrap_or(self.redis_conn.config.default_hash_ttl.into()),
+ )
})
.await
}
@@ -914,10 +969,12 @@ impl super::RedisConnectionPool {
output
.async_and_then(|_| async {
let _: () = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetExpiry,
- self.pool.expire(
- key.tenant_aware_key(self),
- ttl.unwrap_or(self.config.default_hash_ttl.into()),
+ self.redis_conn.pool.expire(
+ key.tenant_aware_key(&self.redis_conn),
+ ttl.unwrap_or(self.redis_conn.config.default_hash_ttl.into()),
),
)
.await
@@ -956,8 +1013,12 @@ impl super::RedisConnectionPool {
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
let output: Result<HsetnxReply, _> = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetHashFieldIfNotExist,
- self.pool.hsetnx(key.tenant_aware_key(self), field, value),
+ self.redis_conn
+ .pool
+ .hsetnx(key.tenant_aware_key(&self.redis_conn), field, value),
)
.await
.change_context(errors::RedisError::SetHashFieldFailed);
@@ -966,8 +1027,12 @@ impl super::RedisConnectionPool {
{
output
.async_and_then(|inner| async {
- self.set_expiry(key, ttl.unwrap_or(self.config.default_hash_ttl).into())
- .await?;
+ self.set_expiry(
+ key,
+ ttl.unwrap_or(self.redis_conn.config.default_hash_ttl)
+ .into(),
+ )
+ .await?;
Ok(inner)
})
.await
@@ -981,10 +1046,13 @@ impl super::RedisConnectionPool {
output
.async_and_then(|inner| async {
let _: () = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetExpiry,
- self.pool.expire(
- key.tenant_aware_key(self),
- ttl.unwrap_or(self.config.default_hash_ttl).into(),
+ self.redis_conn.pool.expire(
+ key.tenant_aware_key(&self.redis_conn),
+ ttl.unwrap_or(self.redis_conn.config.default_hash_ttl)
+ .into(),
),
)
.await
@@ -1061,9 +1129,14 @@ impl super::RedisConnectionPool {
for (field, increment) in fields_to_increment {
values_after_increment.push(
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::IncrementFieldsInHash,
- self.pool
- .hincrby(key.tenant_aware_key(self), field.to_string(), *increment),
+ self.redis_conn.pool.hincrby(
+ key.tenant_aware_key(&self.redis_conn),
+ field.to_string(),
+ *increment,
+ ),
)
.await
.change_context(errors::RedisError::IncrementHashFieldFailed)?,
@@ -1093,13 +1166,13 @@ impl super::RedisConnectionPool {
pattern: &str,
count: Option<u32>,
) -> CustomResult<Vec<String>, errors::RedisError> {
- use futures::StreamExt;
+ use futures::{FutureExt, StreamExt};
- Ok(track_redis_call(
+ Ok(track_redis_call(self.request_id.as_deref(), self.redis_conn.event_emitter.as_ref(),
RedisOperation::Hscan,
- self.pool
+ self.redis_conn.pool
.next()
- .hscan::<&str, &str>(&key.tenant_aware_key(self), pattern, count)
+ .hscan::<&str, &str>(&key.tenant_aware_key(&self.redis_conn), pattern, count)
.filter_map(|value| async move {
match value {
Ok(mut v) => {
@@ -1116,9 +1189,11 @@ impl super::RedisConnectionPool {
}
})
.flatten()
- .collect::<Vec<_>>(),
+ .collect::<Vec<_>>()
+ .map(crate::metrics::ScanOutcome),
)
- .await)
+ .await
+ .0)
}
#[instrument(level = "DEBUG", skip(self))]
@@ -1140,15 +1215,15 @@ impl super::RedisConnectionPool {
count: Option<u32>,
scan_type: Option<crate::types::RedisScanType>,
) -> CustomResult<Vec<String>, errors::RedisError> {
- use futures::StreamExt;
+ use futures::{FutureExt, StreamExt};
let fred_scan_type = scan_type.map(fred::types::ScanType::from);
- Ok(track_redis_call(
+ Ok(track_redis_call(self.request_id.as_deref(), self.redis_conn.event_emitter.as_ref(),
RedisOperation::Scan,
- self.pool
+ self.redis_conn.pool
.next()
- .scan(pattern.tenant_aware_key(self), count, fred_scan_type)
+ .scan(pattern.tenant_aware_key(&self.redis_conn), count, fred_scan_type)
.filter_map(|value| async move {
match value {
Ok(mut v) => {
@@ -1164,9 +1239,11 @@ impl super::RedisConnectionPool {
}
})
.flatten()
- .collect::<Vec<_>>(),
+ .collect::<Vec<_>>()
+ .map(crate::metrics::ScanOutcome),
)
- .await)
+ .await
+ .0)
}
#[instrument(level = "DEBUG", skip(self))]
@@ -1201,7 +1278,7 @@ impl super::RedisConnectionPool {
#[deja::redis(
operation = "get_hash_field",
codec = deja::codec::ResultCodec::<DejaRedisValue, errors::RedisError>,
- state_read = format!("{}:{}", key.tenant_aware_key(self), field),
+ state_read = format!("{}:{}", key.tenant_aware_key(&self.redis_conn), field),
args = {
serde_json::json!({
"key": key.as_str(),
@@ -1216,9 +1293,12 @@ impl super::RedisConnectionPool {
field: &str,
) -> CustomResult<DejaRedisValue, errors::RedisError> {
match track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetHashField,
- self.pool
- .hget::<RedisValue, _, _>(key.tenant_aware_key(self), field),
+ self.redis_conn
+ .pool
+ .hget::<RedisValue, _, _>(key.tenant_aware_key(&self.redis_conn), field),
)
.await
.change_context(errors::RedisError::GetHashFieldFailed)
@@ -1228,9 +1308,13 @@ impl super::RedisConnectionPool {
#[cfg(feature = "multitenancy_fallback")]
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetHashField,
- self.pool
- .hget::<RedisValue, _, _>(key.tenant_unaware_key(self), field),
+ self.redis_conn.pool.hget::<RedisValue, _, _>(
+ key.tenant_unaware_key(&self.redis_conn),
+ field,
+ ),
)
.await
.change_context(errors::RedisError::GetHashFieldFailed)
@@ -1266,8 +1350,12 @@ impl super::RedisConnectionPool {
#[cfg(not(feature = "deja"))]
{
match track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetHashField,
- self.pool.hget(key.tenant_aware_key(self), field),
+ self.redis_conn
+ .pool
+ .hget(key.tenant_aware_key(&self.redis_conn), field),
)
.await
.change_context(errors::RedisError::GetHashFieldFailed)
@@ -1277,8 +1365,12 @@ impl super::RedisConnectionPool {
#[cfg(feature = "multitenancy_fallback")]
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetHashField,
- self.pool.hget(key.tenant_unaware_key(self), field),
+ self.redis_conn
+ .pool
+ .hget(key.tenant_unaware_key(&self.redis_conn), field),
)
.await
.change_context(errors::RedisError::GetHashFieldFailed)
@@ -1298,7 +1390,7 @@ impl super::RedisConnectionPool {
#[deja::redis(
operation = "get_hash_fields",
codec = deja::codec::ResultCodec::<DejaRedisValue, errors::RedisError>,
- state_read = key.tenant_aware_key(self),
+ state_read = key.tenant_aware_key(&self.redis_conn),
args = {
serde_json::json!({
"key": key.as_str(),
@@ -1311,9 +1403,12 @@ impl super::RedisConnectionPool {
key: &RedisKey,
) -> CustomResult<DejaRedisValue, errors::RedisError> {
match track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetHashFields,
- self.pool
- .hgetall::<RedisValue, _>(key.tenant_aware_key(self)),
+ self.redis_conn
+ .pool
+ .hgetall::<RedisValue, _>(key.tenant_aware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetHashFieldFailed)
@@ -1323,9 +1418,12 @@ impl super::RedisConnectionPool {
#[cfg(feature = "multitenancy_fallback")]
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetHashFields,
- self.pool
- .hgetall::<RedisValue, _>(key.tenant_unaware_key(self)),
+ self.redis_conn
+ .pool
+ .hgetall::<RedisValue, _>(key.tenant_unaware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetHashFieldFailed)
@@ -1357,8 +1455,12 @@ impl super::RedisConnectionPool {
#[cfg(not(feature = "deja"))]
{
match track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetHashFields,
- self.pool.hgetall(key.tenant_aware_key(self)),
+ self.redis_conn
+ .pool
+ .hgetall(key.tenant_aware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetHashFieldFailed)
@@ -1368,8 +1470,12 @@ impl super::RedisConnectionPool {
#[cfg(feature = "multitenancy_fallback")]
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetHashFields,
- self.pool.hgetall(key.tenant_unaware_key(self)),
+ self.redis_conn
+ .pool
+ .hgetall(key.tenant_unaware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetHashFieldFailed)
@@ -1415,8 +1521,12 @@ impl super::RedisConnectionPool {
F: Into<MultipleKeys> + Debug + Send + Sync,
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::DeleteHashFields,
- self.pool.hdel(key.tenant_aware_key(self), fields),
+ self.redis_conn
+ .pool
+ .hdel(key.tenant_aware_key(&self.redis_conn), fields),
)
.await
.change_context(errors::RedisError::DeleteHashFieldFailed)
@@ -1428,7 +1538,7 @@ impl super::RedisConnectionPool {
replay = Substitute,
operation = "sadd",
codec = deja::codec::ResultCodec::<SaddReply, errors::RedisError>,
- state_write = key.tenant_aware_key(self),
+ state_write = key.tenant_aware_key(&self.redis_conn),
args = {
serde_json::json!({
"key": key.as_str(),
@@ -1448,8 +1558,12 @@ impl super::RedisConnectionPool {
V::Error: Into<fred::error::RedisError> + Send,
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::Sadd,
- self.pool.sadd(key.tenant_aware_key(self), members),
+ self.redis_conn
+ .pool
+ .sadd(key.tenant_aware_key(&self.redis_conn), members),
)
.await
.change_context(errors::RedisError::SetAddMembersFailed)
@@ -1491,9 +1605,11 @@ impl super::RedisConnectionPool {
)?;
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::StreamAppendEntry,
- self.pool.xadd(
- stream.tenant_aware_key(self),
+ self.redis_conn.pool.xadd(
+ stream.tenant_aware_key(&self.redis_conn),
false,
None,
entry_id,
@@ -1525,8 +1641,12 @@ impl super::RedisConnectionPool {
) -> CustomResult<usize, errors::RedisError> {
let fred_ids: MultipleStrings = ids.into();
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::StreamDeleteEntries,
- self.pool.xdel(stream.tenant_aware_key(self), fred_ids),
+ self.redis_conn
+ .pool
+ .xdel(stream.tenant_aware_key(&self.redis_conn), fred_ids),
)
.await
.change_context(errors::RedisError::StreamDeleteFailed)
@@ -1555,8 +1675,12 @@ impl super::RedisConnectionPool {
.change_context(errors::RedisError::StreamTrimFailed)
.attach_printable("Failed to convert StreamTrimConfig to fred::types::XCap")?;
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::StreamTrimEntries,
- self.pool.xtrim(stream.tenant_aware_key(self), xcap),
+ self.redis_conn
+ .pool
+ .xtrim(stream.tenant_aware_key(&self.redis_conn), xcap),
)
.await
.change_context(errors::RedisError::StreamTrimFailed)
@@ -1585,9 +1709,12 @@ impl super::RedisConnectionPool {
) -> CustomResult<usize, errors::RedisError> {
let fred_ids: MultipleIDs = ids.into();
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::StreamAcknowledgeEntries,
- self.pool
- .xack(stream.tenant_aware_key(self), group, fred_ids),
+ self.redis_conn
+ .pool
+ .xack(stream.tenant_aware_key(&self.redis_conn), group, fred_ids),
)
.await
.change_context(errors::RedisError::StreamAcknowledgeFailed)
@@ -1611,15 +1738,22 @@ impl super::RedisConnectionPool {
stream: &RedisKey,
) -> CustomResult<usize, errors::RedisError> {
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::StreamGetLength,
- self.pool.xlen(stream.tenant_aware_key(self)),
+ self.redis_conn
+ .pool
+ .xlen(stream.tenant_aware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetLengthFailed)
}
fn get_keys_with_prefix(&self, streams: &[RedisKey]) -> MultipleKeys {
- let res: Vec<String> = streams.iter().map(|k| k.tenant_aware_key(self)).collect();
+ let res: Vec<String> = streams
+ .iter()
+ .map(|k| k.tenant_aware_key(&self.redis_conn))
+ .collect();
MultipleKeys::from(res)
}
@@ -1644,9 +1778,11 @@ impl super::RedisConnectionPool {
let strms = self.get_keys_with_prefix(streams);
let ids: MultipleIDs = ids.into();
let reply: XReadResponse<String, String, String, String> = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::StreamReadEntries,
- self.pool.xread_map(
- Some(read_count.unwrap_or(self.config.default_stream_read_count)),
+ self.redis_conn.pool.xread_map(
+ Some(read_count.unwrap_or(self.redis_conn.config.default_stream_read_count)),
None,
strms,
ids,
@@ -1711,8 +1847,10 @@ impl super::RedisConnectionPool {
let reply: XReadResponse<String, String, String, Option<String>> = match group {
Some((group_name, consumer_name)) => {
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::StreamReadWithOptions,
- self.pool.xreadgroup_map(
+ self.redis_conn.pool.xreadgroup_map(
group_name,
consumer_name,
count,
@@ -1726,8 +1864,10 @@ impl super::RedisConnectionPool {
}
None => {
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::StreamReadWithOptions,
- self.pool.xread_map(count, block, strms, ids),
+ self.redis_conn.pool.xread_map(count, block, strms, ids),
)
.await
}
@@ -1792,8 +1932,12 @@ impl super::RedisConnectionPool {
V::Error: Into<fred::error::RedisError> + Send,
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::AppendElementsToList,
- self.pool.rpush(key.tenant_aware_key(self), elements),
+ self.redis_conn
+ .pool
+ .rpush(key.tenant_aware_key(&self.redis_conn), elements),
)
.await
.change_context(errors::RedisError::AppendElementsToListFailed)
@@ -1821,8 +1965,12 @@ impl super::RedisConnectionPool {
stop: i64,
) -> CustomResult<Vec<String>, errors::RedisError> {
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetListElements,
- self.pool.lrange(key.tenant_aware_key(self), start, stop),
+ self.redis_conn
+ .pool
+ .lrange(key.tenant_aware_key(&self.redis_conn), start, stop),
)
.await
.change_context(errors::RedisError::GetListElementsFailed)
@@ -1843,8 +1991,12 @@ impl super::RedisConnectionPool {
)]
pub async fn get_list_length(&self, key: &RedisKey) -> CustomResult<usize, errors::RedisError> {
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetListLength,
- self.pool.llen(key.tenant_aware_key(self)),
+ self.redis_conn
+ .pool
+ .llen(key.tenant_aware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetListLengthFailed)
@@ -1871,8 +2023,12 @@ impl super::RedisConnectionPool {
count: Option<usize>,
) -> CustomResult<Vec<String>, errors::RedisError> {
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::LpopListElements,
- self.pool.lpop(key.tenant_aware_key(self), count),
+ self.redis_conn
+ .pool
+ .lpop(key.tenant_aware_key(&self.redis_conn), count),
)
.await
.change_context(errors::RedisError::PopListElementsFailed)
@@ -1910,9 +2066,15 @@ impl super::RedisConnectionPool {
}
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::ConsumerGroupCreate,
- self.pool
- .xgroup_create(stream.tenant_aware_key(self), group, id, true),
+ self.redis_conn.pool.xgroup_create(
+ stream.tenant_aware_key(&self.redis_conn),
+ group,
+ id,
+ true,
+ ),
)
.await
.change_context(errors::RedisError::ConsumerGroupCreateFailed)
@@ -1939,9 +2101,12 @@ impl super::RedisConnectionPool {
group: &str,
) -> CustomResult<crate::types::ConsumerGroupDestroyReply, errors::RedisError> {
let reply: crate::types::ConsumerGroupDestroyReply = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::ConsumerGroupDestroy,
- self.pool
- .xgroup_destroy(stream.tenant_aware_key(self), group),
+ self.redis_conn
+ .pool
+ .xgroup_destroy(stream.tenant_aware_key(&self.redis_conn), group),
)
.await
.change_context(errors::RedisError::ConsumerGroupDestroyFailed)?;
@@ -1972,9 +2137,14 @@ impl super::RedisConnectionPool {
consumer: &str,
) -> CustomResult<usize, errors::RedisError> {
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::ConsumerGroupDeleteConsumer,
- self.pool
- .xgroup_delconsumer(stream.tenant_aware_key(self), group, consumer),
+ self.redis_conn.pool.xgroup_delconsumer(
+ stream.tenant_aware_key(&self.redis_conn),
+ group,
+ consumer,
+ ),
)
.await
.change_context(errors::RedisError::ConsumerGroupRemoveConsumerFailed)
@@ -2003,9 +2173,14 @@ impl super::RedisConnectionPool {
) -> CustomResult<String, errors::RedisError> {
let id_str = id.to_stream_id();
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::ConsumerGroupSetLastId,
- self.pool
- .xgroup_setid::<(), _, _, _>(stream.tenant_aware_key(self), group, &id_str),
+ self.redis_conn.pool.xgroup_setid::<(), _, _, _>(
+ stream.tenant_aware_key(&self.redis_conn),
+ group,
+ &id_str,
+ ),
)
.await
.change_context(errors::RedisError::ConsumerGroupSetIdFailed)?;
@@ -2053,9 +2228,11 @@ impl super::RedisConnectionPool {
{
let fred_ids: MultipleIDs = ids.into();
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::ConsumerGroupSetMessageOwner,
- self.pool.xclaim(
- stream.tenant_aware_key(self),
+ self.redis_conn.pool.xclaim(
+ stream.tenant_aware_key(&self.redis_conn),
group,
consumer,
min_idle_time,
@@ -2109,8 +2286,10 @@ impl super::RedisConnectionPool {
T: serde::de::DeserializeOwned + FromRedis,
{
let val: T = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::EvaluateRedisScript,
- self.pool.eval(lua_script, key, values),
+ self.redis_conn.pool.eval(lua_script, key, values),
)
.await
.change_context(errors::RedisError::IncrementHashFieldFailed)?;
@@ -2183,8 +2362,8 @@ impl super::RedisConnectionPool {
V: TryInto<RedisValue> + Debug + FromRedis + Send + Sync + serde::de::DeserializeOwned,
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
- let redis_key = key.tenant_aware_key(self);
- let ttl_seconds = ttl.unwrap_or(self.config.default_ttl.into());
+ let redis_key = key.tenant_aware_key(&self.redis_conn);
+ let ttl_seconds = ttl.unwrap_or(self.redis_conn.config.default_ttl.into());
// Get a client from the pool and start transaction
let trx = self.get_transaction();
@@ -2208,11 +2387,15 @@ impl super::RedisConnectionPool {
.attach_printable("Failed to queue get command")?;
// Execute transaction
- let mut results: Vec<RedisValue> =
- track_redis_call(RedisOperation::SetKeyIfNotExistsAndGetValue, trx.exec(true))
- .await
- .change_context(errors::RedisError::SetFailed)
- .attach_printable("Failed to execute the redis transaction")?;
+ let mut results: Vec<RedisValue> = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
+ RedisOperation::SetKeyIfNotExistsAndGetValue,
+ trx.exec(true),
+ )
+ .await
+ .change_context(errors::RedisError::SetFailed)
+ .attach_printable("Failed to execute the redis transaction")?;
let msg = "Got unexpected number of results from transaction";
let get_result = results
diff --git a/crates/redis_interface/src/module/redis_rs.rs b/crates/redis_interface/src/module/redis_rs.rs
index dc1a2f7ecb..e3fde9e2aa 100644
--- a/crates/redis_interface/src/module/redis_rs.rs
+++ b/crates/redis_interface/src/module/redis_rs.rs
@@ -8,7 +8,11 @@ pub mod types;
use std::sync::{atomic, Arc};
-use common_utils::errors::CustomResult;
+use common_utils::{
+ errors::CustomResult,
+ external_service::{ExternalServiceEventEmitter, NoOpEventEmitter},
+ request_context::RequestContext,
+};
use error_stack::ResultExt;
use redis::AsyncCommands;
use tracing::Instrument;
@@ -357,12 +361,47 @@ pub struct RedisConnectionPool {
pub subscriber: Arc<SubscriberClient>,
pub publisher: Arc<PublisherClient>,
pub is_redis_available: Arc<atomic::AtomicBool>,
+ pub event_emitter: Arc<dyn ExternalServiceEventEmitter>,
+}
+
+/// A request-scoped Redis handle.
+///
+/// Wraps the shared [`RedisConnectionPool`] and carries the request ID of the
+/// execution that created it, so per-roundtrip events can be correlated back to
+/// the originating API request.
+#[derive(Clone)]
+pub struct RedisConnectionWithContext {
+ pub redis_conn: Arc<RedisConnectionPool>,
+ pub request_id: Option<String>,
+}
+
+impl RedisConnectionWithContext {
+ pub fn new(pool: Arc<RedisConnectionPool>, context: &dyn RequestContext) -> Self {
+ Self {
+ redis_conn: pool,
+ request_id: context.request_id().map(str::to_owned),
+ }
+ }
+
+ pub fn new_without_context(pool: Arc<RedisConnectionPool>) -> Self {
+ Self {
+ redis_conn: pool,
+ request_id: None,
+ }
+ }
}
impl RedisConnectionPool {
/// Create a new Redis connection
+ pub async fn new_without_event_emitter(
+ conf: &crate::types::RedisSettings,
+ ) -> CustomResult<Self, crate::errors::RedisError> {
+ Self::new(conf, Arc::new(NoOpEventEmitter)).await
+ }
+
pub async fn new(
conf: &crate::types::RedisSettings,
+ event_emitter: Arc<dyn ExternalServiceEventEmitter>,
) -> CustomResult<Self, crate::errors::RedisError> {
let (pool, subscriber, publisher) = match conf.cluster_enabled {
true => {
@@ -488,6 +527,7 @@ impl RedisConnectionPool {
subscriber,
publisher,
key_prefix: String::default(),
+ event_emitter,
})
}
@@ -499,7 +539,22 @@ impl RedisConnectionPool {
subscriber: Arc::clone(&self.subscriber),
publisher: Arc::clone(&self.publisher),
is_redis_available: Arc::clone(&self.is_redis_available),
+ event_emitter: Arc::clone(&self.event_emitter),
+ }
+ }
+
+ /// Prefix `key` with this pool's tenant key prefix.
+ pub fn add_prefix(&self, key: &str) -> String {
+ let physical = if self.key_prefix.is_empty() {
+ key.to_string()
+ } else {
+ format!("{}:{}", self.key_prefix, key)
+ };
+ #[cfg(feature = "deja")]
+ if let Some(corr) = deja::replay_key_namespace() {
+ return format!("{corr}:{physical}");
}
+ physical
}
/// Monitor for connection errors.
diff --git a/crates/redis_interface/src/module/redis_rs/commands.rs b/crates/redis_interface/src/module/redis_rs/commands.rs
index b64f81052b..0653b07e2e 100644
--- a/crates/redis_interface/src/module/redis_rs/commands.rs
+++ b/crates/redis_interface/src/module/redis_rs/commands.rs
@@ -198,18 +198,10 @@ impl DejaRedisValue {
}
}
-impl super::RedisConnectionPool {
+impl super::RedisConnectionWithContext {
+ /// Prefix `key` with the tenant key prefix of the underlying pool.
pub fn add_prefix(&self, key: &str) -> String {
- let physical = if self.key_prefix.is_empty() {
- key.to_string()
- } else {
- format!("{}:{}", self.key_prefix, key)
- };
- #[cfg(feature = "deja")]
- if let Some(corr) = deja::replay_key_namespace() {
- return format!("{corr}:{physical}");
- }
- physical
+ self.redis_conn.add_prefix(key)
}
// ─── Key Commands ────────────────────────────────────────────────────────
@@ -233,12 +225,14 @@ impl super::RedisConnectionPool {
where
V: redis::ToRedisArgs + Debug + Send + Sync + ToSingleRedisArg,
{
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
let options = SetOptions::default()
- .with_expiration(SetExpiry::EX(u64::from(self.config.default_ttl)));
+ .with_expiration(SetExpiry::EX(u64::from(self.redis_conn.config.default_ttl)));
let _: Option<String> = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetKey,
- conn.set_options(key.tenant_aware_key(self), value, options),
+ conn.set_options(key.tenant_aware_key(&self.redis_conn), value, options),
)
.await
.change_context(errors::RedisError::SetFailed)?;
@@ -266,11 +260,13 @@ impl super::RedisConnectionPool {
where
V: redis::ToRedisArgs + Debug + Send + Sync + ToSingleRedisArg,
{
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
let options = SetOptions::default().with_expiration(SetExpiry::KEEPTTL);
let _: Option<String> = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetKeyWithoutModifyingTtl,
- conn.set_options(key.tenant_aware_key(self), value, options),
+ conn.set_options(key.tenant_aware_key(&self.redis_conn), value, options),
)
.await
.change_context(errors::RedisError::SetFailed)?;
@@ -285,8 +281,10 @@ impl super::RedisConnectionPool {
K: redis::ToRedisArgs + Debug + Send + Sync,
V: redis::ToRedisArgs + Debug + Send + Sync,
{
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetMultipleKeysIfNotExist,
conn.mset_nx(key_value_pairs),
)
@@ -366,13 +364,19 @@ impl super::RedisConnectionPool {
#[cfg(not(feature = "deja"))]
{
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
let options = SetOptions::default().with_expiration(SetExpiry::EX(
u64::try_from(seconds).change_context(errors::RedisError::SetExFailed)?,
));
let _: Option<String> = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SerializeAndSetKeyWithExpiry,
- conn.set_options(key.tenant_aware_key(self), serialized.as_slice(), options),
+ conn.set_options(
+ key.tenant_aware_key(&self.redis_conn),
+ serialized.as_slice(),
+ options,
+ ),
)
.await
.change_context(errors::RedisError::SetExFailed)?;
@@ -385,7 +389,7 @@ impl super::RedisConnectionPool {
#[deja::redis(
operation = "get_key",
codec = deja::codec::ResultCodec::<DejaRedisValue, errors::RedisError>,
- state_read = key.tenant_aware_key(self),
+ state_read = key.tenant_aware_key(&self.redis_conn),
args = {
serde_json::json!({
"key": key.as_str(),
@@ -397,10 +401,12 @@ impl super::RedisConnectionPool {
&self,
key: &RedisKey,
) -> CustomResult<DejaRedisValue, errors::RedisError> {
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
match track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetKey,
- conn.get::<_, redis::Value>(key.tenant_aware_key(self)),
+ conn.get::<_, redis::Value>(key.tenant_aware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetFailed)
@@ -415,8 +421,10 @@ impl super::RedisConnectionPool {
#[cfg(feature = "multitenancy_fallback")]
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetKey,
- conn.get::<_, redis::Value>(key.tenant_unaware_key(self)),
+ conn.get::<_, redis::Value>(key.tenant_unaware_key(&self.redis_conn)),
)
.await
.map(DejaRedisValue::from)
@@ -444,10 +452,12 @@ impl super::RedisConnectionPool {
#[cfg(not(feature = "deja"))]
{
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
match track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetKey,
- conn.get::<_, V>(key.tenant_aware_key(self)),
+ conn.get::<_, V>(key.tenant_aware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetFailed)
@@ -462,8 +472,10 @@ impl super::RedisConnectionPool {
#[cfg(feature = "multitenancy_fallback")]
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetKey,
- conn.get::<_, V>(key.tenant_unaware_key(self)),
+ conn.get::<_, V>(key.tenant_unaware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetFailed)
@@ -485,10 +497,14 @@ impl super::RedisConnectionPool {
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();
+ let tenant_aware_keys: Vec<String> = keys
+ .iter()
+ .map(|key| key.tenant_aware_key(&self.redis_conn))
+ .collect();
+ let mut conn = self.redis_conn.pool.clone();
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetMultipleKeys,
conn.mget(&tenant_aware_keys),
)
@@ -507,17 +523,24 @@ impl super::RedisConnectionPool {
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 {
- track_redis_call(RedisOperation::GetKey, conn.get::<_, Option<V>>(&key)).await
- }
- });
+ let tenant_aware_keys: Vec<String> = keys
+ .iter()
+ .map(|key| key.tenant_aware_key(&self.redis_conn))
+ .collect();
+
+ let futures = tenant_aware_keys.iter().map(|redis_key| {
+ let mut conn = self.redis_conn.pool.clone();
+ let key = redis_key.clone();
+ async move {
+ track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
+ RedisOperation::GetKey,
+ conn.get::<_, Option<V>>(&key),
+ )
+ .await
+ }
+ });
let results = futures::future::try_join_all(futures)
.await
@@ -536,7 +559,7 @@ impl super::RedisConnectionPool {
where
V: FromRedisValue + Send + 'static,
{
- if self.config.cluster_enabled {
+ if self.redis_conn.config.cluster_enabled {
// Use individual GET commands for cluster mode to avoid CROSSSLOT errors
self.get_multiple_keys_with_parallel_get(keys).await
} else {
@@ -549,7 +572,7 @@ impl super::RedisConnectionPool {
feature = "deja",
deja::redis(
operation = "get_multiple_keys",
- read_set = keys.iter().map(|key| key.tenant_aware_key(self)).collect::<Vec<_>>(),
+ read_set = keys.iter().map(|key| key.tenant_aware_key(&self.redis_conn)).collect::<Vec<_>>(),
args = {
serde_json::json!({
"key_count": keys.len(),
@@ -592,7 +615,7 @@ impl super::RedisConnectionPool {
{
let tenant_unaware_keys: Vec<RedisKey> = keys
.iter()
- .map(|key| key.tenant_unaware_key(self).into())
+ .map(|key| key.tenant_unaware_key(&self.redis_conn).into())
.collect();
self.get_keys_by_mode(&tenant_unaware_keys).await
@@ -606,10 +629,12 @@ impl super::RedisConnectionPool {
where
V: Send + 'static,
{
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
match track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::Exists,
- conn.exists::<_, bool>(key.tenant_aware_key(self)),
+ conn.exists::<_, bool>(key.tenant_aware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetFailed)
@@ -624,8 +649,10 @@ impl super::RedisConnectionPool {
#[cfg(feature = "multitenancy_fallback")]
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::Exists,
- conn.exists::<_, bool>(key.tenant_unaware_key(self)),
+ conn.exists::<_, bool>(key.tenant_unaware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetFailed)
@@ -696,12 +723,14 @@ impl super::RedisConnectionPool {
)]
#[instrument(level = "DEBUG", skip(self))]
pub async fn delete_key(&self, key: &RedisKey) -> CustomResult<DelReply, errors::RedisError> {
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.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 = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::DeleteKey,
- conn.del(key.tenant_aware_key(self)),
+ conn.del(key.tenant_aware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::DeleteFailed)?;
@@ -721,8 +750,10 @@ impl super::RedisConnectionPool {
#[cfg(feature = "multitenancy_fallback")]
{
let fallback_count: usize = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::DeleteKey,
- conn.del(key.tenant_unaware_key(self)),
+ conn.del(key.tenant_unaware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::DeleteFailed)?;
@@ -775,13 +806,15 @@ impl super::RedisConnectionPool {
where
V: redis::ToRedisArgs + Debug + Send + Sync + ToSingleRedisArg,
{
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
let options = SetOptions::default().with_expiration(SetExpiry::EX(
u64::try_from(seconds).change_context(errors::RedisError::SetExFailed)?,
));
let _: Option<String> = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetKeyWithExpiry,
- conn.set_options(key.tenant_aware_key(self), value, options),
+ conn.set_options(key.tenant_aware_key(&self.redis_conn), value, options),
)
.await
.change_context(errors::RedisError::SetExFailed)?;
@@ -793,7 +826,7 @@ impl super::RedisConnectionPool {
deja::redis(
operation = "set_key_if_not_exists_with_expiry",
codec = deja::codec::ResultCodec::<SetnxReply, errors::RedisError>,
- state_write = key.tenant_aware_key(self),
+ state_write = key.tenant_aware_key(&self.redis_conn),
args = {
serde_json::json!({
"key": key.as_str(),
@@ -813,16 +846,18 @@ impl super::RedisConnectionPool {
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 ttl = seconds.unwrap_or(self.redis_conn.config.default_ttl.into());
+ let mut conn = self.redis_conn.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> = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetKeyIfNotExistsWithExpiry,
- conn.set_options(key.tenant_aware_key(self), value, options),
+ conn.set_options(key.tenant_aware_key(&self.redis_conn), value, options),
)
.await
.change_context(errors::RedisError::SetFailed)?;
@@ -842,10 +877,12 @@ impl super::RedisConnectionPool {
key: &RedisKey,
seconds: i64,
) -> CustomResult<(), errors::RedisError> {
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetExpiry,
- conn.expire::<_, ()>(key.tenant_aware_key(self), seconds),
+ conn.expire::<_, ()>(key.tenant_aware_key(&self.redis_conn), seconds),
)
.await
.change_context(errors::RedisError::SetExpiryFailed)
@@ -857,10 +894,12 @@ impl super::RedisConnectionPool {
key: &RedisKey,
timestamp: i64,
) -> CustomResult<(), errors::RedisError> {
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetExpireAt,
- conn.expire_at::<_, ()>(key.tenant_aware_key(self), timestamp),
+ conn.expire_at::<_, ()>(key.tenant_aware_key(&self.redis_conn), timestamp),
)
.await
.change_context(errors::RedisError::SetExpiryFailed)
@@ -868,10 +907,12 @@ impl super::RedisConnectionPool {
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_ttl(&self, key: &RedisKey) -> CustomResult<i64, errors::RedisError> {
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetTtl,
- conn.ttl::<_, i64>(key.tenant_aware_key(self)),
+ conn.ttl::<_, i64>(key.tenant_aware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetFailed)
@@ -890,20 +931,24 @@ impl super::RedisConnectionPool {
F: redis::ToRedisArgs + Debug + Send + Sync,
V: redis::ToRedisArgs + Debug + Send + Sync,
{
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
let _: () = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetHashFields,
- conn.hset_multiple(key.tenant_aware_key(self), &field_value_pairs),
+ conn.hset_multiple(key.tenant_aware_key(&self.redis_conn), &field_value_pairs),
)
.await
.change_context(errors::RedisError::SetHashFailed)?;
// setting expiry for the key — reuse the same connection
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetHashFields,
conn.expire::<_, ()>(
- key.tenant_aware_key(self),
- ttl.unwrap_or(self.config.default_hash_ttl.into()),
+ key.tenant_aware_key(&self.redis_conn),
+ ttl.unwrap_or(self.redis_conn.config.default_hash_ttl.into()),
),
)
.await
@@ -921,18 +966,28 @@ impl super::RedisConnectionPool {
where
V: redis::ToRedisArgs + ToSingleRedisArg + Debug + Send + Sync,
{
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
let result: HsetnxReply = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetHashFieldIfNotExist,
- conn.hset_nx::<_, _, _, HsetnxReply>(key.tenant_aware_key(self), field, value),
+ conn.hset_nx::<_, _, _, HsetnxReply>(
+ key.tenant_aware_key(&self.redis_conn),
+ field,
+ value,
+ ),
)
.await
.change_context(errors::RedisError::SetHashFieldFailed)?;
// Only set expiry if the field was actually set
if matches!(result, HsetnxReply::KeySet) {
- self.set_expiry(key, ttl.unwrap_or(self.config.default_hash_ttl).into())
- .await?;
+ self.set_expiry(
+ key,
+ ttl.unwrap_or(self.redis_conn.config.default_hash_ttl)
+ .into(),
+ )
+ .await?;
}
Ok(result)
@@ -986,14 +1041,16 @@ impl super::RedisConnectionPool {
where
T: Debug + ToString,
{
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.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(
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::IncrementFieldsInHash,
conn.hincr::<_, _, _, usize>(
- key.tenant_aware_key(self),
+ key.tenant_aware_key(&self.redis_conn),
field.to_string(),
*increment,
),
@@ -1016,7 +1073,7 @@ impl super::RedisConnectionPool {
pattern: &str,
count: Option<u32>,
) -> CustomResult<Vec<String>, errors::RedisError> {
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
let mut results: Vec<String> = Vec::new();
let mut cursor: u64 = 0;
@@ -1033,7 +1090,7 @@ impl super::RedisConnectionPool {
// 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(key.tenant_aware_key(&self.redis_conn))
.arg(cursor)
.arg(REDIS_ARG_MATCH)
.arg(pattern);
@@ -1043,10 +1100,14 @@ impl super::RedisConnectionPool {
}
// HSCAN returns: [cursor, [field1, value1, field2, value2, ...]]
- let reply: (u64, Vec<redis::Value>) =
- track_redis_call(RedisOperation::Hscan, command.query_async(&mut conn))
- .await
- .change_context(errors::RedisError::GetHashFieldFailed)?;
+ let reply: (u64, Vec<redis::Value>) = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
+ RedisOperation::Hscan,
+ command.query_async(&mut conn),
+ )
+ .await
+ .change_context(errors::RedisError::GetHashFieldFailed)?;
cursor = reply.0;
@@ -1076,7 +1137,7 @@ impl super::RedisConnectionPool {
count: Option<u32>,
scan_type: Option<crate::types::RedisScanType>,
) -> CustomResult<Vec<String>, errors::RedisError> {
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
let mut results: Vec<String> = Vec::new();
let mut cursor: u64 = 0;
@@ -1094,7 +1155,7 @@ impl super::RedisConnectionPool {
command
.arg(cursor)
.arg(REDIS_ARG_MATCH)
- .arg(pattern.tenant_aware_key(self));
+ .arg(pattern.tenant_aware_key(&self.redis_conn));
if let Some(count_value) = count {
command.arg(REDIS_ARG_COUNT).arg(count_value);
@@ -1104,10 +1165,14 @@ impl super::RedisConnectionPool {
command.arg(REDIS_ARG_TYPE).arg(scan_type_value.as_ref());
}
- let reply: (u64, Vec<String>) =
- track_redis_call(RedisOperation::Scan, command.query_async(&mut conn))
- .await
- .change_context(errors::RedisError::GetFailed)?;
+ let reply: (u64, Vec<String>) = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
+ RedisOperation::Scan,
+ command.query_async(&mut conn),
+ )
+ .await
+ .change_context(errors::RedisError::GetFailed)?;
cursor = reply.0;
results.extend(reply.1);
@@ -1149,10 +1214,12 @@ impl super::RedisConnectionPool {
where
V: FromRedisValue + Send + 'static,
{
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
match track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetHashField,
- conn.hget::<_, _, V>(key.tenant_aware_key(self), field),
+ conn.hget::<_, _, V>(key.tenant_aware_key(&self.redis_conn), field),
)
.await
.change_context(errors::RedisError::GetHashFieldFailed)
@@ -1162,8 +1229,10 @@ impl super::RedisConnectionPool {
#[cfg(feature = "multitenancy_fallback")]
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetHashField,
- conn.hget::<_, _, V>(key.tenant_unaware_key(self), field),
+ conn.hget::<_, _, V>(key.tenant_unaware_key(&self.redis_conn), field),
)
.await
.change_context(errors::RedisError::GetHashFieldFailed)
@@ -1182,10 +1251,12 @@ impl super::RedisConnectionPool {
where
V: FromRedisValue + Send + 'static,
{
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
match track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetHashFields,
- conn.hgetall::<_, V>(key.tenant_aware_key(self)),
+ conn.hgetall::<_, V>(key.tenant_aware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetHashFieldFailed)
@@ -1195,8 +1266,10 @@ impl super::RedisConnectionPool {
#[cfg(feature = "multitenancy_fallback")]
{
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetHashFields,
- conn.hgetall::<_, V>(key.tenant_unaware_key(self)),
+ conn.hgetall::<_, V>(key.tenant_unaware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetHashFieldFailed)
@@ -1240,11 +1313,13 @@ impl super::RedisConnectionPool {
where
F: redis::ToRedisArgs + Debug + Send + Sync,
{
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
// HDEL returns the number of fields removed (missing fields are ignored, not an error).
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::DeleteHashFields,
- conn.hdel(key.tenant_aware_key(self), fields),
+ conn.hdel(key.tenant_aware_key(&self.redis_conn), fields),
)
.await
.change_context(errors::RedisError::DeleteHashFieldFailed)
@@ -1258,7 +1333,7 @@ impl super::RedisConnectionPool {
replay = Substitute,
operation = "sadd",
codec = deja::codec::ResultCodec::<SaddReply, errors::RedisError>,
- state_write = key.tenant_aware_key(self),
+ state_write = key.tenant_aware_key(&self.redis_conn),
args = {
serde_json::json!({
"key": key.as_str(),
@@ -1276,10 +1351,12 @@ impl super::RedisConnectionPool {
where
V: redis::ToRedisArgs + Debug + Send + Sync,
{
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::Sadd,
- conn.sadd::<_, _, SaddReply>(key.tenant_aware_key(self), members),
+ conn.sadd::<_, _, SaddReply>(key.tenant_aware_key(&self.redis_conn), members),
)
.await
.change_context(errors::RedisError::SetAddMembersFailed)
@@ -1303,11 +1380,13 @@ impl super::RedisConnectionPool {
.map(|(f, v)| (f.into(), v.into()))
.collect();
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
let _: Option<String> = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::StreamAppendEntry,
conn.xadd_map(
- stream.tenant_aware_key(self),
+ stream.tenant_aware_key(&self.redis_conn),
entry_id.to_stream_id(),
&pairs,
),
@@ -1323,10 +1402,12 @@ impl super::RedisConnectionPool {
stream: &RedisKey,
ids: Vec<String>,
) -> CustomResult<usize, errors::RedisError> {
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::StreamDeleteEntries,
- conn.xdel(stream.tenant_aware_key(self), &ids),
+ conn.xdel(stream.tenant_aware_key(&self.redis_conn), &ids),
)
.await
.change_context(errors::RedisError::StreamDeleteFailed)
@@ -1338,15 +1419,17 @@ impl super::RedisConnectionPool {
stream: &RedisKey,
config: StreamTrimConfig,
) -> CustomResult<usize, errors::RedisError> {
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
let options = config
.to_trim_options()
.change_context(errors::RedisError::StreamTrimFailed)?;
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::StreamTrimEntries,
- conn.xtrim_options(stream.tenant_aware_key(self), &options),
+ conn.xtrim_options(stream.tenant_aware_key(&self.redis_conn), &options),
)
.await
.change_context(errors::RedisError::StreamTrimFailed)
@@ -1359,10 +1442,12 @@ impl super::RedisConnectionPool {
group: &str,
ids: Vec<String>,
) -> CustomResult<usize, errors::RedisError> {
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::StreamAcknowledgeEntries,
- conn.xack(stream.tenant_aware_key(self), group, &ids),
+ conn.xack(stream.tenant_aware_key(&self.redis_conn), group, &ids),
)
.await
.change_context(errors::RedisError::StreamAcknowledgeFailed)
@@ -1373,10 +1458,12 @@ impl super::RedisConnectionPool {
&self,
stream: &RedisKey,
) -> CustomResult<usize, errors::RedisError> {
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::StreamGetLength,
- conn.xlen(stream.tenant_aware_key(self)),
+ conn.xlen(stream.tenant_aware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetLengthFailed)
@@ -1392,18 +1479,20 @@ impl super::RedisConnectionPool {
ids: Vec<String>,
read_count: Option<u64>,
) -> CustomResult<StreamReadResult, errors::RedisError> {
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
let stream_keys: Vec<String> = streams
.iter()
- .map(|stream| stream.tenant_aware_key(self))
+ .map(|stream| stream.tenant_aware_key(&self.redis_conn))
.collect();
- let count = read_count.unwrap_or(self.config.default_stream_read_count);
+ let count = read_count.unwrap_or(self.redis_conn.config.default_stream_read_count);
let options = StreamReadOptions::default()
.count(usize::try_from(count).change_context(errors::RedisError::StreamReadFailed)?);
let reply: redis::streams::StreamReadReply = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::StreamReadEntries,
conn.xread_options(&stream_keys, &ids, &options),
)
@@ -1457,10 +1546,10 @@ impl super::RedisConnectionPool {
block: Option<u64>,
group: Option<(&str, &str)>,
) -> CustomResult<StreamReadResult, errors::RedisError> {
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
let stream_keys: Vec<String> = streams
.iter()
- .map(|stream| stream.tenant_aware_key(self))
+ .map(|stream| stream.tenant_aware_key(&self.redis_conn))
.collect();
let mut options = StreamReadOptions::default();
@@ -1480,6 +1569,8 @@ impl super::RedisConnectionPool {
}
let reply: redis::streams::StreamReadReply = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::StreamReadWithOptions,
conn.xread_options(&stream_keys, &ids, &options),
)
@@ -1531,10 +1622,12 @@ impl super::RedisConnectionPool {
where
V: redis::ToRedisArgs + Debug + Send + Sync,
{
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::AppendElementsToList,
- conn.rpush::<_, _, ()>(key.tenant_aware_key(self), elements),
+ conn.rpush::<_, _, ()>(key.tenant_aware_key(&self.redis_conn), elements),
)
.await
.change_context(errors::RedisError::AppendElementsToListFailed)
@@ -1547,11 +1640,13 @@ impl super::RedisConnectionPool {
start: i64,
stop: i64,
) -> CustomResult<Vec<String>, errors::RedisError> {
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetListElements,
conn.lrange::<_, Vec<String>>(
- key.tenant_aware_key(self),
+ key.tenant_aware_key(&self.redis_conn),
isize::try_from(start).change_context(errors::RedisError::GetListElementsFailed)?,
isize::try_from(stop).change_context(errors::RedisError::GetListElementsFailed)?,
),
@@ -1562,10 +1657,12 @@ impl super::RedisConnectionPool {
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_list_length(&self, key: &RedisKey) -> CustomResult<usize, errors::RedisError> {
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::GetListLength,
- conn.llen::<_, usize>(key.tenant_aware_key(self)),
+ conn.llen::<_, usize>(key.tenant_aware_key(&self.redis_conn)),
)
.await
.change_context(errors::RedisError::GetListLengthFailed)
@@ -1577,11 +1674,13 @@ impl super::RedisConnectionPool {
key: &RedisKey,
count: Option<usize>,
) -> CustomResult<Vec<String>, errors::RedisError> {
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
let non_zero_count = count.and_then(std::num::NonZeroUsize::new);
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::LpopListElements,
- conn.lpop::<_, Vec<String>>(key.tenant_aware_key(self), non_zero_count),
+ conn.lpop::<_, Vec<String>>(key.tenant_aware_key(&self.redis_conn), non_zero_count),
)
.await
.change_context(errors::RedisError::PopListElementsFailed)
@@ -1603,10 +1702,16 @@ impl super::RedisConnectionPool {
Err(errors::RedisError::InvalidRedisEntryId)?;
}
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
let _: () = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::ConsumerGroupCreate,
- conn.xgroup_create_mkstream(stream.tenant_aware_key(self), group, id.to_stream_id()),
+ conn.xgroup_create_mkstream(
+ stream.tenant_aware_key(&self.redis_conn),
+ group,
+ id.to_stream_id(),
+ ),
)
.await
.change_context(errors::RedisError::ConsumerGroupCreateFailed)?;
@@ -1619,10 +1724,12 @@ impl super::RedisConnectionPool {
stream: &RedisKey,
group: &str,
) -> CustomResult<crate::types::ConsumerGroupDestroyReply, errors::RedisError> {
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
let reply: crate::types::ConsumerGroupDestroyReply = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::ConsumerGroupDestroy,
- conn.xgroup_destroy(stream.tenant_aware_key(self), group),
+ conn.xgroup_destroy(stream.tenant_aware_key(&self.redis_conn), group),
)
.await
.change_context(errors::RedisError::ConsumerGroupDestroyFailed)?;
@@ -1637,10 +1744,12 @@ impl super::RedisConnectionPool {
group: &str,
consumer: &str,
) -> CustomResult<usize, errors::RedisError> {
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::ConsumerGroupDeleteConsumer,
- conn.xgroup_delconsumer(stream.tenant_aware_key(self), group, consumer),
+ conn.xgroup_delconsumer(stream.tenant_aware_key(&self.redis_conn), group, consumer),
)
.await
.change_context(errors::RedisError::ConsumerGroupRemoveConsumerFailed)
@@ -1653,10 +1762,16 @@ impl super::RedisConnectionPool {
group: &str,
id: &RedisEntryId,
) -> CustomResult<String, errors::RedisError> {
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
let _: () = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::ConsumerGroupSetLastId,
- conn.xgroup_setid(stream.tenant_aware_key(self), group, id.to_stream_id()),
+ conn.xgroup_setid(
+ stream.tenant_aware_key(&self.redis_conn),
+ group,
+ id.to_stream_id(),
+ ),
)
.await
.change_context(errors::RedisError::ConsumerGroupSetIdFailed)?;
@@ -1675,11 +1790,13 @@ impl super::RedisConnectionPool {
where
R: FromRedisValue + Send + 'static,
{
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::ConsumerGroupSetMessageOwner,
conn.xclaim(
- stream.tenant_aware_key(self),
+ stream.tenant_aware_key(&self.redis_conn),
group,
consumer,
min_idle_time,
@@ -1703,7 +1820,7 @@ impl super::RedisConnectionPool {
V: redis::ToRedisArgs + Debug + Send + Sync,
T: serde::de::DeserializeOwned + FromRedisValue,
{
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
let script = redis::Script::new(lua_script);
let mut invocation = script.prepare_invoke();
@@ -1713,6 +1830,8 @@ impl super::RedisConnectionPool {
invocation.arg(values);
let val: T = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::EvaluateRedisScript,
invocation.invoke_async(&mut conn),
)
@@ -1761,10 +1880,10 @@ impl super::RedisConnectionPool {
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 redis_key = key.tenant_aware_key(&self.redis_conn);
+ let ttl_seconds = ttl.unwrap_or(self.redis_conn.config.default_ttl.into());
- let mut conn = self.pool.clone();
+ let mut conn = self.redis_conn.pool.clone();
// Build an atomic pipeline (MULTI/EXEC)
let mut pipe = redis::pipe();
@@ -1784,6 +1903,8 @@ impl super::RedisConnectionPool {
// 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> = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
RedisOperation::SetKeyIfNotExistsAndGetValue,
pipe.query_async(&mut conn),
)
diff --git a/crates/redis_interface/src/test.rs b/crates/redis_interface/src/test.rs
index ddb7ca41ba..7a342317be 100644
--- a/crates/redis_interface/src/test.rs
+++ b/crates/redis_interface/src/test.rs
@@ -15,12 +15,22 @@ use std::collections::HashMap;
use crate::{
ConsumerGroupDestroyReply, DelReply, HsetnxReply, MsetnxReply, RedisConnectionPool,
- RedisEntryId, RedisKey, RedisSettings, RedisValue, SaddReply, SetGetReply, SetnxReply,
- StreamCapKind, StreamCapTrim, StreamTrimConfig,
+ RedisConnectionWithContext, RedisEntryId, RedisKey, RedisSettings, RedisValue, SaddReply,
+ SetGetReply, SetnxReply, StreamCapKind, StreamCapTrim, StreamTrimConfig,
};
// ─── Helpers ──────────────────────────────────────────────────────────────────
+async fn test_connection(
+ settings: &RedisSettings,
+) -> error_stack::Result<RedisConnectionWithContext, crate::errors::RedisError> {
+ let pool = RedisConnectionPool::new_without_event_emitter(settings)
+ .await
+ .map(std::sync::Arc::new)?;
+
+ Ok(RedisConnectionWithContext::new_without_context(pool))
+}
+
/// Generate a unique ID for test key isolation.
/// Uses PID + nanoseconds + counter for global uniqueness across parallel runs.
fn unique_test_id() -> String {
@@ -43,7 +53,7 @@ fn redis_value_to_option_string(v: &RedisValue) -> Option<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> {
+async fn cluster_pool() -> Option<RedisConnectionWithContext> {
let cluster_urls_str = std::env::var("REDIS_CLUSTER_URLS").ok()?;
let cluster_urls: Vec<String> = cluster_urls_str
.split(',')
@@ -79,11 +89,11 @@ async fn cluster_pool() -> Option<RedisConnectionPool> {
..RedisSettings::default()
};
- RedisConnectionPool::new(&settings).await.ok()
+ test_connection(&settings).await.ok()
}
/// Helper: get a cluster pool or skip the test.
-async fn get_cluster_pool_or_skip() -> Option<RedisConnectionPool> {
+async fn get_cluster_pool_or_skip() -> Option<RedisConnectionWithContext> {
let pool = cluster_pool().await;
if pool.is_none() {
tracing::warn!(
@@ -94,7 +104,7 @@ async fn get_cluster_pool_or_skip() -> Option<RedisConnectionPool> {
pool
}
-async fn get_cluster_pool_with_uid() -> Option<(RedisConnectionPool, String)> {
+async fn get_cluster_pool_with_uid() -> Option<(RedisConnectionWithContext, String)> {
let pool = get_cluster_pool_or_skip().await?;
let unique_id = unique_test_id();
Some((pool, unique_id))
@@ -106,7 +116,7 @@ async fn get_cluster_pool_with_uid() -> Option<(RedisConnectionPool, String)> {
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())
+ let redis_conn = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
@@ -136,7 +146,7 @@ async fn test_consumer_group_create() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let _ = pool.set_key(&"key".into(), "value".to_string()).await;
@@ -153,7 +163,7 @@ async fn test_delete_existing_key_success() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
pool.delete_key(&"key not exists".into()).await.is_ok()
@@ -169,7 +179,7 @@ async fn test_delete_non_existing_key_success() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -195,7 +205,7 @@ async fn test_delete_key_returns_correct_reply() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -221,7 +231,7 @@ async fn test_delete_key_reply_semantics() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -255,7 +265,7 @@ async fn test_delete_multiple_keys() {
async fn test_exists_key() {
let is_success = tokio::task::spawn_blocking(move || {
futures::executor::block_on(async {
- let pool = RedisConnectionPool::new(&RedisSettings::default())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -280,7 +290,7 @@ async fn test_exists_key() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let key: RedisKey = format!("test_set_expiry_{}", unique_test_id()).into();
@@ -299,7 +309,7 @@ async fn test_set_key_with_expiry() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let key: RedisKey = format!("test_keepttl_{}", unique_test_id()).into();
@@ -323,7 +333,7 @@ async fn test_set_key_without_modifying_ttl() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let key: RedisKey = format!("test_setnx_new_{}", unique_test_id()).into();
@@ -346,7 +356,7 @@ async fn test_set_key_if_not_exists_with_expiry_new_key() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let key: RedisKey = format!("test_setnx_exist_{}", unique_test_id()).into();
@@ -371,7 +381,7 @@ async fn test_set_key_if_not_exists_with_expiry_existing_key() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let key: RedisKey = format!("test_new_key_string_{}", unique_test_id()).into();
@@ -397,7 +407,7 @@ async fn test_set_key_if_not_exists_and_get_value_new_key() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let key: RedisKey = format!("test_existing_key_string_{}", unique_test_id()).into();
@@ -426,7 +436,7 @@ async fn test_set_key_if_not_exists_and_get_value_existing_key() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let key: RedisKey = format!("test_default_ttl_key_string_{}", unique_test_id()).into();
@@ -452,21 +462,21 @@ async fn test_set_key_if_not_exists_and_get_value_with_default_ttl() {
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())
+ let pool = test_connection(&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 conn1 = pool.clone();
+ let conn2 = 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))
+ conn1.set_key_if_not_exists_and_get_value(&key1, value1, Some(30)),
+ conn2.set_key_if_not_exists_and_get_value(&key2, value2, Some(30))
);
let result1_is_set = matches!(result1, Ok(SetGetReply::ValueSet(_)));
@@ -487,7 +497,7 @@ async fn test_set_key_if_not_exists_and_get_value_concurrent_access() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let key: RedisKey = format!("test_resp3_{}", unique_test_id()).into();
@@ -515,7 +525,7 @@ async fn test_connection_with_custom_config() {
..RedisSettings::default()
};
- let pool = RedisConnectionPool::new(&settings)
+ let pool = test_connection(&settings)
.await
.expect("failed to create redis connection pool with custom config");
@@ -538,7 +548,7 @@ async fn test_connection_with_custom_config() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
@@ -576,7 +586,7 @@ async fn test_get_multiple_keys_success() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
@@ -624,7 +634,7 @@ async fn test_get_multiple_keys_with_missing_keys() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
@@ -647,7 +657,7 @@ async fn test_get_multiple_keys_empty_input() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -678,7 +688,7 @@ async fn test_get_and_deserialize_key() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let key: RedisKey = "nonexistent_deser_key".into();
@@ -697,7 +707,7 @@ async fn test_get_and_deserialize_key_not_found() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
@@ -757,7 +767,7 @@ async fn test_get_and_deserialize_multiple_keys() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -794,7 +804,7 @@ async fn test_serialize_and_set_key_if_not_exist() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -831,7 +841,7 @@ async fn test_serialize_and_set_key_with_expiry() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -870,7 +880,7 @@ async fn test_serialize_and_set_key_without_modifying_ttl() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -897,7 +907,7 @@ async fn test_set_expiry_and_get_ttl() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -934,7 +944,7 @@ async fn test_set_expire_at_and_get_ttl() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let key: RedisKey = format!("test_hash_{}", unique_test_id()).into();
@@ -957,7 +967,7 @@ async fn test_set_hash_fields() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -993,7 +1003,7 @@ async fn test_set_hash_field_if_not_exist_and_get() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -1022,7 +1032,7 @@ async fn test_increment_fields_in_hash() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -1057,7 +1067,7 @@ async fn test_hscan_returns_values() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -1094,7 +1104,7 @@ async fn test_hscan_and_deserialize() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -1137,7 +1147,7 @@ async fn test_sadd_and_get_hash_field_and_deserialize() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -1179,7 +1189,7 @@ async fn test_serialize_and_set_multiple_hash_field_if_not_exist() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -1188,8 +1198,8 @@ async fn test_set_multiple_keys_if_not_exist_msetnx() {
let result = pool
.set_multiple_keys_if_not_exist(&[
- (key1.tenant_aware_key(&pool), "val1"),
- (key2.tenant_aware_key(&pool), "val2"),
+ (key1.tenant_aware_key(&pool.redis_conn), "val1"),
+ (key2.tenant_aware_key(&pool.redis_conn), "val2"),
])
.await;
@@ -1206,7 +1216,7 @@ async fn test_set_multiple_keys_if_not_exist_msetnx() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -1217,8 +1227,8 @@ async fn test_set_multiple_keys_if_not_exist_with_existing_key() {
let result = pool
.set_multiple_keys_if_not_exist(&[
- (key1.tenant_aware_key(&pool), "new1"),
- (key2.tenant_aware_key(&pool), "new2"),
+ (key1.tenant_aware_key(&pool.redis_conn), "new1"),
+ (key2.tenant_aware_key(&pool.redis_conn), "new2"),
])
.await;
@@ -1235,7 +1245,7 @@ async fn test_set_multiple_keys_if_not_exist_with_existing_key() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -1271,7 +1281,7 @@ async fn test_set_multiple_keys_if_not_exists_and_get_values() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let stream: RedisKey = format!("test_stream_append_{}", unique_test_id()).into();
@@ -1296,7 +1306,7 @@ async fn test_stream_append_and_get_length() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -1339,7 +1349,7 @@ async fn test_stream_read_entries_xread() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -1380,7 +1390,7 @@ async fn test_stream_read_entries() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -1441,7 +1451,7 @@ async fn test_stream_read_with_options_xreadgroup() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let stream: RedisKey = format!("test_stream_ack_{}", unique_test_id()).into();
@@ -1479,7 +1489,7 @@ async fn test_stream_acknowledge_entries() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -1521,7 +1531,7 @@ async fn test_stream_delete_entries() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -1589,7 +1599,7 @@ async fn test_stream_trim_entries() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -1625,7 +1635,7 @@ async fn test_consumer_group_operations() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -1662,7 +1672,7 @@ async fn test_consumer_group_destroy() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -1712,7 +1722,7 @@ async fn test_consumer_group_delete_consumer() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -1760,7 +1770,7 @@ async fn test_consumer_group_set_last_id() {
async fn test_list_operations() {
let is_success = tokio::task::spawn_blocking(move || {
futures::executor::block_on(async {
- let pool = RedisConnectionPool::new(&RedisSettings::default())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -1795,7 +1805,7 @@ async fn test_list_operations() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let lua_script = r#"
@@ -1830,7 +1840,7 @@ async fn test_setting_keys_using_scripts() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
@@ -1870,7 +1880,7 @@ async fn test_getting_keys_using_scripts() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let uid = unique_test_id();
@@ -1909,22 +1919,24 @@ async fn test_scan_returns_matching_keys() {
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())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let channel = "test_pubsub_channel";
let test_message = "test_message_value";
- pool.subscriber
+ pool.redis_conn
+ .subscriber
.subscribe(channel)
.await
.expect("failed to subscribe");
- let mut receiver = pool.subscriber.message_rx();
+ let mut receiver = pool.redis_conn.subscriber.message_rx();
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
- pool.publisher
+ pool.redis_conn
+ .publisher
.publish(channel, RedisValue::from_string(test_message.to_string()))
.await
.expect("failed to publish");
@@ -1951,17 +1963,18 @@ async fn test_pubsub_standalone_publish_and_receive() {
async fn test_subscriber_unsubscribe() {
let is_success = tokio::task::spawn_blocking(move || {
futures::executor::block_on(async {
- let pool = RedisConnectionPool::new(&RedisSettings::default())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let channel = "test_unsub_channel";
- pool.subscriber
+ pool.redis_conn
+ .subscriber
.subscribe(channel)
.await
.expect("failed to subscribe");
- let unsub_result = pool.subscriber.unsubscribe(channel).await;
+ let unsub_result = pool.redis_conn.subscriber.unsubscribe(channel).await;
matches!(unsub_result, Ok(()))
})
@@ -1986,7 +1999,7 @@ async fn test_on_error_triggers_shutdown_when_redis_unreachable() {
..RedisSettings::default()
};
- let pool = RedisConnectionPool::new(&settings).await;
+ let pool = test_connection(&settings).await;
let pool = match pool {
Ok(pool) => pool,
Err(_) => return, // If connection fails entirely, skip
@@ -1995,7 +2008,7 @@ async fn test_on_error_triggers_shutdown_when_redis_unreachable() {
let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();
tokio::spawn(async move {
- pool.on_error(shutdown_tx).await;
+ pool.redis_conn.on_error(shutdown_tx).await;
});
let result = tokio::time::timeout(std::time::Duration::from_secs(10), shutdown_rx).await;
@@ -2008,11 +2021,12 @@ async fn test_on_error_triggers_shutdown_when_redis_unreachable() {
#[tokio::test]
async fn test_on_error_keeps_redis_available_when_healthy() {
- let pool = RedisConnectionPool::new(&RedisSettings::default())
+ let pool = test_connection(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let initial_state = pool
+ .redis_conn
.is_redis_available
.load(std::sync::atomic::Ordering::SeqCst);
@@ -2039,17 +2053,17 @@ async fn test_on_error_marks_unavailable_after_threshold() {
..RedisSettings::default()
};
- let pool = RedisConnectionPool::new(&settings).await;
+ let pool = test_connection(&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();
+ let is_available = pool.redis_conn.is_redis_available.clone();
tokio::spawn(async move {
- pool.on_error(shutdown_tx).await;
+ pool.redis_conn.on_error(shutdown_tx).await;
});
let result = tokio::time::timeout(std::time::Duration::from_secs(10), shutdown_rx).await;
@@ -2285,16 +2299,18 @@ async fn test_cluster_pubsub() {
let channel = format!("test_cluster_pubsub_{uid}");
let test_message = "cluster_message";
- pool.subscriber
+ pool.redis_conn
+ .subscriber
.subscribe(&channel)
.await
.expect("failed to subscribe on cluster");
- let mut receiver = pool.subscriber.message_rx();
+ let mut receiver = pool.redis_conn.subscriber.message_rx();
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
- pool.publisher
+ pool.redis_conn
+ .publisher
.publish(&channel, RedisValue::from_string(test_message.to_string()))
.await
.expect("failed to publish on cluster");
diff --git a/crates/router/src/connection.rs b/crates/router/src/connection.rs
index b3e095260f..8b4c7890ae 100644
--- a/crates/router/src/connection.rs
+++ b/crates/router/src/connection.rs
@@ -9,19 +9,6 @@ pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>;
pub type PgPooledConn = async_bb8_diesel::Connection<PgConnection>;
-/// Creates a Redis connection pool for the specified Redis settings
-/// # Panics
-///
-/// Panics if failed to create a redis pool
-#[allow(clippy::expect_used)]
-pub async fn redis_connection(
- conf: &crate::configs::Settings,
-) -> redis_interface::RedisConnectionPool {
- redis_interface::RedisConnectionPool::new(&conf.redis)
- .await
- .expect("Failed to create Redis Connection Pool")
-}
-
// Deja replay (R1): the minimal replay DB routing hook. On a just-leased pg
// connection during replay, route it to the active correlation's schema so
// per-test-case reads/writes stay isolated. The correlation is read from the
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index f12a7608f5..3833347562 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -191,6 +191,7 @@ pub trait GlobalStorageInterface:
+ user_key_store::UserKeyStoreInterface
+ role::RoleInterface
+ RedisConnInterface
+ + RequestIdStore
+ 'static
{
fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static>;
@@ -349,6 +350,10 @@ impl RequestIdStore for Store {
self.router_store.request_id = Some(request_id.clone());
}
self.request_id = Some(request_id.clone());
+ #[cfg(feature = "kv_store")]
+ {
+ self.router_store.request_id = Some(request_id.clone());
+ }
self.update_key_manager_request_id(request_id);
}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index cb8163249e..65e5690904 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1,4 +1,4 @@
-use std::{collections::HashSet, sync::Arc};
+use std::collections::HashSet;
use ::payment_methods::state::PaymentMethodsStorageInterface;
use common_enums::enums::MerchantStorageScheme;
@@ -39,7 +39,7 @@ use hyperswitch_domain_models::{
#[cfg(not(feature = "payouts"))]
use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};
use hyperswitch_masking::Secret;
-use redis_interface::{errors::RedisError, RedisConnectionPool, RedisEntryId};
+use redis_interface::{errors::RedisError, RedisEntryId};
use router_env::{instrument, logger, tracing};
use scheduler::{
db::{process_tracker::ProcessTrackerInterface, queue::QueueInterface},
@@ -3735,7 +3735,9 @@ impl UserInterface for KafkaStore {
}
impl RedisConnInterface for KafkaStore {
- fn get_redis_conn(&self) -> CustomResult<Arc<RedisConnectionPool>, RedisError> {
+ fn get_redis_conn(
+ &self,
+ ) -> CustomResult<redis_interface::RedisConnectionWithContext, RedisError> {
self.diesel_store.get_redis_conn()
}
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 86a378937d..f4bfe7c821 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -157,10 +157,10 @@ impl scheduler::SchedulerSessionState for SessionState {
fn add_request_id(&mut self, request_id: RequestId) {
self.api_client.add_request_id(request_id.clone());
self.store.add_request_id(request_id.to_string());
+ self.global_store.add_request_id(request_id.to_string());
#[cfg(feature = "deja")]
{
self.accounts_store.add_request_id(request_id.to_string());
- self.global_store.add_request_id(request_id.to_string());
}
self.request_id.replace(request_id);
}
@@ -252,10 +252,10 @@ impl SessionStateInfo for SessionState {
fn add_request_id(&mut self, request_id: RequestId) {
self.api_client.add_request_id(request_id.clone());
self.store.add_request_id(request_id.to_string());
+ self.global_store.add_request_id(request_id.to_string());
#[cfg(feature = "deja")]
{
self.accounts_store.add_request_id(request_id.to_string());
- self.global_store.add_request_id(request_id.to_string());
}
self.request_id.replace(request_id);
}
@@ -478,10 +478,22 @@ impl AppState {
.expect("Failed to initialize OpenSearch client.")
.map(Arc::new);
+ let redis_event_emitter: Arc<
+ dyn common_utils::external_service::ExternalServiceEventEmitter,
+ > = if conf.events.emit_external_service_call_events {
+ Arc::new(event_handler.clone())
+ } else {
+ Arc::new(common_utils::external_service::NoOpEventEmitter)
+ };
#[allow(clippy::expect_used)]
- let cache_store = get_cache_store(&conf.clone(), shut_down_signal, testable)
- .await
- .expect("Failed to create store");
+ let cache_store = get_cache_store(
+ &conf.clone(),
+ shut_down_signal,
+ redis_event_emitter,
+ testable,
+ )
+ .await
+ .expect("Failed to create store");
let global_store: Box<dyn GlobalStorageInterface> =
Box::pin(Self::get_store_interface(
&storage_impl,
diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs
index 27ee0c26cd..dc494eefae 100644
--- a/crates/router/src/services.rs
+++ b/crates/router/src/services.rs
@@ -120,9 +120,10 @@ pub async fn get_store(
pub async fn get_cache_store(
config: &Settings,
shut_down_signal: oneshot::Sender<()>,
+ event_emitter: Arc<dyn common_utils::external_service::ExternalServiceEventEmitter>,
_test_transaction: bool,
) -> StorageResult<Arc<RedisStore>> {
- RouterStore::<StoreType>::cache_store(&config.redis, shut_down_signal).await
+ RouterStore::<StoreType>::cache_store(&config.redis, shut_down_signal, event_emitter).await
}
// deja: the per-merchant data-encryption key (DEK) is random. It is stored
diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs
index 055cdc1b54..68f1f756b9 100644
--- a/crates/router/src/services/authentication/blacklist.rs
+++ b/crates/router/src/services/authentication/blacklist.rs
@@ -1,9 +1,7 @@
-use std::sync::Arc;
-
#[cfg(feature = "olap")]
use common_utils::date_time;
use error_stack::ResultExt;
-use redis_interface::RedisConnectionPool;
+use redis_interface::RedisConnectionWithContext;
use super::AuthToken;
#[cfg(feature = "olap")]
@@ -130,7 +128,7 @@ pub async fn check_email_token_in_blacklist(state: &SessionState, token: &str) -
fn get_redis_connection_for_global_tenant<A: SessionStateInfo>(
state: &A,
-) -> RouterResult<Arc<RedisConnectionPool>> {
+) -> RouterResult<RedisConnectionWithContext> {
state
.global_store()
.get_redis_conn()
diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs
index f75bb497ef..2e68639c1b 100644
--- a/crates/router/src/services/authorization.rs
+++ b/crates/router/src/services/authorization.rs
@@ -1,8 +1,6 @@
-use std::sync::Arc;
-
use common_utils::id_type;
use error_stack::ResultExt;
-use redis_interface::RedisConnectionPool;
+use redis_interface::RedisConnectionWithContext;
use router_env::logger;
use super::authentication::AuthToken;
@@ -147,7 +145,7 @@ pub fn check_tenant(
fn get_redis_connection_for_global_tenant<A: SessionStateInfo>(
state: &A,
-) -> RouterResult<Arc<RedisConnectionPool>> {
+) -> RouterResult<RedisConnectionWithContext> {
state
.global_store()
.get_redis_conn()
diff --git a/crates/router/src/services/card_testing_guard.rs b/crates/router/src/services/card_testing_guard.rs
index 09c5dbd950..d3d39a690f 100644
--- a/crates/router/src/services/card_testing_guard.rs
+++ b/crates/router/src/services/card_testing_guard.rs
@@ -1,14 +1,14 @@
-use std::sync::Arc;
-
use error_stack::ResultExt;
-use redis_interface::RedisConnectionPool;
+use redis_interface::RedisConnectionWithContext;
use crate::{
core::errors::{ApiErrorResponse, RouterResult},
routes::app::SessionStateInfo,
};
-fn get_redis_connection<A: SessionStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> {
+fn get_redis_connection<A: SessionStateInfo>(
+ state: &A,
+) -> RouterResult<RedisConnectionWithContext> {
state
.store()
.get_redis_conn()
diff --git a/crates/router/src/services/openidconnect.rs b/crates/router/src/services/openidconnect.rs
index 447a97f62f..de8ebabbad 100644
--- a/crates/router/src/services/openidconnect.rs
+++ b/crates/router/src/services/openidconnect.rs
@@ -4,7 +4,7 @@ use external_services::http_client::client;
use hyperswitch_masking::{ExposeInterface, Secret};
use oidc::TokenResponse;
use openidconnect::{self as oidc, core as oidc_core};
-use redis_interface::RedisConnectionPool;
+use redis_interface::RedisConnectionWithContext;
use storage_impl::errors::ApiClientError;
use crate::{
@@ -198,7 +198,7 @@ fn get_oidc_redis_key(csrf: &str) -> String {
fn get_redis_connection_for_global_tenant(
state: &SessionState,
-) -> UserResult<std::sync::Arc<RedisConnectionPool>> {
+) -> UserResult<RedisConnectionWithContext> {
state
.global_store
.get_redis_conn()
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index ac2023b658..a17506dab0 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -1,5 +1,3 @@
-use std::sync::Arc;
-
#[cfg(feature = "v1")]
use api_models::admin as admin_api;
use api_models::user as user_api;
@@ -17,7 +15,7 @@ use error_stack::ResultExt;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount as DomainMerchantConnectorAccount;
use hyperswitch_masking::{ExposeInterface, Secret};
-use redis_interface::RedisConnectionPool;
+use redis_interface::RedisConnectionWithContext;
use router_env::{env, instrument, logger, tracing};
use crate::{
@@ -144,7 +142,7 @@ pub async fn get_active_user_from_db_by_email(
pub fn get_redis_connection_for_global_tenant(
state: &SessionState,
-) -> UserResult<Arc<RedisConnectionPool>> {
+) -> UserResult<RedisConnectionWithContext> {
state
.global_store
.get_redis_conn()
diff --git a/crates/router/tests/services.rs b/crates/router/tests/services.rs
index b30a143bb9..427df99fa3 100644
--- a/crates/router/tests/services.rs
+++ b/crates/router/tests/services.rs
@@ -26,7 +26,8 @@ async fn get_redis_conn_failure() {
.unwrap();
let _ = state.store.get_redis_conn().map(|conn| {
- conn.is_redis_available
+ conn.redis_conn
+ .is_redis_available
.store(false, atomic::Ordering::SeqCst)
});
diff --git a/crates/scheduler/src/consumer.rs b/crates/scheduler/src/consumer.rs
index 97d7ea3f70..9da2102bf8 100644
--- a/crates/scheduler/src/consumer.rs
+++ b/crates/scheduler/src/consumer.rs
@@ -12,7 +12,7 @@ use diesel_models::enums;
pub use diesel_models::{self, process_tracker as storage};
use error_stack::ResultExt;
use futures::future;
-use redis_interface::{RedisConnectionPool, RedisEntryId};
+use redis_interface::{RedisConnectionWithContext, RedisEntryId};
use router_env::{
instrument,
tracing::{self, Instrument},
@@ -184,7 +184,7 @@ pub async fn consumer_operations<T: SchedulerSessionState + 'static>(
#[instrument(skip(db, redis_conn))]
pub async fn fetch_consumer_tasks(
db: &dyn ProcessTrackerInterface,
- redis_conn: &RedisConnectionPool,
+ redis_conn: &RedisConnectionWithContext,
stream_name: &str,
group_name: &str,
consumer_name: &str,
diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rs
index 10d1633124..ef867a6eff 100644
--- a/crates/scheduler/src/utils.rs
+++ b/crates/scheduler/src/utils.rs
@@ -4,7 +4,7 @@ use common_utils::errors::CustomResult;
use diesel_models::enums::{self, ProcessTrackerStatus};
pub use diesel_models::process_tracker as storage;
use error_stack::{report, ResultExt};
-use redis_interface::{RedisConnectionPool, RedisEntryId};
+use redis_interface::{RedisConnectionWithContext, RedisEntryId};
use router_env::{instrument, tracing};
use uuid::Uuid;
@@ -193,7 +193,7 @@ pub fn divide_into_batches(
}
pub async fn get_batches(
- conn: &RedisConnectionPool,
+ conn: &RedisConnectionWithContext,
stream_name: &str,
group_name: &str,
consumer_name: &str,
diff --git a/crates/storage_impl/src/connection.rs b/crates/storage_impl/src/connection.rs
index 9281e210d8..50d7b759df 100644
--- a/crates/storage_impl/src/connection.rs
+++ b/crates/storage_impl/src/connection.rs
@@ -7,19 +7,6 @@ pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>;
pub type PgPooledConn = async_bb8_diesel::Connection<PgConnection>;
-/// Creates a Redis connection pool for the specified Redis settings
-/// # Panics
-///
-/// Panics if failed to create a redis pool
-#[allow(clippy::expect_used)]
-pub async fn redis_connection(
- redis: &redis_interface::RedisSettings,
-) -> redis_interface::RedisConnectionPool {
- redis_interface::RedisConnectionPool::new(redis)
- .await
- .expect("Failed to create Redis Connection Pool")
-}
-
pub async fn pg_connection_read<T: crate::DatabaseStore>(
store: &T,
) -> errors::CustomResult<
diff --git a/crates/storage_impl/src/kv_router_store.rs b/crates/storage_impl/src/kv_router_store.rs
index 9db8df9a12..03b49738d8 100644
--- a/crates/storage_impl/src/kv_router_store.rs
+++ b/crates/storage_impl/src/kv_router_store.rs
@@ -1,7 +1,10 @@
-use std::{fmt::Debug, sync::Arc};
+use std::fmt::Debug;
use common_enums::enums::MerchantStorageScheme;
-use common_utils::{fallback_reverse_lookup_not_found, types::keymanager::KeyManagerState};
+use common_utils::{
+ fallback_reverse_lookup_not_found, request_context::RequestContext,
+ types::keymanager::KeyManagerState,
+};
use diesel_models::{errors::DatabaseError, kv};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
@@ -11,7 +14,7 @@ use hyperswitch_domain_models::{
#[cfg(not(feature = "payouts"))]
use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};
use hyperswitch_masking::StrongSecret;
-use redis_interface::{errors::RedisError, types::HsetnxReply, RedisConnectionPool};
+use redis_interface::{errors::RedisError, types::HsetnxReply};
use router_env::logger;
use serde::de;
@@ -161,8 +164,16 @@ where
}
}
+impl<T: DatabaseStore> RequestContext for KVRouterStore<T> {
+ fn request_id(&self) -> Option<&str> {
+ self.request_id.as_deref()
+ }
+}
+
impl<T: DatabaseStore> RedisConnInterface for KVRouterStore<T> {
- fn get_redis_conn(&self) -> error_stack::Result<Arc<RedisConnectionPool>, RedisError> {
+ fn get_redis_conn(
+ &self,
+ ) -> error_stack::Result<redis_interface::RedisConnectionWithContext, RedisError> {
self.router_store.get_redis_conn()
}
}
@@ -214,9 +225,7 @@ impl<T: DatabaseStore> KVRouterStore<T> {
("operation", serializable_query.operation().to_string()),
("entity_type", serializable_query.entity_type())
);
- self.router_store
- .cache_store
- .redis_conn
+ self.get_redis_conn()?
.stream_append_entry(
&stream_name.into(),
&redis_interface::RedisEntryId::AutoGeneratedID,
diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs
index 5dd2711a21..0bc9fef8d1 100644
--- a/crates/storage_impl/src/lib.rs
+++ b/crates/storage_impl/src/lib.rs
@@ -1,6 +1,10 @@
use std::{fmt::Debug, sync::Arc};
-use common_utils::types::TenantConfig;
+use common_utils::{
+ external_service::{ExternalServiceEventEmitter, NoOpEventEmitter},
+ request_context::RequestContext,
+ types::TenantConfig,
+};
use diesel_models as store;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
@@ -50,7 +54,7 @@ pub mod tokenization;
#[cfg(not(feature = "payouts"))]
use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};
pub use mock_db::MockDb;
-use redis_interface::{errors::RedisError, RedisConnectionPool, SaddReply};
+use redis_interface::{errors::RedisError, RedisConnectionWithContext, SaddReply};
#[cfg(not(feature = "payouts"))]
pub use crate::database::store::Store;
@@ -66,6 +70,15 @@ pub struct RouterStore<T: DatabaseStore> {
key_manager_state: Option<KeyManagerState>,
}
+impl<T: DatabaseStore> RedisConnInterface for RouterStore<T> {
+ fn get_redis_conn(&self) -> error_stack::Result<RedisConnectionWithContext, RedisError> {
+ Ok(RedisConnectionWithContext::new(
+ Arc::clone(&self.cache_store.get_redis_pool()?),
+ self,
+ ))
+ }
+}
+
impl<T: DatabaseStore> RouterStore<T> {
pub fn set_key_manager_state(&mut self, state: KeyManagerState) {
self.key_manager_state = Some(state);
@@ -117,7 +130,8 @@ where
db_conf,
tenant_config,
encryption_key,
- Self::cache_store(&cache_conf, cache_error_signal).await?,
+ Self::cache_store(&cache_conf, cache_error_signal, Arc::new(NoOpEventEmitter))
+ .await?,
inmemory_cache_stream,
key_manager_state,
)
@@ -147,9 +161,9 @@ where
}
}
-impl<T: DatabaseStore> RedisConnInterface for RouterStore<T> {
- fn get_redis_conn(&self) -> error_stack::Result<Arc<RedisConnectionPool>, RedisError> {
- self.cache_store.get_redis_conn()
+impl<T: DatabaseStore> RequestContext for RouterStore<T> {
+ fn request_id(&self) -> Option<&str> {
+ self.request_id.as_deref()
}
}
@@ -163,15 +177,14 @@ impl<T: DatabaseStore> RouterStore<T> {
key_manager_state: Option<KeyManagerState>,
) -> error_stack::Result<Self, StorageError> {
let db_store = T::new(db_conf, tenant_config, false, key_manager_state.clone()).await?;
- let redis_conn = cache_store.redis_conn.clone();
- let cache_store = Arc::new(RedisStore {
- redis_conn: Arc::new(RedisConnectionPool::clone(
- &redis_conn,
- tenant_config.get_redis_key_prefix(),
- )),
- });
+ let cache_store = Arc::new(
+ cache_store
+ .clone()
+ .clone_pool_with_prefix(tenant_config.get_redis_key_prefix()),
+ );
cache_store
- .redis_conn
+ .get_redis_pool()
+ .change_context(StorageError::InitializationError)?
.subscribe(inmemory_cache_stream)
.await
.change_context(StorageError::InitializationError)
@@ -189,8 +202,9 @@ impl<T: DatabaseStore> RouterStore<T> {
pub async fn cache_store(
cache_conf: &redis_interface::RedisSettings,
cache_error_signal: tokio::sync::oneshot::Sender<()>,
+ event_emitter: Arc<dyn ExternalServiceEventEmitter>,
) -> error_stack::Result<Arc<RedisStore>, StorageError> {
- let cache_store = RedisStore::new(cache_conf)
+ let cache_store = RedisStore::new(cache_conf, event_emitter)
.await
.change_context(StorageError::InitializationError)
.attach_printable("Failed to create cache store")?;
@@ -377,7 +391,7 @@ impl<T: DatabaseStore> RouterStore<T> {
) -> error_stack::Result<Self, StorageError> {
// TODO: create an error enum and return proper error here
let db_store = T::new(db_conf, tenant_config, true, key_manager_state.clone()).await?;
- let cache_store = RedisStore::new(cache_conf)
+ let cache_store = RedisStore::new_without_event_emitter(cache_conf)
.await
.change_context(StorageError::InitializationError)
.attach_printable("failed to create redis cache")?;
@@ -423,7 +437,7 @@ pub trait UniqueConstraints {
fn table_name(&self) -> &str;
async fn check_for_constraints(
&self,
- redis_conn: &Arc<RedisConnectionPool>,
+ redis_conn: &RedisConnectionWithContext,
) -> CustomResult<(), RedisError> {
let constraints = self.unique_constraints();
let unique_contraint_count = constraints.len();
diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs
index 9171845ee8..2aee44073e 100644
--- a/crates/storage_impl/src/mock_db.rs
+++ b/crates/storage_impl/src/mock_db.rs
@@ -95,7 +95,7 @@ impl MockDb {
refunds: Default::default(),
processes: Default::default(),
redis: Arc::new(
- RedisStore::new(redis)
+ RedisStore::new_without_event_emitter(redis)
.await
.change_context(StorageError::InitializationError)?,
),
diff --git a/crates/storage_impl/src/mock_db/redis_conn.rs b/crates/storage_impl/src/mock_db/redis_conn.rs
index 142c750570..e78e525489 100644
--- a/crates/storage_impl/src/mock_db/redis_conn.rs
+++ b/crates/storage_impl/src/mock_db/redis_conn.rs
@@ -1,5 +1,3 @@
-use std::sync::Arc;
-
use redis_interface::errors::RedisError;
use super::MockDb;
@@ -8,7 +6,9 @@ use crate::redis::kv_store::RedisConnInterface;
impl RedisConnInterface for MockDb {
fn get_redis_conn(
&self,
- ) -> Result<Arc<redis_interface::RedisConnectionPool>, error_stack::Report<RedisError>> {
- self.redis.get_redis_conn()
+ ) -> Result<redis_interface::RedisConnectionWithContext, error_stack::Report<RedisError>> {
+ let pool = self.redis.get_redis_pool()?;
+
+ Ok(redis_interface::RedisConnectionWithContext::new_without_context(pool))
}
}
diff --git a/crates/storage_impl/src/redis.rs b/crates/storage_impl/src/redis.rs
index acafdb94ce..541e114d50 100644
--- a/crates/storage_impl/src/redis.rs
+++ b/crates/storage_impl/src/redis.rs
@@ -4,14 +4,12 @@ pub mod pub_sub;
use std::sync::{atomic, Arc};
+use common_utils::external_service::{ExternalServiceEventEmitter, NoOpEventEmitter};
use router_env::tracing::Instrument;
-use self::{kv_store::RedisConnInterface, pub_sub::PubSubInterface};
-
#[derive(Clone)]
pub struct RedisStore {
- // Maybe expose the redis_conn via traits instead of the making the field public
- pub(crate) redis_conn: Arc<redis_interface::RedisConnectionPool>,
+ redis_conn: Arc<redis_interface::RedisConnectionPool>,
}
impl std::fmt::Debug for RedisStore {
@@ -23,11 +21,20 @@ impl std::fmt::Debug for RedisStore {
}
impl RedisStore {
+ pub async fn new_without_event_emitter(
+ conf: &redis_interface::RedisSettings,
+ ) -> error_stack::Result<Self, redis_interface::errors::RedisError> {
+ Self::new(conf, Arc::new(NoOpEventEmitter)).await
+ }
+
pub async fn new(
conf: &redis_interface::RedisSettings,
+ event_emitter: Arc<dyn ExternalServiceEventEmitter>,
) -> error_stack::Result<Self, redis_interface::errors::RedisError> {
Ok(Self {
- redis_conn: Arc::new(redis_interface::RedisConnectionPool::new(conf).await?),
+ redis_conn: Arc::new(
+ redis_interface::RedisConnectionPool::new(conf, event_emitter).await?,
+ ),
})
}
@@ -40,10 +47,8 @@ impl RedisStore {
.in_current_span(),
);
}
-}
-impl RedisConnInterface for RedisStore {
- fn get_redis_conn(
+ pub fn get_redis_pool(
&self,
) -> error_stack::Result<
Arc<redis_interface::RedisConnectionPool>,
@@ -59,4 +64,13 @@ impl RedisConnInterface for RedisStore {
Err(redis_interface::errors::RedisError::RedisConnectionError.into())
}
}
+
+ pub fn clone_pool_with_prefix(&self, key_prefix: &str) -> Self {
+ Self {
+ redis_conn: Arc::new(redis_interface::RedisConnectionPool::clone(
+ &self.redis_conn,
+ key_prefix,
+ )),
+ }
+ }
}
diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs
index b711358433..1d951742f3 100644
--- a/crates/storage_impl/src/redis/cache.rs
+++ b/crates/storage_impl/src/redis/cache.rs
@@ -12,7 +12,7 @@ use common_utils::{
use dyn_clone::DynClone;
use error_stack::{Report, ResultExt};
use moka::future::Cache as MokaCache;
-use redis_interface::{errors::RedisError, RedisConnectionPool, RedisValue};
+use redis_interface::{errors::RedisError, RedisConnectionWithContext, RedisValue};
use router_env::{
logger,
tracing::{self, instrument},
@@ -21,7 +21,7 @@ use router_env::{
use crate::{
errors::StorageError,
metrics,
- redis::{PubSubInterface, RedisConnInterface},
+ redis::{kv_store::RedisConnInterface, pub_sub::PubSubInterface},
};
/// Redis channel name used for publishing invalidation messages
@@ -304,7 +304,7 @@ impl Cache {
#[instrument(skip_all)]
pub async fn get_or_populate_redis<T, F, Fut>(
- redis: &Arc<RedisConnectionPool>,
+ redis: &RedisConnectionWithContext,
key: impl AsRef<str>,
fun: F,
) -> CustomResult<T, StorageError>
@@ -389,7 +389,7 @@ where
.attach_printable("Failed to get redis connection")?;
let cache_key = CacheKey {
key: key.to_string(),
- prefix: redis.key_prefix.clone(),
+ prefix: redis.redis_conn.key_prefix.clone(),
};
// Deja L1 seam: the in-memory (moka) lookup is a process-global cache that
// spans correlations. Instrument the LOOKUP itself (not the surrounding
@@ -412,7 +412,7 @@ where
.push(
CacheKey {
key: key.to_string(),
- prefix: redis.key_prefix.clone(),
+ prefix: redis.redis_conn.key_prefix.clone(),
},
val.clone(),
)
@@ -454,9 +454,9 @@ pub async fn redact_from_redis_and_publish<
logger::debug!(redis_deletion_result=?deletion_result);
- let futures = keys.into_iter().map(|key| async {
+ let redis_conn = &redis_conn;
+ let futures = keys.into_iter().map(move |key| async move {
redis_conn
- .clone()
.publish(IMC_INVALIDATION_CHANNEL, key)
.await
.change_context(StorageError::KVError)
diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs
index bba63f5fca..7766a4ad99 100644
--- a/crates/storage_impl/src/redis/kv_store.rs
+++ b/crates/storage_impl/src/redis/kv_store.rs
@@ -1,4 +1,4 @@
-use std::{fmt::Debug, sync::Arc};
+use std::fmt::Debug;
use common_utils::errors::CustomResult;
use diesel_models::enums::MerchantStorageScheme;
@@ -121,7 +121,7 @@ impl std::fmt::Display for PartitionKey<'_> {
pub trait RedisConnInterface {
fn get_redis_conn(
&self,
- ) -> error_stack::Result<Arc<redis_interface::RedisConnectionPool>, RedisError>;
+ ) -> error_stack::Result<redis_interface::RedisConnectionWithContext, RedisError>;
}
/// An enum to represent what operation to do on
@@ -183,7 +183,7 @@ where
D: crate::database::store::DatabaseStore,
S: serde::Serialize + Debug + KvStorePartition + UniqueConstraints + Sync,
{
- let redis_conn = store.get_redis_conn()?;
+ let redis_conn = store.router_store.get_redis_conn()?;
let key = format!("{partition_key}");
diff --git a/crates/storage_impl/src/redis/pub_sub.rs b/crates/storage_impl/src/redis/pub_sub.rs
index 0430b7caaf..904cc689cc 100644
--- a/crates/storage_impl/src/redis/pub_sub.rs
+++ b/crates/storage_impl/src/redis/pub_sub.rs
@@ -267,3 +267,22 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
Ok(())
}
}
+
+#[async_trait::async_trait]
+impl PubSubInterface for redis_interface::RedisConnectionWithContext {
+ async fn subscribe(&self, channel: &str) -> error_stack::Result<(), redis_errors::RedisError> {
+ self.redis_conn.subscribe(channel).await
+ }
+
+ async fn publish<'a>(
+ &self,
+ channel: &str,
+ key: CacheKind<'a>,
+ ) -> error_stack::Result<usize, redis_errors::RedisError> {
+ self.redis_conn.publish(channel, key).await
+ }
+
+ async fn on_message(&self) -> error_stack::Result<(), redis_errors::RedisError> {
+ self.redis_conn.on_message().await
+ }
+}