lighthouse/common/fallback/src/lib.rs
Mac L 0847986936 Reduce outbound requests to eth1 endpoints (#2340)
## Issue Addressed

#2282 

## Proposed Changes

Reduce the outbound requests made to eth1 endpoints by caching the results from `eth_chainId` and `net_version`.
Further reduce the overall request count by increasing `auto_update_interval_millis` from `7_000` (7 seconds) to `60_000` (1 minute). 
This will result in a reduction from ~2000 requests per hour to 360 requests per hour (during normal operation). A reduction of 82%.

## Additional Info

If an endpoint fails, its state is dropped from the cache and the `eth_chainId` and `net_version` calls will be made for that endpoint again during the regular update cycle (once per minute) until it is back online.


Co-authored-by: Paul Hauner <paul@paulhauner.com>
2021-05-31 04:18:18 +00:00

60 lines
1.5 KiB
Rust

use itertools::{join, zip};
use std::fmt::{Debug, Display};
use std::future::Future;
#[derive(Clone)]
pub struct Fallback<T> {
pub servers: Vec<T>,
}
#[derive(Debug, PartialEq)]
pub enum FallbackError<E> {
AllErrored(Vec<E>),
}
impl<T> Fallback<T> {
pub fn new(servers: Vec<T>) -> Self {
Self { servers }
}
/// Return the first successful result or all errors encountered.
pub async fn first_success<'a, F, O, E, R>(&'a self, func: F) -> Result<O, FallbackError<E>>
where
F: Fn(&'a T) -> R,
R: Future<Output = Result<O, E>>,
{
let mut errors = vec![];
for server in &self.servers {
match func(server).await {
Ok(val) => return Ok(val),
Err(e) => errors.push(e),
}
}
Err(FallbackError::AllErrored(errors))
}
pub fn map_format_error<'a, E, F, S>(&'a self, f: F, error: &FallbackError<E>) -> String
where
F: FnMut(&'a T) -> &'a S,
S: Display + 'a,
E: Debug,
{
match error {
FallbackError::AllErrored(v) => format!(
"All fallback errored: {}",
join(
zip(self.servers.iter().map(f), v.iter())
.map(|(server, error)| format!("{} => {:?}", server, error)),
", "
)
),
}
}
}
impl<T: Display> Fallback<T> {
pub fn format_error<E: Debug>(&self, error: &FallbackError<E>) -> String {
self.map_format_error(|s| s, error)
}
}