rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The order in which calls take a session: each prompt, change, and rewind
//! waits for those the daemon read before it, on any connection, to take
//! their place in the session's queue, as the protocol promises ("Changes
//! and turns take the session one at a time, in the order the daemon took
//! their requests"). A connection runs each call in its own task, so
//! without this a prompt sent right after a model change could start its
//! turn on the old model.
//!
//! The connection lines each call up as it reads it
//! ([`SessionOrder::line_up`]). Once the call's turn is under the turn lock
//! it says so with [`took_place`], and the next call on the session starts;
//! a call that ends first, refused or failed, lets the next start as it
//! ends.

use std::{
    cell::RefCell,
    collections::{BTreeSet, HashMap},
    sync::{Arc, Mutex, MutexGuard, PoisonError},
};

use rho_protocol::{self as wire, InTurnCall, SessionOrder};
use tokio::sync::watch;

use super::Sessions;

// NEXT_MAJOR(rho-protocol Service): take the place as a parameter of the prompt, configure and rewind methods, and remove this task-local.
tokio::task_local! {
    /// The place of the call this task runs, until it took it.
    static PLACE: RefCell<Option<Place>>;
}

/// Each session's line of calls the daemon read and has yet to start or
/// take their place.
#[derive(Default)]
pub(super) struct Lines {
    lines: Arc<Mutex<HashMap<wire::SessionId, Line>>>,
}

/// One session's line. Places are numbered as they join it; a session
/// with no place in line has no entry.
struct Line {
    /// The number the next place takes.
    issued: u64,
    /// The first place that has yet to leave the line; every place before it
    /// has left.
    head: watch::Sender<u64>,
    /// Places after `head` that left, by ending before they started.
    left: BTreeSet<u64>,
}

/// A call's place in its session's line: it starts once `head` reaches
/// it, and leaves when it took its place or drops.
struct Place {
    lines: Arc<Mutex<HashMap<wire::SessionId, Line>>>,
    session: wire::SessionId,
    number: u64,
    head: watch::Receiver<u64>,
}

impl Lines {
    /// A new place at the end of `session`'s line.
    fn join(&self, session: &wire::SessionId) -> Place {
        let mut lines = lock(&self.lines);
        let line = lines.entry(session.clone()).or_insert_with(|| Line {
            issued: 0,
            head: watch::Sender::new(0),
            left: BTreeSet::new(),
        });
        let number = line.issued;
        line.issued += 1;
        Place {
            lines: Arc::clone(&self.lines),
            session: session.clone(),
            number,
            head: line.head.subscribe(),
        }
    }

    /// How many calls wait in `session`'s line for the ones before them;
    /// `None` once its line is gone, no call being in it.
    #[cfg(test)]
    pub(super) fn waiting(&self, session: &wire::SessionId) -> Option<u64> {
        lock(&self.lines).get(session).map(|line| {
            (line.issued - *line.head.borrow()).saturating_sub(1 + line.left.len() as u64)
        })
    }
}

impl Place {
    /// Waits until every place before this one left.
    async fn reached(&mut self) {
        let number = self.number;
        // The sender lives while this place is in line.
        let _ = self.head.wait_for(|head| *head >= number).await;
    }
}

impl Drop for Place {
    fn drop(&mut self) {
        let mut lines = lock(&self.lines);
        let Some(line) = lines.get_mut(&self.session) else {
            return;
        };
        line.left.insert(self.number);
        let mut head = *line.head.borrow();
        while line.left.remove(&head) {
            head += 1;
        }
        line.head.send_replace(head);
        if head == line.issued {
            lines.remove(&self.session);
        }
    }
}

impl SessionOrder for Sessions {
    fn line_up(&self, session: &wire::SessionId, call: InTurnCall) -> InTurnCall {
        let mut place = self.lines.join(session);
        Box::pin(async move {
            place.reached().await;
            PLACE.scope(RefCell::new(Some(place)), call).await;
        })
    }
}

/// Tells `session`'s line that the call this task runs took its place in
/// the session's queue, so the next call may start. Does nothing in a task
/// no line runs, such as a turn the daemon starts on its own, or for
/// another session than the call's.
pub(super) fn took_place(session: &wire::SessionId) {
    let _ = PLACE.try_with(|place| {
        let mut place = place.borrow_mut();
        if place
            .as_ref()
            .is_some_and(|place| place.session == *session)
        {
            place.take();
        }
    });
}

fn lock(
    lines: &Mutex<HashMap<wire::SessionId, Line>>,
) -> MutexGuard<'_, HashMap<wire::SessionId, Line>> {
    lines.lock().unwrap_or_else(PoisonError::into_inner)
}

#[cfg(test)]
#[path = "line_tests.rs"]
mod tests;