orch-cli 0.118.0

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
//! Channel streaming for sessions another cluster node runs. The leader reads them through the
//! same relay `orch stream` uses

use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;
use tokio::sync::Mutex;

use crate::channels::capture::{RemoteRead, RemoteSessions};
use crate::engine::runner::ndjson::Formatter;
use crate::store::cluster::output::{self, Cursor, Output};
use crate::store::{Task, TaskStatus, TaskStore};

#[derive(Debug)]
pub struct ClusterSessions {
    store: Arc<TaskStore>,
    /// Where each session was read up to, keyed by session key
    cursors: Mutex<HashMap<String, (Cursor, Formatter)>>,
}

impl ClusterSessions {
    pub fn new(store: Arc<TaskStore>) -> Self {
        Self {
            store,
            cursors: Mutex::default(),
        }
    }

    /// The task behind a session another node runs. None on a single node
    async fn remote_task(&self, repo: &str, task_id: &str) -> Option<Task> {
        let me = self.store.node()?.name().to_string();
        if me.is_empty() {
            return None;
        }

        let task = match task_id.strip_prefix("internal:") {
            Some(id) => self.store.get(id.parse().ok()?).await.ok()?,
            None => self.store.get_by_external_id(repo, task_id).await.ok()??,
        };
        task.owner_node
            .as_deref()
            .is_some_and(|owner| owner != me)
            .then_some(task)
    }
}

#[async_trait]
impl RemoteSessions for ClusterSessions {
    async fn read(
        &self,
        skey: &str,
        repo: &str,
        task_id: &str,
        seen_alive: bool,
    ) -> Option<RemoteRead> {
        let task = self.remote_task(repo, task_id).await?;
        let mut cursors = self.cursors.lock().await;
        let (cursor, formatter) = cursors.entry(skey.to_string()).or_insert_with(|| {
            let cursor = Cursor {
                task: task.id,
                ..Cursor::default()
            };
            (cursor, Formatter::new(false))
        });
        let read = match output::relay(&self.store, cursor.clone()).await {
            Ok(Some(Output::Lines(chunk))) => {
                if cursor.file != chunk.file {
                    *formatter = Formatter::new(false);
                }

                let entries: Vec<String> = chunk
                    .lines
                    .iter()
                    .flat_map(|line| formatter.format(line))
                    .collect();
                cursor.file = chunk.file;
                cursor.offset = Some(chunk.offset);
                let running = matches!(task.status, TaskStatus::InProgress | TaskStatus::InReview);
                RemoteRead {
                    content: entries.join("\n"),
                    is_final: !running && seen_alive,
                }
            }
            Ok(Some(Output::Offline { node })) => RemoteRead {
                content: format!("{node} runs this task and is offline, the stream ends here"),
                is_final: true,
            },
            Ok(None) => RemoteRead {
                content: String::new(),
                is_final: true,
            },
            Err(e) => {
                tracing::debug!(task_id, err = %e, "remote output read failed");
                RemoteRead::default()
            }
        };
        Some(read)
    }

    async fn forget(&self, skey: &str) {
        self.cursors.lock().await.remove(skey);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn a_single_machine_leaves_every_session_to_tmux() {
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let id = store
            .create_internal("o/r", "t", "", "manual", "", None)
            .await
            .unwrap();
        let sessions = ClusterSessions::new(store);
        let task_id = format!("internal:{id}");
        assert!(
            sessions
                .read(&task_id, "o/r", &task_id, true)
                .await
                .is_none()
        );
    }
}