Skip to main content

thinkingdata_core/
data.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 wire-format data model of the ThinkingData receiver.
16
17use std::collections::{BTreeMap, HashMap};
18
19use serde::Serialize;
20use serde_json::{Map, Value};
21
22use crate::error::{Result, TDError};
23#[cfg(any(feature = "blocking", feature = "async"))]
24use crate::log::td_log_error;
25use crate::utils::format_now;
26#[cfg(any(feature = "blocking", feature = "async"))]
27use crate::utils::{generate_uuid, is_valid_key};
28
29/// The name of the SDK that produced the data, reported as `#lib`.
30pub const LIB_NAME: &str = "Rust";
31
32/// Property keys that are hoisted out of `properties` into dedicated top-level
33/// fields of the wire format.
34#[cfg(any(feature = "blocking", feature = "async"))]
35pub(crate) const PRESET_KEYS: [&str; 7] = [
36    "#ip",
37    "#app_id",
38    "#time",
39    "#first_check_id",
40    "#uuid",
41    "#transaction_property",
42    "#import_tool_id",
43];
44
45/// Every TE preset property (v5.0 documentation, "预置属性与系统字段").
46///
47/// All preset properties start with `#` and are event properties generated or
48/// obtained by TE. Any `#`-prefixed property outside this list is considered
49/// illegal by the receiver and will not be stored.
50pub const PRESET_PROPERTIES: [&str; 48] = [
51    "#ip",
52    "#country",
53    "#country_code",
54    "#province",
55    "#city",
56    "#os_version",
57    "#manufacturer",
58    "#os",
59    "#device_id",
60    "#screen_height",
61    "#screen_width",
62    "#device_model",
63    "#device_type",
64    "#app_version",
65    "#bundle_id",
66    "#lib",
67    "#lib_version",
68    "#network_type",
69    "#carrier",
70    "#browser",
71    "#browser_version",
72    "#duration",
73    "#url",
74    "#url_path",
75    "#referrer",
76    "#referrer_host",
77    "#title",
78    "#screen_name",
79    "#element_id",
80    "#element_type",
81    "#resume_from_background",
82    "#element_selector",
83    "#element_position",
84    "#element_content",
85    "#scene",
86    "#mp_platform",
87    "#app_crashed_reason",
88    "#zone_offset",
89    "#system_language",
90    "#install_time",
91    "#simulator",
92    "#ram",
93    "#disk",
94    "#fps",
95    "#background_duration",
96    "#start_reason",
97    "#ua",
98    "#utm",
99];
100
101/// Whether `key` is one of the TE preset properties documented for v5.0.
102pub fn is_preset_property(key: &str) -> bool {
103    PRESET_PROPERTIES.contains(&key)
104}
105
106/// The kind of data reported to the receiver.
107///
108/// The string forms are the wire values expected by ThinkingData; note the
109/// historical `user_setOnce` casing, which is preserved on purpose.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
111pub enum DataType {
112    /// Ordinary event.
113    Track,
114    /// Updatable event.
115    TrackUpdate,
116    /// Overridable event.
117    TrackOverwrite,
118    /// Overwrite user properties.
119    UserSet,
120    /// Clear user properties.
121    UserUnset,
122    /// Set user properties only once.
123    UserSetOnce,
124    /// Accumulate numeric user properties.
125    UserAdd,
126    /// Append to array user properties.
127    UserAppend,
128    /// Append unique values to array user properties.
129    UserUniqAppend,
130    /// Delete a user; irreversible.
131    UserDel,
132}
133
134impl DataType {
135    /// The wire representation of this data type.
136    pub const fn as_str(self) -> &'static str {
137        match self {
138            DataType::Track => "track",
139            DataType::TrackUpdate => "track_update",
140            DataType::TrackOverwrite => "track_overwrite",
141            DataType::UserSet => "user_set",
142            DataType::UserUnset => "user_unset",
143            DataType::UserSetOnce => "user_setOnce",
144            DataType::UserAdd => "user_add",
145            DataType::UserAppend => "user_append",
146            DataType::UserUniqAppend => "user_uniq_append",
147            DataType::UserDel => "user_del",
148        }
149    }
150
151    /// True when the data type is one of `track`, `track_update`, `track_overwrite`.
152    pub const fn is_track(self) -> bool {
153        matches!(
154            self,
155            DataType::Track | DataType::TrackUpdate | DataType::TrackOverwrite
156        )
157    }
158}
159
160impl std::fmt::Display for DataType {
161    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162        f.write_str(self.as_str())
163    }
164}
165
166impl Serialize for DataType {
167    fn serialize<S: serde::Serializer>(
168        &self,
169        serializer: S,
170    ) -> std::result::Result<S::Ok, S::Error> {
171        serializer.serialize_str(self.as_str())
172    }
173}
174
175/// Conversion into the property map carried by [`Data`].
176///
177/// Implemented for `serde_json::Map`, `HashMap`, `BTreeMap` and
178/// `serde_json::Value`, so callers can pass their favorite container —
179/// including `serde_json::json!({...})` literals, which must be JSON objects:
180///
181/// ```
182/// # fn main() -> Result<(), thinkingdata_core::TDError> {
183/// # #[cfg(feature = "blocking")]
184/// # {
185/// # use std::collections::HashMap;
186/// # use thinkingdata_core::{TDAnalytics, consumer::LogConsumer};
187/// # let dir = std::env::temp_dir().join("thinkingdata-core-doctest-props");
188/// # let consumer = LogConsumer::new(dir.to_str().unwrap())?;
189/// # let ta = TDAnalytics::new(consumer)?;
190///
191/// # // A HashMap of serde_json values…
192/// # let mut properties = HashMap::new();
193/// # properties.insert("product_name".to_string(), "Rust SDK".into());
194/// # properties.insert("price".to_string(), 99.0.into());
195/// # ta.track("account_id_123", "purchase", properties)?;
196///
197/// # // …or a json! literal.
198/// # ta.user_set("account_id_123", serde_json::json!({ "level": 10 }))?;
199///
200/// # ta.close()?;
201/// # }
202/// # Ok(())
203/// # }
204/// ```
205pub trait IntoPropertyMap {
206    /// Convert the value into a `serde_json` property map.
207    ///
208    /// Fails when a [`Value`] argument is not a JSON object.
209    fn into_property_map(self) -> Result<Map<String, Value>>;
210}
211
212impl IntoPropertyMap for Map<String, Value> {
213    fn into_property_map(self) -> Result<Map<String, Value>> {
214        Ok(self)
215    }
216}
217
218impl IntoPropertyMap for HashMap<String, Value> {
219    fn into_property_map(self) -> Result<Map<String, Value>> {
220        Ok(self.into_iter().collect())
221    }
222}
223
224impl IntoPropertyMap for BTreeMap<String, Value> {
225    fn into_property_map(self) -> Result<Map<String, Value>> {
226        Ok(self.into_iter().collect())
227    }
228}
229
230impl IntoPropertyMap for Value {
231    fn into_property_map(self) -> Result<Map<String, Value>> {
232        match self {
233            Value::Object(map) => Ok(map),
234            _ => Err(TDError::msg(
235                "properties must be a JSON object of string keys",
236            )),
237        }
238    }
239}
240
241/// One data point in the ThinkingData wire format.
242///
243/// Fields whose name starts with `#` are preset properties recognized by the
244/// receiver; they are serialized with `omitempty` semantics, except `#type`,
245/// `#time` and `properties` which are always present.
246#[derive(Debug, Clone, Serialize)]
247pub struct Data {
248    /// Account ID of the user (`#account_id`).
249    #[serde(rename = "#account_id", skip_serializing_if = "String::is_empty")]
250    pub account_id: String,
251    /// Anonymous/distinct ID of the user (`#distinct_id`).
252    #[serde(rename = "#distinct_id", skip_serializing_if = "String::is_empty")]
253    pub distinct_id: String,
254    /// Data type (`#type`), always serialized.
255    #[serde(rename = "#type")]
256    pub data_type: DataType,
257    /// Event time, `yyyy-MM-dd HH:mm:ss.SSS` (`#time`), always serialized.
258    #[serde(rename = "#time")]
259    pub time: String,
260    /// Event name (`#event_name`).
261    #[serde(rename = "#event_name", skip_serializing_if = "String::is_empty")]
262    pub event_name: String,
263    /// Event ID for updatable/overridable events (`#event_id`).
264    #[serde(rename = "#event_id", skip_serializing_if = "String::is_empty")]
265    pub event_id: String,
266    /// First-check ID for first events (`#first_check_id`).
267    #[serde(rename = "#first_check_id", skip_serializing_if = "String::is_empty")]
268    pub first_check_id: String,
269    /// IP address used for geolocation (`#ip`).
270    #[serde(rename = "#ip", skip_serializing_if = "String::is_empty")]
271    pub ip: String,
272    /// Unique ID that identifies this data point (`#uuid`).
273    #[serde(rename = "#uuid", skip_serializing_if = "String::is_empty")]
274    pub uuid: String,
275    /// App ID override (`#app_id`).
276    #[serde(rename = "#app_id", skip_serializing_if = "String::is_empty")]
277    pub app_id: String,
278    /// Transaction properties for `track_update`/`track_overwrite`
279    /// (`#transaction_property`).
280    #[serde(
281        rename = "#transaction_property",
282        skip_serializing_if = "String::is_empty"
283    )]
284    pub transaction_property: String,
285    /// Identifier of the import tool (`#import_tool_id`).
286    #[serde(rename = "#import_tool_id", skip_serializing_if = "String::is_empty")]
287    pub import_tool_id: String,
288    /// Custom event/user properties, always serialized.
289    pub properties: Map<String, Value>,
290    /// True when `properties` contains nested (non-scalar) values; used by the
291    /// debug consumer to decide whether timestamps need rewriting.
292    #[cfg(any(feature = "blocking", feature = "async"))]
293    #[serde(skip)]
294    pub(crate) is_complex: bool,
295}
296
297impl Data {
298    /// Create an empty [`Data`] for `data_type`, stamping `#time` with the
299    /// current local time.
300    pub fn new(data_type: DataType) -> Self {
301        Self {
302            account_id: String::new(),
303            distinct_id: String::new(),
304            data_type,
305            time: format_now(),
306            event_name: String::new(),
307            event_id: String::new(),
308            first_check_id: String::new(),
309            ip: String::new(),
310            uuid: String::new(),
311            app_id: String::new(),
312            transaction_property: String::new(),
313            import_tool_id: String::new(),
314            properties: Map::new(),
315            #[cfg(any(feature = "blocking", feature = "async"))]
316            is_complex: false,
317        }
318    }
319
320    /// Validate this snapshot against the limits documented in the TE v5.0
321    /// data rules:
322    ///
323    /// - `#time` must be `yyyy-MM-dd HH:mm:ss` or `yyyy-MM-dd HH:mm:ss.SSS`
324    /// - `#account_id` / `#distinct_id` are limited to 128 characters
325    /// - property values must respect the documented type limits (string
326    ///   ≤ 2 KB, number within ±9E15, list ≤ 500 elements with string elements
327    ///   ≤ 255 bytes, object ≤ 100 sub-properties)
328    ///
329    /// The debug consumer runs this check in stringent mode; other consumers
330    /// leave it to the receiver, which silently drops mismatched values. Call
331    /// it yourself for pre-flight validation.
332    pub fn check_limits(&self) -> Result<()> {
333        if !crate::utils::is_documented_time_format(&self.time) {
334            return Err(TDError::msg(format!(
335                "invalid #time {:?}: expected \"yyyy-MM-dd HH:mm:ss\" or \"yyyy-MM-dd HH:mm:ss.SSS\"",
336                self.time
337            )));
338        }
339        const MAX_ID_LENGTH: usize = 128;
340        if self.account_id.len() > MAX_ID_LENGTH {
341            return Err(TDError::msg(format!(
342                "#account_id exceeds {MAX_ID_LENGTH} characters"
343            )));
344        }
345        if self.distinct_id.len() > MAX_ID_LENGTH {
346            return Err(TDError::msg(format!(
347                "#distinct_id exceeds {MAX_ID_LENGTH} characters"
348            )));
349        }
350        for (key, value) in &self.properties {
351            crate::utils::check_value_limits(key, value)?;
352        }
353        Ok(())
354    }
355}
356
357/// Remove `key` from `properties` and return it when it is a string.
358///
359/// Non-string values are dropped with an error log, matching the Go SDK.
360#[cfg(any(feature = "blocking", feature = "async"))]
361pub(crate) fn extract_string_property(properties: &mut Map<String, Value>, key: &str) -> String {
362    match properties.remove(key) {
363        Some(Value::String(value)) => value,
364        Some(_) => {
365            td_log_error(&format!("Invalid data type for {key}"));
366            String::new()
367        }
368        None => String::new(),
369    }
370}
371
372/// Remove `#time` from `properties` and interpret it.
373///
374/// Strings are passed through unchanged; an empty string or any other type
375/// falls back to the current local time.
376#[cfg(any(feature = "blocking", feature = "async"))]
377pub(crate) fn extract_time(properties: &mut Map<String, Value>) -> String {
378    match properties.remove("#time") {
379        Some(Value::String(value)) if !value.is_empty() => value,
380        Some(_) => format_now(),
381        None => format_now(),
382    }
383}
384
385/// Validate the event name and property values of `data`, and flag complex
386/// (nested) property values.
387///
388/// When `stringent` is set (debug consumer), property keys must also match the
389/// key pattern and the documented v5.0 value limits are enforced; otherwise
390/// invalid keys are passed through, mirroring the Go SDK's lenient consumers.
391#[cfg(any(feature = "blocking", feature = "async"))]
392pub(crate) fn format_properties(data: &mut Data, stringent: bool) -> Result<()> {
393    if !data.event_name.is_empty() && !is_valid_key(&data.event_name) {
394        let message = format!("invalid event name: {}", data.event_name);
395        crate::log::td_log_info(&message);
396        return Err(TDError::InvalidEventName(data.event_name.clone()));
397    }
398
399    for (key, value) in &data.properties {
400        if stringent && !is_valid_key(key) {
401            let message = format!("invalid property key: {key}");
402            crate::log::td_log_info(&message);
403            return Err(TDError::InvalidPropertyKey(key.clone()));
404        }
405
406        if data.data_type == DataType::UserAdd && !value.is_number() {
407            crate::log::td_log_info("invalid property value: only numbers is supported by UserAdd");
408            return Err(TDError::InvalidUserAddValue);
409        }
410
411        // Scalar values serialize as-is; anything else is "complex" and needs
412        // RFC 3339 timestamp rewriting in the debug consumer.
413        match value {
414            Value::Number(_) | Value::Bool(_) | Value::String(_) => {}
415            _ => data.is_complex = true,
416        }
417    }
418
419    if stringent {
420        data.check_limits()?;
421    }
422
423    Ok(())
424}
425
426/// Fill the preset fields of `data` from `properties`, removing the preset
427/// keys from the property map, and generate a `#uuid` when none was supplied.
428#[cfg(any(feature = "blocking", feature = "async"))]
429pub(crate) fn apply_preset_properties(data: &mut Data, properties: &mut Map<String, Value>) {
430    // `PRESET_KEYS` documents the hoisted header fields; extraction is
431    // key-specific below.
432    debug_assert!(PRESET_KEYS.contains(&"#ip"));
433    data.ip = extract_string_property(properties, "#ip");
434    data.app_id = extract_string_property(properties, "#app_id");
435    data.time = extract_time(properties);
436    data.first_check_id = extract_string_property(properties, "#first_check_id");
437    data.transaction_property = extract_string_property(properties, "#transaction_property");
438    data.import_tool_id = extract_string_property(properties, "#import_tool_id");
439    let mut uuid = extract_string_property(properties, "#uuid");
440    if uuid.is_empty() {
441        uuid = generate_uuid();
442    }
443    data.uuid = uuid;
444}
445
446#[cfg(test)]
447mod tests {
448    use super::*;
449
450    pub(super) fn sample_properties() -> Map<String, Value> {
451        let mut props = Map::new();
452        props.insert("string".to_string(), Value::String("v".to_string()));
453        props.insert("number".to_string(), Value::from(1));
454        props.insert("bool".to_string(), Value::Bool(true));
455        props
456    }
457
458    #[test]
459    fn data_serializes_wire_field_names() {
460        let mut data = Data::new(DataType::Track);
461        data.account_id = "acc".to_string();
462        data.event_name = "purchase".to_string();
463        data.properties = sample_properties();
464
465        let json = serde_json::to_value(&data).unwrap();
466        let obj = json.as_object().unwrap();
467        assert_eq!(obj["#account_id"], "acc");
468        assert_eq!(obj["#type"], "track");
469        assert!(obj.get("#distinct_id").is_none());
470        assert!(obj.get("#event_id").is_none());
471        assert!(obj["#time"].as_str().unwrap().contains('.'));
472        assert!(
473            obj["properties"]
474                .as_object()
475                .unwrap()
476                .contains_key("string")
477        );
478    }
479
480    #[test]
481    fn user_del_serializes_empty_properties() {
482        let data = Data::new(DataType::UserDel);
483        let json = serde_json::to_value(&data).unwrap();
484        let obj = json.as_object().unwrap();
485        assert_eq!(obj["#type"], "user_del");
486        assert!(obj["properties"].as_object().unwrap().is_empty());
487    }
488
489    #[test]
490    fn data_type_wire_values() {
491        assert_eq!(DataType::Track.as_str(), "track");
492        assert_eq!(DataType::UserSetOnce.as_str(), "user_setOnce");
493        assert_eq!(DataType::UserUniqAppend.as_str(), "user_uniq_append");
494        assert!(DataType::TrackUpdate.is_track());
495        assert!(!DataType::UserSet.is_track());
496    }
497
498    #[test]
499    fn preset_property_catalog_matches_the_documented_list() {
500        assert_eq!(PRESET_PROPERTIES.len(), 48);
501        assert!(is_preset_property("#lib"));
502        assert!(is_preset_property("#utm"));
503        assert!(is_preset_property("#country_code"));
504        assert!(!is_preset_property("#not_a_preset"));
505        assert!(!is_preset_property("custom_property"));
506    }
507
508    #[test]
509    fn check_limits_accepts_a_well_formed_snapshot() {
510        let mut data = Data::new(DataType::Track);
511        data.account_id = "acc".to_string();
512        data.event_name = "purchase".to_string();
513        data.properties = sample_properties();
514        assert!(data.check_limits().is_ok());
515    }
516
517    #[test]
518    fn check_limits_rejects_malformed_time() {
519        let mut data = Data::new(DataType::Track);
520        data.time = "2024-01-02T03:04:05Z".to_string();
521        let err = data.check_limits().unwrap_err();
522        assert!(err.to_string().contains("#time"), "{err}");
523    }
524
525    #[test]
526    fn check_limits_rejects_oversized_ids() {
527        let mut data = Data::new(DataType::Track);
528        data.account_id = "a".repeat(129);
529        let err = data.check_limits().unwrap_err();
530        assert!(err.to_string().contains("#account_id"), "{err}");
531
532        let mut data = Data::new(DataType::Track);
533        data.distinct_id = "d".repeat(129);
534        let err = data.check_limits().unwrap_err();
535        assert!(err.to_string().contains("#distinct_id"), "{err}");
536    }
537
538    #[test]
539    fn check_limits_rejects_values_over_documented_limits() {
540        let mut data = Data::new(DataType::Track);
541        data.properties
542            .insert("big".to_string(), Value::String("x".repeat(2 * 1024 + 1)));
543        let err = data.check_limits().unwrap_err();
544        assert!(err.to_string().contains("big"), "{err}");
545    }
546}
547
548// Wire-assembly helpers (`apply_preset_properties`, `format_properties`, …)
549// exist only with an API feature, so their tests live behind the same gate.
550#[cfg(all(test, any(feature = "blocking", feature = "async")))]
551mod wire_tests {
552    use super::tests::sample_properties;
553    use super::*;
554
555    #[test]
556    fn preset_keys_are_hoisted_into_fields() {
557        let mut data = Data::new(DataType::Track);
558        data.event_name = "login".to_string();
559        let mut props = sample_properties();
560        props.insert("#ip".to_string(), Value::String("1.2.3.4".to_string()));
561        props.insert(
562            "#time".to_string(),
563            Value::String("2024-01-02 03:04:05.123".to_string()),
564        );
565        props.insert("#uuid".to_string(), Value::String("fixed-uuid".to_string()));
566
567        apply_preset_properties(&mut data, &mut props);
568
569        assert_eq!(data.ip, "1.2.3.4");
570        assert_eq!(data.time, "2024-01-02 03:04:05.123");
571        assert_eq!(data.uuid, "fixed-uuid");
572        assert!(!props.contains_key("#ip"));
573        assert!(!props.contains_key("#time"));
574        assert!(!props.contains_key("#uuid"));
575    }
576
577    #[test]
578    fn missing_uuid_is_generated() {
579        let mut data = Data::new(DataType::Track);
580        let mut props = sample_properties();
581        apply_preset_properties(&mut data, &mut props);
582        assert!(!data.uuid.is_empty());
583    }
584
585    #[test]
586    fn non_string_preset_value_is_dropped() {
587        let mut props = Map::new();
588        props.insert("#ip".to_string(), Value::from(123));
589        let ip = extract_string_property(&mut props, "#ip");
590        assert!(ip.is_empty());
591        assert!(!props.contains_key("#ip"));
592    }
593
594    #[test]
595    fn user_add_rejects_non_numeric_values() {
596        let mut data = Data::new(DataType::UserAdd);
597        data.properties
598            .insert("level".to_string(), Value::String("10".to_string()));
599        assert!(matches!(
600            format_properties(&mut data, false),
601            Err(TDError::InvalidUserAddValue)
602        ));
603    }
604
605    #[test]
606    fn user_add_accepts_numeric_values() {
607        let mut data = Data::new(DataType::UserAdd);
608        data.properties.insert("level".to_string(), Value::from(10));
609        assert!(format_properties(&mut data, false).is_ok());
610    }
611
612    #[test]
613    fn stringent_mode_rejects_invalid_keys() {
614        let mut data = Data::new(DataType::Track);
615        data.event_name = "purchase".to_string();
616        data.properties
617            .insert("bad key".to_string(), Value::from(1));
618        assert!(matches!(
619            format_properties(&mut data, true),
620            Err(TDError::InvalidPropertyKey(_))
621        ));
622
623        let mut lenient = Data::new(DataType::Track);
624        lenient.event_name = "purchase".to_string();
625        lenient
626            .properties
627            .insert("bad key".to_string(), Value::from(1));
628        assert!(format_properties(&mut lenient, false).is_ok());
629    }
630
631    #[test]
632    fn invalid_event_name_is_rejected() {
633        let mut data = Data::new(DataType::Track);
634        data.event_name = "bad event".to_string();
635        assert!(matches!(
636            format_properties(&mut data, false),
637            Err(TDError::InvalidEventName(_))
638        ));
639    }
640
641    #[test]
642    fn complex_values_are_flagged() {
643        let mut data = Data::new(DataType::Track);
644        data.event_name = "purchase".to_string();
645        data.properties
646            .insert("array".to_string(), serde_json::json!(["a", "b"]));
647        format_properties(&mut data, false).unwrap();
648        assert!(data.is_complex);
649    }
650
651    #[test]
652    fn extract_time_falls_back_to_now_for_unsupported_types() {
653        let mut props = Map::new();
654        props.insert("#time".to_string(), Value::from(123));
655        let time = extract_time(&mut props);
656        assert_eq!(time.len(), 23);
657    }
658
659    #[test]
660    fn stringent_format_properties_enforces_value_limits() {
661        let mut data = Data::new(DataType::Track);
662        data.event_name = "purchase".to_string();
663        data.properties
664            .insert("big".to_string(), Value::String("x".repeat(2 * 1024 + 1)));
665        assert!(format_properties(&mut data, false).is_ok());
666        assert!(format_properties(&mut data, true).is_err());
667    }
668}