use std::collections::HashMap; use forge_core::server_settings::Group; use forge_core::store::replication::{ DB_SUBJECT, ReplicationHealth, ReplicationStatus, replication_health, window_secs, }; use forge_core::time::now_unix; use forge_core::{AuditAction, Error}; use serde::Deserialize; use topcoat::Result; use topcoat::context::{Cx, context}; use topcoat::router::content::Form; use topcoat::router::error::{forbidden, see_other}; use topcoat::router::response::Response; use topcoat::router::{page, query_params, route}; use topcoat::view::{View, component, view}; use crate::audit::{self, Actor, Target}; use crate::auth::check_csrf; use crate::i18n::admin::{self as g, K}; use crate::i18n::s; use crate::i18n::{self, Key, Lang}; use crate::live::{Topic, stream_changes}; use crate::pages::admin_backups::backups_rail; use crate::pages::admin_server::{ REPLICATION_KEYS, Row, notice_of, reset_form, save_topic, setting_lines, setting_rows, with_notice, }; use crate::pages::admin_users::admin_only; use crate::pages::issues_list::list_href; use crate::state::AppState; use crate::views::find::{Finder, finder_field}; use crate::views::paging::{paginate, requested_page}; use crate::views::parts::{head, post_act}; use crate::views::repo_list::{PageLink, pager, pager_links}; use crate::views::{alert, enc, rel_time_or_never, shell}; #[query_params(error = bad_request)] struct NoticeQuery { notice: Option, q: Option, exact: Option, case: Option, health: Option, page: Option, } const REPO_ROWS: usize = 10; const HEALTH_MENU: [ReplicationHealth; 4] = [ ReplicationHealth::Error, ReplicationHealth::Lagging, ReplicationHealth::Never, ReplicationHealth::Ok, ]; fn health_dot(health: ReplicationHealth) -> &'static str { match health { ReplicationHealth::Ok => "health-dot ok", ReplicationHealth::Lagging => "health-dot warn", ReplicationHealth::Error => "health-dot bad", ReplicationHealth::Never => "health-dot", } } fn health_tone(health: ReplicationHealth) -> &'static str { match health { ReplicationHealth::Ok | ReplicationHealth::Never => "", ReplicationHealth::Lagging => "warn", ReplicationHealth::Error => "bad", } } fn health_slug(health: ReplicationHealth) -> &'static str { match health { ReplicationHealth::Ok => "ok", ReplicationHealth::Lagging => "lagging", ReplicationHealth::Error => "error", ReplicationHealth::Never => "never", } } fn health_from_slug(slug: &str) -> Option { HEALTH_MENU.into_iter().find(|h| health_slug(*h) == slug) } fn health_text(health: ReplicationHealth, lang: Lang) -> &'static str { match health { ReplicationHealth::Ok => g::t(lang, K::HealthOk), ReplicationHealth::Lagging => g::t(lang, K::HealthLagging), ReplicationHealth::Error => g::t(lang, K::HealthError), ReplicationHealth::Never => g::t(lang, K::HealthNever), } } struct RepoRow { name: String, kind: ReplicationHealth, last_ok: Option, error: String, } fn repo_row(name: String, status: Option<&ReplicationStatus>, now: i64, window: i64) -> RepoRow { RepoRow { name, kind: replication_health(status, now, window), last_ok: status.and_then(|s| s.last_ok_at.clone()), error: status .and_then(|s| s.last_error.clone()) .unwrap_or_default(), } } struct PageData { enabled: bool, db_dot: &'static str, db_health: &'static str, db_last_ok: Option, db_last_attempt: Option, db_error: String, repos: Vec, } async fn page_data(state: &AppState, lang: Lang) -> forge_core::Result { let config = &state.config.replication; let now = now_unix(); let db_window = window_secs(config.db_snapshot_minutes); let repo_window = window_secs(config.reconcile_minutes); let statuses: HashMap = state .store .list_replication_status() .await? .into_iter() .map(|s| (s.subject.clone(), s)) .collect(); let db = statuses.get(DB_SUBJECT); let mut repos = Vec::new(); let ids = state.store.repo_ids().await?; for id in &ids { let status = statuses.get(id); let name = match state.store.repo_by_id(id).await? { Some(repo) => format!("{}/{}", repo.owner_name, repo.name), None => id.clone(), }; repos.push(repo_row(name, status, now, repo_window)); } for status in statuses.values() { if status.subject != DB_SUBJECT && !ids.contains(&status.subject) { let name = g::deleted_repo_name(lang, &status.subject); repos.push(repo_row(name, Some(status), now, repo_window)); } } let db_health = replication_health(db, now, db_window); Ok(PageData { enabled: config.enabled(), db_dot: health_dot(db_health), db_health: health_text(db_health, lang), db_last_ok: db.and_then(|s| s.last_ok_at.clone()), db_last_attempt: db.and_then(|s| s.last_attempt_at.clone()), db_error: db.and_then(|s| s.last_error.clone()).unwrap_or_default(), repos, }) } #[component] async fn replication_view( cx: &Cx, lang: Lang, csrf: String, data: PageData, settings: Vec, notice: Option, list: RepoList, ) -> Result { let RepoList { has_repos, finder, health, rows, page, pages, nav: (links, prev, next), } = list; let all_label = s(lang, "All", "Tümü"); let health_label = s(lang, "Health", "Durum"); let placeholder = s(lang, "Search repositories", "Depolarda ara"); let db_error = format!("{}{}", g::t(lang, K::DatabaseErrorPrefix), data.db_error); Ok(view! { head(title: g::t(lang, K::Replication), post_act(label: g::t(lang, K::ReconcileNow), action: "/admin/replication/reconcile", csrf: csrf.as_str()) ) if let Some(message) = notice {

