rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The job list the rails and `/jobs` read (`Read::Jobs`), followed where
//! the daemon can: one `rho/job/list` with `follow`, then each
//! `rho/job/changed` applied as it arrives, so a read is answered here
//! without asking the daemon. A daemon without
//! [`rho_protocol::DaemonFeature::JobChanges`] answers once, and each read
//! asks it again.
//!
//! The follow lasts as long as the connection: its end closes the changes,
//! and the next read lists again on the next connection.

use std::sync::{Arc, Mutex, PoisonError};

use rho_protocol::{
    methods::{JobList, JobListQueried},
    ClientError, FinishedJobs, JobListParams, JobListQuery, JobListResponse,
};
use tokio::{
    sync::{mpsc, watch},
    task::JoinHandle,
};

use super::{on_connection, Target, LOST};
use crate::{
    app::daemon_client::{Daemon, Link},
    tui::daemon_events::DaemonView,
};

/// The control worker's job reads: the list a follow keeps current, while
/// one does.
#[derive(Default)]
pub(super) struct JobsFollow {
    /// Locked across a read that lists, so two reads at once start one
    /// follow, not two that replace each other.
    followed: tokio::sync::Mutex<Option<Followed>>,
}

/// A followed list, and the task that applies its changes until the
/// connection ends.
struct Followed {
    list: Arc<Mutex<JobListResponse>>,
    applying: JoinHandle<()>,
}

/// What one `rho/job/list` answered.
enum Listed {
    /// Listed once, by a daemon that cannot follow it.
    Once(JobListResponse),
    Followed(Followed),
}

impl JobsFollow {
    /// The daemon's jobs: the followed list while a follow keeps it current,
    /// else a list asked where `target` says, followed when the daemon can.
    pub(super) async fn read(
        &self,
        mut target: watch::Receiver<Target>,
        daemon: &Daemon,
    ) -> DaemonView {
        let mut followed = self.followed.lock().await;
        if let Some(view) = followed.as_ref().and_then(Followed::view) {
            return view;
        }
        *followed = None;
        let answer = on_connection(&mut target, daemon, |link| ask(daemon, link)).await;
        DaemonView::Jobs(match answer {
            Some(Ok(Listed::Followed(follow))) => {
                let jobs = lock(&follow.list).jobs.clone();
                *followed = Some(follow);
                Ok(jobs)
            }
            Some(Ok(Listed::Once(list))) => Ok(list.jobs),
            Some(Err(error)) => Err(error.to_string()),
            None => Err(LOST.to_owned()),
        })
    }
}

impl Followed {
    /// The list as it is now; `None` once the connection ended, so nothing
    /// keeps it current.
    fn view(&self) -> Option<DaemonView> {
        (!self.applying.is_finished()).then(|| DaemonView::Jobs(Ok(lock(&self.list).jobs.clone())))
    }
}

impl Drop for Followed {
    fn drop(&mut self) {
        self.applying.abort();
    }
}

/// Lists the daemon's jobs on `link`, following them when it can. `/jobs`
/// shows finished jobs too, so the follow keeps them.
async fn ask(daemon: &Daemon, link: Arc<Link>) -> Result<Listed, ClientError> {
    if !link.follows_jobs() {
        let list = link.request::<JobList>(&JobListParams {}).await?;
        return Ok(Listed::Once(list));
    }
    // Routed before asking, so no change sent after the answer is lost.
    let (sender, mut changes) = mpsc::unbounded_channel();
    daemon.route_jobs(sender);
    let answer = link
        .request::<JobListQueried>(&JobListQuery::following(FinishedJobs::Include))
        .await?;
    let list = Arc::new(Mutex::new(answer));
    let applying = tokio::spawn({
        let list = Arc::clone(&list);
        async move {
            while let Some(changed) = changes.recv().await {
                lock(&list).apply(changed);
            }
        }
    });
    Ok(Listed::Followed(Followed { list, applying }))
}

fn lock(list: &Mutex<JobListResponse>) -> std::sync::MutexGuard<'_, JobListResponse> {
    // `apply` only replaces, inserts and drops whole jobs, so a panic
    // cannot leave one half-written.
    list.lock().unwrap_or_else(PoisonError::into_inner)
}