Skip to main content

schedr_model/
task.rs

1//! Tasks in DAG JSON: their kind, what they run, and their resolved settings.
2//!
3//! Settings are stored **resolved** (the Python API applies `StepDefaults` and group
4//! defaults), so the master never needs to know where a value came from.
5
6use std::collections::BTreeMap;
7
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10
11use crate::ids::TaskId;
12use crate::secret::{SecretDecl, SecretName};
13use crate::types::TypeDesc;
14use crate::value::{Reference, Template, Value};
15
16#[cfg(test)]
17mod tests;
18
19/// The queue a task goes to when it names none.
20pub const DEFAULT_QUEUE: &str = "default";
21
22/// The default output size limit in bytes (`[outputs] default_max_size`, 1 MiB).
23pub const DEFAULT_MAX_OUTPUT_SIZE: u64 = 1024 * 1024;
24
25/// The default delay between attempts in milliseconds (5 minutes).
26pub const DEFAULT_RETRY_DELAY_MS: u64 = 5 * 60 * 1000;
27
28/// How many times a failed cleanup is retried by default (decision 217).
29pub const DEFAULT_CLEANUP_RETRIES: u32 = 3;
30
31/// The default delay between a cleanup's tries in milliseconds (decision 217).
32pub const DEFAULT_CLEANUP_RETRY_DELAY_MS: u64 = 30 * 1000;
33
34/// A task's settings, resolved from its own arguments and the defaults that apply to it.
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
36#[serde(deny_unknown_fields)]
37pub struct TaskSettings {
38    /// How many times a failed attempt is retried.
39    pub retries: u32,
40    /// The delay before each retry, in milliseconds.
41    pub retry_delay_ms: u64,
42    /// The attempt's timeout in milliseconds; `None` for no timeout.
43    pub timeout_ms: Option<u64>,
44    /// The queue the task goes to.
45    pub queue: String,
46    /// The output size limit in bytes.
47    pub max_output_size: u64,
48    /// A Python task: fork it from the preloaded fork server (`false`: only from the bare
49    /// one, for code that misbehaves next to the preloaded libraries). Not for other tasks.
50    #[serde(default = "yes")]
51    pub preload: bool,
52    /// A Python task: always a new process, never forked (for code that misbehaves after a
53    /// fork). Not for other tasks.
54    #[serde(default)]
55    pub fresh_process: bool,
56    /// When it runs, from its upstream edges (its trigger rule).
57    #[serde(default, skip_serializing_if = "RunIf::is_default")]
58    pub run_if: RunIf,
59    /// At most this many of its instances running at once, across all runs (decided from
60    /// the DAG's current version, decision 87A); `None` for no limit.
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    #[schemars(range(min = 1))]
63    pub max_active: Option<u32>,
64    /// At most this many of its instances running at once within one run (from the run's own
65    /// version); `None` for no limit.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    #[schemars(range(min = 1))]
68    pub max_active_per_run: Option<u32>,
69    /// Its own memory budget in bytes (`memory=`, decision 436), instead of the worker's share:
70    /// the watchdog kills it above; taken only by a worker whose pod limit, less its reserve,
71    /// holds it (decision 437). `None`: the worker's budget.
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    #[schemars(range(min = 16_777_216))]
74    pub memory_bytes: Option<u64>,
75    /// Also capped hard at `memory_bytes` (`hard_memory_limit=True`, decision 438): the
76    /// process's `RLIMIT_DATA`, so an allocation past it fails inside the task.
77    #[serde(default, skip_serializing_if = "is_false")]
78    pub hard_memory_limit: bool,
79}
80
81/// A task's trigger rule: what its upstream edges must have done for it to run (see
82/// archive/PROJECT.md, Outcomes, failures and joins). An edge not taken counts as skipped.
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
84#[serde(rename_all = "snake_case")]
85pub enum RunIf {
86    /// Every edge that wasn't skipped succeeded, and at least one did: skipped when all were
87    /// skipped, `upstream_failed` when one failed.
88    #[default]
89    NoneFailed,
90    /// Every edge succeeded: `upstream_failed` when one failed, otherwise skipped when one
91    /// was skipped.
92    AllSucceeded,
93}
94
95impl RunIf {
96    /// Whether it is the default, [`RunIf::NoneFailed`].
97    #[must_use]
98    pub fn is_default(&self) -> bool {
99        *self == Self::NoneFailed
100    }
101}
102
103/// One of a task's outcomes: its name, and for a `command` task the exit code meaning it.
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
105#[serde(deny_unknown_fields)]
106pub struct OutcomeDecl {
107    /// The name (an `Outcome` enum member's, a class's, or `None`).
108    pub name: String,
109    /// A `command` task's exit code for it; none for other tasks.
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub exit_code: Option<i32>,
112}
113
114/// The outcome of a task without outcomes of its own (`DefaultOutcome.SUCCESS`).
115pub const DEFAULT_OUTCOME: &str = "SUCCESS";
116
117/// A task's outcomes when it declares none: `SUCCESS`, exit code 0 for a command.
118#[must_use]
119pub fn default_outcomes() -> Vec<OutcomeDecl> {
120    vec![OutcomeDecl {
121        name: DEFAULT_OUTCOME.to_owned(),
122        exit_code: Some(0),
123    }]
124}
125
126fn is_default_outcomes(outcomes: &Vec<OutcomeDecl>) -> bool {
127    *outcomes == default_outcomes()
128}
129
130const fn yes() -> bool {
131    true
132}
133
134#[expect(
135    clippy::trivially_copy_pass_by_ref,
136    reason = "serde's skip_serializing_if takes &T"
137)]
138const fn is_false(value: &bool) -> bool {
139    !*value
140}
141
142impl Default for TaskSettings {
143    /// The settings of a task that sets nothing and has no defaults: no retries, a 5 minute
144    /// retry delay, no timeout, the default queue, a 1 MiB output limit, forked from the
145    /// preloaded fork server where there is one.
146    fn default() -> Self {
147        Self {
148            retries: 0,
149            retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
150            timeout_ms: None,
151            queue: DEFAULT_QUEUE.to_owned(),
152            max_output_size: DEFAULT_MAX_OUTPUT_SIZE,
153            preload: true,
154            fresh_process: false,
155            run_if: RunIf::NoneFailed,
156            max_active: None,
157            max_active_per_run: None,
158            memory_bytes: None,
159            hard_memory_limit: false,
160        }
161    }
162}
163
164/// What a `command` task runs.
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
166#[serde(rename_all = "snake_case", deny_unknown_fields)]
167pub enum CommandLine {
168    /// A string run by a shell; it takes no references (decision 99): values go in `env`.
169    Shell(Template),
170    /// A program and its arguments, run without a shell; each element is one argument.
171    Argv(Vec<Template>),
172}
173
174impl CommandLine {
175    /// The templates of this command line, in order.
176    #[must_use]
177    pub fn templates(&self) -> Vec<&Template> {
178        match self {
179            Self::Shell(t) => vec![t],
180            Self::Argv(args) => args.iter().collect(),
181        }
182    }
183}
184
185/// How a wait step waits.
186#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
187#[serde(rename_all = "snake_case")]
188pub enum SensorMode {
189    /// `@sensor`: its function does the waiting.
190    Loop,
191    /// `@sensor.poke`: its function is called every `every_ms`.
192    Poke,
193}
194
195/// The longest `lag` of a [`RunOf`], either way: 10 years (3650 days), so a planned moment plus
196/// or minus it stays a timestamp.
197pub const MAX_LAG_MS: i64 = 3_650 * 24 * 3_600_000;
198
199/// Which run of another DAG a step waits for, and of it which task (decision 353).
200#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
201#[serde(deny_unknown_fields)]
202pub struct RunOf {
203    /// The DAG.
204    pub dag: crate::DagId,
205    /// Its task; `None`: the whole run.
206    #[serde(default, skip_serializing_if = "Option::is_none")]
207    pub task: Option<TaskId>,
208    /// With it, the run whose `planned_for` is the waiting run's minus this many milliseconds;
209    /// without it, the next run to end after the step starts.
210    #[serde(default, skip_serializing_if = "Option::is_none")]
211    pub lag_ms: Option<i64>,
212}
213
214/// An event posted through the API (decision 354), by name and, for a step waiting in a run,
215/// key: `EventNamed("payment-completed", key=dag_ctx.params.order_id)`.
216#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
217#[serde(deny_unknown_fields)]
218pub struct EventNamed {
219    /// Its name.
220    pub name: crate::EventName,
221    /// Its key, a literal or resolved for the run (its params, its own event's key or ID, an
222    /// upstream output): only an event with this key matches. `None`: any of the name; a
223    /// trigger takes none.
224    #[serde(default, skip_serializing_if = "Option::is_none")]
225    pub key: Option<crate::value::Value>,
226}
227
228/// What an `@sensor(wait_for=...)` / `@trigger(wait_for=...)` waits for, and the parameter its
229/// function is given it in (its first): a run of another DAG (`RunOf`, a `RunResult`) or an
230/// event posted (`EventNamed`, an `Event`, decision 354); exactly one of the two.
231#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
232#[serde(deny_unknown_fields)]
233pub struct SensorWaitFor {
234    /// The run, and of it which task.
235    #[serde(default, skip_serializing_if = "Option::is_none")]
236    pub run_of: Option<RunOf>,
237    /// The event.
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    pub event: Option<EventNamed>,
240    /// The function's parameter given the run.
241    pub param: String,
242    /// `@sensor(wait_for=..., timeout=...)`: how long one call may take, in milliseconds; one
243    /// over it fails the attempt (its retries get the same run). `None`: what is left of
244    /// `max_wait`.
245    #[serde(default, skip_serializing_if = "Option::is_none")]
246    pub timeout_ms: Option<u64>,
247}
248
249/// What a [`SensorWaitFor`] waits for.
250#[derive(Debug, Clone, Copy, PartialEq, Eq)]
251pub enum WaitSource<'a> {
252    /// A run of another DAG.
253    RunOf(&'a RunOf),
254    /// An event posted.
255    Event(&'a EventNamed),
256}
257
258impl SensorWaitFor {
259    /// What it waits for; `None` for neither or both (refused when the DAG is validated).
260    #[must_use]
261    pub const fn source(&self) -> Option<WaitSource<'_>> {
262        match (&self.run_of, &self.event) {
263            (Some(run_of), None) => Some(WaitSource::RunOf(run_of)),
264            (None, Some(event)) => Some(WaitSource::Event(event)),
265            _ => None,
266        }
267    }
268}
269
270/// The kind of a task and what it runs.
271#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
272#[serde(tag = "kind", rename_all = "snake_case")]
273pub enum TaskKind {
274    /// A `@task` function, found by task ID when the runner imports the DAG file.
275    Python {
276        /// The arguments by parameter name.
277        #[serde(default)]
278        arguments: BTreeMap<String, Value>,
279        /// A `@branch` task: its output is the list of the downstream task IDs it chose, and
280        /// its outgoing edges are selection edges.
281        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
282        branch: bool,
283    },
284    /// A wait step (`@sensor`, `@sensor.poke`): found by task ID, as a `Python` task, and ending
285    /// with its value or with the `TimedOut` outcome.
286    Sensor {
287        /// The arguments by parameter name.
288        #[serde(default)]
289        arguments: BTreeMap<String, Value>,
290        /// How it waits.
291        mode: SensorMode,
292        /// How often to call it (`Poke`), in milliseconds.
293        #[serde(default, skip_serializing_if = "Option::is_none")]
294        every_ms: Option<u64>,
295        /// How long it waits, in milliseconds; `None`: the worker's `[sensors] default_max_wait`.
296        #[serde(default, skip_serializing_if = "Option::is_none")]
297        max_wait_ms: Option<u64>,
298        /// `@sensor(wait_for=RunOf(...))` (decision 353): called once a matching run of another
299        /// DAG has ended, with it as `param`, rather than at once.
300        #[serde(default, skip_serializing_if = "Option::is_none")]
301        wait_for: Option<SensorWaitFor>,
302        /// `@trigger.poke(every=..., batch=...)` (decision 352): what its pokes return is
303        /// gathered for this many milliseconds from the first item, then sent as one event.
304        #[serde(default, skip_serializing_if = "Option::is_none")]
305        batch_ms: Option<u64>,
306    },
307    /// `first_of` / `at_least` (decision 347): ended by the master, no process and no slot, as
308    /// soon as enough of its upstream edges are taken. Its output is `{"$value": ..., "winner":
309    /// ...}`: the winner's output and ID, or for `at_least` lists of them in the order they ended.
310    FirstOf {
311        /// `at_least`'s count; `None`: `first_of`, ending with one edge.
312        #[serde(default, skip_serializing_if = "Option::is_none")]
313        at_least: Option<u32>,
314    },
315    /// `wait_for(RunOf(...))` (decision 353): waits for a run of another DAG, or one of its
316    /// tasks, ended by the master with no process and no slot. Its value is that run's ID; it
317    /// ends `Failed` when the run (or task) ended otherwise, and `TimedOut` after `max_wait`.
318    WaitFor {
319        /// Which run.
320        run_of: RunOf,
321        /// How long it waits, in milliseconds; `None`: the master's `[sensors] default_max_wait`.
322        #[serde(default, skip_serializing_if = "Option::is_none")]
323        max_wait_ms: Option<u64>,
324    },
325    /// `wait_for(EventNamed(...))` (decision 354): waits for an event posted through the API,
326    /// ended by the master with no process and no slot. Its value is the event (`key`, `data`,
327    /// `at`); `TimedOut` after `max_wait`.
328    WaitForEvent {
329        /// Which event.
330        event: EventNamed,
331        /// How long it waits, in milliseconds; `None`: the master's `[sensors] default_max_wait`.
332        #[serde(default, skip_serializing_if = "Option::is_none")]
333        max_wait_ms: Option<u64>,
334    },
335    /// `TriggerDagOperator` (decisions 357-362, 365, 378-381): starts a `chained` run of another
336    /// DAG, carried out by the master with no process and no slot. Its value is the started
337    /// run's ID; with `wait` it ends when that run has: `Failed` when the run didn't succeed,
338    /// `TimedOut` after `max_wait`.
339    TriggerDag {
340        /// The DAG to start a run of.
341        dag: crate::DagId,
342        /// The run's parameters, over the target's defaults: literals or references, resolved by
343        /// the master and checked against the target's schema when the task runs.
344        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
345        params: BTreeMap<String, Value>,
346        /// The run's `planned_for`, a datetime or a reference; `None`: the parent run's.
347        #[serde(default, skip_serializing_if = "Option::is_none")]
348        planned_for: Option<Value>,
349        /// Whether it waits for the run to end (the default) or ends once the run is created.
350        #[serde(default = "default_wait")]
351        wait: bool,
352        /// How long it waits, in milliseconds; `None`: the master's `[sensors] default_max_wait`.
353        #[serde(default, skip_serializing_if = "Option::is_none")]
354        max_wait_ms: Option<u64>,
355    },
356    /// An inline command, run by the agent.
357    Command {
358        /// The command line.
359        command: CommandLine,
360        /// Extra environment variables for the process.
361        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
362        env: BTreeMap<String, Template>,
363        /// Connections given as variables and files (decision 184:
364        /// `connections={"DB": warehouse}`), by prefix: `DB_URL`, `DB_PGPASSFILE`, ... Each
365        /// is also in the task's `connections`.
366        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
367        connection_env: BTreeMap<String, String>,
368        /// Its part in a resource (M4.8d): a `CommandResource`'s setup, or a resource's
369        /// `cleanup_command`; `None` for any other command.
370        #[serde(default, skip_serializing_if = "Option::is_none")]
371        resource: Option<ResourceRole>,
372    },
373    /// A script declared in a `schedr.toml` (M4.9): run by the agent with the declared
374    /// interpreter, from its script root at the version the master expects. A standalone job's
375    /// task.
376    Script {
377        /// The declaration: `<root>:<schedr.toml's path in the root>#<name>`.
378        job: String,
379        /// The script, relative to the script root.
380        script: String,
381        /// The interpreter: an `[interpreters]` entry of the worker that runs it.
382        interpreter: String,
383        /// Its arguments, each one argument (never a shell string).
384        #[serde(default, skip_serializing_if = "Vec::is_empty")]
385        args: Vec<Template>,
386        /// Extra environment variables for the process.
387        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
388        env: BTreeMap<String, Template>,
389        /// Where it runs, relative to the script root (`schedr.toml`'s directory by default).
390        working_dir: String,
391        /// Its part in a resource (`ScriptResource`, `cleanup_script`), if any.
392        #[serde(default, skip_serializing_if = "Option::is_none")]
393        resource: Option<ResourceRole>,
394    },
395    /// An `EmptyOperator`: completed by the master, no process.
396    Empty,
397}
398
399/// `TriggerDagOperator`'s `wait` when not given: it waits.
400const fn default_wait() -> bool {
401    true
402}
403
404/// A command's or a script's part in a resource, for `schedr task-ctx resource set|get`.
405#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
406#[serde(tag = "role", rename_all = "snake_case", deny_unknown_fields)]
407pub enum ResourceRole {
408    /// A `CommandResource`'s or `ScriptResource`'s setup: its output is the value it reports with `resource set`,
409    /// of the task's `output_type` (`none`: it reports nothing), not its `ProcessResult`.
410    Setup,
411    /// A resource's `cleanup_command` or `cleanup_script`: it reads the setup's value with
412    /// `resource get`.
413    Cleanup {
414        /// The resource's setup task.
415        setup: TaskId,
416    },
417}
418
419/// What a task's cleanup runs: of the same kind as the task (see archive/PROJECT.md, Per-task
420/// cleanup).
421#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
422#[serde(rename_all = "snake_case", deny_unknown_fields)]
423pub enum CleanupRun {
424    /// The function given to `@task(cleanup=...)`, found with the task's when the runner
425    /// imports the DAG file.
426    Python,
427    /// A command, with the task's environment.
428    Command(CommandLine),
429    /// A script of the task's script root (`[jobs.<name>.cleanup]`), with the task's
430    /// environment and working directory.
431    Script {
432        /// The script, relative to the script root.
433        script: String,
434        /// The interpreter: an `[interpreters]` entry of the worker that runs it.
435        interpreter: String,
436        /// Its arguments, each one argument (never a shell string).
437        #[serde(default, skip_serializing_if = "Vec::is_empty")]
438        args: Vec<Template>,
439    },
440}
441
442/// A task's cleanup: `finally` for each of its attempts (see archive/PROJECT.md, Per-task cleanup).
443#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
444#[serde(deny_unknown_fields)]
445pub struct TaskCleanup {
446    /// What it runs.
447    pub run: CleanupRun,
448    /// How long one try may run, in milliseconds; `None`: `[worker] cleanup_timeout`.
449    #[serde(default, skip_serializing_if = "Option::is_none")]
450    pub timeout_ms: Option<u64>,
451    /// How many times it is retried after a failed try, on the same worker.
452    pub retries: u32,
453    /// The delay before each retry, in milliseconds.
454    pub retry_delay_ms: u64,
455    /// The handle types it takes: `None` any, none listed none (a function without a `handles`
456    /// parameter would never see them).
457    #[serde(default, skip_serializing_if = "Option::is_none")]
458    pub handles: Option<Vec<String>>,
459    /// Whether it may run on another worker when its own is lost (`cleanup_anywhere`).
460    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
461    pub anywhere: bool,
462}
463
464/// What a mapped task's instances vary over (decision 69): one instance per element.
465#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
466#[serde(rename_all = "snake_case", deny_unknown_fields)]
467pub enum Expand {
468    /// `.expand(name=values, ...)`: each argument a list (a literal or a reference to a list),
469    /// in the order written; the instances are their cartesian product, the first argument
470    /// varying slowest (decision 79).
471    Product(Vec<Mapped>),
472    /// `.expand_kwargs(values)`: a list of dicts, each one instance's arguments.
473    Kwargs(Value),
474}
475
476/// One mapped argument of `.expand(...)`: its name and the list it maps over.
477#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
478#[serde(deny_unknown_fields)]
479pub struct Mapped {
480    /// The parameter's name.
481    pub name: String,
482    /// Its list: a literal, or a reference to a list.
483    pub value: Value,
484}
485
486/// A task of a DAG.
487#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
488pub struct Task {
489    /// The task's ID, unique within its DAG.
490    pub id: TaskId,
491    /// Its kind and what it runs.
492    #[serde(flatten)]
493    pub kind: TaskKind,
494    /// Its resolved settings.
495    pub settings: TaskSettings,
496    /// The type of its output (`process_result` for commands, `none` for empty tasks).
497    pub output_type: TypeDesc,
498    /// The outcomes it may end with (see archive/PROJECT.md, Task results and outcomes).
499    #[serde(
500        default = "default_outcomes",
501        skip_serializing_if = "is_default_outcomes"
502    )]
503    pub outcomes: Vec<OutcomeDecl>,
504    /// The group it belongs to (the innermost), if any (decision 64).
505    #[serde(default, skip_serializing_if = "Option::is_none")]
506    pub group: Option<String>,
507    /// What its instances vary over, for a mapped task (`.expand(...)`); its `arguments` are
508    /// then the fixed ones (`.partial(...)`).
509    #[serde(default, skip_serializing_if = "Option::is_none")]
510    pub expand: Option<Expand>,
511    /// The secrets it declares (`secrets=`): read on demand, never put in its environment.
512    #[serde(default, skip_serializing_if = "Vec::is_empty")]
513    pub secrets: Vec<SecretDecl>,
514    /// The connections it opens (`connections=`, decision 179), by name: only these, opened
515    /// before it starts.
516    #[serde(default, skip_serializing_if = "Vec::is_empty")]
517    pub connections: Vec<String>,
518    /// Its cleanup, if it has one.
519    #[serde(default, skip_serializing_if = "Option::is_none")]
520    pub cleanup: Option<TaskCleanup>,
521}
522
523impl Task {
524    /// The outcome a `command` task's exit code means, if it declared it.
525    #[must_use]
526    pub fn outcome_of_exit(&self, code: i32) -> Option<&str> {
527        self.outcomes
528            .iter()
529            .find(|o| o.exit_code == Some(code))
530            .map(|o| o.name.as_str())
531    }
532}
533
534impl Task {
535    /// Its cleanup's command line, if it has one.
536    #[must_use]
537    pub fn cleanup_command(&self) -> Option<&CommandLine> {
538        match self.cleanup.as_ref().map(|c| &c.run) {
539            Some(CleanupRun::Command(command)) => Some(command),
540            Some(CleanupRun::Python | CleanupRun::Script { .. }) | None => None,
541        }
542    }
543
544    /// Its cleanup script's arguments, if it has one.
545    #[must_use]
546    pub fn cleanup_script_args(&self) -> &[Template] {
547        match self.cleanup.as_ref().map(|c| &c.run) {
548            Some(CleanupRun::Script { args, .. }) => args,
549            _ => &[],
550        }
551    }
552
553    /// Every reference the task uses (arguments, command line, environment, what it is
554    /// mapped over), in order.
555    #[must_use]
556    pub fn references(&self) -> Vec<&Reference> {
557        let mut found = self.argument_references();
558        match &self.expand {
559            Some(Expand::Product(over)) => {
560                found.extend(over.iter().flat_map(|m| m.value.references()));
561            }
562            Some(Expand::Kwargs(over)) => found.extend(over.references()),
563            None => {}
564        }
565        found
566    }
567
568    /// The secrets its references name, in order (each once).
569    #[must_use]
570    pub fn secret_references(&self) -> Vec<&SecretName> {
571        let mut found: Vec<&SecretName> = Vec::new();
572        for reference in self.references() {
573            if let Reference::Secret(name) = reference
574                && !found.contains(&name)
575            {
576                found.push(name);
577            }
578        }
579        found
580    }
581
582    /// The references of its arguments, command line and environment, in order: all but what
583    /// it is mapped over.
584    #[must_use]
585    pub fn argument_references(&self) -> Vec<&Reference> {
586        match &self.kind {
587            TaskKind::Python { arguments, .. } => {
588                arguments.values().flat_map(Value::references).collect()
589            }
590            TaskKind::Sensor {
591                arguments,
592                wait_for,
593                ..
594            } => arguments
595                .values()
596                .chain(
597                    wait_for
598                        .iter()
599                        .filter_map(|w| w.event.as_ref())
600                        .filter_map(|e| e.key.as_ref()),
601                )
602                .flat_map(Value::references)
603                .collect(),
604            TaskKind::Command { command, env, .. } => command
605                .templates()
606                .into_iter()
607                .chain(
608                    self.cleanup_command()
609                        .into_iter()
610                        .flat_map(CommandLine::templates),
611                )
612                .chain(env.values())
613                .flat_map(Template::references)
614                .collect(),
615            TaskKind::Script { args, env, .. } => args
616                .iter()
617                .chain(self.cleanup_script_args())
618                .chain(env.values())
619                .flat_map(Template::references)
620                .collect(),
621            TaskKind::WaitForEvent { event, .. } => {
622                event.key.iter().flat_map(Value::references).collect()
623            }
624            TaskKind::TriggerDag {
625                params,
626                planned_for,
627                ..
628            } => params
629                .values()
630                .chain(planned_for)
631                .flat_map(Value::references)
632                .collect(),
633            TaskKind::Empty | TaskKind::FirstOf { .. } | TaskKind::WaitFor { .. } => Vec::new(),
634        }
635    }
636}