Skip to main content

thinkingdata_core/
utils.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//! Time and validation helpers shared by the analytics facade and consumers.
16//!
17//! All timestamps are produced with the [`jiff`] crate (the successor of
18//! chrono, which is deliberately not used anywhere in this workspace).
19
20use std::sync::OnceLock;
21
22use regex::Regex;
23
24use crate::error::Result;
25
26/// Time-of-day pattern for the `#time` wire format; milliseconds are appended
27/// separately so the output is exactly `yyyy-MM-dd HH:mm:ss.SSS` (local time).
28const CLOCK_FORMAT: &str = "%Y-%m-%d %H:%M:%S";
29
30/// The timestamp rewrite applied to serialized payloads, ported from the Go
31/// SDK: RFC 3339 timestamps embedded anywhere in a JSON payload are rewritten
32/// to the `yyyy-MM-dd HH:mm:ss.SSS` form the receiver expects.
33const TIME_PATTERN: &str =
34    r#""((\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})(?:\.(\d{3}))\d*)(Z|[+\-]\d{2}:\d{2})""#;
35
36fn time_regex() -> &'static Regex {
37    static TIME_RE: OnceLock<Regex> = OnceLock::new();
38    TIME_RE.get_or_init(|| Regex::new(TIME_PATTERN).expect("valid timestamp regex"))
39}
40
41/// Check that an event name or property key matches
42/// `^[a-zA-Z#][A-Za-z0-9_]{0,49}$` — a 1..=50 character identifier starting
43/// with a letter or `#`.
44///
45/// ```
46/// use thinkingdata_core::utils::is_valid_key;
47///
48/// assert!(is_valid_key("product_name"));
49/// assert!(is_valid_key("#lib"));
50/// assert!(!is_valid_key("9invalid"));
51/// ```
52pub fn is_valid_key(key: &str) -> bool {
53    let mut chars = key.chars();
54    match chars.next() {
55        Some(first) if first.is_ascii_alphabetic() || first == '#' => {}
56        _ => return false,
57    }
58    let mut length = 1usize;
59    for ch in chars {
60        if !(ch.is_ascii_alphanumeric() || ch == '_') {
61            return false;
62        }
63        length += 1;
64        if length > 50 {
65            return false;
66        }
67    }
68    true
69}
70
71/// Rewrite RFC 3339 timestamps inside a serialized JSON payload to
72/// `"yyyy-MM-dd HH:mm:ss.SSS"`, mirroring the Go SDK's `parseTime`.
73///
74/// ```
75/// use thinkingdata_core::utils::parse_time;
76///
77/// let payload = r##"{"#time":"2024-01-02T03:04:05.123456+08:00"}"##;
78/// assert!(parse_time(payload).contains(r#""2024-01-02 03:04:05.123""#));
79/// ```
80pub fn parse_time(payload: &str) -> String {
81    let re = time_regex();
82    if !re.is_match(payload) {
83        return payload.to_string();
84    }
85    let mut current = payload.to_string();
86    loop {
87        let next = re.replace_all(&current, "\"$2 $3.$4\"").into_owned();
88        if next == current {
89            return next;
90        }
91        current = next;
92    }
93}
94
95/// Current local time formatted as `yyyy-MM-dd HH:mm:ss.SSS`.
96pub(crate) fn format_now() -> String {
97    let zoned = jiff::ZonedDateTime::now();
98    let millis = zoned.timestamp().subsec_nanosecond() / 1_000_000;
99    format!("{}.{millis:03}", zoned.strftime(CLOCK_FORMAT))
100}
101
102/// Current local time formatted with an arbitrary jiff `strftime` pattern.
103pub(crate) fn format_with(pattern: &str) -> String {
104    jiff::ZonedDateTime::now().strftime(pattern).to_string()
105}
106
107/// Generate a random (v4) UUID string for the `#uuid` field.
108pub(crate) fn generate_uuid() -> String {
109    uuid::Uuid::new_v4().to_string()
110}
111
112/// Documented property limits from the TE v5.0 data rules.
113pub mod limits {
114    /// Maximum byte length of a string property value (2 KB).
115    pub const MAX_STRING_BYTES: usize = 2 * 1024;
116    /// Maximum absolute value of a numeric property (±9E15).
117    pub const MAX_NUMBER_ABS: f64 = 9e15;
118    /// Maximum number of elements in a list or object-group property (500).
119    pub const MAX_ARRAY_ELEMENTS: usize = 500;
120    /// Maximum byte length of a list element after string conversion (255).
121    pub const MAX_ARRAY_ELEMENT_BYTES: usize = 255;
122    /// Maximum number of sub-properties inside an object property (100).
123    pub const MAX_OBJECT_KEYS: usize = 100;
124    /// Maximum length of `#account_id` / `#distinct_id` (128 characters).
125    pub const MAX_ID_LENGTH: usize = 128;
126}
127
128fn time_format_regex() -> &'static Regex {
129    static RE: OnceLock<Regex> = OnceLock::new();
130    RE.get_or_init(|| {
131        Regex::new(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(\.\d{3})?$").expect("valid time regex")
132    })
133}
134
135/// Whether `value` matches the `#time` formats documented in the data rules:
136/// `yyyy-MM-dd HH:mm:ss` or `yyyy-MM-dd HH:mm:ss.SSS`.
137///
138/// ```
139/// use thinkingdata_core::utils::is_documented_time_format;
140///
141/// assert!(is_documented_time_format("2026-11-17 09:30:00"));
142/// assert!(is_documented_time_format("2026-11-17 09:30:00.123"));
143/// assert!(!is_documented_time_format("2026-11-17T09:30:00Z"));
144/// ```
145pub fn is_documented_time_format(value: &str) -> bool {
146    time_format_regex().is_match(value)
147}
148
149/// Validate one property value against the documented v5.0 type limits.
150///
151/// The receiver silently drops values that break these limits (keeping the
152/// rest of the event), so this check is most useful before submitting data:
153/// the debug consumer runs it in stringent mode via
154/// [`Data::check_limits`](crate::data::Data::check_limits).
155///
156/// Rules enforced:
157///
158/// - string ≤ [`limits::MAX_STRING_BYTES`] (2 KB)
159/// - number within ±[`limits::MAX_NUMBER_ABS`] (9E15)
160/// - list / object group ≤ [`limits::MAX_ARRAY_ELEMENTS`] (500 elements);
161///   string elements ≤ [`limits::MAX_ARRAY_ELEMENT_BYTES`] (255 bytes after
162///   the receiver's string conversion); nested objects are validated too
163/// - object ≤ [`limits::MAX_OBJECT_KEYS`] (100 sub-properties), validated
164///   recursively
165///
166/// `key` is used to build the error message.
167pub fn check_value_limits(key: &str, value: &serde_json::Value) -> Result<()> {
168    use limits::{
169        MAX_ARRAY_ELEMENT_BYTES, MAX_ARRAY_ELEMENTS, MAX_NUMBER_ABS, MAX_OBJECT_KEYS,
170        MAX_STRING_BYTES,
171    };
172    use serde_json::Value;
173
174    let over_limit = |detail: String| {
175        Err(crate::error::TDError::msg(format!(
176            "property {key}: {detail}"
177        )))
178    };
179
180    match value {
181        Value::String(text) => {
182            if text.len() > MAX_STRING_BYTES {
183                return over_limit(format!("string value exceeds {MAX_STRING_BYTES} bytes"));
184            }
185        }
186        Value::Number(number) => {
187            let magnitude = number.as_f64().unwrap_or(f64::INFINITY).abs();
188            if magnitude > MAX_NUMBER_ABS {
189                return over_limit(format!("number value exceeds ±{MAX_NUMBER_ABS}"));
190            }
191        }
192        Value::Array(items) => {
193            if items.len() > MAX_ARRAY_ELEMENTS {
194                return over_limit(format!(
195                    "list has {} elements, limit is {MAX_ARRAY_ELEMENTS}",
196                    items.len()
197                ));
198            }
199            for item in items {
200                match item {
201                    Value::String(text) => {
202                        if text.len() > MAX_ARRAY_ELEMENT_BYTES {
203                            return over_limit(format!(
204                                "list element exceeds {MAX_ARRAY_ELEMENT_BYTES} bytes"
205                            ));
206                        }
207                    }
208                    Value::Object(_) => check_value_limits(key, item)?,
209                    _ => {}
210                }
211            }
212        }
213        Value::Object(entries) => {
214            if entries.len() > MAX_OBJECT_KEYS {
215                return over_limit(format!(
216                    "object has {} sub-properties, limit is {MAX_OBJECT_KEYS}",
217                    entries.len()
218                ));
219            }
220            for (sub_key, sub_value) in entries {
221                check_value_limits(&format!("{key}.{sub_key}"), sub_value)?;
222            }
223        }
224        Value::Null | Value::Bool(_) => {}
225    }
226    Ok(())
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232
233    #[test]
234    fn key_validation_matches_go_pattern() {
235        assert!(is_valid_key("a"));
236        assert!(is_valid_key("#lib"));
237        assert!(is_valid_key("product_name"));
238        assert!(is_valid_key("A9_"));
239        assert!(!is_valid_key(""));
240        assert!(!is_valid_key("9abc"));
241        assert!(!is_valid_key("_abc"));
242        assert!(!is_valid_key("has space"));
243        assert!(!is_valid_key("has-dash"));
244        assert!(!is_valid_key("中文"));
245        assert!(!is_valid_key(&"a".repeat(51)));
246        assert!(is_valid_key(&"a".repeat(50)));
247    }
248
249    #[test]
250    fn parse_time_rewrites_rfc3339_timestamps() {
251        let input = r##"{"#time":"2024-01-02T03:04:05.123456+08:00","x":1}"##;
252        let output = parse_time(input);
253        assert!(output.contains(r#""2024-01-02 03:04:05.123""#), "{output}");
254
255        // No fractional seconds: the pattern requires `.ddd`, so it is left alone.
256        let no_millis = r##"{"#time":"2024-01-02T03:04:05Z"}"##;
257        assert_eq!(parse_time(no_millis), no_millis);
258
259        // Plain payloads pass through untouched.
260        assert_eq!(parse_time("hello"), "hello");
261    }
262
263    #[test]
264    fn format_now_matches_wire_format() {
265        let ts = format_now();
266        // yyyy-MM-dd HH:mm:ss.SSS => 23 characters
267        assert_eq!(ts.len(), 23, "{ts}");
268        assert_eq!(ts.as_bytes()[10], b' ');
269        assert_eq!(ts.as_bytes()[19], b'.');
270    }
271
272    #[test]
273    fn documented_time_format_detection() {
274        assert!(is_documented_time_format("2026-11-17 09:30:00"));
275        assert!(is_documented_time_format("2026-11-17 09:30:00.123"));
276        assert!(!is_documented_time_format("2026-11-17T09:30:00Z"));
277        assert!(!is_documented_time_format("2026-11-17"));
278        assert!(!is_documented_time_format("2026-11-17 09:30:00.123456"));
279    }
280
281    #[test]
282    fn value_limits_follow_the_documented_rules() {
283        use serde_json::json;
284
285        // Strings over 2 KB are rejected.
286        let err = check_value_limits("text", &json!("x".repeat(2 * 1024 + 1))).unwrap_err();
287        assert!(err.to_string().contains("2048 bytes"), "{err}");
288        assert!(check_value_limits("text", &json!("x".repeat(2 * 1024))).is_ok());
289
290        // Numbers beyond ±9E15 are rejected.
291        let err = check_value_limits("num", &json!(9.1e15)).unwrap_err();
292        assert!(
293            err.to_string().contains("9E15") || err.to_string().contains("9000000000000000"),
294            "{err}"
295        );
296        assert!(check_value_limits("num", &json!(9e15)).is_ok());
297
298        // Lists are limited to 500 elements, string elements to 255 bytes.
299        let big: Vec<_> = (0..501).map(|i| json!(i)).collect();
300        let err = check_value_limits("list", &json!(big)).unwrap_err();
301        assert!(err.to_string().contains("500"), "{err}");
302        let err = check_value_limits("list", &json!(["x".repeat(256)])).unwrap_err();
303        assert!(err.to_string().contains("255 bytes"), "{err}");
304        assert!(check_value_limits("list", &json!(["a", "b"])).is_ok());
305
306        // Objects are limited to 100 sub-properties, validated recursively.
307        let mut object = serde_json::Map::new();
308        for i in 0..101 {
309            object.insert(format!("k{i}"), json!(i));
310        }
311        let err = check_value_limits("obj", &serde_json::Value::Object(object)).unwrap_err();
312        assert!(err.to_string().contains("100"), "{err}");
313        let err = check_value_limits(
314            "obj",
315            &json!({ "nested": { "deep": "x".repeat(2 * 1024 + 1) } }),
316        )
317        .unwrap_err();
318        assert!(err.to_string().contains("obj.nested.deep"), "{err}");
319
320        // Nulls and booleans always pass.
321        assert!(check_value_limits("ok", &serde_json::Value::Null).is_ok());
322        assert!(check_value_limits("ok", &json!(true)).is_ok());
323    }
324}