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

fix: add WASM-compatible retry mechanism for RPC requests #481

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
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
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@ helios-opstack = { path = "./opstack" }
tokio = { version = "1", features = ["full"] }
dotenv = "0.15.0"
serde = { version = "1.0.154", features = ["derive"] }
mockito = "0.31"
tracing = "0.1"

[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
alloy = { version = "0.2.1", features = ["full"] }
Expand Down
76 changes: 76 additions & 0 deletions core/execution/rpc/http_rpc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
use std::time::Duration;
Copy link
Collaborator

Choose a reason for hiding this comment

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

It seems that this is not in the right directory so isn't even being compiled? Should be in src/execution/rpc.

use wasmtimer::tokio::sleep;

/// Retry mechanism configuration
#[derive(Clone, Debug)]
pub struct RetryConfig {
/// Maximum number of attempts to execute the request
pub max_attempts: u32,
/// Initial delay between retry attempts
pub initial_backoff: Duration,
/// Maximum delay between retry attempts
pub max_backoff: Duration,
}

impl HttpProvider {
// Add the ability to configure retry settings
pub fn with_retry_config(mut self, config: RetryConfig) -> Self {
self.retry_config = config;
self
}

async fn execute_with_retry<T>(&self, request: Request<T>) -> Result<Response<T>, Error>
where
T: serde::Serialize + Send + Sync,
{
let mut attempts = 0;
let mut backoff = self.retry_config.initial_backoff;

loop {
attempts += 1;
match self.execute_internal(request.clone()).await {
Ok(response) => return Ok(response),
Err(err) => {
if !should_retry(&err) || attempts >= self.retry_config.max_attempts {
return Err(err.into());
}

tracing::debug!(
"Request failed with error: {:?}. Retrying ({}/{})",
err,
attempts,
self.retry_config.max_attempts
);

sleep(backoff).await;

backoff = std::cmp::min(
backoff * 2,
self.retry_config.max_backoff
);
}
}
}
}
}

// Extend the list of errors that can trigger a retry
fn should_retry(error: &Error) -> bool {
match error {
Error::RateLimitExceeded(_) => true,
Error::ConnectionError(_) => true,
Error::TimeoutError => true,
Error::ServerError(status) => status.as_u16() >= 500,
_ => false,
}
}

// Update the existing execute method to use the retry mechanism
impl Provider for HttpProvider {
async fn execute<T>(&self, request: Request<T>) -> Result<Response<T>, Error>
where
T: serde::Serialize + Send + Sync,
{
self.execute_with_retry(request).await
}
}
39 changes: 39 additions & 0 deletions core/execution/rpc/tests/http_rpc_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use mockito::{mock, Server};
use std::time::Duration;

#[tokio::test]
async fn test_retry_mechanism() {
let mut server = Server::new();

// Test successful retry after a temporary error
let mock = server.mock("POST", "/")
.with_status(429) // Rate limit error
.create();

let provider = HttpProvider::new(server.url().as_str());
let request = Request::new("eth_blockNumber", ());

let result = provider.execute(request).await;
assert!(result.is_err());
mock.assert_hits(1);

// Test the maximum number of retry attempts
let mock = server.mock("POST", "/")
.with_status(429)
.expect(3) // Expect exactly 3 attempts
.create();

let result = provider.execute(request).await;
assert!(result.is_err());
mock.assert();

// Test for errors that should not trigger retries
let mock = server.mock("POST", "/")
.with_status(400) // Bad Request
.expect(1) // Expect only 1 attempt
.create();

let result = provider.execute(request).await;
assert!(result.is_err());
mock.assert();
}
Loading