use std::collections::HashSet;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use hatchet_proto::v1;
use rand::Rng;
use super::task::Task;
use crate::config::namespace;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ConditionAction {
Queue,
Skip,
Cancel,
}
impl ConditionAction {
fn to_proto(self) -> i32 {
let action = match self {
Self::Queue => v1::Action::Queue,
Self::Skip => v1::Action::Skip,
Self::Cancel => v1::Action::Cancel,
};
action as i32
}
fn gate(self) -> &'static str {
match self {
Self::Queue => "wait_for",
Self::Skip => "skip_if",
Self::Cancel => "cancel_if",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum Kind {
Sleep(Duration),
Event(String),
Parent(String),
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[must_use = "a condition gates nothing until it is given to wait_for, skip_if or cancel_if"]
pub struct Condition {
kind: Kind,
expression: Option<String>,
readable_key: Option<String>,
scope: Option<String>,
since: Option<SystemTime>,
}
impl Condition {
fn of(kind: Kind) -> Self {
Self {
kind,
expression: None,
readable_key: None,
scope: None,
since: None,
}
}
pub fn sleep(duration: Duration) -> Self {
Self::of(Kind::Sleep(duration))
}
pub fn on_event(key: impl Into<String>) -> Self {
Self::of(Kind::Event(key.into()))
}
pub fn parent<I, O>(parent: &Task<I, O>) -> Self {
Self::parent_by_name(parent.name())
}
pub fn parent_by_name(name: impl Into<String>) -> Self {
Self::of(Kind::Parent(name.into()))
}
pub fn expression(mut self, expression: impl Into<String>) -> Self {
self.expression = Some(expression.into());
self
}
pub fn readable_key(mut self, key: impl Into<String>) -> Self {
self.readable_key = Some(key.into());
self
}
pub fn scope(mut self, scope: impl Into<String>) -> Self {
self.scope = Some(scope.into());
self
}
pub fn since(mut self, at: SystemTime) -> Self {
self.since = Some(at);
self
}
fn readable_data_key(&self) -> String {
if let Some(key) = &self.readable_key {
return key.clone();
}
match &self.kind {
Kind::Sleep(duration) => format!("sleep:{}", duration_expr(*duration)),
Kind::Event(key) => key.clone(),
Kind::Parent(name) => match &self.expression {
Some(expression) => format!("{name}:{expression}"),
None => name.clone(),
},
}
}
pub(crate) fn parent_name(&self) -> Option<&str> {
match &self.kind {
Kind::Parent(name) => Some(name.as_str()),
_ => None,
}
}
fn only_gates_queueing(&self) -> bool {
matches!(self.kind, Kind::Sleep(_) | Kind::Event(_))
}
fn blank_field(&self) -> Option<&'static str> {
let blank = |value: &str| value.trim().is_empty();
match &self.kind {
Kind::Event(key) if blank(key) => return Some("event key"),
Kind::Parent(name) if blank(name) => return Some("parent name"),
_ => {}
}
if self.readable_key.as_deref().is_some_and(blank) {
return Some("readable key");
}
if self.expression.as_deref().is_some_and(blank) {
return Some("expression");
}
if self.scope.as_deref().is_some_and(blank) {
return Some("event scope");
}
None
}
fn invalid_reason(&self) -> Option<String> {
let key = self.readable_data_key();
if let Some(blank) = self.blank_field() {
return Some(if blank == "expression" {
"a condition was given a blank expression; leave `expression` off \
to match unconditionally"
.to_string()
} else {
format!(
"a condition was given a blank {blank}; the engine matches on it \
verbatim, so a blank one leaves the task waiting for ever"
)
});
}
match &self.kind {
Kind::Event(_) => {
if self.since.is_some() && self.scope.is_none() {
return Some(format!(
"the event condition `{key}` sets `since` without `scope`; the \
engine considers earlier events only within a scope"
));
}
return None;
}
Kind::Sleep(duration) => {
if self.expression.is_some() {
return Some(format!(
"the sleep condition `{key}` sets an expression, which only a \
parent or event condition can use"
));
}
if duration.as_millis() == 0 {
return Some(format!(
"the sleep condition `{key}` rounds to zero milliseconds, which \
is what the engine is sent; a sleep condition must wait for \
some time"
));
}
}
Kind::Parent(_) => {}
}
if self.scope.is_some() {
return Some(format!(
"the condition `{key}` sets a scope, which only an event condition has"
));
}
if self.since.is_some() {
return Some(format!(
"the condition `{key}` sets `since`, which only an event condition has"
));
}
None
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[must_use = "an or-group gates nothing until it is given to wait_for, skip_if or cancel_if"]
pub struct OrGroup(Vec<Condition>);
pub fn any_of(conditions: impl IntoIterator<Item = Condition>) -> OrGroup {
OrGroup(conditions.into_iter().collect())
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[must_use = "a condition set gates nothing until it is given to wait_for, skip_if or cancel_if"]
pub struct ConditionSet {
groups: Vec<Vec<Condition>>,
}
impl ConditionSet {
pub fn and(mut self, more: impl Into<ConditionSet>) -> Self {
self.groups.extend(more.into().groups);
self
}
pub(crate) fn is_empty(&self) -> bool {
self.groups.is_empty()
}
pub(crate) fn extend(&mut self, more: ConditionSet) {
self.groups.extend(more.groups);
}
pub(crate) fn parent_names(&self) -> impl Iterator<Item = &str> {
self.conditions().filter_map(Condition::parent_name)
}
fn conditions(&self) -> impl Iterator<Item = &Condition> {
self.groups.iter().flatten()
}
pub(crate) fn wait_kind(&self) -> (&'static str, String) {
let mut kind: Option<&'static str> = None;
let mut keys: Vec<String> = Vec::new();
for condition in self.conditions() {
let this = match condition.kind {
Kind::Sleep(_) => "sleep",
Kind::Event(_) => "user_event",
Kind::Parent(_) => "parent",
};
kind = Some(match kind {
Some(seen) if seen != this => "wait_for",
Some(seen) => seen,
None => this,
});
keys.push(condition.readable_data_key());
}
keys.sort();
(
kind.unwrap_or("wait_for"),
keys.into_iter().next().unwrap_or_default(),
)
}
}
impl From<Condition> for ConditionSet {
fn from(condition: Condition) -> Self {
Self {
groups: vec![vec![condition]],
}
}
}
impl From<OrGroup> for ConditionSet {
fn from(group: OrGroup) -> Self {
Self {
groups: vec![group.0],
}
}
}
impl From<Vec<Condition>> for ConditionSet {
fn from(conditions: Vec<Condition>) -> Self {
Self {
groups: conditions
.into_iter()
.map(|condition| vec![condition])
.collect(),
}
}
}
impl<const N: usize> From<[Condition; N]> for ConditionSet {
fn from(conditions: [Condition; N]) -> Self {
Vec::from(conditions).into()
}
}
impl From<Vec<OrGroup>> for ConditionSet {
fn from(groups: Vec<OrGroup>) -> Self {
Self {
groups: groups.into_iter().map(|group| group.0).collect(),
}
}
}
impl<const N: usize> From<[OrGroup; N]> for ConditionSet {
fn from(groups: [OrGroup; N]) -> Self {
Vec::from(groups).into()
}
}
pub(crate) type Gates<'a> = [(ConditionAction, &'a ConditionSet); 3];
pub(crate) fn validate(gates: Gates<'_>) -> Result<(), String> {
let mut keys: HashSet<String> = HashSet::new();
for (_, set) in gates {
for group in &set.groups {
if group.is_empty() {
return Err(
"an or-group has no conditions; `any_of` needs at least one".to_string()
);
}
}
for condition in set.conditions() {
if let Some(reason) = condition.invalid_reason() {
return Err(reason);
}
if let Some(at) = condition.since
&& at.duration_since(UNIX_EPOCH).is_err()
{
return Err(format!(
"the condition `{}` sets `since` to a time before 1970",
condition.readable_data_key()
));
}
let key = condition.readable_data_key();
if !keys.insert(key.clone()) {
return Err(format!(
"two conditions on this task share the readable key `{key}`; the \
engine tells them apart by that key, so give one of them its own \
with `Condition::readable_key(..)`"
));
}
}
}
let waits = gates.iter().any(|(action, set)| {
*action == ConditionAction::Queue && set.conditions().any(Condition::only_gates_queueing)
});
if !waits {
for (action, set) in gates {
if action == ConditionAction::Queue {
continue;
}
if let Some(condition) = set.conditions().find(|c| c.only_gates_queueing()) {
return Err(format!(
"the `{}` condition `{}` waits on a sleep or an event, but the task \
has no `wait_for` that does; the engine only weighs such a \
condition while the task waits to be queued, so the task would \
never start — add a `wait_for` on a sleep or an event (parents, \
and a `wait_for` made only of parent conditions, do not count; a \
`skip_if` or `cancel_if` on a parent condition needs no pairing at \
all)",
action.gate(),
condition.readable_data_key()
));
}
}
}
Ok(())
}
pub(crate) fn to_proto(namespace: &str, gates: Gates<'_>) -> Option<v1::TaskConditions> {
let mut conditions = v1::TaskConditions::default();
let mut any = false;
for (action, set) in gates {
for group in &set.groups {
let or_group_id = or_group_id();
for condition in group {
any = true;
let base = v1::BaseMatchCondition {
readable_data_key: condition.readable_data_key(),
action: action.to_proto(),
or_group_id: or_group_id.clone(),
expression: condition.expression.clone().unwrap_or_default(),
};
match &condition.kind {
Kind::Sleep(duration) => {
conditions.sleep_conditions.push(v1::SleepMatchCondition {
base: Some(base),
sleep_for: duration_expr(*duration),
});
}
Kind::Event(key) => {
conditions
.user_event_conditions
.push(v1::UserEventMatchCondition {
base: Some(base),
user_event_key: namespace::apply(namespace, key),
event_scope: condition.scope.clone(),
consider_events_since: condition.since.map(timestamp),
});
}
Kind::Parent(name) => {
conditions.parent_override_conditions.push(
v1::ParentOverrideMatchCondition {
base: Some(base),
parent_readable_id: name.clone(),
},
);
}
}
}
}
}
any.then_some(conditions)
}
pub(crate) fn to_durable_proto(
namespace: &str,
conditions: &ConditionSet,
) -> Result<v1::DurableEventListenerConditions, String> {
if conditions.is_empty() {
return Err("a durable wait needs at least one condition".to_string());
}
let mut keys: HashSet<String> = HashSet::new();
let mut mapped = v1::DurableEventListenerConditions::default();
for group in &conditions.groups {
if group.is_empty() {
return Err("an or-group has no conditions; `any_of` needs at least one".to_string());
}
let or_group_id = or_group_id();
for condition in group {
if let Some(reason) = condition.invalid_reason() {
return Err(reason);
}
if let Some(at) = condition.since
&& at.duration_since(UNIX_EPOCH).is_err()
{
return Err(format!(
"the condition `{}` sets `since` to a time before 1970",
condition.readable_data_key()
));
}
let key = condition.readable_data_key();
if !keys.insert(key.clone()) {
return Err(format!(
"two conditions of one durable wait share the readable_key `{key}`; the \
engine indexes the wait's result by that key, so one of the matches \
would be lost — give one of them its own with \
`Condition::readable_key(..)`"
));
}
let base = v1::BaseMatchCondition {
readable_data_key: key,
action: v1::Action::Create as i32,
or_group_id: or_group_id.clone(),
expression: condition.expression.clone().unwrap_or_default(),
};
match &condition.kind {
Kind::Sleep(duration) => mapped.sleep_conditions.push(v1::SleepMatchCondition {
base: Some(base),
sleep_for: duration_expr(*duration),
}),
Kind::Event(event) => {
mapped
.user_event_conditions
.push(v1::UserEventMatchCondition {
base: Some(base),
user_event_key: namespace::apply(namespace, event),
event_scope: condition.scope.clone(),
consider_events_since: condition.since.map(timestamp),
});
}
Kind::Parent(name) => {
return Err(format!(
"the durable wait names the parent task `{name}`, but a durable wait \
cannot read a parent: the engine takes only sleep and event \
conditions here. Read the parent's output with \
`Context::parent_output` instead, or gate the task itself with \
`TaskBuilder::wait_for`"
));
}
}
}
}
Ok(mapped)
}
fn duration_expr(duration: Duration) -> String {
format!("{}ms", duration.as_millis())
}
fn timestamp(at: SystemTime) -> hatchet_proto::prost_types::Timestamp {
let since_epoch = at.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO);
hatchet_proto::prost_types::Timestamp {
seconds: i64::try_from(since_epoch.as_secs()).unwrap_or(i64::MAX),
nanos: i32::try_from(since_epoch.subsec_nanos()).unwrap_or(0),
}
}
fn or_group_id() -> String {
let mut bytes = rand::rng().random::<u128>().to_be_bytes();
bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80; let hex = |part: &[u8]| -> String { part.iter().map(|byte| format!("{byte:02x}")).collect() };
format!(
"{}-{}-{}-{}-{}",
hex(&bytes[0..4]),
hex(&bytes[4..6]),
hex(&bytes[6..8]),
hex(&bytes[8..10]),
hex(&bytes[10..16])
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::TaskBuilder;
fn gates<'a>(
wait_for: &'a ConditionSet,
skip_if: &'a ConditionSet,
cancel_if: &'a ConditionSet,
) -> Gates<'a> {
[
(ConditionAction::Queue, wait_for),
(ConditionAction::Skip, skip_if),
(ConditionAction::Cancel, cancel_if),
]
}
fn only(set: ConditionSet) -> v1::TaskConditions {
let empty = ConditionSet::default();
to_proto("dev_", gates(&set, &empty, &empty)).expect("the set is not empty")
}
#[test]
fn durable_conditions_are_create_conditions_without_parents() {
let set = ConditionSet::from(Condition::sleep(Duration::from_secs(30)))
.and(Condition::on_event("go"));
let conditions = to_durable_proto("dev_", &set).expect("a valid durable wait");
let sleep = &conditions.sleep_conditions[0];
assert_eq!(sleep.sleep_for, "30000ms");
let base = sleep.base.as_ref().expect("a base condition");
assert_eq!(base.readable_data_key, "sleep:30000ms");
assert_eq!(base.action, v1::Action::Create as i32);
let event = &conditions.user_event_conditions[0];
assert_eq!(event.user_event_key, "dev_go");
let base = event.base.as_ref().expect("a base condition");
assert_eq!(base.readable_data_key, "go");
assert_eq!(base.action, v1::Action::Create as i32);
}
#[test]
fn a_durable_or_group_shares_one_group_id() {
let set = ConditionSet::from(any_of([
Condition::on_event("go"),
Condition::sleep(Duration::from_secs(5)),
]));
let conditions = to_durable_proto("dev_", &set).expect("a valid durable wait");
let event = conditions.user_event_conditions[0]
.base
.as_ref()
.expect("a base condition");
let sleep = conditions.sleep_conditions[0]
.base
.as_ref()
.expect("a base condition");
assert_eq!(event.or_group_id, sleep.or_group_id);
assert!(!event.or_group_id.is_empty());
}
#[test]
fn a_parent_condition_cannot_be_waited_for_durably() {
let reason = to_durable_proto(
"dev_",
&ConditionSet::from(Condition::parent_by_name("fetch")),
)
.expect_err("parents are not durable conditions");
assert!(reason.contains("parent"), "{reason}");
}
#[test]
fn a_durable_wait_needs_at_least_one_condition_and_unique_keys() {
assert!(to_durable_proto("dev_", &ConditionSet::default()).is_err());
let twice = ConditionSet::from(Condition::sleep(Duration::from_secs(5)))
.and(Condition::sleep(Duration::from_secs(5)));
let reason = to_durable_proto("dev_", &twice).expect_err("duplicate readable keys");
assert!(reason.contains("readable_key"), "{reason}");
let renamed = ConditionSet::from(Condition::sleep(Duration::from_secs(5)))
.and(Condition::sleep(Duration::from_secs(5)).readable_key("second"));
assert!(to_durable_proto("dev_", &renamed).is_ok());
}
#[test]
fn a_durable_wait_rejects_what_an_invalid_condition_would_hide() {
let blank = to_durable_proto("dev_", &ConditionSet::from(Condition::on_event(" ")))
.expect_err("a blank event key is a mistake");
assert!(blank.contains("blank"), "{blank}");
}
#[test]
fn a_sleep_condition_maps_to_a_sleep_match_condition() {
let conditions = only(Condition::sleep(Duration::from_secs(30)).into());
assert!(conditions.user_event_conditions.is_empty());
assert!(conditions.parent_override_conditions.is_empty());
let [sleep] = conditions.sleep_conditions.as_slice() else {
panic!("exactly one sleep condition: {conditions:?}");
};
assert_eq!(sleep.sleep_for, "30000ms");
let base = sleep.base.as_ref().expect("a base condition");
assert_eq!(base.action, v1::Action::Queue as i32);
assert_eq!(base.readable_data_key, "sleep:30000ms");
assert_eq!(base.expression, "");
assert!(
!base.or_group_id.is_empty(),
"every condition gets a group id"
);
}
#[test]
fn a_sub_second_sleep_keeps_its_milliseconds() {
let conditions = only(Condition::sleep(Duration::from_millis(1500)).into());
assert_eq!(conditions.sleep_conditions[0].sleep_for, "1500ms");
}
#[test]
fn an_event_condition_is_namespaced_but_its_readable_key_is_not() {
let conditions = only(
Condition::on_event("approval.granted")
.expression("input.ok == true")
.scope("tenant-1")
.into(),
);
let [event] = conditions.user_event_conditions.as_slice() else {
panic!("exactly one user event condition: {conditions:?}");
};
assert_eq!(event.user_event_key, "dev_approval.granted");
assert_eq!(event.event_scope.as_deref(), Some("tenant-1"));
assert_eq!(event.consider_events_since, None);
let base = event.base.as_ref().expect("a base condition");
assert_eq!(base.readable_data_key, "approval.granted");
assert_eq!(base.expression, "input.ok == true");
}
#[test]
fn an_event_key_that_already_carries_the_namespace_is_not_prefixed_twice() {
let conditions = only(Condition::on_event("dev_go").into());
let [event] = conditions.user_event_conditions.as_slice() else {
panic!("one condition: {conditions:?}");
};
assert_eq!(event.user_event_key, "dev_go");
}
#[test]
fn an_events_since_is_sent_as_a_timestamp() {
let at = UNIX_EPOCH + Duration::new(1_700_000_000, 250);
let conditions = only(Condition::on_event("go").scope("s").since(at).into());
assert_eq!(
conditions.user_event_conditions[0].consider_events_since,
Some(hatchet_proto::prost_types::Timestamp {
seconds: 1_700_000_000,
nanos: 250,
})
);
}
#[test]
fn a_parent_condition_names_the_parent_and_folds_its_expression_into_its_key() {
let fetch = TaskBuilder::<(), u32>::new("fetch").handler(|_ctx, _input| async { Ok(1) });
let conditions = only(
Condition::parent(&fetch)
.expression("output.count > 0")
.into(),
);
let [parent] = conditions.parent_override_conditions.as_slice() else {
panic!("exactly one parent condition: {conditions:?}");
};
assert_eq!(parent.parent_readable_id, "fetch");
let base = parent.base.as_ref().expect("a base condition");
assert_eq!(base.readable_data_key, "fetch:output.count > 0");
assert_eq!(base.expression, "output.count > 0");
}
#[test]
fn an_explicit_readable_key_wins_over_the_default() {
let conditions = only(
Condition::sleep(Duration::from_secs(1))
.readable_key("first-wait")
.into(),
);
let base = conditions.sleep_conditions[0]
.base
.as_ref()
.expect("a base condition");
assert_eq!(base.readable_data_key, "first-wait");
}
#[test]
fn the_three_gates_map_to_their_own_actions_in_one_task_conditions() {
let wait_for: ConditionSet = Condition::sleep(Duration::from_secs(5)).into();
let skip_if: ConditionSet = Condition::on_event("skip").into();
let cancel_if: ConditionSet = Condition::on_event("stop").into();
let conditions =
to_proto("", gates(&wait_for, &skip_if, &cancel_if)).expect("three non-empty gates");
assert_eq!(conditions.sleep_conditions.len(), 1);
assert_eq!(
conditions.sleep_conditions[0].base.as_ref().unwrap().action,
v1::Action::Queue as i32
);
assert_eq!(conditions.user_event_conditions.len(), 2);
let actions: Vec<i32> = conditions
.user_event_conditions
.iter()
.map(|condition| condition.base.as_ref().unwrap().action)
.collect();
assert_eq!(
actions,
[v1::Action::Skip as i32, v1::Action::Cancel as i32]
);
}
#[test]
fn no_conditions_at_all_send_no_task_conditions() {
let empty = ConditionSet::default();
assert_eq!(to_proto("", gates(&empty, &empty, &empty)), None);
assert!(validate(gates(&empty, &empty, &empty)).is_ok());
}
#[test]
fn an_or_group_shares_one_id_and_lone_conditions_do_not() {
let set = ConditionSet::from(any_of([
Condition::sleep(Duration::from_secs(60)),
Condition::on_event("go"),
]))
.and(Condition::on_event("other"));
let conditions = only(set);
let sleep_group = conditions.sleep_conditions[0]
.base
.as_ref()
.unwrap()
.or_group_id
.clone();
let groups: Vec<String> = conditions
.user_event_conditions
.iter()
.map(|condition| condition.base.as_ref().unwrap().or_group_id.clone())
.collect();
assert_eq!(groups[0], sleep_group, "the or-group members share an id");
assert_ne!(groups[1], sleep_group, "a lone condition gets its own id");
assert_eq!(sleep_group.len(), 36, "a UUID string: {sleep_group}");
assert!(
sleep_group
.chars()
.all(|c| c.is_ascii_hexdigit() || c == '-'),
"a UUID string: {sleep_group}"
);
let version = sleep_group.as_bytes()[14] as char;
assert_eq!(version, '4', "a version 4 UUID: {sleep_group}");
}
#[test]
fn a_list_of_conditions_ands_them_but_any_of_ors_them() {
let anded = ConditionSet::from([
Condition::on_event("a"),
Condition::on_event("b"),
Condition::on_event("c"),
]);
let ids: Vec<String> = only(anded)
.user_event_conditions
.iter()
.map(|condition| condition.base.as_ref().unwrap().or_group_id.clone())
.collect();
let distinct: HashSet<&String> = ids.iter().collect();
assert_eq!(distinct.len(), 3, "each gets its own group: {ids:?}");
let ored = ConditionSet::from(any_of([
Condition::on_event("a"),
Condition::on_event("b"),
Condition::on_event("c"),
]));
let ids: Vec<String> = only(ored)
.user_event_conditions
.iter()
.map(|condition| condition.base.as_ref().unwrap().or_group_id.clone())
.collect();
let distinct: HashSet<&String> = ids.iter().collect();
assert_eq!(distinct.len(), 1, "one group for all of them: {ids:?}");
}
#[test]
fn a_list_of_or_groups_ands_the_groups() {
let set = ConditionSet::from([
any_of([Condition::on_event("a"), Condition::on_event("b")]),
any_of([Condition::on_event("c")]),
]);
let ids: Vec<String> = only(set)
.user_event_conditions
.iter()
.map(|condition| condition.base.as_ref().unwrap().or_group_id.clone())
.collect();
assert_eq!(ids[0], ids[1], "the first group's members share an id");
assert_ne!(ids[2], ids[0], "the second group is its own: {ids:?}");
}
#[test]
fn two_mappings_of_the_same_set_use_different_group_ids() {
let set: ConditionSet = Condition::sleep(Duration::from_secs(1)).into();
let first = only(set.clone());
let second = only(set);
assert_ne!(
first.sleep_conditions[0].base.as_ref().unwrap().or_group_id,
second.sleep_conditions[0]
.base
.as_ref()
.unwrap()
.or_group_id,
);
}
#[test]
fn duplicate_readable_keys_are_rejected_across_all_three_gates() {
let wait_for: ConditionSet = Condition::sleep(Duration::from_secs(5)).into();
let skip_if: ConditionSet = Condition::sleep(Duration::from_secs(5)).into();
let empty = ConditionSet::default();
let Err(reason) = validate(gates(&wait_for, &skip_if, &empty)) else {
panic!("two conditions with the same key should be rejected");
};
assert!(reason.contains("sleep:5000ms"), "{reason}");
assert!(reason.contains("readable_key"), "{reason}");
}
#[test]
fn a_readable_key_of_its_own_settles_a_duplicate() {
let wait_for: ConditionSet = Condition::sleep(Duration::from_secs(5)).into();
let skip_if: ConditionSet = Condition::sleep(Duration::from_secs(5))
.readable_key("give-up")
.into();
let empty = ConditionSet::default();
assert!(validate(gates(&wait_for, &skip_if, &empty)).is_ok());
}
#[test]
fn a_condition_option_that_does_not_fit_its_kind_is_rejected() {
let empty = ConditionSet::default();
for (set, expected) in [
(
ConditionSet::from(Condition::sleep(Duration::from_secs(1)).expression("x")),
"expression",
),
(
ConditionSet::from(Condition::parent_by_name("fetch").scope("s")),
"scope",
),
(
ConditionSet::from(
Condition::sleep(Duration::from_secs(1)).since(SystemTime::UNIX_EPOCH),
),
"since",
),
(
ConditionSet::from(Condition::on_event("go").since(SystemTime::UNIX_EPOCH)),
"scope",
),
(ConditionSet::from(Condition::sleep(Duration::ZERO)), "zero"),
(
ConditionSet::from(Condition::sleep(Duration::from_micros(500))),
"zero",
),
(
ConditionSet::from(Condition::sleep(Duration::from_nanos(1))),
"zero",
),
(ConditionSet::from(any_of([])), "at least one"),
] {
let Err(reason) = validate(gates(&set, &empty, &empty)) else {
panic!("expected a rejection mentioning {expected}");
};
assert!(reason.contains(expected), "{reason} (expected {expected})");
}
}
#[test]
fn a_since_before_the_epoch_is_rejected() {
let set = ConditionSet::from(
Condition::on_event("go")
.scope("s")
.since(UNIX_EPOCH - Duration::from_secs(1)),
);
let empty = ConditionSet::default();
let Err(reason) = validate(gates(&set, &empty, &empty)) else {
panic!("a `since` before 1970 should be rejected");
};
assert!(reason.contains("1970"), "{reason}");
}
#[test]
fn a_sleep_or_event_skip_or_cancel_without_a_wait_for_is_rejected() {
let empty = ConditionSet::default();
for (skip_if, cancel_if, expected) in [
(
ConditionSet::from(Condition::on_event("skip")),
ConditionSet::default(),
"skip_if",
),
(
ConditionSet::default(),
ConditionSet::from(Condition::sleep(Duration::from_secs(5))),
"cancel_if",
),
] {
let Err(reason) = validate(gates(&empty, &skip_if, &cancel_if)) else {
panic!("expected a rejection mentioning {expected}");
};
assert!(reason.contains(expected), "{reason}");
assert!(reason.contains("wait_for"), "{reason}");
let wait_for = ConditionSet::from(Condition::sleep(Duration::from_secs(9)));
assert!(
validate(gates(&wait_for, &skip_if, &cancel_if)).is_ok(),
"a wait_for settles it"
);
}
}
#[test]
fn a_parent_skip_or_cancel_needs_no_wait_for() {
let empty = ConditionSet::default();
let skip_if = ConditionSet::from(Condition::parent_by_name("fetch").expression("output.x"));
assert!(validate(gates(&empty, &skip_if, &empty)).is_ok());
}
#[test]
fn a_wait_for_of_parent_conditions_alone_does_not_pair_with_an_event_skip_if() {
let empty = ConditionSet::default();
let wait_for =
ConditionSet::from(Condition::parent_by_name("start").expression("output.n"));
let skip_if = ConditionSet::from(Condition::on_event("never"));
let Err(reason) = validate(gates(&wait_for, &skip_if, &empty)) else {
panic!("a parent-only `wait_for` does not release an event `skip_if`");
};
assert!(reason.contains("skip_if"), "{reason}");
assert!(
reason.contains("sleep or an event"),
"the message must say what to add: {reason}"
);
}
#[test]
fn a_sleep_or_event_wait_for_does_pair_with_a_sleep_or_event_skip_or_cancel() {
let empty = ConditionSet::default();
let sleeping = ConditionSet::from(Condition::sleep(Duration::from_secs(9)));
let skip_if = ConditionSet::from(Condition::on_event("never"));
assert!(validate(gates(&sleeping, &skip_if, &empty)).is_ok());
let on_event = ConditionSet::from(Condition::on_event("go"));
let cancel_if = ConditionSet::from(Condition::sleep(Duration::from_secs(30)));
assert!(validate(gates(&on_event, &empty, &cancel_if)).is_ok());
let mixed = ConditionSet::from(Condition::parent_by_name("start"))
.and(Condition::sleep(Duration::from_secs(9)));
assert!(validate(gates(&mixed, &skip_if, &empty)).is_ok());
}
#[test]
fn parent_conditions_on_one_parent_with_different_expressions_get_different_keys() {
let wait_for =
ConditionSet::from(Condition::parent_by_name("fetch").expression("output.a"));
let skip_if = ConditionSet::from(Condition::parent_by_name("fetch").expression("output.b"));
let empty = ConditionSet::default();
assert!(
validate(gates(&wait_for, &skip_if, &empty)).is_ok(),
"the expression is part of the default key"
);
let conditions =
to_proto("", gates(&wait_for, &skip_if, &empty)).expect("two parent conditions");
let keys: Vec<&str> = conditions
.parent_override_conditions
.iter()
.map(|condition| condition.base.as_ref().unwrap().readable_data_key.as_str())
.collect();
assert_eq!(keys, ["fetch:output.a", "fetch:output.b"]);
for condition in &conditions.parent_override_conditions {
assert_eq!(condition.parent_readable_id, "fetch");
}
}
#[test]
fn a_parent_condition_without_an_expression_keeps_the_bare_parent_name() {
let conditions = only(Condition::parent_by_name("fetch").into());
let base = conditions.parent_override_conditions[0]
.base
.as_ref()
.expect("a base condition");
assert_eq!(base.readable_data_key, "fetch");
}
#[test]
fn two_identical_parent_conditions_still_need_a_readable_key_of_their_own() {
let wait_for =
ConditionSet::from(Condition::parent_by_name("fetch").expression("output.a"));
let skip_if = ConditionSet::from(Condition::parent_by_name("fetch").expression("output.a"));
let empty = ConditionSet::default();
let Err(reason) = validate(gates(&wait_for, &skip_if, &empty)) else {
panic!("the same parent and the same expression is still one key");
};
assert!(reason.contains("fetch:output.a"), "{reason}");
assert!(reason.contains("readable_key"), "{reason}");
}
#[test]
fn a_blank_string_on_a_condition_is_rejected() {
let empty = ConditionSet::default();
for (set, expected) in [
(ConditionSet::from(Condition::on_event("")), "event key"),
(ConditionSet::from(Condition::on_event(" ")), "event key"),
(
ConditionSet::from(Condition::parent_by_name("")),
"parent name",
),
(
ConditionSet::from(Condition::on_event("go").readable_key("")),
"readable key",
),
(
ConditionSet::from(Condition::parent_by_name("fetch").expression("")),
"expression",
),
(
ConditionSet::from(Condition::on_event("go").expression(" \t")),
"expression",
),
] {
let Err(reason) = validate(gates(&set, &empty, &empty)) else {
panic!("expected a rejection mentioning {expected}");
};
assert!(reason.contains(expected), "{reason} (expected {expected})");
assert!(reason.contains("blank"), "{reason}");
}
}
#[test]
fn a_wait_is_named_after_what_it_is_waiting_on() {
assert_eq!(
ConditionSet::from(Condition::on_event("approve")).wait_kind(),
("user_event", "approve".to_string()),
);
assert_eq!(
ConditionSet::from(Condition::sleep(Duration::from_secs(5))).wait_kind(),
("sleep", "sleep:5000ms".to_string()),
);
assert_eq!(
ConditionSet::from(Condition::parent_by_name("fetch")).wait_kind(),
("parent", "fetch".to_string()),
);
assert_eq!(
ConditionSet::from(any_of([
Condition::on_event("zebra"),
Condition::on_event("aardvark"),
]))
.wait_kind(),
("user_event", "aardvark".to_string()),
);
assert_eq!(
ConditionSet::from(any_of([
Condition::on_event("approve"),
Condition::sleep(Duration::from_secs(5)),
]))
.wait_kind()
.0,
"wait_for",
);
assert_eq!(
ConditionSet::default().wait_kind(),
("wait_for", String::new()),
);
}
#[test]
fn parent_names_lists_only_the_parent_conditions() {
let set = ConditionSet::from(any_of([
Condition::parent_by_name("a"),
Condition::on_event("go"),
]))
.and(Condition::parent_by_name("b"));
assert_eq!(set.parent_names().collect::<Vec<_>>(), ["a", "b"]);
}
}