use std::collections::HashMap;
use rho_protocol::{BackgroundStatus, ChildRole, JobId, JobKind, JobState, JobSummary, SessionId};
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct StartedChild {
pub(super) session: SessionId,
pub(super) title: Option<String>,
}
pub(super) fn started_by(jobs: &[JobSummary], parent: &SessionId) -> Vec<StartedChild> {
let by_id: HashMap<&JobId, &JobSummary> = jobs.iter().map(|job| (&job.id, job)).collect();
jobs.iter()
.filter_map(|job| {
let child = job.child.as_ref()?;
let session = job.session.as_ref()?;
let started = child.role == ChildRole::Started && starter(&by_id, job)? == parent;
started.then(|| StartedChild {
session: session.clone(),
title: child.title.clone(),
})
})
.collect()
}
fn starter<'a>(by_id: &HashMap<&JobId, &'a JobSummary>, job: &JobSummary) -> Option<&'a SessionId> {
let mut parent = by_id.get(job.parent.as_ref()?)?;
for _ in 0..by_id.len() {
match parent.kind {
JobKind::Session => return parent.session.as_ref(),
JobKind::Subagent | JobKind::Workflow => {
parent = by_id.get(parent.parent.as_ref()?)?;
}
_ => return None,
}
}
None
}
pub(super) fn run_ended(jobs: &[JobSummary], session: &SessionId) -> Option<BackgroundStatus> {
let job = jobs
.iter()
.rev()
.find(|job| job.kind == JobKind::Subagent && job.session.as_ref() == Some(session))?;
job_ended(job.state)
}
pub(super) fn job_ended(state: JobState) -> Option<BackgroundStatus> {
match state {
JobState::Completed => Some(BackgroundStatus::Completed),
JobState::Failed | JobState::TimedOut => Some(BackgroundStatus::Failed),
JobState::Cancelled => Some(BackgroundStatus::Cancelled),
JobState::Interrupted | JobState::Unknown => Some(BackgroundStatus::Unknown),
JobState::Idle | JobState::Queued | JobState::Running | JobState::WaitingForInput => None,
_ => Some(BackgroundStatus::Unknown),
}
}
#[cfg(test)]
#[path = "child_jobs_tests.rs"]
mod tests;