Skip to content
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

price-reporter: ws-server: Retry connection on send failure #43

Merged
merged 1 commit into from
Sep 6, 2024
Merged
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
38 changes: 24 additions & 14 deletions price-reporter/src/ws_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,23 @@ impl GlobalPriceStreams {
let mut conn =
Self::connect_with_retries(&pair_info, &config, &mut retry_timestamps).await?;

loop {
match Self::manage_connection(&mut conn, &price_tx).await {
Ok(()) => {},
Err(e) => {
conn = Self::exhaust_retries(e, &pair_info, &config, &mut retry_timestamps)
.await?;
},
}
}
}

/// Manages an exchange connection, sending keepalive messages and
/// forwarding prices to the price receiver
async fn manage_connection(
conn: &mut Box<dyn ExchangeConnection>,
price_tx: &PriceSender,
) -> Result<(), ServerError> {
let delay = tokio::time::sleep(Duration::from_millis(KEEPALIVE_INTERVAL_MS));
tokio::pin!(delay);

Expand All @@ -111,19 +128,8 @@ impl GlobalPriceStreams {

// Forward the next price into the broadcast channel
Some(price_res) = conn.next() => {
match price_res.map_err(ServerError::ExchangeConnection) {
Ok(price) => {
// `send` only errors if there are no more receivers, meaning no more
// clients are subscribed to this price stream. In this case, we remove
// the stream from the global map, and complete the task.
let _ = price_tx.send(price);
}
Err(e) => {
// We failed to stream a price, attempt to
// re-establish the connection
conn = Self::exhaust_retries(e, &pair_info, &config, &mut retry_timestamps).await?;
}
}
let price = price_res.map_err(ServerError::ExchangeConnection)?;
let _ = price_tx.send(price);
}
}
}
Expand Down Expand Up @@ -155,6 +161,7 @@ impl GlobalPriceStreams {
config: &ExchangeConnectionsConfig,
retry_timestamps: &mut Vec<Instant>,
) -> Result<Box<dyn ExchangeConnection>, ServerError> {
let exchange = pair_info.0;
loop {
prev_err = match Self::retry_connection(pair_info, config, retry_timestamps).await {
Ok(conn) => return Ok(conn),
Expand All @@ -165,7 +172,10 @@ impl GlobalPriceStreams {
error!("Exhausted retries for {}", exchange);
return Err(prev_err);
},
Err(e) => e,
Err(e) => {
warn!("Failed to reconnect to {exchange}: {e}");
e
},
};
}
}
Expand Down
Loading