diff --git a/Cargo.lock b/Cargo.lock index 8970615..6b83e52 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2348,6 +2348,7 @@ dependencies = [ "rayon", "serde", "serde_json", + "telemetry", "tempfile", "thiserror 2.0.21", "tokio", @@ -2379,6 +2380,7 @@ dependencies = [ "icons", "log", "pico-args", + "reqwest 0.12.28", "serde", "serde_json", "tauri", @@ -2393,6 +2395,7 @@ dependencies = [ "tauri-plugin-window-controls-overlay", "tauri-runtime-cef", "tauri-runtime-wry", + "telemetry", "tempfile", "thiserror 2.0.21", "tokio", @@ -5771,6 +5774,21 @@ dependencies = [ "parking_lot", ] +[[package]] +name = "quanta" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73be39b77b45d82a4d1a5793fe9a89a5c143ceaa6ad0d8417982566bb0f34e11" +dependencies = [ + "libc", + "portable-atomic", + "raw-cpuid", + "wasip1", + "wasip2", + "web-sys", + "windows-sys 0.61.2", +] + [[package]] name = "quick-xml" version = "0.41.0" @@ -6002,6 +6020,15 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "raw-cpuid" +version = "11.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186" +dependencies = [ + "bitflags 2.13.2", +] + [[package]] name = "raw-window-handle" version = "0.6.2" @@ -7689,6 +7716,29 @@ dependencies = [ "toml 1.1.8+spec-1.1.0", ] +[[package]] +name = "telemetry" +version = "0.3.0" +dependencies = [ + "criterion", + "quanta", + "serde", + "serde_json", + "telemetry-macros", + "tempfile", + "thiserror 2.0.21", + "tokio", +] + +[[package]] +name = "telemetry-macros" +version = "0.3.0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -8362,6 +8412,12 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasip1" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e26842486624357dbeb8f0381cf1fb42f022291fd787d4a816768fec8cc760" + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" @@ -9212,6 +9268,9 @@ name = "wit-bindgen" version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +dependencies = [ + "bitflags 2.13.2", +] [[package]] name = "writeable" diff --git a/Cargo.toml b/Cargo.toml index 974b508..9180fe8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,8 @@ members = [ "crates/tauri", "crates/tauri-plugin-prevent-default", "crates/tauri-plugin-window-controls-overlay", + "crates/telemetry", + "crates/telemetry-macros", ] [workspace.package] @@ -50,12 +52,16 @@ language = { path = "crates/language" } log = "0.4" notify = "8" pico-args = "0.5" +proc-macro2 = "1" +quanta = "0.13" +quote = "1" rayon = "1" reqwest = { version = "0.12", default-features = false, features = [ "rustls-tls", ] } serde = { version = "1", features = ["derive"] } serde_json = "1" +syn = { version = "2", features = ["full", "visit-mut"] } syntect = { version = "5", default-features = false, features = [ "parsing", "default-syntaxes", @@ -79,6 +85,8 @@ tauri-plugin-window-controls-overlay = { path = "crates/tauri-plugin-window-cont # tauri-bundler alpha.4 still copies them, so deb/appimage bundling aborts. tauri-runtime-cef = "=3.0.0-alpha.5" tauri-runtime-wry = "3.0.0-alpha.5" +telemetry = { path = "crates/telemetry" } +telemetry-macros = { path = "crates/telemetry-macros" } tempfile = "3" thiserror = "2" tokio = { version = "1", features = [ diff --git a/crates/git/Cargo.toml b/crates/git/Cargo.toml index bbe6a92..02e0a47 100644 --- a/crates/git/Cargo.toml +++ b/crates/git/Cargo.toml @@ -24,6 +24,7 @@ language.workspace = true thiserror.workspace = true serde.workspace = true serde_json.workspace = true +telemetry.workspace = true tokio = { workspace = true, features = ["fs", "io-util", "process"] } notify.workspace = true keyring.workspace = true diff --git a/crates/git/src/application/backend.rs b/crates/git/src/application/backend.rs index e6f7aa1..acdf7bc 100644 --- a/crates/git/src/application/backend.rs +++ b/crates/git/src/application/backend.rs @@ -305,6 +305,7 @@ impl Backend { self.registry.len() } + #[telemetry::trace] pub async fn open_repository(&self, path: &Path) -> Result { if !path.exists() { return Err(GitError::RepositoryNotFound { @@ -321,9 +322,9 @@ impl Backend { // loading costs, which reads as a multi-second hang. let warm_session = entry.gix.clone(); // Called within an async context, so a runtime exists. - std::mem::drop(tokio::spawn(async move { - let _ = warm_session.handle().head_id(); - })); + std::mem::drop(tokio::spawn(telemetry::scope(warm_object_database( + warm_session, + )))); // First registration only: the walk/summary caches are immutable and // survive generation bumps, so re-opens never need re-warming. @@ -353,23 +354,13 @@ impl Backend { } let scheduler = self.scheduler.clone(); let gix_session = entry.gix.clone(); - tokio::spawn(async move { - let token = CancellationToken::new(); - let Ok(mut report) = scheduler - .run(&token, move || { - crate::engines::gix::status::status(&gix_session, &StatusOptions::default()) - }) - .await - else { - return; - }; - if entry.generation() != generation { - return; - } - report.snapshot_id = entry.next_snapshot_id(); - report.generation = generation; - entry.store_cached("status", &cache_key, CachedValue::Status(Arc::new(report))); - }); + tokio::spawn(telemetry::scope(warm_status( + entry, + scheduler, + gix_session, + generation, + cache_key, + ))); } /// Builds walk + default-page summaries off the interaction path so a @@ -379,28 +370,7 @@ impl Backend { return; }; let scheduler = self.scheduler.clone(); - let path = entry.canonical_path.clone(); - let history_cache = entry.history_cache(); - let lock_entry = entry.clone(); - let generation = entry.generation(); - tokio::spawn(async move { - let token = CancellationToken::new(); - let _ = scheduler - .run(&token, move || { - let _computation = lock_entry.history_lock().lock().unwrap(); - let query = HistoryPageQuery::default(); - let mut guard = history_cache.lock().unwrap(); - let session = crate::engines::git2::Git2Session::new(path); - crate::engines::git2::history::history_page( - &session, - &query, - SnapshotId(0), - generation, - &mut guard, - ) - }) - .await; - }); + tokio::spawn(telemetry::scope(warm_history(entry, scheduler))); } fn watch_paths(&self, session: &crate::engines::gix::GixSession) -> Vec { @@ -555,6 +525,7 @@ impl Backend { Ok(()) } + #[telemetry::trace(skip = ["generation", "next_snapshot_id", "Status"])] pub async fn status( &self, id: RepoId, @@ -618,6 +589,7 @@ impl Backend { best.map(|(_, report)| report) } + #[telemetry::trace(span_only)] pub async fn open_diff( &self, id: RepoId, @@ -642,14 +614,14 @@ impl Backend { let op_for_job = operation.clone(); let scheduler = self.scheduler.clone(); - tokio::spawn(async move { + tokio::spawn(telemetry::scope(async move { let _ = scheduler .run(&token, move || { pipeline::run(job, op_for_job, tx); Ok(()) }) .await; - }); + })); self.operations .prune_completed(self.config.keep_completed_operations); @@ -737,6 +709,7 @@ impl Backend { }) } + #[telemetry::trace(span_only)] pub async fn open_graph( &self, id: RepoId, @@ -761,14 +734,14 @@ impl Backend { let op_for_job = operation.clone(); let scheduler = self.scheduler.clone(); - tokio::spawn(async move { + tokio::spawn(telemetry::scope(async move { let _ = scheduler .run(&token, move || { graph_pipeline::run(job, op_for_job, tx); Ok(()) }) .await; - }); + })); self.graph_operations .prune_completed(self.config.keep_completed_operations); @@ -802,6 +775,7 @@ impl Backend { Ok(self.operations.get(operation_id)?.snapshot_meta()) } + #[telemetry::trace(skip = ["generation", "history_cache", "next_snapshot_id", "History"])] pub async fn history_page( &self, id: RepoId, @@ -854,6 +828,7 @@ impl Backend { Ok(arc) } + #[telemetry::trace(skip = ["generation", "history_cache", "next_snapshot_id", "HistoryChart"])] pub async fn history_chart( &self, id: RepoId, @@ -896,6 +871,7 @@ impl Backend { Ok(arc) } + #[telemetry::trace(skip = ["generation", "next_snapshot_id"])] pub async fn commit_detail( &self, id: RepoId, @@ -990,6 +966,7 @@ impl Backend { })) } + #[telemetry::trace] pub async fn blame( &self, id: RepoId, @@ -1007,6 +984,7 @@ impl Backend { .await } + #[telemetry::trace] pub async fn list_branches_and_tags( &self, id: RepoId, @@ -1026,6 +1004,7 @@ impl Backend { .await } + #[telemetry::trace(skip = ["parse"])] pub async fn branch_ahead_behind( &self, id: RepoId, @@ -1272,6 +1251,7 @@ impl Backend { .await } + #[telemetry::trace] pub async fn commit( &self, id: RepoId, @@ -1298,6 +1278,7 @@ impl Backend { .await } + #[telemetry::trace] pub async fn checkout( &self, id: RepoId, @@ -1601,6 +1582,7 @@ impl Backend { .await } + #[telemetry::trace] pub async fn fetch( &self, id: RepoId, @@ -1626,6 +1608,7 @@ impl Backend { Ok(()) } + #[telemetry::trace] pub async fn push( &self, id: RepoId, @@ -1652,6 +1635,7 @@ impl Backend { Ok(outcomes) } + #[telemetry::trace] pub async fn pull( &self, id: RepoId, @@ -1909,6 +1893,7 @@ impl Backend { /// terminal event. Resolves with the operation id immediately; the /// download itself runs detached on the blocking scheduler so cancel /// works while the caller holds the receiver. + #[telemetry::trace] pub async fn open_clone( &self, mut request: CloneRequest, @@ -2730,6 +2715,76 @@ fn build_snapshot(entry: &Arc) -> Result, + scheduler: Scheduler, + session: crate::engines::gix::GixSession, + generation: Generation, + cache_key: (Generation, StatusOptions), +) { + let token = CancellationToken::new(); + let Ok(mut report) = scheduler + .run(&token, move || { + crate::engines::gix::status::status(&session, &StatusOptions::default()) + }) + .await + else { + telemetry::context! { "outcome" => "cancelled" }; + return; + }; + if entry.generation() != generation { + telemetry::context! { "outcome" => "stale" }; + return; + } + report.snapshot_id = entry.next_snapshot_id(); + report.generation = generation; + entry.store_cached("status", &cache_key, CachedValue::Status(Arc::new(report))); + telemetry::context! { "outcome" => "stored" }; +} + +#[telemetry::trace(name = "app.warmup_history", span_only)] +async fn warm_history(entry: Arc, scheduler: Scheduler) { + let path = entry.canonical_path.clone(); + let history_cache = entry.history_cache(); + let generation = entry.generation(); + let token = CancellationToken::new(); + let result = scheduler + .run(&token, move || { + let _computation = entry.history_lock().lock().unwrap(); + let query = HistoryPageQuery::default(); + let mut guard = history_cache.lock().unwrap(); + let session = crate::engines::git2::Git2Session::new(path); + crate::engines::git2::history::history_page( + &session, + &query, + SnapshotId(0), + generation, + &mut guard, + ) + }) + .await; + let outcome = if result.is_ok() { "stored" } else { "failed" }; + telemetry::record_attribute("outcome", telemetry::AttrValue::from(outcome)); +} + +#[telemetry::trace(skip = [ + "build_options", + "copied", + "deltas", + "id", + "include_untracked", + "new_file", + "old_file", + "recurse_untracked_dirs", + "transpose", + "with_capacity", +])] fn commit_detail_blocking( path: PathBuf, query: CommitDetailQuery, diff --git a/crates/git/src/engines/git2/blame.rs b/crates/git/src/engines/git2/blame.rs index b6c72b9..8f1fc39 100644 --- a/crates/git/src/engines/git2/blame.rs +++ b/crates/git/src/engines/git2/blame.rs @@ -5,6 +5,16 @@ use crate::domain::history::{BlameLine, BlameResult}; use crate::domain::{ObjectId, RelativePath}; use crate::error::{GitError, Result}; +#[telemetry::trace(skip = [ + "final_commit_id", + "final_start_line", + "from_bytes", + "ignore_whitespace", + "is_boundary", + "lines_in_hunk", + "parse", + "sort_by_key", +])] pub fn blame(repo: &git2::Repository, query: &BlameQuery) -> Result { let path = RelativePath::parse(&query.path)?; let mut options = BlameOptions::default(); diff --git a/crates/git/src/engines/git2/chart.rs b/crates/git/src/engines/git2/chart.rs index bd30bd7..d643636 100644 --- a/crates/git/src/engines/git2/chart.rs +++ b/crates/git/src/engines/git2/chart.rs @@ -39,6 +39,7 @@ const SECONDS_PER_YEAR: i64 = 365 * SECONDS_PER_DAY + SECONDS_PER_QUARTER_DAY; /// without walking or diffing anything. `points` holds per-commit stats keyed /// by oid, which is what keeps a moved tip cheap: only commits that are /// genuinely new pay for a tree diff. +#[telemetry::trace] pub fn history_chart_with_store( session: &Git2Session, query: &HistoryChartQuery, diff --git a/crates/git/src/engines/git2/history.rs b/crates/git/src/engines/git2/history.rs index 4e70a50..ddbd1ca 100644 --- a/crates/git/src/engines/git2/history.rs +++ b/crates/git/src/engines/git2/history.rs @@ -14,6 +14,21 @@ use crate::engines::git2::session::Git2Session; use crate::error::{GitError, Result}; use crate::runtime::history_cache::CommitStatPoint; +#[telemetry::trace(skip = [ + "cloned", + "enumerate", + "filter", + "is_default_revision", + "is_merge", + "oid_bytes", + "stat", + "store_stat", + "store_summary", + "store_tags", + "store_walk", + "summary", + "with_capacity", +])] pub fn history_page( session: &Git2Session, query: &HistoryPageQuery, @@ -313,6 +328,7 @@ const PARALLEL_DELTA_THRESHOLD: usize = 16; /// commit across the rayon pool. A single commit touching hundreds of files is /// otherwise one indivisible task inside the commit-level parallel walk, so its /// blob reads and Myers runs pin one core while the rest idle. +#[telemetry::trace] pub(crate) fn per_delta_numstat( repo: &git2::Repository, pairs: &[(git2::Oid, git2::Oid)], diff --git a/crates/git/src/engines/git2/mutations.rs b/crates/git/src/engines/git2/mutations.rs index 440325e..ea09940 100644 --- a/crates/git/src/engines/git2/mutations.rs +++ b/crates/git/src/engines/git2/mutations.rs @@ -144,6 +144,7 @@ fn remove_empty_parents(workdir: &Path, rel: &RelativePath) { } } +#[telemetry::trace] pub fn commit( repo: &git2::Repository, request: &CommitRequest, @@ -241,6 +242,7 @@ pub fn amend(repo: &git2::Repository, request: &AmendRequest) -> Result Result<()> { let _gate = crate::engines::index_lock::gate(); if !request.paths.is_empty() { @@ -401,6 +403,7 @@ pub fn rename_branch( branch_info(repo, new.clone()) } +#[telemetry::trace] pub fn branch_ahead_behind( repo: &git2::Repository, head: &crate::domain::BranchName, @@ -421,6 +424,7 @@ pub fn branch_ahead_behind( }) } +#[telemetry::trace(skip = ["name", "shorthand", "sort_by"])] pub fn list_branches(repo: &git2::Repository) -> Result> { let head_shorthand = repo .head() @@ -506,6 +510,16 @@ fn build_upstream( }) } +#[telemetry::trace(skip = [ + "from_bytes", + "id", + "name", + "parse", + "peel_to_tag", + "short_from_full", + "sort_by", + "target", +])] pub fn list_tags(repo: &git2::Repository) -> Result> { let references = repo.references_glob("refs/tags/*")?; let mut tags = Vec::new(); diff --git a/crates/git/src/engines/git2/remotes.rs b/crates/git/src/engines/git2/remotes.rs index 41e306d..aaebce8 100644 --- a/crates/git/src/engines/git2/remotes.rs +++ b/crates/git/src/engines/git2/remotes.rs @@ -108,6 +108,7 @@ pub fn set_url(repo: &Repository, name: &str, url: &str) -> Result<()> { Ok(()) } +#[telemetry::trace] pub fn fetch( repo: &mut Repository, request: &FetchRequest, @@ -144,6 +145,7 @@ pub fn fetch( Ok(()) } +#[telemetry::trace] pub fn push( repo: &mut Repository, request: &PushRequest, diff --git a/crates/git/src/engines/git2/workflows.rs b/crates/git/src/engines/git2/workflows.rs index e2f7833..115c048 100644 --- a/crates/git/src/engines/git2/workflows.rs +++ b/crates/git/src/engines/git2/workflows.rs @@ -49,6 +49,7 @@ fn conflicted_paths(repo: &Repository) -> Result> { .collect()) } +#[telemetry::trace] pub fn merge(repo: &Repository, request: &MergeRequest) -> Result { let _gate = crate::engines::index_lock::gate(); if merge_in_progress(repo)? { @@ -748,6 +749,7 @@ pub fn stash_pop(repo: &mut Repository, request: &StashPopRequest) -> Result<()> Ok(()) } +#[telemetry::trace] pub fn start_rebase( repo: &Repository, upstream: &crate::domain::RevisionSpec, diff --git a/crates/git/src/engines/gix/status.rs b/crates/git/src/engines/gix/status.rs index 766b548..9fb8bac 100644 --- a/crates/git/src/engines/gix/status.rs +++ b/crates/git/src/engines/gix/status.rs @@ -33,6 +33,7 @@ fn internal(err: impl std::fmt::Display) -> GitError { } } +#[telemetry::trace(skip = ["cmp", "sort_by", "then_with", "SnapshotId", "Generation"])] pub fn status(session: &GixSession, opts: &ApiStatusOptions) -> Result { // The staged and worktree sides are independent computations sharing only // the session, so overlap them on two threads. Each builds its own diff --git a/crates/git/src/runtime/scheduler.rs b/crates/git/src/runtime/scheduler.rs index 87f7949..a304e2b 100644 --- a/crates/git/src/runtime/scheduler.rs +++ b/crates/git/src/runtime/scheduler.rs @@ -9,12 +9,15 @@ use crate::runtime::cancellation::CancellationToken; #[derive(Clone)] pub struct Scheduler { permits: Arc, + max_concurrent: usize, } impl Scheduler { pub fn new(max_concurrent: usize) -> Self { + let max_concurrent = max_concurrent.max(1); Self { - permits: Arc::new(Semaphore::new(max_concurrent.max(1))), + permits: Arc::new(Semaphore::new(max_concurrent)), + max_concurrent, } } @@ -27,13 +30,22 @@ impl Scheduler { F: FnOnce() -> Result + Send + 'static, { token.check()?; - let permit = self.permits.clone().acquire_owned().await?; + // The call-site span around `run` covers queue wait and job alike; this + // span isolates the wait, where the job body has not started yet. + let permit = { + let _queued = telemetry::SpanGuard::enter("scheduler.wait"); + telemetry::record_attribute("pool", telemetry::AttrValue::from(self.max_concurrent)); + self.permits.clone().acquire_owned().await? + }; let token_for_job = token.clone(); + let scope = telemetry::ScopeHandle::capture(); let join = tokio::task::spawn_blocking(move || { let _permit = permit; - let result = job(); - crate::engines::git2::local::clear_all_cached_handles(); - result + telemetry::attach_scope(scope, || { + let result = job(); + crate::engines::git2::local::clear_all_cached_handles(); + result + }) }); match join.await? { Ok(value) => Ok(value), diff --git a/crates/git/src/streaming/graph_pipeline.rs b/crates/git/src/streaming/graph_pipeline.rs index f7c2d4d..a2314d6 100644 --- a/crates/git/src/streaming/graph_pipeline.rs +++ b/crates/git/src/streaming/graph_pipeline.rs @@ -47,6 +47,7 @@ impl GraphJob { } } +#[telemetry::trace(name = "git.graph_stream")] pub fn run(job: GraphJob, op: Arc, tx: Sender) { match compute(&job, &op, &tx) { Ok(()) => {} @@ -85,6 +86,7 @@ impl<'a> Emitter<'a> { } } +#[telemetry::trace(skip = ["is_cancelled", "send"])] fn compute(job: &GraphJob, op: &Arc, tx: &Sender) -> Result<()> { let session = Git2Session::new(job.repo_path.clone()); let decorations = branch_decorations(&session)?; @@ -120,6 +122,9 @@ fn compute(job: &GraphJob, op: &Arc, tx: &Sender) -> }); } + telemetry::context! { + "rows" => emitted, + }; op.mark_complete(); emitter.send(GraphEvent::Completed { operation_id: job.operation_id, diff --git a/crates/git/src/streaming/pipeline.rs b/crates/git/src/streaming/pipeline.rs index 79e9dba..9e4056c 100644 --- a/crates/git/src/streaming/pipeline.rs +++ b/crates/git/src/streaming/pipeline.rs @@ -64,6 +64,7 @@ impl DiffJob { /// - `SectionLayout` for a section is emitted before any of its chunks. /// - Once emitted, a section's `start_row` and `row_count` never change. /// - Absolute row positions are therefore stable for the lifetime of the operation. +#[telemetry::trace(name = "git.diff_stream")] pub fn run(job: DiffJob, op: Arc, tx: Sender) { match compute(&job, &op, &tx) { Ok(()) => {} @@ -121,6 +122,7 @@ fn section_pool() -> &'static rayon::ThreadPool { }) } +#[telemetry::trace(skip = ["is_cancelled", "send", "set_started", "sum"])] fn compute(job: &DiffJob, op: &Arc, tx: &Sender) -> Result<()> { if op.is_cancelled() { return Err(GitError::Cancelled); @@ -131,6 +133,9 @@ fn compute(job: &DiffJob, op: &Arc, tx: &Sender) -> Re if op.is_cancelled() { return Err(GitError::Cancelled); } + telemetry::context! { + "sections" => plans.len() as u64, + }; let metas: Vec = plans.iter().map(|p| p.meta.clone()).collect(); let estimate: u64 = metas.iter().map(|m| if m.binary { 2 } else { 10 }).sum(); op.set_started(metas.clone(), estimate); @@ -282,6 +287,9 @@ fn compute(job: &DiffJob, op: &Arc, tx: &Sender) -> Re return Err(GitError::Cancelled); } + telemetry::context! { + "rows" => total_rows, + }; finish(op, &mut emitter, total_rows, started_at) } diff --git a/crates/tauri/Cargo.toml b/crates/tauri/Cargo.toml index c2a7f4f..5d49a7e 100644 --- a/crates/tauri/Cargo.toml +++ b/crates/tauri/Cargo.toml @@ -35,6 +35,8 @@ highlight.workspace = true icons.workspace = true log.workspace = true pico-args.workspace = true +reqwest.workspace = true +telemetry = { workspace = true, features = ["enabled"] } tauri-plugin-dialog.workspace = true tauri-plugin-log.workspace = true tauri-plugin-prevent-default.workspace = true diff --git a/crates/tauri/src/boot_trace.rs b/crates/tauri/src/boot_trace.rs deleted file mode 100644 index fb21d21..0000000 --- a/crates/tauri/src/boot_trace.rs +++ /dev/null @@ -1,150 +0,0 @@ -use std::collections::HashMap; -use std::sync::{Mutex, OnceLock}; -use std::time::{Instant, SystemTime, UNIX_EPOCH}; - -const MARKER: &str = "[boottrace]"; -const RUST_PID: u32 = 1; - -fn lanes() -> &'static Mutex> { - static LANES: OnceLock>> = OnceLock::new(); - LANES.get_or_init(|| Mutex::new(HashMap::new())) -} - -fn lane(name: &'static str) -> u32 { - let mut map = lanes() - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - if let Some(existing) = map.get(name) { - return *existing; - } - let next = map.len() as u32 + 1; - map.insert(name, next); - next -} - -fn micros(time: SystemTime) -> u128 { - time.duration_since(UNIX_EPOCH) - .map_or(0, |since| since.as_micros()) -} - -fn line(name: &'static str, detail: Option<&str>, ts: u128, dur: u128, tid: u32) -> String { - let args = match detail { - Some(detail) => { - let escaped = serde_json::Value::String(detail.to_owned()).to_string(); - format!(",\"args\":{{\"detail\":{escaped}}}") - } - None => String::new(), - }; - format!( - "{{\"name\":\"{name}\",\"cat\":\"boot\",\"ph\":\"X\",\"ts\":{ts},\"dur\":{dur},\"pid\":{RUST_PID},\"tid\":{tid}{args}}}" - ) -} - -fn emit(name: &'static str, detail: Option<&str>, started: u128, dur: u128) { - log::info!("{MARKER} {}", line(name, detail, started, dur, lane(name))); -} - -pub struct BootSpan { - name: &'static str, - detail: Option, - started_instant: Instant, - started_wall: SystemTime, - ended: bool, -} - -impl BootSpan { - pub fn end(mut self) { - self.finish(); - } - - fn finish(&mut self) { - if self.ended { - return; - } - self.ended = true; - emit( - self.name, - self.detail.as_deref(), - micros(self.started_wall), - self.started_instant.elapsed().as_micros(), - ); - } -} - -impl Drop for BootSpan { - fn drop(&mut self) { - self.finish(); - } -} - -fn make_span( - name: &'static str, - detail: Option, - started_instant: Instant, - started_wall: SystemTime, -) -> BootSpan { - BootSpan { - name, - detail, - started_instant, - started_wall, - ended: false, - } -} - -pub fn span(name: &'static str) -> BootSpan { - make_span(name, None, Instant::now(), SystemTime::now()) -} - -pub fn span_detailed(name: &'static str, detail: impl Into) -> BootSpan { - make_span(name, Some(detail.into()), Instant::now(), SystemTime::now()) -} - -pub fn record(name: &'static str, started_instant: Instant, started_wall: SystemTime) { - emit( - name, - None, - micros(started_wall), - started_instant.elapsed().as_micros(), - ); -} - -pub fn span_from( - name: &'static str, - started_instant: Instant, - started_wall: SystemTime, -) -> BootSpan { - make_span(name, None, started_instant, started_wall) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn line_is_chrome_trace_json() { - let text = line("rust.setup", None, 100, 50, 3); - let value: serde_json::Value = serde_json::from_str(&text).unwrap(); - assert_eq!(value["name"], "rust.setup"); - assert_eq!(value["cat"], "boot"); - assert_eq!(value["ph"], "X"); - assert_eq!(value["ts"], 100); - assert_eq!(value["dur"], 50); - assert_eq!(value["pid"], 1); - assert_eq!(value["tid"], 3); - assert!(value.get("args").is_none()); - } - - #[test] - fn detail_is_json_escaped() { - let text = line("git.open_repository", Some(r#"C:\a\"b"#), 1, 2, 4); - let value: serde_json::Value = serde_json::from_str(&text).unwrap(); - assert_eq!(value["args"]["detail"], r#"C:\a\"b"#); - } - - #[test] - fn lanes_are_stable_and_distinct() { - assert_eq!(lane("boot_trace_test_a"), lane("boot_trace_test_a")); - assert_ne!(lane("boot_trace_test_a"), lane("boot_trace_test_b")); - } -} diff --git a/crates/tauri/src/commands/changes.rs b/crates/tauri/src/commands/changes.rs index 22684ff..3fa8fc2 100644 --- a/crates/tauri/src/commands/changes.rs +++ b/crates/tauri/src/commands/changes.rs @@ -10,6 +10,15 @@ pub async fn git_status( state: SharedState<'_>, repo_id: u64, options: Option, +) -> CommandResult { + telemetry::scope(status(state, repo_id, options)).await +} + +#[telemetry::trace(skip = ["to_repo_id", "to_serialized"], name = "git.status")] +async fn status( + state: SharedState<'_>, + repo_id: u64, + options: Option, ) -> CommandResult { let started_at = std::time::Instant::now(); let report = state @@ -21,6 +30,12 @@ pub async fn git_status( ) .await .map_err(to_serialized)?; + telemetry::context! { + "staged" => report.staged_count() as u64, + "unstaged" => report.unstaged_count() as u64, + "conflicts" => report.conflicts.len() as u64, + "clean" => report.is_clean(), + }; log::info!("git_status repo {repo_id} in {:?}", started_at.elapsed()); Ok((*report).clone()) } @@ -99,6 +114,33 @@ pub async fn git_commit( author_email: Option, expected_generation: Option, on_event: Channel, +) -> CommandResult { + telemetry::scope(commit( + state, + repo_id, + message, + stage_all, + allow_empty, + author_name, + author_email, + expected_generation, + on_event, + )) + .await +} + +#[telemetry::trace(skip = ["to_repo_id", "to_serialized"], name = "git.commit")] +#[allow(clippy::too_many_arguments)] +async fn commit( + state: SharedState<'_>, + repo_id: u64, + message: String, + stage_all: Option, + allow_empty: Option, + author_name: Option, + author_email: Option, + expected_generation: Option, + on_event: Channel, ) -> CommandResult { let author = match (author_name, author_email) { (Some(name), Some(email)) => Some(git::domain::Signature { @@ -109,6 +151,8 @@ pub async fn git_commit( }), _ => None, }; + let stage_all = stage_all.unwrap_or(false); + let allow_empty = allow_empty.unwrap_or(false); let (events, forward) = forward_channel(on_event); let result = state .backend @@ -117,11 +161,11 @@ pub async fn git_commit( git::api::mutations::CommitRequest { message, author, - stage_all: stage_all.unwrap_or(false), + stage_all, // Real commits run the hook pipeline; results ride back so // the hook checker can display them. run_hooks: true, - allow_empty: allow_empty.unwrap_or(false), + allow_empty, }, expected_generation.map(Generation), Some(events), @@ -130,6 +174,18 @@ pub async fn git_commit( // Draining the forwarder first means the last hook line has landed before // the frontend sees the result, so nothing arrives out of order. let _ = forward.await; + telemetry::context! { + "stage_all" => stage_all, + "allow_empty" => allow_empty, + }; + if let Ok(execution) = &result { + telemetry::context! { + "files_changed" => u64::from(execution.summary.files_changed), + "additions" => execution.summary.additions, + "deletions" => execution.summary.deletions, + "hook_runs" => execution.hook_runs.len() as u64, + }; + } result.map_err(to_serialized) } diff --git a/crates/tauri/src/commands/mod.rs b/crates/tauri/src/commands/mod.rs index 0c7bbbb..034537f 100644 --- a/crates/tauri/src/commands/mod.rs +++ b/crates/tauri/src/commands/mod.rs @@ -5,10 +5,12 @@ pub type CommandResult = Result; pub use launch::spawn_detached; pub fn to_serialized(err: GitError) -> SerializedError { + telemetry::record_error(err.code(), &err); SerializedError::from(&err) } pub fn to_session_serialized(err: crate::session::SessionError) -> SerializedError { + telemetry::record_error(err.code(), &err); SerializedError { code: err.code(), message: error_message(&err), @@ -40,6 +42,7 @@ pub mod remotes; pub mod repository; pub mod session; pub mod settings; +pub mod startup; pub mod submodules; pub mod terminal; pub mod workflows; diff --git a/crates/tauri/src/commands/mutations.rs b/crates/tauri/src/commands/mutations.rs index 1835061..8441fff 100644 --- a/crates/tauri/src/commands/mutations.rs +++ b/crates/tauri/src/commands/mutations.rs @@ -139,15 +139,46 @@ pub async fn git_checkout( paths: Option>, expected_generation: Option, ) -> CommandResult<()> { + telemetry::scope(checkout( + state, + repo_id, + target, + force, + mode, + paths, + expected_generation, + )) + .await +} + +#[telemetry::trace(skip = ["to_repo_id", "to_serialized"], name = "git.checkout")] +#[allow(clippy::too_many_arguments)] +async fn checkout( + state: SharedState<'_>, + repo_id: u64, + target: String, + force: Option, + mode: Option, + paths: Option>, + expected_generation: Option, +) -> CommandResult<()> { + let force = force.unwrap_or(false); + let mode = mode.unwrap_or(CheckoutMode::Safe); + let paths = paths.unwrap_or_default(); + telemetry::context! { + "force" => force, + "mode" => format!("{mode:?}"), + "paths" => paths.len() as u64, + }; state .backend .checkout( to_repo_id(repo_id), CheckoutRequest { target: spec(target)?, - force: force.unwrap_or(false), - mode: mode.unwrap_or(CheckoutMode::Safe), - paths: paths.unwrap_or_default(), + force, + mode, + paths, }, gen(expected_generation), ) diff --git a/crates/tauri/src/commands/queries.rs b/crates/tauri/src/commands/queries.rs index 2dee9cf..74fb364 100644 --- a/crates/tauri/src/commands/queries.rs +++ b/crates/tauri/src/commands/queries.rs @@ -14,17 +14,39 @@ pub async fn git_history_page( state: SharedState<'_>, repo_id: u64, query: Option, +) -> CommandResult { + telemetry::scope(history_page(state, repo_id, query)).await +} + +#[telemetry::trace(skip = ["to_repo_id", "to_serialized"], name = "git.history_page")] +async fn history_page( + state: SharedState<'_>, + repo_id: u64, + query: Option, ) -> CommandResult { let started_at = std::time::Instant::now(); + let query = query.unwrap_or_default(); + let limit = query.limit; + let skip = query.skip; + let filtered = + query.search.is_some() || query.path.is_some() || !query.exclude_reachable_from.is_empty(); let page = state .backend .history_page( to_repo_id(repo_id), - query.unwrap_or_default(), + query, git::runtime::cancellation::CancellationToken::new(), ) .await .map_err(to_serialized)?; + telemetry::context! { + "limit" => u64::from(limit), + "skip" => skip, + "filtered" => filtered, + "commits" => page.commits.len() as u64, + "total" => u64::from(page.total), + "has_more" => page.has_more, + }; log::info!( "git_history_page repo {repo_id} in {:?}", started_at.elapsed() @@ -38,15 +60,32 @@ pub async fn git_history_chart( repo_id: u64, query: Option, ) -> CommandResult { + telemetry::scope(history_chart(state, repo_id, query)).await +} + +#[telemetry::trace(skip = ["to_repo_id", "to_serialized"], name = "git.history_chart")] +async fn history_chart( + state: SharedState<'_>, + repo_id: u64, + query: Option, +) -> CommandResult { + let query = query.unwrap_or_default(); + let include_merges = query.include_merges; let chart = state .backend .history_chart( to_repo_id(repo_id), - query.unwrap_or_default(), + query, git::runtime::cancellation::CancellationToken::new(), ) .await .map_err(to_serialized)?; + telemetry::context! { + "buckets" => chart.buckets.len() as u64, + "commits" => u64::from(chart.total_commits), + "include_merges" => include_merges, + "bucket_size" => format!("{:?}", chart.bucket_size), + }; Ok((*chart).clone()) } @@ -57,15 +96,35 @@ pub async fn git_commit_detail( revision: String, detect_renames: Option, ) -> CommandResult { + telemetry::scope(commit_detail(state, repo_id, revision, detect_renames)).await +} + +#[telemetry::trace( + skip = ["parse", "to_repo_id", "to_serialized"], + name = "git.commit_detail" +)] +async fn commit_detail( + state: SharedState<'_>, + repo_id: u64, + revision: String, + detect_renames: Option, +) -> CommandResult { + let detect_renames = detect_renames.unwrap_or(true); let query = CommitDetailQuery { revision: git::domain::RevisionSpec::parse(&revision).map_err(to_serialized)?, - detect_renames: detect_renames.unwrap_or(true), + detect_renames, }; let detail = state .backend .commit_detail(to_repo_id(repo_id), query, Default::default()) .await .map_err(to_serialized)?; + telemetry::context! { + "detect_renames" => detect_renames, + "files" => detail.detail.files.len() as u64, + "additions" => detail.detail.total_additions, + "deletions" => detail.detail.total_deletions, + }; Ok(detail.detail.clone()) } @@ -94,6 +153,17 @@ pub async fn git_blame( path: String, revision: Option, ) -> CommandResult { + telemetry::scope(blame(state, repo_id, path, revision)).await +} + +#[telemetry::trace(skip = ["parse", "to_repo_id", "to_serialized"], name = "git.blame")] +async fn blame( + state: SharedState<'_>, + repo_id: u64, + path: String, + revision: Option, +) -> CommandResult { + let has_revision = revision.is_some(); let revision = match revision { Some(spec) => Some(git::domain::RevisionSpec::parse(&spec).map_err(to_serialized)?), None => None, @@ -103,11 +173,16 @@ pub async fn git_blame( revision, ..Default::default() }; - state + let result = state .backend .blame(to_repo_id(repo_id), query, Default::default()) .await - .map_err(to_serialized) + .map_err(to_serialized)?; + telemetry::context! { + "has_revision" => has_revision, + "lines" => result.lines.len() as u64, + }; + Ok(result) } #[tauri::command] @@ -115,11 +190,24 @@ pub async fn git_list_branches_and_tags( state: SharedState<'_>, repo_id: u64, ) -> CommandResult { - state + telemetry::scope(repo_listing(state, repo_id)).await +} + +#[telemetry::trace( + skip = ["to_repo_id", "to_serialized"], + name = "git.list_branches_and_tags" +)] +async fn repo_listing(state: SharedState<'_>, repo_id: u64) -> CommandResult { + let listing = state .backend .list_branches_and_tags(to_repo_id(repo_id), Default::default()) .await - .map_err(to_serialized) + .map_err(to_serialized)?; + telemetry::context! { + "branches" => listing.branches.len() as u64, + "tags" => listing.tags.len() as u64, + }; + Ok(listing) } #[tauri::command] @@ -129,7 +217,17 @@ pub async fn git_branch_ahead_behind( head: String, base: String, ) -> CommandResult { - state + telemetry::scope(ahead_behind(state, repo_id, head, base)).await +} + +#[telemetry::trace(skip = ["to_repo_id", "to_serialized"], name = "git.ahead_behind")] +async fn ahead_behind( + state: SharedState<'_>, + repo_id: u64, + head: String, + base: String, +) -> CommandResult { + let result = state .backend .branch_ahead_behind( to_repo_id(repo_id), @@ -138,7 +236,12 @@ pub async fn git_branch_ahead_behind( git::runtime::cancellation::CancellationToken::new(), ) .await - .map_err(to_serialized) + .map_err(to_serialized)?; + telemetry::context! { + "ahead" => u64::from(result.ahead), + "behind" => u64::from(result.behind), + }; + Ok(result) } /// Returns `gitau-image` protocol URLs for an image section. The webview @@ -214,11 +317,26 @@ pub async fn git_open_graph( query: Option, on_event: Channel, ) -> CommandResult { + telemetry::scope(open_graph(state, repo_id, query, on_event)).await +} + +#[telemetry::trace(skip = ["to_repo_id", "to_serialized"], name = "git.open_graph")] +async fn open_graph( + state: SharedState<'_>, + repo_id: u64, + query: Option, + on_event: Channel, +) -> CommandResult { + let query = query.unwrap_or_default(); + telemetry::context! { + "has_revision" => query.revision.is_some(), + "exclusions" => query.exclude_reachable_from.len() as u64, + }; let (operation_id, rx) = state .backend .open_graph( to_repo_id(repo_id), - query.unwrap_or_default(), + query, git::runtime::cancellation::CancellationToken::new(), ) .await diff --git a/crates/tauri/src/commands/remotes.rs b/crates/tauri/src/commands/remotes.rs index 79da5ae..33ac6a7 100644 --- a/crates/tauri/src/commands/remotes.rs +++ b/crates/tauri/src/commands/remotes.rs @@ -104,13 +104,29 @@ pub async fn git_fetch( prune: Option, credential: Option, ) -> CommandResult<()> { + telemetry::scope(fetch(state, repo_id, remote, prune, credential)).await +} + +#[telemetry::trace(skip = ["to_repo_id", "to_serialized"], name = "git.fetch")] +async fn fetch( + state: SharedState<'_>, + repo_id: u64, + remote: Option, + prune: Option, + credential: Option, +) -> CommandResult<()> { + let prune = prune.unwrap_or(false); + telemetry::context! { + "prune" => prune, + "has_credential" => credential.is_some(), + }; state .backend .fetch( to_repo_id(repo_id), FetchRequest { remote: remote.unwrap_or_else(|| "origin".into()), - prune: prune.unwrap_or(false), + prune, credential, ..Default::default() }, @@ -130,15 +146,47 @@ pub async fn git_push( set_upstream: Option, credential: Option, ) -> CommandResult> { + telemetry::scope(push( + state, + repo_id, + remote, + refspecs, + force, + set_upstream, + credential, + )) + .await +} + +#[telemetry::trace(skip = ["to_repo_id", "to_serialized"], name = "git.push")] +#[allow(clippy::too_many_arguments)] +async fn push( + state: SharedState<'_>, + repo_id: u64, + remote: Option, + refspecs: Option>, + force: Option, + set_upstream: Option, + credential: Option, +) -> CommandResult> { + let refspecs = refspecs.unwrap_or_default(); + let force = force.unwrap_or(false); + let set_upstream = set_upstream.unwrap_or(false); + telemetry::context! { + "refspecs" => refspecs.len() as u64, + "force" => force, + "set_upstream" => set_upstream, + "has_credential" => credential.is_some(), + }; state .backend .push( to_repo_id(repo_id), PushRequest { remote: remote.unwrap_or_else(|| "origin".into()), - refspecs: refspecs.unwrap_or_default(), - force: force.unwrap_or(false), - set_upstream: set_upstream.unwrap_or(false), + refspecs, + force, + set_upstream, credential, }, git::runtime::cancellation::CancellationToken::new(), @@ -159,6 +207,39 @@ pub async fn git_pull( credential: Option, expected_generation: Option, ) -> CommandResult { + telemetry::scope(pull( + state, + repo_id, + remote, + branch, + fast_forward_only, + rebase, + credential, + expected_generation, + )) + .await +} + +#[telemetry::trace(skip = ["to_repo_id", "to_serialized"], name = "git.pull")] +#[allow(clippy::too_many_arguments)] +async fn pull( + state: SharedState<'_>, + repo_id: u64, + remote: Option, + branch: Option, + fast_forward_only: Option, + rebase: Option, + credential: Option, + expected_generation: Option, +) -> CommandResult { + let fast_forward_only = fast_forward_only.unwrap_or(false); + let rebase = rebase.unwrap_or(false); + telemetry::context! { + "has_branch" => branch.is_some(), + "fast_forward_only" => fast_forward_only, + "rebase" => rebase, + "has_credential" => credential.is_some(), + }; state .backend .pull( @@ -166,8 +247,8 @@ pub async fn git_pull( GitPullRequest { remote: remote.unwrap_or_else(|| "origin".into()), branch, - fast_forward_only: fast_forward_only.unwrap_or(false), - rebase: rebase.unwrap_or(false), + fast_forward_only, + rebase, credential, }, expected_generation.map(git::domain::Generation), @@ -185,6 +266,20 @@ pub async fn git_clone( request: CloneRequest, on_event: Channel, ) -> CommandResult { + telemetry::scope(clone(state, request, on_event)).await +} + +#[telemetry::trace(skip = ["to_repo_id", "to_serialized"], name = "git.clone")] +async fn clone( + state: SharedState<'_>, + request: CloneRequest, + on_event: Channel, +) -> CommandResult { + telemetry::context! { + "bare" => request.bare, + "depth" => u64::from(request.depth.unwrap_or(0)), + "has_credential" => request.credential.is_some(), + }; let (operation_id, mut rx) = state .backend .open_clone( diff --git a/crates/tauri/src/commands/repository.rs b/crates/tauri/src/commands/repository.rs index 5bbccbc..049ec7e 100644 --- a/crates/tauri/src/commands/repository.rs +++ b/crates/tauri/src/commands/repository.rs @@ -16,15 +16,30 @@ use tauri::AppHandle; pub async fn git_open_repository( state: SharedState<'_>, request: OpenRepositoryRequest, +) -> CommandResult { + telemetry::scope(open_repository(state, request)).await +} + +#[telemetry::trace(skip = ["to_repo_id", "to_serialized"], name = "git.open_repository")] +async fn open_repository( + state: SharedState<'_>, + request: OpenRepositoryRequest, ) -> CommandResult { let path = std::path::PathBuf::from(&request.path); - let span = crate::boot_trace::span_detailed("git.open_repository", request.path.as_str()); let opened = state .backend .open_repository(&path) .await .map_err(to_serialized)?; - span.end(); + let head = match &opened.snapshot.head { + git::domain::HeadState::Attached { .. } => "attached", + git::domain::HeadState::Detached { .. } => "detached", + git::domain::HeadState::Unborn { .. } => "unborn", + }; + telemetry::context! { + "has_worktree" => opened.snapshot.workdir.is_some(), + "head" => head, + }; Ok(opened) } @@ -142,11 +157,31 @@ pub async fn git_open_diff( request: Option, on_event: Channel, ) -> CommandResult { + telemetry::scope(open_diff(app, state, repo_id, request, on_event)).await +} + +#[telemetry::trace(skip = ["to_repo_id", "to_serialized"], name = "git.open_diff")] +async fn open_diff( + app: AppHandle, + state: SharedState<'_>, + repo_id: u64, + request: Option, + on_event: Channel, +) -> CommandResult { + let request = request.unwrap_or_default(); + telemetry::context! { + "paths" => request.paths.len() as u64, + "context_lines" => u64::from(request.context_lines), + "detect_renames" => request.detect_renames, + "detect_copies" => request.detect_copies, + "ignore_whitespace" => request.ignore_whitespace, + "comparison" => format!("{:?}", request.comparison), + }; let (operation_id, rx) = state .backend .open_diff( to_repo_id(repo_id), - request.unwrap_or_default(), + request, git::runtime::cancellation::CancellationToken::new(), ) .await diff --git a/crates/tauri/src/commands/session.rs b/crates/tauri/src/commands/session.rs index 9513b25..acac017 100644 --- a/crates/tauri/src/commands/session.rs +++ b/crates/tauri/src/commands/session.rs @@ -24,10 +24,19 @@ pub(crate) async fn open_session_repositories( backend: Arc, paths: Vec, ) -> Vec { + telemetry::scope(open_session_repositories_inner(backend, paths)).await +} + +#[telemetry::trace(skip = ["scope", "spawn"], name = "app.open_session_repositories")] +async fn open_session_repositories_inner( + backend: Arc, + paths: Vec, +) -> Vec { + let requested = paths.len() as u64; let mut set = tokio::task::JoinSet::new(); for path in paths { let backend = Arc::clone(&backend); - set.spawn(async move { + set.spawn(telemetry::scope(async move { match backend.open_repository(Path::new(&path)).await { Ok(opened) => SessionRepository { path, @@ -40,7 +49,7 @@ pub(crate) async fn open_session_repositories( error: Some(error.to_string()), }, } - }); + })); } let mut opened = Vec::new(); while let Some(joined) = set.join_next().await { @@ -48,6 +57,12 @@ pub(crate) async fn open_session_repositories( opened.push(repo); } } + let succeeded = opened.iter().filter(|repo| repo.repo_id.is_some()).count() as u64; + telemetry::context! { + "requested" => requested, + "opened" => succeeded, + "failed" => opened.len() as u64 - succeeded, + }; opened } @@ -56,6 +71,15 @@ pub async fn session_repositories( state: SharedState<'_>, paths: Vec, ) -> CommandResult> { + telemetry::scope(restore_repositories(state, paths)).await +} + +#[telemetry::trace(name = "app.session_repositories")] +async fn restore_repositories( + state: SharedState<'_>, + paths: Vec, +) -> CommandResult> { + let requested = paths.len() as u64; let backend = Arc::clone(&state.backend); let cell = Arc::clone(&state.startup_repos); let session_paths = crate::session::repo_paths(&state.session.load()); @@ -82,5 +106,11 @@ pub async fn session_repositories( }, }); } + let opened = out.iter().filter(|repo| repo.repo_id.is_some()).count() as u64; + telemetry::context! { + "requested" => requested, + "opened" => opened, + "failed" => out.len() as u64 - opened, + }; Ok(out) } diff --git a/crates/tauri/src/commands/settings.rs b/crates/tauri/src/commands/settings.rs index b08890c..53973a3 100644 --- a/crates/tauri/src/commands/settings.rs +++ b/crates/tauri/src/commands/settings.rs @@ -29,6 +29,15 @@ pub fn settings_set( if key == SYNTAX_THEME_LIGHT_KEY || key == SYNTAX_THEME_DARK_KEY { apply_syntax_theme(&state); } + if key == crate::telemetry_service::ENABLED_SETTING_KEY { + crate::telemetry_service::set_enabled( + snapshot + .values + .get(crate::telemetry_service::ENABLED_SETTING_KEY) + .and_then(SettingValue::as_bool) + .unwrap_or(false), + ); + } Ok(snapshot) } diff --git a/crates/tauri/src/commands/startup.rs b/crates/tauri/src/commands/startup.rs new file mode 100644 index 0000000..395ddc8 --- /dev/null +++ b/crates/tauri/src/commands/startup.rs @@ -0,0 +1,26 @@ +use serde::Deserialize; + +use crate::commands::CommandResult; +use crate::state::SharedState; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LaunchMarks { + pub bootstrap_ms: u64, + pub render_ms: u64, +} + +/// Closes the `app.launch` span once the webview has committed its first frame. +#[tauri::command] +pub fn app_launch_ready(state: SharedState<'_>, marks: LaunchMarks) -> CommandResult<()> { + let mut slot = state + .launch + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let Some(launch) = slot.take() else { + return Ok(()); + }; + launch.set_attribute("js_bootstrap_ms", marks.bootstrap_ms.into()); + launch.set_attribute("js_render_ms", marks.render_ms.into()); + Ok(()) +} diff --git a/crates/tauri/src/lib.rs b/crates/tauri/src/lib.rs index a2cf5aa..e43a1fd 100644 --- a/crates/tauri/src/lib.rs +++ b/crates/tauri/src/lib.rs @@ -1,8 +1,8 @@ -mod boot_trace; mod commands; pub mod session; pub mod settings; mod state; +mod telemetry_service; use std::sync::Arc; @@ -55,10 +55,6 @@ fn runtime_attrs() -> tauri_runtime_wry::Wry { #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { - // The webview stays hidden until it finishes loading, so the elapsed - // logged there is the perceived launch time. - let started_at = std::time::Instant::now(); - let started_wall = std::time::SystemTime::now(); tauri::Builder::default() .runtime(runtime_attrs()) .plugin( @@ -94,8 +90,8 @@ pub fn run() { .manage(AppState::default()) .setup(move |app| { let handle = app.handle().clone(); - let _launch = boot_trace::span_from("rust.launch", started_at, started_wall); - let _hook = boot_trace::span("rust.setup.hook"); + crate::telemetry_service::initialize(&app.package_info().version.to_string()); + let setup_started = std::time::Instant::now(); // Wayland gives a client no way to place a toplevel, and CEF's child // X11 host window consumes the pointer press, so a frameless window @@ -111,7 +107,6 @@ pub fn run() { // Settings live in the platform config dir; if it is unavailable // the store keeps operating on in-memory defaults. let state = handle.state::(); - let settings_span = boot_trace::span("rust.settings.init"); match handle.path().app_config_dir() { Ok(config_dir) => { state.settings.initialize(config_dir.join("settings.json")); @@ -121,11 +116,23 @@ pub fn run() { log::warn!("app config dir unavailable; settings stay in memory: {error}"); } } - settings_span.end(); + + crate::telemetry_service::set_enabled( + state + .settings + .get(crate::telemetry_service::ENABLED_SETTING_KEY) + .and_then(|value| value.as_bool()) + .unwrap_or(false), + ); + let launch = + telemetry::sync_scope_unconditional(|| telemetry::SpanGuard::enter("app.launch")); + launch.set_attribute( + "settings_us", + (setup_started.elapsed().as_micros() as u64).into(), + ); // Remote icons and remote repo info caches under the platform // cache dir; without it both stay in-memory only. - let cache_span = boot_trace::span("rust.cache.init"); match handle.path().app_cache_dir() { Ok(cache_dir) => { state.icons.initialize(cache_dir.join("remote-icons")); @@ -140,12 +147,14 @@ pub fn run() { log::warn!("app cache dir unavailable; icons stay in memory: {error}"); } } - cache_span.end(); + launch.set_attribute( + "caches_us", + (setup_started.elapsed().as_micros() as u64).into(), + ); // The whole UI session (tabs + open repos) lives beside settings. // `--session ` overrides it so the dev workspace can run // against a fixture file. - let session_span = boot_trace::span("rust.session.init"); if let Some(path) = crate::session::session_path_override() { // A missing override would silently start empty (the store // treats it as first run), which looks like the flag was @@ -170,9 +179,9 @@ pub fn run() { } } } - session_span.end(); let session_paths = crate::session::repo_paths(&state.session.load()); + let session_repo_count = session_paths.len() as u64; if !session_paths.is_empty() { let cell = Arc::clone(&state.startup_repos); let backend = Arc::clone(&state.backend); @@ -184,10 +193,14 @@ pub fn run() { .await; }); } + launch.set_attribute( + "session_us", + (setup_started.elapsed().as_micros() as u64).into(), + ); + launch.set_attribute("repos", session_repo_count.into()); // Forge connection profile cache beside settings; access tokens // themselves live in the OS keychain, never on this path. - let forge_span = boot_trace::span("rust.forge.init"); match handle.path().app_config_dir() { Ok(config_dir) => { state @@ -199,7 +212,6 @@ pub fn run() { log::warn!("app config dir unavailable; forge accounts stay in memory: {error}"); } } - forge_span.end(); // Periodically revalidate stale owner/org avatars in the // background for as long as the process lives. Setup runs on the @@ -216,7 +228,6 @@ pub fn run() { let cleanup_icons = Arc::clone(&state.icons); let cleanup_backend = Arc::clone(&state.backend); tauri::async_runtime::spawn_blocking(move || { - let _span = boot_trace::span("rust.cache_cleanup"); let icons_removed = cleanup_icons.prune_old_entries(icons::IconConfig::default().prune_after); let info_removed = cleanup_backend @@ -232,17 +243,23 @@ pub fn run() { // Persisted syntax themes must be active before the warm-up // snapshot is taken, otherwise the first diffs use defaults. - let theme_span = boot_trace::span("rust.apply_syntax_theme"); commands::settings::apply_syntax_theme(&handle.state::()); - theme_span.end(); // Warm the syntax highlighter (grammar dumps + embedded themes) // off the main thread so the first diff paints fully styled. tauri::async_runtime::spawn_blocking(|| { - let _span = boot_trace::span("rust.warmup.highlight"); highlight::warm_up(); }); + launch.set_attribute( + "setup_us", + (setup_started.elapsed().as_micros() as u64).into(), + ); + *state + .launch + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(launch); + let mut rx = handle.state::().backend.subscribe_invalidations(); tauri::async_runtime::spawn(async move { use tauri::Emitter; @@ -272,9 +289,16 @@ pub fn run() { if let Err(error) = state.session.persist_current() { log::error!("could not flush session on close: {error}"); } + let _ = state + .launch + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take(); + crate::telemetry_service::flush(); } }) .invoke_handler(tauri::generate_handler![ + commands::startup::app_launch_ready, commands::repository::git_open_repository, commands::repository::git_close_repository, commands::repository::git_remove_repository, @@ -405,50 +429,28 @@ pub fn run() { commands::session::session_save, commands::session::session_repositories, ]) - .on_page_load({ - let navigation = std::sync::Arc::new(std::sync::Mutex::new(None)); - move |webview, payload| { - if webview.label() != "main" { - return; - } - let lock = || { - navigation - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - }; - match payload.event() { - tauri::webview::PageLoadEvent::Started => { - let started = (std::time::Instant::now(), std::time::SystemTime::now()); - *lock() = Some(started); - boot_trace::record( - "rust.webview.contentStart", - started_at, - started_wall, - ); - } - tauri::webview::PageLoadEvent::Finished => { - boot_trace::record("rust.webview.load", started_at, started_wall); - let content_started = lock().take(); - if let Some((instant, wall)) = content_started { - boot_trace::record("rust.webview.content", instant, wall); - } - // The frontend reveals the window once the theme is - // applied and the first frame has committed, so the - // pre-render page never becomes visible. This is the - // fallback for a frontend that never gets that far - // (bundle failure, crash before render): without it the - // window would stay hidden with nothing on screen to - // explain why. - let window = webview.window(); - tauri::async_runtime::spawn(async move { - tokio::time::sleep(std::time::Duration::from_secs(3)).await; - if !matches!(window.is_visible(), Ok(true)) { - let _ = window.show(); - } - }); - } - } + .on_page_load(|webview, payload| { + if webview.label() != "main" + || !matches!( + payload.event(), + tauri::webview::PageLoadEvent::Finished + ) + { + return; } + // The frontend reveals the window once the theme is applied and + // the first frame has committed, so the pre-render page never + // becomes visible. This is the fallback for a frontend that never + // gets that far (bundle failure, crash before render): without it + // the window would stay hidden with nothing on screen to explain + // why. + let window = webview.window(); + tauri::async_runtime::spawn(async move { + tokio::time::sleep(std::time::Duration::from_secs(3)).await; + if !matches!(window.is_visible(), Ok(true)) { + let _ = window.show(); + } + }); }) .run(tauri::generate_context!()) .expect("error while running tauri application"); diff --git a/crates/tauri/src/settings/mod.rs b/crates/tauri/src/settings/mod.rs index 7693fae..03fc33a 100644 --- a/crates/tauri/src/settings/mod.rs +++ b/crates/tauri/src/settings/mod.rs @@ -151,6 +151,10 @@ mod tests { snapshot.values.get("pinnedRepos"), Some(&SettingValue::StringList(Vec::new())) ); + assert_eq!( + snapshot.values.get("telemetryEnabled"), + Some(&SettingValue::Bool(false)) + ); assert!(snapshot.saved_keys.is_empty()); } diff --git a/crates/tauri/src/settings/schema.rs b/crates/tauri/src/settings/schema.rs index f7c7efd..d3735b5 100644 --- a/crates/tauri/src/settings/schema.rs +++ b/crates/tauri/src/settings/schema.rs @@ -230,6 +230,17 @@ pub fn builtin() -> SettingsSchema { .default_value(SettingValue::Str(String::new())), ], }, + SettingsSection { + id: "privacy", + title: "Privacy", + settings: vec![ + boolean("telemetryEnabled", "Send anonymous telemetry") + .description( + "Share anonymous timing and error data to help improve Gitau. Repository names, paths, branch names, and file contents are never sent.", + ) + .default_value(SettingValue::Bool(false)), + ], + }, ], }, SettingsTab { diff --git a/crates/tauri/src/state.rs b/crates/tauri/src/state.rs index abaa69e..fcda786 100644 --- a/crates/tauri/src/state.rs +++ b/crates/tauri/src/state.rs @@ -1,4 +1,4 @@ -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use git::{Backend, BackendConfig, ForgeIconSource}; use icons::{HttpFetcher, IconConfig, IconService}; @@ -13,6 +13,7 @@ pub struct AppState { pub session: Arc, pub icons: Arc, pub startup_repos: Arc>>, + pub launch: Mutex>, } #[derive(Clone, Serialize)] @@ -41,6 +42,7 @@ impl Default for AppState { icon_source, )), startup_repos: Arc::new(tokio::sync::OnceCell::new()), + launch: Mutex::new(None), } } } diff --git a/crates/tauri/src/telemetry_service.rs b/crates/tauri/src/telemetry_service.rs new file mode 100644 index 0000000..b98e606 --- /dev/null +++ b/crates/tauri/src/telemetry_service.rs @@ -0,0 +1,77 @@ +use std::sync::Arc; +use std::time::Duration; + +use tokio::sync::mpsc; +use tokio::sync::mpsc::UnboundedReceiver; + +const DEFAULT_ENDPOINT: &str = "https://gitau-telemetry.arathia.net/v1/batches"; +const FLUSH_INTERVAL: Duration = Duration::from_secs(15); + +pub(crate) const ENABLED_SETTING_KEY: &str = "telemetryEnabled"; + +pub fn initialize(app_version: &str) { + if !telemetry::is_available() { + return; + } + + let endpoint = + std::env::var("GITAU_TELEMETRY_URL").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned()); + let (sender, receiver) = mpsc::unbounded_channel(); + let sink = telemetry::CallbackSink::new(move |batch| { + let _ = sender.send(batch.to_json()); + }); + let config = telemetry::Config::new(telemetry::EnvironmentContext::detect(app_version)) + .enabled(false) + .sample_permille(if cfg!(debug_assertions) { 1000 } else { 250 }) + .buffer_capacity(128); + + if let Err(error) = telemetry::init(config, vec![Arc::new(sink)]) { + log::warn!("telemetry could not start: {error}"); + return; + } + + tauri::async_runtime::spawn(deliver(receiver, endpoint)); + tauri::async_runtime::spawn(async move { + let mut ticker = tokio::time::interval(FLUSH_INTERVAL); + ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + ticker.tick().await; + flush(); + } + }); +} + +async fn deliver(mut receiver: UnboundedReceiver, endpoint: String) { + let client = reqwest::Client::new(); + while let Some(body) = receiver.recv().await { + match client + .post(&endpoint) + .header(reqwest::header::CONTENT_TYPE, "application/json") + .body(body) + .send() + .await + { + Ok(response) if !response.status().is_success() => { + log::warn!("telemetry upload rejected: {}", response.status()); + } + Ok(_) => {} + Err(error) => log::warn!("telemetry upload failed: {error}"), + } + } +} + +pub(crate) fn set_enabled(enabled: bool) { + telemetry::set_enabled(enabled); +} + +pub fn flush() { + let report = telemetry::flush(); + if report.traces > 0 || report.errors > 0 { + log::debug!( + "telemetry flushed {} traces, {} errors, {} dropped", + report.traces, + report.errors, + report.dropped_traces + ); + } +} diff --git a/crates/telemetry-macros/Cargo.toml b/crates/telemetry-macros/Cargo.toml new file mode 100644 index 0000000..712ea35 --- /dev/null +++ b/crates/telemetry-macros/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "telemetry-macros" +version.workspace = true +edition = "2021" +rust-version.workspace = true +description = "Call-site instrumentation macro for the telemetry crate" + +[lib] +proc-macro = true + +[features] +default = [] +enabled = ["dep:proc-macro2", "dep:quote", "dep:syn"] + +[dependencies] +proc-macro2 = { workspace = true, optional = true } +quote = { workspace = true, optional = true } +syn = { workspace = true, optional = true } diff --git a/crates/telemetry-macros/src/lib.rs b/crates/telemetry-macros/src/lib.rs new file mode 100644 index 0000000..3656dc6 --- /dev/null +++ b/crates/telemetry-macros/src/lib.rs @@ -0,0 +1,475 @@ +//! Compile-time call-site instrumentation for the `telemetry` crate. +//! +//! `#[trace]` wraps the annotated function in a span and every non-noise call +//! expression inside its body in a short-lived guard. With the `enabled` +//! feature off the attribute is a pass-through and the crate compiles to +//! nothing. + +#[cfg(feature = "enabled")] +use proc_macro2::{Ident, Span, TokenStream}; +#[cfg(feature = "enabled")] +use quote::quote; +#[cfg(feature = "enabled")] +use std::collections::BTreeSet; +#[cfg(feature = "enabled")] +use syn::{ + bracketed, + parse::{Parse, ParseStream}, + parse_quote, + punctuated::Punctuated, + visit_mut::{self, VisitMut}, + Error, Expr, ItemFn, LitStr, Result, Token, +}; + +#[proc_macro_attribute] +pub fn trace( + attr: proc_macro::TokenStream, + item: proc_macro::TokenStream, +) -> proc_macro::TokenStream { + #[cfg(feature = "enabled")] + { + expand(attr.into(), item.into()).into() + } + #[cfg(not(feature = "enabled"))] + { + let _ = attr; + item + } +} + +#[cfg(feature = "enabled")] +fn expand(attr: TokenStream, item: TokenStream) -> TokenStream { + let mut function: ItemFn = match syn::parse2(item.clone()) { + Ok(function) => function, + Err(_) => return item, + }; + + let args: TraceArgs = match syn::parse2(attr) { + Ok(args) => args, + Err(error) => return error.to_compile_error(), + }; + + if function.sig.constness.is_some() { + return quote!(#function); + } + + let name = args + .name + .unwrap_or_else(|| LitStr::new(&ident_name(&function.sig.ident), Span::call_site())); + + let mut body = (*function.block).clone(); + if !args.span_only { + let mut instrumenter = Instrumenter { skip: args.skip }; + instrumenter.visit_block_mut(&mut body); + } + + let stmts = body.stmts; + let guard = Ident::new("__telemetry_span", Span::mixed_site()); + *function.block = parse_quote!({ + let #guard = ::telemetry::SpanGuard::enter_function(#name); + #(#stmts)* + }); + + quote!(#function) +} + +#[cfg(feature = "enabled")] +#[derive(Default)] +struct TraceArgs { + name: Option, + skip: BTreeSet, + span_only: bool, +} + +#[cfg(feature = "enabled")] +impl Parse for TraceArgs { + fn parse(input: ParseStream<'_>) -> Result { + let mut args = TraceArgs::default(); + while !input.is_empty() { + let ident: Ident = input.parse()?; + match ident.to_string().as_str() { + "name" => { + input.parse::()?; + args.name = Some(input.parse()?); + } + "skip" => { + input.parse::()?; + let content; + bracketed!(content in input); + let names = Punctuated::::parse_terminated(&content)?; + args.skip.extend(names.iter().map(LitStr::value)); + } + "span_only" => args.span_only = true, + other => { + return Err(Error::new( + ident.span(), + format!( + "unknown telemetry argument `{other}`; expected `name`, `skip`, or `span_only`" + ), + )); + } + } + if !input.is_empty() { + input.parse::()?; + } + } + Ok(args) + } +} + +#[cfg(feature = "enabled")] +struct Instrumenter { + skip: BTreeSet, +} + +#[cfg(feature = "enabled")] +impl Instrumenter { + fn should_wrap(&self, name: &str) -> bool { + !name.is_empty() + && !is_noise(name) + && !self.skip.contains(name) + && !name.starts_with("__telemetry") + } +} + +#[cfg(feature = "enabled")] +impl VisitMut for Instrumenter { + fn visit_item_mut(&mut self, _item: &mut syn::Item) {} + + fn visit_expr_repeat_mut(&mut self, repeat: &mut syn::ExprRepeat) { + self.visit_expr_mut(&mut repeat.expr); + } + + fn visit_generic_argument_mut(&mut self, argument: &mut syn::GenericArgument) { + if !matches!(argument, syn::GenericArgument::Const(_)) { + visit_mut::visit_generic_argument_mut(self, argument); + } + } + + fn visit_expr_mut(&mut self, expr: &mut Expr) { + match expr { + Expr::Const(_) => {} + Expr::Await(await_expr) => { + let name = callee_name(&await_expr.base); + match await_expr.base.as_mut() { + Expr::Call(call) => { + self.visit_expr_mut(&mut call.func); + for arg in &mut call.args { + self.visit_expr_mut(arg); + } + } + Expr::MethodCall(method) => { + self.visit_expr_mut(&mut method.receiver); + for arg in &mut method.args { + self.visit_expr_mut(arg); + } + } + base => self.visit_expr_mut(base), + } + if let Some(name) = name.filter(|name| self.should_wrap(name)) { + wrap_await(expr, &name); + } + } + Expr::Call(_) | Expr::MethodCall(_) => { + let name = match expr { + Expr::Call(call) if !is_std_path(&call.func) => callee_name(&call.func), + Expr::Call(_) => None, + Expr::MethodCall(method) => Some(ident_name(&method.method)), + _ => None, + }; + visit_mut::visit_expr_mut(self, expr); + if let Some(name) = name.filter(|name| self.should_wrap(name)) { + wrap(expr, &name); + } + } + other => visit_mut::visit_expr_mut(self, other), + } + } +} + +#[cfg(feature = "enabled")] +fn wrap(expr: &mut Expr, name: &str) { + let name = LitStr::new(name, Span::call_site()); + let original = std::mem::replace(expr, Expr::Verbatim(TokenStream::new())); + *expr = parse_quote!(::telemetry::finish_call( + ::telemetry::SpanGuard::enter(#name), + #original + )); +} + +#[cfg(feature = "enabled")] +fn wrap_await(expr: &mut Expr, name: &str) { + let Expr::Await(await_expr) = expr else { + return; + }; + let name = LitStr::new(name, Span::call_site()); + let base = std::mem::replace( + &mut await_expr.base, + Box::new(Expr::Verbatim(TokenStream::new())), + ); + *expr = parse_quote!(::telemetry::finish_await( + ::telemetry::SpanGuard::enter(#name), + #base + ) + .await); +} + +#[cfg(feature = "enabled")] +fn callee_name(expr: &Expr) -> Option { + match expr { + Expr::Call(call) => callee_name(&call.func), + Expr::MethodCall(method) => Some(ident_name(&method.method)), + Expr::Paren(paren) => callee_name(&paren.expr), + Expr::Path(path) => path + .path + .segments + .last() + .map(|segment| ident_name(&segment.ident)), + _ => None, + } +} + +#[cfg(feature = "enabled")] +fn ident_name(ident: &Ident) -> String { + let name = ident.to_string(); + name.strip_prefix("r#").unwrap_or(&name).to_string() +} + +#[cfg(feature = "enabled")] +fn is_std_path(expr: &Expr) -> bool { + let Expr::Path(path) = expr else { + return false; + }; + let Some(first) = path.path.segments.first() else { + return false; + }; + matches!(first.ident.to_string().as_str(), "std" | "core" | "alloc") +} + +#[cfg(feature = "enabled")] +fn is_noise(name: &str) -> bool { + matches!( + name, + "clone" + | "clone_from" + | "unwrap" + | "unwrap_or" + | "unwrap_or_else" + | "unwrap_or_default" + | "expect" + | "expect_err" + | "ok" + | "err" + | "is_ok" + | "is_err" + | "is_some" + | "is_none" + | "as_ref" + | "as_mut" + | "as_str" + | "as_slice" + | "as_bytes" + | "as_path" + | "as_deref" + | "to_string" + | "to_owned" + | "to_vec" + | "to_path_buf" + | "into" + | "from" + | "from_millis" + | "from_micros" + | "from_nanos" + | "from_secs" + | "from_secs_f32" + | "from_secs_f64" + | "new" + | "default" + | "wrapping_add" + | "wrapping_sub" + | "wrapping_mul" + | "wrapping_div" + | "wrapping_rem" + | "wrapping_neg" + | "wrapping_shl" + | "wrapping_shr" + | "saturating_add" + | "saturating_sub" + | "saturating_mul" + | "saturating_div" + | "checked_add" + | "checked_sub" + | "checked_mul" + | "checked_div" + | "checked_rem" + | "overflowing_add" + | "overflowing_sub" + | "overflowing_mul" + | "rotate_left" + | "rotate_right" + | "leading_zeros" + | "trailing_zeros" + | "count_ones" + | "abs" + | "min" + | "max" + | "pow" + | "as_nanos" + | "as_micros" + | "as_millis" + | "as_secs" + | "subsec_nanos" + | "subsec_micros" + | "subsec_millis" + | "to_le_bytes" + | "to_be_bytes" + | "to_bits" + | "from_bits" + | "now" + | "len" + | "is_empty" + | "iter" + | "iter_mut" + | "into_iter" + | "collect" + | "map" + | "and_then" + | "map_err" + | "ok_or" + | "ok_or_else" + | "or" + | "or_else" + | "insert" + | "get" + | "get_mut" + | "contains" + | "contains_key" + | "push" + | "pop" + | "first" + | "last" + | "next" + | "extend" + | "borrow" + | "borrow_mut" + | "deref" + | "drop" + | "record_attribute" + | "record_error" + | "record_error_detail" + | "record_error_message" + | "Some" + | "Ok" + | "Err" + ) +} + +#[cfg(all(test, feature = "enabled"))] +mod tests { + use super::*; + + #[test] + fn filters_noise_by_name() { + assert!(is_noise("clone")); + assert!(is_noise("unwrap")); + assert!(is_noise("wrapping_add")); + assert!(is_noise("saturating_mul")); + assert!(!is_noise("fetch_staged")); + assert!(!is_noise("compute_diff")); + } + + #[test] + fn rejects_unknown_arguments() { + let parsed = syn::parse2::(quote!(nope = "x")); + assert!(parsed.is_err()); + } + + #[test] + fn adds_a_span_and_call_guards() { + let output = expand( + TokenStream::new(), + quote!( + fn load() { + let fetched = fetch().await; + let copy = fetched.clone(); + consume(copy); + } + ), + ) + .to_string(); + + assert!(output.contains("SpanGuard")); + assert!(output.contains("\"load\"")); + assert!(output.contains("\"fetch\"")); + assert!(output.contains("\"consume\"")); + assert!(!output.contains("\"clone\"")); + } + + #[test] + fn renames_the_root_span() { + let output = expand( + quote!(name = "diff.stream"), + quote!( + fn load() { + fetch(); + } + ), + ) + .to_string(); + + assert!(output.contains("\"diff.stream\"")); + assert!(!output.contains("\"load\"")); + } + + #[test] + fn leaves_const_functions_alone() { + let input = quote!( + const fn load() -> usize { + fetch() + } + ); + assert!(!expand(TokenStream::new(), input) + .to_string() + .contains("SpanGuard")); + } + + #[test] + fn skips_standard_library_calls() { + let output = expand( + TokenStream::new(), + quote!( + fn load() { + std::fs::read("x"); + } + ), + ) + .to_string(); + + assert!(!output.contains("\"read\"")); + } + + #[test] + fn honours_skip_and_span_only() { + let skipped = expand( + quote!(skip = ["expensive_but_known"]), + quote!( + fn load() { + expensive_but_known(); + } + ), + ) + .to_string(); + assert!(!skipped.contains("\"expensive_but_known\"")); + + let span_only = expand( + quote!(span_only), + quote!( + fn load() { + expensive_but_known(); + } + ), + ) + .to_string(); + assert!(!span_only.contains("\"expensive_but_known\"")); + } +} diff --git a/crates/telemetry/Cargo.toml b/crates/telemetry/Cargo.toml new file mode 100644 index 0000000..25920d2 --- /dev/null +++ b/crates/telemetry/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "telemetry" +version.workspace = true +edition = "2021" +rust-version.workspace = true +description = "Optional anonymous timing and error telemetry with compile-time call-site instrumentation" + +[features] +default = [] +enabled = ["dep:quanta", "dep:tokio", "telemetry-macros/enabled"] + +[dependencies] +quanta = { workspace = true, optional = true } +serde.workspace = true +serde_json.workspace = true +telemetry-macros = { path = "../telemetry-macros", default-features = false } +thiserror.workspace = true +tokio = { workspace = true, optional = true } + +[dev-dependencies] +criterion.workspace = true +tempfile.workspace = true +tokio.workspace = true + +[[example]] +name = "waterfall" +required-features = ["enabled"] + +[[bench]] +name = "overhead" +harness = false +required-features = ["enabled"] diff --git a/crates/telemetry/README.md b/crates/telemetry/README.md new file mode 100644 index 0000000..42ffad6 --- /dev/null +++ b/crates/telemetry/README.md @@ -0,0 +1,290 @@ +# telemetry + +Optional, anonymous timing and error telemetry for the Rust side of the app. +Two crates: `telemetry` holds the runtime, `telemetry-macros` holds the +attribute that rewrites call sites. A proc-macro crate cannot export the +runtime, so the split is required. + +Nothing is collected unless a build opts in with the `enabled` feature and the +app calls `init` with collection enabled after consent. + +## Instrumenting code + +```rust +use telemetry::trace; + +#[trace] +async fn load_staged_diffs(repo: &Repo) -> Result { + let staged = fetch_staged(repo).await?; + let parsed = parse(&staged)?; + Ok(parsed) +} +``` + +The attribute does two things: + +1. Opens a span named after the function and closes it when the function + returns, including early returns and `?`. +2. Wraps every call inside the body in a short-lived guard, so + `fetch_staged(...).await` and `parse(&staged)` become child spans. + +Calls inside nested items and `const` blocks are left alone. Calls invoked +inside macro bodies (`format!`, `vec!`, `tracing::info!`) are not seen by the +AST pass and are not instrumented. Standard library calls and a fixed list of +cheap methods (`.clone()`, `.unwrap()`, `.map()`, `.len()`, constructors, and +so on) are skipped. + +Arguments control the pass: + +```rust +#[trace(name = "diff.stream", skip = ["render_hunk"], span_only)] +fn stream(...) { ... } +``` + +- `name = "..."` renames the root span. +- `skip = ["fn_name"]` leaves matching call names uninstrumented. +- `span_only` keeps the function span and skips all call-site guards. + +For one call, wrap it in `telemetry::skip!` instead: + +```rust +let thumbnail = telemetry::skip!(decode_thumbnail(&bytes)); +``` + +The wrapped expression and every call nested inside it stay out of the trace. + +## Performance + +The cost depends on which switch is off: + +| State | Cost | +| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | +| Feature off | Zero. The attribute is a pass-through and every entry point is a no-op. | +| Feature on, runtime off | One relaxed atomic load per instrumented call site. No clock reads, no allocation. | +| Feature on, enabled | Per span: a state lookup, two clock reads, one spinlock pair, and an arena push and pop. Child links are rebuilt in `flush`, not during capture. | + +The benchmark in `benches/overhead.rs` covers primitive costs, a flat call +loop, a nested CPU-bound load with 137 spans and attributes, an async load with +await points, a 16-trace flush, and the runtime-off path: + +```bash +cargo bench -p telemetry --bench overhead --features enabled +``` + +Measured on a Windows desktop with a 1 s warmup and a 3 s measurement: + +| Case | Time | +| ----------------------------- | ------- | +| `std::time::Instant::now` | 20.4 ns | +| `quanta::Instant::now` | 8.5 ns | +| `std::time::Instant::elapsed` | 22.1 ns | +| `quanta::Instant::elapsed` | 10.5 ns | +| Mutex lock and unlock | 8.2 ns | +| Arc clone and drop | 8.0 ns | +| Empty sync scope | 89 ns | +| Scope plus one span | 178 ns | +| 32 tiny calls | 1.72 µs | +| Realistic baseline | 61.0 µs | +| Realistic instrumented | 73.0 µs | +| Async baseline | 25.1 µs | +| Async instrumented | 29.0 µs | +| Runtime off, realistic | 60.9 µs | +| Flush, 16 traces | 0.19 µs | + +An enabled span costs about 50 ns in the flat case. The realistic trace adds +12 µs for 137 spans over a 61 µs CPU-bound operation; the extra per-span cost +there comes from 16 attribute records and an arena that grows past its initial +capacity. Real Git operations take milliseconds and usually produce fewer spans +per unit of work, so the relative cost is lower; the per-span number is what +carries over. + +Timestamps use `quanta`'s TSC-backed clock when the platform supports it. +Calibration runs on a background thread started when collection is enabled. +Traces opened before calibration finishes use `std::time::Instant`, and each +trace pins one clock source, so a span never mixes start and end clocks. + +The runtime-off path adds about 2 ns per call site. Flush converts a span in +about 1.3 ns. The capture path only writes flat arena entries with names, +nanosecond offsets, and parent indices; JSON and waterfall conversion wait for +`flush`. + +If a hot loop shows up in a trace, exclude it with `skip` or +`telemetry::skip!` rather than sampling it away. Sampling drops whole scopes, +so it is a blunt tool when only one call is noisy. + +## Scopes + +Spans live in a task-local stack. A guard outside a scope is a no-op, so async +entry points must open one: + +```rust +let result = telemetry::scope(async move { + load_staged_diffs(&repo).await +}).await; +``` + +`scope` reuses an enclosing scope, so it is safe to call at every task root. +Blocking code uses `telemetry::sync_scope(|| ...)` and must not cross an +`.await`. + +A task-local scope does not follow work into `spawn_blocking`, and calling +`sync_scope` there would start a separate trace. Capture the scope on the +calling task and attach it inside the blocking closure instead: + +```rust +let scope = telemetry::ScopeHandle::capture(); +let join = tokio::task::spawn_blocking(move || { + telemetry::attach_scope(scope, || blocking_git_work()) +}); +``` + +`capture` returns `None` outside a scope or when collection is off, and +`attach_scope` runs the closure unchanged in that case. + +## Errors + +```rust +if let Err(error) = fetch_staged(repo).await { + telemetry::record_error("diff.fetch_failed", &error); + return Err(error); +} +``` + +`record_error` stores the code and the error's Rust type name. It does not call +`Display`, because messages routinely contain paths, URLs, branch names, and +tokens. + +For a specific call site that needs more signal, `record_error_detail` also +stores a sanitized message and up to three source errors, and +`record_error_message` handles failures that are not `Error` values. The +sanitizer redacts URLs, absolute paths, emails, and long opaque identifiers, +then truncates. It is best effort: never pass user-authored text. + +An error attaches to the innermost active span. Errors recorded with no span +active go into the batch-level `errors` list. + +## Context + +```rust +telemetry::context! { + "additions" => diff.additions, + "deletions" => diff.deletions, + "files_changed" => diff.files.len(), +} +``` + +Keys are normalized to lowercase `[a-z0-9._-]`. Text values are sanitized and +truncated to 240 characters. Numeric and boolean values pass through. This is +the only way to make a trace carry more than symbol names and timings, so keep +the values structural and never attach user data. + +## Global context + +`EnvironmentContext::detect(app_version)` reads the target OS, target +architecture, debug/release profile, and a CPU tier bucket (1 to 2, 3 to 4, 5 +to 8, 9 to 16, more than 16 logical cores). It reads no hardware serials, +hostnames, usernames, locale, GPU, or memory size. The context is attached to +every batch. + +## Kill switches + +| Switch | Effect | +| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | +| `enabled` feature off | Attribute is a pass-through; runtime entry points are no-ops; no clock reads | +| `Config::enabled(false)` | No scopes are created | +| `telemetry::set_enabled(bool)` | Works at any time; before `init` it stores the preference, after `init` it applies immediately and clears buffers when disabling | +| `telemetry::enable()` / `disable()` | Shorthand for `set_enabled` | +| `TELEMETRY_ENABLED=0\|false\|no\|off\|disabled` | Hard-disables collection for the process | +| `Config::env_kill_switch(false)` | Ignores the environment variable | + +For the settings UI: + +```rust +if telemetry::is_available() { + let enabled = telemetry::is_enabled(); + // render a switch with `enabled` + // on change: + telemetry::set_enabled(next); +} +``` + +`sample_permille` reduces volume by tracing only a fraction of task scopes. +`min_trace_duration_us` drops short traces. Buffer, span, depth, and attribute +caps bound memory; drops are counted in `dropped_traces()` and in the next +batch. + +## Output + +Call `flush()` periodically and hand the `Batch` to a `Sink`: + +```rust +let sink = telemetry::CallbackSink::new(|batch| { + let body = batch.to_json(); + // enqueue for upload +}); +telemetry::init(config, vec![std::sync::Arc::new(sink)]).unwrap(); +``` + +`to_json` produces the upload shape. `to_chrome_trace_json` produces Chrome +Trace Event JSON, which Perfetto (`ui.perfetto.dev`) and `chrome://tracing` +render as a nested waterfall. `FileSink` appends JSON lines locally for +debugging and stays on disk. + +Sinks run on the flushing thread. They must not block; enqueue the batch if +delivery can stall. + +## What is collected + +- Span names taken from Rust identifiers, start offsets, and durations +- Attributes explicitly attached with `context!` +- Error codes and error type names +- Sanitized error detail only where `record_error_detail` or + `record_error_message` is used +- OS family, architecture, CPU tier bucket, app version, debug/release + +Not collected: arguments, return values, file paths, repository or branch +names, diffs, commit hashes, environment variables, usernames, hostnames, IP +addresses, event timestamps, install identifiers, session identifiers, or any +other stable value. + +## EU privacy notes + +The payload is designed so it cannot single out a person and cannot link two +sessions. With the default error API there are no stable or quasi-stable +identifiers, so the upload is anonymous data rather than personal data. Keep +it that way: + +- Do not add identifiers through `context!`. Doing so turns the payload into + personal data, and the deployer becomes the controller. It then needs a + lawful basis, a retention limit, and a way to honor access and erasure + requests. +- The receiving server must not log or store source IP addresses. An IP is + personal data under GDPR even when the body is anonymous. Terminate TLS + without address logging, or truncate the address before any log write. +- Keep retention short. Timings are only useful for a few weeks. +- Do not enable collection for an app version before the consent screen + exists. The crate defaults to disabled. +- The optional `FileSink` writes to the user's disk. It is a debugging tool, + not a production sink. + +## Example + +```bash +cargo run -p telemetry --example waterfall --features enabled +``` + +The example runs a fake repository load with random timings, records an error +with a path in the message, prints the span tree, and writes two files under +the system temp directory: `batch.json` and `trace.json`. Open `trace.json` at +`ui.perfetto.dev` for the waterfall. + +## Tests + +```bash +cargo test -p telemetry -p telemetry-macros +cargo test -p telemetry -p telemetry-macros --features enabled +cargo bench -p telemetry --bench overhead --features enabled +``` + +The second command exercises the AST pass and a full trace round trip. The +benchmark prints the numbers in the performance table. diff --git a/crates/telemetry/benches/overhead.rs b/crates/telemetry/benches/overhead.rs new file mode 100644 index 0000000..ecfd978 --- /dev/null +++ b/crates/telemetry/benches/overhead.rs @@ -0,0 +1,401 @@ +use std::hint::black_box; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; + +use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; +use telemetry::{trace, Batch, Config, EnvironmentContext, Sink}; + +struct CountingSink { + batches: AtomicU64, +} + +impl Sink for CountingSink { + fn accept(&self, _batch: &Batch) { + self.batches.fetch_add(1, Ordering::Relaxed); + } +} + +#[inline(never)] +fn work(seed: u64, rounds: u64) -> u64 { + let mut state = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15); + for round in 0..rounds { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state = state.wrapping_add(round); + } + state +} + +#[inline(never)] +fn tiny(seed: u64) -> u64 { + seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) +} + +fn tiny_baseline(steps: u64) -> u64 { + let mut total = 0u64; + for step in 0..steps { + total = total.wrapping_add(tiny(step)); + } + total +} + +#[trace] +fn tiny_traced(steps: u64) -> u64 { + let mut total = 0u64; + for step in 0..steps { + total = total.wrapping_add(tiny(step)); + } + total +} + +#[trace(span_only)] +fn tiny_span_only(steps: u64) -> u64 { + let mut total = 0u64; + for step in 0..steps { + total = total.wrapping_add(tiny(step)); + } + total +} + +fn tiny_manual(steps: u64) -> u64 { + telemetry::sync_scope(|| { + let root = telemetry::SpanGuard::enter("tiny_manual"); + let mut total = 0u64; + for step in 0..steps { + let guard = telemetry::SpanGuard::enter("tiny"); + total = total.wrapping_add(tiny(step)); + drop(guard); + } + drop(root); + total + }) +} + +fn flat_baseline(steps: u64) -> u64 { + let mut total = 0u64; + for step in 0..steps { + total = total.wrapping_add(work(step, 32)); + } + total +} + +#[trace] +fn flat_traced(steps: u64) -> u64 { + let mut total = 0u64; + for step in 0..steps { + total = total.wrapping_add(work(step, 32)); + } + total +} + +#[inline(never)] +fn read_index_plain(seed: u64) -> u64 { + work(seed, 1000) +} + +#[inline(never)] +fn scan_objects_plain(seed: u64) -> u64 { + work(seed ^ 0x5bf0_3635, 800) +} + +#[inline(never)] +fn parse_pack_plain(seed: u64) -> u64 { + scan_objects_plain(seed) + .wrapping_add(scan_objects_plain(seed.rotate_left(7))) + .wrapping_add(work(seed, 600)) +} + +#[inline(never)] +fn render_hunk_plain(seed: u64, hunk: u64) -> u64 { + work(seed ^ hunk.wrapping_mul(31), 500) +} + +#[inline(never)] +fn scan_commit_plain(seed: u64) -> u64 { + let mut total = read_index_plain(seed); + total = total.wrapping_add(parse_pack_plain(seed)); + for hunk in 0..4 { + total = total.wrapping_add(render_hunk_plain(seed, hunk)); + } + total +} + +#[inline(never)] +fn realistic_baseline(commits: u64) -> u64 { + let mut total = 0u64; + for commit in 0..commits { + total = total.wrapping_add(scan_commit_plain(commit)); + } + total +} + +#[trace] +#[inline(never)] +fn read_index_traced(seed: u64) -> u64 { + work(seed, 1000) +} + +#[trace] +#[inline(never)] +fn scan_objects_traced(seed: u64) -> u64 { + work(seed ^ 0x5bf0_3635, 800) +} + +#[trace] +#[inline(never)] +fn parse_pack_traced(seed: u64) -> u64 { + scan_objects_traced(seed) + .wrapping_add(scan_objects_traced(seed.rotate_left(7))) + .wrapping_add(work(seed, 600)) +} + +#[trace] +#[inline(never)] +fn render_hunk_traced(seed: u64, hunk: u64) -> u64 { + work(seed ^ hunk.wrapping_mul(31), 500) +} + +#[trace] +#[inline(never)] +fn scan_commit_traced(seed: u64) -> u64 { + let mut total = read_index_traced(seed); + total = total.wrapping_add(parse_pack_traced(seed)); + for hunk in 0..4 { + total = total.wrapping_add(render_hunk_traced(seed, hunk)); + } + telemetry::context! { + "commit" => seed, + "hunks" => 4u64, + }; + total +} + +#[trace] +#[inline(never)] +fn realistic_traced(commits: u64) -> u64 { + let mut total = 0u64; + for commit in 0..commits { + total = total.wrapping_add(scan_commit_traced(commit)); + } + total +} + +#[inline(never)] +async fn read_async_plain(seed: u64) -> u64 { + tokio::task::yield_now().await; + work(seed, 900) +} + +#[inline(never)] +async fn parse_async_plain(seed: u64) -> u64 { + tokio::task::yield_now().await; + work(seed, 1100) +} + +#[inline(never)] +async fn async_baseline(rounds: u64) -> u64 { + let mut total = 0u64; + for round in 0..rounds { + total = total.wrapping_add(read_async_plain(round).await); + total = total.wrapping_add(parse_async_plain(round).await); + } + total +} + +#[trace] +#[inline(never)] +async fn read_async_traced(seed: u64) -> u64 { + tokio::task::yield_now().await; + work(seed, 900) +} + +#[trace] +#[inline(never)] +async fn parse_async_traced(seed: u64) -> u64 { + tokio::task::yield_now().await; + work(seed, 1100) +} + +#[trace] +#[inline(never)] +async fn async_traced(rounds: u64) -> u64 { + let mut total = 0u64; + for round in 0..rounds { + total = total.wrapping_add(read_async_traced(round).await); + total = total.wrapping_add(parse_async_traced(round).await); + } + total +} + +fn primitive_benchmarks(criterion: &mut Criterion) { + let mut group = criterion.benchmark_group("primitives"); + + group.bench_function("instant_now", |bencher| { + bencher.iter(|| black_box(std::time::Instant::now())) + }); + group.bench_function("instant_elapsed", |bencher| { + let start = std::time::Instant::now(); + bencher.iter(|| black_box(start.elapsed())) + }); + group.bench_function("quanta_instant_now", |bencher| { + bencher.iter(|| black_box(quanta::Instant::now())) + }); + group.bench_function("quanta_instant_elapsed", |bencher| { + let start = quanta::Instant::now(); + bencher.iter(|| black_box(start.elapsed())) + }); + + let mutex = std::sync::Mutex::new(0u64); + group.bench_function("mutex_lock_unlock", |bencher| { + bencher.iter(|| { + let mut guard = mutex.lock().unwrap(); + *guard = guard.wrapping_add(1); + black_box(*guard); + }) + }); + + let arc = Arc::new(0u64); + group.bench_function("arc_clone_drop", |bencher| { + bencher.iter(|| { + let clone = Arc::clone(&arc); + black_box(&clone); + }) + }); + + group.finish(); +} + +fn cold_benchmarks(criterion: &mut Criterion) { + let mut group = criterion.benchmark_group("cold"); + + group.bench_function("flat_32_calls_baseline", |bencher| { + bencher.iter(|| black_box(flat_baseline(black_box(32)))) + }); + group.bench_function("flat_32_calls_instrumented", |bencher| { + bencher.iter(|| black_box(telemetry::sync_scope(|| flat_traced(black_box(32))))) + }); + group.bench_function("realistic_baseline", |bencher| { + bencher.iter(|| black_box(realistic_baseline(black_box(8)))) + }); + group.bench_function("realistic_instrumented", |bencher| { + bencher.iter(|| black_box(telemetry::sync_scope(|| realistic_traced(black_box(8))))) + }); + + group.finish(); +} + +fn init_runtime() { + let config = Config::new(EnvironmentContext::detect("bench")) + .enabled(true) + .env_kill_switch(false) + .sample_permille(1000) + .buffer_capacity(512) + .max_spans_per_trace(512) + .max_depth(32); + let sink = CountingSink { + batches: AtomicU64::new(0), + }; + telemetry::init(config, vec![Arc::new(sink)]).expect("fresh process"); + std::thread::sleep(std::time::Duration::from_millis(100)); +} + +fn micro_benchmarks(criterion: &mut Criterion) { + let mut group = criterion.benchmark_group("micro"); + + group.bench_function("scope_only", |bencher| { + bencher.iter(|| telemetry::sync_scope(|| {})) + }); + group.bench_function("one_span", |bencher| { + bencher.iter(|| { + telemetry::sync_scope(|| { + let _guard = telemetry::SpanGuard::enter("one"); + }) + }) + }); + group.bench_function("tiny_32_calls_baseline", |bencher| { + bencher.iter(|| black_box(tiny_baseline(black_box(32)))) + }); + group.bench_function("tiny_32_calls", |bencher| { + bencher.iter(|| black_box(telemetry::sync_scope(|| tiny_traced(black_box(32))))) + }); + group.bench_function("tiny_32_calls_manual", |bencher| { + bencher.iter(|| black_box(tiny_manual(black_box(32)))) + }); + group.bench_function("tiny_32_calls_span_only", |bencher| { + bencher.iter(|| black_box(telemetry::sync_scope(|| tiny_span_only(black_box(32))))) + }); + group.bench_function("flat_8_calls", |bencher| { + bencher.iter(|| black_box(telemetry::sync_scope(|| flat_traced(black_box(8))))) + }); + group.bench_function("flat_32_calls", |bencher| { + bencher.iter(|| black_box(telemetry::sync_scope(|| flat_traced(black_box(32))))) + }); + + group.finish(); +} + +fn realistic_benchmarks(criterion: &mut Criterion) { + let mut group = criterion.benchmark_group("realistic"); + + group.bench_function("baseline", |bencher| { + bencher.iter(|| black_box(realistic_baseline(black_box(8)))) + }); + group.bench_function("instrumented", |bencher| { + bencher.iter(|| black_box(telemetry::sync_scope(|| realistic_traced(black_box(8))))) + }); + + group.finish(); +} + +fn async_benchmarks(criterion: &mut Criterion) { + let runtime = tokio::runtime::Builder::new_current_thread() + .build() + .expect("tokio runtime"); + let mut group = criterion.benchmark_group("async"); + + group.bench_function("baseline", |bencher| { + bencher.iter(|| black_box(runtime.block_on(async_baseline(black_box(8))))) + }); + group.bench_function("instrumented", |bencher| { + bencher.iter(|| black_box(runtime.block_on(telemetry::scope(async_traced(black_box(8)))))) + }); + + group.finish(); +} + +fn flush_benchmarks(criterion: &mut Criterion) { + let mut group = criterion.benchmark_group("flush"); + + group.bench_function("sixteen_traces", |bencher| { + bencher.iter_batched( + || { + let _ = telemetry::flush(); + for _ in 0..16 { + telemetry::sync_scope(|| { + for _ in 0..8 { + let _guard = telemetry::SpanGuard::enter("flush.span"); + } + }); + } + }, + |()| black_box(telemetry::flush()), + BatchSize::SmallInput, + ) + }); + + group.finish(); +} + +fn benchmarks(criterion: &mut Criterion) { + primitive_benchmarks(criterion); + cold_benchmarks(criterion); + init_runtime(); + micro_benchmarks(criterion); + realistic_benchmarks(criterion); + async_benchmarks(criterion); + flush_benchmarks(criterion); +} + +criterion_group!(benches, benchmarks); +criterion_main!(benches); diff --git a/crates/telemetry/examples/waterfall.rs b/crates/telemetry/examples/waterfall.rs new file mode 100644 index 0000000..7cfeee6 --- /dev/null +++ b/crates/telemetry/examples/waterfall.rs @@ -0,0 +1,318 @@ +//! Runs a fake repository load, prints the collected span tree, and writes a +//! Chrome trace for Perfetto. +//! +//! ```text +//! cargo run -p telemetry --example waterfall --features enabled +//! ``` + +use std::fmt::Write as _; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use telemetry::{ + trace, AttrValue, Batch, Config, EnvironmentContext, FlushReport, Sink, Span, SpanGuard, +}; + +struct Rng(u64); + +impl Rng { + fn new() -> Self { + let seed = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|duration| duration.as_nanos() as u64) + .unwrap_or(0x9e37_79b9_7f4a_7c15); + Self(seed | 1) + } + + fn next(&mut self) -> u64 { + let mut state = self.0; + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + self.0 = state; + state + } + + fn range(&mut self, min: u64, max: u64) -> u64 { + min + self.next() % (max - min + 1) + } + + fn work(&mut self, min_ms: u64, max_ms: u64) { + std::thread::sleep(Duration::from_millis(self.range(min_ms, max_ms))); + } +} + +#[derive(Clone, Default)] +struct Capture { + batch: Arc>>, +} + +impl Sink for Capture { + fn accept(&self, batch: &Batch) { + *self.batch.lock().unwrap() = Some(batch.clone()); + } +} + +#[derive(Debug)] +struct DemoError { + path: String, + url: String, +} + +impl std::fmt::Display for DemoError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + formatter, + "could not read {} while posting to {}", + self.path, self.url + ) + } +} + +impl std::error::Error for DemoError {} + +#[trace] +async fn read_index(path: &str) -> Result { + tokio::time::sleep(Duration::from_millis(25)).await; + if path.is_empty() { + return Err(DemoError { + path: path.to_owned(), + url: "https://example.invalid/v1/telemetry".to_owned(), + }); + } + telemetry::context! { "index_entries" => 137u64 }; + Ok(137) +} + +#[trace(skip = ["work"])] +fn hash_objects(rng: &mut Rng, count: u64) -> u64 { + rng.work(6, 18); + let mut total = 0u64; + for _ in 0..count { + total += rng.next() % 4096; + } + telemetry::context! { "objects_hashed" => count }; + total +} + +#[trace(skip = ["work"])] +fn scan_objects(rng: &mut Rng, entries: u64) -> u64 { + rng.work(10, 25); + let objects = entries / 3 + 1; + let checksum = hash_objects(rng, objects); + telemetry::context! { + "objects" => objects, + "checksum" => checksum % 10_000, + }; + objects +} + +#[trace(skip = ["work"])] +fn parse_packfile(rng: &mut Rng, entries: u64) -> u64 { + rng.work(8, 20); + let objects = scan_objects(rng, entries); + telemetry::context! { "packed_objects" => objects }; + objects +} + +#[trace(skip = ["work"])] +fn render_hunk(rng: &mut Rng, index: u64) -> u64 { + rng.work(2, 9); + telemetry::context! { "hunk" => index }; + 64 + rng.next() % 256 +} + +#[trace(skip = ["work"])] +fn render_diff(rng: &mut Rng, objects: u64) -> u64 { + rng.work(8, 20); + let chunks = objects % 5 + 1; + let mut bytes = 0u64; + for chunk in 0..chunks { + bytes += render_hunk(rng, chunk); + } + telemetry::context! { + "chunks" => chunks, + "rendered_bytes" => bytes, + }; + bytes +} + +#[trace(skip = ["work"])] +async fn load_repository(path: &str, rng: &mut Rng) -> Result { + let entries = read_index(path).await?; + let objects = parse_packfile(rng, entries); + let rendered = render_diff(rng, objects); + + let error = DemoError { + path: format!("{path}/.git/objects/pack"), + url: "https://example.invalid/v1/telemetry".to_owned(), + }; + telemetry::record_error_detail("object_store.read_failed", &error); + + telemetry::context! { + "files" => entries, + "objects" => objects, + "rendered_bytes" => rendered, + }; + + Ok(rendered) +} + +fn main() { + let capture = Arc::new(Capture::default()); + let config = Config::new(EnvironmentContext::detect(env!("CARGO_PKG_VERSION"))) + .enabled(true) + .env_kill_switch(false) + .sample_permille(1000) + .buffer_capacity(16); + + telemetry::init(config, vec![capture.clone()]).expect("telemetry is not initialized twice"); + + if !telemetry::is_enabled() { + eprintln!("telemetry is disabled for this process"); + return; + } + + println!("telemetry example: fake repository load\n"); + + let mut rng = Rng::new(); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("tokio runtime"); + + let result = runtime.block_on(telemetry::scope(load_repository( + "/home/example/repository", + &mut rng, + ))); + + telemetry::sync_scope(|| { + let _maintenance = SpanGuard::enter("startup.maintenance"); + std::thread::sleep(Duration::from_millis(12)); + telemetry::context! { "cache_entries" => 42u64 }; + }); + + let report = telemetry::flush(); + let batch = capture.batch.lock().unwrap().take(); + let Some(batch) = batch else { + eprintln!("no batch was flushed"); + return; + }; + + match result { + Ok(bytes) => println!("work completed: {bytes} rendered bytes\n"), + Err(error) => println!("work failed: {error}\n"), + } + + print_batch(&batch, report); + + match write_files(&batch) { + Ok((batch_path, trace_path)) => { + println!("\nbatch json: {}", batch_path.display()); + println!("waterfall: {}", trace_path.display()); + println!("open the waterfall at https://ui.perfetto.dev"); + } + Err(error) => eprintln!("could not write telemetry files: {error}"), + } +} + +fn print_batch(batch: &Batch, report: FlushReport) { + let context = serde_json::to_value(&batch.context).expect("context serializes"); + println!( + "context: os={} arch={} cpu={} build={} app={}", + string(&context["os"]), + string(&context["arch"]), + string(&context["cpuTier"]), + string(&context["buildProfile"]), + string(&context["appVersion"]), + ); + + let mut spans = 0; + let mut errors = batch.errors.len(); + for (index, trace) in batch.traces.iter().enumerate() { + println!("\ntrace {} ({}):", index + 1, duration(trace.duration_us)); + spans += print_span(&trace.root, 1); + errors += count_errors(&trace.root); + } + + for error in &batch.errors { + println!("\nunattached error: {} ({})", error.code, error.kind); + if let Some(message) = &error.message { + println!(" message: {message}"); + } + } + + let error_word = if errors == 1 { "error" } else { "errors" }; + println!( + "\nsummary: {} traces, {spans} spans, {errors} {error_word}, {} dropped", + report.traces, report.dropped_traces + ); +} + +fn count_errors(span: &Span) -> usize { + usize::from(span.error.is_some()) + span.children.iter().map(count_errors).sum::() +} + +fn print_span(span: &Span, depth: usize) -> usize { + let indent = " ".repeat(depth); + let mut line = format!("{indent}{} {}", span.name, duration(span.duration_us)); + if !span.attributes.is_empty() { + let attributes = span + .attributes + .iter() + .map(|(key, value)| format!("{key}={}", value_text(value))) + .collect::>() + .join(", "); + let _ = write!(line, " [{attributes}]"); + } + println!("{line}"); + + if let Some(error) = &span.error { + let error_indent = " ".repeat(depth + 1); + println!("{error_indent}error: {} ({})", error.code, error.kind); + if let Some(message) = &error.message { + println!("{error_indent} message: {message}"); + } + for source in &error.sources { + println!("{error_indent} caused by: {source}"); + } + } + + 1 + span + .children + .iter() + .map(|child| print_span(child, depth + 1)) + .sum::() +} + +fn value_text(value: &AttrValue) -> String { + match value { + AttrValue::Bool(value) => value.to_string(), + AttrValue::Int(value) => value.to_string(), + AttrValue::Uint(value) => value.to_string(), + AttrValue::Float(value) => format!("{value:.2}"), + AttrValue::Text(value) => value.clone(), + } +} + +fn string(value: &serde_json::Value) -> &str { + value.as_str().unwrap_or("?") +} + +fn duration(micros: u64) -> String { + if micros >= 1000 { + format!("{:.1} ms", micros as f64 / 1000.0) + } else { + format!("{micros} us") + } +} + +fn write_files(batch: &Batch) -> std::io::Result<(std::path::PathBuf, std::path::PathBuf)> { + let directory = std::env::temp_dir().join("gitau-telemetry-example"); + std::fs::create_dir_all(&directory)?; + let batch_path = directory.join("batch.json"); + let trace_path = directory.join("trace.json"); + std::fs::write(&batch_path, batch.to_json_pretty())?; + std::fs::write(&trace_path, batch.to_chrome_trace_json())?; + Ok((batch_path, trace_path)) +} diff --git a/crates/telemetry/src/config.rs b/crates/telemetry/src/config.rs new file mode 100644 index 0000000..5cc3fc5 --- /dev/null +++ b/crates/telemetry/src/config.rs @@ -0,0 +1,239 @@ +use serde::{Deserialize, Serialize}; + +/// Coarse hardware class so traces can be grouped without identifying a +/// machine. Buckets overlap enough that adjacent machines are indistinguishable +/// in reports. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CpuTier { + Minimal, + Low, + Medium, + High, + VeryHigh, +} + +impl CpuTier { + pub fn from_logical_cores(cores: usize) -> Self { + match cores { + 0..=2 => Self::Minimal, + 3..=4 => Self::Low, + 5..=8 => Self::Medium, + 9..=16 => Self::High, + _ => Self::VeryHigh, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum OsFamily { + Windows, + #[serde(rename = "macos")] + MacOs, + Linux, + Other, +} + +impl OsFamily { + fn current() -> Self { + if cfg!(target_os = "windows") { + Self::Windows + } else if cfg!(target_os = "macos") { + Self::MacOs + } else if cfg!(target_os = "linux") { + Self::Linux + } else { + Self::Other + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Arch { + X86, + X86_64, + Aarch64, + Other, +} + +impl Arch { + fn current() -> Self { + if cfg!(target_arch = "x86_64") { + Self::X86_64 + } else if cfg!(target_arch = "aarch64") { + Self::Aarch64 + } else if cfg!(target_arch = "x86") { + Self::X86 + } else { + Self::Other + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum BuildProfile { + Debug, + Release, +} + +impl BuildProfile { + fn current() -> Self { + if cfg!(debug_assertions) { + Self::Debug + } else { + Self::Release + } + } +} + +/// Context attached to every batch. Contains no identifier for the machine, +/// install, or user. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EnvironmentContext { + pub app_version: String, + pub build_profile: BuildProfile, + pub os: OsFamily, + pub arch: Arch, + pub cpu_tier: CpuTier, +} + +impl EnvironmentContext { + /// Reads only the target triple and the logical core count. + pub fn detect(app_version: impl Into) -> Self { + let cores = std::thread::available_parallelism() + .map(|count| count.get()) + .unwrap_or(1); + Self { + app_version: app_version.into(), + build_profile: BuildProfile::current(), + os: OsFamily::current(), + arch: Arch::current(), + cpu_tier: CpuTier::from_logical_cores(cores), + } + } +} + +#[derive(Debug, Clone)] +pub struct Config { + pub(crate) context: EnvironmentContext, + pub(crate) enabled: bool, + pub(crate) sample_permille: u16, + pub(crate) buffer_capacity: usize, + pub(crate) max_spans_per_trace: usize, + pub(crate) max_depth: usize, + pub(crate) max_attributes_per_span: usize, + pub(crate) min_trace_duration_us: u64, + pub(crate) env_kill_switch: bool, +} + +impl Config { + /// Collection starts disabled. This is the initial state at [`crate::init`] + /// unless [`crate::set_enabled`] was called before it. + pub fn new(context: EnvironmentContext) -> Self { + Self { + context, + enabled: false, + sample_permille: 250, + buffer_capacity: 64, + max_spans_per_trace: 512, + max_depth: 32, + max_attributes_per_span: 16, + min_trace_duration_us: 0, + env_kill_switch: true, + } + } + + pub fn enabled(mut self, enabled: bool) -> Self { + self.enabled = enabled; + self + } + + pub fn context(&self) -> &EnvironmentContext { + &self.context + } + + /// Fraction of task scopes that are traced, in parts per thousand. `1000` + /// traces everything. + pub fn sample_permille(mut self, permille: u16) -> Self { + self.sample_permille = permille.min(1000); + self + } + + /// Maximum completed traces held between flushes. The oldest is dropped + /// when the buffer is full. + pub fn buffer_capacity(mut self, traces: usize) -> Self { + self.buffer_capacity = traces.max(1); + self + } + + pub fn max_spans_per_trace(mut self, spans: usize) -> Self { + self.max_spans_per_trace = spans.max(1); + self + } + + pub fn max_depth(mut self, depth: usize) -> Self { + self.max_depth = depth.max(1); + self + } + + pub fn max_attributes_per_span(mut self, attributes: usize) -> Self { + self.max_attributes_per_span = attributes; + self + } + + /// Traces shorter than this are discarded at submission. + pub fn min_trace_duration_us(mut self, micros: u64) -> Self { + self.min_trace_duration_us = micros; + self + } + + /// Whether `TELEMETRY_ENABLED=false` (and equivalents) can override the + /// configuration. Defaults to on. + pub fn env_kill_switch(mut self, enabled: bool) -> Self { + self.env_kill_switch = enabled; + self + } +} + +#[derive(Debug, thiserror::Error)] +pub enum InitError { + #[error("telemetry is already initialized")] + AlreadyInitialized, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn buckets_core_counts() { + assert_eq!(CpuTier::from_logical_cores(1), CpuTier::Minimal); + assert_eq!(CpuTier::from_logical_cores(2), CpuTier::Minimal); + assert_eq!(CpuTier::from_logical_cores(4), CpuTier::Low); + assert_eq!(CpuTier::from_logical_cores(8), CpuTier::Medium); + assert_eq!(CpuTier::from_logical_cores(16), CpuTier::High); + assert_eq!(CpuTier::from_logical_cores(64), CpuTier::VeryHigh); + } + + #[test] + fn config_clamps_values() { + let config = Config::new(EnvironmentContext::detect("test")) + .sample_permille(4000) + .buffer_capacity(0) + .max_depth(0); + assert_eq!(config.sample_permille, 1000); + assert_eq!(config.buffer_capacity, 1); + assert_eq!(config.max_depth, 1); + assert!(!config.enabled); + } + + #[test] + fn detects_without_identifiers() { + let context = EnvironmentContext::detect("1.2.3"); + assert_eq!(context.app_version, "1.2.3"); + } +} diff --git a/crates/telemetry/src/error.rs b/crates/telemetry/src/error.rs new file mode 100644 index 0000000..b02ea55 --- /dev/null +++ b/crates/telemetry/src/error.rs @@ -0,0 +1,117 @@ +#[cfg(feature = "enabled")] +use std::error::Error; + +use serde::{Deserialize, Serialize}; + +#[cfg(feature = "enabled")] +use crate::sanitize; + +/// An error reduced to data that is safe to upload. `message` and `sources` +/// are only present when the call site opted into sanitized detail. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ErrorRecord { + pub code: String, + pub kind: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub message: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub sources: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub at_unix_ms: Option, +} + +#[cfg(feature = "enabled")] +impl ErrorRecord { + pub(crate) fn bare(code: &str, _error: &E) -> Self { + Self { + code: sanitize::key_or_default(code), + kind: sanitize::type_name(std::any::type_name::()), + message: None, + sources: Vec::new(), + at_unix_ms: None, + } + } + + pub(crate) fn detailed(code: &str, error: &E) -> Self { + let mut record = Self::bare(code, error); + record.message = Some(sanitize::text(&error.to_string())); + + let mut source = error.source(); + while let Some(cause) = source { + if record.sources.len() >= 3 { + break; + } + record.sources.push(sanitize::text(&cause.to_string())); + source = cause.source(); + } + + record + } + + pub(crate) fn from_message(code: &str, message: &str) -> Self { + Self { + code: sanitize::key_or_default(code), + kind: "message".into(), + message: Some(sanitize::text(message)), + sources: Vec::new(), + at_unix_ms: None, + } + } +} + +#[cfg(all(test, feature = "enabled"))] +mod tests { + use std::fmt; + + use super::*; + + #[derive(Debug)] + struct Inner; + + impl fmt::Display for Inner { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("inner failed at C:\\Users\\bob\\repo") + } + } + + impl Error for Inner {} + + #[derive(Debug)] + struct Outer(Inner); + + impl fmt::Display for Outer { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("outer failed at https://example.com/x") + } + } + + impl Error for Outer { + fn source(&self) -> Option<&(dyn Error + 'static)> { + Some(&self.0) + } + } + + #[test] + fn bare_errors_carry_no_message() { + let record = ErrorRecord::bare("diff_failed", &Outer(Inner)); + assert_eq!(record.code, "diff_failed"); + assert!(record.kind.contains("Outer")); + assert_eq!(record.message, None); + assert!(record.sources.is_empty()); + } + + #[test] + fn detailed_errors_are_sanitized() { + let record = ErrorRecord::detailed("diff_failed", &Outer(Inner)); + assert_eq!(record.message.as_deref(), Some("outer failed at ")); + assert_eq!(record.sources, vec!["inner failed at "]); + } + + #[test] + fn normalized_codes_survive() { + let record = ErrorRecord::from_message("Files Changed", "plain message"); + assert_eq!(record.code, "files_changed"); + assert_eq!(record.message.as_deref(), Some("plain message")); + } +} diff --git a/crates/telemetry/src/export.rs b/crates/telemetry/src/export.rs new file mode 100644 index 0000000..0cedb84 --- /dev/null +++ b/crates/telemetry/src/export.rs @@ -0,0 +1,189 @@ +use std::collections::BTreeMap; + +use serde::Serialize; + +use crate::error::ErrorRecord; +use crate::model::{AttrValue, Batch, Span}; + +impl Batch { + /// Compact JSON for upload or storage. + pub fn to_json(&self) -> String { + serde_json::to_string(self).unwrap_or_else(|_| fallback_json()) + } + + pub fn to_json_pretty(&self) -> String { + serde_json::to_string_pretty(self).unwrap_or_else(|_| fallback_json()) + } + + /// Chrome Trace Event JSON, which Perfetto and `chrome://tracing` render as + /// a nested waterfall. Every span is a complete event; nesting follows the + /// time ranges. + pub fn to_chrome_trace_json(&self) -> String { + let mut events = Vec::new(); + for trace in &self.traces { + let base = trace.start_unix_ms.saturating_mul(1000); + collect_events(&trace.root, base, &mut events); + } + for error in &self.errors { + events.push(ChromeEvent { + name: format!("error: {}", error.code), + cat: "error", + ph: "i", + ts: error.at_unix_ms.unwrap_or(0).saturating_mul(1000), + dur: 0, + pid: 1, + tid: 1, + args: Some(ChromeArgs { + attributes: BTreeMap::new(), + error: Some(error.clone()), + }), + }); + } + let document = ChromeTrace { + display_time_unit: "ms", + trace_events: events, + }; + serde_json::to_string(&document).unwrap_or_else(|_| fallback_json()) + } +} + +fn fallback_json() -> String { + r#"{"error":"serialization failed"}"#.into() +} + +#[derive(Serialize)] +struct ChromeTrace<'a> { + #[serde(rename = "displayTimeUnit")] + display_time_unit: &'a str, + #[serde(rename = "traceEvents")] + trace_events: Vec, +} + +#[derive(Serialize)] +struct ChromeEvent { + name: String, + cat: &'static str, + ph: &'static str, + ts: u64, + dur: u64, + pid: u32, + tid: u32, + #[serde(skip_serializing_if = "Option::is_none")] + args: Option, +} + +#[derive(Serialize)] +struct ChromeArgs { + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + attributes: BTreeMap, + #[serde(skip_serializing_if = "Option::is_none")] + error: Option, +} + +fn collect_events(span: &Span, base_us: u64, events: &mut Vec) { + let args = if span.attributes.is_empty() && span.error.is_none() { + None + } else { + Some(ChromeArgs { + attributes: span.attributes.clone(), + error: span.error.clone(), + }) + }; + + events.push(ChromeEvent { + name: span.name.clone(), + cat: "span", + ph: "X", + ts: base_us.saturating_add(span.start_us), + dur: span.duration_us, + pid: 1, + tid: 1, + args, + }); + + for child in &span.children { + collect_events(child, base_us, events); + } +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use super::*; + use crate::config::EnvironmentContext; + use crate::model::{Trace, SCHEMA_VERSION}; + + fn sample_batch() -> Batch { + let child = Span { + name: "fetch".into(), + start_us: 10, + duration_us: 20, + attributes: BTreeMap::new(), + error: None, + children: Vec::new(), + }; + let root = Span { + name: "load".into(), + start_us: 0, + duration_us: 100, + attributes: BTreeMap::new(), + error: None, + children: vec![child], + }; + Batch { + schema_version: SCHEMA_VERSION, + created_at_unix_ms: 1, + context: EnvironmentContext::detect("test"), + traces: vec![Trace { + start_unix_ms: 1_000, + duration_us: 100, + dropped_spans: 0, + root, + }], + errors: Vec::new(), + dropped_traces: 0, + } + } + + #[test] + fn serializes_a_batch() { + let batch = sample_batch(); + let value: serde_json::Value = serde_json::from_str(&batch.to_json()).unwrap(); + assert_eq!( + value["schemaVersion"].as_u64(), + Some(u64::from(SCHEMA_VERSION)) + ); + assert_eq!(value["traces"][0]["root"]["children"][0]["name"], "fetch"); + } + + #[test] + fn exports_standalone_errors_as_instant_events() { + let mut batch = sample_batch(); + batch.errors.push(ErrorRecord { + code: "fetch_failed".into(), + kind: "test::Error".into(), + message: None, + sources: Vec::new(), + at_unix_ms: Some(2_000), + }); + + let value: serde_json::Value = serde_json::from_str(&batch.to_chrome_trace_json()).unwrap(); + let events = value["traceEvents"].as_array().unwrap(); + let error = events.iter().find(|event| event["ph"] == "i").unwrap(); + assert_eq!(error["name"], "error: fetch_failed"); + assert_eq!(error["ts"].as_u64(), Some(2_000_000)); + } + + #[test] + fn exports_a_chrome_trace() { + let batch = sample_batch(); + let value: serde_json::Value = serde_json::from_str(&batch.to_chrome_trace_json()).unwrap(); + let events = value["traceEvents"].as_array().unwrap(); + assert_eq!(events.len(), 2); + assert_eq!(events[0]["name"], "load"); + assert_eq!(events[0]["ph"], "X"); + assert_eq!(events[0]["ts"].as_u64(), Some(1_000_000)); + assert_eq!(events[1]["ts"].as_u64(), Some(1_000_010)); + } +} diff --git a/crates/telemetry/src/imp.rs b/crates/telemetry/src/imp.rs new file mode 100644 index 0000000..399398e --- /dev/null +++ b/crates/telemetry/src/imp.rs @@ -0,0 +1,743 @@ +use std::cell::{RefCell, UnsafeCell}; +use std::collections::VecDeque; +use std::future::Future; +use std::ops::{Deref, DerefMut}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock}; + +use crate::config::{Config, EnvironmentContext, InitError}; +use crate::error::ErrorRecord; +use crate::model::{unix_ms_now, AttrValue, Batch, Span, Trace, SCHEMA_VERSION}; +use crate::sanitize; +use crate::sink::{FlushReport, Sink}; + +static RUNTIME: OnceLock = OnceLock::new(); +static ENABLED: AtomicBool = AtomicBool::new(false); +static SCOPE_SEQUENCE: AtomicU64 = AtomicU64::new(0); +static DESIRED_ENABLED: AtomicU8 = AtomicU8::new(CONSENT_UNSET); +static FAST_CLOCK_READY: AtomicBool = AtomicBool::new(false); +static FAST_CLOCK_STARTED: AtomicBool = AtomicBool::new(false); + +const CONSENT_UNSET: u8 = 0; +const CONSENT_ON: u8 = 1; +const CONSENT_OFF: u8 = 2; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum ClockSource { + Std, + Quanta, +} + +impl ClockSource { + fn current() -> Self { + if FAST_CLOCK_READY.load(Ordering::Relaxed) { + Self::Quanta + } else { + Self::Std + } + } +} + +#[derive(Clone, Copy)] +enum ClockInstant { + Std(std::time::Instant), + Quanta(quanta::Instant), +} + +struct SpinLock { + locked: AtomicBool, + value: UnsafeCell, +} + +// SAFETY: the only access to `value` is through a guard that holds `locked`, +// and the guard is released before the borrow ends. +unsafe impl Sync for SpinLock {} + +impl SpinLock { + const fn new(value: T) -> Self { + Self { + locked: AtomicBool::new(false), + value: UnsafeCell::new(value), + } + } + + fn lock(&self) -> SpinGuard<'_, T> { + while self + .locked + .compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed) + .is_err() + { + std::hint::spin_loop(); + } + SpinGuard { lock: self } + } +} + +struct SpinGuard<'a, T> { + lock: &'a SpinLock, +} + +impl Deref for SpinGuard<'_, T> { + type Target = T; + + fn deref(&self) -> &T { + // SAFETY: the guard holds the lock until it is dropped. + unsafe { &*self.lock.value.get() } + } +} + +impl DerefMut for SpinGuard<'_, T> { + fn deref_mut(&mut self) -> &mut T { + // SAFETY: the guard holds the lock until it is dropped. + unsafe { &mut *self.lock.value.get() } + } +} + +impl Drop for SpinGuard<'_, T> { + fn drop(&mut self) { + self.lock.locked.store(false, Ordering::Release); + } +} + +impl ClockInstant { + fn now(source: ClockSource) -> Self { + match source { + ClockSource::Std => Self::Std(std::time::Instant::now()), + ClockSource::Quanta => Self::Quanta(quanta::Instant::now()), + } + } + + fn elapsed(self) -> u64 { + match self { + Self::Std(instant) => instant.elapsed().as_nanos() as u64, + Self::Quanta(instant) => instant.elapsed().as_nanos() as u64, + } + } + + fn duration_since(self, earlier: Self) -> u64 { + match (self, earlier) { + (Self::Std(later), Self::Std(earlier)) => { + later.duration_since(earlier).as_nanos() as u64 + } + (Self::Quanta(later), Self::Quanta(earlier)) => { + later.duration_since(earlier).as_nanos() as u64 + } + _ => 0, + } + } +} + +struct Runtime { + context: EnvironmentContext, + enabled: AtomicBool, + env_disabled: bool, + sample_permille: u16, + buffer_capacity: usize, + error_capacity: usize, + min_trace_duration_us: u64, + max_spans_per_trace: usize, + max_depth: usize, + max_attributes_per_span: usize, + traces: Mutex>, + errors: Mutex>, + dropped_total: AtomicU64, + dropped_since_flush: AtomicU64, + sinks: Vec>, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum SpanKind { + Call, + Function, +} + +struct SpanNode { + name: &'static str, + kind: SpanKind, + started_ns: u64, + duration_ns: u64, + parent: Option, + // Keeps the common empty-attribute case to one pointer; the arena copies + // nodes when it grows. Keys stay as static literals and are normalized in + // `flush`. + #[allow(clippy::box_collection)] + attributes: Option>>, + error: Option>, +} + +struct FinishedTrace { + start_unix_ms: u64, + duration_us: u64, + dropped_spans: u64, + root: usize, + arena: Vec, +} + +impl FinishedTrace { + fn to_trace(&self) -> Trace { + let mut children = vec![Vec::new(); self.arena.len()]; + for (index, node) in self.arena.iter().enumerate() { + if let Some(parent) = node.parent { + children[parent].push(index); + } + } + + Trace { + start_unix_ms: self.start_unix_ms, + duration_us: self.duration_us, + dropped_spans: self.dropped_spans, + root: span_from_arena(self, &children, self.root, self.arena[self.root].started_ns), + } + } +} + +struct TraceState { + clock: ClockSource, + epoch: ClockInstant, + arena: Vec, + stack: Vec, + root: Option, + dropped: u64, + max_spans: usize, + max_depth: usize, + max_attributes: usize, +} + +impl TraceState { + fn new(max_spans: usize, max_depth: usize, max_attributes: usize) -> Self { + let clock = ClockSource::current(); + Self { + clock, + epoch: ClockInstant::now(clock), + arena: Vec::with_capacity(64), + stack: Vec::with_capacity(16), + root: None, + dropped: 0, + max_spans, + max_depth, + max_attributes, + } + } +} + +tokio::task_local! { + static TASK_STATE: Arc>; +} + +thread_local! { + static THREAD_STATE: RefCell>>> = const { RefCell::new(None) }; +} + +pub(crate) fn init(config: Config, sinks: Vec>) -> Result<(), InitError> { + let env_disabled = config.env_kill_switch && env_kill_switch_engaged(); + let desired = match DESIRED_ENABLED.load(Ordering::Relaxed) { + CONSENT_ON => Some(true), + CONSENT_OFF => Some(false), + _ => None, + }; + let enabled = desired.unwrap_or(config.enabled) && !env_disabled; + + let runtime = Runtime { + context: config.context, + enabled: AtomicBool::new(enabled), + env_disabled, + sample_permille: config.sample_permille, + buffer_capacity: config.buffer_capacity, + error_capacity: config.buffer_capacity, + min_trace_duration_us: config.min_trace_duration_us, + max_spans_per_trace: config.max_spans_per_trace, + max_depth: config.max_depth, + max_attributes_per_span: config.max_attributes_per_span, + traces: Mutex::new(VecDeque::new()), + errors: Mutex::new(VecDeque::new()), + dropped_total: AtomicU64::new(0), + dropped_since_flush: AtomicU64::new(0), + sinks, + }; + + RUNTIME + .set(runtime) + .map_err(|_| InitError::AlreadyInitialized)?; + ENABLED.store(enabled, Ordering::Release); + if enabled { + start_fast_clock(); + } + Ok(()) +} + +fn start_fast_clock() { + if FAST_CLOCK_STARTED.swap(true, Ordering::AcqRel) { + return; + } + let _ = std::thread::Builder::new() + .name("telemetry-clock".into()) + .spawn(|| { + let _ = quanta::Instant::now(); + FAST_CLOCK_READY.store(true, Ordering::Release); + }); +} + +#[inline] +pub(crate) fn is_enabled() -> bool { + ENABLED.load(Ordering::Relaxed) +} + +pub(crate) fn set_enabled(enabled: bool) { + DESIRED_ENABLED.store( + if enabled { CONSENT_ON } else { CONSENT_OFF }, + Ordering::Relaxed, + ); + + let Some(runtime) = RUNTIME.get() else { + if enabled { + start_fast_clock(); + } + return; + }; + let enabled = enabled && !runtime.env_disabled; + runtime.enabled.store(enabled, Ordering::Relaxed); + ENABLED.store(enabled, Ordering::Release); + if enabled { + start_fast_clock(); + } + + if !enabled { + lock(&runtime.traces).clear(); + lock(&runtime.errors).clear(); + runtime.dropped_since_flush.store(0, Ordering::Relaxed); + } +} + +pub(crate) async fn scope(future: F) -> F::Output { + if !is_enabled() || current_state().is_some() || !sample() { + return future.await; + } + let Some(runtime) = RUNTIME.get() else { + return future.await; + }; + + let state = Arc::new(SpinLock::new(TraceState::new( + runtime.max_spans_per_trace, + runtime.max_depth, + runtime.max_attributes_per_span, + ))); + TASK_STATE.scope(state, future).await +} + +pub(crate) fn sync_scope(f: impl FnOnce() -> R) -> R { + sync_scope_inner(f, true) +} + +pub(crate) fn sync_scope_unconditional(f: impl FnOnce() -> R) -> R { + sync_scope_inner(f, false) +} + +fn sync_scope_inner(f: impl FnOnce() -> R, sampled: bool) -> R { + if !is_enabled() || current_state().is_some() || (sampled && !sample()) { + return f(); + } + let Some(runtime) = RUNTIME.get() else { + return f(); + }; + + let state = Arc::new(SpinLock::new(TraceState::new( + runtime.max_spans_per_trace, + runtime.max_depth, + runtime.max_attributes_per_span, + ))); + let previous = THREAD_STATE.with(|slot| slot.replace(Some(state))); + let _restore = ThreadStateRestore(previous); + f() +} + +#[derive(Clone)] +pub(crate) struct ScopeHandle(Arc>); + +pub(crate) fn capture_scope() -> Option { + if !is_enabled() { + return None; + } + current_state().map(ScopeHandle) +} + +pub(crate) fn attach_scope(handle: &ScopeHandle, f: impl FnOnce() -> R) -> R { + let previous = THREAD_STATE.with(|slot| slot.replace(Some(Arc::clone(&handle.0)))); + let _restore = ThreadStateRestore(previous); + f() +} + +struct ThreadStateRestore(Option>>); + +impl Drop for ThreadStateRestore { + fn drop(&mut self) { + THREAD_STATE.with(|slot| { + *slot.borrow_mut() = self.0.take(); + }); + } +} + +pub(crate) fn record_attribute(key: &'static str, value: AttrValue) { + if !is_enabled() { + return; + } + let Some(state) = current_state() else { + return; + }; + + let mut state = state.lock(); + let Some(&index) = state.stack.last() else { + return; + }; + let max = state.max_attributes; + if let Some(node) = state.arena.get_mut(index) { + insert_attribute(node, key, value, max); + } +} + +pub(crate) fn record_error(code: &'static str, error: &E) { + if !is_enabled() { + return; + } + attach_or_queue(ErrorRecord::bare(code, error)); +} + +pub(crate) fn record_error_detail(code: &'static str, error: &E) { + if !is_enabled() { + return; + } + attach_or_queue(ErrorRecord::detailed(code, error)); +} + +pub(crate) fn record_error_message(code: &'static str, message: &str) { + if !is_enabled() { + return; + } + attach_or_queue(ErrorRecord::from_message(code, message)); +} + +pub(crate) fn flush() -> FlushReport { + let Some(runtime) = RUNTIME.get() else { + return FlushReport::default(); + }; + if !is_enabled() { + return FlushReport::default(); + } + + let finished: Vec = lock(&runtime.traces).drain(..).collect(); + let errors: Vec = lock(&runtime.errors).drain(..).collect(); + let dropped = runtime.dropped_since_flush.swap(0, Ordering::Relaxed); + + if finished.is_empty() && errors.is_empty() { + return FlushReport { + dropped_traces: dropped, + ..FlushReport::default() + }; + } + + let report = FlushReport { + traces: finished.len(), + errors: errors.len(), + dropped_traces: dropped, + sink_failures: 0, + }; + + let traces: Vec = finished.iter().map(FinishedTrace::to_trace).collect(); + let batch = Batch { + schema_version: SCHEMA_VERSION, + created_at_unix_ms: unix_ms_now(), + context: runtime.context.clone(), + traces, + errors, + dropped_traces: dropped, + }; + + let mut failures = 0; + for sink in &runtime.sinks { + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + sink.accept(&batch); + })); + if result.is_err() { + failures += 1; + } + } + + FlushReport { + sink_failures: failures, + ..report + } +} + +pub(crate) fn pending_traces() -> usize { + RUNTIME + .get() + .map(|runtime| lock(&runtime.traces).len()) + .unwrap_or(0) +} + +pub(crate) fn dropped_traces() -> u64 { + RUNTIME + .get() + .map(|runtime| runtime.dropped_total.load(Ordering::Relaxed)) + .unwrap_or(0) +} + +pub(crate) struct Guard { + state: Arc>, + index: usize, + started: ClockInstant, +} + +impl Guard { + pub(crate) fn set_attribute(&self, key: &'static str, value: AttrValue) { + let mut state = self.state.lock(); + let max = state.max_attributes; + if let Some(node) = state.arena.get_mut(self.index) { + insert_attribute(node, key, value, max); + } + } +} + +impl Drop for Guard { + fn drop(&mut self) { + let duration_ns = self.started.elapsed(); + + let mut state = self.state.lock(); + let Some(node) = state.arena.get_mut(self.index) else { + return; + }; + node.duration_ns = duration_ns; + + if state.stack.last() == Some(&self.index) { + state.stack.pop(); + } else { + let Some(position) = state.stack.iter().rposition(|&index| index == self.index) else { + return; + }; + state.stack.remove(position); + } + if !state.stack.is_empty() { + return; + } + + let Some(root) = state.root.take() else { + return; + }; + let duration_us = duration_ns / 1000; + let finished = FinishedTrace { + start_unix_ms: unix_ms_now().saturating_sub(duration_us / 1000), + duration_us, + dropped_spans: state.dropped, + root, + arena: std::mem::take(&mut state.arena), + }; + state.stack.clear(); + state.dropped = 0; + + drop(state); + submit(finished); + } +} + +#[inline] +pub(crate) fn enter(name: &'static str) -> Option { + if !is_enabled() { + return None; + } + enter_span(name, SpanKind::Call) +} + +#[inline] +pub(crate) fn enter_function(name: &'static str) -> Option { + if !is_enabled() { + return None; + } + enter_span(name, SpanKind::Function) +} + +fn enter_span(name: &'static str, kind: SpanKind) -> Option { + let state = current_state()?; + + let (index, started) = { + let mut trace_state = state.lock(); + if kind == SpanKind::Function { + if let Some(&top) = trace_state.stack.last() { + let node = &trace_state.arena[top]; + if node.kind == SpanKind::Call && node.name == name { + return None; + } + } + } + if trace_state.stack.len() >= trace_state.max_depth + || trace_state.arena.len() >= trace_state.max_spans + { + trace_state.dropped += 1; + return None; + } + + let now = ClockInstant::now(trace_state.clock); + let started_ns = now.duration_since(trace_state.epoch); + let parent = trace_state.stack.last().copied(); + let index = trace_state.arena.len(); + if parent.is_none() { + trace_state.root = Some(index); + } + trace_state.arena.push(SpanNode { + name, + kind, + started_ns, + duration_ns: 0, + parent, + attributes: None, + error: None, + }); + trace_state.stack.push(index); + (index, now) + }; + + Some(Guard { + state, + index, + started, + }) +} + +fn current_state() -> Option>> { + if let Some(state) = THREAD_STATE.with(|slot| slot.borrow().clone()) { + return Some(state); + } + TASK_STATE.try_with(Arc::clone).ok() +} + +fn submit(trace: FinishedTrace) { + let Some(runtime) = RUNTIME.get() else { + return; + }; + if !runtime.enabled.load(Ordering::Relaxed) { + return; + } + if trace.duration_us < runtime.min_trace_duration_us { + return; + } + + let mut traces = lock(&runtime.traces); + if traces.len() >= runtime.buffer_capacity { + traces.pop_front(); + runtime.dropped_total.fetch_add(1, Ordering::Relaxed); + runtime.dropped_since_flush.fetch_add(1, Ordering::Relaxed); + } + traces.push_back(trace); +} + +fn queue_error(record: ErrorRecord) { + let Some(runtime) = RUNTIME.get() else { + return; + }; + if !runtime.enabled.load(Ordering::Relaxed) { + return; + } + + let mut errors = lock(&runtime.errors); + if errors.len() >= runtime.error_capacity { + errors.pop_front(); + } + errors.push_back(record); +} + +fn attach_or_queue(mut record: ErrorRecord) { + if let Some(state) = current_state() { + let mut state = state.lock(); + if let Some(&index) = state.stack.last() { + if let Some(node) = state.arena.get_mut(index) { + if node.error.is_none() { + node.error = Some(Box::new(record)); + return; + } + } + } + } + + record.at_unix_ms = Some(unix_ms_now()); + queue_error(record); +} + +fn span_from_arena( + trace: &FinishedTrace, + children: &[Vec], + index: usize, + base_ns: u64, +) -> Span { + let node = &trace.arena[index]; + Span { + name: node.name.to_string(), + start_us: node.started_ns.saturating_sub(base_ns) / 1000, + duration_us: node.duration_ns / 1000, + attributes: node + .attributes + .as_deref() + .map(|entries| { + entries + .iter() + .filter_map(|(key, value)| sanitize::key(key).map(|key| (key, value.clone()))) + .collect() + }) + .unwrap_or_default(), + error: node.error.as_deref().cloned(), + children: children[index] + .iter() + .map(|&child| span_from_arena(trace, children, child, base_ns)) + .collect(), + } +} + +fn insert_attribute( + node: &mut SpanNode, + key: &'static str, + value: AttrValue, + max_attributes: usize, +) { + match &mut node.attributes { + Some(entries) => { + if let Some(slot) = entries.iter_mut().find(|(existing, _)| *existing == key) { + slot.1 = value; + } else if entries.len() < max_attributes { + entries.push((key, value)); + } + } + None if max_attributes > 0 => { + node.attributes = Some(Box::new(vec![(key, value)])); + } + None => {} + } +} + +fn sample() -> bool { + let Some(runtime) = RUNTIME.get() else { + return false; + }; + let permille = runtime.sample_permille; + if permille >= 1000 { + return true; + } + if permille == 0 { + return false; + } + let sequence = SCOPE_SEQUENCE.fetch_add(1, Ordering::Relaxed); + sequence % 1000 < u64::from(permille) +} + +fn env_kill_switch_engaged() -> bool { + std::env::var("TELEMETRY_ENABLED") + .map(|value| { + matches!( + value.trim().to_ascii_lowercase().as_str(), + "0" | "false" | "no" | "off" | "disabled" + ) + }) + .unwrap_or(false) +} + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) +} diff --git a/crates/telemetry/src/lib.rs b/crates/telemetry/src/lib.rs new file mode 100644 index 0000000..edba21b --- /dev/null +++ b/crates/telemetry/src/lib.rs @@ -0,0 +1,336 @@ +//! Anonymous, opt-in timing and error telemetry. +//! +//! The crate records a tree of spans: the name of each traced function or call, +//! its duration, and attributes developers attach explicitly. It never records +//! arguments, paths, repository contents, environment variables, hostnames, or +//! any stable identifier. +//! +//! # Disabling +//! +//! Instrumentation is compiled out unless the `enabled` feature is on. Without +//! it [`SpanGuard::enter`] and every other entry point return without touching +//! a clock, and [`trace`] passes the annotated item through unchanged. +//! +//! Even with the feature on, nothing is collected until [`init`] is called with +//! [`Config::enabled`] set to `true`. [`set_enabled`] changes the state at any +//! time, including before [`init`]. The `TELEMETRY_ENABLED` environment +//! variable set to `0`, `false`, `no`, `off`, or `disabled` hard-disables +//! collection regardless of configuration. +//! +//! # Settings +//! +//! A settings toggle needs three calls: [`is_available`] to hide the control in +//! builds without the feature, [`is_enabled`] to render the current state, and +//! [`set_enabled`] to change it. [`enable`] and [`disable`] are shorthand. +//! +//! # Async scopes +//! +//! Spans live in a task-local stack. Wrap each async task root in [`scope`] so +//! the guards inside it share one tree: +//! +//! ``` +//! # async fn run() { +//! telemetry::scope(async { +//! // traced work here +//! }) +//! .await; +//! # } +//! ``` +//! +//! Blocking code uses [`sync_scope`]. Traced calls outside any scope are +//! dropped without allocating. +//! +//! # Errors +//! +//! [`record_error`] stores an error code plus the error's type name. The +//! displayed message is not captured because messages routinely contain paths, +//! URLs, and branch names. [`record_error_detail`] opts into a sanitized +//! message and source chain for a specific call site. + +extern crate self as telemetry; + +mod config; +mod error; +mod export; +mod model; +mod sanitize; +mod sink; +mod span; + +#[cfg(feature = "enabled")] +mod imp; + +use std::future::Future; +use std::sync::Arc; + +pub use config::{Arch, BuildProfile, Config, CpuTier, EnvironmentContext, InitError, OsFamily}; +pub use error::ErrorRecord; +pub use model::{AttrValue, Batch, Span, Trace, SCHEMA_VERSION}; +pub use sink::{CallbackSink, FileSink, FlushReport, Sink}; +pub use span::{attach_scope, ScopeHandle, SpanGuard}; +pub use telemetry_macros::trace; + +/// Installs the global collector. Call once during startup, after consent. +/// +/// The initial state is [`Config::enabled`] unless [`set_enabled`] was called +/// before this. Repeated calls return [`InitError::AlreadyInitialized`]. +/// `sinks` receive batches from [`flush`]; see [`CallbackSink`] and +/// [`FileSink`]. +pub fn init(config: Config, sinks: Vec>) -> Result<(), InitError> { + #[cfg(feature = "enabled")] + { + imp::init(config, sinks) + } + #[cfg(not(feature = "enabled"))] + { + let _ = (config, sinks); + Ok(()) + } +} + +/// Turns collection on or off. +/// +/// Safe to call before [`init`]: the preference is stored and applied when the +/// collector starts. After initialization it takes effect immediately from any +/// thread. Disabling clears buffered traces and errors, so data is not retained +/// after consent is withdrawn. +pub fn set_enabled(enabled: bool) { + #[cfg(feature = "enabled")] + { + imp::set_enabled(enabled); + } + #[cfg(not(feature = "enabled"))] + { + let _ = enabled; + } +} + +/// Turns collection on. Shorthand for `set_enabled(true)`. +pub fn enable() { + set_enabled(true); +} + +/// Turns collection off and clears buffered data. Shorthand for +/// `set_enabled(false)`. +pub fn disable() { + set_enabled(false); +} + +/// Whether this build includes telemetry. Use this to hide the settings +/// control in builds without the feature. +#[inline] +pub fn is_available() -> bool { + cfg!(feature = "enabled") +} + +/// Whether spans and errors are currently collected. +#[inline] +pub fn is_enabled() -> bool { + #[cfg(feature = "enabled")] + { + imp::is_enabled() + } + #[cfg(not(feature = "enabled"))] + { + false + } +} + +/// Establishes a span scope for an async task. +/// +/// Nested scopes reuse the enclosing one, so calling this in a child task while +/// already inside a scope does not split the trace. +pub async fn scope(future: F) -> F::Output { + #[cfg(feature = "enabled")] + { + imp::scope(future).await + } + #[cfg(not(feature = "enabled"))] + { + future.await + } +} + +/// Ends a call-site span after evaluating the call. Used by [`trace`]. +#[doc(hidden)] +#[inline] +pub fn finish_call(_guard: SpanGuard, value: T) -> T { + value +} + +/// Ends a call-site span after the awaited future completes. Used by [`trace`]. +#[doc(hidden)] +pub async fn finish_await(_guard: SpanGuard, future: F) -> F::Output { + future.await +} + +/// Establishes a span scope for blocking work. Not valid across `.await`. +pub fn sync_scope(f: impl FnOnce() -> R) -> R { + #[cfg(feature = "enabled")] + { + imp::sync_scope(f) + } + #[cfg(not(feature = "enabled"))] + { + f() + } +} + +/// Establishes a span scope for blocking work that sampling cannot skip. +/// +/// Collection must still be enabled. Use for rare, cheap events such as startup +/// where the configured sample rate would leave most occurrences missing. Not +/// valid across `.await`. +pub fn sync_scope_unconditional(f: impl FnOnce() -> R) -> R { + #[cfg(feature = "enabled")] + { + imp::sync_scope_unconditional(f) + } + #[cfg(not(feature = "enabled"))] + { + f() + } +} + +/// Attaches a value to the innermost active span. See the [`context!`] macro. +pub fn record_attribute(key: &'static str, value: AttrValue) { + #[cfg(feature = "enabled")] + { + imp::record_attribute(key, value); + } + #[cfg(not(feature = "enabled"))] + { + let _ = (key, value); + } +} + +/// Records an error code and the error's type name on the innermost span. +/// +/// The displayed message is intentionally not stored. Pass a concrete error +/// type, not `&dyn Error`, so the recorded type name is the useful one. +pub fn record_error(code: &'static str, error: &E) { + #[cfg(feature = "enabled")] + { + imp::record_error(code, error); + } + #[cfg(not(feature = "enabled"))] + { + let _ = (code, error); + } +} + +/// Records an error with a sanitized message and source chain. +/// +/// Prefer [`record_error`]. The sanitizer redacts URLs, absolute paths, email +/// addresses, and long opaque identifiers, then truncates the result. It is +/// best effort, so do not pass free-form user data here. +pub fn record_error_detail(code: &'static str, error: &E) { + #[cfg(feature = "enabled")] + { + imp::record_error_detail(code, error); + } + #[cfg(not(feature = "enabled"))] + { + let _ = (code, error); + } +} + +/// Records a sanitized message under an error code, for failures that are not +/// `std::error::Error` values. +pub fn record_error_message(code: &'static str, message: &str) { + #[cfg(feature = "enabled")] + { + imp::record_error_message(code, message); + } + #[cfg(not(feature = "enabled"))] + { + let _ = (code, message); + } +} + +/// Serializes buffered traces and errors to every installed sink. +/// +/// Tree conversion happens here, not at capture time. Run it on a background +/// thread if the buffer can be large. Sinks run on the calling thread. A +/// panicking sink is counted and skipped. +pub fn flush() -> FlushReport { + #[cfg(feature = "enabled")] + { + imp::flush() + } + #[cfg(not(feature = "enabled"))] + { + FlushReport::default() + } +} + +/// Number of completed traces waiting for [`flush`]. +pub fn pending_traces() -> usize { + #[cfg(feature = "enabled")] + { + imp::pending_traces() + } + #[cfg(not(feature = "enabled"))] + { + 0 + } +} + +/// Number of traces dropped because the buffer was full since startup. +pub fn dropped_traces() -> u64 { + #[cfg(feature = "enabled")] + { + imp::dropped_traces() + } + #[cfg(not(feature = "enabled"))] + { + 0 + } +} + +/// Excludes a call from instrumentation without changing its behavior. +/// +/// The [`trace`] pass does not descend into macro bodies, so no span is created +/// for the wrapped expression or for any calls nested inside it. +/// +/// ```ignore +/// let loaded = telemetry::skip!(decode_thumbnail(&bytes)); +/// ``` +/// +/// Use the `skip = ["..."]` argument on [`trace`] to exclude a name for a whole +/// function instead. +#[macro_export] +macro_rules! skip { + ($($tokens:tt)*) => ($($tokens)*); +} + +/// Attaches key/value context to the innermost active span. +/// +/// ```ignore +/// telemetry::context! { +/// "additions" => diffs.additions, +/// "files_changed" => diffs.files.len(), +/// } +/// ``` +/// +/// Keys are normalized to lowercase `[a-z0-9._-]`. Text values are sanitized +/// and truncated before they are stored. +#[cfg(feature = "enabled")] +#[macro_export] +macro_rules! context { + ($($key:literal => $value:expr),* $(,)?) => { + $( + $crate::record_attribute($key, $crate::AttrValue::from($value)); + )* + }; +} + +/// Compiles to nothing when the `enabled` feature is off, including its +/// arguments. +#[cfg(not(feature = "enabled"))] +#[macro_export] +macro_rules! context { + ($($tt:tt)*) => { + () + }; +} diff --git a/crates/telemetry/src/model.rs b/crates/telemetry/src/model.rs new file mode 100644 index 0000000..d31a4f9 --- /dev/null +++ b/crates/telemetry/src/model.rs @@ -0,0 +1,184 @@ +use std::collections::BTreeMap; +#[cfg(feature = "enabled")] +use std::time::{SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; + +use crate::config::EnvironmentContext; +use crate::error::ErrorRecord; +use crate::sanitize; + +pub const SCHEMA_VERSION: u32 = 1; + +/// A value attached to a span by the developer. Text is sanitized and +/// truncated at construction time. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum AttrValue { + Bool(bool), + Int(i64), + Uint(u64), + Float(f64), + Text(String), +} + +impl From for AttrValue { + fn from(value: bool) -> Self { + Self::Bool(value) + } +} + +impl From for AttrValue { + fn from(value: i64) -> Self { + Self::Int(value) + } +} + +impl From for AttrValue { + fn from(value: u64) -> Self { + Self::Uint(value) + } +} + +impl From for AttrValue { + fn from(value: i32) -> Self { + Self::Int(i64::from(value)) + } +} + +impl From for AttrValue { + fn from(value: u32) -> Self { + Self::Uint(u64::from(value)) + } +} + +impl From for AttrValue { + fn from(value: u16) -> Self { + Self::Uint(u64::from(value)) + } +} + +impl From for AttrValue { + fn from(value: u8) -> Self { + Self::Uint(u64::from(value)) + } +} + +impl From for AttrValue { + fn from(value: i16) -> Self { + Self::Int(i64::from(value)) + } +} + +impl From for AttrValue { + fn from(value: i8) -> Self { + Self::Int(i64::from(value)) + } +} + +impl From for AttrValue { + fn from(value: usize) -> Self { + Self::Uint(value as u64) + } +} + +impl From for AttrValue { + fn from(value: isize) -> Self { + Self::Int(value as i64) + } +} + +impl From for AttrValue { + fn from(value: f64) -> Self { + if value.is_finite() { + Self::Float(value) + } else { + Self::Text("".into()) + } + } +} + +impl From for AttrValue { + fn from(value: f32) -> Self { + Self::from(f64::from(value)) + } +} + +impl From<&str> for AttrValue { + fn from(value: &str) -> Self { + Self::Text(sanitize::text(value)) + } +} + +impl From for AttrValue { + fn from(value: String) -> Self { + Self::Text(sanitize::text(&value)) + } +} + +impl From<&String> for AttrValue { + fn from(value: &String) -> Self { + Self::Text(sanitize::text(value)) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Span { + pub name: String, + pub start_us: u64, + pub duration_us: u64, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub attributes: BTreeMap, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub children: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Trace { + pub start_unix_ms: u64, + pub duration_us: u64, + pub dropped_spans: u64, + pub root: Span, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Batch { + pub schema_version: u32, + pub created_at_unix_ms: u64, + pub context: EnvironmentContext, + pub traces: Vec, + pub errors: Vec, + pub dropped_traces: u64, +} + +#[cfg(feature = "enabled")] +pub(crate) fn unix_ms_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|duration| duration.as_millis() as u64) + .unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sanitizes_text_attributes() { + let value = AttrValue::from("see https://example.com/secret"); + assert_eq!(value, AttrValue::Text("see ".into())); + } + + #[test] + fn clamps_non_finite_floats() { + assert_eq!( + AttrValue::from(f64::NAN), + AttrValue::Text("".into()) + ); + } +} diff --git a/crates/telemetry/src/sanitize.rs b/crates/telemetry/src/sanitize.rs new file mode 100644 index 0000000..85eb440 --- /dev/null +++ b/crates/telemetry/src/sanitize.rs @@ -0,0 +1,232 @@ +const MAX_TEXT_CHARS: usize = 240; +#[cfg(feature = "enabled")] +const MAX_TYPE_CHARS: usize = 128; +#[cfg(feature = "enabled")] +const MAX_KEY_CHARS: usize = 48; + +/// Redacts the shapes that carry personal data in practice: URLs (hosts and +/// tokens), absolute paths, email addresses, and long opaque identifiers. +/// A path swallows the rest of the input because paths may contain spaces. +/// Best effort by design; never pass user-authored text. +pub(crate) fn text(input: &str) -> String { + text_with_limit(input, MAX_TEXT_CHARS) +} + +fn text_with_limit(input: &str, max_chars: usize) -> String { + let mut output = String::with_capacity(input.len().min(max_chars * 2)); + for raw in input.split_whitespace() { + if !output.is_empty() { + output.push(' '); + } + + let candidate = raw.trim_matches(is_wrapping_punctuation); + let candidate = if candidate.is_empty() { raw } else { candidate }; + + if is_url(candidate) { + output.push_str(""); + } else if is_email(candidate) { + output.push_str(""); + } else if is_path(candidate) { + output.push_str(""); + break; + } else if is_opaque_identifier(candidate) { + output.push_str(""); + } else { + output.extend(raw.chars().filter(|ch| !ch.is_control())); + } + + if output.chars().count() >= max_chars { + break; + } + } + + truncate(output, max_chars) +} + +#[cfg(feature = "enabled")] +pub(crate) fn key(input: &str) -> Option { + let mut output = String::with_capacity(input.len().min(MAX_KEY_CHARS)); + for ch in input.chars().take(MAX_KEY_CHARS) { + if ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '-') { + output.push(ch.to_ascii_lowercase()); + } else { + output.push('_'); + } + } + let output = output.trim_matches('_').to_string(); + (!output.is_empty()).then_some(output) +} + +#[cfg(feature = "enabled")] +pub(crate) fn key_or_default(input: &str) -> String { + key(input).unwrap_or_else(|| "unknown".into()) +} + +#[cfg(feature = "enabled")] +pub(crate) fn type_name(input: &str) -> String { + truncate( + input.chars().filter(|ch| !ch.is_control()).collect(), + MAX_TYPE_CHARS, + ) +} + +fn is_wrapping_punctuation(ch: char) -> bool { + matches!( + ch, + '(' | ')' + | '[' + | ']' + | '{' + | '}' + | '<' + | '>' + | '"' + | '\'' + | ',' + | ';' + | ':' + | '.' + | '!' + | '?' + ) +} + +fn is_url(token: &str) -> bool { + token.contains("://") || token.starts_with("www.") +} + +fn is_email(token: &str) -> bool { + let Some(at) = token.find('@') else { + return false; + }; + if token.contains('/') || token.contains('\\') { + return false; + } + let (local, domain) = token.split_at(at); + !local.is_empty() && domain.len() > 1 +} + +fn is_path(token: &str) -> bool { + let bytes = token.as_bytes(); + let windows_drive = bytes.len() >= 3 + && bytes[0].is_ascii_alphabetic() + && bytes[1] == b':' + && matches!(bytes[2], b'\\' | b'/'); + windows_drive + || token.starts_with("\\\\") + || token.starts_with("..\\") + || token.starts_with("../") + || token.starts_with(".\\") + || token.starts_with("~/") + || (token.starts_with('/') && token.len() > 1) +} + +fn is_opaque_identifier(token: &str) -> bool { + let meaningful: Vec = token + .chars() + .filter(|ch| !matches!(ch, '-' | '_')) + .collect(); + if meaningful.len() < 32 { + return false; + } + let alphanumeric = meaningful + .iter() + .filter(|ch| ch.is_ascii_alphanumeric()) + .count(); + let dense = alphanumeric * 10 >= meaningful.len() * 9; + dense && meaningful.iter().any(|ch| ch.is_ascii_digit()) +} + +fn truncate(mut input: String, max_chars: usize) -> String { + if input.chars().count() <= max_chars { + return input; + } + let cut = input + .char_indices() + .nth(max_chars) + .map(|(index, _)| index) + .unwrap_or(input.len()); + input.truncate(cut); + input.push_str("..."); + input +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn redacts_urls() { + assert_eq!( + text("request to https://api.example.com/repos?token=1 failed"), + "request to failed" + ); + } + + #[test] + fn redacts_absolute_paths_and_drops_the_tail() { + assert_eq!( + text(r"open C:\Users\bob\secret\file.txt failed"), + "open " + ); + assert_eq!(text("open /home/bob/secret failed"), "open "); + assert_eq!(text("open ~/secret failed"), "open "); + } + + #[test] + fn redacts_email_addresses() { + assert_eq!( + text("contact bob@example.com for access"), + "contact for access" + ); + assert_eq!(text("contact bob@localhost"), "contact "); + } + + #[test] + fn redacts_long_opaque_identifiers() { + assert_eq!( + text("commit 0123456789abcdef0123456789abcdef01234567 is gone"), + "commit is gone" + ); + assert_eq!( + text("commit 550e8400-e29b-41d4-a716-446655440000 is gone"), + "commit is gone" + ); + } + + #[test] + fn keeps_ordinary_text() { + assert_eq!(text("push rejected by remote"), "push rejected by remote"); + assert_eq!(text("branch main"), "branch main"); + } + + #[test] + fn strips_control_characters() { + assert_eq!(text("bad\u{0}value"), "badvalue"); + } + + #[test] + fn truncates_long_text() { + let long = "a".repeat(400); + let output = text(&long); + assert!(output.ends_with("...")); + assert_eq!(output.chars().count(), MAX_TEXT_CHARS + 3); + } + + #[cfg(feature = "enabled")] + #[test] + fn normalizes_keys() { + assert_eq!(key("Files Changed"), Some("files_changed".into())); + assert_eq!(key("repo.path"), Some("repo.path".into())); + assert_eq!(key(""), None); + assert_eq!(key("!!!"), None); + assert!(key(&"x".repeat(100)).unwrap().len() <= MAX_KEY_CHARS); + } + + #[cfg(feature = "enabled")] + #[test] + fn truncates_type_names() { + let long = "a".repeat(200); + assert_eq!(type_name(&long).chars().count(), MAX_TYPE_CHARS + 3); + } +} diff --git a/crates/telemetry/src/sink.rs b/crates/telemetry/src/sink.rs new file mode 100644 index 0000000..cff3430 --- /dev/null +++ b/crates/telemetry/src/sink.rs @@ -0,0 +1,116 @@ +use std::fs::{File, OpenOptions}; +use std::io::Write; +use std::path::Path; +use std::sync::Mutex; + +use crate::model::Batch; + +/// Receives batches from [`crate::flush`]. +/// +/// Called on the flushing thread, so it must not block. Enqueue the batch for +/// a worker thread if delivery can be slow. +pub trait Sink: Send + Sync + 'static { + fn accept(&self, batch: &Batch); +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct FlushReport { + pub traces: usize, + pub errors: usize, + pub dropped_traces: u64, + pub sink_failures: usize, +} + +pub struct CallbackSink { + callback: F, +} + +impl CallbackSink +where + F: Fn(&Batch) + Send + Sync + 'static, +{ + pub fn new(callback: F) -> Self { + Self { callback } + } +} + +impl Sink for CallbackSink +where + F: Fn(&Batch) + Send + Sync + 'static, +{ + fn accept(&self, batch: &Batch) { + (self.callback)(batch); + } +} + +/// Appends one JSON batch per line. Meant for local debugging; the file stays +/// on the user's machine. +pub struct FileSink { + file: Mutex, +} + +impl FileSink { + pub fn new(path: impl AsRef) -> std::io::Result { + let file = OpenOptions::new().create(true).append(true).open(path)?; + Ok(Self { + file: Mutex::new(file), + }) + } +} + +impl Sink for FileSink { + fn accept(&self, batch: &Batch) { + if let Ok(mut file) = self.file.lock() { + let _ = writeln!(file, "{}", batch.to_json()); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::EnvironmentContext; + use crate::model::SCHEMA_VERSION; + + fn empty_batch() -> Batch { + Batch { + schema_version: SCHEMA_VERSION, + created_at_unix_ms: 0, + context: EnvironmentContext::detect("test"), + traces: Vec::new(), + errors: Vec::new(), + dropped_traces: 0, + } + } + + #[test] + fn callback_sink_sees_batches() { + let seen = std::sync::Arc::new(Mutex::new(0usize)); + let counter = seen.clone(); + let sink = CallbackSink::new(move |_| { + *counter.lock().unwrap() += 1; + }); + sink.accept(&empty_batch()); + assert_eq!(*seen.lock().unwrap(), 1); + } + + #[test] + fn file_sink_appends_json_lines() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("telemetry.jsonl"); + let sink = FileSink::new(&path).unwrap(); + sink.accept(&empty_batch()); + sink.accept(&empty_batch()); + + let contents = std::fs::read_to_string(&path).unwrap(); + let lines: Vec<&str> = contents.lines().collect(); + assert_eq!(lines.len(), 2); + for line in lines { + let value: serde_json::Value = serde_json::from_str(line).unwrap(); + assert_eq!( + value["schemaVersion"].as_u64(), + Some(u64::from(SCHEMA_VERSION)) + ); + } + } +} diff --git a/crates/telemetry/src/span.rs b/crates/telemetry/src/span.rs new file mode 100644 index 0000000..f4d58b0 --- /dev/null +++ b/crates/telemetry/src/span.rs @@ -0,0 +1,111 @@ +#[cfg(feature = "enabled")] +use crate::imp; +use crate::AttrValue; + +/// Times the enclosing scope. Dropping the guard ends the span and, when it is +/// the outermost span, submits the finished trace. +/// +/// Outside a [`crate::scope`] or [`crate::sync_scope`], entering a span is a +/// no-op. With the `enabled` feature off, the guard is zero-sized. +#[must_use = "the span ends when the guard is dropped"] +pub struct SpanGuard { + #[cfg(feature = "enabled")] + inner: Option, +} + +/// A scope captured on one thread so blocking work on another thread can join +/// the same trace. Create with [`ScopeHandle::capture`], resume with +/// [`attach_scope`]. +#[derive(Clone)] +pub struct ScopeHandle { + #[cfg(feature = "enabled")] + inner: Option, +} + +impl ScopeHandle { + /// Captures the active scope. Returns `None` outside a [`crate::scope`] or + /// [`crate::sync_scope`], and when collection is off. + #[inline] + pub fn capture() -> Option { + #[cfg(feature = "enabled")] + { + imp::capture_scope().map(|inner| Self { inner: Some(inner) }) + } + #[cfg(not(feature = "enabled"))] + { + None + } + } +} + +/// Runs blocking code with a captured scope installed on the current thread, +/// so spans it opens join the parent trace instead of starting a new one. +/// +/// Attaching does not sample and does not open a trace. Pass `None` to run `f` +/// unchanged; that is what [`ScopeHandle::capture`] returns when collection is +/// off. +pub fn attach_scope(handle: Option, f: impl FnOnce() -> R) -> R { + #[cfg(feature = "enabled")] + { + match handle.and_then(|handle| handle.inner) { + Some(inner) => imp::attach_scope(&inner, f), + None => f(), + } + } + #[cfg(not(feature = "enabled"))] + { + let _ = handle; + f() + } +} + +impl SpanGuard { + #[inline] + pub fn enter(name: &'static str) -> Self { + #[cfg(feature = "enabled")] + { + Self { + inner: imp::enter(name), + } + } + #[cfg(not(feature = "enabled"))] + { + let _ = name; + Self {} + } + } + + /// Opens the function's own span. Used by [`crate::trace`]. When the + /// caller already opened a call-site span with the same name, this is a + /// no-op so annotated functions do not produce duplicate spans. + #[doc(hidden)] + #[inline] + pub fn enter_function(name: &'static str) -> Self { + #[cfg(feature = "enabled")] + { + Self { + inner: imp::enter_function(name), + } + } + #[cfg(not(feature = "enabled"))] + { + let _ = name; + Self {} + } + } + + /// Attaches a value to this span specifically. [`crate::record_attribute`] + /// targets the innermost active span instead. + pub fn set_attribute(&self, key: &'static str, value: AttrValue) { + #[cfg(feature = "enabled")] + { + if let Some(inner) = &self.inner { + inner.set_attribute(key, value); + } + } + #[cfg(not(feature = "enabled"))] + { + let _ = (key, value); + } + } +} diff --git a/crates/telemetry/tests/passthrough.rs b/crates/telemetry/tests/passthrough.rs new file mode 100644 index 0000000..d2cd086 --- /dev/null +++ b/crates/telemetry/tests/passthrough.rs @@ -0,0 +1,31 @@ +#![cfg(not(feature = "enabled"))] + +#[telemetry::trace] +fn instrumented(value: u32) -> u32 { + value + 1 +} + +#[test] +fn the_attribute_and_runtime_are_inert() { + assert_eq!(instrumented(1), 2); + + telemetry::context! { + "ignored" => 1, + }; + + let guard = telemetry::SpanGuard::enter("ignored"); + guard.set_attribute("ignored", 1i64.into()); + + let error = std::io::Error::other("ignored"); + telemetry::record_error("ignored", &error); + telemetry::record_error_detail("ignored", &error); + telemetry::record_error_message("ignored", "ignored"); + + assert!(!telemetry::is_available()); + telemetry::enable(); + assert!(!telemetry::is_enabled()); + telemetry::disable(); + assert_eq!(telemetry::flush().traces, 0); + assert_eq!(telemetry::pending_traces(), 0); + assert_eq!(telemetry::dropped_traces(), 0); +} diff --git a/crates/telemetry/tests/span_tree.rs b/crates/telemetry/tests/span_tree.rs new file mode 100644 index 0000000..e9c9f04 --- /dev/null +++ b/crates/telemetry/tests/span_tree.rs @@ -0,0 +1,343 @@ +#![cfg(feature = "enabled")] + +use std::future::Future; +use std::sync::{Arc, Mutex, Once, OnceLock}; +use std::time::Duration; + +use telemetry::{AttrValue, Batch, Config, EnvironmentContext, Sink, SpanGuard, Trace}; + +#[derive(Debug, Default)] +struct Capture { + batches: Mutex>, +} + +impl Sink for Capture { + fn accept(&self, batch: &Batch) { + self.batches.lock().unwrap().push(batch.clone()); + } +} + +static CAPTURE: OnceLock> = OnceLock::new(); +static INIT: Once = Once::new(); + +fn setup() { + INIT.call_once(|| { + telemetry::set_enabled(false); + + let capture = Arc::new(Capture::default()); + CAPTURE.set(Arc::clone(&capture)).unwrap(); + + let config = Config::new(EnvironmentContext::detect("test")) + .enabled(true) + .env_kill_switch(false) + .sample_permille(1000) + .buffer_capacity(64); + telemetry::init(config, vec![capture]).unwrap(); + + assert!(!telemetry::is_enabled()); + assert!(telemetry::is_available()); + telemetry::enable(); + assert!(telemetry::is_enabled()); + }); +} + +fn last_batch() -> Batch { + let batches = CAPTURE.get().unwrap().batches.lock().unwrap(); + batches.last().cloned().expect("a flushed batch") +} + +fn trace_named<'a>(batch: &'a Batch, name: &str) -> &'a Trace { + batch + .traces + .iter() + .find(|trace| trace.root.name == name) + .unwrap_or_else(|| panic!("trace `{name}` not found")) +} + +#[telemetry::trace] +fn outer(value: &str) -> usize { + let copied = value.to_owned(); + inner(copied.len()) +} + +fn inner(value: usize) -> usize { + value + 1 +} + +#[telemetry::trace] +fn borrows_temporaries() -> usize { + let text = &make_text(); + let borrowed = take(&make_text()); + text.len() + borrowed +} + +fn make_text() -> String { + String::from("hello") +} + +fn take(text: &str) -> usize { + text.len() +} + +const fn array_len() -> usize { + 3 +} + +fn const_generic() -> usize { + N +} + +#[telemetry::trace] +fn uses_const_contexts() -> usize { + let buffer = [0u8; array_len()]; + const_generic::<{ array_len() }>() + buffer.len() +} + +#[derive(Default)] +struct Counter { + value: usize, +} + +impl Counter { + fn bump(&mut self) -> usize { + self.value += 1; + self.value + } +} + +#[telemetry::trace] +fn kitchen_sink(input: Option<&str>) -> Result { + let mut counter = Counter::default(); + let mut total = 0usize; + + if let Some(text) = input { + total += text.len(); + } + for part in ["a", "b"] { + if part.is_empty() { + continue; + } + total += part.len(); + } + while counter.value < 2 { + total += counter.bump(); + } + + let mapped = input.map(str::len).unwrap_or_default(); + let formatted = format!("{total}-{mapped}"); + let borrowed = &formatted[..1]; + let mut buffer = [0u8; 2]; + buffer[0] = borrowed.len() as u8; + + let result = match input { + Some(text) => text.len(), + None => 0, + }; + let closure = |value: usize| value + result; + let doubled = closure(total); + if doubled > 100 { + return Ok(doubled); + } + + let _ = buffer; + Ok(doubled + counter.value) +} + +fn skipped_work() -> usize { + 10 +} + +fn visible_work() -> usize { + 1 +} + +#[telemetry::trace] +fn skips_one_call() -> usize { + let hidden = telemetry::skip!(skipped_work()); + let visible = visible_work(); + hidden + visible +} + +#[telemetry::trace] +fn outer_traced() -> usize { + inner_traced() +} + +#[telemetry::trace] +fn inner_traced() -> usize { + 1 +} + +#[telemetry::trace] +async fn outer_async() -> u32 { + inner_async().await + 1 +} + +async fn inner_async() -> u32 { + 1 +} + +#[test] +fn builds_traces_and_reports_errors() { + setup(); + + telemetry::sync_scope(|| { + let root = SpanGuard::enter("manual_root"); + { + let _child = SpanGuard::enter("manual_child"); + std::thread::sleep(Duration::from_millis(2)); + telemetry::context! { + "items" => 3u64, + "cached" => false, + }; + } + telemetry::record_error_message( + "manual_failure", + "failed at C:\\Users\\bob\\repo and https://example.com/x", + ); + drop(root); + }); + + assert_eq!(telemetry::sync_scope(|| outer("abc")), 4); + assert_eq!(telemetry::sync_scope(borrows_temporaries), 10); + assert_eq!(telemetry::sync_scope(uses_const_contexts), 6); + assert_eq!( + telemetry::sync_scope(|| kitchen_sink(Some("abc"))).unwrap(), + 13 + ); + assert_eq!(telemetry::sync_scope(outer_traced), 1); + assert_eq!(telemetry::sync_scope(skips_one_call), 11); + + telemetry::sync_scope(|| { + let root = SpanGuard::enter("attached_root"); + let scope = telemetry::ScopeHandle::capture(); + assert!(scope.is_some(), "captured scope"); + std::thread::spawn(move || { + telemetry::attach_scope(scope, || { + let _child = SpanGuard::enter("attached_child"); + }); + }) + .join() + .unwrap(); + drop(root); + }); + + let mut polled = Box::pin(telemetry::scope(async { 7 })); + let waker = std::task::Waker::noop(); + let mut poll_context = std::task::Context::from_waker(waker); + assert!(matches!( + polled.as_mut().poll(&mut poll_context), + std::task::Poll::Ready(7) + )); + + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let value = runtime.block_on(telemetry::scope(outer_async())); + assert_eq!(value, 2); + + drop(runtime); + + let report = telemetry::flush(); + assert_eq!(report.sink_failures, 0); + assert_eq!(report.dropped_traces, 0); + assert!(!CAPTURE.get().unwrap().batches.lock().unwrap().is_empty()); + + let batch = last_batch(); + assert!(batch + .traces + .iter() + .any(|trace| trace.root.name == "manual_root")); + + let manual = trace_named(&batch, "manual_root"); + assert_eq!(manual.root.children.len(), 1); + let child = &manual.root.children[0]; + assert_eq!(child.name, "manual_child"); + assert_eq!(child.attributes.get("items"), Some(&AttrValue::Uint(3))); + assert_eq!( + child.attributes.get("cached"), + Some(&AttrValue::Bool(false)) + ); + + let attached = trace_named(&batch, "attached_root"); + assert_eq!(attached.root.children.len(), 1); + assert_eq!(attached.root.children[0].name, "attached_child"); + + let error = manual.root.error.as_ref().expect("error on root"); + assert_eq!(error.code, "manual_failure"); + assert_eq!(error.message.as_deref(), Some("failed at ")); + + let traced = trace_named(&batch, "outer"); + let child_names: Vec<&str> = traced + .root + .children + .iter() + .map(|span| span.name.as_str()) + .collect(); + assert_eq!(child_names, vec!["inner"]); + assert!(traced + .root + .children + .iter() + .all(|span| span.duration_us <= traced.root.duration_us)); + + let const_contexts = trace_named(&batch, "uses_const_contexts"); + assert!(const_contexts + .root + .children + .iter() + .any(|span| span.name == "const_generic")); + + let nested = trace_named(&batch, "outer_traced"); + assert_eq!(nested.root.children.len(), 1); + assert_eq!(nested.root.children[0].name, "inner_traced"); + assert!(nested.root.children[0].children.is_empty()); + + let skipped = trace_named(&batch, "skips_one_call"); + let skipped_children: Vec<&str> = skipped + .root + .children + .iter() + .map(|span| span.name.as_str()) + .collect(); + assert_eq!(skipped_children, vec!["visible_work"]); + + let borrowed = trace_named(&batch, "borrows_temporaries"); + let borrowed_children: Vec<&str> = borrowed + .root + .children + .iter() + .map(|span| span.name.as_str()) + .collect(); + assert_eq!(borrowed_children, vec!["make_text", "take"]); + let take_span = borrowed + .root + .children + .iter() + .find(|span| span.name == "take") + .unwrap(); + assert!(take_span + .children + .iter() + .any(|span| span.name == "make_text")); + + let asynchronous = trace_named(&batch, "outer_async"); + let async_children: Vec<&str> = asynchronous + .root + .children + .iter() + .map(|span| span.name.as_str()) + .collect(); + assert_eq!(async_children, vec!["inner_async"]); + + let chrome: serde_json::Value = serde_json::from_str(&batch.to_chrome_trace_json()).unwrap(); + assert!(chrome["traceEvents"].as_array().unwrap().len() >= 5); + + telemetry::set_enabled(false); + assert!(!telemetry::is_enabled()); + telemetry::sync_scope(|| { + let _ = SpanGuard::enter("after_disable"); + }); + assert_eq!(telemetry::pending_traces(), 0); +} diff --git a/package.json b/package.json index 09aa13f..e7df0b0 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,6 @@ "lint:fix": "oxlint --fix", "format": "oxfmt", "format:check": "oxfmt --check", - "boot-trace": "node scripts/boot-trace.mjs", "typecheck": "tsc --noEmit", "icons": "node scripts/generate-icons.mjs", "tauri": "dotenv -- tauri", diff --git a/scripts/boot-trace.mjs b/scripts/boot-trace.mjs deleted file mode 100644 index ac78a29..0000000 --- a/scripts/boot-trace.mjs +++ /dev/null @@ -1,168 +0,0 @@ -import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; -import { homedir } from "node:os"; -import { basename, dirname, join, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -// Must match the marker emitted by src/lib/bootstrap/boot-timing.ts and -// crates/tauri/src/boot_trace.rs. -const MARKER = "[boottrace]"; - -const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); - -const TARGETS = { - dev: "gitau-dev.log", - release: "gitau.log", -}; - -function usage() { - console.log( - [ - "usage: node scripts/boot-trace.mjs [dev|release|] [out.json]", - "", - " dev trace the debug log (default)", - " release trace the release log", - " trace a specific log file", - ].join("\n") - ); -} - -function logDir() { - const conf = JSON.parse( - readFileSync(join(root, "crates/tauri/tauri.conf.json"), "utf8") - ); - const id = conf.identifier; - if (process.platform === "win32") { - const local = - process.env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local"); - return join(local, id, "logs"); - } - if (process.platform === "darwin") { - return join(homedir(), "Library", "Logs", id); - } - const data = - process.env.XDG_DATA_HOME ?? join(homedir(), ".local", "share"); - return join(data, id, "logs"); -} - -function resolveTarget(arg) { - const named = Object.hasOwn(TARGETS, arg); - const path = named ? join(logDir(), TARGETS[arg]) : resolve(arg); - if (!existsSync(path)) { - if (named) { - console.error(`no ${arg} log at ${path}`); - console.error( - "run the app first, or pass an explicit log file path" - ); - } else { - console.error(`no such log file: ${path}`); - } - process.exit(1); - } - return path; -} - -function parseEvents(text) { - const events = []; - for (const line of text.split(/\r?\n/)) { - const at = line.indexOf(MARKER); - if (at === -1) continue; - const body = line.slice(at + MARKER.length).trim(); - try { - events.push(JSON.parse(body)); - } catch { - // A line truncated mid-flush at process exit is not an error. - } - } - return events; -} - -function metadata(events) { - const laneNames = new Map(); - for (const event of events) { - const key = `${event.pid}:${event.tid}`; - if (!laneNames.has(key)) laneNames.set(key, event.name); - } - const rows = [ - { name: "process_name", ph: "M", pid: 1, args: { name: "tauri" } }, - { name: "process_name", ph: "M", pid: 2, args: { name: "webview" } }, - ]; - for (const [key, name] of laneNames) { - const [pid, tid] = key.split(":").map(Number); - rows.push({ name: "thread_name", ph: "M", pid, tid, args: { name } }); - } - return rows; -} - -function summarize(events) { - const start = Math.min(...events.map((event) => event.ts)); - const end = Math.max(...events.map((event) => event.ts + (event.dur ?? 0))); - const lines = events - .filter((event) => event.ph === "X" || event.ph === "i") - .sort((a, b) => a.ts - b.ts) - .map((event) => { - const from = ((event.ts - start) / 1000).toFixed(1).padStart(7); - if (event.ph === "i") { - return ` ${from}ms (mark) ${event.name}`; - } - const to = ((event.ts + event.dur - start) / 1000) - .toFixed(1) - .padStart(7); - return ` ${from}ms -> ${to}ms ${event.name}`; - }); - return [ - `span ${((end - start) / 1000).toFixed(1)}ms, ${events.length} events`, - ...lines, - ].join("\n"); -} - -function main() { - const [target, output] = process.argv.slice(2); - if (target === "-h" || target === "--help") { - usage(); - return; - } - - const inputPath = resolveTarget(target ?? "dev"); - const events = parseEvents(readFileSync(inputPath, "utf8")).sort( - (a, b) => a.ts - b.ts - ); - if (events.length === 0) { - console.error(`no ${MARKER} lines in ${inputPath}`); - process.exit(1); - } - - // The log is append-only; summarize only the latest run. - const launches = events.filter((event) => event.name === "rust.launch"); - const runStart = launches.length - ? launches[launches.length - 1].ts - : Number.NEGATIVE_INFINITY; - const run = - launches.length > 1 - ? events.filter((event) => event.ts >= runStart) - : events; - - const label = basename(inputPath).replace(/\.[^.]+$/, ""); - const outPath = resolve( - output ?? - join( - root, - "node_modules/.cache/gitau-boot-trace", - `${label}.trace.json` - ) - ); - mkdirSync(dirname(outPath), { recursive: true }); - writeFileSync( - outPath, - JSON.stringify({ traceEvents: [...metadata(run), ...run] }) - ); - - if (launches.length > 1) { - console.log(`latest of ${launches.length} runs in ${inputPath}`); - } - console.log(summarize(run)); - console.log( - `\nwrote ${outPath} (open in chrome://tracing or ui.perfetto.dev)` - ); -} - -main(); diff --git a/src/components/active-tab-host.tsx b/src/components/active-tab-host.tsx index 6f012d5..de0d48b 100644 --- a/src/components/active-tab-host.tsx +++ b/src/components/active-tab-host.tsx @@ -3,7 +3,6 @@ import { useSelector } from "@tanstack/react-store"; import { Activity, memo, useEffect, useLayoutEffect } from "react"; import { useAppServices } from "@/contexts/services-context"; -import { bootMark } from "@/lib/bootstrap/boot-timing"; import { createTabRouter, type TabRouter, @@ -28,9 +27,6 @@ import { * in the runtime registry so each tab's memory history persists. Always * keeps at least one tab. */ -let reportedFirstMount = false; -let reportedFirstPaint = false; - export function ActiveTabHost() { const services = useAppServices(); @@ -47,19 +43,6 @@ export function ActiveTabHost() { // Runtime creation is a side effect: it bumps the registry version // store, which must not happen during render. useLayoutEffect(() => { - if (!reportedFirstMount) { - reportedFirstMount = true; - bootMark("first.mount"); - // Double rAF lands after the browser painted the committed tree. - requestAnimationFrame(() => - requestAnimationFrame(() => { - if (!reportedFirstPaint) { - reportedFirstPaint = true; - bootMark("first.paint"); - } - }) - ); - } for (const tab of tabs) { const runtime = getOrCreateRuntime(tab); runtime.router ??= createTabRouter( diff --git a/src/components/onboarding-dialog.tsx b/src/components/onboarding-dialog.tsx index eadc342..696ded8 100644 --- a/src/components/onboarding-dialog.tsx +++ b/src/components/onboarding-dialog.tsx @@ -21,6 +21,7 @@ import { } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Scritto } from "@/components/ui/scritto"; +import { SwitchIndicator } from "@/components/ui/switch"; import { Tabs, TabsList, TabsTab } from "@/components/ui/tabs"; import type { AppCommandActions } from "@/contexts/app-command-context"; import { useAppCommands } from "@/contexts/app-command-context"; @@ -42,6 +43,12 @@ const STEPS = [ description: "Gitau opens changed files in this editor. Pick one you already use, or set your own command.", }, + { + id: "privacy", + title: "Help improve Gitau", + description: + "Share anonymous timing and error data so slow paths and failures can be fixed. Off unless you turn it on.", + }, { id: "start", title: "Add a repository", @@ -187,6 +194,22 @@ export function OnboardingDialog() { )} + {activeTab === "privacy" && ( + + + + )} {activeTab === "start" && ( setValue(!value)} + className={cn( + CHOICE_CARD, + value ? CHOICE_CARD_SELECTED : CHOICE_CARD_IDLE, + "gap-6" + )} + > + + + Send anonymous telemetry + + + Timing and error data only. Repository names, paths, branch + names, and file contents are never sent. + + + + + ); +} + const START_ACTIONS: { command: keyof AppCommandActions; icon: LucideIcon; diff --git a/src/components/ui/switch.tsx b/src/components/ui/switch.tsx index a840d31..8811785 100644 --- a/src/components/ui/switch.tsx +++ b/src/components/ui/switch.tsx @@ -5,27 +5,53 @@ import type React from "react"; import { cn } from "@/lib/utils"; +const SWITCH_ROOT_CLASS = + "inline-flex h-[calc(var(--thumb-size)+2px)] w-[calc(var(--thumb-size)*2-2px)] shrink-0 items-center rounded-full p-px transition-[background-color,box-shadow] duration-200 outline-none [--thumb-size:--spacing(5)] focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background sm:[--thumb-size:--spacing(4)] data-checked:bg-primary data-unchecked:bg-input data-disabled:cursor-not-allowed data-disabled:opacity-64"; + +const SWITCH_THUMB_CLASS = + "pointer-events-none block aspect-square h-full origin-left rounded-(--thumb-size) bg-background shadow-sm/5 will-change-transform [transition:translate_.15s,border-radius_.15s,scale_.1s_.1s,transform-origin_.15s] in-[[role=switch]:active,[data-slot=label]:active,[data-slot=field-label]:active]:rounded-[var(--thumb-size)/calc(var(--thumb-size)*1.1)] in-[[role=switch]:active,[data-slot=label]:active,[data-slot=field-label]:active]:not-data-disabled:scale-x-110 data-checked:origin-[var(--thumb-size)_50%] data-checked:translate-x-[calc(var(--thumb-size)-4px)]"; + export function Switch({ className, ...props }: SwitchPrimitive.Root.Props): React.ReactElement { return ( ); } +export function SwitchIndicator({ + checked, + className, +}: { + checked: boolean; + className?: string; +}) { + return ( +