ibc_telemetry/
lib.rs

1pub mod broadcast_error;
2pub mod encoder;
3mod path_identifier;
4pub mod server;
5pub mod state;
6
7use std::error::Error;
8use std::net::{SocketAddr, ToSocketAddrs};
9use std::ops::Range;
10use std::sync::Arc;
11
12use once_cell::sync::OnceCell;
13use tokio::task::JoinHandle;
14use tracing::{debug, warn};
15
16pub use crate::state::TelemetryState;
17
18pub fn new_state(
19    tx_latency_submitted_range: Range<u64>,
20    tx_latency_submitted_buckets: u64,
21    tx_latency_confirmed_range: Range<u64>,
22    tx_latency_confirmed_buckets: u64,
23    namespace: &str,
24) -> Arc<TelemetryState> {
25    Arc::new(TelemetryState::new(
26        tx_latency_submitted_range,
27        tx_latency_submitted_buckets,
28        tx_latency_confirmed_range,
29        tx_latency_confirmed_buckets,
30        namespace,
31    ))
32}
33
34static GLOBAL_STATE: OnceCell<Arc<TelemetryState>> = OnceCell::new();
35
36pub fn init(
37    tx_latency_submitted_range: Range<u64>,
38    tx_latency_submitted_buckets: u64,
39    tx_latency_confirmed_range: Range<u64>,
40    tx_latency_confirmed_buckets: u64,
41    namespace: &str,
42) -> &'static Arc<TelemetryState> {
43    let new_state = new_state(
44        tx_latency_submitted_range,
45        tx_latency_submitted_buckets,
46        tx_latency_confirmed_range,
47        tx_latency_confirmed_buckets,
48        namespace,
49    );
50    match GLOBAL_STATE.set(new_state) {
51        Ok(_) => debug!("initialised telemetry global state"),
52        Err(_) => debug!("telemetry global state was already set"),
53    }
54    GLOBAL_STATE.get().unwrap()
55}
56
57pub fn global() -> &'static Arc<TelemetryState> {
58    match GLOBAL_STATE.get() {
59        Some(state) => state,
60        None => {
61            warn!(
62                "global telemetry state not set, will initialize it using default histogram ranges"
63            );
64            init(
65                Range {
66                    start: 500,
67                    end: 10000,
68                },
69                10,
70                Range {
71                    start: 1000,
72                    end: 20000,
73                },
74                10,
75                "",
76            )
77        }
78    }
79}
80
81pub type BoxError = Box<dyn Error + Send + Sync>;
82
83pub fn spawn<A>(
84    addr: A,
85    state: Arc<TelemetryState>,
86) -> Result<(SocketAddr, JoinHandle<Result<(), BoxError>>), BoxError>
87where
88    A: ToSocketAddrs + Send + 'static,
89{
90    let addr = addr.to_socket_addrs()?.next().unwrap();
91    let handle = tokio::spawn(server::listen(addr, state));
92
93    Ok((addr, handle))
94}