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};
#[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 {
pub fn metadata(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
self.metadata.insert(key.into(), value.into());
self
}
pub fn priority(mut self, priority: Priority) -> Self {
self.priority = Some(priority);
self
}
pub fn worker_label(mut self, key: impl Into<String>, label: DesiredLabel) -> Self {
self.worker_labels.insert(key.into(), label);
self
}
pub fn child_key(mut self, child_key: impl Into<String>) -> Self {
self.child_key = Some(child_key.into());
self
}
pub fn sticky(mut self) -> Self {
self.sticky = true;
self
}
pub fn desired_worker_id(mut self, worker_id: impl Into<String>) -> Self {
self.desired_worker_id = Some(worker_id.into());
self
}
pub(crate) fn has_child_key(&self) -> bool {
self.child_key.is_some()
}
}
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,
}
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() {
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()));
}
#[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);
}
}