1use jiff::Timestamp;
4
5use crate::database::{Database, DbError};
6use crate::query::{db_time, in_tx, on_pool, parse_time, sql};
7
8#[derive(Debug, Clone, PartialEq, Eq)]
10pub struct OtherRun {
11 pub run_id: String,
13 pub state: String,
16 pub ended_at: Option<Timestamp>,
18}
19
20#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum Matching {
23 PlannedFor(Timestamp),
25 EndedAfter(Timestamp),
27 EndedAfterRun(Timestamp, String),
30}
31
32#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct SensorWait {
35 pub since: Timestamp,
37 pub handed: Option<(String, Timestamp)>,
39 pub waited: Option<(String, Timestamp)>,
41}
42
43impl Database {
44 pub async fn runs_of(
51 &self,
52 dag: &str,
53 task: Option<&str>,
54 matching: Matching,
55 ) -> Result<Vec<OtherRun>, DbError> {
56 const RUNS_FOR: &str = "SELECT id{text}, state, {ts<}ended_at{>ts} FROM runs \
59 WHERE dag_id = $1 AND planned_for = $2{ts} ORDER BY triggered_at DESC, id DESC LIMIT 1";
60 const TASKS_FOR: &str = "SELECT r.id{text}, COALESCE(t.state, CASE WHEN r.state IN \
62 ('queued', 'running') THEN 'queued' ELSE 'missing' END), {ts<}t.ended_at{>ts} \
63 FROM runs r LEFT JOIN task_instances t \
64 ON t.run_id = r.id AND t.task_id = $3 AND t.map_index = -1 \
65 WHERE r.dag_id = $1 AND r.planned_for = $2{ts} \
66 ORDER BY r.triggered_at DESC, r.id DESC LIMIT 1";
67 const RUN_ENDED: &str = "SELECT id{text}, state, {ts<}ended_at{>ts} FROM runs \
68 WHERE dag_id = $1 AND ended_at >= $2{ts} ORDER BY ended_at, id LIMIT 1";
69 const TASK_ENDED: &str = "SELECT r.id{text}, t.state, {ts<}t.ended_at{>ts} \
70 FROM task_instances t JOIN runs r ON r.id = t.run_id \
71 WHERE t.task_id = $3 AND t.map_index = -1 AND t.ended_at >= $2{ts} AND r.dag_id = $1 \
72 ORDER BY t.ended_at, r.id LIMIT 1";
73 const RUN_AFTER: &str = "SELECT id{text}, state, {ts<}ended_at{>ts} FROM runs \
74 WHERE dag_id = $1 AND ended_at >= $2{ts} AND (ended_at > $2{ts} OR id > $4{uuid}) \
75 ORDER BY ended_at, id LIMIT 1";
76 const TASK_AFTER: &str = "SELECT r.id{text}, t.state, {ts<}t.ended_at{>ts} \
77 FROM task_instances t JOIN runs r ON r.id = t.run_id \
78 WHERE t.task_id = $3 AND t.map_index = -1 AND t.ended_at >= $2{ts} AND r.dag_id = $1 \
79 AND (t.ended_at > $2{ts} OR r.id > $4{uuid}) ORDER BY t.ended_at, r.id LIMIT 1";
80 let (query, at, after) = match (matching, task.is_some()) {
81 (Matching::PlannedFor(at), false) => (RUNS_FOR, at, None),
82 (Matching::PlannedFor(at), true) => (TASKS_FOR, at, None),
83 (Matching::EndedAfter(at), false) => (RUN_ENDED, at, None),
84 (Matching::EndedAfter(at), true) => (TASK_ENDED, at, None),
85 (Matching::EndedAfterRun(at, run), false) => (RUN_AFTER, at, Some(run)),
86 (Matching::EndedAfterRun(at, run), true) => (TASK_AFTER, at, Some(run)),
87 };
88 let rows: Vec<(String, String, Option<String>)> = on_pool!(self, |pool, backend| {
89 let mut statement = sqlx::query_as(sql(backend, query))
90 .bind(dag)
91 .bind(db_time(at))
92 .bind(task.unwrap_or_default());
93 if let Some(after) = &after {
94 statement = statement.bind(after);
95 }
96 statement.fetch_all(pool).await?
97 });
98 rows.into_iter()
99 .map(|(run_id, state, ended_at)| {
100 Ok(OtherRun {
101 run_id,
102 state,
103 ended_at: ended_at.map(|at| parse_time("ended_at", &at)).transpose()?,
104 })
105 })
106 .collect()
107 }
108
109 pub async fn park_wait(
119 &self,
120 instance_id: &str,
121 look_at: Timestamp,
122 (waits_dag, waits_event): (Option<&str>, Option<&str>),
123 ) -> Result<(), DbError> {
124 const PARK: &str = "UPDATE task_instances SET look_at = $1{ts}, waits_dag = $2, \
125 waits_event = $3 WHERE id = $4{uuid} AND state = 'queued'";
126 in_tx!(self, |tx, backend| {
127 sqlx::query(sql(backend, PARK))
128 .bind(db_time(look_at))
129 .bind(waits_dag)
130 .bind(waits_event)
131 .bind(instance_id)
132 .execute(&mut *tx)
133 .await?;
134 });
135 Ok(())
136 }
137
138 pub async fn ready_since(&self, instance_id: &str) -> Result<Option<Timestamp>, DbError> {
144 const SINCE: &str = "SELECT {ts<}ready_at{>ts} FROM task_instances WHERE id = $1{uuid} AND ready_at IS NOT NULL";
145 let row: Option<(String,)> = on_pool!(self, |pool, backend| {
146 sqlx::query_as(sql(backend, SINCE))
147 .bind(instance_id)
148 .fetch_optional(pool)
149 .await?
150 });
151 row.map(|(at,)| parse_time("task_instances.ready_at", &at))
152 .transpose()
153 }
154
155 pub async fn succeeded_since(
164 &self,
165 of: (&str, Option<&str>),
166 started: &str,
167 from: RunOfFrom<'_>,
168 limit: u32,
169 ) -> Result<Vec<(String, Timestamp, Timestamp)>, DbError> {
170 self.runs_since(of, started, from, limit, false).await
171 }
172
173 pub async fn ended_since(
180 &self,
181 of: (&str, Option<&str>),
182 from: RunOfFrom<'_>,
183 limit: u32,
184 ) -> Result<Vec<(String, Timestamp, Timestamp)>, DbError> {
185 self.runs_since(of, "", from, limit, true).await
186 }
187
188 async fn runs_since(
189 &self,
190 (dag, task): (&str, Option<&str>),
191 started: &str,
192 from: RunOfFrom<'_>,
193 limit: u32,
194 any_end: bool,
195 ) -> Result<Vec<(String, Timestamp, Timestamp)>, DbError> {
196 const RUNS_ENDED: &str = "SELECT r.id{text}, {ts<}r.planned_for{>ts}, {ts<}r.ended_at{>ts} FROM runs r \
197 WHERE r.dag_id = $1 AND r.state IN ('success', 'failed', 'cancelled') AND r.ended_at >= $2{ts} \
198 AND (r.ended_at > $2{ts} OR $4 IS NULL OR r.id > $4{uuid}) \
199 ORDER BY r.ended_at, r.id LIMIT $3";
200 const TASKS_ENDED: &str = "SELECT r.id{text}, {ts<}r.planned_for{>ts}, {ts<}t.ended_at{>ts} \
201 FROM task_instances t JOIN runs r ON r.id = t.run_id \
202 WHERE t.task_id = $5 AND t.map_index = -1 \
203 AND t.state IN ('success', 'failed', 'cancelled', 'skipped', 'upstream_failed') \
204 AND t.ended_at >= $2{ts} AND r.dag_id = $1 \
205 AND (t.ended_at > $2{ts} OR $4 IS NULL OR r.id > $4{uuid}) \
206 ORDER BY t.ended_at, r.id LIMIT $3";
207 const RUNS: &str = "SELECT r.id{text}, {ts<}r.planned_for{>ts}, {ts<}r.ended_at{>ts} FROM runs r \
208 WHERE r.dag_id = $1 AND r.state = 'success' AND r.ended_at >= $2{ts} \
209 AND (r.ended_at > $2{ts} OR $5 IS NULL OR r.id > $5{uuid}) \
210 AND NOT EXISTS (SELECT 1 FROM events e WHERE e.dag_id = $3 AND e.key = r.id{text}) \
211 ORDER BY r.ended_at, r.id LIMIT $4";
212 const TASKS: &str = "SELECT r.id{text}, {ts<}r.planned_for{>ts}, {ts<}t.ended_at{>ts} \
213 FROM task_instances t JOIN runs r ON r.id = t.run_id \
214 WHERE t.task_id = $6 AND t.map_index = -1 AND t.state = 'success' \
215 AND t.ended_at >= $2{ts} AND r.dag_id = $1 \
216 AND (t.ended_at > $2{ts} OR $5 IS NULL OR r.id > $5{uuid}) \
217 AND NOT EXISTS (SELECT 1 FROM events e WHERE e.dag_id = $3 AND e.key = r.id{text}) \
218 ORDER BY t.ended_at, r.id LIMIT $4";
219 let (since, after_run) = match from {
220 RunOfFrom::Since(at) => (at, None),
221 RunOfFrom::After(seen) => (seen.at, Some(seen.run.as_str())),
222 };
223 let rows: Vec<(String, String, String)> = on_pool!(self, |pool, backend| {
224 let query = match (task.is_some(), any_end) {
227 (true, false) => TASKS,
228 (false, false) => RUNS,
229 (true, true) => TASKS_ENDED,
230 (false, true) => RUNS_ENDED,
231 };
232 let mut statement = sqlx::query_as(sql(backend, query))
233 .bind(dag)
234 .bind(db_time(since));
235 if !any_end {
236 statement = statement.bind(started);
237 }
238 statement = statement.bind(i64::from(limit)).bind(after_run);
239 if let Some(task) = task {
240 statement = statement.bind(task);
241 }
242 statement.fetch_all(pool).await?
243 });
244 rows.into_iter()
245 .map(|(id, at, ended)| {
246 Ok::<_, DbError>((
247 id,
248 parse_time("runs.planned_for", &at)?,
249 parse_time("ended_at", &ended)?,
250 ))
251 })
252 .collect()
253 }
254
255 pub async fn live_since(&self, dag: &str) -> Result<Option<Timestamp>, DbError> {
261 const SINCE: &str = "SELECT {ts<}live_since{>ts} FROM dag_triggers WHERE dag_id = $1 \
262 AND live_since IS NOT NULL";
263 let row: Option<(String,)> = on_pool!(self, |pool, backend| {
264 sqlx::query_as(sql(backend, SINCE))
265 .bind(dag)
266 .fetch_optional(pool)
267 .await?
268 });
269 row.map(|(at,)| parse_time("dag_triggers.live_since", &at))
270 .transpose()
271 }
272
273 pub async fn run_of_seen(&self, dag: &str, source: &str) -> Result<Option<RunOfSeen>, DbError> {
280 const SEEN: &str = "SELECT {ts<}run_of_seen_at{>ts}, run_of_seen_run FROM trigger_progress \
281 WHERE dag_id = $1 AND run_of_source = $2 AND run_of_seen_at IS NOT NULL \
282 AND run_of_seen_run IS NOT NULL";
283 let row: Option<(String, String)> = on_pool!(self, |pool, backend| {
284 sqlx::query_as(sql(backend, SEEN))
285 .bind(dag)
286 .bind(source)
287 .fetch_optional(pool)
288 .await?
289 });
290 row.map(|(at, run)| {
291 Ok(RunOfSeen {
292 at: parse_time("trigger_progress.run_of_seen_at", &at)?,
293 run,
294 })
295 })
296 .transpose()
297 }
298
299 pub async fn set_run_of_seen(
306 &self,
307 dag: &str,
308 source: &str,
309 seen: &RunOfSeen,
310 ) -> Result<(), DbError> {
311 const SET: &str = "INSERT INTO trigger_progress \
312 (dag_id, failures, run_of_source, run_of_seen_at, run_of_seen_run) \
313 VALUES ($1, 0, $2, $3{ts}, $4) ON CONFLICT (dag_id) DO UPDATE SET \
314 run_of_source = excluded.run_of_source, run_of_seen_at = excluded.run_of_seen_at, \
315 run_of_seen_run = excluded.run_of_seen_run";
316 in_tx!(self, |tx, backend| {
317 sqlx::query(sql(backend, SET))
318 .bind(dag)
319 .bind(source)
320 .bind(db_time(seen.at))
321 .bind(&seen.run)
322 .execute(&mut *tx)
323 .await?;
324 });
325 Ok(())
326 }
327}
328
329#[derive(Debug, Clone, PartialEq, Eq)]
331pub struct RunOfSeen {
332 pub at: Timestamp,
334 pub run: String,
336}
337
338#[derive(Debug, Clone, Copy)]
340pub enum RunOfFrom<'a> {
341 Since(Timestamp),
343 After(&'a RunOfSeen),
345}
346
347impl Database {
348 pub async fn sensor_wait(
355 &self,
356 instance_id: &str,
357 now: Timestamp,
358 ) -> Result<Option<SensorWait>, DbError> {
359 const START: &str = "UPDATE task_instances \
362 SET waiting_since = COALESCE(ready_at, $2{ts}) \
363 WHERE id = $1{uuid} AND waiting_since IS NULL";
364 const READ: &str = "SELECT {ts<}waiting_since{>ts}, handed_run, {ts<}handed_at{>ts}, \
365 waited_run, {ts<}waited_at{>ts} FROM task_instances \
366 WHERE id = $1{uuid} AND waiting_since IS NOT NULL";
367 type Row = (
368 String,
369 Option<String>,
370 Option<String>,
371 Option<String>,
372 Option<String>,
373 );
374 let read: Option<Row> = on_pool!(self, |pool, backend| {
375 sqlx::query_as(sql(backend, READ))
376 .bind(instance_id)
377 .fetch_optional(pool)
378 .await?
379 });
380 let row = if let Some(row) = read {
381 Some(row)
382 } else {
383 in_tx!(self, |tx, backend| {
384 sqlx::query(sql(backend, START))
385 .bind(instance_id)
386 .bind(db_time(now))
387 .execute(&mut *tx)
388 .await?;
389 sqlx::query_as(sql(backend, READ))
390 .bind(instance_id)
391 .fetch_optional(&mut *tx)
392 .await?
393 })
394 };
395 let pair = |run: Option<String>, at: Option<String>, what| match (run, at) {
396 (Some(run), Some(at)) => parse_time(what, &at).map(|at| Some((run, at))),
397 _ => Ok(None),
398 };
399 row.map(|(since, handed, handed_at, waited, waited_at)| {
400 let handed = pair(handed, handed_at, "task_instances.handed_at")?;
401 let waited = pair(waited, waited_at, "task_instances.waited_at")?;
402 Ok(SensorWait {
403 since: parse_time("task_instances.waiting_since", &since)?,
404 handed,
405 waited,
406 })
407 })
408 .transpose()
409 }
410
411 pub async fn hand_run(
420 &self,
421 instance_id: &str,
422 run_id: &str,
423 ended_at: Timestamp,
424 ) -> Result<(), DbError> {
425 const HAND: &str = "UPDATE task_instances SET handed_run = $2, handed_at = $3{ts}, \
426 look_at = NULL WHERE id = $1{uuid}";
427 in_tx!(self, |tx, backend| {
429 sqlx::query(sql(backend, HAND))
430 .bind(instance_id)
431 .bind(run_id)
432 .bind(db_time(ended_at))
433 .execute(&mut *tx)
434 .await?;
435 });
436 Ok(())
437 }
438
439 pub async fn not_yet(&self, instance_id: &str) -> Result<(), DbError> {
446 const SEEN: &str = "UPDATE task_instances SET waited_run = handed_run, waited_at = handed_at \
447 WHERE id = $1{uuid}";
448 const HANDED: &str = "SELECT handed_run FROM task_instances WHERE id = $1{uuid}";
452 const PASS: &str = "INSERT INTO sensor_passed (instance_id, item) \
453 SELECT $1{uuid}, id FROM named_events WHERE id = $2{uuid} \
454 ON CONFLICT (instance_id, item) DO NOTHING";
455 in_tx!(self, |tx, backend| {
456 let handed: Option<Option<String>> = sqlx::query_scalar(sql(backend, HANDED))
457 .bind(instance_id)
458 .fetch_optional(&mut *tx)
459 .await?;
460 if let Some(item) = handed
462 .flatten()
463 .filter(|item| uuid::Uuid::parse_str(item).is_ok())
464 {
465 sqlx::query(sql(backend, PASS))
466 .bind(instance_id)
467 .bind(item)
468 .execute(&mut *tx)
469 .await?;
470 }
471 sqlx::query(sql(backend, SEEN))
472 .bind(instance_id)
473 .execute(&mut *tx)
474 .await?;
475 });
476 Ok(())
477 }
478
479 pub async fn run_result(
487 &self,
488 run_id: &str,
489 task: Option<&schedr_model::TaskId>,
490 ) -> Result<Option<serde_json::Value>, DbError> {
491 const RUN: &str = "SELECT dag_id, {ts<}planned_for{>ts}, state, {ts<}ended_at{>ts} \
492 FROM runs WHERE id = $1{uuid}";
493 const TASK: &str = "SELECT state, outcome, {ts<}ended_at{>ts} FROM task_instances \
494 WHERE run_id = $1{uuid} AND task_id = $2 AND map_index = -1";
495 let run: Option<(String, String, String, Option<String>)> =
496 on_pool!(self, |pool, backend| {
497 sqlx::query_as(sql(backend, RUN))
498 .bind(run_id)
499 .fetch_optional(pool)
500 .await?
501 });
502 let Some((dag_id, planned_for, state, ended_at)) = run else {
503 return Ok(None);
504 };
505 let time = |what, at: &str| {
507 parse_time(what, at).map(|t| serde_json::json!({"$datetime": t.to_string()}))
508 };
509 let mut result = serde_json::json!({
510 "run_id": run_id,
511 "dag_id": dag_id,
512 "planned_for": time("runs.planned_for", &planned_for)?,
513 "state": state,
514 "ended_at": ended_at.as_deref().map(|at| time("runs.ended_at", at)).transpose()?,
515 });
516 let Some(task) = task else {
517 return Ok(Some(result));
518 };
519 let found: Option<(String, Option<String>, Option<String>)> =
520 on_pool!(self, |pool, backend| {
521 sqlx::query_as(sql(backend, TASK))
522 .bind(run_id)
523 .bind(task.as_str())
524 .fetch_optional(pool)
525 .await?
526 });
527 let mut output = self.outputs_of(run_id, &[task]).await?.remove(task);
529 if output.is_none() {
530 let elements = self.instance_results(run_id, task).await?;
531 output = (!elements.is_empty()).then(|| {
532 serde_json::Value::Array(
533 elements
534 .into_iter()
535 .map(|e| e.output.unwrap_or(serde_json::Value::Null))
536 .collect(),
537 )
538 });
539 }
540 result["task_id"] = serde_json::json!(task.as_str());
541 result["task_state"] = serde_json::json!(found.as_ref().map(|(state, ..)| state));
542 result["outcome"] =
543 serde_json::json!(found.as_ref().and_then(|(_, outcome, _)| outcome.as_ref()));
544 result["output"] = output.unwrap_or(serde_json::Value::Null);
545 Ok(Some(result))
546 }
547}
548
549impl Database {
550 pub async fn hand_trigger_run(&self, dag: &str, seen: &RunOfSeen) -> Result<(), DbError> {
557 const HAND: &str = "INSERT INTO trigger_progress (dag_id, failures, run_of_handed_run, \
560 run_of_handed_at) VALUES ($1, 0, $2, $3{ts}) ON CONFLICT (dag_id) DO UPDATE SET \
561 failures = CASE WHEN COALESCE(trigger_progress.run_of_handed_run, '') = excluded.run_of_handed_run \
562 THEN trigger_progress.failures ELSE 0 END, \
563 not_before = CASE WHEN COALESCE(trigger_progress.run_of_handed_run, '') = excluded.run_of_handed_run \
564 THEN trigger_progress.not_before ELSE NULL END, \
565 run_of_handed_run = excluded.run_of_handed_run, \
566 run_of_handed_at = excluded.run_of_handed_at";
567 in_tx!(self, |tx, backend| {
568 sqlx::query(sql(backend, HAND))
569 .bind(dag)
570 .bind(&seen.run)
571 .bind(db_time(seen.at))
572 .execute(&mut *tx)
573 .await?;
574 });
575 Ok(())
576 }
577
578 pub async fn trigger_run_handed(&self, dag: &str) -> Result<Option<RunOfSeen>, DbError> {
584 const READ: &str = "SELECT run_of_handed_run, {ts<}run_of_handed_at{>ts} FROM trigger_progress \
585 WHERE dag_id = $1 AND run_of_handed_run IS NOT NULL AND run_of_handed_at IS NOT NULL";
586 let row: Option<(String, String)> = on_pool!(self, |pool, backend| {
587 sqlx::query_as(sql(backend, READ))
588 .bind(dag)
589 .fetch_optional(pool)
590 .await?
591 });
592 row.map(|(run, at)| {
593 Ok(RunOfSeen {
594 at: parse_time("trigger_progress.run_of_handed_at", &at)?,
595 run,
596 })
597 })
598 .transpose()
599 }
600
601 pub async fn pass_trigger_run(
613 &self,
614 dag: &str,
615 source: &str,
616 skipped: Option<&str>,
617 call: Option<&str>,
618 ) -> Result<bool, DbError> {
619 const PASS: &str = "UPDATE trigger_progress SET run_of_source = $2, \
620 run_of_seen_at = CASE WHEN run_of_seen_at IS NOT NULL AND run_of_seen_at > run_of_handed_at \
621 AND EXISTS (SELECT 1 FROM named_events e WHERE e.id = run_of_handed_run{uuid}) THEN run_of_seen_at ELSE run_of_handed_at END, \
622 run_of_seen_run = CASE WHEN run_of_seen_at IS NOT NULL AND run_of_seen_at > run_of_handed_at \
623 AND EXISTS (SELECT 1 FROM named_events e WHERE e.id = run_of_handed_run{uuid}) THEN run_of_seen_run ELSE run_of_handed_run END, \
624 run_of_handed_run = NULL, run_of_handed_at = NULL, failures = 0, not_before = NULL, \
625 last_error = COALESCE($3, last_error) \
626 WHERE dag_id = $1 AND run_of_handed_run IS NOT NULL AND instance_id IS NULL";
627 const END_AND_PASS: &str = "UPDATE trigger_progress SET run_of_source = $2, \
628 run_of_seen_at = CASE WHEN run_of_seen_at IS NOT NULL AND run_of_seen_at > run_of_handed_at \
629 AND EXISTS (SELECT 1 FROM named_events e WHERE e.id = run_of_handed_run{uuid}) THEN run_of_seen_at ELSE run_of_handed_at END, \
630 run_of_seen_run = CASE WHEN run_of_seen_at IS NOT NULL AND run_of_seen_at > run_of_handed_at \
631 AND EXISTS (SELECT 1 FROM named_events e WHERE e.id = run_of_handed_run{uuid}) THEN run_of_seen_run ELSE run_of_handed_run END, \
632 run_of_handed_run = NULL, run_of_handed_at = NULL, failures = 0, not_before = NULL, \
633 last_error = COALESCE($3, last_error), instance_id = NULL, worker_id = NULL, \
634 dag_version_id = NULL, code_hash = NULL \
635 WHERE dag_id = $1 AND run_of_handed_run IS NOT NULL AND instance_id = $4";
636 const KEEP: &str = "INSERT INTO trigger_progress_passed (dag_id, item) \
639 SELECT dag_id, run_of_handed_run FROM trigger_progress t WHERE dag_id = $1 \
640 AND run_of_handed_run IS NOT NULL AND ($2 IS NULL AND instance_id IS NULL \
641 OR instance_id = $2) AND EXISTS (SELECT 1 FROM named_events e \
642 WHERE e.id = t.run_of_handed_run{uuid}) ON CONFLICT (dag_id, item) DO NOTHING";
643 let passed = in_tx!(self, |tx, backend| {
644 sqlx::query(sql(backend, KEEP))
645 .bind(dag)
646 .bind(call)
647 .execute(&mut *tx)
648 .await?;
649 let statement = match call {
650 Some(call) => sqlx::query(sql(backend, END_AND_PASS))
651 .bind(dag)
652 .bind(source)
653 .bind(skipped)
654 .bind(call),
655 None => sqlx::query(sql(backend, PASS))
656 .bind(dag)
657 .bind(source)
658 .bind(skipped),
659 };
660 statement.execute(&mut *tx).await?.rows_affected()
661 });
662 Ok(passed == 1)
663 }
664}
665
666impl Database {
667 pub async fn pass_trigger_run_stored(
675 &self,
676 dag: &str,
677 source: &str,
678 call: &str,
679 ) -> Result<bool, DbError> {
680 const PASS: &str = "UPDATE trigger_progress SET run_of_source = $2, \
681 run_of_seen_at = CASE WHEN run_of_seen_at IS NOT NULL AND run_of_seen_at > run_of_handed_at \
682 AND EXISTS (SELECT 1 FROM named_events e WHERE e.id = run_of_handed_run{uuid}) THEN run_of_seen_at ELSE run_of_handed_at END, \
683 run_of_seen_run = CASE WHEN run_of_seen_at IS NOT NULL AND run_of_seen_at > run_of_handed_at \
684 AND EXISTS (SELECT 1 FROM named_events e WHERE e.id = run_of_handed_run{uuid}) THEN run_of_seen_run ELSE run_of_handed_run END, \
685 run_of_handed_run = NULL, run_of_handed_at = NULL, failures = 0, not_before = NULL \
686 WHERE dag_id = $1 AND run_of_handed_run IS NOT NULL AND instance_id = $3";
687 const KEEP: &str = "INSERT INTO trigger_progress_passed (dag_id, item) \
688 SELECT dag_id, run_of_handed_run FROM trigger_progress t WHERE dag_id = $1 \
689 AND run_of_handed_run IS NOT NULL AND instance_id = $2 \
690 AND EXISTS (SELECT 1 FROM named_events e WHERE e.id = t.run_of_handed_run{uuid}) \
691 ON CONFLICT (dag_id, item) DO NOTHING";
692 let passed = in_tx!(self, |tx, backend| {
693 sqlx::query(sql(backend, KEEP))
694 .bind(dag)
695 .bind(call)
696 .execute(&mut *tx)
697 .await?;
698 sqlx::query(sql(backend, PASS))
699 .bind(dag)
700 .bind(source)
701 .bind(call)
702 .execute(&mut *tx)
703 .await?
704 .rows_affected()
705 });
706 Ok(passed == 1)
707 }
708
709 pub async fn trigger_call_refused(
716 &self,
717 dag: &str,
718 error: &str,
719 not_before: Option<Timestamp>,
720 ) -> Result<(), DbError> {
721 const REFUSED: &str = "UPDATE trigger_progress SET last_error = $2, failures = failures + 1, \
722 not_before = $3{ts} WHERE dag_id = $1 AND instance_id IS NULL";
723 in_tx!(self, |tx, backend| {
724 sqlx::query(sql(backend, REFUSED))
725 .bind(dag)
726 .bind(error)
727 .bind(not_before.map(db_time))
728 .execute(&mut *tx)
729 .await?;
730 });
731 Ok(())
732 }
733}