From c80f705c25bb8943e70076e40961320595f6ce81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 20 Oct 2026 18:49:05 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20restart=20the=20server=20fr?= =?UTF-8?q?om=20the=20admin=20page=20and=20follow=20it=20back=20without=20?= =?UTF-8?q?a=20reload?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The button asks for a graceful stop through the self-update path (exit 75, systemd restarts). The page shows Restarting and re-renders itself when the event stream reconnects to a new boot id. --- crates/forge-web/src/pages/admin_server.rs | 200 ++++++++++++++++++++- crates/forge-web/src/self_update.rs | 20 +++ 2 files changed, 219 insertions(+), 1 deletion(-) diff --git a/crates/forge-web/src/pages/admin_server.rs b/crates/forge-web/src/pages/admin_server.rs index aceed2c..49bb795 100644 --- a/crates/forge-web/src/pages/admin_server.rs +++ b/crates/forge-web/src/pages/admin_server.rs @@ -7,11 +7,18 @@ //! A field with an override has "Reset to file value". Secret fields are write-only: the page //! shows only whether they are set. See `forge_core::server_settings` for the rules. //! Saving and resetting are audited, with the keys but never the values. +//! +//! "Restart server" asks for a graceful stop through the self-update path: the process exits with +//! `RESTART_EXIT_CODE` and systemd (`Restart=on-failure`) starts the binary again, which picks up a +//! newly installed one. The page that follows shows "Restarting" and follows an event stream. The +//! stream sends the server's boot id when it connects, so the browser's own reconnect after the +//! restart brings a new id, and the page then re-renders itself with no reload and no polling. use std::collections::{BTreeMap, HashMap}; use forge_core::server_settings::{self as ss, Field, FieldView, Group, Kind, Source, Ty}; use forge_core::{AuditAction, Error}; +use futures_util::StreamExt; use serde::Deserialize; use topcoat::Result; use topcoat::context::{Cx, app_context}; @@ -26,6 +33,8 @@ use crate::auth::check_csrf; use crate::i18n::admin::{self as g, K}; use crate::i18n::{self, Key, Lang}; use crate::pages::admin_users::admin_only; +use crate::pages::ci_runs::{changed_event, events_response}; +use crate::self_update; use crate::state::AppState; use crate::views::{enc, shell}; @@ -33,6 +42,39 @@ use crate::views::{enc, shell}; pub(crate) struct ServerQuery { notice: Option, tab: Option, + /// The boot id of the server that was asked to restart. + restarting: Option, +} + +/// Picks the English or Turkish text. +fn s(lang: Lang, en: &'static str, tr: &'static str) -> &'static str { + match lang { + Lang::En => en, + Lang::Tr => tr, + } +} + +/// How long the restart waits after the request is answered, so the redirect that follows is +/// served by the old process. +const RESTART_GRACE: std::time::Duration = std::time::Duration::from_millis(750); + +/// Where the page stands in a restart. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Restart { + /// No restart was asked from this page. + None, + /// Asked, and this process is still the old one or on its way down. + Pending, + /// Asked, and a new process answered. + Done, +} + +fn restart_state(asked: Option<&str>) -> Restart { + match asked { + None | Some("") => Restart::None, + Some(id) if id == self_update::boot_id() => Restart::Pending, + Some(_) => Restart::Done, + } } struct OptionRow { @@ -170,15 +212,27 @@ async fn server_view( group: Group, rows: Vec, notice: Option, + restart: Restart, ) -> Result { let tab = group.slug(); let any_editable = rows.iter().any(|r| !r.fixed); + let live = (restart == Restart::Pending).then_some("/admin/server/events"); Ok(view! { +

(g::t(lang, K::ServerSettings))

(g::t(lang, K::ServerSettingsIntro))

(match lang { Lang::Tr => "Sürüm", _ => "Version" }) " " (forge_ci::build::display())

