redis-tower 0.1.2

A Tower-based Redis client with strong typing, composable middleware, and resilience
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
//! Redis transactions (MULTI/EXEC) with optional WATCH support.
//!
//! [`Transaction`] builds a sequence of commands that are executed atomically
//! via MULTI/EXEC. [`Transaction::watch`] protects a body that is already
//! known; if any watched key is modified before EXEC, the transaction is
//! aborted and [`TransactionResult::Aborted`] is returned. Read/compute/build
//! optimistic locking uses [`transaction`] with an exclusive connection.
//!
//! # Example
//!
//! ```no_run
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! use redis_tower::{Transaction, RedisConnection, commands::*};
//!
//! let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
//! let result = Transaction::new()
//!     .push(Set::new("x", "1"))
//!     .push(Incr::new("x"))
//!     .execute(&mut conn)
//!     .await?;
//! # let _ = result;
//! # Ok(())
//! # }
//! ```

use std::any::Any;
use std::future::Future;
use std::sync::Arc;

use redis_tower_commands::Watch;
use redis_tower_core::{Command, Frame, RedisConnection, RedisError};
use redis_tower_protocol::helpers::{array, bulk};
use tokio::sync::Mutex;

use crate::client::RedisClient;
use crate::executor::RedisExecutor;
use crate::pipeline::{PipelineResults, ResponseParser};

/// A connection type that can execute a WATCH/MULTI/EXEC transaction.
///
/// Implemented by [`RedisConnection`]. The `Arc<Mutex<C>>` blanket impl
/// and the [`RedisClient`] impl allow shared clients to be passed directly
/// to [`Transaction::execute`].
///
/// ## Exclusive access
///
/// Transactions require exclusive access to a single connection for the
/// duration of WATCH/MULTI/EXEC. Direct [`Transaction::execute`] calls satisfy
/// this on the shared implementations by submitting or locking the complete
/// exchange at once. The closure-based [`transaction`] helpers additionally
/// span a user-supplied read/build window and are therefore available only on
/// executors that can reserve one connection across separate calls.
pub trait TransactionExecutor {
    /// Whether the executor can keep a standalone WATCH active on the same
    /// physical connection across the read/build window used by
    /// [`transaction`] and [`transaction_with_retries`].
    ///
    /// Shared and routed executors set this to `false`: locking or routing each
    /// call independently cannot reserve one connection from WATCH through
    /// EXEC. Direct [`Transaction::watch`] remains safe for a body that is
    /// already known because all of its WATCH/MULTI/EXEC frames are handed to
    /// [`execute_transaction`](Self::execute_transaction) in one call.
    const SUPPORTS_TRANSACTION_RETRY: bool = true;

    /// Reject the closure-based transaction helpers before WATCH or any other
    /// command is sent when this executor cannot reserve their full window.
    fn validate_transaction_retry(&self) -> Result<(), RedisError> {
        if Self::SUPPORTS_TRANSACTION_RETRY {
            Ok(())
        } else {
            Err(RedisError::Redis(
                "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"
                    .to_string(),
            ))
        }
    }

    /// Execute a WATCH/MULTI/EXEC transaction.
    ///
    /// `watch_frames` is the serialized WATCH command (empty if no WATCH keys).
    /// `command_frames` are the commands to queue between MULTI and EXEC.
    ///
    /// Returns `Ok(Some(responses))` if the transaction committed,
    /// `Ok(None)` if it was aborted by a WATCH violation.
    fn execute_transaction(
        &mut self,
        watch_frames: Vec<Frame>,
        command_frames: Vec<Frame>,
    ) -> impl Future<Output = Result<Option<Vec<Frame>>, RedisError>> + Send;
}

impl TransactionExecutor for RedisConnection {
    fn execute_transaction(
        &mut self,
        watch_frames: Vec<Frame>,
        command_frames: Vec<Frame>,
    ) -> impl Future<Output = Result<Option<Vec<Frame>>, RedisError>> + Send {
        RedisConnection::execute_transaction(self, watch_frames, command_frames)
    }
}

