1use 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
26pub const LIB_NAME: &str = "Rust";
28
29pub(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
41pub 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
97pub fn is_preset_property(key: &str) -> bool {
99 PRESET_PROPERTIES.contains(&key)
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
107pub enum DataType {
108 Track,
110 TrackUpdate,
112 TrackOverwrite,
114 UserSet,
116 UserUnset,
118 UserSetOnce,
120 UserAdd,
122 UserAppend,
124 UserUniqAppend,
126 UserDel,
128}
129
130impl DataType {
131 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 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
171pub trait IntoPropertyMap {
201 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#[derive(Debug, Clone, Serialize)]
242pub struct Data {
243 #[serde(rename = "#account_id", skip_serializing_if = "String::is_empty")]
245 pub account_id: String,
246 #[serde(rename = "#distinct_id", skip_serializing_if = "String::is_empty")]
248 pub distinct_id: String,
249 #[serde(rename = "#type")]
251 pub data_type: DataType,
252 #[serde(rename = "#time")]
254 pub time: String,
255 #[serde(rename = "#event_name", skip_serializing_if = "String::is_empty")]
257 pub event_name: String,
258 #[serde(rename = "#event_id", skip_serializing_if = "String::is_empty")]
260 pub event_id: String,
261 #[serde(rename = "#first_check_id", skip_serializing_if = "String::is_empty")]
263 pub first_check_id: String,
264 #[serde(rename = "#ip", skip_serializing_if = "String::is_empty")]
266 pub ip: String,
267 #[serde(rename = "#uuid", skip_serializing_if = "String::is_empty")]
269 pub uuid: String,
270 #[serde(rename = "#app_id", skip_serializing_if = "String::is_empty")]
272 pub app_id: String,
273 #[serde(
276 rename = "#transaction_property",
277 skip_serializing_if = "String::is_empty"
278 )]
279 pub transaction_property: String,
280 #[serde(rename = "#import_tool_id", skip_serializing_if = "String::is_empty")]
282 pub import_tool_id: String,
283 pub properties: Map<String, Value>,
285 #[serde(skip)]
288 pub(crate) is_complex: bool,
289}
290
291impl Data {
292 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 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
350pub(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
364pub(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
376pub(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 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
416pub(crate) fn apply_preset_properties(data: &mut Data, properties: &mut Map<String, Value>) {
419 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}