(message.as_str())

}
backups_rail(lang: lang, current: "replication")

(g::t(lang, K::Settings))

if !data.enabled {

(g::t(lang, K::ReplicationOff))

}
setting_lines(lang: lang, rows: settings)
reset_form(csrf: csrf.clone(), back: "/admin/replication".to_owned())
if data.enabled {

(crate::i18n::s(lang, "Status", "Durum"))

(g::t(lang, K::Database)) (data.db_health)
if !data.db_error.is_empty() { alert(message: db_error.as_str()) }
(g::t(lang, K::LastDbSnapshotShipped)) rel_time_or_never(lang: lang, stamp: data.db_last_ok.as_deref())
(g::t(lang, K::LastDbAttempt)) rel_time_or_never(lang: lang, stamp: data.db_last_attempt.as_deref())
}

(g::t(lang, K::Repos))

if !has_repos {

(g::t(lang, K::NoReposYet))

} else { if rows.is_empty() {

(s(lang, "No repository matches.", "Eşleşen depo yok."))

} for row in rows.into_iter() {
(row.name.as_str()) (health_text(row.kind, lang)) " · " (g::t(lang, K::LastSuccess)) ": " rel_time_or_never(lang: lang, stamp: row.last_ok.as_deref())
if !row.error.is_empty() { alert(message: row.error.as_str()) } } }
pager(page: page, pages: pages, links: links, prev: prev, next: next, lang: lang)
}) } async fn page_fingerprint(state: &AppState) -> Result { let data = page_data(state, Lang::En).await?; let rows: Vec<_> = data .repos .iter() .map(|row| { ( &row.name, health_text(row.kind, Lang::En), &row.last_ok, &row.error, ) }) .collect(); Ok(format!( "{}|{}|{:?}|{:?}|{}|{:?}", data.enabled, data.db_health, data.db_last_ok, data.db_last_attempt, data.db_error, rows )) } #[route(GET "/admin/replication/events")] async fn replication_events(cx: &Cx) -> Result { admin_only(cx).await?; let state = context::(cx).clone(); stream_changes( cx, crate::live::admin(), &[Topic::AdminReplication], move || { let state = state.clone(); async move { page_fingerprint(&state).await } }, ) .await } struct RepoList { has_repos: bool, finder: Finder, health: Option, rows: Vec, page: u64, pages: u64, nav: (Vec, Option, Option), } fn repo_list(repos: Vec, query: &NoticeQuery) -> RepoList { let finder = Finder::new( query.q.as_deref(), query.exact.as_deref(), query.case.as_deref(), ); let health = query.health.as_deref().and_then(health_from_slug); let has_repos = !repos.is_empty(); let matching: Vec = repos .into_iter() .filter(|row| health.is_none_or(|h| row.kind == h)) .filter(|row| finder.matches_any(&[row.name.as_str(), row.error.as_str()])) .collect(); let (rows, page, pages) = paginate( matching, requested_page(query.page.as_deref()), REPO_ROWS as u64, ); let health_key = health.map_or("", health_slug); let nav = pager_links(page, pages, |n| { let number = n.to_string(); let mut params = finder.params(); params.push(("health", health_key)); params.push(("page", number.as_str())); list_href("/admin/replication", ¶ms) }); RepoList { has_repos, finder, health, rows, page, pages, nav, } } #[page("/admin/replication")] async fn replication_page(cx: &Cx) -> Result { let viewer = admin_only(cx).await?; let query = query_params::(cx)?; let lang = i18n::lang(cx, Some(&viewer.0)); let state = context::(cx); let mut data = page_data(state, lang).await?; let list = repo_list(std::mem::take(&mut data.repos), query); let settings = setting_rows(state, lang, REPLICATION_KEYS).await?; let csrf = viewer.1.csrf_token.clone(); let title = g::t(lang, K::Replication); Ok(view! { shell(title: title, viewer: Some(&viewer), replication_view(lang: lang, csrf: csrf, data: data, settings: settings, notice: query.notice.clone(), list: list)) }) } #[route(POST "/admin/replication")] async fn replication_save(cx: &Cx, Form(form): Form>) -> Result { let viewer = admin_only(cx).await?; if !check_csrf(&viewer.1, form.get("csrf").map_or("", String::as_str)) { return Err(forbidden().into()); } let lang = i18n::lang(cx, Some(&viewer.0)); let state = context::(cx); let notice = notice_of( lang, save_topic( cx, state, &viewer.0, Group::Backups, REPLICATION_KEYS, form, lang, ) .await, ); Err(see_other(with_notice("/admin/replication", ¬ice)).into()) } #[derive(Deserialize)] struct ReconcileForm { #[serde(default)] csrf: String, } #[route(POST "/admin/replication/reconcile")] async fn replication_reconcile(cx: &Cx, Form(form): Form) -> Result { let viewer = admin_only(cx).await?; if !check_csrf(&viewer.1, &form.csrf) { return Err(forbidden().into()); } let lang = i18n::lang(cx, Some(&viewer.0)); let state = context::(cx); let notice = match reconcile_now(cx, state, &viewer.0, lang).await { Ok(()) => g::t(lang, K::ReconcileStarted).to_owned(), Err(Error::Config(message)) => message, Err(other) => other.to_string(), }; let location = format!("/admin/replication?notice={}", enc(¬ice)); Err(see_other(&location).into()) } async fn reconcile_now( cx: &Cx, state: &AppState, user: &forge_core::User, lang: Lang, ) -> forge_core::Result<()> { if !state.config.replication.enabled() { return Err(Error::Config( g::t(lang, K::ErrReplicationNotConfigured).to_owned(), )); } audit::record( &state.store, Some(cx), Actor::User(user), AuditAction::ReplicationReconcileStarted, Target { kind: "replication", id: "", name: "", }, serde_json::json!({ "trigger": "manual" }), ) .await; state.replication.request_reconcile(); Ok(()) } #[cfg(test)] mod tests { use super::*; use forge_core::model::Visibility; use topcoat::router::request::Request; use topcoat::router::{Body, Router, to_bytes}; use crate::auth::SESSION_COOKIE; use crate::test_support::{app_router, create_session, test_config, test_state}; const ADMIN_TOKEN: &str = "replication-admin-session"; const USER_TOKEN: &str = "replication-user-session"; const CSRF: &str = "replication-csrf"; const TARGET: &str = "sb@standby.example:/srv/forge-standby"; struct Fixture { _dir: tempfile::TempDir, router: Router, state: AppState, repo_id: String, } async fn fixture(configured: bool) -> Fixture { let dir = tempfile::tempdir().expect("tempdir"); let data_dir = dir.path().join("data"); std::fs::create_dir_all(&data_dir).expect("data dir"); let mut state = test_state(&data_dir).await; let mut config = test_config(&data_dir); if configured { config.replication.target = TARGET.into(); } state.config = std::sync::Arc::new(config); state.settings = crate::state::settings_for(&state.config); let admin = state .store .create_user("root", None, "h", true) .await .expect("admin"); let user = state .store .create_user("plain", None, "h", false) .await .expect("user"); create_session(&state.store, &admin.id, ADMIN_TOKEN, CSRF).await; create_session(&state.store, &user.id, USER_TOKEN, CSRF).await; let repo = state .store .create_repo(&admin.id, "demo", "", Visibility::Private, "main") .await .expect("repo"); let router = app_router(state.clone()); Fixture { _dir: dir, router, state, repo_id: repo.id, } } async fn send( router: &Router, method: &str, uri: &str, token: Option<&str>, form: Option, ) -> (u16, String) { let mut builder = Request::builder().method(method).uri(uri); if let Some(token) = token { builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={token}")); } let body = match form { Some(form) => { builder = builder.header("content-type", "application/x-www-form-urlencoded"); Body::from(form) } None => Body::empty(), }; let res = router.handle(builder.body(body).expect("request")).await; let status = res.status().as_u16(); let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body"); (status, String::from_utf8_lossy(&bytes).into_owned()) } #[tokio::test] async fn replication_page_and_reconcile() { let fx = fixture(true).await; let (anon, _) = send(&fx.router, "GET", "/admin/replication", None, None).await; assert_eq!(anon, 404, "anonymous page"); let (user, _) = send( &fx.router, "GET", "/admin/replication", Some(USER_TOKEN), None, ) .await; assert_eq!(user, 404, "plain user page"); let (posted, _) = send( &fx.router, "POST", "/admin/replication/reconcile", Some(USER_TOKEN), Some(format!("csrf={CSRF}")), ) .await; assert_eq!(posted, 404, "plain user reconcile"); assert!(!fx.state.replication.take_reconcile_request()); let store = &fx.state.store; store .record_replication_ok(DB_SUBJECT, None) .await .expect("db ok"); store .record_replication_ok(&fx.repo_id, Some("abc")) .await .expect("repo ok"); store .record_replication_error("gone-repo-id", "remove failed") .await .expect("stale"); let (status, body) = send( &fx.router, "GET", "/admin/replication", Some(ADMIN_TOKEN), None, ) .await; assert_eq!(status, 200); assert!(body.contains("sb@standby.example:/srv/forge-standby")); assert!(body.contains("root/demo"), "repo name is shown"); assert!(body.contains("ok")); assert!( body.contains("gone-repo-id"), "stale rows are shown until cleaned" ); assert!(body.contains("pending cleanup")); assert!(body.contains("Reconcile now")); let (bad, _) = send( &fx.router, "POST", "/admin/replication/reconcile", Some(ADMIN_TOKEN), Some("csrf=wrong".into()), ) .await; assert_eq!(bad, 403, "reconcile without csrf"); assert!(!fx.state.replication.take_reconcile_request()); let (status, _) = send( &fx.router, "POST", "/admin/replication/reconcile", Some(ADMIN_TOKEN), Some(format!("csrf={CSRF}")), ) .await; assert_eq!(status, 303, "reconcile with csrf"); assert!(fx.state.replication.take_reconcile_request()); let audit = fx .state .store .list_audit(&Default::default(), None, 10) .await .expect("audit"); assert!( audit .iter() .any(|e| e.action == AuditAction::ReplicationReconcileStarted), "the request is audited" ); } #[tokio::test] async fn unconfigured_page_says_so_and_reconcile_is_refused() { let fx = fixture(false).await; let (status, body) = send( &fx.router, "GET", "/admin/replication", Some(ADMIN_TOKEN), None, ) .await; assert_eq!(status, 200); assert!(body.contains("Replication is off")); let (status, _) = send( &fx.router, "POST", "/admin/replication/reconcile", Some(ADMIN_TOKEN), Some(format!("csrf={CSRF}")), ) .await; assert_eq!(status, 303); assert!(!fx.state.replication.take_reconcile_request()); let audit = fx .state .store .list_audit(&Default::default(), None, 10) .await .expect("audit"); assert!( !audit .iter() .any(|e| e.action == AuditAction::ReplicationReconcileStarted) ); } }