Skip to main content

redis_tower_commands/
raw.rs

1//! Escape hatches for custom, module, and newly introduced Redis commands.
2//!
3//! [`RawCommand`] preserves binary arguments and returns a raw `Frame`.
4//! [`RawCommand::query`] adds any `FromFrame` decoder while keeping identical
5//! wire bytes. Cluster callers must separately provide enough key/routing
6//! information for safe placement; a decoder does not make an unknown command
7//! routable.
8//!
9//! ```
10//! use redis_tower_commands::RawCommand;
11//! use redis_tower_core::Command;
12//!
13//! let command = RawCommand::new("SCARD").arg("members").query::<i64>();
14//! assert_eq!(command.name(), "SCARD");
15//! ```
16//!
17//! See the [command cookbook] for reply-shape and Cluster guidance.
18//!
19//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#raw-custom-and-module-replies
20
21use std::marker::PhantomData;
22
23use redis_tower_core::{Command, Frame, FromFrame, RedisError};
24use redis_tower_protocol::helpers::{array, bulk};
25
26/// Execute an arbitrary Redis command by name.
27///
28/// Use this for commands not covered by typed structs, custom modules,
29/// or commands added in newer Redis versions.
30///
31/// # Example
32///
33/// ```no_run
34/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
35/// use redis_tower_commands::RawCommand;
36/// use redis_tower_core::RedisConnection;
37/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
38/// let result = conn.execute(RawCommand::new("CUSTOM.CMD").arg("key").arg("val")).await?;
39/// # let _ = result;
40/// # Ok(())
41/// # }
42/// ```
43#[derive(Clone)]
44pub struct RawCommand {
45    name_str: String,
46    args: Vec<Vec<u8>>,
47}
48
49impl RawCommand {
50    /// Create a new raw command with the given command name.
51    pub fn new(name: impl Into<String>) -> Self {
52        let name_str = name.into();
53        Self {
54            name_str,
55            args: Vec::new(),
56        }
57    }
58
59    /// Append an argument to this command.
60    pub fn arg(mut self, arg: impl AsRef<[u8]>) -> Self {
61        self.args.push(arg.as_ref().to_vec());
62        self
63    }
64
65    /// Decode this command's reply into a typed value `T` instead of a raw [`Frame`].
66    ///
67    /// Returns a [`TypedRawCommand`] whose `Response` is `T`, so `execute`
68    /// yields a decoded value. `T` can be any type implementing
69    /// [`FromFrame`]: scalars, `String`, `Bytes`,
70    /// `Option<T>`, `Vec<T>`, tuples, and `HashMap<K, V>`.
71    ///
72    /// # Example
73    ///
74    /// ```no_run
75    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
76    /// use redis_tower_commands::RawCommand;
77    /// use redis_tower_core::RedisConnection;
78    /// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
79    /// let count: i64 = conn.execute(RawCommand::new("SCARD").arg("s").query()).await?;
80    /// let members: Vec<String> =
81    ///     conn.execute(RawCommand::new("SMEMBERS").arg("s").query()).await?;
82    /// # let _ = (count, members);
83    /// # Ok(())
84    /// # }
85    /// ```
86    pub fn query<T: FromFrame>(self) -> TypedRawCommand<T> {
87        TypedRawCommand {
88            inner: self,
89            _marker: PhantomData,
90        }
91    }
92}
93
94/// A [`RawCommand`] that decodes its reply into a typed value `T`.
95///
96/// Created by [`RawCommand::query`]. Sends the exact same wire bytes as the
97/// underlying `RawCommand`, but [`parse_response`](Command::parse_response)
98/// runs `T::from_frame` so `execute` returns a `T` rather than a `Frame`.
99pub struct TypedRawCommand<T> {
100    inner: RawCommand,
101    // `fn() -> T` keeps `TypedRawCommand` `Send`/`Sync` regardless of `T`.
102    _marker: PhantomData<fn() -> T>,
103}
104
105impl<T> Clone for TypedRawCommand<T> {
106    fn clone(&self) -> Self {
107        Self {
108            inner: self.inner.clone(),
109            _marker: PhantomData,
110        }
111    }
112}
113
114impl<T: FromFrame + Send + 'static> Command for TypedRawCommand<T> {
115    type Response = T;
116
117    fn to_frame(&self) -> Frame {
118        self.inner.to_frame()
119    }
120
121    fn parse_response(&self, frame: Frame) -> Result<T, RedisError> {
122        T::from_frame(frame)
123    }
124
125    fn name(&self) -> &str {
126        self.inner.name()
127    }
128}
129
130impl Command for RawCommand {
131    type Response = Frame;
132
133    fn to_frame(&self) -> Frame {
134        let mut frames = Vec::with_capacity(1 + self.args.len());
135        frames.push(bulk(self.name_str.as_str()));
136        for arg in &self.args {
137            frames.push(bulk(arg.as_slice()));
138        }
139        array(frames)
140    }
141
142    fn parse_response(&self, frame: Frame) -> Result<Frame, RedisError> {
143        Ok(frame)
144    }
145
146    fn name(&self) -> &str {
147        &self.name_str
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154    use bytes::Bytes;
155
156    #[test]
157    fn to_frame_single_command() {
158        let cmd = RawCommand::new("PING");
159        let frame = cmd.to_frame();
160        let expected = Frame::Array(Some(vec![Frame::BulkString(Some(Bytes::from("PING")))]));
161        assert_eq!(frame, expected);
162    }
163
164    #[test]
165    fn to_frame_with_args() {
166        let cmd = RawCommand::new("SET").arg("key").arg("value");
167        let frame = cmd.to_frame();
168        let expected = Frame::Array(Some(vec![
169            Frame::BulkString(Some(Bytes::from("SET"))),
170            Frame::BulkString(Some(Bytes::from("key"))),
171            Frame::BulkString(Some(Bytes::from("value"))),
172        ]));
173        assert_eq!(frame, expected);
174    }
175
176    #[test]
177    fn parse_response_passes_through() {
178        let cmd = RawCommand::new("PING");
179        let frame = Frame::SimpleString(Bytes::from("PONG"));
180        let result = cmd.parse_response(frame.clone()).unwrap();
181        assert_eq!(result, frame);
182    }
183
184    #[test]
185    fn name_returns_command_name() {
186        let cmd = RawCommand::new("CUSTOM.CMD");
187        assert_eq!(cmd.name(), "CUSTOM.CMD");
188    }
189
190    #[test]
191    fn multiple_args_binary() {
192        let cmd = RawCommand::new("SET")
193            .arg(b"bin\x00key".as_slice())
194            .arg(b"\xff\xfe".as_slice());
195        let frame = cmd.to_frame();
196        match frame {
197            Frame::Array(Some(frames)) => assert_eq!(frames.len(), 3),
198            other => panic!("expected array, got {other:?}"),
199        }
200    }
201
202    // -- TypedRawCommand (query) --
203
204    #[test]
205    fn query_sends_same_wire_bytes() {
206        let raw = RawCommand::new("INCR").arg("ctr");
207        let expected = raw.to_frame();
208        let typed = RawCommand::new("INCR").arg("ctr").query::<i64>();
209        assert_eq!(typed.to_frame(), expected);
210        assert_eq!(typed.name(), "INCR");
211    }
212
213    #[test]
214    fn query_decodes_integer() {
215        let typed = RawCommand::new("INCR").arg("ctr").query::<i64>();
216        let n = typed.parse_response(Frame::Integer(7)).unwrap();
217        assert_eq!(n, 7);
218    }
219
220    #[test]
221    fn query_decodes_vec_of_strings() {
222        let typed = RawCommand::new("SMEMBERS").arg("s").query::<Vec<String>>();
223        let frame = Frame::Array(Some(vec![
224            Frame::BulkString(Some(Bytes::from("a"))),
225            Frame::BulkString(Some(Bytes::from("b"))),
226        ]));
227        let v = typed.parse_response(frame).unwrap();
228        assert_eq!(v, vec!["a", "b"]);
229    }
230
231    #[test]
232    fn query_decodes_option_none_on_nil() {
233        let typed = RawCommand::new("GET")
234            .arg("missing")
235            .query::<Option<String>>();
236        let v = typed.parse_response(Frame::BulkString(None)).unwrap();
237        assert_eq!(v, None);
238    }
239
240    #[test]
241    fn query_surfaces_error_frame() {
242        let typed = RawCommand::new("GET").arg("k").query::<String>();
243        let r = typed.parse_response(Frame::Error(Bytes::from("WRONGTYPE nope")));
244        assert!(r.is_err());
245    }
246
247    #[test]
248    fn query_to_frame_is_identity() {
249        let typed = RawCommand::new("PING").query::<Frame>();
250        let echoed = typed
251            .parse_response(Frame::SimpleString(Bytes::from("PONG")))
252            .unwrap();
253        assert_eq!(echoed, Frame::SimpleString(Bytes::from("PONG")));
254    }
255
256    #[test]
257    fn typed_raw_command_is_clone_and_send() {
258        fn assert_send<T: Send>() {}
259        assert_send::<TypedRawCommand<String>>();
260        let typed = RawCommand::new("GET").arg("k").query::<String>();
261        let _clone = typed.clone();
262    }
263}