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,
|
2021-04-14 20:44:13 -07:00
|
|
|
disk_max_size: u64,
|
|
|
|
disk_cur_size: u64,
|
2021-04-14 19:11:00 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
impl LowMemCache {
|
2021-04-14 20:44:13 -07:00
|
|
|
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>> {
|
|
|
|
if let Some(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
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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
|
|
|
}
|
|
|
|
}
|