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