impl<C: TransactionExecutor + Send> TransactionExecutor for Arc<Mutex<C>> {
    const SUPPORTS_TRANSACTION_RETRY: bool = false;

    fn execute_transaction(
        &mut self,
        watch_frames: Vec<Frame>,
        command_frames: Vec<Frame>,
    ) -> impl Future<Output = Result<Option<Vec<Frame>>, RedisError>> + Send {
        let arc = Arc::clone(self);
        async move {
            arc.lock()
                .await
                .execute_transaction(watch_frames, command_frames)
                .await
        }
    }
}

impl TransactionExecutor for RedisClient {
    const SUPPORTS_TRANSACTION_RETRY: bool = false;

    fn execute_transaction(
        &mut self,
        watch_frames: Vec<Frame>,
        command_frames: Vec<Frame>,
    ) -> impl Future<Output = Result<Option<Vec<Frame>>, RedisError>> + Send {
        let arc = Arc::clone(&self.inner);
        async move {
            arc.lock()
                .await
                .execute_transaction(watch_frames, command_frames)
                .await
        }
    }
}

/// A type-erased command entry for transactions.
struct TransactionEntry {
    frame: Frame,
    parser: ResponseParser,
}

/// Builds and executes a Redis transaction (MULTI/EXEC).
///
/// Supports optional WATCH keys for optimistic locking. If a watched key
/// is modified by another client before EXEC, the transaction is aborted
/// and [`TransactionResult::Aborted`] is returned.
///
/// Accepts any type that implements [`TransactionExecutor`], including
/// [`RedisConnection`], [`RedisClient`], and `Arc<Mutex<C>>` for any
/// `C: TransactionExecutor + Send`.
///
/// # Example
///
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use redis_tower::{Transaction, TransactionResult, RedisConnection};
/// use redis_tower::commands::*;
///
/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
/// let result = Transaction::new()
///     .push(Set::new("x", "1"))
///     .push(Incr::new("x"))
///     .execute(&mut conn)
///     .await?;
///
/// match result {
///     TransactionResult::Committed(results) => {
///         let val: &i64 = results.get(1)?;
///         assert_eq!(*val, 2);
///     }
///     TransactionResult::Aborted => {
///         // WATCH key was modified
///     }
/// }
/// # Ok(())
/// # }
/// ```
pub struct Transaction {
    watch_keys: Vec<String>,
    entries: Vec<TransactionEntry>,
}

/// The outcome of a transaction execution.
#[must_use = "transaction result must be handled"]
pub enum TransactionResult {
    /// Transaction committed successfully. Results can be extracted by index.
    Committed(PipelineResults),
    /// Transaction was aborted because a WATCHed key was modified.
    Aborted,
}

impl TransactionResult {
    /// Returns `Some(results)` if the transaction committed, `None` if aborted.
    pub fn committed(self) -> Option<PipelineResults> {
        match self {
            TransactionResult::Committed(results) => Some(results),
            TransactionResult::Aborted => None,
        }
    }

    /// Returns `true` if the transaction was aborted due to a WATCH violation.
    pub fn is_aborted(&self) -> bool {
        matches!(self, TransactionResult::Aborted)
    }

    /// Returns `true` if the transaction committed successfully.
    pub fn is_committed(&self) -> bool {
        matches!(self, TransactionResult::Committed(_))
    }

    /// Unwraps the committed results, panicking if the transaction was aborted.
    ///
    /// # Panics
    ///
    /// Panics if the transaction was aborted. Use this only in tests or when
    /// the transaction cannot possibly be aborted (no WATCH keys).
    #[track_caller]
    pub fn unwrap(self) -> PipelineResults {
        match self {
            TransactionResult::Committed(results) => results,
            TransactionResult::Aborted => {
                panic!("called `TransactionResult::unwrap()` on an `Aborted` value")
            }
        }
    }
}

impl Transaction {
    /// Create a new empty transaction.
    pub fn new() -> Self {
        Self {
            watch_keys: Vec::new(),
            entries: Vec::new(),
        }
    }

