Skip to content

Commit

Permalink
add lru cache backend; update arg parsing; add version to Cargo.lock;…
Browse files Browse the repository at this point in the history
… add caching for eth_maxPriorityFeePerGas
  • Loading branch information
dshiell committed Aug 8, 2024
1 parent c0c2610 commit 852daa2
Show file tree
Hide file tree
Showing 9 changed files with 236 additions and 20 deletions.
84 changes: 83 additions & 1 deletion Cargo.lock

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

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "cached-eth-rpc"
version = "0.1.0"
version = "1.0.3"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand All @@ -10,10 +10,12 @@ actix-web = "4.8"
alloy-primitives = { version = "0.7", features = ["serde"] }
anyhow = "1.0"
async-trait = "0.1"
chrono = "0.4.38"
clap = { version = "4.4", features = ["derive"] }
dashmap = { version = "6.0", features = ["serde"] }
env_logger = "0.11"
hex = "0.4"
lru = "0.12.4"
r2d2 = "0.8"
redis = { version = "0.24", features = ["r2d2", "async-std"] }
reqwest = { version = "0.11", features = ["rustls", "json", "serde_json"] }
Expand Down
16 changes: 16 additions & 0 deletions src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ pub struct Args {
#[arg(short, long = "endpoint", value_parser = endpoint_parser)]
pub endpoints: Vec<(String, Url)>,

#[arg(short, long, default_value = "100000")]
pub lru_max_items: usize,

#[arg(short, long = "cache", default_value = "lru", value_parser = cache_backend_parser)]
pub cache_type: String,

#[arg(
short,
long,
Expand All @@ -34,3 +40,13 @@ fn endpoint_parser(s: &str) -> Result<(String, Url), String> {

Ok((name, url))
}

fn cache_backend_parser(s: &str) -> Result<String, String> {
match s {
"memory" => {}
"lru" => {}
"redis" => {}
_ => return Err(format!("Invalid cache backend: {}", s)),
}
Ok(s.to_owned())
}
57 changes: 57 additions & 0 deletions src/cache/lru_backend.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use lru::LruCache;
use std::num::NonZeroUsize;
use std::sync::{Arc, Mutex};

use anyhow::Context;
use serde_json::{from_str, Value};

use super::{CacheBackend, CacheBackendFactory, CacheStatus};

pub struct LruBackendFactory {
data: Arc<Mutex<LruCache<String, String>>>,
}

impl LruBackendFactory {
pub fn new(cap: usize) -> Self {
Self {
data: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(cap).unwrap()))),
}
}
}

impl CacheBackendFactory for LruBackendFactory {
fn get_instance(&self) -> anyhow::Result<Box<dyn CacheBackend>> {
Ok(Box::new(LruBackend {
data: self.data.clone(),
}))
}
}

pub struct LruBackend {
data: Arc<Mutex<LruCache<String, String>>>,
}

impl CacheBackend for LruBackend {
fn read(&mut self, method: &str, params_key: &str) -> anyhow::Result<CacheStatus> {
let key = format!("{method}:{params_key}");

let mut lru_cache = self.data.lock().unwrap();
let v = match lru_cache.get(&key) {
Some(value) => {
let value = from_str::<Value>(&value).context("fail to deserialize cache value")?;

CacheStatus::Cached { key, value }
}

None => CacheStatus::Missed { key },
};

Ok(v)
}

fn write(&mut self, key: &str, value: &str) -> anyhow::Result<()> {
let mut lru_cache = self.data.lock().unwrap();
let _ = lru_cache.put(key.to_string(), value.to_string());
Ok(())
}
}
1 change: 1 addition & 0 deletions src/cache/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod lru_backend;
pub mod memory_backend;
pub mod redis_backend;

Expand Down
Loading

0 comments on commit 852daa2

Please sign in to comment.