Skip to main content

goldrush_sdk/
tracing.rs

1use tracing::{debug, error, info, instrument, warn};
2use uuid::Uuid;
3
4/// Request correlation ID for tracing requests across the system.
5#[derive(Debug, Clone)]
6pub struct RequestId(pub String);
7
8impl RequestId {
9    /// Generate a new random request ID.
10    pub fn new() -> Self {
11        Self(Uuid::new_v4().to_string())
12    }
13    
14    /// Create a request ID from an existing string.
15    pub fn from_string<S: Into<String>>(id: S) -> Self {
16        Self(id.into())
17    }
18}
19
20impl Default for RequestId {
21    fn default() -> Self {
22        Self::new()
23    }
24}
25
26impl std::fmt::Display for RequestId {
27    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28        write!(f, "{}", self.0)
29    }
30}
31
32/// Tracing context for SDK operations.
33#[derive(Debug, Clone)]
34pub struct TracingContext {
35    pub request_id: RequestId,
36    pub operation: String,
37    pub chain_name: Option<String>,
38}
39
40impl TracingContext {
41    pub fn new<S: Into<String>>(operation: S) -> Self {
42        Self {
43            request_id: RequestId::new(),
44            operation: operation.into(),
45            chain_name: None,
46        }
47    }
48    
49    pub fn with_chain<S: Into<String>>(mut self, chain_name: S) -> Self {
50        self.chain_name = Some(chain_name.into());
51        self
52    }
53}
54
55/// Macro for creating instrumented spans with request context.
56#[macro_export]
57macro_rules! trace_request {
58    ($ctx:expr, $msg:expr) => {
59        tracing::info!(
60            request_id = %$ctx.request_id,
61            operation = %$ctx.operation,
62            chain = ?$ctx.chain_name,
63            $msg
64        )
65    };
66    ($ctx:expr, $msg:expr, $($field:tt)*) => {
67        tracing::info!(
68            request_id = %$ctx.request_id,
69            operation = %$ctx.operation,
70            chain = ?$ctx.chain_name,
71            $msg,
72            $($field)*
73        )
74    };
75}
76
77/// Macro for error logging with context.
78#[macro_export]
79macro_rules! trace_error {
80    ($ctx:expr, $err:expr, $msg:expr) => {
81        tracing::error!(
82            request_id = %$ctx.request_id,
83            operation = %$ctx.operation,
84            chain = ?$ctx.chain_name,
85            error = %$err,
86            $msg
87        )
88    };
89}
90
91/// Instrument a function with tracing context.
92pub fn instrument_request<F, T>(ctx: &TracingContext, f: F) -> T
93where
94    F: FnOnce() -> T,
95{
96    let span = tracing::info_span!(
97        "sdk_request",
98        request_id = %ctx.request_id,
99        operation = %ctx.operation,
100        chain = ?ctx.chain_name
101    );
102    
103    let _enter = span.enter();
104    f()
105}