diff --git a/Cargo.lock b/Cargo.lock index b8052e8b9..0c37a850a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -911,6 +911,7 @@ dependencies = [ "horizon-assets", "horizon-core", "horizon-protocol", + "horizon-telemetry", "horizon-theme", "horizon-world", "log", diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 12aeaae4a..838e56ace 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -27,6 +27,8 @@ log = "0.4" chrono = { version = "0.4.42", default-features = false, features = ["clock", "std"] } flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] } horizon-theme = { path = "../horizon-theme" } +# Opt-in data collection: the game keeps, the launcher sends (docs/telemetry.md). +horizon-telemetry = { path = "../horizon-telemetry", default-features = false } arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] } zip = { version = "2", default-features = false, features = ["deflate"] } # Controllers (evdev + libudev on Linux, IOKit on macOS, Windows.Gaming.Input). diff --git a/crates/horizon-client/src/crash.rs b/crates/horizon-client/src/crash.rs index 7e57355f2..e0ece85f2 100644 --- a/crates/horizon-client/src/crash.rs +++ b/crates/horizon-client/src/crash.rs @@ -1,7 +1,8 @@ //! Crash reports, laid out like vanilla's CrashReport.getFriendlyReport: a comment, the time, //! a description, the error with its stack, then the details of the game and the machine. //! Written to `crash-reports/crash--client.txt` in the game folder when -//! the main thread panics or `main` gets an error back. Nothing is sent anywhere. +//! the main thread panics or `main` gets an error back. It leaves the machine only scrubbed, and +//! only if the player allows crash reports (`telemetry`). use std::fmt::Write as _; use std::path::{Path, PathBuf}; use std::sync::Mutex; @@ -105,7 +106,7 @@ impl Report { } /// The release this binary came with: launcher installs live in a folder named after the tag. -fn release_tag() -> Option { +pub fn release_tag() -> Option { let exe = std::env::current_exe().ok()?; let folder = exe.parent()?.file_name()?.to_str()?; (folder.starts_with('v') && folder[1..].starts_with(|c: char| c.is_ascii_digit())) @@ -270,6 +271,7 @@ fn deliver(home: &Path, report: Report) -> Option { ), ); crate::logging::flush(); + crate::telemetry::keep_crash(home, &report); match report.save(home) { Ok(path) => { eprintln!("Horizon: crash report saved to {}", path.display()); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 4771c3322..950a504fe 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -901,6 +901,8 @@ struct Game<'a> { creative_screen: Creative, control: Option, frame_stats: horizon_client::control::FrameStats, + /// This play session's frame and tick times, for opt-in performance statistics. + perf: horizon_client::telemetry::Session, /// Control replies waiting for a rendered frame or a benchmark deadline. pending_screenshot: Option>, pending_bench: Option<(Instant, std::sync::mpsc::Sender)>, @@ -5708,6 +5710,7 @@ impl Game<'_> { seed: Option, creative: bool, ) -> Result<()> { + self.perf.world_opening(); let save_root = std::env::current_dir()?.join("saves").join(folder); horizon_client::save::upgrade_older_world(&save_root)?; horizon_client::save::migrate_legacy(&save_root)?; @@ -6136,6 +6139,27 @@ impl Game<'_> { /// Leaving the game with a world open (window closed, Quit, `quit`): /// menu items go back (Player.closeContainer), then the world is saved, /// once. + /// Keeps this play session's performance summary for the launcher to send, if the player + /// allows performance statistics (`horizon_client::telemetry`), and starts the next one. + pub(super) fn finish_perf(&mut self) { + let s = &self.settings; + let settings = horizon_telemetry::payload::Settings { + render_distance: s.render_distance.clamp(0, 255) as u8, + simulation_distance: s.simulation_distance.clamp(0, 255) as u8, + // 260 is the slider's "unlimited". + max_fps: if s.max_fps >= 260 { + 0 + } else { + s.max_fps.min(u32::from(u16::MAX)) as u16 + }, + vsync: s.vsync, + fullscreen: s.fullscreen, + graphics: s.graphics_preset.clone(), + }; + self.perf + .finish(&horizon_client::logging::game_home(), settings); + } + pub(super) fn save_for_exit(&mut self) -> Result<()> { if self.title.is_some() || self.saved_for_exit { return Ok(()); @@ -6157,6 +6181,7 @@ impl Game<'_> { if self.remote.is_some() { return self.leave_server(None); } + self.finish_perf(); self.stats.custom("leave_game", 1); self.save_game()?; self.lan_close(false); @@ -8879,7 +8904,12 @@ impl ApplicationHandler for Game<'_> { for _ in 0..steps { let started = Instant::now(); if self.title.is_none() && !self.pause { + let tick = Instant::now(); horizon_client::spans::time("tick", || self.tick())?; + // In single player the tick is the integrated server's. + if self.remote.is_none() { + self.perf.tick(tick.elapsed().as_secs_f32() * 1000.0); + } self.tick_ambience(); self.tick_fov(); } else if self.title.is_some() { @@ -8965,6 +8995,11 @@ impl ApplicationHandler for Game<'_> { } if rendered { self.frame_stats.record(elapsed.as_secs_f32() * 1000.0); + if self.title.is_some() { + self.perf.title_shown(); + } else if self.screen == Screen::Playing && self.player.is_some() { + self.perf.frame(elapsed.as_secs_f32() * 1000.0); + } self.frames += 1; self.fps_frames += 1; horizon_client::crash::debug_crash_tick(); @@ -9019,6 +9054,7 @@ impl ApplicationHandler for Game<'_> { if let Err(e) = self.save_for_exit() { log::warn!("Horizon: failed to save the world on exit: {e}"); } + self.finish_perf(); } } /// clouds.png as filled cells (`CloudRenderer.prepare`: alpha 10 or more). @@ -9397,6 +9433,7 @@ pub fn run() -> Result<()> { creative_screen: Creative::load(&game_root)?, control: None, frame_stats: Default::default(), + perf: Default::default(), pending_screenshot: None, pending_bench: None, flight: None, diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 61115df1f..24a2d0e3a 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -151,6 +151,7 @@ fn number_format(f: &play::NumberFormat) -> horizon_client::scoreboard::NumberFo impl Game<'_> { /// Leave the title for a server (ConnectScreen): an empty world fed by the connection. pub(super) fn connect_server(&mut self, address: &str, name: &str) -> Result<()> { + self.perf.world_opening(); let root = self.options.resources.clone(); let builtin = Builtin::find(&root) .and_then(|p| Builtin::load(&p).ok()) @@ -262,6 +263,7 @@ impl Game<'_> { /// Disconnect and return to the multiplayer screen (DisconnectedScreen). pub(super) fn leave_server(&mut self, reason: Option) -> Result<()> { + self.finish_perf(); if reason.is_none() { // Leaving on purpose: nothing for auto-reconnect to retry. self.extras_left(); diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 2b47e2a89..6cc4d5df2 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -432,6 +432,13 @@ impl Renderer { info.backend, info.device_type ); + crate::telemetry::set_gpu( + &info.name, + format!("{} {}", info.driver, info.driver_info) + .trim() + .to_owned(), + format!("{:?}", info.backend), + ); crate::crash::set_detail( "Graphics Adapter", format!( diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 07ba1af2a..a7e3913bb 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -143,6 +143,7 @@ pub mod stopwatches; pub mod streaming; pub mod structure_blocks; pub mod tab_list; +pub mod telemetry; pub mod testgen; pub mod text; pub mod title; diff --git a/crates/horizon-client/src/main.rs b/crates/horizon-client/src/main.rs index 30ccd26a4..8004b2fa7 100644 --- a/crates/horizon-client/src/main.rs +++ b/crates/horizon-client/src/main.rs @@ -5,6 +5,7 @@ mod game; use horizon_client::{crash, logging}; fn main() { + horizon_client::telemetry::mark_start(); let args: Vec = std::env::args().skip(1).collect(); let game_args = args.iter().take_while(|a| *a != "--dedicated"); let help = game_args.clone().any(|a| a == "--help" || a == "-h"); diff --git a/crates/horizon-client/src/telemetry.rs b/crates/horizon-client/src/telemetry.rs new file mode 100644 index 000000000..5abc3bd89 --- /dev/null +++ b/crates/horizon-client/src/telemetry.rs @@ -0,0 +1,373 @@ +//! The game's part in opt-in data collection (`horizon_telemetry`, docs/telemetry.md). When the +//! player allows it, the game keeps a scrubbed crash report, or a play session's performance +//! summary, in the outbox. It never sends anything itself: the launcher does, at its next start. +//! Without the player's yes for that kind nothing is kept, and crash-reports/ stays local. +use std::path::Path; +use std::sync::{Mutex, OnceLock}; +use std::time::Instant; + +use horizon_telemetry::payload::{Crash, Perf, Settings, System, Timings}; +use horizon_telemetry::scrub::Scrubber; +use horizon_telemetry::{Item, Payload, Source, outbox}; + +/// A session shorter than this says too little to keep. +const MIN_SECONDS: f32 = 60.0; + +/// The details of a crash report that say what the game was doing, and only those: not the +/// world, the server or the resource packs. +const CRASH_DETAILS: [&str; 3] = ["Horizon Version", "Graphics Adapter", "Render Settings"]; + +static STARTED: OnceLock = OnceLock::new(); +/// The GPU's name, driver and backend, once the renderer has its adapter. +static GPU: Mutex> = Mutex::new(None); + +/// When the game started, for the time to the title screen. Call first thing in `main`. +pub fn mark_start() { + STARTED.get_or_init(Instant::now); +} + +pub fn set_gpu(name: &str, driver: String, backend: String) { + *GPU.lock().unwrap_or_else(|e| e.into_inner()) = Some((name.to_owned(), driver, backend)); +} + +/// This machine, with the GPU once the renderer knows it. +pub fn system() -> System { + let mut system = System::detect(); + if let Some((gpu, driver, backend)) = GPU.lock().unwrap_or_else(|e| e.into_inner()).clone() { + system.gpu = gpu; + system.driver = driver; + system.backend = backend; + } + system +} + +/// The release (`v2026.10.15`), or the client's crate version for a build from source. +pub fn version() -> String { + crate::crash::release_tag().unwrap_or_else(|| format!("dev {}", env!("CARGO_PKG_VERSION"))) +} + +/// What a crash report becomes when it may leave: the error and stack, the thread, and the +/// details in [`CRASH_DETAILS`], with the world's name and folder and the server's address +/// scrubbed wherever they appear. No log lines. +pub fn crash_item(report: &crate::crash::Report) -> Item { + let mut scrubber = Scrubber::new(); + for (key, value) in &report.details { + match key.as_str() { + // `Name (saves/folder)`, as game.rs sets it. + "World" => { + let (name, folder) = value.rsplit_once(" (saves/").unwrap_or((value, "")); + scrubber = scrubber.term(name).term(folder.trim_end_matches(')')); + } + "Server" => { + let host = value.rsplit_once(':').map_or(value.as_str(), |(h, _)| h); + scrubber = scrubber.term(value.as_str()).term(host); + } + _ => {} + } + } + let crash = Crash { + system: system(), + error: scrubber.scrub(&report.error), + stack: scrubber.scrub(&report.stack), + thread: report.thread.clone(), + details: report + .details + .iter() + .filter(|(k, _)| CRASH_DETAILS.contains(&k.as_str())) + .map(|(k, v)| (k.clone(), scrubber.scrub(v))) + .collect(), + }; + let mut item = Item::new(Source::Game, version(), Payload::Crash(crash)); + // A huge stack keeps its top, where the error is. + while item.validate().is_err() { + let Payload::Crash(crash) = &mut item.payload else { + break; + }; + let keep = crash.stack.lines().count() * 3 / 4; + if keep == 0 { + crash.stack.clear(); + break; + } + crash.stack = crash + .stack + .lines() + .take(keep) + .map(|l| format!("{l}\n")) + .collect(); + } + item +} + +/// Keeps the crash for the launcher to send, if the player allows crash reports. +pub fn keep_crash(home: &Path, report: &crate::crash::Report) { + if let Err(e) = outbox::push(home, &crash_item(report)) { + log::warn!("Horizon: could not keep the crash report to send: {e}"); + } +} + +/// One play session's performance, from entering a world to leaving it: frame and tick +/// times as [`Timings`] (fixed size whatever the length), never the frames themselves. +#[derive(Default)] +pub struct Session { + frames: Timings, + ticks: Timings, + played_ms: f32, + to_title_ms: Option, + /// The start was measured: only the first session carries it. + title_measured: bool, + to_world_ms: Option, + opening: Option, +} + +impl Session { + /// The title screen drew a frame: the first time, how long the start took. + pub fn title_shown(&mut self) { + if !self.title_measured { + self.title_measured = true; + self.to_title_ms = STARTED.get().map(|s| s.elapsed().as_millis() as u32); + } + } + + /// A world starts loading. + pub fn world_opening(&mut self) { + self.opening.get_or_insert_with(Instant::now); + } + + /// A frame drawn while playing (not in menus or loading). + pub fn frame(&mut self, ms: f32) { + if let Some(opening) = self.opening.take() + && self.to_world_ms.is_none() + { + self.to_world_ms = Some(opening.elapsed().as_millis() as u32); + } + self.frames.record(ms); + self.played_ms += ms; + } + + /// One tick of the integrated server, in single player. + pub fn tick(&mut self, ms: f32) { + self.ticks.record(ms); + } + + /// The session's summary, if it was long enough to say something. + pub fn summary(&self, settings: Settings) -> Option { + let seconds = self.played_ms / 1000.0; + (seconds >= MIN_SECONDS).then(|| Perf { + system: system(), + settings, + seconds: seconds as u32, + frames: self.frames.summary(), + ticks: (self.ticks.count() > 0).then(|| self.ticks.summary()), + peak_ram_mb: peak_ram_mb(), + to_title_ms: self.to_title_ms, + to_world_ms: self.to_world_ms, + }) + } + + /// Keeps the session's summary for the launcher to send, if the player allows performance + /// statistics, and starts the next session (the time to the title goes with the first). + pub fn finish(&mut self, home: &Path, settings: Settings) { + if horizon_telemetry::Consent::load(home).allows(horizon_telemetry::Kind::Perf) + && let Some(perf) = self.summary(settings) + { + let item = Item::new(Source::Game, version(), Payload::Perf(perf)); + if let Err(e) = outbox::push(home, &item) { + log::warn!("Horizon: could not keep the session's performance summary: {e}"); + } + } + *self = Self { + title_measured: self.title_measured, + ..Self::default() + }; + } +} + +/// The game's resident memory: the peak on Linux, what it uses now elsewhere. +fn peak_ram_mb() -> u32 { + let kib = if cfg!(target_os = "linux") { + std::fs::read_to_string("/proc/self/status") + .ok() + .and_then(|t| { + t.lines() + .find(|l| l.starts_with("VmHWM:"))? + .split_whitespace() + .nth(1)? + .parse::() + .ok() + }) + } else if cfg!(target_os = "macos") { + std::process::Command::new("ps") + .args(["-o", "rss=", "-p", &std::process::id().to_string()]) + .output() + .ok() + .and_then(|o| { + String::from_utf8_lossy(&o.stdout) + .trim() + .parse::() + .ok() + }) + } else { + None + }; + kib.map_or(0, |k| (k / 1024) as u32) +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_telemetry::{Choices, Consent, Kind}; + + fn home(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!( + "horizon-client-telemetry-{name}-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + fn allow(home: &Path, choices: Choices) { + let mut consent = Consent::load(home); + consent.answer(choices); + consent.save(home).unwrap(); + } + + fn report() -> crate::crash::Report { + crate::crash::Report { + time: chrono::Local::now(), + description: "Unexpected error".into(), + error: + "panicked at src/save.rs:10:5:\nno level.dat in /Users/ana/horizon/saves/Ana's Base" + .into(), + stack: "horizon_client::save::load (crates/horizon-client/src/save.rs:10:5)\n".into(), + thread: "Render thread".into(), + side: "client", + details: vec![ + ( + "Horizon Version".into(), + "v2026.10.15 (client 0.1.0)".into(), + ), + ( + "Operating System".into(), + "macos (aarch64) version macOS 26.0".into(), + ), + ("World".into(), "Castle Ana (saves/Ana's Base)".into()), + ("Server".into(), "play.example.net:25565".into()), + ("Resource Packs".into(), "Ana's pack".into()), + ], + log: vec!["[CHAT] hi".into()], + } + } + + #[test] + fn a_crash_keeps_only_what_says_what_happened() { + let item = crash_item(&report()); + let Payload::Crash(crash) = &item.payload else { + panic!("a crash item"); + }; + assert_eq!( + crash.error, + "panicked at src/save.rs:10:5:\nno level.dat in /Users//horizon/saves/" + ); + assert_eq!( + crash.details, + [( + "Horizon Version".to_owned(), + "v2026.10.15 (client 0.1.0)".to_owned() + )] + ); + let json = serde_json::to_string(&item).unwrap(); + for private in [ + "Castle Ana", + "Ana's Base", + "example.net", + "Ana's pack", + "CHAT", + ] { + assert!(!json.contains(private), "{private} in {json}"); + } + assert!(item.validate().is_ok()); + } + + #[test] + fn a_huge_stack_is_cut_to_fit() { + let mut report = report(); + report.stack = + "horizon_client::game::deep (crates/horizon-client/src/game.rs:1:1)\n".repeat(2000); + let item = crash_item(&report); + assert!(item.validate().is_ok()); + let Payload::Crash(crash) = item.payload else { + panic!("a crash item"); + }; + assert!(crash.stack.lines().count() > 100); + } + + #[test] + fn crashes_stay_local_without_consent() { + let home = home("crash"); + keep_crash(&home, &report()); + assert!(outbox::pending(&home).is_empty()); + allow( + &home, + Choices { + performance: true, + ..Choices::NONE + }, + ); + keep_crash(&home, &report()); + assert!(outbox::pending(&home).is_empty()); + allow( + &home, + Choices { + crashes: true, + ..Choices::NONE + }, + ); + keep_crash(&home, &report()); + let pending = outbox::pending(&home); + assert_eq!(pending.len(), 1); + assert_eq!(pending[0].1.kind(), Kind::Crash); + } + + #[test] + fn a_session_is_kept_only_with_consent_and_once_long_enough() { + let home = home("session"); + let mut session = Session::default(); + session.world_opening(); + (0..2000).for_each(|_| session.frame(16.6)); + session.finish(&home, Settings::default()); + assert!(outbox::pending(&home).is_empty(), "33 s, and no consent"); + allow( + &home, + Choices { + performance: true, + ..Choices::NONE + }, + ); + (0..2000).for_each(|_| session.frame(16.6)); + session.finish(&home, Settings::default()); + assert!(outbox::pending(&home).is_empty(), "33 s is too short"); + session.world_opening(); + (0..4000).for_each(|_| session.frame(16.6)); + (0..1200).for_each(|_| session.tick(4.0)); + session.finish( + &home, + Settings { + render_distance: 12, + ..Settings::default() + }, + ); + let pending = outbox::pending(&home); + assert_eq!(pending.len(), 1); + let Payload::Perf(perf) = &pending[0].1.payload else { + panic!("a perf item"); + }; + assert_eq!(perf.seconds, 66); + assert_eq!(perf.frames.count, 4000); + assert_eq!(perf.ticks.as_ref().unwrap().p50_ms, 4.0); + assert_eq!(perf.settings.render_distance, 12); + assert!(perf.to_world_ms.is_some()); + assert!(serde_json::to_vec(&pending[0].1).unwrap().len() < 1024); + } +}