diff --git a/crates/iz-web/src/backup.rs b/crates/iz-web/src/backup.rs index 89a5676..476c3b9 100644 --- a/crates/iz-web/src/backup.rs +++ b/crates/iz-web/src/backup.rs @@ -12,18 +12,24 @@ //! The admin settings page can ask for a run now through [`BackupTrigger`]. At most one run is pending or //! running: a request made meanwhile starts nothing. Scheduled and requested runs both hold the busy flag, so //! they never overlap. +//! +//! Every run records its outcome in the `settings` table (the attempt time, the last success, and the error of +//! the latest attempt), so a failing backup is visible on the Backups card. [`status`] reads it back and +//! [`is_stale`] says when no success is recent enough to warn about. use std::os::unix::fs::DirBuilderExt; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; -use iz_core::clock::stamp_of; +use iz_core::clock::{stamp_of, timestamp_of}; use iz_core::config::BackupConfig; use iz_core::manifest::{self, MANIFEST_NAME}; use iz_core::staging::{ATTACHMENTS_DIR, blob_path}; use iz_core::store::{Store, new_id}; +use iz_core::time::now_stamp; use iz_core::{Error, Result}; +use jiff::Timestamp; use tokio::sync::{Notify, watch}; use crate::state::AppState; @@ -71,6 +77,61 @@ const SET_STAMP_FORMAT: &str = "%Y%m%dT%H%M%SZ"; /// Length of a set's directory name, which is the stamp format above. const SET_NAME_LEN: usize = 16; +/// Settings key: when a run was last attempted (a UTC stamp). +pub const LAST_ATTEMPT_SETTING: &str = "backup_last_attempt"; +/// Settings key: when a run last succeeded (a UTC stamp). Never cleared, so the card shows the last good set. +pub const LAST_SUCCESS_SETTING: &str = "backup_last_success"; +/// Settings key: the text of the error of the latest attempt. Empty after a success. +pub const LAST_ERROR_SETTING: &str = "backup_last_error"; +/// Time without a success after which the settings page warns. Reason: two days lets one scheduled run be +/// missed without a warning, and a longer gap means the backups are not happening. +const STALE_AFTER: Duration = Duration::from_secs(2 * 24 * 3600); +/// Longest error text kept, in characters. Reason: the settings page shows it on one line. +const ERROR_TEXT_MAX: usize = 200; + +/// The recorded outcome of the backup runs, as the settings page reads it. Stamps are UTC; `None` when no +/// value was recorded. +#[derive(Debug, Clone, Default)] +pub struct BackupStatus { + /// When the latest attempt started. + pub last_attempt: Option, + /// When the last successful run finished. + pub last_success: Option, + /// The text of the error of the latest attempt. `None` when that attempt succeeded. + pub last_error: Option, +} + +/// Reads the recorded outcome. Empty values count as not recorded. +pub async fn status(store: &Store) -> Result { + Ok(BackupStatus { + last_attempt: store + .get_setting(LAST_ATTEMPT_SETTING) + .await? + .filter(|value| !value.is_empty()), + last_success: store + .get_setting(LAST_SUCCESS_SETTING) + .await? + .filter(|value| !value.is_empty()), + last_error: store + .get_setting(LAST_ERROR_SETTING) + .await? + .filter(|value| !value.is_empty()), + }) +} + +/// Whether the backups are overdue at `now`: no success was ever recorded, or the last one is older than +/// [`STALE_AFTER`] or two backup intervals, whichever is longer, so a weekly schedule is not always overdue. +/// A stamp that does not parse counts as no success. +pub fn is_stale(last_success: Option<&str>, interval_hours: u32, now: Timestamp) -> bool { + let Some(last) = last_success.and_then(|stamp| timestamp_of(stamp).ok()) else { + return true; + }; + let limit = i64::try_from(STALE_AFTER.as_secs()) + .unwrap_or(i64::MAX) + .max(i64::from(interval_hours) * 2 * 3600); + now.as_second().saturating_sub(last.as_second()) > limit +} + /// Starts the backup worker when the config has a `[backup]` section. Without one this does nothing. /// The first backup runs at once, then one every `interval_hours`, or sooner when an administrator asks for /// one (see [`BackupTrigger`]). @@ -105,38 +166,21 @@ pub fn spawn(state: AppState, mut stop: watch::Receiver) { }); } -/// One backup: write a set, publish it, prune the old sets, ping the healthcheck. A failure is logged and -/// leaves no partial set. A stop request cancels a set in progress and removes it. +/// One backup: record the attempt, write and publish a set, prune the old sets, ping the healthcheck, and +/// record the outcome. A failure is logged and recorded, and leaves no partial set. A stop request cancels a +/// set in progress and removes it. async fn run_once( state: &AppState, policy: &BackupConfig, client: Option<&reqwest::Client>, stop: &mut watch::Receiver, ) { - if let Err(error) = ensure_dir(&policy.dir) { - tracing::warn!(error = %error, "backup directory cannot be created"); - return; - } - let now = jiff::Timestamp::now(); - let name = now.strftime(SET_STAMP_FORMAT).to_string(); - let created_at = match stamp_of(now) { - Ok(stamp) => stamp, - Err(error) => { - tracing::warn!(error = %error, "backup time cannot be stamped"); - return; - } - }; - let tmp = policy.dir.join(format!("{TMP_PREFIX}{}", new_id())); - let outcome = tokio::select! { - result = write_set(&state.store, &state.config.data_dir, &state.key, &tmp, &created_at) => result, - _ = stop.wait_for(|stopped| *stopped) => { - Err(Error::Io(std::io::Error::other("stopped before the set was finished"))) - } - }; - let outcome = outcome.and_then(|files| publish(&tmp, &policy.dir, &name).map(|()| files)); - match outcome { - Ok(files) => { + record_outcome(&state.store, LAST_ATTEMPT_SETTING, &now_stamp()).await; + match write_and_publish(state, policy, stop).await { + Ok((name, files)) => { tracing::info!(set = %name, files, "backup set written"); + record_outcome(&state.store, LAST_SUCCESS_SETTING, &now_stamp()).await; + record_outcome(&state.store, LAST_ERROR_SETTING, "").await; let keep = usize::try_from(policy.keep).unwrap_or(usize::MAX); match prune(&policy.dir, keep) { Ok(0) => {} @@ -148,13 +192,58 @@ async fn run_once( } } Err(error) => { - // Only the directory this run created is removed, by its exact path. - let _ = std::fs::remove_dir_all(&tmp); + record_outcome(&state.store, LAST_ERROR_SETTING, &error_text(&error)).await; tracing::warn!(error = %error, "backup failed; the partial set was removed"); } } } +/// Writes one set in a temporary directory and publishes it under its stamp. Returns the set's name and its +/// file count. On failure this removes the temporary directory, by its exact path. +async fn write_and_publish( + state: &AppState, + policy: &BackupConfig, + stop: &mut watch::Receiver, +) -> Result<(String, usize)> { + ensure_dir(&policy.dir)?; + let now = Timestamp::now(); + let name = now.strftime(SET_STAMP_FORMAT).to_string(); + let created_at = stamp_of(now)?; + let tmp = policy.dir.join(format!("{TMP_PREFIX}{}", new_id())); + let outcome = tokio::select! { + result = write_set(&state.store, &state.config.data_dir, &state.key, &tmp, &created_at) => result, + _ = stop.wait_for(|stopped| *stopped) => { + Err(Error::Io(std::io::Error::other("stopped before the set was finished"))) + } + }; + let outcome = outcome.and_then(|files| publish(&tmp, &policy.dir, &name).map(|()| files)); + if outcome.is_err() { + // Only the directory this run created is removed, by its exact path. + let _ = std::fs::remove_dir_all(&tmp); + } + outcome.map(|files| (name, files)) +} + +/// Stores one outcome value. A failure is logged and never fails or stops the run. +async fn record_outcome(store: &Store, key: &str, value: &str) { + if let Err(error) = store.set_setting(key, value).await { + tracing::error!(error = %error, key, "backup outcome not recorded"); + } +} + +/// The short text kept for a failed run and shown on the settings page. It never holds a database message, +/// since those can echo statement text, and it names no path: a filesystem error keeps only its OS reason. +fn error_text(error: &Error) -> String { + let text = match error { + Error::Io(_) => error.to_string(), + Error::Conflict(text) => text.clone(), + Error::Database(_) => "database error".to_owned(), + Error::Migration(_) => "migration error".to_owned(), + _ => "backup failed".to_owned(), + }; + text.chars().take(ERROR_TEXT_MAX).collect() +} + /// Writes the files of one set into `tmp` and the manifest and its MAC last. Returns the number of files /// listed, not counting the manifest. The caller removes `tmp` on error. async fn write_set( @@ -329,4 +418,13 @@ mod tests { assert!(dir.path().join("notes").exists()); assert!(dir.path().join(format!("{TMP_PREFIX}abc")).exists()); } + + #[test] + fn a_backup_is_stale_without_a_success_or_after_two_days() { + let now: Timestamp = "2026-10-28T12:00:00Z".parse().expect("time"); + assert!(is_stale(None, 24, now)); + assert!(!is_stale(Some("2026-10-26T12:00:00.000000000Z"), 24, now)); + assert!(is_stale(Some("2026-10-26T11:59:59.000000000Z"), 24, now)); + assert!(!is_stale(Some("2026-10-26T11:59:59.000000000Z"), 168, now)); + } } diff --git a/crates/iz-web/src/i18n/admin.rs b/crates/iz-web/src/i18n/admin.rs index 434aa5e..c57859c 100644 --- a/crates/iz-web/src/i18n/admin.rs +++ b/crates/iz-web/src/i18n/admin.rs @@ -56,6 +56,11 @@ pub enum K { BackupHelp, BackupOff, BackupNow, + BackupLastAttempt, + BackupLastSuccess, + BackupNever, + BackupFailed, + BackupStale, // Notices NoticeSenderSaved, NoticeCheckOk, @@ -270,6 +275,16 @@ pub fn t(lang: Lang, key: K) -> &'static str { } (K::BackupNow, En) => "Back up now", (K::BackupNow, Tr) => "Şimdi yedekle", + (K::BackupLastAttempt, En) => "Last attempt: {}", + (K::BackupLastAttempt, Tr) => "Son deneme: {}", + (K::BackupLastSuccess, En) => "Last successful backup: {}", + (K::BackupLastSuccess, Tr) => "Son başarılı yedekleme: {}", + (K::BackupNever, En) => "none yet", + (K::BackupNever, Tr) => "henüz yok", + (K::BackupFailed, En) => "The latest backup failed: {}", + (K::BackupFailed, Tr) => "Son yedekleme başarısız oldu: {}", + (K::BackupStale, En) => "No successful backup in the last 2 days.", + (K::BackupStale, Tr) => "Son 2 günde başarılı yedekleme yok.", (K::ErrBackupOff, En) => { "Backups are off, so there is nothing to start. Set [backup] dir first." } diff --git a/crates/iz-web/src/pages/settings.rs b/crates/iz-web/src/pages/settings.rs index 850ddfc..8f18e1d 100644 --- a/crates/iz-web/src/pages/settings.rs +++ b/crates/iz-web/src/pages/settings.rs @@ -21,14 +21,16 @@ use topcoat::router::{StatusCode, route}; use topcoat::view::view; use crate::auth::{CurrentMember, Need, query_param, require_csrf, require_role}; +use crate::backup; use crate::i18n::admin::{K, t}; use crate::i18n::{Lang, lang}; use crate::live::{AdminSection, Topic}; use crate::mail; use crate::pages::admin::{CsrfForm, REFUSED, back, notice_text, record, user_text, viewer_of}; use crate::pages::board::the_board; +use crate::pages::task::local_text; use crate::state::AppState; -use crate::views::admin::{SenderForm, SettingsView, settings_content}; +use crate::views::admin::{BackupCard, SenderForm, SettingsView, settings_content}; use crate::views::structure::{MemberRow, ServerInfo, StorageInfo}; use crate::views::{ViewerInfo, respond, shell}; use iz_core::authz::Role; @@ -38,6 +40,8 @@ use iz_core::store::attachments::{ parse_extensions, }; use iz_core::store::audit::AuditEntry; +use iz_core::zones::parse_zone; +use jiff::tz::TimeZone; use topcoat::router::path_param_segment; /// The sender form as posted. @@ -97,6 +101,7 @@ fn sender_form(stored: &SenderState) -> SenderForm { /// The page's data: the stored settings, or the typed `form` when a save was refused. async fn settings_view( state: &AppState, + me: &CurrentMember, lang: Lang, form: Option, notice: Option, @@ -137,7 +142,34 @@ async fn settings_view( extensions, server: server_info(state).await?, storage, - backups: state.config.backup.is_some(), + backup: backup_card(state, me).await?, + }) +} + +/// The Backups card: whether backups are on and the recorded outcome, with the times in the viewer's zone. +/// The warning about a missing recent success is shown only when backups are on. +async fn backup_card(state: &AppState, me: &CurrentMember) -> Result { + let enabled = state.config.backup.is_some(); + let status = backup::status(&state.store).await?; + let zone = parse_zone(&me.member.zoneinfo).unwrap_or(TimeZone::UTC); + let in_zone = |stamp: &Option| { + stamp + .as_deref() + .map(|stamp| local_text(stamp, &zone)) + .unwrap_or_default() + }; + Ok(BackupCard { + enabled, + last_attempt: in_zone(&status.last_attempt), + last_success: in_zone(&status.last_success), + last_error: status.last_error.clone().unwrap_or_default(), + stale: state.config.backup.as_ref().is_some_and(|policy| { + backup::is_stale( + status.last_success.as_deref(), + policy.interval_hours, + Timestamp::now(), + ) + }), }) } @@ -228,7 +260,7 @@ async fn settings_page(cx: &Cx) -> Result { let queued = query_param(cx, "queued"); let notice = query_param(cx, "notice").and_then(|code| notice_text(language, &code, queued.as_deref())); - let page = settings_view(state, language, None, notice, None).await?; + let page = settings_view(state, &me, language, None, notice, None).await?; render(cx, &me, page, StatusCode::OK).await } @@ -302,7 +334,8 @@ async fn save_sender(cx: &Cx, form: Option>) -> Result { let message = user_text(error)?; - let page = settings_view(state, language, Some(typed), None, Some(message)).await?; + let page = + settings_view(state, &me, language, Some(typed), None, Some(message)).await?; render(cx, &me, page, REFUSED).await } } @@ -334,7 +367,7 @@ async fn check_sender(cx: &Cx, form: Option>) -> Result } Err(error) => { let message = user_text(error)?; - let page = settings_view(state, language, None, None, Some(message)).await?; + let page = settings_view(state, &me, language, None, None, Some(message)).await?; render(cx, &me, page, REFUSED).await } } @@ -370,7 +403,7 @@ async fn send_test(cx: &Cx, form: Option>) -> Result { } Err(error) => { let message = user_text(error)?; - let page = settings_view(state, language, None, None, Some(message)).await?; + let page = settings_view(state, &me, language, None, None, Some(message)).await?; render(cx, &me, page, REFUSED).await } } @@ -386,7 +419,7 @@ async fn back_up_now(cx: &Cx, form: Option>) -> Result let language = lang(cx, me.member.locale_override.as_deref()); if state.config.backup.is_none() { let alert = t(language, K::ErrBackupOff).to_owned(); - let page = settings_view(state, language, None, None, Some(alert)).await?; + let page = settings_view(state, &me, language, None, None, Some(alert)).await?; return render(cx, &me, page, REFUSED).await; } let started = state.backup.request(); @@ -446,7 +479,7 @@ async fn save_reminders(cx: &Cx, form: Option>) -> Result< } Err(error) => { let message = user_text(error)?; - let page = settings_view(state, language, None, None, Some(message)).await?; + let page = settings_view(state, &me, language, None, None, Some(message)).await?; render(cx, &me, page, REFUSED).await } } @@ -483,7 +516,7 @@ async fn send_message(cx: &Cx, form: Option>) -> Result { let message = user_text(error)?; - let page = settings_view(state, language, None, None, Some(message)).await?; + let page = settings_view(state, &me, language, None, None, Some(message)).await?; render(cx, &me, page, REFUSED).await } } @@ -527,7 +560,7 @@ async fn save_role(cx: &Cx, form: Option>) -> Result } Err(error) => { let message = user_text(error)?; - let page = settings_view(state, language, None, None, Some(message)).await?; + let page = settings_view(state, &me, language, None, None, Some(message)).await?; render(cx, &me, page, REFUSED).await } } @@ -574,7 +607,7 @@ async fn save_storage(cx: &Cx, form: Option>) -> Result { let message = user_text(error)?; - let page = settings_view(state, language, None, None, Some(message)).await?; + let page = settings_view(state, &me, language, None, None, Some(message)).await?; render(cx, &me, page, REFUSED).await } } @@ -631,7 +664,7 @@ async fn save_limits(cx: &Cx, form: Option>) -> Result { let message = user_text(error)?; - let page = settings_view(state, language, None, None, Some(message)).await?; + let page = settings_view(state, &me, language, None, None, Some(message)).await?; render(cx, &me, page, REFUSED).await } } diff --git a/crates/iz-web/src/views/admin.rs b/crates/iz-web/src/views/admin.rs index 6727183..f7a0f6b 100644 --- a/crates/iz-web/src/views/admin.rs +++ b/crates/iz-web/src/views/admin.rs @@ -9,7 +9,7 @@ use topcoat::Result; use topcoat::view::{View, component, view}; use crate::i18n::Lang; -use crate::i18n::admin::{K, t}; +use crate::i18n::admin::{K, fill, t}; use crate::i18n::structure::{K as StructureK, t as structure_t}; use crate::views::board::flag; use crate::views::structure::{limits_section, members_section, server_section, storage_section}; @@ -138,8 +138,40 @@ pub struct SettingsView { pub server: crate::views::structure::ServerInfo, /// Where attachments are kept and how far the move between places has got. pub storage: crate::views::structure::StorageInfo, - /// Whether scheduled backups are on (`[backup] dir` is set), so the "Back up now" button is shown. - pub backups: bool, + /// The Backups card: whether backups are on, and the outcome of the last runs. + pub backup: BackupCard, +} + +/// The Backups card. Times are already in the viewer's zone; an empty text means nothing was recorded. +#[derive(Debug, Clone, Default)] +pub struct BackupCard { + /// Whether scheduled backups are on (`[backup] dir` is set). The button and the status show only then. + pub enabled: bool, + /// When the latest attempt started, as `YYYY-MM-DD HH:MM`. + pub last_attempt: String, + /// When the last success finished, as `YYYY-MM-DD HH:MM`. + pub last_success: String, + /// The error of the latest attempt, shown in an alert. Empty when that attempt succeeded. + pub last_error: String, + /// Whether no success is recent enough: the warning is shown only when backups are on. + pub stale: bool, +} + +/// One status line of the Backups card: its label with the time, or "none yet" when nothing was recorded. +fn backup_line(lang: Lang, key: K, stamp: &str) -> String { + let when = if stamp.is_empty() { + t(lang, K::BackupNever) + } else { + stamp + }; + fill(t(lang, key), &[when]) +} + +/// The alert for a failed latest attempt, with the short error the worker recorded. +#[component] +async fn backup_failed_alert(lang: Lang, error: &str) -> Result { + let text = fill(t(lang, K::BackupFailed), &[error]); + Ok(view! { alert(message: text.as_str()) }) } /// The rules page: the list, the form (new or editing), and the choices of the form. @@ -316,8 +348,16 @@ pub async fn settings_content(page: &SettingsView, csrf: &str) -> Result

