multicast-codemode 2.0.0

Portable durable Code Mode runtime for multicast tools
Documentation
use multicast::telemetry::{is_enabled, opentelemetry};
use opentelemetry::trace::{
    Link, SpanContext, SpanId, Status, TraceContextExt, TraceFlags, TraceId, TraceState, Tracer,
};
use opentelemetry::{Context, KeyValue, global};
use serde::{Deserialize, Serialize};
use web_time::Instant;

use crate::{ExecutionState, ExecutionStatus};

/// Saved workflow identity attached to execution spans, never metric labels.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkflowIdentity {
    /// Workflow's catalog name.
    pub name: String,
    /// Digest of the workflow program and input schema.
    pub version: String,
}

/// Last active pass's tracing identity, safe to retain in the execution store.
///
/// Only trace identifiers and workflow identity are retained. Request headers,
/// baggage, arguments, results, and credentials are not copied into this record.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionTrace {
    /// Lowercase hexadecimal trace identifier.
    pub trace_id: String,
    /// Lowercase hexadecimal span identifier.
    pub span_id: String,
    /// W3C trace flags byte.
    pub trace_flags: u8,
    /// Workflow identity, when this execution was started as a named workflow.
    pub workflow: Option<WorkflowIdentity>,
}

impl ExecutionTrace {
    fn span_context(&self) -> Option<SpanContext> {
        let span = SpanContext::new(
            TraceId::from_hex(&self.trace_id).ok()?,
            SpanId::from_hex(&self.span_id).ok()?,
            TraceFlags::new(self.trace_flags),
            false,
            TraceState::default(),
        );
        span.is_valid().then_some(span)
    }
}

pub(crate) struct Observation {
    context: Context,
    metric: &'static str,
    started: Instant,
    enabled: bool,
    finished: bool,
}

impl Observation {
    pub(crate) fn pass(state: &ExecutionState, workflow: Option<&WorkflowIdentity>) -> Self {
        let mut attrs = vec![KeyValue::new("incurs.execution.id", state.id.clone())];
        if let Some(workflow) = workflow {
            attrs.push(KeyValue::new("incurs.workflow.name", workflow.name.clone()));
            attrs.push(KeyValue::new(
                "incurs.workflow.version",
                workflow.version.clone(),
            ));
        }
        Self::new(
            "incurs.codemode.pass",
            "incurs.codemode.pass.duration",
            attrs,
            state.trace.as_ref(),
        )
    }

    pub(crate) fn lineage(
        &self,
        root: &str,
        parent: Option<&str>,
        definition: Option<&crate::WorkflowReference>,
    ) {
        let span = self.context.span();
        span.set_attribute(KeyValue::new("incurs.workflow.root.id", root.to_string()));
        if let Some(parent) = parent {
            span.set_attribute(KeyValue::new(
                "incurs.workflow.parent.id",
                parent.to_string(),
            ));
        }
        if let Some(definition) = definition {
            span.set_attribute(KeyValue::new(
                "incurs.workflow.definition.version",
                definition.version.clone(),
            ));
        }
    }

    pub(crate) fn call(id: &str, seq: u64, connector: &str, method: &str) -> Self {
        Self::new(
            "incurs.codemode.call",
            "incurs.codemode.call.duration",
            vec![
                KeyValue::new("incurs.execution.id", id.to_string()),
                KeyValue::new("incurs.step.sequence", seq as i64),
                KeyValue::new("incurs.connector.name", connector.to_string()),
                KeyValue::new("incurs.tool.name", method.to_string()),
            ],
            None,
        )
    }

    fn new(
        name: &'static str,
        metric: &'static str,
        attrs: Vec<KeyValue>,
        previous: Option<&ExecutionTrace>,
    ) -> Self {
        let enabled = is_enabled();
        let parent = Context::current();
        let context = if enabled {
            let tracer = global::tracer("multicast-codemode");
            let mut builder = tracer.span_builder(name).with_attributes(attrs);
            if let Some(previous) = previous.and_then(ExecutionTrace::span_context) {
                builder = builder.with_links(vec![Link::new(previous, Vec::new(), 0)]);
            }
            parent.with_span(tracer.build_with_context(builder, &parent))
        } else {
            parent
        };
        Self {
            context,
            metric,
            started: Instant::now(),
            enabled,
            finished: false,
        }
    }

    pub(crate) fn context(&self) -> Context {
        self.context.clone()
    }

    pub(crate) fn trace(&self, workflow: Option<WorkflowIdentity>) -> Option<ExecutionTrace> {
        let span = self.context.span();
        let sc = span.span_context();
        (self.enabled && sc.is_valid()).then(|| ExecutionTrace {
            trace_id: sc.trace_id().to_string(),
            span_id: sc.span_id().to_string(),
            trace_flags: sc.trace_flags().to_u8(),
            workflow,
        })
    }

    pub(crate) fn finish(&mut self, outcome: &'static str) {
        self.finish_after(outcome, self.started.elapsed().as_secs_f64());
    }

    fn finish_after(&mut self, outcome: &'static str, seconds: f64) {
        if self.finished {
            return;
        }
        self.finished = true;
        if !self.enabled {
            return;
        }
        let attrs = vec![KeyValue::new("incurs.outcome", outcome)];
        let span = self.context.span();
        span.set_attribute(attrs[0].clone());
        if outcome == "error" {
            span.set_status(Status::error("execution_error"));
        }
        global::meter("multicast-codemode")
            .f64_histogram(self.metric)
            .with_unit("s")
            .build()
            .record(seconds, &attrs);
        span.end();
    }
}

impl Drop for Observation {
    fn drop(&mut self) {
        self.finish("cancelled");
    }
}

pub(crate) fn outcome(status: ExecutionStatus) -> &'static str {
    match status {
        ExecutionStatus::Running => "running",
        ExecutionStatus::Paused => "paused",
        ExecutionStatus::Completed => "completed",
        ExecutionStatus::Error => "error",
        ExecutionStatus::Rejected => "rejected",
        ExecutionStatus::Cancelled => "cancelled",
        ExecutionStatus::RolledBack => "rolled_back",
    }
}

pub(crate) fn approval(state: &ExecutionState, now: u64, decision: &'static str) {
    if state.status != ExecutionStatus::Paused
        || !state
            .log
            .iter()
            .any(|entry| entry.state == crate::LogEntryState::Pending)
        || !is_enabled()
    {
        return;
    }
    let mut observation = Observation::new(
        "incurs.codemode.approval",
        "incurs.codemode.approval.duration",
        vec![KeyValue::new("incurs.execution.id", state.id.clone())],
        state.trace.as_ref(),
    );
    observation.finish_after(
        decision,
        now.saturating_sub(state.updated_at) as f64 / 1000.0,
    );
}