use std::fs::{File, TryLockError};
use std::time::{Duration, Instant};
use isothrum_runner::store::{OperationId, Store};
use crate::VERSION;
use crate::discovery::{ServiceInfo, ServicePaths};
use crate::error::ClientError;
use crate::proto::{Command, PROTOCOL, Reply, Request};
use crate::spawn;
use crate::wire::{Reader, Writer, connect, write_line};
const ANSWER_WAIT: Duration = Duration::from_secs(3);
const SILENT_WAIT: Duration = Duration::from_secs(5);
const STOP_WAIT: Duration = Duration::from_secs(20);
const END_WAIT: Duration = Duration::from_secs(5);
const TURN_WAIT: Duration = Duration::from_secs(60);
const POLL: Duration = Duration::from_millis(50);
const ROUNDS: usize = 8;
const START_SLACK_S: u64 = 2;
type Result<T, E = ClientError> = std::result::Result<T, E>;
pub(crate) type Opened = (Reader, Writer, ServiceInfo);
pub(crate) struct Turn {
_file: File,
}
impl Turn {
pub(crate) async fn take(paths: &ServicePaths) -> Result<Turn> {
spawn::create_home(paths.home())?;
let file = File::options().create(true).truncate(false).write(true).open(paths.replace_lock())?;
let deadline = Instant::now() + TURN_WAIT;
loop {
match file.try_lock() {
Ok(()) => return Ok(Turn { _file: file }),
Err(TryLockError::WouldBlock) if Instant::now() < deadline => tokio::time::sleep(POLL).await,
Err(TryLockError::WouldBlock) => {
return Err(ClientError::Unavailable(format!(
"another client kept replacing the runner service of {} for a minute",
paths.home().display()
)));
}
Err(TryLockError::Error(e)) => return Err(e.into()),
}
}
}
}
enum Found {
Nothing,
Answered(Opened, u32),
Silent(Option<ServiceInfo>),
}
pub(crate) async fn make_room(paths: &ServicePaths, build: Option<&str>) -> Result<Option<Opened>> {
let (mut rounds, mut silent_since) = (0, None::<Instant>);
while rounds < ROUNDS {
match look(paths).await {
Found::Nothing => return Ok(None),
Found::Answered(opened, protocol) if protocol == PROTOCOL && opened.2.version == VERSION && of_build(&opened.2, build) => {
return Ok(Some(opened));
}
Found::Answered(opened, _) => stop(paths, opened).await?,
Found::Silent(info) => {
if silent_since.get_or_insert_with(Instant::now).elapsed() < SILENT_WAIT {
tokio::time::sleep(Duration::from_millis(250)).await;
continue;
}
end_silent(paths, info).await?;
}
}
silent_since = None;
rounds += 1;
}
Err(ClientError::Unavailable(format!(
"the runner service of {} couldn't be replaced: one kept coming back",
paths.home().display()
)))
}
fn of_build(info: &ServiceInfo, build: Option<&str>) -> bool {
build.is_none_or(|build| info.build.as_deref() == Some(build))
}
async fn look(paths: &ServicePaths) -> Found {
let info = paths.read_info();
if let Some(info) = &info
&& let Ok(Some((opened, protocol))) = tokio::time::timeout(ANSWER_WAIT, greet(info.clone())).await
{
return Found::Answered(opened, protocol);
}
if held(paths) { Found::Silent(info) } else { Found::Nothing }
}
async fn greet(info: ServiceInfo) -> Option<(Opened, u32)> {
let (mut reader, mut writer) = connect(&info.endpoint).await.ok()?;
let hello = Request {
id: 0,
command: Command::Hello { protocol: PROTOCOL },
};
write_line(&mut writer, &hello).await.ok()?;
match reader.next::<Reply>().await.ok()?? {
Reply::Hello { protocol, version, .. } => Some(((reader, writer, ServiceInfo { version, ..info }), protocol)),
_ => None,
}
}
fn held(paths: &ServicePaths) -> bool {
let file = match File::options().write(true).open(paths.lock()) {
Ok(file) => file,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return false,
Err(_) => return true,
};
!matches!(file.try_lock(), Ok(()))
}
enum Asked {
Stopping,
Busy(Vec<OperationId>),
Silent,
}
async fn stop(paths: &ServicePaths, opened: Opened) -> Result<()> {
let info = opened.2.clone();
match ask_to_stop(opened).await? {
Asked::Stopping => {
if !gone(paths, &info, STOP_WAIT).await {
tracing::warn!(pid = info.pid, "the runner service agreed to stop and didn't: it is ended");
end(paths, &info).await?;
}
Ok(())
}
Asked::Busy(operations) if operations.is_empty() => {
tokio::time::sleep(Duration::from_millis(200)).await;
Ok(())
}
Asked::Busy(operations) => Err(ClientError::Busy {
version: info.version,
pid: info.pid,
operations,
}),
Asked::Silent => end_silent(paths, Some(info)).await,
}
}
async fn ask_to_stop((mut reader, mut writer, info): Opened) -> Result<Asked> {
let request = Request {
id: 1,
command: Command::ShutdownIfIdle,
};
if write_line(&mut writer, &request).await.is_err() {
return Ok(Asked::Silent);
}
let answer = tokio::time::timeout(ANSWER_WAIT, async {
loop {
match reader.next::<Reply>().await {
Ok(Some(reply)) if reply.id() != Some(1) => {}
other => return other,
}
}
});
match answer.await {
Ok(Ok(Some(Reply::Ok { .. }) | None)) => Ok(Asked::Stopping),
Ok(Ok(Some(Reply::Busy { operations, .. }))) => Ok(Asked::Busy(operations)),
Ok(Ok(Some(Reply::Error { report, .. }))) => Err(ClientError::Protocol(format!(
"the runner service (Isothrum {}) refused to stop: {}",
info.version, report.message
))),
Ok(Ok(Some(other))) => Err(ClientError::Protocol(format!("expected the answer to `shutdown_if_idle`, got {other:?}"))),
Ok(Err(_)) | Err(_) => Ok(Asked::Silent),
}
}
async fn end_silent(paths: &ServicePaths, info: Option<ServiceInfo>) -> Result<()> {
let Some(info) = info.or_else(|| paths.read_info()) else {
return Err(ClientError::Unavailable(format!(
"a process holds the runner service of {} and says nothing of itself: it was left running",
paths.home().display()
)));
};
let operations = unfinished_of(paths, info.pid)?;
if !operations.is_empty() {
return Err(ClientError::Busy {
version: info.version,
pid: info.pid,
operations,
});
}
tracing::warn!(pid = info.pid, version = %info.version, "the runner service doesn't answer: it is ended");
end(paths, &info).await
}
fn unfinished_of(paths: &ServicePaths, pid: u32) -> Result<Vec<OperationId>> {
let rows = Store::read_existing(paths.home(), in_flight).map_err(|e| {
ClientError::Unavailable(format!(
"the runner service (pid {pid}) doesn't answer, and the journal can't be read to tell whether it runs operations ({e}): it was left running"
))
})?;
Ok(rows
.unwrap_or_default()
.into_iter()
.filter(|row| row.owner.pid == pid)
.map(|row| row.id)
.collect())
}
fn in_flight(tx: &isothrum_runner::store::Tx<'_>) -> isothrum_runner::Result<Vec<isothrum_runner::store::OperationRow>> {
tx.in_flight()
}
async fn end(paths: &ServicePaths, info: &ServiceInfo) -> Result<()> {
for force in [false, true] {
if !held(paths) {
return Ok(());
}
if !is_the_service(info).await {
return Err(ClientError::Unavailable(format!(
"the runner service of {} doesn't answer, and pid {} isn't the process its service.json names (it started after): nothing was ended",
paths.home().display(),
info.pid
)));
}
terminate(info.pid, force);
if gone(paths, info, END_WAIT).await {
return Ok(());
}
}
Err(ClientError::Unavailable(format!("the runner service (pid {}) didn't end", info.pid)))
}
async fn is_the_service(info: &ServiceInfo) -> bool {
let Some(said) = isothrum_runner::rfc3339_seconds(&info.started) else {
return false;
};
isothrum_runner::process_started_at(info.pid)
.await
.is_some_and(|started| started <= said.saturating_add(START_SLACK_S))
}
async fn gone(paths: &ServicePaths, info: &ServiceInfo, wait: Duration) -> bool {
let deadline = Instant::now() + wait;
loop {
if !held(paths) && connect(&info.endpoint).await.is_err() {
return true;
}
if Instant::now() >= deadline {
return false;
}
tokio::time::sleep(POLL).await;
}
}
#[cfg(unix)]
fn terminate(pid: u32, force: bool) {
use nix::sys::signal::{Signal, kill};
let Some(pid) = i32::try_from(pid).ok().filter(|p| *p > 1).map(nix::unistd::Pid::from_raw) else {
return;
};
let signal = if force { Signal::SIGKILL } else { Signal::SIGTERM };
if let Err(e) = kill(pid, signal) {
tracing::debug!(%pid, error = %e, "the runner service couldn't be signalled (it may have ended)");
}
}
#[cfg(windows)]
#[expect(
clippy::disallowed_methods,
reason = "the client ends a service of another release it replaces, with Windows' own taskkill: the runner's process module isn't the client's"
)]
fn terminate(pid: u32, _force: bool) {
use std::os::windows::process::CommandExt as _;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
let mut command = std::process::Command::new("taskkill");
command
.args(["/PID", &pid.to_string(), "/F"])
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.creation_flags(CREATE_NO_WINDOW);
if let Err(e) = command.status() {
tracing::debug!(pid, error = %e, "taskkill couldn't run to end the runner service");
}
}