hatchet-client 0.1.0

Rust SDK for Hatchet: run workers and trigger tasks
Documentation
//! Assembling the request that triggers a run of another workflow.
//!
//! [`RunOpts`] and [`request`] are shared by every way of starting a child
//! or standalone run: H6's `Context::spawn` (fire-and-forget) and H7's
//! `Task::run`/`Task::run_no_wait` (which additionally wait on the result)
//! all build the same [`hatchet_proto::v1::TriggerWorkflowRequest`] here.

use std::collections::BTreeMap;

use hatchet_proto::v1;
use serde::Serialize;
use serde_json::{Map, Value};

use crate::declare::{DesiredLabel, Priority, wire_name};
use crate::error::{Error, Result};

/// Options for triggering a run of another workflow.
///
/// Every setter takes `self` by value and returns it, so calls chain:
///
/// ```
/// use hatchet_client::{DesiredLabel, Priority, RunOpts};
///
/// let opts = RunOpts::default()
///     .metadata("customer", "acme")
///     .priority(Priority::High)
///     .worker_label("os", DesiredLabel::eq("linux").required());
/// ```
#[derive(Clone, Debug, Default)]
#[must_use = "run options change nothing until they are passed to a call that triggers a run"]
pub struct RunOpts {
    metadata: Map<String, Value>,
    priority: Option<Priority>,
    worker_labels: BTreeMap<String, DesiredLabel>,
    child_key: Option<String>,
    sticky: bool,
    desired_worker_id: Option<String>,
}

impl RunOpts {
    /// Adds one key to the run's additional metadata. Calling this
    /// repeatedly accumulates keys; a later call with the same key
    /// overwrites the earlier value.
    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Overrides the priority the triggered run's tasks are scheduled at.
    pub fn priority(mut self, priority: Priority) -> Self {
        self.priority = Some(priority);
        self
    }

    /// Asks for a worker whose label `key` satisfies `label` to pick up the
    /// triggered run's tasks.
    pub fn worker_label(mut self, key: impl Into<String>, label: DesiredLabel) -> Self {
        self.worker_labels.insert(key.into(), label);
        self
    }

    /// Deduplicates a child run: retriggering the same parent task run with
    /// the same `child_key` (or the same `child_index`, which the SDK sets
    /// automatically per spawn call) returns the existing child run instead
    /// of starting a new one. Ignored for a run with no parent.
    pub fn child_key(mut self, child_key: impl Into<String>) -> Self {
        self.child_key = Some(child_key.into());
        self
    }

    /// Asks for the triggered run to go to the worker running *this* task.
    ///
    /// Only meaningful for a child run — a run started from inside a handler
    /// with [`Context::spawn`](crate::Context::spawn),
    /// [`Context::spawn_workflow`](crate::Context::spawn_workflow) or
    /// [`Context::run`](crate::Context::run). There is no worker to stick to
    /// when a run is triggered from a plain client, and asking for one there
    /// is an [`Error::InvalidArgument`](crate::Error::InvalidArgument) rather
    /// than a request that quietly does nothing; name the worker with
    /// [`desired_worker_id`](RunOpts::desired_worker_id) if you really have
    /// its id.
    ///
    /// The engine's own note on the field says it "requires the workflow
    /// definition to have a sticky strategy", so the workflow being triggered
    /// should carry [`Workflow::sticky`](crate::Workflow::sticky). When it
    /// does not, the engine silently drops the pin instead of erroring or
    /// hanging: on v0.80.0 a child with no sticky strategy of its own was
    /// never pinned to the requested worker, and on both v0.80.0 and
    /// v0.107.0 pointing at a worker that does not serve the child workflow
    /// at all is silently rerouted to one that does. This SDK does not guard
    /// against either case client-side, since neither one hangs.
    ///
    /// ```
    /// use hatchet_client::RunOpts;
    ///
    /// // Inside a handler: `ctx.spawn(&child, &input, RunOpts::default().sticky())`
    /// // asks the child to run on this task's own worker.
    /// let opts = RunOpts::default().sticky();
    /// ```
    pub fn sticky(mut self) -> Self {
        self.sticky = true;
        self
    }

