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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
#![allow(unused_imports)]
use crate::prelude::*;
use error_chain::bail;
use fxhash::FxHashMap;
use fxhash::FxHashSet;
use multimap::MultiMap;
use serde::Deserialize;
use serde::{de::DeserializeOwned, de::Deserializer, Serialize, Serializer};
use std::cell::RefCell;
use std::ops::Deref;
use std::ops::DerefMut;
use std::rc::Rc;
use std::sync::Mutex as StdMutex;
use std::sync::RwLock as StdRwLock;
use std::sync::Weak;
use std::{fmt::Debug, sync::Arc};
use tokio::sync::broadcast;
use tokio::sync::mpsc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use tracing_futures::Instrument;

use super::dao::*;
use super::row::*;
use super::DioMutState;
use crate::comms::*;
use crate::error::*;
use crate::event::*;
use crate::header::PrimaryKeyScope;
use crate::index::*;
use crate::lint::*;
use crate::meta::*;
use crate::spec::*;
use crate::time::*;
use crate::transaction::*;
use crate::tree::*;
use crate::trust::LoadResult;

use crate::crypto::{EncryptedPrivateKey, PrivateSignKey};
use crate::{
    crypto::EncryptKey,
    session::{AteSession, AteSessionProperty},
};

#[derive(Debug)]
pub(crate) struct DioState {
    pub(super) cache_load: FxHashMap<PrimaryKey, (Arc<EventData>, EventLeaf)>,
}

/// Represents a series of mutations that the user is making on a particular chain-of-trust
/// with a specific set of facts attached to a session. All changes are stored in memory
/// until the commit function is invoked which will feed them into the chain.
///
/// If you decide to abort the transaction then call the `cancel` function before it goes
/// out of scope however if you mutate data and do not call `commit` then the data will be
/// lost (or an assert will be triggerd when in Debug mode).
///
/// These objects are multi-thread safe and allow for very high concurrency through async
/// operations.
///
/// When setting the scope for the DIO it will behave differently when the commit function
/// is invoked based on what scope you set for the transaction.
pub struct Dio {
    pub(super) chain: Arc<Chain>,
    pub(super) multi: ChainMultiUser,
    pub(super) state: StdMutex<DioState>,
    pub(super) session: StdRwLock<Box<dyn AteSession>>,
    pub(super) time: Arc<TimeKeeper>,
    pub(crate) log_format: Option<MessageFormat>,
}

pub(crate) struct DioScope {
    pop: Option<Arc<Dio>>,
    _negative: Rc<()>,
}

impl DioScope {
    pub fn new(dio: &Arc<Dio>) -> Self {
        DioScope {
            pop: Dio::current_set(Some(Arc::clone(dio))),
            _negative: Rc::new(()),
        }
    }
}

impl Drop for DioScope {
    fn drop(&mut self) {
        Dio::current_set(self.pop.take());
    }
}

pub(crate) enum DioWeak {
    Uninitialized,
    Weak(Weak<Dio>),
}

impl Default for DioWeak {
    fn default() -> Self {
        match Dio::current_get() {
            Some(a) => DioWeak::Weak(Arc::downgrade(&a)),
            None => DioWeak::Uninitialized,
        }
    }
}

impl Clone for DioWeak {
    fn clone(&self) -> Self {
        match self {
            Self::Uninitialized => Self::default(),
            Self::Weak(a) => Self::Weak(Weak::clone(a)),
        }
    }
}

impl From<&Arc<Dio>> for DioWeak {
    fn from(val: &Arc<Dio>) -> Self {
        DioWeak::Weak(Arc::downgrade(val))
    }
}

impl From<&Arc<DioMut>> for DioWeak {
    fn from(val: &Arc<DioMut>) -> Self {
        DioWeak::Weak(Arc::downgrade(&val.dio))
    }
}

impl Dio {
    thread_local! {
        static CURRENT: RefCell<Option<Arc<Dio>>> = RefCell::new(None)
    }

    pub(crate) fn current_get() -> Option<Arc<Dio>> {
        Dio::CURRENT.with(|dio| {
            let dio = dio.borrow();
            return dio.clone();
        })
    }

