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