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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
#[cfg(test)]
mod lib_test;
use data_encoding::BASE32_NOPAD;
use futures::channel::oneshot::{channel, Receiver, Sender};
pub use rusqlite;
use std::{
collections::HashMap,
sync::{mpsc, Arc, Mutex, Weak},
time::{Duration, SystemTime, UNIX_EPOCH},
};
use rusqlite::{Connection, OptionalExtension};
#[derive(Clone)]
pub struct Cache {
inner: Arc<CacheImpl>,
}
#[derive(Clone, Debug)]
pub struct CacheConfig {
pub flush_interval: Duration,
pub flush_gc_ratio: u64,
pub max_ttl: Option<Duration>,
}
impl Default for CacheConfig {
fn default() -> Self {
CacheConfig {
flush_interval: Duration::from_secs(10),
flush_gc_ratio: 30,
max_ttl: None,
}
}
}
#[derive(Clone)]
pub struct Topic {
inner: Arc<TopicImpl>,
}
struct CacheImpl {
config: CacheConfig,
conn: Mutex<Connection>,
lazy_expiry_update: Mutex<HashMap<(Arc<str>, String), u64>>,
stop_tx: Mutex<mpsc::Sender<()>>,
completion_rx: Mutex<mpsc::Receiver<()>>,
}
struct TopicImpl {
cache: Cache,
table_name: Arc<str>,
listeners: Mutex<HashMap<String, Vec<Sender<()>>>>,
}
impl Drop for CacheImpl {
fn drop(&mut self) {
self.stop_tx.lock().unwrap().send(()).unwrap();
self.completion_rx.lock().unwrap().recv().unwrap();
}
}
impl Cache {
pub fn new(config: CacheConfig, conn: Connection) -> Result<Self, rusqlite::Error> {
assert!(config.flush_gc_ratio > 0);
let (stop_tx, stop_rx) = mpsc::channel::<()>();
let (completion_tx, completion_rx) = mpsc::channel::<()>();
conn.execute_batch("pragma journal_mode = wal;")?;
let inner = Arc::new(CacheImpl {
conn: Mutex::new(conn),
config: config.clone(),
lazy_expiry_update: Mutex::new(HashMap::new()),
stop_tx: Mutex::new(stop_tx),
completion_rx: Mutex::new(completion_rx),
});
let w = Arc::downgrade(&inner);
std::thread::spawn(move || periodic_task(config, stop_rx, completion_tx, w));
Ok(Self { inner })
}
fn flush(&self) {
let lazy_expiry_update = std::mem::replace(
&mut *self.inner.lazy_expiry_update.lock().unwrap(),
HashMap::new(),
);
for ((table_name, key), expiry) in lazy_expiry_update {
let res = self.inner.conn.lock().unwrap().execute(
&format!("update {} set expiry = ? where k = ?", table_name),
rusqlite::params![expiry, key],
);
if let Err(e) = res {
tracing::error!(table = &*table_name, key = key.as_str(), error = %e, "error updating expiry");
}
}
}
fn gc(&self) -> Result<(), rusqlite::Error> {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let tables = self
.inner
.conn
.lock()
.unwrap()
.unchecked_transaction()?
.prepare("select name from sqlite_master where type = 'table' and name like 'topic_%'")?
.query_map(rusqlite::params![], |x| x.get::<_, String>(0))?
.collect::<Result<Vec<String>, rusqlite::Error>>()?;
let mut total = 0usize;
for table in tables {
let count = self.inner.conn.lock().unwrap().execute(
&format!("delete from {} where expiry < ?", table),
rusqlite::params![now],
)?;
total += count;
}
if total != 0 {
tracing::info!(total = total, "gc deleted rows");
}
Ok(())
}
pub fn topic(&self, key: &str) -> Result<Topic, rusqlite::Error> {
let table_name = format!("topic_{}", BASE32_NOPAD.encode(key.as_bytes()));
self.inner.conn.lock().unwrap().execute_batch(&format!(
r#"
begin transaction;
create table if not exists {} (
k text primary key not null,
v blob not null,
created_at integer not null default (cast(strftime('%s', 'now') as integer)),
expiry integer not null,
ttl integer not null
);
create index {}_by_expiry on {} (expiry);
commit;
"#,
table_name, table_name, table_name,
))?;
Ok(Topic {
inner: Arc::new(TopicImpl {
cache: self.clone(),
table_name: Arc::from(table_name),
listeners: Mutex::new(HashMap::new()),
}),
})
}
}
pub struct Value {
pub data: Vec<u8>,
pub created_at: u64,
}
impl Topic {
pub fn get(&self, key: &str) -> Result<Option<Value>, rusqlite::Error> {
let conn = self.inner.cache.inner.conn.lock().unwrap();
let mut stmt = conn.prepare_cached(&format!(
"select v, created_at, ttl from {} where k = ?",
self.inner.table_name,
))?;
let rsp: Option<(Vec<u8>, u64, u64)> = stmt
.query_row(rusqlite::params![key], |x| {
Ok((x.get(0)?, x.get(1)?, x.get(2)?))
})
.optional()?;
if let Some((data, created_at, ttl)) = rsp {
self.inner
.cache
.inner
.lazy_expiry_update
.lock()
.unwrap()
.insert(
(self.inner.table_name.clone(), key.to_string()),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
+ ttl,
);
Ok(Some(Value { data, created_at }))
} else {
Ok(None)
}
}
pub async fn get_for_update(
&self,
key: &str,
) -> Result<(KeyUpdater, Option<Value>), rusqlite::Error> {
loop {
let receiver: Option<Receiver<()>>;
{
let mut listeners = self.inner.listeners.lock().unwrap();
if let Some(arr) = listeners.get_mut(key) {
let (tx, rx) = channel();
arr.push(tx);
receiver = Some(rx);
} else {
receiver = None;
listeners.insert(key.to_string(), vec![]);
}
}
if let Some(receiver) = receiver {
let _ = receiver.await;
} else {
break;
}
}
let data = self.get(key)?;
Ok((
KeyUpdater {
topic: self.clone(),
key: key.to_string(),
},
data,
))
}
pub fn set(&self, key: &str, value: &[u8], ttl: Duration) -> Result<(), rusqlite::Error> {
let conn = self.inner.cache.inner.conn.lock().unwrap();
let mut stmt = conn.prepare_cached(&format!(
"replace into {} (k, v, expiry, ttl) values(?, ?, ?, ?)",
self.inner.table_name
))?;
let mut ttl = ttl.as_secs();
if let Some(max_ttl) = self.inner.cache.inner.config.max_ttl {
let max_ttl = max_ttl.as_secs();
ttl = ttl.min(max_ttl);
}
let expiry = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
+ ttl;
stmt.execute(rusqlite::params![key, value, expiry, ttl])?;
self.inner
.cache
.inner
.lazy_expiry_update
.lock()
.unwrap()
.remove(&(self.inner.table_name.clone(), key.to_string()));
Ok(())
}
pub fn delete(&self, key: &str) -> Result<(), rusqlite::Error> {
let conn = self.inner.cache.inner.conn.lock().unwrap();
let mut stmt = conn.prepare_cached(&format!(
"delete from {} where k = ?",
self.inner.table_name
))?;
stmt.execute(rusqlite::params![key])?;
Ok(())
}
}
pub struct KeyUpdater {
topic: Topic,
key: String,
}
impl Drop for KeyUpdater {
fn drop(&mut self) {
let mut listeners = self.topic.inner.listeners.lock().unwrap();
listeners.remove(self.key.as_str()).unwrap();
}
}
impl KeyUpdater {
pub fn write(self, value: &[u8], ttl: Duration) -> Result<(), rusqlite::Error> {
self.topic.set(&self.key, value, ttl)?;
Ok(())
}
}
fn periodic_task(
config: CacheConfig,
stop_rx: mpsc::Receiver<()>,
completion_tx: mpsc::Sender<()>,
w: Weak<CacheImpl>,
) {
let mut gc_ratio_counter = 0u64;
loop {
let tx = stop_rx.recv_timeout(config.flush_interval);
if tx.is_ok() {
break;
}
let inner = if let Some(x) = w.upgrade() {
x
} else {
break;
};
let cache = Cache { inner };
cache.flush();
gc_ratio_counter += 1;
if gc_ratio_counter == config.flush_gc_ratio {
gc_ratio_counter = 0;
if let Err(e) = cache.gc() {
tracing::error!(error = %e, "gc failed");
}
}
}
tracing::info!("exiting periodic task");
completion_tx.send(()).unwrap();
}