Skip to main content

redis_tower_commands/
transaction.rs

1//! Low-level Redis transaction control commands.
2//!
3//! These builders expose `MULTI`, `EXEC`, `WATCH`, and related wire commands.
4//! Application code should normally use
5//! [`redis_tower::Transaction`](https://docs.rs/redis-tower/latest/redis_tower/struct.Transaction.html),
6//! which submits a complete atomic exchange and returns typed results. Do not
7//! issue these primitives as separate calls on a multiplexed connection.
8//!
9//! ```
10//! use redis_tower_commands::Watch;
11//! use redis_tower_core::Command;
12//!
13//! let command = Watch::keys(["account:1", "account:2"]);
14//! assert_eq!(command.name(), "WATCH");
15//! ```
16//!
17//! See the [command cookbook] for pipeline, transaction, and exclusive WATCH
18//! ownership rules.
19//!
20//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#pipelines-transactions-and-cluster-slots
21
22use crate::CommandArg;
23use redis_tower_core::{Command, Frame, RedisError};
24use redis_tower_protocol::helpers::{array, bulk};
25
26/// MULTI
27///
28/// Marks the start of a transaction block. Subsequent commands are queued for
29/// atomic execution with EXEC.
30#[derive(Clone)]
31pub struct Multi;
32
33impl Multi {
34    /// Create a new [`Multi`] command.
35    pub fn new() -> Self {
36        Self
37    }
38}
39
40impl Default for Multi {
41    fn default() -> Self {
42        Self::new()
43    }
44}
45
46impl Command for Multi {
47    type Response = ();
48
49    fn to_frame(&self) -> Frame {
50        array(vec![bulk("MULTI")])
51    }
52
53    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
54        match frame {
55            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
56            other => Err(RedisError::UnexpectedResponse {
57                expected: "OK",
58                actual: format!("{other:?}"),
59            }),
60        }
61    }
62
63    fn name(&self) -> &str {
64        "MULTI"
65    }
66}
67
68/// EXEC
69///
70/// Executes all commands queued in a transaction. Returns `None` if the
71/// transaction was aborted (a watched key changed), or `Some(results)` with one
72/// frame per queued command otherwise.
73#[derive(Clone)]
74pub struct Exec;
75
76impl Exec {
77    /// Create a new [`Exec`] command.
78    pub fn new() -> Self {
79        Self
80    }
81}
82
83impl Default for Exec {
84    fn default() -> Self {
85        Self::new()
86    }
87}
88
89impl Command for Exec {
90    type Response = Option<Vec<Frame>>;
91
92    fn to_frame(&self) -> Frame {
93        array(vec![bulk("EXEC")])
94    }
95
96    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
97        match frame {
98            Frame::Array(None) | Frame::Null => Ok(None),
99            Frame::Array(Some(frames)) => Ok(Some(frames)),
100            other => Err(RedisError::UnexpectedResponse {
101                expected: "array or null",
102                actual: format!("{other:?}"),
103            }),
104        }
105    }
106
107    fn name(&self) -> &str {
108        "EXEC"
109    }
110}
111
112/// DISCARD
113///
114/// Discards all commands queued in a transaction and exits the transaction
115/// block.
116#[derive(Clone)]
117pub struct Discard;
118
119impl Discard {
120    /// Create a new [`Discard`] command.
121    pub fn new() -> Self {
122        Self
123    }
124}
125
126impl Default for Discard {
127    fn default() -> Self {
128        Self::new()
129    }
130}
131
132impl Command for Discard {
133    type Response = ();
134
135    fn to_frame(&self) -> Frame {
136        array(vec![bulk("DISCARD")])
137    }
138
139    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
140        match frame {
141            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
142            other => Err(RedisError::UnexpectedResponse {
143                expected: "OK",
144                actual: format!("{other:?}"),
145            }),
146        }
147    }
148
149    fn name(&self) -> &str {
150        "DISCARD"
151    }
152}
153
154/// WATCH key [key ...]
155///
156/// Marks the given keys to be watched for conditional execution of a
157/// transaction (optimistic locking).
158#[derive(Clone)]
159pub struct Watch {
160    keys: Vec<CommandArg>,
161}
162
163impl Watch {
164    /// Create a new [`Watch`] command.
165    pub fn new(key: impl Into<CommandArg>) -> Self {
166        Self {
167            keys: vec![key.into()],
168        }
169    }
170
171    /// Create the [`Watch`] command for the supplied keys.
172    pub fn keys(keys: impl IntoIterator<Item = impl Into<CommandArg>>) -> Self {
173        Self {
174            keys: keys.into_iter().map(Into::into).collect(),
175        }
176    }
177}
178
179impl Command for Watch {
180    type Response = ();
181
182    fn to_frame(&self) -> Frame {
183        let mut args = vec![bulk("WATCH")];
184        for key in &self.keys {
185            args.push(bulk(key));
186        }
187        array(args)
188    }
189
190    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
191        match frame {
192            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
193            other => Err(RedisError::UnexpectedResponse {
194                expected: "OK",
195                actual: format!("{other:?}"),
196            }),
197        }
198    }
199
200    fn name(&self) -> &str {
201        "WATCH"
202    }
203}
204
205/// UNWATCH
206///
207/// Flushes all previously watched keys for a transaction.
208#[derive(Clone)]
209pub struct Unwatch;
210
211impl Unwatch {
212    /// Create a new [`Unwatch`] command.
213    pub fn new() -> Self {
214        Self
215    }
216}
217
218impl Default for Unwatch {
219    fn default() -> Self {
220        Self::new()
221    }
222}
223
224impl Command for Unwatch {
225    type Response = ();
226
227    fn to_frame(&self) -> Frame {
228        array(vec![bulk("UNWATCH")])
229    }
230
231    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
232        match frame {
233            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
234            other => Err(RedisError::UnexpectedResponse {
235                expected: "OK",
236                actual: format!("{other:?}"),
237            }),
238        }
239    }
240
241    fn name(&self) -> &str {
242        "UNWATCH"
243    }
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249    use bytes::Bytes;
250    use redis_tower_core::Command;
251    use redis_tower_protocol::Frame;
252    use redis_tower_protocol::helpers::{array, bulk};
253
254    // -- Multi --
255
256    #[test]
257    fn multi_to_frame() {
258        let cmd = Multi::new();
259        assert_eq!(cmd.to_frame(), array(vec![bulk("MULTI")]));
260    }
261
262    #[test]
263    fn multi_parse_ok() {
264        let cmd = Multi::new();
265        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
266            .unwrap();
267    }
268
269    #[test]
270    fn multi_parse_error_on_integer() {
271        let cmd = Multi::new();
272        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
273    }
274
275    // -- Exec --
276
277    #[test]
278    fn exec_to_frame() {
279        let cmd = Exec::new();
280        assert_eq!(cmd.to_frame(), array(vec![bulk("EXEC")]));
281    }
282
283    #[test]
284    fn exec_parse_results() {
285        let cmd = Exec::new();
286        let frame = array(vec![Frame::Integer(1), Frame::Integer(2)]);
287        let result = cmd.parse_response(frame).unwrap();
288        assert_eq!(result, Some(vec![Frame::Integer(1), Frame::Integer(2)]));
289    }
290
291    #[test]
292    fn exec_parse_aborted() {
293        let cmd = Exec::new();
294        assert_eq!(cmd.parse_response(Frame::Array(None)).unwrap(), None);
295        assert_eq!(cmd.parse_response(Frame::Null).unwrap(), None);
296    }
297
298    // -- Discard --
299
300    #[test]
301    fn discard_to_frame() {
302        let cmd = Discard::new();
303        assert_eq!(cmd.to_frame(), array(vec![bulk("DISCARD")]));
304    }
305
306    #[test]
307    fn discard_parse_ok() {
308        let cmd = Discard::new();
309        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
310            .unwrap();
311    }
312
313    // -- Watch --
314
315    #[test]
316    fn watch_single_to_frame() {
317        let cmd = Watch::new("k1");
318        assert_eq!(cmd.to_frame(), array(vec![bulk("WATCH"), bulk("k1")]));
319    }
320
321    #[test]
322    fn watch_multiple_to_frame() {
323        let cmd = Watch::keys(vec!["k1", "k2"]);
324        assert_eq!(
325            cmd.to_frame(),
326            array(vec![bulk("WATCH"), bulk("k1"), bulk("k2")])
327        );
328    }
329
330    #[test]
331    fn watch_parse_ok() {
332        let cmd = Watch::new("k1");
333        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
334            .unwrap();
335    }
336
337    // -- Unwatch --
338
339    #[test]
340    fn unwatch_to_frame() {
341        let cmd = Unwatch::new();
342        assert_eq!(cmd.to_frame(), array(vec![bulk("UNWATCH")]));
343    }
344
345    #[test]
346    fn unwatch_parse_ok() {
347        let cmd = Unwatch::new();
348        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
349            .unwrap();
350    }
351}