General-purpose retrying library, written in Rust, to simplify the task of adding retry behavior to functions.
Support sync and async (tokio, async-std) functions.
tokio - builds retrying for using with tokio asynchronous runtime. async_std - builds retrying for using with tokio asynchronous runtime.
The main public interface in retrying is retrying::retry
macros.
#[retrying::retry]
fn my_function(){}
This macros has a lot of configuration options and allows developers to write fault tolerant functions without thinking about implementation of retry functionality.
Config option | OS Environments | Default | Description |
---|---|---|---|
stop=attempts(u32 ) |
{PREFIX}__STOP__ATTEMPTS | std::usize::MAX | Number of retries |
stop=delay(u32 ) |
{PREFIX}__STOP__DELAY | std::usize::MAX | Retrying period (seconds) |
You can combine several stop conditions by using the or(||
) operator. For example, configuration
#[retrying::retry(stop=(attempts(10)||delay(60)))]
fn my_function(){}
means function should retry 10 times but doesn't make new attemp after 60 seconds.
Config option | OS Environments | Default | Description |
---|---|---|---|
wait=fixed(u32 ) |
{PREFIX}__WAIT__FIXED | 0 | Number of seconds between retries |
wait=random(min=u32 ,max=u32 ) |
{PREFIX}__WAIT__RANDOM__(MIN|MAX) | min=0,max=3600 | Randomly wait min to max seconds between retries |
wait=exponential(multiplier=u32 , min=u32 , max=u32 , exp_base=u32 ) |
{PREFIX}__WAIT__EXPONENTIAL__(MULTIPLIER|MIN|MAX|EXP_BASE) | multiplier=1, min=0,max=3600, exp_base=2 | Wait multiplier * exp_base^(num of retry - 1) + min seconds between each retry starting with min seconds, then up to max seconds, then max seconds afterwards |
Only one wait option possible.
Config option | OS Environments | Default | Description |
---|---|---|---|
retry=if_exception(exception1|exception2) | {PREFIX}__RETRY__RETRY_IF_EXCEPTION | - | Retry only on specific exeptions |
retry=if_not_exception(exception1|exception2) | {PREFIX}__RETRY__RETRY_IF_NOT_EXCEPTION | - | Don't retry on specific list of exeptions |
Retrying allow to override macros configuration in runtime using env variables. To enable this feature you need to specify prefix for configuration env variable like
#[retrying::retry(env_prefix="test")]
Also, it is possible to combine macros configuration option with env_prefix
but take into account that OS environment variables has higher priority than options configuration in code.
For example,
#[retrying::retry(stop=attempts(2), env_prefix="test")]
In runtime macros will check availability of OS env variable TEST__STOP__STOP_AFTER_ATTEMPT and if variable is set then number of retry attempt will be the value of TEST__STOP__ATTEMPTS.
Examples are available in ./crates/retrying/example and can be tested using cargo. Sync:
cargo run --example sync
Async tokio:
cargo run --features="tokio" --example tokio
Async async-std:
cargo run --features="async_std" --example async_std