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

18fc0184aad64464f4de866f22110c0a01433b54Ahmet Kaan GümüşParent: 102b9af
  • 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/in-web/src/backup.rsmodified+77 -3
@@ -7,13 +7,19 @@
7 //! A failed run is logged and the next one is tried at the next interval; a failed ping is logged and nothing7 //! A failed run is logged and the next one is tried at the next interval; a failed ping is logged and nothing
8 //! else. The ping URL carries a secret, so it is never logged. The worker is not started without a `[backup]`8 //! else. The ping URL carries a secret, so it is never logged. The worker is not started without a `[backup]`
9 //! table.9 //! table.
10+//!
11+//! After every run, scheduled or manual, the outcome is recorded in the `settings` table (see [`record_outcome`])
12+//! so the admin page can show the last success, the last attempt and the error of a failed run. The recorded
13+//! error is short text, never the ping URL.
10 14
11 use std::sync::atomic::{AtomicBool, Ordering};15 use std::sync::atomic::{AtomicBool, Ordering};
12 use std::time::Duration;16 use std::time::Duration;
13 17
14 use in_core::backup;18 use in_core::backup;
15 use in_core::config::Backup;19 use in_core::config::Backup;
16-use in_core::time::now_stamp;20+use in_core::error::Error;
21+use in_core::store::Store;
22+use in_core::time::{now_stamp, stamp_before};
17 use tokio::sync::{Notify, watch};23 use tokio::sync::{Notify, watch};
18 24
19 use crate::state::AppState;25 use crate::state::AppState;
@@ -21,6 +27,18 @@ use crate::state::AppState;
21 /// How long the dead-man ping may take.27 /// How long the dead-man ping may take.
22 pub const PING_TIMEOUT: Duration = Duration::from_secs(10);28 pub const PING_TIMEOUT: Duration = Duration::from_secs(10);
23 29
30+/// Settings key: when a run was last attempted (a stamp). Written after every run.
31+pub const LAST_ATTEMPT_AT: &str = "backup.last_attempt_at";
32+/// Settings key: when a run last succeeded (a stamp).
33+pub const LAST_SUCCESS_AT: &str = "backup.last_success_at";
34+/// Settings key: the short error of the latest run. Present only while the latest run failed.
35+pub const LAST_ERROR: &str = "backup.last_error";
36+/// The longest error text that is stored, in characters. Long errors are cut so the admin page stays short.
37+const ERROR_CHARS: usize = 200;
38+/// The shortest time without a successful backup before the admin page warns: two days, in seconds. The
39+/// limit is never shorter than two backup intervals (see [`is_stale`]).
40+pub const STALE_AFTER: Duration = Duration::from_secs(2 * 24 * 60 * 60);
41+
24 /// Asks the backup worker for a run now. At most one run is pending or running: a request made while one is42 /// Asks the backup worker for a run now. At most one run is pending or running: a request made while one is
25 /// pending or running starts nothing.43 /// pending or running starts nothing.
26 #[derive(Default)]44 #[derive(Default)]
@@ -70,6 +88,46 @@ async fn run_once(state: &AppState, config: &Backup) -> in_core::error::Result<s
70 Ok(set)88 Ok(set)
71 }89 }
72 90
91+/// The short text of a failed run: the first line of its error, without control characters, cut to
92+/// [`ERROR_CHARS`] characters.
93+fn short_error(error: &Error) -> String {
94+ let text = error.to_string();
95+ let line = text.lines().next().unwrap_or_default();
96+ line.chars()
97+ .filter(|c| !c.is_control())
98+ .take(ERROR_CHARS)
99+ .collect()
100+}
101+
102+/// Stores the outcome of one run: the attempt time always; on success the success time and no error; on
103+/// failure the short error. A store failure is logged and never fails the run.
104+async fn record_outcome(store: &Store, outcome: &in_core::error::Result<std::path::PathBuf>) {
105+ let now = now_stamp();
106+ let recorded: in_core::error::Result<()> = async {
107+ store.set_setting(LAST_ATTEMPT_AT, &now).await?;
108+ match outcome {
109+ Ok(_) => {
110+ store.set_setting(LAST_SUCCESS_AT, &now).await?;
111+ store.clear_setting(LAST_ERROR).await
112+ }
113+ Err(error) => store.set_setting(LAST_ERROR, &short_error(error)).await,
114+ }
115+ }
116+ .await;
117+ if let Err(error) = recorded {
118+ tracing::error!(error = %error, "backup: the outcome was not recorded");
119+ }
120+}
121+
122+/// True when there is no successful backup within the limit: [`STALE_AFTER`] or two backup intervals,
123+/// whichever is longer, so a weekly schedule is not always overdue. The stamps have a fixed width, so
124+/// comparing them as text compares their times.
125+pub fn is_stale(last_success: Option<&str>, interval_hours: u32) -> bool {
126+ let interval = Duration::from_secs(u64::from(interval_hours) * 2 * 60 * 60);
127+ let limit = STALE_AFTER.max(interval);
128+ last_success.is_none_or(|stamp| stamp < stamp_before(limit).as_str())
129+}
130+
73 /// Pings the dead-man URL once. Only failures are logged, and the URL itself never is.131 /// Pings the dead-man URL once. Only failures are logged, and the URL itself never is.
74 async fn ping(url: &str) {132 async fn ping(url: &str) {
75 let client = match reqwest::Client::builder().timeout(PING_TIMEOUT).build() {133 let client = match reqwest::Client::builder().timeout(PING_TIMEOUT).build() {
@@ -97,7 +155,9 @@ pub async fn run(state: AppState, mut stop: watch::Receiver<bool>) {
97 let every = Duration::from_secs(u64::from(config.interval_hours) * 60 * 60);155 let every = Duration::from_secs(u64::from(config.interval_hours) * 60 * 60);
98 loop {156 loop {
99 state.backup.begin();157 state.backup.begin();
100- match run_once(&state, &config).await {158+ let outcome = run_once(&state, &config).await;
159+ record_outcome(&state.store, &outcome).await;
160+ match outcome {
101 Ok(_) => {161 Ok(_) => {
102 if let Some(url) = &config.healthcheck_url {162 if let Some(url) = &config.healthcheck_url {
103 ping(url).await;163 ping(url).await;
@@ -116,7 +176,11 @@ pub async fn run(state: AppState, mut stop: watch::Receiver<bool>) {
116 176
117 #[cfg(test)]177 #[cfg(test)]
118 mod tests {178 mod tests {
119- use super::BackupTrigger;179+ use std::time::Duration;
180+
181+ use in_core::time::{now_stamp, stamp_before};
182+
183+ use super::{BackupTrigger, is_stale};
120 184
121 #[test]185 #[test]
122 fn a_second_request_while_one_is_pending_starts_nothing() {186 fn a_second_request_while_one_is_pending_starts_nothing() {
@@ -128,4 +192,14 @@ mod tests {
128 trigger.finish();192 trigger.finish();
129 assert!(trigger.request());193 assert!(trigger.request());
130 }194 }
195+
196+ #[test]
197+ fn no_success_within_the_limit_is_stale() {
198+ assert!(is_stale(None, 24));
199+ assert!(!is_stale(Some(&now_stamp()), 24));
200+ // Three days ago: stale on a daily schedule, not on a weekly one (limit two weeks).
201+ let three_days = stamp_before(Duration::from_secs(3 * 86_400));
202+ assert!(is_stale(Some(&three_days), 24));
203+ assert!(!is_stale(Some(&three_days), 168));
204+ }
131 }205 }
crates/in-web/src/i18n/admin.rsmodified+28 -0
@@ -148,6 +148,14 @@ pub enum AK {
148 NoticeBackup,148 NoticeBackup,
149 /// Refusal: backups are off, so there is nothing to start.149 /// Refusal: backups are off, so there is nothing to start.
150 RefusalBackupOff,150 RefusalBackupOff,
151+ /// Label: when the last successful backup ran.
152+ BackupLast,
153+ /// Label: when the last attempt ran, successful or not.
154+ BackupAttempt,
155+ /// Shown in place of a time when there is none yet.
156+ BackupNever,
157+ /// Warning: backups are on, but none has succeeded within the limit (see `backup::is_stale`).
158+ BackupStale,
151 }159 }
152 160
153 /// The text of `key` in `lang`.161 /// The text of `key` in `lang`.
@@ -299,6 +307,18 @@ pub fn a(lang: Lang, key: AK) -> &'static str {
299 }307 }
300 (AK::NoticeBackup, Lang::En) => "Backup started. It runs in the background.",308 (AK::NoticeBackup, Lang::En) => "Backup started. It runs in the background.",
301 (AK::NoticeBackup, Lang::Tr) => "Yedekleme başlatıldı. Arka planda çalışır.",309 (AK::NoticeBackup, Lang::Tr) => "Yedekleme başlatıldı. Arka planda çalışır.",
310+ (AK::BackupLast, Lang::En) => "Last successful backup",
311+ (AK::BackupLast, Lang::Tr) => "Son başarılı yedekleme",
312+ (AK::BackupAttempt, Lang::En) => "Last attempt",
313+ (AK::BackupAttempt, Lang::Tr) => "Son deneme",
314+ (AK::BackupNever, Lang::En) => "never",
315+ (AK::BackupNever, Lang::Tr) => "henüz yok",
316+ (AK::BackupStale, Lang::En) => {
317+ "No successful backup for longer than expected. Check the backup directory and the last attempt."
318+ }
319+ (AK::BackupStale, Lang::Tr) => {
320+ "Beklenenden uzun süredir başarılı yedekleme yok. Yedek dizinini ve son denemeyi kontrol edin."
321+ }
302 (AK::RefusalBackupOff, Lang::En) => {322 (AK::RefusalBackupOff, Lang::En) => {
303 "Backups are off, so there is nothing to start. Set [backup] dir first."323 "Backups are off, so there is nothing to start. Set [backup] dir first."
304 }324 }
@@ -316,6 +336,14 @@ pub fn backup_schedule(lang: Lang, hours: u32, keep: u32) -> String {
316 }336 }
317 }337 }
318 338
339+/// The alert line of a failed latest run, with the short error the worker recorded.
340+pub fn backup_failed(lang: Lang, error: &str) -> String {
341+ match lang {
342+ Lang::En => format!("The last backup failed: {error}"),
343+ Lang::Tr => format!("Son yedekleme başarısız oldu: {error}"),
344+ }
345+}
346+
319 /// The sentence for a refusal word. Range refusals (any word ending `_range`) get their own text; backups347 /// The sentence for a refusal word. Range refusals (any word ending `_range`) get their own text; backups
320 /// that are off get theirs; anything else gets the generic one.348 /// that are off get theirs; anything else gets the generic one.
321 pub fn refusal(lang: Lang, word: &str) -> &'static str {349 pub fn refusal(lang: Lang, word: &str) -> &'static str {
crates/in-web/src/pages/admin.rsmodified+56 -11
@@ -2,7 +2,8 @@
2 //! claim, stored as `members.is_admin`) sees it. Anyone else gets `404`, and so does a write from them.2 //! claim, stored as `members.is_admin`) sees it. Anyone else gets `404`, and so does a write from them.
3 //!3 //!
4 //! The page shows: health (the database and the blob store answer), the storage backend and its free space4 //! The page shows: health (the database and the blob store answer), the storage backend and its free space
5-//! or reachability, the backup schedule with a button that asks for a backup now, the base URL, every person5+//! or reachability, the backup schedule with the last success and attempt, an alert for a failed latest run,
6+//! a warning when no success is recent, and a button that asks for a backup now, the base URL, every person
6 //! with their quota, every service with its usage and quota, the defaults with the layer each value comes from7 //! with their quota, every service with its usage and quota, the defaults with the layer each value comes from
7 //! (UI, file or built-in default), and the audit log with keyset paging and filters.8 //! (UI, file or built-in default), and the audit log with keyset paging and filters.
8 //!9 //!
@@ -35,15 +36,16 @@ use topcoat::view::{View, component, view};
35 36
36 use crate::audit::{self, Entry};37 use crate::audit::{self, Entry};
37 use crate::auth::{Viewer, require_admin, require_admin_csrf};38 use crate::auth::{Viewer, require_admin, require_admin_csrf};
39+use crate::backup::{LAST_ATTEMPT_AT, LAST_ERROR, LAST_SUCCESS_AT, is_stale};
38 use crate::health::{probe_blobs, probe_database};40 use crate::health::{probe_blobs, probe_database};
39 use crate::i18n::Lang;41 use crate::i18n::Lang;
40-use crate::i18n::admin::{AK, a, backup_schedule, notice, refusal};42+use crate::i18n::admin::{AK, a, backup_failed, backup_schedule, notice, refusal};
41 use crate::live::{Topic, stream_changes};43 use crate::live::{Topic, stream_changes};
42 use crate::oidc::percent_encode;44 use crate::oidc::percent_encode;
43 use crate::pages::drive::{viewer_lang, with_param};45 use crate::pages::drive::{viewer_lang, with_param};
44 use crate::state::AppState;46 use crate::state::AppState;
45 use crate::views::drive::{size_text, stamp_text};47 use crate::views::drive::{size_text, stamp_text};
46-use crate::views::{ViewerInfo, alert, notice as flash_notice, shell};48+use crate::views::{ViewerInfo, alert, notice as flash_notice, shell, warning};
47 49
48 /// One mebibyte, the unit of the admin's byte fields.50 /// One mebibyte, the unit of the admin's byte fields.
49 const MIB: i64 = 1024 * 1024;51 const MIB: i64 = 1024 * 1024;
@@ -149,8 +151,8 @@ pub struct BackupForm {
149 pub csrf: String,151 pub csrf: String,
150 }152 }
151 153
152-/// What the backups section shows: where the sets go and how often a run happens. `None` when the154+/// What the backups section shows: where the sets go, how often a run happens, and the outcome the worker
153-/// configuration has no `[backup]` table.155+/// recorded. `None` when the configuration has no `[backup]` table.
154 #[derive(Debug, Clone)]156 #[derive(Debug, Clone)]
155 pub struct BackupStatus {157 pub struct BackupStatus {
156 /// The directory that receives the sets.158 /// The directory that receives the sets.
@@ -159,6 +161,35 @@ pub struct BackupStatus {
159 pub interval_hours: u32,161 pub interval_hours: u32,
160 /// Sets kept.162 /// Sets kept.
161 pub keep: u32,163 pub keep: u32,
164+ /// When a run was last attempted, if one ran.
165+ pub last_attempt: Option<String>,
166+ /// When a run last succeeded, if one did.
167+ pub last_success: Option<String>,
168+ /// The short error of the latest run, present only while that run failed.
169+ pub last_error: Option<String>,
170+ /// True when no success is recent enough (see `backup::is_stale`).
171+ pub stale: bool,
172+}
173+
174+/// The backups section's data: the configuration and what the worker recorded. `None` when backups are off.
175+async fn backup_status(state: &AppState) -> Result<Option<BackupStatus>> {
176+ let Some(config) = state.config.backup.as_ref() else {
177+ return Ok(None);
178+ };
179+ let last_success = state.store.get_setting(LAST_SUCCESS_AT).await?;
180+ Ok(Some(BackupStatus {
181+ dir: config.dir.display().to_string(),
182+ interval_hours: config.interval_hours,
183+ keep: config.keep,
184+ last_attempt: state.store.get_setting(LAST_ATTEMPT_AT).await?,
185+ stale: is_stale(last_success.as_deref(), config.interval_hours),
186+ last_success,
187+ last_error: state
188+ .store
189+ .get_setting(LAST_ERROR)
190+ .await?
191+ .filter(|error| !error.is_empty()),
192+ }))
162 }193 }
163 194
164 /// Whether a field's form unit is MiB.195 /// Whether a field's form unit is MiB.
@@ -410,7 +441,8 @@ async fn storage_section(lang: Lang, status: &StorageStatus) -> Result<impl View
410 })441 })
411 }442 }
412 443
413-/// The backups section: the directory and schedule, and the button that asks for a run now. Without444+/// The backups section: the directory and schedule, the last success and attempt, an alert when the latest
445+/// run failed, a warning when no success is recent, and the button that asks for a run now. Without
414 /// `[backup]` it says that backups are off.446 /// `[backup]` it says that backups are off.
415 #[component]447 #[component]
416 async fn backup_section(448 async fn backup_section(
@@ -422,6 +454,15 @@ async fn backup_section(
422 backup_schedule(lang, s.interval_hours, s.keep)454 backup_schedule(lang, s.interval_hours, s.keep)
423 });455 });
424 let dir = status.map_or_else(String::new, |s| s.dir.clone());456 let dir = status.map_or_else(String::new, |s| s.dir.clone());
457+ let never = || a(lang, AK::BackupNever).to_owned();
458+ let last_success = status.and_then(|s| s.last_success.as_deref());
459+ let last_success = last_success.map_or_else(never, stamp_text);
460+ let last_attempt = status.and_then(|s| s.last_attempt.as_deref());
461+ let last_attempt = last_attempt.map_or_else(never, stamp_text);
462+ let failed = status
463+ .and_then(|s| s.last_error.as_deref())
464+ .map(|error| backup_failed(lang, error));
465+ let stale = status.is_some_and(|s| s.stale);
425 Ok(view! {466 Ok(view! {
426 <section class="admin-section">467 <section class="admin-section">
427 <h2>(a(lang, AK::Backups))</h2>468 <h2>(a(lang, AK::Backups))</h2>
@@ -429,7 +470,15 @@ async fn backup_section(
429 <ul>470 <ul>
430 <li>(a(lang, AK::BackupDir)) ": " <code>(dir.as_str())</code></li>471 <li>(a(lang, AK::BackupDir)) ": " <code>(dir.as_str())</code></li>
431 <li>(schedule.as_str())</li>472 <li>(schedule.as_str())</li>
473+ <li>(a(lang, AK::BackupLast)) ": " (last_success.as_str())</li>
474+ <li>(a(lang, AK::BackupAttempt)) ": " (last_attempt.as_str())</li>
432 </ul>475 </ul>
476+ if let Some(text) = failed.as_deref() {
477+ alert(message: text)
478+ }
479+ if stale {
480+ warning(message: a(lang, AK::BackupStale))
481+ }
433 <form method="post" action="/admin/backup" class="inline-form">482 <form method="post" action="/admin/backup" class="inline-form">
434 <input type="hidden" name="csrf" value=(csrf)>483 <input type="hidden" name="csrf" value=(csrf)>
435 <button class="button" type="submit">(a(lang, AK::BackupNow))</button>484 <button class="button" type="submit">(a(lang, AK::BackupNow))</button>
@@ -734,11 +783,7 @@ async fn admin_page(cx: &Cx) -> Result<impl View> {
734 }783 }
735 let defaults = default_rows(state).await?;784 let defaults = default_rows(state).await?;
736 let storage = storage_status(state).await;785 let storage = storage_status(state).await;
737- let backups = state.config.backup.as_ref().map(|config| BackupStatus {786+ let backups = backup_status(state).await?;
738- dir: config.dir.display().to_string(),
739- interval_hours: config.interval_hours,
740- keep: config.keep,
741- });
742 let probes = probe_all(state).await;787 let probes = probe_all(state).await;
743 let page = state788 let page = state
744 .store789 .store
crates/in-web/src/views/mod.rsmodified+6 -0
@@ -159,6 +159,12 @@ pub async fn notice(message: &str) -> Result<impl View> {
159 Ok(view! { <div class="notice" role="status">(message)</div> })159 Ok(view! { <div class="notice" role="status">(message)</div> })
160 }160 }
161 161
162+/// Something to look at that is not a failure yet, such as a state that has gone stale.
163+#[component]
164+pub async fn warning(message: &str) -> Result<impl View> {
165+ Ok(view! { <div class="warning" role="status">(message)</div> })
166+}
167+
162 /// A section with nothing in it yet: a title, then what to do next.168 /// A section with nothing in it yet: a title, then what to do next.
163 #[component]169 #[component]
164 pub async fn empty_state(title: &str, #[default] child: Child<'_>) -> Result<impl View> {170 pub async fn empty_state(title: &str, #[default] child: Child<'_>) -> Result<impl View> {
docs/architecture.mdmodified+7 -1
@@ -143,7 +143,7 @@ The sweeper removes unreferenced blobs older than 24 h.
143 | `GET /links`, `POST /links`, `/links/{id}/revoke`, `/links/{id}/remint` | my share links |143 | `GET /links`, `POST /links`, `/links/{id}/revoke`, `/links/{id}/remint` | my share links |
144 | `GET/POST /s/{token}` (anonymous) | public share page, folder browsing, password gate, download, media, thumbs |144 | `GET/POST /s/{token}` (anonymous) | public share page, folder browsing, password gate, download, media, thumbs |
145 | `GET /settings` + POST | preferences (theme; language follows `im` unless overridden), storage usage |145 | `GET /settings` + POST | preferences (theme; language follows `im` unless overridden), storage usage |
146-| `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 |146+| `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 |
147 | `GET /avatar/{sub}` | photo proxy with disk cache (contracts.md 3.2) |147 | `GET /avatar/{sub}` | photo proxy with disk cache (contracts.md 3.2) |
148 | `GET /auth/login`, `/auth/callback`, `POST /auth/logout`, `POST /auth/backchannel-logout` | OIDC client |148 | `GET /auth/login`, `/auth/callback`, `POST /auth/logout`, `POST /auth/backchannel-logout` | OIDC client |
149 | `GET /-/alive`, live streams, `/healthz`, `/assets/*` | |149 | `GET /-/alive`, live streams, `/healthz`, `/assets/*` | |
@@ -240,6 +240,12 @@ and has no sessions.
240 - **backup** (optional): snapshot + blob tree manifest, HMAC-SHA256 over the manifest (`manifest.mac`, keyed from240 - **backup** (optional): snapshot + blob tree manifest, HMAC-SHA256 over the manifest (`manifest.mac`, keyed from
241 `in.key`, checked before a restore parses anything), keep N, dead-man pings. The worker also runs when the admin241 `in.key`, checked before a restore parses anything), keep N, dead-man pings. The worker also runs when the admin
242 page asks (`BackupTrigger`: one busy flag and a `Notify` the worker waits on); at most one run is pending or running.242 page asks (`BackupTrigger`: one busy flag and a `Notify` the worker waits on); at most one run is pending or running.
243+ After every run, scheduled or manual, the outcome is written to `settings` (no migration): `backup.last_attempt_at`
244+ always, `backup.last_success_at` on success (and the error is cleared), `backup.last_error` on failure (the first
245+ line of the error, control characters removed, at most 200 characters; never the ping URL). The admin Backups
246+ section shows the last success and the last attempt, an alert while the latest run failed, and a warning when
247+ backups are on and the last success is older than the limit: `max(2 days, 2 × interval_hours)`
248+ (`backup::is_stale`). `/healthz` does not show any of this.
243 249
244 ---250 ---
245 251
style/_components.scssmodified+8 -0
@@ -163,6 +163,14 @@ textarea::placeholder {
163 border-color: var(--accent-soft);163 border-color: var(--accent-soft);
164 }164 }
165 165
166+.warning {
167+ padding: var(--space-3) var(--space-4);
168+ border-radius: var(--radius-sm);
169+ border: 1px solid var(--warn);
170+ background: var(--warn-soft);
171+ color: var(--warn);
172+}
173+
166 // --- Tables and badges ------------------------------------------------------------------------174 // --- Tables and badges ------------------------------------------------------------------------
167 175
168 .table-wrap {176 .table-wrap {