Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 6 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,17 @@ exclude = [
]

[features]
default = ["tokio"]
default = ["tokio", "std"]
std = ["log/std", "rand/std", "futures/std"]
not-send = []

[dependencies]
tokio = { version = "1", features = ["time"], optional = true }
async-std = { version = "1", optional = true }
log = "0.4"
rand = "0.8"
futures = "0.3"
log = { version = "0.4", default-features = false }
rand = { version = "0.8", default-features = false, features = ["small_rng"] }
futures = { version = "0.3", default-features = false, features = ["alloc"] }
dyn-clone = "1.0"

[dev-dependencies]
tokio = { version = "1", features = ["macros", "rt", "sync"] }
Expand Down
14 changes: 6 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ To use with your project, add the following to your Cargo.toml:
stream-reconnect = "0.3"
```

*Minimum supported rust version: 1.43.1*
_Minimum supported rust version: 1.43.1_

## Runtime Support

Expand Down Expand Up @@ -54,12 +54,10 @@ impl UnderlyingStream<String, Result<Message, WsError>, WsError> for MyWs {

// Establishes connection.
// Additionally, this will be used when reconnect tries are attempted.
fn establish(addr: String) -> Pin<Box<dyn Future<Output = Result<Self::Stream, WsError>> + Send>> {
Box::pin(async move {
// In this case, we are trying to connect to the WebSocket endpoint
let ws_connection = connect_async(addr).await.unwrap().0;
Ok(ws_connection)
})
async fn establish(addr: String) -> Result<Self::Stream, WsError> {
// In this case, we are trying to connect to the WebSocket endpoint
let ws_connection = connect_async(addr).await.unwrap().0;
Ok(ws_connection)
}

// The following errors are considered disconnect errors.
Expand Down Expand Up @@ -97,4 +95,4 @@ ws_stream.send("hello world!".into()).await.unwrap();

## License

MIT
MIT
41 changes: 39 additions & 2 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
//! specifically related to reconnect behavior.

use crate::strategies::ExpBackoffStrategy;
use std::sync::Arc;
use std::time::Duration;
use alloc::{boxed::Box, sync::Arc};
use core::time::Duration;
use futures::future::BoxFuture;

pub type DurationIterator = Box<dyn Iterator<Item = Duration> + Send + Sync>;

Expand All @@ -27,6 +28,11 @@ impl ReconnectOptions {
pub(crate) fn on_connect_fail_callback(&self) -> &Arc<dyn Fn() + Send + Sync> {
&self.0.on_connect_fail_callback
}
pub(crate) fn sleep_provider(
&self,
) -> Arc<dyn Fn(Duration) -> BoxFuture<'static, ()> + Send + Sync> {
self.0.sleep_provider.clone()
}
}

#[derive(Clone)]
Expand All @@ -36,20 +42,51 @@ struct Inner {
on_connect_callback: Arc<dyn Fn() + Send + Sync>,
on_disconnect_callback: Arc<dyn Fn() + Send + Sync>,
on_connect_fail_callback: Arc<dyn Fn() + Send + Sync>,
sleep_provider: Arc<dyn Fn(Duration) -> BoxFuture<'static, ()> + Send + Sync>,
}

impl ReconnectOptions {
/// By default, the [ReconnectStream](crate::ReconnectStream) will not try to reconnect if the first connect attempt fails.
/// By default, the retries iterator waits longer and longer between reconnection attempts,
/// until it eventually perpetually tries to reconnect every 30 minutes.
#[allow(clippy::new_without_default)]
#[cfg(feature = "std")]
pub fn new() -> Self {
ReconnectOptions(Box::new(Inner {
retries_to_attempt_fn: Arc::new(|| Box::new(ExpBackoffStrategy::default().into_iter())),
exit_if_first_connect_fails: true,
on_connect_callback: Arc::new(|| {}),
on_disconnect_callback: Arc::new(|| {}),
on_connect_fail_callback: Arc::new(|| {}),
sleep_provider: Arc::new(|duration| {
Box::pin({
#[cfg(feature = "tokio")]
{
tokio::time::sleep(duration)
}
#[cfg(feature = "async-std")]
{
async_std::task::sleep(delay)
}
})
}),
}))
}

/// By default, the [ReconnectStream](crate::ReconnectStream) will not try to reconnect if the first connect attempt fails.
/// By default, the retries iterator waits longer and longer between reconnection attempts,
/// until it eventually perpetually tries to reconnect every 30 minutes.
#[allow(clippy::new_without_default)]
pub fn with_sleep_provider(
sleep_provider: impl Fn(Duration) -> BoxFuture<'static, ()> + Send + Sync + 'static,
) -> Self {
ReconnectOptions(Box::new(Inner {
retries_to_attempt_fn: Arc::new(|| Box::new(ExpBackoffStrategy::default().into_iter())),
exit_if_first_connect_fails: true,
on_connect_callback: Arc::new(|| {}),
on_disconnect_callback: Arc::new(|| {}),
on_connect_fail_callback: Arc::new(|| {}),
sleep_provider: Arc::new(sleep_provider),
}))
}

Expand Down
9 changes: 9 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,15 @@
//! # fn main() {}
//! ```

