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}
291
292impl Data {
293 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 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#[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#[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#[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#[cfg(any(feature = "blocking", feature = "async"))]
415pub(crate) fn apply_preset_properties(data: &mut Data, properties: &mut Map<String, Value>) {
416 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#[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}