schedr_model/trigger.rs
1//! A DAG's trigger, as stored in DAG JSON: what starts its runs.
2//!
3//! Cron expressions and time zone names are validated by the master when it stores a DAG;
4//! here they are plain data (see archive/PROJECT.md, Native API: triggers are typed objects).
5
6use jiff::Timestamp;
7use schemars::JsonSchema;
8use serde::{Deserialize, Serialize};
9
10#[cfg(test)]
11mod tests;
12
13/// What starts runs of a DAG besides people.
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
15#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
16pub enum Trigger {
17 /// Nothing: manual runs only (the DAG is switched off but for those).
18 None,
19 /// A cron expression (5 or 6 fields, or a preset such as `@daily`) evaluated in a time zone.
20 Cron {
21 /// The cron expression.
22 expression: String,
23 /// An IANA time zone name, e.g. `Europe/Warsaw`; `UTC` by default in the Python API.
24 timezone: String,
25 /// Whether missed fire times get runs in order (`true`) or only the most recent
26 /// (`false`).
27 catchup: bool,
28 /// The first run it creates is for the first fire time at or after it; without it,
29 /// the moment the master first stored the DAG.
30 #[serde(default)]
31 start: Option<Timestamp>,
32 /// The last run it creates is for the last fire time at or before it.
33 #[serde(default)]
34 end: Option<Timestamp>,
35 },
36 /// A fixed interval measured in real time (UTC), unaffected by daylight saving.
37 Every {
38 /// The interval in milliseconds; fire times are whole intervals from `start`, or from
39 /// the Unix epoch without one.
40 interval_ms: u64,
41 /// Whether missed fire times get runs in order (`true`) or only the most recent
42 /// (`false`).
43 catchup: bool,
44 /// The first run it creates is for the first fire time at or after it; without it,
45 /// the moment the master first stored the DAG.
46 #[serde(default)]
47 start: Option<Timestamp>,
48 /// The last run it creates is for the last fire time at or before it.
49 #[serde(default)]
50 end: Option<Timestamp>,
51 },
52 /// A single fire time (it has no previous fire time).
53 Once {
54 /// The fire time.
55 at: Timestamp,
56 },
57 /// A `@trigger` function, which runs in a worker's watcher host and yields events: each new
58 /// one starts a run.
59 Event {
60 /// Its function as a task of kind `sensor`: its literal arguments, whether it is called
61 /// every so often, its queue, its secrets and connections. It isn't in the graph.
62 task: Box<crate::task::Task>,
63 /// Started again from its bookmark when no event came for this long; `None`: never.
64 #[serde(default, skip_serializing_if = "Option::is_none")]
65 restart_if_idle_ms: Option<u64>,
66 /// It runs from this moment on.
67 #[serde(default)]
68 start: Option<Timestamp>,
69 /// It stops at this moment.
70 #[serde(default)]
71 end: Option<Timestamp>,
72 /// `@trigger(wait_for=RunOf(...), run_retries=N)` (decision 353): a run its function
73 /// raised on is tried again this many times, then passed, recorded; `None`: tried until
74 /// `schedr triggers skip` passes it.
75 #[serde(default, skip_serializing_if = "Option::is_none")]
76 run_retries: Option<u32>,
77 },
78 /// `trigger=RunOf(...)` (decision 353): a run per run of another DAG (or its task) that
79 /// succeeded while this one is live, planned for that run's `planned_for` plus `lag`, or for
80 /// the moment the master saw it.
81 RunOf {
82 /// Which runs.
83 run_of: crate::task::RunOf,
84 },
85 /// `trigger=Chained()` (decision 398): only other DAGs' `TriggerDagOperator`s start its
86 /// runs (and people, by hand); the scheduler never does.
87 Chained {
88 /// The DAGs whose operators may start it; `None`: any DAG. Never empty.
89 #[serde(default, skip_serializing_if = "Option::is_none")]
90 by: Option<Vec<crate::DagId>>,
91 },
92 /// `trigger=EventNamed(...)` (decision 354): a run per event of that name posted through the
93 /// API while this DAG is live, keyed by the event's key, planned for its `at`.
94 EventNamed {
95 /// Which events: its name (a trigger takes no key).
96 event: crate::task::EventNamed,
97 },
98}
99
100/// The longest key an event may have, in bytes: it is stored with every event and sent back as a
101/// trigger's `after`. Python says it first ([`RunEvent`]'s data is limited by the trigger's
102/// `max_output_size`).
103pub const MAX_EVENT_KEY: usize = 1024;
104
105/// Whether a terminal or a page would act on `c` instead of showing it: a control character,
106/// a line or paragraph separator, or a bidirectional override or isolate (Grok's review of
107/// M4.11e: a key with U+2028 broke `schedr events list`'s table).
108#[must_use]
109pub const fn acts_on_display(c: char) -> bool {
110 c.is_control()
111 || matches!(
112 c,
113 '\u{2028}' | '\u{2029}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}'
114 | '\u{2066}'..='\u{2069}'
115 )
116}
117
118/// Whether a text can be an event's key.
119///
120/// # Errors
121///
122/// What is wrong with it.
123pub fn check_event_key(key: &str) -> Result<(), String> {
124 if key.is_empty() || key.len() > MAX_EVENT_KEY || key.chars().any(acts_on_display) {
125 return Err(format!(
126 "an event's key has 1 to {MAX_EVENT_KEY} bytes and no control, line-separator or \
127 bidirectional characters, got {} bytes",
128 key.len()
129 ));
130 }
131 Ok(())
132}
133
134/// What a `@trigger` found, as stored and given to the run it starts.
135#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
136#[serde(deny_unknown_fields)]
137pub struct RunEvent {
138 /// Its key, unique in its DAG.
139 pub key: String,
140 /// Its data, as stored JSON.
141 #[schemars(with = "serde_json::Value")]
142 pub data: serde_json::Value,
143 /// When it happened, if it said; the run is planned for this moment.
144 #[serde(default)]
145 pub at: Option<Timestamp>,
146}
147
148impl Trigger {
149 /// Its kind as the UI names it and `dag_triggers.kind` stores it (decision 459):
150 /// `schedule` (cron, every, once), `run_of`, `chained` or `event` (by a trigger or by name);
151 /// `None` for no trigger. A change of kind pauses it; another trigger of the same kind
152 /// keeps its switch.
153 #[must_use]
154 pub const fn kind(&self) -> Option<&'static str> {
155 match self {
156 Self::None => None,
157 Self::Cron { .. } | Self::Every { .. } | Self::Once { .. } => Some("schedule"),
158 Self::RunOf { .. } => Some("run_of"),
159 Self::Chained { .. } => Some("chained"),
160 Self::Event { .. } | Self::EventNamed { .. } => Some("event"),
161 }
162 }
163
164 /// Whether the scheduler never creates runs: only people (or other DAGs) do.
165 #[must_use]
166 pub const fn is_manual_only(&self) -> bool {
167 matches!(self, Self::None)
168 }
169
170 /// Whether `dag` may start its runs with a `TriggerDagOperator` (decision 398): it is
171 /// `Chained`, for any DAG or one of those it names.
172 #[must_use]
173 pub fn chained_from(&self, dag: &crate::DagId) -> bool {
174 match self {
175 Self::Chained { by: None } => true,
176 Self::Chained { by: Some(by) } => by.contains(dag),
177 _ => false,
178 }
179 }
180
181 /// Whether another DAG's runs start its runs (`trigger=RunOf(...)`).
182 #[must_use]
183 pub const fn is_run_of(&self) -> bool {
184 matches!(self, Self::RunOf { .. })
185 }
186
187 /// Whether events start its runs: it has no fire times.
188 #[must_use]
189 pub const fn is_event(&self) -> bool {
190 matches!(self, Self::Event { .. })
191 }
192
193 /// Whether its runs bring an event: a `@trigger`'s, or the run of another DAG that started
194 /// it (`RunOf`).
195 #[must_use]
196 pub const fn brings_event(&self) -> bool {
197 matches!(
198 self,
199 Self::Event { .. } | Self::RunOf { .. } | Self::EventNamed { .. }
200 )
201 }
202
203 /// Whether missed fire times get runs in order; `false` for triggers without `catchup`
204 /// (a single fire time has nothing to catch up on).
205 #[must_use]
206 pub const fn catchup(&self) -> bool {
207 match self {
208 Self::Cron { catchup, .. } | Self::Every { catchup, .. } => *catchup,
209 Self::None
210 | Self::Chained { .. }
211 | Self::Once { .. }
212 | Self::Event { .. }
213 | Self::RunOf { .. }
214 | Self::EventNamed { .. } => false,
215 }
216 }
217
218 /// Where the runs it creates start (see the `start` fields); `None` for triggers without
219 /// one.
220 #[must_use]
221 pub const fn start(&self) -> Option<Timestamp> {
222 match self {
223 Self::Cron { start, .. } | Self::Every { start, .. } | Self::Event { start, .. } => {
224 *start
225 }
226 Self::None
227 | Self::Chained { .. }
228 | Self::Once { .. }
229 | Self::RunOf { .. }
230 | Self::EventNamed { .. } => None,
231 }
232 }
233
234 /// Where the runs it creates end (see the `end` fields); `None` for triggers without one.
235 #[must_use]
236 pub const fn end(&self) -> Option<Timestamp> {
237 match self {
238 Self::Cron { end, .. } | Self::Every { end, .. } | Self::Event { end, .. } => *end,
239 Self::None
240 | Self::Chained { .. }
241 | Self::Once { .. }
242 | Self::RunOf { .. }
243 | Self::EventNamed { .. } => None,
244 }
245 }
246}