use std::{
sync::{Mutex, MutexGuard, PoisonError},
time::Duration,
};
use rho_protocol::ClientInfo;
use tokio::sync::Notify;
use crate::daemon::{Executable, FileIdentity, ProbeError};
pub(super) const UPGRADE_CHECK_INTERVAL: Duration = Duration::from_secs(1);
#[derive(Default)]
pub(super) struct Upgrades {
pending: Mutex<Option<String>>,
newer_client: Mutex<Option<String>>,
heard_newer: Notify,
}
#[derive(Default)]
pub(super) struct Watch {
probed: Option<FileIdentity>,
warned: Option<String>,
}
#[derive(Debug, PartialEq, Eq)]
pub(super) enum Check {
Wait,
Upgrade,
}
impl Upgrades {
pub(super) fn heard(&self, client: &ClientInfo) {
if !crate::update::version_is_newer(&client.version, env!("CARGO_PKG_VERSION")) {
return;
}
let mut newest = lock(&self.newer_client);
if newest
.as_deref()
.is_none_or(|newest| crate::update::version_is_newer(&client.version, newest))
{
*newest = Some(client.version.clone());
}
drop(newest);
self.heard_newer.notify_one();
}
pub(super) fn pending(&self) -> Option<String> {
lock(&self.pending).clone()
}
pub(super) async fn next_check(&self, interval: &mut tokio::time::Interval) {
tokio::select! {
_ = interval.tick() => {}
() = self.heard_newer.notified() => {}
}
}
pub(super) async fn check(&self, executable: &Executable, watch: &mut Watch) -> Check {
let Some(replacement) = executable.replacement() else {
*lock(&self.pending) = None;
watch.probed = None;
let newer_client = lock(&self.newer_client).clone();
if newer_client.is_some() && watch.warned != newer_client {
tracing::warn!(
client = newer_client.as_deref(),
executable = %executable.path().display(),
"a newer rho client connected, but the daemon's executable was not \
replaced; restart the daemon from the newer rho to upgrade it"
);
watch.warned = newer_client;
}
return Check::Wait;
};
if watch.probed != Some(replacement.identity) {
let probed = executable.probe().await;
match &probed {
Ok(version) => tracing::info!(
%version,
executable = %executable.path().display(),
"the daemon's executable was replaced; upgrading once nothing would be cut short"
),
Err(error) if error.is_transient() => tracing::debug!(
%error,
executable = %executable.path().display(),
"could not probe the daemon's replaced executable; trying again"
),
Err(error) => tracing::warn!(
%error,
executable = %executable.path().display(),
"the daemon's executable was replaced by one that is not rho; not upgrading"
),
}
if !probed.as_ref().is_err_and(ProbeError::is_transient) {
watch.probed = Some(replacement.identity);
}
*lock(&self.pending) = probed.ok();
}
match *lock(&self.pending) {
Some(_) => Check::Upgrade,
None => Check::Wait,
}
}
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}