diff --git a/Cargo.toml b/Cargo.toml index 7b4138a..3f89012 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,6 +2,9 @@ members = ["crates/*"] resolver = "2" +[workspace.package] +version = "0.1.0" + [workspace.dependencies] noretry = { path = "crates/noretry" } diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ae6cfb3 --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +Copyright 2026 Kasper Juul Hermansen + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b9edeb0 --- /dev/null +++ b/README.md @@ -0,0 +1,100 @@ +# noretry + +A simple retry library for Rust with both sync and async support. + +## Usage + +Async (enabled by default via the `tokio` feature): + +```rust +let result = noretry::retry_async(|| async { + do_something().await +}) +.await +.map_err(|e| e.into_inner())?; +``` + +Sync: + +```rust +let result = noretry::retry(|| { + do_something() +}) +.map_err(|e| e.into_inner())?; +``` + +Both use sensible defaults: 3 attempts, exponential backoff, 100ms initial delay, 30s cap, and jitter. + +Errors returned from the closure are automatically treated as transient (retryable) via the `From` impl on `Retryable`. Use `?` as normal and retries happen transparently. + +## Features + +The `tokio` feature is enabled by default, providing `retry_async` and `run_async`. To use only the sync API: + +```toml +noretry = { version = "0.1", default-features = false } +``` + +## Builder + +For more control, use the builder with `run` (sync) or `run_async`: + +```rust +noretry::builder() + .with_max_attempts(5) + .with_linear_backoff() + .build() + .run_async(|| async { + do_something().await + }) + .await?; +``` + +## Backoff strategies + +Exponential backoff (default): + +```rust +noretry::builder() + .with_exponential_backoff() + .build() +``` + +Linear backoff: + +```rust +noretry::builder() + .with_linear_backoff() + .build() +``` + +Both strategies support configurable initial delay, max delay cap, and jitter (enabled by default): + +```rust +use std::time::Duration; + +noretry::builder() + .with_initial_delay(Duration::from_millis(200)) + .with_max_delay(Duration::from_secs(10)) + .with_jitter(false) + .build() +``` + +## Permanent errors + +If an error should not be retried, mark it as permanent using `map_err`: + +```rust +use noretry::Retryable; + +noretry::builder() + .build() + .run_async(|| async { + do_something() + .await + .map_err(Retryable::permanent)? + }) + .await; +``` + +The result is a `RetryError::Permanent` or `RetryError::Exhausted`, both of which carry the original error. Call `.into_inner()` to extract it. diff --git a/crates/noretry/Cargo.toml b/crates/noretry/Cargo.toml index ef827ad..88db363 100644 --- a/crates/noretry/Cargo.toml +++ b/crates/noretry/Cargo.toml @@ -1,11 +1,20 @@ [package] name = "noretry" -version = "0.1.0" +version.workspace = true edition = "2024" +description = "noretry is a simple retryable abstraction for your functions" +repository = "https://git.kjuulh.io/kjuulh/noretry" +readme = "../../README.md" +license-file = "../../LICENSE" +publish = true + +[features] +default = ["tokio"] +tokio = ["dep:tokio"] [dependencies] fastrand.workspace = true -tokio.workspace = true +tokio = { workspace = true, optional = true } [dev-dependencies] anyhow.workspace = true diff --git a/crates/noretry/src/lib.rs b/crates/noretry/src/lib.rs index d8d5e40..1587ad8 100644 --- a/crates/noretry/src/lib.rs +++ b/crates/noretry/src/lib.rs @@ -1,6 +1,22 @@ use std::fmt; use std::time::Duration; +pub fn retry(f: T) -> Result> +where + T: Fn() -> Result>, +{ + builder().build().run(f) +} + +#[cfg(feature = "tokio")] +pub async fn retry_async(f: T) -> Result> +where + T: Fn() -> TFut + Send + 'static, + TFut: Future>>, +{ + builder().build().run_async(f).await +} + pub fn builder() -> RetryBuilder { RetryBuilder { max_attempts: 3, @@ -75,7 +91,37 @@ pub struct RetryOptions { } impl RetryOptions { - pub async fn run(self, f: T) -> Result> + pub fn run(self, f: T) -> Result> + where + T: Fn() -> Result>, + { + let mut last_error = None; + + for attempt in 1..=self.max_attempts { + match f() { + Ok(success) => return Ok(success), + Err(Retryable::Permanent { error }) => { + return Err(RetryError::Permanent { error }); + } + Err(Retryable::Transient { error }) => { + last_error = Some(error); + + if attempt < self.max_attempts { + let delay = self.get_delay(attempt); + std::thread::sleep(delay); + } + } + } + } + + Err(RetryError::Exhausted { + last_error: last_error.unwrap(), + attempts: self.max_attempts, + }) + } + + #[cfg(feature = "tokio")] + pub async fn run_async(self, f: T) -> Result> where T: Fn() -> TFut + Send + 'static, TFut: Future>>, @@ -128,6 +174,16 @@ pub enum Retryable { Permanent { error: E }, } +impl Retryable { + pub fn permanent(error: E) -> Self { + Self::Permanent { error } + } + + pub fn transient(error: E) -> Self { + Self::Transient { error } + } +} + impl From for Retryable { fn from(value: E) -> Self { Self::Transient { error: value } diff --git a/crates/noretry/tests/mod.rs b/crates/noretry/tests/mod.rs index 1ac93f2..1633890 100644 --- a/crates/noretry/tests/mod.rs +++ b/crates/noretry/tests/mod.rs @@ -2,9 +2,7 @@ use noretry::Retryable; #[tokio::test] async fn test_can_call() -> anyhow::Result<()> { - let res = noretry::builder() - .build() - .run(my_func) + let res = noretry::retry_async(my_func) .await .map_err(|e| e.into_inner())?; @@ -18,7 +16,7 @@ async fn test_can_fail() { let res = noretry::builder() .with_max_attempts(2) .build() - .run(fail) + .run_async(fail) .await; if let Err(noretry::RetryError::Exhausted { @@ -48,7 +46,7 @@ async fn test_permanent_error() { let res = noretry::builder() .with_max_attempts(5) .build() - .run(fail_permanent) + .run_async(fail_permanent) .await; if let Err(noretry::RetryError::Permanent { error }) = res { @@ -59,7 +57,37 @@ async fn test_permanent_error() { } async fn fail_permanent() -> Result> { - Err(Retryable::Permanent { - error: anyhow::anyhow!("not retryable"), - }) + Err(anyhow::anyhow!("not retryable")).map_err(Retryable::permanent)? +} + +#[test] +fn test_sync_retry() -> anyhow::Result<()> { + let res = noretry::retry(|| Ok::<_, Retryable>("hello".to_string())) + .map_err(|e| e.into_inner())?; + + assert_eq!("hello", res.as_str()); + + Ok(()) +} + +#[test] +fn test_sync_retry_exhausted() { + let res = noretry::builder() + .with_max_attempts(2) + .with_initial_delay(std::time::Duration::from_millis(1)) + .build() + .run(|| -> Result> { + Err(anyhow::anyhow!("sync fail"))? + }); + + if let Err(noretry::RetryError::Exhausted { + attempts, + last_error, + }) = res + { + assert_eq!(2, attempts); + assert_eq!("sync fail", last_error.to_string()); + } else { + panic!("expected exhausted error") + } }