Skip to main content

trumly_fs/
telemetry.rs

1//! Anonymous usage data, off until the person says yes.
2//!
3//! What is kept: a random install id, the version, the OS, the name of what was done (`pack_added`, `check_run`) and
4//! rounded counts. Never ids, titles, field values, file paths or model content. Everything is written to a local queue
5//! first so `trumly telemetry show` can display exactly what would be sent; sending is done elsewhere (the editor, or
6//! nothing at all) and a down endpoint costs nothing but a retry later.
7//!
8//! State lives in `~/.trumly/telemetry.json` (or `$TRUMLY_HOME`). `DO_NOT_TRACK=1` or `TRUMLY_TELEMETRY=off` always wins.
9
10use std::fs;
11use std::io::Write;
12use std::path::PathBuf;
13
14use serde_json::{json, Value};
15
16/// Where trumly keeps per-user files: `$TRUMLY_HOME`, else `~/.trumly`.
17pub fn trumly_home() -> Option<PathBuf> {
18    if let Some(h) = std::env::var_os("TRUMLY_HOME") {
19        return Some(PathBuf::from(h));
20    }
21    std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(|h| PathBuf::from(h).join(".trumly"))
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum State {
26    /// never asked: nothing is recorded, and the editor should ask
27    Unset,
28    On,
29    Off,
30}
31
32impl State {
33    pub fn as_str(self) -> &'static str {
34        match self {
35            State::Unset => "unset",
36            State::On => "on",
37            State::Off => "off",
38        }
39    }
40    pub fn parse(s: &str) -> Option<State> {
41        match s {
42            "unset" => Some(State::Unset),
43            "on" => Some(State::On),
44            "off" => Some(State::Off),
45            _ => None,
46        }
47    }
48}
49
50fn config_path() -> Option<PathBuf> {
51    trumly_home().map(|h| h.join("telemetry.json"))
52}
53
54fn queue_path() -> Option<PathBuf> {
55    trumly_home().map(|h| h.join("telemetry-queue.jsonl"))
56}
57
58fn read_config() -> Value {
59    config_path().and_then(|p| fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_else(|| json!({}))
60}
61
62/// Switched off from outside, whatever the file says.
63pub fn forced_off() -> bool {
64    std::env::var("DO_NOT_TRACK").is_ok_and(|v| !v.is_empty() && v != "0") || std::env::var("TRUMLY_TELEMETRY").is_ok_and(|v| v.eq_ignore_ascii_case("off"))
65}
66
67/// What the person chose (ignoring the environment overrides).
68pub fn chosen() -> State {
69    read_config().get("state").and_then(Value::as_str).and_then(State::parse).unwrap_or(State::Unset)
70}
71
72/// What is in force: `Off` when forced off.
73pub fn state() -> State {
74    if forced_off() {
75        State::Off
76    } else {
77        chosen()
78    }
79}
80
81/// A random id for this install. Made only when someone turns telemetry on.
82fn new_install_id() -> String {
83    let mut bytes = [0u8; 16];
84    let ok = fs::File::open("/dev/urandom").and_then(|mut f| std::io::Read::read_exact(&mut f, &mut bytes)).is_ok();
85    if !ok {
86        use std::hash::{BuildHasher, Hasher};
87        let mut h = std::collections::hash_map::RandomState::new().build_hasher();
88        h.write_u128(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()));
89        h.write_u32(std::process::id());
90        let a = h.finish();
91        h.write_u64(a);
92        bytes[..8].copy_from_slice(&a.to_le_bytes());
93        bytes[8..].copy_from_slice(&h.finish().to_le_bytes());
94    }
95    bytes.iter().map(|b| format!("{b:02x}")).collect()
96}
97
98/// The install id, if telemetry has been turned on at some point.
99pub fn install_id() -> Option<String> {
100    read_config().get("install").and_then(Value::as_str).map(str::to_string)
101}
102
103/// Where events go: `$TRUMLY_TELEMETRY_URL`, else `endpoint` in the config file, else nowhere (they stay local).
104pub fn endpoint() -> Option<String> {
105    std::env::var("TRUMLY_TELEMETRY_URL").ok().filter(|s| !s.is_empty()).or_else(|| read_config().get("endpoint").and_then(Value::as_str).map(str::to_string))
106}
107
108pub fn set_state(s: State) -> Result<(), String> {
109    let path = config_path().ok_or("no home folder")?;
110    let mut cfg = read_config();
111    if !cfg.is_object() {
112        cfg = json!({});
113    }
114    cfg["state"] = json!(s.as_str());
115    if s == State::On && cfg.get("install").and_then(Value::as_str).is_none() {
116        cfg["install"] = json!(new_install_id());
117    }
118    if s == State::Off {
119        // turning it off also forgets the id and anything not yet sent
120        if let Some(o) = cfg.as_object_mut() {
121            o.remove("install");
122        }
123        if let Some(q) = queue_path() {
124            let _ = fs::remove_file(q);
125        }
126    }
127    fs::create_dir_all(path.parent().unwrap()).map_err(|e| format!("cannot create {}: {e}", path.parent().unwrap().display()))?;
128    fs::write(&path, serde_json::to_string_pretty(&cfg).unwrap()).map_err(|e| format!("cannot write {}: {e}", path.display()))
129}
130
131/// `2026-10-21T17:40:00Z`, rounded down to the minute.
132pub fn now_iso() -> String {
133    let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
134    let (days, rem) = ((secs / 86400) as i64, secs % 86400);
135    // civil-from-days (Howard Hinnant)
136    let z = days + 719_468;
137    let era = z.div_euclid(146_097);
138    let doe = z.rem_euclid(146_097);
139    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
140    let y = yoe + era * 400;
141    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
142    let mp = (5 * doy + 2) / 153;
143    let d = doy - (153 * mp + 2) / 5 + 1;
144    let m = if mp < 10 { mp + 3 } else { mp - 9 };
145    let y = if m <= 2 { y + 1 } else { y };
146    format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:00Z", rem / 3600, rem % 3600 / 60)
147}
148
149/// A count rounded into a band, so the number itself says little.
150pub fn bucket(n: usize) -> &'static str {
151    match n {
152        0 => "0",
153        1..=9 => "1-9",
154        10..=49 => "10-49",
155        50..=199 => "50-199",
156        _ => "200+",
157    }
158}
159
160/// The event as it would be sent.
161pub fn event(name: &str, src: &str, props: Value) -> Option<Value> {
162    Some(json!({"event": name, "ts": now_iso(), "install": install_id()?, "version": env!("CARGO_PKG_VERSION"), "os": std::env::consts::OS, "src": src, "props": props}))
163}
164
165const QUEUE_LIMIT: usize = 1000;
166
167/// Record an event if telemetry is on. Never fails and never blocks on the network.
168pub fn track(name: &str, src: &str, props: Value) {
169    if state() != State::On {
170        return;
171    }
172    let (Some(ev), Some(path)) = (event(name, src, props), queue_path()) else { return };
173    push(&path, &ev);
174}
175
176fn push(path: &PathBuf, ev: &Value) {
177    let _ = fs::create_dir_all(path.parent().unwrap());
178    if let Ok(mut f) = fs::OpenOptions::new().create(true).append(true).open(path) {
179        let _ = writeln!(f, "{ev}");
180    }
181    // keep the queue bounded: when nobody is sending, the oldest events go
182    if let Ok(text) = fs::read_to_string(path) {
183        let lines: Vec<&str> = text.lines().collect();
184        if lines.len() > QUEUE_LIMIT {
185            let _ = fs::write(path, lines[lines.len() - QUEUE_LIMIT..].join("\n") + "\n");
186        }
187    }
188}
189
190/// Add an event someone else made (the editor's) to the queue, if telemetry is on. Only the fields we define are kept.
191pub fn record(name: &str, props: Value) -> bool {
192    if state() != State::On || name.is_empty() || name.len() > 48 || !name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') {
193        return false;
194    }
195    let props = match props {
196        Value::Object(m) if m.len() <= 12 && m.iter().all(|(k, v)| k.len() <= 32 && (v.is_boolean() || v.is_number() || v.as_str().is_some_and(|s| s.len() <= 48))) => Value::Object(m),
197        _ => json!({}),
198    };
199    track(name, "editor", props);
200    true
201}
202
203/// The first `max` queued events, oldest first.
204pub fn queued(max: usize) -> Vec<Value> {
205    queue_path().and_then(|p| fs::read_to_string(p).ok()).map(|t| t.lines().filter_map(|l| serde_json::from_str(l).ok()).take(max).collect()).unwrap_or_default()
206}
207
208pub fn queued_count() -> usize {
209    queue_path().and_then(|p| fs::read_to_string(p).ok()).map_or(0, |t| t.lines().count())
210}
211
212/// Drop the first `n` events once they have been sent.
213pub fn ack(n: usize) {
214    let Some(path) = queue_path() else { return };
215    let Ok(text) = fs::read_to_string(&path) else { return };
216    let rest: Vec<&str> = text.lines().skip(n).collect();
217    if rest.is_empty() {
218        let _ = fs::remove_file(&path);
219    } else {
220        let _ = fs::write(&path, rest.join("\n") + "\n");
221    }
222}