    fn current_set(val: Option<Arc<Dio>>) -> Option<Arc<Dio>> {
        Dio::CURRENT.with(|dio| {
            let mut dio = dio.borrow_mut();
            match val {
                Some(a) => dio.replace(a),
                None => dio.take(),
            }
        })
    }

    pub fn chain(&self) -> &Arc<Chain> {
        &self.chain
    }

    async fn run_async<F>(&self, future: F) -> F::Output
    where
        F: std::future::Future,
    {
        let key_str = self.chain.key().to_string();
        TaskEngine::run_until(future.instrument(span!(Level::DEBUG, "dio", key = key_str.as_str())))
            .await
    }

    pub async fn load_raw(self: &Arc<Self>, key: &PrimaryKey) -> Result<EventData, LoadError> {
        self.run_async(self.__load_raw(key)).await
    }

    pub(super) async fn __load_raw(
        self: &Arc<Self>,
        key: &PrimaryKey,
    ) -> Result<EventData, LoadError> {
        let leaf = match self.multi.lookup_primary(key).await {
            Some(a) => a,
            None => bail!(LoadErrorKind::NotFound(key.clone())),
        };
        let data = self.multi.load(leaf).await?.data;
        Ok(data)
    }

    pub async fn load<D>(self: &Arc<Self>, key: &PrimaryKey) -> Result<Dao<D>, LoadError>
    where
        D: DeserializeOwned,
    {
        self.run_async(self.__load(key)).await
    }

    pub(super) async fn __load<D>(self: &Arc<Self>, key: &PrimaryKey) -> Result<Dao<D>, LoadError>
    where
        D: DeserializeOwned,
    {
        {
            let state = self.state.lock().unwrap();
            if let Some((dao, leaf)) = state.cache_load.get(key) {
                let (row_header, row) =
                    Row::from_event(self, dao.deref(), leaf.created, leaf.updated)?;
                return Ok(Dao::new(self, row_header, row));
            }
        }

        let leaf = match self.multi.lookup_primary(key).await {
            Some(a) => a,
            None => bail!(LoadErrorKind::NotFound(key.clone())),
        };
        Ok(self.load_from_entry(leaf).await?)
    }

    pub async fn load_and_take<D>(self: &Arc<Self>, key: &PrimaryKey) -> Result<D, LoadError>
    where
        D: DeserializeOwned,
    {
        let ret: Dao<D> = self.load(key).await?;
        Ok(ret.take())
    }

    pub async fn exists(&self, key: &PrimaryKey) -> bool {
        self.run_async(self.__exists(key)).await
    }

    pub(super) async fn __exists(&self, key: &PrimaryKey) -> bool {
        {
            let state = self.state.lock().unwrap();
            if let Some((_, _)) = state.cache_load.get(key) {
                return true;
            }
        }

        self.multi.lookup_primary(key).await.is_some()
    }

    pub(crate) async fn load_from_entry<D>(
        self: &Arc<Self>,
        leaf: EventLeaf,
    ) -> Result<Dao<D>, LoadError>
    where
        D: DeserializeOwned,
    {
        self.run_async(self.__load_from_entry(leaf)).await
    }

    pub(super) async fn __load_from_entry<D>(
        self: &Arc<Self>,
        leaf: EventLeaf,
    ) -> Result<Dao<D>, LoadError>
    where
        D: DeserializeOwned,
    {
        let evt = self.multi.load(leaf).await?;
        let session = self.session();

        Ok(self.load_from_event(session.as_ref(), evt.data, evt.header.as_header()?, leaf)?)
    }

    pub(crate) fn load_from_event<D>(
        self: &Arc<Self>,
        session: &'_ dyn AteSession,
        mut data: EventData,
        header: EventHeader,
        leaf: EventLeaf,
    ) -> Result<Dao<D>, LoadError>
    where
        D: DeserializeOwned,
    {
        data.data_bytes = match data.data_bytes {
            Some(data) => Some(self.multi.data_as_overlay(&header.meta, data, session)?),
            None => None,
        };

        let mut state = self.state.lock().unwrap();
        match header.meta.get_data_key() {
            Some(key) => {
                let (row_header, row) = Row::from_event(self, &data, leaf.created, leaf.updated)?;
                state.cache_load.insert(key.clone(), (Arc::new(data), leaf));
                Ok(Dao::new(self, row_header, row))
            }
            None => Err(LoadErrorKind::NoPrimaryKey.into()),
        }
    }

