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
223
224
225
226
227
228
229
230
231
232
use {
crate::{
core::{
cache::{CacheRead, CacheWrite, OwnedRef},
deser::Deser,
primitive::Object,
storage::{Error, StorageRead, StorageWrite},
},
Addr,
},
log::debug,
std::{
collections::HashMap,
sync::{Arc, Mutex},
},
tokio::io::{self, AsyncRead, AsyncWrite},
};
#[derive(Debug, Hash, Eq, PartialEq)]
enum CacheKey {
Object(Addr),
Bytes(Addr),
}
#[derive(Debug)]
enum CacheValue {
Object(Arc<Object>),
Bytes(Arc<Vec<u8>>),
}
pub struct DeserCache<S> {
deser: Deser,
storage: S,
// TODO: use an LRU or something useful. This is just a simple test of Caching + Deser.
// TODO: use a RwLock here. Or ideally a lock-free data structure.
cache: Mutex<HashMap<CacheKey, CacheValue>>,
}
impl<S> DeserCache<S> {
pub fn new(storage: S) -> Self {
Self {
// TODO: use a passed in deser.
deser: Deser::default(),
storage,
cache: Mutex::new(HashMap::new()),
}
}
}
#[async_trait::async_trait]
impl<S> CacheRead for DeserCache<S>
where
S: StorageRead + Send,
{
type OwnedRef = Arc<Object>;
async fn read_unstructured<A, W>(&self, addr: A, mut w: W) -> Result<u64, Error>
where
A: AsRef<Addr> + Into<Addr> + Send,
W: AsyncWrite + Unpin + Send,
{
let addr_ref = addr.as_ref();
let buf = {
let cache = self.cache.lock().map_err(|_| Error::Unhandled {
message: "cache mutex poisoned".to_owned(),
})?;
cache
// TODO: impl Borrow for CacheKey, to avoid this Addr clone.
.get(&CacheKey::Bytes(addr_ref.clone()))
.and_then(|k| match k {
CacheValue::Bytes(buf) => Some(Arc::clone(&buf)),
CacheValue::Object(_) => None,
})
};
if let Some(buf) = buf {
let len = io::copy(&mut buf.as_slice(), &mut w).await?;
return Ok(len);
}
// we could have a concurrency issue here, where we read from storage twice.
// This is low-risk (ie won't corrupt data/etc), and should be tweaked based on
// what results in better performance.
// Optimizing for duplicate cache inserts vs holding the lock longer.
// Possibly even keeping some type of LockState to have short lock length?
// /shrug, bench concern for down the road.
let buf = {
let mut buf = Vec::new();
let _: u64 = StorageRead::read(&self.storage, addr_ref.clone(), &mut buf).await?;
Arc::new(buf)
};
{
let mut cache = self.cache.lock().map_err(|_| Error::Unhandled {
message: "cache mutex poisoned".to_owned(),
})?;
let prev = cache.insert(
CacheKey::Bytes(addr_ref.clone()),
CacheValue::Bytes(Arc::clone(&buf)),
);
if prev.is_some() {
debug!("cache inserted twice, needless storage read");
}
}
let len = io::copy(&mut buf.as_slice(), &mut w).await?;
Ok(len)
}
async fn read_structured<A>(&self, addr: A) -> Result<Self::OwnedRef, Error>
where
A: AsRef<Addr> + Into<Addr> + Send,
{
let addr_ref = addr.as_ref();
{
let cache = self.cache.lock().map_err(|_| Error::Unhandled {
message: "cache mutex poisoned".to_owned(),
})?;
// TODO: impl Borrow for CacheKey, to avoid this Addr clone.
if let Some(CacheValue::Object(obj)) = cache.get(&CacheKey::Object(addr_ref.clone())) {
return Ok(Arc::clone(&obj));
}
}
// we could have a concurrency issue here, where we read from storage twice.
// This is low-risk (ie won't corrupt data/etc), and should be tweaked based on
// what results in better performance.
// Optimizing for duplicate cache inserts vs holding the lock longer.
// Possibly even keeping some type of LockState to have short lock length?
// /shrug, bench concern for down the road.
let obj = {
let buf = {
let mut buf = Vec::new();
let _: u64 = StorageRead::read(&self.storage, addr_ref.clone(), &mut buf).await?;
buf
};
let obj = self
.deser
.from_slice::<Object>(&buf)
.map_err(|err| Error::Unhandled {
message: format!("deser: {}", err),
})?;
Arc::new(obj)
};
{
let mut cache = self.cache.lock().map_err(|_| Error::Unhandled {
message: "cache mutex poisoned".to_owned(),
})?;
let cache_value = cache.insert(
CacheKey::Object(addr_ref.clone()),
CacheValue::Object(Arc::clone(&obj)),
);
if cache_value.is_some() {
debug!("cache inserted twice, needless storage read");
}
}
Ok(obj)
}
}
impl OwnedRef for Arc<Object> {
type Ref = Self;
fn as_ref_structured(&self) -> &Self::Ref {
self
}
fn into_owned_structured(self) -> Object {
use std::ops::Deref;
(*self.deref()).clone()
}
}
#[async_trait::async_trait]
impl<S> CacheWrite for DeserCache<S>
where
S: StorageWrite + Send,
{
async fn write_unstructured<R>(&self, mut r: R) -> Result<Addr, Error>
where
R: AsyncRead + Unpin + Send,
{
let buf = {
let mut buf = Vec::new();
let _: u64 = io::copy(&mut r, &mut buf).await?;
Arc::new(buf)
};
let addr = Addr::hash(buf.as_ref());
let new_to_cache = {
let mut cache = self.cache.lock().map_err(|_| Error::Unhandled {
message: "cache mutex poisoned".to_owned(),
})?;
cache
.insert(
CacheKey::Bytes(addr.clone()),
CacheValue::Bytes(Arc::clone(&buf)),
)
.is_none()
};
// as an optimization, if it's already in the memory cache we should be able to ignore
// writing it to storage.
//
// :WARN: If this fails the cache won't be invalidated, we could/should defer writing to
// cache until after failure.
if new_to_cache {
let _: u64 = self
.storage
.write(addr.clone(), &mut buf.as_slice())
.await?;
}
Ok(addr)
}
async fn write_structured<T>(&self, object: T) -> Result<Addr, Error>
where
T: Into<Object> + Send,
{
let object = object.into();
let buf = Deser::default()
.to_vec(&object)
.map_err(|err| Error::Unhandled {
message: format!("deser: {}", err),
})?;
let addr = Addr::hash(&buf);
let new_to_cache = {
let mut cache = self.cache.lock().map_err(|_| Error::Unhandled {
message: "cache mutex poisoned".to_owned(),
})?;
cache
.insert(
CacheKey::Object(addr.clone()),
CacheValue::Object(Arc::new(object)),
)
.is_none()
};
// as an optimization, if it's already in the memory cache we should be able to ignore
// writing it to storage.
//
// :WARN: If this fails the cache won't be invalidated, we could/should defer writing to
// cache until after failure.
if new_to_cache {
let _: u64 = self
.storage
.write(addr.clone(), &mut buf.as_slice())
.await?;
}
Ok(addr)
}
}