diff --git a/crates/forge-core/src/store/admin_alerts.rs b/crates/forge-core/src/store/admin_alerts.rs index e5eca56..420f1ce 100644 --- a/crates/forge-core/src/store/admin_alerts.rs +++ b/crates/forge-core/src/store/admin_alerts.rs @@ -253,6 +253,17 @@ impl Store { fetch_all(&conn, &sql, params, map_notice).await } + pub async fn admin_notice(&self, user_id: &str, id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!("SELECT {NOTICE_COLS} FROM admin_notifications WHERE id = ?1 AND user_id = ?2"), + (id.to_owned(), user_id.to_owned()), + map_notice, + ) + .await + } + /// Marks one of the user's alert rows read. Another user's row changes nothing. pub async fn mark_admin_notice_read(&self, user_id: &str, id: &str) -> Result<()> { let conn = self.inner.conn.lock().await; diff --git a/crates/forge-core/src/store/imports.rs b/crates/forge-core/src/store/imports.rs index 51429d9..22a8205 100644 --- a/crates/forge-core/src/store/imports.rs +++ b/crates/forge-core/src/store/imports.rs @@ -204,6 +204,22 @@ impl Store { Ok(()) } + pub async fn requeue_failed_import(&self, id: &str) -> Result { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE import_jobs SET state = 'queued', error = NULL, finished_at = NULL, \ + updated_at = ?2 WHERE id = ?1 AND state = 'failed' AND NOT EXISTS (\ + SELECT 1 FROM import_jobs other WHERE other.repo_id = \ + (SELECT repo_id FROM import_jobs WHERE id = ?1) \ + AND other.state IN ('queued', 'running'))", + vec![text(id), text(&now_stamp())], + ) + .await + .map_err(db_err)?; + Ok(changed > 0) + } + /// Records the current stage and how far it is. pub async fn set_import_progress( &self, diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index 4849876..d49bf35 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -837,6 +837,39 @@ impl Store { affected(n) } + pub async fn save_profile( + &self, + user_id: &str, + display_name: &str, + about: &str, + timezone: &str, + ) -> Result<()> { + let display_name = match validate_display_name(display_name)? { + Some(name) => Value::Text(name), + None => Value::Null, + }; + if about.chars().count() > MAX_ABOUT_CHARS { + return Err(Error::Invalid(format!( + "about is longer than {MAX_ABOUT_CHARS} characters" + ))); + } + crate::tz::validate_timezone(timezone)?; + let conn = self.inner.conn.lock().await; + let n = conn + .execute( + "UPDATE users SET display_name = ?2, about = ?3, timezone = ?4 WHERE id = ?1", + vec![ + Value::Text(user_id.to_owned()), + display_name, + Value::Text(about.to_owned()), + Value::Text(timezone.to_owned()), + ], + ) + .await + .map_err(db_err)?; + affected(n) + } + /// Inserts or replaces the user's avatar. `png` is the re-encoded image, `hash` its digest. pub async fn set_avatar(&self, user_id: &str, png: &[u8], hash: &str) -> Result<()> { let conn = self.inner.conn.lock().await; @@ -1583,6 +1616,30 @@ impl Store { affected(n) } + pub async fn reset_password(&self, user_id: &str, password_hash: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let n = tx + .execute( + "UPDATE users SET password_hash = ?2, password_changed_at = ?3 WHERE id = ?1", + (user_id.to_string(), password_hash.to_string(), now_stamp()), + ) + .await + .map_err(db_err)?; + affected(n)?; + tx.execute( + "DELETE FROM sessions WHERE user_id = ?1", + (user_id.to_string(),), + ) + .await + .map_err(db_err)?; + Ok(()) + } + .await; + finish(tx, outcome).await + } + /// Deletes every session of the user except `keep_session_id`. Returns how many were removed. pub async fn delete_sessions_except( &self, diff --git a/crates/forge-core/src/store/webhooks.rs b/crates/forge-core/src/store/webhooks.rs index 5fb0482..31000cc 100644 --- a/crates/forge-core/src/store/webhooks.rs +++ b/crates/forge-core/src/store/webhooks.rs @@ -308,25 +308,28 @@ impl Store { .await } - /// The repo's hooks, oldest first, each with the state of its most recent delivery + /// The repo's hooks, oldest first, each with the state and stamp of its most recent delivery /// (`None` when it has none yet). pub async fn list_webhooks( &self, repo_id: &str, - ) -> Result)>> { + ) -> Result)>> { let sql = format!( "SELECT {WEBHOOK_COLS}, \ (SELECT d.state FROM webhook_deliveries d WHERE d.hook_id = webhooks.id \ + ORDER BY d.created_at DESC, d.id DESC LIMIT 1), \ + (SELECT d.created_at FROM webhook_deliveries d WHERE d.hook_id = webhooks.id \ ORDER BY d.created_at DESC, d.id DESC LIMIT 1) \ FROM webhooks WHERE repo_id = ?1 ORDER BY created_at, id" ); let conn = self.read_conn().await; fetch_all(&conn, &sql, (repo_id.to_string(),), |row| { let last = match col_opt_text(row, 7)? { - Some(s) => Some( + Some(s) => Some(( DeliveryState::parse(&s) .ok_or_else(|| Error::Database(format!("unknown delivery state {s:?}")))?, - ), + col_text(row, 8)?, + )), None => None, }; Ok((map_webhook(row)?, last)) @@ -922,7 +925,10 @@ mod tests { assert_eq!(failed.duration_ms, Some(12)); assert!(failed.delivered_at.is_none()); assert_eq!( - store.list_webhooks(&repo.id).await.unwrap()[0].1, + store.list_webhooks(&repo.id).await.unwrap()[0] + .1 + .as_ref() + .map(|(state, _)| *state), Some(DeliveryState::Failed) ); diff --git a/crates/forge-web-account/Cargo.toml b/crates/forge-web-account/Cargo.toml index 07c6fc6..5836c27 100644 --- a/crates/forge-web-account/Cargo.toml +++ b/crates/forge-web-account/Cargo.toml @@ -12,7 +12,6 @@ forge-web-pages.workspace = true forge-core.workspace = true forge-git.workspace = true forge-ci.workspace = true -forge-web-base.workspace = true topcoat = { workspace = true, default-features = false, features = ["router", "view", "runtime", "cookie", "asset", "serve", "sse", "discover", "compression", "multipart", "tower"] } tokio.workspace = true futures-util.workspace = true @@ -31,8 +30,6 @@ hex.workspace = true sha2.workspace = true time.workspace = true ulid.workspace = true -zip = { workspace = true } -tar.workspace = true webauthn-rs = { version = "0.6.2", features = ["danger-allow-state-serialisation", "conditional-ui"] } diff --git a/crates/forge-web-account/src/pages/activity.rs b/crates/forge-web-account/src/pages/activity.rs index 7634443..3deeb5b 100644 --- a/crates/forge-web-account/src/pages/activity.rs +++ b/crates/forge-web-account/src/pages/activity.rs @@ -41,7 +41,7 @@ fn run_json(run: &ActorRun) -> Value { } /// How a finished run ended, as the activity JSON names it. None for any other state. -pub(crate) fn outcome_word(state: RunState) -> Option<&'static str> { +fn outcome_word(state: RunState) -> Option<&'static str> { match state { RunState::Success => Some("passed"), RunState::Failure | RunState::Error => Some("failed"), @@ -53,7 +53,7 @@ pub(crate) fn outcome_word(state: RunState) -> Option<&'static str> { /// The viewer's activity as JSON. `reviews` and `mentions` count unread inbox rows, `failing` counts /// refs whose newest run failed, `running` and `finished` list the viewer's CI runs and `waiting` /// lists the newest review requests and mentions. Reads only; the caller decides how to send it. -pub(crate) async fn activity_json(state: &AppState, user: &User) -> Result { +async fn activity_json(state: &AppState, user: &User) -> Result { let kinds = state.store.inbox_kind_counts(&user.id).await?; let runs = state.store.actor_runs(&user.id, RECENT_SECS).await?; let waiting = state.store.waiting_on(&user.id, WAITING_LIMIT).await?; diff --git a/crates/forge-web-account/src/pages/admin_backups.rs b/crates/forge-web-account/src/pages/admin_backups.rs index 653bb49..2e2cbf5 100644 --- a/crates/forge-web-account/src/pages/admin_backups.rs +++ b/crates/forge-web-account/src/pages/admin_backups.rs @@ -29,10 +29,9 @@ use crate::pages::admin_server::{ BACKUP_KEYS, Row, notice_of, reset_form, save_topic, setting_lines, setting_rows, with_notice, }; use crate::pages::admin_users::admin_only; -use crate::pages::issues_list::stamp_unix; use crate::state::AppState; use crate::views::parts::{RailItem, head, post_act, rail}; -use crate::views::{alert, enc, rel_time, shell}; +use crate::views::{alert, enc, human_size, rel_time, shell, stamp_unix}; /// Runs shown on the page. const RUN_LIMIT: u32 = 20; @@ -59,21 +58,6 @@ struct RunRow { detail: String, } -/// `"512 B"`, `"12.3 KiB"`, `"4.0 MiB"` and so on. -fn human_bytes(bytes: u64) -> String { - const UNITS: [&str; 4] = ["KiB", "MiB", "GiB", "TiB"]; - if bytes < 1024 { - return format!("{bytes} B"); - } - let mut value = bytes as f64 / 1024.0; - let mut unit = 0; - while value >= 1024.0 && unit + 1 < UNITS.len() { - value /= 1024.0; - unit += 1; - } - format!("{value:.1} {}", UNITS[unit]) -} - fn duration_text(run: &BackupRun) -> String { let start = stamp_unix(&run.started_at); let Some(end) = run.finished_at.as_deref().map(stamp_unix) else { @@ -101,7 +85,7 @@ fn run_row(run: &BackupRun, lang: Lang) -> RunRow { trigger: g::trigger_name(lang, run.trigger).to_owned(), started: run.started_at.clone(), duration: duration_text(run), - size: run.bytes.map(human_bytes).unwrap_or_default(), + size: run.bytes.map(|b| human_size(lang, b)).unwrap_or_default(), status, detail, } @@ -583,11 +567,4 @@ mod tests { ); assert_eq!(fx.state.jobs.running(), None); } - - #[test] - fn human_bytes_scales() { - assert_eq!(human_bytes(512), "512 B"); - assert_eq!(human_bytes(2048), "2.0 KiB"); - assert_eq!(human_bytes(3 * 1024 * 1024), "3.0 MiB"); - } } diff --git a/crates/forge-web-account/src/pages/admin_health.rs b/crates/forge-web-account/src/pages/admin_health.rs index 9f20b10..21f2652 100644 --- a/crates/forge-web-account/src/pages/admin_health.rs +++ b/crates/forge-web-account/src/pages/admin_health.rs @@ -1,6 +1,6 @@ //! Page: instance health for admins (`/admin/health`). A summary line, then one sheet with the alerts, //! a storage topic with the data disk's usage bar, and a services topic. Every number is a cheap query -//! or a short external probe (`df`), so there is no polling; reloading the page, or opening it again, +//! or a `statvfs` call, so there is no polling; reloading the page, or opening it again, //! reads fresh values. The tree size of the repos (`du`) walks every repo, so a background task caches //! it (see [`spawn_repo_size`]) and the page only reads the cache. Non-admins get 404. @@ -80,10 +80,12 @@ struct Usage { path: String, /// Percent used, the bar's fill. pct: u8, - /// At least 90% used. + /// At least [`DISK_BAD_PCT`] used. bad: bool, } +const DISK_BAD_PCT: u8 = 90; + /// One fact in the storage topic: one row. struct Fact { label: &'static str, @@ -102,6 +104,18 @@ struct Service { stamp: Option, } +impl Service { + fn new(label: &'static str, dot: Dot, value: String) -> Self { + Self { + label, + dot, + value, + detail: String::new(), + stamp: None, + } + } +} + /// Everything the page shows, and how many items need attention. struct Health { usage: Option, @@ -127,15 +141,6 @@ fn space(lang: Lang, total: u64, avail: u64) -> (u8, String) { (pct, text) } -/// `(total, available)` bytes from `df -Pk ` output. -fn parse_df(output: &str) -> Option<(u64, u64)> { - let line = output.lines().nth(1)?; - let fields: Vec<&str> = line.split_whitespace().collect(); - let total: u64 = fields.get(1)?.parse().ok()?; - let avail: u64 = fields.get(3)?.parse().ok()?; - Some((total.saturating_mul(1024), avail.saturating_mul(1024))) -} - /// Kilobytes from `du -sk ` output, as bytes. fn parse_du(output: &str) -> Option { let kb: u64 = output.split_whitespace().next()?.parse().ok()?; @@ -155,7 +160,11 @@ async fn probe(program: &str, args: &[&str], path: &Path, limit: Duration) -> Op } async fn disk(path: &Path) -> Option<(u64, u64)> { - parse_df(&probe("df", &["-Pk"], path, Duration::from_secs(3)).await?) + let path = path.to_path_buf(); + tokio::task::spawn_blocking(move || crate::alerts::disk_space(&path)) + .await + .ok() + .flatten() } async fn tree_size(path: &Path, limit: Duration) -> Option { @@ -255,7 +264,7 @@ async fn gather(state: &AppState, lang: Lang) -> Result { free_of_total, path: data_dir.to_string_lossy().into_owned(), pct, - bad: pct >= 90, + bad: pct >= DISK_BAD_PCT, } }); @@ -286,7 +295,11 @@ async fn gather(state: &AppState, lang: Lang) -> Result { label: at(lang, A::BackupDirectory), value: text, detail: backup, - dot: if pct >= 90 { Dot::Bad } else { Dot::Neutral }, + dot: if pct >= DISK_BAD_PCT { + Dot::Bad + } else { + Dot::Neutral + }, } } None => Fact { @@ -347,20 +360,16 @@ async fn gather(state: &AppState, lang: Lang) -> Result { stamp: Some(run.started_at.clone()), } } - None if backup_on => Service { - label: at(lang, A::LastBackup), - dot: Dot::Neutral, - value: at(lang, A::Never).to_owned(), - detail: String::new(), - stamp: None, - }, - None => Service { - label: at(lang, A::LastBackup), - dot: Dot::Off, - value: at(lang, A::NotConfigured).to_owned(), - detail: String::new(), - stamp: None, - }, + None if backup_on => Service::new( + at(lang, A::LastBackup), + Dot::Neutral, + at(lang, A::Never).to_owned(), + ), + None => Service::new( + at(lang, A::LastBackup), + Dot::Off, + at(lang, A::NotConfigured).to_owned(), + ), }); let replicating = !live.replication.target.trim().is_empty(); @@ -390,22 +399,18 @@ async fn gather(state: &AppState, lang: Lang) -> Result { stamp: status.last_ok_at.clone(), } } - None => Service { - label: at(lang, A::Replication), - dot: Dot::Neutral, - value: at(lang, A::Never).to_owned(), - detail: String::new(), - stamp: None, - }, + None => Service::new( + at(lang, A::Replication), + Dot::Neutral, + at(lang, A::Never).to_owned(), + ), } } else { - Service { - label: at(lang, A::Replication), - dot: Dot::Off, - value: at(lang, A::NotConfigured).to_owned(), - detail: String::new(), - stamp: None, - } + Service::new( + at(lang, A::Replication), + Dot::Off, + at(lang, A::NotConfigured).to_owned(), + ) }); let uptime = uptime_secs().map_or_else( @@ -488,7 +493,6 @@ async fn health_view( nav: (Vec, Option, Option), ) -> Result { // The heading counts every active alert; the sheet lists the current page of them. - let count = total; let (links, prev, next) = nav; let Health { usage, @@ -498,7 +502,7 @@ async fn health_view( attention, } = health; // An active alert needs attention as much as a failing service does. - let attention = attention + count; + let attention = attention + total; // The verdict leads the head's line, with its dot, so the page says how things are first. let summary = if attention > 0 { SubPart { @@ -517,9 +521,9 @@ async fn health_view( Ok(view! { head(title: at(lang, A::Health), sub: sub, live: Some("/admin/health/events"))
- if count > 0 { + if total > 0 {