use_prelude!();
use std::sync::Arc;
use ffi_sdk::COrderByParam;
use tracing::{debug, error};
use crate::{
ditto::{DittoHandleWrapper, WeakDittoHandleWrapper},
error::{DittoError, ErrorKind},
};
pub struct Subscription {
pub(super) ditto: WeakDittoHandleWrapper,
pub(super) collection_name: char_p::Box,
pub(super) query: char_p::Box,
pub(super) query_args: Option<Vec<u8>>,
pub(super) order_by: Vec<(String, QuerySortDirection)>,
pub(super) limit: i32,
pub(super) offset: u32,
}
impl Subscription {
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
ditto: DittoHandleWrapper,
collection_name: char_p::Box,
query: &str,
query_args: Option<Vec<u8>>,
order_by: &'_ [COrderByParam<'_>],
limit: i32,
offset: u32,
) -> Self {
let query = char_p::new(query);
{
let code = ffi_sdk::ditto_add_subscription(
&ditto,
collection_name.as_ref(),
query.as_ref(),
query_args.as_ref().map(|qa| (&qa[..]).into()),
order_by.into(),
limit,
offset,
);
if code != 0 {
error!(
collection = %collection_name,
%query,
error = %DittoError::from_ffi(ErrorKind::InvalidInput),
"error adding subscription",
);
}
};
let order_by: Vec<(String, QuerySortDirection)> = order_by
.iter()
.map(|o| (o.query_c_str.to_str_with_null().to_string(), o.direction))
.collect();
Subscription {
ditto: Arc::downgrade(&ditto),
collection_name,
query,
query_args,
order_by,
limit,
offset,
}
}
}
impl crate::observer::Observer for Subscription {}
impl Drop for Subscription {
fn drop(&mut self) {
debug!(
collection = %self.collection_name,
query = %self.query,
"dropping subscription",
);
if let Some(ditto) = self.ditto.upgrade() {
{
let order_by = self
.order_by
.iter()
.map(|query_and_direction| COrderByParam {
query_c_str: query_and_direction
.0
.as_str()
.try_into()
.expect("valid string"),
direction: query_and_direction.1,
})
.collect::<Vec<COrderByParam<'_>>>();
let code = ffi_sdk::ditto_remove_subscription(
&ditto,
self.collection_name.as_ref(),
self.query.as_ref(),
self.query_args.as_ref().map(|qa| (&qa[..]).into()),
order_by[..].into(),
self.limit,
self.offset,
);
if code != 0 {
error!(
collection = %self.collection_name,
query = %self.query,
error = %DittoError::from_ffi(ErrorKind::InvalidInput),
"error removing subscription",
);
}
}
}
}
}