Skip to main content

schedr_model/
commands.rs

1//! Commands: actions a person asks for (UI, CLI, API), written by the webserver as command
2//! rows and applied by the master, which stays the only writer of scheduling state (see
3//! archive/PROJECT.md, Web UI and CLI: how the webserver gets state).
4
5use jiff::Timestamp;
6use serde::{Deserialize, Serialize};
7
8use crate::ids::{DagId, TaskId};
9
10#[cfg(test)]
11mod tests;
12
13/// The event a manual run of an event-triggered DAG brings. It is never stored as an event: a key
14/// given here would make the real event a repeat later.
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(tag = "kind", rename_all = "snake_case")]
17pub enum AskedEvent {
18    /// One the trigger found, by its key.
19    Stored {
20        /// Its key.
21        key: String,
22    },
23    /// One given here.
24    Given {
25        /// Its key.
26        key: String,
27        /// Its data.
28        data: serde_json::Value,
29        /// When it happened; the run's moment otherwise.
30        #[serde(default, skip_serializing_if = "Option::is_none")]
31        at: Option<Timestamp>,
32    },
33}
34
35/// A backfill asked for: a `backfill` run per fire time from `from` to `to` (now if not given)
36/// with no successful, queued or running run, or every one with `all`; with `dry_run`, only
37/// counted.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(deny_unknown_fields)]
40pub struct BackfillRequest {
41    /// The DAG.
42    pub dag_id: DagId,
43    /// The range's first moment.
44    pub from: Timestamp,
45    /// Its last moment; now if not given.
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    pub to: Option<Timestamp>,
48    /// A run for every fire time (`--all`).
49    #[serde(default)]
50    pub all: bool,
51    /// Values for the runs' parameters, over the DAG's defaults.
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub params: Option<serde_json::Map<String, serde_json::Value>>,
54    /// Count only, creating nothing (`--dry-run`).
55    #[serde(default)]
56    pub dry_run: bool,
57}
58
59/// An action asked for by a person.
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
62pub enum Command {
63    /// Start a manual run, for `planned_for` (`--for`) or now.
64    TriggerRun {
65        /// The DAG.
66        dag_id: DagId,
67        /// The moment the run is for; now if not given.
68        #[serde(default, skip_serializing_if = "Option::is_none")]
69        planned_for: Option<Timestamp>,
70        /// Values for the run's parameters, as JSON, over the DAG's defaults (decision 138).
71        #[serde(default, skip_serializing_if = "Option::is_none")]
72        params: Option<serde_json::Map<String, serde_json::Value>>,
73        /// The event it brings, for a DAG a trigger starts.
74        #[serde(default, skip_serializing_if = "Option::is_none")]
75        event: Option<AskedEvent>,
76    },
77    /// Create a backfill (`schedr runs backfill`, decisions 363, 364, 400-404).
78    Backfill(BackfillRequest),
79    /// Cancel a backfill's queued and running runs (`schedr runs cancel --backfill`,
80    /// decision 402); its finished runs stay.
81    CancelBackfill {
82        /// The backfill.
83        backfill_id: String,
84    },
85    /// Start a DAG's trigger again from its bookmark, whatever stopped it (`schedr triggers restart`).
86    RestartTrigger {
87        /// Its DAG.
88        dag_id: DagId,
89    },
90    /// Pass the run an `@trigger(wait_for=...)` keeps failing on, so it is called for the next
91    /// (`schedr triggers skip`, decision 353); refused while a call of it runs.
92    SkipTriggerRun {
93        /// Its DAG.
94        dag_id: DagId,
95    },
96    /// Cancel a run (queued or running).
97    CancelRun {
98        /// The run.
99        run_id: String,
100    },
101    /// Stop the scheduler from creating runs of a DAG; optionally cancel its runs in progress.
102    PauseDag {
103        /// The DAG.
104        dag_id: DagId,
105        /// Also cancel its queued and running runs.
106        #[serde(default)]
107        cancel_runs: bool,
108    },
109    /// Let the scheduler create runs of a DAG again.
110    UnpauseDag {
111        /// The DAG.
112        dag_id: DagId,
113    },
114    /// Switch a wait step back on (`schedr sensors switch-on`, decision 338).
115    SwitchOnSensor {
116        /// Its DAG.
117        dag_id: DagId,
118        /// The wait step.
119        sensor: TaskId,
120    },
121    /// Cancel one task of a run (`schedr tasks cancel`): stopped if it runs, cancelled at
122    /// once if it hasn't started; the tasks downstream of it are cancelled.
123    CancelTask {
124        /// The run.
125        run_id: String,
126        /// The task.
127        task_id: TaskId,
128        /// One instance of a mapped task; none: the whole task (decision 82).
129        #[serde(default, skip_serializing_if = "Option::is_none")]
130        map_index: Option<i32>,
131    },
132    /// Queue an `unschedulable` task of an unfinished run again (`schedr tasks retry`).
133    RetryTask {
134        /// The run.
135        run_id: String,
136        /// The task.
137        task_id: TaskId,
138        /// The instance of a mapped task (decision 82).
139        #[serde(default, skip_serializing_if = "Option::is_none")]
140        map_index: Option<i32>,
141    },
142    /// Drain a worker for maintenance (`schedr workers drain`): no new tasks, its running ones
143    /// finish; kept across restarts until resumed.
144    DrainWorker {
145        /// The worker.
146        worker_id: String,
147    },
148    /// Let a drained worker take tasks again (`schedr workers resume`).
149    ResumeWorker {
150        /// The worker.
151        worker_id: String,
152    },
153    /// Render connections on a worker (`schedr connections check`, decisions 174, 193): every
154    /// secret present or missing, never a value. Each root on a worker having its current
155    /// code; the command's result fills in as the workers answer.
156    CheckConnections {
157        /// The root; none: every root with connections.
158        #[serde(default, skip_serializing_if = "Option::is_none")]
159        root: Option<String>,
160        /// One connection; none: all of the root's.
161        #[serde(default, skip_serializing_if = "Option::is_none")]
162        name: Option<String>,
163        /// The worker to run it on; none: one the master picks.
164        #[serde(default, skip_serializing_if = "Option::is_none")]
165        worker: Option<String>,
166    },
167    /// Open a connection on a worker and run its check (`schedr connections test`, decisions
168    /// 193, 198-200): beside the tasks, no slot, one at a time per worker.
169    TestConnection {
170        /// The connection.
171        name: String,
172        /// Its root; none: the one root defining it.
173        #[serde(default, skip_serializing_if = "Option::is_none")]
174        root: Option<String>,
175        /// The worker to run it on; none: one the master picks.
176        #[serde(default, skip_serializing_if = "Option::is_none")]
177        worker: Option<String>,
178        /// How long it may take (decision 200: 60 s unless given), in milliseconds.
179        timeout_ms: u64,
180    },
181}
182
183/// The longest a connection test may be given (`--timeout`): an hour.
184pub const MAX_CONNECTION_TEST_MS: u64 = 3_600_000;
185
186/// How long a worker gives a connections check (its secrets read, each connection rendered),
187/// waiting for its turn included; a test is given its own timeout.
188pub const CONNECTION_CHECK_TIMEOUT_MS: u64 = 30_000;
189
190/// How long past its time the master waits for a connections job's answer before calling it
191/// lost (a test's process being stopped, the answer on its way).
192pub const CONNECTION_ANSWER_MARGIN_MS: u64 = 30_000;
193
194/// The result of a connections command, as stored with it: one job per root, filled in as
195/// the workers answer.
196#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
197#[serde(deny_unknown_fields)]
198pub struct ConnectionsResult {
199    /// A job per root.
200    pub jobs: Vec<ConnectionJobResult>,
201}
202
203impl ConnectionsResult {
204    /// Whether every job has an answer (or never will).
205    #[must_use]
206    pub fn finished(&self) -> bool {
207        self.jobs.iter().all(|job| job.state != JobState::Running)
208    }
209}
210
211/// One root's job: the worker it went to and, once it answered, each connection's report.
212#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
213#[serde(deny_unknown_fields)]
214pub struct ConnectionJobResult {
215    /// The root.
216    pub root: String,
217    /// The worker running it.
218    pub worker: String,
219    /// Where it stands.
220    pub state: JobState,
221    /// Why it has no answer (`lost`).
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub reason: Option<String>,
224    /// Each connection's report, once done.
225    #[serde(default, skip_serializing_if = "Vec::is_empty")]
226    pub connections: Vec<ConnectionReport>,
227}
228
229/// Where a connections job stands.
230#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
231#[serde(rename_all = "snake_case")]
232pub enum JobState {
233    /// Sent to its worker, no answer yet.
234    Running,
235    /// Answered.
236    Done,
237    /// No answer came: its worker went away or restarted, the master restarted, or the
238    /// answer didn't come in time.
239    Lost,
240}
241
242/// What a worker found about one connection: never a value.
243#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
244#[serde(deny_unknown_fields)]
245pub struct ConnectionReport {
246    /// The connection.
247    pub name: String,
248    /// Whether it rendered (a check) or opened and passed its check (a test).
249    pub ok: bool,
250    /// Each secret it names, and whether the worker's storage has it.
251    #[serde(default, skip_serializing_if = "Vec::is_empty")]
252    pub secrets: Vec<SecretReport>,
253    /// What went wrong, masked.
254    #[serde(default, skip_serializing_if = "Option::is_none")]
255    pub error: Option<String>,
256    /// How long a test took, in milliseconds.
257    #[serde(default, skip_serializing_if = "Option::is_none")]
258    pub duration_ms: Option<u64>,
259}
260
261/// A secret a connection names, as the worker found it.
262#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
263#[serde(deny_unknown_fields)]
264pub struct SecretReport {
265    /// The secret, as a DAG writes it (`secrets['etl/db']['password']`).
266    pub secret: String,
267    /// What the storage said.
268    pub state: SecretState,
269    /// Why it can't be read, for a `denied` or `unavailable` one.
270    #[serde(default, skip_serializing_if = "Option::is_none")]
271    pub message: Option<String>,
272}
273
274/// What a storage said of a secret.
275#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
276#[serde(rename_all = "snake_case")]
277pub enum SecretState {
278    /// It is there.
279    Present,
280    /// It isn't, and its default stands in (decision 176).
281    Default,
282    /// It isn't.
283    Missing,
284    /// The worker may not read it.
285    Denied,
286    /// The storage didn't answer.
287    Unavailable,
288}
289
290impl Command {
291    /// The command's kind, as stored in its row (`trigger_run`, `cancel_run`, ...).
292    #[must_use]
293    pub const fn kind(&self) -> &'static str {
294        match self {
295            Self::TriggerRun { .. } => "trigger_run",
296            Self::Backfill(_) => "backfill",
297            Self::CancelBackfill { .. } => "cancel_backfill",
298            Self::CancelRun { .. } => "cancel_run",
299            Self::PauseDag { .. } => "pause_dag",
300            Self::UnpauseDag { .. } => "unpause_dag",
301            Self::SwitchOnSensor { .. } => "switch_on_sensor",
302            Self::RestartTrigger { .. } => "restart_trigger",
303            Self::SkipTriggerRun { .. } => "skip_trigger_run",
304            Self::CancelTask { .. } => "cancel_task",
305            Self::RetryTask { .. } => "retry_task",
306            Self::DrainWorker { .. } => "drain_worker",
307            Self::ResumeWorker { .. } => "resume_worker",
308            Self::CheckConnections { .. } => "check_connections",
309            Self::TestConnection { .. } => "test_connection",
310        }
311    }
312}
313
314/// Where a command stands.
315#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
316#[serde(rename_all = "snake_case")]
317pub enum CommandStatus {
318    /// Written, not yet applied by the master.
319    Pending,
320    /// Applied.
321    Applied,
322    /// Not applied, with a reason.
323    Rejected,
324}