rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The hooks files the daemon reads and writes for its clients, and the one
//! rule every write follows. `rho/hooks/file/*` (`hooks_file.rs`) reads and
//! replaces the user's file whole; `rho/hooks/config/*` (`hooks_config.rs`)
//! edits the user's or a project's one hook at a time. Both go through
//! [`HooksStore::snapshot`] and [`HooksStore::edit`], so they agree on a
//! file's revision and on what may be written.
//!
//! A file's revision is the SHA-256 of its bytes. A write lands only text a
//! session would load, so a copied file never leaves the daemon running no
//! hooks at all. Sessions read the file as they open and on
//! `rho/session/hooks/reload`, so a write changes no loaded session.
//!
//! An edit holds the file's edit lock from the read its revision is checked
//! against through its write, as a `config.toml` edit does, so no other rho
//! process replaces the file in between. A text editor takes no lock, so
//! its save can still land in that window, which lasts microseconds.

use std::{
    io,
    path::{Path, PathBuf},
};

use rho_protocol::{ConfigRevision, ErrorCode, RpcError};
use sha2::{Digest, Sha256};

use crate::hooks::HookConfigError;

/// The revision of an absent file, which no hex digest equals, so it differs
/// from an empty file's.
const ABSENT: &str = "absent";

/// The hooks files the daemon writes: the user's, and any project's a
/// client names.
pub(super) struct HooksStore {
    /// The user's hooks file.
    user: PathBuf,
    /// Held from an edit's read through its write, so this daemon's edits
    /// wait for each other instead of finding the edit lock held. One for
    /// every file, since edits are rare.
    edits: tokio::sync::Mutex<()>,
}

/// One hooks file, with the rules a session loads it by.
pub(super) enum HooksTarget {
    /// The user's file.
    User(PathBuf),
    /// The file of the project at `root`, at `path`.
    Project { root: PathBuf, path: PathBuf },
}

/// What an edit leaves at its file.
pub(super) enum Replacement {
    /// The file's new text, which must load.
    Text(String),
    /// No file.
    Delete,
}

/// A hooks file as read at one moment.
pub(super) struct Snapshot {
    /// Where the file is, as clients are shown it.
    pub(super) path: PathBuf,
    /// The revision of `bytes`.
    pub(super) revision: ConfigRevision,
    /// Its bytes; `None` when there is no file.
    bytes: Option<Vec<u8>>,
}

impl HooksStore {
    pub(super) fn new(rho_home: &Path) -> Self {
        Self {
            user: crate::hooks::user_hooks_path(rho_home),
            edits: tokio::sync::Mutex::new(()),
        }
    }

    /// The user's hooks file.
    pub(super) fn user(&self) -> HooksTarget {
        HooksTarget::User(self.user.clone())
    }

    /// The hooks file of the project a session opened in `workspace` loads,
    /// found as `rho/hooks/list` finds it. Refused when that is the user's
    /// file, as when `workspace` is the home outside a repository or the
    /// project's `.rho` links to the Rho home: edited as a project's, the
    /// user's file would be held to the project rules.
    pub(super) fn project(&self, workspace: &Path) -> Result<HooksTarget, RpcError> {
        let root = crate::hooks::project_root(workspace);
        let path = crate::hooks::project_hooks_path(&root);
        let shared = matches!(
            (path.parent(), self.user.parent()),
            (Some(project), Some(user)) if crate::plugins::state::same_location(project, user)
        );
        if shared {
            return Err(RpcError::new(
                ErrorCode::InvalidParams,
                format!(
                    "{}: this project's hooks file is the user's; use scope `user`",
                    path.display()
                ),
            ));
        }
        Ok(HooksTarget::Project { root, path })
    }

    /// The file `target` names as it is now.
    pub(super) fn snapshot(&self, target: &HooksTarget) -> Result<Snapshot, RpcError> {
        Snapshot::read(target.path())
    }

