feat: add sync and async

Signed-off-by: kjuulh <contact@kjuulh.io>
This commit is contained in:
2026-02-03 20:43:21 +01:00
parent ad736bc8c0
commit ec9a60318f
6 changed files with 214 additions and 11 deletions

View File

@@ -2,6 +2,9 @@
members = ["crates/*"] members = ["crates/*"]
resolver = "2" resolver = "2"
[workspace.package]
version = "0.1.0"
[workspace.dependencies] [workspace.dependencies]
noretry = { path = "crates/noretry" } noretry = { path = "crates/noretry" }

7
LICENSE Normal file
View File

@@ -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.

100
README.md Normal file
View File

@@ -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.

View File

@@ -1,11 +1,20 @@
[package] [package]
name = "noretry" name = "noretry"
version = "0.1.0" version.workspace = true
edition = "2024" 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] [dependencies]
fastrand.workspace = true fastrand.workspace = true
tokio.workspace = true tokio = { workspace = true, optional = true }
[dev-dependencies] [dev-dependencies]
anyhow.workspace = true anyhow.workspace = true

View File

@@ -1,6 +1,22 @@
use std::fmt; use std::fmt;
use std::time::Duration; use std::time::Duration;
pub fn retry<T, TOk, TError>(f: T) -> Result<TOk, RetryError<TError>>
where
T: Fn() -> Result<TOk, Retryable<TError>>,
{
builder().build().run(f)
}
#[cfg(feature = "tokio")]
pub async fn retry_async<T, TFut, TOk, TError>(f: T) -> Result<TOk, RetryError<TError>>
where
T: Fn() -> TFut + Send + 'static,
TFut: Future<Output = Result<TOk, Retryable<TError>>>,
{
builder().build().run_async(f).await
}
pub fn builder() -> RetryBuilder { pub fn builder() -> RetryBuilder {
RetryBuilder { RetryBuilder {
max_attempts: 3, max_attempts: 3,
@@ -75,7 +91,37 @@ pub struct RetryOptions {
} }
impl RetryOptions { impl RetryOptions {
pub async fn run<T, TFut, TOk, TError>(self, f: T) -> Result<TOk, RetryError<TError>> pub fn run<T, TOk, TError>(self, f: T) -> Result<TOk, RetryError<TError>>
where
T: Fn() -> Result<TOk, Retryable<TError>>,
{
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<T, TFut, TOk, TError>(self, f: T) -> Result<TOk, RetryError<TError>>
where where
T: Fn() -> TFut + Send + 'static, T: Fn() -> TFut + Send + 'static,
TFut: Future<Output = Result<TOk, Retryable<TError>>>, TFut: Future<Output = Result<TOk, Retryable<TError>>>,
@@ -128,6 +174,16 @@ pub enum Retryable<E> {
Permanent { error: E }, Permanent { error: E },
} }
impl<E> Retryable<E> {
pub fn permanent(error: E) -> Self {
Self::Permanent { error }
}
pub fn transient(error: E) -> Self {
Self::Transient { error }
}
}
impl<E> From<E> for Retryable<E> { impl<E> From<E> for Retryable<E> {
fn from(value: E) -> Self { fn from(value: E) -> Self {
Self::Transient { error: value } Self::Transient { error: value }

View File

@@ -2,9 +2,7 @@ use noretry::Retryable;
#[tokio::test] #[tokio::test]
async fn test_can_call() -> anyhow::Result<()> { async fn test_can_call() -> anyhow::Result<()> {
let res = noretry::builder() let res = noretry::retry_async(my_func)
.build()
.run(my_func)
.await .await
.map_err(|e| e.into_inner())?; .map_err(|e| e.into_inner())?;
@@ -18,7 +16,7 @@ async fn test_can_fail() {
let res = noretry::builder() let res = noretry::builder()
.with_max_attempts(2) .with_max_attempts(2)
.build() .build()
.run(fail) .run_async(fail)
.await; .await;
if let Err(noretry::RetryError::Exhausted { if let Err(noretry::RetryError::Exhausted {
@@ -48,7 +46,7 @@ async fn test_permanent_error() {
let res = noretry::builder() let res = noretry::builder()
.with_max_attempts(5) .with_max_attempts(5)
.build() .build()
.run(fail_permanent) .run_async(fail_permanent)
.await; .await;
if let Err(noretry::RetryError::Permanent { error }) = res { if let Err(noretry::RetryError::Permanent { error }) = res {
@@ -59,7 +57,37 @@ async fn test_permanent_error() {
} }
async fn fail_permanent() -> Result<String, Retryable<anyhow::Error>> { async fn fail_permanent() -> Result<String, Retryable<anyhow::Error>> {
Err(Retryable::Permanent { Err(anyhow::anyhow!("not retryable")).map_err(Retryable::permanent)?
error: anyhow::anyhow!("not retryable"), }
})
#[test]
fn test_sync_retry() -> anyhow::Result<()> {
let res = noretry::retry(|| Ok::<_, Retryable<anyhow::Error>>("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<String, Retryable<anyhow::Error>> {
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")
}
} }