Skip to main content

zebrad/
sentry.rs

1//! Integration with sentry.io for event reporting.
2
3use std::{
4    borrow::Cow,
5    collections::BTreeMap,
6    env,
7    panic::PanicHookInfo,
8    sync::{
9        atomic::{AtomicU64, Ordering},
10        Mutex, MutexGuard, PoisonError,
11    },
12    thread,
13    time::{Duration, Instant, SystemTime},
14};
15
16use sentry::{
17    integrations::{backtrace::current_stacktrace, tracing::EventFilter},
18    protocol::{
19        Context, Envelope, Event, Exception, Frame, Log, LogAttribute, Map, Mechanism,
20        SessionAttributes, SessionStatus, SessionUpdate, Stacktrace, Value,
21    },
22    types::random_uuid,
23    ClientInitGuard, ClientOptions, Hub, Scope,
24};
25use tracing::Level;
26use zebra_chain::{
27    block::Height,
28    parameters::{Network, NetworkUpgrade},
29};
30
31use crate::{
32    application::{build_version, ZebradApp},
33    components::{
34        metrics::{
35            node_context::{self, ChainPosition},
36            sentry_policy::{SentryPolicy, TRANSPORT_QUEUE_ENVELOPES},
37        },
38        sync::progress,
39    },
40};
41
42mod metrics_adapter;
43
44/// Sends a tip block delay to Sentry with the block's height, so that nodes can be compared block
45/// by block.
46///
47/// The height isn't a label on the `zcash.chain.tip.block_delay_seconds` histogram, because
48/// Prometheus would keep a series per height, so the metrics policy skips that histogram.
49pub(crate) fn send_tip_block_delay(height: Height, seconds: f64) {
50    tip_block_delay(node_context::network(), height, seconds).capture();
51}
52
53/// Returns a tip block delay with the block's height and, once the network is known, its network
54/// upgrade.
55///
56/// The network upgrade comes from the block's own height, because the tip height that the node
57/// context reports lags behind a new tip, which would put an activation block in the previous
58/// upgrade.
59fn tip_block_delay(
60    network: Option<&Network>,
61    height: Height,
62    seconds: f64,
63) -> sentry::metrics::DistributionMetric {
64    let distribution =
65        sentry::metrics::distribution("zcash.chain.tip.block_delay_seconds", seconds)
66            .unit(sentry::protocol::Unit::Second)
67            .attribute("chain.height", height.0);
68
69    match network {
70        Some(network) => distribution.attribute(
71            "chain.network_upgrade",
72            NetworkUpgrade::current(network, height).to_string(),
73        ),
74        None => distribution,
75    }
76}
77
78/// Keeps the Sentry client open until [`end`] drops it.
79///
80/// `zebrad` exits with `process::exit`, which skips destructors, so the guard must be dropped
81/// explicitly to end the release health session and flush queued events and logs.
82static CLIENT_GUARD: Mutex<Option<ClientInitGuard>> = Mutex::new(None);
83
84/// The release health session in progress.
85///
86/// Zebra tracks sessions itself instead of through the SDK. The SDK keeps a session per hub, and
87/// a thread's hub keeps the session it copied when the thread first used Sentry, so a session
88/// the SDK started later, such as a daily one, would miss errors reported on other threads.
89static SESSION: Mutex<Option<SessionUpdate<'static>>> = Mutex::new(None);
90
91/// Errors reported from any thread since the session in progress started.
92static SESSION_ERRORS: AtomicU64 = AtomicU64::new(0);
93
94/// How long one release health session lasts before it is ended and replaced.
95///
96/// Sentry drops session updates for sessions that started more than five days earlier, so a
97/// longer session could never report how it ended.
98const SESSION_ROTATION_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60);
99
100/// Environment and CI metadata attached to all Sentry events.
101#[derive(Debug, Default)]
102struct Metadata {
103    environment: Option<String>,
104    tags: BTreeMap<&'static str, String>,
105    ci_context: BTreeMap<&'static str, String>,
106}
107
108impl Metadata {
109    fn from_env() -> Self {
110        Self::from_lookup(env_var)
111    }
112
113    fn from_lookup<F>(lookup: F) -> Self
114    where
115        F: Fn(&str) -> Option<String>,
116    {
117        let mut metadata = Self {
118            environment: lookup_value(&lookup, "SENTRY_ENVIRONMENT"),
119            ..Default::default()
120        };
121
122        insert_lookup_values(
123            &lookup,
124            &mut metadata.ci_context,
125            &[
126                ("GITHUB_RUN_ID", "run_id"),
127                ("GITHUB_RUN_ATTEMPT", "run_attempt"),
128                ("GITHUB_WORKFLOW", "workflow"),
129                ("GITHUB_JOB", "job"),
130            ],
131        );
132
133        insert_lookup_values(
134            &lookup,
135            &mut metadata.tags,
136            &[
137                ("GITHUB_EVENT_NAME", "deploy.trigger"),
138                ("CI_PR_NUMBER", "pr.number"),
139                ("CI_TEST_ID", "test.id"),
140            ],
141        );
142
143        if let Some(git_ref) = slugged_git_ref(&lookup) {
144            metadata.tags.insert("git.ref", git_ref);
145        }
146
147        let git_sha = lookup_value(&lookup, "GITHUB_SHA")
148            .or_else(|| ZebradApp::git_commit().map(ToOwned::to_owned));
149        if let Some(git_sha) = git_sha {
150            metadata.tags.insert("git.sha", git_sha);
151        }
152
153        if lookup_value(&lookup, "GITHUB_ACTIONS").is_some_and(|v| v.eq_ignore_ascii_case("true")) {
154            metadata
155                .tags
156                .insert("ci.provider", "github-actions".to_owned());
157        }
158
159        metadata
160    }
161
162    fn client_options(&self) -> ClientOptions {
163        self.client_options_with_release(release_name())
164    }
165
166    fn client_options_with_release(&self, release: String) -> ClientOptions {
167        let log_attributes = self.log_attributes();
168        let network = self.tags.get("chain.network").cloned();
169        let started_at = Instant::now();
170        let options = ClientOptions::new()
171            .release(release)
172            // The Sentry metrics flush budget is a share of this queue.
173            .transport_channel_capacity(TRANSPORT_QUEUE_ENVELOPES)
174            .transport(metrics_adapter::transport_factory())
175            // Suspect commits need in-app stack frames. Only ERROR events and panics are sent as
176            // events, so capturing the stack stays off the common paths.
177            .attach_stacktrace(true)
178            .before_send(|mut event| {
179                if event.level >= sentry::Level::Error {
180                    SESSION_ERRORS.fetch_add(1, Ordering::Relaxed);
181                }
182                mark_zebra_frames_in_app(&mut event);
183                add_chain_tags(&mut event, node_context::chain_position());
184                Some(event)
185            })
186            .before_send_log(move |mut log| {
187                merge_log_attributes(&mut log, &log_attributes);
188                merge_log_attributes(
189                    &mut log,
190                    &chain_log_attributes(node_context::chain_position()),
191                );
192                Some(log)
193            })
194            .before_send_metric(move |mut metric| {
195                add_metric_attributes(
196                    &mut metric.attributes,
197                    network.as_deref(),
198                    node_context::chain_position(),
199                    started_at.elapsed(),
200                );
201                Some(metric)
202            });
203
204        match &self.environment {
205            Some(environment) => options.environment(environment.clone()),
206            None => options,
207        }
208    }
209
210    /// Build the static CI/git attributes to attach to every outgoing [`Log`].
211    ///
212    /// `Scope::set_tag` only propagates to [`Event`]s, so Logs need their own
213    /// enrichment path. CI context is namespaced under `ci.*` to mirror the
214    /// grouping used for Event contexts.
215    fn log_attributes(&self) -> Vec<(String, LogAttribute)> {
216        let mut attrs = Vec::with_capacity(self.tags.len() + self.ci_context.len());
217        for (key, value) in &self.tags {
218            attrs.push(((*key).to_owned(), LogAttribute::from(value.clone())));
219        }
220        for (key, value) in &self.ci_context {
221            attrs.push((format!("ci.{key}"), LogAttribute::from(value.clone())));
222        }
223        attrs
224    }
225
226    fn apply_to_scope(&self, scope: &mut Scope) {
227        for (key, value) in &self.tags {
228            scope.set_tag(key, value.as_str());
229        }
230
231        if !self.ci_context.is_empty() {
232            scope.set_context("ci", Context::Other(context_map(&self.ci_context)));
233        }
234    }
235
236    #[cfg(test)]
237    fn environment(&self) -> Option<&str> {
238        self.environment.as_deref()
239    }
240}
241
242/// Starts the Sentry client and its release health sessions, which are replaced daily.
243pub(crate) fn init(network: &Network) {
244    let mut metadata = Metadata::from_env();
245    metadata.tags.insert("chain.network", network.to_string());
246
247    let guard = sentry::init(metadata.client_options());
248    sentry::configure_scope(|scope| metadata.apply_to_scope(scope));
249
250    let enabled = guard.is_enabled();
251    *CLIENT_GUARD.lock().unwrap_or_else(PoisonError::into_inner) = Some(guard);
252
253    // A disabled client has no sessions to rotate.
254    if !enabled {
255        return;
256    }
257
258    start_run_sessions();
259
260    let rotation = thread::Builder::new()
261        .name("sentry session rotation".to_owned())
262        .spawn(|| loop {
263            thread::sleep(SESSION_ROTATION_INTERVAL);
264            rotate_session();
265        });
266    if let Err(error) = rotation {
267        warn!(?error, "unable to start Sentry session rotation");
268    }
269}
270
271/// Starts the first release health session of this run.
272///
273/// Every session of the run reports the same random ID as its distinct ID, so Sentry's crash-free
274/// users rate is the share of runs without a crash.
275fn start_run_sessions() {
276    let Some(client) = Hub::current().client() else {
277        return;
278    };
279    let options = client.options();
280    let Some(release) = options.release.clone() else {
281        return;
282    };
283
284    let attributes = SessionAttributes {
285        release,
286        environment: options.environment.clone(),
287        ip_address: None,
288        user_agent: None,
289    };
290
291    start_session(attributes, random_uuid().to_string());
292}
293
294/// Starts a release health session and reports that it started.
295fn start_session(attributes: SessionAttributes<'static>, run_id: String) {
296    let session = SessionUpdate {
297        session_id: random_uuid(),
298        distinct_id: Some(run_id),
299        sequence: None,
300        timestamp: None,
301        started: SystemTime::now(),
302        init: true,
303        duration: None,
304        status: SessionStatus::Ok,
305        errors: 0,
306        attributes,
307    };
308
309    send_session(session.clone());
310    *lock_session() = Some(session);
311}
312
313/// Ends the session in progress with `status`, reports it, and returns it.
314fn end_session(status: SessionStatus) -> Option<SessionUpdate<'static>> {
315    let mut session = lock_session().take()?;
316
317    session.init = false;
318    session.status = status;
319    session.errors = SESSION_ERRORS.swap(0, Ordering::Relaxed);
320    session.timestamp = Some(SystemTime::now());
321    session.duration = session
322        .started
323        .elapsed()
324        .ok()
325        .map(|duration| duration.as_secs_f64());
326
327    send_session(session.clone());
328    Some(session)
329}
330
331/// Ends the session in progress as exited and starts the next session of the same run.
332fn rotate_session() {
333    if let Some(ended) = end_session(SessionStatus::Exited) {
334        let run_id = ended
335            .distinct_id
336            .expect("every session is started with the run ID");
337        start_session(ended.attributes, run_id);
338    }
339}
340
341fn send_session(session: SessionUpdate<'static>) {
342    if let Some(client) = Hub::current().client() {
343        let mut envelope = Envelope::new();
344        envelope.add_item(session);
345        client.send_envelope(envelope);
346    }
347}
348
349fn lock_session() -> MutexGuard<'static, Option<SessionUpdate<'static>>> {
350    SESSION.lock().unwrap_or_else(PoisonError::into_inner)
351}
352
353/// Ends the release health session with `status`, sends the metrics that are due without waiting
354/// between envelopes, then closes the client.
355///
356/// The session update is queued before the metrics, so metrics can't take its place in the
357/// transport queue.
358///
359/// Returns `false` if queued events, logs, and metrics could not be sent before the shutdown
360/// timeout.
361pub(crate) fn end(status: SessionStatus) -> bool {
362    end_session(status);
363    metrics_adapter::flush_at_exit();
364
365    let guard = CLIENT_GUARD
366        .lock()
367        .unwrap_or_else(PoisonError::into_inner)
368        .take();
369
370    guard.is_none_or(|guard| guard.close(None))
371}
372
373/// Adds the chain position to `event`, keeping any tags the event already has.
374fn add_chain_tags(event: &mut Event<'static>, chain_position: Option<ChainPosition>) {
375    let Some(chain_position) = chain_position else {
376        return;
377    };
378
379    event
380        .tags
381        .entry("chain.height".to_owned())
382        .or_insert_with(|| chain_position.tip_height.0.to_string());
383    event
384        .tags
385        .entry("chain.network_upgrade".to_owned())
386        .or_insert_with(|| chain_position.network_upgrade.to_string());
387}
388
389/// Returns the chain position as log attributes, with the height as a number so that log
390/// queries can aggregate it.
391fn chain_log_attributes(chain_position: Option<ChainPosition>) -> Vec<(String, LogAttribute)> {
392    let Some(chain_position) = chain_position else {
393        return Vec::new();
394    };
395
396    vec![
397        (
398            "chain.height".to_owned(),
399            LogAttribute::from(chain_position.tip_height.0),
400        ),
401        (
402            "chain.network_upgrade".to_owned(),
403            LogAttribute::from(chain_position.network_upgrade.to_string()),
404        ),
405    ]
406}
407
408/// Adds the network, the network upgrade at the tip, whether the node is near the tip, and the
409/// process uptime to a metric's attributes, keeping any the metric already has.
410///
411/// Unlike events and logs, metrics don't get the tip height, because a block timing value is often
412/// for a block above the tip.
413fn add_metric_attributes(
414    attributes: &mut Map<Cow<'static, str>, LogAttribute>,
415    network: Option<&str>,
416    chain_position: Option<ChainPosition>,
417    uptime: Duration,
418) {
419    if let Some(network) = network {
420        attributes
421            .entry("chain.network".into())
422            .or_insert_with(|| network.to_owned().into());
423    }
424    if let Some(chain_position) = chain_position {
425        attributes
426            .entry("chain.network_upgrade".into())
427            .or_insert_with(|| chain_position.network_upgrade.to_string().into());
428        attributes
429            .entry("chain.near_tip".into())
430            .or_insert_with(|| chain_position.near_tip.into());
431    }
432    attributes
433        .entry("process.uptime_seconds".into())
434        .or_insert_with(|| uptime.as_secs().into());
435}
436
437/// Returns the Sentry tracing layer, or `None` if [`init`] has not bound an enabled client.
438///
439/// Must be called after [`init`].
440pub(crate) fn tracing_layer<S>() -> Option<impl tracing_subscriber::Layer<S>>
441where
442    S: tracing::Subscriber + for<'span> tracing_subscriber::registry::LookupSpan<'span>,
443{
444    is_client_enabled().then(|| {
445        sentry::integrations::tracing::layer()
446            // Zebra doesn't send Sentry traces, so a Sentry span would never be sent, and building
447            // one costs work on every poll of an instrumented future, such as each peer message.
448            .span_filter(|_| false)
449            .event_filter(|metadata| match *metadata.level() {
450                Level::ERROR => EventFilter::Event | EventFilter::Log,
451                Level::WARN => EventFilter::Log | EventFilter::Breadcrumb,
452                // Sync progress is logged once a minute, so sending it gives Sentry each node's
453                // height and network upgrade over time without the volume of all INFO logs.
454                Level::INFO if metadata.target() == progress::LOG_TARGET => {
455                    EventFilter::Log | EventFilter::Breadcrumb
456                }
457                Level::INFO => EventFilter::Breadcrumb,
458                _ => EventFilter::Ignore,
459            })
460    })
461}
462
463/// Returns the recorder that sends every metric to Sentry, starting the thread that flushes it on
464/// the first call. Returns `None` if [`init`] has not bound an enabled client, or if that thread
465/// can't start.
466///
467/// Must be called after the tracing subscriber is installed, so a failure to start the thread is
468/// logged.
469pub(crate) fn metrics_recorder() -> Option<&'static SentryPolicy> {
470    if !is_client_enabled() {
471        return None;
472    }
473
474    metrics_adapter::start()
475}
476
477fn is_client_enabled() -> bool {
478    Hub::current()
479        .client()
480        .is_some_and(|client| client.is_enabled())
481}
482
483/// Builds the Sentry event for a panic.
484///
485/// Like Sentry's panic integration, the panic message becomes the issue title and the current
486/// stack trace locates and groups it. Zebra's panic report is attached for its diagnostic
487/// metadata.
488pub(crate) fn panic_event_from(
489    panic_info: &PanicHookInfo<'_>,
490    panic_report: impl ToString,
491) -> Event<'static> {
492    let exception = Exception {
493        ty: "panic".into(),
494        mechanism: Some(Mechanism {
495            ty: "panic".into(),
496            handled: Some(false),
497            ..Default::default()
498        }),
499        value: Some(
500            panic_info
501                .payload_as_str()
502                .unwrap_or("Box<dyn Any>")
503                .to_owned(),
504        ),
505        stacktrace: current_stacktrace().map(without_panic_handling_frames),
506        ..Default::default()
507    };
508
509    let mut panic_context = Map::new();
510    panic_context.insert("report".to_owned(), panic_report.to_string().into());
511    if let Some(location) = panic_info.location() {
512        panic_context.insert("location".to_owned(), location.to_string().into());
513    }
514
515    let mut event = Event {
516        exception: vec![exception].into(),
517        level: sentry::Level::Fatal,
518        ..Default::default()
519    };
520    event
521        .contexts
522        .insert("panic".to_owned(), Context::Other(panic_context));
523
524    event
525}
526
527/// Removes the frames that handle the panic: the standard library's panic machinery and the
528/// panic hook that builds the event.
529///
530/// Sentry names an issue after its newest in-app frame, and the hook's frames are in-app, so
531/// without this every panic would point at the hook instead of the code that panicked.
532fn without_panic_handling_frames(mut stacktrace: Stacktrace) -> Stacktrace {
533    let starts_panic = |frame: &Frame| {
534        frame.function.as_deref().is_some_and(|function| {
535            function.starts_with("std::panicking::") || function.ends_with("rust_begin_unwind")
536        })
537    };
538    let is_runtime = |frame: &Frame| {
539        frame.function.as_deref().is_some_and(|function| {
540            function.starts_with("std::")
541                || function.starts_with("core::")
542                || function.ends_with("rust_begin_unwind")
543        })
544    };
545
546    // Frames are ordered from oldest to newest.
547    if let Some(mut first_panic_frame) = stacktrace.frames.iter().rposition(starts_panic) {
548        while first_panic_frame > 0 && is_runtime(&stacktrace.frames[first_panic_frame - 1]) {
549            first_panic_frame -= 1;
550        }
551        stacktrace.frames.truncate(first_panic_frame);
552    }
553
554    stacktrace
555}
556
557/// Marks the stack frames from Zebra's crates as in-app, and every other frame as not in-app.
558///
559/// The SDK classifies frames by function name, but release builds keep only line tables, so
560/// inlined frames lose their module path. When no frame matches, the SDK marks every frame
561/// in-app. Zebra's frames keep their source file, so Zebra classifies frames by path instead, and
562/// frames without one are not in-app.
563fn mark_zebra_frames_in_app(event: &mut Event<'static>) {
564    let exception_stacktraces = event
565        .exception
566        .values
567        .iter_mut()
568        .filter_map(|exception| exception.stacktrace.as_mut());
569    let thread_stacktraces = event
570        .threads
571        .values
572        .iter_mut()
573        .filter_map(|thread| thread.stacktrace.as_mut());
574
575    for stacktrace in exception_stacktraces
576        .chain(thread_stacktraces)
577        .chain(event.stacktrace.as_mut())
578    {
579        for frame in &mut stacktrace.frames {
580            frame.in_app = Some(frame.abs_path.as_deref().is_some_and(is_zebra_source));
581        }
582    }
583}
584
585/// Returns whether `path` is a source file in one of Zebra's crates.
586///
587/// A crate's sources are in `<crate directory>/src/`. The directory is the crate name in a
588/// checkout, such as `/zebra/zebrad/src/` in the Docker images, and the crate name and version
589/// in the Cargo registry, such as `zebra-chain-14.0.0/src/`.
590fn is_zebra_source(path: &str) -> bool {
591    let is_zebra_crate = |dir: &str| {
592        dir == "zebrad"
593            || ["zebrad-", "zebra-", "tower-batch-control", "tower-fallback"]
594                .iter()
595                .any(|prefix| dir.starts_with(prefix))
596    };
597
598    let dirs = || path.split(['/', '\\']);
599
600    dirs()
601        .zip(dirs().skip(1))
602        .any(|(dir, next)| next == "src" && is_zebra_crate(dir))
603}
604
605/// Merge `attrs` into `log.attributes`, letting existing keys win.
606///
607/// Tracing event fields are already present on the [`Log`] when the
608/// `before_send_log` hook fires, so we must not overwrite them; this keeps
609/// our CI/git metadata as a fallback that enriches (but never masks) the
610/// log's own attributes.
611fn merge_log_attributes(log: &mut Log, attrs: &[(String, LogAttribute)]) {
612    for (key, value) in attrs {
613        log.attributes
614            .entry(key.clone())
615            .or_insert_with(|| value.clone());
616    }
617}
618
619fn env_var(key: &str) -> Option<String> {
620    env::var(key).ok()
621}
622
623fn lookup_value<F>(lookup: &F, key: &str) -> Option<String>
624where
625    F: Fn(&str) -> Option<String>,
626{
627    let value = lookup(key)?;
628    let value = value.trim();
629
630    (!value.is_empty()).then(|| value.to_owned())
631}
632
633fn insert_lookup_values<F>(
634    lookup: &F,
635    target: &mut BTreeMap<&'static str, String>,
636    mappings: &[(&str, &'static str)],
637) where
638    F: Fn(&str) -> Option<String>,
639{
640    for (env_key, target_key) in mappings {
641        if let Some(value) = lookup_value(lookup, env_key) {
642            target.insert(*target_key, value);
643        }
644    }
645}
646
647fn slugged_git_ref<F>(lookup: &F) -> Option<String>
648where
649    F: Fn(&str) -> Option<String>,
650{
651    [
652        "GITHUB_REF_POINT_SLUG_URL",
653        "GITHUB_HEAD_REF_SLUG_URL",
654        "GITHUB_REF_NAME_SLUG_URL",
655    ]
656    .into_iter()
657    .find_map(|key| lookup_value(lookup, key))
658}
659
660fn context_map(values: &BTreeMap<&'static str, String>) -> Map<String, Value> {
661    values
662        .iter()
663        .map(|(key, value)| (key.to_string(), Value::String(value.clone())))
664        .collect()
665}
666
667fn release_name() -> String {
668    release_name_from(&env_var)
669}
670
671fn release_name_from<F>(lookup: &F) -> String
672where
673    F: Fn(&str) -> Option<String>,
674{
675    lookup_value(lookup, "SENTRY_RELEASE").unwrap_or_else(|| build_version().to_string())
676}
677
678#[cfg(test)]
679mod tests {
680    use std::{
681        collections::{BTreeMap, HashMap},
682        panic,
683        sync::{Arc, Mutex},
684        time::{Duration, SystemTime},
685    };
686
687    use sentry::{
688        protocol::{
689            Context, EnvelopeItem, Event, Frame, ItemContainer, Log, LogAttribute, LogLevel, Map,
690            Metric, MetricType, SessionStatus, Stacktrace, Unit, Value,
691        },
692        test::{with_captured_envelopes_options, with_captured_events_options},
693        Client, ClientOptions, Hub, Scope,
694    };
695    use tracing_subscriber::{layer::SubscriberExt, Registry};
696    use zebra_chain::{
697        block::Height,
698        parameters::{Network, NetworkUpgrade},
699    };
700
701    use crate::{
702        application::build_version,
703        components::metrics::sentry_policy::{SentryPolicy, TRANSPORT_QUEUE_ENVELOPES},
704    };
705
706    use super::{
707        add_chain_tags, add_metric_attributes, chain_log_attributes, end_session, is_zebra_source,
708        merge_log_attributes, metrics_adapter, panic_event_from, release_name_from, rotate_session,
709        start_run_sessions, tracing_layer, without_panic_handling_frames, ChainPosition, Metadata,
710    };
711
712    /// Returns the metrics that Sentry receives while `send` runs with a client built from
713    /// `metadata`.
714    fn sent_metrics(metadata: &Metadata, send: impl FnOnce()) -> Vec<Metric> {
715        with_captured_envelopes_options(
716            send,
717            metadata.client_options_with_release("zebrad@test".to_string()),
718        )
719        .iter()
720        .flat_map(|envelope| envelope.items())
721        .filter_map(|item| match item {
722            EnvelopeItem::ItemContainer(ItemContainer::Metrics(metrics)) => Some(metrics),
723            _ => None,
724        })
725        .flatten()
726        .cloned()
727        .collect()
728    }
729
730    fn metric_attribute<'a>(metric: &'a Metric, key: &str) -> Option<&'a Value> {
731        metric.attributes.get(key).map(|attribute| &attribute.0)
732    }
733
734    fn tracing_layer_installed_with(client: Option<Client>) -> bool {
735        let hub = Hub::new(client.map(Arc::new), Arc::new(Scope::default()));
736        Hub::run(Arc::new(hub), || tracing_layer::<Registry>().is_some())
737    }
738
739    #[test]
740    fn tracing_layer_requires_a_client() {
741        assert!(!tracing_layer_installed_with(None));
742    }
743
744    #[test]
745    fn tracing_layer_requires_an_enabled_client() {
746        let disabled = Client::from(ClientOptions::default());
747
748        assert!(!tracing_layer_installed_with(Some(disabled)));
749    }
750
751    #[test]
752    fn tracing_layer_is_installed_with_an_enabled_client() {
753        let enabled = Client::from(sentry::apply_defaults(
754            ClientOptions::new().dsn("https://[email protected]/1"),
755        ));
756
757        assert!(tracing_layer_installed_with(Some(enabled)));
758    }
759
760    #[test]
761    fn tracing_layer_creates_no_sentry_spans() {
762        let enabled = Client::from(sentry::apply_defaults(
763            ClientOptions::new().dsn("https://[email protected]/1"),
764        ));
765        let hub = Hub::new(Some(Arc::new(enabled)), Arc::new(Scope::default()));
766
767        Hub::run(Arc::new(hub), || {
768            let layer = tracing_layer().expect("an enabled client installs the layer");
769            let subscriber = Registry::default().with(layer);
770
771            tracing::subscriber::with_default(subscriber, || {
772                let _span = tracing::info_span!("work").entered();
773
774                assert!(Hub::current()
775                    .configure_scope(|scope| scope.get_span())
776                    .is_none());
777            });
778        });
779    }
780
781    #[test]
782    fn metadata_ignores_empty_values() {
783        let env = HashMap::from([
784            ("SENTRY_ENVIRONMENT", "".to_string()),
785            ("CI_TEST_ID", "   ".to_string()),
786        ]);
787        let metadata = Metadata::from_lookup(|key| env.get(key).cloned());
788
789        assert_eq!(metadata.environment(), None);
790        assert_eq!(metadata.tags.get("test.id"), None);
791        assert!(metadata.ci_context.is_empty());
792    }
793
794    #[test]
795    fn metadata_reads_expected_tags_and_ci_context() {
796        let env = HashMap::from([
797            ("SENTRY_ENVIRONMENT", "stage".to_string()),
798            ("GITHUB_ACTIONS", "true".to_string()),
799            ("GITHUB_EVENT_NAME", "push".to_string()),
800            ("GITHUB_REF_POINT_SLUG_URL", "main".to_string()),
801            ("GITHUB_SHA", "deadbeef".to_string()),
802            ("GITHUB_RUN_ID", "42".to_string()),
803            ("GITHUB_RUN_ATTEMPT", "2".to_string()),
804            ("GITHUB_WORKFLOW", "CI".to_string()),
805            ("GITHUB_JOB", "deploy".to_string()),
806            ("CI_TEST_ID", "sync-full-mainnet".to_string()),
807        ]);
808        let metadata = Metadata::from_lookup(|key| env.get(key).cloned());
809
810        assert_eq!(metadata.environment(), Some("stage"));
811        assert_eq!(
812            metadata.tags.get("deploy.trigger").map(String::as_str),
813            Some("push"),
814        );
815        assert_eq!(
816            metadata.tags.get("git.ref").map(String::as_str),
817            Some("main"),
818        );
819        assert_eq!(
820            metadata.tags.get("git.sha").map(String::as_str),
821            Some("deadbeef"),
822        );
823        assert_eq!(
824            metadata.tags.get("ci.provider").map(String::as_str),
825            Some("github-actions"),
826        );
827        assert_eq!(
828            metadata.tags.get("test.id").map(String::as_str),
829            Some("sync-full-mainnet"),
830        );
831        assert_eq!(
832            metadata.ci_context.get("run_id").map(String::as_str),
833            Some("42"),
834        );
835        assert_eq!(
836            metadata.ci_context.get("run_attempt").map(String::as_str),
837            Some("2"),
838        );
839        assert_eq!(
840            metadata.ci_context.get("workflow").map(String::as_str),
841            Some("CI"),
842        );
843        assert_eq!(
844            metadata.ci_context.get("job").map(String::as_str),
845            Some("deploy"),
846        );
847    }
848
849    #[test]
850    fn metadata_reads_pull_request_number_from_ci_input() {
851        let env = HashMap::from([
852            ("GITHUB_ACTIONS", "true".to_string()),
853            ("GITHUB_REF_POINT_SLUG_URL", "fix-sentry-tags".to_string()),
854            ("CI_PR_NUMBER", "84".to_string()),
855        ]);
856        let metadata = Metadata::from_lookup(|key| env.get(key).cloned());
857
858        assert_eq!(
859            metadata.tags.get("git.ref").map(String::as_str),
860            Some("fix-sentry-tags"),
861        );
862        assert_eq!(
863            metadata.tags.get("pr.number").map(String::as_str),
864            Some("84"),
865        );
866    }
867
868    #[test]
869    fn metadata_prefers_slugged_git_ref_when_available() {
870        let env = HashMap::from([
871            (
872                "GITHUB_REF_POINT_SLUG_URL",
873                "feature-use-sentry".to_string(),
874            ),
875            (
876                "GITHUB_HEAD_REF_SLUG_URL",
877                "feature-use-plus-sentry".to_string(),
878            ),
879            ("GITHUB_REF_NAME_SLUG_URL", "84-merge".to_string()),
880        ]);
881        let metadata = Metadata::from_lookup(|key| env.get(key).cloned());
882
883        assert_eq!(
884            metadata.tags.get("git.ref").map(String::as_str),
885            Some("feature-use-sentry"),
886        );
887    }
888
889    #[test]
890    fn metadata_ignores_missing_slugged_git_ref() {
891        let env = HashMap::from([
892            ("GITHUB_ACTIONS", "true".to_string()),
893            ("GITHUB_EVENT_NAME", "push".to_string()),
894        ]);
895        let metadata = Metadata::from_lookup(|key| env.get(key).cloned());
896
897        assert_eq!(metadata.tags.get("git.ref"), None);
898    }
899
900    #[test]
901    fn release_name_prefers_sentry_release_override() {
902        let env = HashMap::from([("SENTRY_RELEASE", "[email protected]".to_string())]);
903
904        let release = release_name_from(&|key| env.get(key).cloned());
905
906        assert_eq!(release, "[email protected]");
907    }
908
909    #[test]
910    fn release_name_defaults_to_build_version() {
911        let env: HashMap<&str, String> = HashMap::new();
912
913        let release = release_name_from(&|key| env.get(key).cloned());
914
915        assert_eq!(release, build_version().to_string());
916    }
917
918    #[test]
919    fn client_options_leave_sessions_to_zebra_and_roundtrip_environment() {
920        let env = HashMap::from([("SENTRY_ENVIRONMENT", "stage".to_string())]);
921        let metadata = Metadata::from_lookup(|key| env.get(key).cloned());
922
923        let options = metadata.client_options_with_release("zebrad@test".to_string());
924
925        assert!(!options.auto_session_tracking);
926        assert_eq!(options.environment.as_deref(), Some("stage"));
927        assert_eq!(options.release.as_deref(), Some("zebrad@test"));
928        assert_eq!(
929            options.transport_channel_capacity.map(usize::from),
930            Some(TRANSPORT_QUEUE_ENVELOPES),
931            "the metrics flush budget leaves room in this queue",
932        );
933        assert!(
934            options.transport.is_some(),
935            "metrics flushes check the transport the client sends through",
936        );
937    }
938
939    #[test]
940    fn client_options_omits_environment_when_unset() {
941        let metadata = Metadata::from_lookup(|_: &str| -> Option<String> { None });
942
943        let options = metadata.client_options_with_release("zebrad@test".to_string());
944
945        assert!(options.environment.is_none());
946    }
947
948    #[test]
949    fn log_attributes_include_tags_and_ci_context() {
950        let env = HashMap::from([
951            ("GITHUB_ACTIONS", "true".to_string()),
952            ("GITHUB_EVENT_NAME", "push".to_string()),
953            ("GITHUB_SHA", "deadbeef".to_string()),
954            ("GITHUB_REF_POINT_SLUG_URL", "main".to_string()),
955            ("GITHUB_RUN_ID", "42".to_string()),
956            ("GITHUB_RUN_ATTEMPT", "2".to_string()),
957            ("GITHUB_WORKFLOW", "CI".to_string()),
958            ("GITHUB_JOB", "deploy".to_string()),
959            ("CI_TEST_ID", "sync-full-mainnet".to_string()),
960            ("CI_PR_NUMBER", "84".to_string()),
961        ]);
962        let metadata = Metadata::from_lookup(|key| env.get(key).cloned());
963
964        let attrs: BTreeMap<String, LogAttribute> = metadata.log_attributes().into_iter().collect();
965
966        let expect = |key: &str, value: &str| {
967            assert_eq!(
968                attrs.get(key).and_then(|attr| attr.0.as_str()),
969                Some(value),
970                "missing or wrong log attribute {key}",
971            );
972        };
973
974        expect("test.id", "sync-full-mainnet");
975        expect("git.sha", "deadbeef");
976        expect("git.ref", "main");
977        expect("ci.provider", "github-actions");
978        expect("pr.number", "84");
979        expect("deploy.trigger", "push");
980        expect("ci.run_id", "42");
981        expect("ci.run_attempt", "2");
982        expect("ci.workflow", "CI");
983        expect("ci.job", "deploy");
984    }
985
986    #[test]
987    fn merge_log_attributes_preserves_existing() {
988        let mut log = Log {
989            level: LogLevel::Info,
990            body: "test".to_string(),
991            trace_id: None,
992            timestamp: SystemTime::UNIX_EPOCH,
993            severity_number: None,
994            attributes: BTreeMap::new(),
995        };
996
997        log.attributes.insert(
998            "git.sha".to_string(),
999            LogAttribute::from("event-sha".to_string()),
1000        );
1001
1002        let attrs = vec![
1003            (
1004                "git.sha".to_string(),
1005                LogAttribute::from("metadata-sha".to_string()),
1006            ),
1007            (
1008                "ci.run_id".to_string(),
1009                LogAttribute::from("42".to_string()),
1010            ),
1011        ];
1012
1013        merge_log_attributes(&mut log, &attrs);
1014
1015        assert_eq!(
1016            log.attributes
1017                .get("git.sha")
1018                .and_then(|attr| attr.0.as_str()),
1019            Some("event-sha"),
1020            "pre-existing attribute must not be overwritten",
1021        );
1022        assert_eq!(
1023            log.attributes
1024                .get("ci.run_id")
1025                .and_then(|attr| attr.0.as_str()),
1026            Some("42"),
1027            "new attribute must be inserted",
1028        );
1029    }
1030
1031    /// Returns the chain position at `tip_height` on Mainnet.
1032    fn chain_position(tip_height: u32, near_tip: bool) -> ChainPosition {
1033        let tip_height = Height(tip_height);
1034        ChainPosition {
1035            tip_height,
1036            network_upgrade: NetworkUpgrade::current(&Network::Mainnet, tip_height),
1037            near_tip,
1038        }
1039    }
1040
1041    #[test]
1042    fn chain_tags_keep_existing_event_tags() {
1043        let mut event = Event::default();
1044        event
1045            .tags
1046            .insert("chain.height".to_owned(), "event-height".to_owned());
1047
1048        add_chain_tags(&mut event, Some(chain_position(3_543_405, true)));
1049
1050        assert_eq!(
1051            event.tags.get("chain.height").map(String::as_str),
1052            Some("event-height"),
1053        );
1054        assert_eq!(
1055            event.tags.get("chain.network_upgrade").map(String::as_str),
1056            Some("Nu7"),
1057        );
1058    }
1059
1060    #[test]
1061    fn chain_tags_are_omitted_before_the_tip_is_known() {
1062        let mut event = Event::default();
1063
1064        add_chain_tags(&mut event, None);
1065
1066        assert!(event.tags.is_empty());
1067        assert!(chain_log_attributes(None).is_empty());
1068    }
1069
1070    #[test]
1071    fn chain_log_attributes_report_height_as_a_number() {
1072        let attrs: BTreeMap<String, LogAttribute> =
1073            chain_log_attributes(Some(chain_position(3_543_405, true)))
1074                .into_iter()
1075                .collect();
1076
1077        assert_eq!(
1078            attrs.get("chain.height").and_then(|attr| attr.0.as_u64()),
1079            Some(3_543_405),
1080        );
1081        assert_eq!(
1082            attrs
1083                .get("chain.network_upgrade")
1084                .and_then(|attr| attr.0.as_str()),
1085            Some("Nu7"),
1086        );
1087    }
1088
1089    #[test]
1090    fn tip_block_delays_are_sent_with_their_block_height() {
1091        let metadata = Metadata::from_lookup(|_: &str| -> Option<String> { None });
1092
1093        // The Mainnet NU7 activation block, which the tip height read by other metrics often
1094        // hasn't reached yet.
1095        let height = Height(3_543_405);
1096
1097        let metrics = sent_metrics(&metadata, || {
1098            super::tip_block_delay(Some(&Network::Mainnet), height, 2.0).capture();
1099        });
1100
1101        let [metric] = metrics.as_slice() else {
1102            panic!("expected one tip block delay, got {metrics:?}");
1103        };
1104        assert_eq!(metric.name, "zcash.chain.tip.block_delay_seconds");
1105        assert_eq!(metric.r#type, MetricType::Distribution);
1106        assert_eq!(metric.value, 2.0);
1107        assert_eq!(metric.unit, Some(Unit::Second));
1108        assert_eq!(
1109            metric_attribute(metric, "chain.height").and_then(Value::as_u64),
1110            Some(3_543_405),
1111        );
1112        assert_eq!(
1113            metric_attribute(metric, "chain.network_upgrade").and_then(Value::as_str),
1114            Some("Nu7"),
1115        );
1116    }
1117
1118    #[test]
1119    fn metrics_are_sent_with_their_unit_and_labels() {
1120        let mut metadata = Metadata::from_lookup(|_: &str| -> Option<String> { None });
1121        metadata.tags.insert("chain.network", "Mainnet".to_owned());
1122        let policy = SentryPolicy::default();
1123
1124        metrics::with_local_recorder(&policy, || {
1125            crate::components::metrics::describe_all();
1126
1127            metrics::histogram!("sync.stage.duration_seconds", "stage" => "obtain_tips")
1128                .record(2.0);
1129            // Sent directly with its block height, so the policy skips it.
1130            metrics::histogram!(
1131                "zcash.chain.tip.block_delay_seconds",
1132                "chain.network_upgrade" => "Nu7",
1133            )
1134            .record(2.0);
1135            metrics::counter!("sync.block.error.count", "kind" => "not_found").increment(3);
1136            metrics::gauge!("zebra.state.rocksdb.total_disk_size_bytes").set(1024.0);
1137        });
1138        let metrics = sent_metrics(&metadata, || policy.flush(metrics_adapter::send));
1139
1140        let sent = |name: &str| {
1141            metrics
1142                .iter()
1143                .find(|metric| metric.name == name)
1144                .unwrap_or_else(|| panic!("{name} is sent: {metrics:?}"))
1145        };
1146
1147        let stage = sent("sync.stage.duration_seconds");
1148        assert_eq!(stage.r#type, MetricType::Distribution);
1149        assert_eq!(stage.value, 2.0);
1150        assert_eq!(stage.unit, Some(Unit::Second));
1151        assert_eq!(
1152            metric_attribute(stage, "stage").and_then(Value::as_str),
1153            Some("obtain_tips"),
1154        );
1155        assert_eq!(
1156            metric_attribute(stage, "chain.network").and_then(Value::as_str),
1157            Some("Mainnet"),
1158        );
1159        assert!(
1160            metrics
1161                .iter()
1162                .all(|metric| metric.name != "zcash.chain.tip.block_delay_seconds"),
1163            "the policy doesn't send the tip block delay a second time",
1164        );
1165
1166        let errors = sent("sync.block.error.count");
1167        assert_eq!(errors.r#type, MetricType::Counter);
1168        assert_eq!(errors.value, 3.0);
1169        assert_eq!(
1170            metric_attribute(errors, "kind").and_then(Value::as_str),
1171            Some("not_found"),
1172        );
1173
1174        let disk_size = sent("zebra.state.rocksdb.total_disk_size_bytes");
1175        assert_eq!(disk_size.r#type, MetricType::Gauge);
1176        assert_eq!(disk_size.value, 1024.0);
1177        assert_eq!(disk_size.unit, Some(Unit::Byte));
1178    }
1179
1180    #[test]
1181    fn metric_attributes_are_added_once_known_and_keep_existing_ones() {
1182        let mut attributes = Map::new();
1183        add_metric_attributes(&mut attributes, None, None, Duration::ZERO);
1184        assert_eq!(
1185            attributes.keys().collect::<Vec<_>>(),
1186            ["process.uptime_seconds"],
1187        );
1188
1189        let mut attributes = Map::new();
1190        attributes.insert("chain.network_upgrade".into(), "metric-upgrade".into());
1191        add_metric_attributes(
1192            &mut attributes,
1193            Some("Mainnet"),
1194            Some(chain_position(3_543_405, true)),
1195            Duration::from_millis(90_500),
1196        );
1197        let attribute = |key: &str| attributes.get(key).map(|attr| &attr.0);
1198
1199        assert_eq!(
1200            attribute("chain.network").and_then(|value| value.as_str()),
1201            Some("Mainnet"),
1202        );
1203        assert_eq!(
1204            attribute("chain.network_upgrade").and_then(|value| value.as_str()),
1205            Some("metric-upgrade"),
1206        );
1207        assert_eq!(
1208            attribute("process.uptime_seconds").and_then(|value| value.as_u64()),
1209            Some(90),
1210        );
1211    }
1212
1213    #[test]
1214    fn metrics_say_whether_the_node_was_near_the_tip() {
1215        for near_tip in [false, true] {
1216            let mut attributes = Map::new();
1217            add_metric_attributes(
1218                &mut attributes,
1219                None,
1220                Some(chain_position(3_000_000, near_tip)),
1221                Duration::ZERO,
1222            );
1223
1224            assert_eq!(
1225                attributes
1226                    .get("chain.near_tip")
1227                    .and_then(|attr| attr.0.as_bool()),
1228                Some(near_tip),
1229            );
1230        }
1231    }
1232
1233    #[test]
1234    fn memory_metrics_are_sent_with_their_units() {
1235        let metadata = Metadata::from_lookup(|_: &str| -> Option<String> { None });
1236
1237        let policy = metrics_adapter::start().expect("the test can start the flush thread");
1238
1239        let metrics = sent_metrics(&metadata, || {
1240            metrics::with_local_recorder(policy, || {
1241                crate::components::metrics::describe_all();
1242                metrics::gauge!("state.memory.index.entries").set(2_000_000.0);
1243                metrics::gauge!("state.memory.backup.restore.duration_seconds").set(25.0);
1244                metrics::counter!("state.memory.fork.evicted.count").increment(2);
1245                // Recorded directly, so its unit is checked on every platform.
1246                metrics::gauge!("process.memory.rss_fraction").set(0.5);
1247                crate::components::metrics::record();
1248            });
1249
1250            super::end(SessionStatus::Crashed);
1251        });
1252
1253        let mut metrics: Vec<_> = metrics
1254            .iter()
1255            .map(|metric| (metric.name.to_string(), metric.r#type, metric.unit.clone()))
1256            .collect();
1257        metrics.sort_by(|a, b| a.0.cmp(&b.0));
1258
1259        let mut expected = vec![
1260            (
1261                "state.memory.backup.restore.duration_seconds".to_string(),
1262                MetricType::Gauge,
1263                Some(Unit::Second),
1264            ),
1265            (
1266                "state.memory.fork.evicted.count".to_string(),
1267                MetricType::Counter,
1268                None,
1269            ),
1270            (
1271                "state.memory.index.entries".to_string(),
1272                MetricType::Gauge,
1273                None,
1274            ),
1275            (
1276                "process.memory.rss_fraction".to_string(),
1277                MetricType::Gauge,
1278                Some(Unit::Ratio),
1279            ),
1280        ];
1281        if cfg!(target_os = "linux") {
1282            expected.push((
1283                "process.memory.rss_bytes".to_string(),
1284                MetricType::Gauge,
1285                Some(Unit::Byte),
1286            ));
1287        }
1288        expected.sort_by(|a, b| a.0.cmp(&b.0));
1289        assert_eq!(metrics, expected);
1290    }
1291
1292    #[test]
1293    fn counts_since_the_last_flush_are_sent_at_shutdown() {
1294        let metadata = Metadata::from_lookup(|_: &str| -> Option<String> { None });
1295
1296        let policy = metrics_adapter::start().expect("the test can start the flush thread");
1297
1298        let metrics = sent_metrics(&metadata, || {
1299            metrics::with_local_recorder(policy, || {
1300                metrics::counter!("sync.restart.count", "reason" => "sync_step_timeout")
1301                    .increment(1);
1302            });
1303
1304            super::end(SessionStatus::Crashed);
1305        });
1306
1307        let [metric] = metrics.as_slice() else {
1308            panic!("expected the restart count, got {metrics:?}");
1309        };
1310
1311        assert_eq!(metric.name, "sync.restart.count");
1312        assert_eq!(metric.value, 1.0);
1313    }
1314
1315    #[test]
1316    fn errors_from_any_hub_count_toward_the_session_in_progress() {
1317        let metadata = Metadata::from_lookup(|_: &str| -> Option<String> { None });
1318
1319        let envelopes = with_captured_envelopes_options(
1320            || {
1321                start_run_sessions();
1322                // Hubs on other threads are copied once, before any later session starts.
1323                let earlier_hub = Hub::new_from_top(Hub::current());
1324
1325                rotate_session();
1326                earlier_hub.capture_event(Event {
1327                    level: sentry::Level::Error,
1328                    ..Default::default()
1329                });
1330                end_session(SessionStatus::Crashed);
1331            },
1332            metadata.client_options_with_release("zebrad@test".to_string()),
1333        );
1334
1335        let sessions: Vec<_> = envelopes
1336            .iter()
1337            .flat_map(|envelope| envelope.items())
1338            .filter_map(|item| match item {
1339                EnvelopeItem::SessionUpdate(session) => Some(session),
1340                _ => None,
1341            })
1342            .collect();
1343
1344        let summary: Vec<_> = sessions
1345            .iter()
1346            .map(|session| (session.init, session.status, session.errors))
1347            .collect();
1348        assert_eq!(
1349            summary,
1350            [
1351                (true, SessionStatus::Ok, 0),
1352                (false, SessionStatus::Exited, 0),
1353                (true, SessionStatus::Ok, 0),
1354                (false, SessionStatus::Crashed, 1),
1355            ],
1356        );
1357        assert_eq!(sessions[0].session_id, sessions[1].session_id);
1358        assert_eq!(sessions[2].session_id, sessions[3].session_id);
1359        assert_ne!(sessions[0].session_id, sessions[2].session_id);
1360        assert!(
1361            sessions.iter().all(|session| session.distinct_id.is_some()
1362                && session.distinct_id == sessions[0].distinct_id),
1363            "every session of a run reports the run ID",
1364        );
1365    }
1366
1367    #[test]
1368    fn panic_events_use_the_panic_message_and_stack() {
1369        static EVENT: Mutex<Option<Event<'static>>> = Mutex::new(None);
1370
1371        let previous_hook = panic::take_hook();
1372        panic::set_hook(Box::new(|panic_info| {
1373            *EVENT.lock().expect("only this hook locks it") =
1374                Some(panic_event_from(panic_info, "full panic report"));
1375        }));
1376        let result = panic::catch_unwind(|| panic!("listener failed"));
1377        panic::set_hook(previous_hook);
1378        assert!(result.is_err());
1379
1380        let event = EVENT
1381            .lock()
1382            .expect("the hook has returned")
1383            .take()
1384            .expect("the hook captured the panic");
1385        let exception = &event.exception.values[0];
1386
1387        assert_eq!(exception.value.as_deref(), Some("listener failed"));
1388        assert_eq!(
1389            exception.mechanism.as_ref().and_then(|m| m.handled),
1390            Some(false)
1391        );
1392        // Optimized builds can inline the panicking closure and shorten function names, so check
1393        // that no frame that handles the panic remains, rather than naming the newest frame. Older
1394        // frames, such as the test's own `catch_unwind`, are expected to remain.
1395        let frames = &exception
1396            .stacktrace
1397            .as_ref()
1398            .expect("panic events carry a stack trace")
1399            .frames;
1400        let panic_handling = [
1401            "current_stacktrace",
1402            "panic_event_from",
1403            "rust_begin_unwind",
1404            "begin_panic_handler",
1405            "rust_panic_with_hook",
1406            "panic_with_hook",
1407            "panic_fmt",
1408        ];
1409        assert!(!frames.is_empty(), "the stack keeps the code that panicked");
1410        for function in frames.iter().filter_map(|frame| frame.function.as_deref()) {
1411            assert!(
1412                !panic_handling.iter().any(|name| function.contains(name)),
1413                "the stack ends at the code that panicked, without the panic handling: {function}",
1414            );
1415        }
1416
1417        let Some(Context::Other(panic_context)) = event.contexts.get("panic") else {
1418            panic!("panic events carry the panic report");
1419        };
1420        assert_eq!(
1421            panic_context
1422                .get("report")
1423                .and_then(|report| report.as_str()),
1424            Some("full panic report"),
1425        );
1426        assert!(panic_context
1427            .get("location")
1428            .and_then(|location| location.as_str())
1429            .is_some_and(|location| location.contains("sentry.rs")));
1430    }
1431
1432    #[test]
1433    fn panic_stacks_end_at_the_code_that_panicked() {
1434        let frame = |function: &str| Frame {
1435            function: Some(function.to_owned()),
1436            ..Default::default()
1437        };
1438        // Oldest first, as Sentry orders frames.
1439        let stacktrace = Stacktrace {
1440            frames: vec![
1441                frame("std::rt::lang_start"),
1442                frame("std::panicking::catch_unwind"),
1443                frame("zebrad::components::start"),
1444                frame("zebra_network::open_listener"),
1445                frame("core::panicking::panic_fmt"),
1446                frame("__rustc::rust_begin_unwind"),
1447                frame("std::panicking::panic_with_hook"),
1448                frame("zebrad::application::panic_hook"),
1449                frame("zebrad::sentry::panic_event_from"),
1450            ],
1451            ..Default::default()
1452        };
1453
1454        let functions: Vec<_> = without_panic_handling_frames(stacktrace)
1455            .frames
1456            .into_iter()
1457            .filter_map(|frame| frame.function)
1458            .collect();
1459
1460        assert_eq!(
1461            functions,
1462            [
1463                "std::rt::lang_start",
1464                "std::panicking::catch_unwind",
1465                "zebrad::components::start",
1466                "zebra_network::open_listener",
1467            ],
1468        );
1469    }
1470
1471    /// Returns the frames Sentry uses for suspect commits: the exception stack traces, or the
1472    /// current thread's stack trace when no exception has one.
1473    fn suspect_commit_stacktrace<'a>(event: &'a Event<'static>) -> Option<&'a Stacktrace> {
1474        event
1475            .exception
1476            .iter()
1477            .find_map(|exception| exception.stacktrace.as_ref())
1478            .or_else(|| {
1479                event
1480                    .threads
1481                    .iter()
1482                    .find(|thread| thread.current)
1483                    .and_then(|thread| thread.stacktrace.as_ref())
1484            })
1485    }
1486
1487    #[test]
1488    fn error_events_carry_in_app_frames_for_suspect_commits() {
1489        let metadata = Metadata::default();
1490
1491        let events = with_captured_events_options(
1492            || {
1493                let layer = tracing_layer().expect("the test client is enabled");
1494                let subscriber = Registry::default().with(layer);
1495
1496                tracing::subscriber::with_default(subscriber, || {
1497                    tracing::error!("block commit failed");
1498
1499                    let error = std::io::Error::other("disk full");
1500                    tracing::error!(
1501                        error = &error as &dyn std::error::Error,
1502                        "block commit failed"
1503                    );
1504                });
1505            },
1506            // `sentry::init` adds the default integrations, which capture and classify stacks.
1507            sentry::apply_defaults(metadata.client_options_with_release("zebrad@test".to_string())),
1508        );
1509
1510        assert_eq!(events.len(), 2, "both ERROR events are sent: {events:?}");
1511
1512        for event in &events {
1513            let frames = &suspect_commit_stacktrace(event)
1514                .expect("ERROR events carry a stack trace")
1515                .frames;
1516            let in_app_frames: Vec<_> = frames
1517                .iter()
1518                .filter(|frame| frame.in_app == Some(true))
1519                .collect();
1520
1521            assert!(
1522                in_app_frames.iter().any(|frame| frame
1523                    .abs_path
1524                    .as_deref()
1525                    .is_some_and(|path| path.ends_with("zebrad/src/sentry.rs"))),
1526                "the code that logged the error is an in-app frame with its source path: {frames:?}",
1527            );
1528            assert!(
1529                in_app_frames.iter().all(|frame| frame
1530                    .abs_path
1531                    .as_deref()
1532                    .is_some_and(|path| path.contains("zebrad/src/"))),
1533                "dependency frames are not in-app: {in_app_frames:?}",
1534            );
1535        }
1536    }
1537
1538    #[test]
1539    fn zebra_sources_are_recognized_in_checkouts_and_the_registry() {
1540        for zebra_path in [
1541            "/zebra/zebrad/src/components/sync.rs",
1542            "/home/user/zebra/zebra-network/src/peer_set/initialize.rs",
1543            "/root/.cargo/registry/src/index.crates.io-0000/zebra-chain-14.0.0/src/block.rs",
1544            "/zebra/tower-batch-control/src/service.rs",
1545        ] {
1546            assert!(is_zebra_source(zebra_path), "{zebra_path} is Zebra's");
1547        }
1548
1549        for other_path in [
1550            "/root/.cargo/registry/src/index.crates.io-0000/tokio-1.47.0/src/runtime/task.rs",
1551            "/rustc/f8297e351a40c1439a467bbbb6879088047f50b3/library/std/src/panicking.rs",
1552            "/zebra/zebrad/build.rs",
1553        ] {
1554            assert!(!is_zebra_source(other_path), "{other_path} is not Zebra's");
1555        }
1556    }
1557}