(t(lang, K::BackupHeading))

- if page.backups { + if page.backup.enabled {

(t(lang, K::BackupHelp))

+ if page.backup.stale { +
(t(lang, K::BackupStale))
+ } + if !page.backup.last_error.is_empty() { + backup_failed_alert(lang: lang, error: page.backup.last_error.as_str()) + } +

(backup_line(lang, K::BackupLastSuccess, page.backup.last_success.as_str()))

+

(backup_line(lang, K::BackupLastAttempt, page.backup.last_attempt.as_str()))

diff --git a/docs/architecture.md b/docs/architecture.md index b9aaaad..b24bbd5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -147,7 +147,7 @@ Pages (session; Viewer may read, writes need Member, admin pages need Admin; all | `GET /columns` + POSTs | columns (admin) | | `GET /rules` + POSTs | mail rules (admin), sentence rendering, enable switch, edit | | `GET /logs` | admin: outbox (retry), decisions, activity (filters, keyset paging) | -| `GET /settings` + POSTs | profile/preferences (all); members & roles, sender (check, test), limits, attachment storage (+ migration status), message to members, server (admin); `POST /settings/backup` "Back up now" (admin, CSRF, audited, 303 back with a notice, 422 with an alert when `[backup]` is off) | +| `GET /settings` + POSTs | profile/preferences (all); members & roles, sender (check, test), limits, attachment storage (+ migration status), message to members, server (admin); `POST /settings/backup` "Back up now" (admin, CSRF, audited, 303 back with a notice, 422 with an alert when `[backup]` is off); the Backups card shows the recorded outcome of the runs (section 8) | | `GET /avatar/{sub}` | photo proxy with disk cache, only for members of this board | | OIDC client routes, `/-/alive`, live streams, `/healthz`, `/assets/*` | | @@ -205,6 +205,13 @@ activity and mail ledger, audit rows past `AUDIT_RETENTION_DAYS` = 365 in batche `BackupTrigger` on `AppState` holds an atomic busy flag (set by a request or a scheduled run, cleared when the run ends) and a `Notify`. At most one run is pending or running; a request made meanwhile starts nothing. All stop with the stop flag. +Every backup run, scheduled or requested, records its outcome in `settings`: `backup_last_attempt` (when the run +started), `backup_last_success` (when a set was published; never cleared) and `backup_last_error` (a short text, +empty after a success). The error text names the kind of failure and never a path or a database message. The +Backups card on the settings page shows the last success and attempt in the viewer's zone, the error of a failed +latest attempt in an alert, and a warning when backups are on and no success is within two days. `/healthz` does +not report backups. + --- ## 9. Live diff --git a/style/_components.scss b/style/_components.scss index 874a823..c05da9a 100644 --- a/style/_components.scss +++ b/style/_components.scss @@ -145,7 +145,8 @@ textarea::placeholder { // --- Alerts ----------------------------------------------------------------------------------- .alert, -.notice { +.notice, +.warning { padding: var(--space-3) var(--space-4); border-radius: var(--radius-sm); border: 1px solid transparent; @@ -157,6 +158,13 @@ textarea::placeholder { border-color: var(--danger); } +// A condition the admin should look at, not a failure of the request. +.warning { + background: var(--warn-soft); + color: var(--warn); + border-color: var(--warn); +} + .notice { background: var(--accent-soft); color: var(--text);