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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
pub use ipfs_sqlite_block_store::TempPin;
use ipfs_sqlite_block_store::{
cache::SqliteCacheTracker, BlockStore, Config, SizeTargets, Synchronous,
};
use lazy_static::lazy_static;
use libipld::codec::References;
use libipld::store::StoreParams;
use libipld::{Block, Cid, Ipld, Result};
use parking_lot::{Condvar, Mutex};
use prometheus::core::{Collector, Desc};
use prometheus::proto::MetricFamily;
use prometheus::{HistogramOpts, HistogramVec, IntCounterVec, IntGauge, Opts, Registry};
use std::future::Future;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use crate::executor::{Executor, JoinHandle};
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StorageConfig {
pub path: Option<PathBuf>,
pub cache_size_blocks: u64,
pub cache_size_bytes: u64,
pub gc_interval: Duration,
pub gc_min_blocks: usize,
pub gc_target_duration: Duration,
}
impl StorageConfig {
pub fn new(path: Option<PathBuf>, cache_size: u64, gc_interval: Duration) -> Self {
Self {
path,
cache_size_blocks: cache_size,
cache_size_bytes: u64::MAX,
gc_interval,
gc_min_blocks: usize::MAX,
gc_target_duration: Duration::new(u64::MAX, 1_000_000_000 - 1),
}
}
}
#[derive(Clone)]
pub struct StorageService<S: StoreParams> {
executor: Executor,
store: Arc<Mutex<BlockStore<S>>>,
gc_target_duration: Duration,
gc_min_blocks: usize,
_gc_task: Arc<JoinHandle<()>>,
exit: Arc<(Mutex<bool>, Condvar)>,
}
impl<S: StoreParams> Drop for StorageService<S> {
fn drop(&mut self) {
*self.exit.0.lock() = true;
self.exit.1.notify_all();
}
}
impl<S: StoreParams> StorageService<S>
where
Ipld: References<S::Codecs>,
{
pub fn open(config: StorageConfig, executor: Executor) -> Result<Self> {
let size = SizeTargets::new(config.cache_size_blocks, config.cache_size_bytes);
let store_config = Config::default()
.with_size_targets(size)
.with_pragma_synchronous(Synchronous::Normal);
let store = if let Some(path) = config.path {
std::fs::create_dir_all(&path)?;
let path = path.join("db");
let tracker = SqliteCacheTracker::open(&path, |access, _| Some(access))?;
BlockStore::open(path, store_config.with_cache_tracker(tracker))?
} else {
let tracker = SqliteCacheTracker::memory(|access, _| Some(access))?;
BlockStore::memory(store_config.with_cache_tracker(tracker))?
};
let store = Arc::new(Mutex::new(store));
let gc = store.clone();
let gc_interval = config.gc_interval;
let gc_min_blocks = config.gc_min_blocks;
let gc_target_duration = config.gc_target_duration;
let exit = Arc::new((Mutex::new(false), Condvar::new()));
let exit2 = exit.clone();
let gc_task = executor.spawn_blocking(move || {
enum Phase {
Gc,
Delete,
}
let mut phase = Phase::Gc;
loop {
let mut should_exit = exit.0.lock();
let timeout = exit.1.wait_for(&mut should_exit, gc_interval / 2);
if *should_exit {
break;
}
if timeout.timed_out() {
match phase {
Phase::Gc => {
tracing::trace!("gc_loop running incremental gc");
gc.lock()
.incremental_gc(gc_min_blocks, gc_target_duration)
.ok();
phase = Phase::Delete;
}
Phase::Delete => {
tracing::trace!("gc_loop running incremental delete orphaned");
gc.lock()
.incremental_delete_orphaned(gc_min_blocks, gc_target_duration)
.ok();
phase = Phase::Gc;
}
}
}
}
});
Ok(Self {
executor,
gc_target_duration: config.gc_target_duration,
gc_min_blocks: config.gc_min_blocks,
store,
_gc_task: Arc::new(gc_task),
exit: exit2,
})
}
pub fn ro<F: FnOnce(&mut Batch<'_, S>) -> Result<R>, R>(
&self,
op: &'static str,
f: F,
) -> Result<R> {
observe_query(op, || {
let mut lock = self.store.lock();
let mut txn = Batch(lock.transaction()?);
f(&mut txn)
})
}
pub fn rw<F: FnOnce(&mut Batch<'_, S>) -> Result<R>, R>(
&self,
op: &'static str,
f: F,
) -> Result<R> {
observe_query(op, || {
let mut lock = self.store.lock();
let mut txn = Batch(lock.transaction()?);
let res = f(&mut txn);
if res.is_ok() {
txn.0.commit()?;
}
res
})
}
pub fn create_temp_pin(&self) -> Result<TempPin> {
self.rw("create_temp_pin", |x| x.create_temp_pin())
}
pub fn temp_pin(
&self,
temp: &TempPin,
iter: impl IntoIterator<Item = Cid> + Send + 'static,
) -> Result<()> {
self.rw("temp_pin", |x| x.temp_pin(temp, iter))
}
pub fn iter(&self) -> Result<impl Iterator<Item = Cid>> {
self.ro("iter", |x| x.iter())
}
pub fn contains(&self, cid: &Cid) -> Result<bool> {
self.ro("contains", |x| x.contains(cid))
}
pub fn get(&self, cid: &Cid) -> Result<Option<Vec<u8>>> {
self.ro("get", |x| x.get(cid))
}
pub fn insert(&self, block: &Block<S>) -> Result<()> {
self.rw("insert", |x| x.insert(block))
}
pub fn alias(&self, alias: &[u8], cid: Option<&Cid>) -> Result<()> {
self.rw("alias", |x| x.alias(alias, cid))
}
pub fn resolve(&self, alias: &[u8]) -> Result<Option<Cid>> {
self.ro("resolve", |x| x.resolve(alias))
}
pub fn reverse_alias(&self, cid: &Cid) -> Result<Option<Vec<Vec<u8>>>> {
self.ro("reverse_alias", |x| x.reverse_alias(cid))
}
pub fn missing_blocks(&self, cid: &Cid) -> Result<Vec<Cid>> {
self.ro("missing_blocks", |x| x.missing_blocks(cid))
}
pub async fn evict(&self) -> Result<()> {
let store = self.store.clone();
let gc_min_blocks = self.gc_min_blocks;
let gc_target_duration = self.gc_target_duration;
self.executor
.spawn_blocking(move || {
while !store
.lock()
.incremental_gc(gc_min_blocks, gc_target_duration)?
{}
while !store
.lock()
.incremental_delete_orphaned(gc_min_blocks, gc_target_duration)?
{
}
Ok(())
})
.await?
}
pub async fn flush(&self) -> Result<()> {
let store = self.store.clone();
let flush = self.executor.spawn_blocking(move || store.lock().flush());
Ok(observe_future("flush", flush).await??)
}
pub fn register_metrics(&self, registry: &Registry) -> Result<()> {
registry.register(Box::new(QUERIES_TOTAL.clone()))?;
registry.register(Box::new(QUERY_DURATION.clone()))?;
registry.register(Box::new(SqliteStoreCollector::new(self.store.clone())))?;
Ok(())
}
}
lazy_static! {
pub static ref QUERIES_TOTAL: IntCounterVec = IntCounterVec::new(
Opts::new(
"block_store_queries_total",
"Number of block store requests labelled by type."
),
&["type"],
)
.unwrap();
pub static ref QUERY_DURATION: HistogramVec = HistogramVec::new(
HistogramOpts::new(
"block_store_query_duration",
"Duration of store queries labelled by type.",
),
&["type"],
)
.unwrap();
}
fn observe_query<T, F>(name: &'static str, query: F) -> Result<T>
where
F: FnOnce() -> Result<T>,
{
QUERIES_TOTAL.with_label_values(&[name]).inc();
let timer = QUERY_DURATION.with_label_values(&[name]).start_timer();
let res = query();
if res.is_ok() {
timer.observe_duration();
} else {
timer.stop_and_discard();
}
res
}
async fn observe_future<T, F>(name: &'static str, query: F) -> Result<T>
where
F: Future<Output = anyhow::Result<T>>,
{
QUERIES_TOTAL.with_label_values(&[name]).inc();
let timer = QUERY_DURATION.with_label_values(&[name]).start_timer();
let res = query.await;
if res.is_ok() {
timer.observe_duration();
} else {
timer.stop_and_discard();
}
Ok(res?)
}
struct SqliteStoreCollector<S: StoreParams> {
store: Arc<Mutex<BlockStore<S>>>,
desc: Desc,
}
impl<S: StoreParams> Collector for SqliteStoreCollector<S>
where
Ipld: References<S::Codecs>,
{
fn desc(&self) -> Vec<&Desc> {
vec![&self.desc]
}
fn collect(&self) -> Vec<MetricFamily> {
let mut family = vec![];
if let Ok(stats) = self.store.lock().get_store_stats() {
let store_block_count =
IntGauge::new("block_store_block_count", "Number of stored blocks").unwrap();
store_block_count.set(stats.count() as _);
family.push(store_block_count.collect()[0].clone());
let store_size =
IntGauge::new("block_store_size", "Size in bytes of stored blocks").unwrap();
store_size.set(stats.size() as _);
family.push(store_size.collect()[0].clone());
}
family
}
}
impl<S: StoreParams> SqliteStoreCollector<S> {
pub fn new(store: Arc<Mutex<BlockStore<S>>>) -> Self {
let desc = Desc::new(
"block_store_stats".into(),
".".into(),
Default::default(),
Default::default(),
)
.unwrap();
Self { store, desc }
}
}
pub struct Batch<'a, S>(ipfs_sqlite_block_store::Transaction<'a, S>);
impl<'a, S: StoreParams> Batch<'a, S>
where
S: StoreParams,
Ipld: References<S::Codecs>,
{
pub fn create_temp_pin(&self) -> Result<TempPin> {
Ok(self.0.temp_pin())
}
pub fn temp_pin(
&self,
temp: &TempPin,
iter: impl IntoIterator<Item = Cid> + Send + 'static,
) -> Result<()> {
for link in iter {
self.0.extend_temp_pin(&temp, &link)?;
}
Ok(())
}
pub fn iter(&self) -> Result<impl Iterator<Item = Cid>> {
let cids = self.0.get_block_cids::<Vec<Cid>>()?;
Ok(cids.into_iter())
}
pub fn contains(&self, cid: &Cid) -> Result<bool> {
Ok(self.0.has_block(cid)?)
}
pub fn get(&mut self, cid: &Cid) -> Result<Option<Vec<u8>>> {
Ok(self.0.get_block(cid)?)
}
pub fn insert(&mut self, block: &Block<S>) -> Result<()> {
Ok(self.0.put_block(block, None)?)
}
pub fn resolve(&self, alias: &[u8]) -> Result<Option<Cid>> {
Ok(self.0.resolve(alias)?)
}
pub fn alias(&mut self, alias: &[u8], cid: Option<&Cid>) -> Result<()> {
Ok(self.0.alias(alias, cid)?)
}
pub fn reverse_alias(&self, cid: &Cid) -> Result<Option<Vec<Vec<u8>>>> {
Ok(self.0.reverse_alias(cid)?)
}
pub fn missing_blocks(&self, cid: &Cid) -> Result<Vec<Cid>> {
Ok(self.0.get_missing_blocks(cid)?)
}
}
#[cfg(test)]
mod tests {
use crate::executor::Executor;
use super::*;
use libipld::cbor::DagCborCodec;
use libipld::multihash::Code;
use libipld::store::DefaultParams;
use libipld::{alias, ipld};
fn create_block(ipld: &Ipld) -> Block<DefaultParams> {
Block::encode(DagCborCodec, Code::Blake3_256, ipld).unwrap()
}
macro_rules! assert_evicted {
($store:expr, $block:expr) => {
assert_eq!($store.reverse_alias($block.cid()).unwrap(), None);
};
}
macro_rules! assert_pinned {
($store:expr, $block:expr) => {
assert_eq!(
$store
.reverse_alias($block.cid())
.unwrap()
.map(|a| !a.is_empty()),
Some(true)
);
};
}
macro_rules! assert_unpinned {
($store:expr, $block:expr) => {
assert_eq!(
$store
.reverse_alias($block.cid())
.unwrap()
.map(|a| !a.is_empty()),
Some(false)
);
};
}
fn tracing_try_init() {
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.try_init()
.ok();
}
fn create_store() -> StorageService<DefaultParams> {
let config = StorageConfig::new(None, 2, Duration::from_secs(100));
StorageService::open(config, Executor::new()).unwrap()
}
#[async_std::test]
async fn test_store_evict() {
tracing_try_init();
let store = create_store();
let blocks = [
create_block(&ipld!(0)),
create_block(&ipld!(1)),
create_block(&ipld!(2)),
create_block(&ipld!(3)),
];
store.insert(&blocks[0]).unwrap();
store.insert(&blocks[1]).unwrap();
store.flush().await.unwrap();
store.evict().await.unwrap();
assert_unpinned!(&store, &blocks[0]);
assert_unpinned!(&store, &blocks[1]);
store.insert(&blocks[2]).unwrap();
store.flush().await.unwrap();
store.evict().await.unwrap();
assert_evicted!(&store, &blocks[0]);
assert_unpinned!(&store, &blocks[1]);
assert_unpinned!(&store, &blocks[2]);
store.get(blocks[1].cid()).unwrap();
store.insert(&blocks[3]).unwrap();
store.flush().await.unwrap();
store.evict().await.unwrap();
assert_unpinned!(&store, &blocks[1]);
assert_evicted!(&store, &blocks[2]);
assert_unpinned!(&store, &blocks[3]);
}
#[async_std::test]
#[allow(clippy::many_single_char_names)]
async fn test_store_unpin() {
tracing_try_init();
let store = create_store();
let a = create_block(&ipld!({ "a": [] }));
let b = create_block(&ipld!({ "b": [a.cid()] }));
let c = create_block(&ipld!({ "c": [a.cid()] }));
let x = alias!(x).as_bytes().to_vec();
let y = alias!(y).as_bytes().to_vec();
store.insert(&a).unwrap();
store.insert(&b).unwrap();
store.insert(&c).unwrap();
store.alias(&x, Some(b.cid())).unwrap();
store.alias(&y, Some(c.cid())).unwrap();
store.flush().await.unwrap();
assert_pinned!(&store, &a);
assert_pinned!(&store, &b);
assert_pinned!(&store, &c);
store.alias(&x, None).unwrap();
store.flush().await.unwrap();
assert_pinned!(&store, &a);
assert_unpinned!(&store, &b);
assert_pinned!(&store, &c);
store.alias(&y, None).unwrap();
store.flush().await.unwrap();
assert_unpinned!(&store, &a);
assert_unpinned!(&store, &b);
assert_unpinned!(&store, &c);
}
#[async_std::test]
#[allow(clippy::many_single_char_names)]
async fn test_store_unpin2() {
tracing_try_init();
let store = create_store();
let a = create_block(&ipld!({ "a": [] }));
let b = create_block(&ipld!({ "b": [a.cid()] }));
let x = alias!(x).as_bytes().to_vec();
let y = alias!(y).as_bytes().to_vec();
store.insert(&a).unwrap();
store.insert(&b).unwrap();
store.alias(&x, Some(b.cid())).unwrap();
store.alias(&y, Some(b.cid())).unwrap();
store.flush().await.unwrap();
assert_pinned!(&store, &a);
assert_pinned!(&store, &b);
store.alias(&x, None).unwrap();
store.flush().await.unwrap();
assert_pinned!(&store, &a);
assert_pinned!(&store, &b);
store.alias(&y, None).unwrap();
store.flush().await.unwrap();
assert_unpinned!(&store, &a);
assert_unpinned!(&store, &b);
}
}