Skip to main content

sva_core/
json.rs

1// Concern: the JSON scalar, array and envelope-meta spellings every emitter agrees on | Non-concern: what any one object holds (output.rs, sva-analysis's json.rs) | IO: (a value) -> a fragment
2
3use std::sync::OnceLock;
4use std::sync::atomic::{AtomicU64, Ordering};
5
6#[cfg(not(target_arch = "wasm32"))]
7use std::time::{SystemTime, UNIX_EPOCH};
8
9/// One spelling, every emitter, wherever a declared key holds nothing.
10pub const NONE: &str = "null";
11
12pub fn escape(s: &str) -> String {
13    let mut out = String::with_capacity(s.len());
14    for c in s.chars() {
15        match c {
16            '"' => out.push_str("\\\""),
17            '\\' => out.push_str("\\\\"),
18            '\n' => out.push_str("\\n"),
19            '\r' => out.push_str("\\r"),
20            '\t' => out.push_str("\\t"),
21            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
22            c => out.push(c),
23        }
24    }
25    out
26}
27
28/// JSON has no NaN or infinity, so a measurement at one reads as `null`.
29pub fn num(v: f64) -> String {
30    if v.is_finite() {
31        format!("{v}")
32    } else {
33        NONE.to_string()
34    }
35}
36
37/// The `cli` standard's collection: `count` is the whole of it, `has_more` that `items` is
38/// not, and `next_cursor` a `--from` value the caller passes back for the rest.
39pub fn collection(
40    items: impl IntoIterator<Item = String>,
41    held: usize,
42    next: Option<String>,
43) -> String {
44    let written: Vec<String> = items.into_iter().collect();
45    let cursor = next
46        .as_ref()
47        .map_or_else(|| NONE.to_string(), |at| format!("\"{}\"", escape(at)));
48    format!(
49        "{{ \"items\": [{}], \"pagination\": {{ \"count\": {held}, \"has_more\": {}, \"next_cursor\": {cursor} }} }}",
50        written.join(", "),
51        next.is_some()
52    )
53}
54
55pub fn list<T>(items: &[T], f: impl Fn(&T) -> String) -> String {
56    collection(items.iter().map(f), items.len(), None)
57}
58
59/// `items` holds the first `shown`; `resumes_at` names the second the next one begins at.
60pub fn capped<T>(
61    items: &[T],
62    shown: usize,
63    resumes_at: impl Fn(usize) -> f64,
64    f: impl Fn(&T) -> String,
65) -> String {
66    let next = (shown < items.len()).then(|| format!("{}s", resumes_at(shown)));
67    collection(items[..shown].iter().map(f), items.len(), next)
68}
69
70pub fn strings(items: &[impl AsRef<str>]) -> String {
71    list(items, |s| format!("\"{}\"", escape(s.as_ref())))
72}
73
74#[cfg(not(target_arch = "wasm32"))]
75fn timestamp() -> u64 {
76    SystemTime::now()
77        .duration_since(UNIX_EPOCH)
78        .map(|d| d.as_secs())
79        .unwrap_or(0)
80}
81
82#[cfg(target_arch = "wasm32")]
83fn timestamp() -> u64 {
84    0
85}
86
87/// Nanoseconds and the process id part two runs inside one second; a wasm module has
88/// neither, and answers one page's sequence off the counter alone.
89fn origin() -> u64 {
90    #[cfg(not(target_arch = "wasm32"))]
91    {
92        let nanos = SystemTime::now()
93            .duration_since(UNIX_EPOCH)
94            .map(|d| d.as_nanos() as u64)
95            .unwrap_or(0);
96        nanos ^ ((std::process::id() as u64) << 40)
97    }
98    #[cfg(target_arch = "wasm32")]
99    {
100        0
101    }
102}
103
104/// So an agent can quote the response it is asking about.
105fn request_id() -> String {
106    static ORIGIN: OnceLock<u64> = OnceLock::new();
107    static ANSWERED: AtomicU64 = AtomicU64::new(0);
108    let n = ANSWERED.fetch_add(1, Ordering::Relaxed);
109    format!("req_{:016x}{n:06x}", ORIGIN.get_or_init(origin))
110}
111
112pub fn meta() -> String {
113    format!(
114        "{{ \"request_id\": \"{}\", \"timestamp\": {} }}",
115        request_id(),
116        timestamp()
117    )
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    #[test]
125    fn a_non_finite_measurement_reads_as_null_in_every_emitter() {
126        assert_eq!(num(0.5), "0.5");
127        assert_eq!(num(f64::NAN), "null");
128        assert_eq!(num(f64::INFINITY), "null");
129        assert_eq!(num(f64::NEG_INFINITY), "null");
130    }
131
132    #[test]
133    fn a_control_character_is_escaped_rather_than_emitted_raw() {
134        assert_eq!(escape("a\"b\\c\nd\u{1}"), "a\\\"b\\\\c\\nd\\u0001");
135    }
136
137    #[test]
138    fn every_response_carries_its_own_request_id_beside_the_timestamp() {
139        let (first, second) = (meta(), meta());
140        assert!(first.contains("\"request_id\": \"req_"), "{first}");
141        assert!(first.contains("\"timestamp\": "), "{first}");
142        assert_ne!(first, second, "two responses are never the same request");
143    }
144
145    #[test]
146    fn the_origin_carries_more_than_the_whole_second_two_runs_would_share() {
147        let (a, b) = (origin(), origin());
148        assert_ne!(a, b, "the origin carries more than whole seconds");
149    }
150
151    #[test]
152    fn an_empty_collection_is_an_empty_items_list_with_a_zero_count() {
153        assert!(list(&[] as &[f64], |v| num(*v)).contains("\"items\": []"));
154        assert!(strings(&[] as &[&str]).contains("\"count\": 0"));
155        assert!(strings(&["a", "b\"c"]).contains("[\"a\", \"b\\\"c\"]"));
156        let cut = capped(&[1.0, 2.0, 3.0], 2, |n| n as f64 / 4.0, |v| num(*v));
157        assert!(
158            cut.contains("\"count\": 3") && cut.contains("\"has_more\": true"),
159            "{cut}"
160        );
161        assert!(
162            cut.contains("\"items\": [1, 2]"),
163            "the page, not the whole: {cut}"
164        );
165        assert!(
166            cut.contains("\"next_cursor\": \"0.5s\""),
167            "a `--from` value: {cut}"
168        );
169    }
170}