Skip to main content

redis_tower/
transaction.rs

1//! Redis transactions (MULTI/EXEC) with optional WATCH support.
2//!
3//! [`Transaction`] builds a sequence of commands that are executed atomically
4//! via MULTI/EXEC. [`Transaction::watch`] protects a body that is already
5//! known; if any watched key is modified before EXEC, the transaction is
6//! aborted and [`TransactionResult::Aborted`] is returned. Read/compute/build
7//! optimistic locking uses [`transaction`] with an exclusive connection.
8//!
9//! # Example
10//!
11//! ```no_run
12//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
13//! use redis_tower::{Transaction, RedisConnection, commands::*};
14//!
15//! let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
16//! let result = Transaction::new()
17//!     .push(Set::new("x", "1"))
18//!     .push(Incr::new("x"))
19//!     .execute(&mut conn)
20//!     .await?;
21//! # let _ = result;
22//! # Ok(())
23//! # }
24//! ```
25
26use std::any::Any;
27use std::future::Future;
28use std::sync::Arc;
29
30use redis_tower_commands::{CommandArg, Watch};
31use redis_tower_core::{Command, Frame, RedisConnection, RedisError};
32use redis_tower_protocol::helpers::{array, bulk};
33use tokio::sync::Mutex;
34
35use crate::client::RedisClient;
36use crate::executor::RedisExecutor;
37use crate::pipeline::{PipelineResults, ResponseParser};
38
39/// A connection type that can execute a WATCH/MULTI/EXEC transaction.
40///
41/// Implemented by [`RedisConnection`]. The `Arc<Mutex<C>>` blanket impl
42/// and the [`RedisClient`] impl allow shared clients to be passed directly
43/// to [`Transaction::execute`].
44///
45/// ## Exclusive access
46///
47/// Transactions require exclusive access to a single connection for the
48/// duration of WATCH/MULTI/EXEC. Direct [`Transaction::execute`] calls satisfy
49/// this on the shared implementations by submitting or locking the complete
50/// exchange at once. The closure-based [`transaction`] helpers additionally
51/// span a user-supplied read/build window and are therefore available only on
52/// executors that can reserve one connection across separate calls.
53pub trait TransactionExecutor {
54    /// Whether the executor can keep a standalone WATCH active on the same
55    /// physical connection across the read/build window used by
56    /// [`transaction`] and [`transaction_with_retries`].
57    ///
58    /// Shared and routed executors set this to `false`: locking or routing each
59    /// call independently cannot reserve one connection from WATCH through
60    /// EXEC. Direct [`Transaction::watch`] remains safe for a body that is
61    /// already known because all of its WATCH/MULTI/EXEC frames are handed to
62    /// [`execute_transaction`](Self::execute_transaction) in one call.
63    const SUPPORTS_TRANSACTION_RETRY: bool = true;
64
65    /// Reject the closure-based transaction helpers before WATCH or any other
66    /// command is sent when this executor cannot reserve their full window.
67    fn validate_transaction_retry(&self) -> Result<(), RedisError> {
68        if Self::SUPPORTS_TRANSACTION_RETRY {
69            Ok(())
70        } else {
71            Err(RedisError::Redis(
72                "transaction() and transaction_with_retries() are unsupported by this executor; Transaction::watch() is safe only when the body is already known; use an exclusive RedisConnection for WATCH/read/build retries"
73                    .to_string(),
74            ))
75        }
76    }
77
78    /// Execute a WATCH/MULTI/EXEC transaction.
79    ///
80    /// `watch_frames` is the serialized WATCH command (empty if no WATCH keys).
81    /// `command_frames` are the commands to queue between MULTI and EXEC.
82    ///
83    /// Returns `Ok(Some(responses))` if the transaction committed,
84    /// `Ok(None)` if it was aborted by a WATCH violation.
85    fn execute_transaction(
86        &mut self,
87        watch_frames: Vec<Frame>,
88        command_frames: Vec<Frame>,
89    ) -> impl Future<Output = Result<Option<Vec<Frame>>, RedisError>> + Send;
90}
91
92impl TransactionExecutor for RedisConnection {
93    fn execute_transaction(
94        &mut self,
95        watch_frames: Vec<Frame>,
96        command_frames: Vec<Frame>,
97    ) -> impl Future<Output = Result<Option<Vec<Frame>>, RedisError>> + Send {
98        RedisConnection::execute_transaction(self, watch_frames, command_frames)
99    }
100}
101
102impl<C: TransactionExecutor + Send> TransactionExecutor for Arc<Mutex<C>> {
103    const SUPPORTS_TRANSACTION_RETRY: bool = false;
104
105    fn execute_transaction(
106        &mut self,
107        watch_frames: Vec<Frame>,
108        command_frames: Vec<Frame>,
109    ) -> impl Future<Output = Result<Option<Vec<Frame>>, RedisError>> + Send {
110        let arc = Arc::clone(self);
111        async move {
112            arc.lock()
113                .await
114                .execute_transaction(watch_frames, command_frames)
115                .await
116        }
117    }
118}
119
120impl TransactionExecutor for RedisClient {
121    const SUPPORTS_TRANSACTION_RETRY: bool = false;
122
123    fn execute_transaction(
124        &mut self,
125        watch_frames: Vec<Frame>,
126        command_frames: Vec<Frame>,
127    ) -> impl Future<Output = Result<Option<Vec<Frame>>, RedisError>> + Send {
128        let arc = Arc::clone(&self.inner);
129        async move {
130            arc.lock()
131                .await
132                .execute_transaction(watch_frames, command_frames)
133                .await
134        }
135    }
136}
137
138/// A type-erased command entry for transactions.
139struct TransactionEntry {
140    frame: Frame,
141    parser: ResponseParser,
142}
143
144/// Builds and executes a Redis transaction (MULTI/EXEC).
145///
146/// Supports optional WATCH keys for optimistic locking. If a watched key
147/// is modified by another client before EXEC, the transaction is aborted
148/// and [`TransactionResult::Aborted`] is returned.
149///
150/// Accepts any type that implements [`TransactionExecutor`], including
151/// [`RedisConnection`], [`RedisClient`], and `Arc<Mutex<C>>` for any
152/// `C: TransactionExecutor + Send`.
153///
154/// # Example
155///
156/// ```no_run
157/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
158/// use redis_tower::{Transaction, TransactionResult, RedisConnection};
159/// use redis_tower::commands::*;
160///
161/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
162/// let result = Transaction::new()
163///     .push(Set::new("x", "1"))
164///     .push(Incr::new("x"))
165///     .execute(&mut conn)
166///     .await?;
167///
168/// match result {
169///     TransactionResult::Committed(results) => {
170///         let val: &i64 = results.get(1)?;
171///         assert_eq!(*val, 2);
172///     }
173///     TransactionResult::Aborted => {
174///         // WATCH key was modified
175///     }
176/// }
177/// # Ok(())
178/// # }
179/// ```
180pub struct Transaction {
181    watch_keys: Vec<CommandArg>,
182    entries: Vec<TransactionEntry>,
183}
184
185/// The outcome of a transaction execution.
186#[must_use = "transaction result must be handled"]
187pub enum TransactionResult {
188    /// Transaction committed successfully. Results can be extracted by index.
189    Committed(PipelineResults),
190    /// Transaction was aborted because a WATCHed key was modified.
191    Aborted,
192}
193
194impl TransactionResult {
195    /// Returns `Some(results)` if the transaction committed, `None` if aborted.
196    pub fn committed(self) -> Option<PipelineResults> {
197        match self {
198            TransactionResult::Committed(results) => Some(results),
199            TransactionResult::Aborted => None,
200        }
201    }
202
203    /// Returns `true` if the transaction was aborted due to a WATCH violation.
204    pub fn is_aborted(&self) -> bool {
205        matches!(self, TransactionResult::Aborted)
206    }
207
208    /// Returns `true` if the transaction committed successfully.
209    pub fn is_committed(&self) -> bool {
210        matches!(self, TransactionResult::Committed(_))
211    }
212
213    /// Unwraps the committed results, panicking if the transaction was aborted.
214    ///
215    /// # Panics
216    ///
217    /// Panics if the transaction was aborted. Use this only in tests or when
218    /// the transaction cannot possibly be aborted (no WATCH keys).
219    #[track_caller]
220    pub fn unwrap(self) -> PipelineResults {
221        match self {
222            TransactionResult::Committed(results) => results,
223            TransactionResult::Aborted => {
224                panic!("called `TransactionResult::unwrap()` on an `Aborted` value")
225            }
226        }
227    }
228}
229
230impl Transaction {
231    /// Create a new empty transaction.
232    pub fn new() -> Self {
233        Self {
234            watch_keys: Vec::new(),
235            entries: Vec::new(),
236        }
237    }
238
239    /// Watch keys for optimistic locking.
240    ///
241    /// If any watched key is modified by another client between the WATCH
242    /// and the EXEC, the transaction will be aborted.
243    pub fn watch(mut self, keys: impl IntoIterator<Item = impl Into<CommandArg>>) -> Self {
244        self.watch_keys.extend(keys.into_iter().map(Into::into));
245        self
246    }
247
248    /// Add a command to the transaction. Returns `self` for chaining.
249    pub fn push<Cmd: Command + 'static>(mut self, cmd: Cmd) -> Self {
250        let frame = cmd.to_frame();
251        let parser = Box::new(
252            move |response: Frame| -> Result<Box<dyn Any + Send>, RedisError> {
253                let result = cmd.parse_response(response)?;
254                Ok(Box::new(result))
255            },
256        );
257        self.entries.push(TransactionEntry { frame, parser });
258        self
259    }
260
261    /// Execute the transaction.
262    ///
263    /// Accepts any [`TransactionExecutor`]: [`RedisConnection`], [`RedisClient`],
264    /// `Arc<Mutex<RedisConnection>>`, etc.
265    ///
266    /// Sends WATCH (if any), MULTI, all queued commands, and EXEC
267    /// atomically under a single connection lock. For `Arc<Mutex<C>>`-based
268    /// executors, the mutex is held for the entire WATCH/MULTI/EXEC sequence,
269    /// preventing any interleaving with other callers.
270    pub async fn execute<E: TransactionExecutor>(
271        self,
272        conn: &mut E,
273    ) -> Result<TransactionResult, RedisError> {
274        // Build WATCH frames.
275        let watch_frames: Vec<Frame> = if self.watch_keys.is_empty() {
276            Vec::new()
277        } else {
278            let mut args = vec![bulk("WATCH")];
279            for key in &self.watch_keys {
280                args.push(bulk(key));
281            }
282            vec![array(args)]
283        };
284
285        let command_frames: Vec<Frame> = self.entries.iter().map(|e| e.frame.clone()).collect();
286
287        let exec_result = conn
288            .execute_transaction(watch_frames, command_frames)
289            .await?;
290
291        match exec_result {
292            None => Ok(TransactionResult::Aborted),
293            Some(responses) => {
294                let mut results = Vec::with_capacity(responses.len());
295                for (entry, response) in self.entries.into_iter().zip(responses) {
296                    if let Frame::Error(ref e) = response {
297                        results.push(Err(RedisError::Redis(
298                            String::from_utf8_lossy(e).into_owned(),
299                        )));
300                    } else {
301                        results.push((entry.parser)(response));
302                    }
303                }
304                Ok(TransactionResult::Committed(PipelineResults::from_raw(
305                    results,
306                )))
307            }
308        }
309    }
310
311    /// Returns the number of queued commands.
312    pub fn len(&self) -> usize {
313        self.entries.len()
314    }
315
316    /// Returns true if no commands are queued.
317    pub fn is_empty(&self) -> bool {
318        self.entries.is_empty()
319    }
320}
321
322impl Default for Transaction {
323    fn default() -> Self {
324        Self::new()
325    }
326}
327
328/// Default number of WATCH/EXEC attempts used by [`transaction`] before it
329/// gives up and returns [`RedisError::TransactionAborted`].
330pub const DEFAULT_TRANSACTION_RETRIES: usize = 16;
331
332/// Run a WATCH-protected transaction, retrying on optimistic-lock conflicts.
333///
334/// This is the ergonomic port of redis-rs's `transaction`/`transaction_async`
335/// helpers. It implements the standard optimistic-locking loop:
336///
337/// 1. `WATCH` the given keys.
338/// 2. Call `build`, which may read the watched keys on `conn` and returns the
339///    [`Transaction`] body to commit (the commands to run between MULTI/EXEC).
340/// 3. Run MULTI/EXEC. If a watched key was modified by another client, EXEC is
341///    aborted and the whole sequence is retried from step 1.
342///
343/// The loop runs until EXEC commits or the retry cap is reached. On a commit it
344/// returns the [`PipelineResults`]; if the cap is exhausted it returns
345/// [`RedisError::TransactionAborted`].
346///
347/// Because the reads in `build` must happen *inside* the WATCH window, `conn`
348/// must be an exclusively held connection for the duration of the call -- pass
349/// a [`RedisConnection`] (`&mut`) or otherwise ensure no other task issues
350/// commands on the same connection while the transaction is in flight. (This is
351/// the same requirement redis-rs places on its `transaction` helper.) The
352/// returned `Transaction` should carry the commands only; the WATCH is issued
353/// by this helper, so do not also call [`Transaction::watch`] on it.
354/// Shared or routed executors that cannot reserve this complete window reject
355/// the helper before WATCH is sent or `build` is invoked. A direct
356/// [`Transaction::watch`] is suitable only when its body is already known; use
357/// a dedicated [`RedisConnection`] for read/compute/build retries.
358///
359/// Uses [`DEFAULT_TRANSACTION_RETRIES`] as the cap. Use
360/// [`transaction_with_retries`] to choose a different cap.
361///
362/// # Example
363///
364/// ```no_run
365/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
366/// use redis_tower::{transaction, Transaction, RedisConnection};
367/// use redis_tower::commands::{Get, Set};
368///
369/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
370///
371/// // Atomically double the value at `counter`, retrying if another client
372/// // touches it between the read and the EXEC.
373/// let results = transaction(&mut conn, ["counter"], async |c| {
374///     let current: i64 = match c.execute(Get::new("counter")).await? {
375///         Some(bytes) => String::from_utf8_lossy(&bytes).parse().unwrap_or(0),
376///         None => 0,
377///     };
378///     Ok(Transaction::new().push(Set::new("counter", (current * 2).to_string())))
379/// })
380/// .await?;
381/// # let _ = results;
382/// # Ok(())
383/// # }
384/// ```
385pub async fn transaction<C, F>(
386    conn: &mut C,
387    keys: impl IntoIterator<Item = impl Into<CommandArg>>,
388    build: F,
389) -> Result<PipelineResults, RedisError>
390where
391    C: RedisExecutor + TransactionExecutor + Send,
392    F: AsyncFnMut(&mut C) -> Result<Transaction, RedisError>,
393{
394    transaction_with_retries(conn, keys, DEFAULT_TRANSACTION_RETRIES, build).await
395}
396
397/// Like [`transaction`], but with an explicit retry cap.
398///
399/// `max_retries` is the number of *additional* attempts made after the first,
400/// so the closure is invoked at most `max_retries + 1` times. A cap of `0`
401/// makes a single attempt and surfaces a WATCH abort immediately as
402/// [`RedisError::TransactionAborted`].
403///
404/// See [`transaction`] for the full contract.
405pub async fn transaction_with_retries<C, F>(
406    conn: &mut C,
407    keys: impl IntoIterator<Item = impl Into<CommandArg>>,
408    max_retries: usize,
409    mut build: F,
410) -> Result<PipelineResults, RedisError>
411where
412    C: RedisExecutor + TransactionExecutor + Send,
413    F: AsyncFnMut(&mut C) -> Result<Transaction, RedisError>,
414{
415    // Some routed executors cannot reserve one physical connection across the
416    // standalone WATCH, user-supplied read/build closure, and later EXEC. Fail
417    // before WATCH or any closure side effect instead of silently weakening
418    // optimistic locking.
419    conn.validate_transaction_retry()?;
420
421    let keys: Vec<CommandArg> = keys.into_iter().map(Into::into).collect();
422    let mut remaining = max_retries;
423
424    loop {
425        // WATCH the keys so the reads in `build` are covered by the optimistic
426        // lock. Skip the round-trip entirely when there is nothing to watch.
427        if !keys.is_empty() {
428            conn.execute(Watch::keys(keys.clone())).await?;
429        }
430
431        // Build the atomic body. The closure may read the watched keys here.
432        let txn = build(conn).await?;
433
434        // Run MULTI/EXEC. The WATCH issued above is still active on the
435        // connection, so the body carries no watch keys of its own.
436        match txn.execute(&mut *conn).await? {
437            TransactionResult::Committed(results) => return Ok(results),
438            TransactionResult::Aborted => {
439                // A watched key changed. EXEC already cleared the WATCH state,
440                // so the next iteration re-watches from scratch.
441                if remaining == 0 {
442                    return Err(RedisError::TransactionAborted);
443                }
444                remaining -= 1;
445            }
446        }
447    }
448}
449
450#[cfg(test)]
451mod tests {
452    use super::*;
453
454    #[cfg(unix)]
455    fn connected_pair() -> (RedisConnection, tokio::net::UnixStream) {
456        let (client, server) = tokio::net::UnixStream::pair().unwrap();
457        (
458            RedisConnection::from_stream(redis_tower_core::RedisStream::Unix(client)),
459            server,
460        )
461    }
462
463    #[cfg(unix)]
464    async fn assert_no_wire_request(mut server: tokio::net::UnixStream) {
465        use tokio::io::AsyncReadExt;
466
467        let mut bytes = [0u8; 128];
468        assert!(
469            tokio::time::timeout(
470                std::time::Duration::from_millis(25),
471                server.read(&mut bytes),
472            )
473            .await
474            .is_err(),
475            "transaction helper wrote to Redis before rejecting the executor"
476        );
477    }
478
479    fn assert_retry_helper_unsupported(result: &Result<PipelineResults, RedisError>) {
480        let error = match result {
481            Err(error) => error,
482            Ok(_) => panic!("shared executor was accepted"),
483        };
484        let message = error.to_string();
485        assert!(message.contains("transaction_with_retries()"));
486        assert!(message.contains("Transaction::watch()"));
487    }
488
489    fn committed() -> TransactionResult {
490        TransactionResult::Committed(PipelineResults::from_raw(Vec::new()))
491    }
492
493    #[test]
494    fn retry_helper_capability_is_limited_to_exclusive_connections() {
495        const {
496            assert!(<RedisConnection as TransactionExecutor>::SUPPORTS_TRANSACTION_RETRY);
497            assert!(!<RedisClient as TransactionExecutor>::SUPPORTS_TRANSACTION_RETRY);
498            assert!(!<crate::MultiplexedClient as TransactionExecutor>::SUPPORTS_TRANSACTION_RETRY);
499            assert!(
500                !<Arc<Mutex<RedisConnection>> as TransactionExecutor>::SUPPORTS_TRANSACTION_RETRY
501            );
502        }
503    }
504
505    #[test]
506    fn committed_returns_some_for_committed() {
507        assert!(committed().committed().is_some());
508    }
509
510    #[test]
511    fn committed_returns_none_for_aborted() {
512        assert!(TransactionResult::Aborted.committed().is_none());
513    }
514
515    #[test]
516    fn is_aborted_reports_correctly() {
517        assert!(TransactionResult::Aborted.is_aborted());
518        assert!(!committed().is_aborted());
519    }
520
521    #[test]
522    fn is_committed_reports_correctly() {
523        assert!(committed().is_committed());
524        assert!(!TransactionResult::Aborted.is_committed());
525    }
526
527    #[test]
528    fn unwrap_succeeds_on_committed() {
529        let results = committed().unwrap();
530        assert!(results.is_empty());
531    }
532
533    #[test]
534    #[should_panic(expected = "Aborted")]
535    fn unwrap_panics_on_aborted() {
536        let _ = TransactionResult::Aborted.unwrap();
537    }
538
539    /// A mock transaction executor for unit tests.
540    struct MockTransactionConn {
541        /// Simulates committed responses (one per command frame).
542        responses: Option<Vec<Frame>>,
543    }
544
545    impl TransactionExecutor for MockTransactionConn {
546        fn execute_transaction(
547            &mut self,
548            _watch_frames: Vec<Frame>,
549            command_frames: Vec<Frame>,
550        ) -> impl Future<Output = Result<Option<Vec<Frame>>, RedisError>> + Send {
551            let responses = self.responses.take().map(|_| {
552                // Return one SimpleString "OK" per queued command.
553                command_frames
554                    .iter()
555                    .map(|_| Frame::SimpleString(bytes::Bytes::from("OK")))
556                    .collect::<Vec<_>>()
557            });
558            async move { Ok(responses) }
559        }
560    }
561
562    #[derive(Default)]
563    struct CapturingBinaryTransactionConn {
564        direct_watch_frames: Vec<Frame>,
565        helper_watch_frames: Vec<Frame>,
566    }
567
568    impl RedisExecutor for CapturingBinaryTransactionConn {
569        fn execute<Cmd: Command>(
570            &mut self,
571            cmd: Cmd,
572        ) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
573            self.helper_watch_frames.push(cmd.to_frame());
574            let response = cmd.parse_response(Frame::SimpleString(bytes::Bytes::from("OK")));
575            async move { response }
576        }
577    }
578
579    impl TransactionExecutor for CapturingBinaryTransactionConn {
580        fn execute_transaction(
581            &mut self,
582            watch_frames: Vec<Frame>,
583            command_frames: Vec<Frame>,
584        ) -> impl Future<Output = Result<Option<Vec<Frame>>, RedisError>> + Send {
585            self.direct_watch_frames.extend(watch_frames);
586            let responses = command_frames
587                .iter()
588                .map(|_| Frame::SimpleString(bytes::Bytes::from("OK")))
589                .collect();
590            async move { Ok(Some(responses)) }
591        }
592    }
593
594    #[tokio::test]
595    async fn transaction_wrappers_preserve_binary_watch_keys() {
596        let key = b"watch\0\xff\r\nkey".as_slice();
597        let expected = array(vec![bulk("WATCH"), bulk(key)]);
598
599        let mut direct = CapturingBinaryTransactionConn::default();
600        let _ = Transaction::new()
601            .watch([key])
602            .execute(&mut direct)
603            .await
604            .unwrap();
605        assert_eq!(direct.direct_watch_frames, std::slice::from_ref(&expected));
606
607        let mut helper = CapturingBinaryTransactionConn::default();
608        transaction(&mut helper, [key], async |_conn| Ok(Transaction::new()))
609            .await
610            .unwrap();
611        assert_eq!(helper.helper_watch_frames, [expected]);
612    }
613
614    #[tokio::test]
615    async fn transaction_execute_accepts_transaction_executor() {
616        use redis_tower_commands::Set;
617
618        let mut conn = MockTransactionConn {
619            responses: Some(vec![]),
620        };
621        let result = Transaction::new()
622            .push(Set::new("x", "1"))
623            .execute(&mut conn)
624            .await
625            .unwrap();
626        assert!(result.is_committed());
627    }
628
629    #[tokio::test]
630    async fn transaction_execute_accepts_arc_mutex_executor() {
631        use redis_tower_commands::Set;
632
633        let conn = Arc::new(Mutex::new(MockTransactionConn {
634            responses: Some(vec![]),
635        }));
636        let mut executor = Arc::clone(&conn);
637        let result = Transaction::new()
638            .push(Set::new("x", "1"))
639            .execute(&mut executor)
640            .await
641            .unwrap();
642        assert!(result.is_committed());
643    }
644
645    /// A mock that also implements [`RedisExecutor`] (for the WATCH/read path)
646    /// and can be scripted to abort a fixed number of EXECs before committing,
647    /// so the [`transaction`] retry loop can be exercised without a server.
648    struct RetryMockConn {
649        /// Number of EXECs to abort (WATCH violation) before the next commits.
650        aborts_before_commit: usize,
651        /// How many `execute_transaction` calls were made.
652        exec_calls: usize,
653        /// How many plain commands (i.e. WATCH) were issued via `execute`.
654        watch_calls: usize,
655    }
656
657    impl RedisExecutor for RetryMockConn {
658        fn execute<Cmd: Command>(
659            &mut self,
660            cmd: Cmd,
661        ) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
662            self.watch_calls += 1;
663            // Only WATCH is exercised in these tests; reply OK to it.
664            let result = cmd.parse_response(Frame::SimpleString(bytes::Bytes::from("OK")));
665            async move { result }
666        }
667    }
668
669    impl TransactionExecutor for RetryMockConn {
670        fn execute_transaction(
671            &mut self,
672            _watch_frames: Vec<Frame>,
673            command_frames: Vec<Frame>,
674        ) -> impl Future<Output = Result<Option<Vec<Frame>>, RedisError>> + Send {
675            self.exec_calls += 1;
676            let abort = self.aborts_before_commit > 0;
677            if abort {
678                self.aborts_before_commit -= 1;
679            }
680            let responses = if abort {
681                // EXEC aborted by a WATCH violation.
682                None
683            } else {
684                Some(
685                    command_frames
686                        .iter()
687                        .map(|_| Frame::SimpleString(bytes::Bytes::from("OK")))
688                        .collect::<Vec<_>>(),
689                )
690            };
691            async move { Ok(responses) }
692        }
693    }
694
695    #[tokio::test]
696    async fn transaction_helper_rejects_arc_mutex_before_watch_or_build() {
697        use std::sync::atomic::{AtomicUsize, Ordering};
698
699        let inner = Arc::new(Mutex::new(RetryMockConn {
700            aborts_before_commit: 0,
701            exec_calls: 0,
702            watch_calls: 0,
703        }));
704        let mut shared = Arc::clone(&inner);
705        let build_calls = Arc::new(AtomicUsize::new(0));
706        let build_counter = Arc::clone(&build_calls);
707
708        let result = transaction_with_retries(
709            &mut shared,
710            ["key"],
711            0,
712            async move |_conn: &mut Arc<Mutex<RetryMockConn>>| {
713                build_counter.fetch_add(1, Ordering::SeqCst);
714                Ok(Transaction::new())
715            },
716        )
717        .await;
718
719        assert_retry_helper_unsupported(&result);
720        assert_eq!(build_calls.load(Ordering::SeqCst), 0);
721        let inner = inner.lock().await;
722        assert_eq!(inner.watch_calls, 0);
723        assert_eq!(inner.exec_calls, 0);
724    }
725
726    #[tokio::test]
727    #[cfg(unix)]
728    async fn transaction_helper_rejects_redis_client_before_watch_or_build() {
729        use std::sync::atomic::{AtomicUsize, Ordering};
730
731        let (conn, server) = connected_pair();
732        let mut client = RedisClient::from_connection(conn);
733        let build_calls = Arc::new(AtomicUsize::new(0));
734        let build_counter = Arc::clone(&build_calls);
735
736        let result = transaction_with_retries(
737            &mut client,
738            ["key"],
739            0,
740            async move |_conn: &mut RedisClient| {
741                build_counter.fetch_add(1, Ordering::SeqCst);
742                Ok(Transaction::new())
743            },
744        )
745        .await;
746
747        assert_retry_helper_unsupported(&result);
748        assert_eq!(build_calls.load(Ordering::SeqCst), 0);
749        assert_no_wire_request(server).await;
750    }
751
752    #[tokio::test]
753    #[cfg(unix)]
754    async fn transaction_helper_rejects_multiplexed_client_before_watch_or_build() {
755        use std::sync::atomic::{AtomicUsize, Ordering};
756
757        let (conn, server) = connected_pair();
758        let mut client = crate::MultiplexedClient::from_connection(conn);
759        let build_calls = Arc::new(AtomicUsize::new(0));
760        let build_counter = Arc::clone(&build_calls);
761
762        let result = transaction_with_retries(
763            &mut client,
764            ["key"],
765            0,
766            async move |_conn: &mut crate::MultiplexedClient| {
767                build_counter.fetch_add(1, Ordering::SeqCst);
768                Ok(Transaction::new())
769            },
770        )
771        .await;
772
773        assert_retry_helper_unsupported(&result);
774        assert_eq!(build_calls.load(Ordering::SeqCst), 0);
775        assert_no_wire_request(server).await;
776        client.shutdown().await;
777    }
778
779    #[tokio::test]
780    async fn transaction_commits_on_first_attempt() {
781        use redis_tower_commands::Set;
782
783        let mut conn = RetryMockConn {
784            aborts_before_commit: 0,
785            exec_calls: 0,
786            watch_calls: 0,
787        };
788        let results = transaction(&mut conn, ["counter"], async |_c| {
789            Ok(Transaction::new().push(Set::new("counter", "1")))
790        })
791        .await
792        .unwrap();
793
794        assert_eq!(results.len(), 1);
795        assert_eq!(conn.exec_calls, 1, "should EXEC exactly once");
796        assert_eq!(conn.watch_calls, 1, "should WATCH exactly once");
797    }
798
799    #[tokio::test]
800    async fn transaction_retries_until_commit() {
801        use std::sync::atomic::{AtomicUsize, Ordering};
802
803        use redis_tower_commands::Set;
804
805        let mut conn = RetryMockConn {
806            aborts_before_commit: 2,
807            exec_calls: 0,
808            watch_calls: 0,
809        };
810        let build_calls = Arc::new(AtomicUsize::new(0));
811        let bc = Arc::clone(&build_calls);
812
813        let results = transaction(&mut conn, ["k"], async move |_c: &mut RetryMockConn| {
814            bc.fetch_add(1, Ordering::SeqCst);
815            Ok(Transaction::new().push(Set::new("k", "1")))
816        })
817        .await
818        .unwrap();
819
820        assert_eq!(results.len(), 1);
821        // Two aborts then a commit -> three attempts, each re-WATCHing.
822        assert_eq!(build_calls.load(Ordering::SeqCst), 3);
823        assert_eq!(conn.exec_calls, 3);
824        assert_eq!(conn.watch_calls, 3);
825    }
826
827    #[tokio::test]
828    async fn transaction_gives_up_after_retry_cap() {
829        use std::sync::atomic::{AtomicUsize, Ordering};
830
831        use redis_tower_commands::Set;
832
833        let mut conn = RetryMockConn {
834            // Always aborts -- the cap, not a commit, must terminate the loop.
835            aborts_before_commit: usize::MAX,
836            exec_calls: 0,
837            watch_calls: 0,
838        };
839        let build_calls = Arc::new(AtomicUsize::new(0));
840        let bc = Arc::clone(&build_calls);
841
842        let result =
843            transaction_with_retries(&mut conn, ["k"], 2, async move |_c: &mut RetryMockConn| {
844                bc.fetch_add(1, Ordering::SeqCst);
845                Ok(Transaction::new().push(Set::new("k", "1")))
846            })
847            .await;
848
849        assert!(matches!(result, Err(RedisError::TransactionAborted)));
850        // First attempt + 2 retries = 3 invocations.
851        assert_eq!(build_calls.load(Ordering::SeqCst), 3);
852        assert_eq!(conn.exec_calls, 3);
853    }
854
855    #[tokio::test]
856    async fn transaction_without_keys_skips_watch() {
857        use redis_tower_commands::Set;
858
859        let mut conn = RetryMockConn {
860            aborts_before_commit: 0,
861            exec_calls: 0,
862            watch_calls: 0,
863        };
864        let empty: [&str; 0] = [];
865        let results = transaction(&mut conn, empty, async |_c| {
866            Ok(Transaction::new().push(Set::new("k", "1")))
867        })
868        .await
869        .unwrap();
870
871        assert_eq!(results.len(), 1);
872        assert_eq!(conn.exec_calls, 1);
873        assert_eq!(conn.watch_calls, 0, "no keys means no WATCH round-trip");
874    }
875
876    #[tokio::test]
877    async fn transaction_zero_retries_surfaces_abort_immediately() {
878        use redis_tower_commands::Set;
879
880        let mut conn = RetryMockConn {
881            aborts_before_commit: usize::MAX,
882            exec_calls: 0,
883            watch_calls: 0,
884        };
885        let result = transaction_with_retries(&mut conn, ["k"], 0, async |_c| {
886            Ok(Transaction::new().push(Set::new("k", "1")))
887        })
888        .await;
889
890        assert!(matches!(result, Err(RedisError::TransactionAborted)));
891        assert_eq!(conn.exec_calls, 1, "cap of 0 makes a single attempt");
892    }
893}