//! Opt-in data collection from the launcher (`horizon_telemetry`): the player's answer, what //! would be sent, deleting it, bug reports and benchmark uploads, and sending the outbox when //! the launcher starts and closes. The window, the CLI and the MCP server all go through here. use std::path::{Path, PathBuf}; use horizon_telemetry::payload::{Bug, Crash, Perf, System, Timings}; use horizon_telemetry::scrub::Scrubber; use horizon_telemetry::upload::{self, Flush}; use horizon_telemetry::{outbox, Choices, Consent, Item, Kind, Payload, Source}; use crate::{account::Accounts, backend}; /// Each switch: its name, and in plain words exactly what it sends. pub const SWITCHES: [(Kind, &str, &str); 4] = [ ( Kind::Perf, "Performance statistics", "After each session: frame-time percentiles and a 14-bucket histogram, tick times, peak memory and startup times, with your OS, CPU, GPU, driver, memory size and the settings that change performance.", ), ( Kind::Crash, "Crash reports", "When the game crashes: the error, where in Horizon's code it happened, your graphics adapter and settings. No log, no world or server, no user name in paths.", ), ( Kind::Bug, "Bug reports", "Only the reports you write and send yourself, with the game's log if you add it after reading it.", ), ( Kind::Benchmark, "Benchmark uploads", "The results of benchmarks you run, for the community results on playhorizon.dev.", ), ]; /// Never sent, whatever the switches say. pub const NEVER: &str = "Never sent: your account name or UUID, world names, server addresses, chat, or your IP address. Each report is dated to the day, under a random install ID you can delete."; pub fn home() -> PathBuf { backend::game_home() } pub fn consent() -> Consent { Consent::load(&home()) } /// Records the player's answer. Waiting items of kinds now off are deleted at once. pub fn answer(choices: Choices) -> Result { let home = home(); let mut consent = Consent::load(&home); consent.answer(choices); consent.save(&home).map_err(|e| e.to_string())?; outbox::retain_allowed(&home); Ok(consent) } /// The exact JSON the next upload would send, under a line saying what it is. With nothing /// waiting, one example of each kind, made on this machine. pub fn preview() -> (String, String) { let home = home(); let waiting = outbox::retain_allowed(&home).len(); if waiting > 0 { let what = format!( "{waiting} item{} waiting to be sent, exactly as they will leave (compressed):", if waiting == 1 { "" } else { "s" } ); return (what, upload::preview(&home)); } let system = System::detect(); let examples = vec![ Item::new( Source::Game, "v2026.10.15", Payload::Perf(Perf { system: system.clone(), seconds: 1800, frames: Timings::new().summary(), ..Perf::default() }), ), Item::new( Source::Game, "v2026.10.15", Payload::Crash(Crash { system: system.clone(), error: "panicked at crates/horizon-client/src/game.rs:120:9: …".into(), stack: "horizon_client::game::Game::tick (crates/horizon-client/src/game.rs:120:9)" .into(), thread: "Render thread".into(), details: vec![("Graphics".into(), "Apple M4 Pro (Metal)".into())], }), ), Item::new( Source::Launcher, backend::VERSION, Payload::Bug(Bug { system, text: "What you write.".into(), log: None, }), ), ]; let json = serde_json::to_string_pretty(&serde_json::json!({ "schema": horizon_telemetry::SCHEMA, "install_id": consent().install_id, "items": examples, })) .unwrap_or_default(); ( "Nothing is waiting. One example of each kind, from this machine (a benchmark upload is the report itself, see docs/benchmark-report.md):".into(), json, ) } /// "Delete my data": the server deletes everything sent under this install's ID, the waiting /// items go, and the install gets a new ID. If the server can't be reached the ID is kept, so /// the deletion can be asked again. pub fn delete_my_data() -> Result { let home = home(); let mut consent = Consent::load(&home); outbox::clear(&home).map_err(|e| e.to_string())?; let remote = match horizon_telemetry::endpoint() { _ if consent.install_id.is_empty() => "Nothing was ever sent from here.", None => "Nothing was sent: there is no data server yet.", Some(url) => { upload::delete_remote(&url, &consent.install_id) .map_err(|e| format!("The server could not be reached ({e}). Try again later."))?; "The server deleted everything sent from here." } }; consent.reset_install_id(); consent.save(&home).map_err(|e| e.to_string())?; Ok(format!( "{remote} Nothing is waiting, and this install has a new ID." )) } /// Hides the player's account names and UUIDs and their worlds' folder names, besides what /// `Scrubber` finds on its own. pub fn scrubber() -> Scrubber { let mut s = Scrubber::new(); for account in Accounts::load().accounts { s = s.term(account.name).term(account.uuid); } let saves = std::fs::read_dir(home().join("saves")) .into_iter() .flatten() .flatten(); for world in saves { s = s.term(world.file_name().to_string_lossy()); } s } /// The end of the game's log as a bug report would carry it: scrubbed, without chat. pub fn log_for_report() -> Option { let (_, text) = backend::read_logs(300, false).ok()?; let kept: Vec<&str> = text.lines().filter(|l| !l.contains("[CHAT]")).collect(); let mut log = scrubber().scrub(&kept.join("\n")); // Within the item's size, the newest lines first to stay. while log.len() > 64 * 1024 { let cut = log.find('\n').map_or(log.len(), |i| i + 1); log.drain(..cut); } Some(log) } /// A bug report, ready to be read before it is kept. pub fn bug_report(text: &str, with_log: bool) -> Result { let item = Item::new( Source::Launcher, backend::VERSION, Payload::Bug(Bug { system: System::detect(), text: scrubber().scrub(text.trim()), log: with_log.then(log_for_report).flatten(), }), ); item.validate()?; Ok(item) } /// An error unless the player allows `kind`. pub fn ensure_allowed(kind: Kind) -> Result<(), String> { if consent().allows(kind) { return Ok(()); } Err(format!( "{} are off: turn them on in Settings → Data collection first.", label(kind) )) } /// Keeps `item` and sends the outbox; says what happened. pub fn submit(item: &Item) -> Result { ensure_allowed(item.kind())?; if !outbox::push(&home(), item).map_err(|e| e.to_string())? { return Err("Today's limit for these is reached; try again tomorrow.".into()); } Ok(match send() { Flush::Sent { .. } => "Sent. Thank you.".into(), Flush::Nothing if horizon_telemetry::endpoint().is_none() => { "Kept to be sent once the data server is up.".into() } _ => "Kept; it will be sent the next time the launcher starts.".into(), }) } /// A benchmark report file (`docs/benchmark-report.md`), scrubbed, as an upload. pub fn benchmark_report(path: &Path) -> Result { let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; let report: serde_json::Value = serde_json::from_str(&scrubber().scrub(&text)) .map_err(|e| format!("{}: not a JSON report ({e})", path.display()))?; let item = Item::new( Source::Launcher, backend::VERSION, Payload::Benchmark(report), ); item.validate()?; Ok(item) } pub fn label(kind: Kind) -> &'static str { SWITCHES.iter().find(|s| s.0 == kind).map_or("", |s| s.1) } /// Sends what is waiting, if there is a server and the player allows it. pub fn send() -> Flush { match horizon_telemetry::endpoint() { Some(url) => upload::flush(&home(), &url), None => Flush::Nothing, } } /// [`send`] on its own thread, at start and when the window closes. pub fn send_in_background() -> std::thread::JoinHandle<()> { std::thread::spawn(|| drop(send())) } /// The status as `telemetry status` and the MCP tool give it. pub fn status_json() -> serde_json::Value { let consent = consent(); serde_json::json!({ "asked": !consent.needs_asking(), "consent_version": consent.version, "answered": consent.answered, "choices": consent.choices, "install_id": consent.install_id, "waiting": outbox::pending(&home()).len(), "server": horizon_telemetry::endpoint(), }) } /// [`send`] as the launcher closes, waiting at most a few seconds for it. pub fn send_before_exit() { let (tx, rx) = std::sync::mpsc::channel(); std::thread::spawn(move || { send(); let _ = tx.send(()); }); let _ = rx.recv_timeout(std::time::Duration::from_secs(3)); } /// The kinds named as the CLI and MCP take them: `performance`, `crashes`, `bugs`, /// `benchmarks` (or `perf`, `crash`…), or `all`. pub fn parse_kinds(names: &[String]) -> Result, String> { let mut kinds = Vec::new(); for name in names { match name.as_str() { "all" => kinds.extend(Kind::ALL), "performance" => kinds.push(Kind::Perf), "crashes" => kinds.push(Kind::Crash), "bugs" => kinds.push(Kind::Bug), "benchmarks" => kinds.push(Kind::Benchmark), other => kinds.push(Kind::from_name(other).ok_or_else(|| { format!("{other}: one of performance, crashes, bugs, benchmarks, all") })?), } } Ok(kinds) } /// Turns `kinds` on or off, keeping the other switches as they are (off if never asked). pub fn set(kinds: &[Kind], on: bool) -> Result { let current = consent(); let mut choices = if current.needs_asking() { Choices::NONE } else { current.choices }; for &kind in kinds { choices.set(kind, on); } answer(choices) } #[cfg(test)] mod tests { use super::*; #[test] fn kinds_are_named_in_plain_words_or_short() { let names = |n: &[&str]| parse_kinds(&n.iter().map(|s| s.to_string()).collect::>()); assert_eq!( names(&["performance", "crash"]).unwrap(), [Kind::Perf, Kind::Crash] ); assert_eq!(names(&["all"]).unwrap(), Kind::ALL); assert!(names(&["everything"]).is_err()); } #[test] fn every_kind_has_a_switch() { assert!(Kind::ALL.iter().all(|&k| !label(k).is_empty())); } }