Crates.io | backoff-macro |
lib.rs | backoff-macro |
version | 0.2.0 |
source | src |
created_at | 2024-05-23 06:20:04.881783 |
updated_at | 2024-05-23 07:39:07.056508 |
description | Mark an async function with #[backoff] to get the default ExponentialBackoff behavior. (tokio compatible) |
homepage | |
repository | https://github.com/yourusername/backoff-macro |
max_upload_size | |
id | 1249188 |
size | 9,820 |
backoff_macro
is a Rust procedural macro that adds retry logic with exponential backoff to asynchronous functions. This crate leverages the backoff
crate to handle retries and allows users to simply annotate their functions with #[backoff]
to enable this functionality.
Add backoff_macro
to your Cargo.toml
:
[dependencies]
backoff_macro = "0.1.0"
backoff = "0.3.0"
tokio = { version = "1", features = ["full"] }
To use the #[backoff]
macro, simply annotate your asynchronous function with #[backoff]
. The function should return a Result<T, E>
type, where E
implements the From<E>
trait for backoff::Error<E>
.
Here's a basic example demonstrating how to use the #[backoff]
macro:
use backoff_macro::backoff;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::error::Error;
use tokio::main;
#[backoff]
async fn dummy_function(attempts: Arc<AtomicUsize>) -> Result<(), &'static str> {
let current_attempts = attempts.fetch_add(1, Ordering::SeqCst);
if current_attempts < 2 {
Err("error")
} else {
Ok(())
}
}
#[main]
async fn main() -> Result<(), Box<dyn Error>> {
let attempts = Arc::new(AtomicUsize::new(0));
let result = dummy_function(attempts.clone()).await;
match result {
Ok(_) => println!("Function succeeded after retries"),
Err(e) => println!("Function failed after retries: {}", e),
}
Ok(())
}
#[backoff]
to annotate the asynchronous function you want to apply retry logic to.backoff::future::retry
method.Result<T, E>
type.Contributions are welcome! If you find a bug or have a feature request, please open an issue on the GitHub repository.
This project is licensed under the MIT License. See the LICENSE file for details.