    pub async fn children_keys(
        self: &Arc<Self>,
        parent_id: PrimaryKey,
        collection_id: u64,
    ) -> Result<Vec<PrimaryKey>, LoadError> {
        self.run_async(self.__children_keys(parent_id, collection_id))
            .await
    }

    pub async fn __children_keys(
        self: &Arc<Self>,
        parent_id: PrimaryKey,
        collection_id: u64,
    ) -> Result<Vec<PrimaryKey>, LoadError> {
        // Build the secondary index key
        let collection_key = MetaCollection {
            parent_id,
            collection_id,
        };

        // Build a list of keys
        let keys = match self.multi.lookup_secondary_raw(&collection_key).await {
            Some(a) => a,
            None => return Ok(Vec::new()),
        };
        Ok(keys)
    }

    pub async fn all_keys(self: &Arc<Self>) -> Vec<PrimaryKey> {
        self.run_async(self.__all_keys()).await
    }

    pub async fn __all_keys(self: &Arc<Self>) -> Vec<PrimaryKey> {
        let guard = self.multi.inside_async.read().await;
        let keys = guard.chain.timeline.pointers.all_keys();
        keys.map(|a| a.clone()).collect::<Vec<_>>()
    }

    pub async fn children<D>(
        self: &Arc<Self>,
        parent_id: PrimaryKey,
        collection_id: u64,
    ) -> Result<Vec<Dao<D>>, LoadError>
    where
        D: DeserializeOwned,
    {
        self.children_ext(parent_id, collection_id, false, false)
            .await
    }

    pub async fn children_ext<D>(
        self: &Arc<Self>,
        parent_id: PrimaryKey,
        collection_id: u64,
        allow_missing_keys: bool,
        allow_serialization_error: bool,
    ) -> Result<Vec<Dao<D>>, LoadError>
    where
        D: DeserializeOwned,
    {
        self.run_async(self.__children_ext(
            parent_id,
            collection_id,
            allow_missing_keys,
            allow_serialization_error,
        ))
        .await
    }

    pub(super) async fn __children_ext<D>(
        self: &Arc<Self>,
        parent_id: PrimaryKey,
        collection_id: u64,
        allow_missing_keys: bool,
        allow_serialization_error: bool,
    ) -> Result<Vec<Dao<D>>, LoadError>
    where
        D: DeserializeOwned,
    {
        // Load all the objects
        let keys = self.__children_keys(parent_id, collection_id).await?;
        Ok(self
            .__load_many_ext(
                keys.into_iter(),
                allow_missing_keys,
                allow_serialization_error,
            )
            .await?)
    }

    pub async fn load_many<D>(
        self: &Arc<Self>,
        keys: impl Iterator<Item = PrimaryKey>,
    ) -> Result<Vec<Dao<D>>, LoadError>
    where
        D: DeserializeOwned,
    {
        self.load_many_ext(keys, false, false).await
    }

    pub async fn load_many_ext<D>(
        self: &Arc<Self>,
        keys: impl Iterator<Item = PrimaryKey>,
        allow_missing_keys: bool,
        allow_serialization_error: bool,
    ) -> Result<Vec<Dao<D>>, LoadError>
    where
        D: DeserializeOwned,
    {
        self.run_async(self.__load_many_ext(keys, allow_missing_keys, allow_serialization_error))
            .await
    }

