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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
// Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under both the MIT license found in the
// LICENSE-MIT file in the root directory of this source tree and the Apache
// License, Version 2.0 found in the LICENSE-APACHE file in the root directory
// of this source tree.

//! Storage management module for AKD. A wrapper around the underlying database interaction
//! to manage interactions with the data layer to optimize things like caching and
//! transaction management

use crate::storage::cache::TimedCache;
use crate::storage::transaction::Transaction;
use crate::storage::types::DbRecord;
use crate::storage::types::KeyData;
use crate::storage::types::ValueState;
use crate::storage::types::ValueStateKey;
use crate::storage::Database;
use crate::storage::DbSetState;
use crate::storage::Storable;
use crate::storage::StorageError;
use crate::AkdLabel;
use crate::AkdValue;

use log::{debug, error, info, warn};
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;

use super::types::ValueStateRetrievalFlag;

type Metric = usize;

const METRIC_GET: Metric = 0;
const METRIC_BATCH_GET: Metric = 1;
const METRIC_SET: Metric = 2;
const METRIC_BATCH_SET: Metric = 3;
const METRIC_READ_TIME: Metric = 4;
const METRIC_WRITE_TIME: Metric = 5;
const METRIC_TOMBSTONE: Metric = 6;
const METRIC_GET_USER_STATE: Metric = 7;
const METRIC_GET_USER_DATA: Metric = 8;
const METRIC_GET_USER_STATE_VERSIONS: Metric = 9;

const NUM_METRICS: usize = 10;

#[cfg(test)]
mod tests;

/// Represents the manager of the storage mediums, including caching
/// and transactional operations (creating the transaction, commiting it, etc)
pub struct StorageManager<Db: Database + Sync + Send> {
    cache: Option<TimedCache>,
    transaction: Transaction,
    /// The underlying database managed by this storage manager
    pub db: Db,

    metrics: [Arc<AtomicU64>; NUM_METRICS],
}

impl<Db: Database + Sync + Send> Clone for StorageManager<Db> {
    fn clone(&self) -> Self {
        Self {
            cache: self.cache.clone(),
            transaction: Transaction::new(),
            db: self.db.clone(),
            metrics: self.metrics.clone(),
        }
    }
}

unsafe impl<Db: Database + Sync + Send> Sync for StorageManager<Db> {}
unsafe impl<Db: Database + Sync + Send> Send for StorageManager<Db> {}

impl<Db: Database + Sync + Send> StorageManager<Db> {
    /// Create a new storage manager with NO CACHE
    pub fn new_no_cache(db: &Db) -> Self {
        Self {
            cache: None,
            transaction: Transaction::new(),
            db: db.clone(),
            metrics: [0; NUM_METRICS].map(|_| Arc::new(AtomicU64::new(0))),
        }
    }

    /// Create a new storage manager with a cache utilizing the options provided (or defaults)
    pub fn new(
        db: &Db,
        cache_item_lifetime: Option<Duration>,
        cache_limit_bytes: Option<usize>,
        cache_clean_frequency: Option<Duration>,
    ) -> Self {
        Self {
            cache: Some(TimedCache::new(
                cache_item_lifetime,
                cache_limit_bytes,
                cache_clean_frequency,
            )),
            transaction: Transaction::new(),
            db: db.clone(),
            metrics: [0; NUM_METRICS].map(|_| Arc::new(AtomicU64::new(0))),
        }
    }

    /// Log metrics from the storage manager (cache, transaction, and storage hit rates etc)
    pub async fn log_metrics(&self, level: log::Level) {
        if let Some(cache) = &self.cache {
            cache.log_metrics(level)
        }

        self.transaction.log_metrics(level).await;

        let snapshot = self
            .metrics
            .iter()
            .map(|metric| metric.load(Ordering::Relaxed))
            .collect::<Vec<_>>();

        let msg = format!(
            "
===================================================
============ Database operation counts ============
===================================================
    SET {}, 
    BATCH SET {}, 
    GET {}, 
    BATCH GET {}
    TOMBSTONE {}
    GET USER STATE {}
    GET USER DATA {}
    GET USER STATE VERSIONS {}
===================================================
============ Database operation timing ============
===================================================
    TIME READ {} ms
    TIME WRITE {} ms",
            snapshot[METRIC_SET],
            snapshot[METRIC_BATCH_SET],
            snapshot[METRIC_GET],
            snapshot[METRIC_BATCH_GET],
            snapshot[METRIC_TOMBSTONE],
            snapshot[METRIC_GET_USER_STATE],
            snapshot[METRIC_GET_USER_DATA],
            snapshot[METRIC_GET_USER_STATE_VERSIONS],
            snapshot[METRIC_READ_TIME],
            snapshot[METRIC_WRITE_TIME]
        );

        match level {
            // Currently logs cannot be captured unless they are
            // println!. Normally Level::Trace should use the trace! macro.
            log::Level::Trace => println!("{}", msg),
            log::Level::Debug => debug!("{}", msg),
            log::Level::Info => info!("{}", msg),
            log::Level::Warn => warn!("{}", msg),
            _ => error!("{}", msg),
        }
    }

