Skip to main content

agentmux_srv/drone/executor/blocks/
wait.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Wait block: the run stops for a time or for an event
5//! (docs/specs/SPEC_DRONE_GENERAL_AUTOMATION_2026_11_11.md ยง3.3, "Waiting").
6//!
7//! `{ "for": "30m" }` waits that long (`500ms`, `45s`, `30m`, `2h`, `1d`, or a
8//! number of seconds); `{ "until": "2026-12-01T09:00:00Z" }` waits for a time
9//! (RFC 3339); `{ "on": "label" }` waits for an event: the label says what it is
10//! for, the key that ends it is made when the wait starts (`backend::drone_wait`).
11//! Exactly one of the three. The scheduler does the waiting
12//! (`scheduler/wait.rs`), because the wait is kept in the run's checkpoint.
13
14use serde_json::Value;
15
16use crate::backend::storage::drone_types::FlowNode;
17
18/// The longest a run may be told to wait: 30 days.
19pub const MAX_WAIT_MS: i64 = 30 * 24 * 3_600_000;
20
21/// What a Wait block waits for.
22#[derive(Debug, Clone, PartialEq)]
23pub enum Wait {
24    /// This long from when the wait starts, in milliseconds.
25    For(i64),
26    /// This time, in milliseconds since 1970.
27    Until(i64),
28    /// An event, called `label`.
29    On(String),
30}
31
32/// A duration as written: `500ms`, `45s`, `30m`, `2h`, `1d` or a number of seconds.
33fn duration_ms(text: &str) -> Option<i64> {
34    let t = text.trim();
35    let split = t.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(t.len());
36    let (number, unit) = t.split_at(split);
37    let n: f64 = number.parse().ok().filter(|n: &f64| n.is_finite() && *n >= 0.0)?;
38    let unit_ms = match unit.trim() {
39        "ms" => 1.0,
40        "" | "s" => 1_000.0,
41        "m" => 60_000.0,
42        "h" => 3_600_000.0,
43        "d" => 86_400_000.0,
44        _ => return None,
45    };
46    let ms = n * unit_ms;
47    (ms <= MAX_WAIT_MS as f64).then_some(ms as i64)
48}
49
50/// The block's setting, with templates filled in by `resolve`. A time that is
51/// not in the future is allowed (the wait is over at once); one more than 30
52/// days from `now_ms` is not.
53pub fn parse(node: &FlowNode, resolve: &dyn Fn(&str) -> String, now_ms: i64) -> Result<Wait, String> {
54    let text = |key: &str| match node.data.get(key) {
55        None | Some(Value::Null) => None,
56        Some(Value::String(s)) => Some(resolve(s)),
57        Some(other) => Some(other.to_string()),
58    };
59    let (f, u, o) = (text("for"), text("until"), text("on"));
60    let id = &node.id;
61    match (f, u, o) {
62        (Some(f), None, None) => duration_ms(&f)
63            .map(Wait::For)
64            .ok_or_else(|| format!("{id}: `for` must be a length of time up to 30 days, like 90s, 30m, 2h or 1d, and it is {f:?}")),
65        (None, Some(u), None) => {
66            let at = chrono::DateTime::parse_from_rfc3339(u.trim())
67                .map_err(|_| format!("{id}: `until` must be a time like 2026-12-01T09:00:00Z, and it is {u:?}"))?
68                .timestamp_millis();
69            if at - now_ms > MAX_WAIT_MS {
70                return Err(format!("{id}: `until` is more than 30 days away, the longest a run waits"));
71            }
72            Ok(Wait::Until(at))
73        }
74        (None, None, Some(o)) if !o.trim().is_empty() => Ok(Wait::On(o.trim().to_string())),
75        (None, None, Some(_)) => Err(format!("{id}: `on` must say what the run waits for")),
76        (None, None, None) => Err(format!("{id}: a Wait block needs `for`, `until` or `on`")),
77        _ => Err(format!("{id}: a Wait block takes only one of `for`, `until` and `on`")),
78    }
79}
80
81/// The block setting is well formed, as far as it can be told before the run:
82/// one that is a template is checked when the wait starts.
83pub fn check(node: &FlowNode) -> Result<(), String> {
84    let templated = ["for", "until", "on"].iter().any(|k| node.data.get(*k).and_then(Value::as_str).is_some_and(|s| s.contains("{{")));
85    if templated {
86        return Ok(());
87    }
88    parse(node, &|t| t.to_string(), agentmux_common::time::now_ms()).map(|_| ())
89}
90
91#[cfg(test)]
92mod tests {
93    use super::*;
94    use crate::drone::types::NodePosition;
95    use serde_json::json;
96
97    fn wait_node(extra: Value) -> FlowNode {
98        let mut data = json!({ "kind": "wait" });
99        data.as_object_mut().unwrap().extend(extra.as_object().cloned().unwrap_or_default());
100        FlowNode { id: "w".to_string(), position: NodePosition::default(), data, node_type: None }
101    }
102
103    fn read(extra: Value) -> Result<Wait, String> {
104        parse(&wait_node(extra), &|t| t.replace("{{n}}", "5m"), 1_796_000_000_000)
105    }
106
107    #[test]
108    fn a_length_of_time_is_read_in_the_units_people_write() {
109        for (text, ms) in [("500ms", 500), ("45s", 45_000), ("30m", 1_800_000), ("2h", 7_200_000), ("1d", 86_400_000), ("90", 90_000), (" 1.5h ", 5_400_000), ("0s", 0)] {
110            assert_eq!(read(json!({ "for": text })), Ok(Wait::For(ms)), "{text}");
111        }
112        assert_eq!(read(json!({ "for": 20 })), Ok(Wait::For(20_000)), "a number is seconds");
113        assert_eq!(read(json!({ "for": "{{n}}" })), Ok(Wait::For(300_000)), "templates are filled in");
114    }
115
116    #[test]
117    fn a_length_that_is_not_one_is_refused_and_says_what_to_write() {
118        for bad in ["", "soon", "-5m", "5 weeks", "31d", "NaNs"] {
119            let why = read(json!({ "for": bad })).unwrap_err();
120            assert!(why.contains("`for` must be a length of time up to 30 days"), "{bad}: {why}");
121        }
122    }
123
124    #[test]
125    fn a_time_is_read_as_rfc_3339_and_may_already_have_passed() {
126        assert_eq!(read(json!({ "until": "2026-12-01T09:00:00Z" })), Ok(Wait::Until(1_796_115_600_000)));
127        assert_eq!(read(json!({ "until": "2026-12-01T10:00:00+01:00" })), Ok(Wait::Until(1_796_115_600_000)));
128        assert!(matches!(read(json!({ "until": "1999-01-01T00:00:00Z" })), Ok(Wait::Until(_))));
129        assert!(read(json!({ "until": "tomorrow" })).unwrap_err().contains("`until` must be a time like"));
130        assert!(read(json!({ "until": "2999-01-01T00:00:00Z" })).unwrap_err().contains("more than 30 days"));
131    }
132
133    #[test]
134    fn an_event_wait_needs_a_label_and_exactly_one_setting_is_given() {
135        assert_eq!(read(json!({ "on": "deploy.finished" })), Ok(Wait::On("deploy.finished".to_string())));
136        assert!(read(json!({ "on": "  " })).unwrap_err().contains("`on` must say"));
137        assert!(read(json!({})).unwrap_err().contains("needs `for`, `until` or `on`"));
138        assert!(read(json!({ "for": "1m", "on": "x" })).unwrap_err().contains("only one of"));
139    }
140}