forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

scheduler.rs582 lines, 20.8 KiBHistoryRawDownload
1//! Scheduled backups and fsck, the run slot they share with manual and CLI triggers, and the job
2//! bodies. Every run is recorded in `backup_runs`. Only one run is active at a time: a second
3//! trigger gets "already running" while the first is in progress.
4
5use std::path::PathBuf;
6use std::sync::{Arc, Mutex, PoisonError};
7use std::time::{Duration, SystemTime};
8
9use crate::live::Topic;
10use forge_core::store::backup_runs::{BackupRun, RunKind, RunTrigger};
11use forge_core::{Error, Result};
12use time::OffsetDateTime;
13use time::format_description::well_known::Rfc3339;
14
15use super::{
16 BackupOptions, BackupSource, BackupSummary, FsckSummary, create_backup, healthcheck, retention,
17 run_fsck, verify_backup,
18};
19use crate::state::AppState;
20
21/// After a failed run, the next try waits at least this long.
22const RETRY_AFTER_SECS: i64 = 60 * 60;
23/// Pause after each pass. A due job that did not clear its due time (it could not take the run
24/// slot while a manual run held it, say) waits this long instead of spinning the loop.
25const RECHECK: Duration = Duration::from_secs(30);
26
27/// The one run slot of this process.
28#[derive(Default)]
29pub struct Jobs {
30 running: Mutex<Option<RunKind>>,
31}
32
33/// Holds the run slot. Dropping it frees the slot.
34pub struct JobGuard {
35 jobs: Arc<Jobs>,
36 kind: RunKind,
37}
38
39impl Jobs {
40 /// Takes the run slot for `kind`. Fails with "already running" while another run holds it.
41 pub fn claim(self: &Arc<Self>, kind: RunKind) -> Result<JobGuard> {
42 let mut slot = self.running.lock().unwrap_or_else(PoisonError::into_inner);
43 if let Some(current) = *slot {
44 return Err(Error::Conflict(format!(
45 "already running: a {} run is in progress",
46 current.as_str()
47 )));
48 }
49 *slot = Some(kind);
50 runs_changed();
51 Ok(JobGuard {
52 jobs: Arc::clone(self),
53 kind,
54 })
55 }
56
57 /// The kind of run in progress, if any.
58 pub fn running(&self) -> Option<RunKind> {
59 *self.running.lock().unwrap_or_else(PoisonError::into_inner)
60 }
61}
62
63impl Drop for JobGuard {
64 fn drop(&mut self) {
65 let mut slot = self
66 .jobs
67 .running
68 .lock()
69 .unwrap_or_else(PoisonError::into_inner);
70 if *slot == Some(self.kind) {
71 *slot = None;
72 }
73 drop(slot);
74 runs_changed();
75 }
76}
77
78/// A run started or finished, or its slot was taken or freed: the backup and health pages of the
79/// admin area follow it.
80fn runs_changed() {
81 let hub = crate::live::admin();
82 hub.bump(&Topic::AdminBackups);
83 hub.bump(&Topic::AdminHealth);
84}
85
86fn started_unix(run: &BackupRun) -> Option<i64> {
87 OffsetDateTime::parse(&run.started_at, &Rfc3339)
88 .ok()
89 .map(|t| t.unix_timestamp())
90}
91
92/// Seconds until a job of this kind is due. Zero means run now.
93///
94/// The base is the start of the last successful run plus `every_secs`. With no success on record
95/// the job is due at once. When the latest attempt failed, the next try also waits
96/// `retry_after_secs` from that attempt, so a broken setup does not retry every tick.
97pub fn secs_until_due(
98 now: OffsetDateTime,
99 last_ok: Option<&BackupRun>,
100 last_attempt: Option<&BackupRun>,
101 every_secs: i64,
102 retry_after_secs: i64,
103) -> i64 {
104 let mut due = match last_ok.and_then(started_unix) {
105 Some(t) => t.saturating_add(every_secs),
106 None => now.unix_timestamp(),
107 };
108 if let Some(attempt) = last_attempt.filter(|run| run.ok != Some(true))
109 && let Some(t) = started_unix(attempt)
110 {
111 due = due.max(t.saturating_add(retry_after_secs));
112 }
113 (due - now.unix_timestamp()).max(0)
114}
115
116/// Starts the scheduler loop. The caller checks that `[backup] dir` is set.
117///
118/// Each pass sleeps until the earliest of the backup and fsck is due, runs what is due, and then
119/// works out the next instant from the run history again.
120pub fn spawn(state: AppState) -> tokio::task::JoinHandle<()> {
121 tokio::spawn(async move {
122 loop {
123 match next_due_in(&state).await {
124 Ok(wait) => {
125 let until = tokio::time::Instant::now()
126 + Duration::from_secs(u64::try_from(wait).unwrap_or(0));
127 tokio::time::sleep_until(until).await;
128 }
129 Err(e) => {
130 tracing::error!(error = %e, "backup scheduler could not read its history");
131 tokio::time::sleep(RECHECK).await;
132 continue;
133 }
134 }
135 run_due(&state).await;
136 tokio::time::sleep(RECHECK).await;
137 }
138 })
139}
140
141/// How often a job of this kind is due, in seconds.
142fn interval_secs(state: &AppState, kind: RunKind) -> i64 {
143 let cfg = &state.config.backup;
144 match kind {
145 RunKind::Backup => {
146 i64::try_from(cfg.interval_hours.saturating_mul(3600)).unwrap_or(i64::MAX)
147 }
148 RunKind::Fsck => {
149 i64::try_from(cfg.fsck_interval_days.saturating_mul(86_400)).unwrap_or(i64::MAX)
150 }
151 }
152}
153
154/// Seconds until a job of this kind is due, from its run history. Zero means run now.
155async fn secs_until_run(state: &AppState, kind: RunKind) -> Result<i64> {
156 let (ok, attempt) = due_inputs(state, kind).await?;
157 Ok(secs_until_due(
158 OffsetDateTime::now_utc(),
159 ok.as_ref(),
160 attempt.as_ref(),
161 interval_secs(state, kind),
162 RETRY_AFTER_SECS,
163 ))
164}
165
166/// Seconds until the earlier of the backup and the fsck is due. Zero means one is due now.
167async fn next_due_in(state: &AppState) -> Result<i64> {
168 let backup = secs_until_run(state, RunKind::Backup).await?;
169 let fsck = secs_until_run(state, RunKind::Fsck).await?;
170 Ok(backup.min(fsck))
171}
172
173/// Runs each job that is due now. A job that cannot take the run slot, because a manual run holds
174/// it, is left for the next pass.
175async fn run_due(state: &AppState) {
176 for kind in [RunKind::Backup, RunKind::Fsck] {
177 let due = match secs_until_run(state, kind).await {
178 Ok(wait) => wait == 0,
179 Err(e) => {
180 tracing::error!(error = %e, kind = kind.as_str(), "scheduler could not read its history");
181 false
182 }
183 };
184 if !due {
185 continue;
186 }
187 let Ok(guard) = state.jobs.claim(kind) else {
188 continue;
189 };
190 let outcome = match kind {
191 RunKind::Backup => scheduled_backup(state).await.map(|_| ()),
192 RunKind::Fsck => fsck_job(state, RunTrigger::Schedule, false)
193 .await
194 .map(|_| ()),
195 };
196 if let Err(e) = outcome {
197 tracing::error!(error = %e, kind = kind.as_str(), "scheduled run failed");
198 }
199 drop(guard);
200 }
201}
202
203async fn due_inputs(
204 state: &AppState,
205 kind: RunKind,
206) -> Result<(Option<BackupRun>, Option<BackupRun>)> {
207 let ok = state.store.last_ok(kind).await?;
208 let attempt = state.store.last_run(kind).await?;
209 Ok((ok, attempt))
210}
211
212/// The configured backup directory as an absolute path.
213pub fn configured_dir(state: &AppState) -> Result<PathBuf> {
214 std::path::absolute(&state.config.backup.dir).map_err(Error::Io)
215}
216
217async fn scheduled_backup(state: &AppState) -> Result<BackupSummary> {
218 let opts = BackupOptions {
219 out: configured_dir(state)?,
220 include_key: false,
221 scope: super::Scope::All,
222 };
223 backup_job(state, RunTrigger::Schedule, opts, true).await
224}
225
226/// Runs one backup set and records it. The caller holds the run slot.
227///
228/// The set is verified before the run counts as ok. `prune` applies retention to `opts.out` after
229/// a good run. Healthcheck pings are sent for scheduled runs only.
230pub async fn backup_job(
231 state: &AppState,
232 trigger: RunTrigger,
233 opts: BackupOptions,
234 prune: bool,
235) -> Result<BackupSummary> {
236 let run_id = state.store.start_run(RunKind::Backup, trigger).await?;
237 runs_changed();
238 let healthcheck_url = Some(state.config.backup.healthcheck_url.as_str())
239 .filter(|url| trigger == RunTrigger::Schedule && !url.is_empty());
240 if let Some(url) = healthcheck_url {
241 healthcheck::start(url).await;
242 }
243
244 let outcome = backup_set(state, &opts).await;
245 match &outcome {
246 Ok(_) => crate::alerts::backup_finished(state, Ok(())).await,
247 Err(e) => crate::alerts::backup_finished(state, Err(&e.to_string())).await,
248 }
249 match &outcome {
250 Ok(summary) => {
251 let path = summary.path.to_string_lossy().into_owned();
252 record_finish(state, &run_id, true, Some(&path), Some(summary.bytes), None).await;
253 }
254 Err(e) => {
255 record_finish(state, &run_id, false, None, None, Some(&e.to_string())).await;
256 }
257 }
258 if outcome.is_ok() && prune {
259 match retention::prune(&opts.out, state.config.backup.keep, SystemTime::now()) {
260 Ok(report) => tracing::info!(
261 sets = report.sets_removed.len(),
262 partials = report.partials_removed.len(),
263 "backup retention applied"
264 ),
265 Err(e) => tracing::warn!(error = %e, "backup retention failed"),
266 }
267 }
268 if let Some(url) = healthcheck_url {
269 match &outcome {
270 Ok(_) => healthcheck::success(url).await,
271 Err(e) => healthcheck::failure(url, &e.to_string()).await,
272 }
273 }
274 outcome
275}
276
277async fn backup_set(state: &AppState, opts: &BackupOptions) -> Result<BackupSummary> {
278 let source = BackupSource {
279 store: state.store.clone(),
280 git: (*state.git).clone(),
281 base_url: state.config.base_url.clone(),
282 };
283 let summary = create_backup(&source, opts).await?;
284 let report = verify_backup(&summary.path, &source.git).await?;
285 if !report.is_ok() {
286 return Err(Error::Invalid(format!(
287 "the new backup set failed verification: {}",
288 report.problems.join("; ")
289 )));
290 }
291 Ok(summary)
292}
293
294/// Runs fsck over every repo and the database, and records it. The caller holds the run slot.
295pub async fn fsck_job(state: &AppState, trigger: RunTrigger, full: bool) -> Result<FsckSummary> {
296 let run_id = state.store.start_run(RunKind::Fsck, trigger).await?;
297 runs_changed();
298 let outcome = run_fsck(&state.store, &state.git, full).await;
299 match &outcome {
300 Ok(summary) if summary.is_ok() => crate::alerts::fsck_finished(state, Ok(())).await,
301 Ok(summary) => crate::alerts::fsck_finished(state, Err(&summary.problems.join("\n"))).await,
302 Err(e) => crate::alerts::fsck_finished(state, Err(&e.to_string())).await,
303 }
304 match &outcome {
305 Ok(summary) if summary.is_ok() => {
306 record_finish(state, &run_id, true, None, None, None).await;
307 }
308 Ok(summary) => {
309 let text = summary.problems.join("\n");
310 record_finish(state, &run_id, false, None, None, Some(&text)).await;
311 }
312 Err(e) => {
313 record_finish(state, &run_id, false, None, None, Some(&e.to_string())).await;
314 }
315 }
316 outcome
317}
318
319/// Writes the outcome of a run. A failure to record is logged, because the run itself has already
320/// happened.
321async fn record_finish(
322 state: &AppState,
323 run_id: &str,
324 ok: bool,
325 path: Option<&str>,
326 bytes: Option<u64>,
327 error: Option<&str>,
328) {
329 if let Err(e) = state.store.finish_run(run_id, ok, path, bytes, error).await {
330 tracing::error!(error = %e, run_id, "could not record the outcome of a backup run");
331 }
332 runs_changed();
333}
334
335/// Starts a manual run in the background and returns at once. The caller claimed the run slot
336/// (so it could refuse with "already running" and record the audit entry first). Fails with a
337/// config error, freeing the slot, when no backup directory is set.
338pub fn start_manual(state: &AppState, guard: JobGuard) -> Result<()> {
339 if !state.config.backup.enabled() {
340 return Err(Error::Config(
341 "backups are not configured: set [backup] dir in the config file".into(),
342 ));
343 }
344 let kind = guard.kind;
345 let state = state.clone();
346 tokio::spawn(async move {
347 let _guard = guard;
348 let outcome: Result<()> = match kind {
349 RunKind::Backup => match configured_dir(&state) {
350 Ok(out) => backup_job(
351 &state,
352 RunTrigger::Manual,
353 BackupOptions {
354 out,
355 include_key: false,
356 scope: super::Scope::All,
357 },
358 true,
359 )
360 .await
361 .map(|_| ()),
362 Err(e) => Err(e),
363 },
364 RunKind::Fsck => fsck_job(&state, RunTrigger::Manual, false)
365 .await
366 .map(|_| ()),
367 };
368 if let Err(e) = outcome {
369 tracing::error!(error = %e, kind = kind.as_str(), "manual run failed");
370 }
371 });
372 Ok(())
373}
374
375/// Runs a backup now and waits for it, holding the run slot in `guard`. For the CLI through the
376/// internal socket.
377pub async fn run_backup_now(
378 state: &AppState,
379 guard: JobGuard,
380 trigger: RunTrigger,
381 opts: BackupOptions,
382 prune: bool,
383) -> Result<BackupSummary> {
384 let _guard = guard;
385 backup_job(state, trigger, opts, prune).await
386}
387
388/// Runs fsck now and waits for it, holding the run slot in `guard`. For the CLI through the
389/// internal socket.
390pub async fn run_fsck_now(
391 state: &AppState,
392 guard: JobGuard,
393 trigger: RunTrigger,
394 full: bool,
395) -> Result<FsckSummary> {
396 let _guard = guard;
397 fsck_job(state, trigger, full).await
398}
399
400#[cfg(test)]
401mod tests {
402 use super::*;
403 use forge_core::model::Visibility;
404 use forge_git::repo::{init_bare, repo_path};
405 use tokio::io::{AsyncReadExt, AsyncWriteExt};
406 use tokio::net::TcpListener;
407
408 fn at(stamp: &str) -> OffsetDateTime {
409 OffsetDateTime::parse(stamp, &Rfc3339).expect("stamp")
410 }
411
412 fn run(kind: RunKind, started: &str, ok: Option<bool>) -> BackupRun {
413 BackupRun {
414 id: format!("id-{started}"),
415 kind,
416 trigger: RunTrigger::Schedule,
417 started_at: started.to_string(),
418 finished_at: None,
419 ok,
420 path: None,
421 bytes: None,
422 error: None,
423 }
424 }
425
426 const DAY: i64 = 86_400;
427 const HOUR: i64 = 3600;
428
429 #[test]
430 fn never_run_is_due_now() {
431 let now = at("2026-10-15T12:00:00Z");
432 assert_eq!(secs_until_due(now, None, None, DAY, HOUR), 0);
433 }
434
435 #[test]
436 fn next_run_follows_the_last_success() {
437 let now = at("2026-10-15T12:00:00Z");
438 let last = run(RunKind::Backup, "2026-10-15T06:00:00Z", Some(true));
439 // Last success six hours ago with a 24 hour interval: due in eighteen hours.
440 assert_eq!(
441 secs_until_due(now, Some(&last), Some(&last), DAY, HOUR),
442 18 * HOUR
443 );
444 let old = run(RunKind::Backup, "2026-10-13T00:00:00Z", Some(true));
445 assert_eq!(secs_until_due(now, Some(&old), Some(&old), DAY, HOUR), 0);
446 }
447
448 #[test]
449 fn a_failed_attempt_waits_before_retrying() {
450 let now = at("2026-10-15T12:00:00Z");
451 let old_ok = run(RunKind::Backup, "2026-10-13T00:00:00Z", Some(true));
452 // The latest attempt failed 10 minutes ago: the retry waits the rest of the hour.
453 let failed = run(RunKind::Backup, "2026-10-15T11:50:00Z", Some(false));
454 assert_eq!(
455 secs_until_due(now, Some(&old_ok), Some(&failed), DAY, HOUR),
456 50 * 60
457 );
458 // A run that never finished counts as a failed attempt.
459 let unfinished = run(RunKind::Backup, "2026-10-15T11:50:00Z", None);
460 assert_eq!(
461 secs_until_due(now, None, Some(&unfinished), DAY, HOUR),
462 50 * 60
463 );
464 // Failed long ago: due now.
465 let stale = run(RunKind::Backup, "2026-10-15T09:00:00Z", Some(false));
466 assert_eq!(secs_until_due(now, None, Some(&stale), DAY, HOUR), 0);
467 }
468
469 #[test]
470 fn the_slot_is_exclusive_and_freed_on_drop() {
471 let jobs = Arc::new(Jobs::default());
472 let guard = jobs.claim(RunKind::Backup).expect("first claim");
473 assert_eq!(jobs.running(), Some(RunKind::Backup));
474 match jobs.claim(RunKind::Fsck) {
475 Err(Error::Conflict(message)) => assert!(message.contains("already running")),
476 other => panic!("expected a conflict, got {:?}", other.map(|_| ())),
477 }
478 drop(guard);
479 assert_eq!(jobs.running(), None);
480 assert!(jobs.claim(RunKind::Fsck).is_ok());
481 }
482
483 /// A tiny server that answers `count` requests and records the request lines.
484 async fn ping_server(count: usize) -> (String, Arc<Mutex<Vec<String>>>) {
485 let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
486 let addr = listener.local_addr().expect("addr");
487 let seen = Arc::new(Mutex::new(Vec::new()));
488 let log = Arc::clone(&seen);
489 tokio::spawn(async move {
490 for _ in 0..count {
491 let Ok((mut sock, _)) = listener.accept().await else {
492 return;
493 };
494 let mut buf = vec![0u8; 8192];
495 let n = sock.read(&mut buf).await.unwrap_or(0);
496 let text = String::from_utf8_lossy(&buf[..n]).into_owned();
497 log.lock()
498 .unwrap_or_else(PoisonError::into_inner)
499 .push(text.lines().next().unwrap_or_default().to_owned());
500 let _ = sock
501 .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
502 .await;
503 }
504 });
505 (format!("http://{addr}/hc/token-123"), seen)
506 }
507
508 #[tokio::test]
509 async fn manual_start_without_a_dir_is_a_config_error_and_frees_the_slot() {
510 let dir = tempfile::tempdir().expect("tempdir");
511 let state = crate::test_support::test_state(dir.path()).await;
512 let guard = state.jobs.claim(RunKind::Backup).expect("claim");
513 assert!(matches!(start_manual(&state, guard), Err(Error::Config(_))));
514 assert_eq!(state.jobs.running(), None);
515 }
516
517 #[tokio::test]
518 async fn a_fresh_install_wakes_at_once() {
519 let dir = tempfile::tempdir().expect("tempdir");
520 let state = crate::test_support::test_state(dir.path()).await;
521 assert_eq!(next_due_in(&state).await.expect("next due"), 0);
522 }
523
524 #[tokio::test]
525 async fn scheduled_backup_is_recorded_verified_and_pinged() {
526 let dir = tempfile::tempdir().expect("tempdir");
527 let data_dir = dir.path().join("data");
528 std::fs::create_dir_all(&data_dir).expect("data dir");
529 let out = dir.path().join("out");
530 let (url, pings) = ping_server(2).await;
531
532 let mut state = crate::test_support::test_state(&data_dir).await;
533 let mut config = crate::test_support::test_config(&data_dir);
534 config.backup.dir = out.clone();
535 config.backup.keep = 1;
536 config.backup.healthcheck_url = url;
537 state.config = Arc::new(config);
538
539 let owner = state
540 .store
541 .create_user("tahinli", None, "hash", false)
542 .await
543 .expect("user");
544 let repo = state
545 .store
546 .create_repo(&owner.id, "demo", "", Visibility::Private, "main")
547 .await
548 .expect("repo");
549 let path = repo_path(&data_dir, &repo.id).expect("path");
550 init_bare(&state.git, &path, "main").await.expect("init");
551
552 let first = scheduled_backup(&state).await.expect("first backup");
553 assert!(first.path.starts_with(&out));
554 // A second run: retention keeps only the newest complete set. Set names have one-second
555 // stamps, so the runs must not share a second.
556 tokio::time::sleep(Duration::from_millis(1100)).await;
557 let second = scheduled_backup(&state).await.expect("second backup");
558 assert_ne!(first.path, second.path);
559 let sets: Vec<_> = std::fs::read_dir(&out)
560 .expect("read out")
561 .filter_map(|e| e.ok().map(|e| e.file_name()))
562 .collect();
563 assert_eq!(sets.len(), 1, "{sets:?}");
564
565 let runs = state.store.recent_runs(10).await.expect("runs");
566 assert_eq!(runs.len(), 2);
567 assert!(runs.iter().all(|r| r.ok == Some(true)));
568 assert!(runs.iter().all(|r| r.trigger == RunTrigger::Schedule));
569 assert!(runs[0].path.is_some());
570
571 // The first scheduled run pings start and success; the second run's pings are not needed.
572 for _ in 0..100 {
573 if pings.lock().unwrap_or_else(PoisonError::into_inner).len() >= 2 {
574 break;
575 }
576 tokio::time::sleep(Duration::from_millis(10)).await;
577 }
578 let seen = pings.lock().unwrap_or_else(PoisonError::into_inner).clone();
579 assert_eq!(seen[0], "GET /hc/token-123/start HTTP/1.1");
580 assert_eq!(seen[1], "GET /hc/token-123 HTTP/1.1");
581 }
582}