rpi-tools 0.35.0

Built-in agent tools (read/write/edit/bash/powershell) + ExecutionEnv, Rust port of pi harness tools
Documentation
//! Mirrors `packages/agent/src/harness/tools/file-mutation-queue.ts` — serializes
//! file-mutating operations per canonical path so concurrent edits to the same
//! path (or a symlink + its target) don't interleave.
//!
//! The TS uses a `WeakMap<ExecutionEnv, MutationQueueState>` keyed by env
//! instance. Rust has no per-instance map keyed by trait object, so each env
//! impl carries an `Arc<MutationQueueRegistry>` field and exposes it via the
//! [`MutatingEnv`] accessor trait. The mutation-dependent tools (write, edit)
//! hold `Arc<dyn MutatingEnv>`; read and bash don't need it.
//!
//! A caller cancelled while waiting still takes its turn with the cancelled
//! token. The guard stays held until the operation settles.

use std::collections::HashMap;
use std::sync::{Arc, Mutex, MutexGuard};

use futures::future::BoxFuture;
use tokio::sync::Mutex as AsyncMutex;
use tokio_util::sync::CancellationToken;

use crate::env::ExecutionEnv;
use crate::error::{FileError, FileErrorCode};

/// Active path queues. Each lease represents a holder or waiter.
#[derive(Default)]
pub struct MutationQueueRegistry {
    queues: Mutex<HashMap<String, QueueEntry>>,
}

struct QueueEntry {
    mutex: Arc<AsyncMutex<()>>,
    users: usize,
}

struct QueueLease<'a> {
    registry: &'a MutationQueueRegistry,
    key: &'a str,
    mutex: Arc<AsyncMutex<()>>,
}

impl Drop for QueueLease<'_> {
    fn drop(&mut self) {
        let mut queues = self.registry.entries();
        if let Some(entry) = queues.get_mut(self.key) {
            entry.users -= 1;
            if entry.users == 0 {
                queues.remove(self.key);
            }
        }
    }
}

impl MutationQueueRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    fn entries(&self) -> MutexGuard<'_, HashMap<String, QueueEntry>> {
        // This lock protects only bookkeeping and is never held across I/O.
        self.queues
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    fn lease<'a>(&'a self, key: &'a str) -> QueueLease<'a> {
        let mut queues = self.entries();
        let mutex = if let Some(entry) = queues.get_mut(key) {
            entry.users += 1;
            entry.mutex.clone()
        } else {
            let mutex = Arc::new(AsyncMutex::new(()));
            queues.insert(
                key.to_owned(),
                QueueEntry {
                    mutex: mutex.clone(),
                    users: 1,
                },
            );
            mutex
        };
        QueueLease {
            registry: self,
            key,
            mutex,
        }
    }

    pub(crate) async fn with_key<F, R>(
        &self,
        key: &str,
        cancel: &CancellationToken,
        f: F,
    ) -> Result<R, FileError>
    where
        F: for<'a> FnOnce(&'a CancellationToken) -> BoxFuture<'a, Result<R, FileError>>,
        R: Send + 'static,
    {
        let lease = self.lease(key);
        // Drop the per-key guard before releasing the lease, including when
        // the future is dropped while waiting or while running the closure.
        let _guard = lease.mutex.lock().await;
        f(cancel).await
    }
}

/// Accessor used by [`with_file_mutation_queue`] to reach the env's registry
/// AND its `ExecutionEnv` methods. Concrete env impls (`OsExecutionEnv`,
/// `InMemoryExecutionEnv`) implement this; the write/edit tools hold
/// `Arc<dyn MutatingEnv>`.
///
/// Implementors can expose a delegated execution environment alongside their
/// mutation queue registry.
pub trait MutatingEnv: Send + Sync {
    /// The underlying `ExecutionEnv` (for `FileSystem`/`Shell` calls).
    fn as_env(&self) -> &dyn ExecutionEnv;

    /// The registry holding per-canonical-path mutexes.
    fn mutation_registry(&self) -> &MutationQueueRegistry;
}

