forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.2 MiBb00f3f4Tahinli1 month ago147 commits

admin_replication.rs585 lines, 19.7 KiBHistoryRawDownload
1//! Page: standby replication (`/admin/replication`). Instance admins only; anyone else gets 404.
2//!
3//! Shows the `[replication]` target, the last database snapshot shipped, and one row per repo
4//! with its health: ok, lagging (no success within twice the interval), error, or never replicated.
5//! "Reconcile now" queues a full pass for the worker. It is a POST with a CSRF token, and it is
6//! audited as `replication_reconcile_started`.
7
8use std::collections::HashMap;
9use std::time::Duration;
10
11use forge_core::store::replication::{DB_SUBJECT, ReplicationStatus};
12use forge_core::time::stamp_ago;
13use forge_core::tz::format_in_tz;
14use forge_core::{AuditAction, Error};
15use serde::Deserialize;
16use topcoat::Result;
17use topcoat::context::{Cx, app_context};
18use topcoat::router::content::Form;
19use topcoat::router::error::{forbidden, see_other};
20use topcoat::router::response::Response;
21use topcoat::router::{page, query_params, route};
22use topcoat::view::{View, component, view};
23
24use crate::audit::{self, Actor, Target};
25use crate::auth::check_csrf;
26use crate::i18n::admin::{self as g, K};
27use crate::i18n::{self, Key, Lang};
28use crate::live::{Topic, stream_changes};
29use crate::pages::admin_users::admin_only;
30use crate::pages::issues_list::stamp_unix;
31use crate::state::AppState;
32use crate::views::{enc, shell};
33
34#[query_params(error = bad_request)]
35pub(crate) struct NoticeQuery {
36 notice: Option<String>,
37}
38
39/// How a subject reads on the page.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41enum Health {
42 Ok,
43 Lagging,
44 Error,
45 Never,
46}
47
48impl Health {
49 fn label(self, lang: Lang) -> &'static str {
50 match self {
51 Health::Ok => g::t(lang, K::HealthOk),
52 Health::Lagging => g::t(lang, K::HealthLagging),
53 Health::Error => g::t(lang, K::HealthError),
54 Health::Never => g::t(lang, K::HealthNever),
55 }
56 }
57}
58
59/// Health of one subject. `cutoff` is the oldest success that still counts as current; stamps are
60/// fixed-width UTC, so a text comparison orders them.
61fn health(status: Option<&ReplicationStatus>, cutoff: &str) -> Health {
62 match status {
63 None => Health::Never,
64 Some(s) if s.last_error.is_some() => Health::Error,
65 Some(s) => match s.last_ok_at.as_deref() {
66 None => Health::Never,
67 Some(ok) if ok >= cutoff => Health::Ok,
68 Some(_) => Health::Lagging,
69 },
70 }
71}
72
73/// One line of the repos table, already formatted.
74struct RepoRow {
75 name: String,
76 health: &'static str,
77 last_ok: String,
78 error: String,
79}
80
81/// Everything the page shows, already formatted.
82struct PageData {
83 enabled: bool,
84 target: String,
85 db_health: &'static str,
86 db_last_ok: String,
87 db_last_attempt: String,
88 db_error: String,
89 interval: String,
90 healthcheck: &'static str,
91 repos: Vec<RepoRow>,
92}
93
94fn ok_text(stamp: Option<&str>, tz: &str, lang: Lang) -> String {
95 match stamp {
96 Some(stamp) => format_in_tz(stamp_unix(stamp), tz),
97 None => i18n::t(lang, Key::Never).to_owned(),
98 }
99}
100
101/// Builds the page data from the config, the status rows and the repo list.
102async fn page_data(state: &AppState, tz: &str, lang: Lang) -> forge_core::Result<PageData> {
103 let config = &state.config.replication;
104 let db_cutoff = stamp_ago(Duration::from_secs(config.db_snapshot_minutes * 60 * 2));
105 let repo_cutoff = stamp_ago(Duration::from_secs(config.reconcile_minutes * 60 * 2));
106
107 let statuses: HashMap<String, ReplicationStatus> = state
108 .store
109 .list_replication_status()
110 .await?
111 .into_iter()
112 .map(|s| (s.subject.clone(), s))
113 .collect();
114
115 let db = statuses.get(DB_SUBJECT);
116 let mut repos = Vec::new();
117 let ids = state.store.repo_ids().await?;
118 for id in &ids {
119 let status = statuses.get(id);
120 let name = match state.store.repo_by_id(id).await? {
121 Some(repo) => format!("{}/{}", repo.owner_name, repo.name),
122 None => id.clone(),
123 };
124 repos.push(RepoRow {
125 name,
126 health: health(status, &repo_cutoff).label(lang),
127 last_ok: ok_text(status.and_then(|s| s.last_ok_at.as_deref()), tz, lang),
128 error: status
129 .and_then(|s| s.last_error.clone())
130 .unwrap_or_default(),
131 });
132 }
133 // Repos deleted since their last push: their standby copy is removed at the next reconcile.
134 for status in statuses.values() {
135 if status.subject != DB_SUBJECT && !ids.contains(&status.subject) {
136 repos.push(RepoRow {
137 name: g::deleted_repo_name(lang, &status.subject),
138 health: health(Some(status), &repo_cutoff).label(lang),
139 last_ok: ok_text(status.last_ok_at.as_deref(), tz, lang),
140 error: status.last_error.clone().unwrap_or_default(),
141 });
142 }
143 }
144
145 Ok(PageData {
146 enabled: config.enabled(),
147 target: config.target.clone(),
148 db_health: health(db, &db_cutoff).label(lang),
149 db_last_ok: ok_text(db.and_then(|s| s.last_ok_at.as_deref()), tz, lang),
150 db_last_attempt: ok_text(db.and_then(|s| s.last_attempt_at.as_deref()), tz, lang),
151 db_error: db.and_then(|s| s.last_error.clone()).unwrap_or_default(),
152 interval: g::interval_line(lang, config.db_snapshot_minutes, config.reconcile_minutes),
153 healthcheck: if config.healthcheck_url.is_empty() {
154 g::t(lang, K::HealthcheckNotSet)
155 } else {
156 g::t(lang, K::HealthcheckSet)
157 },
158 repos,
159 })
160}
161
162#[component]
163async fn replication_view(
164 lang: Lang,
165 csrf: String,
166 data: PageData,
167 notice: Option<String>,
168) -> Result<impl View> {
169 Ok(view! {
170 <div data-live="/admin/replication/events">
171 <section class="page-head">
172 <h1>(g::t(lang, K::Replication))</h1>
173 <p class="muted">(g::t(lang, K::ReplicationIntro))</p>
174 </section>
175 if let Some(message) = notice {
176 <section class="card notice" role="status">
177 <p>(message.as_str())</p>
178 </section>
179 }
180 <section class="card">
181 <h2>(g::t(lang, K::Standby))</h2>
182 if data.enabled {
183 <dl class="details">
184 <dt>(g::t(lang, K::ReplicationTarget))</dt><dd><code>(data.target.as_str())</code></dd>
185 <dt>(g::t(lang, K::Interval))</dt><dd>(data.interval.as_str())</dd>
186 <dt>(g::t(lang, K::Healthcheck))</dt><dd>(data.healthcheck)</dd>
187 <dt>(g::t(lang, K::Database))</dt><dd>(data.db_health)</dd>
188 <dt>(g::t(lang, K::LastDbSnapshotShipped))</dt><dd class="small">(data.db_last_ok.as_str())</dd>
189 <dt>(g::t(lang, K::LastDbAttempt))</dt><dd class="small">(data.db_last_attempt.as_str())</dd>
190 </dl>
191 if !data.db_error.is_empty() {
192 <p class="error">(g::t(lang, K::DatabaseErrorPrefix))(data.db_error.as_str())</p>
193 }
194 } else {
195 <p>(g::t(lang, K::ReplicationOff))</p>
196 }
197 <div class="actions">
198 <form method="post" action="/admin/replication/reconcile">
199 <input type="hidden" name="csrf" value=(csrf.as_str())>
200 <button type="submit" class="primary">(g::t(lang, K::ReconcileNow))</button>
201 </form>
202 </div>
203 </section>
204 <section class="card">
205 <h2>(g::t(lang, K::Repos))</h2>
206 if data.repos.is_empty() {
207 <p class="muted">(g::t(lang, K::NoReposYet))</p>
208 } else {
209 <div class="table-wrap">
210 <table class="table queue-table">
211 <thead>
212 <tr>
213 <th>(g::t(lang, K::TableRepo))</th>
214 <th>(g::t(lang, K::TableStatus))</th>
215 <th>(g::t(lang, K::LastSuccess))</th>
216 <th>(g::t(lang, K::TableError))</th>
217 </tr>
218 </thead>
219 <tbody>
220 for row in data.repos.into_iter() {
221 <tr>
222 <td data-label=(g::t(lang, K::TableRepo))>(row.name.as_str())</td>
223 <td data-label=(g::t(lang, K::TableStatus))>(row.health)</td>
224 <td class="small" data-label=(g::t(lang, K::LastSuccess))>(row.last_ok.as_str())</td>
225 <td class="small" data-label=(g::t(lang, K::TableError))>(row.error.as_str())</td>
226 </tr>
227 }
228 </tbody>
229 </table>
230 </div>
231 }
232 </section>
233 </div>
234 })
235}
236
237/// What the replication page shows, as one string. The health labels are read at each wake, so a
238/// wake also refreshes a copy that has gone stale since the last change.
239async fn page_fingerprint(state: &AppState) -> Result<String> {
240 let data = page_data(state, "UTC", Lang::En).await?;
241 let rows: Vec<_> = data
242 .repos
243 .iter()
244 .map(|row| (&row.name, row.health, &row.last_ok, &row.error))
245 .collect();
246 Ok(format!(
247 "{}|{}|{}|{}|{}|{}|{:?}",
248 data.enabled,
249 data.db_health,
250 data.db_last_ok,
251 data.db_last_attempt,
252 data.db_error,
253 data.target,
254 rows
255 ))
256}
257
258/// The replication page's change stream. Admins only.
259#[route(GET "/admin/replication/events")]
260async fn replication_events(cx: &Cx) -> Result<Response> {
261 admin_only(cx).await?;
262 let state = app_context::<AppState>(cx).clone();
263 stream_changes(
264 cx,
265 crate::live::admin(),
266 &[Topic::AdminReplication],
267 move || {
268 let state = state.clone();
269 async move { page_fingerprint(&state).await }
270 },
271 )
272 .await
273}
274
275#[page("/admin/replication")]
276async fn replication_page(cx: &Cx) -> Result<impl View> {
277 let viewer = admin_only(cx).await?;
278 let query = query_params::<NoticeQuery>(cx)?;
279 let lang = i18n::lang(cx, Some(&viewer.0));
280 let state = app_context::<AppState>(cx);
281 let data = page_data(state, viewer.0.timezone.as_str(), lang).await?;
282 let csrf = viewer.1.csrf_token.clone();
283 let title = g::t(lang, K::Replication);
284 Ok(view! {
285 shell(title: title, viewer: Some(&viewer), replication_view(lang: lang, csrf: csrf, data: data, notice: query.notice.clone()))
286 })
287}
288
289#[derive(Deserialize)]
290struct ReconcileForm {
291 #[serde(default)]
292 csrf: String,
293}
294
295#[route(POST "/admin/replication/reconcile")]
296async fn replication_reconcile(cx: &Cx, Form(form): Form<ReconcileForm>) -> Result<Response> {
297 let viewer = admin_only(cx).await?;
298 if !check_csrf(&viewer.1, &form.csrf) {
299 return Err(forbidden().into());
300 }
301 let lang = i18n::lang(cx, Some(&viewer.0));
302 let state = app_context::<AppState>(cx);
303 let notice = match reconcile_now(cx, state, &viewer.0, lang).await {
304 Ok(()) => g::t(lang, K::ReconcileStarted).to_owned(),
305 Err(Error::Config(message)) => message,
306 Err(other) => other.to_string(),
307 };
308 let location = format!("/admin/replication?notice={}", enc(&notice));
309 Err(see_other(&location).into())
310}
311
312/// Queues a reconcile pass and audits the request. Refused when replication is not configured.
313async fn reconcile_now(
314 cx: &Cx,
315 state: &AppState,
316 user: &forge_core::User,
317 lang: Lang,
318) -> forge_core::Result<()> {
319 if !state.config.replication.enabled() {
320 return Err(Error::Config(
321 g::t(lang, K::ErrReplicationNotConfigured).to_owned(),
322 ));
323 }
324 audit::record(
325 &state.store,
326 Some(cx),
327 Actor::User(user),
328 AuditAction::ReplicationReconcileStarted,
329 Target {
330 kind: "replication",
331 id: "",
332 name: "",
333 },
334 serde_json::json!({ "trigger": "manual" }),
335 )
336 .await;
337 state.replication.request_reconcile();
338 Ok(())
339}
340
341#[cfg(test)]
342mod tests {
343 use super::*;
344 use forge_core::model::Visibility;
345 use topcoat::router::request::Request;
346 use topcoat::router::{Body, Router, to_bytes};
347
348 use crate::auth::SESSION_COOKIE;
349 use crate::test_support::{app_router, create_session, test_config, test_state};
350
351 const ADMIN_TOKEN: &str = "replication-admin-session";
352 const USER_TOKEN: &str = "replication-user-session";
353 const CSRF: &str = "replication-csrf";
354 const TARGET: &str = "sb@standby.example:/srv/forge-standby";
355
356 struct Fixture {
357 _dir: tempfile::TempDir,
358 router: Router,
359 state: AppState,
360 repo_id: String,
361 }
362
363 /// An instance with an admin, a plain user and one repo. Replication is configured when asked.
364 async fn fixture(configured: bool) -> Fixture {
365 let dir = tempfile::tempdir().expect("tempdir");
366 let data_dir = dir.path().join("data");
367 std::fs::create_dir_all(&data_dir).expect("data dir");
368 let mut state = test_state(&data_dir).await;
369 let mut config = test_config(&data_dir);
370 if configured {
371 config.replication.target = TARGET.into();
372 }
373 state.config = std::sync::Arc::new(config);
374 let admin = state
375 .store
376 .create_user("root", None, "h", true)
377 .await
378 .expect("admin");
379 let user = state
380 .store
381 .create_user("plain", None, "h", false)
382 .await
383 .expect("user");
384 create_session(&state.store, &admin.id, ADMIN_TOKEN, CSRF).await;
385 create_session(&state.store, &user.id, USER_TOKEN, CSRF).await;
386 let repo = state
387 .store
388 .create_repo(&admin.id, "demo", "", Visibility::Private, "main")
389 .await
390 .expect("repo");
391 let router = app_router(state.clone());
392 Fixture {
393 _dir: dir,
394 router,
395 state,
396 repo_id: repo.id,
397 }
398 }
399
400 async fn send(
401 router: &Router,
402 method: &str,
403 uri: &str,
404 token: Option<&str>,
405 form: Option<String>,
406 ) -> (u16, String) {
407 let mut builder = Request::builder().method(method).uri(uri);
408 if let Some(token) = token {
409 builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={token}"));
410 }
411 let body = match form {
412 Some(form) => {
413 builder = builder.header("content-type", "application/x-www-form-urlencoded");
414 Body::from(form)
415 }
416 None => Body::empty(),
417 };
418 let res = router.handle(builder.body(body).expect("request")).await;
419 let status = res.status().as_u16();
420 let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body");
421 (status, String::from_utf8_lossy(&bytes).into_owned())
422 }
423
424 #[tokio::test]
425 async fn page_and_reconcile_are_404_for_anonymous_and_non_admins() {
426 let fx = fixture(true).await;
427 let (anon, _) = send(&fx.router, "GET", "/admin/replication", None, None).await;
428 assert_eq!(anon, 404);
429 let (user, _) = send(
430 &fx.router,
431 "GET",
432 "/admin/replication",
433 Some(USER_TOKEN),
434 None,
435 )
436 .await;
437 assert_eq!(user, 404);
438 let (posted, _) = send(
439 &fx.router,
440 "POST",
441 "/admin/replication/reconcile",
442 Some(USER_TOKEN),
443 Some(format!("csrf={CSRF}")),
444 )
445 .await;
446 assert_eq!(posted, 404);
447 assert!(!fx.state.replication.take_reconcile_request());
448 }
449
450 #[tokio::test]
451 async fn page_shows_target_db_and_repo_health_without_secrets() {
452 let fx = fixture(true).await;
453 let store = &fx.state.store;
454 store
455 .record_replication_ok(DB_SUBJECT, None)
456 .await
457 .expect("db ok");
458 store
459 .record_replication_ok(&fx.repo_id, Some("abc"))
460 .await
461 .expect("repo ok");
462 store
463 .record_replication_error("gone-repo-id", "remove failed")
464 .await
465 .expect("stale");
466
467 let (status, body) = send(
468 &fx.router,
469 "GET",
470 "/admin/replication",
471 Some(ADMIN_TOKEN),
472 None,
473 )
474 .await;
475 assert_eq!(status, 200);
476 assert!(body.contains("sb@standby.example:/srv/forge-standby"));
477 assert!(body.contains("root/demo"), "repo name is shown");
478 assert!(body.contains("ok"));
479 assert!(
480 body.contains("gone-repo-id"),
481 "stale rows are shown until cleaned"
482 );
483 assert!(body.contains("pending cleanup"));
484 assert!(body.contains("Reconcile now"));
485 }
486
487 #[tokio::test]
488 async fn unconfigured_page_says_so_and_reconcile_is_refused() {
489 let fx = fixture(false).await;
490 let (status, body) = send(
491 &fx.router,
492 "GET",
493 "/admin/replication",
494 Some(ADMIN_TOKEN),
495 None,
496 )
497 .await;
498 assert_eq!(status, 200);
499 assert!(body.contains("Replication is off"));
500
501 let (status, _) = send(
502 &fx.router,
503 "POST",
504 "/admin/replication/reconcile",
505 Some(ADMIN_TOKEN),
506 Some(format!("csrf={CSRF}")),
507 )
508 .await;
509 assert_eq!(status, 303);
510 assert!(!fx.state.replication.take_reconcile_request());
511 let audit = fx
512 .state
513 .store
514 .list_audit(&Default::default(), None, 10)
515 .await
516 .expect("audit");
517 assert!(
518 !audit
519 .iter()
520 .any(|e| e.action == AuditAction::ReplicationReconcileStarted)
521 );
522 }
523
524 #[tokio::test]
525 async fn reconcile_needs_csrf_and_is_audited() {
526 let fx = fixture(true).await;
527 let (bad, _) = send(
528 &fx.router,
529 "POST",
530 "/admin/replication/reconcile",
531 Some(ADMIN_TOKEN),
532 Some("csrf=wrong".into()),
533 )
534 .await;
535 assert_eq!(bad, 403);
536 assert!(!fx.state.replication.take_reconcile_request());
537
538 let (status, _) = send(
539 &fx.router,
540 "POST",
541 "/admin/replication/reconcile",
542 Some(ADMIN_TOKEN),
543 Some(format!("csrf={CSRF}")),
544 )
545 .await;
546 assert_eq!(status, 303);
547 assert!(fx.state.replication.take_reconcile_request());
548 let audit = fx
549 .state
550 .store
551 .list_audit(&Default::default(), None, 10)
552 .await
553 .expect("audit");
554 assert!(
555 audit
556 .iter()
557 .any(|e| e.action == AuditAction::ReplicationReconcileStarted),
558 "the request is audited"
559 );
560 }
561
562 #[test]
563 fn health_reads_errors_before_age() {
564 let cutoff = "2026-01-01T00:00:00.000000000Z";
565 let fresh = ReplicationStatus {
566 subject: "r".into(),
567 last_ok_at: Some("2026-06-01T00:00:00.000000000Z".into()),
568 last_error: None,
569 last_attempt_at: None,
570 refs_sha256: None,
571 };
572 assert_eq!(health(Some(&fresh), cutoff), Health::Ok);
573 let old = ReplicationStatus {
574 last_ok_at: Some("2025-06-01T00:00:00.000000000Z".into()),
575 ..fresh.clone()
576 };
577 assert_eq!(health(Some(&old), cutoff), Health::Lagging);
578 let failing = ReplicationStatus {
579 last_error: Some("boom".into()),
580 ..fresh.clone()
581 };
582 assert_eq!(health(Some(&failing), cutoff), Health::Error);
583 assert_eq!(health(None, cutoff), Health::Never);
584 }
585}