    /// Asks for the triggered run to go to one named worker, whatever is
    /// running this code. [`sticky`](RunOpts::sticky) is the same thing
    /// without having to carry the id around; an id given here wins over it.
    ///
    /// ```
    /// use hatchet_client::RunOpts;
    ///
    /// let opts = RunOpts::default().desired_worker_id("9d1f0b1e-worker-id");
    /// ```
    pub fn desired_worker_id(mut self, worker_id: impl Into<String>) -> Self {
        self.desired_worker_id = Some(worker_id.into());
        self
    }

    /// Whether [`child_key`](RunOpts::child_key) was set.
    ///
    /// The one caller that has to know is
    /// [`DurableContext::spawn_many`](crate::DurableContext::spawn_many): one
    /// key shared by several children is how the engine is asked to fold them
    /// into a single run.
    pub(crate) fn has_child_key(&self) -> bool {
        self.child_key.is_some()
    }
}

/// Identifies the parent task run a triggered workflow is a child of, and
/// where in that parent's spawn order this child sits.
pub(crate) struct ParentRef<'a> {
    pub(crate) workflow_run_id: &'a str,
    pub(crate) task_run_external_id: &'a str,
    pub(crate) child_index: i32,
    pub(crate) worker_id: &'a str,
}

/// Builds the `TriggerWorkflow` request for running `name` (declared in
/// `namespace`) with `input`, applying `opts`, and — when `parent` is given
/// — recording it as a child run of that parent task.
///
/// `child_key` from `opts` is only meaningful for a child run; it is
/// dropped when `parent` is `None`, since the engine's deduplication is
/// keyed on `(parent_id, parent_task_run_external_id, child_key)`.
pub(crate) fn request<I: Serialize>(
    namespace: &str,
    name: &str,
    input: &I,
    opts: &RunOpts,
    parent: Option<ParentRef<'_>>,
) -> Result<v1::TriggerWorkflowRequest> {
    let input = serde_json::to_string(input).map_err(|error| Error::Json(error.to_string()))?;
    let additional_metadata = if opts.metadata.is_empty() {
        None
    } else {
        Some(
            serde_json::to_string(&opts.metadata)
                .map_err(|error| Error::Json(error.to_string()))?,
        )
    };
    let desired_worker_labels = opts
        .worker_labels
        .iter()
        .map(|(key, label)| (key.clone(), label.to_proto()))
        .collect();

    let (parent_id, parent_task_run_external_id, child_index, child_key, parent_worker_id) =
        match parent {
            Some(parent) => (
                Some(parent.workflow_run_id.to_string()),
                Some(parent.task_run_external_id.to_string()),
                Some(parent.child_index),
                opts.child_key.clone(),
                Some(parent.worker_id),
            ),
            None => (None, None, None, None, None),
        };

    let desired_worker_id = match (&opts.desired_worker_id, opts.sticky, parent_worker_id) {
        (Some(explicit), _, _) => Some(explicit.clone()),
        (None, true, Some(worker_id)) => Some(worker_id.to_string()),
        (None, true, None) => {
            return Err(Error::InvalidArgument(
                "`RunOpts::sticky` only means something for a run started from inside a \
                 task handler, which is what knows the worker to stick to; from a client, \
                 name the worker with `RunOpts::desired_worker_id` instead"
                    .to_string(),
            ));
        }
        (None, false, _) => None,
    };

    Ok(v1::TriggerWorkflowRequest {
        name: wire_name(namespace, name),
        input,
        parent_id,
        parent_task_run_external_id,
        child_index,
        child_key,
        additional_metadata,
        desired_worker_id,
        priority: opts.priority.map(Priority::to_proto),
        desired_worker_labels,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::collections::HashMap;

    #[test]
    fn request_with_default_opts_and_no_parent() {
        let request = request(
            "dev_",
            "Agent-Run",
            &json!({"repo": "x"}),
            &RunOpts::default(),
            None,
        )
        .unwrap();
        assert_eq!(
            request,
            v1::TriggerWorkflowRequest {
                name: "dev_agent-run".to_string(),
                input: r#"{"repo":"x"}"#.to_string(),
                ..Default::default()
            }
        );
    }

    #[test]
    fn request_carries_metadata_as_a_json_object() {
        let opts = RunOpts::default().metadata("a", "b").metadata("n", 1);
        let request = request("dev_", "agent-run", &json!({}), &opts, None).unwrap();
        let metadata: Value =
            serde_json::from_str(request.additional_metadata.as_ref().unwrap()).unwrap();
        assert_eq!(metadata, json!({"a": "b", "n": 1}));
    }

    #[test]
    fn request_carries_priority() {
        let opts = RunOpts::default().priority(Priority::High);
        let request = request("dev_", "agent-run", &json!({}), &opts, None).unwrap();
        assert_eq!(request.priority, Some(3));
    }

    #[test]
    fn request_carries_desired_worker_labels() {
        let label = DesiredLabel::eq("linux").required();
        let opts = RunOpts::default().worker_label("os", label.clone());
        let request = request("dev_", "agent-run", &json!({}), &opts, None).unwrap();
        assert_eq!(request.desired_worker_labels["os"], label.to_proto());
    }

    #[test]
    fn child_key_is_ignored_without_a_parent() {
        let opts = RunOpts::default().child_key("k");
        let request = request("dev_", "agent-run", &json!({}), &opts, None).unwrap();
        assert_eq!(request.child_key, None);
    }

    #[test]
    fn a_parent_carries_its_ids_index_and_child_key() {
        let opts = RunOpts::default().child_key("k");
        let parent = ParentRef {
            workflow_run_id: "run-1",
            task_run_external_id: "task-run-1",
            child_index: 2,
            worker_id: "worker-7",
        };
        let request = request("dev_", "agent-run", &json!({}), &opts, Some(parent)).unwrap();
        assert_eq!(request.parent_id, Some("run-1".to_string()));
        assert_eq!(
            request.parent_task_run_external_id,
            Some("task-run-1".to_string())
        );
        assert_eq!(request.child_index, Some(2));
        assert_eq!(request.child_key, Some("k".to_string()));
    }

    #[test]
    fn input_that_cannot_be_serialized_is_a_json_error() {
        // JSON object keys must be strings; a tuple key cannot be serialized.
        let input: HashMap<(i32, i32), i32> = HashMap::from([((1, 2), 3)]);
        let error = request("dev_", "agent-run", &input, &RunOpts::default(), None).unwrap_err();
        assert!(matches!(error, Error::Json(_)), "{error:?}");
    }

    #[test]
    fn sticky_takes_the_current_workers_id_from_the_parent() {
        let opts = RunOpts::default().sticky();
        let parent = ParentRef {
            workflow_run_id: "run-1",
            task_run_external_id: "task-run-1",
            child_index: 0,
            worker_id: "worker-7",
        };
        let request = request("dev_", "child", &json!({}), &opts, Some(parent)).unwrap();
        assert_eq!(request.desired_worker_id, Some("worker-7".to_string()));
    }

    #[test]
    fn an_explicit_worker_id_wins_over_sticky() {
        let opts = RunOpts::default().sticky().desired_worker_id("worker-9");
        let parent = ParentRef {
            workflow_run_id: "run-1",
            task_run_external_id: "task-run-1",
            child_index: 0,
            worker_id: "worker-7",
        };
        let request = request("dev_", "child", &json!({}), &opts, Some(parent)).unwrap();
        assert_eq!(request.desired_worker_id, Some("worker-9".to_string()));
    }

    #[test]
    fn an_explicit_worker_id_needs_no_parent() {
        let opts = RunOpts::default().desired_worker_id("worker-9");
        let request = request("dev_", "child", &json!({}), &opts, None).unwrap();
        assert_eq!(request.desired_worker_id, Some("worker-9".to_string()));
    }

    /// A top-level trigger has no worker to stick to, and silently ignoring the
    /// request would be the worst of both worlds: the caller believes the run is
    /// pinned and it is not.
    #[test]
    fn sticky_without_a_parent_is_an_invalid_argument() {
        let opts = RunOpts::default().sticky();
        let error = request("dev_", "child", &json!({}), &opts, None).unwrap_err();
        assert!(matches!(error, Error::InvalidArgument(_)), "{error:?}");
        assert!(error.to_string().contains("desired_worker_id"), "{error}");
    }

    #[test]
    fn without_either_option_the_field_stays_unset() {
        let parent = ParentRef {
            workflow_run_id: "run-1",
            task_run_external_id: "task-run-1",
            child_index: 0,
            worker_id: "worker-7",
        };
        let request = request(
            "dev_",
            "child",
            &json!({}),
            &RunOpts::default(),
            Some(parent),
        )
        .unwrap();
        assert_eq!(request.desired_worker_id, None);
    }
}