    /// While the file `target` names is still at revision `expected`,
    /// replaces it with what `edit` makes of it, and returns its new
    /// revision. A stale `expected` is a conflict before `edit` runs. New
    /// text is written atomically, creating its directory, once it loads as
    /// a session loads `target`; [`Replacement::Delete`] removes the file.
    pub(super) async fn edit(
        &self,
        target: &HooksTarget,
        expected: &ConfigRevision,
        edit: impl FnOnce(&Snapshot) -> Result<Replacement, RpcError>,
    ) -> Result<ConfigRevision, RpcError> {
        let path = target.path();
        let _editing = self.edits.lock().await;
        let _locked = lock(path)?;
        let current = Snapshot::read(path)?;
        if current.revision != *expected {
            return Err(RpcError::new(
                ErrorCode::ConfigConflict,
                format!(
                    "{} changed since it was read; read it again",
                    current.path.display()
                ),
            ));
        }
        let replacement = edit(&current)?;
        let written = match &replacement {
            Replacement::Text(text) => {
                target
                    .check(text)
                    .map_err(|error| RpcError::new(ErrorCode::InvalidParams, error.to_string()))?;
                crate::config_writer::write_bytes_atomically(path, text.as_bytes())
            }
            Replacement::Delete => match std::fs::remove_file(path) {
                Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
                removed => removed,
            },
        };
        written.map_err(|error| {
            RpcError::new(
                ErrorCode::InternalError,
                format!("could not write {}: {error}", path.display()),
            )
        })?;
        Ok(revision(match &replacement {
            Replacement::Text(text) => Some(text.as_bytes()),
            Replacement::Delete => None,
        }))
    }
}

impl HooksTarget {
    fn path(&self) -> &Path {
        match self {
            Self::User(path) | Self::Project { path, .. } => path,
        }
    }

    /// Checks `text` as a session loads this file: a project's under the
    /// project rules, such as naming each program by path.
    fn check(&self, text: &str) -> Result<(), HookConfigError> {
        match self {
            Self::User(path) => crate::hooks::check_user_hooks(path, text),
            Self::Project { root, .. } => crate::hooks::check_project_hooks(root, text),
        }
    }
}

impl Snapshot {
    fn read(path: &Path) -> Result<Self, RpcError> {
        let bytes = match std::fs::read(path) {
            Ok(bytes) => Some(bytes),
            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
            Err(error) => {
                return Err(RpcError::new(
                    ErrorCode::InternalError,
                    format!("could not read {}: {error}", path.display()),
                ));
            }
        };
        Ok(Self {
            path: crate::paths::without_verbatim_prefix(path.to_path_buf()),
            revision: revision(bytes.as_deref()),
            bytes,
        })
    }

    /// The file's text; `None` when there is no file. TOML is UTF-8, so
    /// other bytes are a file only a hand edit fixes.
    pub(super) fn text(&self) -> Result<Option<&str>, RpcError> {
        self.bytes
            .as_deref()
            .map(|bytes| {
                std::str::from_utf8(bytes).map_err(|_| {
                    RpcError::new(
                        ErrorCode::ConfigInvalid,
                        format!("{} is not UTF-8 text", self.path.display()),
                    )
                })
            })
            .transpose()
    }
}

/// The revision of a file holding `bytes`, or of no file.
fn revision(bytes: Option<&[u8]>) -> ConfigRevision {
    ConfigRevision::new(bytes.map_or_else(
        || ABSENT.to_owned(),
        |bytes| hex::encode(Sha256::digest(bytes)),
    ))
}

/// The edit lock of the file at `path`, which every rho writer of it takes.
/// Held by another, it is a conflict the client can retry after reading
/// again.
fn lock(path: &Path) -> Result<crate::config_writer::edit_lock::EditFileLock, RpcError> {
    crate::config_writer::edit_lock::acquire_edit_lock(path).map_err(|error| {
        if error.kind() == io::ErrorKind::WouldBlock {
            RpcError::new(
                ErrorCode::ConfigConflict,
                format!("{} is being edited; read it again", path.display()),
            )
        } else {
            RpcError::new(
                ErrorCode::InternalError,
                format!("could not lock {}: {error}", path.display()),
            )
        }
    })
}