orch-cli 0.119.0

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
//! Session output from the node that runs a task. A node reads `output.json` from its own state
//! dir and sends complete lines over the cluster listener. Output never goes into the Raft log

use std::fs;
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock};
use std::time::Duration;

use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use axum::{Json, Router};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use tokio::task;

use super::discovery;
use super::network::{self, SECRET_HEADER};
use super::registry;
use crate::cli::task::stream::newest_output;
use crate::store::{Task, TaskStore};
use crate::sys::home;

/// Replayed when a viewer first opens a file, as the local tail does
const BACKLOG_BYTES: u64 = 64 * 1024;

/// The most one request returns, so a viewer far behind catches up over several requests
const MAX_CHUNK_BYTES: u64 = 256 * 1024;

static CLIENT: LazyLock<reqwest::Client> = LazyLock::new(|| {
    reqwest::Client::builder()
        .connect_timeout(Duration::from_secs(3))
        .timeout(Duration::from_secs(10))
        .build()
        .unwrap_or_default()
});

/// What a viewer asks for: a task, and where it stopped reading. A different `file` starts over
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Cursor {
    pub task: i64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub offset: Option<u64>,
}

/// Complete lines after the cursor. `file` is relative to the state dir and changes with each attempt
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Chunk {
    pub file: Option<String>,
    pub offset: u64,
    pub lines: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Output {
    Lines(Chunk),
    /// The node that runs the task does not answer
    Offline {
        node: String,
    },
}

/// The task dir and its review dir, named as the runner names them
fn task_dirs(state: &Path, task: &Task) -> Vec<PathBuf> {
    let name = task
        .external_id
        .clone()
        .filter(|id| !id.is_empty())
        .unwrap_or_else(|| format!("internal:{}", task.id));
    let tasks = state.join(&task.repo).join("tasks");
    vec![tasks.join(format!("{name}-review")), tasks.join(name)]
}

/// The lines of the task's newest output file after the cursor. Stateless, so any viewer can ask
pub fn read_chunk(state: &Path, dirs: &[PathBuf], cursor: &Cursor) -> Chunk {
    let Some(path) = newest_output(dirs) else {
        return Chunk::default();
    };
    let file = path
        .strip_prefix(state)
        .unwrap_or(&path)
        .display()
        .to_string();
    let len = fs::metadata(&path).map_or(0, |m| m.len());
    // A new attempt or a truncated file starts over from the backlog
    let start = match cursor.offset {
        Some(offset) if cursor.file.as_deref() == Some(file.as_str()) && offset <= len => offset,
        _ => len.saturating_sub(BACKLOG_BYTES),
    };
    let skip_first = start > 0 && cursor.file.as_deref() != Some(file.as_str());
    let mut buf = Vec::new();
    let read = File::open(&path).and_then(|mut f| {
        f.seek(SeekFrom::Start(start))?;
        f.take(MAX_CHUNK_BYTES).read_to_end(&mut buf)
    });
    if read.is_err() {
        return Chunk {
            file: Some(file),
            offset: start,
            lines: Vec::new(),
        };
    }

    // Only whole lines go out, unless one line fills the whole chunk
    let end = match buf.iter().rposition(|&b| b == b'\n') {
        Some(i) => i + 1,
        None if buf.len() as u64 == MAX_CHUNK_BYTES => buf.len(),
        None => 0,
    };
    let mut lines: Vec<String> = String::from_utf8_lossy(&buf[..end])
        .lines()
        .map(String::from)
        .collect();
    // The backlog starts mid-line
    if skip_first && !lines.is_empty() {
        lines.remove(0);
    }

    Chunk {
        file: Some(file),
        offset: start + end as u64,
        lines,
    }
}

async fn read_local(task: &Task, cursor: Cursor) -> anyhow::Result<Chunk> {
    let state = home::state_dir()?;
    let dirs = task_dirs(&state, task);
    Ok(task::spawn_blocking(move || read_chunk(&state, &dirs, &cursor)).await?)
}

#[derive(Clone)]
struct App {
    store: TaskStore,
    secret: Arc<str>,
}

/// `GET /cluster/output` on the cluster listener. It serves only tasks in this node's store
pub(crate) fn router(store: TaskStore, secret: Arc<str>) -> Router {
    Router::new()
        .route("/cluster/output", get(serve))
        .with_state(App { store, secret })
}

async fn serve(State(a): State<App>, headers: HeaderMap, Query(cursor): Query<Cursor>) -> Response {
    if !network::secret_ok(&a.secret, &headers) {
        return StatusCode::UNAUTHORIZED.into_response();
    }

    let Ok(task) = a.store.get(cursor.task).await else {
        return StatusCode::NOT_FOUND.into_response();
    };
    match read_local(&task, cursor).await {
        Ok(chunk) => Json(chunk).into_response(),
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:#}")).into_response(),
    }
}

/// Why a fetch from a peer failed
#[derive(Debug)]
pub enum FetchError {
    /// No connection, or no answer in time
    Unreachable(String),
    Refused(StatusCode, String),
}

/// Ask the node at `addr` for the output after `cursor`
pub async fn fetch(addr: &str, secret: &str, cursor: &Cursor) -> Result<Chunk, FetchError> {
    let res = CLIENT
        .get(format!("http://{addr}/cluster/output"))
        .header(SECRET_HEADER, secret)
        .query(cursor)
        .send()
        .await
        .map_err(|e| FetchError::Unreachable(e.to_string()))?;
    let status = res.status();
    if !status.is_success() {
        let body = res.text().await.unwrap_or_default();
        return Err(FetchError::Refused(status, body));
    }

    res.json()
        .await
        .map_err(|e| FetchError::Unreachable(e.to_string()))
}

/// The cluster address of the member named `name`. A node's Raft id comes from its name
fn member_addr(store: &TaskStore, name: &str) -> Option<String> {
    let node = store.node()?;
    let id = discovery::node_id(name);
    let metrics = node.raft.metrics().borrow().clone();
    metrics
        .membership_config
        .membership()
        .nodes()
        .find(|(member, _)| **member == id)
        .map(|(_, n)| n.addr.clone())
}

/**
 * The task's output, read here when this node runs it and fetched from its owner otherwise. A
 * single node, a task no node took yet and a task this node owns read the local state dir, so
 * without a cluster this is the local tail
 **/
pub async fn relay(store: &TaskStore, cursor: Cursor) -> anyhow::Result<Option<Output>> {
    let Ok(task) = store.get(cursor.task).await else {
        return Ok(None);
    };
    let remote = match (store.node(), task.owner_node.as_deref()) {
        (Some(node), Some(owner)) if !node.name().is_empty() && owner != node.name() => node
            .secret
            .clone()
            .map(|secret| (owner.to_string(), secret)),
        _ => None,
    };
    let Some((owner, secret)) = remote else {
        return Ok(Some(Output::Lines(read_local(&task, cursor).await?)));
    };

    let offline = registry::read(store)
        .await
        .unwrap_or_default()
        .iter()
        .any(|e| e.node == owner && !e.online_at(Utc::now()));
    let Some(addr) = member_addr(store, &owner).filter(|_| !offline) else {
        return Ok(Some(Output::Offline { node: owner }));
    };
    match fetch(&addr, &secret, &cursor).await {
        Ok(chunk) => Ok(Some(Output::Lines(chunk))),
        Err(FetchError::Unreachable(e)) => {
            tracing::debug!(node = %owner, err = %e, "owner node did not answer an output request");
            Ok(Some(Output::Offline { node: owner }))
        }
        Err(FetchError::Refused(StatusCode::NOT_FOUND, _)) => Ok(None),
        Err(FetchError::Refused(status, body)) => {
            anyhow::bail!("{owner} refused the output request ({status}): {body}")
        }
    }
}

#[cfg(test)]
mod tests;