    /// Start an in-memory transaction of changes
    pub async fn begin_transaction(&self) -> bool {
        let started = self.transaction.begin_transaction().await;

        // disable the cache cleaning since we're in a write transaction
        // and will want to keep cache'd objects for the life of the transaction
        if let Some(cache) = &self.cache {
            cache.disable_clean();
        }

        started
    }

    /// Commit a transaction in the database
    pub async fn commit_transaction(&self) -> Result<(), StorageError> {
        // this retrieves all the trans operations, and "de-activates" the transaction flag
        let records = self.transaction.commit_transaction().await?;

        // The transaction is now complete (or reverted) and therefore we can re-enable
        // the cache cleaning status
        if let Some(cache) = &self.cache {
            cache.enable_clean();
        }

        if records.is_empty() {
            // no-op, there's nothing to commit
            return Ok(());
        }

        let _epoch = match records.last() {
            Some(DbRecord::Azks(azks)) => Ok(azks.latest_epoch),
            other => Err(StorageError::Transaction(format!(
                "The last record in the transaction log is NOT an Azks record {:?}",
                other
            ))),
        }?;

        // update the cache
        if let Some(cache) = &self.cache {
            cache.batch_put(&records).await;
        }

        // Write to the database
        self.tic_toc(
            METRIC_WRITE_TIME,
            self.db.batch_set(records, DbSetState::TransactionCommit),
        )
        .await?;
        self.increment_metric(METRIC_BATCH_SET);
        Ok(())
    }

    /// Rollback a transaction
    pub async fn rollback_transaction(&self) -> Result<(), StorageError> {
        self.transaction.rollback_transaction().await?;
        // The transaction is being reverted and therefore we can re-enable
        // the cache cleaning status
        if let Some(cache) = &self.cache {
            cache.enable_clean();
        }
        Ok(())
    }

    /// Retrieve a flag determining if there is a transaction active
    pub async fn is_transaction_active(&self) -> bool {
        self.transaction.is_transaction_active().await
    }

    /// Store a record in the database
    pub async fn set(&self, record: DbRecord) -> Result<(), StorageError> {
        // we're in a transaction, set the item in the transaction
        if self.is_transaction_active().await {
            self.transaction.set(&record).await;
            return Ok(());
        }

        // update the cache
        if let Some(cache) = &self.cache {
            cache.put(&record).await;
        }

        // write to the database
        self.tic_toc(METRIC_WRITE_TIME, self.db.set(record)).await?;
        self.increment_metric(METRIC_SET);
        Ok(())
    }

    /// Set a batch of records in the database
    pub async fn batch_set(&self, records: Vec<DbRecord>) -> Result<(), StorageError> {
        if records.is_empty() {
            // nothing to do, save the cycles
            return Ok(());
        }

        // we're in a transaction, set the items in the transaction
        if self.is_transaction_active().await {
            self.transaction.batch_set(&records).await;
            return Ok(());
        }

        // update the cache
        if let Some(cache) = &self.cache {
            cache.batch_put(&records).await;
        }

        // Write to the database
        self.tic_toc(
            METRIC_WRITE_TIME,
            self.db.batch_set(records, DbSetState::General),
        )
        .await?;
        self.increment_metric(METRIC_BATCH_SET);
        Ok(())
    }

    /// Retrieve a stored record directly from the data layer, ignoring any caching or transaction processes
    pub async fn get_direct<St: Storable>(
        &self,
        id: &St::StorageKey,
    ) -> Result<DbRecord, StorageError> {
        // cache miss, read direct from db
        let record = self
            .tic_toc(METRIC_READ_TIME, self.db.get::<St>(id))
            .await?;
        self.increment_metric(METRIC_GET);
        Ok(record)
    }

    /// Retrieve a stored record from the database
    pub async fn get<St: Storable>(&self, id: &St::StorageKey) -> Result<DbRecord, StorageError> {
        // we're in a transaction, meaning the object _might_ be newer and therefore we should try and read if from the transaction
        // log instead of the raw storage layer
        if self.is_transaction_active().await {
            if let Some(result) = self.transaction.get::<St>(id).await {
                return Ok(result);
            }
        }

        // check for a cache hit
        if let Some(cache) = &self.cache {
            if let Some(result) = cache.hit_test::<St>(id).await {
                return Ok(result);
            }
        }

        // cache miss, read direct from db
        let record = self
            .tic_toc(METRIC_READ_TIME, self.db.get::<St>(id))
            .await?;
        if let Some(cache) = &self.cache {
            // cache the result
            cache.put(&record).await;
        }
        self.increment_metric(METRIC_GET);
        Ok(record)
    }

