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
//! Manage the synchronization properties of your Ditto instance from here.

use std::{
    ops::Deref,
    sync::{Arc, RwLock, Weak},
};

use tracing::{debug, error};

/// We need to use `hashbrown` for its `.raw_entry_mut()` API (so as to be able
/// to use `Arc<T>` with `&T`…)
use crate::{
    ditto::{Ditto, DittoFields},
    error::DittoError,
    store::dql::*,
    utils::extension_traits::FfiResultIntoRustResult,
    utils::SetArc,
};

pub struct Sync {
    ditto: Weak<DittoFields>,
    subscriptions: RwLock<SetArc<SyncSubscription>>,
}

impl Sync {
    pub(crate) fn new(ditto: Weak<DittoFields>) -> Self {
        Self {
            ditto,
            subscriptions: RwLock::new(SetArc::default()),
        }
    }

    /// Gets temporary access to the set of currently registered subscriptions.
    ///
    /// A (read) lock is held until the return value is dropped: this means
    /// that neither [`Self::register_subscription()`] nor
    /// [`SyncSubscription::cancel()`] can make progress until this read
    /// lock is released.
    pub fn subscriptions(&self) -> impl '_ + Deref<Target = SetArc<SyncSubscription>> {
        self.subscriptions.read().unwrap()
    }

    /// Run the provided query on the device of connected peers and send the
    /// results of the query back to the local peer's data store.
    ///
    /// The returned [`SyncSubscription`] object must be kept in scope
    /// for as long as you want to keep receiving updates.
    ///
    /// Use placeholders to incorporate values from the optional `query_args`
    /// parameter into the query. The keys of the `QueryArguments` object must
    /// match the placeholders used within the query. You cannot use placeholders
    /// in the `FROM` clause.
    pub fn register_subscription<Q>(
        &self,
        query: Q,
        query_args: Option<QueryArguments>,
    ) -> Result<Arc<SyncSubscription>, DittoError>
    where
        Q: TryInto<Query, Error = DittoError>,
    {
        let ditto = Ditto::upgrade(&self.ditto)?;
        let new_sub = Arc::new(SyncSubscription::new(
            &ditto,
            query.try_into()?,
            query_args,
        )?);
        self.subscriptions.write().unwrap().insert(new_sub.clone());
        Ok(new_sub)
    }

    pub(crate) fn unregister_subscription(&self, subscription: &SyncSubscription) -> bool {
        let subscriptions = &mut *self.subscriptions.write().unwrap();
        let removed = subscriptions.remove(subscription);
        if removed {
            debug!(%subscription, "unregistering sync subscription");
            if let Ok(ditto) = Ditto::upgrade(&self.ditto) {
                if let Err(error) = ffi_sdk::dittoffi_try_remove_sync_subscription(
                    &ditto.ditto,
                    subscription.query.prepare_ffi(),
                    subscription.query_args.as_ref().map(|qa| qa.cbor().into()),
                )
                .into_rust_result()
                {
                    let ditto_error = DittoError::from(error);
                    error!(
                        error = %ditto_error,
                        %subscription,
                        "failed to unregister sync subscription",
                    );
                }
                return true;
            }
        }
        false
    }
}