From 18fc0184aad64464f4de866f22110c0a01433b54 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:11:08 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20backup=20outcome=20recorded?= =?UTF-8?q?=20and=20shown,=20with=20a=20warning=20when=20backups=20are=20o?= =?UTF-8?q?verdue?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/in-web/src/backup.rs | 80 ++++++++++++++++++++++++++++++-- crates/in-web/src/i18n/admin.rs | 28 +++++++++++ crates/in-web/src/pages/admin.rs | 67 +++++++++++++++++++++----- crates/in-web/src/views/mod.rs | 6 +++ docs/architecture.md | 8 +++- style/_components.scss | 8 ++++ 6 files changed, 182 insertions(+), 15 deletions(-) diff --git a/crates/in-web/src/backup.rs b/crates/in-web/src/backup.rs index e7bdb7e..2787d28 100644 --- a/crates/in-web/src/backup.rs +++ b/crates/in-web/src/backup.rs @@ -7,13 +7,19 @@ //! A failed run is logged and the next one is tried at the next interval; a failed ping is logged and nothing //! else. The ping URL carries a secret, so it is never logged. The worker is not started without a `[backup]` //! table. +//! +//! After every run, scheduled or manual, the outcome is recorded in the `settings` table (see [`record_outcome`]) +//! so the admin page can show the last success, the last attempt and the error of a failed run. The recorded +//! error is short text, never the ping URL. use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use in_core::backup; use in_core::config::Backup; -use in_core::time::now_stamp; +use in_core::error::Error; +use in_core::store::Store; +use in_core::time::{now_stamp, stamp_before}; use tokio::sync::{Notify, watch}; use crate::state::AppState; @@ -21,6 +27,18 @@ use crate::state::AppState; /// How long the dead-man ping may take. pub const PING_TIMEOUT: Duration = Duration::from_secs(10); +/// Settings key: when a run was last attempted (a stamp). Written after every run. +pub const LAST_ATTEMPT_AT: &str = "backup.last_attempt_at"; +/// Settings key: when a run last succeeded (a stamp). +pub const LAST_SUCCESS_AT: &str = "backup.last_success_at"; +/// Settings key: the short error of the latest run. Present only while the latest run failed. +pub const LAST_ERROR: &str = "backup.last_error"; +/// The longest error text that is stored, in characters. Long errors are cut so the admin page stays short. +const ERROR_CHARS: usize = 200; +/// The shortest time without a successful backup before the admin page warns: two days, in seconds. The +/// limit is never shorter than two backup intervals (see [`is_stale`]). +pub const STALE_AFTER: Duration = Duration::from_secs(2 * 24 * 60 * 60); + /// Asks the backup worker for a run now. At most one run is pending or running: a request made while one is /// pending or running starts nothing. #[derive(Default)] @@ -70,6 +88,46 @@ async fn run_once(state: &AppState, config: &Backup) -> in_core::error::Result String { + let text = error.to_string(); + let line = text.lines().next().unwrap_or_default(); + line.chars() + .filter(|c| !c.is_control()) + .take(ERROR_CHARS) + .collect() +} + +/// Stores the outcome of one run: the attempt time always; on success the success time and no error; on +/// failure the short error. A store failure is logged and never fails the run. +async fn record_outcome(store: &Store, outcome: &in_core::error::Result) { + let now = now_stamp(); + let recorded: in_core::error::Result<()> = async { + store.set_setting(LAST_ATTEMPT_AT, &now).await?; + match outcome { + Ok(_) => { + store.set_setting(LAST_SUCCESS_AT, &now).await?; + store.clear_setting(LAST_ERROR).await + } + Err(error) => store.set_setting(LAST_ERROR, &short_error(error)).await, + } + } + .await; + if let Err(error) = recorded { + tracing::error!(error = %error, "backup: the outcome was not recorded"); + } +} + +/// True when there is no successful backup within the limit: [`STALE_AFTER`] or two backup intervals, +/// whichever is longer, so a weekly schedule is not always overdue. The stamps have a fixed width, so +/// comparing them as text compares their times. +pub fn is_stale(last_success: Option<&str>, interval_hours: u32) -> bool { + let interval = Duration::from_secs(u64::from(interval_hours) * 2 * 60 * 60); + let limit = STALE_AFTER.max(interval); + last_success.is_none_or(|stamp| stamp < stamp_before(limit).as_str()) +} + /// Pings the dead-man URL once. Only failures are logged, and the URL itself never is. async fn ping(url: &str) { let client = match reqwest::Client::builder().timeout(PING_TIMEOUT).build() { @@ -97,7 +155,9 @@ pub async fn run(state: AppState, mut stop: watch::Receiver) { let every = Duration::from_secs(u64::from(config.interval_hours) * 60 * 60); loop { state.backup.begin(); - match run_once(&state, &config).await { + let outcome = run_once(&state, &config).await; + record_outcome(&state.store, &outcome).await; + match outcome { Ok(_) => { if let Some(url) = &config.healthcheck_url { ping(url).await; @@ -116,7 +176,11 @@ pub async fn run(state: AppState, mut stop: watch::Receiver) { #[cfg(test)] mod tests { - use super::BackupTrigger; + use std::time::Duration; + + use in_core::time::{now_stamp, stamp_before}; + + use super::{BackupTrigger, is_stale}; #[test] fn a_second_request_while_one_is_pending_starts_nothing() { @@ -128,4 +192,14 @@ mod tests { trigger.finish(); assert!(trigger.request()); } + + #[test] + fn no_success_within_the_limit_is_stale() { + assert!(is_stale(None, 24)); + assert!(!is_stale(Some(&now_stamp()), 24)); + // Three days ago: stale on a daily schedule, not on a weekly one (limit two weeks). + let three_days = stamp_before(Duration::from_secs(3 * 86_400)); + assert!(is_stale(Some(&three_days), 24)); + assert!(!is_stale(Some(&three_days), 168)); + } } diff --git a/crates/in-web/src/i18n/admin.rs b/crates/in-web/src/i18n/admin.rs index 5435e2e..630f788 100644 --- a/crates/in-web/src/i18n/admin.rs +++ b/crates/in-web/src/i18n/admin.rs @@ -148,6 +148,14 @@ pub enum AK { NoticeBackup, /// Refusal: backups are off, so there is nothing to start. RefusalBackupOff, + /// Label: when the last successful backup ran. + BackupLast, + /// Label: when the last attempt ran, successful or not. + BackupAttempt, + /// Shown in place of a time when there is none yet. + BackupNever, + /// Warning: backups are on, but none has succeeded within the limit (see `backup::is_stale`). + BackupStale, } /// The text of `key` in `lang`. @@ -299,6 +307,18 @@ pub fn a(lang: Lang, key: AK) -> &'static str { } (AK::NoticeBackup, Lang::En) => "Backup started. It runs in the background.", (AK::NoticeBackup, Lang::Tr) => "Yedekleme başlatıldı. Arka planda çalışır.", + (AK::BackupLast, Lang::En) => "Last successful backup", + (AK::BackupLast, Lang::Tr) => "Son başarılı yedekleme", + (AK::BackupAttempt, Lang::En) => "Last attempt", + (AK::BackupAttempt, Lang::Tr) => "Son deneme", + (AK::BackupNever, Lang::En) => "never", + (AK::BackupNever, Lang::Tr) => "henüz yok", + (AK::BackupStale, Lang::En) => { + "No successful backup for longer than expected. Check the backup directory and the last attempt." + } + (AK::BackupStale, Lang::Tr) => { + "Beklenenden uzun süredir başarılı yedekleme yok. Yedek dizinini ve son denemeyi kontrol edin." + } (AK::RefusalBackupOff, Lang::En) => { "Backups are off, so there is nothing to start. Set [backup] dir first." } @@ -316,6 +336,14 @@ pub fn backup_schedule(lang: Lang, hours: u32, keep: u32) -> String { } } +/// The alert line of a failed latest run, with the short error the worker recorded. +pub fn backup_failed(lang: Lang, error: &str) -> String { + match lang { + Lang::En => format!("The last backup failed: {error}"), + Lang::Tr => format!("Son yedekleme başarısız oldu: {error}"), + } +} + /// The sentence for a refusal word. Range refusals (any word ending `_range`) get their own text; backups /// that are off get theirs; anything else gets the generic one. pub fn refusal(lang: Lang, word: &str) -> &'static str { diff --git a/crates/in-web/src/pages/admin.rs b/crates/in-web/src/pages/admin.rs index 8e87132..5b21379 100644 --- a/crates/in-web/src/pages/admin.rs +++ b/crates/in-web/src/pages/admin.rs @@ -2,7 +2,8 @@ //! claim, stored as `members.is_admin`) sees it. Anyone else gets `404`, and so does a write from them. //! //! The page shows: health (the database and the blob store answer), the storage backend and its free space -//! or reachability, the backup schedule with a button that asks for a backup now, the base URL, every person +//! or reachability, the backup schedule with the last success and attempt, an alert for a failed latest run, +//! a warning when no success is recent, and a button that asks for a backup now, the base URL, every person //! with their quota, every service with its usage and quota, the defaults with the layer each value comes from //! (UI, file or built-in default), and the audit log with keyset paging and filters. //! @@ -35,15 +36,16 @@ use topcoat::view::{View, component, view}; use crate::audit::{self, Entry}; use crate::auth::{Viewer, require_admin, require_admin_csrf}; +use crate::backup::{LAST_ATTEMPT_AT, LAST_ERROR, LAST_SUCCESS_AT, is_stale}; use crate::health::{probe_blobs, probe_database}; use crate::i18n::Lang; -use crate::i18n::admin::{AK, a, backup_schedule, notice, refusal}; +use crate::i18n::admin::{AK, a, backup_failed, backup_schedule, notice, refusal}; use crate::live::{Topic, stream_changes}; use crate::oidc::percent_encode; use crate::pages::drive::{viewer_lang, with_param}; use crate::state::AppState; use crate::views::drive::{size_text, stamp_text}; -use crate::views::{ViewerInfo, alert, notice as flash_notice, shell}; +use crate::views::{ViewerInfo, alert, notice as flash_notice, shell, warning}; /// One mebibyte, the unit of the admin's byte fields. const MIB: i64 = 1024 * 1024; @@ -149,8 +151,8 @@ pub struct BackupForm { pub csrf: String, } -/// What the backups section shows: where the sets go and how often a run happens. `None` when the -/// configuration has no `[backup]` table. +/// What the backups section shows: where the sets go, how often a run happens, and the outcome the worker +/// recorded. `None` when the configuration has no `[backup]` table. #[derive(Debug, Clone)] pub struct BackupStatus { /// The directory that receives the sets. @@ -159,6 +161,35 @@ pub struct BackupStatus { pub interval_hours: u32, /// Sets kept. pub keep: u32, + /// When a run was last attempted, if one ran. + pub last_attempt: Option, + /// When a run last succeeded, if one did. + pub last_success: Option, + /// The short error of the latest run, present only while that run failed. + pub last_error: Option, + /// True when no success is recent enough (see `backup::is_stale`). + pub stale: bool, +} + +/// The backups section's data: the configuration and what the worker recorded. `None` when backups are off. +async fn backup_status(state: &AppState) -> Result> { + let Some(config) = state.config.backup.as_ref() else { + return Ok(None); + }; + let last_success = state.store.get_setting(LAST_SUCCESS_AT).await?; + Ok(Some(BackupStatus { + dir: config.dir.display().to_string(), + interval_hours: config.interval_hours, + keep: config.keep, + last_attempt: state.store.get_setting(LAST_ATTEMPT_AT).await?, + stale: is_stale(last_success.as_deref(), config.interval_hours), + last_success, + last_error: state + .store + .get_setting(LAST_ERROR) + .await? + .filter(|error| !error.is_empty()), + })) } /// Whether a field's form unit is MiB. @@ -410,7 +441,8 @@ async fn storage_section(lang: Lang, status: &StorageStatus) -> Result

