use std::future::Future;
use futures_util::{stream::FuturesUnordered, StreamExt};
use rho_protocol::{
methods::{SessionInspect, SessionMcp, SessionProcesses},
ProcessOutputParams, SessionInspectParams, SessionMcpParams, SessionProcessesParams,
SessionReport,
};
use tokio::sync::{mpsc, watch};
use super::{jobs_follow::JobsFollow, on_attachment, report_answer, Change, Control, Target, LOST};
use crate::{app::daemon_client::Daemon, tui::daemon_events::DaemonView};
#[derive(Debug, PartialEq)]
pub(super) enum Read {
Mcp,
Jobs,
Processes(Option<ProcessOutputParams>),
Inspect(SessionReport),
}
impl Read {
pub(super) async fn answer(
self,
mut target: watch::Receiver<Target>,
daemon: &Daemon,
jobs: &JobsFollow,
views: &mpsc::UnboundedSender<DaemonView>,
) {
let view = match self {
Self::Mcp => {
let answer = on_attachment(&mut target, |link, session| async move {
link.request::<SessionMcp>(&SessionMcpParams { session })
.await
})
.await;
DaemonView::McpInventory(match answer {
Some((_, answer)) => answer
.map(Box::new)
.map_err(|error| format!("could not read session MCP inventory: {error}")),
None => Err(LOST.to_owned()),
})
}
Self::Jobs => jobs.read(target, daemon).await,
Self::Processes(output) => {
let answer = on_attachment(&mut target, |link, session| {
let output = output.clone();
async move {
link.request::<SessionProcesses>(&SessionProcessesParams {
session,
output,
})
.await
}
})
.await;
DaemonView::Processes {
asked: output,
result: match answer {
Some((_, answer)) => answer.map_err(|error| error.to_string()),
None => Err(LOST.to_owned()),
},
}
}
Self::Inspect(report) => {
let answer = on_attachment(&mut target, |link, session| async move {
link.request::<SessionInspect>(&SessionInspectParams { session, report })
.await
})
.await;
DaemonView::Report {
report,
result: report_answer(answer),
}
}
};
let _ = views.send(view);
}
}
pub(super) struct Reads<F> {
reading: FuturesUnordered<F>,
}
impl<F: Future<Output = ()>> Reads<F> {
pub(super) fn new() -> Self {
Self {
reading: FuturesUnordered::new(),
}
}
pub(super) async fn next_change(
&mut self,
requests: &mut mpsc::UnboundedReceiver<Control>,
mut start: impl FnMut(Read) -> F,
) -> Option<Change> {
loop {
tokio::select! {
request = requests.recv() => match request? {
Control::Read(read) => self.reading.push(start(read)),
Control::Change(change) => {
while self.reading.next().await.is_some() {}
return Some(change);
}
},
Some(()) = self.reading.next(), if !self.reading.is_empty() => {}
}
}
}
}
#[cfg(test)]
#[path = "reads_tests.rs"]
mod tests;