| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | use std::collections::HashMap; |
| 11 | use std::time::Duration; |
| 12 | |
| 13 | use forge_core::server_settings::Group; |
| 14 | use forge_core::store::replication::{DB_SUBJECT, ReplicationStatus}; |
| 15 | use forge_core::time::stamp_ago; |
| 16 | use forge_core::{AuditAction, Error}; |
| 17 | use serde::Deserialize; |
| 18 | use topcoat::Result; |
| 19 | use topcoat::context::{Cx, context}; |
| 20 | use topcoat::router::content::Form; |
| 21 | use topcoat::router::error::{forbidden, see_other}; |
| 22 | use topcoat::router::response::Response; |
| 23 | use topcoat::router::{page, query_params, route}; |
| 24 | use topcoat::view::{View, component, view}; |
| 25 | |
| 26 | use crate::audit::{self, Actor, Target}; |
| 27 | use crate::auth::check_csrf; |
| 28 | use crate::i18n::admin::{self as g, K}; |
| 29 | use crate::i18n::s; |
| 30 | use crate::i18n::{self, Key, Lang}; |
| 31 | use crate::live::{Topic, stream_changes}; |
| 32 | use crate::pages::admin_backups::backups_rail; |
| 33 | use crate::pages::admin_server::{ |
| 34 | REPLICATION_KEYS, Row, notice_of, reset_form, save_topic, setting_lines, setting_rows, |
| 35 | with_notice, |
| 36 | }; |
| 37 | use crate::pages::admin_users::admin_only; |
| 38 | use crate::pages::issues_list::list_href; |
| 39 | use crate::state::AppState; |
| 40 | use crate::views::find::{Finder, finder_field}; |
| 41 | use crate::views::parts::{head, post_act}; |
| 42 | use crate::views::repo_list::{PageLink, pager, pager_links}; |
| 43 | use crate::views::{alert, enc, rel_time_or_never, shell}; |
| 44 | |
| 45 | #[query_params(error = bad_request)] |
| 46 | pub(crate) struct NoticeQuery { |
| 47 | notice: Option<String>, |
| 48 | q: Option<String>, |
| 49 | exact: Option<String>, |
| 50 | case: Option<String>, |
| 51 | |
| 52 | health: Option<String>, |
| 53 | page: Option<String>, |
| 54 | } |
| 55 | |
| 56 | |
| 57 | const REPO_ROWS: usize = 10; |
| 58 | |
| 59 | |
| 60 | const HEALTH_KEYS: [&str; 4] = ["error", "lagging", "never", "ok"]; |
| 61 | |
| 62 | |
| 63 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 64 | enum Health { |
| 65 | Ok, |
| 66 | Lagging, |
| 67 | Error, |
| 68 | Never, |
| 69 | } |
| 70 | |
| 71 | impl Health { |
| 72 | |
| 73 | fn dot(self) -> &'static str { |
| 74 | match self { |
| 75 | Health::Ok => "health-dot ok", |
| 76 | Health::Lagging => "health-dot warn", |
| 77 | Health::Error => "health-dot bad", |
| 78 | Health::Never => "health-dot", |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | |
| 83 | fn tone(self) -> &'static str { |
| 84 | match self { |
| 85 | Health::Ok | Health::Never => "", |
| 86 | Health::Lagging => "warn", |
| 87 | Health::Error => "bad", |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | fn key(self) -> &'static str { |
| 92 | match self { |
| 93 | Health::Ok => "ok", |
| 94 | Health::Lagging => "lagging", |
| 95 | Health::Error => "error", |
| 96 | Health::Never => "never", |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | fn from_key(key: &str) -> Option<Health> { |
| 101 | [Health::Ok, Health::Lagging, Health::Error, Health::Never] |
| 102 | .into_iter() |
| 103 | .find(|h| h.key() == key) |
| 104 | } |
| 105 | |
| 106 | fn label(self, lang: Lang) -> &'static str { |
| 107 | match self { |
| 108 | Health::Ok => g::t(lang, K::HealthOk), |
| 109 | Health::Lagging => g::t(lang, K::HealthLagging), |
| 110 | Health::Error => g::t(lang, K::HealthError), |
| 111 | Health::Never => g::t(lang, K::HealthNever), |
| 112 | } |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | |
| 117 | |
| 118 | fn health(status: Option<&ReplicationStatus>, cutoff: &str) -> Health { |
| 119 | match status { |
| 120 | None => Health::Never, |
| 121 | Some(s) if s.last_error.is_some() => Health::Error, |
| 122 | Some(s) => match s.last_ok_at.as_deref() { |
| 123 | None => Health::Never, |
| 124 | Some(ok) if ok >= cutoff => Health::Ok, |
| 125 | Some(_) => Health::Lagging, |
| 126 | }, |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | |
| 131 | struct RepoRow { |
| 132 | name: String, |
| 133 | kind: Health, |
| 134 | dot: &'static str, |
| 135 | tone: &'static str, |
| 136 | health: &'static str, |
| 137 | |
| 138 | last_ok: Option<String>, |
| 139 | error: String, |
| 140 | } |
| 141 | |
| 142 | impl RepoRow { |
| 143 | fn copy(&self) -> RepoRow { |
| 144 | RepoRow { |
| 145 | name: self.name.clone(), |
| 146 | kind: self.kind, |
| 147 | dot: self.dot, |
| 148 | tone: self.tone, |
| 149 | health: self.health, |
| 150 | last_ok: self.last_ok.clone(), |
| 151 | error: self.error.clone(), |
| 152 | } |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | |
| 157 | struct PageData { |
| 158 | enabled: bool, |
| 159 | db_dot: &'static str, |
| 160 | db_health: &'static str, |
| 161 | db_last_ok: Option<String>, |
| 162 | db_last_attempt: Option<String>, |
| 163 | db_error: String, |
| 164 | repos: Vec<RepoRow>, |
| 165 | } |
| 166 | |
| 167 | |
| 168 | async fn page_data(state: &AppState, lang: Lang) -> forge_core::Result<PageData> { |
| 169 | let config = &state.config.replication; |
| 170 | let db_cutoff = stamp_ago(Duration::from_secs(config.db_snapshot_minutes * 60 * 2)); |
| 171 | let repo_cutoff = stamp_ago(Duration::from_secs(config.reconcile_minutes * 60 * 2)); |
| 172 | |
| 173 | let statuses: HashMap<String, ReplicationStatus> = state |
| 174 | .store |
| 175 | .list_replication_status() |
| 176 | .await? |
| 177 | .into_iter() |
| 178 | .map(|s| (s.subject.clone(), s)) |
| 179 | .collect(); |
| 180 | |
| 181 | let db = statuses.get(DB_SUBJECT); |
| 182 | let mut repos = Vec::new(); |
| 183 | let ids = state.store.repo_ids().await?; |
| 184 | for id in &ids { |
| 185 | let status = statuses.get(id); |
| 186 | let name = match state.store.repo_by_id(id).await? { |
| 187 | Some(repo) => format!("{}/{}", repo.owner_name, repo.name), |
| 188 | None => id.clone(), |
| 189 | }; |
| 190 | let h = health(status, &repo_cutoff); |
| 191 | repos.push(RepoRow { |
| 192 | name, |
| 193 | kind: h, |
| 194 | dot: h.dot(), |
| 195 | tone: h.tone(), |
| 196 | health: h.label(lang), |
| 197 | last_ok: status.and_then(|s| s.last_ok_at.clone()), |
| 198 | error: status |
| 199 | .and_then(|s| s.last_error.clone()) |
| 200 | .unwrap_or_default(), |
| 201 | }); |
| 202 | } |
| 203 | |
| 204 | for status in statuses.values() { |
| 205 | if status.subject != DB_SUBJECT && !ids.contains(&status.subject) { |
| 206 | let h = health(Some(status), &repo_cutoff); |
| 207 | repos.push(RepoRow { |
| 208 | name: g::deleted_repo_name(lang, &status.subject), |
| 209 | kind: h, |
| 210 | dot: h.dot(), |
| 211 | tone: h.tone(), |
| 212 | health: h.label(lang), |
| 213 | last_ok: status.last_ok_at.clone(), |
| 214 | error: status.last_error.clone().unwrap_or_default(), |
| 215 | }); |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | Ok(PageData { |
| 220 | enabled: config.enabled(), |
| 221 | db_dot: health(db, &db_cutoff).dot(), |
| 222 | db_health: health(db, &db_cutoff).label(lang), |
| 223 | db_last_ok: db.and_then(|s| s.last_ok_at.clone()), |
| 224 | db_last_attempt: db.and_then(|s| s.last_attempt_at.clone()), |
| 225 | db_error: db.and_then(|s| s.last_error.clone()).unwrap_or_default(), |
| 226 | repos, |
| 227 | }) |
| 228 | } |
| 229 | |
| 230 | #[component] |
| 231 | async fn replication_view( |
| 232 | cx: &Cx, |
| 233 | lang: Lang, |
| 234 | csrf: String, |
| 235 | data: PageData, |
| 236 | settings: Vec<Row>, |
| 237 | notice: Option<String>, |
| 238 | list: RepoList, |
| 239 | ) -> Result<impl View> { |
| 240 | let RepoList { |
| 241 | finder, |
| 242 | health, |
| 243 | rows, |
| 244 | page, |
| 245 | pages, |
| 246 | nav: (links, prev, next), |
| 247 | } = list; |
| 248 | let has_repos = !data.repos.is_empty(); |
| 249 | let all_label = s(lang, "All", "Tümü"); |
| 250 | let health_label = s(lang, "Health", "Durum"); |
| 251 | let placeholder = s(lang, "Search repositories", "Depolarda ara"); |
| 252 | let db_error = format!("{}{}", g::t(lang, K::DatabaseErrorPrefix), data.db_error); |
| 253 | Ok(view! { |
| 254 | head(title: g::t(lang, K::Replication), |
| 255 | post_act(label: g::t(lang, K::ReconcileNow), action: "/admin/replication/reconcile", csrf: csrf.as_str()) |
| 256 | ) |
| 257 | if let Some(message) = notice { |
| 258 | <p class="state" role="status">(message.as_str())</p> |
| 259 | } |
| 260 | <div class="work"> |
| 261 | backups_rail(lang: lang, current: "replication") |
| 262 | <div class="sheet" data-live="/admin/replication/events"> |
| 263 | <section class="sec"> |
| 264 | <h2>(g::t(lang, K::Settings))</h2> |
| 265 | if !data.enabled { |
| 266 | <p class="state">(g::t(lang, K::ReplicationOff))</p> |
| 267 | } |
| 268 | <form method="post" action="/admin/replication" class="srv-form"> |
| 269 | <input type="hidden" name="csrf" value=(csrf.as_str())> |
| 270 | <input type="hidden" name="back" value="/admin/replication"> |
| 271 | setting_lines(lang: lang, rows: settings) |
| 272 | <div class="acts srv-save"> |
| 273 | <button type="submit" class="primary">(i18n::t(lang, Key::Save))</button> |
| 274 | </div> |
| 275 | </form> |
| 276 | reset_form(csrf: csrf.clone(), back: "/admin/replication".to_owned()) |
| 277 | </section> |
| 278 | if data.enabled { |
| 279 | <section class="sec"> |
| 280 | <h2>(crate::i18n::s(lang, "Status", "Durum"))</h2> |
| 281 | <div class="line" data-kb-row=""> |
| 282 | <span class="name">(g::t(lang, K::Database))</span> |
| 283 | <span class="val"><span class=(data.db_dot) aria-hidden="true"></span> (data.db_health)</span> |
| 284 | </div> |
| 285 | if !data.db_error.is_empty() { |
| 286 | alert(message: db_error.as_str()) |
| 287 | } |
| 288 | <div class="line" data-kb-row=""> |
| 289 | <span class="name">(g::t(lang, K::LastDbSnapshotShipped))</span> |
| 290 | <span class="val">rel_time_or_never(lang: lang, stamp: data.db_last_ok.as_deref())</span> |
| 291 | </div> |
| 292 | <div class="line" data-kb-row=""> |
| 293 | <span class="name">(g::t(lang, K::LastDbAttempt))</span> |
| 294 | <span class="val">rel_time_or_never(lang: lang, stamp: data.db_last_attempt.as_deref())</span> |
| 295 | </div> |
| 296 | </section> |
| 297 | } |
| 298 | <section class="sec"> |
| 299 | <h2>(g::t(lang, K::Repos))</h2> |
| 300 | if !has_repos { |
| 301 | <p class="state">(g::t(lang, K::NoReposYet))</p> |
| 302 | } else { |
| 303 | <form class="sec-tools" method="get" action="/admin/replication" role="search"> |
| 304 | finder_field(lang: lang, finder: finder, placeholder: placeholder, id: Some("replication-q")) |
| 305 | <label class="find-filter"> |
| 306 | (health_label) " " |
| 307 | <select name="health" data-autosubmit="true"> |
| 308 | <option value="" selected=(health.is_none())>(all_label)</option> |
| 309 | for key in HEALTH_KEYS { |
| 310 | if let Some(h) = Health::from_key(key) { |
| 311 | <option value=(key) selected=(health == Some(h))>(h.label(lang))</option> |
| 312 | } |
| 313 | } |
| 314 | </select> |
| 315 | </label> |
| 316 | </form> |
| 317 | if rows.is_empty() { |
| 318 | <p class="state">(s(lang, "No repository matches.", "Eşleşen depo yok."))</p> |
| 319 | } |
| 320 | for row in rows.into_iter() { |
| 321 | <div class="line" data-kb-row=""> |
| 322 | <span class="name">(row.name.as_str())</span> |
| 323 | <span class="val"><span class=(row.dot) aria-hidden="true"></span> <span class=(row.tone)>(row.health)</span> " · " (g::t(lang, K::LastSuccess)) ": " rel_time_or_never(lang: lang, stamp: row.last_ok.as_deref())</span> |
| 324 | </div> |
| 325 | if !row.error.is_empty() { |
| 326 | alert(message: row.error.as_str()) |
| 327 | } |
| 328 | } |
| 329 | } |
| 330 | </section> |
| 331 | pager(page: page, pages: pages, links: links, prev: prev, next: next, lang: lang) |
| 332 | </div> |
| 333 | </div> |
| 334 | }) |
| 335 | } |
| 336 | |
| 337 | |
| 338 | |
| 339 | async fn page_fingerprint(state: &AppState) -> Result<String> { |
| 340 | let data = page_data(state, Lang::En).await?; |
| 341 | let rows: Vec<_> = data |
| 342 | .repos |
| 343 | .iter() |
| 344 | .map(|row| (&row.name, row.health, &row.last_ok, &row.error)) |
| 345 | .collect(); |
| 346 | Ok(format!( |
| 347 | "{}|{}|{:?}|{:?}|{}|{:?}", |
| 348 | data.enabled, data.db_health, data.db_last_ok, data.db_last_attempt, data.db_error, rows |
| 349 | )) |
| 350 | } |
| 351 | |
| 352 | |
| 353 | #[route(GET "/admin/replication/events")] |
| 354 | async fn replication_events(cx: &Cx) -> Result<Response> { |
| 355 | admin_only(cx).await?; |
| 356 | let state = context::<AppState>(cx).clone(); |
| 357 | stream_changes( |
| 358 | cx, |
| 359 | crate::live::admin(), |
| 360 | &[Topic::AdminReplication], |
| 361 | move || { |
| 362 | let state = state.clone(); |
| 363 | async move { page_fingerprint(&state).await } |
| 364 | }, |
| 365 | ) |
| 366 | .await |
| 367 | } |
| 368 | |
| 369 | |
| 370 | struct RepoList { |
| 371 | finder: Finder, |
| 372 | health: Option<Health>, |
| 373 | rows: Vec<RepoRow>, |
| 374 | page: u64, |
| 375 | pages: u64, |
| 376 | nav: (Vec<PageLink>, Option<String>, Option<String>), |
| 377 | } |
| 378 | |
| 379 | |
| 380 | fn repo_list(data: &mut PageData, query: &NoticeQuery) -> RepoList { |
| 381 | let finder = Finder::new( |
| 382 | query.q.as_deref(), |
| 383 | query.exact.as_deref(), |
| 384 | query.case.as_deref(), |
| 385 | ); |
| 386 | let health = query.health.as_deref().and_then(Health::from_key); |
| 387 | let matching: Vec<RepoRow> = data |
| 388 | .repos |
| 389 | .iter() |
| 390 | .filter(|row| health.is_none_or(|h| row.kind == h)) |
| 391 | .filter(|row| finder.matches_any(&[row.name.as_str(), row.error.as_str()])) |
| 392 | .map(RepoRow::copy) |
| 393 | .collect(); |
| 394 | let pages = (matching.len() as u64).div_ceil(REPO_ROWS as u64).max(1); |
| 395 | let page = query |
| 396 | .page |
| 397 | .as_deref() |
| 398 | .and_then(|p| p.parse::<u64>().ok()) |
| 399 | .unwrap_or(1) |
| 400 | .clamp(1, pages); |
| 401 | let rows = matching |
| 402 | .into_iter() |
| 403 | .skip((page - 1) as usize * REPO_ROWS) |
| 404 | .take(REPO_ROWS) |
| 405 | .collect(); |
| 406 | let health_key = health.map_or("", Health::key); |
| 407 | let nav = pager_links(page, pages, |n| { |
| 408 | let number = n.to_string(); |
| 409 | let mut params = finder.params(); |
| 410 | params.push(("health", health_key)); |
| 411 | params.push(("page", number.as_str())); |
| 412 | list_href("/admin/replication", ¶ms) |
| 413 | }); |
| 414 | RepoList { |
| 415 | finder, |
| 416 | health, |
| 417 | rows, |
| 418 | page, |
| 419 | pages, |
| 420 | nav, |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | #[page("/admin/replication")] |
| 425 | async fn replication_page(cx: &Cx) -> Result<impl View> { |
| 426 | let viewer = admin_only(cx).await?; |
| 427 | let query = query_params::<NoticeQuery>(cx)?; |
| 428 | let lang = i18n::lang(cx, Some(&viewer.0)); |
| 429 | let state = context::<AppState>(cx); |
| 430 | let mut data = page_data(state, lang).await?; |
| 431 | let list = repo_list(&mut data, query); |
| 432 | let settings = setting_rows(state, lang, REPLICATION_KEYS).await?; |
| 433 | let csrf = viewer.1.csrf_token.clone(); |
| 434 | let title = g::t(lang, K::Replication); |
| 435 | Ok(view! { |
| 436 | shell(title: title, viewer: Some(&viewer), replication_view(lang: lang, csrf: csrf, data: data, settings: settings, notice: query.notice.clone(), list: list)) |
| 437 | }) |
| 438 | } |
| 439 | |
| 440 | |
| 441 | #[route(POST "/admin/replication")] |
| 442 | async fn replication_save(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> Result<Response> { |
| 443 | let viewer = admin_only(cx).await?; |
| 444 | if !check_csrf(&viewer.1, form.get("csrf").map_or("", String::as_str)) { |
| 445 | return Err(forbidden().into()); |
| 446 | } |
| 447 | let lang = i18n::lang(cx, Some(&viewer.0)); |
| 448 | let state = context::<AppState>(cx); |
| 449 | let notice = notice_of( |
| 450 | lang, |
| 451 | save_topic( |
| 452 | cx, |
| 453 | state, |
| 454 | &viewer.0, |
| 455 | Group::Backups, |
| 456 | REPLICATION_KEYS, |
| 457 | form, |
| 458 | lang, |
| 459 | ) |
| 460 | .await, |
| 461 | ); |
| 462 | Err(see_other(with_notice("/admin/replication", ¬ice)).into()) |
| 463 | } |
| 464 | |
| 465 | #[derive(Deserialize)] |
| 466 | struct ReconcileForm { |
| 467 | #[serde(default)] |
| 468 | csrf: String, |
| 469 | } |
| 470 | |
| 471 | #[route(POST "/admin/replication/reconcile")] |
| 472 | async fn replication_reconcile(cx: &Cx, Form(form): Form<ReconcileForm>) -> Result<Response> { |
| 473 | let viewer = admin_only(cx).await?; |
| 474 | if !check_csrf(&viewer.1, &form.csrf) { |
| 475 | return Err(forbidden().into()); |
| 476 | } |
| 477 | let lang = i18n::lang(cx, Some(&viewer.0)); |
| 478 | let state = context::<AppState>(cx); |
| 479 | let notice = match reconcile_now(cx, state, &viewer.0, lang).await { |
| 480 | Ok(()) => g::t(lang, K::ReconcileStarted).to_owned(), |
| 481 | Err(Error::Config(message)) => message, |
| 482 | Err(other) => other.to_string(), |
| 483 | }; |
| 484 | let location = format!("/admin/replication?notice={}", enc(¬ice)); |
| 485 | Err(see_other(&location).into()) |
| 486 | } |
| 487 | |
| 488 | |
| 489 | async fn reconcile_now( |
| 490 | cx: &Cx, |
| 491 | state: &AppState, |
| 492 | user: &forge_core::User, |
| 493 | lang: Lang, |
| 494 | ) -> forge_core::Result<()> { |
| 495 | if !state.config.replication.enabled() { |
| 496 | return Err(Error::Config( |
| 497 | g::t(lang, K::ErrReplicationNotConfigured).to_owned(), |
| 498 | )); |
| 499 | } |
| 500 | audit::record( |
| 501 | &state.store, |
| 502 | Some(cx), |
| 503 | Actor::User(user), |
| 504 | AuditAction::ReplicationReconcileStarted, |
| 505 | Target { |
| 506 | kind: "replication", |
| 507 | id: "", |
| 508 | name: "", |
| 509 | }, |
| 510 | serde_json::json!({ "trigger": "manual" }), |
| 511 | ) |
| 512 | .await; |
| 513 | state.replication.request_reconcile(); |
| 514 | Ok(()) |
| 515 | } |
| 516 | |
| 517 | #[cfg(test)] |
| 518 | mod tests { |
| 519 | use super::*; |
| 520 | use forge_core::model::Visibility; |
| 521 | use topcoat::router::request::Request; |
| 522 | use topcoat::router::{Body, Router, to_bytes}; |
| 523 | |
| 524 | use crate::auth::SESSION_COOKIE; |
| 525 | use crate::test_support::{app_router, create_session, test_config, test_state}; |
| 526 | |
| 527 | const ADMIN_TOKEN: &str = "replication-admin-session"; |
| 528 | const USER_TOKEN: &str = "replication-user-session"; |
| 529 | const CSRF: &str = "replication-csrf"; |
| 530 | const TARGET: &str = "sb@standby.example:/srv/forge-standby"; |
| 531 | |
| 532 | struct Fixture { |
| 533 | _dir: tempfile::TempDir, |
| 534 | router: Router, |
| 535 | state: AppState, |
| 536 | repo_id: String, |
| 537 | } |
| 538 | |
| 539 | |
| 540 | async fn fixture(configured: bool) -> Fixture { |
| 541 | let dir = tempfile::tempdir().expect("tempdir"); |
| 542 | let data_dir = dir.path().join("data"); |
| 543 | std::fs::create_dir_all(&data_dir).expect("data dir"); |
| 544 | let mut state = test_state(&data_dir).await; |
| 545 | let mut config = test_config(&data_dir); |
| 546 | if configured { |
| 547 | config.replication.target = TARGET.into(); |
| 548 | } |
| 549 | state.config = std::sync::Arc::new(config); |
| 550 | state.settings = crate::state::settings_for(&state.config); |
| 551 | let admin = state |
| 552 | .store |
| 553 | .create_user("root", None, "h", true) |
| 554 | .await |
| 555 | .expect("admin"); |
| 556 | let user = state |
| 557 | .store |
| 558 | .create_user("plain", None, "h", false) |
| 559 | .await |
| 560 | .expect("user"); |
| 561 | create_session(&state.store, &admin.id, ADMIN_TOKEN, CSRF).await; |
| 562 | create_session(&state.store, &user.id, USER_TOKEN, CSRF).await; |
| 563 | let repo = state |
| 564 | .store |
| 565 | .create_repo(&admin.id, "demo", "", Visibility::Private, "main") |
| 566 | .await |
| 567 | .expect("repo"); |
| 568 | let router = app_router(state.clone()); |
| 569 | Fixture { |
| 570 | _dir: dir, |
| 571 | router, |
| 572 | state, |
| 573 | repo_id: repo.id, |
| 574 | } |
| 575 | } |
| 576 | |
| 577 | async fn send( |
| 578 | router: &Router, |
| 579 | method: &str, |
| 580 | uri: &str, |
| 581 | token: Option<&str>, |
| 582 | form: Option<String>, |
| 583 | ) -> (u16, String) { |
| 584 | let mut builder = Request::builder().method(method).uri(uri); |
| 585 | if let Some(token) = token { |
| 586 | builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={token}")); |
| 587 | } |
| 588 | let body = match form { |
| 589 | Some(form) => { |
| 590 | builder = builder.header("content-type", "application/x-www-form-urlencoded"); |
| 591 | Body::from(form) |
| 592 | } |
| 593 | None => Body::empty(), |
| 594 | }; |
| 595 | let res = router.handle(builder.body(body).expect("request")).await; |
| 596 | let status = res.status().as_u16(); |
| 597 | let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body"); |
| 598 | (status, String::from_utf8_lossy(&bytes).into_owned()) |
| 599 | } |
| 600 | |
| 601 | |
| 602 | |
| 603 | #[tokio::test] |
| 604 | async fn replication_page_and_reconcile() { |
| 605 | let fx = fixture(true).await; |
| 606 | |
| 607 | |
| 608 | let (anon, _) = send(&fx.router, "GET", "/admin/replication", None, None).await; |
| 609 | assert_eq!(anon, 404, "anonymous page"); |
| 610 | let (user, _) = send( |
| 611 | &fx.router, |
| 612 | "GET", |
| 613 | "/admin/replication", |
| 614 | Some(USER_TOKEN), |
| 615 | None, |
| 616 | ) |
| 617 | .await; |
| 618 | assert_eq!(user, 404, "plain user page"); |
| 619 | let (posted, _) = send( |
| 620 | &fx.router, |
| 621 | "POST", |
| 622 | "/admin/replication/reconcile", |
| 623 | Some(USER_TOKEN), |
| 624 | Some(format!("csrf={CSRF}")), |
| 625 | ) |
| 626 | .await; |
| 627 | assert_eq!(posted, 404, "plain user reconcile"); |
| 628 | assert!(!fx.state.replication.take_reconcile_request()); |
| 629 | |
| 630 | |
| 631 | let store = &fx.state.store; |
| 632 | store |
| 633 | .record_replication_ok(DB_SUBJECT, None) |
| 634 | .await |
| 635 | .expect("db ok"); |
| 636 | store |
| 637 | .record_replication_ok(&fx.repo_id, Some("abc")) |
| 638 | .await |
| 639 | .expect("repo ok"); |
| 640 | store |
| 641 | .record_replication_error("gone-repo-id", "remove failed") |
| 642 | .await |
| 643 | .expect("stale"); |
| 644 | |
| 645 | let (status, body) = send( |
| 646 | &fx.router, |
| 647 | "GET", |
| 648 | "/admin/replication", |
| 649 | Some(ADMIN_TOKEN), |
| 650 | None, |
| 651 | ) |
| 652 | .await; |
| 653 | assert_eq!(status, 200); |
| 654 | assert!(body.contains("sb@standby.example:/srv/forge-standby")); |
| 655 | assert!(body.contains("root/demo"), "repo name is shown"); |
| 656 | assert!(body.contains("ok")); |
| 657 | assert!( |
| 658 | body.contains("gone-repo-id"), |
| 659 | "stale rows are shown until cleaned" |
| 660 | ); |
| 661 | assert!(body.contains("pending cleanup")); |
| 662 | assert!(body.contains("Reconcile now")); |
| 663 | |
| 664 | |
| 665 | let (bad, _) = send( |
| 666 | &fx.router, |
| 667 | "POST", |
| 668 | "/admin/replication/reconcile", |
| 669 | Some(ADMIN_TOKEN), |
| 670 | Some("csrf=wrong".into()), |
| 671 | ) |
| 672 | .await; |
| 673 | assert_eq!(bad, 403, "reconcile without csrf"); |
| 674 | assert!(!fx.state.replication.take_reconcile_request()); |
| 675 | |
| 676 | let (status, _) = send( |
| 677 | &fx.router, |
| 678 | "POST", |
| 679 | "/admin/replication/reconcile", |
| 680 | Some(ADMIN_TOKEN), |
| 681 | Some(format!("csrf={CSRF}")), |
| 682 | ) |
| 683 | .await; |
| 684 | assert_eq!(status, 303, "reconcile with csrf"); |
| 685 | assert!(fx.state.replication.take_reconcile_request()); |
| 686 | let audit = fx |
| 687 | .state |
| 688 | .store |
| 689 | .list_audit(&Default::default(), None, 10) |
| 690 | .await |
| 691 | .expect("audit"); |
| 692 | assert!( |
| 693 | audit |
| 694 | .iter() |
| 695 | .any(|e| e.action == AuditAction::ReplicationReconcileStarted), |
| 696 | "the request is audited" |
| 697 | ); |
| 698 | } |
| 699 | |
| 700 | #[tokio::test] |
| 701 | async fn unconfigured_page_says_so_and_reconcile_is_refused() { |
| 702 | let fx = fixture(false).await; |
| 703 | let (status, body) = send( |
| 704 | &fx.router, |
| 705 | "GET", |
| 706 | "/admin/replication", |
| 707 | Some(ADMIN_TOKEN), |
| 708 | None, |
| 709 | ) |
| 710 | .await; |
| 711 | assert_eq!(status, 200); |
| 712 | assert!(body.contains("Replication is off")); |
| 713 | |
| 714 | let (status, _) = send( |
| 715 | &fx.router, |
| 716 | "POST", |
| 717 | "/admin/replication/reconcile", |
| 718 | Some(ADMIN_TOKEN), |
| 719 | Some(format!("csrf={CSRF}")), |
| 720 | ) |
| 721 | .await; |
| 722 | assert_eq!(status, 303); |
| 723 | assert!(!fx.state.replication.take_reconcile_request()); |
| 724 | let audit = fx |
| 725 | .state |
| 726 | .store |
| 727 | .list_audit(&Default::default(), None, 10) |
| 728 | .await |
| 729 | .expect("audit"); |
| 730 | assert!( |
| 731 | !audit |
| 732 | .iter() |
| 733 | .any(|e| e.action == AuditAction::ReplicationReconcileStarted) |
| 734 | ); |
| 735 | } |
| 736 | |
| 737 | #[test] |
| 738 | fn health_reads_errors_before_age() { |
| 739 | let cutoff = "2026-01-01T00:00:00.000000000Z"; |
| 740 | let fresh = ReplicationStatus { |
| 741 | subject: "r".into(), |
| 742 | last_ok_at: Some("2026-06-01T00:00:00.000000000Z".into()), |
| 743 | last_error: None, |
| 744 | last_attempt_at: None, |
| 745 | refs_sha256: None, |
| 746 | }; |
| 747 | assert_eq!(health(Some(&fresh), cutoff), Health::Ok); |
| 748 | let old = ReplicationStatus { |
| 749 | last_ok_at: Some("2025-06-01T00:00:00.000000000Z".into()), |
| 750 | ..fresh.clone() |
| 751 | }; |
| 752 | assert_eq!(health(Some(&old), cutoff), Health::Lagging); |
| 753 | let failing = ReplicationStatus { |
| 754 | last_error: Some("boom".into()), |
| 755 | ..fresh.clone() |
| 756 | }; |
| 757 | assert_eq!(health(Some(&failing), cutoff), Health::Error); |
| 758 | assert_eq!(health(None, cutoff), Health::Never); |
| 759 | } |
| 760 | } |