Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Prevent retention of cached object reference across async boundary #195

Closed
Closed
Show file tree
Hide file tree
Changes from all 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
14 changes: 14 additions & 0 deletions Cargo.lock

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

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ log = "0.4.17"
env_logger = "0.10.0"
mime_guess = "2.0.4"
futures-util = "0.3.21"
tokio = { version = "1.24.1", features = ["macros", "rt", "process", "sync"] }
dashmap = "5.5.1"
tokio = { version = "1.24.1", features = ["macros", "rt", "process"] }
tokio-stream = "0.1.9"
anyhow = "1"
serde = "1"
Expand Down
34 changes: 17 additions & 17 deletions src/file_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use actix_web::http::StatusCode;
use anyhow::Context;
use async_trait::async_trait;
use chrono::{DateTime, TimeZone, Utc};
use dashmap::DashMap;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::atomic::{
Expand All @@ -12,7 +13,6 @@ use std::sync::atomic::{
};
use std::sync::Arc;
use std::time::SystemTime;
use tokio::sync::RwLock;

/// The maximum time in milliseconds that a file can be cached before its freshness is checked
/// (in production mode)
Expand Down Expand Up @@ -68,7 +68,7 @@ impl<T> Cached<T> {
}

pub struct FileCache<T: AsyncFromStrWithState> {
cache: Arc<RwLock<HashMap<PathBuf, Cached<T>>>>,
cache: Arc<DashMap<PathBuf, Cached<T>>>,
/// Files that are loaded at the beginning of the program,
/// and used as fallback when there is no match for the request in the file system
static_files: HashMap<PathBuf, Cached<T>>,
Expand Down Expand Up @@ -96,21 +96,25 @@ impl<T: AsyncFromStrWithState> FileCache<T> {
}

pub async fn get(&self, app_state: &AppState, path: &PathBuf) -> anyhow::Result<Arc<T>> {
log::trace!("Attempting to get from cache {:?}", path);
if let Some(cached) = self.cache.read().await.get(path) {
if let Some(cached) = self.cache.get(path) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we just need to clone the result of self.cache.get before if..let here.

if app_state.config.environment.is_prod() && !cached.needs_check() {
log::trace!("Cache answer without filesystem lookup for {:?}", path);
return Ok(Arc::clone(&cached.content));
}
match app_state
.file_system
.modified_since(app_state, path, cached.last_check_time(), true)
.await
{
let modified_res = app_state.file_system.modified_since(
app_state,
path,
cached.last_check_time(),
true,
);
drop(cached);
match modified_res.await {
Ok(false) => {
log::trace!("Cache answer with filesystem metadata read for {:?}", path);
cached.update_check_time();
return Ok(Arc::clone(&cached.content));
if let Some(cached) = self.cache.get(path) {
cached.update_check_time();
return Ok(Arc::clone(&cached.content));
}
}
Ok(true) => log::trace!("{path:?} was changed, updating cache..."),
Err(e) => log::trace!("Cannot read metadata of {path:?}, re-loading it: {e:#}"),
Expand Down Expand Up @@ -149,19 +153,15 @@ impl<T: AsyncFromStrWithState> FileCache<T> {
match parsed {
Ok(value) => {
let new_val = Arc::clone(&value.content);
log::trace!("Writing to cache {:?}", path);
self.cache.write().await.insert(path.clone(), value);
log::trace!("Done writing to cache {:?}", path);
self.cache.insert(path.clone(), value);
log::trace!("{:?} loaded in cache", path);
Ok(new_val)
}
Err(e) => {
log::trace!(
"Evicting {path:?} from the cache because the following error occurred: {e}"
);
log::trace!("Removing from cache {:?}", path);
self.cache.write().await.remove(path);
log::trace!("Done removing from cache {:?}", path);
self.cache.remove(path);
Err(e)
}
}
Expand Down