1use rusqlite::{params, Connection, OptionalExtension};
6use serde::{Deserialize, Serialize};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
9#[serde(rename_all = "snake_case")]
10pub enum RunState {
11 Queued,
12 WaitingForUnlock,
13 Planning,
14 AwaitingApproval,
15 Running,
16 StepDispatching,
17 StepDone,
18 RetryWait,
19 Paused,
20 Uncertain,
21 NeedsAttention,
22 Succeeded,
23 Failed,
24 SkippedStale,
25 Cancelled,
26}
27
28impl RunState {
29 pub fn as_str(self) -> &'static str {
30 match self {
31 Self::Queued => "queued",
32 Self::WaitingForUnlock => "waiting_for_unlock",
33 Self::Planning => "planning",
34 Self::AwaitingApproval => "awaiting_approval",
35 Self::Running => "running",
36 Self::StepDispatching => "step_dispatching",
37 Self::StepDone => "step_done",
38 Self::RetryWait => "retry_wait",
39 Self::Paused => "paused",
40 Self::Uncertain => "uncertain",
41 Self::NeedsAttention => "needs_attention",
42 Self::Succeeded => "succeeded",
43 Self::Failed => "failed",
44 Self::SkippedStale => "skipped_stale",
45 Self::Cancelled => "cancelled",
46 }
47 }
48
49 fn parse(value: &str) -> Result<Self, String> {
50 match value {
51 "queued" => Ok(Self::Queued),
52 "waiting_for_unlock" => Ok(Self::WaitingForUnlock),
53 "planning" => Ok(Self::Planning),
54 "awaiting_approval" => Ok(Self::AwaitingApproval),
55 "running" => Ok(Self::Running),
56 "step_dispatching" => Ok(Self::StepDispatching),
57 "step_done" => Ok(Self::StepDone),
58 "retry_wait" => Ok(Self::RetryWait),
59 "paused" => Ok(Self::Paused),
60 "uncertain" => Ok(Self::Uncertain),
61 "needs_attention" => Ok(Self::NeedsAttention),
62 "succeeded" => Ok(Self::Succeeded),
63 "failed" => Ok(Self::Failed),
64 "skipped_stale" => Ok(Self::SkippedStale),
65 "cancelled" => Ok(Self::Cancelled),
66 _ => Err(format!("Unknown operation state `{value}`")),
67 }
68 }
69
70 pub fn terminal(self) -> bool {
71 matches!(
72 self,
73 Self::Succeeded | Self::Failed | Self::SkippedStale | Self::Cancelled
74 )
75 }
76}
77
78const EDGES: &[(RunState, RunState)] = &[
79 (RunState::Queued, RunState::WaitingForUnlock),
80 (RunState::Queued, RunState::Planning),
81 (RunState::Queued, RunState::Cancelled),
82 (RunState::WaitingForUnlock, RunState::Planning),
83 (RunState::WaitingForUnlock, RunState::Cancelled),
84 (RunState::Planning, RunState::Running),
85 (RunState::Planning, RunState::AwaitingApproval),
86 (RunState::Planning, RunState::Paused),
87 (RunState::Planning, RunState::SkippedStale),
88 (RunState::Planning, RunState::Cancelled),
89 (RunState::AwaitingApproval, RunState::Planning),
90 (RunState::AwaitingApproval, RunState::Cancelled),
91 (RunState::Running, RunState::StepDispatching),
92 (RunState::Running, RunState::RetryWait),
93 (RunState::Running, RunState::Paused),
94 (RunState::Running, RunState::Uncertain),
95 (RunState::Running, RunState::Succeeded),
96 (RunState::Running, RunState::Failed),
97 (RunState::Running, RunState::Cancelled),
98 (RunState::StepDispatching, RunState::StepDone),
99 (RunState::StepDispatching, RunState::Uncertain),
100 (RunState::StepDispatching, RunState::Paused),
101 (RunState::StepDone, RunState::Running),
102 (RunState::Uncertain, RunState::StepDone),
103 (RunState::Uncertain, RunState::Running),
104 (RunState::Uncertain, RunState::NeedsAttention),
105 (RunState::RetryWait, RunState::Planning),
106 (RunState::Paused, RunState::Planning),
107 (RunState::NeedsAttention, RunState::Planning),
108];
109
110pub fn can_transition(from: RunState, to: RunState) -> bool {
111 EDGES.contains(&(from, to))
112}
113
114pub fn init_schema(conn: &Connection) -> Result<(), String> {
115 conn.execute_batch(
116 "CREATE TABLE IF NOT EXISTS ops_schedules (
117 id TEXT PRIMARY KEY, kind TEXT NOT NULL, target TEXT NOT NULL, rule TEXT NOT NULL,
118 enabled INTEGER NOT NULL, policy_rev INTEGER NOT NULL, next_due_at TEXT,
119 last_run_id TEXT, max_lateness_secs INTEGER, created_at TEXT NOT NULL,
120 updated_at TEXT NOT NULL
121 );
122 CREATE TABLE IF NOT EXISTS ops_runs (
123 id TEXT PRIMARY KEY, schedule_id TEXT, kind TEXT NOT NULL, state TEXT NOT NULL,
124 plan TEXT NOT NULL, plan_hash TEXT NOT NULL, input_revs TEXT NOT NULL,
125 policy_rev INTEGER NOT NULL, plugin_provenance TEXT,
126 missed_occurrences INTEGER NOT NULL DEFAULT 0, attempt INTEGER NOT NULL DEFAULT 0,
127 next_attempt_at TEXT, lease_epoch INTEGER, created_at TEXT NOT NULL,
128 started_at TEXT, finished_at TEXT, outcome TEXT, error_code TEXT, error_msg TEXT
129 );
130 CREATE INDEX IF NOT EXISTS ops_runs_schedule ON ops_runs(schedule_id, created_at DESC);
131 CREATE TABLE IF NOT EXISTS ops_steps (
132 run_id TEXT NOT NULL, seq INTEGER NOT NULL, kind TEXT NOT NULL, target TEXT NOT NULL,
133 state TEXT NOT NULL, idempotency_key TEXT NOT NULL, issuer_ref TEXT, output TEXT,
134 attempt INTEGER NOT NULL, started_at TEXT, finished_at TEXT,
135 PRIMARY KEY (run_id, seq)
136 );
137 CREATE TABLE IF NOT EXISTS ops_lease (
138 id INTEGER PRIMARY KEY CHECK (id = 1), holder TEXT NOT NULL, pid INTEGER NOT NULL,
139 host TEXT NOT NULL, epoch INTEGER NOT NULL, acquired_at TEXT NOT NULL,
140 heartbeat_at TEXT NOT NULL
141 );",
142 )
143 .map_err(|e| e.to_string())
144}
145
146#[derive(Debug, Clone, Serialize)]
147pub struct Schedule {
148 pub id: String,
149 pub kind: String,
150 pub target: String,
151 pub rule: String,
152 pub enabled: bool,
153 pub policy_rev: i64,
154 pub next_due_at: Option<String>,
155 pub last_run_id: Option<String>,
156 pub max_lateness_secs: Option<i64>,
157 pub created_at: String,
158 pub updated_at: String,
159}
160
161fn schedule_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Schedule> {
162 Ok(Schedule {
163 id: row.get(0)?,
164 kind: row.get(1)?,
165 target: row.get(2)?,
166 rule: row.get(3)?,
167 enabled: row.get::<_, i64>(4)? != 0,
168 policy_rev: row.get(5)?,
169 next_due_at: row.get(6)?,
170 last_run_id: row.get(7)?,
171 max_lateness_secs: row.get(8)?,
172 created_at: row.get(9)?,
173 updated_at: row.get(10)?,
174 })
175}
176
177pub fn add_schedule(
178 conn: &Connection,
179 id: &str,
180 kind: &str,
181 target: &str,
182 rule: &str,
183 next_due_at: Option<&str>,
184 max_lateness_secs: Option<i64>,
185) -> Result<Schedule, String> {
186 let now = crate::iso_now();
187 conn.execute(
188 "INSERT INTO ops_schedules (id, kind, target, rule, enabled, policy_rev, next_due_at, max_lateness_secs, created_at, updated_at)
189 VALUES (?1, ?2, ?3, ?4, 1, 1, ?5, ?6, ?7, ?7)",
190 params![id, kind, target, rule, next_due_at, max_lateness_secs, now],
191 ).map_err(|e| e.to_string())?;
192 get_schedule(conn, id)?.ok_or_else(|| "Schedule was not stored".to_string())
193}
194
195pub fn get_schedule(conn: &Connection, id: &str) -> Result<Option<Schedule>, String> {
196 conn.query_row(
197 "SELECT id, kind, target, rule, enabled, policy_rev, next_due_at, last_run_id, max_lateness_secs, created_at, updated_at FROM ops_schedules WHERE id = ?1",
198 [id], schedule_row,
199 ).optional().map_err(|e| e.to_string())
200}
201
202pub fn list_schedules(conn: &Connection) -> Result<Vec<Schedule>, String> {
203 let mut stmt = conn.prepare(
204 "SELECT id, kind, target, rule, enabled, policy_rev, next_due_at, last_run_id, max_lateness_secs, created_at, updated_at FROM ops_schedules ORDER BY created_at DESC",
205 ).map_err(|e| e.to_string())?;
206 let schedules = stmt
207 .query_map([], schedule_row)
208 .map_err(|e| e.to_string())?
209 .collect::<Result<Vec<_>, _>>()
210 .map_err(|e| e.to_string())?;
211 Ok(schedules)
212}
213
214pub fn update_schedule_due(
215 conn: &Connection,
216 id: &str,
217 next_due_at: Option<&str>,
218) -> Result<(), String> {
219 conn.execute(
220 "UPDATE ops_schedules SET next_due_at = ?2, updated_at = ?3 WHERE id = ?1",
221 params![id, next_due_at, crate::iso_now()],
222 )
223 .map_err(|e| e.to_string())?;
224 Ok(())
225}
226
227pub fn complete_schedule_occurrence(
230 conn: &Connection,
231 id: &str,
232 run_id: &str,
233 next_due_at: Option<&str>,
234) -> Result<(), String> {
235 conn.execute(
236 "UPDATE ops_schedules SET last_run_id = ?2, next_due_at = ?3, updated_at = ?4 WHERE id = ?1",
237 params![id, run_id, next_due_at, crate::iso_now()],
238 )
239 .map_err(|e| e.to_string())?;
240 Ok(())
241}
242
243fn assert_epoch(conn: &Connection, epoch: i64) -> Result<(), String> {
244 let held = holder(conn)?
245 .ok_or_else(|| "No operations lease is held".to_string())?
246 .epoch;
247 if held != epoch {
248 return Err("Operations lease changed; refusing stale worker write".to_string());
249 }
250 Ok(())
251}
252
253pub fn complete_schedule_occurrence_fenced(
254 conn: &Connection,
255 id: &str,
256 run_id: &str,
257 next_due_at: Option<&str>,
258 epoch: i64,
259) -> Result<(), String> {
260 assert_epoch(conn, epoch)?;
261 complete_schedule_occurrence(conn, id, run_id, next_due_at)
262}
263
264#[derive(Debug, Clone, Serialize)]
265pub struct Run {
266 pub id: String,
267 pub schedule_id: Option<String>,
268 pub kind: String,
269 pub state: RunState,
270 pub missed_occurrences: i64,
271 pub lease_epoch: Option<i64>,
272 pub created_at: String,
273 pub started_at: Option<String>,
274 pub finished_at: Option<String>,
275 pub outcome: Option<String>,
276 pub error_code: Option<String>,
277 pub error_msg: Option<String>,
278}
279
280fn run_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Run> {
281 let state: String = row.get(3)?;
282 Ok(Run {
283 id: row.get(0)?,
284 schedule_id: row.get(1)?,
285 kind: row.get(2)?,
286 state: RunState::parse(&state).map_err(|_| rusqlite::Error::InvalidQuery)?,
287 missed_occurrences: row.get(4)?,
288 lease_epoch: row.get(5)?,
289 created_at: row.get(6)?,
290 started_at: row.get(7)?,
291 finished_at: row.get(8)?,
292 outcome: row.get(9)?,
293 error_code: row.get(10)?,
294 error_msg: row.get(11)?,
295 })
296}
297
298const RUN_COLUMNS: &str = "id, schedule_id, kind, state, missed_occurrences, lease_epoch, created_at, started_at, finished_at, outcome, error_code, error_msg";
299
300pub fn create_run(
301 conn: &Connection,
302 id: &str,
303 schedule: Option<&Schedule>,
304 missed_occurrences: i64,
305 lease_epoch: Option<i64>,
306) -> Result<Run, String> {
307 create_run_with_kind(
308 conn,
309 id,
310 schedule,
311 "backup.package",
312 missed_occurrences,
313 lease_epoch,
314 )
315}
316
317pub fn create_run_with_kind(
321 conn: &Connection,
322 id: &str,
323 schedule: Option<&Schedule>,
324 manual_kind: &str,
325 missed_occurrences: i64,
326 lease_epoch: Option<i64>,
327) -> Result<Run, String> {
328 let (schedule_id, kind, policy_rev) = match schedule {
329 Some(s) => (Some(s.id.as_str()), s.kind.as_str(), s.policy_rev),
330 None => (None, manual_kind, 1),
331 };
332 let now = crate::iso_now();
333 conn.execute(
334 "INSERT INTO ops_runs (id, schedule_id, kind, state, plan, plan_hash, input_revs, policy_rev, missed_occurrences, lease_epoch, created_at)
335 VALUES (?1, ?2, ?3, 'queued', '{}', '', '{}', ?4, ?5, ?6, ?7)",
336 params![id, schedule_id, kind, policy_rev, missed_occurrences, lease_epoch, now],
337 ).map_err(|e| e.to_string())?;
338 get_run(conn, id)?.ok_or_else(|| "Run was not stored".to_string())
339}
340
341pub fn create_run_fenced(
342 conn: &Connection,
343 id: &str,
344 schedule: Option<&Schedule>,
345 missed_occurrences: i64,
346 epoch: i64,
347) -> Result<Run, String> {
348 assert_epoch(conn, epoch)?;
349 create_run(conn, id, schedule, missed_occurrences, Some(epoch))
350}
351
352pub fn record_plugin_provenance(
357 conn: &Connection,
358 run_id: &str,
359 plugin: &str,
360 hash: &str,
361) -> Result<(), String> {
362 let current: Option<String> = conn
363 .query_row(
364 "SELECT plugin_provenance FROM ops_runs WHERE id = ?1",
365 [run_id],
366 |r| r.get(0),
367 )
368 .optional()
369 .map_err(|e| e.to_string())?
370 .ok_or_else(|| format!("No run {run_id}"))?;
371 let mut map: serde_json::Map<String, serde_json::Value> = match current {
372 Some(t) if !t.is_empty() => serde_json::from_str(&t).map_err(|e| e.to_string())?,
373 _ => Default::default(),
374 };
375 map.insert(plugin.into(), hash.into());
376 conn.execute(
377 "UPDATE ops_runs SET plugin_provenance = ?2 WHERE id = ?1",
378 params![run_id, serde_json::Value::Object(map).to_string()],
379 )
380 .map_err(|e| e.to_string())?;
381 Ok(())
382}
383
384pub fn plugin_provenance(
386 conn: &Connection,
387 run_id: &str,
388) -> Result<std::collections::BTreeMap<String, String>, String> {
389 let text: Option<String> = conn
390 .query_row(
391 "SELECT plugin_provenance FROM ops_runs WHERE id = ?1",
392 [run_id],
393 |r| r.get(0),
394 )
395 .optional()
396 .map_err(|e| e.to_string())?
397 .ok_or_else(|| format!("No run {run_id}"))?;
398 match text {
399 Some(t) if !t.is_empty() => serde_json::from_str(&t).map_err(|e| e.to_string()),
400 _ => Ok(Default::default()),
401 }
402}
403
404pub fn get_run(conn: &Connection, id: &str) -> Result<Option<Run>, String> {
405 conn.query_row(
406 &format!("SELECT {RUN_COLUMNS} FROM ops_runs WHERE id = ?1"),
407 [id],
408 run_row,
409 )
410 .optional()
411 .map_err(|e| e.to_string())
412}
413
414pub fn list_runs(conn: &Connection) -> Result<Vec<Run>, String> {
415 let mut stmt = conn
416 .prepare(&format!(
417 "SELECT {RUN_COLUMNS} FROM ops_runs ORDER BY created_at DESC"
418 ))
419 .map_err(|e| e.to_string())?;
420 let runs = stmt
421 .query_map([], run_row)
422 .map_err(|e| e.to_string())?
423 .collect::<Result<Vec<_>, _>>()
424 .map_err(|e| e.to_string())?;
425 Ok(runs)
426}
427
428pub fn transition_run(
429 conn: &Connection,
430 id: &str,
431 to: RunState,
432 outcome: Option<&str>,
433 error: Option<(&str, &str)>,
434) -> Result<Run, String> {
435 let current = get_run(conn, id)?.ok_or_else(|| format!("No such operation `{id}`"))?;
436 if !can_transition(current.state, to) {
437 return Err(format!(
438 "Illegal operation transition {} -> {}",
439 current.state.as_str(),
440 to.as_str()
441 ));
442 }
443 let now = crate::iso_now();
444 let started = if to == RunState::Running && current.started_at.is_none() {
445 Some(now.as_str())
446 } else {
447 None
448 };
449 let finished = if to.terminal() {
450 Some(now.as_str())
451 } else {
452 None
453 };
454 let (error_code, error_msg) = error.map_or((None, None), |(code, msg)| (Some(code), Some(msg)));
455 conn.execute(
456 "UPDATE ops_runs SET state = ?2, started_at = COALESCE(?3, started_at), finished_at = COALESCE(?4, finished_at), outcome = COALESCE(?5, outcome), error_code = ?6, error_msg = ?7 WHERE id = ?1",
457 params![id, to.as_str(), started, finished, outcome, error_code, error_msg],
458 ).map_err(|e| e.to_string())?;
459 get_run(conn, id)?.ok_or_else(|| "Run disappeared".to_string())
460}
461
462pub fn transition_run_fenced(
464 conn: &Connection,
465 id: &str,
466 epoch: i64,
467 to: RunState,
468 outcome: Option<&str>,
469 error: Option<(&str, &str)>,
470) -> Result<Run, String> {
471 assert_epoch(conn, epoch)?;
472 transition_run(conn, id, to, outcome, error)
473}
474
475#[derive(Debug, Clone, Serialize)]
476pub struct Lease {
477 pub holder: String,
478 pub epoch: i64,
479}
480
481pub fn acquire_lease(
482 conn: &Connection,
483 holder: &str,
484 pid: i64,
485 host: &str,
486) -> Result<Lease, String> {
487 let now = crate::iso_now();
488 conn.execute(
489 "INSERT OR IGNORE INTO ops_lease (id, holder, pid, host, epoch, acquired_at, heartbeat_at) VALUES (1, ?1, ?2, ?3, 0, ?4, ?4)",
490 params![holder, pid, host, now],
491 ).map_err(|e| e.to_string())?;
492 conn.execute(
493 "UPDATE ops_lease SET holder = ?1, pid = ?2, host = ?3, epoch = epoch + 1, acquired_at = ?4, heartbeat_at = ?4 WHERE id = 1",
494 params![holder, pid, host, now],
495 ).map_err(|e| e.to_string())?;
496 let epoch = conn
497 .query_row("SELECT epoch FROM ops_lease WHERE id = 1", [], |row| {
498 row.get(0)
499 })
500 .map_err(|e| e.to_string())?;
501 Ok(Lease {
502 holder: holder.to_string(),
503 epoch,
504 })
505}
506
507pub fn holder(conn: &Connection) -> Result<Option<Lease>, String> {
508 conn.query_row(
509 "SELECT holder, epoch FROM ops_lease WHERE id = 1",
510 [],
511 |row| {
512 Ok(Lease {
513 holder: row.get(0)?,
514 epoch: row.get(1)?,
515 })
516 },
517 )
518 .optional()
519 .map_err(|e| e.to_string())
520}
521
522pub fn mark_interrupted(conn: &Connection) -> Result<(), String> {
523 conn.execute("UPDATE ops_runs SET state = 'paused' WHERE state IN ('queued', 'planning', 'running', 'retry_wait')", [])
524 .map_err(|e| e.to_string())?;
525 conn.execute(
526 "UPDATE ops_steps SET state = 'uncertain' WHERE state = 'dispatching'",
527 [],
528 )
529 .map_err(|e| e.to_string())?;
530 Ok(())
531}
532
533pub const DEPLOY_KIND: &str = "deploy.push";
542
543pub const DEPLOY_MAX_ATTEMPTS: i64 = 5;
545
546pub const DEPLOY_EXPIRY_DAYS: i64 = 7;
549
550fn deploy_key(node_id: &str, target: &str, sha256: &str) -> String {
551 format!("{node_id}|{target}|{sha256}")
552}
553
554fn open_deploys(
555 conn: &Connection,
556 node_id: &str,
557 target: &str,
558) -> Result<Vec<(Run, String)>, String> {
559 let prefix = format!("{node_id}|{target}|");
560 let mut stmt = conn
561 .prepare(&format!(
562 "SELECT {RUN_COLUMNS}, plan_hash FROM ops_runs WHERE kind = ?1 \
563 AND substr(plan_hash, 1, length(?2)) = ?2 \
564 AND state NOT IN ('succeeded', 'failed', 'skipped_stale', 'cancelled') \
565 ORDER BY created_at"
566 ))
567 .map_err(|e| e.to_string())?;
568 let rows = stmt
569 .query_map(params![DEPLOY_KIND, prefix], |row| {
570 Ok((run_row(row)?, row.get::<_, String>(12)?))
571 })
572 .map_err(|e| e.to_string())?
573 .collect::<Result<Vec<_>, _>>()
574 .map_err(|e| e.to_string())?;
575 Ok(rows)
576}
577
578fn walk_to_running(conn: &Connection, run: &Run) -> Result<(), String> {
580 use RunState::*;
581 let path: &[RunState] = match run.state {
582 Running => &[],
583 Queued => &[Planning, Running],
584 Planning => &[Running],
585 AwaitingApproval | Paused | RetryWait | NeedsAttention => &[Planning, Running],
586 Uncertain | StepDone => &[Running],
587 StepDispatching => &[StepDone, Running],
588 other => return Err(format!("operation is already {}", other.as_str())),
589 };
590 for to in path {
591 transition_run(conn, &run.id, *to, None, None)?;
592 }
593 Ok(())
594}
595
596fn set_step(conn: &Connection, run_id: &str, state: &str, output: Option<&str>) {
597 let _ = conn.execute(
598 "UPDATE ops_steps SET state = ?2, output = COALESCE(?3, output), finished_at = ?4 \
599 WHERE run_id = ?1 AND seq = 0",
600 params![run_id, state, output, crate::iso_now()],
601 );
602}
603
604fn close_deploy(
605 conn: &Connection,
606 run: &Run,
607 to: RunState,
608 outcome: &str,
609 error: Option<(&str, &str)>,
610) -> Result<(), String> {
611 if run.state != RunState::AwaitingApproval {
612 walk_to_running(conn, run)?;
613 }
614 transition_run(conn, &run.id, to, Some(outcome), error)?;
615 Ok(())
616}
617
618fn expire_deploys(conn: &Connection) -> Result<(), String> {
620 let mut stmt = conn
621 .prepare(&format!(
622 "SELECT {RUN_COLUMNS} FROM ops_runs WHERE kind = ?1 \
623 AND state NOT IN ('succeeded', 'failed', 'skipped_stale', 'cancelled') \
624 AND julianday('now') - julianday(created_at) > ?2"
625 ))
626 .map_err(|e| e.to_string())?;
627 let old = stmt
628 .query_map(params![DEPLOY_KIND, DEPLOY_EXPIRY_DAYS], run_row)
629 .map_err(|e| e.to_string())?
630 .collect::<Result<Vec<_>, _>>()
631 .map_err(|e| e.to_string())?;
632 for run in old {
633 close_deploy(
634 conn,
635 &run,
636 RunState::Cancelled,
637 "expired without a result",
638 None,
639 )?;
640 }
641 Ok(())
642}
643
644pub fn deploy_dispatch(
648 conn: &Connection,
649 node_id: &str,
650 node_name: &str,
651 target: &str,
652 sha256: &str,
653 held: bool,
654) -> Result<String, String> {
655 init_schema(conn)?;
656 expire_deploys(conn)?;
657 let key = deploy_key(node_id, target, sha256);
658 let mut current: Option<Run> = None;
659 for (run, k) in open_deploys(conn, node_id, target)? {
660 if k == key {
661 current = Some(run);
662 } else {
663 close_deploy(
664 conn,
665 &run,
666 RunState::Cancelled,
667 "superseded by newer bytes",
668 None,
669 )?;
670 }
671 }
672 let run = match current {
673 Some(r) => r,
674 None => {
675 let id = crate::new_uuid();
676 create_run_with_kind(conn, &id, None, DEPLOY_KIND, 0, None)?;
677 let plan = serde_json::json!({
678 "node": node_id, "node_name": node_name, "target": target, "sha256": sha256,
679 })
680 .to_string();
681 conn.execute(
682 "UPDATE ops_runs SET plan = ?2, plan_hash = ?3 WHERE id = ?1",
683 params![id, plan, key],
684 )
685 .map_err(|e| e.to_string())?;
686 transition_run(conn, &id, RunState::Planning, None, None)?;
687 if held {
688 transition_run(conn, &id, RunState::AwaitingApproval, None, None)?;
689 }
690 get_run(conn, &id)?.ok_or_else(|| "Run was not stored".to_string())?
691 }
692 };
693 if held {
694 return Ok(run.id);
695 }
696 walk_to_running(conn, &run)?;
697 conn.execute(
698 "INSERT INTO ops_steps (run_id, seq, kind, target, state, idempotency_key, attempt, started_at) \
699 VALUES (?1, 0, 'node.apply', ?2, 'dispatching', ?3, 1, ?4) \
700 ON CONFLICT(run_id, seq) DO UPDATE SET state = 'dispatching', attempt = attempt + 1, \
701 finished_at = NULL",
702 params![run.id, format!("{node_name}/{target}"), sha256, crate::iso_now()],
703 )
704 .map_err(|e| e.to_string())?;
705 Ok(run.id)
706}
707
708pub fn deploy_result(
712 conn: &Connection,
713 node_id: &str,
714 target: &str,
715 sha256: &str,
716 ok: bool,
717 error: Option<&str>,
718) -> Result<(), String> {
719 init_schema(conn)?;
720 let key = deploy_key(node_id, target, sha256);
721 for (run, k) in open_deploys(conn, node_id, target)? {
722 if k != key {
723 continue;
724 }
725 if ok {
726 set_step(conn, &run.id, "done", Some("applied"));
727 close_deploy(conn, &run, RunState::Succeeded, "applied", None)?;
728 continue;
729 }
730 let msg = error.unwrap_or("not applied");
731 let attempts: i64 = conn
732 .query_row(
733 "SELECT attempt FROM ops_steps WHERE run_id = ?1 AND seq = 0",
734 [&run.id],
735 |r| r.get(0),
736 )
737 .unwrap_or(1);
738 set_step(conn, &run.id, "failed", Some(msg));
739 if attempts >= DEPLOY_MAX_ATTEMPTS {
740 close_deploy(
741 conn,
742 &run,
743 RunState::Failed,
744 "failed",
745 Some(("apply_failed", msg)),
746 )?;
747 } else {
748 walk_to_running(conn, &run)?;
749 transition_run(
750 conn,
751 &run.id,
752 RunState::RetryWait,
753 None,
754 Some(("apply_failed", msg)),
755 )?;
756 }
757 }
758 Ok(())
759}
760
761pub fn deploy_observed(
764 conn: &Connection,
765 node_id: &str,
766 target: &str,
767 current_sha256: Option<&str>,
768) -> Result<(), String> {
769 let Some(current) = current_sha256 else {
770 return Ok(());
771 };
772 init_schema(conn)?;
773 let key = deploy_key(node_id, target, current);
774 for (run, k) in open_deploys(conn, node_id, target)? {
775 if k == key {
776 set_step(conn, &run.id, "done", Some("found on the node"));
777 close_deploy(conn, &run, RunState::Succeeded, "found on the node", None)?;
778 }
779 }
780 Ok(())
781}
782
783#[cfg(test)]
784mod tests {
785 use super::*;
786
787 #[test]
788 fn every_drawn_edge_is_allowed_and_every_other_edge_is_refused() {
789 let states = [
790 RunState::Queued,
791 RunState::WaitingForUnlock,
792 RunState::Planning,
793 RunState::AwaitingApproval,
794 RunState::Running,
795 RunState::StepDispatching,
796 RunState::StepDone,
797 RunState::RetryWait,
798 RunState::Paused,
799 RunState::Uncertain,
800 RunState::NeedsAttention,
801 RunState::Succeeded,
802 RunState::Failed,
803 RunState::SkippedStale,
804 RunState::Cancelled,
805 ];
806 for from in states {
807 for to in states {
808 assert_eq!(
809 can_transition(from, to),
810 EDGES.contains(&(from, to)),
811 "{} -> {}",
812 from.as_str(),
813 to.as_str()
814 );
815 }
816 }
817 }
818
819 #[test]
820 fn a_run_remembers_which_plugin_build_it_used() {
821 let conn = Connection::open_in_memory().unwrap();
822 init_schema(&conn).unwrap();
823 create_run_with_kind(&conn, "r1", None, "backup.package", 0, None).unwrap();
824 assert!(plugin_provenance(&conn, "r1").unwrap().is_empty());
825 record_plugin_provenance(&conn, "r1", "ntfy", "aa11").unwrap();
826 record_plugin_provenance(&conn, "r1", "other", "bb22").unwrap();
827 record_plugin_provenance(&conn, "r1", "ntfy", "cc33").unwrap();
829 let got = plugin_provenance(&conn, "r1").unwrap();
830 assert_eq!(got["ntfy"], "cc33");
831 assert_eq!(got["other"], "bb22");
832 assert!(record_plugin_provenance(&conn, "missing", "ntfy", "x").is_err());
833 }
834
835 #[test]
836 fn a_run_with_an_empty_or_unreadable_plugin_record_is_handled() {
837 let conn = Connection::open_in_memory().unwrap();
838 init_schema(&conn).unwrap();
839 create_run_with_kind(&conn, "r1", None, "backup.package", 0, None).unwrap();
840 conn.execute(
842 "UPDATE ops_runs SET plugin_provenance = '' WHERE id = 'r1'",
843 [],
844 )
845 .unwrap();
846 assert!(plugin_provenance(&conn, "r1").unwrap().is_empty());
847 record_plugin_provenance(&conn, "r1", "ntfy", "aa11").unwrap();
848 assert_eq!(plugin_provenance(&conn, "r1").unwrap()["ntfy"], "aa11");
849 conn.execute(
851 "UPDATE ops_runs SET plugin_provenance = 'not json' WHERE id = 'r1'",
852 [],
853 )
854 .unwrap();
855 assert!(plugin_provenance(&conn, "r1").is_err());
856 assert!(record_plugin_provenance(&conn, "r1", "ntfy", "bb22").is_err());
857 assert!(plugin_provenance(&conn, "missing").is_err());
858 }
859
860 fn deploy_conn() -> Connection {
861 let conn = Connection::open_in_memory().unwrap();
862 init_schema(&conn).unwrap();
863 conn
864 }
865
866 fn deploy_state(conn: &Connection, id: &str) -> RunState {
867 get_run(conn, id).unwrap().unwrap().state
868 }
869
870 #[test]
871 fn a_deployment_run_follows_one_push_to_its_result() {
872 let c = deploy_conn();
873 let id = deploy_dispatch(&c, "n1", "edge", "env", "aa", false).unwrap();
874 assert_eq!(deploy_state(&c, &id), RunState::Running);
875 assert_eq!(
877 deploy_dispatch(&c, "n1", "edge", "env", "aa", false).unwrap(),
878 id
879 );
880 let attempt: i64 = c
881 .query_row(
882 "SELECT attempt FROM ops_steps WHERE run_id = ?1",
883 [&id],
884 |r| r.get(0),
885 )
886 .unwrap();
887 assert_eq!(attempt, 2);
888 deploy_result(&c, "n1", "env", "aa", true, None).unwrap();
889 assert_eq!(deploy_state(&c, &id), RunState::Succeeded);
890 let step: String = c
891 .query_row(
892 "SELECT state FROM ops_steps WHERE run_id = ?1",
893 [&id],
894 |r| r.get(0),
895 )
896 .unwrap();
897 assert_eq!(step, "done");
898 deploy_result(&c, "n1", "env", "zz", true, None).unwrap();
900 }
901
902 #[test]
903 fn a_held_push_waits_then_is_the_same_run_when_it_is_sent() {
904 let c = deploy_conn();
905 let id = deploy_dispatch(&c, "n1", "edge", "env", "aa", true).unwrap();
906 assert_eq!(deploy_state(&c, &id), RunState::AwaitingApproval);
907 assert_eq!(
908 deploy_dispatch(&c, "n1", "edge", "env", "aa", true).unwrap(),
909 id
910 );
911 assert_eq!(
912 deploy_dispatch(&c, "n1", "edge", "env", "aa", false).unwrap(),
913 id
914 );
915 assert_eq!(deploy_state(&c, &id), RunState::Running);
916 }
917
918 #[test]
919 fn new_bytes_for_a_target_cancel_the_older_run() {
920 let c = deploy_conn();
921 let old = deploy_dispatch(&c, "n1", "edge", "env", "aa", true).unwrap();
922 let sent = deploy_dispatch(&c, "n1", "edge", "env", "bb", false).unwrap();
923 assert_ne!(old, sent);
924 assert_eq!(deploy_state(&c, &old), RunState::Cancelled);
925 assert_eq!(deploy_state(&c, &sent), RunState::Running);
926 let other = deploy_dispatch(&c, "n1", "edge", "web", "aa", false).unwrap();
928 assert_eq!(deploy_state(&c, &sent), RunState::Running);
929 assert_eq!(deploy_state(&c, &other), RunState::Running);
930 }
931
932 #[test]
933 fn a_lock_mid_push_is_settled_by_what_the_node_holds_next() {
934 let c = deploy_conn();
937 let id = deploy_dispatch(&c, "n1", "edge", "env", "aa", false).unwrap();
938 mark_interrupted(&c).unwrap();
939 assert_eq!(deploy_state(&c, &id), RunState::Paused);
940 let step: String = c
941 .query_row(
942 "SELECT state FROM ops_steps WHERE run_id = ?1",
943 [&id],
944 |r| r.get(0),
945 )
946 .unwrap();
947 assert_eq!(step, "uncertain");
948 deploy_observed(&c, "n1", "env", Some("old")).unwrap();
950 assert_eq!(deploy_state(&c, &id), RunState::Paused);
951 assert_eq!(
952 deploy_dispatch(&c, "n1", "edge", "env", "aa", false).unwrap(),
953 id
954 );
955 assert_eq!(deploy_state(&c, &id), RunState::Running);
956 mark_interrupted(&c).unwrap();
958 deploy_observed(&c, "n1", "env", Some("aa")).unwrap();
959 assert_eq!(deploy_state(&c, &id), RunState::Succeeded);
960 deploy_observed(&c, "n1", "env", None).unwrap();
961 }
962
963 #[test]
964 fn a_push_that_keeps_failing_retries_and_then_fails() {
965 let c = deploy_conn();
966 let mut id = String::new();
967 for n in 1..=DEPLOY_MAX_ATTEMPTS {
968 id = deploy_dispatch(&c, "n1", "edge", "env", "aa", false).unwrap();
969 deploy_result(&c, "n1", "env", "aa", false, Some("disk full")).unwrap();
970 let want = if n < DEPLOY_MAX_ATTEMPTS {
971 RunState::RetryWait
972 } else {
973 RunState::Failed
974 };
975 assert_eq!(deploy_state(&c, &id), want, "after send {n}");
976 }
977 let run = get_run(&c, &id).unwrap().unwrap();
978 assert_eq!(run.error_code.as_deref(), Some("apply_failed"));
979 assert_eq!(run.error_msg.as_deref(), Some("disk full"));
980 }
981
982 #[test]
983 fn an_old_open_deployment_is_cancelled_the_next_time_one_is_sent() {
984 let c = deploy_conn();
985 let old = deploy_dispatch(&c, "n1", "edge", "env", "aa", true).unwrap();
986 c.execute(
987 "UPDATE ops_runs SET created_at = '2020-01-01T00:00:00.000Z' WHERE id = ?1",
988 [&old],
989 )
990 .unwrap();
991 deploy_dispatch(&c, "n2", "other", "env", "bb", false).unwrap();
992 assert_eq!(deploy_state(&c, &old), RunState::Cancelled);
993 }
994}