Skip to content

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

Merged
merged 14 commits into from
Jul 23, 2025
Merged
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
20 changes: 19 additions & 1 deletion Cargo.lock

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

6 changes: 5 additions & 1 deletion lazer/sdk/rust/client/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "pyth-lazer-client"
version = "0.1.3"
version = "1.0.0"
edition = "2021"
description = "A Rust client for Pyth Lazer"
license = "Apache-2.0"
Expand All @@ -17,6 +17,9 @@ anyhow = "1.0"
tracing = "0.1"
url = "2.4"
derive_more = { version = "1.0.0", features = ["from"] }
backoff = { version = "0.4.0", features = ["futures", "tokio"] }
ttl_cache = "0.5.1"


[dev-dependencies]
bincode = "1.3.3"
Expand All @@ -25,3 +28,4 @@ hex = "0.4.3"
libsecp256k1 = "0.7.1"
bs58 = "0.5.1"
alloy-primitives = "0.8.19"
tracing-subscriber = { version = "0.3.19", features = ["env-filter", "json"] }
48 changes: 36 additions & 12 deletions lazer/sdk/rust/client/examples/subscribe_price_feeds.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use std::time::Duration;

use base64::Engine;
use futures_util::StreamExt;
use pyth_lazer_client::{AnyResponse, LazerClient};
use pyth_lazer_client::backoff::PythLazerExponentialBackoffBuilder;
use pyth_lazer_client::client::PythLazerClientBuilder;
use pyth_lazer_client::ws_connection::AnyResponse;
use pyth_lazer_protocol::message::{
EvmMessage, LeEcdsaMessage, LeUnsignedMessage, Message, SolanaMessage,
};
Expand All @@ -9,8 +12,10 @@ use pyth_lazer_protocol::router::{
Channel, DeliveryFormat, FixedRate, Format, JsonBinaryEncoding, PriceFeedId, PriceFeedProperty,
SubscriptionParams, SubscriptionParamsRepr,
};
use pyth_lazer_protocol::subscription::{Request, Response, SubscribeRequest, SubscriptionId};
use pyth_lazer_protocol::subscription::{Response, SubscribeRequest, SubscriptionId};
use tokio::pin;
use tracing::level_filters::LevelFilter;
use tracing_subscriber::EnvFilter;

fn get_lazer_access_token() -> String {
// Place your access token in your env at LAZER_ACCESS_TOKEN or set it here
Expand All @@ -20,11 +25,32 @@ fn get_lazer_access_token() -> String {

#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt()
.with_env_filter(
EnvFilter::builder()
.with_default_directive(LevelFilter::INFO.into())
.from_env()?,
)
.json()
.init();

// Create and start the client
let mut client = LazerClient::new(
"wss://pyth-lazer.dourolabs.app/v1/stream",
&get_lazer_access_token(),
)?;
let mut client = PythLazerClientBuilder::new(get_lazer_access_token())
// Optionally override the default endpoints
.with_endpoints(vec![
"wss://pyth-lazer-0.dourolabs.app/v1/stream".parse()?,
"wss://pyth-lazer-1.dourolabs.app/v1/stream".parse()?,
])
// Optionally set the number of connections
.with_num_connections(4)
// Optionally set the backoff strategy
.with_backoff(PythLazerExponentialBackoffBuilder::default().build())
// Optionally set the timeout for each connection
.with_timeout(Duration::from_secs(5))
// Optionally set the channel capacity for responses
.with_channel_capacity(1000)
.build()?;

let stream = client.start().await?;
pin!(stream);

Expand Down Expand Up @@ -72,16 +98,16 @@ async fn main() -> anyhow::Result<()> {
];

for req in subscription_requests {
client.subscribe(Request::Subscribe(req)).await?;
client.subscribe(req).await?;
}

println!("Subscribed to price feeds. Waiting for updates...");

// Process the first few updates
let mut count = 0;
while let Some(msg) = stream.next().await {
while let Some(msg) = stream.recv().await {
// The stream gives us base64-encoded binary messages. We need to decode, parse, and verify them.
match msg? {
match msg {
AnyResponse::Json(msg) => match msg {
Response::StreamUpdated(update) => {
println!("Received a JSON update for {:?}", update.subscription_id);
Expand Down Expand Up @@ -189,8 +215,6 @@ async fn main() -> anyhow::Result<()> {
println!("Unsubscribed from {sub_id:?}");
}

tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
client.close().await?;
Ok(())
}

Expand Down
69 changes: 69 additions & 0 deletions lazer/sdk/rust/client/src/backoff.rs
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 {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

document here as well? maybe default as well?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason I didn't implement default is that we need to have access token. Default doesn't make sense since it will be in an invalid state.

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()
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm fine with this but generally my take was reexposing what we use in the API and we still use ExponentialBackoff from the backoff crate. now that you have a builder it makes sense that you have your own wrapper type for the api of the lazer client. later when you convert it you can remove the following error as well: bail!("max_elapsed_time is not supported in Pyth Lazer client");

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah it's a good improvement. I'll add this + docs in another PR to unblock the progress of monitor for now.

}
Loading