Skip to main content

thinkingdata_core/
analytics.rs

1// Copyright 2026 houseme
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The analytics facades: [`TDAnalytics`] (blocking) and [`TDAnalyticsAsync`]
16//! (async).
17//!
18//! Both facades share one implementation strategy: they validate inputs,
19//! merge super properties, hoist preset keys (`#ip`, `#uuid`, `#time`, …)
20//! into the wire format and hand the finished [`Data`] snapshot to the
21//! injected consumer. Only the delivery call differs (`add` vs
22//! `add_async`).
23//!
24//! ```
25//! # #[cfg(feature = "blocking")]
26//! # fn main() -> Result<(), thinkingdata_core::TDError> {
27//! # use thinkingdata_core::{TDAnalytics, consumer::LogConsumer};
28//!
29//! # let dir = std::env::temp_dir().join("thinkingdata-core-doctest-analytics");
30//! # let dir = std::env::temp_dir().join("thinkingdata-core-doctest-analytics");
31//! # let consumer = LogConsumer::new(dir.to_str().unwrap())?;
32//! # let ta = TDAnalytics::new(consumer)?;
33//!
34//! # // Super properties are applied to every subsequent event…
35//! # ta.set_super_properties(serde_json::json!({ "channel": "rust" }))?;
36//!
37//! # ta.track("account_id_123", "purchase", serde_json::json!({ "price": 99.0 }))?;
38//! # ta.user_set("account_id_123", serde_json::json!({ "vip": true }))?;
39//!
40//! # ta.close()?;
41//! # Ok(())
42//! # }
43//! ```
44
45use std::sync::{Arc, RwLock};
46
47use serde_json::{Map, Value};
48
49use crate::SDK_VERSION;
50use crate::data::{
51    Data, DataType, IntoPropertyMap, LIB_NAME, apply_preset_properties, format_properties,
52};
53use crate::error::{Result, TDError};
54use crate::utils::is_valid_key;
55
56#[cfg(feature = "async")]
57use crate::consumer::AsyncConsumer;
58#[cfg(feature = "blocking")]
59use crate::consumer::Consumer;
60
61/// A function producing dynamic super properties, evaluated once per event
62/// outside of any lock.
63type DynamicSuperProperties = Arc<dyn Fn() -> Map<String, Value> + Send + Sync>;
64
65/// Shared super-property state used by both facades.
66#[derive(Default)]
67struct SuperProperties {
68    static_props: RwLock<Map<String, Value>>,
69    dynamic_props: RwLock<Option<DynamicSuperProperties>>,
70}
71
72impl SuperProperties {
73    /// Snapshot of the static super properties.
74    fn get(&self) -> Map<String, Value> {
75        self.static_props
76            .read()
77            .expect("ThinkingData super properties poisoned")
78            .clone()
79    }
80
81    /// Snapshot of the dynamic super properties; the user callback is invoked
82    /// outside of the lock so it may reenter the SDK.
83    fn get_dynamic(&self) -> Map<String, Value> {
84        let action = self
85            .dynamic_props
86            .read()
87            .expect("ThinkingData super properties poisoned")
88            .clone();
89        if let Some(action) = action {
90            action()
91        } else {
92            Map::new()
93        }
94    }
95
96    /// Validate and merge static super properties.
97    fn set(&self, properties: Map<String, Value>) -> Result<()> {
98        for key in properties.keys() {
99            if !is_valid_key(key) {
100                return Err(TDError::InvalidPropertyKey(key.clone()));
101            }
102        }
103        let mut guard = self
104            .static_props
105            .write()
106            .expect("ThinkingData super properties poisoned");
107        for (key, value) in properties {
108            guard.insert(key, value);
109        }
110        Ok(())
111    }
112}
113
114/// Validate event parameters shared by every `track*` operation.
115fn validate_event(data_type: DataType, event_name: &str, event_id: &str) -> Result<()> {
116    if event_name.is_empty() {
117        crate::log::td_log_error("the event name must be provided");
118        return Err(TDError::EmptyEventName);
119    }
120    // eventId must not be null unless the type is plain `track`.
121    if event_id.is_empty() && data_type != DataType::Track {
122        crate::log::td_log_error("the event id must be provided");
123        return Err(TDError::EmptyEventId);
124    }
125    Ok(())
126}
127
128/// Compose the property map of a track event, in the Go SDK's precedence
129/// order: super properties < dynamic super properties < preset `#lib` fields
130/// < custom properties.
131fn compose_track_properties(
132    super_properties: &Map<String, Value>,
133    dynamic: &Map<String, Value>,
134    custom: Map<String, Value>,
135) -> Map<String, Value> {
136    let mut properties = super_properties.clone();
137    for (key, value) in dynamic {
138        properties.insert(key.clone(), value.clone());
139    }
140    properties.insert("#lib".to_string(), Value::String(LIB_NAME.to_string()));
141    properties.insert(
142        "#lib_version".to_string(),
143        Value::String(SDK_VERSION.to_string()),
144    );
145    for (key, value) in custom {
146        properties.insert(key, value);
147    }
148    properties
149}
150
151/// Build the final [`Data`] snapshot: hoist preset keys out of `properties`
152/// and validate names/keys/values according to the consumer's stringency.
153fn build_data(
154    account_id: &str,
155    distinct_id: &str,
156    data_type: DataType,
157    event_name: &str,
158    event_id: &str,
159    stringent: bool,
160    mut properties: Map<String, Value>,
161) -> Result<Data> {
162    if account_id.is_empty() && distinct_id.is_empty() {
163        let message =
164            "invalid parameters: account_id and distinct_id cannot be empty at the same time";
165        crate::log::td_log_error(message);
166        return Err(TDError::EmptyIds);
167    }
168
169    let mut data = Data::new(data_type);
170    data.account_id = account_id.to_string();
171    data.distinct_id = distinct_id.to_string();
172    data.event_name = event_name.to_string();
173    data.event_id = event_id.to_string();
174    apply_preset_properties(&mut data, &mut properties);
175    data.properties = properties;
176    format_properties(&mut data, stringent)?;
177    Ok(data)
178}
179
180/// Reject `user_unset` calls without keys.
181fn validate_unset_keys(keys: &[impl AsRef<str>]) -> Result<()> {
182    if keys.is_empty() {
183        crate::log::td_log_info("invalid params for UserUnset: keys is nil");
184        return Err(TDError::EmptyUnsetKeys);
185    }
186    Ok(())
187}
188
189// ---------------------------------------------------------------------------
190// Blocking facade
191// ---------------------------------------------------------------------------
192
193/// The blocking analytics facade of the SDK, ported from the Go SDK's
194/// `TDAnalytics`.
195///
196/// It is cheap to clone; every clone shares the same consumer and super
197/// property state. See the [crate documentation](crate) for a quick start.
198#[cfg(feature = "blocking")]
199#[derive(Clone)]
200pub struct TDAnalytics {
201    consumer: Arc<dyn Consumer>,
202    super_properties: Arc<SuperProperties>,
203}
204
205#[cfg(feature = "blocking")]
206impl TDAnalytics {
207    /// Create an analytics instance delegating delivery to `consumer`.
208    pub fn new(consumer: impl Consumer + 'static) -> Result<Self> {
209        crate::log::td_log_info("init SDK success");
210        Ok(Self {
211            consumer: Arc::new(consumer),
212            super_properties: Arc::new(SuperProperties::default()),
213        })
214    }
215
216    /// The injected consumer.
217    pub fn consumer(&self) -> &Arc<dyn Consumer> {
218        &self.consumer
219    }
220
221    /// Set common properties applied to every subsequent `track*` event.
222    ///
223    /// Keys are validated against the key pattern; an invalid key returns an
224    /// error instead of silently corrupting the stream.
225    pub fn set_super_properties(&self, properties: impl IntoPropertyMap) -> Result<()> {
226        self.super_properties.set(properties.into_property_map()?)
227    }
228
229    /// Snapshot of the currently registered super properties.
230    pub fn super_properties(&self) -> Map<String, Value> {
231        self.super_properties.get()
232    }
233
234    /// Remove every registered super property.
235    pub fn clear_super_properties(&self) {
236        self.super_properties
237            .static_props
238            .write()
239            .expect("ThinkingData super properties poisoned")
240            .clear();
241    }
242
243    /// Register a callback producing dynamic common properties. It is
244    /// evaluated once per event, outside of any lock; avoid heavy work in it.
245    pub fn set_dynamic_super_properties<F, P>(&self, action: F)
246    where
247        F: Fn() -> P + Send + Sync + 'static,
248        P: IntoPropertyMap,
249    {
250        let action = Arc::new(move || action().into_property_map().unwrap_or_default());
251        *self
252            .super_properties
253            .dynamic_props
254            .write()
255            .expect("ThinkingData super properties poisoned") = Some(action);
256    }
257
258    /// Snapshot of the dynamic super properties.
259    pub fn dynamic_super_properties(&self) -> Map<String, Value> {
260        self.super_properties.get_dynamic()
261    }
262
263    /// Report an ordinary event attributed to `account_id`.
264    pub fn track(
265        &self,
266        account_id: &str,
267        event_name: &str,
268        properties: impl IntoPropertyMap,
269    ) -> Result<()> {
270        self.track_with_distinct_id(account_id, "", event_name, properties)
271    }
272
273    /// Report an ordinary event with explicit account and distinct IDs.
274    pub fn track_with_distinct_id(
275        &self,
276        account_id: &str,
277        distinct_id: &str,
278        event_name: &str,
279        properties: impl IntoPropertyMap,
280    ) -> Result<()> {
281        self.track_impl(
282            account_id,
283            distinct_id,
284            DataType::Track,
285            event_name,
286            "",
287            properties,
288        )
289    }
290
291    /// Report a first-check event; `first_check_id` deduplicates it.
292    pub fn track_first(
293        &self,
294        account_id: &str,
295        event_name: &str,
296        first_check_id: &str,
297        properties: impl IntoPropertyMap,
298    ) -> Result<()> {
299        self.track_first_with_distinct_id(account_id, "", event_name, first_check_id, properties)
300    }
301
302    /// Report a first-check event with explicit account and distinct IDs.
303    pub fn track_first_with_distinct_id(
304        &self,
305        account_id: &str,
306        distinct_id: &str,
307        event_name: &str,
308        first_check_id: &str,
309        properties: impl IntoPropertyMap,
310    ) -> Result<()> {
311        if first_check_id.is_empty() {
312            let message = "the 'firstCheckId' must be provided";
313            crate::log::td_log_info(message);
314            return Err(TDError::EmptyFirstCheckId);
315        }
316        let mut map = properties.into_property_map()?;
317        map.insert(
318            "#first_check_id".to_string(),
319            Value::String(first_check_id.to_string()),
320        );
321        self.track_impl(
322            account_id,
323            distinct_id,
324            DataType::Track,
325            event_name,
326            "",
327            map,
328        )
329    }
330
331    /// Report an updatable event identified by `event_id`.
332    pub fn track_update(
333        &self,
334        account_id: &str,
335        event_name: &str,
336        event_id: &str,
337        properties: impl IntoPropertyMap,
338    ) -> Result<()> {
339        self.track_update_with_distinct_id(account_id, "", event_name, event_id, properties)
340    }
341
342    /// Report an updatable event with explicit account and distinct IDs.
343    pub fn track_update_with_distinct_id(
344        &self,
345        account_id: &str,
346        distinct_id: &str,
347        event_name: &str,
348        event_id: &str,
349        properties: impl IntoPropertyMap,
350    ) -> Result<()> {
351        self.track_impl(
352            account_id,
353            distinct_id,
354            DataType::TrackUpdate,
355            event_name,
356            event_id,
357            properties,
358        )
359    }
360
361    /// Report an overridable event identified by `event_id`.
362    pub fn track_overwrite(
363        &self,
364        account_id: &str,
365        event_name: &str,
366        event_id: &str,
367        properties: impl IntoPropertyMap,
368    ) -> Result<()> {
369        self.track_overwrite_with_distinct_id(account_id, "", event_name, event_id, properties)
370    }
371
372    /// Report an overridable event with explicit account and distinct IDs.
373    pub fn track_overwrite_with_distinct_id(
374        &self,
375        account_id: &str,
376        distinct_id: &str,
377        event_name: &str,
378        event_id: &str,
379        properties: impl IntoPropertyMap,
380    ) -> Result<()> {
381        self.track_impl(
382            account_id,
383            distinct_id,
384            DataType::TrackOverwrite,
385            event_name,
386            event_id,
387            properties,
388        )
389    }
390
391    fn track_impl(
392        &self,
393        account_id: &str,
394        distinct_id: &str,
395        data_type: DataType,
396        event_name: &str,
397        event_id: &str,
398        properties: impl IntoPropertyMap,
399    ) -> Result<()> {
400        validate_event(data_type, event_name, event_id)?;
401        let custom = properties.into_property_map()?;
402        let properties = compose_track_properties(
403            &self.super_properties.get(),
404            &self.super_properties.get_dynamic(),
405            custom,
406        );
407        let data = build_data(
408            account_id,
409            distinct_id,
410            data_type,
411            event_name,
412            event_id,
413            self.consumer.is_stringent(),
414            properties,
415        )?;
416        self.consumer.add(&data)
417    }
418
419    /// Set user properties, overwriting existing values.
420    pub fn user_set(&self, account_id: &str, properties: impl IntoPropertyMap) -> Result<()> {
421        self.user_set_with_distinct_id(account_id, "", properties)
422    }
423
424    /// Set user properties with explicit account and distinct IDs.
425    pub fn user_set_with_distinct_id(
426        &self,
427        account_id: &str,
428        distinct_id: &str,
429        properties: impl IntoPropertyMap,
430    ) -> Result<()> {
431        self.user_impl(
432            account_id,
433            distinct_id,
434            DataType::UserSet,
435            properties.into_property_map()?,
436        )
437    }
438
439    /// Set user properties only where they were not set before.
440    pub fn user_set_once(&self, account_id: &str, properties: impl IntoPropertyMap) -> Result<()> {
441        self.user_set_once_with_distinct_id(account_id, "", properties)
442    }
443
444    /// `user_set_once` with explicit account and distinct IDs.
445    pub fn user_set_once_with_distinct_id(
446        &self,
447        account_id: &str,
448        distinct_id: &str,
449        properties: impl IntoPropertyMap,
450    ) -> Result<()> {
451        self.user_impl(
452            account_id,
453            distinct_id,
454            DataType::UserSetOnce,
455            properties.into_property_map()?,
456        )
457    }
458
459    /// Accumulate numeric user properties.
460    pub fn user_add(&self, account_id: &str, properties: impl IntoPropertyMap) -> Result<()> {
461        self.user_add_with_distinct_id(account_id, "", properties)
462    }
463
464    /// `user_add` with explicit account and distinct IDs.
465    pub fn user_add_with_distinct_id(
466        &self,
467        account_id: &str,
468        distinct_id: &str,
469        properties: impl IntoPropertyMap,
470    ) -> Result<()> {
471        self.user_impl(
472            account_id,
473            distinct_id,
474            DataType::UserAdd,
475            properties.into_property_map()?,
476        )
477    }
478
479    /// Append values to array-typed user properties.
480    pub fn user_append(&self, account_id: &str, properties: impl IntoPropertyMap) -> Result<()> {
481        self.user_append_with_distinct_id(account_id, "", properties)
482    }
483
484    /// `user_append` with explicit account and distinct IDs.
485    pub fn user_append_with_distinct_id(
486        &self,
487        account_id: &str,
488        distinct_id: &str,
489        properties: impl IntoPropertyMap,
490    ) -> Result<()> {
491        self.user_impl(
492            account_id,
493            distinct_id,
494            DataType::UserAppend,
495            properties.into_property_map()?,
496        )
497    }
498
499    /// Append unique values to array-typed user properties.
500    pub fn user_uniq_append(
501        &self,
502        account_id: &str,
503        properties: impl IntoPropertyMap,
504    ) -> Result<()> {
505        self.user_uniq_append_with_distinct_id(account_id, "", properties)
506    }
507
508    /// `user_uniq_append` with explicit account and distinct IDs.
509    pub fn user_uniq_append_with_distinct_id(
510        &self,
511        account_id: &str,
512        distinct_id: &str,
513        properties: impl IntoPropertyMap,
514    ) -> Result<()> {
515        self.user_impl(
516            account_id,
517            distinct_id,
518            DataType::UserUniqAppend,
519            properties.into_property_map()?,
520        )
521    }
522
523    /// Clear the listed user properties.
524    pub fn user_unset<S: AsRef<str>>(&self, account_id: &str, keys: &[S]) -> Result<()> {
525        self.user_unset_with_distinct_id(account_id, "", keys)
526    }
527
528    /// Clear the listed user properties with explicit account and distinct IDs.
529    pub fn user_unset_with_distinct_id<S: AsRef<str>>(
530        &self,
531        account_id: &str,
532        distinct_id: &str,
533        keys: &[S],
534    ) -> Result<()> {
535        validate_unset_keys(keys)?;
536        let mut properties = Map::new();
537        for key in keys {
538            properties.insert(key.as_ref().to_string(), Value::from(0));
539        }
540        self.user_impl(account_id, distinct_id, DataType::UserUnset, properties)
541    }
542
543    /// Clear user properties using a property map (values are ignored by the
544    /// receiver, but preset keys keep their values, matching the Lua SDK).
545    pub fn user_unset_with_properties(
546        &self,
547        account_id: &str,
548        properties: impl IntoPropertyMap,
549    ) -> Result<()> {
550        self.user_unset_with_properties_with_distinct_id(account_id, "", properties)
551    }
552
553    /// `user_unset_with_properties` with explicit account and distinct IDs.
554    pub fn user_unset_with_properties_with_distinct_id(
555        &self,
556        account_id: &str,
557        distinct_id: &str,
558        properties: impl IntoPropertyMap,
559    ) -> Result<()> {
560        let mut map = properties.into_property_map()?;
561        if map.is_empty() {
562            crate::log::td_log_info("invalid params for UserUnset: properties is nil");
563            return Err(TDError::EmptyUnsetKeys);
564        }
565        for (key, value) in map.iter_mut() {
566            if !key.starts_with('#') {
567                *value = Value::from(0);
568            }
569        }
570        self.user_impl(account_id, distinct_id, DataType::UserUnset, map)
571    }
572
573    /// Delete the user; this operation cannot be undone.
574    pub fn user_del(&self, account_id: &str) -> Result<()> {
575        self.user_del_with_distinct_id(account_id, "")
576    }
577
578    /// Delete the user with explicit account and distinct IDs.
579    pub fn user_del_with_distinct_id(&self, account_id: &str, distinct_id: &str) -> Result<()> {
580        self.user_impl(account_id, distinct_id, DataType::UserDel, Map::new())
581    }
582
583    /// Delete the user together with final property values.
584    pub fn user_del_with_properties(
585        &self,
586        account_id: &str,
587        properties: impl IntoPropertyMap,
588    ) -> Result<()> {
589        self.user_del_with_properties_with_distinct_id(account_id, "", properties)
590    }
591
592    /// `user_del_with_properties` with explicit account and distinct IDs.
593    pub fn user_del_with_properties_with_distinct_id(
594        &self,
595        account_id: &str,
596        distinct_id: &str,
597        properties: impl IntoPropertyMap,
598    ) -> Result<()> {
599        self.user_impl(
600            account_id,
601            distinct_id,
602            DataType::UserDel,
603            properties.into_property_map()?,
604        )
605    }
606
607    fn user_impl(
608        &self,
609        account_id: &str,
610        distinct_id: &str,
611        data_type: DataType,
612        properties: Map<String, Value>,
613    ) -> Result<()> {
614        let data = build_data(
615            account_id,
616            distinct_id,
617            data_type,
618            "",
619            "",
620            self.consumer.is_stringent(),
621            properties,
622        )?;
623        self.consumer.add(&data)
624    }
625
626    /// Deliver everything currently buffered by the consumer.
627    pub fn flush(&self) -> Result<()> {
628        self.consumer.flush()
629    }
630
631    /// Flush and shut the consumer down.
632    pub fn close(&self) -> Result<()> {
633        self.consumer.close()
634    }
635}
636
637// ---------------------------------------------------------------------------
638// Async facade
639// ---------------------------------------------------------------------------
640
641/// The asynchronous analytics facade, mirroring [`TDAnalytics`] with async
642/// methods over the [`AsyncConsumer`] trait. Available with the `async`
643/// feature.
644///
645/// ```
646/// # #[cfg(feature = "async")]
647/// # async fn demo() -> Result<(), thinkingdata_core::TDError> {
648/// # use thinkingdata_core::{TDAnalyticsAsync, consumer::BatchConsumer};
649///
650/// # let consumer = BatchConsumer::new("https://receiver.thinkingdata.io", "your_app_id")?;
651/// # let ta = TDAnalyticsAsync::new(consumer)?;
652///
653/// # ta.set_super_properties(serde_json::json!({ "channel": "rust" }))?;
654/// # ta.track("account_id_123", "purchase", serde_json::json!({ "price": 99.0 })).await?;
655/// # ta.close().await?;
656/// # Ok(())
657/// # }
658/// ```
659#[cfg(feature = "async")]
660#[derive(Clone)]
661pub struct TDAnalyticsAsync {
662    consumer: Arc<dyn AsyncConsumer>,
663    super_properties: Arc<SuperProperties>,
664}
665
666#[cfg(feature = "async")]
667impl TDAnalyticsAsync {
668    /// Create an analytics instance delegating delivery to `consumer`.
669    pub fn new(consumer: impl AsyncConsumer + 'static) -> Result<Self> {
670        crate::log::td_log_info("init SDK success");
671        Ok(Self {
672            consumer: Arc::new(consumer),
673            super_properties: Arc::new(SuperProperties::default()),
674        })
675    }
676
677    /// The injected consumer.
678    pub fn consumer(&self) -> &Arc<dyn AsyncConsumer> {
679        &self.consumer
680    }
681
682    /// Set common properties applied to every subsequent `track*` event.
683    pub fn set_super_properties(&self, properties: impl IntoPropertyMap) -> Result<()> {
684        self.super_properties.set(properties.into_property_map()?)
685    }
686
687    /// Snapshot of the currently registered super properties.
688    pub fn super_properties(&self) -> Map<String, Value> {
689        self.super_properties.get()
690    }
691
692    /// Remove every registered super property.
693    pub fn clear_super_properties(&self) {
694        self.super_properties
695            .static_props
696            .write()
697            .expect("ThinkingData super properties poisoned")
698            .clear();
699    }
700
701    /// Register a callback producing dynamic common properties. It is
702    /// evaluated once per event, outside of any lock; avoid heavy work in it.
703    pub fn set_dynamic_super_properties<F, P>(&self, action: F)
704    where
705        F: Fn() -> P + Send + Sync + 'static,
706        P: IntoPropertyMap,
707    {
708        let action = Arc::new(move || action().into_property_map().unwrap_or_default());
709        *self
710            .super_properties
711            .dynamic_props
712            .write()
713            .expect("ThinkingData super properties poisoned") = Some(action);
714    }
715
716    /// Snapshot of the dynamic super properties.
717    pub fn dynamic_super_properties(&self) -> Map<String, Value> {
718        self.super_properties.get_dynamic()
719    }
720
721    /// Report an ordinary event attributed to `account_id`.
722    pub async fn track(
723        &self,
724        account_id: &str,
725        event_name: &str,
726        properties: impl IntoPropertyMap,
727    ) -> Result<()> {
728        self.track_with_distinct_id(account_id, "", event_name, properties)
729            .await
730    }
731
732    /// Report an ordinary event with explicit account and distinct IDs.
733    pub async fn track_with_distinct_id(
734        &self,
735        account_id: &str,
736        distinct_id: &str,
737        event_name: &str,
738        properties: impl IntoPropertyMap,
739    ) -> Result<()> {
740        self.track_impl(
741            account_id,
742            distinct_id,
743            DataType::Track,
744            event_name,
745            "",
746            properties,
747        )
748        .await
749    }
750
751    /// Report a first-check event; `first_check_id` deduplicates it.
752    pub async fn track_first(
753        &self,
754        account_id: &str,
755        event_name: &str,
756        first_check_id: &str,
757        properties: impl IntoPropertyMap,
758    ) -> Result<()> {
759        self.track_first_with_distinct_id(account_id, "", event_name, first_check_id, properties)
760            .await
761    }
762
763    /// Report a first-check event with explicit account and distinct IDs.
764    pub async fn track_first_with_distinct_id(
765        &self,
766        account_id: &str,
767        distinct_id: &str,
768        event_name: &str,
769        first_check_id: &str,
770        properties: impl IntoPropertyMap,
771    ) -> Result<()> {
772        if first_check_id.is_empty() {
773            let message = "the 'firstCheckId' must be provided";
774            crate::log::td_log_info(message);
775            return Err(TDError::EmptyFirstCheckId);
776        }
777        let mut map = properties.into_property_map()?;
778        map.insert(
779            "#first_check_id".to_string(),
780            Value::String(first_check_id.to_string()),
781        );
782        self.track_impl(
783            account_id,
784            distinct_id,
785            DataType::Track,
786            event_name,
787            "",
788            map,
789        )
790        .await
791    }
792
793    /// Report an updatable event identified by `event_id`.
794    pub async fn track_update(
795        &self,
796        account_id: &str,
797        event_name: &str,
798        event_id: &str,
799        properties: impl IntoPropertyMap,
800    ) -> Result<()> {
801        self.track_update_with_distinct_id(account_id, "", event_name, event_id, properties)
802            .await
803    }
804
805    /// Report an updatable event with explicit account and distinct IDs.
806    pub async fn track_update_with_distinct_id(
807        &self,
808        account_id: &str,
809        distinct_id: &str,
810        event_name: &str,
811        event_id: &str,
812        properties: impl IntoPropertyMap,
813    ) -> Result<()> {
814        self.track_impl(
815            account_id,
816            distinct_id,
817            DataType::TrackUpdate,
818            event_name,
819            event_id,
820            properties,
821        )
822        .await
823    }
824
825    /// Report an overridable event identified by `event_id`.
826    pub async fn track_overwrite(
827        &self,
828        account_id: &str,
829        event_name: &str,
830        event_id: &str,
831        properties: impl IntoPropertyMap,
832    ) -> Result<()> {
833        self.track_overwrite_with_distinct_id(account_id, "", event_name, event_id, properties)
834            .await
835    }
836
837    /// Report an overridable event with explicit account and distinct IDs.
838    pub async fn track_overwrite_with_distinct_id(
839        &self,
840        account_id: &str,
841        distinct_id: &str,
842        event_name: &str,
843        event_id: &str,
844        properties: impl IntoPropertyMap,
845    ) -> Result<()> {
846        self.track_impl(
847            account_id,
848            distinct_id,
849            DataType::TrackOverwrite,
850            event_name,
851            event_id,
852            properties,
853        )
854        .await
855    }
856
857    async fn track_impl(
858        &self,
859        account_id: &str,
860        distinct_id: &str,
861        data_type: DataType,
862        event_name: &str,
863        event_id: &str,
864        properties: impl IntoPropertyMap,
865    ) -> Result<()> {
866        validate_event(data_type, event_name, event_id)?;
867        let custom = properties.into_property_map()?;
868        let properties = compose_track_properties(
869            &self.super_properties.get(),
870            &self.super_properties.get_dynamic(),
871            custom,
872        );
873        let data = build_data(
874            account_id,
875            distinct_id,
876            data_type,
877            event_name,
878            event_id,
879            self.consumer.is_stringent(),
880            properties,
881        )?;
882        self.consumer.add_async(&data).await
883    }
884
885    /// Set user properties, overwriting existing values.
886    pub async fn user_set(&self, account_id: &str, properties: impl IntoPropertyMap) -> Result<()> {
887        self.user_set_with_distinct_id(account_id, "", properties)
888            .await
889    }
890
891    /// Set user properties with explicit account and distinct IDs.
892    pub async fn user_set_with_distinct_id(
893        &self,
894        account_id: &str,
895        distinct_id: &str,
896        properties: impl IntoPropertyMap,
897    ) -> Result<()> {
898        self.user_impl(
899            account_id,
900            distinct_id,
901            DataType::UserSet,
902            properties.into_property_map()?,
903        )
904        .await
905    }
906
907    /// Set user properties only where they were not set before.
908    pub async fn user_set_once(
909        &self,
910        account_id: &str,
911        properties: impl IntoPropertyMap,
912    ) -> Result<()> {
913        self.user_set_once_with_distinct_id(account_id, "", properties)
914            .await
915    }
916
917    /// `user_set_once` with explicit account and distinct IDs.
918    pub async fn user_set_once_with_distinct_id(
919        &self,
920        account_id: &str,
921        distinct_id: &str,
922        properties: impl IntoPropertyMap,
923    ) -> Result<()> {
924        self.user_impl(
925            account_id,
926            distinct_id,
927            DataType::UserSetOnce,
928            properties.into_property_map()?,
929        )
930        .await
931    }
932
933    /// Accumulate numeric user properties.
934    pub async fn user_add(&self, account_id: &str, properties: impl IntoPropertyMap) -> Result<()> {
935        self.user_add_with_distinct_id(account_id, "", properties)
936            .await
937    }
938
939    /// `user_add` with explicit account and distinct IDs.
940    pub async fn user_add_with_distinct_id(
941        &self,
942        account_id: &str,
943        distinct_id: &str,
944        properties: impl IntoPropertyMap,
945    ) -> Result<()> {
946        self.user_impl(
947            account_id,
948            distinct_id,
949            DataType::UserAdd,
950            properties.into_property_map()?,
951        )
952        .await
953    }
954
955    /// Append values to array-typed user properties.
956    pub async fn user_append(
957        &self,
958        account_id: &str,
959        properties: impl IntoPropertyMap,
960    ) -> Result<()> {
961        self.user_append_with_distinct_id(account_id, "", properties)
962            .await
963    }
964
965    /// `user_append` with explicit account and distinct IDs.
966    pub async fn user_append_with_distinct_id(
967        &self,
968        account_id: &str,
969        distinct_id: &str,
970        properties: impl IntoPropertyMap,
971    ) -> Result<()> {
972        self.user_impl(
973            account_id,
974            distinct_id,
975            DataType::UserAppend,
976            properties.into_property_map()?,
977        )
978        .await
979    }
980
981    /// Append unique values to array-typed user properties.
982    pub async fn user_uniq_append(
983        &self,
984        account_id: &str,
985        properties: impl IntoPropertyMap,
986    ) -> Result<()> {
987        self.user_uniq_append_with_distinct_id(account_id, "", properties)
988            .await
989    }
990
991    /// `user_uniq_append` with explicit account and distinct IDs.
992    pub async fn user_uniq_append_with_distinct_id(
993        &self,
994        account_id: &str,
995        distinct_id: &str,
996        properties: impl IntoPropertyMap,
997    ) -> Result<()> {
998        self.user_impl(
999            account_id,
1000            distinct_id,
1001            DataType::UserUniqAppend,
1002            properties.into_property_map()?,
1003        )
1004        .await
1005    }
1006
1007    /// Clear the listed user properties.
1008    pub async fn user_unset<S: AsRef<str>>(&self, account_id: &str, keys: &[S]) -> Result<()> {
1009        self.user_unset_with_distinct_id(account_id, "", keys).await
1010    }
1011
1012    /// Clear the listed user properties with explicit account and distinct IDs.
1013    pub async fn user_unset_with_distinct_id<S: AsRef<str>>(
1014        &self,
1015        account_id: &str,
1016        distinct_id: &str,
1017        keys: &[S],
1018    ) -> Result<()> {
1019        validate_unset_keys(keys)?;
1020        let mut properties = Map::new();
1021        for key in keys {
1022            properties.insert(key.as_ref().to_string(), Value::from(0));
1023        }
1024        self.user_impl(account_id, distinct_id, DataType::UserUnset, properties)
1025            .await
1026    }
1027
1028    /// Clear user properties using a property map (values are ignored by the
1029    /// receiver, but preset keys keep their values, matching the Lua SDK).
1030    pub async fn user_unset_with_properties(
1031        &self,
1032        account_id: &str,
1033        properties: impl IntoPropertyMap,
1034    ) -> Result<()> {
1035        self.user_unset_with_properties_with_distinct_id(account_id, "", properties)
1036            .await
1037    }
1038
1039    /// `user_unset_with_properties` with explicit account and distinct IDs.
1040    pub async fn user_unset_with_properties_with_distinct_id(
1041        &self,
1042        account_id: &str,
1043        distinct_id: &str,
1044        properties: impl IntoPropertyMap,
1045    ) -> Result<()> {
1046        let mut map = properties.into_property_map()?;
1047        if map.is_empty() {
1048            crate::log::td_log_info("invalid params for UserUnset: properties is nil");
1049            return Err(TDError::EmptyUnsetKeys);
1050        }
1051        for (key, value) in map.iter_mut() {
1052            if !key.starts_with('#') {
1053                *value = Value::from(0);
1054            }
1055        }
1056        self.user_impl(account_id, distinct_id, DataType::UserUnset, map)
1057            .await
1058    }
1059
1060    /// Delete the user; this operation cannot be undone.
1061    pub async fn user_del(&self, account_id: &str) -> Result<()> {
1062        self.user_del_with_distinct_id(account_id, "").await
1063    }
1064
1065    /// Delete the user with explicit account and distinct IDs.
1066    pub async fn user_del_with_distinct_id(
1067        &self,
1068        account_id: &str,
1069        distinct_id: &str,
1070    ) -> Result<()> {
1071        self.user_impl(account_id, distinct_id, DataType::UserDel, Map::new())
1072            .await
1073    }
1074
1075    /// Delete the user together with final property values.
1076    pub async fn user_del_with_properties(
1077        &self,
1078        account_id: &str,
1079        properties: impl IntoPropertyMap,
1080    ) -> Result<()> {
1081        self.user_del_with_properties_with_distinct_id(account_id, "", properties)
1082            .await
1083    }
1084
1085    /// `user_del_with_properties` with explicit account and distinct IDs.
1086    pub async fn user_del_with_properties_with_distinct_id(
1087        &self,
1088        account_id: &str,
1089        distinct_id: &str,
1090        properties: impl IntoPropertyMap,
1091    ) -> Result<()> {
1092        self.user_impl(
1093            account_id,
1094            distinct_id,
1095            DataType::UserDel,
1096            properties.into_property_map()?,
1097        )
1098        .await
1099    }
1100
1101    async fn user_impl(
1102        &self,
1103        account_id: &str,
1104        distinct_id: &str,
1105        data_type: DataType,
1106        properties: Map<String, Value>,
1107    ) -> Result<()> {
1108        let data = build_data(
1109            account_id,
1110            distinct_id,
1111            data_type,
1112            "",
1113            "",
1114            self.consumer.is_stringent(),
1115            properties,
1116        )?;
1117        self.consumer.add_async(&data).await
1118    }
1119
1120    /// Deliver everything currently buffered by the consumer.
1121    pub async fn flush(&self) -> Result<()> {
1122        self.consumer.flush_async().await
1123    }
1124
1125    /// Flush and shut the consumer down.
1126    pub async fn close(&self) -> Result<()> {
1127        self.consumer.close_async().await
1128    }
1129}