Skip to main content

base/telemetry/
inventory.rs

1//! The event kinds as data, for the inventory in `docs/telemetry.md`.
2//!
3//! What each kind means is declared once, beside its constructor in
4//! `event_kinds!`; its fields are read off the payload type's JSON schema.
5//! [`render_markdown`] turns both into the table, and
6//! `crates/telemetry/tests/producers.rs` fails when the document and the code
7//! disagree.
8
9use serde_json::Value;
10
11/// Which file an event is written to.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum Recorded {
15    /// The session's own `telemetry/<session-id>.jsonl`.
16    Session,
17    /// The daemon's `telemetry/pool.jsonl`: things that happen to no session.
18    Pool,
19    /// Either, depending on where it was emitted.
20    Both,
21}
22
23impl Recorded {
24    fn label(self) -> &'static str {
25        match self {
26            Recorded::Session => "会话",
27            Recorded::Pool => "池",
28            Recorded::Both => "会话 / 池",
29        }
30    }
31}
32
33pub struct KindInfo {
34    pub kind: &'static str,
35    pub when: &'static str,
36    pub recorded: Recorded,
37    pub schema: fn() -> schemars::Schema,
38}
39
40impl KindInfo {
41    /// The payload's fields, sorted: `name`, `name?` when it can be absent or
42    /// `null`, and the values an enum field takes.
43    pub fn fields(&self) -> Vec<String> {
44        let schema = (self.schema)();
45        let root = schema.as_value();
46        let required: Vec<&str> = root["required"]
47            .as_array()
48            .map(|names| names.iter().filter_map(Value::as_str).collect())
49            .unwrap_or_default();
50        let Some(properties) = root["properties"].as_object() else {
51            return Vec::new();
52        };
53        let mut names: Vec<&String> = properties.keys().collect();
54        names.sort();
55        names
56            .into_iter()
57            .map(|name| {
58                let optional = if required.contains(&name.as_str()) {
59                    ""
60                } else {
61                    "?"
62                };
63                let values = enum_values(root, &properties[name]);
64                if values.is_empty() {
65                    format!("`{name}{optional}`")
66                } else {
67                    format!("`{name}{optional}`({})", values.join(" / "))
68                }
69            })
70            .collect()
71    }
72}
73
74fn enum_values(root: &Value, property: &Value) -> Vec<String> {
75    let resolved = match property["$ref"].as_str() {
76        Some(reference) => reference
77            .strip_prefix("#/$defs/")
78            .map(|name| &root["$defs"][name])
79            .unwrap_or(property),
80        None => property,
81    };
82    let quoted = |v: &Value| v.as_str().map(|s| format!("`{s}`"));
83    if let Some(values) = resolved["enum"].as_array() {
84        return values.iter().filter_map(quoted).collect();
85    }
86    resolved["oneOf"]
87        .as_array()
88        .map(|variants| {
89            variants
90                .iter()
91                .filter_map(|v| v.get("const").and_then(quoted))
92                .collect()
93        })
94        .unwrap_or_default()
95}
96
97/// The inventory table of `docs/telemetry.md`.
98pub fn render_markdown() -> String {
99    let mut out = String::new();
100    out.push_str("| `type` | 何时发 | 记在哪 | 字段(信封之外) |\n");
101    out.push_str("|---|---|---|---|\n");
102    for info in crate::telemetry::EventPayload::inventory() {
103        out.push_str(&format!(
104            "| `{}` | {} | {} | {} |\n",
105            info.kind,
106            info.when.trim(),
107            info.recorded.label(),
108            info.fields().join("、"),
109        ));
110    }
111    out
112}
113
114#[cfg(test)]
115mod tests {
116    #[test]
117    fn the_inventory_has_every_kind_in_order() {
118        let kinds: Vec<&str> = crate::telemetry::EventPayload::inventory()
119            .iter()
120            .map(|i| i.kind)
121            .collect();
122        assert_eq!(kinds, crate::telemetry::EventPayload::KINDS);
123    }
124
125    #[test]
126    fn every_kind_has_fields_and_says_when() {
127        for info in crate::telemetry::EventPayload::inventory() {
128            assert!(!info.when.trim().is_empty(), "{}", info.kind);
129            assert!(!info.fields().is_empty(), "{}", info.kind);
130        }
131    }
132
133    #[test]
134    fn enum_fields_list_their_values_and_optional_fields_say_so() {
135        let tool_execution = crate::telemetry::EventPayload::inventory()
136            .into_iter()
137            .find(|i| i.kind == "tool_execution")
138            .unwrap();
139        let fields = tool_execution.fields().join(" ");
140        assert!(
141            fields.contains("`outcome`(`approved` / `denied` / `succeeded`"),
142            "{fields}"
143        );
144        assert!(fields.contains("`error_message?`"), "{fields}");
145        assert!(fields.contains("`tool_name`"), "{fields}");
146    }
147}