From 7f1e12a612d723e9b21131dc0be5230893aa3007 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 14:02:35 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20back=20up=20now=20from=20th?= =?UTF-8?q?e=20admin=20health=20page=20while=20the=20server=20runs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 10 +++- crates/im-core/src/model.rs | 3 ++ crates/im-web/src/backups.rs | 69 +++++++++++++++++++++++-- crates/im-web/src/boot.rs | 3 ++ crates/im-web/src/i18n/admin.rs | 9 ++++ crates/im-web/src/pages/admin/health.rs | 57 ++++++++++++++++++-- crates/im-web/src/pages/admin/mod.rs | 2 + crates/im-web/src/state.rs | 3 ++ docs/architecture.md | 6 ++- 9 files changed, 152 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 06cbbee..614fe98 100644 --- a/README.md +++ b/README.md @@ -105,8 +105,16 @@ every file. `interval_hours` sets the schedule and `keep` how many sets are kept only when they are real sets with a manifest. An optional `healthcheck_url` is pinged after each run, with the failure URL on error (a dead-man check). +While the server runs, an administrator can start a backup from the admin Health page with the "Back up now" +button (it appears when `[backup] dir` is set). The running backup worker writes the set in the background, and +the page shows the last success or error once the run ends. Only one backup runs at a time: a press while one is +pending or running starts nothing. The button is audited. + +`im backup now` writes a set from the command line, but only while the server is stopped, because the command +needs the data directory's lock. + ```sh -im --config /etc/im/im.toml backup now # write a set now +im --config /etc/im/im.toml backup now # write a set now (server stopped only) im --config /etc/im/im.toml fsck # check the database and the signing keys im --config /etc/im/im.toml restore --from # verify, then restore ``` diff --git a/crates/im-core/src/model.rs b/crates/im-core/src/model.rs index 200e83d..6b3621e 100644 --- a/crates/im-core/src/model.rs +++ b/crates/im-core/src/model.rs @@ -198,6 +198,8 @@ pub enum AuditAction { KeyRetired, /// A backup set was written (scheduled, or by `im backup now`). BackupWritten, + /// An administrator asked for a backup now from the admin health page. + BackupRequested, } impl AuditAction { @@ -247,6 +249,7 @@ impl AuditAction { AuditAction::KeyRotated => "keys.rotated", AuditAction::KeyRetired => "keys.retired", AuditAction::BackupWritten => "backup.written", + AuditAction::BackupRequested => "backup.requested", } } } diff --git a/crates/im-web/src/backups.rs b/crates/im-web/src/backups.rs index ca0d887..2892d96 100644 --- a/crates/im-web/src/backups.rs +++ b/crates/im-web/src/backups.rs @@ -5,15 +5,21 @@ //! last attempt is at least `interval_hours` old. The attempt time is recorded before the run, so a failing //! run is retried at the interval and not every minute. The same [`run_and_record`] serves `im backup now`. //! +//! The admin health page asks for a run now through [`BackupTrigger`]. At most one run is pending or running: +//! a request made meanwhile starts nothing. `im backup now` is still the way to back up while the server is +//! stopped, because it cannot run beside the server's data directory lock. +//! //! The dead-man URL gets `/start` before a run, `` after a good run and `/fail` after a bad //! one. A ping that fails is logged and never fails the backup. +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use im_core::backup; use im_core::config::Config; use im_core::store::Store; use im_core::time::{now_stamp, unix_now, unix_seconds}; +use tokio::sync::Notify; use tokio::task::JoinHandle; use crate::backchannel::http_client; @@ -23,6 +29,43 @@ use crate::state::AppState; /// How often the worker checks whether a run is due. const TICK: Duration = Duration::from_secs(60); +/// Asks the backup worker for a run now. A run is pending or running at most once: a request made while one is +/// pending or running starts nothing. +#[derive(Default)] +pub struct BackupTrigger { + /// True from a request, or from the start of a due scheduled run, until that run ends. + busy: AtomicBool, + /// Wakes the worker out of its tick when a request arrives. + wake: Notify, +} + +impl BackupTrigger { + /// Asks for a run now. Returns true when this request starts one, false when one is already pending or + /// running. + pub fn request(&self) -> bool { + if self.busy.swap(true, Ordering::AcqRel) { + return false; + } + self.wake.notify_one(); + true + } + + /// True when a run was requested and has not started yet. + fn requested(&self) -> bool { + self.busy.load(Ordering::Acquire) + } + + /// Marks a run as running, so requests made meanwhile start nothing. + fn begin(&self) { + self.busy.store(true, Ordering::Release); + } + + /// Marks the run as ended. A request made after this starts a new run. + fn finish(&self) { + self.busy.store(false, Ordering::Release); + } +} + /// Settings key: when a run was last attempted (a stamp). pub const LAST_ATTEMPT: &str = "backup.last_attempt"; /// Settings key: when a run last succeeded (a stamp). @@ -41,12 +84,14 @@ pub fn spawn(state: AppState) -> Option> { loop { tokio::select! { () = tokio::time::sleep(TICK) => {} + () = state.backup.wake.notified() => {} () = stopped(&mut stop) => break, } - if due(&state.store, &state.config).await - && let Err(error) = run_and_record(&state.config, &state.store, &state.key).await - { - tracing::error!(error = %error, "scheduled backup failed"); + if state.backup.requested() || due(&state.store, &state.config).await { + state.backup.begin(); + // `run_and_record` logs and records its own failure, so the result is not needed here. + let _ = run_and_record(&state.config, &state.store, &state.key).await; + state.backup.finish(); } } })) @@ -134,3 +179,19 @@ async fn ping(http: &reqwest::Client, url: &str) { Err(error) => tracing::warn!(error = %error, "dead-man ping failed"), } } + +#[cfg(test)] +mod tests { + use super::BackupTrigger; + + #[test] + fn a_second_request_while_one_is_pending_starts_nothing() { + let trigger = BackupTrigger::default(); + assert!(trigger.request()); + assert!(!trigger.request()); + trigger.begin(); + assert!(!trigger.request()); + trigger.finish(); + assert!(trigger.request()); + } +} diff --git a/crates/im-web/src/boot.rs b/crates/im-web/src/boot.rs index bd7a64b..f2ac1fb 100644 --- a/crates/im-web/src/boot.rs +++ b/crates/im-web/src/boot.rs @@ -22,6 +22,7 @@ use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService use crate::api::directory::StreamSlots; use crate::backchannel; +use crate::backups::BackupTrigger; use crate::live::{LiveHub, MAX_ANONYMOUS_STREAMS}; use crate::mail; use crate::oidc::signing; @@ -162,6 +163,7 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result { store, key: Arc::new(key), live: Arc::new(LiveHub::default()), + backup: Arc::new(BackupTrigger::default()), throttle: Arc::new(Throttle::default()), photo_uploads: Arc::new(Throttle::photo_uploads()), email_changes: Arc::new(Throttle::email_changes()), @@ -286,6 +288,7 @@ mod tests { store, key: Arc::new(key), live: Arc::new(LiveHub::default()), + backup: Arc::new(BackupTrigger::default()), throttle: Arc::new(Throttle::default()), photo_uploads: Arc::new(Throttle::photo_uploads()), email_changes: Arc::new(Throttle::email_changes()), diff --git a/crates/im-web/src/i18n/admin.rs b/crates/im-web/src/i18n/admin.rs index d7f23b3..6142dd6 100644 --- a/crates/im-web/src/i18n/admin.rs +++ b/crates/im-web/src/i18n/admin.rs @@ -228,6 +228,9 @@ pub enum A { HealthBackupLast, HealthBackupError, HealthBackupOff, + BackupNow, + NoticeBackupStarted, + ErrBackupOff, HealthUsers, HealthAdmins, HealthBytes, @@ -656,6 +659,12 @@ fn pair(key: A) -> (&'static str, &'static str) { "Backups are off. Set [backup] dir to turn them on.", "Yedekleme kapalı. Açmak için [backup] dir ayarlayın.", ), + A::BackupNow => ("Back up now", "Şimdi yedekle"), + A::NoticeBackupStarted => ("Backup started", "Yedekleme başlatıldı"), + A::ErrBackupOff => ( + "Backups are off, so there is nothing to start. Set [backup] dir first.", + "Yedekleme kapalı, başlatılacak bir şey yok. Önce [backup] dir ayarlayın.", + ), A::HealthUsers => ("Accounts", "Hesaplar"), A::HealthAdmins => ("Enabled administrators", "Etkin yöneticiler"), A::HealthBytes => ("Database size", "Veritabanı boyutu"), diff --git a/crates/im-web/src/pages/admin/health.rs b/crates/im-web/src/pages/admin/health.rs index d66f700..8bec0ab 100644 --- a/crates/im-web/src/pages/admin/health.rs +++ b/crates/im-web/src/pages/admin/health.rs @@ -2,22 +2,42 @@ //! and the account counts. Read only; nothing here changes anything. //! //! A service shows the answer of its last health probe, or "not checked" before the first one. +//! +//! When backups are on, the backups section has a "Back up now" button (`POST /admin/health/backup`). It asks the +//! running backup worker for one run, and redirects back with a notice; the run itself happens in the background, +//! and the last outcome shows here once it ends. Only one run is pending or running at a time. +use im_core::model::AuditAction; +use serde::Deserialize; +use serde_json::json; use topcoat::Result; use topcoat::context::{Cx, app_context}; -use topcoat::router::page; +use topcoat::router::content::Form; +use topcoat::router::error::SeeOther; +use topcoat::router::{page, route}; use topcoat::view::{View, component, view}; -use crate::auth::require_admin; +use crate::audit::{Actor, record}; +use crate::auth::{require_admin, require_admin_csrf}; use crate::i18n::Lang; use crate::i18n::admin::{A, text}; -use crate::pages::admin::{Tab, frame_info, tabs}; +use crate::pages::admin::{ + FlashQuery, Tab, action_button, done, error_text, flash_messages, frame_info, notice_text, + refused, tabs, +}; use crate::state::AppState; use crate::views::{ViewerInfo, shell}; +/// The form of the backup button: only the CSRF token. +#[derive(Deserialize, Default)] +struct CsrfForm { + #[serde(default)] + csrf: String, +} + /// `GET /admin/health`. #[page("/admin/health")] -async fn health_page(cx: &Cx) -> Result { +async fn health_page(cx: &Cx, Form(query): Form) -> Result { let viewer = require_admin(cx).await?; let state = app_context::(cx); let (lang, info) = frame_info(cx, &viewer); @@ -40,6 +60,9 @@ async fn health_page(cx: &Cx) -> Result { cx, lang, info, + viewer.session.csrf_token.clone(), + notice_text(lang, &query.notice).map(str::to_owned), + error_text(lang, &query.error).map(str::to_owned), services .into_iter() .map(|service| ServiceRow { @@ -56,6 +79,27 @@ async fn health_page(cx: &Cx) -> Result { )) } +/// `POST /admin/health/backup`: asks the backup worker for a backup now. Refused when backups are off. A request +/// made while a run is pending or running starts nothing, and gets the same notice. +#[route(POST "/admin/health/backup")] +async fn back_up_now(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_admin_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + if !state.config.backup.enabled() { + return Ok(refused("/admin/health", "backup-off")); + } + let started = state.backup.request(); + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::BackupRequested, + None, + json!({ "started": started }), + ) + .await; + Ok(done("/admin/health", "backup-started")) +} + /// The backup settings as the page reads them. struct Backups { last_success: Option, @@ -75,6 +119,9 @@ fn health_view( cx: &Cx, lang: Lang, info: ViewerInfo, + csrf: String, + success: Option, + problem: Option, services: Vec, outbox: Vec<(String, i64)>, users: u64, @@ -88,6 +135,7 @@ fn health_view(

