viewpoint_core/context/trace/
action_handle.rs

1//! Action handle for tracking action duration in traces.
2
3use std::sync::Arc;
4use tokio::sync::RwLock;
5
6use super::types::TracingState;
7
8/// Handle for tracking an action's duration in the trace.
9pub struct ActionHandle {
10    state: Arc<RwLock<TracingState>>,
11    index: usize,
12}
13
14impl ActionHandle {
15    /// Create a new action handle.
16    pub(crate) fn new(state: Arc<RwLock<TracingState>>, index: usize) -> Self {
17        Self { state, index }
18    }
19
20    /// Complete the action with success.
21    pub async fn complete(self, result: Option<serde_json::Value>) {
22        let end_time = std::time::SystemTime::now()
23            .duration_since(std::time::UNIX_EPOCH)
24            .unwrap_or_default()
25            .as_secs_f64()
26            * 1000.0;
27
28        let mut state = self.state.write().await;
29        if let Some(action) = state.actions.get_mut(self.index) {
30            action.end_time = Some(end_time);
31            action.result = result;
32        }
33    }
34
35    /// Complete the action with an error.
36    pub async fn fail(self, error: &str) {
37        let end_time = std::time::SystemTime::now()
38            .duration_since(std::time::UNIX_EPOCH)
39            .unwrap_or_default()
40            .as_secs_f64()
41            * 1000.0;
42
43        let mut state = self.state.write().await;
44        if let Some(action) = state.actions.get_mut(self.index) {
45            action.end_time = Some(end_time);
46            action.result = Some(serde_json::json!({ "error": error }));
47        }
48    }
49}