    /// Watch keys for optimistic locking.
    ///
    /// If any watched key is modified by another client between the WATCH
    /// and the EXEC, the transaction will be aborted.
    pub fn watch(mut self, keys: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.watch_keys.extend(keys.into_iter().map(Into::into));
        self
    }

    /// Add a command to the transaction. Returns `self` for chaining.
    pub fn push<Cmd: Command + 'static>(mut self, cmd: Cmd) -> Self {
        let frame = cmd.to_frame();
        let parser = Box::new(
            move |response: Frame| -> Result<Box<dyn Any + Send>, RedisError> {
                let result = cmd.parse_response(response)?;
                Ok(Box::new(result))
            },
        );
        self.entries.push(TransactionEntry { frame, parser });
        self
    }

    /// Execute the transaction.
    ///
    /// Accepts any [`TransactionExecutor`]: [`RedisConnection`], [`RedisClient`],
    /// `Arc<Mutex<RedisConnection>>`, etc.
    ///
    /// Sends WATCH (if any), MULTI, all queued commands, and EXEC
    /// atomically under a single connection lock. For `Arc<Mutex<C>>`-based
    /// executors, the mutex is held for the entire WATCH/MULTI/EXEC sequence,
    /// preventing any interleaving with other callers.
    pub async fn execute<E: TransactionExecutor>(
        self,
        conn: &mut E,
    ) -> Result<TransactionResult, RedisError> {
        // Build WATCH frames.
        let watch_frames: Vec<Frame> = if self.watch_keys.is_empty() {
            Vec::new()
        } else {
            let mut args = vec![bulk("WATCH")];
            for key in &self.watch_keys {
                args.push(bulk(key.as_str()));
            }
            vec![array(args)]
        };

        let command_frames: Vec<Frame> = self.entries.iter().map(|e| e.frame.clone()).collect();

        let exec_result = conn
            .execute_transaction(watch_frames, command_frames)
            .await?;

        match exec_result {
            None => Ok(TransactionResult::Aborted),
            Some(responses) => {
                let mut results = Vec::with_capacity(responses.len());
                for (entry, response) in self.entries.into_iter().zip(responses) {
                    if let Frame::Error(ref e) = response {
                        results.push(Err(RedisError::Redis(
                            String::from_utf8_lossy(e).into_owned(),
                        )));
                    } else {
                        results.push((entry.parser)(response));
                    }
                }
                Ok(TransactionResult::Committed(PipelineResults::from_raw(
                    results,
                )))
            }
        }
    }

    /// Returns the number of queued commands.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns true if no commands are queued.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

impl Default for Transaction {
    fn default() -> Self {
        Self::new()
    }
}

/// Default number of WATCH/EXEC attempts used by [`transaction`] before it
/// gives up and returns [`RedisError::TransactionAborted`].
pub const DEFAULT_TRANSACTION_RETRIES: usize = 16;