    /// Retrieve a batch of records by id from the database
    pub async fn batch_get<St: Storable>(
        &self,
        ids: &[St::StorageKey],
    ) -> Result<Vec<DbRecord>, StorageError> {
        let mut map = Vec::new();

        if ids.is_empty() {
            // nothing to retrieve, save the cycles
            return Ok(map);
        }

        let mut key_set: HashSet<St::StorageKey> = ids.iter().cloned().collect::<HashSet<_>>();

        let trans_active = self.is_transaction_active().await;
        // first check the transaction log & cache records
        for id in ids.iter() {
            if trans_active {
                // we're in a transaction, meaning the object _might_ be newer and therefore we should try and read if from the transaction
                // log instead of the raw storage layer
                if let Some(result) = self.transaction.get::<St>(id).await {
                    map.push(result);
                    key_set.remove(id);
                    continue;
                }
            }

            // check if item is cached
            if let Some(cache) = &self.cache {
                if let Some(result) = cache.hit_test::<St>(id).await {
                    map.push(result);
                    key_set.remove(id);
                    continue;
                }
            }
        }

        if !key_set.is_empty() {
            // these are items to be retrieved from the backing database (not in pending transaction or in the object cache)
            let keys = key_set.into_iter().collect::<Vec<_>>();
            let mut results = self
                .tic_toc(METRIC_READ_TIME, self.db.batch_get::<St>(&keys))
                .await?;

            // cache the db returned results
            if let Some(cache) = &self.cache {
                cache.batch_put(&results).await;
            }

            map.append(&mut results);
            self.increment_metric(METRIC_BATCH_GET);
        }
        Ok(map)
    }

    /// Flush the caching of objects (if present)
    pub async fn flush_cache(&self) {
        if let Some(cache) = &self.cache {
            cache.flush().await;
        }
    }

    /// Tombstone a set of records adhereing to the caching + transactional
    /// settings of the storage manager
    pub async fn tombstone_value_states(&self, keys: &[ValueStateKey]) -> Result<(), StorageError> {
        if keys.is_empty() {
            return Ok(());
        }

        let data = self.batch_get::<ValueState>(keys).await?;
        let mut new_data = vec![];
        for record in data {
            if let DbRecord::ValueState(value_state) = record {
                new_data.push(DbRecord::ValueState(ValueState {
                    epoch: value_state.epoch,
                    label: value_state.label,
                    plaintext_val: crate::AkdValue(crate::TOMBSTONE.to_vec()),
                    username: value_state.username,
                    version: value_state.version,
                }));
            }
        }
        if !new_data.is_empty() {
            debug!("Tombstoning {} entries", new_data.len());
            self.batch_set(new_data).await?;
            self.increment_metric(METRIC_TOMBSTONE);
        }

        Ok(())
    }

    /// Retrieve the specified user state object based on the retrieval flag from the database
    pub async fn get_user_state(
        &self,
        username: &AkdLabel,
        flag: ValueStateRetrievalFlag,
    ) -> Result<ValueState, StorageError> {
        let maybe_db_state = match self
            .tic_toc(METRIC_READ_TIME, self.db.get_user_state(username, flag))
            .await
        {
            Err(StorageError::NotFound(_)) => Ok(None),
            Ok(something) => Ok(Some(something)),
            Err(other) => Err(other),
        }?;
        self.increment_metric(METRIC_GET_USER_STATE);

        // in the event we are in a transaction, there may be an updated object in the
        // transactional storage. Therefore we should update the db retrieved value if
        // we can with what's in the transaction log
        if self.is_transaction_active().await {
            if let Some(transaction_value) = self.transaction.get_user_state(username, flag).await {
                if let Some(db_value) = &maybe_db_state {
                    if let Some(record) = Self::compare_db_and_transaction_records(
                        db_value.epoch,
                        transaction_value,
                        flag,
                    ) {
                        return Ok(record);
                    }
                } else {
                    // no db record, but there is a transaction record so use that
                    return Ok(transaction_value);
                }
            }
        }

        if let Some(state) = maybe_db_state {
            // cache the item for future access
            if let Some(cache) = &self.cache {
                cache.put(&DbRecord::ValueState(state.clone())).await;
            }

            Ok(state)
        } else {
            Err(StorageError::NotFound(format!("ValueState {:?}", username)))
        }
    }

