use std::{sync::Arc, time::Duration};
use rho_protocol::WorktreeVerdict;
use rho_sdk::SessionId;
use tokio::time::Instant;
use super::{worktree::Prune, LoadedSession, Sessions};
use crate::app::{daemon_host::jobs::SessionJob, session_runtime::SessionRuntime};
pub(in crate::app) const UNLOAD_IDLE_AFTER: Duration = Duration::from_secs(60);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Residency {
InUse,
IdleSince(Instant),
Unloaded,
}
impl Residency {
pub(super) fn mark_in_use(&mut self) -> bool {
match self {
Self::Unloaded => false,
Self::InUse | Self::IdleSince(_) => {
*self = Self::InUse;
true
}
}
}
}
impl Sessions {
pub(in crate::app::daemon_host) async fn unload_idle(&self, grace: Duration) {
loop {
tokio::select! {
() = self.stopping.cancelled() => return,
() = tokio::time::sleep(grace) => {}
}
self.sweep(grace).await;
}
}
async fn sweep(&self, grace: Duration) {
let sessions: Vec<_> = self
.loaded()
.iter()
.map(|(id, session)| (id.clone(), Arc::clone(session)))
.collect();
let mut left = false;
for (id, session) in sessions {
left |= self.unload_if_idle(&id, &session, grace).await;
}
if left {
let _ = tokio::task::spawn_blocking(crate::daemon::release_freed_memory).await;
}
}
async fn unload_if_idle(
&self,
id: &SessionId,
session: &Arc<LoadedSession>,
grace: Duration,
) -> bool {
let _unloading = self.unloading.read().await;
let _reopening = self.reopening.lock(id).await;
let idle_since = {
let mut turn = session.turn();
let busy = matches!(self.jobs.session_job(id), SessionJob::Busy(_))
|| turn.hold.is_some()
|| session.feed.followed()
|| session.runtime_keeps_loaded();
let now = Instant::now();
let idle_since = match turn.residency {
Residency::Unloaded => return false,
Residency::InUse | Residency::IdleSince(_) if busy => {
turn.residency = Residency::InUse;
return false;
}
Residency::InUse => {
turn.residency = Residency::IdleSince(now);
return false;
}
Residency::IdleSince(since) if now.duration_since(since) < grace => {
return false;
}
Residency::IdleSince(since) => since,
};
if !self.evict(id, session, &mut turn) {
return false;
}
idle_since
};
let runtime = session.runtime.lock().await.take();
let saved = runtime.as_ref().is_none_or(SessionRuntime::is_saved);
if let Some(runtime) = runtime {
runtime.shutdown().await;
}
let idle_for = idle_since.elapsed();
if saved {
tracing::info!(
session = %id,
job = %session.job,
?idle_for,
unload_idle_after = ?grace,
"unloaded idle session"
);
} else {
let record = self.jobs.get(&session.job);
self.jobs.remove(&session.job);
let kept = match record {
Some(record) => self.prune_worktree(&record, Prune::Now).await,
None => None,
};
if let Some(kept) =
kept.filter(|kept| !matches!(kept.verdict, WorktreeVerdict::Merged { .. }))
{
tracing::warn!(
session = %id,
branch = %kept.worktree.branch,
path = %kept.worktree.path.display(),
verdict = ?kept.verdict,
"kept the worktree of a discarded unsaved session; rho no longer tracks it"
);
}
tracing::info!(
session = %id,
job = %session.job,
?idle_for,
unload_idle_after = ?grace,
"discarded unsaved idle session"
);
}
true
}
}
impl Sessions {
pub(in crate::app::daemon_host) fn upgrade_blockers(&self) -> usize {
let loaded: Vec<_> = self
.loaded()
.iter()
.map(|(id, session)| (id.clone(), Arc::clone(session)))
.collect();
loaded
.iter()
.filter(|(id, session)| {
!matches!(self.jobs.session_job(id), SessionJob::Busy(_))
&& session.keeps_upgrade_waiting()
})
.count()
}
}
impl LoadedSession {
fn keeps_upgrade_waiting(&self) -> bool {
if self.turn().hold.is_some() {
return true;
}
match self.runtime.try_lock() {
Ok(runtime) => runtime.as_ref().is_some_and(|runtime| {
runtime.has_background_work() || (!runtime.is_saved() && self.feed.followed())
}),
Err(_) => true,
}
}
fn runtime_keeps_loaded(&self) -> bool {
match self.runtime.try_lock() {
Ok(runtime) => runtime
.as_ref()
.is_some_and(SessionRuntime::has_background_work),
Err(_) => true,
}
}
}
#[cfg(test)]
#[path = "unload_tests.rs"]
mod tests;