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 || match action().into_property_map() {
251            Ok(map) => map,
252            Err(err) => {
253                crate::log::td_log_warning(&format!("dynamic super properties ignored: {err}"));
254                Map::new()
255            }
256        });
257        *self
258            .super_properties
259            .dynamic_props
260            .write()
261            .expect("ThinkingData super properties poisoned") = Some(action);
262    }
263
264    /// Snapshot of the dynamic super properties.
265    pub fn dynamic_super_properties(&self) -> Map<String, Value> {
266        self.super_properties.get_dynamic()
267    }
268
269    /// Report an ordinary event attributed to `account_id`.
270    pub fn track(
271        &self,
272        account_id: &str,
273        event_name: &str,
274        properties: impl IntoPropertyMap,
275    ) -> Result<()> {
276        self.track_with_distinct_id(account_id, "", event_name, properties)
277    }
278
279    /// Report an ordinary event with explicit account and distinct IDs.
280    pub fn track_with_distinct_id(
281        &self,
282        account_id: &str,
283        distinct_id: &str,
284        event_name: &str,
285        properties: impl IntoPropertyMap,
286    ) -> Result<()> {
287        self.track_impl(
288            account_id,
289            distinct_id,
290            DataType::Track,
291            event_name,
292            "",
293            properties,
294        )
295    }
296
297    /// Report a first-check event; `first_check_id` deduplicates it.
298    pub fn track_first(
299        &self,
300        account_id: &str,
301        event_name: &str,
302        first_check_id: &str,
303        properties: impl IntoPropertyMap,
304    ) -> Result<()> {
305        self.track_first_with_distinct_id(account_id, "", event_name, first_check_id, properties)
306    }
307
308    /// Report a first-check event with explicit account and distinct IDs.
309    pub fn track_first_with_distinct_id(
310        &self,
311        account_id: &str,
312        distinct_id: &str,
313        event_name: &str,
314        first_check_id: &str,
315        properties: impl IntoPropertyMap,
316    ) -> Result<()> {
317        if first_check_id.is_empty() {
318            let message = "the 'firstCheckId' must be provided";
319            crate::log::td_log_info(message);
320            return Err(TDError::EmptyFirstCheckId);
321        }
322        let mut map = properties.into_property_map()?;
323        map.insert(
324            "#first_check_id".to_string(),
325            Value::String(first_check_id.to_string()),
326        );
327        self.track_impl(
328            account_id,
329            distinct_id,
330            DataType::Track,
331            event_name,
332            "",
333            map,
334        )
335    }
336
337    /// Report an updatable event identified by `event_id`.
338    pub fn track_update(
339        &self,
340        account_id: &str,
341        event_name: &str,
342        event_id: &str,
343        properties: impl IntoPropertyMap,
344    ) -> Result<()> {
345        self.track_update_with_distinct_id(account_id, "", event_name, event_id, properties)
346    }
347
348    /// Report an updatable event with explicit account and distinct IDs.
349    pub fn track_update_with_distinct_id(
350        &self,
351        account_id: &str,
352        distinct_id: &str,
353        event_name: &str,
354        event_id: &str,
355        properties: impl IntoPropertyMap,
356    ) -> Result<()> {
357        self.track_impl(
358            account_id,
359            distinct_id,
360            DataType::TrackUpdate,
361            event_name,
362            event_id,
363            properties,
364        )
365    }
366
367    /// Report an overridable event identified by `event_id`.
368    pub fn track_overwrite(
369        &self,
370        account_id: &str,
371        event_name: &str,
372        event_id: &str,
373        properties: impl IntoPropertyMap,
374    ) -> Result<()> {
375        self.track_overwrite_with_distinct_id(account_id, "", event_name, event_id, properties)
376    }
377
378    /// Report an overridable event with explicit account and distinct IDs.
379    pub fn track_overwrite_with_distinct_id(
380        &self,
381        account_id: &str,
382        distinct_id: &str,
383        event_name: &str,
384        event_id: &str,
385        properties: impl IntoPropertyMap,
386    ) -> Result<()> {
387        self.track_impl(
388            account_id,
389            distinct_id,
390            DataType::TrackOverwrite,
391            event_name,
392            event_id,
393            properties,
394        )
395    }
396
397    fn track_impl(
398        &self,
399        account_id: &str,
400        distinct_id: &str,
401        data_type: DataType,
402        event_name: &str,
403        event_id: &str,
404        properties: impl IntoPropertyMap,
405    ) -> Result<()> {
406        validate_event(data_type, event_name, event_id)?;
407        let custom = properties.into_property_map()?;
408        let properties = compose_track_properties(
409            &self.super_properties.get(),
410            &self.super_properties.get_dynamic(),
411            custom,
412        );
413        let data = build_data(
414            account_id,
415            distinct_id,
416            data_type,
417            event_name,
418            event_id,
419            self.consumer.is_stringent(),
420            properties,
421        )?;
422        self.consumer.add(&data)
423    }
424
425    /// Set user properties, overwriting existing values.
426    pub fn user_set(&self, account_id: &str, properties: impl IntoPropertyMap) -> Result<()> {
427        self.user_set_with_distinct_id(account_id, "", properties)
428    }
429
430    /// Set user properties with explicit account and distinct IDs.
431    pub fn user_set_with_distinct_id(
432        &self,
433        account_id: &str,
434        distinct_id: &str,
435        properties: impl IntoPropertyMap,
436    ) -> Result<()> {
437        self.user_impl(
438            account_id,
439            distinct_id,
440            DataType::UserSet,
441            properties.into_property_map()?,
442        )
443    }
444
445    /// Set user properties only where they were not set before.
446    pub fn user_set_once(&self, account_id: &str, properties: impl IntoPropertyMap) -> Result<()> {
447        self.user_set_once_with_distinct_id(account_id, "", properties)
448    }
449
450    /// `user_set_once` with explicit account and distinct IDs.
451    pub fn user_set_once_with_distinct_id(
452        &self,
453        account_id: &str,
454        distinct_id: &str,
455        properties: impl IntoPropertyMap,
456    ) -> Result<()> {
457        self.user_impl(
458            account_id,
459            distinct_id,
460            DataType::UserSetOnce,
461            properties.into_property_map()?,
462        )
463    }
464
465    /// Accumulate numeric user properties.
466    pub fn user_add(&self, account_id: &str, properties: impl IntoPropertyMap) -> Result<()> {
467        self.user_add_with_distinct_id(account_id, "", properties)
468    }
469
470    /// `user_add` with explicit account and distinct IDs.
471    pub fn user_add_with_distinct_id(
472        &self,
473        account_id: &str,
474        distinct_id: &str,
475        properties: impl IntoPropertyMap,
476    ) -> Result<()> {
477        self.user_impl(
478            account_id,
479            distinct_id,
480            DataType::UserAdd,
481            properties.into_property_map()?,
482        )
483    }
484
485    /// Append values to array-typed user properties.
486    pub fn user_append(&self, account_id: &str, properties: impl IntoPropertyMap) -> Result<()> {
487        self.user_append_with_distinct_id(account_id, "", properties)
488    }
489
490    /// `user_append` with explicit account and distinct IDs.
491    pub fn user_append_with_distinct_id(
492        &self,
493        account_id: &str,
494        distinct_id: &str,
495        properties: impl IntoPropertyMap,
496    ) -> Result<()> {
497        self.user_impl(
498            account_id,
499            distinct_id,
500            DataType::UserAppend,
501            properties.into_property_map()?,
502        )
503    }
504
505    /// Append unique values to array-typed user properties.
506    pub fn user_uniq_append(
507        &self,
508        account_id: &str,
509        properties: impl IntoPropertyMap,
510    ) -> Result<()> {
511        self.user_uniq_append_with_distinct_id(account_id, "", properties)
512    }
513
514    /// `user_uniq_append` with explicit account and distinct IDs.
515    pub fn user_uniq_append_with_distinct_id(
516        &self,
517        account_id: &str,
518        distinct_id: &str,
519        properties: impl IntoPropertyMap,
520    ) -> Result<()> {
521        self.user_impl(
522            account_id,
523            distinct_id,
524            DataType::UserUniqAppend,
525            properties.into_property_map()?,
526        )
527    }
528
529    /// Clear the listed user properties.
530    pub fn user_unset<S: AsRef<str>>(&self, account_id: &str, keys: &[S]) -> Result<()> {
531        self.user_unset_with_distinct_id(account_id, "", keys)
532    }
533
534    /// Clear the listed user properties with explicit account and distinct IDs.
535    pub fn user_unset_with_distinct_id<S: AsRef<str>>(
536        &self,
537        account_id: &str,
538        distinct_id: &str,
539        keys: &[S],
540    ) -> Result<()> {
541        validate_unset_keys(keys)?;
542        let mut properties = Map::new();
543        for key in keys {
544            properties.insert(key.as_ref().to_string(), Value::from(0));
545        }
546        self.user_impl(account_id, distinct_id, DataType::UserUnset, properties)
547    }
548
549    /// Clear user properties using a property map (values are ignored by the
550    /// receiver, but preset keys keep their values, matching the Lua SDK).
551    pub fn user_unset_with_properties(
552        &self,
553        account_id: &str,
554        properties: impl IntoPropertyMap,
555    ) -> Result<()> {
556        self.user_unset_with_properties_with_distinct_id(account_id, "", properties)
557    }
558
559    /// `user_unset_with_properties` with explicit account and distinct IDs.
560    pub fn user_unset_with_properties_with_distinct_id(
561        &self,
562        account_id: &str,
563        distinct_id: &str,
564        properties: impl IntoPropertyMap,
565    ) -> Result<()> {
566        let mut map = properties.into_property_map()?;
567        if map.is_empty() {
568            crate::log::td_log_info("invalid params for UserUnset: properties is nil");
569            return Err(TDError::EmptyUnsetKeys);
570        }
571        for (key, value) in map.iter_mut() {
572            if !key.starts_with('#') {
573                *value = Value::from(0);
574            }
575        }
576        self.user_impl(account_id, distinct_id, DataType::UserUnset, map)
577    }
578
579    /// Delete the user; this operation cannot be undone.
580    pub fn user_del(&self, account_id: &str) -> Result<()> {
581        self.user_del_with_distinct_id(account_id, "")
582    }
583
584    /// Delete the user with explicit account and distinct IDs.
585    pub fn user_del_with_distinct_id(&self, account_id: &str, distinct_id: &str) -> Result<()> {
586        self.user_impl(account_id, distinct_id, DataType::UserDel, Map::new())
587    }
588
589    /// Delete the user together with final property values.
590    pub fn user_del_with_properties(
591        &self,
592        account_id: &str,
593        properties: impl IntoPropertyMap,
594    ) -> Result<()> {
595        self.user_del_with_properties_with_distinct_id(account_id, "", properties)
596    }
597
598    /// `user_del_with_properties` with explicit account and distinct IDs.
599    pub fn user_del_with_properties_with_distinct_id(
600        &self,
601        account_id: &str,
602        distinct_id: &str,
603        properties: impl IntoPropertyMap,
604    ) -> Result<()> {
605        self.user_impl(
606            account_id,
607            distinct_id,
608            DataType::UserDel,
609            properties.into_property_map()?,
610        )
611    }
612
613    fn user_impl(
614        &self,
615        account_id: &str,
616        distinct_id: &str,
617        data_type: DataType,
618        properties: Map<String, Value>,
619    ) -> Result<()> {
620        let data = build_data(
621            account_id,
622            distinct_id,
623            data_type,
624            "",
625            "",
626            self.consumer.is_stringent(),
627            properties,
628        )?;
629        self.consumer.add(&data)
630    }
631
632    /// Deliver everything currently buffered by the consumer.
633    pub fn flush(&self) -> Result<()> {
634        self.consumer.flush()
635    }
636
637    /// Flush and shut the consumer down.
638    pub fn close(&self) -> Result<()> {
639        self.consumer.close()
640    }
641}
642
643// ---------------------------------------------------------------------------
644// Async facade
645// ---------------------------------------------------------------------------
646
647/// The asynchronous analytics facade, mirroring [`TDAnalytics`] with async
648/// methods over the [`AsyncConsumer`] trait. Available with the `async`
649/// feature.
650///
651/// ```
652/// # #[cfg(feature = "async")]
653/// # async fn demo() -> Result<(), thinkingdata_core::TDError> {
654/// # use thinkingdata_core::{TDAnalyticsAsync, consumer::BatchConsumer};
655///
656/// # let consumer = BatchConsumer::new("https://receiver.thinkingdata.io", "your_app_id")?;
657/// # let ta = TDAnalyticsAsync::new(consumer)?;
658///
659/// # ta.set_super_properties(serde_json::json!({ "channel": "rust" }))?;
660/// # ta.track("account_id_123", "purchase", serde_json::json!({ "price": 99.0 })).await?;
661/// # ta.close().await?;
662/// # Ok(())
663/// # }
664/// ```
665#[cfg(feature = "async")]
666#[derive(Clone)]
667pub struct TDAnalyticsAsync {
668    consumer: Arc<dyn AsyncConsumer>,
669    super_properties: Arc<SuperProperties>,
670}
671
672#[cfg(feature = "async")]
673impl TDAnalyticsAsync {
674    /// Create an analytics instance delegating delivery to `consumer`.
675    pub fn new(consumer: impl AsyncConsumer + 'static) -> Result<Self> {
676        crate::log::td_log_info("init SDK success");
677        Ok(Self {
678            consumer: Arc::new(consumer),
679            super_properties: Arc::new(SuperProperties::default()),
680        })
681    }
682
683    /// The injected consumer.
684    pub fn consumer(&self) -> &Arc<dyn AsyncConsumer> {
685        &self.consumer
686    }
687
688    /// Set common properties applied to every subsequent `track*` event.
689    pub fn set_super_properties(&self, properties: impl IntoPropertyMap) -> Result<()> {
690        self.super_properties.set(properties.into_property_map()?)
691    }
692
693    /// Snapshot of the currently registered super properties.
694    pub fn super_properties(&self) -> Map<String, Value> {
695        self.super_properties.get()
696    }
697
698    /// Remove every registered super property.
699    pub fn clear_super_properties(&self) {
700        self.super_properties
701            .static_props
702            .write()
703            .expect("ThinkingData super properties poisoned")
704            .clear();
705    }
706
707    /// Register a callback producing dynamic common properties. It is
708    /// evaluated once per event, outside of any lock; avoid heavy work in it.
709    pub fn set_dynamic_super_properties<F, P>(&self, action: F)
710    where
711        F: Fn() -> P + Send + Sync + 'static,
712        P: IntoPropertyMap,
713    {
714        let action = Arc::new(move || match action().into_property_map() {
715            Ok(map) => map,
716            Err(err) => {
717                crate::log::td_log_warning(&format!("dynamic super properties ignored: {err}"));
718                Map::new()
719            }
720        });
721        *self
722            .super_properties
723            .dynamic_props
724            .write()
725            .expect("ThinkingData super properties poisoned") = Some(action);
726    }
727
728    /// Snapshot of the dynamic super properties.
729    pub fn dynamic_super_properties(&self) -> Map<String, Value> {
730        self.super_properties.get_dynamic()
731    }
732
733    /// Report an ordinary event attributed to `account_id`.
734    pub async fn track(
735        &self,
736        account_id: &str,
737        event_name: &str,
738        properties: impl IntoPropertyMap,
739    ) -> Result<()> {
740        self.track_with_distinct_id(account_id, "", event_name, properties)
741            .await
742    }
743
744    /// Report an ordinary event with explicit account and distinct IDs.
745    pub async fn track_with_distinct_id(
746        &self,
747        account_id: &str,
748        distinct_id: &str,
749        event_name: &str,
750        properties: impl IntoPropertyMap,
751    ) -> Result<()> {
752        self.track_impl(
753            account_id,
754            distinct_id,
755            DataType::Track,
756            event_name,
757            "",
758            properties,
759        )
760        .await
761    }
762
763    /// Report a first-check event; `first_check_id` deduplicates it.
764    pub async fn track_first(
765        &self,
766        account_id: &str,
767        event_name: &str,
768        first_check_id: &str,
769        properties: impl IntoPropertyMap,
770    ) -> Result<()> {
771        self.track_first_with_distinct_id(account_id, "", event_name, first_check_id, properties)
772            .await
773    }
774
775    /// Report a first-check event with explicit account and distinct IDs.
776    pub async fn track_first_with_distinct_id(
777        &self,
778        account_id: &str,
779        distinct_id: &str,
780        event_name: &str,
781        first_check_id: &str,
782        properties: impl IntoPropertyMap,
783    ) -> Result<()> {
784        if first_check_id.is_empty() {
785            let message = "the 'firstCheckId' must be provided";
786            crate::log::td_log_info(message);
787            return Err(TDError::EmptyFirstCheckId);
788        }
789        let mut map = properties.into_property_map()?;
790        map.insert(
791            "#first_check_id".to_string(),
792            Value::String(first_check_id.to_string()),
793        );
794        self.track_impl(
795            account_id,
796            distinct_id,
797            DataType::Track,
798            event_name,
799            "",
800            map,
801        )
802        .await
803    }
804
805    /// Report an updatable event identified by `event_id`.
806    pub async fn track_update(
807        &self,
808        account_id: &str,
809        event_name: &str,
810        event_id: &str,
811        properties: impl IntoPropertyMap,
812    ) -> Result<()> {
813        self.track_update_with_distinct_id(account_id, "", event_name, event_id, properties)
814            .await
815    }
816
817    /// Report an updatable event with explicit account and distinct IDs.
818    pub async fn track_update_with_distinct_id(
819        &self,
820        account_id: &str,
821        distinct_id: &str,
822        event_name: &str,
823        event_id: &str,
824        properties: impl IntoPropertyMap,
825    ) -> Result<()> {
826        self.track_impl(
827            account_id,
828            distinct_id,
829            DataType::TrackUpdate,
830            event_name,
831            event_id,
832            properties,
833        )
834        .await
835    }
836
837    /// Report an overridable event identified by `event_id`.
838    pub async fn track_overwrite(
839        &self,
840        account_id: &str,
841        event_name: &str,
842        event_id: &str,
843        properties: impl IntoPropertyMap,
844    ) -> Result<()> {
845        self.track_overwrite_with_distinct_id(account_id, "", event_name, event_id, properties)
846            .await
847    }
848
849    /// Report an overridable event with explicit account and distinct IDs.
850    pub async fn track_overwrite_with_distinct_id(
851        &self,
852        account_id: &str,
853        distinct_id: &str,
854        event_name: &str,
855        event_id: &str,
856        properties: impl IntoPropertyMap,
857    ) -> Result<()> {
858        self.track_impl(
859            account_id,
860            distinct_id,
861            DataType::TrackOverwrite,
862            event_name,
863            event_id,
864            properties,
865        )
866        .await
867    }
868
869    async fn track_impl(
870        &self,
871        account_id: &str,
872        distinct_id: &str,
873        data_type: DataType,
874        event_name: &str,
875        event_id: &str,
876        properties: impl IntoPropertyMap,
877    ) -> Result<()> {
878        validate_event(data_type, event_name, event_id)?;
879        let custom = properties.into_property_map()?;
880        let properties = compose_track_properties(
881            &self.super_properties.get(),
882            &self.super_properties.get_dynamic(),
883            custom,
884        );
885        let data = build_data(
886            account_id,
887            distinct_id,
888            data_type,
889            event_name,
890            event_id,
891            self.consumer.is_stringent(),
892            properties,
893        )?;
894        self.consumer.add_async(&data).await
895    }
896
897    /// Set user properties, overwriting existing values.
898    pub async fn user_set(&self, account_id: &str, properties: impl IntoPropertyMap) -> Result<()> {
899        self.user_set_with_distinct_id(account_id, "", properties)
900            .await
901    }
902
903    /// Set user properties with explicit account and distinct IDs.
904    pub async fn user_set_with_distinct_id(
905        &self,
906        account_id: &str,
907        distinct_id: &str,
908        properties: impl IntoPropertyMap,
909    ) -> Result<()> {
910        self.user_impl(
911            account_id,
912            distinct_id,
913            DataType::UserSet,
914            properties.into_property_map()?,
915        )
916        .await
917    }
918
919    /// Set user properties only where they were not set before.
920    pub async fn user_set_once(
921        &self,
922        account_id: &str,
923        properties: impl IntoPropertyMap,
924    ) -> Result<()> {
925        self.user_set_once_with_distinct_id(account_id, "", properties)
926            .await
927    }
928
929    /// `user_set_once` with explicit account and distinct IDs.
930    pub async fn user_set_once_with_distinct_id(
931        &self,
932        account_id: &str,
933        distinct_id: &str,
934        properties: impl IntoPropertyMap,
935    ) -> Result<()> {
936        self.user_impl(
937            account_id,
938            distinct_id,
939            DataType::UserSetOnce,
940            properties.into_property_map()?,
941        )
942        .await
943    }
944
945    /// Accumulate numeric user properties.
946    pub async fn user_add(&self, account_id: &str, properties: impl IntoPropertyMap) -> Result<()> {
947        self.user_add_with_distinct_id(account_id, "", properties)
948            .await
949    }
950
951    /// `user_add` with explicit account and distinct IDs.
952    pub async fn user_add_with_distinct_id(
953        &self,
954        account_id: &str,
955        distinct_id: &str,
956        properties: impl IntoPropertyMap,
957    ) -> Result<()> {
958        self.user_impl(
959            account_id,
960            distinct_id,
961            DataType::UserAdd,
962            properties.into_property_map()?,
963        )
964        .await
965    }
966
967    /// Append values to array-typed user properties.
968    pub async fn user_append(
969        &self,
970        account_id: &str,
971        properties: impl IntoPropertyMap,
972    ) -> Result<()> {
973        self.user_append_with_distinct_id(account_id, "", properties)
974            .await
975    }
976
977    /// `user_append` with explicit account and distinct IDs.
978    pub async fn user_append_with_distinct_id(
979        &self,
980        account_id: &str,
981        distinct_id: &str,
982        properties: impl IntoPropertyMap,
983    ) -> Result<()> {
984        self.user_impl(
985            account_id,
986            distinct_id,
987            DataType::UserAppend,
988            properties.into_property_map()?,
989        )
990        .await
991    }
992
993    /// Append unique values to array-typed user properties.
994    pub async fn user_uniq_append(
995        &self,
996        account_id: &str,
997        properties: impl IntoPropertyMap,
998    ) -> Result<()> {
999        self.user_uniq_append_with_distinct_id(account_id, "", properties)
1000            .await
1001    }
1002
1003    /// `user_uniq_append` with explicit account and distinct IDs.
1004    pub async fn user_uniq_append_with_distinct_id(
1005        &self,
1006        account_id: &str,
1007        distinct_id: &str,
1008        properties: impl IntoPropertyMap,
1009    ) -> Result<()> {
1010        self.user_impl(
1011            account_id,
1012            distinct_id,
1013            DataType::UserUniqAppend,
1014            properties.into_property_map()?,
1015        )
1016        .await
1017    }
1018
1019    /// Clear the listed user properties.
1020    pub async fn user_unset<S: AsRef<str>>(&self, account_id: &str, keys: &[S]) -> Result<()> {
1021        self.user_unset_with_distinct_id(account_id, "", keys).await
1022    }
1023
1024    /// Clear the listed user properties with explicit account and distinct IDs.
1025    pub async fn user_unset_with_distinct_id<S: AsRef<str>>(
1026        &self,
1027        account_id: &str,
1028        distinct_id: &str,
1029        keys: &[S],
1030    ) -> Result<()> {
1031        validate_unset_keys(keys)?;
1032        let mut properties = Map::new();
1033        for key in keys {
1034            properties.insert(key.as_ref().to_string(), Value::from(0));
1035        }
1036        self.user_impl(account_id, distinct_id, DataType::UserUnset, properties)
1037            .await
1038    }
1039
1040    /// Clear user properties using a property map (values are ignored by the
1041    /// receiver, but preset keys keep their values, matching the Lua SDK).
1042    pub async fn user_unset_with_properties(
1043        &self,
1044        account_id: &str,
1045        properties: impl IntoPropertyMap,
1046    ) -> Result<()> {
1047        self.user_unset_with_properties_with_distinct_id(account_id, "", properties)
1048            .await
1049    }
1050
1051    /// `user_unset_with_properties` with explicit account and distinct IDs.
1052    pub async fn user_unset_with_properties_with_distinct_id(
1053        &self,
1054        account_id: &str,
1055        distinct_id: &str,
1056        properties: impl IntoPropertyMap,
1057    ) -> Result<()> {
1058        let mut map = properties.into_property_map()?;
1059        if map.is_empty() {
1060            crate::log::td_log_info("invalid params for UserUnset: properties is nil");
1061            return Err(TDError::EmptyUnsetKeys);
1062        }
1063        for (key, value) in map.iter_mut() {
1064            if !key.starts_with('#') {
1065                *value = Value::from(0);
1066            }
1067        }
1068        self.user_impl(account_id, distinct_id, DataType::UserUnset, map)
1069            .await
1070    }
1071
1072    /// Delete the user; this operation cannot be undone.
1073    pub async fn user_del(&self, account_id: &str) -> Result<()> {
1074        self.user_del_with_distinct_id(account_id, "").await
1075    }
1076
1077    /// Delete the user with explicit account and distinct IDs.
1078    pub async fn user_del_with_distinct_id(
1079        &self,
1080        account_id: &str,
1081        distinct_id: &str,
1082    ) -> Result<()> {
1083        self.user_impl(account_id, distinct_id, DataType::UserDel, Map::new())
1084            .await
1085    }
1086
1087    /// Delete the user together with final property values.
1088    pub async fn user_del_with_properties(
1089        &self,
1090        account_id: &str,
1091        properties: impl IntoPropertyMap,
1092    ) -> Result<()> {
1093        self.user_del_with_properties_with_distinct_id(account_id, "", properties)
1094            .await
1095    }
1096
1097    /// `user_del_with_properties` with explicit account and distinct IDs.
1098    pub async fn user_del_with_properties_with_distinct_id(
1099        &self,
1100        account_id: &str,
1101        distinct_id: &str,
1102        properties: impl IntoPropertyMap,
1103    ) -> Result<()> {
1104        self.user_impl(
1105            account_id,
1106            distinct_id,
1107            DataType::UserDel,
1108            properties.into_property_map()?,
1109        )
1110        .await
1111    }
1112
1113    async fn user_impl(
1114        &self,
1115        account_id: &str,
1116        distinct_id: &str,
1117        data_type: DataType,
1118        properties: Map<String, Value>,
1119    ) -> Result<()> {
1120        let data = build_data(
1121            account_id,
1122            distinct_id,
1123            data_type,
1124            "",
1125            "",
1126            self.consumer.is_stringent(),
1127            properties,
1128        )?;
1129        self.consumer.add_async(&data).await
1130    }
1131
1132    /// Deliver everything currently buffered by the consumer.
1133    pub async fn flush(&self) -> Result<()> {
1134        self.consumer.flush_async().await
1135    }
1136
1137    /// Flush and shut the consumer down.
1138    pub async fn close(&self) -> Result<()> {
1139        self.consumer.close_async().await
1140    }
1141}