(a(lang, AK::Backups))

@@ -429,7 +470,15 @@ async fn backup_section(
  • (a(lang, AK::BackupDir)) ": " (dir.as_str())
  • (schedule.as_str())
  • +
  • (a(lang, AK::BackupLast)) ": " (last_success.as_str())
  • +
  • (a(lang, AK::BackupAttempt)) ": " (last_attempt.as_str())
+ if let Some(text) = failed.as_deref() { + alert(message: text) + } + if stale { + warning(message: a(lang, AK::BackupStale)) + }
@@ -734,11 +783,7 @@ async fn admin_page(cx: &Cx) -> Result { } let defaults = default_rows(state).await?; let storage = storage_status(state).await; - let backups = state.config.backup.as_ref().map(|config| BackupStatus { - dir: config.dir.display().to_string(), - interval_hours: config.interval_hours, - keep: config.keep, - }); + let backups = backup_status(state).await?; let probes = probe_all(state).await; let page = state .store diff --git a/crates/in-web/src/views/mod.rs b/crates/in-web/src/views/mod.rs index b06b04f..f235bdc 100644 --- a/crates/in-web/src/views/mod.rs +++ b/crates/in-web/src/views/mod.rs @@ -159,6 +159,12 @@ pub async fn notice(message: &str) -> Result { Ok(view! {
(message)
}) } +/// Something to look at that is not a failure yet, such as a state that has gone stale. +#[component] +pub async fn warning(message: &str) -> Result { + Ok(view! {
(message)
}) +} + /// A section with nothing in it yet: a title, then what to do next. #[component] pub async fn empty_state(title: &str, #[default] child: Child<'_>) -> Result { diff --git a/docs/architecture.md b/docs/architecture.md index 8e39762..7301db9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -143,7 +143,7 @@ The sweeper removes unreferenced blobs older than 24 h. | `GET /links`, `POST /links`, `/links/{id}/revoke`, `/links/{id}/remint` | my share links | | `GET/POST /s/{token}` (anonymous) | public share page, folder browsing, password gate, download, media, thumbs | | `GET /settings` + POST | preferences (theme; language follows `im` unless overridden), storage usage | -| `GET /admin` + POSTs (instance admin) | people with quotas (set quota), services with quotas, default quotas, storage backend status, backup schedule and `POST /admin/backup` (back up now), base URL, audit log, health | +| `GET /admin` + POSTs (instance admin) | people with quotas (set quota), services with quotas, default quotas, storage backend status, backup schedule, last success and attempt, the latest error and the stale warning, and `POST /admin/backup` (back up now), base URL, audit log, health | | `GET /avatar/{sub}` | photo proxy with disk cache (contracts.md 3.2) | | `GET /auth/login`, `/auth/callback`, `POST /auth/logout`, `POST /auth/backchannel-logout` | OIDC client | | `GET /-/alive`, live streams, `/healthz`, `/assets/*` | | @@ -240,6 +240,12 @@ and has no sessions. - **backup** (optional): snapshot + blob tree manifest, HMAC-SHA256 over the manifest (`manifest.mac`, keyed from `in.key`, checked before a restore parses anything), keep N, dead-man pings. The worker also runs when the admin page asks (`BackupTrigger`: one busy flag and a `Notify` the worker waits on); at most one run is pending or running. + After every run, scheduled or manual, the outcome is written to `settings` (no migration): `backup.last_attempt_at` + always, `backup.last_success_at` on success (and the error is cleared), `backup.last_error` on failure (the first + line of the error, control characters removed, at most 200 characters; never the ping URL). The admin Backups + section shows the last success and the last attempt, an alert while the latest run failed, and a warning when + backups are on and the last success is older than the limit: `max(2 days, 2 × interval_hours)` + (`backup::is_stale`). `/healthz` does not show any of this. --- diff --git a/style/_components.scss b/style/_components.scss index 23322fb..a68d3d2 100644 --- a/style/_components.scss +++ b/style/_components.scss @@ -163,6 +163,14 @@ textarea::placeholder { border-color: var(--accent-soft); } +.warning { + padding: var(--space-3) var(--space-4); + border-radius: var(--radius-sm); + border: 1px solid var(--warn); + background: var(--warn-soft); + color: var(--warn); +} + // --- Tables and badges ------------------------------------------------------------------------ .table-wrap {