orch-cli 0.117.0

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
//! The projects of a cluster that this node does not host, and their `.orch.yml` as the default
//! branch holds it. See `docs/content/docs/cluster.md`

use std::collections::HashSet;
use std::path::{Path, PathBuf};

use anyhow::Context;
use async_trait::async_trait;
use tokio::fs;

use crate::config;
use crate::github::http::{FileFetch, GhHttp};
use crate::store::TaskStore;
use crate::store::cluster::registry;
use crate::sys::home;

const CONFIG_FILE: &str = ".orch.yml";

/// The ETag of the file next to it. Kept on disk, so a restart still gets a 304
const ETAG_FILE: &str = ".orch.yml.etag";

/// Reads a project's `.orch.yml` from its default branch
#[async_trait]
pub(crate) trait Contents: Send + Sync {
    async fn orch_yml(&self, repo: &str, etag: Option<&str>) -> anyhow::Result<FileFetch>;
}

#[async_trait]
impl Contents for GhHttp {
    async fn orch_yml(&self, repo: &str, etag: Option<&str>) -> anyhow::Result<FileFetch> {
        self.get_file_if_changed(repo, CONFIG_FILE, etag).await
    }
}

/// The repos in the node registry, offline nodes included, that `hosted` lacks. Empty on one
/// machine, so it reads nothing and calls nothing
pub(crate) async fn remote_projects(store: &TaskStore, hosted: &HashSet<String>) -> Vec<String> {
    if store.node().is_none() {
        return Vec::new();
    }

    match registry::read(store).await {
        Ok(entries) => registry::hosts_by_project(&entries)
            .into_keys()
            .filter(|repo| !hosted.contains(repo))
            .collect(),
        Err(e) => {
            tracing::warn!(err = %e, "cannot read the node registry for the cluster's projects");
            Vec::new()
        }
    }
}

/// `owner/name` with no path tricks, since the slug becomes a directory
fn valid_slug(repo: &str) -> bool {
    let mut parts = repo.split('/');
    let ok = |p: Option<&str>| {
        p.is_some_and(|p| {
            !p.is_empty()
                && p != "."
                && p != ".."
                && p.chars()
                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
        })
    };
    ok(parts.next()) && ok(parts.next()) && parts.next().is_none()
}

/// Where this node keeps the `.orch.yml` of a project it does not host. The engine reads the
/// project's settings from it as from a checkout
pub(crate) fn config_dir(repo: &str) -> anyhow::Result<PathBuf> {
    anyhow::ensure!(valid_slug(repo), "not an owner/name repo slug: {repo}");
    Ok(home::state_dir()?
        .join("cluster")
        .join("projects")
        .join(repo))
}

/**
 * Read `.orch.yml` of `repo` again when it changed on the default branch, into `dir`. A 304 keeps
 * the file. A file that does not parse keeps the last good one, and a missing file leaves an empty
 * config, so the global values apply. True when the file in `dir` changed
 **/
pub(crate) async fn refresh(source: &dyn Contents, dir: &Path, repo: &str) -> anyhow::Result<bool> {
    let file = dir.join(CONFIG_FILE);
    let etag_file = dir.join(ETAG_FILE);
    // An ETag without its file would make a 304 keep nothing
    let etag = if fs::try_exists(&file).await.unwrap_or(false) {
        fs::read_to_string(&etag_file)
            .await
            .ok()
            .map(|e| e.trim().to_string())
            .filter(|e| !e.is_empty())
    } else {
        None
    };
    let (content, etag) = match source.orch_yml(repo, etag.as_deref()).await? {
        FileFetch::NotModified => return Ok(false),
        FileFetch::Found { content, etag } => {
            if let Err(e) = serde_norway::from_str::<serde_norway::Value>(&content) {
                tracing::warn!(repo, err = %e, "the default branch has an invalid .orch.yml, keeping the last good one");
                return Ok(false);
            }
            (content, etag)
        }
        FileFetch::Missing => ("{}\n".to_string(), None),
    };

    fs::create_dir_all(dir)
        .await
        .with_context(|| format!("creating {}", dir.display()))?;
    fs::write(&file, &content)
        .await
        .with_context(|| format!("writing {}", file.display()))?;
    match etag {
        Some(etag) => fs::write(&etag_file, etag).await?,
        None => {
            let _ = fs::remove_file(&etag_file).await;
        }
    }
    tracing::info!(repo, "read .orch.yml from the default branch");
    config::reloaded(&file);
    Ok(true)
}

/// `refresh` for each project, logging the ones that fail
pub(crate) async fn refresh_all(source: &dyn Contents, projects: &[(String, PathBuf)]) {
    for (repo, dir) in projects {
        if let Err(e) = refresh(source, dir, repo).await {
            tracing::warn!(repo = %repo, err = %e, "cannot read .orch.yml from the default branch");
        }
    }
}

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