rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! What `rho/fs/read` answers: a file's bytes, in the answer when they fit
//! what it carries, else streamed, never past the call's limit.

use std::{
    fs::File,
    io::{self, Read as _},
    path::{Path, PathBuf},
};

use base64::Engine as _;
use rho_protocol::{
    methods::{FsRead, FsReadContent, FsReadParams, HostPath},
    Caller, HostStreamWriter, RpcError,
};
use tokio::io::AsyncReadExt as _;

use super::{blocking, failed, modified_ns, not_a_folder, spawn_stream};

/// The most bytes a streamed file read asks the system for at once.
//
// What a host stream holds unread before a write waits (1 MiB,
// `rho_protocol::host_streams`): a bigger read would only wait longer.
const READ_CHUNK_BYTES: u64 = 1 << 20;

/// Reads `params.path`, as `read` answers.
pub(super) async fn read(caller: &Caller, params: FsReadParams) -> Result<FsRead, RpcError> {
    // The most the answer carries itself.
    let inline = params.limit.min(u64::from(params.inline_limit()));
    let FsReadParams {
        folder,
        path,
        limit,
        ..
    } = params;
    let Some(opened) = blocking(move || open_to_read(&folder, &path, inline)).await?? else {
        return Ok(FsRead::Gone);
    };
    let Opened {
        file,
        path,
        size,
        modified_ns,
        mut head,
    } = opened;
    let content = if head.len() as u64 <= inline {
        // The file ended within what the answer carries.
        FsReadContent::Inline {
            data: base64::engine::general_purpose::STANDARD.encode(&head),
            truncated: false,
        }
    } else if inline == limit {
        // `head` holds one byte past the limit: the file has more.
        head.truncate(head.len() - 1);
        FsReadContent::Inline {
            data: base64::engine::general_purpose::STANDARD.encode(&head),
            truncated: true,
        }
    } else {
        let stream = spawn_stream(caller, |writer| {
            stream_file(file, path, head, limit, writer)
        })?;
        FsReadContent::Stream { stream }
    };
    Ok(FsRead::File {
        size,
        modified_ns,
        content,
    })
}

/// A file `read` opened, with its first bytes.
struct Opened {
    file: File,
    path: PathBuf,
    size: u64,
    modified_ns: Option<u64>,
    /// Up to `inline + 1` bytes: one past what the answer carries tells
    /// whether the file has more.
    head: Vec<u8>,
}

/// Opens `path` in `folder` to read, reading its first `inline + 1` bytes;
/// `None` when it is not a file.
fn open_to_read(
    folder: &HostPath,
    path: &HostPath,
    inline: u64,
) -> Result<Option<Opened>, RpcError> {
    let in_folder = Path::new(folder.as_str());
    if !in_folder.is_dir() {
        return Err(not_a_folder(folder));
    }
    // An absolute path replaces the folder.
    let path = in_folder.join(path.as_str());
    let could_not_read =
        |error: io::Error| failed(format!("Couldn't read {}: {error}", path.display()));
    let Some((file, metadata)) = crate::git::open_regular(&path).map_err(could_not_read)? else {
        return Ok(None);
    };
    let mut head = Vec::new();
    (&file)
        .take(inline + 1)
        .read_to_end(&mut head)
        .map_err(could_not_read)?;
    Ok(Some(Opened {
        file,
        path,
        size: metadata.len(),
        modified_ns: modified_ns(&metadata),
        head,
    }))
}

/// Streams the rest of a file `read` answers with a stream: `head`, what
/// was read of it already, then up to `limit` bytes in all, ending
/// truncated when it has more. Never reads past `limit + 1` bytes.
async fn stream_file(
    file: File,
    path: PathBuf,
    head: Vec<u8>,
    limit: u64,
    mut writer: HostStreamWriter,
) {
    let mut sent = head.len() as u64;
    if writer.write(head).await.is_err() {
        return;
    }
    let mut file = tokio::fs::File::from_std(file);
    loop {
        // One byte past the limit tells a file that has more.
        let ask = (limit - sent).saturating_add(1).min(READ_CHUNK_BYTES);
        let mut chunk = Vec::new();
        if let Err(error) = (&mut file).take(ask).read_to_end(&mut chunk).await {
            writer.fail(format!("Couldn't read {}: {error}", path.display()));
            return;
        }
        let ended = (chunk.len() as u64) < ask;
        let past = sent + chunk.len() as u64 > limit;
        if past {
            chunk.pop();
        }
        sent += chunk.len() as u64;
        if !chunk.is_empty() && writer.write(chunk).await.is_err() {
            return;
        }
        if past {
            writer.truncate();
            return;
        }
        if ended {
            writer.finish();
            return;
        }
    }
}