From 72da983d5b91d8bd45703cc26a05ccddcff2104d 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:05:09 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20back=20up=20now=20from=20th?= =?UTF-8?q?e=20settings=20page=20while=20the=20server=20runs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 +++ crates/iz-web/src/backup.rs | 56 +++++++++++++++++++++++++++-- crates/iz-web/src/boot.rs | 2 ++ crates/iz-web/src/family.rs | 1 + crates/iz-web/src/i18n/admin.rs | 31 ++++++++++++++++ crates/iz-web/src/pages/admin.rs | 1 + crates/iz-web/src/pages/settings.rs | 29 ++++++++++++++- crates/iz-web/src/state.rs | 3 ++ crates/iz-web/src/views/admin.rs | 14 ++++++++ docs/architecture.md | 6 ++-- 10 files changed, 142 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 73e0d1c..ed81312 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,10 @@ With a `[backup]` section, iz writes a backup set into `dir` every `interval_hou - `manifest.json`: a SHA-256 for each file, and - `manifest.mac`: an HMAC-SHA256 of `manifest.json`, keyed from `iz.key`. +While the server runs, an administrator can start a backup from the Settings page with the "Back up now" button +(it appears when `[backup] dir` is set). The running backup worker writes the set in the background. Only one run +is pending or running at a time: a press while one is pending or running starts nothing. The button is audited. + Backups do not copy `iz.key`. Keep that copy separately, as described in First run. A set can only be checked and restored with the same `iz.key` that wrote it; a set without a valid `manifest.mac` is refused. diff --git a/crates/iz-web/src/backup.rs b/crates/iz-web/src/backup.rs index 7746c28..89a5676 100644 --- a/crates/iz-web/src/backup.rs +++ b/crates/iz-web/src/backup.rs @@ -8,9 +8,14 @@ //! stamp only when complete, so a directory with a manifest is always a whole set. A failed set is removed. //! Only directories this worker created, or names that match the stamp pattern and hold a manifest, are ever //! deleted. Nothing is written in place. +//! +//! 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. 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; @@ -19,10 +24,42 @@ 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::{Error, Result}; -use tokio::sync::watch; +use tokio::sync::{Notify, watch}; use crate::state::AppState; +/// 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 scheduled run, until that run ends. + busy: AtomicBool, + /// Wakes the worker out of its wait 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 + } + + /// 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); + } +} + /// Prefix of a set that is still being written. Reason: a crash leaves a visibly unfinished directory. const TMP_PREFIX: &str = ".tmp-"; /// The database copy inside a set. @@ -35,7 +72,8 @@ const SET_STAMP_FORMAT: &str = "%Y%m%dT%H%M%SZ"; const SET_NAME_LEN: usize = 16; /// 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`. +/// The first backup runs at once, then one every `interval_hours`, or sooner when an administrator asks for +/// one (see [`BackupTrigger`]). pub fn spawn(state: AppState, mut stop: watch::Receiver) { let Some(policy) = state.config.backup.clone() else { return; @@ -54,9 +92,12 @@ pub fn spawn(state: AppState, mut stop: watch::Receiver) { }; let interval = Duration::from_secs(u64::from(policy.interval_hours) * 3600); loop { + state.backup.begin(); run_once(&state, &policy, client.as_ref(), &mut stop).await; + state.backup.finish(); tokio::select! { () = tokio::time::sleep(interval) => {} + () = state.backup.wake.notified() => {} _ = stop.wait_for(|stopped| *stopped) => break, } } @@ -231,6 +272,17 @@ async fn ping(client: &reqwest::Client, url: &str) { mod tests { use super::*; + #[test] + fn a_second_request_while_one_is_pending_or_running_starts_nothing() { + let trigger = BackupTrigger::default(); + assert!(trigger.request()); + assert!(!trigger.request()); + trigger.begin(); + assert!(!trigger.request()); + trigger.finish(); + assert!(trigger.request()); + } + /// A finished set on disk: a directory with a manifest, named by its stamp. fn fake_set(dir: &Path, name: &str) { let set = dir.join(name); diff --git a/crates/iz-web/src/boot.rs b/crates/iz-web/src/boot.rs index 9904fd6..c7207c4 100644 --- a/crates/iz-web/src/boot.rs +++ b/crates/iz-web/src/boot.rs @@ -123,6 +123,7 @@ async fn open_state(config: Config) -> iz_core::Result { family: Arc::default(), in_store, blob_lock: Arc::default(), + backup: Arc::default(), }) } @@ -202,6 +203,7 @@ mod tests { family: Arc::default(), in_store: None, blob_lock: Arc::default(), + backup: Arc::default(), }; (dir, state) } diff --git a/crates/iz-web/src/family.rs b/crates/iz-web/src/family.rs index e960d3a..267b84d 100644 --- a/crates/iz-web/src/family.rs +++ b/crates/iz-web/src/family.rs @@ -237,6 +237,7 @@ mod tests { family: std::sync::Arc::default(), in_store: None, blob_lock: std::sync::Arc::default(), + backup: std::sync::Arc::default(), }; let request = http::Request::get("/no/such/page") .header(http::header::ACCEPT, "text/html") diff --git a/crates/iz-web/src/i18n/admin.rs b/crates/iz-web/src/i18n/admin.rs index f6525fe..434aa5e 100644 --- a/crates/iz-web/src/i18n/admin.rs +++ b/crates/iz-web/src/i18n/admin.rs @@ -51,6 +51,11 @@ pub enum K { MessageSubject, MessageBody, SendMessage, + // Backups + BackupHeading, + BackupHelp, + BackupOff, + BackupNow, // Notices NoticeSenderSaved, NoticeCheckOk, @@ -61,6 +66,7 @@ pub enum K { NoticeRuleDeleted, NoticeRuleSwitched, NoticeRetried, + NoticeBackupStarted, // Rules RulesTitle, RulesHelp, @@ -131,6 +137,7 @@ pub enum K { ReasonProject, FilterKind, // Errors + ErrBackupOff, } /// The text of `key` in `lang`. Placeholders are `{}` and are filled by [`fill`]. @@ -245,6 +252,30 @@ pub fn t(lang: Lang, key: K) -> &'static str { (K::NoticeRuleSwitched, Tr) => "Kural değiştirildi.", (K::NoticeRetried, En) => "Queued again.", (K::NoticeRetried, Tr) => "Yeniden kuyruğa alındı.", + (K::NoticeBackupStarted, En) => "Backup started.", + (K::NoticeBackupStarted, Tr) => "Yedekleme başlatıldı.", + (K::BackupHeading, En) => "Backups", + (K::BackupHeading, Tr) => "Yedeklemeler", + (K::BackupHelp, En) => { + "Backups run on the schedule in the [backup] section. Back up now starts one run in the background, and the server keeps running." + } + (K::BackupHelp, Tr) => { + "Yedeklemeler [backup] bölümündeki takvimde çalışır. Şimdi yedekle arka planda bir yedekleme başlatır ve sunucu çalışmaya devam eder." + } + (K::BackupOff, En) => { + "Backups are off. Set [backup] dir in the config file to turn them on." + } + (K::BackupOff, Tr) => { + "Yedekleme kapalı. Açmak için yapılandırma dosyasında [backup] dir ayarlayın." + } + (K::BackupNow, En) => "Back up now", + (K::BackupNow, Tr) => "Şimdi yedekle", + (K::ErrBackupOff, En) => { + "Backups are off, so there is nothing to start. Set [backup] dir first." + } + (K::ErrBackupOff, Tr) => { + "Yedekleme kapalı, başlatılacak bir şey yok. Önce [backup] dir ayarlayın." + } (K::RulesTitle, En) => "Mail rules", (K::RulesTitle, Tr) => "Mail kuralları", (K::RulesHelp, En) => "A rule mails people when something happens on the board.", diff --git a/crates/iz-web/src/pages/admin.rs b/crates/iz-web/src/pages/admin.rs index faed501..1bb103d 100644 --- a/crates/iz-web/src/pages/admin.rs +++ b/crates/iz-web/src/pages/admin.rs @@ -53,6 +53,7 @@ pub fn notice_text(lang: Lang, code: &str, queued: Option<&str>) -> Option t(lang, K::NoticeRuleDeleted).to_owned(), "rule_switched" => t(lang, K::NoticeRuleSwitched).to_owned(), "retried" => t(lang, K::NoticeRetried).to_owned(), + "backup" => t(lang, K::NoticeBackupStarted).to_owned(), "role_set" => structure_t(lang, StructureK::NoticeRoleSet).to_owned(), "limits" => structure_t(lang, StructureK::NoticeLimitsSaved).to_owned(), "storage" => structure_t(lang, StructureK::NoticeStorageSaved).to_owned(), diff --git a/crates/iz-web/src/pages/settings.rs b/crates/iz-web/src/pages/settings.rs index b89f007..850ddfc 100644 --- a/crates/iz-web/src/pages/settings.rs +++ b/crates/iz-web/src/pages/settings.rs @@ -25,7 +25,7 @@ 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, user_text, viewer_of}; +use crate::pages::admin::{CsrfForm, REFUSED, back, notice_text, record, user_text, viewer_of}; use crate::pages::board::the_board; use crate::state::AppState; use crate::views::admin::{SenderForm, SettingsView, settings_content}; @@ -137,6 +137,7 @@ async fn settings_view( extensions, server: server_info(state).await?, storage, + backups: state.config.backup.is_some(), }) } @@ -375,6 +376,32 @@ async fn send_test(cx: &Cx, form: Option>) -> Result { } } +/// `POST /settings/backup`: asks the backup worker for a backup now. Refused when `[backup] dir` is not set. A +/// request made while a run is pending or running starts nothing, and gets the same notice. +#[route(POST "/settings/backup")] +async fn back_up_now(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; + 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?; + return render(cx, &me, page, REFUSED).await; + } + let started = state.backup.request(); + record( + state, + &me, + "backup.requested", + "settings", + None, + serde_json::json!({ "started": started }), + ) + .await; + back("/settings?notice=backup") +} + /// `POST /settings/reminders`: the lead time (0 is off) and the cap per member per hour. #[route(POST "/settings/reminders")] async fn save_reminders(cx: &Cx, form: Option>) -> Result { diff --git a/crates/iz-web/src/state.rs b/crates/iz-web/src/state.rs index 68f8ae8..accad1b 100644 --- a/crates/iz-web/src/state.rs +++ b/crates/iz-web/src/state.rs @@ -5,6 +5,7 @@ use std::sync::Arc; use iz_core::config::Config; use iz_core::store::Store; +use crate::backup::BackupTrigger; use crate::family::FamilyCache; use crate::in_store::InStore; use crate::live::LiveHub; @@ -32,4 +33,6 @@ pub struct AppState { /// local copy's removal, and a Files copy's deletion. The mover and the deleter take it, so a stale record /// can never remove the live copy (see `attachments.rs`). pub blob_lock: Arc>, + /// Asks the backup worker for a run now (the settings page). Shared with the worker. + pub backup: Arc, } diff --git a/crates/iz-web/src/views/admin.rs b/crates/iz-web/src/views/admin.rs index e0d3e12..6727183 100644 --- a/crates/iz-web/src/views/admin.rs +++ b/crates/iz-web/src/views/admin.rs @@ -138,6 +138,8 @@ 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 rules page: the list, the form (new or editing), and the choices of the form. @@ -312,6 +314,18 @@ pub async fn settings_content(page: &SettingsView, csrf: &str) -> Result(t(lang, K::SendMessage)) +
+

