1use rusqlite::{params, OptionalExtension, Row};
23use serde::{Deserialize, Serialize};
24
25use super::store::Store;
26use super::StoreError;
27
28pub(crate) const SCHEMA: &str = "
31 CREATE TABLE IF NOT EXISTS db_job_incidents (
32 id TEXT PRIMARY KEY,
33 job_id TEXT NOT NULL,
34 job_source TEXT NOT NULL DEFAULT '',
35 job_name TEXT NOT NULL DEFAULT '',
36 work_id TEXT NOT NULL DEFAULT '',
37 task_num INTEGER,
38 owner_uid TEXT NOT NULL DEFAULT '',
39 first_run_id TEXT NOT NULL,
40 last_run_id TEXT NOT NULL,
41 failures INTEGER NOT NULL DEFAULT 1,
42 opened_at_ms INTEGER NOT NULL,
43 last_failed_at_ms INTEGER NOT NULL,
44 ended_at_ms INTEGER,
45 end_reason TEXT NOT NULL DEFAULT '',
46 ended_by_run TEXT NOT NULL DEFAULT '',
47 recovered_at_ms INTEGER,
48 notified INTEGER NOT NULL DEFAULT 0
49 );
50 CREATE UNIQUE INDEX IF NOT EXISTS idx_ids_job_incidents_open ON db_job_incidents(job_id)
51 WHERE ended_at_ms IS NULL;
52 CREATE INDEX IF NOT EXISTS idx_ids_job_incidents_job ON db_job_incidents(job_id, opened_at_ms);
53 CREATE TABLE IF NOT EXISTS db_job_incident_cursors (
54 job_id TEXT PRIMARY KEY,
55 ended_at_ms INTEGER NOT NULL,
56 run_id TEXT NOT NULL
57 );
58 CREATE TABLE IF NOT EXISTS db_job_incident_runs (
59 run_id TEXT PRIMARY KEY,
60 incident_id TEXT NOT NULL,
61 counted_at_ms INTEGER NOT NULL,
62 run_ended_ms INTEGER NOT NULL DEFAULT 0
63 );";
64
65pub mod ended {
67 pub const RECOVERED: &str = "recovered";
70 pub const TASK_CLOSED: &str = "task_closed";
74}
75
76#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ts_rs::TS)]
78#[ts(export, export_to = "../../../frontend/types/rpc/")]
79pub struct JobIncident {
80 pub id: String,
81 pub job_id: String,
82 pub job_source: String,
83 pub job_name: String,
84 pub work_id: String,
86 #[ts(type = "number | null")]
88 pub task_num: Option<i64>,
89 pub owner_uid: String,
91 pub first_run_id: String,
92 pub last_run_id: String,
93 #[ts(type = "number")]
95 pub failures: i64,
96 #[ts(type = "number")]
97 pub opened_at_ms: i64,
98 #[ts(type = "number")]
99 pub last_failed_at_ms: i64,
100 #[ts(type = "number | null")]
101 pub ended_at_ms: Option<i64>,
102 pub end_reason: String,
104 pub ended_by_run: String,
106 #[ts(type = "number | null")]
109 pub recovered_at_ms: Option<i64>,
110 pub notified: bool,
113}
114
115const COLS: &str = "id, job_id, job_source, job_name, work_id, task_num, owner_uid, first_run_id, last_run_id, \
116 failures, opened_at_ms, last_failed_at_ms, ended_at_ms, end_reason, ended_by_run, \
117 recovered_at_ms, notified";
118
119fn row_to_incident(row: &Row) -> rusqlite::Result<JobIncident> {
120 Ok(JobIncident {
121 id: row.get("id")?,
122 job_id: row.get("job_id")?,
123 job_source: row.get("job_source")?,
124 job_name: row.get("job_name")?,
125 work_id: row.get("work_id")?,
126 task_num: row.get("task_num")?,
127 owner_uid: row.get("owner_uid")?,
128 first_run_id: row.get("first_run_id")?,
129 last_run_id: row.get("last_run_id")?,
130 failures: row.get("failures")?,
131 opened_at_ms: row.get("opened_at_ms")?,
132 last_failed_at_ms: row.get("last_failed_at_ms")?,
133 ended_at_ms: row.get("ended_at_ms")?,
134 end_reason: row.get("end_reason")?,
135 ended_by_run: row.get("ended_by_run")?,
136 recovered_at_ms: row.get("recovered_at_ms")?,
137 notified: row.get::<_, i64>("notified")? != 0,
138 })
139}
140
141fn counted(conn: &rusqlite::Connection, run_id: &str) -> Result<bool, StoreError> {
143 Ok(conn
144 .query_row("SELECT 1 FROM db_job_incident_runs WHERE run_id = ?1", params![run_id], |_| Ok(()))
145 .optional()?
146 .is_some())
147}
148
149fn count_run(conn: &rusqlite::Connection, run_id: &str, incident_id: &str, now_ms: i64) -> Result<(), StoreError> {
153 conn.execute(
154 "INSERT OR REPLACE INTO db_job_incident_runs (run_id, incident_id, counted_at_ms, run_ended_ms)
155 VALUES (?1, ?2, ?3, COALESCE((SELECT ended_at_ms FROM db_job_runs WHERE id = ?1), 0))",
156 params![run_id, incident_id, now_ms],
157 )?;
158 Ok(())
159}
160
161#[derive(Debug, Clone, PartialEq, Eq)]
164pub struct IncidentCursor {
165 pub ended_at_ms: i64,
166 pub run_id: String,
167}
168
169impl Store {
170 pub fn job_incident_open(&self, incident: &JobIncident) -> Result<bool, StoreError> {
174 let mut conn = self.conn().lock().unwrap();
175 let tx = conn.transaction()?;
176 if counted(&tx, &incident.first_run_id)? {
177 return Ok(false);
178 }
179 let n = tx.execute(
180 &format!(
181 "INSERT OR IGNORE INTO db_job_incidents ({COLS}) VALUES
182 (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, NULL, '', '', NULL, ?13)"
183 ),
184 params![
185 incident.id,
186 incident.job_id,
187 incident.job_source,
188 incident.job_name,
189 incident.work_id,
190 incident.task_num,
191 incident.owner_uid,
192 incident.first_run_id,
193 incident.last_run_id,
194 incident.failures,
195 incident.opened_at_ms,
196 incident.last_failed_at_ms,
197 incident.notified as i64,
198 ],
199 )?;
200 if n > 0 {
201 count_run(&tx, &incident.first_run_id, &incident.id, incident.opened_at_ms)?;
202 }
203 tx.commit()?;
204 Ok(n > 0)
205 }
206
207 pub fn job_incident_open_for(&self, job_id: &str) -> Result<Option<JobIncident>, StoreError> {
209 let conn = self.conn().lock().unwrap();
210 Ok(conn
211 .query_row(
212 &format!("SELECT {COLS} FROM db_job_incidents WHERE job_id = ?1 AND ended_at_ms IS NULL"),
213 params![job_id],
214 row_to_incident,
215 )
216 .optional()?)
217 }
218
219 #[cfg(test)]
221 pub fn job_incident_latest(&self, job_id: &str) -> Result<Option<JobIncident>, StoreError> {
222 let conn = self.conn().lock().unwrap();
223 Ok(conn
224 .query_row(
225 &format!(
226 "SELECT {COLS} FROM db_job_incidents WHERE job_id = ?1
227 ORDER BY opened_at_ms DESC, rowid DESC LIMIT 1"
228 ),
229 params![job_id],
230 row_to_incident,
231 )
232 .optional()?)
233 }
234
235 pub fn job_incident_mark_notified(&self, id: &str) -> Result<(), StoreError> {
237 let conn = self.conn().lock().unwrap();
238 conn.execute("UPDATE db_job_incidents SET notified = 1 WHERE id = ?1 AND ended_at_ms IS NULL", params![id])?;
239 Ok(())
240 }
241
242 pub fn job_incident_set_task(&self, id: &str, work_id: &str, task_num: i64) -> Result<(), StoreError> {
244 let conn = self.conn().lock().unwrap();
245 conn.execute(
246 "UPDATE db_job_incidents SET work_id = ?2, task_num = ?3 WHERE id = ?1",
247 params![id, work_id, task_num],
248 )?;
249 Ok(())
250 }
251
252 pub fn job_incident_fail_again(
256 &self,
257 id: &str,
258 seen_run_id: &str,
259 run_id: &str,
260 now_ms: i64,
261 ) -> Result<Option<i64>, StoreError> {
262 let mut conn = self.conn().lock().unwrap();
263 let tx = conn.transaction()?;
264 if counted(&tx, run_id)? {
265 return Ok(None);
266 }
267 let count: Option<i64> = tx
268 .query_row(
269 "UPDATE db_job_incidents
270 SET failures = failures + 1, last_run_id = ?3, last_failed_at_ms = ?4
271 WHERE id = ?1 AND last_run_id = ?2 AND ended_at_ms IS NULL
272 RETURNING failures",
273 params![id, seen_run_id, run_id, now_ms],
274 |r| r.get(0),
275 )
276 .optional()?;
277 if count.is_some() {
278 count_run(&tx, run_id, id, now_ms)?;
279 }
280 tx.commit()?;
281 Ok(count)
282 }
283
284 pub fn job_incident_run_counted(&self, run_id: &str) -> Result<bool, StoreError> {
286 let conn = self.conn().lock().unwrap();
287 counted(&conn, run_id)
288 }
289
290 pub fn job_incident_recovered_by(&self, job_id: &str, run_id: &str) -> Result<Option<JobIncident>, StoreError> {
293 let conn = self.conn().lock().unwrap();
294 Ok(conn
295 .query_row(
296 &format!(
297 "SELECT {COLS} FROM db_job_incidents
298 WHERE job_id = ?1 AND ended_by_run = ?2 AND end_reason = ?3 AND recovered_at_ms IS NOT NULL"
299 ),
300 params![job_id, run_id, ended::RECOVERED],
301 row_to_incident,
302 )
303 .optional()?)
304 }
305
306 pub fn job_incident_reopen(&self, id: &str, run_id: &str, now_ms: i64) -> Result<Option<i64>, StoreError> {
312 let mut conn = self.conn().lock().unwrap();
313 let tx = conn.transaction()?;
314 if counted(&tx, run_id)? {
315 return Ok(None);
316 }
317 let count: Option<i64> = tx
318 .query_row(
319 "UPDATE OR IGNORE db_job_incidents
320 SET ended_at_ms = NULL, end_reason = '', ended_by_run = '', recovered_at_ms = NULL, notified = 0,
321 failures = failures + 1, last_run_id = ?2, last_failed_at_ms = ?3
322 WHERE id = ?1 AND ended_by_run = ?2 AND recovered_at_ms IS NOT NULL
323 RETURNING failures",
324 params![id, run_id, now_ms],
325 |r| r.get(0),
326 )
327 .optional()?;
328 if count.is_some() {
329 count_run(&tx, run_id, id, now_ms)?;
330 }
331 tx.commit()?;
332 Ok(count)
333 }
334
335 pub fn job_incident_end_task_closed(&self, id: &str, now_ms: i64) -> Result<bool, StoreError> {
338 let conn = self.conn().lock().unwrap();
339 let n = conn.execute(
340 "UPDATE db_job_incidents SET ended_at_ms = ?2, end_reason = ?3
341 WHERE id = ?1 AND ended_at_ms IS NULL",
342 params![id, now_ms, ended::TASK_CLOSED],
343 )?;
344 Ok(n > 0)
345 }
346
347 pub fn job_incidents_recover(&self, job_id: &str, run_id: &str, now_ms: i64) -> Result<Vec<JobIncident>, StoreError> {
355 let mut conn = self.conn().lock().unwrap();
356 let tx = conn.transaction()?;
357 let ended: i64 = tx
358 .query_row("SELECT COALESCE(ended_at_ms, 0) FROM db_job_runs WHERE id = ?1", params![run_id], |r| r.get(0))
359 .optional()?
360 .unwrap_or(0);
361 let before = {
362 let mut stmt = tx.prepare(&format!(
363 "SELECT {COLS} FROM db_job_incidents i
364 WHERE job_id = ?1 AND recovered_at_ms IS NULL
365 AND NOT EXISTS (SELECT 1 FROM db_job_incident_runs c
366 WHERE c.incident_id = i.id
367 AND (c.run_ended_ms > ?2 OR (c.run_ended_ms = ?2 AND c.run_id > ?3)))
368 ORDER BY opened_at_ms"
369 ))?;
370 let rows = stmt.query_map(params![job_id, ended, run_id], row_to_incident)?;
371 rows.collect::<Result<Vec<_>, _>>()?
372 };
373 for inc in &before {
374 tx.execute(
375 "UPDATE db_job_incidents
376 SET recovered_at_ms = ?3, ended_by_run = ?2, notified = 0,
377 end_reason = CASE WHEN ended_at_ms IS NULL THEN ?4 ELSE end_reason END,
378 ended_at_ms = COALESCE(ended_at_ms, ?3)
379 WHERE id = ?1 AND recovered_at_ms IS NULL",
380 params![inc.id, run_id, now_ms, ended::RECOVERED],
381 )?;
382 }
383 if !before.is_empty() {
384 tx.execute("DELETE FROM db_job_incident_runs WHERE run_id = ?1", params![run_id])?;
388 }
389 tx.commit()?;
390 Ok(before)
391 }
392
393 pub fn job_incident_cursor(&self, job_id: &str) -> Result<Option<IncidentCursor>, StoreError> {
395 let conn = self.conn().lock().unwrap();
396 Ok(conn
397 .query_row(
398 "SELECT ended_at_ms, run_id FROM db_job_incident_cursors WHERE job_id = ?1",
399 params![job_id],
400 |r| Ok(IncidentCursor { ended_at_ms: r.get(0)?, run_id: r.get(1)? }),
401 )
402 .optional()?)
403 }
404
405 pub fn job_incident_cursor_advance(
411 &self,
412 job_id: &str,
413 from: Option<&IncidentCursor>,
414 to: &IncidentCursor,
415 outcome: &str,
416 ) -> Result<bool, StoreError> {
417 let conn = self.conn().lock().unwrap();
418 let unchanged = "EXISTS (SELECT 1 FROM db_job_runs WHERE id = ?3 AND outcome = ?4)";
419 let n = match from {
420 None => conn.execute(
421 &format!(
422 "INSERT OR IGNORE INTO db_job_incident_cursors (job_id, ended_at_ms, run_id)
423 SELECT ?1, ?2, ?3 WHERE {unchanged}"
424 ),
425 params![job_id, to.ended_at_ms, to.run_id, outcome],
426 )?,
427 Some(from) => conn.execute(
428 &format!(
429 "UPDATE db_job_incident_cursors SET ended_at_ms = ?2, run_id = ?3
430 WHERE job_id = ?1 AND ended_at_ms = ?5 AND run_id = ?6 AND {unchanged}"
431 ),
432 params![job_id, to.ended_at_ms, to.run_id, outcome, from.ended_at_ms, from.run_id],
433 )?,
434 };
435 Ok(n > 0)
436 }
437}
438
439#[cfg(test)]
440mod tests {
441 use super::*;
442
443 fn incident(id: &str, job: &str, run: &str) -> JobIncident {
444 JobIncident {
445 id: id.into(),
446 job_id: job.into(),
447 first_run_id: run.into(),
448 last_run_id: run.into(),
449 failures: 1,
450 notified: true,
451 ..Default::default()
452 }
453 }
454
455 #[test]
456 fn a_job_has_at_most_one_open_incident_and_each_failure_counts_once() {
457 let store = Store::open_in_memory().unwrap();
458 store.job_runs_ensure_schema().unwrap();
459 assert!(store.job_incident_open(&incident("i1", "j", "r1")).unwrap());
460 assert!(!store.job_incident_open(&incident("i2", "j", "r2")).unwrap(), "j already has one open");
461 assert_eq!(store.job_incident_fail_again("i1", "r1", "r2", 5).unwrap(), Some(2));
462 assert_eq!(store.job_incident_fail_again("i1", "r1", "r2", 5).unwrap(), None, "counted already");
463 assert!(store.job_incident_end_task_closed("i1", 9).unwrap());
464 assert!(!store.job_incident_end_task_closed("i1", 9).unwrap());
465 assert_eq!(store.job_incident_fail_again("i1", "r2", "r4", 10).unwrap(), None, "ended");
466 assert!(store.job_incident_open_for("j").unwrap().is_none());
467 assert!(store.job_incident_open(&incident("i3", "j", "r4")).unwrap(), "a new one after the end");
468
469 let recovered = store.job_incidents_recover("j", "r5", 20).unwrap();
470 assert_eq!(recovered.iter().map(|i| i.id.as_str()).collect::<Vec<_>>(), ["i1", "i3"], "the closed one too");
471 let i3 = store.job_incident_latest("j").unwrap().unwrap();
472 assert_eq!((i3.end_reason.as_str(), i3.recovered_at_ms, i3.notified), (ended::RECOVERED, Some(20), false));
473 assert!(store.job_incidents_recover("j", "r6", 30).unwrap().is_empty());
474 }
475
476 #[test]
477 fn the_cursor_moves_only_from_where_it_was_and_while_the_run_is_unchanged() {
478 let store = Store::open_in_memory().unwrap();
479 store.job_runs_ensure_schema().unwrap();
480 for id in ["a", "b", "c", "d"] {
481 let run = super::super::job_runs::JobRun::new(id, "j", "cron", "J", "schedule", "finished", 1);
482 store.job_run_insert(&run).unwrap();
483 }
484 let at = |ms: i64, id: &str| IncidentCursor { ended_at_ms: ms, run_id: id.into() };
485 assert!(store.job_incident_cursor_advance("j", None, &at(1, "a"), "unknown").unwrap());
486 assert!(!store.job_incident_cursor_advance("j", None, &at(1, "a"), "unknown").unwrap(), "taken");
487 assert!(store.job_incident_cursor_advance("j", Some(&at(1, "a")), &at(2, "b"), "unknown").unwrap());
488 assert!(!store.job_incident_cursor_advance("j", Some(&at(1, "a")), &at(3, "c"), "unknown").unwrap(), "moved on");
489 assert!(!store.job_incident_cursor_advance("j", Some(&at(2, "b")), &at(4, "d"), "ok").unwrap(), "d changed since it was read");
490 assert_eq!(store.job_incident_cursor("j").unwrap(), Some(at(2, "b")));
491 }
492}