diff --git a/Cargo.lock b/Cargo.lock index c12d566..27663d5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -456,6 +456,7 @@ dependencies = [ "tracing-subscriber", "uuid", "windows", + "windows-service", "zeroize", ] @@ -1888,6 +1889,12 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "widestring" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" + [[package]] name = "winapi" version = "0.3.9" @@ -2031,6 +2038,17 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows-service" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "857224b3b211c6f3616921f081ee54721ee3ad2ace2fac6a6337e032f7b4dcf2" +dependencies = [ + "bitflags", + "widestring", + "windows-sys 0.61.2", +] + [[package]] name = "windows-strings" version = "0.4.2" diff --git a/Cargo.toml b/Cargo.toml index 30969dc..f8c673c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,3 +28,4 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] } uuid = { version = "1", features = ["v4", "serde"] } windows = { version = "0.61", features = ["Win32_Foundation", "Win32_Security_Cryptography"] } zeroize = "1.8" +windows-service = "0.8" diff --git a/crates/ghostlight-dungeon/Cargo.toml b/crates/ghostlight-dungeon/Cargo.toml index 556e73a..1f8962c 100644 --- a/crates/ghostlight-dungeon/Cargo.toml +++ b/crates/ghostlight-dungeon/Cargo.toml @@ -25,6 +25,7 @@ tracing-subscriber.workspace = true uuid.workspace = true windows.workspace = true zeroize.workspace = true +windows-service.workspace = true [dev-dependencies] tempfile = "3" diff --git a/crates/ghostlight-dungeon/src/main.rs b/crates/ghostlight-dungeon/src/main.rs index 4220707..33b2013 100644 --- a/crates/ghostlight-dungeon/src/main.rs +++ b/crates/ghostlight-dungeon/src/main.rs @@ -17,9 +17,14 @@ use ghostlight_dungeon::{ use serde::Serialize; use std::{ collections::{BTreeMap, BTreeSet}, + ffi::OsString, net::SocketAddr, path::PathBuf, - sync::Arc, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, + time::Duration, }; use tokio::sync::Mutex; use tower_http::services::ServeDir; @@ -34,8 +39,19 @@ struct AppState { deepseek_status: String, } -#[tokio::main] -async fn main() -> anyhow::Result<()> { +fn main() -> anyhow::Result<()> { + #[cfg(windows)] + if std::env::args().any(|argument| argument == "--service") { + windows_service_host::run()?; + return Ok(()); + } + tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build()? + .block_on(run_daemon(None)) +} + +async fn run_daemon(shutdown: Option>) -> anyhow::Result<()> { tracing_subscriber::fmt() .with_env_filter(EnvFilter::from_default_env()) .init(); @@ -119,10 +135,98 @@ async fn main() -> anyhow::Result<()> { let address: SocketAddr = "0.0.0.0:8831".parse()?; let listener = tokio::net::TcpListener::bind(address).await?; tracing::info!(%address, "GhostlightDungeon listening"); - axum::serve(listener, app).await?; + let server = axum::serve(listener, app); + if let Some(shutdown) = shutdown { + server + .with_graceful_shutdown(async move { + while !shutdown.load(Ordering::Acquire) { + tokio::time::sleep(Duration::from_millis(200)).await; + } + }) + .await?; + } else { + server.await?; + } Ok(()) } +#[cfg(windows)] +mod windows_service_host { + use super::*; + use windows_service::{ + define_windows_service, + service::{ + ServiceControl, ServiceControlAccept, ServiceExitCode, ServiceState, ServiceStatus, + ServiceType, + }, + service_control_handler::{self, ServiceControlHandlerResult}, + service_dispatcher, + }; + + const NAME: &str = "GhostlightDungeon"; + const TYPE: ServiceType = ServiceType::OWN_PROCESS; + + pub fn run() -> windows_service::Result<()> { + service_dispatcher::start(NAME, ffi_service_main) + } + define_windows_service!(ffi_service_main, service_main); + + fn service_main(_arguments: Vec) { + let _ = run_service(); + } + + fn run_service() -> windows_service::Result<()> { + let shutdown = Arc::new(AtomicBool::new(false)); + let handler_flag = shutdown.clone(); + let handler = move |event| match event { + ServiceControl::Stop => { + handler_flag.store(true, Ordering::Release); + ServiceControlHandlerResult::NoError + } + ServiceControl::Interrogate => ServiceControlHandlerResult::NoError, + _ => ServiceControlHandlerResult::NotImplemented, + }; + let status = service_control_handler::register(NAME, handler)?; + status.set_service_status(ServiceStatus { + service_type: TYPE, + current_state: ServiceState::StartPending, + controls_accepted: ServiceControlAccept::empty(), + exit_code: ServiceExitCode::Win32(0), + checkpoint: 1, + wait_hint: Duration::from_secs(30), + process_id: None, + })?; + status.set_service_status(ServiceStatus { + service_type: TYPE, + current_state: ServiceState::Running, + controls_accepted: ServiceControlAccept::STOP, + exit_code: ServiceExitCode::Win32(0), + checkpoint: 0, + wait_hint: Duration::default(), + process_id: None, + })?; + let runtime = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .map_err(|_| windows_service::Error::Winapi(std::io::Error::last_os_error()))?; + let result = runtime.block_on(run_daemon(Some(shutdown))); + status.set_service_status(ServiceStatus { + service_type: TYPE, + current_state: ServiceState::Stopped, + controls_accepted: ServiceControlAccept::empty(), + exit_code: if result.is_ok() { + ServiceExitCode::Win32(0) + } else { + ServiceExitCode::Win32(1) + }, + checkpoint: 0, + wait_hint: Duration::default(), + process_id: None, + })?; + Ok(()) + } +} + async fn health(State(state): State) -> Json { Json( serde_json::json!({"schema":"ghostlight.service_health.v1","status":"ok","storeIdentity":state.store.identity(),"deepseek":state.deepseek_status}),