#![cfg_attr(not(any(feature = "std", test)), no_std)]
#![warn(
clippy::alloc_instead_of_core,
clippy::std_instead_of_alloc,
clippy::std_instead_of_core
)]

extern crate alloc;

#[doc(inline)]
pub use crate::config::ReconnectOptions;
pub use crate::stream::{ReconnectStream, UnderlyingStream};
Expand Down
61 changes: 47 additions & 14 deletions src/strategies.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,18 @@
//! Provides the strategies used in stubborn io items
use rand::{rngs::StdRng, Rng, SeedableRng};
use std::time::Duration;
use alloc::boxed::Box;
use core::time::Duration;
use dyn_clone::DynClone;
use rand::{Rng, RngCore, SeedableRng};

#[cfg(feature = "std")]
use rand::rngs::StdRng;

#[cfg(not(feature = "std"))]
use rand::rngs::SmallRng;

pub trait RngCoreClone: RngCore + Send + Sync + DynClone {}
dyn_clone::clone_trait_object!(RngCoreClone);
impl<R> RngCoreClone for R where R: RngCore + Send + Sync + Clone {}

/// Type used for defining the exponential backoff strategy.
/// # Examples
Expand All @@ -24,7 +36,7 @@ pub struct ExpBackoffStrategy {
max: Option<Duration>,
factor: f64,
jitter: f64,
seed: Option<u64>,
rng: Option<Box<dyn RngCoreClone + Send + Sync>>,
}

impl ExpBackoffStrategy {
Expand All @@ -34,7 +46,7 @@ impl ExpBackoffStrategy {
max: None,
factor,
jitter,
seed: None,
rng: None,
}
}

Expand All @@ -46,8 +58,22 @@ impl ExpBackoffStrategy {
}

/// Set the seed used to generate jitter. Otherwise, will set RNG via entropy.
pub fn with_seed(mut self, seed: u64) -> Self {
self.seed = Some(seed);
pub fn with_seed(self, seed: u64) -> Self {
self.with_rng({
#[cfg(feature = "std")]
{
StdRng::seed_from_u64(seed)
}
#[cfg(not(feature = "std"))]
{
SmallRng::seed_from_u64(seed)
}
})
}

/// Set the RNG used to generate jitter. Otherwise, will set RNG via entropy.
pub fn with_rng<R: RngCoreClone + Send + Sync + 'static>(mut self, rng: R) -> Self {
self.rng = Some(Box::new(rng));
self
}
}
Expand All @@ -59,7 +85,7 @@ impl Default for ExpBackoffStrategy {
max: Some(Duration::from_secs(30 * 60)),
factor: 2.0,
jitter: 0.05,
seed: None,
rng: None,
}
}
}
Expand All @@ -70,11 +96,18 @@ impl IntoIterator for ExpBackoffStrategy {

fn into_iter(self) -> Self::IntoIter {
let init = self.min.as_secs_f64();
let rng = match self.seed {
Some(seed) => StdRng::seed_from_u64(seed),
None => StdRng::from_entropy(),
};

let rng = self.rng.clone().unwrap_or_else(|| {
Box::new({
#[cfg(feature = "std")]
{
StdRng::from_entropy()
}
#[cfg(not(feature = "std"))]
{
SmallRng::from_entropy()
}
})
});
ExpBackoffIter {
strategy: self,
init,
Expand All @@ -89,7 +122,7 @@ pub struct ExpBackoffIter {
strategy: ExpBackoffStrategy,
init: f64,
pow: u32,
rng: StdRng,
rng: Box<dyn RngCoreClone>,
}

impl Iterator for ExpBackoffIter {
Expand All @@ -110,7 +143,7 @@ impl Iterator for ExpBackoffIter {
#[cfg(test)]
mod test {
use super::ExpBackoffStrategy;
use std::time::Duration;
use core::time::Duration;

#[test]
fn test_exponential_backoff_jitter_values() {
Expand Down
Loading