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
use std::{
ops::Deref,
sync::{Arc, RwLock, Weak},
};
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()),
}
}
pub fn subscriptions(&self) -> impl '_ + Deref<Target = SetArc<SyncSubscription>> {
self.subscriptions.read().unwrap()
}
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 {
::log::debug!("Unregistering sync subscription with query `{subscription}`",);
if let Ok(ditto) = Ditto::upgrade(&self.ditto) {
if let Err(error) = ffi_sdk::dittoffi_try_experimental_remove_dql_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);
::log::error!(
"Failed to unregister sync subscription `{subscription}`: {ditto_error}",
);
}
return true;
}
}
false
}
}