Skip to main content

hatchet_client/declare/
condition.rs

1//! Conditions: when a task may start, when it is skipped, and when it is
2//! cancelled.
3//!
4//! All three gates travel in one wire field — `CreateTaskOpts.conditions`,
5//! a [`TaskConditions`](hatchet_proto::v1::TaskConditions) split by *kind*
6//! (sleep, user event, parent) rather than by gate. What separates them is
7//! `BaseMatchCondition.action`: `QUEUE` for `wait_for`, `SKIP` for `skip_if`,
8//! `CANCEL` for `cancel_if`.
9
10use 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/// Which gate a condition belongs to, as the engine's `Action` enum.
20#[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    /// The builder method this gate is set with, for error messages.
38    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/// What a condition waits on.
48#[derive(Clone, Debug, PartialEq, Eq)]
49enum Kind {
50    Sleep(Duration),
51    Event(String),
52    Parent(String),
53}
54
55/// One thing a task can wait on, be skipped by, or be cancelled by.
56///
57/// Build one with [`sleep`](Condition::sleep),
58/// [`on_event`](Condition::on_event) or [`parent`](Condition::parent), then
59/// give it to [`TaskBuilder::wait_for`](crate::TaskBuilder::wait_for),
60/// [`skip_if`](crate::TaskBuilder::skip_if) or
61/// [`cancel_if`](crate::TaskBuilder::cancel_if). Several conditions on one
62/// gate must *all* be satisfied; wrap them in [`any_of`] for "any one of
63/// these".
64///
65/// A sleep or event condition is a gate on *queueing*, so a task whose only
66/// conditions are a `skip_if` or `cancel_if` of that kind would never start
67/// at all; one is always paired with a `wait_for` that is itself a sleep or
68/// an event. A `wait_for` made only of parent conditions does not release it
69/// — that was measured, and is why the declaration is rejected.
70///
71/// Mistakes — an option that does not fit the kind, two conditions on one
72/// task sharing a readable key, a `skip_if` that could never be reached —
73/// are reported as
74/// [`Error::InvalidDeclaration`](crate::Error::InvalidDeclaration) when the
75/// task is registered, never as a panic.
76///
77/// ```
78/// use std::time::Duration;
79///
80/// use hatchet_client::{Condition, TaskBuilder, any_of};
81///
82/// let review = TaskBuilder::<(), ()>::new("review")
83///     // Start when the reviewer approves, or after an hour, whichever
84///     // comes first.
85///     .wait_for(any_of([
86///         Condition::on_event("review.approved"),
87///         Condition::sleep(Duration::from_secs(3600)),
88///     ]))
89///     // Never run at all if the change was withdrawn first.
90///     .skip_if(Condition::on_event("review.withdrawn"))
91///     .handler(|_ctx, _input| async { Ok(()) });
92/// # let _ = review;
93/// ```
94#[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    /// Satisfied once `duration` has passed since the task became eligible.
116    ///
117    /// For a task with no parents that is the moment the run was *triggered*,
118    /// not the moment the engine got round to it: a six-second sleep was
119    /// measured firing about six seconds after the trigger even though an
120    /// unconditioned sibling in the same run did not start until four
121    /// seconds in.
122    ///
123    /// The engine takes the duration as a string; this SDK sends whole
124    /// milliseconds, as the official Go SDK does, so a duration under one
125    /// millisecond is rejected rather than rounded away. Short sleeps are not
126    /// dependable: against both v0.80.0 and v0.107.0 a one-second sleep
127    /// condition was observed never to fire, while a five-second one fired
128    /// as expected. Prefer a few seconds or more.
129    pub fn sleep(duration: Duration) -> Self {
130        Self::of(Kind::Sleep(duration))
131    }
132
133    /// Satisfied by an event pushed under `key`.
134    ///
135    /// The key is namespaced exactly as
136    /// [`EventsClient::push`](crate::EventsClient::push) namespaces it, so
137    /// `Condition::on_event("go")` is satisfied by `push("go", …)` from a
138    /// client with the same namespace. (The official Go SDK does not
139    /// namespace condition keys; the official Python SDK does, and so does
140    /// this one — otherwise a namespaced client could never satisfy its own
141    /// condition.) A key that already starts with the namespace is left
142    /// alone, so another namespace's events can be waited on by full key.
143    ///
144    /// A condition still waiting is weighed against every later push of the
145    /// same key, not only the first: an [`expression`](Condition::expression)
146    /// that a push failed to satisfy leaves the condition pending, and a
147    /// subsequent push that does satisfy it releases the task (measured on
148    /// both supported engines).
149    pub fn on_event(key: impl Into<String>) -> Self {
150        Self::of(Kind::Event(key.into()))
151    }
152
153    /// Satisfied by what `parent` produced, judged by
154    /// [`expression`](Condition::expression) over `output`.
155    ///
156    /// `parent` must be a parent of the task this condition is put on.
157    pub fn parent<I, O>(parent: &Task<I, O>) -> Self {
158        Self::parent_by_name(parent.name())
159    }
160
161    /// Like [`Condition::parent`], but naming the parent rather than
162    /// borrowing its handle — for a parent declared elsewhere.
163    pub fn parent_by_name(name: impl Into<String>) -> Self {
164        Self::of(Kind::Parent(name.into()))
165    }
166
167    /// The CEL expression that decides whether the condition is satisfied.
168    ///
169    /// A parent condition reads the parent's output as `output`
170    /// (`output.count > 0`); an event condition reads the event's payload as
171    /// `input` (`input.ok == true`). A sleep condition takes no expression.
172    ///
173    /// The engine does not check the expression when the workflow is
174    /// registered: a malformed or never-true expression shows up as a task
175    /// that never starts, not as an error.
176    pub fn expression(mut self, expression: impl Into<String>) -> Self {
177        self.expression = Some(expression.into());
178        self
179    }
180
181    /// Overrides the key this condition is known by — the key the engine
182    /// tells one task's conditions apart by, and which must therefore be
183    /// unique among them.
184    ///
185    /// The default is `sleep:<duration>` for a sleep, the event key (before
186    /// namespacing) for an event, and the parent's name for a parent
187    /// condition — plus `:<expression>` when a parent condition has one, so
188    /// that two conditions reading the same parent through different
189    /// expressions do not collide. (The official Python SDK folds the
190    /// expression *and* the current time into that key; the time is left out
191    /// here so that the same declaration always maps to the same request.)
192    pub fn readable_key(mut self, key: impl Into<String>) -> Self {
193        self.readable_key = Some(key.into());
194        self
195    }
196
197    /// Only matches events pushed with this scope
198    /// ([`PushOpts::scope`](crate::PushOpts::scope)). Event conditions only.
199    pub fn scope(mut self, scope: impl Into<String>) -> Self {
200        self.scope = Some(scope.into());
201        self
202    }
203
204    /// Also matches events pushed after `at` but before the task started
205    /// waiting. Event conditions only, and only together with
206    /// [`scope`](Condition::scope) — the official Go SDK documents the
207    /// engine as requiring both.
208    pub fn since(mut self, at: SystemTime) -> Self {
209        self.since = Some(at);
210        self
211    }
212
213    /// The key this condition is known by: the override, or the default for
214    /// its kind.
215    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    /// The parent this condition reads, if it is a parent condition.
230    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    /// Whether the engine only ever evaluates this condition while the task
238    /// is waiting to be queued. A parent condition is evaluated as soon as
239    /// the parent finishes; a sleep or an event is not, so on a `skip_if` or
240    /// a `cancel_if` it leaves the task waiting for a `wait_for` that must
241    /// be there too.
242    fn only_gates_queueing(&self) -> bool {
243        matches!(self.kind, Kind::Sleep(_) | Kind::Event(_))
244    }
245
246    /// The name of the first string this condition carries that is blank —
247    /// empty or nothing but whitespace — if any.
248    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    /// Why this condition cannot be sent, if any.
268    fn invalid_reason(&self) -> Option<String> {
269        let key = self.readable_data_key();
270        // Every string a condition carries names something the engine has to
271        // match on, so a blank one can only ever be a mistake — and one that
272        // shows up as a task that silently never starts rather than as an
273        // error, since the engine checks none of them.
274        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                // `scope` and `since` belong to an event condition, so the
295                // checks below do not apply to one.
296                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                // Whole milliseconds are what goes on the wire, so anything
306                // under one of them *is* a zero-duration sleep to the engine.
307                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/// A group of conditions of which *any one* satisfies the gate. Made by
332/// [`any_of`].
333#[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
337/// Satisfied as soon as *any* of `conditions` is.
338///
339/// Conditions given separately must all be satisfied (the engine ANDs them);
340/// the ones in one `any_of` are ORed together, because they share an or-group
341/// id on the wire.
342///
343/// ```
344/// use std::time::Duration;
345///
346/// use hatchet_client::{Condition, TaskBuilder, any_of};
347///
348/// let ship = TaskBuilder::<(), ()>::new("ship")
349///     .wait_for(any_of([
350///         Condition::on_event("qa.signed-off"),
351///         Condition::sleep(Duration::from_secs(24 * 3600)),
352///     ]))
353///     .handler(|_ctx, _input| async { Ok(()) });
354/// # let _ = ship;
355/// ```
356pub fn any_of(conditions: impl IntoIterator<Item = Condition>) -> OrGroup {
357    OrGroup(conditions.into_iter().collect())
358}
359
360/// What one gate waits on: or-groups that must *all* be satisfied.
361///
362/// Never built literally — a [`Condition`], an [`OrGroup`], or a collection
363/// of either converts into one, and [`ConditionSet::and`] adds to it.
364///
365/// ```
366/// use std::time::Duration;
367///
368/// use hatchet_client::{Condition, ConditionSet, TaskBuilder, any_of};
369///
370/// // "after the sleep, and once either event has arrived"
371/// let gate = ConditionSet::from(Condition::sleep(Duration::from_secs(30))).and(any_of([
372///     Condition::on_event("ready"),
373///     Condition::on_event("forced"),
374/// ]));
375/// let publish = TaskBuilder::<(), ()>::new("publish")
376///     .wait_for(gate)
377///     .handler(|_ctx, _input| async { Ok(()) });
378/// # let _ = publish;
379/// ```
380#[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    /// Each inner vector is one or-group; a lone condition is a group of
384    /// one. Groups AND together, members of a group OR together.
385    groups: Vec<Vec<Condition>>,
386}
387
388impl ConditionSet {
389    /// Adds another condition or group that must *also* be satisfied.
390    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    /// The parents every parent condition in this set reads.
404    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    /// What a durable wait on this set is waiting on, as a kind and one
413    /// resource — `("user_event", "approve")`, `("sleep", "sleep:5000ms")`.
414    ///
415    /// It goes into the reason an eviction carries, which is what a dashboard
416    /// and the engine's log show, so the official SDKs' words are used:
417    /// `sleep`, `user_event`, `parent`, and `wait_for` for a set that mixes
418    /// them (`sdks/go/pkg/worker/context.go:1203`). The resource is the first
419    /// readable key in sorted order — a stable choice rather than an arbitrary
420    /// one, since a set has no order the handler chose.
421    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
492/// The gates of one task: `wait_for`, `skip_if`, `cancel_if`, in that order.
493pub(crate) type Gates<'a> = [(ConditionAction, &'a ConditionSet); 3];
494
495/// Why this task's conditions cannot be sent, if any. The caller adds the
496/// task and workflow names.
497pub(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    // A sleep or an event on `skip_if`/`cancel_if` gates queueing: with
531    // nothing of that kind on `wait_for` to queue on, the task never starts
532    // and the run never finishes (observed on both v0.80.0 and v0.107.0).
533    // Neither parents nor a `wait_for` made only of parent conditions
534    // release it — measured, see
535    // `hatchet-integration-tests`' `conditions::a_parent_condition_wait_for_
536    // does_not_release_an_event_skip_if`.
537    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
564/// Folds the three gates into the one wire field, or `None` when there is
565/// nothing to send. Call [`validate`] first.
566pub(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
612/// The conditions of one durable wait.
613///
614/// Three things differ from [`to_proto`], which maps a *task's* gates:
615///
616/// * every condition is a `CREATE` condition — a durable wait is not a gate on
617///   queueing, it is a point the handler is standing on
618///   (`pkg/worker/context.go:1186`);
619/// * a parent condition cannot be expressed
620///   (`DurableEventListenerConditions` has no parent field —
621///   `api-contracts/v1/shared/condition.proto:46-49`), so it is rejected with
622///   an explanation rather than dropped;
623/// * the pairing rule [`validate`] enforces for task conditions (a sleep or an
624///   event on `skip_if`/`cancel_if` needs one on `wait_for`) does not apply:
625///   there is only one gate here.
626///
627/// The readable key still has to be unique, and for a stronger reason than on
628/// a task: the engine indexes the wait's result by it
629/// (`{"CREATE": {"<readable key>": [payload, …]}}`, measured on both supported
630/// engines), so two conditions sharing a key would lose one of the matches.
631///
632/// The event key is namespaced exactly as
633/// [`EventsClient::push`](crate::EventsClient::push) namespaces it; the
634/// *readable* key is not, because that is the key the engine echoes back and
635/// the handler should recognise the one it asked for.
636pub(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
708/// How the engine takes a sleep duration: whole milliseconds, which is what
709/// the official Go SDK sends. The official Python SDK sends
710/// `"<n>h"`/`"<n>m"`/`"<n>s"` instead, which cannot express a sub-second
711/// wait; the engine accepts either.
712fn duration_expr(duration: Duration) -> String {
713    format!("{}ms", duration.as_millis())
714}
715
716/// A `SystemTime` at or after the epoch, as the engine's timestamp.
717///
718/// A time before 1970 is rejected by [`validate`], so the `unwrap_or` below
719/// is belt and braces; the nanosecond conversion cannot fail at all, since
720/// `subsec_nanos` is under a billion.
721fn 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
729/// A random UUID v4 in the canonical 36-character form.
730///
731/// The engine documents `or_group_id` as a UUID
732/// (`api-contracts/v1/shared/condition.proto:19`) and rejects anything else
733/// that is not empty. This is the only place the SDK needs a UUID, so it is
734/// made from `rand` — already a dependency — rather than by adding a crate.
735fn or_group_id() -> String {
736    let mut bytes = rand::rng().random::<u128>().to_be_bytes();
737    bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
738    bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant RFC 4122
739    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        // The readable key is *not* namespaced — it is what comes back in the
787        // result map, and the handler should recognise the key it asked for.
788        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        // …and the same two are fine once one of them is renamed.
831        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    /// Acceptance criterion 4: an or-group shares one id, and everything
973    /// else gets its own.
974    #[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            // Rounds to `"0ms"` on the wire, which is the very value the
1113            // zero-duration rule exists to keep off it.
1114            (
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    /// The engine weighs a sleep or event `skip_if`/`cancel_if` only while
1146    /// the task waits to be queued, so on its own it leaves the task waiting
1147    /// for ever (seen on both supported engines).
1148    #[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    /// Measured on both supported engines: a `wait_for` made only of parent
1185    /// conditions does not release a task that also carries a sleep or event
1186    /// `skip_if`/`cancel_if` — it hangs exactly as one with no `wait_for` at
1187    /// all does. Only a sleep or an event counts towards the pairing.
1188    #[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        // A parent condition beside a sleep in the same `wait_for` does not
1217        // spoil the pairing.
1218        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    /// Two conditions on one parent, told apart by their expressions rather
1224    /// than colliding on the bare parent name.
1225    #[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        // Two of a kind stay that kind, and the resource is the first key in
1318        // sorted order however the set was written.
1319        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        // A mixed set is neither.
1328        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}