    pub(super) async fn __load_many_ext<D>(
        self: &Arc<Self>,
        keys: impl Iterator<Item = PrimaryKey>,
        allow_missing_keys: bool,
        allow_serialization_error: bool,
    ) -> Result<Vec<Dao<D>>, LoadError>
    where
        D: DeserializeOwned,
    {
        // This is the main return list
        let mut already = FxHashSet::default();
        let mut ret = Vec::new();

        let inside_async = self.multi.inside_async.read().await;

        // We either find existing objects in the cache or build a list of objects to load
        let to_load = {
            let mut to_load = Vec::new();

            let state = self.state.lock().unwrap();
            for key in keys {
                if let Some((dao, leaf)) = state.cache_load.get(&key) {
                    let (row_header, row) =
                        Row::from_event(self, dao.deref(), leaf.created, leaf.updated)?;
                    already.insert(row.key.clone());
                    ret.push(Dao::new(self, row_header, row));
                    continue;
                }

                to_load.push(match inside_async.chain.lookup_primary(&key) {
                    Some(a) => a,
                    None => continue,
                });
            }
            to_load
        };

        // Load all the objects that have not yet been loaded
        let to_load = inside_async.chain.load_many(to_load).await?;

        // Now process all the objects
        let ret = {
            let mut state = self.state.lock().unwrap();
            let session = self.session();
            for mut evt in to_load {
                let mut header = evt.header.as_header()?;

                let key = match header.meta.get_data_key() {
                    Some(k) => k,
                    None => {
                        continue;
                    }
                };

                if let Some((dao, leaf)) = state.cache_load.get(&key) {
                    let (row_header, row) =
                        Row::from_event(self, dao.deref(), leaf.created, leaf.updated)?;

                    already.insert(row.key.clone());
                    ret.push(Dao::new(self, row_header, row));
                }

                let (row_header, row) = match self.__process_load_row(
                    session.as_ref(),
                    &mut evt,
                    &mut header.meta,
                    allow_missing_keys,
                    allow_serialization_error,
                )? {
                    Some(a) => a,
                    None => {
                        continue;
                    }
                };
                state
                    .cache_load
                    .insert(row.key.clone(), (Arc::new(evt.data), evt.leaf));

                already.insert(row.key.clone());
                ret.push(Dao::new(self, row_header, row));
            }
            ret
        };

        Ok(ret)
    }

    pub(crate) fn data_as_overlay(
        self: &Arc<Self>,
        session: &'_ dyn AteSession,
        data: &mut EventData,
    ) -> Result<(), TransformError> {
        data.data_bytes = match &data.data_bytes {
            Some(d) => Some(self.multi.data_as_overlay(&data.meta, d.clone(), session)?),
            None => None,
        };
        Ok(())
    }

    pub(super) fn __process_load_row<D>(
        self: &Arc<Self>,
        session: &'_ dyn AteSession,
        evt: &mut LoadResult,
        meta: &Metadata,
        allow_missing_keys: bool,
        allow_serialization_error: bool,
    ) -> Result<Option<(RowHeader, Row<D>)>, LoadError>
    where
        D: DeserializeOwned,
    {
        evt.data.data_bytes = match &evt.data.data_bytes {
            Some(data) => {
                let data = match self.multi.data_as_overlay(meta, data.clone(), session) {
                    Ok(a) => a,
                    Err(TransformError(TransformErrorKind::MissingReadKey(_hash), _))
                        if allow_missing_keys =>
                    {
                        //trace!("Missing read key {} - ignoring row", _hash);
                        return Ok(None);
                    }
                    Err(err) => {
                        bail!(LoadErrorKind::TransformationError(err.0));
                    }
                };
                Some(data)
            }
            None => {
                return Ok(None);
            }
        };

        let (row_header, row) =
            match Row::from_event(self, &evt.data, evt.leaf.created, evt.leaf.updated) {
                Ok(a) => a,
                Err(err) => {
                    if allow_serialization_error {
                        //trace!("Serialization error {} - ignoring row", err);
                        return Ok(None);
                    }
                    bail!(LoadErrorKind::SerializationError(err.0));
                }
            };
        Ok(Some((row_header, row)))
    }