/// Run a WATCH-protected transaction, retrying on optimistic-lock conflicts.
///
/// This is the ergonomic port of redis-rs's `transaction`/`transaction_async`
/// helpers. It implements the standard optimistic-locking loop:
///
/// 1. `WATCH` the given keys.
/// 2. Call `build`, which may read the watched keys on `conn` and returns the
///    [`Transaction`] body to commit (the commands to run between MULTI/EXEC).
/// 3. Run MULTI/EXEC. If a watched key was modified by another client, EXEC is
///    aborted and the whole sequence is retried from step 1.
///
/// The loop runs until EXEC commits or the retry cap is reached. On a commit it
/// returns the [`PipelineResults`]; if the cap is exhausted it returns
/// [`RedisError::TransactionAborted`].
///
/// Because the reads in `build` must happen *inside* the WATCH window, `conn`
/// must be an exclusively held connection for the duration of the call -- pass
/// a [`RedisConnection`] (`&mut`) or otherwise ensure no other task issues
/// commands on the same connection while the transaction is in flight. (This is
/// the same requirement redis-rs places on its `transaction` helper.) The
/// returned `Transaction` should carry the commands only; the WATCH is issued
/// by this helper, so do not also call [`Transaction::watch`] on it.
/// Shared or routed executors that cannot reserve this complete window reject
/// the helper before WATCH is sent or `build` is invoked. A direct
/// [`Transaction::watch`] is suitable only when its body is already known; use
/// a dedicated [`RedisConnection`] for read/compute/build retries.
///
/// Uses [`DEFAULT_TRANSACTION_RETRIES`] as the cap. Use
/// [`transaction_with_retries`] to choose a different cap.
///
/// # Example
///
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use redis_tower::{transaction, Transaction, RedisConnection};
/// use redis_tower::commands::{Get, Set};
///
/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
///
/// // Atomically double the value at `counter`, retrying if another client
/// // touches it between the read and the EXEC.
/// let results = transaction(&mut conn, ["counter"], async |c| {
///     let current: i64 = match c.execute(Get::new("counter")).await? {
///         Some(bytes) => String::from_utf8_lossy(&bytes).parse().unwrap_or(0),
///         None => 0,
///     };
///     Ok(Transaction::new().push(Set::new("counter", (current * 2).to_string())))
/// })
/// .await?;
/// # let _ = results;
/// # Ok(())
/// # }
/// ```
pub async fn transaction<C, F>(
    conn: &mut C,
    keys: impl IntoIterator<Item = impl Into<String>>,
    build: F,
) -> Result<PipelineResults, RedisError>
where
    C: RedisExecutor + TransactionExecutor + Send,
    F: AsyncFnMut(&mut C) -> Result<Transaction, RedisError>,
{
    transaction_with_retries(conn, keys, DEFAULT_TRANSACTION_RETRIES, build).await
}