+ if restart == Restart::Pending { +
+

(s(lang, "Restarting...", "Yeniden başlatılıyor...")) " " (s(lang, "This page comes back by itself when the server is up again.", "Sunucu tekrar ayağa kalkınca bu sayfa kendiliğinden geri gelir."))

+
+ } else if restart == Restart::Done { +
+

(s(lang, "The server restarted. Settings that needed a restart are applied now.", "Sunucu yeniden başladı. Yeniden başlatma gerektiren ayarlar artık uygulandı."))

+
+ }
}) } @@ -265,7 +340,7 @@ async fn server_page(cx: &Cx) -> Result { let csrf = viewer.1.csrf_token.clone(); let title = g::t(lang, K::ServerSettings); Ok(view! { - shell(title: title, viewer: Some(&viewer), server_view(lang: lang, csrf: csrf, group: group, rows: rows, notice: query.notice.clone())) + shell(title: title, viewer: Some(&viewer), server_view(lang: lang, csrf: csrf, group: group, rows: rows, notice: query.notice.clone(), restart: restart_state(query.restarting.as_deref()))) }) } @@ -342,6 +417,63 @@ async fn save( Ok(Some(())) } +#[derive(Deserialize, Default)] +struct RestartForm { + #[serde(default)] + csrf: String, + #[serde(default)] + tab: String, +} + +/// Audits the request, answers with the page that shows "Restarting", and a moment later asks the +/// server to stop gracefully. The process then exits with `RESTART_EXIT_CODE` and systemd starts it. +#[route(POST "/admin/server/restart")] +async fn server_restart(cx: &Cx, Form(form): Form) -> Result { + let viewer = admin_only(cx).await?; + if !check_csrf(&viewer.1, &form.csrf) { + return Err(forbidden().into()); + } + let state = app_context::(cx); + let group = Group::parse(&form.tab).unwrap_or(Group::General); + audit::record( + &state.store, + Some(cx), + Actor::User(&viewer.0), + AuditAction::ServerRestarted, + Target { + kind: "server", + id: "", + name: "", + }, + serde_json::json!({ "boot_id": self_update::boot_id() }), + ) + .await; + tracing::info!(actor_id = %viewer.0.id, "server restart requested from the admin page"); + tokio::spawn(async { + tokio::time::sleep(RESTART_GRACE).await; + self_update::request_restart(); + }); + Err(see_other(format!( + "/admin/server?tab={}&restarting={}", + group.slug(), + enc(self_update::boot_id()) + )) + .into()) +} + +/// The stream of the "Restarting" page. It sends one `changed` event with the boot id when it +/// connects and then stays quiet. The server going down closes it, the browser reconnects by +/// itself, and the first event of the new process re-renders the page. +#[route(GET "/admin/server/events")] +async fn server_events(cx: &Cx) -> Result { + admin_only(cx).await?; + let events = futures_util::stream::once(std::future::ready(changed_event( + self_update::boot_id().to_owned(), + ))) + .chain(futures_util::stream::pending()); + events_response(cx, events) +} + #[derive(Deserialize, Default)] struct ResetForm { #[serde(default)] @@ -670,6 +802,72 @@ mod tests { assert!(fx.state.store.server_overrides().await.unwrap().is_empty()); } + #[tokio::test] + async fn restart_is_admin_only_audited_and_the_page_shows_the_restarting_state() { + let fx = fixture().await; + for token in [None, Some(USER_TOKEN)] { + let form = format!("csrf={CSRF}&tab=general"); + let (status, _, _) = send( + &fx.router, + "POST", + "/admin/server/restart", + token, + Some(form), + ) + .await; + assert_eq!(status, 404); + let (status, _, _) = send(&fx.router, "GET", "/admin/server/events", token, None).await; + assert_eq!(status, 404); + } + let (status, _, _) = send( + &fx.router, + "POST", + "/admin/server/restart", + Some(ADMIN_TOKEN), + Some("csrf=wrong&tab=general".to_owned()), + ) + .await; + assert_eq!(status, 403); + + // The page offers the button with a confirm step. + let page = admin_get(&fx, "/admin/server").await; + assert!(page.contains("Restart server")); + assert!(page.contains("confirm-inline")); + assert!(!page.contains("Restarting...")); + + let form = format!("csrf={CSRF}&tab=general"); + let (status, _, location) = send( + &fx.router, + "POST", + "/admin/server/restart", + Some(ADMIN_TOKEN), + Some(form), + ) + .await; + assert_eq!(status, 303); + assert!(location.contains(&format!("restarting={}", self_update::boot_id()))); + let entries = fx + .state + .store + .list_audit(&Default::default(), None, 50) + .await + .unwrap(); + assert!( + entries + .iter() + .any(|e| e.action == AuditAction::ServerRestarted) + ); + + // Same process: "Restarting" with the event stream. A new process: back to normal. + let page = admin_get(&fx, &location).await; + assert!(page.contains("Restarting...")); + assert!(page.contains(r#"data-live="/admin/server/events""#)); + let page = admin_get(&fx, "/admin/server?restarting=an-older-boot").await; + assert!(!page.contains("Restarting...")); + assert!(!page.contains("data-live=")); + assert!(page.contains("The server restarted")); + } + #[tokio::test] async fn saving_is_audited_without_values() { let fx = fixture().await; diff --git a/crates/forge-web/src/self_update.rs b/crates/forge-web/src/self_update.rs index f9f8966..0aff3f9 100644 --- a/crates/forge-web/src/self_update.rs +++ b/crates/forge-web/src/self_update.rs @@ -88,6 +88,26 @@ pub async fn restart_requested() { RESTART.notified().await; } +/// Asks the server to stop gracefully and exit with `RESTART_EXIT_CODE`, so the supervisor starts +/// the binary again. The same path a self-update swap takes, without a swap. Used by the admin +/// "Restart server" button. +pub fn request_restart() { + RESTART_REQUESTED.store(true, Ordering::SeqCst); + RESTART.notify_one(); +} + +/// An id that is new for every process start. A page that sees it change knows the server +/// restarted. +pub fn boot_id() -> &'static str { + static ID: OnceLock = OnceLock::new(); + ID.get_or_init(|| { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()); + format!("{:x}{nanos:x}", std::process::id()) + }) +} + /// Whether a swap asked the process to exit with `RESTART_EXIT_CODE`. pub fn restart_pending() -> bool { RESTART_REQUESTED.load(Ordering::SeqCst)