-
Notifications
You must be signed in to change notification settings - Fork 300
Remove blocking IO #1803
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
Merged
Merged
Remove blocking IO #1803
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
This file contains hidden or 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 hidden or 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 |
---|---|---|
@@ -1,166 +1,32 @@ | ||
use std::any::Any; | ||
use std::collections::HashMap; | ||
use std::error::Error; | ||
use std::sync::RwLock; | ||
use std::sync::Arc; | ||
use std::time::Instant; | ||
|
||
use rocket::tokio::sync::RwLock; | ||
use rocket::tokio::task; | ||
|
||
type CacheItem = (Box<dyn Any + Send + Sync>, Instant); | ||
type Generator = fn() -> Result<Box<dyn Any>, Box<dyn Error>>; | ||
use rocket::State; | ||
|
||
const CACHE_TTL_SECS: u64 = 120; | ||
|
||
lazy_static! { | ||
static ref CACHE: RwLock<HashMap<Generator, CacheItem>> = RwLock::new(HashMap::new()); | ||
} | ||
|
||
pub async fn get<T>(generator: Generator) -> Result<T, Box<dyn Error>> | ||
where | ||
T: Send + Sync + Clone + 'static, | ||
{ | ||
if let Some(cached) = get_cached(generator) { | ||
Ok(cached) | ||
} else { | ||
task::spawn_blocking(move || { | ||
update_cache::<T>(generator) | ||
// stringify the error to make it Send | ||
.map_err(|e| e.to_string()) | ||
}) | ||
.await | ||
.map_err(Box::new)? | ||
// put the previously stringified error back in a box | ||
.map_err(|e| e.as_str().into()) | ||
} | ||
} | ||
pub type Cache<T> = State<Arc<RwLock<T>>>; | ||
|
||
fn get_cached<T>(generator: Generator) -> Option<T> | ||
where | ||
T: Send + Sync + Clone + 'static, | ||
{ | ||
let cache = CACHE.read().unwrap(); | ||
cache.get(&generator).map(|&(ref data, timestamp)| { | ||
#[async_trait] | ||
pub trait Cached: Send + Sync + Clone + 'static { | ||
fn get_timestamp(&self) -> Instant; | ||
async fn fetch() -> Result<Self, Box<dyn Error + Send + Sync>>; | ||
async fn get(cache: &Cache<Self>) -> Self { | ||
let cached = cache.read().await.clone(); | ||
let timestamp = cached.get_timestamp(); | ||
if timestamp.elapsed().as_secs() > CACHE_TTL_SECS { | ||
// Update the cache in the background | ||
task::spawn_blocking(move || { | ||
let _ = update_cache::<T>(generator); | ||
let cache: Arc<_> = cache.inner().clone(); | ||
task::spawn(async move { | ||
match Self::fetch().await { | ||
Ok(data) => *cache.write().await = data, | ||
Err(e) => eprintln!("failed to update cache: {e}"), | ||
} | ||
}); | ||
} | ||
data.downcast_ref::<T>().unwrap().clone() | ||
}) | ||
} | ||
|
||
fn update_cache<T>(generator: Generator) -> Result<T, Box<dyn Error>> | ||
where | ||
T: Send + Sync + Clone + 'static, | ||
{ | ||
if let Ok(data) = generator()?.downcast::<T>() { | ||
let cloned: T = (*data).clone(); | ||
CACHE | ||
.write() | ||
.unwrap() | ||
.insert(generator, (Box::new(cloned), Instant::now())); | ||
Ok(*data) | ||
} else { | ||
Err("the generator returned the wrong type".into()) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use rocket::tokio; | ||
|
||
use super::{get, Generator, CACHE, CACHE_TTL_SECS}; | ||
use std::any::Any; | ||
use std::error::Error; | ||
use std::sync::atomic::{AtomicBool, Ordering}; | ||
use std::thread; | ||
use std::time::{Duration, Instant}; | ||
|
||
#[tokio::test] | ||
async fn test_cache_basic() { | ||
static GENERATOR_CALLED: AtomicBool = AtomicBool::new(false); | ||
|
||
fn generator() -> Result<Box<dyn Any>, Box<dyn Error>> { | ||
GENERATOR_CALLED.store(true, Ordering::SeqCst); | ||
Ok(Box::new("hello world")) | ||
} | ||
|
||
// The first time it will call the generator | ||
GENERATOR_CALLED.store(false, Ordering::SeqCst); | ||
assert_eq!(get::<&'static str>(generator).await.unwrap(), "hello world"); | ||
assert!(GENERATOR_CALLED.load(Ordering::SeqCst)); | ||
|
||
// The second time it won't call the generator, but reuse the latest value | ||
GENERATOR_CALLED.store(false, Ordering::SeqCst); | ||
assert_eq!(get::<&'static str>(generator).await.unwrap(), "hello world"); | ||
assert!(!GENERATOR_CALLED.load(Ordering::SeqCst)); | ||
} | ||
|
||
#[tokio::test] | ||
async fn test_cache_refresh() { | ||
static GENERATOR_CALLED: AtomicBool = AtomicBool::new(false); | ||
|
||
fn generator() -> Result<Box<dyn Any>, Box<dyn Error>> { | ||
GENERATOR_CALLED.store(true, Ordering::SeqCst); | ||
thread::sleep(Duration::from_millis(100)); | ||
Ok(Box::new("hello world")) | ||
} | ||
|
||
// Initialize the value in the cache | ||
GENERATOR_CALLED.store(false, Ordering::SeqCst); | ||
assert_eq!(get::<&'static str>(generator).await.unwrap(), "hello world"); | ||
assert!(GENERATOR_CALLED.load(Ordering::SeqCst)); | ||
|
||
// Tweak the cache to fake an expired TTL | ||
let expired = Instant::now() - Duration::from_secs(CACHE_TTL_SECS * 2); | ||
CACHE | ||
.write() | ||
.unwrap() | ||
.get_mut(&(generator as Generator)) | ||
.unwrap() | ||
.1 = expired; | ||
|
||
// The second time it won't call the generator, but start another thread to refresh the | ||
// value in the background | ||
GENERATOR_CALLED.store(false, Ordering::SeqCst); | ||
assert_eq!(get::<&'static str>(generator).await.unwrap(), "hello world"); | ||
assert!(!GENERATOR_CALLED.load(Ordering::SeqCst)); | ||
|
||
// Then the background updater thread will finish | ||
thread::sleep(Duration::from_millis(200)); | ||
assert!(GENERATOR_CALLED.load(Ordering::SeqCst)); | ||
} | ||
|
||
#[tokio::test] | ||
async fn test_errors_skip_cache() { | ||
static GENERATOR_CALLED: AtomicBool = AtomicBool::new(false); | ||
|
||
fn generator() -> Result<Box<dyn Any>, Box<dyn Error>> { | ||
GENERATOR_CALLED.store(true, Ordering::SeqCst); | ||
Err("an error".into()) | ||
} | ||
|
||
// The first time it will call the generator | ||
GENERATOR_CALLED.store(false, Ordering::SeqCst); | ||
assert_eq!( | ||
get::<&'static str>(generator) | ||
.await | ||
.unwrap_err() | ||
.to_string(), | ||
"an error" | ||
); | ||
assert!(GENERATOR_CALLED.load(Ordering::SeqCst)); | ||
|
||
// The second time it will also call the generator | ||
GENERATOR_CALLED.store(false, Ordering::SeqCst); | ||
assert_eq!( | ||
get::<&'static str>(generator) | ||
.await | ||
.unwrap_err() | ||
.to_string(), | ||
"an error" | ||
); | ||
assert!(GENERATOR_CALLED.load(Ordering::SeqCst)); | ||
cached | ||
} | ||
} |
This file contains hidden or 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
Oops, something went wrong.
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.
This is a change in behavior, the caches will now already be prefilled with data at startup. Previously, I think the first request using a cache would actually block until some data could be retrieved.
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.
I think that's a good call, yeah.