    /// Retrieve all values states for a given user
    pub async fn get_user_data(&self, username: &AkdLabel) -> Result<KeyData, StorageError> {
        let maybe_db_data = match self
            .tic_toc(METRIC_READ_TIME, self.db.get_user_data(username))
            .await
        {
            Err(StorageError::NotFound(_)) => Ok(None),
            Ok(something) => Ok(Some(something)),
            Err(other) => Err(other),
        }?;
        self.increment_metric(METRIC_GET_USER_DATA);

        if self.is_transaction_active().await {
            // there are transaction-based values in the current transaction, they should override database-retrieved values
            let mut map = maybe_db_data
                .map(|data| {
                    data.states
                        .into_iter()
                        .map(|state| (state.epoch, state))
                        .collect::<HashMap<u64, _>>()
                })
                .unwrap_or_else(HashMap::new);

            let transaction_records = self
                .transaction
                .get_users_data(&[username.clone()])
                .await
                .remove(username)
                .unwrap_or_default();
            for transaction_record in transaction_records.into_iter() {
                map.insert(transaction_record.epoch, transaction_record);
            }

            return Ok(KeyData {
                states: map.into_values().collect::<Vec<_>>(),
            });
        }

        if let Some(data) = maybe_db_data {
            Ok(data)
        } else {
            Err(StorageError::NotFound(format!(
                "ValueState records for {:?}",
                username
            )))
        }
    }

    /// Retrieve the user -> state version mapping in bulk. This is the same as get_user_state in a loop, but with less data retrieved from the storage layer
    pub async fn get_user_state_versions(
        &self,
        usernames: &[AkdLabel],
        flag: ValueStateRetrievalFlag,
    ) -> Result<HashMap<AkdLabel, (u64, AkdValue)>, StorageError> {
        let mut data = self
            .tic_toc(
                METRIC_READ_TIME,
                self.db.get_user_state_versions(usernames, flag),
            )
            .await?;
        self.increment_metric(METRIC_GET_USER_STATE_VERSIONS);

        // in the event we are in a transaction, there may be an updated object in the
        // transactional storage. Therefore we should update the db retrieved value if
        // we can with what's in the transaction log
        if self.is_transaction_active().await {
            let transaction_records = self.transaction.get_users_states(usernames, flag).await;
            for (label, value_state) in transaction_records.into_iter() {
                if let Some((epoch, _)) = data.get(&label) {
                    // there is an existing DB record, check if we should updated it from the transaction log
                    if let Some(updated_record) =
                        Self::compare_db_and_transaction_records(*epoch, value_state, flag)
                    {
                        data.insert(label, (*epoch, updated_record.plaintext_val));
                    }
                } else {
                    // there is no db-equivalent record, but there IS a record in the transaction log.
                    // Take the transaction log value
                    data.insert(label, (value_state.epoch, value_state.plaintext_val));
                }
            }
        }

        Ok(data)
    }

    fn compare_db_and_transaction_records(
        state_epoch: u64,
        transaction_value: ValueState,
        flag: ValueStateRetrievalFlag,
    ) -> Option<ValueState> {
        match flag {
            ValueStateRetrievalFlag::SpecificVersion(_) => {
                return Some(transaction_value);
            }
            ValueStateRetrievalFlag::SpecificEpoch(_) => {
                return Some(transaction_value);
            }
            ValueStateRetrievalFlag::LeqEpoch(_) => {
                if transaction_value.epoch >= state_epoch {
                    // the transaction has either the same epoch or an epoch in the future, and therefore should
                    // override the db value
                    return Some(transaction_value);
                }
            }
            ValueStateRetrievalFlag::MaxEpoch => {
                if transaction_value.epoch >= state_epoch {
                    // the transaction has either the same epoch or an epoch in the future, and therefore should
                    // override the db value
                    return Some(transaction_value);
                }
            }
            ValueStateRetrievalFlag::MinEpoch => {
                if transaction_value.epoch <= state_epoch {
                    // the transaction has either the same epoch or an older epoch, and therefore should
                    // override the db value
                    return Some(transaction_value);
                }
            }
        }
        None
    }

    fn increment_metric(&self, _metric: Metric) {
        #[cfg(feature = "runtime_metrics")]
        {
            self.metrics[_metric].fetch_add(1, Ordering::Relaxed);
        }
    }

    async fn tic_toc<T>(&self, _metric: Metric, f: impl std::future::Future<Output = T>) -> T {
        #[cfg(feature = "runtime_metrics")]
        {
            let tic = std::time::Instant::now();
            let out = f.await;
            let delta = std::time::Instant::now().duration_since(tic);

            self.metrics[_metric].fetch_add(delta.as_millis() as u64, Ordering::Relaxed);

            out
        }
        #[cfg(not(feature = "runtime_metrics"))]
        {
            f.await
        }
    }
}