    pub fn session<'a>(&'a self) -> DioSessionGuard<'a> {
        DioSessionGuard::new(self)
    }

    pub fn session_mut<'a>(&'a self) -> DioSessionGuardMut<'a> {
        DioSessionGuardMut::new(self)
    }

    pub async fn wait_for_accurate_timing(&self) {
        self.time.wait_for_high_accuracy().await;
    }

    pub(crate) fn run_decache(self: &Arc<Dio>, mut decache: broadcast::Receiver<Vec<PrimaryKey>>) {
        let dio = Arc::downgrade(self);

        TaskEngine::spawn(async move {
            loop {
                let recv =
                    crate::engine::timeout(std::time::Duration::from_secs(1), decache.recv()).await;
                let dio = match Weak::upgrade(&dio) {
                    Some(a) => a,
                    None => {
                        break;
                    }
                };
                let recv = match recv {
                    Ok(a) => a,
                    Err(_) => {
                        continue;
                    }
                };
                let recv = match recv {
                    Ok(a) => a,
                    Err(_) => {
                        break;
                    }
                };

                let mut state = dio.state.lock().unwrap();
                for key in recv {
                    state.cache_load.remove(&key);
                }
            }
        });
    }
}

pub struct DioSessionGuard<'a> {
    lock: std::sync::RwLockReadGuard<'a, Box<dyn AteSession>>,
}

impl<'a> DioSessionGuard<'a> {
    fn new(dio: &'a Dio) -> DioSessionGuard<'a> {
        DioSessionGuard {
            lock: dio.session.read().unwrap(),
        }
    }

    pub fn as_ref(&self) -> &dyn AteSession {
        self.lock.deref().deref()
    }
}

impl<'a> Deref for DioSessionGuard<'a> {
    type Target = dyn AteSession;

    fn deref(&self) -> &Self::Target {
        self.lock.deref().deref()
    }
}

pub struct DioSessionGuardMut<'a> {
    lock: std::sync::RwLockWriteGuard<'a, Box<dyn AteSession>>,
}

impl<'a> DioSessionGuardMut<'a> {
    fn new(dio: &'a Dio) -> DioSessionGuardMut<'a> {
        DioSessionGuardMut {
            lock: dio.session.write().unwrap(),
        }
    }

    pub fn as_ref(&self) -> &dyn AteSession {
        self.lock.deref().deref()
    }

    pub fn as_mut(&mut self) -> &mut dyn AteSession {
        self.lock.deref_mut().deref_mut()
    }
}

impl<'a> Deref for DioSessionGuardMut<'a> {
    type Target = dyn AteSession;

    fn deref(&self) -> &Self::Target {
        self.lock.deref().deref()
    }
}

impl<'a> DerefMut for DioSessionGuardMut<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.lock.deref_mut().deref_mut()
    }
}

impl Chain {
    /// Opens a data access layer that allows read only access to data within the chain
    /// In order to make changes to data you must use '.dio_mut', '.dio_fire', '.dio_full' or '.dio_trans'
    pub async fn dio(self: &Arc<Chain>, session: &'_ dyn AteSession) -> Arc<Dio> {
        TaskEngine::run_until(self.__dio(session)).await
    }

    pub(crate) async fn __dio(self: &Arc<Chain>, session: &'_ dyn AteSession) -> Arc<Dio> {
        let decache = self.decache.subscribe();
        let multi = self.multi().await;
        let ret = Dio {
            chain: Arc::clone(self),
            state: StdMutex::new(DioState {
                cache_load: FxHashMap::default(),
            }),
            session: StdRwLock::new(session.clone_session()),
            log_format: Some(multi.default_format.clone()),
            multi,
            time: Arc::clone(&self.time),
        };
        let ret = Arc::new(ret);
        ret.run_decache(decache);
        ret
    }
}

impl Dio {
    pub async fn as_mut(self: &Arc<Self>) -> Arc<DioMut> {
        self.trans(TransactionScope::Local).await
    }

    pub async fn trans(self: &Arc<Self>, scope: TransactionScope) -> Arc<DioMut> {
        TaskEngine::run_until(self.__trans(scope)).await
    }

    pub(crate) async fn __trans(self: &Arc<Self>, scope: TransactionScope) -> Arc<DioMut> {
        DioMut::__new(self, scope).await
    }
}