use std::{
ffi::OsStr,
fs::File,
io::{self, Write},
path::{Path, PathBuf},
time::Duration,
};
use rho_sdk::CancellationToken;
const SIGNAL_POLL: Duration = Duration::from_millis(500);
pub(super) const PARENT_ENDED: &str = "the Rho session that started this background work ended \
before it finished";
const EXPIRED_AFTER: Duration = Duration::from_secs(30 * 24 * 60 * 60);
#[derive(Clone, Debug, PartialEq, Eq)]
pub(in crate::app::daemon_host::sessions) struct WakeDir(PathBuf);
impl WakeDir {
pub(in crate::app::daemon_host::sessions) fn in_home(rho_home: &Path) -> Self {
Self(rho_home.join("t3-wakes"))
}
pub(super) fn path(&self) -> &Path {
&self.0
}
}
#[derive(Clone, Debug, PartialEq)]
pub(in crate::app::daemon_host::sessions) struct WakeSignal {
dir: WakeDir,
token: String,
}
impl WakeSignal {
pub(super) fn create(dir: &WakeDir) -> io::Result<(Self, File)> {
crate::subagent::ensure_private_directory(dir.path())?;
let signal = Self {
dir: dir.clone(),
token: uuid::Uuid::new_v4().to_string(),
};
let lock = crate::daemon::create_private_file(&signal.lock_path())?;
lock.lock()?;
Ok((signal, lock))
}
pub(super) fn parse(dir: &WakeDir, token: &str) -> Option<Self> {
Some(Self {
dir: dir.clone(),
token: uuid::Uuid::parse_str(token.trim()).ok()?.to_string(),
})
}
pub(in crate::app::daemon_host::sessions) fn recorded(
dir: &WakeDir,
session_id: &str,
) -> Option<Self> {
let token = WaitRecord::of(dir, session_id)?.read()?.token;
Self::parse(dir, &token)
}
pub(in crate::app::daemon_host::sessions) fn forget(dir: &WakeDir, session_id: &str) {
if let Some(signal) = Self::recorded(dir, session_id) {
signal.cleanup();
}
if let Some(record) = WaitRecord::of(dir, session_id) {
record.remove();
}
}
pub(super) fn token(&self) -> &str {
&self.token
}
fn path(&self) -> PathBuf {
self.dir.path().join(&self.token)
}
fn lock_path(&self) -> PathBuf {
self.path().with_extension("lock")
}
pub(super) fn fire(&self, summary: &str) -> io::Result<()> {
write_whole(&self.path(), &self.path().with_extension("tmp"), summary)
}
pub(super) fn remove(&self) {
let _ = std::fs::remove_file(self.path());
}
pub(super) fn cleanup(&self) {
self.remove();
let _ = std::fs::remove_file(self.lock_path());
}
pub(super) fn parent_ended(&self) -> bool {
released(&self.lock_path())
}
pub(in crate::app::daemon_host::sessions) async fn wait(
&self,
session_id: &str,
cancel: &CancellationToken,
) -> Option<String> {
let record = WaitRecord::of(&self.dir, session_id);
if let Some(record) = &record {
if let Some(summary) = record.read().and_then(|recorded| {
(recorded.token == self.token)
.then_some(recorded.summary)
.flatten()
}) {
return Some(summary);
}
prune_expired(&self.dir);
let _ = record.write(&self.token, None);
}
let summary = loop {
if let Ok(summary) = std::fs::read_to_string(self.path()) {
break summary;
}
if self.parent_ended() {
break PARENT_ENDED.into();
}
tokio::select! {
() = cancel.cancelled() => return None,
() = tokio::time::sleep(SIGNAL_POLL) => {}
}
};
let recorded = record
.as_ref()
.is_none_or(|record| record.write(&self.token, Some(&summary)));
if recorded {
self.cleanup();
}
Some(summary)
}
}
struct WaitRecord {
path: PathBuf,
}
struct RecordedWait {
token: String,
summary: Option<String>,
}
impl WaitRecord {
fn of(dir: &WakeDir, session_id: &str) -> Option<Self> {
let session_id = uuid::Uuid::parse_str(session_id).ok()?;
Some(Self {
path: dir.path().join(format!("{session_id}.watcher")),
})
}
fn read(&self) -> Option<RecordedWait> {
std::fs::read_to_string(&self.path)
.ok()
.map(|contents| Self::parse(&contents))
}
fn parse(contents: &str) -> RecordedWait {
let (token, summary) = match contents.split_once('\n') {
Some((token, summary)) => (token, Some(summary.to_owned())),
None => (contents, None),
};
RecordedWait {
token: token.to_owned(),
summary,
}
}
fn write(&self, token: &str, summary: Option<&str>) -> bool {
let contents = match summary {
Some(summary) => format!("{token}\n{summary}"),
None => token.to_owned(),
};
let written = write_whole(
&self.path,
&self.path.with_extension("watcher-tmp"),
&contents,
);
if let Err(error) = &written {
tracing::warn!(%error, "could not record the T3 wake watcher's wait");
}
written.is_ok()
}
fn remove(&self) {
let _ = std::fs::remove_file(&self.path);
}
}
fn prune_expired(dir: &WakeDir) {
let Ok(entries) = std::fs::read_dir(dir.path()) else {
return;
};
for path in entries.flatten().map(|entry| entry.path()) {
let expired = std::fs::metadata(&path)
.and_then(|metadata| metadata.modified())
.is_ok_and(|modified| modified.elapsed().is_ok_and(|age| age > EXPIRED_AFTER));
if expired && unusable(dir, &path) {
let _ = std::fs::remove_file(path);
}
}
}
fn unusable(dir: &WakeDir, path: &Path) -> bool {
let parent_ended =
|token: &str| WakeSignal::parse(dir, token).is_none_or(|signal| signal.parent_ended());
match path.extension().and_then(OsStr::to_str) {
Some("watcher") => std::fs::read_to_string(path).is_ok_and(|contents| {
let recorded = WaitRecord::parse(&contents);
recorded.summary.is_some() || parent_ended(&recorded.token)
}),
Some("lock") => released(path),
Some("tmp" | "watcher-tmp") => true,
None => path
.file_name()
.and_then(OsStr::to_str)
.is_some_and(parent_ended),
Some(_) => false,
}
}
pub(super) fn released(path: &Path) -> bool {
match File::open(path) {
Ok(lock) => lock.try_lock().is_ok(),
Err(error) => error.kind() == io::ErrorKind::NotFound,
}
}
fn write_whole(path: &Path, staging: &Path, contents: &str) -> io::Result<()> {
crate::daemon::create_private_file(staging)?.write_all(contents.as_bytes())?;
std::fs::rename(staging, path)
}
#[cfg(test)]
#[path = "signal_tests.rs"]
mod tests;