orch-cli 0.119.0

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
use std::collections::BTreeMap;
use std::env;
use std::fs::OpenOptions;
use std::io::Write;

use tokio::net::TcpListener;
use tokio::time;

use super::*;
use crate::store::TaskStatus;
use crate::store::cluster::{Node, NodeConfig, Version, start_node_on, start_single};

fn write_output(state: &Path, repo: &str, task: &str, attempt: u32, body: &str) -> PathBuf {
    let dir = state
        .join(repo)
        .join("tasks")
        .join(task)
        .join("attempts")
        .join(attempt.to_string());
    fs::create_dir_all(&dir).unwrap();
    let path = dir.join("output.json");
    fs::write(&path, body).unwrap();
    path
}

#[test]
fn read_chunk_returns_whole_lines_and_continues_from_the_offset() {
    let state = tempfile::tempdir().unwrap();
    let path = write_output(state.path(), "o/r", "5", 1, "one\ntw");
    let dirs = [state.path().join("o/r/tasks/5")];

    let first = read_chunk(state.path(), &dirs, &Cursor::default());
    assert_eq!(
        first.file.as_deref(),
        Some("o/r/tasks/5/attempts/1/output.json")
    );
    assert_eq!(first.lines, vec!["one"]);
    assert_eq!(first.offset, 4);

    OpenOptions::new()
        .append(true)
        .open(&path)
        .unwrap()
        .write_all(b"o\nthree\n")
        .unwrap();
    let cursor = Cursor {
        task: 5,
        file: first.file,
        offset: Some(first.offset),
    };
    let next = read_chunk(state.path(), &dirs, &cursor);
    assert_eq!(next.lines, vec!["two", "three"]);

    // A cursor on another attempt's file starts over
    let other = Cursor {
        file: Some("o/r/tasks/5/attempts/0/output.json".into()),
        ..cursor
    };
    assert_eq!(
        read_chunk(state.path(), &dirs, &other).lines,
        vec!["one", "two", "three"]
    );
}

#[test]
fn read_chunk_skips_the_cut_line_of_the_backlog() {
    let state = tempfile::tempdir().unwrap();
    let long = "x".repeat(usize::try_from(BACKLOG_BYTES).unwrap());
    write_output(state.path(), "o/r", "5", 1, &format!("{long}\nlast\n"));
    let chunk = read_chunk(
        state.path(),
        &[state.path().join("o/r/tasks/5")],
        &Cursor::default(),
    );
    assert_eq!(chunk.lines, vec!["last"]);
}

#[test]
fn read_chunk_without_output_names_no_file() {
    let state = tempfile::tempdir().unwrap();
    let chunk = read_chunk(
        state.path(),
        &[state.path().join("o/r/tasks/5")],
        &Cursor::default(),
    );
    assert_eq!(chunk, Chunk::default());
}

struct Pair {
    a: (TaskStore, Node),
    b: (TaskStore, Node),
    b_addr: String,
    _dirs: [tempfile::TempDir; 2],
}

/// Two voters named `a` and `b`, with the Raft ids their names give, as on a real tailnet
async fn pair(secret: &str) -> Pair {
    let dirs = [tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()];
    let mut listeners = Vec::new();
    let mut voters = BTreeMap::new();
    for name in ["a", "b"] {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        voters.insert(
            discovery::node_id(name),
            listener.local_addr().unwrap().to_string(),
        );
        listeners.push(listener);
    }

    let mut started = Vec::new();
    for ((name, dir), listener) in ["a", "b"].iter().zip(&dirs).zip(listeners) {
        let store = TaskStore::open_single(&dir.path().join("orch.db"))
            .await
            .unwrap();
        let id = discovery::node_id(name);
        let node = start_node_on(
            &store,
            &dir.path().join("raft.db"),
            NodeConfig {
                name: (*name).to_string(),
                id,
                addr: voters[&id].clone(),
                secret: secret.into(),
                voters: voters.clone(),
                elect: true,
                version: Version::current(),
                auto_upgrade: false,
            },
            listener,
        )
        .await
        .unwrap();
        started.push((store, node));
    }

    let b = started.pop().unwrap();
    let a = started.pop().unwrap();
    for _ in 0..200 {
        if a.1.has_leader() && b.1.has_leader() {
            break;
        }

        time::sleep(Duration::from_millis(50)).await;
    }

    Pair {
        a,
        b,
        b_addr: voters[&discovery::node_id("b")].clone(),
        _dirs: dirs,
    }
}

