use std::sync::{Arc, RwLock};
use serde_json::{Map, Value};
use crate::SDK_VERSION;
use crate::data::{
Data, DataType, IntoPropertyMap, LIB_NAME, apply_preset_properties, format_properties,
};
use crate::error::{Result, TDError};
use crate::utils::is_valid_key;
#[cfg(feature = "async")]
use crate::consumer::AsyncConsumer;
#[cfg(feature = "blocking")]
use crate::consumer::Consumer;
type DynamicSuperProperties = Arc<dyn Fn() -> Map<String, Value> + Send + Sync>;
#[derive(Default)]
struct SuperProperties {
static_props: RwLock<Map<String, Value>>,
dynamic_props: RwLock<Option<DynamicSuperProperties>>,
}
impl SuperProperties {
fn get(&self) -> Map<String, Value> {
self.static_props
.read()
.expect("ThinkingData super properties poisoned")
.clone()
}
fn get_dynamic(&self) -> Map<String, Value> {
let action = self
.dynamic_props
.read()
.expect("ThinkingData super properties poisoned")
.clone();
if let Some(action) = action {
action()
} else {
Map::new()
}
}
fn set(&self, properties: Map<String, Value>) -> Result<()> {
for key in properties.keys() {
if !is_valid_key(key) {
return Err(TDError::InvalidPropertyKey(key.clone()));
}
}
let mut guard = self
.static_props
.write()
.expect("ThinkingData super properties poisoned");
for (key, value) in properties {
guard.insert(key, value);
}
Ok(())
}
}
fn validate_event(data_type: DataType, event_name: &str, event_id: &str) -> Result<()> {
if event_name.is_empty() {
crate::log::td_log_error("the event name must be provided");
return Err(TDError::EmptyEventName);
}
if event_id.is_empty() && data_type != DataType::Track {
crate::log::td_log_error("the event id must be provided");
return Err(TDError::EmptyEventId);
}
Ok(())
}
fn compose_track_properties(
super_properties: &Map<String, Value>,
dynamic: &Map<String, Value>,
custom: Map<String, Value>,
) -> Map<String, Value> {
let mut properties = super_properties.clone();
for (key, value) in dynamic {
properties.insert(key.clone(), value.clone());
}
properties.insert("#lib".to_string(), Value::String(LIB_NAME.to_string()));
properties.insert(
"#lib_version".to_string(),
Value::String(SDK_VERSION.to_string()),
);
for (key, value) in custom {
properties.insert(key, value);
}
properties
}
fn build_data(
account_id: &str,
distinct_id: &str,
data_type: DataType,
event_name: &str,
event_id: &str,
stringent: bool,
mut properties: Map<String, Value>,
) -> Result<Data> {
if account_id.is_empty() && distinct_id.is_empty() {
let message =
"invalid parameters: account_id and distinct_id cannot be empty at the same time";
crate::log::td_log_error(message);
return Err(TDError::EmptyIds);
}
let mut data = Data::new(data_type);
data.account_id = account_id.to_string();
data.distinct_id = distinct_id.to_string();
data.event_name = event_name.to_string();
data.event_id = event_id.to_string();
apply_preset_properties(&mut data, &mut properties);
data.properties = properties;
format_properties(&mut data, stringent)?;
Ok(data)
}
fn validate_unset_keys(keys: &[impl AsRef<str>]) -> Result<()> {
if keys.is_empty() {
crate::log::td_log_info("invalid params for UserUnset: keys is nil");
return Err(TDError::EmptyUnsetKeys);
}
Ok(())
}
#[cfg(feature = "blocking")]
#[derive(Clone)]
pub struct TDAnalytics {
consumer: Arc<dyn Consumer>,
super_properties: Arc<SuperProperties>,
}
#[cfg(feature = "blocking")]
impl TDAnalytics {
pub fn new(consumer: impl Consumer + 'static) -> Result<Self> {
crate::log::td_log_info("init SDK success");
Ok(Self {
consumer: Arc::new(consumer),
super_properties: Arc::new(SuperProperties::default()),
})
}
pub fn consumer(&self) -> &Arc<dyn Consumer> {
&self.consumer
}
pub fn set_super_properties(&self, properties: impl IntoPropertyMap) -> Result<()> {
self.super_properties.set(properties.into_property_map()?)
}
pub fn super_properties(&self) -> Map<String, Value> {
self.super_properties.get()
}
pub fn clear_super_properties(&self) {
self.super_properties
.static_props
.write()
.expect("ThinkingData super properties poisoned")
.clear();
}
pub fn set_dynamic_super_properties<F, P>(&self, action: F)
where
F: Fn() -> P + Send + Sync + 'static,
P: IntoPropertyMap,
{
let action = Arc::new(move || match action().into_property_map() {
Ok(map) => map,
Err(err) => {
crate::log::td_log_warning(&format!("dynamic super properties ignored: {err}"));
Map::new()
}
});
*self
.super_properties
.dynamic_props
.write()
.expect("ThinkingData super properties poisoned") = Some(action);
}
pub fn dynamic_super_properties(&self) -> Map<String, Value> {
self.super_properties.get_dynamic()
}
pub fn track(
&self,
account_id: &str,
event_name: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.track_with_distinct_id(account_id, "", event_name, properties)
}
pub fn track_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
event_name: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.track_impl(
account_id,
distinct_id,
DataType::Track,
event_name,
"",
properties,
)
}
pub fn track_first(
&self,
account_id: &str,
event_name: &str,
first_check_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.track_first_with_distinct_id(account_id, "", event_name, first_check_id, properties)
}
pub fn track_first_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
event_name: &str,
first_check_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
if first_check_id.is_empty() {
let message = "the 'firstCheckId' must be provided";
crate::log::td_log_info(message);
return Err(TDError::EmptyFirstCheckId);
}
let mut map = properties.into_property_map()?;
map.insert(
"#first_check_id".to_string(),
Value::String(first_check_id.to_string()),
);
self.track_impl(
account_id,
distinct_id,
DataType::Track,
event_name,
"",
map,
)
}
pub fn track_update(
&self,
account_id: &str,
event_name: &str,
event_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.track_update_with_distinct_id(account_id, "", event_name, event_id, properties)
}
pub fn track_update_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
event_name: &str,
event_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.track_impl(
account_id,
distinct_id,
DataType::TrackUpdate,
event_name,
event_id,
properties,
)
}
pub fn track_overwrite(
&self,
account_id: &str,
event_name: &str,
event_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.track_overwrite_with_distinct_id(account_id, "", event_name, event_id, properties)
}
pub fn track_overwrite_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
event_name: &str,
event_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.track_impl(
account_id,
distinct_id,
DataType::TrackOverwrite,
event_name,
event_id,
properties,
)
}
fn track_impl(
&self,
account_id: &str,
distinct_id: &str,
data_type: DataType,
event_name: &str,
event_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
validate_event(data_type, event_name, event_id)?;
let custom = properties.into_property_map()?;
let properties = compose_track_properties(
&self.super_properties.get(),
&self.super_properties.get_dynamic(),
custom,
);
let data = build_data(
account_id,
distinct_id,
data_type,
event_name,
event_id,
self.consumer.is_stringent(),
properties,
)?;
self.consumer.add(&data)
}
pub fn user_set(&self, account_id: &str, properties: impl IntoPropertyMap) -> Result<()> {
self.user_set_with_distinct_id(account_id, "", properties)
}
pub fn user_set_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.user_impl(
account_id,
distinct_id,
DataType::UserSet,
properties.into_property_map()?,
)
}
pub fn user_set_once(&self, account_id: &str, properties: impl IntoPropertyMap) -> Result<()> {
self.user_set_once_with_distinct_id(account_id, "", properties)
}
pub fn user_set_once_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.user_impl(
account_id,
distinct_id,
DataType::UserSetOnce,
properties.into_property_map()?,
)
}
pub fn user_add(&self, account_id: &str, properties: impl IntoPropertyMap) -> Result<()> {
self.user_add_with_distinct_id(account_id, "", properties)
}
pub fn user_add_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.user_impl(
account_id,
distinct_id,
DataType::UserAdd,
properties.into_property_map()?,
)
}
pub fn user_append(&self, account_id: &str, properties: impl IntoPropertyMap) -> Result<()> {
self.user_append_with_distinct_id(account_id, "", properties)
}
pub fn user_append_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.user_impl(
account_id,
distinct_id,
DataType::UserAppend,
properties.into_property_map()?,
)
}
pub fn user_uniq_append(
&self,
account_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.user_uniq_append_with_distinct_id(account_id, "", properties)
}
pub fn user_uniq_append_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.user_impl(
account_id,
distinct_id,
DataType::UserUniqAppend,
properties.into_property_map()?,
)
}
pub fn user_unset<S: AsRef<str>>(&self, account_id: &str, keys: &[S]) -> Result<()> {
self.user_unset_with_distinct_id(account_id, "", keys)
}
pub fn user_unset_with_distinct_id<S: AsRef<str>>(
&self,
account_id: &str,
distinct_id: &str,
keys: &[S],
) -> Result<()> {
validate_unset_keys(keys)?;
let mut properties = Map::new();
for key in keys {
properties.insert(key.as_ref().to_string(), Value::from(0));
}
self.user_impl(account_id, distinct_id, DataType::UserUnset, properties)
}
pub fn user_unset_with_properties(
&self,
account_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.user_unset_with_properties_with_distinct_id(account_id, "", properties)
}
pub fn user_unset_with_properties_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
let mut map = properties.into_property_map()?;
if map.is_empty() {
crate::log::td_log_info("invalid params for UserUnset: properties is nil");
return Err(TDError::EmptyUnsetKeys);
}
for (key, value) in map.iter_mut() {
if !key.starts_with('#') {
*value = Value::from(0);
}
}
self.user_impl(account_id, distinct_id, DataType::UserUnset, map)
}
pub fn user_del(&self, account_id: &str) -> Result<()> {
self.user_del_with_distinct_id(account_id, "")
}
pub fn user_del_with_distinct_id(&self, account_id: &str, distinct_id: &str) -> Result<()> {
self.user_impl(account_id, distinct_id, DataType::UserDel, Map::new())
}
pub fn user_del_with_properties(
&self,
account_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.user_del_with_properties_with_distinct_id(account_id, "", properties)
}
pub fn user_del_with_properties_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.user_impl(
account_id,
distinct_id,
DataType::UserDel,
properties.into_property_map()?,
)
}
fn user_impl(
&self,
account_id: &str,
distinct_id: &str,
data_type: DataType,
properties: Map<String, Value>,
) -> Result<()> {
let data = build_data(
account_id,
distinct_id,
data_type,
"",
"",
self.consumer.is_stringent(),
properties,
)?;
self.consumer.add(&data)
}
pub fn flush(&self) -> Result<()> {
self.consumer.flush()
}
pub fn close(&self) -> Result<()> {
self.consumer.close()
}
}
#[cfg(feature = "async")]
#[derive(Clone)]
pub struct TDAnalyticsAsync {
consumer: Arc<dyn AsyncConsumer>,
super_properties: Arc<SuperProperties>,
}
#[cfg(feature = "async")]
impl TDAnalyticsAsync {
pub fn new(consumer: impl AsyncConsumer + 'static) -> Result<Self> {
crate::log::td_log_info("init SDK success");
Ok(Self {
consumer: Arc::new(consumer),
super_properties: Arc::new(SuperProperties::default()),
})
}
pub fn consumer(&self) -> &Arc<dyn AsyncConsumer> {
&self.consumer
}
pub fn set_super_properties(&self, properties: impl IntoPropertyMap) -> Result<()> {
self.super_properties.set(properties.into_property_map()?)
}
pub fn super_properties(&self) -> Map<String, Value> {
self.super_properties.get()
}
pub fn clear_super_properties(&self) {
self.super_properties
.static_props
.write()
.expect("ThinkingData super properties poisoned")
.clear();
}
pub fn set_dynamic_super_properties<F, P>(&self, action: F)
where
F: Fn() -> P + Send + Sync + 'static,
P: IntoPropertyMap,
{
let action = Arc::new(move || match action().into_property_map() {
Ok(map) => map,
Err(err) => {
crate::log::td_log_warning(&format!("dynamic super properties ignored: {err}"));
Map::new()
}
});
*self
.super_properties
.dynamic_props
.write()
.expect("ThinkingData super properties poisoned") = Some(action);
}
pub fn dynamic_super_properties(&self) -> Map<String, Value> {
self.super_properties.get_dynamic()
}
pub async fn track(
&self,
account_id: &str,
event_name: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.track_with_distinct_id(account_id, "", event_name, properties)
.await
}
pub async fn track_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
event_name: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.track_impl(
account_id,
distinct_id,
DataType::Track,
event_name,
"",
properties,
)
.await
}
pub async fn track_first(
&self,
account_id: &str,
event_name: &str,
first_check_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.track_first_with_distinct_id(account_id, "", event_name, first_check_id, properties)
.await
}
pub async fn track_first_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
event_name: &str,
first_check_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
if first_check_id.is_empty() {
let message = "the 'firstCheckId' must be provided";
crate::log::td_log_info(message);
return Err(TDError::EmptyFirstCheckId);
}
let mut map = properties.into_property_map()?;
map.insert(
"#first_check_id".to_string(),
Value::String(first_check_id.to_string()),
);
self.track_impl(
account_id,
distinct_id,
DataType::Track,
event_name,
"",
map,
)
.await
}
pub async fn track_update(
&self,
account_id: &str,
event_name: &str,
event_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.track_update_with_distinct_id(account_id, "", event_name, event_id, properties)
.await
}
pub async fn track_update_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
event_name: &str,
event_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.track_impl(
account_id,
distinct_id,
DataType::TrackUpdate,
event_name,
event_id,
properties,
)
.await
}
pub async fn track_overwrite(
&self,
account_id: &str,
event_name: &str,
event_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.track_overwrite_with_distinct_id(account_id, "", event_name, event_id, properties)
.await
}
pub async fn track_overwrite_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
event_name: &str,
event_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.track_impl(
account_id,
distinct_id,
DataType::TrackOverwrite,
event_name,
event_id,
properties,
)
.await
}
async fn track_impl(
&self,
account_id: &str,
distinct_id: &str,
data_type: DataType,
event_name: &str,
event_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
validate_event(data_type, event_name, event_id)?;
let custom = properties.into_property_map()?;
let properties = compose_track_properties(
&self.super_properties.get(),
&self.super_properties.get_dynamic(),
custom,
);
let data = build_data(
account_id,
distinct_id,
data_type,
event_name,
event_id,
self.consumer.is_stringent(),
properties,
)?;
self.consumer.add_async(&data).await
}
pub async fn user_set(&self, account_id: &str, properties: impl IntoPropertyMap) -> Result<()> {
self.user_set_with_distinct_id(account_id, "", properties)
.await
}
pub async fn user_set_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.user_impl(
account_id,
distinct_id,
DataType::UserSet,
properties.into_property_map()?,
)
.await
}
pub async fn user_set_once(
&self,
account_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.user_set_once_with_distinct_id(account_id, "", properties)
.await
}
pub async fn user_set_once_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.user_impl(
account_id,
distinct_id,
DataType::UserSetOnce,
properties.into_property_map()?,
)
.await
}
pub async fn user_add(&self, account_id: &str, properties: impl IntoPropertyMap) -> Result<()> {
self.user_add_with_distinct_id(account_id, "", properties)
.await
}
pub async fn user_add_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.user_impl(
account_id,
distinct_id,
DataType::UserAdd,
properties.into_property_map()?,
)
.await
}
pub async fn user_append(
&self,
account_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.user_append_with_distinct_id(account_id, "", properties)
.await
}
pub async fn user_append_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.user_impl(
account_id,
distinct_id,
DataType::UserAppend,
properties.into_property_map()?,
)
.await
}
pub async fn user_uniq_append(
&self,
account_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.user_uniq_append_with_distinct_id(account_id, "", properties)
.await
}
pub async fn user_uniq_append_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.user_impl(
account_id,
distinct_id,
DataType::UserUniqAppend,
properties.into_property_map()?,
)
.await
}
pub async fn user_unset<S: AsRef<str>>(&self, account_id: &str, keys: &[S]) -> Result<()> {
self.user_unset_with_distinct_id(account_id, "", keys).await
}
pub async fn user_unset_with_distinct_id<S: AsRef<str>>(
&self,
account_id: &str,
distinct_id: &str,
keys: &[S],
) -> Result<()> {
validate_unset_keys(keys)?;
let mut properties = Map::new();
for key in keys {
properties.insert(key.as_ref().to_string(), Value::from(0));
}
self.user_impl(account_id, distinct_id, DataType::UserUnset, properties)
.await
}
pub async fn user_unset_with_properties(
&self,
account_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.user_unset_with_properties_with_distinct_id(account_id, "", properties)
.await
}
pub async fn user_unset_with_properties_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
let mut map = properties.into_property_map()?;
if map.is_empty() {
crate::log::td_log_info("invalid params for UserUnset: properties is nil");
return Err(TDError::EmptyUnsetKeys);
}
for (key, value) in map.iter_mut() {
if !key.starts_with('#') {
*value = Value::from(0);
}
}
self.user_impl(account_id, distinct_id, DataType::UserUnset, map)
.await
}
pub async fn user_del(&self, account_id: &str) -> Result<()> {
self.user_del_with_distinct_id(account_id, "").await
}
pub async fn user_del_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
) -> Result<()> {
self.user_impl(account_id, distinct_id, DataType::UserDel, Map::new())
.await
}
pub async fn user_del_with_properties(
&self,
account_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.user_del_with_properties_with_distinct_id(account_id, "", properties)
.await
}
pub async fn user_del_with_properties_with_distinct_id(
&self,
account_id: &str,
distinct_id: &str,
properties: impl IntoPropertyMap,
) -> Result<()> {
self.user_impl(
account_id,
distinct_id,
DataType::UserDel,
properties.into_property_map()?,
)
.await
}
async fn user_impl(
&self,
account_id: &str,
distinct_id: &str,
data_type: DataType,
properties: Map<String, Value>,
) -> Result<()> {
let data = build_data(
account_id,
distinct_id,
data_type,
"",
"",
self.consumer.is_stringent(),
properties,
)?;
self.consumer.add_async(&data).await
}
pub async fn flush(&self) -> Result<()> {
self.consumer.flush_async().await
}
pub async fn close(&self) -> Result<()> {
self.consumer.close_async().await
}
}