1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
/*
This file is part of jellything (https://codeberg.org/metamuffin/jellything)
which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
Copyright (C) 2025 metamuffin <metamuffin.org>
*/
use crate::{CacheKey, Config, backends::CacheStorage};
use anyhow::Result;
use base64::Engine;
use rand::random;
use std::{
fs::{File, rename},
io::{ErrorKind, Read, Write},
path::PathBuf,
};
pub struct Filesystem(PathBuf);
impl Filesystem {
pub fn new(config: &Config) -> Self {
Self(config.path.clone())
}
fn path(&self, key: CacheKey) -> PathBuf {
let filename = base64::engine::general_purpose::URL_SAFE.encode(key.0);
let filename = &filename[..30]; // 180 bits
self.0.join(filename)
}
fn temp_path(&self) -> PathBuf {
self.0.join(format!("temp-{:016x}", random::<u128>()))
}
}
impl CacheStorage for Filesystem {
fn store(&self, key: CacheKey, value: &[u8]) -> Result<()> {
let temp = self.temp_path();
File::create(&temp)?.write_all(value)?;
rename(temp, self.path(key))?;
Ok(())
}
fn read(&self, key: CacheKey) -> Result<Option<Vec<u8>>> {
match File::open(self.path(key)) {
Ok(mut f) => {
let mut data = Vec::new();
f.read_to_end(&mut data)?;
Ok(Some(data))
}
Err(e) if e.kind() == ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
}
|