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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13pub struct WorkflowIdentity {
14 pub name: String,
16 pub version: String,
18}
19
20#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct ExecutionTrace {
26 pub trace_id: String,
28 pub span_id: String,
30 pub trace_flags: u8,
32 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("multicast.execution.id", state.id.clone())];
60 if let Some(workflow) = workflow {
61 attrs.push(KeyValue::new(
62 "multicast.workflow.name",
63 workflow.name.clone(),
64 ));
65 attrs.push(KeyValue::new(
66 "multicast.workflow.version",
67 workflow.version.clone(),
68 ));
69 }
70 Self::new(
71 "multicast.codemode.pass",
72 "multicast.codemode.pass.duration",
73 attrs,
74 state.trace.as_ref(),
75 )
76 }
77
78 pub(crate) fn lineage(
79 &self,
80 root: &str,
81 parent: Option<&str>,
82 definition: Option<&crate::WorkflowReference>,
83 ) {
84 let span = self.context.span();
85 span.set_attribute(KeyValue::new(
86 "multicast.workflow.root.id",
87 root.to_string(),
88 ));
89 if let Some(parent) = parent {
90 span.set_attribute(KeyValue::new(
91 "multicast.workflow.parent.id",
92 parent.to_string(),
93 ));
94 }
95 if let Some(definition) = definition {
96 span.set_attribute(KeyValue::new(
97 "multicast.workflow.definition.version",
98 definition.version.clone(),
99 ));
100 }
101 }
102
103 pub(crate) fn call(id: &str, seq: u64, connector: &str, method: &str) -> Self {
104 Self::new(
105 "multicast.codemode.call",
106 "multicast.codemode.call.duration",
107 vec![
108 KeyValue::new("multicast.execution.id", id.to_string()),
109 KeyValue::new("multicast.step.sequence", seq as i64),
110 KeyValue::new("multicast.connector.name", connector.to_string()),
111 KeyValue::new("multicast.tool.name", method.to_string()),
112 ],
113 None,
114 )
115 }
116
117 fn new(
118 name: &'static str,
119 metric: &'static str,
120 attrs: Vec<KeyValue>,
121 previous: Option<&ExecutionTrace>,
122 ) -> Self {
123 let enabled = is_enabled();
124 let parent = Context::current();
125 let context = if enabled {
126 let tracer = global::tracer("multicast-codemode");
127 let mut builder = tracer.span_builder(name).with_attributes(attrs);
128 if let Some(previous) = previous.and_then(ExecutionTrace::span_context) {
129 builder = builder.with_links(vec![Link::new(previous, Vec::new(), 0)]);
130 }
131 parent.with_span(tracer.build_with_context(builder, &parent))
132 } else {
133 parent
134 };
135 Self {
136 context,
137 metric,
138 started: Instant::now(),
139 enabled,
140 finished: false,
141 }
142 }
143
144 pub(crate) fn context(&self) -> Context {
145 self.context.clone()
146 }
147
148 pub(crate) fn trace(&self, workflow: Option<WorkflowIdentity>) -> Option<ExecutionTrace> {
149 let span = self.context.span();
150 let sc = span.span_context();
151 (self.enabled && sc.is_valid()).then(|| ExecutionTrace {
152 trace_id: sc.trace_id().to_string(),
153 span_id: sc.span_id().to_string(),
154 trace_flags: sc.trace_flags().to_u8(),
155 workflow,
156 })
157 }
158
159 pub(crate) fn finish(&mut self, outcome: &'static str) {
160 self.finish_after(outcome, self.started.elapsed().as_secs_f64());
161 }
162
163 fn finish_after(&mut self, outcome: &'static str, seconds: f64) {
164 if self.finished {
165 return;
166 }
167 self.finished = true;
168 if !self.enabled {
169 return;
170 }
171 let attrs = vec![KeyValue::new("multicast.outcome", outcome)];
172 let span = self.context.span();
173 span.set_attribute(attrs[0].clone());
174 if outcome == "error" {
175 span.set_status(Status::error("execution_error"));
176 }
177 global::meter("multicast-codemode")
178 .f64_histogram(self.metric)
179 .with_unit("s")
180 .build()
181 .record(seconds, &attrs);
182 span.end();
183 }
184}
185
186impl Drop for Observation {
187 fn drop(&mut self) {
188 self.finish("cancelled");
189 }
190}
191
192pub(crate) fn outcome(status: ExecutionStatus) -> &'static str {
193 match status {
194 ExecutionStatus::Running => "running",
195 ExecutionStatus::Paused => "paused",
196 ExecutionStatus::Completed => "completed",
197 ExecutionStatus::Error => "error",
198 ExecutionStatus::Rejected => "rejected",
199 ExecutionStatus::Cancelled => "cancelled",
200 ExecutionStatus::RolledBack => "rolled_back",
201 }
202}
203
204pub(crate) fn approval(state: &ExecutionState, now: u64, decision: &'static str) {
205 if state.status != ExecutionStatus::Paused
206 || !state
207 .log
208 .iter()
209 .any(|entry| entry.state == crate::LogEntryState::Pending)
210 || !is_enabled()
211 {
212 return;
213 }
214 let mut observation = Observation::new(
215 "multicast.codemode.approval",
216 "multicast.codemode.approval.duration",
217 vec![KeyValue::new("multicast.execution.id", state.id.clone())],
218 state.trace.as_ref(),
219 );
220 observation.finish_after(
221 decision,
222 now.saturating_sub(state.updated_at) as f64 / 1000.0,
223 );
224}