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}
291
292impl Data {
293    /// Create an empty [`Data`] for `data_type`, stamping `#time` with the
294    /// current local time.
295    pub fn new(data_type: DataType) -> Self {
296        Self {
297            account_id: String::new(),
298            distinct_id: String::new(),
299            data_type,
300            time: format_now(),
301            event_name: String::new(),
302            event_id: String::new(),
303            first_check_id: String::new(),
304            ip: String::new(),
305            uuid: String::new(),
306            app_id: String::new(),
307            transaction_property: String::new(),
308            import_tool_id: String::new(),
309            properties: Map::new(),
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.
353#[cfg(any(feature = "blocking", feature = "async"))]
354pub(crate) fn extract_string_property(properties: &mut Map<String, Value>, key: &str) -> String {
355    match properties.remove(key) {
356        Some(Value::String(value)) => value,
357        Some(_) => {
358            td_log_error(&format!("Invalid data type for {key}"));
359            String::new()
360        }
361        None => String::new(),
362    }
363}
364
365/// Remove `#time` from `properties` and interpret it.
366///
367/// Strings are passed through unchanged; an empty string or any other type
368/// falls back to the current local time.
369#[cfg(any(feature = "blocking", feature = "async"))]
370pub(crate) fn extract_time(properties: &mut Map<String, Value>) -> String {
371    match properties.remove("#time") {
372        Some(Value::String(value)) if !value.is_empty() => value,
373        Some(_) => format_now(),
374        None => format_now(),
375    }
376}
377
378/// Validate the event name and property values of `data`, and flag complex
379/// (nested) property values.
380///
381/// When `stringent` is set (debug consumer), property keys must also match the
382/// key pattern and the documented v5.0 value limits are enforced; otherwise
383/// invalid keys are passed through, mirroring the Go SDK's lenient consumers.
384#[cfg(any(feature = "blocking", feature = "async"))]
385pub(crate) fn format_properties(data: &mut Data, stringent: bool) -> Result<()> {
386    if !data.event_name.is_empty() && !is_valid_key(&data.event_name) {
387        let message = format!("invalid event name: {}", data.event_name);
388        crate::log::td_log_info(&message);
389        return Err(TDError::InvalidEventName(data.event_name.clone()));
390    }
391
392    for (key, value) in &data.properties {
393        if stringent && !is_valid_key(key) {
394            let message = format!("invalid property key: {key}");
395            crate::log::td_log_info(&message);
396            return Err(TDError::InvalidPropertyKey(key.clone()));
397        }
398
399        if data.data_type == DataType::UserAdd && !value.is_number() {
400            crate::log::td_log_info("invalid property value: only numbers is supported by UserAdd");
401            return Err(TDError::InvalidUserAddValue);
402        }
403    }
404
405    if stringent {
406        data.check_limits()?;
407    }
408
409    Ok(())
410}
411
412/// Fill the preset fields of `data` from `properties`, removing the preset
413/// keys from the property map, and generate a `#uuid` when none was supplied.
414#[cfg(any(feature = "blocking", feature = "async"))]
415pub(crate) fn apply_preset_properties(data: &mut Data, properties: &mut Map<String, Value>) {
416    // `PRESET_KEYS` documents the hoisted header fields; extraction is
417    // key-specific below.
418    debug_assert!(PRESET_KEYS.contains(&"#ip"));
419    data.ip = extract_string_property(properties, "#ip");
420    data.app_id = extract_string_property(properties, "#app_id");
421    data.time = extract_time(properties);
422    data.first_check_id = extract_string_property(properties, "#first_check_id");
423    data.transaction_property = extract_string_property(properties, "#transaction_property");
424    data.import_tool_id = extract_string_property(properties, "#import_tool_id");
425    let mut uuid = extract_string_property(properties, "#uuid");
426    if uuid.is_empty() {
427        uuid = generate_uuid();
428    }
429    data.uuid = uuid;
430}
431
432#[cfg(test)]
433mod tests {
434    use super::*;
435
436    pub(super) fn sample_properties() -> Map<String, Value> {
437        let mut props = Map::new();
438        props.insert("string".to_string(), Value::String("v".to_string()));
439        props.insert("number".to_string(), Value::from(1));
440        props.insert("bool".to_string(), Value::Bool(true));
441        props
442    }
443
444    #[test]
445    fn data_serializes_wire_field_names() {
446        let mut data = Data::new(DataType::Track);
447        data.account_id = "acc".to_string();
448        data.event_name = "purchase".to_string();
449        data.properties = sample_properties();
450
451        let json = serde_json::to_value(&data).unwrap();
452        let obj = json.as_object().unwrap();
453        assert_eq!(obj["#account_id"], "acc");
454        assert_eq!(obj["#type"], "track");
455        assert!(obj.get("#distinct_id").is_none());
456        assert!(obj.get("#event_id").is_none());
457        assert!(obj["#time"].as_str().unwrap().contains('.'));
458        assert!(
459            obj["properties"]
460                .as_object()
461                .unwrap()
462                .contains_key("string")
463        );
464    }
465
466    #[test]
467    fn user_del_serializes_empty_properties() {
468        let data = Data::new(DataType::UserDel);
469        let json = serde_json::to_value(&data).unwrap();
470        let obj = json.as_object().unwrap();
471        assert_eq!(obj["#type"], "user_del");
472        assert!(obj["properties"].as_object().unwrap().is_empty());
473    }
474
475    #[test]
476    fn data_type_wire_values() {
477        assert_eq!(DataType::Track.as_str(), "track");
478        assert_eq!(DataType::UserSetOnce.as_str(), "user_setOnce");
479        assert_eq!(DataType::UserUniqAppend.as_str(), "user_uniq_append");
480        assert!(DataType::TrackUpdate.is_track());
481        assert!(!DataType::UserSet.is_track());
482    }
483
484    #[test]
485    fn preset_property_catalog_matches_the_documented_list() {
486        assert_eq!(PRESET_PROPERTIES.len(), 48);
487        assert!(is_preset_property("#lib"));
488        assert!(is_preset_property("#utm"));
489        assert!(is_preset_property("#country_code"));
490        assert!(!is_preset_property("#not_a_preset"));
491        assert!(!is_preset_property("custom_property"));
492    }
493
494    #[test]
495    fn check_limits_accepts_a_well_formed_snapshot() {
496        let mut data = Data::new(DataType::Track);
497        data.account_id = "acc".to_string();
498        data.event_name = "purchase".to_string();
499        data.properties = sample_properties();
500        assert!(data.check_limits().is_ok());
501    }
502
503    #[test]
504    fn check_limits_rejects_malformed_time() {
505        let mut data = Data::new(DataType::Track);
506        data.time = "2024-01-02T03:04:05Z".to_string();
507        let err = data.check_limits().unwrap_err();
508        assert!(err.to_string().contains("#time"), "{err}");
509    }
510
511    #[test]
512    fn check_limits_rejects_oversized_ids() {
513        let mut data = Data::new(DataType::Track);
514        data.account_id = "a".repeat(129);
515        let err = data.check_limits().unwrap_err();
516        assert!(err.to_string().contains("#account_id"), "{err}");
517
518        let mut data = Data::new(DataType::Track);
519        data.distinct_id = "d".repeat(129);
520        let err = data.check_limits().unwrap_err();
521        assert!(err.to_string().contains("#distinct_id"), "{err}");
522    }
523
524    #[test]
525    fn check_limits_rejects_values_over_documented_limits() {
526        let mut data = Data::new(DataType::Track);
527        data.properties
528            .insert("big".to_string(), Value::String("x".repeat(2 * 1024 + 1)));
529        let err = data.check_limits().unwrap_err();
530        assert!(err.to_string().contains("big"), "{err}");
531    }
532}
533
534// Wire-assembly helpers (`apply_preset_properties`, `format_properties`, …)
535// exist only with an API feature, so their tests live behind the same gate.
536#[cfg(all(test, any(feature = "blocking", feature = "async")))]
537mod wire_tests {
538    use super::tests::sample_properties;
539    use super::*;
540
541    #[test]
542    fn preset_keys_are_hoisted_into_fields() {
543        let mut data = Data::new(DataType::Track);
544        data.event_name = "login".to_string();
545        let mut props = sample_properties();
546        props.insert("#ip".to_string(), Value::String("1.2.3.4".to_string()));
547        props.insert(
548            "#time".to_string(),
549            Value::String("2024-01-02 03:04:05.123".to_string()),
550        );
551        props.insert("#uuid".to_string(), Value::String("fixed-uuid".to_string()));
552
553        apply_preset_properties(&mut data, &mut props);
554
555        assert_eq!(data.ip, "1.2.3.4");
556        assert_eq!(data.time, "2024-01-02 03:04:05.123");
557        assert_eq!(data.uuid, "fixed-uuid");
558        assert!(!props.contains_key("#ip"));
559        assert!(!props.contains_key("#time"));
560        assert!(!props.contains_key("#uuid"));
561    }
562
563    #[test]
564    fn missing_uuid_is_generated() {
565        let mut data = Data::new(DataType::Track);
566        let mut props = sample_properties();
567        apply_preset_properties(&mut data, &mut props);
568        assert!(!data.uuid.is_empty());
569    }
570
571    #[test]
572    fn non_string_preset_value_is_dropped() {
573        let mut props = Map::new();
574        props.insert("#ip".to_string(), Value::from(123));
575        let ip = extract_string_property(&mut props, "#ip");
576        assert!(ip.is_empty());
577        assert!(!props.contains_key("#ip"));
578    }
579
580    #[test]
581    fn user_add_rejects_non_numeric_values() {
582        let mut data = Data::new(DataType::UserAdd);
583        data.properties
584            .insert("level".to_string(), Value::String("10".to_string()));
585        assert!(matches!(
586            format_properties(&mut data, false),
587            Err(TDError::InvalidUserAddValue)
588        ));
589    }
590
591    #[test]
592    fn user_add_accepts_numeric_values() {
593        let mut data = Data::new(DataType::UserAdd);
594        data.properties.insert("level".to_string(), Value::from(10));
595        assert!(format_properties(&mut data, false).is_ok());
596    }
597
598    #[test]
599    fn stringent_mode_rejects_invalid_keys() {
600        let mut data = Data::new(DataType::Track);
601        data.event_name = "purchase".to_string();
602        data.properties
603            .insert("bad key".to_string(), Value::from(1));
604        assert!(matches!(
605            format_properties(&mut data, true),
606            Err(TDError::InvalidPropertyKey(_))
607        ));
608
609        let mut lenient = Data::new(DataType::Track);
610        lenient.event_name = "purchase".to_string();
611        lenient
612            .properties
613            .insert("bad key".to_string(), Value::from(1));
614        assert!(format_properties(&mut lenient, false).is_ok());
615    }
616
617    #[test]
618    fn invalid_event_name_is_rejected() {
619        let mut data = Data::new(DataType::Track);
620        data.event_name = "bad event".to_string();
621        assert!(matches!(
622            format_properties(&mut data, false),
623            Err(TDError::InvalidEventName(_))
624        ));
625    }
626
627    #[test]
628    fn extract_time_falls_back_to_now_for_unsupported_types() {
629        let mut props = Map::new();
630        props.insert("#time".to_string(), Value::from(123));
631        let time = extract_time(&mut props);
632        assert_eq!(time.len(), 23);
633    }
634
635    #[test]
636    fn stringent_format_properties_enforces_value_limits() {
637        let mut data = Data::new(DataType::Track);
638        data.event_name = "purchase".to_string();
639        data.properties
640            .insert("big".to_string(), Value::String("x".repeat(2 * 1024 + 1)));
641        assert!(format_properties(&mut data, false).is_ok());
642        assert!(format_properties(&mut data, true).is_err());
643    }
644}