1use 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
39pub trait TransactionExecutor {
54 const SUPPORTS_TRANSACTION_RETRY: bool = true;
64
65 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 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
138struct TransactionEntry {
140 frame: Frame,
141 parser: ResponseParser,
142}
143
144pub struct Transaction {
181 watch_keys: Vec<CommandArg>,
182 entries: Vec<TransactionEntry>,
183}
184
185#[must_use = "transaction result must be handled"]
187pub enum TransactionResult {
188 Committed(PipelineResults),
190 Aborted,
192}
193
194impl TransactionResult {
195 pub fn committed(self) -> Option<PipelineResults> {
197 match self {
198 TransactionResult::Committed(results) => Some(results),
199 TransactionResult::Aborted => None,
200 }
201 }
202
203 pub fn is_aborted(&self) -> bool {
205 matches!(self, TransactionResult::Aborted)
206 }
207
208 pub fn is_committed(&self) -> bool {
210 matches!(self, TransactionResult::Committed(_))
211 }
212
213 #[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 pub fn new() -> Self {
233 Self {
234 watch_keys: Vec::new(),
235 entries: Vec::new(),
236 }
237 }
238
239 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 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 pub async fn execute<E: TransactionExecutor>(
271 self,
272 conn: &mut E,
273 ) -> Result<TransactionResult, RedisError> {
274 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 pub fn len(&self) -> usize {
313 self.entries.len()
314 }
315
316 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
328pub const DEFAULT_TRANSACTION_RETRIES: usize = 16;
331
332pub 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
397pub 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 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 if !keys.is_empty() {
428 conn.execute(Watch::keys(keys.clone())).await?;
429 }
430
431 let txn = build(conn).await?;
433
434 match txn.execute(&mut *conn).await? {
437 TransactionResult::Committed(results) => return Ok(results),
438 TransactionResult::Aborted => {
439 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 struct MockTransactionConn {
541 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 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 struct RetryMockConn {
649 aborts_before_commit: usize,
651 exec_calls: usize,
653 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 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 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 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 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 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}