rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Where a question a session holds goes once that session's turn ends
//! without answering it.
//!
//! A question a started session asks is held first by the session that
//! started it, when that session may answer it (see `peer_wake`): the
//! request names it as `held_by`, and it may answer
//! (`answer_question`). As a turn of the holder ends with the question
//! still open, the question moves on, one level at a time:
//!
//! - **Up**, when the holder reports to the session that started it (see
//!   `app::starter_report`), that starter is loaded to hear, and it may act
//!   on sessions: it holds the question now, and is told of it, with the
//!   holder's last answer as its note. Nothing below the top waits on a
//!   person, so a question its brief does not settle reaches the session
//!   that may decide.
//! - **To the person**, otherwise: the question is theirs, as one never
//!   told is.
//!
//! A question whose session still has a notice waiting in the holder's
//! inbox, which no turn of the holder took, stays with the holder: the
//! turn that takes the notice moves it on as it ends. A holder that is gone
//! gives each question it holds to the person (see `PeerWake`'s drop).
//! Each move tells the asking session's clients
//! ([`rho_protocol::SessionEvent::InputHolderChanged`]). A person may
//! answer a held question first, from the asking session.
//!
//! The inbox keeps one notice per session, so of several questions of one
//! session passed up together the starter's notice names the last; the
//! starter holds them all, and `sessions wait` lists each.

use std::sync::Arc;

use rho_protocol as wire;

use super::{super::jobs::HeldBy, inputs::Inputs, peer_wake::ask_of, LoadedSession};
use crate::app::peer_sessions::PassedUp;

/// Whether a move of held questions outlives the daemon.
pub(super) enum Kept {
    /// Saved on the asking session's job, for the questions it asked
    /// without waiting (see `self_questions`), as held by the session, or,
    /// `None`, the person: a restart gives them back to it.
    Saved(Option<HeldBy>),
    /// Only in this daemon: a holder that unloads, or a restart giving a
    /// question back to the holder its job saved.
    InMemory,
}

impl LoadedSession {
    /// Moves each of `requests`, questions of this session still open and
    /// held by `from`, a session, or the person, to `to`, either, keeping
    /// the move as `kept` says. Returns the questions it moved.
    pub(super) fn give_held(
        &self,
        requests: &[wire::InputRequestId],
        from: Option<&wire::SessionId>,
        to: Option<&wire::SessionId>,
        kept: Kept,
    ) -> Vec<(wire::InputRequestId, wire::QuestionAsk)> {
        let moved = self.feed.move_held(requests, from, to);
        match kept {
            Kept::Saved(held_by) => {
                let inputs = self
                    .inputs
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                self.save_holders(&inputs, moved.iter().map(|(id, _)| *id), held_by);
            }
            Kept::InMemory => {}
        }
        moved
    }

    /// Saves on the job that `held_by` holds each of `requests` that is a
    /// question the session asked without waiting, as `inputs` has them.
    pub(super) fn save_holders(
        &self,
        inputs: &Inputs,
        requests: impl IntoIterator<Item = wire::InputRequestId>,
        held_by: Option<HeldBy>,
    ) {
        for request in requests {
            if let Some(question) = inputs.own_question(request) {
                self.jobs
                    .hold_question(&self.job, question, held_by.clone());
            }
        }
    }

    /// Moves on each open question this session holds, its turn having
    /// ended with `note` as its last answer: up to `starter`, the session
    /// it reports to while that session is loaded (see
    /// `PeerWake::report_target`), when that session may act on sessions,
    /// else to the person. Call as the turn ends.
    pub(super) fn pass_on_held(&self, note: Option<String>, starter: Option<Arc<LoadedSession>>) {
        let held = self.peer_wake.take_held_questions();
        if held.is_empty() {
            return;
        }
        let up = starter
            .filter(|starter| self.jobs.may_act_on_sessions(&starter.job).is_ok())
            .and_then(|starter| {
                let inbox = starter.peer_wake.inbox()?.clone();
                Some((starter, inbox))
            });
        let holder = self.peer_wake.owner();
        for (asking, requests) in held {
            // No turn of this session saw it yet.
            if self
                .peer_wake
                .inbox()
                .is_some_and(|inbox| inbox.holds_notice_of(asking.id.as_str()))
            {
                self.peer_wake.hold_questions(&asking, requests);
                continue;
            }
            let Some((starter, inbox)) = &up else {
                let to_person = Kept::Saved(/*held_by*/ None);
                asking.give_held(&requests, Some(holder), /*to*/ None, to_person);
                continue;
            };
            let held_by = HeldBy {
                session: starter.id.clone(),
                passed_by: Some(self.id.clone()),
            };
            let moved = asking.give_held(
                &requests,
                Some(holder),
                Some(starter.peer_wake.owner()),
                Kept::Saved(Some(held_by)),
            );
            if moved.is_empty() {
                continue;
            }
            // Told before held: a turn of the starter that ends between the
            // two keeps the question rather than moving on one it was never
            // told of. A turn that also took the notice in that gap leaves
            // it held until the starter's next turn ends; that takes a
            // whole model turn between two statements.
            for (request, question) in &moved {
                inbox.tell_held(
                    asking.id.as_str(),
                    asking.feed.name(),
                    *request,
                    ask_of(question),
                    Some(PassedUp {
                        by: holder.to_string(),
                        note: note.clone(),
                    }),
                );
            }
            starter
                .peer_wake
                .hold_questions(&asking, moved.into_iter().map(|(request, _)| request));
        }
    }
}