(t(lang, K::BackupHeading))

+ if page.backups { +

(t(lang, K::BackupHelp))

+
+ + +
+ } else { +

(t(lang, K::BackupOff))

+ } +
members_section(lang: lang, members: &page.members, csrf: csrf) storage_section(lang: lang, info: &page.storage, csrf: csrf) limits_section(lang: lang, limit_mib: page.limit_mib.as_str(), extensions: page.extensions.as_str(), csrf: csrf) diff --git a/docs/architecture.md b/docs/architecture.md index 34b8795..b9aaaad 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) | +| `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 /avatar/{sub}` | photo proxy with disk cache, only for members of this board | | OIDC client routes, `/-/alive`, live streams, `/healthz`, `/assets/*` | | @@ -201,7 +201,9 @@ Member, or Admin. Truth-table tested. ## 8. Workers directory mirror, family list, mail outbox, reminders, attachment mover, sweeper (sessions, JTIs, retention of -activity and mail ledger, audit rows past `AUDIT_RETENTION_DAYS` = 365 in batches of 500, orphaned temp files), optional backup. All stop with the stop flag. +activity and mail ledger, audit rows past `AUDIT_RETENTION_DAYS` = 365 in batches of 500, orphaned temp files), optional backup. The backup worker is also woken by "Back up now" on the settings page: +`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. ---