mangadex-home-rs/src/cache/low_mem.rs

59 lines
1.6 KiB
Rust
Raw Normal View History

2021-04-14 19:11:00 -07:00
//! Low memory caching stuff
2021-04-18 14:06:40 -07:00
use std::path::PathBuf;
2021-04-14 19:11:00 -07:00
use async_trait::async_trait;
use lru::LruCache;
2021-04-18 14:06:40 -07:00
use super::{BoxedImageStream, Cache, CacheError, CacheKey, CacheStream, ImageMetadata};
2021-04-14 19:11:00 -07:00
pub struct LowMemCache {
2021-04-18 14:06:40 -07:00
on_disk: LruCache<CacheKey, ImageMetadata>,
2021-04-14 19:11:00 -07:00
disk_path: PathBuf,
disk_max_size: u64,
disk_cur_size: u64,
2021-04-14 19:11:00 -07:00
}
impl LowMemCache {
pub fn new(disk_max_size: u64, disk_path: PathBuf) -> Self {
2021-04-14 19:11:00 -07:00
Self {
on_disk: LruCache::unbounded(),
disk_path,
disk_max_size,
disk_cur_size: 0,
}
}
}
2021-04-18 14:06:40 -07:00
// todo: schedule eviction
2021-04-14 19:11:00 -07:00
#[async_trait]
impl Cache for LowMemCache {
2021-04-18 14:06:40 -07:00
async fn get(
&mut self,
key: &CacheKey,
) -> Option<Result<(CacheStream, &ImageMetadata), CacheError>> {
2021-04-18 14:25:28 -07:00
let metadata = self.on_disk.get(key)?;
let path = self.disk_path.clone().join(PathBuf::from(key.clone()));
super::fs::read_file(&path).await.map(|res| {
res.map(|stream| (CacheStream::Fs(stream), metadata))
.map_err(Into::into)
})
2021-04-14 19:11:00 -07:00
}
2021-04-18 14:06:40 -07:00
async fn put(
2021-04-17 20:19:27 -07:00
&mut self,
key: CacheKey,
2021-04-18 14:06:40 -07:00
image: BoxedImageStream,
metadata: ImageMetadata,
) -> Result<(CacheStream, &ImageMetadata), CacheError> {
let path = self.disk_path.clone().join(PathBuf::from(key.clone()));
self.on_disk.put(key.clone(), metadata);
super::fs::write_file(&path, image)
.await
.map(CacheStream::Fs)
.map(move |stream| (stream, self.on_disk.get(&key).unwrap()))
.map_err(Into::into)
2021-04-14 19:11:00 -07:00
}
}