/// Like [`transaction`], but with an explicit retry cap.
///
/// `max_retries` is the number of *additional* attempts made after the first,
/// so the closure is invoked at most `max_retries + 1` times. A cap of `0`
/// makes a single attempt and surfaces a WATCH abort immediately as
/// [`RedisError::TransactionAborted`].
///
/// See [`transaction`] for the full contract.
pub async fn transaction_with_retries<C, F>(
    conn: &mut C,
    keys: impl IntoIterator<Item = impl Into<String>>,
    max_retries: usize,
    mut build: F,
) -> Result<PipelineResults, RedisError>
where
    C: RedisExecutor + TransactionExecutor + Send,
    F: AsyncFnMut(&mut C) -> Result<Transaction, RedisError>,
{
    // Some routed executors cannot reserve one physical connection across the
    // standalone WATCH, user-supplied read/build closure, and later EXEC. Fail
    // before WATCH or any closure side effect instead of silently weakening
    // optimistic locking.
    conn.validate_transaction_retry()?;

    let keys: Vec<String> = keys.into_iter().map(Into::into).collect();
    let mut remaining = max_retries;

    loop {
        // WATCH the keys so the reads in `build` are covered by the optimistic
        // lock. Skip the round-trip entirely when there is nothing to watch.
        if !keys.is_empty() {
            conn.execute(Watch::keys(keys.clone())).await?;
        }

        // Build the atomic body. The closure may read the watched keys here.
        let txn = build(conn).await?;

        // Run MULTI/EXEC. The WATCH issued above is still active on the
        // connection, so the body carries no watch keys of its own.
        match txn.execute(&mut *conn).await? {
            TransactionResult::Committed(results) => return Ok(results),
            TransactionResult::Aborted => {
                // A watched key changed. EXEC already cleared the WATCH state,
                // so the next iteration re-watches from scratch.
                if remaining == 0 {
                    return Err(RedisError::TransactionAborted);
                }
                remaining -= 1;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(unix)]
    fn connected_pair() -> (RedisConnection, tokio::net::UnixStream) {
        let (client, server) = tokio::net::UnixStream::pair().unwrap();
        (
            RedisConnection::from_stream(redis_tower_core::RedisStream::Unix(client)),
            server,
        )
    }

    #[cfg(unix)]
    async fn assert_no_wire_request(mut server: tokio::net::UnixStream) {
        use tokio::io::AsyncReadExt;

        let mut bytes = [0u8; 128];
        assert!(
            tokio::time::timeout(
                std::time::Duration::from_millis(25),
                server.read(&mut bytes),
            )
            .await
            .is_err(),
            "transaction helper wrote to Redis before rejecting the executor"
        );
    }

    fn assert_retry_helper_unsupported(result: &Result<PipelineResults, RedisError>) {
        let error = match result {
            Err(error) => error,
            Ok(_) => panic!("shared executor was accepted"),
        };
        let message = error.to_string();
        assert!(message.contains("transaction_with_retries()"));
        assert!(message.contains("Transaction::watch()"));
    }

    fn committed() -> TransactionResult {
        TransactionResult::Committed(PipelineResults::from_raw(Vec::new()))
    }

    #[test]
    fn retry_helper_capability_is_limited_to_exclusive_connections() {
        const {
            assert!(<RedisConnection as TransactionExecutor>::SUPPORTS_TRANSACTION_RETRY);
            assert!(!<RedisClient as TransactionExecutor>::SUPPORTS_TRANSACTION_RETRY);
            assert!(!<crate::MultiplexedClient as TransactionExecutor>::SUPPORTS_TRANSACTION_RETRY);
            assert!(
                !<Arc<Mutex<RedisConnection>> as TransactionExecutor>::SUPPORTS_TRANSACTION_RETRY
            );
        }
    }

    #[test]
    fn committed_returns_some_for_committed() {
        assert!(committed().committed().is_some());
    }

    #[test]
    fn committed_returns_none_for_aborted() {
        assert!(TransactionResult::Aborted.committed().is_none());
    }

    #[test]
    fn is_aborted_reports_correctly() {
        assert!(TransactionResult::Aborted.is_aborted());
        assert!(!committed().is_aborted());
    }

    #[test]
    fn is_committed_reports_correctly() {
        assert!(committed().is_committed());
        assert!(!TransactionResult::Aborted.is_committed());
    }

    #[test]
    fn unwrap_succeeds_on_committed() {
        let results = committed().unwrap();
        assert!(results.is_empty());
    }

    #[test]
    #[should_panic(expected = "Aborted")]
    fn unwrap_panics_on_aborted() {
        let _ = TransactionResult::Aborted.unwrap();
    }

    /// A mock transaction executor for unit tests.
    struct MockTransactionConn {
        /// Simulates committed responses (one per command frame).
        responses: Option<Vec<Frame>>,
    }

    impl TransactionExecutor for MockTransactionConn {
        fn execute_transaction(
            &mut self,
            _watch_frames: Vec<Frame>,
            command_frames: Vec<Frame>,
        ) -> impl Future<Output = Result<Option<Vec<Frame>>, RedisError>> + Send {
            let responses = self.responses.take().map(|_| {
                // Return one SimpleString "OK" per queued command.
                command_frames
                    .iter()
                    .map(|_| Frame::SimpleString(bytes::Bytes::from("OK")))
                    .collect::<Vec<_>>()
            });
            async move { Ok(responses) }
        }
    }

    #[tokio::test]
    async fn transaction_execute_accepts_transaction_executor() {
        use redis_tower_commands::Set;

        let mut conn = MockTransactionConn {
            responses: Some(vec![]),
        };
        let result = Transaction::new()
            .push(Set::new("x", "1"))
            .execute(&mut conn)
            .await
            .unwrap();
        assert!(result.is_committed());
    }

    #[tokio::test]
    async fn transaction_execute_accepts_arc_mutex_executor() {
        use redis_tower_commands::Set;

        let conn = Arc::new(Mutex::new(MockTransactionConn {
            responses: Some(vec![]),
        }));
        let mut executor = Arc::clone(&conn);
        let result = Transaction::new()
            .push(Set::new("x", "1"))
            .execute(&mut executor)
            .await
            .unwrap();
        assert!(result.is_committed());
    }

    /// A mock that also implements [`RedisExecutor`] (for the WATCH/read path)
    /// and can be scripted to abort a fixed number of EXECs before committing,
    /// so the [`transaction`] retry loop can be exercised without a server.
    struct RetryMockConn {
        /// Number of EXECs to abort (WATCH violation) before the next commits.
        aborts_before_commit: usize,
        /// How many `execute_transaction` calls were made.
        exec_calls: usize,
        /// How many plain commands (i.e. WATCH) were issued via `execute`.
        watch_calls: usize,
    }

    impl RedisExecutor for RetryMockConn {
        fn execute<Cmd: Command>(
            &mut self,
            cmd: Cmd,
        ) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
            self.watch_calls += 1;
            // Only WATCH is exercised in these tests; reply OK to it.
            let result = cmd.parse_response(Frame::SimpleString(bytes::Bytes::from("OK")));
            async move { result }
        }
    }

    impl TransactionExecutor for RetryMockConn {
        fn execute_transaction(
            &mut self,
            _watch_frames: Vec<Frame>,
            command_frames: Vec<Frame>,
        ) -> impl Future<Output = Result<Option<Vec<Frame>>, RedisError>> + Send {
            self.exec_calls += 1;
            let abort = self.aborts_before_commit > 0;
            if abort {
                self.aborts_before_commit -= 1;
            }
            let responses = if abort {
                // EXEC aborted by a WATCH violation.
                None
            } else {
                Some(
                    command_frames
                        .iter()
                        .map(|_| Frame::SimpleString(bytes::Bytes::from("OK")))
                        .collect::<Vec<_>>(),
                )
            };
            async move { Ok(responses) }
        }
    }

    #[tokio::test]
    async fn transaction_helper_rejects_arc_mutex_before_watch_or_build() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let inner = Arc::new(Mutex::new(RetryMockConn {
            aborts_before_commit: 0,
            exec_calls: 0,
            watch_calls: 0,
        }));
        let mut shared = Arc::clone(&inner);
        let build_calls = Arc::new(AtomicUsize::new(0));
        let build_counter = Arc::clone(&build_calls);

        let result = transaction_with_retries(
            &mut shared,
            ["key"],
            0,
            async move |_conn: &mut Arc<Mutex<RetryMockConn>>| {
                build_counter.fetch_add(1, Ordering::SeqCst);
                Ok(Transaction::new())
            },
        )
        .await;

        assert_retry_helper_unsupported(&result);
        assert_eq!(build_calls.load(Ordering::SeqCst), 0);
        let inner = inner.lock().await;
        assert_eq!(inner.watch_calls, 0);
        assert_eq!(inner.exec_calls, 0);
    }

    #[tokio::test]
    #[cfg(unix)]
    async fn transaction_helper_rejects_redis_client_before_watch_or_build() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let (conn, server) = connected_pair();
        let mut client = RedisClient::from_connection(conn);
        let build_calls = Arc::new(AtomicUsize::new(0));
        let build_counter = Arc::clone(&build_calls);

        let result = transaction_with_retries(
            &mut client,
            ["key"],
            0,
            async move |_conn: &mut RedisClient| {
                build_counter.fetch_add(1, Ordering::SeqCst);
                Ok(Transaction::new())
            },
        )
        .await;

        assert_retry_helper_unsupported(&result);
        assert_eq!(build_calls.load(Ordering::SeqCst), 0);
        assert_no_wire_request(server).await;
    }

    #[tokio::test]
    #[cfg(unix)]
    async fn transaction_helper_rejects_multiplexed_client_before_watch_or_build() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let (conn, server) = connected_pair();
        let mut client = crate::MultiplexedClient::from_connection(conn);
        let build_calls = Arc::new(AtomicUsize::new(0));
        let build_counter = Arc::clone(&build_calls);

        let result = transaction_with_retries(
            &mut client,
            ["key"],
            0,
            async move |_conn: &mut crate::MultiplexedClient| {
                build_counter.fetch_add(1, Ordering::SeqCst);
                Ok(Transaction::new())
            },
        )
        .await;

        assert_retry_helper_unsupported(&result);
        assert_eq!(build_calls.load(Ordering::SeqCst), 0);
        assert_no_wire_request(server).await;
        client.shutdown().await;
    }

    #[tokio::test]
    async fn transaction_commits_on_first_attempt() {
        use redis_tower_commands::Set;

        let mut conn = RetryMockConn {
            aborts_before_commit: 0,
            exec_calls: 0,
            watch_calls: 0,
        };
        let results = transaction(&mut conn, ["counter"], async |_c| {
            Ok(Transaction::new().push(Set::new("counter", "1")))
        })
        .await
        .unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(conn.exec_calls, 1, "should EXEC exactly once");
        assert_eq!(conn.watch_calls, 1, "should WATCH exactly once");
    }

    #[tokio::test]
    async fn transaction_retries_until_commit() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        use redis_tower_commands::Set;

        let mut conn = RetryMockConn {
            aborts_before_commit: 2,
            exec_calls: 0,
            watch_calls: 0,
        };
        let build_calls = Arc::new(AtomicUsize::new(0));
        let bc = Arc::clone(&build_calls);

        let results = transaction(&mut conn, ["k"], async move |_c: &mut RetryMockConn| {
            bc.fetch_add(1, Ordering::SeqCst);
            Ok(Transaction::new().push(Set::new("k", "1")))
        })
        .await
        .unwrap();

        assert_eq!(results.len(), 1);
        // Two aborts then a commit -> three attempts, each re-WATCHing.
        assert_eq!(build_calls.load(Ordering::SeqCst), 3);
        assert_eq!(conn.exec_calls, 3);
        assert_eq!(conn.watch_calls, 3);
    }

    #[tokio::test]
    async fn transaction_gives_up_after_retry_cap() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        use redis_tower_commands::Set;

        let mut conn = RetryMockConn {
            // Always aborts -- the cap, not a commit, must terminate the loop.
            aborts_before_commit: usize::MAX,
            exec_calls: 0,
            watch_calls: 0,
        };
        let build_calls = Arc::new(AtomicUsize::new(0));
        let bc = Arc::clone(&build_calls);

        let result =
            transaction_with_retries(&mut conn, ["k"], 2, async move |_c: &mut RetryMockConn| {
                bc.fetch_add(1, Ordering::SeqCst);
                Ok(Transaction::new().push(Set::new("k", "1")))
            })
            .await;

        assert!(matches!(result, Err(RedisError::TransactionAborted)));
        // First attempt + 2 retries = 3 invocations.
        assert_eq!(build_calls.load(Ordering::SeqCst), 3);
        assert_eq!(conn.exec_calls, 3);
    }

    #[tokio::test]
    async fn transaction_without_keys_skips_watch() {
        use redis_tower_commands::Set;

        let mut conn = RetryMockConn {
            aborts_before_commit: 0,
            exec_calls: 0,
            watch_calls: 0,
        };
        let empty: [&str; 0] = [];
        let results = transaction(&mut conn, empty, async |_c| {
            Ok(Transaction::new().push(Set::new("k", "1")))
        })
        .await
        .unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(conn.exec_calls, 1);
        assert_eq!(conn.watch_calls, 0, "no keys means no WATCH round-trip");
    }

    #[tokio::test]
    async fn transaction_zero_retries_surfaces_abort_immediately() {
        use redis_tower_commands::Set;

        let mut conn = RetryMockConn {
            aborts_before_commit: usize::MAX,
            exec_calls: 0,
            watch_calls: 0,
        };
        let result = transaction_with_retries(&mut conn, ["k"], 0, async |_c| {
            Ok(Transaction::new().push(Set::new("k", "1")))
        })
        .await;

        assert!(matches!(result, Err(RedisError::TransactionAborted)));
        assert_eq!(conn.exec_calls, 1, "cap of 0 makes a single attempt");
    }
}