aboutsummaryrefslogtreecommitdiff
path: root/cache/src/backends
diff options
context:
space:
mode:
authormetamuffin <metamuffin@disroot.org>2025-11-30 12:32:44 +0100
committermetamuffin <metamuffin@disroot.org>2025-11-30 12:32:44 +0100
commit8174d129fbabd2d39323678d11d868893ddb429a (patch)
tree7979a528114cd5fb827f748f678a916e8e8eeddc /cache/src/backends
parent5db15c323d76dca9ae71b0204d63dcb09fbbcbc5 (diff)
downloadjellything-8174d129fbabd2d39323678d11d868893ddb429a.tar
jellything-8174d129fbabd2d39323678d11d868893ddb429a.tar.bz2
jellything-8174d129fbabd2d39323678d11d868893ddb429a.tar.zst
new sync cache
Diffstat (limited to 'cache/src/backends')
-rw-r--r--cache/src/backends/filesystem.rs51
-rw-r--r--cache/src/backends/mod.rs14
2 files changed, 65 insertions, 0 deletions
diff --git a/cache/src/backends/filesystem.rs b/cache/src/backends/filesystem.rs
new file mode 100644
index 0000000..39fb7a2
--- /dev/null
+++ b/cache/src/backends/filesystem.rs
@@ -0,0 +1,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()),
+ }
+ }
+}
diff --git a/cache/src/backends/mod.rs b/cache/src/backends/mod.rs
new file mode 100644
index 0000000..370c5ab
--- /dev/null
+++ b/cache/src/backends/mod.rs
@@ -0,0 +1,14 @@
+/*
+ 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>
+*/
+pub mod filesystem;
+
+use crate::CacheKey;
+use anyhow::Result;
+
+pub(crate) trait CacheStorage: Send + Sync + 'static {
+ fn store(&self, key: CacheKey, value: &[u8]) -> Result<()>;
+ fn read(&self, key: CacheKey) -> Result<Option<Vec<u8>>>;
+}