Add automatic websocket reconnection
Signed-off-by: Nikolaos Karaolidis <nick@karaolidis.com>
This commit is contained in:
42
src/lib/alpaca/clock.rs
Normal file
42
src/lib/alpaca/clock.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use crate::types::alpaca::api::incoming::clock::Clock;
|
||||
use backoff::{future::retry_notify, ExponentialBackoff};
|
||||
use governor::DefaultDirectRateLimiter;
|
||||
use log::warn;
|
||||
use reqwest::{Client, Error};
|
||||
use std::time::Duration;
|
||||
|
||||
pub async fn get(
|
||||
client: &Client,
|
||||
rate_limiter: &DefaultDirectRateLimiter,
|
||||
backoff: Option<ExponentialBackoff>,
|
||||
api_base: &str,
|
||||
) -> Result<Clock, Error> {
|
||||
retry_notify(
|
||||
backoff.unwrap_or_default(),
|
||||
|| async {
|
||||
rate_limiter.until_ready().await;
|
||||
client
|
||||
.get(&format!("https://{}.alpaca.markets/v2/clock", api_base))
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()
|
||||
.map_err(|e| match e.status() {
|
||||
Some(reqwest::StatusCode::BAD_REQUEST | reqwest::StatusCode::FORBIDDEN) => {
|
||||
backoff::Error::Permanent(e)
|
||||
}
|
||||
_ => e.into(),
|
||||
})?
|
||||
.json::<Clock>()
|
||||
.await
|
||||
.map_err(backoff::Error::Permanent)
|
||||
},
|
||||
|e, duration: Duration| {
|
||||
warn!(
|
||||
"Failed to get clock, will retry in {} seconds: {}.",
|
||||
duration.as_secs(),
|
||||
e
|
||||
);
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
Reference in New Issue
Block a user