Skip to main content

multicast_codemode/
telemetry.rs

1use multicast::telemetry::{is_enabled, opentelemetry};
2use opentelemetry::trace::{
3    Link, SpanContext, SpanId, Status, TraceContextExt, TraceFlags, TraceId, TraceState, Tracer,
4};
5use opentelemetry::{Context, KeyValue, global};
6use serde::{Deserialize, Serialize};
7use web_time::Instant;
8
9use crate::{ExecutionState, ExecutionStatus};
10
11/// Saved workflow identity attached to execution spans, never metric labels.
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13pub struct WorkflowIdentity {
14    /// Workflow's catalog name.
15    pub name: String,
16    /// Digest of the workflow program and input schema.
17    pub version: String,
18}
19
20/// Last active pass's tracing identity, safe to retain in the execution store.
21///
22/// Only trace identifiers and workflow identity are retained. Request headers,
23/// baggage, arguments, results, and credentials are not copied into this record.
24#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct ExecutionTrace {
26    /// Lowercase hexadecimal trace identifier.
27    pub trace_id: String,
28    /// Lowercase hexadecimal span identifier.
29    pub span_id: String,
30    /// W3C trace flags byte.
31    pub trace_flags: u8,
32    /// Workflow identity, when this execution was started as a named workflow.
33    pub workflow: Option<WorkflowIdentity>,
34}
35
36impl ExecutionTrace {
37    fn span_context(&self) -> Option<SpanContext> {
38        let span = SpanContext::new(
39            TraceId::from_hex(&self.trace_id).ok()?,
40            SpanId::from_hex(&self.span_id).ok()?,
41            TraceFlags::new(self.trace_flags),
42            false,
43            TraceState::default(),
44        );
45        span.is_valid().then_some(span)
46    }
47}
48
49pub(crate) struct Observation {
50    context: Context,
51    metric: &'static str,
52    started: Instant,
53    enabled: bool,
54    finished: bool,
55}
56
57impl Observation {
58    pub(crate) fn pass(state: &ExecutionState, workflow: Option<&WorkflowIdentity>) -> Self {
59        let mut attrs = vec![KeyValue::new("incurs.execution.id", state.id.clone())];
60        if let Some(workflow) = workflow {
61            attrs.push(KeyValue::new("incurs.workflow.name", workflow.name.clone()));
62            attrs.push(KeyValue::new(
63                "incurs.workflow.version",
64                workflow.version.clone(),
65            ));
66        }
67        Self::new(
68            "incurs.codemode.pass",
69            "incurs.codemode.pass.duration",
70            attrs,
71            state.trace.as_ref(),
72        )
73    }
74
75    pub(crate) fn lineage(
76        &self,
77        root: &str,
78        parent: Option<&str>,
79        definition: Option<&crate::WorkflowReference>,
80    ) {
81        let span = self.context.span();
82        span.set_attribute(KeyValue::new("incurs.workflow.root.id", root.to_string()));
83        if let Some(parent) = parent {
84            span.set_attribute(KeyValue::new(
85                "incurs.workflow.parent.id",
86                parent.to_string(),
87            ));
88        }
89        if let Some(definition) = definition {
90            span.set_attribute(KeyValue::new(
91                "incurs.workflow.definition.version",
92                definition.version.clone(),
93            ));
94        }
95    }
96
97    pub(crate) fn call(id: &str, seq: u64, connector: &str, method: &str) -> Self {
98        Self::new(
99            "incurs.codemode.call",
100            "incurs.codemode.call.duration",
101            vec![
102                KeyValue::new("incurs.execution.id", id.to_string()),
103                KeyValue::new("incurs.step.sequence", seq as i64),
104                KeyValue::new("incurs.connector.name", connector.to_string()),
105                KeyValue::new("incurs.tool.name", method.to_string()),
106            ],
107            None,
108        )
109    }
110
111    fn new(
112        name: &'static str,
113        metric: &'static str,
114        attrs: Vec<KeyValue>,
115        previous: Option<&ExecutionTrace>,
116    ) -> Self {
117        let enabled = is_enabled();
118        let parent = Context::current();
119        let context = if enabled {
120            let tracer = global::tracer("multicast-codemode");
121            let mut builder = tracer.span_builder(name).with_attributes(attrs);
122            if let Some(previous) = previous.and_then(ExecutionTrace::span_context) {
123                builder = builder.with_links(vec![Link::new(previous, Vec::new(), 0)]);
124            }
125            parent.with_span(tracer.build_with_context(builder, &parent))
126        } else {
127            parent
128        };
129        Self {
130            context,
131            metric,
132            started: Instant::now(),
133            enabled,
134            finished: false,
135        }
136    }
137
138    pub(crate) fn context(&self) -> Context {
139        self.context.clone()
140    }
141
142    pub(crate) fn trace(&self, workflow: Option<WorkflowIdentity>) -> Option<ExecutionTrace> {
143        let span = self.context.span();
144        let sc = span.span_context();
145        (self.enabled && sc.is_valid()).then(|| ExecutionTrace {
146            trace_id: sc.trace_id().to_string(),
147            span_id: sc.span_id().to_string(),
148            trace_flags: sc.trace_flags().to_u8(),
149            workflow,
150        })
151    }
152
153    pub(crate) fn finish(&mut self, outcome: &'static str) {
154        self.finish_after(outcome, self.started.elapsed().as_secs_f64());
155    }
156
157    fn finish_after(&mut self, outcome: &'static str, seconds: f64) {
158        if self.finished {
159            return;
160        }
161        self.finished = true;
162        if !self.enabled {
163            return;
164        }
165        let attrs = vec![KeyValue::new("incurs.outcome", outcome)];
166        let span = self.context.span();
167        span.set_attribute(attrs[0].clone());
168        if outcome == "error" {
169            span.set_status(Status::error("execution_error"));
170        }
171        global::meter("multicast-codemode")
172            .f64_histogram(self.metric)
173            .with_unit("s")
174            .build()
175            .record(seconds, &attrs);
176        span.end();
177    }
178}
179
180impl Drop for Observation {
181    fn drop(&mut self) {
182        self.finish("cancelled");
183    }
184}
185
186pub(crate) fn outcome(status: ExecutionStatus) -> &'static str {
187    match status {
188        ExecutionStatus::Running => "running",
189        ExecutionStatus::Paused => "paused",
190        ExecutionStatus::Completed => "completed",
191        ExecutionStatus::Error => "error",
192        ExecutionStatus::Rejected => "rejected",
193        ExecutionStatus::Cancelled => "cancelled",
194        ExecutionStatus::RolledBack => "rolled_back",
195    }
196}
197
198pub(crate) fn approval(state: &ExecutionState, now: u64, decision: &'static str) {
199    if state.status != ExecutionStatus::Paused
200        || !state
201            .log
202            .iter()
203            .any(|entry| entry.state == crate::LogEntryState::Pending)
204        || !is_enabled()
205    {
206        return;
207    }
208    let mut observation = Observation::new(
209        "incurs.codemode.approval",
210        "incurs.codemode.approval.duration",
211        vec![KeyValue::new("incurs.execution.id", state.id.clone())],
212        state.trace.as_ref(),
213    );
214    observation.finish_after(
215        decision,
216        now.saturating_sub(state.updated_at) as f64 / 1000.0,
217    );
218}