forge
Explore
Log in

Don't you dare go Hollow

Backup outcome recorded and shown, with a warning when backups are overdue

Browse files at this commit

551228fa764545ac10598882520b904d8bca3954Ahmet Kaan GümüşParent: 72da983
  • feat
    • backup outcome recorded and shown, with a warning when backups are overdue
Show full message
✨ feat: backup outcome recorded and shown, with a warning when backups are overdue
crates/iz-web/src/backup.rsmodified+126 -28
@@ -12,18 +12,24 @@
12 //! The admin settings page can ask for a run now through [`BackupTrigger`]. At most one run is pending or12 //! The admin settings page can ask for a run now through [`BackupTrigger`]. At most one run is pending or
13 //! running: a request made meanwhile starts nothing. Scheduled and requested runs both hold the busy flag, so13 //! running: a request made meanwhile starts nothing. Scheduled and requested runs both hold the busy flag, so
14 //! they never overlap.14 //! they never overlap.
15+//!
16+//! Every run records its outcome in the `settings` table (the attempt time, the last success, and the error of
17+//! the latest attempt), so a failing backup is visible on the Backups card. [`status`] reads it back and
18+//! [`is_stale`] says when no success is recent enough to warn about.
15 19
16 use std::os::unix::fs::DirBuilderExt;20 use std::os::unix::fs::DirBuilderExt;
17 use std::path::{Path, PathBuf};21 use std::path::{Path, PathBuf};
18 use std::sync::atomic::{AtomicBool, Ordering};22 use std::sync::atomic::{AtomicBool, Ordering};
19 use std::time::Duration;23 use std::time::Duration;
20 24
21-use iz_core::clock::stamp_of;25+use iz_core::clock::{stamp_of, timestamp_of};
22 use iz_core::config::BackupConfig;26 use iz_core::config::BackupConfig;
23 use iz_core::manifest::{self, MANIFEST_NAME};27 use iz_core::manifest::{self, MANIFEST_NAME};
24 use iz_core::staging::{ATTACHMENTS_DIR, blob_path};28 use iz_core::staging::{ATTACHMENTS_DIR, blob_path};
25 use iz_core::store::{Store, new_id};29 use iz_core::store::{Store, new_id};
30+use iz_core::time::now_stamp;
26 use iz_core::{Error, Result};31 use iz_core::{Error, Result};
32+use jiff::Timestamp;
27 use tokio::sync::{Notify, watch};33 use tokio::sync::{Notify, watch};
28 34
29 use crate::state::AppState;35 use crate::state::AppState;
@@ -71,6 +77,61 @@ const SET_STAMP_FORMAT: &str = "%Y%m%dT%H%M%SZ";
71 /// Length of a set's directory name, which is the stamp format above.77 /// Length of a set's directory name, which is the stamp format above.
72 const SET_NAME_LEN: usize = 16;78 const SET_NAME_LEN: usize = 16;
73 79
80+/// Settings key: when a run was last attempted (a UTC stamp).
81+pub const LAST_ATTEMPT_SETTING: &str = "backup_last_attempt";
82+/// Settings key: when a run last succeeded (a UTC stamp). Never cleared, so the card shows the last good set.
83+pub const LAST_SUCCESS_SETTING: &str = "backup_last_success";
84+/// Settings key: the text of the error of the latest attempt. Empty after a success.
85+pub const LAST_ERROR_SETTING: &str = "backup_last_error";
86+/// Time without a success after which the settings page warns. Reason: two days lets one scheduled run be
87+/// missed without a warning, and a longer gap means the backups are not happening.
88+const STALE_AFTER: Duration = Duration::from_secs(2 * 24 * 3600);
89+/// Longest error text kept, in characters. Reason: the settings page shows it on one line.
90+const ERROR_TEXT_MAX: usize = 200;
91+
92+/// The recorded outcome of the backup runs, as the settings page reads it. Stamps are UTC; `None` when no
93+/// value was recorded.
94+#[derive(Debug, Clone, Default)]
95+pub struct BackupStatus {
96+ /// When the latest attempt started.
97+ pub last_attempt: Option<String>,
98+ /// When the last successful run finished.
99+ pub last_success: Option<String>,
100+ /// The text of the error of the latest attempt. `None` when that attempt succeeded.
101+ pub last_error: Option<String>,
102+}
103+
104+/// Reads the recorded outcome. Empty values count as not recorded.
105+pub async fn status(store: &Store) -> Result<BackupStatus> {
106+ Ok(BackupStatus {
107+ last_attempt: store
108+ .get_setting(LAST_ATTEMPT_SETTING)
109+ .await?
110+ .filter(|value| !value.is_empty()),
111+ last_success: store
112+ .get_setting(LAST_SUCCESS_SETTING)
113+ .await?
114+ .filter(|value| !value.is_empty()),
115+ last_error: store
116+ .get_setting(LAST_ERROR_SETTING)
117+ .await?
118+ .filter(|value| !value.is_empty()),
119+ })
120+}
121+
122+/// Whether the backups are overdue at `now`: no success was ever recorded, or the last one is older than
123+/// [`STALE_AFTER`] or two backup intervals, whichever is longer, so a weekly schedule is not always overdue.
124+/// A stamp that does not parse counts as no success.
125+pub fn is_stale(last_success: Option<&str>, interval_hours: u32, now: Timestamp) -> bool {
126+ let Some(last) = last_success.and_then(|stamp| timestamp_of(stamp).ok()) else {
127+ return true;
128+ };
129+ let limit = i64::try_from(STALE_AFTER.as_secs())
130+ .unwrap_or(i64::MAX)
131+ .max(i64::from(interval_hours) * 2 * 3600);
132+ now.as_second().saturating_sub(last.as_second()) > limit
133+}
134+
74 /// Starts the backup worker when the config has a `[backup]` section. Without one this does nothing.135 /// Starts the backup worker when the config has a `[backup]` section. Without one this does nothing.
75 /// The first backup runs at once, then one every `interval_hours`, or sooner when an administrator asks for136 /// The first backup runs at once, then one every `interval_hours`, or sooner when an administrator asks for
76 /// one (see [`BackupTrigger`]).137 /// one (see [`BackupTrigger`]).
@@ -105,38 +166,21 @@ pub fn spawn(state: AppState, mut stop: watch::Receiver<bool>) {
105 });166 });
106 }167 }
107 168
108-/// One backup: write a set, publish it, prune the old sets, ping the healthcheck. A failure is logged and169+/// One backup: record the attempt, write and publish a set, prune the old sets, ping the healthcheck, and
109-/// leaves no partial set. A stop request cancels a set in progress and removes it.170+/// record the outcome. A failure is logged and recorded, and leaves no partial set. A stop request cancels a
171+/// set in progress and removes it.
110 async fn run_once(172 async fn run_once(
111 state: &AppState,173 state: &AppState,
112 policy: &BackupConfig,174 policy: &BackupConfig,
113 client: Option<&reqwest::Client>,175 client: Option<&reqwest::Client>,
114 stop: &mut watch::Receiver<bool>,176 stop: &mut watch::Receiver<bool>,
115 ) {177 ) {
116- if let Err(error) = ensure_dir(&policy.dir) {178+ record_outcome(&state.store, LAST_ATTEMPT_SETTING, &now_stamp()).await;
117- tracing::warn!(error = %error, "backup directory cannot be created");179+ match write_and_publish(state, policy, stop).await {
118- return;180+ Ok((name, files)) => {
119- }
120- let now = jiff::Timestamp::now();
121- let name = now.strftime(SET_STAMP_FORMAT).to_string();
122- let created_at = match stamp_of(now) {
123- Ok(stamp) => stamp,
124- Err(error) => {
125- tracing::warn!(error = %error, "backup time cannot be stamped");
126- return;
127- }
128- };
129- let tmp = policy.dir.join(format!("{TMP_PREFIX}{}", new_id()));
130- let outcome = tokio::select! {
131- result = write_set(&state.store, &state.config.data_dir, &state.key, &tmp, &created_at) => result,
132- _ = stop.wait_for(|stopped| *stopped) => {
133- Err(Error::Io(std::io::Error::other("stopped before the set was finished")))
134- }
135- };
136- let outcome = outcome.and_then(|files| publish(&tmp, &policy.dir, &name).map(|()| files));
137- match outcome {
138- Ok(files) => {
139 tracing::info!(set = %name, files, "backup set written");181 tracing::info!(set = %name, files, "backup set written");
182+ record_outcome(&state.store, LAST_SUCCESS_SETTING, &now_stamp()).await;
183+ record_outcome(&state.store, LAST_ERROR_SETTING, "").await;
140 let keep = usize::try_from(policy.keep).unwrap_or(usize::MAX);184 let keep = usize::try_from(policy.keep).unwrap_or(usize::MAX);
141 match prune(&policy.dir, keep) {185 match prune(&policy.dir, keep) {
142 Ok(0) => {}186 Ok(0) => {}
@@ -148,13 +192,58 @@ async fn run_once(
148 }192 }
149 }193 }
150 Err(error) => {194 Err(error) => {
151- // Only the directory this run created is removed, by its exact path.195+ record_outcome(&state.store, LAST_ERROR_SETTING, &error_text(&error)).await;
152- let _ = std::fs::remove_dir_all(&tmp);
153 tracing::warn!(error = %error, "backup failed; the partial set was removed");196 tracing::warn!(error = %error, "backup failed; the partial set was removed");
154 }197 }
155 }198 }
156 }199 }
157 200
201+/// Writes one set in a temporary directory and publishes it under its stamp. Returns the set's name and its
202+/// file count. On failure this removes the temporary directory, by its exact path.
203+async fn write_and_publish(
204+ state: &AppState,
205+ policy: &BackupConfig,
206+ stop: &mut watch::Receiver<bool>,
207+) -> Result<(String, usize)> {
208+ ensure_dir(&policy.dir)?;
209+ let now = Timestamp::now();
210+ let name = now.strftime(SET_STAMP_FORMAT).to_string();
211+ let created_at = stamp_of(now)?;
212+ let tmp = policy.dir.join(format!("{TMP_PREFIX}{}", new_id()));
213+ let outcome = tokio::select! {
214+ result = write_set(&state.store, &state.config.data_dir, &state.key, &tmp, &created_at) => result,
215+ _ = stop.wait_for(|stopped| *stopped) => {
216+ Err(Error::Io(std::io::Error::other("stopped before the set was finished")))
217+ }
218+ };
219+ let outcome = outcome.and_then(|files| publish(&tmp, &policy.dir, &name).map(|()| files));
220+ if outcome.is_err() {
221+ // Only the directory this run created is removed, by its exact path.
222+ let _ = std::fs::remove_dir_all(&tmp);
223+ }
224+ outcome.map(|files| (name, files))
225+}
226+
227+/// Stores one outcome value. A failure is logged and never fails or stops the run.
228+async fn record_outcome(store: &Store, key: &str, value: &str) {
229+ if let Err(error) = store.set_setting(key, value).await {
230+ tracing::error!(error = %error, key, "backup outcome not recorded");
231+ }
232+}
233+
234+/// The short text kept for a failed run and shown on the settings page. It never holds a database message,
235+/// since those can echo statement text, and it names no path: a filesystem error keeps only its OS reason.
236+fn error_text(error: &Error) -> String {
237+ let text = match error {
238+ Error::Io(_) => error.to_string(),
239+ Error::Conflict(text) => text.clone(),
240+ Error::Database(_) => "database error".to_owned(),
241+ Error::Migration(_) => "migration error".to_owned(),
242+ _ => "backup failed".to_owned(),
243+ };
244+ text.chars().take(ERROR_TEXT_MAX).collect()
245+}
246+
158 /// Writes the files of one set into `tmp` and the manifest and its MAC last. Returns the number of files247 /// Writes the files of one set into `tmp` and the manifest and its MAC last. Returns the number of files
159 /// listed, not counting the manifest. The caller removes `tmp` on error.248 /// listed, not counting the manifest. The caller removes `tmp` on error.
160 async fn write_set(249 async fn write_set(
@@ -329,4 +418,13 @@ mod tests {
329 assert!(dir.path().join("notes").exists());418 assert!(dir.path().join("notes").exists());
330 assert!(dir.path().join(format!("{TMP_PREFIX}abc")).exists());419 assert!(dir.path().join(format!("{TMP_PREFIX}abc")).exists());
331 }420 }
421+
422+ #[test]
423+ fn a_backup_is_stale_without_a_success_or_after_two_days() {
424+ let now: Timestamp = "2026-10-28T12:00:00Z".parse().expect("time");
425+ assert!(is_stale(None, 24, now));
426+ assert!(!is_stale(Some("2026-10-26T12:00:00.000000000Z"), 24, now));
427+ assert!(is_stale(Some("2026-10-26T11:59:59.000000000Z"), 24, now));
428+ assert!(!is_stale(Some("2026-10-26T11:59:59.000000000Z"), 168, now));
429+ }
332 }430 }
crates/iz-web/src/i18n/admin.rsmodified+15 -0
@@ -56,6 +56,11 @@ pub enum K {
56 BackupHelp,56 BackupHelp,
57 BackupOff,57 BackupOff,
58 BackupNow,58 BackupNow,
59+ BackupLastAttempt,
60+ BackupLastSuccess,
61+ BackupNever,
62+ BackupFailed,
63+ BackupStale,
59 // Notices64 // Notices
60 NoticeSenderSaved,65 NoticeSenderSaved,
61 NoticeCheckOk,66 NoticeCheckOk,
@@ -270,6 +275,16 @@ pub fn t(lang: Lang, key: K) -> &'static str {
270 }275 }
271 (K::BackupNow, En) => "Back up now",276 (K::BackupNow, En) => "Back up now",
272 (K::BackupNow, Tr) => "Şimdi yedekle",277 (K::BackupNow, Tr) => "Şimdi yedekle",
278+ (K::BackupLastAttempt, En) => "Last attempt: {}",
279+ (K::BackupLastAttempt, Tr) => "Son deneme: {}",
280+ (K::BackupLastSuccess, En) => "Last successful backup: {}",
281+ (K::BackupLastSuccess, Tr) => "Son başarılı yedekleme: {}",
282+ (K::BackupNever, En) => "none yet",
283+ (K::BackupNever, Tr) => "henüz yok",
284+ (K::BackupFailed, En) => "The latest backup failed: {}",
285+ (K::BackupFailed, Tr) => "Son yedekleme başarısız oldu: {}",
286+ (K::BackupStale, En) => "No successful backup in the last 2 days.",
287+ (K::BackupStale, Tr) => "Son 2 günde başarılı yedekleme yok.",
273 (K::ErrBackupOff, En) => {288 (K::ErrBackupOff, En) => {
274 "Backups are off, so there is nothing to start. Set [backup] dir first."289 "Backups are off, so there is nothing to start. Set [backup] dir first."
275 }290 }
crates/iz-web/src/pages/settings.rsmodified+45 -12
@@ -21,14 +21,16 @@ use topcoat::router::{StatusCode, route};
21 use topcoat::view::view;21 use topcoat::view::view;
22 22
23 use crate::auth::{CurrentMember, Need, query_param, require_csrf, require_role};23 use crate::auth::{CurrentMember, Need, query_param, require_csrf, require_role};
24+use crate::backup;
24 use crate::i18n::admin::{K, t};25 use crate::i18n::admin::{K, t};
25 use crate::i18n::{Lang, lang};26 use crate::i18n::{Lang, lang};
26 use crate::live::{AdminSection, Topic};27 use crate::live::{AdminSection, Topic};
27 use crate::mail;28 use crate::mail;
28 use crate::pages::admin::{CsrfForm, REFUSED, back, notice_text, record, user_text, viewer_of};29 use crate::pages::admin::{CsrfForm, REFUSED, back, notice_text, record, user_text, viewer_of};
29 use crate::pages::board::the_board;30 use crate::pages::board::the_board;
31+use crate::pages::task::local_text;
30 use crate::state::AppState;32 use crate::state::AppState;
31-use crate::views::admin::{SenderForm, SettingsView, settings_content};33+use crate::views::admin::{BackupCard, SenderForm, SettingsView, settings_content};
32 use crate::views::structure::{MemberRow, ServerInfo, StorageInfo};34 use crate::views::structure::{MemberRow, ServerInfo, StorageInfo};
33 use crate::views::{ViewerInfo, respond, shell};35 use crate::views::{ViewerInfo, respond, shell};
34 use iz_core::authz::Role;36 use iz_core::authz::Role;
@@ -38,6 +40,8 @@ use iz_core::store::attachments::{
38 parse_extensions,40 parse_extensions,
39 };41 };
40 use iz_core::store::audit::AuditEntry;42 use iz_core::store::audit::AuditEntry;
43+use iz_core::zones::parse_zone;
44+use jiff::tz::TimeZone;
41 use topcoat::router::path_param_segment;45 use topcoat::router::path_param_segment;
42 46
43 /// The sender form as posted.47 /// The sender form as posted.
@@ -97,6 +101,7 @@ fn sender_form(stored: &SenderState) -> SenderForm {
97 /// The page's data: the stored settings, or the typed `form` when a save was refused.101 /// The page's data: the stored settings, or the typed `form` when a save was refused.
98 async fn settings_view(102 async fn settings_view(
99 state: &AppState,103 state: &AppState,
104+ me: &CurrentMember,
100 lang: Lang,105 lang: Lang,
101 form: Option<SenderForm>,106 form: Option<SenderForm>,
102 notice: Option<String>,107 notice: Option<String>,
@@ -137,7 +142,34 @@ async fn settings_view(
137 extensions,142 extensions,
138 server: server_info(state).await?,143 server: server_info(state).await?,
139 storage,144 storage,
140- backups: state.config.backup.is_some(),145+ backup: backup_card(state, me).await?,
146+ })
147+}
148+
149+/// The Backups card: whether backups are on and the recorded outcome, with the times in the viewer's zone.
150+/// The warning about a missing recent success is shown only when backups are on.
151+async fn backup_card(state: &AppState, me: &CurrentMember) -> Result<BackupCard> {
152+ let enabled = state.config.backup.is_some();
153+ let status = backup::status(&state.store).await?;
154+ let zone = parse_zone(&me.member.zoneinfo).unwrap_or(TimeZone::UTC);
155+ let in_zone = |stamp: &Option<String>| {
156+ stamp
157+ .as_deref()
158+ .map(|stamp| local_text(stamp, &zone))
159+ .unwrap_or_default()
160+ };
161+ Ok(BackupCard {
162+ enabled,
163+ last_attempt: in_zone(&status.last_attempt),
164+ last_success: in_zone(&status.last_success),
165+ last_error: status.last_error.clone().unwrap_or_default(),
166+ stale: state.config.backup.as_ref().is_some_and(|policy| {
167+ backup::is_stale(
168+ status.last_success.as_deref(),
169+ policy.interval_hours,
170+ Timestamp::now(),
171+ )
172+ }),
141 })173 })
142 }174 }
143 175
@@ -228,7 +260,7 @@ async fn settings_page(cx: &Cx) -> Result<Response> {
228 let queued = query_param(cx, "queued");260 let queued = query_param(cx, "queued");
229 let notice =261 let notice =
230 query_param(cx, "notice").and_then(|code| notice_text(language, &code, queued.as_deref()));262 query_param(cx, "notice").and_then(|code| notice_text(language, &code, queued.as_deref()));
231- let page = settings_view(state, language, None, notice, None).await?;263+ let page = settings_view(state, &me, language, None, notice, None).await?;
232 render(cx, &me, page, StatusCode::OK).await264 render(cx, &me, page, StatusCode::OK).await
233 }265 }
234 266
@@ -302,7 +334,8 @@ async fn save_sender(cx: &Cx, form: Option<Form<SenderSubmit>>) -> Result<Respon
302 }334 }
303 Err(error) => {335 Err(error) => {
304 let message = user_text(error)?;336 let message = user_text(error)?;
305- let page = settings_view(state, language, Some(typed), None, Some(message)).await?;337+ let page =
338+ settings_view(state, &me, language, Some(typed), None, Some(message)).await?;
306 render(cx, &me, page, REFUSED).await339 render(cx, &me, page, REFUSED).await
307 }340 }
308 }341 }
@@ -334,7 +367,7 @@ async fn check_sender(cx: &Cx, form: Option<Form<CsrfForm>>) -> Result<Response>
334 }367 }
335 Err(error) => {368 Err(error) => {
336 let message = user_text(error)?;369 let message = user_text(error)?;
337- let page = settings_view(state, language, None, None, Some(message)).await?;370+ let page = settings_view(state, &me, language, None, None, Some(message)).await?;
338 render(cx, &me, page, REFUSED).await371 render(cx, &me, page, REFUSED).await
339 }372 }
340 }373 }
@@ -370,7 +403,7 @@ async fn send_test(cx: &Cx, form: Option<Form<CsrfForm>>) -> Result<Response> {
370 }403 }
371 Err(error) => {404 Err(error) => {
372 let message = user_text(error)?;405 let message = user_text(error)?;
373- let page = settings_view(state, language, None, None, Some(message)).await?;406+ let page = settings_view(state, &me, language, None, None, Some(message)).await?;
374 render(cx, &me, page, REFUSED).await407 render(cx, &me, page, REFUSED).await
375 }408 }
376 }409 }
@@ -386,7 +419,7 @@ async fn back_up_now(cx: &Cx, form: Option<Form<CsrfForm>>) -> Result<Response>
386 let language = lang(cx, me.member.locale_override.as_deref());419 let language = lang(cx, me.member.locale_override.as_deref());
387 if state.config.backup.is_none() {420 if state.config.backup.is_none() {
388 let alert = t(language, K::ErrBackupOff).to_owned();421 let alert = t(language, K::ErrBackupOff).to_owned();
389- let page = settings_view(state, language, None, None, Some(alert)).await?;422+ let page = settings_view(state, &me, language, None, None, Some(alert)).await?;
390 return render(cx, &me, page, REFUSED).await;423 return render(cx, &me, page, REFUSED).await;
391 }424 }
392 let started = state.backup.request();425 let started = state.backup.request();
@@ -446,7 +479,7 @@ async fn save_reminders(cx: &Cx, form: Option<Form<RemindersSubmit>>) -> Result<
446 }479 }
447 Err(error) => {480 Err(error) => {
448 let message = user_text(error)?;481 let message = user_text(error)?;
449- let page = settings_view(state, language, None, None, Some(message)).await?;482+ let page = settings_view(state, &me, language, None, None, Some(message)).await?;
450 render(cx, &me, page, REFUSED).await483 render(cx, &me, page, REFUSED).await
451 }484 }
452 }485 }
@@ -483,7 +516,7 @@ async fn send_message(cx: &Cx, form: Option<Form<MessageSubmit>>) -> Result<Resp
483 }516 }
484 Err(error) => {517 Err(error) => {
485 let message = user_text(error)?;518 let message = user_text(error)?;
486- let page = settings_view(state, language, None, None, Some(message)).await?;519+ let page = settings_view(state, &me, language, None, None, Some(message)).await?;
487 render(cx, &me, page, REFUSED).await520 render(cx, &me, page, REFUSED).await
488 }521 }
489 }522 }
@@ -527,7 +560,7 @@ async fn save_role(cx: &Cx, form: Option<Form<RoleSubmit>>) -> Result<Response>
527 }560 }
528 Err(error) => {561 Err(error) => {
529 let message = user_text(error)?;562 let message = user_text(error)?;
530- let page = settings_view(state, language, None, None, Some(message)).await?;563+ let page = settings_view(state, &me, language, None, None, Some(message)).await?;
531 render(cx, &me, page, REFUSED).await564 render(cx, &me, page, REFUSED).await
532 }565 }
533 }566 }
@@ -574,7 +607,7 @@ async fn save_storage(cx: &Cx, form: Option<Form<StorageSubmit>>) -> Result<Resp
574 }607 }
575 Err(error) => {608 Err(error) => {
576 let message = user_text(error)?;609 let message = user_text(error)?;
577- let page = settings_view(state, language, None, None, Some(message)).await?;610+ let page = settings_view(state, &me, language, None, None, Some(message)).await?;
578 render(cx, &me, page, REFUSED).await611 render(cx, &me, page, REFUSED).await
579 }612 }
580 }613 }
@@ -631,7 +664,7 @@ async fn save_limits(cx: &Cx, form: Option<Form<LimitsSubmit>>) -> Result<Respon
631 }664 }
632 Err(error) => {665 Err(error) => {
633 let message = user_text(error)?;666 let message = user_text(error)?;
634- let page = settings_view(state, language, None, None, Some(message)).await?;667+ let page = settings_view(state, &me, language, None, None, Some(message)).await?;
635 render(cx, &me, page, REFUSED).await668 render(cx, &me, page, REFUSED).await
636 }669 }
637 }670 }
crates/iz-web/src/views/admin.rsmodified+44 -4
@@ -9,7 +9,7 @@ use topcoat::Result;
9 use topcoat::view::{View, component, view};9 use topcoat::view::{View, component, view};
10 10
11 use crate::i18n::Lang;11 use crate::i18n::Lang;
12-use crate::i18n::admin::{K, t};12+use crate::i18n::admin::{K, fill, t};
13 use crate::i18n::structure::{K as StructureK, t as structure_t};13 use crate::i18n::structure::{K as StructureK, t as structure_t};
14 use crate::views::board::flag;14 use crate::views::board::flag;
15 use crate::views::structure::{limits_section, members_section, server_section, storage_section};15 use crate::views::structure::{limits_section, members_section, server_section, storage_section};
@@ -138,8 +138,40 @@ pub struct SettingsView {
138 pub server: crate::views::structure::ServerInfo,138 pub server: crate::views::structure::ServerInfo,
139 /// Where attachments are kept and how far the move between places has got.139 /// Where attachments are kept and how far the move between places has got.
140 pub storage: crate::views::structure::StorageInfo,140 pub storage: crate::views::structure::StorageInfo,
141- /// Whether scheduled backups are on (`[backup] dir` is set), so the "Back up now" button is shown.141+ /// The Backups card: whether backups are on, and the outcome of the last runs.
142- pub backups: bool,142+ pub backup: BackupCard,
143+}
144+
145+/// The Backups card. Times are already in the viewer's zone; an empty text means nothing was recorded.
146+#[derive(Debug, Clone, Default)]
147+pub struct BackupCard {
148+ /// Whether scheduled backups are on (`[backup] dir` is set). The button and the status show only then.
149+ pub enabled: bool,
150+ /// When the latest attempt started, as `YYYY-MM-DD HH:MM`.
151+ pub last_attempt: String,
152+ /// When the last success finished, as `YYYY-MM-DD HH:MM`.
153+ pub last_success: String,
154+ /// The error of the latest attempt, shown in an alert. Empty when that attempt succeeded.
155+ pub last_error: String,
156+ /// Whether no success is recent enough: the warning is shown only when backups are on.
157+ pub stale: bool,
158+}
159+
160+/// One status line of the Backups card: its label with the time, or "none yet" when nothing was recorded.
161+fn backup_line(lang: Lang, key: K, stamp: &str) -> String {
162+ let when = if stamp.is_empty() {
163+ t(lang, K::BackupNever)
164+ } else {
165+ stamp
166+ };
167+ fill(t(lang, key), &[when])
168+}
169+
170+/// The alert for a failed latest attempt, with the short error the worker recorded.
171+#[component]
172+async fn backup_failed_alert(lang: Lang, error: &str) -> Result<impl View> {
173+ let text = fill(t(lang, K::BackupFailed), &[error]);
174+ Ok(view! { alert(message: text.as_str()) })
143 }175 }
144 176
145 /// The rules page: the list, the form (new or editing), and the choices of the form.177 /// 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<impl Vi
316 </section>348 </section>
317 <section class="card" id="backups">349 <section class="card" id="backups">
318 <h2>(t(lang, K::BackupHeading))</h2>350 <h2>(t(lang, K::BackupHeading))</h2>
319- if page.backups {351+ if page.backup.enabled {
320 <p class="field-hint">(t(lang, K::BackupHelp))</p>352 <p class="field-hint">(t(lang, K::BackupHelp))</p>
353+ if page.backup.stale {
354+ <div class="warning" role="status">(t(lang, K::BackupStale))</div>
355+ }
356+ if !page.backup.last_error.is_empty() {
357+ backup_failed_alert(lang: lang, error: page.backup.last_error.as_str())
358+ }
359+ <p class="field-hint">(backup_line(lang, K::BackupLastSuccess, page.backup.last_success.as_str()))</p>
360+ <p class="field-hint">(backup_line(lang, K::BackupLastAttempt, page.backup.last_attempt.as_str()))</p>
321 <form method="post" action="/settings/backup">361 <form method="post" action="/settings/backup">
322 <input type="hidden" name="csrf" value=(csrf)>362 <input type="hidden" name="csrf" value=(csrf)>
323 <button class="button" type="submit">(t(lang, K::BackupNow))</button>363 <button class="button" type="submit">(t(lang, K::BackupNow))</button>
docs/architecture.mdmodified+8 -1
@@ -147,7 +147,7 @@ Pages (session; Viewer may read, writes need Member, admin pages need Admin; all
147 | `GET /columns` + POSTs | columns (admin) |147 | `GET /columns` + POSTs | columns (admin) |
148 | `GET /rules` + POSTs | mail rules (admin), sentence rendering, enable switch, edit |148 | `GET /rules` + POSTs | mail rules (admin), sentence rendering, enable switch, edit |
149 | `GET /logs` | admin: outbox (retry), decisions, activity (filters, keyset paging) |149 | `GET /logs` | admin: outbox (retry), decisions, activity (filters, keyset paging) |
150-| `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) |150+| `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) |
151 | `GET /avatar/{sub}` | photo proxy with disk cache, only for members of this board |151 | `GET /avatar/{sub}` | photo proxy with disk cache, only for members of this board |
152 | OIDC client routes, `/-/alive`, live streams, `/healthz`, `/assets/*` | |152 | OIDC client routes, `/-/alive`, live streams, `/healthz`, `/assets/*` | |
153 153
@@ -205,6 +205,13 @@ activity and mail ledger, audit rows past `AUDIT_RETENTION_DAYS` = 365 in batche
205 `BackupTrigger` on `AppState` holds an atomic busy flag (set by a request or a scheduled run, cleared when the run ends)205 `BackupTrigger` on `AppState` holds an atomic busy flag (set by a request or a scheduled run, cleared when the run ends)
206 and a `Notify`. At most one run is pending or running; a request made meanwhile starts nothing. All stop with the stop flag.206 and a `Notify`. At most one run is pending or running; a request made meanwhile starts nothing. All stop with the stop flag.
207 207
208+Every backup run, scheduled or requested, records its outcome in `settings`: `backup_last_attempt` (when the run
209+started), `backup_last_success` (when a set was published; never cleared) and `backup_last_error` (a short text,
210+empty after a success). The error text names the kind of failure and never a path or a database message. The
211+Backups card on the settings page shows the last success and attempt in the viewer's zone, the error of a failed
212+latest attempt in an alert, and a warning when backups are on and no success is within two days. `/healthz` does
213+not report backups.
214+
208 ---215 ---
209 216
210 ## 9. Live217 ## 9. Live
style/_components.scssmodified+9 -1
@@ -145,7 +145,8 @@ textarea::placeholder {
145 // --- Alerts -----------------------------------------------------------------------------------145 // --- Alerts -----------------------------------------------------------------------------------
146 146
147 .alert,147 .alert,
148-.notice {148+.notice,
149+.warning {
149 padding: var(--space-3) var(--space-4);150 padding: var(--space-3) var(--space-4);
150 border-radius: var(--radius-sm);151 border-radius: var(--radius-sm);
151 border: 1px solid transparent;152 border: 1px solid transparent;
@@ -157,6 +158,13 @@ textarea::placeholder {
157 border-color: var(--danger);158 border-color: var(--danger);
158 }159 }
159 160
161+// A condition the admin should look at, not a failure of the request.
162+.warning {
163+ background: var(--warn-soft);
164+ color: var(--warn);
165+ border-color: var(--warn);
166+}
167+
160 .notice {168 .notice {
161 background: var(--accent-soft);169 background: var(--accent-soft);
162 color: var(--text);170 color: var(--text);