1use std::collections::HashSet;
11use std::time::{Duration, SystemTime, UNIX_EPOCH};
12
13use hatchet_proto::v1;
14use rand::Rng;
15
16use super::task::Task;
17use crate::config::namespace;
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub(crate) enum ConditionAction {
22 Queue,
23 Skip,
24 Cancel,
25}
26
27impl ConditionAction {
28 fn to_proto(self) -> i32 {
29 let action = match self {
30 Self::Queue => v1::Action::Queue,
31 Self::Skip => v1::Action::Skip,
32 Self::Cancel => v1::Action::Cancel,
33 };
34 action as i32
35 }
36
37 fn gate(self) -> &'static str {
39 match self {
40 Self::Queue => "wait_for",
41 Self::Skip => "skip_if",
42 Self::Cancel => "cancel_if",
43 }
44 }
45}
46
47#[derive(Clone, Debug, PartialEq, Eq)]
49enum Kind {
50 Sleep(Duration),
51 Event(String),
52 Parent(String),
53}
54
55#[derive(Clone, Debug, PartialEq, Eq)]
95#[must_use = "a condition gates nothing until it is given to wait_for, skip_if or cancel_if"]
96pub struct Condition {
97 kind: Kind,
98 expression: Option<String>,
99 readable_key: Option<String>,
100 scope: Option<String>,
101 since: Option<SystemTime>,
102}
103
104impl Condition {
105 fn of(kind: Kind) -> Self {
106 Self {
107 kind,
108 expression: None,
109 readable_key: None,
110 scope: None,
111 since: None,
112 }
113 }
114
115 pub fn sleep(duration: Duration) -> Self {
130 Self::of(Kind::Sleep(duration))
131 }
132
133 pub fn on_event(key: impl Into<String>) -> Self {
150 Self::of(Kind::Event(key.into()))
151 }
152
153 pub fn parent<I, O>(parent: &Task<I, O>) -> Self {
158 Self::parent_by_name(parent.name())
159 }
160
161 pub fn parent_by_name(name: impl Into<String>) -> Self {
164 Self::of(Kind::Parent(name.into()))
165 }
166
167 pub fn expression(mut self, expression: impl Into<String>) -> Self {
177 self.expression = Some(expression.into());
178 self
179 }
180
181 pub fn readable_key(mut self, key: impl Into<String>) -> Self {
193 self.readable_key = Some(key.into());
194 self
195 }
196
197 pub fn scope(mut self, scope: impl Into<String>) -> Self {
200 self.scope = Some(scope.into());
201 self
202 }
203
204 pub fn since(mut self, at: SystemTime) -> Self {
209 self.since = Some(at);
210 self
211 }
212
213 fn readable_data_key(&self) -> String {
216 if let Some(key) = &self.readable_key {
217 return key.clone();
218 }
219 match &self.kind {
220 Kind::Sleep(duration) => format!("sleep:{}", duration_expr(*duration)),
221 Kind::Event(key) => key.clone(),
222 Kind::Parent(name) => match &self.expression {
223 Some(expression) => format!("{name}:{expression}"),
224 None => name.clone(),
225 },
226 }
227 }
228
229 pub(crate) fn parent_name(&self) -> Option<&str> {
231 match &self.kind {
232 Kind::Parent(name) => Some(name.as_str()),
233 _ => None,
234 }
235 }
236
237 fn only_gates_queueing(&self) -> bool {
243 matches!(self.kind, Kind::Sleep(_) | Kind::Event(_))
244 }
245
246 fn blank_field(&self) -> Option<&'static str> {
249 let blank = |value: &str| value.trim().is_empty();
250 match &self.kind {
251 Kind::Event(key) if blank(key) => return Some("event key"),
252 Kind::Parent(name) if blank(name) => return Some("parent name"),
253 _ => {}
254 }
255 if self.readable_key.as_deref().is_some_and(blank) {
256 return Some("readable key");
257 }
258 if self.expression.as_deref().is_some_and(blank) {
259 return Some("expression");
260 }
261 if self.scope.as_deref().is_some_and(blank) {
262 return Some("event scope");
263 }
264 None
265 }
266
267 fn invalid_reason(&self) -> Option<String> {
269 let key = self.readable_data_key();
270 if let Some(blank) = self.blank_field() {
275 return Some(if blank == "expression" {
276 "a condition was given a blank expression; leave `expression` off \
277 to match unconditionally"
278 .to_string()
279 } else {
280 format!(
281 "a condition was given a blank {blank}; the engine matches on it \
282 verbatim, so a blank one leaves the task waiting for ever"
283 )
284 });
285 }
286 match &self.kind {
287 Kind::Event(_) => {
288 if self.since.is_some() && self.scope.is_none() {
289 return Some(format!(
290 "the event condition `{key}` sets `since` without `scope`; the \
291 engine considers earlier events only within a scope"
292 ));
293 }
294 return None;
297 }
298 Kind::Sleep(duration) => {
299 if self.expression.is_some() {
300 return Some(format!(
301 "the sleep condition `{key}` sets an expression, which only a \
302 parent or event condition can use"
303 ));
304 }
305 if duration.as_millis() == 0 {
308 return Some(format!(
309 "the sleep condition `{key}` rounds to zero milliseconds, which \
310 is what the engine is sent; a sleep condition must wait for \
311 some time"
312 ));
313 }
314 }
315 Kind::Parent(_) => {}
316 }
317 if self.scope.is_some() {
318 return Some(format!(
319 "the condition `{key}` sets a scope, which only an event condition has"
320 ));
321 }
322 if self.since.is_some() {
323 return Some(format!(
324 "the condition `{key}` sets `since`, which only an event condition has"
325 ));
326 }
327 None
328 }
329}
330
331#[derive(Clone, Debug, PartialEq, Eq)]
334#[must_use = "an or-group gates nothing until it is given to wait_for, skip_if or cancel_if"]
335pub struct OrGroup(Vec<Condition>);
336
337pub fn any_of(conditions: impl IntoIterator<Item = Condition>) -> OrGroup {
357 OrGroup(conditions.into_iter().collect())
358}
359
360#[derive(Clone, Debug, Default, PartialEq, Eq)]
381#[must_use = "a condition set gates nothing until it is given to wait_for, skip_if or cancel_if"]
382pub struct ConditionSet {
383 groups: Vec<Vec<Condition>>,
386}
387
388impl ConditionSet {
389 pub fn and(mut self, more: impl Into<ConditionSet>) -> Self {
391 self.groups.extend(more.into().groups);
392 self
393 }
394
395 pub(crate) fn is_empty(&self) -> bool {
396 self.groups.is_empty()
397 }
398
399 pub(crate) fn extend(&mut self, more: ConditionSet) {
400 self.groups.extend(more.groups);
401 }
402
403 pub(crate) fn parent_names(&self) -> impl Iterator<Item = &str> {
405 self.conditions().filter_map(Condition::parent_name)
406 }
407
408 fn conditions(&self) -> impl Iterator<Item = &Condition> {
409 self.groups.iter().flatten()
410 }
411
412 pub(crate) fn wait_kind(&self) -> (&'static str, String) {
422 let mut kind: Option<&'static str> = None;
423 let mut keys: Vec<String> = Vec::new();
424 for condition in self.conditions() {
425 let this = match condition.kind {
426 Kind::Sleep(_) => "sleep",
427 Kind::Event(_) => "user_event",
428 Kind::Parent(_) => "parent",
429 };
430 kind = Some(match kind {
431 Some(seen) if seen != this => "wait_for",
432 Some(seen) => seen,
433 None => this,
434 });
435 keys.push(condition.readable_data_key());
436 }
437 keys.sort();
438 (
439 kind.unwrap_or("wait_for"),
440 keys.into_iter().next().unwrap_or_default(),
441 )
442 }
443}
444
445impl From<Condition> for ConditionSet {
446 fn from(condition: Condition) -> Self {
447 Self {
448 groups: vec![vec![condition]],
449 }
450 }
451}
452
453impl From<OrGroup> for ConditionSet {
454 fn from(group: OrGroup) -> Self {
455 Self {
456 groups: vec![group.0],
457 }
458 }
459}
460
461impl From<Vec<Condition>> for ConditionSet {
462 fn from(conditions: Vec<Condition>) -> Self {
463 Self {
464 groups: conditions
465 .into_iter()
466 .map(|condition| vec![condition])
467 .collect(),
468 }
469 }
470}
471
472impl<const N: usize> From<[Condition; N]> for ConditionSet {
473 fn from(conditions: [Condition; N]) -> Self {
474 Vec::from(conditions).into()
475 }
476}
477
478impl From<Vec<OrGroup>> for ConditionSet {
479 fn from(groups: Vec<OrGroup>) -> Self {
480 Self {
481 groups: groups.into_iter().map(|group| group.0).collect(),
482 }
483 }
484}
485
486impl<const N: usize> From<[OrGroup; N]> for ConditionSet {
487 fn from(groups: [OrGroup; N]) -> Self {
488 Vec::from(groups).into()
489 }
490}
491
492pub(crate) type Gates<'a> = [(ConditionAction, &'a ConditionSet); 3];
494
495pub(crate) fn validate(gates: Gates<'_>) -> Result<(), String> {
498 let mut keys: HashSet<String> = HashSet::new();
499 for (_, set) in gates {
500 for group in &set.groups {
501 if group.is_empty() {
502 return Err(
503 "an or-group has no conditions; `any_of` needs at least one".to_string()
504 );
505 }
506 }
507 for condition in set.conditions() {
508 if let Some(reason) = condition.invalid_reason() {
509 return Err(reason);
510 }
511 if let Some(at) = condition.since
512 && at.duration_since(UNIX_EPOCH).is_err()
513 {
514 return Err(format!(
515 "the condition `{}` sets `since` to a time before 1970",
516 condition.readable_data_key()
517 ));
518 }
519 let key = condition.readable_data_key();
520 if !keys.insert(key.clone()) {
521 return Err(format!(
522 "two conditions on this task share the readable key `{key}`; the \
523 engine tells them apart by that key, so give one of them its own \
524 with `Condition::readable_key(..)`"
525 ));
526 }
527 }
528 }
529
530 let waits = gates.iter().any(|(action, set)| {
538 *action == ConditionAction::Queue && set.conditions().any(Condition::only_gates_queueing)
539 });
540 if !waits {
541 for (action, set) in gates {
542 if action == ConditionAction::Queue {
543 continue;
544 }
545 if let Some(condition) = set.conditions().find(|c| c.only_gates_queueing()) {
546 return Err(format!(
547 "the `{}` condition `{}` waits on a sleep or an event, but the task \
548 has no `wait_for` that does; the engine only weighs such a \
549 condition while the task waits to be queued, so the task would \
550 never start — add a `wait_for` on a sleep or an event (parents, \
551 and a `wait_for` made only of parent conditions, do not count; a \
552 `skip_if` or `cancel_if` on a parent condition needs no pairing at \
553 all)",
554 action.gate(),
555 condition.readable_data_key()
556 ));
557 }
558 }
559 }
560
561 Ok(())
562}
563
564pub(crate) fn to_proto(namespace: &str, gates: Gates<'_>) -> Option<v1::TaskConditions> {
567 let mut conditions = v1::TaskConditions::default();
568 let mut any = false;
569 for (action, set) in gates {
570 for group in &set.groups {
571 let or_group_id = or_group_id();
572 for condition in group {
573 any = true;
574 let base = v1::BaseMatchCondition {
575 readable_data_key: condition.readable_data_key(),
576 action: action.to_proto(),
577 or_group_id: or_group_id.clone(),
578 expression: condition.expression.clone().unwrap_or_default(),
579 };
580 match &condition.kind {
581 Kind::Sleep(duration) => {
582 conditions.sleep_conditions.push(v1::SleepMatchCondition {
583 base: Some(base),
584 sleep_for: duration_expr(*duration),
585 });
586 }
587 Kind::Event(key) => {
588 conditions
589 .user_event_conditions
590 .push(v1::UserEventMatchCondition {
591 base: Some(base),
592 user_event_key: namespace::apply(namespace, key),
593 event_scope: condition.scope.clone(),
594 consider_events_since: condition.since.map(timestamp),
595 });
596 }
597 Kind::Parent(name) => {
598 conditions.parent_override_conditions.push(
599 v1::ParentOverrideMatchCondition {
600 base: Some(base),
601 parent_readable_id: name.clone(),
602 },
603 );
604 }
605 }
606 }
607 }
608 }
609 any.then_some(conditions)
610}
611
612pub(crate) fn to_durable_proto(
637 namespace: &str,
638 conditions: &ConditionSet,
639) -> Result<v1::DurableEventListenerConditions, String> {
640 if conditions.is_empty() {
641 return Err("a durable wait needs at least one condition".to_string());
642 }
643
644 let mut keys: HashSet<String> = HashSet::new();
645 let mut mapped = v1::DurableEventListenerConditions::default();
646 for group in &conditions.groups {
647 if group.is_empty() {
648 return Err("an or-group has no conditions; `any_of` needs at least one".to_string());
649 }
650 let or_group_id = or_group_id();
651 for condition in group {
652 if let Some(reason) = condition.invalid_reason() {
653 return Err(reason);
654 }
655 if let Some(at) = condition.since
656 && at.duration_since(UNIX_EPOCH).is_err()
657 {
658 return Err(format!(
659 "the condition `{}` sets `since` to a time before 1970",
660 condition.readable_data_key()
661 ));
662 }
663 let key = condition.readable_data_key();
664 if !keys.insert(key.clone()) {
665 return Err(format!(
666 "two conditions of one durable wait share the readable_key `{key}`; the \
667 engine indexes the wait's result by that key, so one of the matches \
668 would be lost — give one of them its own with \
669 `Condition::readable_key(..)`"
670 ));
671 }
672 let base = v1::BaseMatchCondition {
673 readable_data_key: key,
674 action: v1::Action::Create as i32,
675 or_group_id: or_group_id.clone(),
676 expression: condition.expression.clone().unwrap_or_default(),
677 };
678 match &condition.kind {
679 Kind::Sleep(duration) => mapped.sleep_conditions.push(v1::SleepMatchCondition {
680 base: Some(base),
681 sleep_for: duration_expr(*duration),
682 }),
683 Kind::Event(event) => {
684 mapped
685 .user_event_conditions
686 .push(v1::UserEventMatchCondition {
687 base: Some(base),
688 user_event_key: namespace::apply(namespace, event),
689 event_scope: condition.scope.clone(),
690 consider_events_since: condition.since.map(timestamp),
691 });
692 }
693 Kind::Parent(name) => {
694 return Err(format!(
695 "the durable wait names the parent task `{name}`, but a durable wait \
696 cannot read a parent: the engine takes only sleep and event \
697 conditions here. Read the parent's output with \
698 `Context::parent_output` instead, or gate the task itself with \
699 `TaskBuilder::wait_for`"
700 ));
701 }
702 }
703 }
704 }
705 Ok(mapped)
706}
707
708fn duration_expr(duration: Duration) -> String {
713 format!("{}ms", duration.as_millis())
714}
715
716fn timestamp(at: SystemTime) -> hatchet_proto::prost_types::Timestamp {
722 let since_epoch = at.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO);
723 hatchet_proto::prost_types::Timestamp {
724 seconds: i64::try_from(since_epoch.as_secs()).unwrap_or(i64::MAX),
725 nanos: i32::try_from(since_epoch.subsec_nanos()).unwrap_or(0),
726 }
727}
728
729fn or_group_id() -> String {
736 let mut bytes = rand::rng().random::<u128>().to_be_bytes();
737 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() };
740 format!(
741 "{}-{}-{}-{}-{}",
742 hex(&bytes[0..4]),
743 hex(&bytes[4..6]),
744 hex(&bytes[6..8]),
745 hex(&bytes[8..10]),
746 hex(&bytes[10..16])
747 )
748}
749
750#[cfg(test)]
751mod tests {
752 use super::*;
753 use crate::TaskBuilder;
754
755 fn gates<'a>(
756 wait_for: &'a ConditionSet,
757 skip_if: &'a ConditionSet,
758 cancel_if: &'a ConditionSet,
759 ) -> Gates<'a> {
760 [
761 (ConditionAction::Queue, wait_for),
762 (ConditionAction::Skip, skip_if),
763 (ConditionAction::Cancel, cancel_if),
764 ]
765 }
766
767 fn only(set: ConditionSet) -> v1::TaskConditions {
768 let empty = ConditionSet::default();
769 to_proto("dev_", gates(&set, &empty, &empty)).expect("the set is not empty")
770 }
771
772 #[test]
773 fn durable_conditions_are_create_conditions_without_parents() {
774 let set = ConditionSet::from(Condition::sleep(Duration::from_secs(30)))
775 .and(Condition::on_event("go"));
776 let conditions = to_durable_proto("dev_", &set).expect("a valid durable wait");
777
778 let sleep = &conditions.sleep_conditions[0];
779 assert_eq!(sleep.sleep_for, "30000ms");
780 let base = sleep.base.as_ref().expect("a base condition");
781 assert_eq!(base.readable_data_key, "sleep:30000ms");
782 assert_eq!(base.action, v1::Action::Create as i32);
783
784 let event = &conditions.user_event_conditions[0];
785 assert_eq!(event.user_event_key, "dev_go");
786 let base = event.base.as_ref().expect("a base condition");
789 assert_eq!(base.readable_data_key, "go");
790 assert_eq!(base.action, v1::Action::Create as i32);
791 }
792
793 #[test]
794 fn a_durable_or_group_shares_one_group_id() {
795 let set = ConditionSet::from(any_of([
796 Condition::on_event("go"),
797 Condition::sleep(Duration::from_secs(5)),
798 ]));
799 let conditions = to_durable_proto("dev_", &set).expect("a valid durable wait");
800 let event = conditions.user_event_conditions[0]
801 .base
802 .as_ref()
803 .expect("a base condition");
804 let sleep = conditions.sleep_conditions[0]
805 .base
806 .as_ref()
807 .expect("a base condition");
808 assert_eq!(event.or_group_id, sleep.or_group_id);
809 assert!(!event.or_group_id.is_empty());
810 }
811
812 #[test]
813 fn a_parent_condition_cannot_be_waited_for_durably() {
814 let reason = to_durable_proto(
815 "dev_",
816 &ConditionSet::from(Condition::parent_by_name("fetch")),
817 )
818 .expect_err("parents are not durable conditions");
819 assert!(reason.contains("parent"), "{reason}");
820 }
821
822 #[test]
823 fn a_durable_wait_needs_at_least_one_condition_and_unique_keys() {
824 assert!(to_durable_proto("dev_", &ConditionSet::default()).is_err());
825 let twice = ConditionSet::from(Condition::sleep(Duration::from_secs(5)))
826 .and(Condition::sleep(Duration::from_secs(5)));
827 let reason = to_durable_proto("dev_", &twice).expect_err("duplicate readable keys");
828 assert!(reason.contains("readable_key"), "{reason}");
829
830 let renamed = ConditionSet::from(Condition::sleep(Duration::from_secs(5)))
832 .and(Condition::sleep(Duration::from_secs(5)).readable_key("second"));
833 assert!(to_durable_proto("dev_", &renamed).is_ok());
834 }
835
836 #[test]
837 fn a_durable_wait_rejects_what_an_invalid_condition_would_hide() {
838 let blank = to_durable_proto("dev_", &ConditionSet::from(Condition::on_event(" ")))
839 .expect_err("a blank event key is a mistake");
840 assert!(blank.contains("blank"), "{blank}");
841 }
842
843 #[test]
844 fn a_sleep_condition_maps_to_a_sleep_match_condition() {
845 let conditions = only(Condition::sleep(Duration::from_secs(30)).into());
846 assert!(conditions.user_event_conditions.is_empty());
847 assert!(conditions.parent_override_conditions.is_empty());
848 let [sleep] = conditions.sleep_conditions.as_slice() else {
849 panic!("exactly one sleep condition: {conditions:?}");
850 };
851 assert_eq!(sleep.sleep_for, "30000ms");
852 let base = sleep.base.as_ref().expect("a base condition");
853 assert_eq!(base.action, v1::Action::Queue as i32);
854 assert_eq!(base.readable_data_key, "sleep:30000ms");
855 assert_eq!(base.expression, "");
856 assert!(
857 !base.or_group_id.is_empty(),
858 "every condition gets a group id"
859 );
860 }
861
862 #[test]
863 fn a_sub_second_sleep_keeps_its_milliseconds() {
864 let conditions = only(Condition::sleep(Duration::from_millis(1500)).into());
865 assert_eq!(conditions.sleep_conditions[0].sleep_for, "1500ms");
866 }
867
868 #[test]
869 fn an_event_condition_is_namespaced_but_its_readable_key_is_not() {
870 let conditions = only(
871 Condition::on_event("approval.granted")
872 .expression("input.ok == true")
873 .scope("tenant-1")
874 .into(),
875 );
876 let [event] = conditions.user_event_conditions.as_slice() else {
877 panic!("exactly one user event condition: {conditions:?}");
878 };
879 assert_eq!(event.user_event_key, "dev_approval.granted");
880 assert_eq!(event.event_scope.as_deref(), Some("tenant-1"));
881 assert_eq!(event.consider_events_since, None);
882 let base = event.base.as_ref().expect("a base condition");
883 assert_eq!(base.readable_data_key, "approval.granted");
884 assert_eq!(base.expression, "input.ok == true");
885 }
886
887 #[test]
888 fn an_event_key_that_already_carries_the_namespace_is_not_prefixed_twice() {
889 let conditions = only(Condition::on_event("dev_go").into());
890 let [event] = conditions.user_event_conditions.as_slice() else {
891 panic!("one condition: {conditions:?}");
892 };
893 assert_eq!(event.user_event_key, "dev_go");
894 }
895
896 #[test]
897 fn an_events_since_is_sent_as_a_timestamp() {
898 let at = UNIX_EPOCH + Duration::new(1_700_000_000, 250);
899 let conditions = only(Condition::on_event("go").scope("s").since(at).into());
900 assert_eq!(
901 conditions.user_event_conditions[0].consider_events_since,
902 Some(hatchet_proto::prost_types::Timestamp {
903 seconds: 1_700_000_000,
904 nanos: 250,
905 })
906 );
907 }
908
909 #[test]
910 fn a_parent_condition_names_the_parent_and_folds_its_expression_into_its_key() {
911 let fetch = TaskBuilder::<(), u32>::new("fetch").handler(|_ctx, _input| async { Ok(1) });
912 let conditions = only(
913 Condition::parent(&fetch)
914 .expression("output.count > 0")
915 .into(),
916 );
917 let [parent] = conditions.parent_override_conditions.as_slice() else {
918 panic!("exactly one parent condition: {conditions:?}");
919 };
920 assert_eq!(parent.parent_readable_id, "fetch");
921 let base = parent.base.as_ref().expect("a base condition");
922 assert_eq!(base.readable_data_key, "fetch:output.count > 0");
923 assert_eq!(base.expression, "output.count > 0");
924 }
925
926 #[test]
927 fn an_explicit_readable_key_wins_over_the_default() {
928 let conditions = only(
929 Condition::sleep(Duration::from_secs(1))
930 .readable_key("first-wait")
931 .into(),
932 );
933 let base = conditions.sleep_conditions[0]
934 .base
935 .as_ref()
936 .expect("a base condition");
937 assert_eq!(base.readable_data_key, "first-wait");
938 }
939
940 #[test]
941 fn the_three_gates_map_to_their_own_actions_in_one_task_conditions() {
942 let wait_for: ConditionSet = Condition::sleep(Duration::from_secs(5)).into();
943 let skip_if: ConditionSet = Condition::on_event("skip").into();
944 let cancel_if: ConditionSet = Condition::on_event("stop").into();
945 let conditions =
946 to_proto("", gates(&wait_for, &skip_if, &cancel_if)).expect("three non-empty gates");
947
948 assert_eq!(conditions.sleep_conditions.len(), 1);
949 assert_eq!(
950 conditions.sleep_conditions[0].base.as_ref().unwrap().action,
951 v1::Action::Queue as i32
952 );
953 assert_eq!(conditions.user_event_conditions.len(), 2);
954 let actions: Vec<i32> = conditions
955 .user_event_conditions
956 .iter()
957 .map(|condition| condition.base.as_ref().unwrap().action)
958 .collect();
959 assert_eq!(
960 actions,
961 [v1::Action::Skip as i32, v1::Action::Cancel as i32]
962 );
963 }
964
965 #[test]
966 fn no_conditions_at_all_send_no_task_conditions() {
967 let empty = ConditionSet::default();
968 assert_eq!(to_proto("", gates(&empty, &empty, &empty)), None);
969 assert!(validate(gates(&empty, &empty, &empty)).is_ok());
970 }
971
972 #[test]
975 fn an_or_group_shares_one_id_and_lone_conditions_do_not() {
976 let set = ConditionSet::from(any_of([
977 Condition::sleep(Duration::from_secs(60)),
978 Condition::on_event("go"),
979 ]))
980 .and(Condition::on_event("other"));
981 let conditions = only(set);
982
983 let sleep_group = conditions.sleep_conditions[0]
984 .base
985 .as_ref()
986 .unwrap()
987 .or_group_id
988 .clone();
989 let groups: Vec<String> = conditions
990 .user_event_conditions
991 .iter()
992 .map(|condition| condition.base.as_ref().unwrap().or_group_id.clone())
993 .collect();
994
995 assert_eq!(groups[0], sleep_group, "the or-group members share an id");
996 assert_ne!(groups[1], sleep_group, "a lone condition gets its own id");
997 assert_eq!(sleep_group.len(), 36, "a UUID string: {sleep_group}");
998 assert!(
999 sleep_group
1000 .chars()
1001 .all(|c| c.is_ascii_hexdigit() || c == '-'),
1002 "a UUID string: {sleep_group}"
1003 );
1004 let version = sleep_group.as_bytes()[14] as char;
1005 assert_eq!(version, '4', "a version 4 UUID: {sleep_group}");
1006 }
1007
1008 #[test]
1009 fn a_list_of_conditions_ands_them_but_any_of_ors_them() {
1010 let anded = ConditionSet::from([
1011 Condition::on_event("a"),
1012 Condition::on_event("b"),
1013 Condition::on_event("c"),
1014 ]);
1015 let ids: Vec<String> = only(anded)
1016 .user_event_conditions
1017 .iter()
1018 .map(|condition| condition.base.as_ref().unwrap().or_group_id.clone())
1019 .collect();
1020 let distinct: HashSet<&String> = ids.iter().collect();
1021 assert_eq!(distinct.len(), 3, "each gets its own group: {ids:?}");
1022
1023 let ored = ConditionSet::from(any_of([
1024 Condition::on_event("a"),
1025 Condition::on_event("b"),
1026 Condition::on_event("c"),
1027 ]));
1028 let ids: Vec<String> = only(ored)
1029 .user_event_conditions
1030 .iter()
1031 .map(|condition| condition.base.as_ref().unwrap().or_group_id.clone())
1032 .collect();
1033 let distinct: HashSet<&String> = ids.iter().collect();
1034 assert_eq!(distinct.len(), 1, "one group for all of them: {ids:?}");
1035 }
1036
1037 #[test]
1038 fn a_list_of_or_groups_ands_the_groups() {
1039 let set = ConditionSet::from([
1040 any_of([Condition::on_event("a"), Condition::on_event("b")]),
1041 any_of([Condition::on_event("c")]),
1042 ]);
1043 let ids: Vec<String> = only(set)
1044 .user_event_conditions
1045 .iter()
1046 .map(|condition| condition.base.as_ref().unwrap().or_group_id.clone())
1047 .collect();
1048 assert_eq!(ids[0], ids[1], "the first group's members share an id");
1049 assert_ne!(ids[2], ids[0], "the second group is its own: {ids:?}");
1050 }
1051
1052 #[test]
1053 fn two_mappings_of_the_same_set_use_different_group_ids() {
1054 let set: ConditionSet = Condition::sleep(Duration::from_secs(1)).into();
1055 let first = only(set.clone());
1056 let second = only(set);
1057 assert_ne!(
1058 first.sleep_conditions[0].base.as_ref().unwrap().or_group_id,
1059 second.sleep_conditions[0]
1060 .base
1061 .as_ref()
1062 .unwrap()
1063 .or_group_id,
1064 );
1065 }
1066
1067 #[test]
1068 fn duplicate_readable_keys_are_rejected_across_all_three_gates() {
1069 let wait_for: ConditionSet = Condition::sleep(Duration::from_secs(5)).into();
1070 let skip_if: ConditionSet = Condition::sleep(Duration::from_secs(5)).into();
1071 let empty = ConditionSet::default();
1072 let Err(reason) = validate(gates(&wait_for, &skip_if, &empty)) else {
1073 panic!("two conditions with the same key should be rejected");
1074 };
1075 assert!(reason.contains("sleep:5000ms"), "{reason}");
1076 assert!(reason.contains("readable_key"), "{reason}");
1077 }
1078
1079 #[test]
1080 fn a_readable_key_of_its_own_settles_a_duplicate() {
1081 let wait_for: ConditionSet = Condition::sleep(Duration::from_secs(5)).into();
1082 let skip_if: ConditionSet = Condition::sleep(Duration::from_secs(5))
1083 .readable_key("give-up")
1084 .into();
1085 let empty = ConditionSet::default();
1086 assert!(validate(gates(&wait_for, &skip_if, &empty)).is_ok());
1087 }
1088
1089 #[test]
1090 fn a_condition_option_that_does_not_fit_its_kind_is_rejected() {
1091 let empty = ConditionSet::default();
1092 for (set, expected) in [
1093 (
1094 ConditionSet::from(Condition::sleep(Duration::from_secs(1)).expression("x")),
1095 "expression",
1096 ),
1097 (
1098 ConditionSet::from(Condition::parent_by_name("fetch").scope("s")),
1099 "scope",
1100 ),
1101 (
1102 ConditionSet::from(
1103 Condition::sleep(Duration::from_secs(1)).since(SystemTime::UNIX_EPOCH),
1104 ),
1105 "since",
1106 ),
1107 (
1108 ConditionSet::from(Condition::on_event("go").since(SystemTime::UNIX_EPOCH)),
1109 "scope",
1110 ),
1111 (ConditionSet::from(Condition::sleep(Duration::ZERO)), "zero"),
1112 (
1115 ConditionSet::from(Condition::sleep(Duration::from_micros(500))),
1116 "zero",
1117 ),
1118 (
1119 ConditionSet::from(Condition::sleep(Duration::from_nanos(1))),
1120 "zero",
1121 ),
1122 (ConditionSet::from(any_of([])), "at least one"),
1123 ] {
1124 let Err(reason) = validate(gates(&set, &empty, &empty)) else {
1125 panic!("expected a rejection mentioning {expected}");
1126 };
1127 assert!(reason.contains(expected), "{reason} (expected {expected})");
1128 }
1129 }
1130
1131 #[test]
1132 fn a_since_before_the_epoch_is_rejected() {
1133 let set = ConditionSet::from(
1134 Condition::on_event("go")
1135 .scope("s")
1136 .since(UNIX_EPOCH - Duration::from_secs(1)),
1137 );
1138 let empty = ConditionSet::default();
1139 let Err(reason) = validate(gates(&set, &empty, &empty)) else {
1140 panic!("a `since` before 1970 should be rejected");
1141 };
1142 assert!(reason.contains("1970"), "{reason}");
1143 }
1144
1145 #[test]
1149 fn a_sleep_or_event_skip_or_cancel_without_a_wait_for_is_rejected() {
1150 let empty = ConditionSet::default();
1151 for (skip_if, cancel_if, expected) in [
1152 (
1153 ConditionSet::from(Condition::on_event("skip")),
1154 ConditionSet::default(),
1155 "skip_if",
1156 ),
1157 (
1158 ConditionSet::default(),
1159 ConditionSet::from(Condition::sleep(Duration::from_secs(5))),
1160 "cancel_if",
1161 ),
1162 ] {
1163 let Err(reason) = validate(gates(&empty, &skip_if, &cancel_if)) else {
1164 panic!("expected a rejection mentioning {expected}");
1165 };
1166 assert!(reason.contains(expected), "{reason}");
1167 assert!(reason.contains("wait_for"), "{reason}");
1168
1169 let wait_for = ConditionSet::from(Condition::sleep(Duration::from_secs(9)));
1170 assert!(
1171 validate(gates(&wait_for, &skip_if, &cancel_if)).is_ok(),
1172 "a wait_for settles it"
1173 );
1174 }
1175 }
1176
1177 #[test]
1178 fn a_parent_skip_or_cancel_needs_no_wait_for() {
1179 let empty = ConditionSet::default();
1180 let skip_if = ConditionSet::from(Condition::parent_by_name("fetch").expression("output.x"));
1181 assert!(validate(gates(&empty, &skip_if, &empty)).is_ok());
1182 }
1183
1184 #[test]
1189 fn a_wait_for_of_parent_conditions_alone_does_not_pair_with_an_event_skip_if() {
1190 let empty = ConditionSet::default();
1191 let wait_for =
1192 ConditionSet::from(Condition::parent_by_name("start").expression("output.n"));
1193 let skip_if = ConditionSet::from(Condition::on_event("never"));
1194 let Err(reason) = validate(gates(&wait_for, &skip_if, &empty)) else {
1195 panic!("a parent-only `wait_for` does not release an event `skip_if`");
1196 };
1197 assert!(reason.contains("skip_if"), "{reason}");
1198 assert!(
1199 reason.contains("sleep or an event"),
1200 "the message must say what to add: {reason}"
1201 );
1202 }
1203
1204 #[test]
1205 fn a_sleep_or_event_wait_for_does_pair_with_a_sleep_or_event_skip_or_cancel() {
1206 let empty = ConditionSet::default();
1207
1208 let sleeping = ConditionSet::from(Condition::sleep(Duration::from_secs(9)));
1209 let skip_if = ConditionSet::from(Condition::on_event("never"));
1210 assert!(validate(gates(&sleeping, &skip_if, &empty)).is_ok());
1211
1212 let on_event = ConditionSet::from(Condition::on_event("go"));
1213 let cancel_if = ConditionSet::from(Condition::sleep(Duration::from_secs(30)));
1214 assert!(validate(gates(&on_event, &empty, &cancel_if)).is_ok());
1215
1216 let mixed = ConditionSet::from(Condition::parent_by_name("start"))
1219 .and(Condition::sleep(Duration::from_secs(9)));
1220 assert!(validate(gates(&mixed, &skip_if, &empty)).is_ok());
1221 }
1222
1223 #[test]
1226 fn parent_conditions_on_one_parent_with_different_expressions_get_different_keys() {
1227 let wait_for =
1228 ConditionSet::from(Condition::parent_by_name("fetch").expression("output.a"));
1229 let skip_if = ConditionSet::from(Condition::parent_by_name("fetch").expression("output.b"));
1230 let empty = ConditionSet::default();
1231 assert!(
1232 validate(gates(&wait_for, &skip_if, &empty)).is_ok(),
1233 "the expression is part of the default key"
1234 );
1235
1236 let conditions =
1237 to_proto("", gates(&wait_for, &skip_if, &empty)).expect("two parent conditions");
1238 let keys: Vec<&str> = conditions
1239 .parent_override_conditions
1240 .iter()
1241 .map(|condition| condition.base.as_ref().unwrap().readable_data_key.as_str())
1242 .collect();
1243 assert_eq!(keys, ["fetch:output.a", "fetch:output.b"]);
1244 for condition in &conditions.parent_override_conditions {
1245 assert_eq!(condition.parent_readable_id, "fetch");
1246 }
1247 }
1248
1249 #[test]
1250 fn a_parent_condition_without_an_expression_keeps_the_bare_parent_name() {
1251 let conditions = only(Condition::parent_by_name("fetch").into());
1252 let base = conditions.parent_override_conditions[0]
1253 .base
1254 .as_ref()
1255 .expect("a base condition");
1256 assert_eq!(base.readable_data_key, "fetch");
1257 }
1258
1259 #[test]
1260 fn two_identical_parent_conditions_still_need_a_readable_key_of_their_own() {
1261 let wait_for =
1262 ConditionSet::from(Condition::parent_by_name("fetch").expression("output.a"));
1263 let skip_if = ConditionSet::from(Condition::parent_by_name("fetch").expression("output.a"));
1264 let empty = ConditionSet::default();
1265 let Err(reason) = validate(gates(&wait_for, &skip_if, &empty)) else {
1266 panic!("the same parent and the same expression is still one key");
1267 };
1268 assert!(reason.contains("fetch:output.a"), "{reason}");
1269 assert!(reason.contains("readable_key"), "{reason}");
1270 }
1271
1272 #[test]
1273 fn a_blank_string_on_a_condition_is_rejected() {
1274 let empty = ConditionSet::default();
1275 for (set, expected) in [
1276 (ConditionSet::from(Condition::on_event("")), "event key"),
1277 (ConditionSet::from(Condition::on_event(" ")), "event key"),
1278 (
1279 ConditionSet::from(Condition::parent_by_name("")),
1280 "parent name",
1281 ),
1282 (
1283 ConditionSet::from(Condition::on_event("go").readable_key("")),
1284 "readable key",
1285 ),
1286 (
1287 ConditionSet::from(Condition::parent_by_name("fetch").expression("")),
1288 "expression",
1289 ),
1290 (
1291 ConditionSet::from(Condition::on_event("go").expression(" \t")),
1292 "expression",
1293 ),
1294 ] {
1295 let Err(reason) = validate(gates(&set, &empty, &empty)) else {
1296 panic!("expected a rejection mentioning {expected}");
1297 };
1298 assert!(reason.contains(expected), "{reason} (expected {expected})");
1299 assert!(reason.contains("blank"), "{reason}");
1300 }
1301 }
1302
1303 #[test]
1304 fn a_wait_is_named_after_what_it_is_waiting_on() {
1305 assert_eq!(
1306 ConditionSet::from(Condition::on_event("approve")).wait_kind(),
1307 ("user_event", "approve".to_string()),
1308 );
1309 assert_eq!(
1310 ConditionSet::from(Condition::sleep(Duration::from_secs(5))).wait_kind(),
1311 ("sleep", "sleep:5000ms".to_string()),
1312 );
1313 assert_eq!(
1314 ConditionSet::from(Condition::parent_by_name("fetch")).wait_kind(),
1315 ("parent", "fetch".to_string()),
1316 );
1317 assert_eq!(
1320 ConditionSet::from(any_of([
1321 Condition::on_event("zebra"),
1322 Condition::on_event("aardvark"),
1323 ]))
1324 .wait_kind(),
1325 ("user_event", "aardvark".to_string()),
1326 );
1327 assert_eq!(
1329 ConditionSet::from(any_of([
1330 Condition::on_event("approve"),
1331 Condition::sleep(Duration::from_secs(5)),
1332 ]))
1333 .wait_kind()
1334 .0,
1335 "wait_for",
1336 );
1337 assert_eq!(
1338 ConditionSet::default().wait_kind(),
1339 ("wait_for", String::new()),
1340 );
1341 }
1342
1343 #[test]
1344 fn parent_names_lists_only_the_parent_conditions() {
1345 let set = ConditionSet::from(any_of([
1346 Condition::parent_by_name("a"),
1347 Condition::on_event("go"),
1348 ]))
1349 .and(Condition::parent_by_name("b"));
1350 assert_eq!(set.parent_names().collect::<Vec<_>>(), ["a", "b"]);
1351 }
1352}