prism3_retry/lib.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025.
4 * 3-Prism Co. Ltd.
5 *
6 * All rights reserved.
7 *
8 ******************************************************************************/
9//! # Prism3 Retry - Retry module
10//!
11//! A fully-featured, type-safe retry management system, ported from Java's
12//! `ltd.qubit.commons.util.retry` package to Rust.
13//!
14//! ## Design Philosophy
15//!
16//! ### Core Design Principles
17//!
18//! 1. **Type Safety First** - Leverage Rust's type system to ensure type safety
19//! at compile time
20//! 2. **Result Error Handling** - Use Rust's Result type for error handling
21//! instead of exceptions
22//! 3. **Zero-Cost Abstraction** - Use enums instead of trait objects to avoid
23//! dynamic dispatch overhead
24//! 4. **Unified Interface** - Provide generic APIs that support all primitive
25//! types and custom types
26//! 5. **Event-Driven** - Support various event listeners during the retry process
27//!
28//! ## Module Structure
29//!
30//! ```text
31//! retry/
32//! |-- mod.rs # Module entry point, exports public API
33//! |-- builder.rs # RetryBuilder struct (core retry builder)
34//! |-- config.rs # RetryConfig trait and DefaultRetryConfig
35//! |-- delay_strategy.rs # RetryDelayStrategy enum
36//! |-- events.rs # Event type definitions
37//! |-- error.rs # Error type definitions
38//! |-- executor.rs # RetryExecutor executor
39//! ```
40//!
41//! ## Core Features
42//!
43//! - ✅ **Type-Safe Retry** - Use generic API to support any return type
44//! - ✅ **Multiple Delay Strategies** - Support fixed delay, random delay,
45//! exponential backoff
46//! - ✅ **Flexible Error Handling** - Result-based error handling with error
47//! type identification
48//! - ✅ **Result-Driven Retry** - Support retry logic based on return values
49//! - ✅ **Event Listening** - Support various event callbacks during retry
50//! process
51//! - ✅ **Configuration Integration** - Seamless integration with
52//! prism3-config's config module
53//! - ✅ **Timeout Control** - Support single operation timeout and overall
54//! timeout control
55//! - ✅ **Sync and Async** - Support both synchronous and asynchronous
56//! operation retries
57//!
58//! ## Usage Examples
59//!
60//! ### Basic Synchronous Retry
61//! ```rust
62//! use prism3_retry::{RetryBuilder, RetryDelayStrategy, RetryResult, RetryEvent};
63//! use std::time::Duration;
64//!
65//! // Basic retry configuration
66//! let executor = RetryBuilder::new()
67//! .set_max_attempts(3)
68//! .set_delay_strategy(RetryDelayStrategy::Fixed { delay: Duration::from_secs(1) })
69//! .failed_on_results(vec!["RETRY".to_string(), "TEMP_FAIL".to_string()])
70//! .on_retry(|event: &RetryEvent<String>| println!("Retry attempt {}", event.attempt_count()))
71//! .build();
72//!
73//! // Use RetryResult type alias to simplify return type
74//! let result: RetryResult<String> = executor.run(|| -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
75//! // Can use ? operator, io::Error will be automatically converted to
76//! // RetryError through From trait
77//! // Example: std::fs::read_to_string("config.txt")?;
78//! Ok("SUCCESS".to_string())
79//! });
80//!
81//! assert!(result.is_ok());
82//! ```
83//!
84//! ### Async Retry with Timeout Control
85//! ```rust,no_run
86//! use prism3_retry::{RetryBuilder, RetryResult};
87//! use std::time::Duration;
88//!
89//! # async fn example() {
90//! // Configure timeout control
91//! let executor = RetryBuilder::<String>::new()
92//! .set_max_attempts(3)
93//! .set_operation_timeout(Some(Duration::from_secs(5))) // Max 5 seconds per operation
94//! .set_max_duration(Some(Duration::from_secs(30))) // Max 30 seconds total
95//! .build();
96//!
97//! // Use RetryResult to simplify async function return type
98//! let result: RetryResult<String> = executor.run_async(|| async {
99//! // Async operation timeout will be truly interrupted
100//! // Can use ? operator, errors will be automatically converted
101//! // Example: tokio::fs::read_to_string("config.txt").await?;
102//! Ok("SUCCESS".to_string())
103//! }).await;
104//!
105//! assert!(result.is_ok());
106//! # }
107//! ```
108//!
109//! For detailed usage, please refer to the documentation of each struct.
110//!
111//! ## Author
112//!
113//! Haixing Hu
114
115pub mod builder;
116pub mod config;
117pub mod default_config;
118pub mod delay_strategy;
119pub mod error;
120pub mod event;
121pub mod executor;
122pub mod simple_config;
123
124// Re-export public API
125pub use builder::RetryBuilder;
126pub use config::RetryConfig;
127pub use default_config::DefaultRetryConfig;
128pub use delay_strategy::RetryDelayStrategy;
129pub use error::RetryError;
130pub use event::{
131 AbortEvent, AbortReason, FailureEvent, RetryDecision, RetryEvent, RetryReason, SuccessEvent,
132};
133pub use executor::RetryExecutor;
134pub use simple_config::SimpleRetryConfig;
135
136// Common type aliases
137pub type RetryResult<T> = Result<T, RetryError>;
138
139/// Type alias for retry builder using default configuration
140///
141/// This is the most commonly used `RetryBuilder` type, using
142/// `DefaultRetryConfig` as the configuration type.
143///
144/// # Example
145///
146/// ```rust
147/// use prism3_retry::DefaultRetryBuilder;
148///
149/// let builder = DefaultRetryBuilder::<String>::new()
150/// .set_max_attempts(3)
151/// .build();
152/// ```
153pub type DefaultRetryBuilder<T> = RetryBuilder<T, DefaultRetryConfig>;
154
155/// Type alias for retry executor using default configuration
156///
157/// This is the most commonly used `RetryExecutor` type, using
158/// `DefaultRetryConfig` as the configuration type.
159///
160/// # Example
161///
162/// ```rust
163/// use prism3_retry::{RetryBuilder, DefaultRetryExecutor};
164///
165/// let executor: DefaultRetryExecutor<String> = RetryBuilder::new()
166/// .set_max_attempts(3)
167/// .build();
168/// ```
169pub type DefaultRetryExecutor<T> = RetryExecutor<T, DefaultRetryConfig>;