use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use sapphire_ipc::{Endpoint, RpcError};
use sapphire_workspace::AppContext;
use tokio::sync::Notify;
use crate::error::{Error, Result};
use crate::settings::{AppSettings, Settings};
use crate::{AppServer, Sigterm, selection_at};
pub(crate) const RESTART_DELAY: Duration = Duration::from_millis(50);
pub(crate) const CANNOT_RESTART: &str = "this server cannot restart itself; restart its service";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Exit {
Stopped,
Restart,
}
pub(crate) fn request(restart: Option<Arc<Notify>>) -> std::result::Result<(), RpcError> {
let restart = restart.ok_or_else(|| RpcError::internal(CANNOT_RESTART))?;
tracing::info!("a restart was requested");
tokio::spawn(async move {
tokio::task::yield_now().await;
tokio::time::sleep(RESTART_DELAY).await;
restart.notify_one();
});
Ok(())
}
pub async fn serve_restarting<A, F>(ctx: &'static AppContext, owner: A, build: F) -> Result<()>
where
A: AppSettings + Clone,
F: Fn(&Settings) -> AppServer,
{
let _log = sapphire_workspace::logging::install(ctx)?;
let mut rounds = Rounds {
ctx,
owner: Arc::new(owner),
selection: None,
listener: None,
sigterm: None,
};
let mut restarted = false;
loop {
match rounds.serve(&build).await {
Ok(Exit::Stopped) => return Ok(()),
Ok(Exit::Restart) => {
tracing::info!("restarting (requested over IPC)");
restarted = true;
}
Err(err) => {
if restarted {
tracing::error!("restart failed: {err}");
}
return Err(err);
}
}
}
}
struct Rounds {
ctx: &'static AppContext,
owner: Arc<dyn AppSettings>,
selection: Option<PathBuf>,
listener: Option<(Endpoint, sapphire_ipc::Listener)>,
sigterm: Option<Sigterm>,
}
impl Rounds {
async fn serve<F>(&mut self, build: &F) -> Result<Exit>
where
F: Fn(&Settings) -> AppServer,
{
let ctx = self.ctx;
let load = |selection: &Option<PathBuf>| {
Settings::load_with(
ctx,
Arc::clone(&self.owner),
selection_at(ctx, selection.clone()),
)
};
let mut settings = load(&self.selection)?;
let mut server = build(&settings);
if !std::ptr::eq(server.ctx, ctx) {
return Err(Error::Config(format!(
"the build function serves {}, not {}",
server.ctx.app_name, ctx.app_name
)));
}
if server.selection_file != self.selection {
self.selection = server.selection_file.clone();
settings = load(&self.selection)?;
}
server.settings = Some(settings);
if server.signals && self.sigterm.is_none() {
self.sigterm = Sigterm::register()?;
}
let endpoint = server.endpoint_or_default()?;
if self
.listener
.as_ref()
.is_none_or(|(bound, _)| *bound != endpoint)
{
drop(self.listener.take());
#[cfg(unix)]
let bound = sapphire_ipc::bind(&endpoint).await?;
#[cfg(windows)]
let bound = sapphire_ipc::bind(&endpoint)?;
self.listener = Some((endpoint, bound));
}
let (_, bound) = self.listener.as_mut().expect("bound above");
let restart = Arc::new(Notify::new());
server
.serve_on(bound, Some(restart), &mut self.sigterm)
.await
}
}