use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use crate::error::{Error, Result};
pub(super) struct ThumbFiles {
dir: PathBuf,
publishing: Vec<tokio::sync::Mutex<()>>,
}
const PUBLISH_STRIPES: usize = 64;
fn file_name(id: &str) -> String {
let plain = !id.is_empty()
&& id.len() <= 100
&& !id.starts_with('.')
&& id
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.');
if plain {
id.to_owned()
} else {
let hex: String = id.bytes().map(|b| format!("{b:02x}")).collect();
format!("x{hex}")
}
}
impl ThumbFiles {
pub(super) fn new(dir: PathBuf) -> Self {
ThumbFiles {
dir,
publishing: (0..PUBLISH_STRIPES)
.map(|_| tokio::sync::Mutex::new(()))
.collect(),
}
}
pub(super) fn publish_lock(&self, library: &str, media: &str) -> &tokio::sync::Mutex<()> {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
(library, media).hash(&mut hasher);
&self.publishing[hasher.finish() as usize % PUBLISH_STRIPES]
}
fn library_dir(&self, library: &str) -> PathBuf {
self.dir.join(file_name(library))
}
fn path(&self, library: &str, media: &str) -> PathBuf {
self.library_dir(library).join(file_name(media))
}
pub(super) async fn read(&self, library: &str, media: &str) -> Option<Vec<u8>> {
tokio::fs::read(self.path(library, media)).await.ok()
}
pub(super) async fn write(&self, library: &str, media: &str, data: &[u8]) -> Result<()> {
static NEXT: AtomicU64 = AtomicU64::new(0);
let storage = |e: std::io::Error| Error::storage(format!("thumbnail cache: {e}"));
let path = self.path(library, media);
tokio::fs::create_dir_all(self.library_dir(library))
.await
.map_err(storage)?;
let mut temporary = path.clone().into_os_string();
temporary.push(format!(
".{}-{}.part",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
if let Err(error) = tokio::fs::write(&temporary, data).await {
let _ = tokio::fs::remove_file(&temporary).await;
return Err(storage(error));
}
if let Err(error) = tokio::fs::rename(&temporary, &path).await {
let _ = tokio::fs::remove_file(&temporary).await;
return Err(storage(error));
}
Ok(())
}
pub(super) async fn remove(&self, library: &str, media: &str) {
let _ = tokio::fs::remove_file(self.path(library, media)).await;
}
pub(super) async fn remove_library(&self, library: &str) {
let _ = tokio::fs::remove_dir_all(self.library_dir(library)).await;
}
}
#[cfg(test)]
mod tests {
use super::{ThumbFiles, file_name};
#[tokio::test]
async fn writes_of_one_thumbnail_under_its_lock_all_succeed() {
let dir = std::env::temp_dir().join(format!(
"redseat-thumbs-test-{}-{}",
std::process::id(),
line!()
));
let files = std::sync::Arc::new(ThumbFiles::new(dir.clone()));
let data = vec![7u8; 64 * 1024];
let writes: Vec<_> = (0..16)
.map(|_| {
let files = files.clone();
let data = data.clone();
tokio::spawn(async move {
let _publishing = files.publish_lock("lib", "media").lock().await;
files.write("lib", "media", &data).await
})
})
.collect();
for write in writes {
write.await.unwrap().unwrap();
}
assert_eq!(files.read("lib", "media").await, Some(data));
let mut entries = tokio::fs::read_dir(dir.join("lib")).await.unwrap();
let mut names = Vec::new();
while let Some(entry) = entries.next_entry().await.unwrap() {
names.push(entry.file_name());
}
assert_eq!(names, ["media"]);
let _ = tokio::fs::remove_dir_all(dir).await;
}
#[test]
fn keeps_plain_ids_and_encodes_others() {
assert_eq!(file_name("abc-DEF_1"), "abc-DEF_1");
assert_eq!(file_name("a/b"), "x612f62");
assert_eq!(file_name(".."), "x2e2e");
assert_eq!(file_name(""), "x");
}
}