hatchet-client 0.1.0

Rust SDK for Hatchet: run workers and trigger tasks
Documentation
//! The spans this SDK opens, and — with the `otel` feature — the trace
//! context it carries between runs.
//!
//! Every span is an ordinary `tracing` span named and attributed the way the
//! official Go SDK names its own (`sdks/go/opentelemetry/otel_attributes.go:6-46`),
//! with the fields `tracing-opentelemetry` reads for a span's kind and
//! status (`otel.kind`, `otel.status_code`, `otel.status_description`). A
//! subscriber without an OpenTelemetry layer sees plain spans; one with a
//! `tracing-opentelemetry` layer exports them as OpenTelemetry spans — with
//! or without the feature. All of them are at `INFO`, and no span records a
//! run's input, output or metadata.
//!
//! What the feature adds is what crosses the engine: a trigger writes its
//! span's W3C `traceparent` into the run's additional metadata ([`inject`]),
//! and a worker makes the run's span a child of the `traceparent` it finds
//! there ([`start_step_run`]). That needs the OpenTelemetry context API, so
//! it is the only part behind the feature.

use hatchet_proto::root::AssignedAction;
use tracing::Span;
use tracing::field::Empty;

#[cfg(feature = "otel")]
mod traceparent;

#[cfg(feature = "otel")]
pub(crate) use traceparent::inject;

/// Without the `otel` feature nothing crosses the engine: `metadata` is sent
/// exactly as the caller built it.
#[cfg(not(feature = "otel"))]
pub(crate) fn inject(_span: &Span, _metadata: &mut Option<String>) {}

/// The `instrumentor` attribute every span carries
/// (`otel_attributes.go:8-11`).
const INSTRUMENTOR: &str = "hatchet";

/// A count as the `i64` attribute Go records (`attribute.Int`):
/// `tracing-opentelemetry` would write a `u64` as a string.
fn count(n: usize) -> i64 {
    i64::try_from(n).unwrap_or(i64::MAX)
}

/// Triggering one run: `hatchet.run_workflow`, a producer span naming the
/// workflow as it was declared — before the namespace and lowercasing, as
/// Go records `w.declaration.Name()` (`sdks/go/workflow.go:940-946`). The
/// run's id is recorded as `hatchet.child_workflow_run_id` once the engine
/// has given one (`:1057`).
pub(crate) fn run_workflow(name: &str) -> Span {
    tracing::info_span!(
        "hatchet.run_workflow",
        otel.kind = "producer",
        otel.status_code = Empty,
        otel.status_description = Empty,
        instrumentor = INSTRUMENTOR,
        hatchet.workflow_name = name,
        hatchet.child_workflow_run_id = Empty,
    )
}

/// Triggering many runs of one workflow: one `hatchet.run_workflows` span,
/// whose traceparent every item carries (`sdks/go/workflow.go:1070-1077,
/// 1151`).
pub(crate) fn run_workflows(name: &str, runs: usize) -> Span {
    tracing::info_span!(
        "hatchet.run_workflows",
        otel.kind = "producer",
        otel.status_code = Empty,
        otel.status_description = Empty,
        instrumentor = INSTRUMENTOR,
        hatchet.workflow_name = name,
        hatchet.num_workflows = count(runs),
    )
}

/// Running one action: `hatchet.start_step_run`, a consumer span carrying
/// the attributes Go's middleware sets (`sdks/go/opentelemetry/attributes.go:16-50`):
/// always the tenant, worker, workflow run, step run, step, action and step
/// names and the retry count; the workflow, workflow version, parent run,
/// child index and child key only when the action has them. Not the input,
/// not the metadata — Go attaches neither.
///
/// With the `otel` feature, the span continues the trace named by the
/// action's `traceparent` (`sdks/go/opentelemetry/middleware.go:30-38`); a
/// missing or malformed one leaves it a root.
pub(crate) fn start_step_run(action: &AssignedAction, worker_id: &str) -> Span {
    let span = tracing::info_span!(
        "hatchet.start_step_run",
        otel.kind = "consumer",
        otel.status_code = Empty,
        otel.status_description = Empty,
        instrumentor = INSTRUMENTOR,
        hatchet.tenant_id = action.tenant_id.as_str(),
        hatchet.worker_id = worker_id,
        hatchet.workflow_run_id = action.workflow_run_id.as_str(),
        hatchet.step_run_id = action.task_run_external_id.as_str(),
        hatchet.step_id = action.task_id.as_str(),
        hatchet.action_name = action.action_id.as_str(),
        hatchet.step_name = action.task_name.as_str(),
        hatchet.retry_count = i64::from(action.retry_count),
        hatchet.workflow_id = Empty,
        hatchet.workflow_version_id = Empty,
        hatchet.parent_workflow_run_id = Empty,
        hatchet.child_workflow_index = Empty,
        hatchet.child_workflow_key = Empty,
    );
    // First, before anything can start the OpenTelemetry span: its parent is
    // fixed from then on.
    #[cfg(feature = "otel")]
    if !span.is_disabled() {
        traceparent::continue_from(&span, action.additional_metadata.as_deref());
    }
    if let Some(id) = &action.workflow_id {
        span.record("hatchet.workflow_id", id.as_str());
    }
    if let Some(id) = &action.workflow_version_id {
        span.record("hatchet.workflow_version_id", id.as_str());
    }
    if let Some(id) = &action.parent_workflow_run_id {
        span.record("hatchet.parent_workflow_run_id", id.as_str());
    }
    if let Some(index) = action.child_workflow_index {
        span.record("hatchet.child_workflow_index", i64::from(index));
    }
    if let Some(key) = &action.child_workflow_key {
        span.record("hatchet.child_workflow_key", key.as_str());
    }
    span
}

