Skip to main content

redis_tower_core/
command.rs

1use redis_tower_protocol::Frame;
2use tokio::time::Instant;
3
4use crate::error::RedisError;
5
6/// A typed Redis command.
7///
8/// Each Redis command is represented as a struct that implements this trait.
9/// The associated `Response` type ensures compile-time type safety for
10/// command results.
11///
12/// # Example
13///
14/// ```no_run
15/// use redis_tower_core::{Command, Frame, RedisError};
16/// use redis_tower_protocol::helpers::{array, bulk};
17///
18/// pub struct Ping;
19///
20/// impl Command for Ping {
21///     type Response = String;
22///
23///     fn to_frame(&self) -> Frame {
24///         array(vec![bulk("PING")])
25///     }
26///
27///     fn parse_response(&self, frame: Frame) -> Result<String, RedisError> {
28///         match frame {
29///             Frame::SimpleString(s) => Ok(String::from_utf8_lossy(&s).into_owned()),
30///             _ => Err(RedisError::UnexpectedResponse {
31///                 expected: "simple string",
32///                 actual: format!("{frame:?}"),
33///             }),
34///         }
35///     }
36///
37///     fn name(&self) -> &str { "PING" }
38/// }
39/// ```
40pub trait Command: Send + 'static {
41    /// The typed response this command produces.
42    type Response: Send + 'static;
43
44    /// Serialize this command into a RESP frame for the wire.
45    fn to_frame(&self) -> Frame;
46
47    /// Parse a RESP response frame into the typed response.
48    ///
49    /// Takes `&self` so that parsing can depend on command configuration
50    /// (e.g., optional flags that change the response shape).
51    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError>;
52
53    /// The Redis command name, for observability (metrics, tracing spans).
54    fn name(&self) -> &str;
55
56    /// Whether this command is safe to retry on connection errors.
57    ///
58    /// Returns `true` for read-only commands (GET, HGET, LRANGE, etc.) and
59    /// commands where re-execution produces the same result (e.g. SET without
60    /// side-effect sub-commands). Returns `false` (the default) for all other
61    /// write commands where retrying may cause silent data duplication.
62    ///
63    /// Override this method in command implementations to declare idempotency.
64    fn idempotent(&self) -> bool {
65        false
66    }
67
68    /// Whether this command blocks the connection until data is available or a
69    /// timeout elapses -- `BLPOP`, `BRPOP`, `BLMOVE`, `BZPOPMIN`/`BZPOPMAX`, and
70    /// `XREAD`/`XREADGROUP` with `BLOCK`.
71    ///
72    /// Returns `false` by default. This matters for multiplexed clients: a
73    /// blocking command holds the single shared pipeline worker for its entire
74    /// duration, stalling every other concurrent caller on that connection. Run
75    /// blocking commands on a dedicated `RedisConnection` or a pooled connection
76    /// instead. The flag lets callers and middleware detect such commands.
77    fn is_blocking(&self) -> bool {
78        false
79    }
80
81    /// Return the absolute deadline attached to this command, if any.
82    ///
83    /// Most commands have no deadline. [`WithDeadline`] overrides this method
84    /// so deadline-aware middleware and resource acquisition can share one
85    /// end-to-end budget instead of starting a fresh timeout at each stage.
86    /// Implementations that wrap another command should propagate the wrapped
87    /// command's deadline.
88    fn deadline(&self) -> Option<Instant> {
89        None
90    }
91}
92
93/// A typed command carrying an absolute deadline.
94///
95/// The deadline is an absolute [`tokio::time::Instant`], so cloning or retrying
96/// the command does not reset its time budget. Deadline-aware middleware and
97/// pools can inspect it through [`Command::deadline`].
98///
99/// When envelopes are nested, the earliest deadline wins; wrapping a command
100/// can therefore shorten, but never extend, an existing budget.
101#[derive(Debug, Clone)]
102pub struct WithDeadline<C> {
103    command: C,
104    deadline: Instant,
105}
106
107impl<C> WithDeadline<C> {
108    /// Wrap `command` with an absolute `deadline`.
109    pub fn new(command: C, deadline: Instant) -> Self {
110        Self { command, deadline }
111    }
112
113    /// Wrap `command` with a deadline relative to now.
114    pub fn after(command: C, timeout: std::time::Duration) -> Self {
115        Self::new(command, Instant::now() + timeout)
116    }
117
118    /// Return the envelope's absolute deadline.
119    ///
120    /// For nested envelopes, [`Command::deadline`] returns the effective
121    /// earliest deadline while this accessor returns the deadline stored on
122    /// this envelope itself.
123    pub fn deadline(&self) -> Instant {
124        self.deadline
125    }
126
127    /// Borrow the wrapped command.
128    pub fn get_ref(&self) -> &C {
129        &self.command
130    }
131
132    /// Mutably borrow the wrapped command.
133    pub fn get_mut(&mut self) -> &mut C {
134        &mut self.command
135    }
136
137    /// Consume the envelope and return the wrapped command.
138    pub fn into_inner(self) -> C {
139        self.command
140    }
141}
142
143impl<C: Command> Command for WithDeadline<C> {
144    type Response = C::Response;
145
146    fn to_frame(&self) -> Frame {
147        self.command.to_frame()
148    }
149
150    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
151        self.command.parse_response(frame)
152    }
153
154    fn name(&self) -> &str {
155        self.command.name()
156    }
157
158    fn idempotent(&self) -> bool {
159        self.command.idempotent()
160    }
161
162    fn is_blocking(&self) -> bool {
163        self.command.is_blocking()
164    }
165
166    fn deadline(&self) -> Option<Instant> {
167        Some(match self.command.deadline() {
168            Some(inner) => self.deadline.min(inner),
169            None => self.deadline,
170        })
171    }
172}
173
174/// Deadline metadata understood by the deadline-aware mode of
175/// [`CommandTimeoutLayer`](https://docs.rs/redis-tower/latest/redis_tower/struct.CommandTimeoutLayer.html).
176///
177/// Typed [`Command`] requests implement this trait automatically. Raw RESP
178/// [`Frame`] requests are also supported and report no per-request deadline,
179/// preserving the static-timeout behavior of frame-level middleware stacks.
180/// Custom request types can implement this trait to use
181/// `CommandTimeoutLayer::with_request_deadlines`.
182pub trait RequestDeadline {
183    /// Return the request's absolute deadline, if it carries one.
184    fn request_deadline(&self) -> Option<Instant>;
185}
186
187impl<C: Command> RequestDeadline for C {
188    fn request_deadline(&self) -> Option<Instant> {
189        Command::deadline(self)
190    }
191}
192
193impl RequestDeadline for Frame {
194    fn request_deadline(&self) -> Option<Instant> {
195        None
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    #[derive(Debug, Clone)]
204    struct TestCommand;
205
206    impl Command for TestCommand {
207        type Response = Frame;
208
209        fn to_frame(&self) -> Frame {
210            Frame::Null
211        }
212
213        fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
214            Ok(frame)
215        }
216
217        fn name(&self) -> &str {
218            "TEST"
219        }
220
221        fn idempotent(&self) -> bool {
222            true
223        }
224
225        fn is_blocking(&self) -> bool {
226            true
227        }
228    }
229
230    #[test]
231    fn with_deadline_delegates_command_metadata() {
232        let deadline = Instant::now() + std::time::Duration::from_secs(1);
233        let command = WithDeadline::new(TestCommand, deadline);
234
235        assert_eq!(command.name(), "TEST");
236        assert!(command.idempotent());
237        assert!(command.is_blocking());
238        assert_eq!(Command::deadline(&command), Some(deadline));
239        assert!(matches!(command.to_frame(), Frame::Null));
240        assert!(matches!(
241            command.parse_response(Frame::Null),
242            Ok(Frame::Null)
243        ));
244    }
245
246    #[test]
247    fn nested_envelopes_keep_the_earliest_deadline() {
248        let early = Instant::now() + std::time::Duration::from_secs(1);
249        let late = early + std::time::Duration::from_secs(1);
250
251        let shortened = WithDeadline::new(WithDeadline::new(TestCommand, late), early);
252        let not_extended = WithDeadline::new(WithDeadline::new(TestCommand, early), late);
253
254        assert_eq!(Command::deadline(&shortened), Some(early));
255        assert_eq!(Command::deadline(&not_extended), Some(early));
256    }
257
258    #[test]
259    fn raw_frames_have_no_request_deadline() {
260        assert_eq!(Frame::Null.request_deadline(), None);
261    }
262}