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

feat(transport): retry layer #849

Merged
merged 19 commits into from
Jul 5, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
8 changes: 4 additions & 4 deletions crates/transport-http/src/hyper_transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,10 @@ where
trace!(body = %String::from_utf8_lossy(&body), "response body");

if status != hyper::StatusCode::OK {
return Err(TransportErrorKind::custom_str(&format!(
"HTTP error {status} with body: {}",
String::from_utf8_lossy(&body)
)));
return Err(TransportErrorKind::http_error(
status.as_u16() as i64,
String::from_utf8_lossy(&body).to_string(),
yash-atreya marked this conversation as resolved.
Show resolved Hide resolved
));
}

// Deser a Box<RawValue> from the body. If deser fails, return
Expand Down
8 changes: 4 additions & 4 deletions crates/transport-http/src/reqwest_transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,10 @@ impl Http<Client> {
trace!(body = %String::from_utf8_lossy(&body), "response body");

if status != reqwest::StatusCode::OK {
return Err(TransportErrorKind::custom_str(&format!(
"HTTP error {status} with body: {}",
String::from_utf8_lossy(&body)
)));
return Err(TransportErrorKind::http_error(
status.as_u16() as i64,
String::from_utf8_lossy(&body).to_string(),
yash-atreya marked this conversation as resolved.
Show resolved Hide resolved
));
}

// Deser a Box<RawValue> from the body. If deser fails, return
Expand Down
1 change: 1 addition & 0 deletions crates/transport/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ serde.workspace = true
thiserror.workspace = true
tower.workspace = true
url.workspace = true
tracing.workspace = true

[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen-futures = "0.4"
Expand Down
71 changes: 70 additions & 1 deletion crates/transport/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use alloy_json_rpc::{Id, RpcError, RpcResult};
use alloy_json_rpc::{ErrorPayload, Id, RpcError, RpcResult};
use serde_json::value::RawValue;
use std::{error::Error as StdError, fmt::Debug};
use thiserror::Error;
Expand Down Expand Up @@ -31,6 +31,10 @@ pub enum TransportErrorKind {
#[error("subscriptions are not available on this provider")]
PubsubUnavailable,

/// HTTP Error with code and body
#[error("{0}")]
HttpError(#[from] HTTPError),

/// Custom error.
#[error("{0}")]
Custom(#[source] Box<dyn StdError + Send + Sync + 'static>),
Expand Down Expand Up @@ -67,4 +71,69 @@ impl TransportErrorKind {
pub const fn pubsub_unavailable() -> TransportError {
RpcError::Transport(Self::PubsubUnavailable)
}

/// Instantiate a new `TrasnportError::HttpError`.
pub const fn http_error(status: i64, body: String) -> TransportError {
RpcError::Transport(Self::HttpError(HTTPError { status, body }))
}
}

/// Type for holding HTTP errors such as 429 or -32005 by the RPC provider.
#[derive(Debug, thiserror::Error)]
yash-atreya marked this conversation as resolved.
Show resolved Hide resolved
#[error("HTTP error {status} with body: {body}")]
pub struct HTTPError {
pub status: i64,
yash-atreya marked this conversation as resolved.
Show resolved Hide resolved
pub body: String,
yash-atreya marked this conversation as resolved.
Show resolved Hide resolved
}

impl HTTPError {
/// Analyzes the `status` and `body` to determine whether the request should be retried.
pub fn is_retry_err(&self) -> bool {
// alchemy throws it this way
if self.status == 429 {
return true;
}

// This is an infura error code for `exceeded project rate limit`
if self.status == -32005 {
return true;
}

// alternative alchemy error for specific IPs
if self.status == -32016 && self.body.contains("rate limit") {
return true;
}

// quick node error `"credits limited to 6000/sec"`
// <https://github.com/foundry-rs/foundry/pull/6712#issuecomment-1951441240>
if self.status == -32012 && self.body.contains("credits") {
return true;
}

// quick node rate limit error: `100/second request limit reached - reduce calls per second
// or upgrade your account at quicknode.com` <https://github.com/foundry-rs/foundry/issues/4894>
if self.status == -32007 && self.body.contains("request limit reached") {
return true;
}

match self.body.as_str() {
// this is commonly thrown by infura and is apparently a load balancer issue, see also <https://github.com/MetaMask/metamask-extension/issues/7234>
"header not found" => true,
// also thrown by infura if out of budget for the day and ratelimited
"daily request count exceeded, request rate limited" => true,
msg => {
msg.contains("rate limit")
|| msg.contains("rate exceeded")
|| msg.contains("too many requests")
|| msg.contains("credits limited")
|| msg.contains("request limit")
}
}
}
}

impl From<&ErrorPayload> for HTTPError {
fn from(value: &ErrorPayload) -> Self {
yash-atreya marked this conversation as resolved.
Show resolved Hide resolved
Self { status: value.code, body: value.message.clone() }
}
}
6 changes: 6 additions & 0 deletions crates/transport/src/layers/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
//! Module for housing transport layers.

mod retry;

/// RetryBackoffLayer
pub use retry::{RateLimitRetryPolicy, RetryBackoffLayer, RetryBackoffService, RetryPolicy};
Loading
Loading