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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
|
/*
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) 2023 metamuffin <metamuffin.org>
*/
use crate::{AssetLocationExt, CONF};
use anyhow::{anyhow, Context};
use base64::Engine;
use bincode::{Decode, Encode};
use jellycommon::AssetLocation;
use log::{info, warn};
use std::{
any::Any,
collections::{BTreeMap, HashMap},
future::Future,
io::Seek,
sync::{
atomic::{AtomicUsize, Ordering},
Arc, LazyLock, RwLock,
},
time::Instant,
};
use tokio::sync::Mutex;
pub fn cache_location(seed: &[&str]) -> (usize, AssetLocation) {
use sha2::Digest;
let mut d = sha2::Sha512::new();
for s in seed {
d.update(s.as_bytes());
d.update(b"\0");
}
let d = d.finalize();
let n = d[0] as usize | (d[1] as usize) << 8 | (d[2] as usize) << 16 | (d[3] as usize) << 24;
let fname = base64::engine::general_purpose::URL_SAFE.encode(d);
let fname = &fname[..22];
let fname = format!("{}-{}", seed[0], fname); // about 128 bits
(n, AssetLocation::Cache(fname.into()))
}
const CACHE_GENERATION_BUCKET_COUNT: usize = 1024;
pub static CACHE_GENERATION_LOCKS: LazyLock<[Mutex<()>; CACHE_GENERATION_BUCKET_COUNT]> =
LazyLock::new(|| [(); CACHE_GENERATION_BUCKET_COUNT].map(|_| Mutex::new(())));
pub async fn async_cache_file<Fun, Fut>(
seed: &[&str],
generate: Fun,
) -> Result<AssetLocation, anyhow::Error>
where
Fun: FnOnce(tokio::fs::File) -> Fut,
Fut: Future<Output = Result<(), anyhow::Error>>,
{
let (bucket, location) = cache_location(seed);
// we need a lock even if it exists since somebody might be still in the process of writing.
let _guard = CACHE_GENERATION_LOCKS[bucket % CACHE_GENERATION_BUCKET_COUNT]
.lock()
.await;
let exists = tokio::fs::try_exists(location.path())
.await
.context("unable to test for cache file existance")?;
if !exists {
let f = tokio::fs::File::create(location.path())
.await
.context("creating new cache file")?;
match generate(f).await {
Ok(()) => (),
Err(e) => {
warn!("cache generation failed, unlinking entry");
tokio::fs::remove_file(location.path()).await?;
return Err(e);
}
}
}
drop(_guard);
Ok(location)
}
pub fn cache_file<Fun>(seed: &[&str], mut generate: Fun) -> Result<AssetLocation, anyhow::Error>
where
Fun: FnMut(std::fs::File) -> Result<(), anyhow::Error>,
{
let (bucket, location) = cache_location(seed);
// we need a lock even if it exists since somebody might be still in the process of writing.
let _guard = CACHE_GENERATION_LOCKS[bucket % CACHE_GENERATION_BUCKET_COUNT].blocking_lock();
let exists = location.path().exists();
if !exists {
let f = std::fs::File::create(location.path()).context("creating new cache file")?;
match generate(f) {
Ok(()) => (),
Err(e) => {
warn!("cache generation failed, unlinking entry");
std::fs::remove_file(location.path())?;
return Err(e);
}
}
}
drop(_guard);
Ok(location)
}
pub struct InMemoryCacheEntry {
size: usize,
last_access: Instant,
object: Arc<dyn Any + Send + Sync + 'static>,
}
pub static CACHE_IN_MEMORY_OBJECTS: LazyLock<RwLock<HashMap<AssetLocation, InMemoryCacheEntry>>> =
LazyLock::new(|| RwLock::new(HashMap::new()));
pub static CACHE_IN_MEMORY_SIZE: AtomicUsize = AtomicUsize::new(0);
pub fn cache_memory<Fun, T>(seed: &[&str], mut generate: Fun) -> Result<Arc<T>, anyhow::Error>
where
Fun: FnMut() -> Result<T, anyhow::Error>,
T: Encode + Decode + Send + Sync + 'static,
{
let (_, location) = cache_location(seed);
{
let mut g = CACHE_IN_MEMORY_OBJECTS.write().unwrap();
if let Some(entry) = g.get_mut(&location) {
entry.last_access = Instant::now();
let object = entry
.object
.clone()
.downcast::<T>()
.map_err(|_| anyhow!("inconsistent types for in-memory cache"))?;
return Ok(object);
}
}
let location = cache_file(seed, move |mut file| {
let object = generate()?;
bincode::encode_into_std_write(&object, &mut file, bincode::config::standard())
.context("encoding cache object")?;
Ok(())
})?;
let mut file = std::fs::File::open(location.path())?;
let object = bincode::decode_from_std_read::<T, _, _>(&mut file, bincode::config::standard())
.context("decoding cache object")?;
let object = Arc::new(object);
let size = file.stream_position()? as usize; // this is an approximation mainly since varint is used in bincode
{
let mut g = CACHE_IN_MEMORY_OBJECTS.write().unwrap();
g.insert(
location,
InMemoryCacheEntry {
size,
last_access: Instant::now(),
object: object.clone(),
},
);
CACHE_IN_MEMORY_SIZE.fetch_add(size, Ordering::Relaxed);
}
cleanup_cache();
Ok(object)
}
pub fn cleanup_cache() {
let current_size = CACHE_IN_MEMORY_SIZE.load(Ordering::Relaxed);
if current_size < CONF.max_in_memory_cache_size {
return;
}
info!("running cache eviction");
let mut g = CACHE_IN_MEMORY_OBJECTS.write().unwrap();
// TODO: if two entries have *exactly* the same size, only one of the will be remove; this is fine for now
let mut k = BTreeMap::new();
for (loc, entry) in g.iter() {
k.insert(entry.last_access.elapsed(), (loc.to_owned(), entry.size));
}
let mut reduction = 0;
for (loc, size) in k.values().rev().take(k.len().div_ceil(2)) {
g.remove(loc);
reduction += size;
}
CACHE_IN_MEMORY_SIZE.fetch_sub(reduction, Ordering::Relaxed);
drop(g);
info!("done");
}
|