/// Running one batch: the same `hatchet.start_step_run`, one for the whole
/// batch, as Go's middleware wraps a `START_BATCH` like any other action
/// (`pkg/worker/worker.go:911`). A batch assignment names no single run, so
/// only what it has is recorded — tenant, worker, action — plus
/// `hatchet.batch_id` and `hatchet.batch_size` (the members it names), which
/// are this SDK's own: Go defines no batch attribute. The members' own
/// metadata is not read; the batch continues a trace only if the assignment
/// itself carries a `traceparent`.
pub(crate) fn start_batch_run(action: &AssignedAction, worker_id: &str, members: usize) -> Span {
    let span = tracing::info_span!(
        "hatchet.start_step_run",
        otel.kind = "consumer",
        otel.status_code = Empty,
        otel.status_description = Empty,
        instrumentor = INSTRUMENTOR,
        hatchet.tenant_id = action.tenant_id.as_str(),
        hatchet.worker_id = worker_id,
        hatchet.action_name = action.action_id.as_str(),
        hatchet.batch_id = action.batch_id.as_deref().unwrap_or_default(),
        hatchet.batch_size = count(members),
    );
    #[cfg(feature = "otel")]
    if !span.is_disabled() {
        traceparent::continue_from(&span, action.additional_metadata.as_deref());
    }
    span
}

/// An engine-sent cancellation: `hatchet.cancel_step_run`, as the official
/// Python SDK opens it (`sdks/python/hatchet_sdk/opentelemetry/instrumentor.py:524-541`).
/// Go defines the name (`otel_attributes.go:42`) but opens no span for a
/// cancellation.
pub(crate) fn cancel_step_run(task_run_external_id: &str) -> Span {
    tracing::info_span!(
        "hatchet.cancel_step_run",
        otel.kind = "consumer",
        instrumentor = INSTRUMENTOR,
        hatchet.step_run_id = task_run_external_id,
    )
}

/// Pushing one event: `hatchet.push_event`, a producer span naming the key
/// as the caller gave it — before the namespace, as Go records it
/// (`pkg/client/event.go:166-176`).
pub(crate) fn push_event(key: &str) -> Span {
    tracing::info_span!(
        "hatchet.push_event",
        otel.kind = "producer",
        otel.status_code = Empty,
        otel.status_description = Empty,
        instrumentor = INSTRUMENTOR,
        hatchet.event_key = key,
    )
}

/// Pushing events in one call: `hatchet.bulk_push_event`
/// (`pkg/client/event.go:234-245`), whose traceparent every event carries
/// (`:262`).
pub(crate) fn bulk_push_event(events: usize) -> Span {
    tracing::info_span!(
        "hatchet.bulk_push_event",
        otel.kind = "producer",
        otel.status_code = Empty,
        otel.status_description = Empty,
        instrumentor = INSTRUMENTOR,
        hatchet.num_events = count(events),
    )
}

/// Marks `span` as having succeeded (`SetStatus(codes.Ok, "")`).
pub(crate) fn record_ok(span: &Span) {
    span.record("otel.status_code", "ok");
}

/// Marks `span` as having failed with `message`
/// (`SetStatus(codes.Error, err.Error())`).
pub(crate) fn record_error(span: &Span, message: &str) {
    span.record("otel.status_description", message);
}

/// [`record_ok`] or [`record_error`], from how `result` came out.
pub(crate) fn record_result<T, E: std::fmt::Display>(span: &Span, result: &Result<T, E>) {
    match result {
        Ok(_) => record_ok(span),
        Err(error) => record_error(span, &error.to_string()),
    }
}