/// Compute the canonical-path queue key. A missing destination inherits the
/// canonical path of its nearest resolvable ancestor, so a create and a later
/// overwrite use the same queue even through a directory alias. Backends
/// without canonical paths fall back to their absolute paths.
pub async fn get_mutation_queue_key(
    env: &dyn ExecutionEnv,
    path: &str,
    cancel: Option<&CancellationToken>,
) -> Result<String, FileError> {
    let absolute = env.absolute_path(path, cancel).await?;
    let abs_str = absolute.to_string_lossy();
    match env.canonical_path(&abs_str, cancel).await {
        Ok(canonical) => return Ok(canonical.to_string_lossy().into_owned()),
        Err(e) if e.code == FileErrorCode::NotSupported => return Ok(abs_str.into_owned()),
        Err(e) if e.code == FileErrorCode::NotFound => {}
        Err(e) => return Err(e),
    }

    for ancestor in absolute.ancestors().skip(1) {
        match env
            .canonical_path(&ancestor.to_string_lossy(), cancel)
            .await
        {
            Ok(canonical) => {
                if let Ok(suffix) = absolute.strip_prefix(ancestor) {
                    return Ok(canonical.join(suffix).to_string_lossy().into_owned());
                }
                break;
            }
            Err(e) if e.code == FileErrorCode::NotFound => continue,
            Err(e) if e.code == FileErrorCode::Aborted => return Err(e),
            // Preserve the absolute fallback when an ancestor cannot be
            // resolved. The mutation will report any actual filesystem error.
            Err(_) => break,
        }
    }
    Ok(abs_str.into_owned())
}

/// Serialize mutations per canonical path. A cancelled waiter still takes
/// its turn and passes the token to the closure, which observes cancellation
/// at its mutation boundary.
pub async fn with_file_mutation_queue<F, R>(
    env: &dyn MutatingEnv,
    path: &str,
    cancel: &CancellationToken,
    f: F,
) -> Result<R, FileError>
where
    F: for<'a> FnOnce(&'a CancellationToken) -> BoxFuture<'a, Result<R, FileError>>,
    R: Send + 'static,
{
    let key = get_mutation_queue_key(env.as_env(), path, Some(cancel)).await?;
    env.mutation_registry().with_key(&key, cancel, f).await
}

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

    #[cfg(unix)]
    #[tokio::test]
    async fn missing_destination_shares_queue_through_directory_alias() {
        let temp = tempfile::tempdir().unwrap();
        let real = temp.path().join("real");
        std::fs::create_dir(&real).unwrap();
        std::os::unix::fs::symlink(&real, temp.path().join("alias")).unwrap();
        let env = crate::OsExecutionEnv::with_cwd(temp.path().to_path_buf());

        let alias_key = get_mutation_queue_key(&env, "alias/sub/new.txt", None)
            .await
            .unwrap();
        let real_key = get_mutation_queue_key(&env, "real/sub/new.txt", None)
            .await
            .unwrap();

        std::fs::create_dir(real.join("sub")).unwrap();
        std::fs::write(real.join("sub/new.txt"), "written").unwrap();
        let existing_key = get_mutation_queue_key(&env, "alias/sub/new.txt", None)
            .await
            .unwrap();

        assert_eq!(alias_key, real_key);
        assert_eq!(alias_key, existing_key);
    }

    #[tokio::test]
    async fn missing_destination_keeps_queue_key_when_created() {
        let temp = tempfile::tempdir().unwrap();
        let env = crate::OsExecutionEnv::with_cwd(temp.path().to_path_buf());
        let before = get_mutation_queue_key(&env, "sub/new.txt", None)
            .await
            .unwrap();

        std::fs::create_dir(temp.path().join("sub")).unwrap();
        std::fs::write(temp.path().join("sub/new.txt"), "written").unwrap();
        let after = get_mutation_queue_key(&env, "sub/new.txt", None)
            .await
            .unwrap();

        assert_eq!(before, after);
    }

    #[tokio::test]
    async fn completed_mutations_release_queue_entries() {
        let env = crate::InMemoryExecutionEnv::with_cwd("/".into());
        let cancel = CancellationToken::new();
        for index in 0..10_000 {
            with_file_mutation_queue(&env, &format!("/note-{index}.txt"), &cancel, |_| {
                Box::pin(async { Ok(()) })
            })
            .await
            .unwrap();
        }
        let retained = env.mutation_registry().entries().len();
        assert_eq!(
            retained, 0,
            "idle registry retained {retained} path entries"
        );
    }

    #[tokio::test]
    async fn dropping_a_waiter_preserves_the_queue_until_the_holder_finishes() {
        let queues = MutationQueueRegistry::new();
        let cancel = CancellationToken::new();
        let mut holder = Box::pin(queues.with_key("/note", &cancel, |_| {
            Box::pin(std::future::pending::<Result<(), FileError>>())
        }));
        assert!(futures::poll!(&mut holder).is_pending());

        let mut waiter =
            Box::pin(queues.with_key("/note", &cancel, |_| Box::pin(async { Ok(()) })));
        assert!(futures::poll!(&mut waiter).is_pending());
        assert_eq!(queues.entries()["/note"].users, 2);
        drop(waiter);
        assert_eq!(queues.entries()["/note"].users, 1);

        let mut next = Box::pin(queues.with_key("/note", &cancel, |_| Box::pin(async { Ok(()) })));
        assert!(futures::poll!(&mut next).is_pending());
        drop(holder);
        next.await.unwrap();
        assert!(queues.entries().is_empty());
    }
}