1use 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
29pub const LIB_NAME: &str = "Rust";
31
32#[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
45pub 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
101pub fn is_preset_property(key: &str) -> bool {
103 PRESET_PROPERTIES.contains(&key)
104}
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
111pub enum DataType {
112 Track,
114 TrackUpdate,
116 TrackOverwrite,
118 UserSet,
120 UserUnset,
122 UserSetOnce,
124 UserAdd,
126 UserAppend,
128 UserUniqAppend,
130 UserDel,
132}
133
134impl DataType {
135 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 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
175pub trait IntoPropertyMap {
206 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#[derive(Debug, Clone, Serialize)]
247pub struct Data {
248 #[serde(rename = "#account_id", skip_serializing_if = "String::is_empty")]
250 pub account_id: String,
251 #[serde(rename = "#distinct_id", skip_serializing_if = "String::is_empty")]
253 pub distinct_id: String,
254 #[serde(rename = "#type")]
256 pub data_type: DataType,
257 #[serde(rename = "#time")]
259 pub time: String,
260 #[serde(rename = "#event_name", skip_serializing_if = "String::is_empty")]
262 pub event_name: String,
263 #[serde(rename = "#event_id", skip_serializing_if = "String::is_empty")]
265 pub event_id: String,
266 #[serde(rename = "#first_check_id", skip_serializing_if = "String::is_empty")]
268 pub first_check_id: String,
269 #[serde(rename = "#ip", skip_serializing_if = "String::is_empty")]
271 pub ip: String,
272 #[serde(rename = "#uuid", skip_serializing_if = "String::is_empty")]
274 pub uuid: String,
275 #[serde(rename = "#app_id", skip_serializing_if = "String::is_empty")]
277 pub app_id: String,
278 #[serde(
281 rename = "#transaction_property",
282 skip_serializing_if = "String::is_empty"
283 )]
284 pub transaction_property: String,
285 #[serde(rename = "#import_tool_id", skip_serializing_if = "String::is_empty")]
287 pub import_tool_id: String,
288 pub properties: Map<String, Value>,
290 #[cfg(any(feature = "blocking", feature = "async"))]
293 #[serde(skip)]
294 pub(crate) is_complex: bool,
295}
296
297impl Data {
298 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 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#[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#[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#[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 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#[cfg(any(feature = "blocking", feature = "async"))]
429pub(crate) fn apply_preset_properties(data: &mut Data, properties: &mut Map<String, Value>) {
430 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#[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}