1use anyhow::{Context, Result};
10use rusqlite::{params, Connection, OptionalExtension};
11use serde::Serialize;
12
13pub const TRACKED_COMMANDS: [&str; 8] = [
31 "scan",
32 "faces",
33 "embed",
34 "classify",
35 "dedupe",
36 "fix-dates",
37 "prune",
38 "locations",
39];
40
41pub fn ensure_pipeline_runs_table(conn: &Connection) -> rusqlite::Result<()> {
42 conn.execute_batch(
43 "CREATE TABLE IF NOT EXISTS pipeline_runs (
44 command TEXT PRIMARY KEY,
45 started_at TEXT NOT NULL,
46 finished_at TEXT,
47 status TEXT NOT NULL,
48 duration_ms INTEGER,
49 summary TEXT
50 );",
51 )
52}
53
54pub fn start_run(conn: &Connection, command: &str) -> rusqlite::Result<()> {
55 conn.execute(
56 "INSERT INTO pipeline_runs (command, started_at, status)
57 VALUES (?1, datetime('now'), 'running')
58 ON CONFLICT(command) DO UPDATE SET
59 started_at = excluded.started_at,
60 status = 'running',
61 finished_at = NULL,
62 duration_ms = NULL,
63 summary = NULL",
64 params![command],
65 )?;
66 Ok(())
67}
68
69pub fn finish_run(
70 conn: &Connection,
71 command: &str,
72 status: &str,
73 duration_ms: i64,
74 summary: Option<&str>,
75) -> rusqlite::Result<()> {
76 conn.execute(
77 "UPDATE pipeline_runs SET
78 finished_at = datetime('now'),
79 status = ?2,
80 duration_ms = ?3,
81 summary = ?4
82 WHERE command = ?1",
83 params![command, status, duration_ms, summary],
84 )?;
85 Ok(())
86}
87
88pub fn track_in<T, F>(
100 conn: &Connection,
101 ctx: &crate::library::LibraryContext,
102 guard: &crate::library_locks::CommandGuard,
103 command: &str,
104 f: F,
105) -> Result<T>
106where
107 F: FnOnce() -> Result<T>,
108{
109 guard.ensure_matches(ctx, command)?;
110 ctx.ensure_root_identity()?;
115 ensure_pipeline_runs_table(conn)?;
116 start_run(conn, command)?;
117 let started = std::time::Instant::now();
118 let result = f();
119 let duration_ms = started.elapsed().as_millis().min(i64::MAX as u128) as i64;
120 match result {
121 Ok(value) => {
122 finish_run(conn, command, "success", duration_ms, None)?;
123 Ok(value)
124 }
125 Err(error) => {
126 if let Err(record_error) = finish_run(
129 conn,
130 command,
131 "failed",
132 duration_ms,
133 Some(&error.to_string()),
134 ) {
135 return Err(error.context(format!(
136 "also could not record the failed run: {record_error}"
137 )));
138 }
139 Err(error)
140 }
141 }
142}
143
144pub fn record_heartbeat_in(
150 conn: &Connection,
151 ctx: &crate::library::LibraryContext,
152 command: &str,
153) -> Result<()> {
154 ctx.ensure_root_identity()?;
157 ensure_pipeline_runs_table(conn)?;
158 conn.execute(
159 "INSERT INTO pipeline_runs (command, started_at, status, summary)
160 VALUES (?1, datetime('now'), 'success', 'last successful cycle')
161 ON CONFLICT(command) DO UPDATE SET
162 started_at = excluded.started_at,
163 status = 'success',
164 finished_at = NULL,
165 duration_ms = NULL,
166 summary = excluded.summary",
167 params![command],
168 )?;
169 Ok(())
170}
171
172pub fn read_all_in(
178 conn: &Connection,
179 ctx: &crate::library::LibraryContext,
180) -> Result<Vec<PipelineRunStatus>> {
181 ensure_pipeline_runs_table(conn)?;
182 let mut out = Vec::with_capacity(TRACKED_COMMANDS.len());
183 for command in TRACKED_COMMANDS {
184 out.push(read_one_in(conn, ctx, command)?);
185 }
186 if conn
192 .query_row(
193 "SELECT 1 FROM pipeline_runs WHERE command = 'watch'",
194 [],
195 |r| r.get::<_, i64>(0),
196 )
197 .optional()?
198 .is_some()
199 {
200 out.push(read_one_in(conn, ctx, "watch")?);
201 }
202 Ok(out)
203}
204
205fn read_one_in(
208 conn: &Connection,
209 ctx: &crate::library::LibraryContext,
210 command: &str,
211) -> Result<PipelineRunStatus> {
212 let row: Option<(String, Option<i64>, String)> = conn
213 .query_row(
214 "SELECT started_at, duration_ms, status FROM pipeline_runs WHERE command = ?1",
215 params![command],
216 |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
217 )
218 .optional()?;
219 let currently_running = crate::library_locks::command_locked(ctx, command)?;
220 let (last_run_at, status, duration_ms) = match row {
221 None => (None, None, None),
222 Some((started_at, duration_ms, stored_status)) => {
223 let status = if stored_status == "running" && !currently_running {
224 "crashed".to_string()
225 } else {
226 stored_status
227 };
228 (Some(started_at), Some(status), duration_ms)
229 }
230 };
231 Ok(PipelineRunStatus {
232 command: command.to_string(),
233 last_run_at,
234 status,
235 duration_ms,
236 currently_running,
237 })
238}
239
240pub fn install_sigint_handler_in(
252 ctx: std::sync::Arc<crate::library::LibraryContext>,
253 command: &'static str,
254) -> Result<()> {
255 ctx.ensure_root_identity()
256 .context("validating the library before installing the SIGINT handler")?;
257 ctrlc::set_handler(move || {
258 if ctx.ensure_root_identity().is_ok() {
259 if let Ok(conn) = crate::library_db::open_without_create(&ctx.paths.db) {
260 let _ = conn.busy_timeout(std::time::Duration::from_secs(5));
261 let started_at: Option<String> = conn
262 .query_row(
263 "SELECT started_at FROM pipeline_runs WHERE command = ?1",
264 params![command],
265 |r| r.get(0),
266 )
267 .optional()
268 .ok()
269 .flatten();
270 let duration_ms = started_at
271 .and_then(|s| {
272 chrono::NaiveDateTime::parse_from_str(&s, "%Y-%m-%d %H:%M:%S").ok()
273 })
274 .map(|started| {
275 (chrono::Utc::now().naive_utc() - started)
276 .num_milliseconds()
277 .max(0)
278 })
279 .unwrap_or(0);
280 let _ = finish_run(&conn, command, "interrupted", duration_ms, None);
281 }
282 }
283 std::process::exit(130);
284 })
285 .context("installing SIGINT handler")
286}
287
288#[derive(Debug, Clone, PartialEq, Serialize)]
289pub struct PipelineRunStatus {
290 pub command: String,
291 pub last_run_at: Option<String>,
292 pub status: Option<String>,
295 pub duration_ms: Option<i64>,
296 pub currently_running: bool,
297}
298
299#[cfg(test)]
300mod tests {
301 use super::*;
302
303 fn test_db() -> Connection {
304 let conn = Connection::open_in_memory().unwrap();
305 ensure_pipeline_runs_table(&conn).unwrap();
306 conn
307 }
308
309 #[test]
310 fn heartbeat_records_last_cycle_and_reads_back() {
311 let (_t, ctx, conn) = in_library();
312 assert!(read_all_in(&conn, &ctx)
314 .unwrap()
315 .iter()
316 .all(|r| r.command != "watch"));
317 record_heartbeat_in(&conn, &ctx, "watch").unwrap();
318 let w = read_all_in(&conn, &ctx)
319 .unwrap()
320 .into_iter()
321 .find(|r| r.command == "watch")
322 .expect("the heartbeat row must surface in the run read");
323 assert!(w.last_run_at.is_some(), "started_at is the last-cycle time");
324 assert_eq!(w.status.as_deref(), Some("success"));
325 assert!(!w.currently_running, "no watch process holds the lock");
326
327 record_heartbeat_in(&conn, &ctx, "watch").unwrap();
330 assert_eq!(
331 read_all_in(&conn, &ctx)
332 .unwrap()
333 .iter()
334 .filter(|r| r.command == "watch")
335 .count(),
336 1
337 );
338 }
339
340 #[test]
341 fn ensure_pipeline_runs_table_is_idempotent() {
342 let conn = test_db();
343 ensure_pipeline_runs_table(&conn).unwrap();
344 }
345
346 #[test]
347 fn start_run_then_finish_run_records_success() {
348 let conn = test_db();
349 start_run(&conn, "embed").unwrap();
350
351 let status: String = conn
352 .query_row(
353 "SELECT status FROM pipeline_runs WHERE command = 'embed'",
354 [],
355 |r| r.get(0),
356 )
357 .unwrap();
358 assert_eq!(status, "running");
359
360 finish_run(&conn, "embed", "success", 1234, None).unwrap();
361
362 let (status, duration_ms, summary): (String, i64, Option<String>) = conn
363 .query_row(
364 "SELECT status, duration_ms, summary FROM pipeline_runs WHERE command = 'embed'",
365 [],
366 |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
367 )
368 .unwrap();
369 assert_eq!(status, "success");
370 assert_eq!(duration_ms, 1234);
371 assert_eq!(summary, None);
372 }
373
374 #[test]
375 fn start_run_upserts_resetting_prior_finish_fields() {
376 let conn = test_db();
377 start_run(&conn, "embed").unwrap();
378 finish_run(&conn, "embed", "failed", 500, Some("boom")).unwrap();
379
380 start_run(&conn, "embed").unwrap(); let (status, duration_ms, summary): (String, Option<i64>, Option<String>) = conn
383 .query_row(
384 "SELECT status, duration_ms, summary FROM pipeline_runs WHERE command = 'embed'",
385 [],
386 |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
387 )
388 .unwrap();
389 assert_eq!(status, "running");
390 assert_eq!(duration_ms, None);
391 assert_eq!(summary, None);
392
393 let count: i64 = conn
394 .query_row("SELECT COUNT(*) FROM pipeline_runs", [], |r| r.get(0))
395 .unwrap();
396 assert_eq!(count, 1, "upsert, not a second row");
397 }
398
399 fn in_library() -> (
404 tempfile::TempDir,
405 crate::library::LibraryContext,
406 Connection,
407 ) {
408 let temp = tempfile::tempdir().unwrap();
409 let root = temp.path().join("photos");
410 std::fs::create_dir(&root).unwrap();
411 let ctx = crate::library::LibraryContext::new(&root, &temp.path().join("cache")).unwrap();
412 std::fs::create_dir_all(&ctx.paths.locks).unwrap();
413 let conn = Connection::open_in_memory().unwrap();
414 ensure_pipeline_runs_table(&conn).unwrap();
415 (temp, ctx, conn)
416 }
417
418 #[test]
419 fn track_in_records_runs_under_an_already_held_command_guard() {
420 let (_t, ctx, conn) = in_library();
421 let guard = crate::library_locks::try_command(&ctx, "scan").unwrap();
422 let result = track_in(&conn, &ctx, &guard, "scan", || Ok(7)).unwrap();
423 assert_eq!(result, 7);
424 let (status, summary): (String, Option<String>) = conn
425 .query_row(
426 "SELECT status, summary FROM pipeline_runs WHERE command = 'scan'",
427 [],
428 |r| Ok((r.get(0)?, r.get(1)?)),
429 )
430 .unwrap();
431 assert_eq!(status, "success");
432 assert_eq!(summary, None);
433 let count: i64 = conn
436 .query_row("SELECT COUNT(*) FROM pipeline_runs", [], |r| r.get(0))
437 .unwrap();
438 assert_eq!(count, 1);
439 let failed: Result<()> =
440 track_in(&conn, &ctx, &guard, "scan", || Err(anyhow::anyhow!("boom")));
441 failed.unwrap_err();
442 let (status, summary): (String, Option<String>) = conn
443 .query_row(
444 "SELECT status, summary FROM pipeline_runs WHERE command = 'scan'",
445 [],
446 |r| Ok((r.get(0)?, r.get(1)?)),
447 )
448 .unwrap();
449 assert_eq!(status, "failed");
450 assert_eq!(summary.as_deref(), Some("boom"));
451 }
452
453 #[test]
454 fn track_in_refuses_a_guard_from_another_command_or_library() {
455 let (_t, ctx, conn) = in_library();
456 let guard = crate::library_locks::try_command(&ctx, "scan").unwrap();
457 let result: Result<()> = track_in(&conn, &ctx, &guard, "embed", || Ok(()));
459 let err = result.unwrap_err();
460 assert!(format!("{err:#}").contains("scan"), "{err:#}");
461 let count: i64 = conn
462 .query_row("SELECT COUNT(*) FROM pipeline_runs", [], |r| r.get(0))
463 .unwrap();
464 assert_eq!(count, 0, "a refused guard must write no row");
465
466 let temp = tempfile::tempdir().unwrap();
469 let other_root = temp.path().join("other");
470 std::fs::create_dir(&other_root).unwrap();
471 let other =
472 crate::library::LibraryContext::new(&other_root, &temp.path().join("cache")).unwrap();
473 let result: Result<()> = track_in(&conn, &other, &guard, "scan", || Ok(()));
474 let err = result.unwrap_err();
475 assert!(
476 format!("{err:#}").contains(other_root.file_name().unwrap().to_string_lossy().as_ref()),
477 "{err:#}"
478 );
479 let count: i64 = conn
480 .query_row("SELECT COUNT(*) FROM pipeline_runs", [], |r| r.get(0))
481 .unwrap();
482 assert_eq!(count, 0);
483 }
484
485 #[test]
486 fn read_all_in_answers_liveness_from_the_library_locks() {
487 let (_t, ctx, conn) = in_library();
488 let guard = crate::library_locks::try_command(&ctx, "scan").unwrap();
489 track_in(&conn, &ctx, &guard, "scan", || Ok(())).unwrap();
490 drop(guard);
492 let _faces = crate::library_locks::try_command(&ctx, "faces").unwrap();
496 let statuses = read_all_in(&conn, &ctx).unwrap();
497 let scan = statuses.iter().find(|s| s.command == "scan").unwrap();
498 assert_eq!(scan.status.as_deref(), Some("success"));
499 assert!(!scan.currently_running);
500 let faces = statuses.iter().find(|s| s.command == "faces").unwrap();
501 assert_eq!(faces.status, None);
502 assert!(faces.currently_running);
503 }
504
505 #[test]
506 fn install_sigint_handler_in_validates_the_library_before_installing() {
507 let temp = tempfile::tempdir().unwrap();
512 let root = temp.path().join("photos");
513 std::fs::create_dir(&root).unwrap();
514 let ctx = std::sync::Arc::new(
515 crate::library::LibraryContext::new(&root, &temp.path().join("cache")).unwrap(),
516 );
517 std::fs::rename(&root, temp.path().join("moved")).unwrap();
518 std::fs::create_dir(&root).unwrap();
519 let err = install_sigint_handler_in(ctx, "scan").unwrap_err();
520 assert!(format!("{err:#}").contains("no longer names"), "{err:#}");
521 }
522}