forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.7 MiB37e985dTahinli3 hours ago363 commits

worker.rs650 lines, 21.3 KiBHistoryRawDownload
1use std::path::{Path, PathBuf};
2use std::time::{Duration, Instant};
3
4use forge_core::Store;
5use forge_core::store::replication::DB_SUBJECT;
6use forge_core::store::snapshot::verify_snapshot;
7use forge_git::GitEnv;
8use forge_git::backup::refs_checksum;
9use forge_git::maintenance::{clear_standby_prune, standby_prune_due};
10
11use super::{
12 KEEP_SNAPSHOTS, Layout, SshTransport, StandbyTransport, Target, is_snapshot_name, push_repo,
13 remote_refs_checksum, sh_quote, snapshot_stamp,
14};
15use crate::backup::healthcheck;
16use crate::live::Topic;
17use crate::state::AppState;
18
19const BACKSTOP: Duration = Duration::from_secs(15 * 60);
20
21pub struct Ctx<T> {
22 pub store: Store,
23 pub git: GitEnv,
24 pub data_dir: PathBuf,
25 pub layout: Layout,
26 pub transport: T,
27}
28
29#[derive(Debug, Default, PartialEq, Eq)]
30pub struct ReconcileReport {
31 pub replicated: usize,
32 pub failures: Vec<String>,
33}
34
35pub fn spawn(state: AppState) {
36 tokio::spawn(run(state));
37}
38
39async fn run(state: AppState) {
40 let config = state.config.replication.clone();
41 let target = match Target::parse(&config.target, config.ssh_port) {
42 Ok(target) => target,
43 Err(e) => {
44 tracing::error!(error = %e, "replication: invalid target, worker not started");
45 return;
46 }
47 };
48 let layout = match Layout::new(&target.base) {
49 Ok(layout) => layout,
50 Err(e) => {
51 tracing::error!(error = %e, "replication: invalid remote base, worker not started");
52 return;
53 }
54 };
55 let transport = SshTransport::new(
56 target,
57 config.identity_file.clone(),
58 config.known_hosts_file.clone(),
59 );
60 let ctx = Ctx {
61 store: state.store.clone(),
62 git: (*state.git).clone(),
63 data_dir: state.git.data_dir.clone(),
64 layout,
65 transport,
66 };
67 tracing::info!(target = %config.target, "replication: worker started");
68
69 let db_every = Duration::from_secs(config.db_snapshot_minutes.max(1) * 60);
70 let reconcile_every = Duration::from_secs(config.reconcile_minutes.max(1) * 60);
71 let mut next_db = Instant::now();
72 let mut next_reconcile = Instant::now();
73 loop {
74 let backstop = Instant::now() + BACKSTOP;
75 let next = [
76 state.replication.next_due(),
77 Some(next_db),
78 Some(next_reconcile),
79 Some(backstop),
80 ]
81 .into_iter()
82 .flatten()
83 .min()
84 .unwrap_or(backstop);
85 tokio::select! {
86 () = tokio::time::sleep_until(tokio::time::Instant::from_std(next)) => {}
87 () = state.replication.wait() => {}
88 }
89 for repo_id in state.replication.take_due(Instant::now()) {
90 match ctx.store.repo_by_id(&repo_id).await {
91 Ok(Some(_)) => {
92 let _ = replicate_repo(&ctx, &repo_id).await;
93 }
94 Ok(None) => {}
95 Err(e) => tracing::error!(error = %e, "replication: could not look up repo"),
96 }
97 }
98 let now = Instant::now();
99 if now >= next_db {
100 next_db = now + db_every;
101 if let Err(e) = ship_db(&ctx).await {
102 tracing::error!(error = %e, "replication: database snapshot not shipped");
103 }
104 }
105 let requested = state.replication.take_reconcile_request();
106 if requested || now >= next_reconcile {
107 next_reconcile = Instant::now() + reconcile_every;
108 let report = reconcile_once(&ctx).await;
109 tracing::info!(
110 replicated = report.replicated,
111 failures = report.failures.len(),
112 "replication: reconcile finished"
113 );
114 ping(&config.healthcheck_url, &report).await;
115 }
116 }
117}
118
119async fn ping(url: &str, report: &ReconcileReport) {
120 if url.is_empty() {
121 return;
122 }
123 if report.failures.is_empty() {
124 healthcheck::success(url).await;
125 } else {
126 healthcheck::failure(url, &report.failures.join("; ")).await;
127 }
128}
129
130pub async fn record(
131 store: &Store,
132 subject: &str,
133 result: Result<Option<String>, String>,
134) -> Result<(), String> {
135 match result {
136 Ok(refs) => {
137 if let Err(e) = store.record_replication_ok(subject, refs.as_deref()).await {
138 tracing::error!(error = %e, subject, "replication: could not record success");
139 }
140 status_changed();
141 Ok(())
142 }
143 Err(e) => {
144 tracing::warn!(subject, error = %e, "replication: step failed");
145 if let Err(db) = store.record_replication_error(subject, &e).await {
146 tracing::error!(error = %db, subject, "replication: could not record failure");
147 }
148 status_changed();
149 Err(e)
150 }
151 }
152}
153
154fn status_changed() {
155 let hub = crate::live::admin();
156 hub.bump(&Topic::AdminReplication);
157 hub.bump(&Topic::AdminHealth);
158}
159
160pub async fn replicate_repo<T: StandbyTransport>(
161 ctx: &Ctx<T>,
162 repo_id: &str,
163) -> Result<(), String> {
164 let result = replicate_inner(ctx, repo_id).await;
165 record(&ctx.store, repo_id, result).await
166}
167
168async fn replicate_inner<T: StandbyTransport>(
169 ctx: &Ctx<T>,
170 repo_id: &str,
171) -> Result<Option<String>, String> {
172 let local = forge_git::repo::repo_path(&ctx.data_dir, repo_id).map_err(|e| e.to_string())?;
173 if !local.is_dir() {
174 return Err(format!(
175 "local repo directory is missing: {}",
176 local.display()
177 ));
178 }
179 let remote = ctx.layout.repo_dir(repo_id)?;
180 replicate_dir(ctx, &local, &remote).await
181}
182
183async fn replicate_dir<T: StandbyTransport>(
184 ctx: &Ctx<T>,
185 local: &Path,
186 remote: &str,
187) -> Result<Option<String>, String> {
188 ctx.transport
189 .run(&format!("git init --bare --quiet {}", sh_quote(remote)))
190 .await?;
191
192 push_repo(&ctx.transport, &ctx.git, local, remote).await?;
193 let mut local_sum = local_checksum(&ctx.git, local).await?;
194 let mut remote_sum = remote_refs_checksum(&ctx.transport, remote).await?;
195 if remote_sum != local_sum {
196 push_repo(&ctx.transport, &ctx.git, local, remote).await?;
197 local_sum = local_checksum(&ctx.git, local).await?;
198 remote_sum = remote_refs_checksum(&ctx.transport, remote).await?;
199 if remote_sum != local_sum {
200 return Err(format!(
201 "refs checksum mismatch after re-push: local {local_sum}, standby {remote_sum}"
202 ));
203 }
204 }
205 if standby_prune_due(local) {
206 ctx.transport
207 .run(&format!(
208 "git -C {} gc --quiet --prune=now",
209 sh_quote(remote)
210 ))
211 .await
212 .map_err(|e| format!("standby prune failed: {e}"))?;
213 clear_standby_prune(local);
214 }
215 Ok(Some(local_sum))
216}
217
218async fn local_checksum(git: &GitEnv, local: &Path) -> Result<String, String> {
219 refs_checksum(git, local).await.map_err(|e| e.to_string())
220}
221
222pub async fn ship_db<T: StandbyTransport>(ctx: &Ctx<T>) -> Result<(), String> {
223 let result = ship_db_inner(ctx).await;
224 record(&ctx.store, DB_SUBJECT, result.map(|()| None)).await
225}
226
227async fn ship_db_inner<T: StandbyTransport>(ctx: &Ctx<T>) -> Result<(), String> {
228 let run_dir = ctx.data_dir.join("run");
229 std::fs::create_dir_all(&run_dir)
230 .map_err(|e| format!("cannot create {}: {e}", run_dir.display()))?;
231 let snap = run_dir.join("replica-snap.db");
232 remove_snapshot_files(&snap)?;
233 ctx.store
234 .snapshot_to(&snap)
235 .await
236 .map_err(|e| e.to_string())?;
237 let shipped = ship_snapshot(ctx, &snap).await;
238 let _ = remove_snapshot_files(&snap);
239 shipped
240}
241
242async fn ship_snapshot<T: StandbyTransport>(ctx: &Ctx<T>, snap: &Path) -> Result<(), String> {
243 verify_snapshot(snap).await.map_err(|e| e.to_string())?;
244
245 let db_dir = ctx.layout.db_dir();
246 ctx.transport
247 .run(&format!("mkdir -p {}", sh_quote(&db_dir)))
248 .await?;
249
250 let stamp = snapshot_stamp();
251 let name = format!("forge-{stamp}.db");
252 ctx.transport
253 .upload(snap, &ctx.layout.snapshot_file(&stamp))
254 .await?;
255
256 let latest_tmp = format!("{db_dir}/.latest-tmp");
257 ctx.transport
258 .run(&format!(
259 "ln -sfn -- {} {} && mv -T -- {} {}",
260 sh_quote(&name),
261 sh_quote(&latest_tmp),
262 sh_quote(&latest_tmp),
263 sh_quote(&ctx.layout.latest_link())
264 ))
265 .await?;
266
267 prune_snapshots(ctx, &name).await
268}
269
270async fn prune_snapshots<T: StandbyTransport>(
271 ctx: &Ctx<T>,
272 keep_always: &str,
273) -> Result<(), String> {
274 let db_dir = ctx.layout.db_dir();
275 let listing = ctx
276 .transport
277 .run(&format!("ls -1 -- {}", sh_quote(&db_dir)))
278 .await?;
279 let text = String::from_utf8_lossy(&listing);
280 let mut names: Vec<&str> = text.lines().filter(|name| is_snapshot_name(name)).collect();
281 names.sort_unstable();
282 let excess = names.len().saturating_sub(KEEP_SNAPSHOTS);
283 let victims: Vec<String> = names
284 .iter()
285 .take(excess)
286 .filter(|name| **name != keep_always)
287 .map(|name| sh_quote(&format!("{db_dir}/{name}")))
288 .collect();
289 if victims.is_empty() {
290 return Ok(());
291 }
292 ctx.transport
293 .run(&format!("rm -f -- {}", victims.join(" ")))
294 .await
295 .map(|_| ())
296}
297
298fn remove_snapshot_files(snap: &Path) -> Result<(), String> {
299 for suffix in ["", "-wal", "-shm"] {
300 let mut path = snap.as_os_str().to_owned();
301 path.push(suffix);
302 match std::fs::remove_file(&path) {
303 Ok(()) => {}
304 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
305 Err(e) => return Err(format!("cannot remove {}: {e}", Path::new(&path).display())),
306 }
307 }
308 Ok(())
309}
310
311pub async fn reconcile_once<T: StandbyTransport>(ctx: &Ctx<T>) -> ReconcileReport {
312 let mut report = ReconcileReport::default();
313 let ids = match ctx.store.repo_ids().await {
314 Ok(ids) => ids,
315 Err(e) => {
316 report.failures.push(format!("cannot list repos: {e}"));
317 return report;
318 }
319 };
320 for id in &ids {
321 match replicate_repo(ctx, id).await {
322 Ok(()) => report.replicated += 1,
323 Err(e) => report.failures.push(format!("{id}: {e}")),
324 }
325 }
326
327 let statuses = match ctx.store.list_replication_status().await {
328 Ok(statuses) => statuses,
329 Err(e) => {
330 report
331 .failures
332 .push(format!("cannot list replication status: {e}"));
333 return report;
334 }
335 };
336 for status in statuses {
337 if status.subject == DB_SUBJECT || ids.iter().any(|id| *id == status.subject) {
338 continue;
339 }
340 match remove_remote_repo(ctx, &status.subject).await {
341 Ok(()) => {
342 if let Err(e) = ctx.store.delete_replication_status(&status.subject).await {
343 report.failures.push(format!("{}: {e}", status.subject));
344 }
345 status_changed();
346 }
347 Err(e) => report
348 .failures
349 .push(format!("{}: remove failed: {e}", status.subject)),
350 }
351 }
352 report
353}
354
355async fn remove_remote_repo<T: StandbyTransport>(
356 ctx: &Ctx<T>,
357 subject: &str,
358) -> Result<(), String> {
359 let remote = ctx.layout.repo_dir(subject)?;
360 ctx.transport
361 .run(&format!("rm -rf -- {}", sh_quote(&remote)))
362 .await
363 .map(|_| ())
364}
365
366#[cfg(test)]
367mod tests {
368 use std::path::Path;
369
370 use forge_core::Store;
371 use forge_core::Visibility;
372 use forge_core::store::replication::DB_SUBJECT;
373 use forge_core::store::snapshot::verify_snapshot;
374 use forge_git::GitEnv;
375 use forge_git::backup::refs_checksum;
376 use forge_git::maintenance::{prune_unreachable, standby_prune_due};
377
378 use super::super::{Layout, LocalTransport, remote_refs_checksum};
379 use super::{Ctx, ReconcileReport, reconcile_once, replicate_repo, ship_db};
380
381 fn plumbing(git_dir: &Path, args: &[&str]) -> String {
382 let out = std::process::Command::new("git")
383 .arg(format!("--git-dir={}", git_dir.display()))
384 .args(args)
385 .env("GIT_AUTHOR_NAME", "t")
386 .env("GIT_AUTHOR_EMAIL", "t@example.com")
387 .env("GIT_COMMITTER_NAME", "t")
388 .env("GIT_COMMITTER_EMAIL", "t@example.com")
389 .output()
390 .expect("git runs");
391 assert!(out.status.success(), "git {args:?}: {out:?}");
392 String::from_utf8_lossy(&out.stdout).trim().to_string()
393 }
394
395 fn commit_to(git_dir: &Path, refname: &str, message: &str) {
396 let tree = plumbing(git_dir, &["hash-object", "-t", "tree", "-w", "--stdin"]);
397 let commit = plumbing(git_dir, &["commit-tree", &tree, "-m", message]);
398 plumbing(git_dir, &["update-ref", refname, &commit]);
399 }
400
401 struct Fixture {
402 _dir: tempfile::TempDir,
403 ctx: Ctx<LocalTransport>,
404 standby: std::path::PathBuf,
405 repo_id: String,
406 local_repo: std::path::PathBuf,
407 }
408
409 async fn fixture() -> Fixture {
410 let dir = tempfile::tempdir().expect("tempdir");
411 let data_dir = dir.path().join("data");
412 std::fs::create_dir_all(&data_dir).expect("data dir");
413 let store = Store::open(&dir.path().join("forge.db"))
414 .await
415 .expect("store");
416 let tahinli = store
417 .create_user("Tahinli", None, "hash", false)
418 .await
419 .expect("user");
420 let repo = store
421 .create_repo(&tahinli.id, "demo", "", Visibility::Private, "main")
422 .await
423 .expect("repo");
424 let git = GitEnv {
425 git_bin: "git".into(),
426 data_dir: data_dir.clone(),
427 };
428 let local_repo = forge_git::repo::repo_path(&data_dir, &repo.id).expect("path");
429 forge_git::repo::init_bare(&git, &local_repo, "main")
430 .await
431 .expect("init bare");
432 commit_to(&local_repo, "refs/heads/main", "first");
433
434 let standby = dir.path().join("standby");
435 std::fs::create_dir_all(&standby).expect("standby");
436 let standby_str = standby.to_str().expect("utf8 path");
437 let ctx = Ctx {
438 store,
439 git,
440 data_dir,
441 layout: Layout::new(standby_str).expect("layout"),
442 transport: LocalTransport,
443 };
444 Fixture {
445 _dir: dir,
446 ctx,
447 standby,
448 repo_id: repo.id,
449 local_repo,
450 }
451 }
452
453 #[tokio::test]
454 async fn push_records_matching_checksum_and_follows_new_refs() {
455 let f = fixture().await;
456 replicate_repo(&f.ctx, &f.repo_id)
457 .await
458 .expect("first push");
459
460 let remote = f.ctx.layout.repo_dir(&f.repo_id).expect("remote dir");
461 assert!(
462 Path::new(&remote).join("HEAD").is_file(),
463 "bare repo created"
464 );
465 let local_sum = refs_checksum(&f.ctx.git, &f.local_repo).await.expect("sum");
466 let remote_sum = remote_refs_checksum(&f.ctx.transport, &remote)
467 .await
468 .expect("remote sum");
469 assert_eq!(local_sum, remote_sum);
470 let status = f
471 .ctx
472 .store
473 .replication_status(&f.repo_id)
474 .await
475 .expect("status")
476 .expect("row");
477 assert!(status.last_ok_at.is_some());
478 assert_eq!(status.refs_sha256.as_deref(), Some(local_sum.as_str()));
479 assert_eq!(status.last_error, None);
480
481 commit_to(&f.local_repo, "refs/heads/main", "second");
482 commit_to(&f.local_repo, "refs/tags/v1", "tagged");
483 replicate_repo(&f.ctx, &f.repo_id)
484 .await
485 .expect("second push");
486 let local_sum = refs_checksum(&f.ctx.git, &f.local_repo).await.expect("sum");
487 let remote_sum = remote_refs_checksum(&f.ctx.transport, &remote)
488 .await
489 .expect("remote sum");
490 assert_eq!(
491 local_sum, remote_sum,
492 "tags and the new head reached the standby"
493 );
494 }
495
496 #[tokio::test]
497 async fn a_force_update_removes_the_standby_copy_of_the_old_commit() {
498 let f = fixture().await;
499 replicate_repo(&f.ctx, &f.repo_id)
500 .await
501 .expect("first push");
502 let old = plumbing(&f.local_repo, &["rev-parse", "refs/heads/main"]);
503 commit_to(&f.local_repo, "refs/heads/main", "rewritten");
504 prune_unreachable(&f.ctx.git, &f.local_repo, "--prune=now")
505 .await
506 .expect("local prune");
507 assert!(standby_prune_due(&f.local_repo));
508
509 replicate_repo(&f.ctx, &f.repo_id)
510 .await
511 .expect("second push");
512 let remote = f.ctx.layout.repo_dir(&f.repo_id).expect("remote dir");
513 let found = std::process::Command::new("git")
514 .arg(format!("--git-dir={remote}"))
515 .args(["cat-file", "-e", &old])
516 .status()
517 .expect("cat-file");
518 assert!(
519 !found.success(),
520 "the standby still holds the overwritten commit"
521 );
522 assert!(!standby_prune_due(&f.local_repo), "the mark is cleared");
523 }
524
525 #[tokio::test]
526 async fn a_failed_push_is_recorded_and_keeps_the_last_success() {
527 let f = fixture().await;
528 replicate_repo(&f.ctx, &f.repo_id).await.expect("push");
529 let ok = f
530 .ctx
531 .store
532 .replication_status(&f.repo_id)
533 .await
534 .expect("status")
535 .expect("row");
536
537 std::fs::remove_dir_all(&f.local_repo).expect("remove local repo");
538 assert!(replicate_repo(&f.ctx, &f.repo_id).await.is_err());
539 let failed = f
540 .ctx
541 .store
542 .replication_status(&f.repo_id)
543 .await
544 .expect("status")
545 .expect("row");
546 assert!(failed.last_error.is_some());
547 assert_eq!(failed.last_ok_at, ok.last_ok_at);
548 }
549
550 #[tokio::test]
551 async fn deleted_repo_is_removed_from_the_standby_at_reconcile() {
552 let f = fixture().await;
553 let report = reconcile_once(&f.ctx).await;
554 assert_eq!(
555 report,
556 ReconcileReport {
557 replicated: 1,
558 failures: vec![]
559 }
560 );
561
562 let remote = f.ctx.layout.repo_dir(&f.repo_id).expect("remote dir");
563 assert!(Path::new(&remote).is_dir());
564
565 f.ctx
566 .store
567 .delete_repo(&f.repo_id)
568 .await
569 .expect("delete repo");
570 let report = reconcile_once(&f.ctx).await;
571 assert!(report.failures.is_empty(), "{:?}", report.failures);
572 assert!(!Path::new(&remote).exists(), "standby copy is gone");
573 assert!(
574 f.ctx
575 .store
576 .replication_status(&f.repo_id)
577 .await
578 .expect("status")
579 .is_none(),
580 "status row is gone"
581 );
582 assert!(
583 f.standby.join("repos").is_dir(),
584 "only the repo dir is removed"
585 );
586 }
587
588 #[tokio::test]
589 async fn database_snapshot_ships_with_latest_link_and_prunes_to_24() {
590 let f = fixture().await;
591 let db_dir = f.standby.join("db");
592 std::fs::create_dir_all(&db_dir).expect("db dir");
593 for i in 0..30 {
594 std::fs::write(db_dir.join(format!("forge-19990101T{i:06}Z.db")), b"old")
595 .expect("old snapshot");
596 }
597 std::fs::write(db_dir.join("forge-19990101T000000Z.db.tmp"), b"x").expect("stray");
598
599 ship_db(&f.ctx).await.expect("ship");
600
601 let mut names: Vec<String> = std::fs::read_dir(&db_dir)
602 .expect("list")
603 .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
604 .filter(|n| n.starts_with("forge-") && n.ends_with(".db"))
605 .collect();
606 names.sort();
607 assert_eq!(names.len(), 24, "pruned to the newest 24: {names:?}");
608 assert!(!db_dir.join("forge-19990101T000000Z.db").exists());
609 assert!(db_dir.join("forge-19990101T000029Z.db").exists());
610 assert!(
611 db_dir.join("forge-19990101T000000Z.db.tmp").exists(),
612 "foreign files stay"
613 );
614
615 let newest = names.last().expect("newest").clone();
616 let link = std::fs::read_link(db_dir.join("latest")).expect("latest is a symlink");
617 assert_eq!(
618 link.to_string_lossy(),
619 newest,
620 "latest points at the new snapshot"
621 );
622 let info = verify_snapshot(&db_dir.join(&newest))
623 .await
624 .expect("shipped copy verifies");
625 assert!(info.repos.iter().any(|r| r.0 == f.repo_id));
626
627 let status = f
628 .ctx
629 .store
630 .replication_status(DB_SUBJECT)
631 .await
632 .expect("status")
633 .expect("row");
634 assert!(status.last_ok_at.is_some());
635 assert_eq!(status.last_error, None);
636 assert!(
637 !f.ctx.data_dir.join("run").join("replica-snap.db").exists(),
638 "the local staging copy is removed"
639 );
640 }
641
642 #[tokio::test]
643 async fn reconcile_reports_failures_without_stopping_other_repos() {
644 let f = fixture().await;
645 std::fs::remove_dir_all(&f.local_repo).expect("remove local repo");
646 let report = reconcile_once(&f.ctx).await;
647 assert_eq!(report.replicated, 0);
648 assert_eq!(report.failures.len(), 1, "{:?}", report.failures);
649 }
650}