Skip to main content

schedr_model/
dag.rs

1//! A DAG as stored in DAG JSON: what the Python runner sends after parsing a DAG file.
2
3use jiff::Timestamp;
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6
7use crate::ids::{DagId, TaskId};
8use crate::states::TaskInstanceState;
9use crate::task::Task;
10use crate::trigger::Trigger;
11use crate::version::SchedrVersion;
12
13#[cfg(test)]
14mod tests;
15
16/// Where a DAG is defined: a DAG root and a file path relative to it.
17#[derive(
18    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
19)]
20#[serde(deny_unknown_fields)]
21pub struct DagLocation {
22    /// The root's name (see archive/PROJECT.md, DAG roots).
23    pub root: String,
24    /// The file's path relative to the root, with `/` separators.
25    pub path: String,
26}
27
28/// Why one task depends on another.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
30#[serde(rename_all = "snake_case")]
31pub enum EdgeKind {
32    /// The downstream task takes the upstream task's output (or a part of it).
33    Data,
34    /// An order-only dependency (`>>`), no data passed.
35    Order,
36    /// From a `@branch` task: taken when the branch chose the downstream task.
37    Selection,
38    /// From a resource's setup to a user (`uses=`): it can stop the user, never make it run.
39    Requirement,
40}
41
42/// A dependency: `to` runs after `from`, when `from` ended with one of the outcomes `on`.
43#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
44#[serde(deny_unknown_fields)]
45pub struct Edge {
46    /// The upstream task.
47    pub from: TaskId,
48    /// The downstream task.
49    pub to: TaskId,
50    /// Why the dependency exists.
51    pub kind: EdgeKind,
52    /// The upstream outcomes the edge is taken on (`.on(...)`); empty for any outcome. An edge
53    /// not taken counts as skipped in the downstream task's trigger rule.
54    #[serde(default, skip_serializing_if = "Vec::is_empty")]
55    pub on: Vec<String>,
56}
57
58impl Edge {
59    /// Whether the edge is taken by an upstream task that succeeded with `outcome`.
60    #[must_use]
61    pub fn taken_on(&self, outcome: &str) -> bool {
62        self.on.is_empty() || self.on.iter().any(|on| on == outcome)
63    }
64}
65
66/// A resource: one thing of two parts, each a task of the DAG, both always there (decision 259).
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
68#[serde(deny_unknown_fields)]
69pub struct Resource {
70    /// The task that creates it; its ID is the resource's.
71    pub setup: TaskId,
72    /// The task that undoes it, once every user is done.
73    pub cleanup: TaskId,
74    /// The tasks that need it.
75    pub users: Vec<TaskId>,
76    /// Whether what follows its group waits for its cleanup (decision 266); the edges from
77    /// the cleanup say so, this is for showing them (decision 272).
78    #[serde(default = "yes", skip_serializing_if = "is_yes")]
79    pub blocking: bool,
80    /// How long a user may stay `unschedulable` before it fails, so the cleanup can run
81    /// (decision 273); none: no limit.
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub unschedulable_timeout_ms: Option<u64>,
84}
85
86const fn yes() -> bool {
87    true
88}
89
90#[expect(
91    clippy::trivially_copy_pass_by_ref,
92    reason = "serde's skip_serializing_if"
93)]
94const fn is_yes(value: &bool) -> bool {
95    *value
96}
97
98/// Where a resource stands in a run, from its two tasks' states (decision 275).
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
100#[serde(rename_all = "snake_case")]
101pub enum ResourceState {
102    /// Its setup hasn't ended yet.
103    SettingUp,
104    /// Its setup succeeded; its cleanup waits for the users.
105    WaitingForUsers,
106    /// Its cleanup is queued, running or waiting to be tried again.
107    CleaningUp,
108    /// Its cleanup succeeded.
109    Cleaned,
110    /// Its cleanup failed after its last retry.
111    CleanupFailed,
112    /// Its cleanup was cancelled (`schedr tasks cancel`): what the setup made may be left.
113    CleanupCancelled,
114    /// Its setup didn't succeed: there is nothing to clean.
115    NotNeeded,
116}
117
118impl ResourceState {
119    /// The state of a resource whose setup and cleanup are in these states.
120    #[must_use]
121    pub const fn of(setup: TaskInstanceState, cleanup: TaskInstanceState) -> Self {
122        use TaskInstanceState as S;
123        match cleanup {
124            S::Success => Self::Cleaned,
125            S::Failed => Self::CleanupFailed,
126            S::Queued | S::Unschedulable | S::Running | S::CleaningUp | S::UpForRetry => {
127                Self::CleaningUp
128            }
129            S::Skipped | S::UpstreamFailed => Self::NotNeeded,
130            // Cancelled with a setup that didn't succeed (a cancelled run): nothing was made.
131            S::Cancelled => match setup {
132                S::Failed | S::Skipped | S::UpstreamFailed | S::Cancelled => Self::NotNeeded,
133                _ => Self::CleanupCancelled,
134            },
135            S::Scheduled => match setup {
136                S::Success => Self::WaitingForUsers,
137                S::Failed | S::Skipped | S::UpstreamFailed | S::Cancelled => Self::NotNeeded,
138                _ => Self::SettingUp,
139            },
140        }
141    }
142}
143
144/// A DAG: its identity, trigger, tasks and dependencies.
145#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
146#[serde(deny_unknown_fields)]
147pub struct Dag {
148    /// The schedr version whose runner produced this JSON.
149    pub produced_by: SchedrVersion,
150    /// The DAG's ID.
151    pub id: DagId,
152    /// Where it is defined.
153    pub location: DagLocation,
154    /// A description shown in the UI.
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub description: Option<String>,
157    /// Tags shown in the UI and used for filtering.
158    #[serde(default, skip_serializing_if = "Vec::is_empty")]
159    pub tags: Vec<String>,
160    /// What starts its runs (besides people and other DAGs).
161    pub trigger: Trigger,
162    /// `since` of the run on the DAG's first fire time (see archive/PROJECT.md, Runs).
163    pub initial_since: Option<Timestamp>,
164    /// At most this many runs at a time; `None` for no limit.
165    pub max_active_runs: Option<u32>,
166    /// At most this many of its tasks running at once, across all its runs (each instance of
167    /// a mapped task counts); `None` for no limit.
168    #[serde(default, skip_serializing_if = "Option::is_none")]
169    #[schemars(range(min = 1))]
170    pub max_active_tasks: Option<u32>,
171    /// The tasks, in declaration order.
172    pub tasks: Vec<Task>,
173    /// The dependencies between them.
174    pub edges: Vec<Edge>,
175    /// The task groups (decision 64), for the UI and the API; the master schedules tasks only.
176    #[serde(default, skip_serializing_if = "Vec::is_empty")]
177    pub groups: Vec<Group>,
178    /// The run parameters it takes (`Dag(params=...)`); none: it takes none.
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub params: Option<Params>,
181    /// Its resources.
182    #[serde(default, skip_serializing_if = "Vec::is_empty")]
183    pub resources: Vec<Resource>,
184    /// The channels it notifies, and of which events (`Dag(notify=...)`, decision 409).
185    #[serde(default, skip_serializing_if = "Vec::is_empty")]
186    pub notify: Vec<crate::notify::NotifyEntry>,
187}
188
189/// The run parameters a DAG takes (`Dag(params=SomeDataclass)`, decision 138).
190#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
191#[serde(deny_unknown_fields)]
192pub struct Params {
193    /// The declared class's type: a dataclass or a Pydantic model. Values are stored by it,
194    /// as outputs are (tagged).
195    #[serde(rename = "type")]
196    pub ty: crate::TypeDesc,
197    /// A JSON Schema of the class, as JSON values (a date as `format: date`): what the master
198    /// checks a trigger's values against, and what the UI's form is built from.
199    #[schemars(with = "serde_json::Map<String, serde_json::Value>")]
200    pub schema: serde_json::Value,
201    /// The fields' defaults, as JSON: the values of a scheduled run, and of the fields a
202    /// trigger leaves out.
203    #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
204    pub defaults: serde_json::Map<String, serde_json::Value>,
205}
206
207/// A group of tasks (`with group("load"):`): a name for some of a DAG's tasks, drawn as a box
208/// around them in the UI. It has no state and no rule of its own (decision 56A).
209#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
210#[serde(deny_unknown_fields)]
211pub struct Group {
212    /// The group's ID, unique within its DAG (`load`, `load.eu` for a nested one).
213    pub id: String,
214    /// The group it is nested in, if any.
215    #[serde(default, skip_serializing_if = "Option::is_none")]
216    pub parent: Option<String>,
217}
218
219impl Dag {
220    /// The task with the given ID.
221    #[must_use]
222    pub fn task(&self, id: &TaskId) -> Option<&Task> {
223        self.tasks.iter().find(|t| &t.id == id)
224    }
225
226    /// The resource whose cleanup `id` is.
227    #[must_use]
228    pub fn resource_of_cleanup(&self, id: &TaskId) -> Option<&Resource> {
229        self.resources.iter().find(|r| &r.cleanup == id)
230    }
231
232    /// The edges into `id`, in order (one upstream task may have several, on different
233    /// outcomes).
234    pub fn edges_into<'a>(&'a self, id: &'a TaskId) -> impl Iterator<Item = &'a Edge> + 'a {
235        self.edges.iter().filter(move |e| &e.to == id)
236    }
237
238    /// The tasks `id` directly depends on, in edge order, without repeats.
239    #[must_use]
240    pub fn upstream_of(&self, id: &TaskId) -> Vec<&TaskId> {
241        let mut upstream: Vec<&TaskId> = Vec::new();
242        for edge in self.edges.iter().filter(|e| &e.to == id) {
243            if !upstream.contains(&&edge.from) {
244                upstream.push(&edge.from);
245            }
246        }
247        upstream
248    }
249
250    /// The tasks that directly depend on `id`, in edge order, without repeats.
251    #[must_use]
252    pub fn downstream_of(&self, id: &TaskId) -> Vec<&TaskId> {
253        let mut downstream: Vec<&TaskId> = Vec::new();
254        for edge in self.edges.iter().filter(|e| &e.from == id) {
255            if !downstream.contains(&&edge.to) {
256                downstream.push(&edge.to);
257            }
258        }
259        downstream
260    }
261}