/// A task `b` runs, with its row on both nodes
async fn task_on_b(pair: &Pair) -> i64 {
    let store = &pair.a.0;
    let id = store
        .create_internal("o/r", "t", "", "manual", "", None)
        .await
        .unwrap();
    store
        .update_status_and_fields(
            id,
            TaskStatus::InProgress,
            &[("owner_node", serde_json::json!("b"))],
        )
        .await
        .unwrap();
    for _ in 0..200 {
        if let Ok(t) = pair.b.0.get(id).await
            && t.owner_node.as_deref() == Some("b")
        {
            return id;
        }

        time::sleep(Duration::from_millis(50)).await;
    }

    panic!("task {id} never reached b");
}

/// Points `ORCH_HOME` at a temp dir. nextest runs each test in its own process
fn orch_home() -> (tempfile::TempDir, PathBuf) {
    let home = tempfile::tempdir().unwrap();
    // SAFETY: set before any thread of this test reads the environment
    unsafe { env::set_var("ORCH_HOME", home.path()) };
    let state = home::state_dir().unwrap();
    (home, state)
}

#[tokio::test(flavor = "multi_thread")]
async fn a_stream_asked_on_one_node_returns_the_output_of_the_node_that_runs_the_task() {
    let (_home, state) = orch_home();
    let pair = pair("s3cret").await;
    let id = task_on_b(&pair).await;
    write_output(&state, "o/r", &format!("internal:{id}"), 1, "from b\n");

    let cursor = Cursor {
        task: id,
        ..Cursor::default()
    };
    let chunk = fetch(&pair.b_addr, "s3cret", &cursor).await.unwrap();
    assert_eq!(chunk.lines, vec!["from b"]);
    let relayed = relay(&pair.a.0, cursor.clone()).await.unwrap();
    assert_eq!(relayed, Some(Output::Lines(chunk)));

    // A task that is not in the store is not served
    let missing = Cursor {
        task: id + 100,
        ..Cursor::default()
    };
    assert!(matches!(
        fetch(&pair.b_addr, "s3cret", &missing).await,
        Err(FetchError::Refused(StatusCode::NOT_FOUND, _))
    ));
    assert_eq!(relay(&pair.a.0, missing).await.unwrap(), None);

    pair.a.1.stop().await;
    pair.b.1.stop().await;
}

#[tokio::test(flavor = "multi_thread")]
async fn an_output_request_without_the_secret_is_refused() {
    let (_home, state) = orch_home();
    let pair = pair("s3cret").await;
    let id = task_on_b(&pair).await;
    write_output(
        &state,
        "o/r",
        &format!("internal:{id}"),
        1,
        "secret output\n",
    );
    let cursor = Cursor {
        task: id,
        ..Cursor::default()
    };

    assert!(matches!(
        fetch(&pair.b_addr, "wrong", &cursor).await,
        Err(FetchError::Refused(StatusCode::UNAUTHORIZED, _))
    ));
    let bare = reqwest::get(format!("http://{}/cluster/output?task={id}", pair.b_addr))
        .await
        .unwrap();
    assert_eq!(bare.status(), StatusCode::UNAUTHORIZED);

    pair.a.1.stop().await;
    pair.b.1.stop().await;
}

#[tokio::test(flavor = "multi_thread")]
async fn an_offline_owner_gives_a_clear_answer() {
    let (_home, _state) = orch_home();
    let pair = pair("s3cret").await;
    let id = task_on_b(&pair).await;
    pair.b.1.stop().await;

    let out = relay(
        &pair.a.0,
        Cursor {
            task: id,
            ..Cursor::default()
        },
    )
    .await
    .unwrap();
    assert_eq!(out, Some(Output::Offline { node: "b".into() }));
    pair.a.1.stop().await;
}

#[tokio::test]
async fn a_single_machine_reads_its_own_state_dir() {
    let (_home, state) = orch_home();
    let dir = tempfile::tempdir().unwrap();
    let store = TaskStore::open_single(&dir.path().join("orch.db"))
        .await
        .unwrap();
    let node = start_single(&store, &dir.path().join("raft.db"))
        .await
        .unwrap();
    let id = store
        .create_internal("o/r", "t", "", "manual", "", None)
        .await
        .unwrap();
    write_output(&state, "o/r", &format!("internal:{id}"), 1, "here\n");

    let out = relay(
        &store,
        Cursor {
            task: id,
            ..Cursor::default()
        },
    )
    .await
    .unwrap();
    let Some(Output::Lines(chunk)) = out else {
        panic!("expected lines, got {out:?}");
    };
    assert_eq!(chunk.lines, vec!["here"]);
    node.stop().await;
}