use std::collections::{BTreeMap, HashMap};
use serde::Serialize;
use serde_json::{Map, Value};
use crate::error::{Result, TDError};
use crate::log::td_log_error;
use crate::utils::{format_now, generate_uuid, is_valid_key};
pub const LIB_NAME: &str = "Rust";
pub(crate) const PRESET_KEYS: [&str; 7] = [
"#ip",
"#app_id",
"#time",
"#first_check_id",
"#uuid",
"#transaction_property",
"#import_tool_id",
];
pub const PRESET_PROPERTIES: [&str; 48] = [
"#ip",
"#country",
"#country_code",
"#province",
"#city",
"#os_version",
"#manufacturer",
"#os",
"#device_id",
"#screen_height",
"#screen_width",
"#device_model",
"#device_type",
"#app_version",
"#bundle_id",
"#lib",
"#lib_version",
"#network_type",
"#carrier",
"#browser",
"#browser_version",
"#duration",
"#url",
"#url_path",
"#referrer",
"#referrer_host",
"#title",
"#screen_name",
"#element_id",
"#element_type",
"#resume_from_background",
"#element_selector",
"#element_position",
"#element_content",
"#scene",
"#mp_platform",
"#app_crashed_reason",
"#zone_offset",
"#system_language",
"#install_time",
"#simulator",
"#ram",
"#disk",
"#fps",
"#background_duration",
"#start_reason",
"#ua",
"#utm",
];
pub fn is_preset_property(key: &str) -> bool {
PRESET_PROPERTIES.contains(&key)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DataType {
Track,
TrackUpdate,
TrackOverwrite,
UserSet,
UserUnset,
UserSetOnce,
UserAdd,
UserAppend,
UserUniqAppend,
UserDel,
}
impl DataType {
pub const fn as_str(self) -> &'static str {
match self {
DataType::Track => "track",
DataType::TrackUpdate => "track_update",
DataType::TrackOverwrite => "track_overwrite",
DataType::UserSet => "user_set",
DataType::UserUnset => "user_unset",
DataType::UserSetOnce => "user_setOnce",
DataType::UserAdd => "user_add",
DataType::UserAppend => "user_append",
DataType::UserUniqAppend => "user_uniq_append",
DataType::UserDel => "user_del",
}
}
pub const fn is_track(self) -> bool {
matches!(
self,
DataType::Track | DataType::TrackUpdate | DataType::TrackOverwrite
)
}
}
impl std::fmt::Display for DataType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl Serialize for DataType {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
pub trait IntoPropertyMap {
fn into_property_map(self) -> Result<Map<String, Value>>;
}
impl IntoPropertyMap for Map<String, Value> {
fn into_property_map(self) -> Result<Map<String, Value>> {
Ok(self)
}
}
impl IntoPropertyMap for HashMap<String, Value> {
fn into_property_map(self) -> Result<Map<String, Value>> {
Ok(self.into_iter().collect())
}
}
impl IntoPropertyMap for BTreeMap<String, Value> {
fn into_property_map(self) -> Result<Map<String, Value>> {
Ok(self.into_iter().collect())
}
}
impl IntoPropertyMap for Value {
fn into_property_map(self) -> Result<Map<String, Value>> {
match self {
Value::Object(map) => Ok(map),
_ => Err(TDError::msg(
"properties must be a JSON object of string keys",
)),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct Data {
#[serde(rename = "#account_id", skip_serializing_if = "String::is_empty")]
pub account_id: String,
#[serde(rename = "#distinct_id", skip_serializing_if = "String::is_empty")]
pub distinct_id: String,
#[serde(rename = "#type")]
pub data_type: DataType,
#[serde(rename = "#time")]
pub time: String,
#[serde(rename = "#event_name", skip_serializing_if = "String::is_empty")]
pub event_name: String,
#[serde(rename = "#event_id", skip_serializing_if = "String::is_empty")]
pub event_id: String,
#[serde(rename = "#first_check_id", skip_serializing_if = "String::is_empty")]
pub first_check_id: String,
#[serde(rename = "#ip", skip_serializing_if = "String::is_empty")]
pub ip: String,
#[serde(rename = "#uuid", skip_serializing_if = "String::is_empty")]
pub uuid: String,
#[serde(rename = "#app_id", skip_serializing_if = "String::is_empty")]
pub app_id: String,
#[serde(
rename = "#transaction_property",
skip_serializing_if = "String::is_empty"
)]
pub transaction_property: String,
#[serde(rename = "#import_tool_id", skip_serializing_if = "String::is_empty")]
pub import_tool_id: String,
pub properties: Map<String, Value>,
#[serde(skip)]
pub(crate) is_complex: bool,
}
impl Data {
pub fn new(data_type: DataType) -> Self {
Self {
account_id: String::new(),
distinct_id: String::new(),
data_type,
time: format_now(),
event_name: String::new(),
event_id: String::new(),
first_check_id: String::new(),
ip: String::new(),
uuid: String::new(),
app_id: String::new(),
transaction_property: String::new(),
import_tool_id: String::new(),
properties: Map::new(),
is_complex: false,
}
}
pub fn check_limits(&self) -> Result<()> {
if !crate::utils::is_documented_time_format(&self.time) {
return Err(TDError::msg(format!(
"invalid #time {:?}: expected \"yyyy-MM-dd HH:mm:ss\" or \"yyyy-MM-dd HH:mm:ss.SSS\"",
self.time
)));
}
const MAX_ID_LENGTH: usize = 128;
if self.account_id.len() > MAX_ID_LENGTH {
return Err(TDError::msg(format!(
"#account_id exceeds {MAX_ID_LENGTH} characters"
)));
}
if self.distinct_id.len() > MAX_ID_LENGTH {
return Err(TDError::msg(format!(
"#distinct_id exceeds {MAX_ID_LENGTH} characters"
)));
}
for (key, value) in &self.properties {
crate::utils::check_value_limits(key, value)?;
}
Ok(())
}
}
pub(crate) fn extract_string_property(properties: &mut Map<String, Value>, key: &str) -> String {
match properties.remove(key) {
Some(Value::String(value)) => value,
Some(_) => {
td_log_error(&format!("Invalid data type for {key}"));
String::new()
}
None => String::new(),
}
}
pub(crate) fn extract_time(properties: &mut Map<String, Value>) -> String {
match properties.remove("#time") {
Some(Value::String(value)) if !value.is_empty() => value,
Some(_) => format_now(),
None => format_now(),
}
}
pub(crate) fn format_properties(data: &mut Data, stringent: bool) -> Result<()> {
if !data.event_name.is_empty() && !is_valid_key(&data.event_name) {
let message = format!("invalid event name: {}", data.event_name);
crate::log::td_log_info(&message);
return Err(TDError::InvalidEventName(data.event_name.clone()));
}
for (key, value) in &data.properties {
if stringent && !is_valid_key(key) {
let message = format!("invalid property key: {key}");
crate::log::td_log_info(&message);
return Err(TDError::InvalidPropertyKey(key.clone()));
}
if data.data_type == DataType::UserAdd && !value.is_number() {
crate::log::td_log_info("invalid property value: only numbers is supported by UserAdd");
return Err(TDError::InvalidUserAddValue);
}
match value {
Value::Number(_) | Value::Bool(_) | Value::String(_) => {}
_ => data.is_complex = true,
}
}
if stringent {
data.check_limits()?;
}
Ok(())
}
pub(crate) fn apply_preset_properties(data: &mut Data, properties: &mut Map<String, Value>) {
debug_assert!(PRESET_KEYS.contains(&"#ip"));
data.ip = extract_string_property(properties, "#ip");
data.app_id = extract_string_property(properties, "#app_id");
data.time = extract_time(properties);
data.first_check_id = extract_string_property(properties, "#first_check_id");
data.transaction_property = extract_string_property(properties, "#transaction_property");
data.import_tool_id = extract_string_property(properties, "#import_tool_id");
let mut uuid = extract_string_property(properties, "#uuid");
if uuid.is_empty() {
uuid = generate_uuid();
}
data.uuid = uuid;
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_properties() -> Map<String, Value> {
let mut props = Map::new();
props.insert("string".to_string(), Value::String("v".to_string()));
props.insert("number".to_string(), Value::from(1));
props.insert("bool".to_string(), Value::Bool(true));
props
}
#[test]
fn data_serializes_wire_field_names() {
let mut data = Data::new(DataType::Track);
data.account_id = "acc".to_string();
data.event_name = "purchase".to_string();
data.properties = sample_properties();
let json = serde_json::to_value(&data).unwrap();
let obj = json.as_object().unwrap();
assert_eq!(obj["#account_id"], "acc");
assert_eq!(obj["#type"], "track");
assert!(obj.get("#distinct_id").is_none());
assert!(obj.get("#event_id").is_none());
assert!(obj["#time"].as_str().unwrap().contains('.'));
assert!(
obj["properties"]
.as_object()
.unwrap()
.contains_key("string")
);
}
#[test]
fn user_del_serializes_empty_properties() {
let data = Data::new(DataType::UserDel);
let json = serde_json::to_value(&data).unwrap();
let obj = json.as_object().unwrap();
assert_eq!(obj["#type"], "user_del");
assert!(obj["properties"].as_object().unwrap().is_empty());
}
#[test]
fn preset_keys_are_hoisted_into_fields() {
let mut data = Data::new(DataType::Track);
data.event_name = "login".to_string();
let mut props = sample_properties();
props.insert("#ip".to_string(), Value::String("1.2.3.4".to_string()));
props.insert(
"#time".to_string(),
Value::String("2024-01-02 03:04:05.123".to_string()),
);
props.insert("#uuid".to_string(), Value::String("fixed-uuid".to_string()));
apply_preset_properties(&mut data, &mut props);
assert_eq!(data.ip, "1.2.3.4");
assert_eq!(data.time, "2024-01-02 03:04:05.123");
assert_eq!(data.uuid, "fixed-uuid");
assert!(!props.contains_key("#ip"));
assert!(!props.contains_key("#time"));
assert!(!props.contains_key("#uuid"));
}
#[test]
fn missing_uuid_is_generated() {
let mut data = Data::new(DataType::Track);
let mut props = sample_properties();
apply_preset_properties(&mut data, &mut props);
assert!(!data.uuid.is_empty());
}
#[test]
fn non_string_preset_value_is_dropped() {
let mut props = Map::new();
props.insert("#ip".to_string(), Value::from(123));
let ip = extract_string_property(&mut props, "#ip");
assert!(ip.is_empty());
assert!(!props.contains_key("#ip"));
}
#[test]
fn user_add_rejects_non_numeric_values() {
let mut data = Data::new(DataType::UserAdd);
data.properties
.insert("level".to_string(), Value::String("10".to_string()));
assert!(matches!(
format_properties(&mut data, false),
Err(TDError::InvalidUserAddValue)
));
}
#[test]
fn user_add_accepts_numeric_values() {
let mut data = Data::new(DataType::UserAdd);
data.properties.insert("level".to_string(), Value::from(10));
assert!(format_properties(&mut data, false).is_ok());
}
#[test]
fn stringent_mode_rejects_invalid_keys() {
let mut data = Data::new(DataType::Track);
data.event_name = "purchase".to_string();
data.properties
.insert("bad key".to_string(), Value::from(1));
assert!(matches!(
format_properties(&mut data, true),
Err(TDError::InvalidPropertyKey(_))
));
let mut lenient = Data::new(DataType::Track);
lenient.event_name = "purchase".to_string();
lenient
.properties
.insert("bad key".to_string(), Value::from(1));
assert!(format_properties(&mut lenient, false).is_ok());
}
#[test]
fn invalid_event_name_is_rejected() {
let mut data = Data::new(DataType::Track);
data.event_name = "bad event".to_string();
assert!(matches!(
format_properties(&mut data, false),
Err(TDError::InvalidEventName(_))
));
}
#[test]
fn complex_values_are_flagged() {
let mut data = Data::new(DataType::Track);
data.event_name = "purchase".to_string();
data.properties
.insert("array".to_string(), serde_json::json!(["a", "b"]));
format_properties(&mut data, false).unwrap();
assert!(data.is_complex);
}
#[test]
fn extract_time_falls_back_to_now_for_unsupported_types() {
let mut props = Map::new();
props.insert("#time".to_string(), Value::from(123));
let time = extract_time(&mut props);
assert_eq!(time.len(), 23);
}
#[test]
fn data_type_wire_values() {
assert_eq!(DataType::Track.as_str(), "track");
assert_eq!(DataType::UserSetOnce.as_str(), "user_setOnce");
assert_eq!(DataType::UserUniqAppend.as_str(), "user_uniq_append");
assert!(DataType::TrackUpdate.is_track());
assert!(!DataType::UserSet.is_track());
}
#[test]
fn preset_property_catalog_matches_the_documented_list() {
assert_eq!(PRESET_PROPERTIES.len(), 48);
assert!(is_preset_property("#lib"));
assert!(is_preset_property("#utm"));
assert!(is_preset_property("#country_code"));
assert!(!is_preset_property("#not_a_preset"));
assert!(!is_preset_property("custom_property"));
}
#[test]
fn check_limits_accepts_a_well_formed_snapshot() {
let mut data = Data::new(DataType::Track);
data.account_id = "acc".to_string();
data.event_name = "purchase".to_string();
data.properties = sample_properties();
assert!(data.check_limits().is_ok());
}
#[test]
fn check_limits_rejects_malformed_time() {
let mut data = Data::new(DataType::Track);
data.time = "2024-01-02T03:04:05Z".to_string();
let err = data.check_limits().unwrap_err();
assert!(err.to_string().contains("#time"), "{err}");
}
#[test]
fn check_limits_rejects_oversized_ids() {
let mut data = Data::new(DataType::Track);
data.account_id = "a".repeat(129);
let err = data.check_limits().unwrap_err();
assert!(err.to_string().contains("#account_id"), "{err}");
let mut data = Data::new(DataType::Track);
data.distinct_id = "d".repeat(129);
let err = data.check_limits().unwrap_err();
assert!(err.to_string().contains("#distinct_id"), "{err}");
}
#[test]
fn check_limits_rejects_values_over_documented_limits() {
let mut data = Data::new(DataType::Track);
data.properties
.insert("big".to_string(), Value::String("x".repeat(2 * 1024 + 1)));
let err = data.check_limits().unwrap_err();
assert!(err.to_string().contains("big"), "{err}");
}
#[test]
fn stringent_format_properties_enforces_value_limits() {
let mut data = Data::new(DataType::Track);
data.event_name = "purchase".to_string();
data.properties
.insert("big".to_string(), Value::String("x".repeat(2 * 1024 + 1)));
assert!(format_properties(&mut data, false).is_ok());
assert!(format_properties(&mut data, true).is_err());
}
}