1use jiff::Timestamp;
5use schedr_model::RunEvent;
6
7use crate::database::{Database, DbError};
8use crate::query::{db_time, in_tx, on_pool, optional_time, sql, to_json};
9use crate::runs::NewRun;
10
11macro_rules! queued_event_from {
13 () => {
14 "FROM runs WHERE state = 'queued' AND kind = 'event'"
15 };
16}
17pub(crate) use queued_event_from;
18
19macro_rules! trigger_pass_from {
21 () => {
22 "FROM dag_triggers WHERE (NOT paused AND kind IN ('run_of', 'event')) OR EXISTS (SELECT 1 FROM trigger_progress p WHERE p.instance_id IS NOT NULL)"
23 };
24}
25pub(crate) use trigger_pass_from;
26
27macro_rules! triggers_due_from {
31 () => {
32 "FROM dag_triggers WHERE kind IN ('run_of', 'event') AND NOT paused AND (next_fire_at IS NULL OR next_fire_at <= $1{ts})"
33 };
34}
35pub(crate) use triggers_due_from;
36
37#[cfg(test)]
38mod tests;
39
40#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct StoredEvent {
43 pub event: RunEvent,
45 pub received_at: Timestamp,
47}
48
49type EventRow = (String, String, Option<String>, String);
50
51fn stored_event((key, data, at, received_at): EventRow) -> Result<StoredEvent, DbError> {
52 Ok(StoredEvent {
53 event: RunEvent {
54 key,
55 data: crate::query::from_json("events.data", &data)?,
56 at: optional_time("events.at", at)?,
57 },
58 received_at: crate::query::parse_time("events.received_at", &received_at)?,
59 })
60}
61
62#[derive(Debug, Clone, PartialEq, Eq, Default)]
64pub struct TriggerRecord {
65 pub dag_id: String,
67 pub instance_id: Option<String>,
69 pub worker_id: Option<String>,
71 pub dag_version_id: Option<String>,
73 pub code_hash: Option<String>,
75 pub bookmark: Option<String>,
77 pub last_planned_for: Option<Timestamp>,
79 pub last_error: Option<String>,
81 pub failures: u32,
83 pub not_before: Option<Timestamp>,
85 pub stopped_why: Option<String>,
87 pub stopped_on: Option<String>,
89 pub started_at: Option<Timestamp>,
91 pub last_event_at: Option<Timestamp>,
93 pub last_restart_at: Option<Timestamp>,
95 pub last_poked_at: Option<Timestamp>,
97}
98
99pub const STOPPED_BACK_PRESSURE: &str = "back_pressure";
101pub const STOPPED_RETURNED: &str = "returned";
103
104type Row = (
105 String,
106 Option<String>,
107 Option<String>,
108 Option<String>,
109 Option<String>,
110 Option<String>,
111 Option<String>,
112 Option<String>,
113 i32,
114 Option<String>,
115 Option<String>,
116 Option<String>,
117 Option<String>,
118 Option<String>,
119 Option<String>,
120 Option<String>,
121);
122
123fn record(row: Row) -> Result<TriggerRecord, DbError> {
124 let (
125 dag_id,
126 instance_id,
127 worker_id,
128 version,
129 code_hash,
130 bookmark,
131 last,
132 last_error,
133 failures,
134 not_before,
135 stopped_why,
136 stopped_on,
137 started_at,
138 last_event_at,
139 last_restart_at,
140 last_poked_at,
141 ) = row;
142 Ok(TriggerRecord {
143 dag_id,
144 instance_id,
145 worker_id,
146 dag_version_id: version,
147 code_hash,
148 bookmark,
149 last_planned_for: optional_time("trigger_progress.last_planned_for", last)?,
150 last_error,
151 failures: u32::try_from(failures).unwrap_or(0),
152 not_before: optional_time("trigger_progress.not_before", not_before)?,
153 stopped_why,
154 stopped_on,
155 started_at: optional_time("trigger_progress.started_at", started_at)?,
156 last_event_at: optional_time("trigger_progress.last_event_at", last_event_at)?,
157 last_restart_at: optional_time("trigger_progress.last_restart_at", last_restart_at)?,
158 last_poked_at: optional_time("trigger_progress.last_poked_at", last_poked_at)?,
159 })
160}
161
162impl Database {
163 pub async fn triggers(&self) -> Result<Vec<TriggerRecord>, DbError> {
169 const ALL: &str = "SELECT dag_id, instance_id{text}, worker_id, dag_version_id{text}, \
170 code_hash, bookmark, {ts<}last_planned_for{>ts}, last_error, failures, {ts<}not_before{>ts}, \
171 stopped_why, stopped_on, {ts<}started_at{>ts}, {ts<}last_event_at{>ts}, \
172 {ts<}last_restart_at{>ts}, {ts<}last_poked_at{>ts} \
173 FROM trigger_progress ORDER BY dag_id";
174 let rows: Vec<Row> = on_pool!(self, |pool, backend| {
175 sqlx::query_as(sql(backend, ALL)).fetch_all(pool).await?
176 });
177 rows.into_iter().map(record).collect()
178 }
179
180 pub async fn trigger(&self, dag_id: &str) -> Result<Option<TriggerRecord>, DbError> {
186 const ONE: &str = "SELECT dag_id, instance_id{text}, worker_id, dag_version_id{text}, \
187 code_hash, bookmark, {ts<}last_planned_for{>ts}, last_error, failures, {ts<}not_before{>ts}, \
188 stopped_why, stopped_on, {ts<}started_at{>ts}, {ts<}last_event_at{>ts}, \
189 {ts<}last_restart_at{>ts}, {ts<}last_poked_at{>ts} \
190 FROM trigger_progress WHERE dag_id = $1";
191 let row: Option<Row> = on_pool!(self, |pool, backend| {
192 sqlx::query_as(sql(backend, ONE))
193 .bind(dag_id)
194 .fetch_optional(pool)
195 .await?
196 });
197 row.map(record).transpose()
198 }
199
200 pub async fn trigger_assigned(
206 &self,
207 dag_id: &str,
208 instance_id: &str,
209 worker_id: &str,
210 dag_version_id: &str,
211 code_hash: &str,
212 now: Timestamp,
213 ) -> Result<(), DbError> {
214 const SET: &str = "INSERT INTO trigger_progress \
215 (dag_id, instance_id, worker_id, dag_version_id, code_hash, started_at) \
216 VALUES ($1, $2, $3, $4, $5, $6{ts}) ON CONFLICT (dag_id) DO UPDATE SET \
217 instance_id = excluded.instance_id, worker_id = excluded.worker_id, \
218 dag_version_id = excluded.dag_version_id, code_hash = excluded.code_hash, \
219 started_at = excluded.started_at, stopped_why = NULL, stopped_on = NULL";
220 in_tx!(self, |tx, backend| {
221 sqlx::query(sql(backend, SET))
222 .bind(dag_id)
223 .bind(instance_id)
224 .bind(worker_id)
225 .bind(dag_version_id)
226 .bind(code_hash)
227 .bind(db_time(now))
228 .execute(&mut *tx)
229 .await?;
230 });
231 Ok(())
232 }
233
234 pub async fn trigger_ended(
241 &self,
242 dag_id: &str,
243 instance_id: &str,
244 error: Option<&str>,
245 not_before: Option<Timestamp>,
246 ) -> Result<bool, DbError> {
247 const END: &str = "UPDATE trigger_progress SET instance_id = NULL, worker_id = NULL, \
248 dag_version_id = NULL, code_hash = NULL, last_error = COALESCE($1, last_error), \
249 failures = failures + $2, not_before = $3{ts} \
250 WHERE dag_id = $4 AND instance_id = $5";
251 let ended = in_tx!(self, |tx, backend| {
252 sqlx::query(sql(backend, END))
253 .bind(error)
254 .bind(i32::from(error.is_some()))
255 .bind(not_before.map(db_time))
256 .bind(dag_id)
257 .bind(instance_id)
258 .execute(&mut *tx)
259 .await?
260 .rows_affected()
261 });
262 Ok(ended == 1)
263 }
264
265 pub async fn store_event(
273 &self,
274 run_id: &str,
275 run: &NewRun<'_>,
276 event: &RunEvent,
277 ) -> Result<Option<String>, DbError> {
278 const EVENT: &str = "INSERT INTO events (dag_id, key, data, at, received_at) \
279 VALUES ($1, $2, $3{json}, $4{ts}, $5{ts}) ON CONFLICT (dag_id, key) DO NOTHING";
280 const BOOKMARK: &str = "INSERT INTO trigger_progress \
281 (dag_id, bookmark, last_planned_for, failures, last_event_at) \
282 VALUES ($1, $2, $3{ts}, 0, $4{ts}) ON CONFLICT (dag_id) DO UPDATE SET \
283 bookmark = excluded.bookmark, failures = 0, last_error = NULL, \
284 last_event_at = excluded.last_event_at, \
285 last_planned_for = COALESCE(excluded.last_planned_for, trigger_progress.last_planned_for)";
286 let dag_id = run.dag_id.as_str();
287 Box::pin(self.atomically(async {
288 let new = in_tx!(self, |tx, backend| {
289 sqlx::query(sql(backend, EVENT))
290 .bind(dag_id)
291 .bind(&event.key)
292 .bind(to_json(&event.data))
293 .bind(event.at.map(db_time))
294 .bind(db_time(run.triggered_at))
295 .execute(&mut *tx)
296 .await?
297 .rows_affected()
298 }) == 1;
299 if new {
300 self.insert_run_as(run_id, run).await?;
301 }
302 in_tx!(self, |tx, backend| {
303 sqlx::query(sql(backend, BOOKMARK))
304 .bind(dag_id)
305 .bind(&event.key)
306 .bind(new.then(|| db_time(run.planned_for)))
307 .bind(db_time(run.triggered_at))
308 .execute(&mut *tx)
309 .await?;
310 });
311 Ok(new.then(|| run_id.to_owned()))
312 }))
313 .await
314 }
315
316 pub async fn store_batch(
326 &self,
327 run_id: &str,
328 run: &NewRun<'_>,
329 key: &str,
330 items: &[(RunEvent, serde_json::Value)],
331 ) -> Result<Option<String>, DbError> {
332 const EVENT: &str = "INSERT INTO events (dag_id, key, data, at, received_at) \
333 VALUES ($1, $2, $3{json}, $4{ts}, $5{ts}) ON CONFLICT (dag_id, key) DO NOTHING";
334 const BOOKMARK: &str = "INSERT INTO trigger_progress \
335 (dag_id, bookmark, last_planned_for, failures, last_event_at) \
336 VALUES ($1, $2, $3{ts}, 0, $4{ts}) ON CONFLICT (dag_id) DO UPDATE SET \
337 bookmark = excluded.bookmark, failures = 0, last_error = NULL, \
338 last_event_at = excluded.last_event_at, \
339 last_planned_for = COALESCE(excluded.last_planned_for, trigger_progress.last_planned_for)";
340 let dag_id = run.dag_id.as_str();
341 Box::pin(self.atomically(async {
342 let mut new = Vec::new();
343 for (item, raw) in items {
344 let stored = in_tx!(self, |tx, backend| {
345 sqlx::query(sql(backend, EVENT))
346 .bind(dag_id)
347 .bind(&item.key)
348 .bind(to_json(&item.data))
349 .bind(item.at.map(db_time))
350 .bind(db_time(run.triggered_at))
351 .execute(&mut *tx)
352 .await?
353 .rows_affected()
354 }) == 1;
355 if stored {
356 new.push((item, raw));
357 }
358 }
359 let started = new.last().map(|(last, _)| RunEvent {
360 key: last.key.clone(),
361 data: serde_json::Value::Array(new.iter().map(|(_, raw)| (*raw).clone()).collect()),
362 at: None,
363 });
364 if let Some(event) = &started {
365 let run = NewRun {
366 event: Some(event),
367 ..run.clone()
368 };
369 self.insert_run_as(run_id, &run).await?;
370 }
371 in_tx!(self, |tx, backend| {
372 sqlx::query(sql(backend, BOOKMARK))
373 .bind(dag_id)
374 .bind(key)
375 .bind(started.is_some().then(|| db_time(run.planned_for)))
376 .bind(db_time(run.triggered_at))
377 .execute(&mut *tx)
378 .await?;
379 });
380 Ok(started.map(|_| run_id.to_owned()))
381 }))
382 .await
383 }
384
385 pub async fn set_trigger_stopped(
392 &self,
393 dag_id: &str,
394 why: Option<(&str, &str)>,
395 ) -> Result<(), DbError> {
396 const SET: &str =
397 "UPDATE trigger_progress SET stopped_why = $1, stopped_on = $2 WHERE dag_id = $3";
398 in_tx!(self, |tx, backend| {
399 sqlx::query(sql(backend, SET))
400 .bind(why.map(|(why, _)| why))
401 .bind(why.map(|(_, on)| on))
402 .bind(dag_id)
403 .execute(&mut *tx)
404 .await?;
405 });
406 Ok(())
407 }
408
409 pub async fn trigger_idle_restart(&self, dag_id: &str, now: Timestamp) -> Result<(), DbError> {
415 const SET: &str = "UPDATE trigger_progress SET last_restart_at = $1{ts} WHERE dag_id = $2";
416 in_tx!(self, |tx, backend| {
417 sqlx::query(sql(backend, SET))
418 .bind(db_time(now))
419 .bind(dag_id)
420 .execute(&mut *tx)
421 .await?;
422 });
423 Ok(())
424 }
425
426 pub async fn trigger_poked(
433 &self,
434 dag_id: &str,
435 instance_id: &str,
436 at: Timestamp,
437 error: Option<&str>,
438 failures: u32,
439 ) -> Result<(), DbError> {
440 const SET: &str = "UPDATE trigger_progress SET last_poked_at = $1{ts}, last_error = $2, \
441 failures = $3 WHERE dag_id = $4 AND instance_id = $5";
442 in_tx!(self, |tx, backend| {
443 sqlx::query(sql(backend, SET))
444 .bind(db_time(at))
445 .bind(error)
446 .bind(i32::try_from(failures).unwrap_or(i32::MAX))
447 .bind(dag_id)
448 .bind(instance_id)
449 .execute(&mut *tx)
450 .await?;
451 });
452 Ok(())
453 }
454
455 pub async fn queued_event_runs(&self) -> Result<Vec<(String, i64)>, DbError> {
461 const COUNT: &str = concat!(
462 "SELECT dag_id, COUNT(*) ",
463 queued_event_from!(),
464 " GROUP BY dag_id"
465 );
466 if self.skipped(crate::probe::Check::QueuedEventRuns).await? {
467 return Ok(Vec::new());
468 }
469 let rows: Vec<(String, i64)> = on_pool!(self, |pool, backend| {
470 sqlx::query_as(sql(backend, COUNT)).fetch_all(pool).await?
471 });
472 Ok(rows)
473 }
474
475 pub async fn restart_trigger(&self, dag_id: &str) -> Result<(), DbError> {
483 const SET: &str = "UPDATE trigger_progress SET stopped_why = NULL, stopped_on = NULL, \
484 not_before = NULL, dag_version_id = NULL WHERE dag_id = $1";
485 in_tx!(self, |tx, backend| {
486 sqlx::query(sql(backend, SET))
487 .bind(dag_id)
488 .execute(&mut *tx)
489 .await?;
490 });
491 Ok(())
492 }
493
494 pub async fn stored_event(&self, dag_id: &str, key: &str) -> Result<Option<RunEvent>, DbError> {
500 const ONE: &str = "SELECT key, data{text}, {ts<}at{>ts}, {ts<}received_at{>ts} FROM events \
501 WHERE dag_id = $1 AND key = $2";
502 let row: Option<EventRow> = on_pool!(self, |pool, backend| {
503 sqlx::query_as(sql(backend, ONE))
504 .bind(dag_id)
505 .bind(key)
506 .fetch_optional(pool)
507 .await?
508 });
509 Ok(row.map(stored_event).transpose()?.map(|found| found.event))
510 }
511
512 pub async fn events(
519 &self,
520 dag_id: &str,
521 limit: u32,
522 after: Option<(Timestamp, &str)>,
523 ) -> Result<Vec<StoredEvent>, DbError> {
524 const ALL: &str = "SELECT key, data{text}, {ts<}at{>ts}, {ts<}received_at{>ts} FROM events \
525 WHERE dag_id = $1 AND ($2{ts} IS NULL OR received_at < $2{ts} \
526 OR (received_at = $2{ts} AND key > $3{text})) \
527 ORDER BY received_at DESC, key LIMIT $4";
528 let rows: Vec<EventRow> = on_pool!(self, |pool, backend| {
529 sqlx::query_as(sql(backend, ALL))
530 .bind(dag_id)
531 .bind(after.map(|(at, _)| db_time(at)))
532 .bind(after.map(|(_, key)| key))
533 .bind(i64::from(limit))
534 .fetch_all(pool)
535 .await?
536 });
537 rows.into_iter().map(stored_event).collect()
538 }
539
540 pub async fn queued_event_runs_of(&self, dag_id: &str) -> Result<i64, DbError> {
546 const COUNT: &str = "SELECT COUNT(*) FROM runs \
547 WHERE state = 'queued' AND kind = 'event' AND dag_id = $1";
548 let count: i64 = on_pool!(self, |pool, backend| {
549 sqlx::query_scalar(sql(backend, COUNT))
550 .bind(dag_id)
551 .fetch_one(pool)
552 .await?
553 });
554 Ok(count)
555 }
556
557 pub async fn run_event(&self, run_id: &str) -> Result<Option<RunEvent>, DbError> {
563 const EVENT: &str = "SELECT event{text} FROM runs WHERE id = $1{uuid}";
564 let text: Option<Option<String>> = on_pool!(self, |pool, backend| {
565 sqlx::query_scalar(sql(backend, EVENT))
566 .bind(run_id)
567 .fetch_optional(pool)
568 .await?
569 });
570 text.flatten()
571 .map(|t| crate::query::from_json("runs.event", &t))
572 .transpose()
573 }
574}