This repository has been archived by the owner on Oct 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 794
feat: cached provider PoC #949
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||
---|---|---|---|---|
@@ -0,0 +1,98 @@ | ||||
use crate::ProviderError; | ||||
use dashmap::DashMap; | ||||
use serde::{de::DeserializeOwned, Deserialize, Serialize}; | ||||
use std::{ | ||||
fs::File, | ||||
io::{BufReader, BufWriter}, | ||||
path::PathBuf, | ||||
}; | ||||
|
||||
#[derive(Clone, Debug, Default)] | ||||
/// Simple in-memory K-V cache using concurrent dashmap which flushes | ||||
/// its state to disk on `Drop`. | ||||
pub struct Cache { | ||||
path: PathBuf, | ||||
// serialized request / response pair | ||||
requests: DashMap<String, String>, | ||||
} | ||||
|
||||
// Helper type for (de)serialization | ||||
#[derive(Serialize, Deserialize)] | ||||
struct CachedRequest<'a, T> { | ||||
method: &'a str, | ||||
params: T, | ||||
} | ||||
|
||||
impl Cache { | ||||
/// Instantiates a new cache at a file path. | ||||
pub fn new(path: PathBuf) -> Result<Self, ProviderError> { | ||||
// try to read the already existing requests | ||||
let reader = | ||||
BufReader::new(File::options().write(true).read(true).create(true).open(&path)?); | ||||
let requests = serde_json::from_reader(reader).unwrap_or_default(); | ||||
Ok(Self { path, requests }) | ||||
} | ||||
|
||||
pub fn get<T: Serialize, R: DeserializeOwned>( | ||||
&self, | ||||
method: &str, | ||||
params: &T, | ||||
) -> Result<Option<R>, ProviderError> { | ||||
let key = serde_json::to_string(&CachedRequest { method, params })?; | ||||
let value = self.requests.get(&key); | ||||
value.map(|x| serde_json::from_str(&x).map_err(ProviderError::SerdeJson)).transpose() | ||||
} | ||||
|
||||
pub fn set<T: Serialize, R: Serialize>( | ||||
&self, | ||||
method: &str, | ||||
params: T, | ||||
response: R, | ||||
) -> Result<(), ProviderError> { | ||||
let key = serde_json::to_string(&CachedRequest { method, params })?; | ||||
let value = serde_json::to_string(&response)?; | ||||
self.requests.insert(key, value); | ||||
Ok(()) | ||||
} | ||||
} | ||||
|
||||
impl Drop for Cache { | ||||
fn drop(&mut self) { | ||||
let file = match File::options().write(true).read(true).create(true).open(&self.path) { | ||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this should be
|
||||
Ok(inner) => BufWriter::new(inner), | ||||
Err(err) => { | ||||
tracing::error!("could not open cache file {}", err); | ||||
return | ||||
} | ||||
}; | ||||
|
||||
// overwrite the cache | ||||
if let Err(err) = serde_json::to_writer(file, &self.requests) { | ||||
tracing::error!("could not write to cache file {}", err); | ||||
}; | ||||
} | ||||
} | ||||
|
||||
#[cfg(test)] | ||||
mod tests { | ||||
use crate::{Middleware, Provider}; | ||||
use ethers_core::types::{Address, U256}; | ||||
|
||||
#[tokio::test] | ||||
async fn test_cache() { | ||||
let tmp = tempfile::tempdir().unwrap(); | ||||
let cache = tmp.path().join("cache"); | ||||
let (provider, mock) = Provider::mocked(); | ||||
let provider = provider.with_cache(cache.clone()); | ||||
let addr = Address::random(); | ||||
|
||||
assert!(provider.cache().unwrap().requests.is_empty()); | ||||
|
||||
mock.push(U256::from(100u64)).unwrap(); | ||||
let res = provider.get_balance(addr, None).await.unwrap(); | ||||
assert_eq!(res, 100.into()); | ||||
|
||||
assert!(!provider.cache().unwrap().requests.is_empty()); | ||||
dbg!(&provider.cache()); | ||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||
} | ||||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
should this be <String, serde_json::Value>?