1use std::collections::{BTreeMap, HashMap};
8use std::sync::Arc;
9
10use jiff::Timestamp;
11use schedr_model::{Dag, DagId, RunKind, RunState};
12use uuid::Uuid;
13
14use crate::database::{Database, DbError};
15use crate::query::{db_time, from_name, in_tx, on_pool, parse_time, sql, sql_text};
16
17macro_rules! queued_from {
19 () => {
20 "FROM runs WHERE state = 'queued'"
21 };
22}
23pub(crate) use queued_from;
24
25#[cfg(test)]
26mod tests;
27
28const DAGS_PER_QUERY: usize = 500;
30
31fn among(column: &str, count: usize) -> String {
33 if count == 0 {
34 return String::new();
35 }
36 let wanted: Vec<String> = (1..=count).map(|n| format!("${n}")).collect();
37 format!(" AND {column} IN ({})", wanted.join(", "))
38}
39
40fn last_scheduled_query(count: usize) -> String {
45 let among = among("d.dag_id", count);
46 format!(
47 "SELECT d.dag_id, {{ts<}}(SELECT MAX(r.planned_for) FROM runs r \
48 WHERE r.kind = 'scheduled' AND r.dag_id = d.dag_id){{>ts}} \
49 FROM dags d WHERE TRUE{among}"
50 )
51}
52
53pub(crate) fn dag_id_of(text: String) -> Result<DagId, DbError> {
54 DagId::new(text).map_err(|e| DbError::InvalidData {
55 what: "dag_id",
56 reason: e.to_string(),
57 })
58}
59
60#[derive(Debug, Clone)]
62pub struct NewRun<'a> {
63 pub dag_id: &'a DagId,
65 pub dag_version_id: &'a str,
67 pub kind: RunKind,
69 pub state: RunState,
71 pub planned_for: Timestamp,
73 pub since: Timestamp,
75 pub triggered_at: Timestamp,
77 pub triggered_by: &'a str,
79 pub params: &'a serde_json::Value,
81 pub event: Option<&'a schedr_model::RunEvent>,
83 pub parent_run_id: Option<&'a str>,
86 pub backfill_id: Option<&'a str>,
88}
89
90pub static NO_PARAMS: std::sync::LazyLock<serde_json::Value> =
92 std::sync::LazyLock::new(|| serde_json::Value::Object(serde_json::Map::new()));
93
94#[derive(Debug, Clone, PartialEq, Eq)]
96pub struct QueuedRun {
97 pub id: String,
99 pub kind: RunKind,
101 pub triggered_at: Timestamp,
103 pub planned_for: Timestamp,
105}
106
107#[derive(Debug, Clone, Default, PartialEq, Eq)]
110pub struct RunOverview {
111 pub running: BTreeMap<String, u32>,
113 pub last_scheduled: BTreeMap<String, Timestamp>,
115 pub queued: BTreeMap<String, Vec<QueuedRun>>,
117}
118
119impl RunOverview {
120 #[must_use]
122 pub fn running(&self, dag_id: &DagId) -> u32 {
123 self.running.get(dag_id.as_str()).copied().unwrap_or(0)
124 }
125
126 #[must_use]
128 pub fn last_scheduled(&self, dag_id: &DagId) -> Option<Timestamp> {
129 self.last_scheduled.get(dag_id.as_str()).copied()
130 }
131
132 #[must_use]
134 pub fn queued(&self, dag_id: &DagId) -> &[QueuedRun] {
135 self.queued.get(dag_id.as_str()).map_or(&[], Vec::as_slice)
136 }
137}
138
139#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct ActiveDag {
142 pub paused: bool,
145 pub held: Option<Held>,
148 pub first_seen: Timestamp,
150 pub version_id: String,
152 pub dag: Arc<Dag>,
154}
155
156#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct Held {
159 pub path: String,
161 pub exception: String,
163 pub message: String,
165 pub schedr_version: String,
168}
169
170impl Held {
171 #[must_use]
175 pub fn reason(&self, dag_id: &str) -> String {
176 use schedr_model::runner::{
177 INVALID_DAG_EXCEPTION, INVALID_PATH_EXCEPTION, PARSE_RESULT_TOO_LARGE_EXCEPTION,
178 };
179 let path = &self.path;
180 let message = &self.message;
181 let what = match self.exception.as_str() {
182 PARSE_RESULT_TOO_LARGE_EXCEPTION => format!(
183 "the parse result of its file `{path}` (the JSON of all the file's DAGs \
184 together, not of `{dag_id}` alone) is too large for the master: {message}. \
185 Every DAG of the file is held until it fits: move large DAGs to files of their \
186 own, keep large data out of the DAGs' arguments (load it when the task runs), \
187 or raise [grpc] max_message_size"
188 ),
189 INVALID_DAG_EXCEPTION => format!(
190 "its file `{path}` imports, but defines a DAG the master's checks refuse \
191 ({message}). Every DAG of the file is held while one is invalid: fix that DAG, \
192 or move it to a file of its own"
193 ),
194 INVALID_PATH_EXCEPTION => format!(
195 "its file `{path}` isn't inside its root ({message}). Every DAG of the file is \
196 held until it is"
197 ),
198 exception => format!(
199 "its file `{path}` fails to import with schedr {} ({exception}: {message}), so \
200 its tasks couldn't run. Every DAG of the file is held until it imports: fix \
201 the file, or, if it stopped importing when schedr was upgraded, roll back",
202 self.schedr_version
203 ),
204 };
205 format!("DAG `{dag_id}` is held, no runs are created and it can't be triggered: {what}")
206 }
207 #[must_use]
211 pub fn by_file(errors: &[crate::dags::ImportErrorRecord]) -> HashMap<(String, String), Self> {
212 errors
213 .iter()
214 .filter(|e| !e.error.is_transient())
215 .map(|e| {
216 let held = Self {
217 path: e.path.clone(),
218 exception: e.error.exception.clone(),
219 message: e.error.message.clone(),
220 schedr_version: e.schedr_version.clone(),
221 };
222 ((e.root.clone(), e.path.clone()), held)
223 })
224 .collect()
225 }
226
227 #[must_use]
229 pub fn of(dag: &Dag, held: &HashMap<(String, String), Self>) -> Option<Self> {
230 held.get(&(dag.location.root.clone(), dag.location.path.clone()))
231 .cloned()
232 }
233}
234
235impl Database {
236 pub async fn insert_run(&self, run: &NewRun<'_>) -> Result<Option<String>, DbError> {
243 self.insert_run_as(&Uuid::now_v7().to_string(), run).await
244 }
245
246 pub async fn insert_run_as(
253 &self,
254 id: &str,
255 run: &NewRun<'_>,
256 ) -> Result<Option<String>, DbError> {
257 const INSERT: &str = "INSERT INTO runs \
258 (id, dag_id, dag_version_id, kind, state, planned_for, since, triggered_at, \
259 triggered_by, started_at, params, event, parent_run_id, backfill_id) \
260 VALUES ($1{uuid}, $2, $3{uuid}, $4, $5, $6{ts}, $7{ts}, $8{ts}, $9, $10{ts}, \
261 $11{json}, $12{json}, $13{uuid}, $14{uuid}) ON CONFLICT DO NOTHING";
262 let started_at = (run.state == RunState::Running).then(|| db_time(run.triggered_at));
263 let inserted = in_tx!(self, |tx, backend| {
264 sqlx::query(sql(backend, INSERT))
265 .bind(id)
266 .bind(run.dag_id.as_str())
267 .bind(run.dag_version_id)
268 .bind(run.kind.to_string())
269 .bind(run.state.to_string())
270 .bind(db_time(run.planned_for))
271 .bind(db_time(run.since))
272 .bind(db_time(run.triggered_at))
273 .bind(run.triggered_by)
274 .bind(started_at)
275 .bind(run.params.to_string())
276 .bind(run.event.map(crate::query::to_json))
277 .bind(run.parent_run_id)
278 .bind(run.backfill_id)
279 .execute(&mut *tx)
280 .await?
281 .rows_affected()
282 });
283 Ok((inserted == 1).then(|| id.to_owned()))
284 }
285
286 pub async fn run_params(&self, run_id: &str) -> Result<Option<serde_json::Value>, DbError> {
292 const PARAMS: &str = "SELECT params{text} FROM runs WHERE id = $1{uuid}";
293 let text: Option<String> = on_pool!(self, |pool, backend| {
294 sqlx::query_scalar(sql(backend, PARAMS))
295 .bind(run_id)
296 .fetch_optional(pool)
297 .await?
298 });
299 text.map(|t| crate::query::from_json("runs.params", &t))
300 .transpose()
301 }
302
303 pub async fn last_scheduled_for(&self, dag_id: &DagId) -> Result<Option<Timestamp>, DbError> {
310 const LAST: &str = "SELECT {ts<}MAX(planned_for){>ts} FROM runs \
311 WHERE dag_id = $1 AND kind = 'scheduled'";
312 self.optional_time(LAST, dag_id, None).await
313 }
314
315 pub async fn nearest_earlier_run(
321 &self,
322 dag_id: &DagId,
323 before: Timestamp,
324 ) -> Result<Option<Timestamp>, DbError> {
325 const NEAREST: &str = "SELECT {ts<}MAX(planned_for){>ts} FROM runs \
326 WHERE dag_id = $1 AND planned_for < $2{ts}";
327 self.optional_time(NEAREST, dag_id, Some(before)).await
328 }
329
330 async fn optional_time(
331 &self,
332 query: &'static str,
333 dag_id: &DagId,
334 at: Option<Timestamp>,
335 ) -> Result<Option<Timestamp>, DbError> {
336 let text: Option<String> = on_pool!(self, |pool, backend| {
337 let mut q = sqlx::query_scalar(sql(backend, query)).bind(dag_id.as_str());
338 if let Some(at) = at {
339 q = q.bind(db_time(at));
340 }
341 q.fetch_one(pool).await?
342 });
343 text.map(|t| parse_time("runs.planned_for", &t)).transpose()
344 }
345
346 pub async fn running_count(&self, dag_id: &DagId) -> Result<u32, DbError> {
352 const COUNT: &str = "SELECT COUNT(*) FROM runs WHERE dag_id = $1 AND state = 'running'";
353 let count: i64 = on_pool!(self, |pool, backend| {
354 sqlx::query_scalar(sql(backend, COUNT))
355 .bind(dag_id.as_str())
356 .fetch_one(pool)
357 .await?
358 });
359 Ok(u32::try_from(count).unwrap_or(u32::MAX))
360 }
361
362 pub async fn queued_runs(&self, dag_id: &DagId) -> Result<Vec<QueuedRun>, DbError> {
368 const QUEUED: &str = "SELECT id{text}, kind, {ts<}triggered_at{>ts}, \
369 {ts<}planned_for{>ts} FROM runs \
370 WHERE dag_id = $1 AND state = 'queued' ORDER BY triggered_at, planned_for, id";
371 let rows: Vec<(String, String, String, String)> = on_pool!(self, |pool, backend| {
372 sqlx::query_as(sql(backend, QUEUED))
373 .bind(dag_id.as_str())
374 .fetch_all(pool)
375 .await?
376 });
377 rows.into_iter()
378 .map(|(id, kind, triggered_at, planned_for)| {
379 Ok(QueuedRun {
380 id,
381 kind: from_name("runs.kind", kind)?,
382 triggered_at: parse_time("runs.triggered_at", &triggered_at)?,
383 planned_for: parse_time("runs.planned_for", &planned_for)?,
384 })
385 })
386 .collect()
387 }
388
389 pub async fn run_overview(&self) -> Result<RunOverview, DbError> {
397 let mut overview = RunOverview::default();
398 self.overview_into(&mut overview, &[]).await?;
399 Ok(overview)
400 }
401
402 pub async fn run_overview_of(&self, dags: &[&DagId]) -> Result<RunOverview, DbError> {
410 let mut overview = RunOverview::default();
411 for chunk in dags.chunks(DAGS_PER_QUERY) {
412 self.overview_into(&mut overview, chunk).await?;
413 }
414 Ok(overview)
415 }
416
417 async fn overview_into(
419 &self,
420 overview: &mut RunOverview,
421 dags: &[&DagId],
422 ) -> Result<(), DbError> {
423 type Rows = (
424 Vec<(String, i64)>,
425 Vec<(String, Option<String>)>,
426 Vec<(String, String, String, String, String)>,
427 );
428 let among = among("dag_id", dags.len());
429 let running = format!(
430 "SELECT dag_id, COUNT(*) FROM runs WHERE state = 'running'{among} GROUP BY dag_id"
431 );
432 let last = last_scheduled_query(dags.len());
433 let queued = format!(
434 "SELECT dag_id, id{{text}}, kind, {{ts<}}triggered_at{{>ts}}, \
435 {{ts<}}planned_for{{>ts}} FROM runs \
436 WHERE state = 'queued'{among} ORDER BY dag_id, triggered_at, planned_for, id"
437 );
438 let (running, last, queued): Rows = on_pool!(self, |pool, backend| {
440 let mut running_query = sqlx::query_as(sql_text(backend, &running));
441 let mut last_query = sqlx::query_as(sql_text(backend, &last));
442 let mut queued_query = sqlx::query_as(sql_text(backend, &queued));
443 for dag in dags {
444 running_query = running_query.bind(dag.as_str());
445 last_query = last_query.bind(dag.as_str());
446 queued_query = queued_query.bind(dag.as_str());
447 }
448 (
449 running_query.fetch_all(&mut *pool).await?,
450 last_query.fetch_all(&mut *pool).await?,
451 queued_query.fetch_all(&mut *pool).await?,
452 )
453 });
454 for (dag, count) in running {
455 overview
456 .running
457 .insert(dag, u32::try_from(count).unwrap_or(u32::MAX));
458 }
459 for (dag, at) in last {
460 let Some(at) = at else { continue };
462 overview
463 .last_scheduled
464 .insert(dag, parse_time("runs.planned_for", &at)?);
465 }
466 for (dag, id, kind, triggered_at, planned_for) in queued {
467 overview.queued.entry(dag).or_default().push(QueuedRun {
468 id,
469 kind: from_name("runs.kind", kind)?,
470 triggered_at: parse_time("runs.triggered_at", &triggered_at)?,
471 planned_for: parse_time("runs.planned_for", &planned_for)?,
472 });
473 }
474 Ok(())
475 }
476
477 pub async fn runs_in_progress(&self, dag_id: &DagId) -> Result<Vec<String>, DbError> {
483 const IN_PROGRESS: &str = "SELECT id{text} FROM runs \
484 WHERE dag_id = $1 AND state IN ('queued', 'running') ORDER BY triggered_at, id";
485 let ids: Vec<String> = on_pool!(self, |pool, backend| {
486 sqlx::query_scalar(sql(backend, IN_PROGRESS))
487 .bind(dag_id.as_str())
488 .fetch_all(pool)
489 .await?
490 });
491 Ok(ids)
492 }
493
494 pub async fn mark_late_failure(
502 &self,
503 run_id: &str,
504 reason: &str,
505 ) -> Result<Option<String>, DbError> {
506 const MARK: &str = "UPDATE runs SET late_failure = $1 \
507 WHERE id = $2{uuid} AND state = 'success' AND late_failure IS NULL RETURNING dag_id";
508 let marked: Option<(String,)> = in_tx!(self, |tx, backend| {
509 sqlx::query_as(sql(backend, MARK))
510 .bind(reason)
511 .bind(run_id)
512 .fetch_optional(&mut *tx)
513 .await?
514 });
515 Ok(marked.map(|(dag_id,)| dag_id))
516 }
517
518 pub async fn start_run(&self, run_id: &str, now: Timestamp) -> Result<(), DbError> {
524 const START: &str = "UPDATE runs SET state = 'running', started_at = $1{ts} \
525 WHERE id = $2{uuid} AND state = 'queued'";
526 in_tx!(self, |tx, backend| {
527 sqlx::query(sql(backend, START))
528 .bind(db_time(now))
529 .bind(run_id)
530 .execute(&mut *tx)
531 .await?;
532 });
533 Ok(())
534 }
535
536 pub async fn active_dags(&self) -> Result<Vec<ActiveDag>, DbError> {
543 let mut active = Vec::new();
544 self.active_into(&mut active, &[]).await?;
545 Ok(active)
546 }
547
548 pub async fn dags_with_queued_runs(&self) -> Result<Vec<DagId>, DbError> {
555 const QUEUED: &str = concat!("SELECT DISTINCT dag_id ", queued_from!());
556 if self.skipped(crate::probe::Check::QueuedRuns).await? {
557 return Ok(Vec::new());
558 }
559 let rows: Vec<String> = on_pool!(self, |pool, backend| {
560 sqlx::query_scalar(sql(backend, QUEUED))
561 .fetch_all(pool)
562 .await?
563 });
564 rows.into_iter().map(dag_id_of).collect()
565 }
566
567 pub async fn active_dag_versions(&self) -> Result<Vec<(DagId, String)>, DbError> {
575 const VERSIONS: &str = "SELECT dag_id, current_version_id{text} FROM dags \
576 WHERE current_version_id IS NOT NULL AND removed_at IS NULL AND conflict IS NULL \
577 ORDER BY dag_id";
578 let rows: Vec<(String, String)> = on_pool!(self, |pool, backend| {
579 sqlx::query_as(sql(backend, VERSIONS))
580 .fetch_all(pool)
581 .await?
582 });
583 rows.into_iter()
584 .map(|(dag, version)| Ok((dag_id_of(dag)?, version)))
585 .collect()
586 }
587
588 pub async fn active_dags_of(&self, dags: &[&DagId]) -> Result<Vec<ActiveDag>, DbError> {
594 let mut active = Vec::new();
595 for chunk in dags.chunks(DAGS_PER_QUERY) {
596 self.active_into(&mut active, chunk).await?;
597 }
598 active.sort_by(|a, b| a.dag.id.cmp(&b.dag.id));
599 Ok(active)
600 }
601
602 async fn active_into(
604 &self,
605 active: &mut Vec<ActiveDag>,
606 dags: &[&DagId],
607 ) -> Result<(), DbError> {
608 let text = format!(
609 "SELECT COALESCE(t.paused, TRUE), {{ts<}}d.first_seen_at{{>ts}}, \
610 d.current_version_id{{text}} \
611 FROM dags d LEFT JOIN dag_triggers t ON t.dag_id = d.dag_id \
612 WHERE d.current_version_id IS NOT NULL \
613 AND d.removed_at IS NULL AND d.conflict IS NULL{} ORDER BY d.dag_id",
614 among("d.dag_id", dags.len())
615 );
616 let rows: Vec<(bool, String, String)> = on_pool!(self, |pool, backend| {
617 let mut query = sqlx::query_as(sql_text(backend, &text));
618 for dag in dags {
619 query = query.bind(dag.as_str());
620 }
621 query.fetch_all(pool).await?
622 });
623 active.reserve(rows.len());
624 let held = Held::by_file(&self.current_import_errors().await?);
626 for (paused, first_seen, version_id) in rows {
627 let dag = self.dag_version(&version_id).await?;
629 active.push(ActiveDag {
630 paused,
631 held: Held::of(&dag, &held),
632 first_seen: parse_time("dags.first_seen_at", &first_seen)?,
633 version_id,
634 dag,
635 });
636 }
637 Ok(())
638 }
639}