Skip to main content

zebrad/components/metrics/
node_context.rs

1//! The node's position on the chain, which telemetry backends attach to the signals they send.
2//!
3//! The sync progress task records it in every build, whichever backends are compiled in.
4
5use std::sync::{
6    atomic::{AtomicBool, AtomicU32, Ordering},
7    OnceLock,
8};
9
10use zebra_chain::{
11    block::Height,
12    parameters::{Network, NetworkUpgrade},
13};
14
15/// The network this node runs on, once `zebrad start` or the progress task records it.
16static NETWORK: OnceLock<Network> = OnceLock::new();
17
18/// The best chain tip height, or [`UNKNOWN_TIP_HEIGHT`] until the progress task records one.
19///
20/// Backends read this instead of the chain tip watch channel, because Sentry calls `before_send`
21/// and `before_send_log` from inside tracing, where instrumented chain tip reads would re-enter the
22/// tracing layers.
23static TIP_HEIGHT: AtomicU32 = AtomicU32::new(UNKNOWN_TIP_HEIGHT);
24
25/// Above `Height::MAX`, so it is never a real height.
26const UNKNOWN_TIP_HEIGHT: u32 = u32::MAX;
27
28/// Whether the syncer was close to the chain tip when the progress task last checked.
29static NEAR_TIP: AtomicBool = AtomicBool::new(false);
30
31/// The node's position on the chain when the progress task last checked.
32#[derive(Clone, Copy, Debug, Eq, PartialEq)]
33pub(crate) struct ChainPosition {
34    /// The best chain tip height.
35    pub(crate) tip_height: Height,
36    /// The network upgrade at the tip.
37    pub(crate) network_upgrade: NetworkUpgrade,
38    /// Whether the syncer is close to the chain tip.
39    pub(crate) near_tip: bool,
40}
41
42/// Records the network this node runs on. A node only runs on one network, so later calls keep
43/// the first one.
44pub(crate) fn set_network(network: &Network) {
45    NETWORK.get_or_init(|| network.clone());
46}
47
48/// Returns the network this node runs on, once it has been recorded.
49pub(crate) fn network() -> Option<&'static Network> {
50    NETWORK.get()
51}
52
53/// Records the best chain tip height on `network`, and whether the syncer is close to the tip.
54pub(crate) fn record(network: &Network, tip_height: Height, near_tip: bool) {
55    set_network(network);
56    NEAR_TIP.store(near_tip, Ordering::Relaxed);
57    TIP_HEIGHT.store(tip_height.0, Ordering::Relaxed);
58}
59
60/// Returns the node's position on the chain, once the progress task has recorded one.
61#[cfg_attr(not(feature = "sentry"), allow(dead_code))]
62pub(crate) fn chain_position() -> Option<ChainPosition> {
63    let network = NETWORK.get()?;
64    let tip_height = TIP_HEIGHT.load(Ordering::Relaxed);
65    let tip_height = (tip_height != UNKNOWN_TIP_HEIGHT).then_some(Height(tip_height))?;
66
67    Some(ChainPosition {
68        tip_height,
69        network_upgrade: NetworkUpgrade::current(network, tip_height),
70        near_tip: NEAR_TIP.load(Ordering::Relaxed),
71    })
72}