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