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