(text(lang, A::HealthTitle))

(text(lang, A::HealthIntro))

+ flash_messages(success: success, problem: problem)

(text(lang, A::HealthServices))

if services.is_empty() {

(text(lang, A::NoServices))

@@ -116,6 +164,7 @@ fn health_view(
(text(lang, A::HealthBackupError))
(error)
} + action_button(action: "/admin/health/backup".to_owned(), csrf: csrf, label: text(lang, A::BackupNow), class: "button primary", on: "") } else {

(text(lang, A::HealthBackupOff))

} diff --git a/crates/im-web/src/pages/admin/mod.rs b/crates/im-web/src/pages/admin/mod.rs index 195cfe8..3358c24 100644 --- a/crates/im-web/src/pages/admin/mod.rs +++ b/crates/im-web/src/pages/admin/mod.rs @@ -120,6 +120,7 @@ pub fn notice_text(lang: Lang, code: &str) -> Option<&'static str> { "key-retired" => A::NoticeKeyRetired, "file-value" => A::NoticeFileValue, "message-sent" => A::NoticeMessageSent, + "backup-started" => A::NoticeBackupStarted, _ => return None, }; Some(text(lang, key)) @@ -142,6 +143,7 @@ pub fn error_text(lang: Lang, code: &str) -> Option<&'static str> { "message-email" => A::ErrMessageEmailInvalid, "rate-limited" => A::ErrMessageRateLimited, "key-current" => A::ErrKeyNotRetirable, + "backup-off" => A::ErrBackupOff, "invite-gone" => A::ErrInviteGone, "no-client" => A::ErrNoSuchClient, "settings" => A::ErrSettingsInvalid, diff --git a/crates/im-web/src/state.rs b/crates/im-web/src/state.rs index d032876..8ac2b8f 100644 --- a/crates/im-web/src/state.rs +++ b/crates/im-web/src/state.rs @@ -7,6 +7,7 @@ use im_core::store::Store; use tokio::sync::{Semaphore, watch}; use crate::api::directory::StreamSlots; +use crate::backups::BackupTrigger; use crate::live::LiveHub; use crate::throttle::Throttle; @@ -25,6 +26,8 @@ pub struct AppState { pub key: Arc<[u8; 32]>, /// The change counters of the live pages. pub live: Arc, + /// Asks the backup worker for a run now (the admin health page). Shared with the worker. + pub backup: Arc, /// Failed sign-in and second-factor counters. pub throttle: Arc, /// Profile photo uploads per account, one hour window (see `throttle::PHOTO_UPLOAD_LIMIT`). diff --git a/docs/architecture.md b/docs/architecture.md index b0f679e..6603dee 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -180,6 +180,7 @@ Files beside the DB in `data_dir`: `im.key`, `photos/` (0600, written b | `GET /admin/keys` + POST rotate | admin | signing keys and their state | | `GET /admin/audit` | admin | filters (action, actor, target, date range), keyset paging | | `GET /admin/health` | admin | services health, outboxes, disk, DB size, last backup | +| `POST /admin/health/backup` | admin | "Back up now": asks the backup worker for one run (ignored while one is pending or running); audited; 303 back with a notice | | `GET /photo/{id}` | user | photo bytes or initials SVG | | `GET /-/alive`, `GET /.../events` | per page | live streams | | `GET /healthz`, `GET /assets/*` | anyone | | @@ -262,7 +263,10 @@ in the store as single conditional statements so they cannot race. sent mail older than 30 days, failed and abandoned mail older than 30 days, back-channel deliveries finished more than 7 days ago, and audit entries older than 365 days. - **backup** (optional, `[backup] dir`): `VACUUM INTO` snapshot + photos + manifest on an interval, keeps N, - pings a dead-man URL (`/start`, success, `/fail`). + pings a dead-man URL (`/start`, success, `/fail`). It also wakes on a request from the admin health page + (`BackupTrigger` on `AppState`: an atomic "pending or running" flag plus a `Notify`). At most one run is pending + or running; a request meanwhile starts nothing. `im backup now` runs the same code only while the server is + stopped, because it needs the data directory lock. ---