use std::time::Duration;
use aither_core::llm::{AgentPath, CallIdentity, StoredFile};
use async_channel::{Receiver, Sender};
use futures_lite::future::or;
use crate::job_registry::PendingCompletion;
use crate::monitor::{MonitorEnded, MonitorIncrement, MonitorStalled};
use crate::process_tree::JobProcess;
use crate::terminal::{CompletedCommand, TerminalError, TimeoutKill};
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct JobStarted {
pub(crate) agent: AgentPath,
pub(crate) task_id: String,
pub(crate) output_preview: String,
pub(crate) output_file: StoredFile,
}
impl JobStarted {
#[must_use]
pub const fn agent(&self) -> &AgentPath {
&self.agent
}
#[must_use]
pub fn task_id(&self) -> &str {
&self.task_id
}
#[must_use]
pub fn output_preview(&self) -> &str {
&self.output_preview
}
#[must_use]
pub const fn output_file(&self) -> &StoredFile {
&self.output_file
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct JobEnded {
pub(crate) agent: AgentPath,
pub(crate) info: crate::JobInfo,
pub(crate) result: Result<CompletedCommand, TerminalError>,
pub(crate) timeout_kill: Option<TimeoutKill>,
pub(crate) pending: Option<PendingCompletion>,
}
impl JobEnded {
#[must_use]
pub const fn agent(&self) -> &AgentPath {
&self.agent
}
#[must_use]
pub const fn info(&self) -> &crate::JobInfo {
&self.info
}
#[must_use]
pub const fn result(&self) -> &Result<CompletedCommand, TerminalError> {
&self.result
}
#[must_use]
pub const fn timeout_kill(&self) -> Option<&TimeoutKill> {
self.timeout_kill.as_ref()
}
pub fn into_parts(
self,
) -> (
crate::JobInfo,
Result<CompletedCommand, TerminalError>,
Option<TimeoutKill>,
Option<PendingCompletion>,
) {
(self.info, self.result, self.timeout_kill, self.pending)
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct LongRunning {
pub(crate) agent: AgentPath,
pub(crate) task_id: String,
pub(crate) script: String,
pub(crate) after: Duration,
}
impl LongRunning {
#[must_use]
pub const fn agent(&self) -> &AgentPath {
&self.agent
}
#[must_use]
pub fn task_id(&self) -> &str {
&self.task_id
}
#[must_use]
pub fn script(&self) -> &str {
&self.script
}
#[must_use]
pub const fn after(&self) -> Duration {
self.after
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct StdinBlocked {
pub(crate) agent: AgentPath,
pub(crate) task_id: String,
pub(crate) script: String,
}
impl StdinBlocked {
#[must_use]
pub const fn agent(&self) -> &AgentPath {
&self.agent
}
#[must_use]
pub fn task_id(&self) -> &str {
&self.task_id
}
#[must_use]
pub fn script(&self) -> &str {
&self.script
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct StdinWatchFailed {
pub(crate) agent: AgentPath,
pub(crate) task_id: String,
pub(crate) script: String,
pub(crate) error: String,
}
impl StdinWatchFailed {
#[must_use]
pub const fn agent(&self) -> &AgentPath {
&self.agent
}
#[must_use]
pub fn task_id(&self) -> &str {
&self.task_id
}
#[must_use]
pub fn script(&self) -> &str {
&self.script
}
#[must_use]
pub fn error(&self) -> &str {
&self.error
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct DescendantsKilled {
pub(crate) agent: AgentPath,
pub(crate) task_id: String,
pub(crate) call: Option<CallIdentity>,
pub(crate) processes: Vec<JobProcess>,
}
impl DescendantsKilled {
#[must_use]
pub const fn agent(&self) -> &AgentPath {
&self.agent
}
#[must_use]
pub fn task_id(&self) -> &str {
&self.task_id
}
#[must_use]
pub const fn call(&self) -> Option<&CallIdentity> {
self.call.as_ref()
}
#[must_use]
pub fn processes(&self) -> &[JobProcess] {
&self.processes
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum ShellEvent {
JobStarted(JobStarted),
JobEnded(Box<JobEnded>),
LongRunning(LongRunning),
StdinBlocked(StdinBlocked),
StdinWatchFailed(StdinWatchFailed),
DescendantsKilled(DescendantsKilled),
MonitorIncrement(MonitorIncrement),
MonitorStalled(MonitorStalled),
MonitorEnded(MonitorEnded),
}
impl ShellEvent {
#[must_use]
pub const fn agent(&self) -> &AgentPath {
match self {
Self::JobStarted(event) => event.agent(),
Self::JobEnded(event) => event.agent(),
Self::LongRunning(event) => event.agent(),
Self::StdinBlocked(event) => event.agent(),
Self::StdinWatchFailed(event) => event.agent(),
Self::DescendantsKilled(event) => event.agent(),
Self::MonitorIncrement(event) => event.agent(),
Self::MonitorStalled(event) => event.agent(),
Self::MonitorEnded(event) => event.agent(),
}
}
}
#[derive(Clone, Debug)]
pub struct EventSender {
agent: AgentPath,
started: Sender<ShellEvent>,
facts: Sender<ShellEvent>,
ended: Sender<ShellEvent>,
}
impl EventSender {
pub(crate) const fn agent(&self) -> &AgentPath {
&self.agent
}
pub(crate) async fn send(
&self,
event: ShellEvent,
) -> Result<(), Box<async_channel::SendError<ShellEvent>>> {
match event {
ShellEvent::JobStarted(_) => self.started.send(event).await,
ShellEvent::JobEnded(_) => self.ended.send(event).await,
ShellEvent::LongRunning(_)
| ShellEvent::StdinBlocked(_)
| ShellEvent::StdinWatchFailed(_)
| ShellEvent::DescendantsKilled(_)
| ShellEvent::MonitorIncrement(_)
| ShellEvent::MonitorStalled(_)
| ShellEvent::MonitorEnded(_) => self.facts.send(event).await,
}
.map_err(Box::new)
}
}
#[derive(Clone, Debug)]
struct Queue {
tx: Sender<ShellEvent>,
rx: Receiver<ShellEvent>,
}
impl Queue {
fn new() -> Self {
let (tx, rx) = async_channel::unbounded();
Self { tx, rx }
}
}
#[derive(Clone, Debug)]
pub struct ShellEvents {
started: Queue,
facts: Queue,
ended: Queue,
}
impl Default for ShellEvents {
fn default() -> Self {
Self::new()
}
}
impl ShellEvents {
#[must_use]
pub fn new() -> Self {
Self {
started: Queue::new(),
facts: Queue::new(),
ended: Queue::new(),
}
}
pub(crate) fn sender(&self, agent: AgentPath) -> EventSender {
EventSender {
agent,
started: self.started.tx.clone(),
facts: self.facts.tx.clone(),
ended: self.ended.tx.clone(),
}
}
#[must_use]
pub fn try_recv(&self) -> Option<ShellEvent> {
self.started
.rx
.try_recv()
.or_else(|_| self.facts.rx.try_recv())
.or_else(|_| self.ended.rx.try_recv())
.ok()
}
pub async fn recv(&self) -> ShellEvent {
or(
self.started.rx.recv(),
or(self.facts.rx.recv(), self.ended.rx.recv()),
)
.await
.expect("a handle holds the senders of its own queues")
}
pub async fn recv_timeout(&self, duration: Duration) -> Option<ShellEvent> {
or(async { Some(self.recv().await) }, async {
async_io::Timer::after(duration).await;
None
})
.await
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.started.rx.is_empty() && self.facts.rx.is_empty() && self.ended.rx.is_empty()
}
#[cfg(test)]
pub(crate) fn take_started(&self) -> Vec<JobStarted> {
std::iter::from_fn(|| self.started.rx.try_recv().ok())
.filter_map(|event| match event {
ShellEvent::JobStarted(started) => Some(started),
_ => None,
})
.collect()
}
#[cfg(test)]
pub(crate) async fn recv_completed(&self) -> JobEnded {
match self
.ended
.rx
.recv()
.await
.expect("a handle holds the senders of its own queues")
{
ShellEvent::JobEnded(ended) => *ended,
_ => unreachable!("the ended queue holds ended jobs"),
}
}
#[cfg(test)]
pub(crate) fn take_completed(&self) -> Vec<JobEnded> {
std::iter::from_fn(|| self.ended.rx.try_recv().ok())
.filter_map(|event| match event {
ShellEvent::JobEnded(ended) => Some(*ended),
_ => None,
})
.collect()
}
#[cfg(test)]
pub(crate) fn take_job_alerts(&self) -> Vec<ShellEvent> {
std::iter::from_fn(|| self.facts.rx.try_recv().ok()).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::monitor::MonitorStalled;
fn stalled(task_id: &str) -> ShellEvent {
ShellEvent::MonitorStalled(MonitorStalled {
agent: AgentPath::main(),
task_id: task_id.to_string(),
stall_secs: 1,
})
}
#[tokio::test]
async fn a_handle_waits_for_events_it_never_loses_the_queues_of() {
let events = ShellEvents::new();
let reader = events.clone();
assert!(
reader
.recv_timeout(Duration::from_millis(50))
.await
.is_none()
);
events
.sender(AgentPath::main())
.send(stalled("late"))
.await
.unwrap();
let ShellEvent::MonitorStalled(event) = reader.recv().await else {
panic!("the raised event is the one read");
};
assert_eq!(event.task_id(), "late");
}
#[tokio::test]
async fn senders_of_one_handle_reach_every_reader_of_it_once() {
let events = ShellEvents::new();
let (first, second) = (
events.sender(AgentPath::main()),
events.sender(AgentPath::main()),
);
first.send(stalled("one")).await.unwrap();
second.send(stalled("two")).await.unwrap();
let reader = events.clone();
assert!(
matches!(events.try_recv(), Some(ShellEvent::MonitorStalled(e)) if e.task_id() == "one")
);
assert!(
matches!(reader.try_recv(), Some(ShellEvent::MonitorStalled(e)) if e.task_id() == "two")
);
assert!(events.is_empty());
}
}