forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

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