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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
use fnv::{FnvHashMap, FnvHashSet};
use libipld::Cid;
use std::{
fmt::Debug,
ops::DerefMut,
sync::{Arc, Mutex},
time::{Duration, Instant},
};
mod async_tracker;
mod sqlite_tracker;
pub use async_tracker::{AsyncCacheTracker, Spawner};
pub use sqlite_tracker::SqliteCacheTracker;
#[cfg(test)]
mod tests;
#[derive(Debug, Clone, Copy)]
pub struct BlockInfo {
id: i64,
codec: u64,
len: usize,
}
impl BlockInfo {
pub fn new(id: i64, cid: &Cid, data: &[u8]) -> Self {
Self {
id,
codec: cid.codec(),
len: data.len(),
}
}
pub fn id(&self) -> i64 {
self.id
}
pub fn codec(&self) -> u64 {
self.codec
}
pub fn block_len(&self) -> usize {
self.len
}
}
#[allow(unused_variables)]
pub trait CacheTracker: Debug + Send {
fn blocks_accessed(&mut self, blocks: Vec<BlockInfo>) {}
fn blocks_written(&mut self, blocks: Vec<BlockInfo>) {}
fn delete_ids(&mut self, ids: &[i64]) {}
fn sort_ids(&self, ids: &mut [i64]) {}
fn retain_ids(&mut self, ids: &[i64]) {}
}
impl CacheTracker for Box<dyn CacheTracker> {
fn blocks_accessed(&mut self, blocks: Vec<BlockInfo>) {
self.as_mut().blocks_accessed(blocks)
}
fn blocks_written(&mut self, blocks: Vec<BlockInfo>) {
self.as_mut().blocks_written(blocks)
}
fn sort_ids(&self, ids: &mut [i64]) {
self.as_ref().sort_ids(ids)
}
fn delete_ids(&mut self, ids: &[i64]) {
self.as_mut().delete_ids(ids)
}
fn retain_ids(&mut self, ids: &[i64]) {
self.as_mut().retain_ids(ids)
}
}
#[derive(Debug)]
pub struct NoopCacheTracker;
impl CacheTracker for NoopCacheTracker {}
#[derive(Debug)]
pub struct SortByIdCacheTracker;
impl CacheTracker for SortByIdCacheTracker {
fn sort_ids(&self, ids: &mut [i64]) {
ids.sort_unstable();
}
}
pub struct InMemCacheTracker<T, F> {
cache: Arc<Mutex<FnvHashMap<i64, T>>>,
mk_cache_entry: F,
created: Instant,
}
impl<T, F> InMemCacheTracker<T, F>
where
T: Ord + Clone + Debug,
F: Fn(Duration, BlockInfo) -> Option<T>,
{
pub fn new(mk_cache_entry: F) -> Self {
Self {
cache: Arc::new(Mutex::new(FnvHashMap::default())),
mk_cache_entry,
created: Instant::now(),
}
}
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct SortKey<T: Ord> {
time: Option<T>,
id: i64,
}
impl<T: Ord> SortKey<T> {
pub fn new(time: Option<T>, id: i64) -> Self {
Self { time, id }
}
}
fn get_key<T: Ord + Clone>(
cache: &mut impl DerefMut<Target = FnvHashMap<i64, T>>,
id: i64,
) -> SortKey<T> {
SortKey::new(cache.get(&id).cloned(), id)
}
impl<T, F> CacheTracker for InMemCacheTracker<T, F>
where
T: Ord + Clone + Debug + Send,
F: Fn(Duration, BlockInfo) -> Option<T> + Send,
{
fn blocks_accessed(&mut self, blocks: Vec<BlockInfo>) {
let now = Instant::now().checked_duration_since(self.created).unwrap();
let mut cache = self.cache.lock().unwrap();
for block in blocks {
if let Some(value) = (self.mk_cache_entry)(now, block) {
cache.insert(block.id, value);
} else {
cache.remove(&block.id);
}
}
}
fn delete_ids(&mut self, ids: &[i64]) {
let mut cache = self.cache.lock().unwrap();
for id in ids {
cache.remove(id);
}
}
fn retain_ids(&mut self, ids: &[i64]) {
let ids = ids.iter().cloned().collect::<FnvHashSet<_>>();
let mut cache = self.cache.lock().unwrap();
cache.retain(|id, _| ids.contains(id));
}
fn sort_ids(&self, ids: &mut [i64]) {
let mut cache = self.cache.lock().unwrap();
ids.sort_unstable_by_key(move |id| get_key(&mut cache, *id));
}
}
impl<T: Debug, F> std::fmt::Debug for InMemCacheTracker<T, F> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("InMemLruCacheTracker")
.field("cache", &self.cache.lock().unwrap())
.finish()
}
}
#[cfg(test)]
#[test]
fn sort_key_sort_order() {
assert!(
SortKey::new(None, i64::max_value())
< SortKey::new(Some(Duration::default()), i64::min_value())
);
}