-
Notifications
You must be signed in to change notification settings - Fork 267
feat(lazer): add resilient client in rust #2859
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
0849884
0f612e7
49ed653
8f6845d
dd275dc
5679ae1
67022b6
efb3f8b
cb3803e
d80ffc6
856a925
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
use std::time::Duration; | ||
|
||
use backoff::{ | ||
default::{INITIAL_INTERVAL_MILLIS, MAX_INTERVAL_MILLIS, MULTIPLIER, RANDOMIZATION_FACTOR}, | ||
ExponentialBackoff, ExponentialBackoffBuilder, | ||
}; | ||
|
||
#[derive(Debug)] | ||
pub struct PythLazerExponentialBackoffBuilder { | ||
initial_interval: Duration, | ||
randomization_factor: f64, | ||
multiplier: f64, | ||
max_interval: Duration, | ||
} | ||
|
||
impl Default for PythLazerExponentialBackoffBuilder { | ||
fn default() -> Self { | ||
Self { | ||
initial_interval: Duration::from_millis(INITIAL_INTERVAL_MILLIS), | ||
randomization_factor: RANDOMIZATION_FACTOR, | ||
multiplier: MULTIPLIER, | ||
max_interval: Duration::from_millis(MAX_INTERVAL_MILLIS), | ||
} | ||
} | ||
} | ||
|
||
impl PythLazerExponentialBackoffBuilder { | ||
pub fn new() -> Self { | ||
Default::default() | ||
} | ||
|
||
/// The initial retry interval. | ||
pub fn with_initial_interval(&mut self, initial_interval: Duration) -> &mut Self { | ||
self.initial_interval = initial_interval; | ||
self | ||
} | ||
|
||
/// The randomization factor to use for creating a range around the retry interval. | ||
/// | ||
/// A randomization factor of 0.5 results in a random period ranging between 50% below and 50% | ||
/// above the retry interval. | ||
pub fn with_randomization_factor(&mut self, randomization_factor: f64) -> &mut Self { | ||
self.randomization_factor = randomization_factor; | ||
self | ||
} | ||
|
||
/// The value to multiply the current interval with for each retry attempt. | ||
pub fn with_multiplier(&mut self, multiplier: f64) -> &mut Self { | ||
self.multiplier = multiplier; | ||
self | ||
} | ||
|
||
/// The maximum value of the back off period. Once the retry interval reaches this | ||
/// value it stops increasing. | ||
pub fn with_max_interval(&mut self, max_interval: Duration) -> &mut Self { | ||
self.max_interval = max_interval; | ||
self | ||
} | ||
|
||
pub fn build(&self) -> ExponentialBackoff { | ||
ExponentialBackoffBuilder::default() | ||
.with_initial_interval(self.initial_interval) | ||
.with_randomization_factor(self.randomization_factor) | ||
.with_multiplier(self.multiplier) | ||
.with_max_interval(self.max_interval) | ||
.with_max_elapsed_time(None) | ||
.build() | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
use std::time::Duration; | ||
|
||
use crate::{ | ||
resilient_ws_connection::PythLazerResilientWSConnection, ws_connection::AnyResponse, | ||
CHANNEL_CAPACITY, | ||
}; | ||
use anyhow::{bail, Result}; | ||
use backoff::ExponentialBackoff; | ||
use pyth_lazer_protocol::subscription::{SubscribeRequest, SubscriptionId}; | ||
use tokio::sync::mpsc::{self, error::TrySendError}; | ||
use tracing::{error, warn}; | ||
use ttl_cache::TtlCache; | ||
use url::Url; | ||
|
||
const DEDUP_CACHE_SIZE: usize = 100_000; | ||
const DEDUP_TTL: Duration = Duration::from_secs(10); | ||
|
||
pub struct PythLazerClient { | ||
endpoints: Vec<Url>, | ||
access_token: String, | ||
num_connections: usize, | ||
ws_connections: Vec<PythLazerResilientWSConnection>, | ||
backoff: ExponentialBackoff, | ||
} | ||
|
||
impl PythLazerClient { | ||
/// Creates a new client instance | ||
/// | ||
/// # Arguments | ||
/// * `endpoints` - A vector of endpoint URLs | ||
/// * `access_token` - The access token for authentication | ||
/// * `num_connections` - The number of WebSocket connections to maintain | ||
pub fn new( | ||
endpoints: Vec<Url>, | ||
access_token: String, | ||
num_connections: usize, | ||
backoff: ExponentialBackoff, | ||
) -> Result<Self> { | ||
if backoff.max_elapsed_time.is_some() { | ||
bail!("max_elapsed_time is not supported in Pyth Lazer client"); | ||
} | ||
if endpoints.is_empty() { | ||
bail!("At least one endpoint must be provided"); | ||
} | ||
Ok(Self { | ||
endpoints, | ||
access_token, | ||
num_connections, | ||
ws_connections: Vec::with_capacity(num_connections), | ||
backoff, | ||
}) | ||
} | ||
|
||
pub async fn start(&mut self, channel_capacity: usize) -> Result<mpsc::Receiver<AnyResponse>> { | ||
let (sender, receiver) = mpsc::channel::<AnyResponse>(channel_capacity); | ||
let (ws_connection_sender, mut ws_connection_receiver) = | ||
mpsc::channel::<AnyResponse>(CHANNEL_CAPACITY); | ||
|
||
for i in 0..self.num_connections { | ||
let endpoint = self.endpoints[i % self.endpoints.len()].clone(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It will panic if There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed. |
||
let connection = PythLazerResilientWSConnection::new( | ||
endpoint, | ||
self.access_token.clone(), | ||
self.backoff.clone(), | ||
ws_connection_sender.clone(), | ||
); | ||
self.ws_connections.push(connection); | ||
} | ||
|
||
let mut seen_updates = TtlCache::new(DEDUP_CACHE_SIZE); | ||
|
||
tokio::spawn(async move { | ||
while let Some(response) = ws_connection_receiver.recv().await { | ||
let cache_key = response.cache_key(); | ||
if seen_updates.contains_key(&cache_key) { | ||
continue; | ||
} | ||
seen_updates.insert(cache_key, response.clone(), DEDUP_TTL); | ||
|
||
match sender.try_send(response) { | ||
Ok(_) => (), | ||
Err(TrySendError::Full(r)) => { | ||
warn!("Sender channel is full, responses will be delayed"); | ||
if sender.send(r).await.is_err() { | ||
error!("Sender channel is closed, stopping client"); | ||
} | ||
} | ||
Err(TrySendError::Closed(_)) => { | ||
error!("Sender channel is closed, stopping client"); | ||
} | ||
} | ||
} | ||
}); | ||
|
||
Ok(receiver) | ||
} | ||
|
||
pub async fn subscribe(&mut self, subscribe_request: SubscribeRequest) -> Result<()> { | ||
for connection in &mut self.ws_connections { | ||
connection.subscribe(subscribe_request.clone()).await?; | ||
} | ||
Ok(()) | ||
} | ||
|
||
pub async fn unsubscribe(&mut self, subscription_id: SubscriptionId) -> Result<()> { | ||
for connection in &mut self.ws_connections { | ||
connection.unsubscribe(subscription_id).await?; | ||
} | ||
Ok(()) | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this seems to be part of your public interface. you need to reexport it to downstream consumers. Other thing is to have a wrapper that has what you need (because i see you are not supporting everything there)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
added a builder wrapper.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A builder would also be nice for the
PythLazerClient
itself. You can movechannel_capacity
fromstart()
argument to the builder. The builder can also provide default values for everything exceptaccess_token
.