Skip to main content

redis_tower/
executor.rs

1//! The [`RedisExecutor`] trait for executing Redis commands.
2//!
3//! All redis-tower client types implement this trait. Application code
4//! can depend on `impl RedisExecutor` rather than concrete client types,
5//! making it straightforward to substitute a mock in tests.
6
7use std::future::Future;
8use std::pin::Pin;
9use std::sync::Arc;
10use std::task::{Context, Poll};
11
12use redis_tower_core::{Command, RedisConnection, RedisError};
13use tokio::sync::Mutex;
14
15use crate::caching::CachedClient;
16use crate::client::RedisClient;
17use crate::multiplexed::{CachedMultiplexedClient, MultiplexedClient};
18use crate::resilient::ResilientRedisClient;
19
20/// Trait for executing Redis commands, enabling test mocking.
21///
22/// All redis-tower client types implement this trait. Application code
23/// can depend on `impl RedisExecutor` rather than concrete client types,
24/// making it easy to substitute a mock in tests.
25///
26/// # Example
27///
28/// ```no_run
29/// use redis_tower::RedisExecutor;
30/// use redis_tower::commands::Incr;
31/// # use redis_tower::{RedisClient, RedisError};
32///
33/// async fn increment(redis: &mut impl RedisExecutor, key: &str) -> Result<i64, RedisError> {
34///     redis.execute(Incr::new(key)).await
35/// }
36/// # async fn call(mut client: RedisClient) -> Result<(), RedisError> {
37/// #     let _count = increment(&mut client, "visits").await?;
38/// #     Ok(())
39/// # }
40/// ```
41pub trait RedisExecutor {
42    /// Execute a Redis command and return its typed response.
43    fn execute<Cmd: Command>(
44        &mut self,
45        cmd: Cmd,
46    ) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send;
47}
48
49impl RedisExecutor for RedisConnection {
50    fn execute<Cmd: Command>(
51        &mut self,
52        cmd: Cmd,
53    ) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
54        RedisConnection::execute(self, cmd)
55    }
56}
57
58impl RedisExecutor for RedisClient {
59    fn execute<Cmd: Command>(
60        &mut self,
61        cmd: Cmd,
62    ) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
63        RedisClient::execute(self, cmd)
64    }
65}
66
67impl RedisExecutor for ResilientRedisClient {
68    fn execute<Cmd: Command>(
69        &mut self,
70        cmd: Cmd,
71    ) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
72        ResilientRedisClient::execute(self, cmd)
73    }
74}
75
76impl RedisExecutor for CachedClient {
77    fn execute<Cmd: Command>(
78        &mut self,
79        cmd: Cmd,
80    ) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
81        CachedClient::execute(self, cmd)
82    }
83}
84
85/// Blanket impl: any `Arc<Mutex<C>>` where `C: RedisExecutor + Send` is also
86/// a `RedisExecutor`. This makes `RedisClient` (which wraps `Arc<Mutex<RedisConnection>>`)
87/// and any user-defined Arc-wrapped executor automatically composable with
88/// generic API wrappers like [`Json`](crate::json_api::Json).
89impl<C: RedisExecutor + Send> RedisExecutor for Arc<Mutex<C>> {
90    fn execute<Cmd: Command>(
91        &mut self,
92        cmd: Cmd,
93    ) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
94        let arc = Arc::clone(self);
95        async move { arc.lock().await.execute(cmd).await }
96    }
97}
98
99/// Blanket impl: `&mut C` implements `RedisExecutor` when `C: RedisExecutor`.
100///
101/// This allows passing `&mut conn` or `&mut client` to APIs that accept
102/// `impl RedisExecutor` by value, e.g. `Json::new(&mut conn)`.
103impl<C: RedisExecutor + Send + ?Sized> RedisExecutor for &mut C {
104    fn execute<Cmd: Command>(
105        &mut self,
106        cmd: Cmd,
107    ) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
108        (**self).execute(cmd)
109    }
110}
111
112/// `MultiplexedClient` implements `RedisExecutor`. Internally its `execute`
113/// method takes `&self` (channel send -- no real mutation), but the trait's
114/// `&mut self` contract is satisfied trivially.
115impl RedisExecutor for MultiplexedClient {
116    fn execute<Cmd: Command>(
117        &mut self,
118        cmd: Cmd,
119    ) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
120        MultiplexedClient::execute(self, cmd)
121    }
122}
123
124/// The cached multiplexed newtype retains the same executor surface as the
125/// standard [`MultiplexedClient`]. Its `execute` method also takes `&self`;
126/// the trait's mutable receiver is satisfied trivially.
127impl RedisExecutor for CachedMultiplexedClient {
128    fn execute<Cmd: Command>(
129        &mut self,
130        cmd: Cmd,
131    ) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
132        CachedMultiplexedClient::execute(self, cmd)
133    }
134}
135
136/// A Tower [`Service`](tower_service::Service) adapter over any cloneable
137/// [`RedisExecutor`].
138///
139/// redis-tower's middleware [`Layer`](tower_layer::Layer)s wrap a `Service`,
140/// but the high-level clients (`RedisClient`, `MultiplexedClient`,
141/// `CachedMultiplexedClient`, `ConnectionPool`, `CachedClient`,
142/// `ResilientRedisClient`) are
143/// `RedisExecutor`s rather than `Service`s. This newtype bridges them so a
144/// `tower::ServiceBuilder` stack can sit in front of a real client.
145///
146/// Every request routes through [`RedisExecutor::execute`], so cluster
147/// MOVED/ASK redirects and sentinel rediscovery are preserved. (The raw
148/// `Service<Cmd>` impls on `ClusterConnection`/`SentinelConnection` route a
149/// single hop and bypass that logic -- do not use them as a layering base;
150/// wrap the cluster/sentinel *client* in an `ExecutorService` instead.)
151///
152/// The wrapped executor must be [`Clone`] because each `call` clones the handle
153/// into an owned `'static` future. Every redis-tower client is a cheap
154/// `Arc`-based handle, so the clone shares the underlying connection rather than
155/// opening a new one.
156///
157/// # Example
158///
159/// ```no_run
160/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
161/// use std::time::Duration;
162/// use tower::ServiceBuilder;
163/// use redis_tower::{CommandTimeoutLayer, ExecutorService, MultiplexedClient};
164///
165/// // `client` is any cloneable RedisExecutor (e.g. a MultiplexedClient).
166/// let client = MultiplexedClient::connect("127.0.0.1:6379").await?;
167/// let service = ServiceBuilder::new()
168///     .layer(CommandTimeoutLayer::new(Duration::from_secs(1)))
169///     .service(ExecutorService::new(client));
170/// # let _ = service;
171/// # Ok(())
172/// # }
173/// ```
174#[derive(Clone, Debug)]
175pub struct ExecutorService<P> {
176    inner: P,
177}
178
179impl<P> ExecutorService<P> {
180    /// Wrap a cloneable [`RedisExecutor`] as a Tower
181    /// [`Service`](tower_service::Service).
182    pub fn new(inner: P) -> Self {
183        Self { inner }
184    }
185
186    /// Consume the adapter and return the wrapped executor.
187    pub fn into_inner(self) -> P {
188        self.inner
189    }
190
191    /// Borrow the wrapped executor.
192    pub fn get_ref(&self) -> &P {
193        &self.inner
194    }
195}
196
197impl<P, Cmd> tower_service::Service<Cmd> for ExecutorService<P>
198where
199    P: RedisExecutor + Clone + Send + 'static,
200    Cmd: Command + Send + 'static,
201{
202    type Response = Cmd::Response;
203    type Error = RedisError;
204    type Future = Pin<Box<dyn Future<Output = Result<Cmd::Response, RedisError>> + Send>>;
205
206    /// Always ready: the underlying [`RedisExecutor`] exposes no readiness
207    /// signal, so back-pressure (if any) is enforced inside `execute` itself.
208    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
209        Poll::Ready(Ok(()))
210    }
211
212    fn call(&mut self, cmd: Cmd) -> Self::Future {
213        // Clone the handle so the returned future owns its executor (Tower
214        // futures are `'static` and cannot borrow `self`). The clone is a cheap
215        // Arc bump that shares the underlying connection.
216        let mut inner = self.inner.clone();
217        Box::pin(async move { inner.execute(cmd).await })
218    }
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224    use redis_tower_core::Frame;
225    use std::collections::VecDeque;
226
227    /// A mock Redis executor that returns pre-configured frames.
228    struct MockRedis {
229        responses: VecDeque<Frame>,
230    }
231
232    impl MockRedis {
233        fn new(responses: Vec<Frame>) -> Self {
234            Self {
235                responses: VecDeque::from(responses),
236            }
237        }
238    }
239
240    impl RedisExecutor for MockRedis {
241        fn execute<Cmd: Command>(
242            &mut self,
243            cmd: Cmd,
244        ) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
245            let frame = self.responses.pop_front().unwrap_or(Frame::Null);
246            async move { cmd.parse_response(frame) }
247        }
248    }
249
250    #[tokio::test]
251    async fn mock_executor_returns_response() {
252        use bytes::Bytes;
253        use redis_tower_commands::Get;
254
255        let mut mock = MockRedis::new(vec![Frame::BulkString(Some(Bytes::from("hello")))]);
256        let result: Option<Bytes> = mock.execute(Get::new("key")).await.unwrap();
257        assert_eq!(result, Some(Bytes::from("hello")));
258    }
259
260    #[tokio::test]
261    async fn arc_mutex_implements_executor() {
262        use bytes::Bytes;
263        use redis_tower_commands::Get;
264
265        // Verify Arc<Mutex<MockRedis>> implements RedisExecutor at runtime too.
266        let mock = Arc::new(Mutex::new(MockRedis::new(vec![Frame::BulkString(Some(
267            Bytes::from("world"),
268        ))])));
269        let mut executor = Arc::clone(&mock);
270        let result: Option<Bytes> = executor.execute(Get::new("key")).await.unwrap();
271        assert_eq!(result, Some(Bytes::from("world")));
272    }
273
274    #[tokio::test]
275    async fn mut_ref_implements_executor() {
276        use bytes::Bytes;
277        use redis_tower_commands::Get;
278
279        // Verify &mut MockRedis implements RedisExecutor (used by Json::new(&mut conn)).
280        let mut mock = MockRedis::new(vec![Frame::BulkString(Some(Bytes::from("ref")))]);
281        let result: Option<Bytes> = mock.execute(Get::new("key")).await.unwrap();
282        assert_eq!(result, Some(Bytes::from("ref")));
283    }
284
285    #[tokio::test]
286    async fn executor_service_bridges_to_tower() {
287        use bytes::Bytes;
288        use redis_tower_commands::Get;
289        use std::future::poll_fn;
290        use tower_service::Service;
291
292        // Arc<Mutex<MockRedis>> is RedisExecutor + Clone, so it can be bridged.
293        let mock = Arc::new(Mutex::new(MockRedis::new(vec![Frame::BulkString(Some(
294            Bytes::from("via-service"),
295        ))])));
296        let mut svc = ExecutorService::new(mock);
297
298        // ExecutorService is Clone (derive); cloning shares the executor.
299        let _clone = svc.clone();
300
301        // Drive it as a Tower Service: poll_ready then call.
302        poll_fn(|cx| Service::<Get>::poll_ready(&mut svc, cx))
303            .await
304            .unwrap();
305        let result: Option<Bytes> = svc.call(Get::new("key")).await.unwrap();
306        assert_eq!(result, Some(Bytes::from("via-service")));
307    }
308}