perf(skills): batch remote skill discovery reads

This commit is contained in:
Jeremy Rose
2026-07-08 10:32:10 +10:00
parent be33f80bc6
commit 6885fd4907
15 changed files with 906 additions and 188 deletions
+177 -167
View File
@@ -20,6 +20,9 @@ use codex_config::merge_toml_values;
use codex_config::project_root_markers_from_config;
use codex_exec_server::ExecutorFileSystem;
use codex_exec_server::LOCAL_FS;
use codex_exec_server::MAX_BATCH_READ_PATHS;
use codex_exec_server::WalkEntryKind;
use codex_exec_server::WalkOptions;
use codex_protocol::protocol::Product;
use codex_protocol::protocol::SkillScope;
use codex_utils_absolute_path::AbsolutePathBuf;
@@ -29,10 +32,9 @@ use codex_utils_plugins::DISCOVERABLE_PLUGIN_MANIFEST_PATHS;
use codex_utils_plugins::PluginSkillRoot;
use codex_utils_plugins::plugin_namespace_for_skill_path;
use dirs::home_dir;
use futures::future::join_all;
use serde::Deserialize;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::error::Error;
use std::fmt;
use std::io;
@@ -151,6 +153,68 @@ struct SkillFileDiscovery {
warnings: Vec<String>,
}
struct SkillReadCache {
files: HashMap<PathUri, io::Result<String>>,
}
impl SkillReadCache {
async fn load(fs: &dyn ExecutorFileSystem, skill_files: &[PathUri]) -> Self {
let mut paths = Vec::with_capacity(skill_files.len() * 2);
let mut seen = HashSet::new();
for skill_path in skill_files {
if seen.insert(skill_path.clone()) {
paths.push(skill_path.clone());
}
let Some(skill_dir) = skill_path.parent() else {
continue;
};
let Ok(metadata_dir) = skill_dir.join(SKILLS_METADATA_DIR) else {
continue;
};
let Ok(metadata_path) = metadata_dir.join(SKILLS_METADATA_FILENAME) else {
continue;
};
if seen.insert(metadata_path.clone()) {
paths.push(metadata_path);
}
}
let mut files = HashMap::with_capacity(paths.len());
for chunk in paths.chunks(MAX_BATCH_READ_PATHS) {
match fs.read_files(chunk, /*sandbox*/ None).await {
Ok(results) => {
for result in results {
files.insert(
result.path,
result.result.and_then(|bytes| {
String::from_utf8(bytes)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
}),
);
}
}
Err(error) => {
let kind = error.kind();
let message = error.to_string();
for path in chunk {
files.insert(path.clone(), Err(io::Error::new(kind, message.clone())));
}
}
}
}
Self { files }
}
fn read_text(&mut self, path: &PathUri) -> io::Result<String> {
self.files.remove(path).unwrap_or_else(|| {
Err(io::Error::new(
io::ErrorKind::NotFound,
format!("batched read omitted {path}"),
))
})
}
}
#[derive(Debug)]
enum SkillParseError {
Read(std::io::Error),
@@ -500,165 +564,121 @@ async fn discover_skills_under_root(
root: &PathUri,
symlink_policy: SymlinkPolicy,
) -> SkillFileDiscovery {
let root = root.clone();
let mut discovery = SkillFileDiscovery {
skill_files: Vec::new(),
plugin_roots: HashSet::new(),
namespace_roots: HashSet::from([root.clone()]),
warnings: Vec::new(),
};
match fs.get_metadata(&root, /*sandbox*/ None).await {
Ok(metadata) if metadata.is_directory => {}
Ok(_) => return discovery,
let walk = match fs
.walk(
root,
WalkOptions {
max_depth: MAX_SCAN_DEPTH,
max_directories: MAX_SKILLS_DIRS_PER_ROOT,
max_entries: MAX_SKILLS_DIRS_PER_ROOT * 10,
follow_directory_symlinks: matches!(
symlink_policy,
SymlinkPolicy::FollowDirectories
),
skip_hidden_directories: true,
},
/*sandbox*/ None,
)
.await
{
Ok(walk) => walk,
Err(err) if err.kind() == io::ErrorKind::NotFound => return discovery,
Err(err) => {
discovery
.warnings
.push(format!("failed to stat skills root {root}: {err:#}"));
.push(format!("failed to walk skills root {root}: {err:#}"));
return discovery;
}
};
let canonical_paths_complete = walk.canonical_paths_complete;
discovery
.warnings
.extend(walk.errors.into_iter().map(|error| {
format!(
"failed to scan skill path {}: {}",
error.path, error.message
)
}));
if walk.truncated {
discovery.warnings.push(format!(
"skills scan reached its traversal limit (root: {root})"
));
}
fn enqueue_dir(
queue: &mut VecDeque<(PathUri, usize)>,
visited_dirs: &mut HashSet<PathUri>,
truncated_by_dir_limit: &mut bool,
path: PathUri,
depth: usize,
) {
if depth > MAX_SCAN_DEPTH {
return;
}
if visited_dirs.len() >= MAX_SKILLS_DIRS_PER_ROOT {
*truncated_by_dir_limit = true;
return;
}
if visited_dirs.insert(path.clone()) {
queue.push_back((path, depth));
}
}
let follow_symlinks = matches!(symlink_policy, SymlinkPolicy::FollowDirectories);
let mut visited_dirs: HashSet<PathUri> = HashSet::from([root.clone()]);
let mut queue: VecDeque<(PathUri, usize)> = VecDeque::from([(root.clone(), 0)]);
let mut truncated_by_dir_limit = false;
while let Some((dir, depth)) = queue.pop_front() {
let entries = match fs.read_directory(&dir, /*sandbox*/ None).await {
Ok(entries) => entries,
Err(err) => {
discovery
.warnings
.push(format!("failed to read skills directory {dir}: {err:#}"));
continue;
}
};
let paths = entries
.into_iter()
.filter_map(|entry| {
let file_name = entry.file_name;
if DISCOVERABLE_PLUGIN_MANIFEST_PATHS
.iter()
.any(|path| path.split('/').next() == Some(file_name.as_str()))
for entry in walk.entries {
match entry.kind {
WalkEntryKind::Directory => {
if !has_hidden_ancestor_below_root(&entry.path, root)
&& DISCOVERABLE_PLUGIN_MANIFEST_PATHS
.iter()
.any(|path| path.split('/').next() == entry.path.basename().as_deref())
&& let Some(plugin_root) = entry
.canonical_path
.as_ref()
.unwrap_or(&entry.path)
.parent()
{
discovery.plugin_roots.insert(dir.clone());
discovery.plugin_roots.insert(plugin_root);
}
if file_name.starts_with('.') {
return None;
}
match dir.join(&file_name) {
Ok(path) => Some((file_name, path)),
Err(err) => {
discovery.warnings.push(format!(
"failed to resolve skill path {dir}/{file_name}: {err}"
));
None
}
}
})
.collect::<Vec<_>>();
let metadata_results = join_all(
paths
.iter()
.map(|(_, path)| fs.get_metadata(path, /*sandbox*/ None)),
)
.await;
for ((file_name, path), metadata_result) in paths.into_iter().zip(metadata_results) {
let metadata = match metadata_result {
Ok(metadata) => metadata,
Err(err) => {
discovery
.warnings
.push(format!("failed to stat skill path {path}: {err:#}"));
continue;
}
};
if metadata.is_symlink {
if !follow_symlinks {
continue;
}
match fs.read_directory(&path, /*sandbox*/ None).await {
Ok(_) => {
let resolved_dir = canonicalize_uri_for_skill_identity(fs, &path).await;
discovery.namespace_roots.insert(resolved_dir.clone());
enqueue_dir(
&mut queue,
&mut visited_dirs,
&mut truncated_by_dir_limit,
resolved_dir,
depth + 1,
);
}
Err(err)
if matches!(
err.kind(),
io::ErrorKind::NotADirectory | io::ErrorKind::NotFound
) => {}
Err(err) => discovery.warnings.push(format!(
"failed to read skills symlink directory {path}: {err:#}"
)),
}
continue;
}
if metadata.is_directory {
enqueue_dir(
&mut queue,
&mut visited_dirs,
&mut truncated_by_dir_limit,
path,
depth + 1,
);
continue;
}
if metadata.is_file && file_name == SKILLS_FILENAME {
discovery.skill_files.push(path);
WalkEntryKind::File
if !has_hidden_ancestor_below_root(&entry.path, root)
&& entry.path.basename().as_deref() == Some(SKILLS_FILENAME) =>
{
let (skill_path, has_canonical_alias) = match entry.canonical_path {
Some(canonical_path) => (canonical_path, true),
None => (entry.path, false),
};
if has_canonical_alias && let Some(namespace_root) = skill_path.parent() {
discovery.namespace_roots.insert(namespace_root);
}
discovery.skill_files.push(skill_path);
}
WalkEntryKind::File => {}
}
}
if truncated_by_dir_limit {
tracing::warn!(
"skills scan truncated after {} directories (root: {})",
MAX_SKILLS_DIRS_PER_ROOT,
root
);
if !canonical_paths_complete {
let canonicalized_skill_files =
futures::future::join_all(discovery.skill_files.into_iter().map(|path| async move {
let canonical_path = fs
.canonicalize(&path, /*sandbox*/ None)
.await
.unwrap_or_else(|_| path.clone());
(path, canonical_path)
}))
.await;
discovery.skill_files = canonicalized_skill_files
.into_iter()
.map(|(walk_path, canonical_path)| {
if walk_path != canonical_path
&& let Some(namespace_root) = canonical_path.parent()
{
discovery.namespace_roots.insert(namespace_root);
}
canonical_path
})
.collect();
}
discovery
}
async fn canonicalize_uri_for_skill_identity(
file_system: &dyn ExecutorFileSystem,
path: &PathUri,
) -> PathUri {
file_system
.canonicalize(path, /*sandbox*/ None)
.await
.unwrap_or_else(|_| path.clone())
fn has_hidden_ancestor_below_root(path: &PathUri, root: &PathUri) -> bool {
let mut ancestor = path.parent();
while let Some(current) = ancestor {
if &current == root {
return false;
}
if current.basename().is_some_and(|name| name.starts_with('.')) {
return true;
}
ancestor = current.parent();
}
false
}
async fn load_skills_under_root(
@@ -680,12 +700,14 @@ async fn load_skills_under_root(
};
let SkillFileDiscovery {
skill_files,
namespace_roots: _namespace_roots,
warnings,
..
} = discover_skills_under_root(fs, &PathUri::from_abs_path(root), symlink_policy).await;
for warning in warnings {
error!("{warning}");
}
let mut read_cache = SkillReadCache::load(fs, &skill_files).await;
for path_uri in skill_files {
let path = match path_uri.to_abs_path() {
Ok(path) => path,
@@ -701,6 +723,7 @@ async fn load_skills_under_root(
plugin_id,
plugin_namespace,
plugin_root.as_ref(),
&mut read_cache,
)
.await
{
@@ -721,11 +744,11 @@ async fn parse_skill_file(
plugin_id: Option<&str>,
plugin_namespace: Option<&str>,
plugin_root: Option<&AbsolutePathBuf>,
read_cache: &mut SkillReadCache,
) -> Result<SkillMetadata, SkillParseError> {
let path_uri = PathUri::from_abs_path(path);
let contents = fs
.read_file_text(&path_uri, /*sandbox*/ None)
.await
let contents = read_cache
.read_text(&path_uri)
.map_err(SkillParseError::Read)?;
let ParsedSkillFrontmatter {
name: base_name,
@@ -737,12 +760,10 @@ async fn parse_skill_file(
interface,
dependencies,
policy,
} = load_skill_metadata(fs, path, plugin_root).await;
} = load_skill_metadata(path, plugin_root, read_cache);
validate_len(&name, MAX_QUALIFIED_NAME_LEN, "qualified name")?;
let resolved_path = canonicalize_for_skill_identity(fs, path).await;
Ok(SkillMetadata {
name,
description,
@@ -750,7 +771,7 @@ async fn parse_skill_file(
interface,
dependencies,
policy,
path_to_skills_md: resolved_path,
path_to_skills_md: path.clone(),
scope,
plugin_id: plugin_id.map(str::to_string),
})
@@ -833,10 +854,10 @@ async fn namespaced_skill_name(
.unwrap_or_else(|| base_name.to_string())
}
async fn load_skill_metadata(
fs: &dyn ExecutorFileSystem,
fn load_skill_metadata(
skill_path: &AbsolutePathBuf,
plugin_root: Option<&AbsolutePathBuf>,
read_cache: &mut SkillReadCache,
) -> LoadedSkillMetadata {
// Fail open: optional metadata should not block loading SKILL.md.
let Some(skill_dir) = skill_path.parent() else {
@@ -846,27 +867,16 @@ async fn load_skill_metadata(
.join(SKILLS_METADATA_DIR)
.join(SKILLS_METADATA_FILENAME);
let metadata_path_uri = PathUri::from_abs_path(&metadata_path);
match fs.get_metadata(&metadata_path_uri, /*sandbox*/ None).await {
Ok(metadata) if metadata.is_file => {}
Ok(_) => return LoadedSkillMetadata::default(),
Err(error) if error.kind() == io::ErrorKind::NotFound => {
return LoadedSkillMetadata::default();
}
Err(error) => {
tracing::warn!(
"ignoring {path}: failed to stat {label}: {error}",
path = metadata_path.display(),
label = SKILLS_METADATA_FILENAME
);
return LoadedSkillMetadata::default();
}
}
let contents = match fs
.read_file_text(&metadata_path_uri, /*sandbox*/ None)
.await
{
let contents = match read_cache.read_text(&metadata_path_uri) {
Ok(contents) => contents,
Err(error)
if matches!(
error.kind(),
io::ErrorKind::NotFound | io::ErrorKind::IsADirectory
) =>
{
return LoadedSkillMetadata::default();
}
Err(error) => {
tracing::warn!(
"ignoring {path}: failed to read {label}: {error}",
@@ -157,6 +157,7 @@ pub async fn load_environment_skills_from_root(
max_directories: MAX_SKILLS_DIRS_PER_ROOT,
max_entries: MAX_SKILLS_ENTRIES_PER_ROOT,
follow_directory_symlinks: true,
skip_hidden_directories: false,
},
/*sandbox*/ None,
)
+218
View File
@@ -4,7 +4,19 @@ use codex_config::ConfigLayerEntry;
use codex_config::ConfigLayerStack;
use codex_config::ConfigRequirements;
use codex_config::ConfigRequirementsToml;
use codex_exec_server::CopyOptions;
use codex_exec_server::CreateDirectoryOptions;
use codex_exec_server::ExecutorFileSystem;
use codex_exec_server::ExecutorFileSystemFuture;
use codex_exec_server::FileMetadata;
use codex_exec_server::FileSystemReadStream;
use codex_exec_server::FileSystemSandboxContext;
use codex_exec_server::LOCAL_FS;
use codex_exec_server::ReadDirectoryEntry;
use codex_exec_server::ReadFileResult;
use codex_exec_server::RemoveOptions;
use codex_exec_server::WalkOptions;
use codex_exec_server::WalkOutcome;
use codex_protocol::protocol::Product;
use codex_protocol::protocol::SkillScope;
use codex_utils_absolute_path::AbsolutePathBuf;
@@ -16,6 +28,9 @@ use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use tempfile::TempDir;
use toml::Value as TomlValue;
@@ -26,6 +41,136 @@ struct TestConfig {
config_layer_stack: ConfigLayerStack,
}
struct RecordingReadFiles {
inner: Arc<dyn ExecutorFileSystem>,
batches: Mutex<Vec<Vec<PathUri>>>,
single_reads: Mutex<Vec<PathUri>>,
canonicalizes: AtomicUsize,
walks: AtomicUsize,
directory_reads: AtomicUsize,
}
impl RecordingReadFiles {
fn new(inner: Arc<dyn ExecutorFileSystem>) -> Self {
Self {
inner,
batches: Mutex::new(Vec::new()),
single_reads: Mutex::new(Vec::new()),
canonicalizes: AtomicUsize::new(0),
walks: AtomicUsize::new(0),
directory_reads: AtomicUsize::new(0),
}
}
}
impl ExecutorFileSystem for RecordingReadFiles {
fn canonicalize<'a>(
&'a self,
path: &'a PathUri,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, PathUri> {
self.canonicalizes.fetch_add(1, Ordering::Relaxed);
self.inner.canonicalize(path, sandbox)
}
fn read_file<'a>(
&'a self,
path: &'a PathUri,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
self.single_reads
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(path.clone());
self.inner.read_file(path, sandbox)
}
fn read_files<'a>(
&'a self,
paths: &'a [PathUri],
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<ReadFileResult>> {
self.batches
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(paths.to_vec());
self.inner.read_files(paths, sandbox)
}
fn read_file_stream<'a>(
&'a self,
path: &'a PathUri,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileSystemReadStream> {
self.inner.read_file_stream(path, sandbox)
}
fn write_file<'a>(
&'a self,
path: &'a PathUri,
contents: Vec<u8>,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, ()> {
self.inner.write_file(path, contents, sandbox)
}
fn create_directory<'a>(
&'a self,
path: &'a PathUri,
options: CreateDirectoryOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, ()> {
self.inner.create_directory(path, options, sandbox)
}
fn get_metadata<'a>(
&'a self,
path: &'a PathUri,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
self.inner.get_metadata(path, sandbox)
}
fn read_directory<'a>(
&'a self,
path: &'a PathUri,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<ReadDirectoryEntry>> {
self.directory_reads.fetch_add(1, Ordering::Relaxed);
self.inner.read_directory(path, sandbox)
}
fn walk<'a>(
&'a self,
path: &'a PathUri,
options: WalkOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, WalkOutcome> {
self.walks.fetch_add(1, Ordering::Relaxed);
self.inner.walk(path, options, sandbox)
}
fn remove<'a>(
&'a self,
path: &'a PathUri,
options: RemoveOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, ()> {
self.inner.remove(path, options, sandbox)
}
fn copy<'a>(
&'a self,
source_path: &'a PathUri,
destination_path: &'a PathUri,
options: CopyOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, ()> {
self.inner
.copy(source_path, destination_path, options, sandbox)
}
}
async fn make_config(codex_home: &TempDir) -> TestConfig {
make_config_for_cwd(codex_home, codex_home.path().to_path_buf()).await
}
@@ -384,6 +529,79 @@ fn write_skill_metadata_at(skill_dir: &Path, contents: &str) -> PathBuf {
path
}
#[tokio::test]
async fn batches_discovered_skill_and_optional_metadata_reads() {
let root = tempfile::tempdir().expect("tempdir");
let first_skill = write_skill_at(root.path(), "first", "first", "first description");
let second_skill = write_skill_at(root.path(), "second", "second", "second description");
write_skill_metadata_at(
first_skill.parent().expect("skill parent"),
"policy:\n allow_implicit_invocation: false\n",
);
let file_system = Arc::new(RecordingReadFiles::new(Arc::clone(&LOCAL_FS)));
let outcome = load_skills_from_roots(
[SkillRoot {
path: root.path().abs(),
scope: SkillScope::User,
file_system: file_system.clone(),
plugin_id: None,
plugin_namespace: None,
plugin_root: None,
}],
/*plugin_skill_snapshots*/ None,
)
.await;
assert!(
outcome.errors.is_empty(),
"unexpected errors: {:?}",
outcome.errors
);
assert_eq!(outcome.skills.len(), 2);
// The root keeps its existing identity canonicalization; discovered files should not add N
// more remote calls.
assert_eq!(file_system.canonicalizes.load(Ordering::Relaxed), 1);
assert_eq!(file_system.walks.load(Ordering::Relaxed), 1);
assert_eq!(file_system.directory_reads.load(Ordering::Relaxed), 0);
let batches = file_system
.batches
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
assert_eq!(batches.len(), 1);
let mut actual_paths = batches[0].clone();
actual_paths.sort_by_key(ToString::to_string);
let first_skill = normalized(&first_skill);
let second_skill = normalized(&second_skill);
let first_metadata = first_skill
.parent()
.expect("skill parent")
.join(SKILLS_METADATA_DIR)
.join(SKILLS_METADATA_FILENAME);
let second_metadata = second_skill
.parent()
.expect("skill parent")
.join(SKILLS_METADATA_DIR)
.join(SKILLS_METADATA_FILENAME);
let mut expected_paths = vec![
PathUri::from_abs_path(&first_skill),
PathUri::from_abs_path(&second_skill),
PathUri::from_abs_path(&first_metadata),
PathUri::from_abs_path(&second_metadata),
];
expected_paths.sort_by_key(ToString::to_string);
assert_eq!(actual_paths, expected_paths);
assert_eq!(
file_system
.single_reads
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone(),
Vec::<PathUri>::new()
);
}
fn write_skill_interface_at(skill_dir: &Path, contents: &str) -> PathBuf {
write_skill_metadata_at(skill_dir, contents)
}
@@ -25,6 +25,7 @@ pub const EXEC_EXITED_METHOD: &str = "process/exited";
pub const EXEC_CLOSED_METHOD: &str = "process/closed";
pub const ENVIRONMENT_INFO_METHOD: &str = "environment/info";
pub const FS_READ_FILE_METHOD: &str = "fs/readFile";
pub const FS_READ_FILES_METHOD: &str = "fs/readFiles";
pub const FS_OPEN_METHOD: &str = "fs/open";
pub const FS_READ_BLOCK_METHOD: &str = "fs/readBlock";
pub const FS_CLOSE_METHOD: &str = "fs/close";
@@ -258,6 +259,33 @@ pub struct FsReadFileResponse {
pub data_base64: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FsReadFilesParams {
pub paths: Vec<PathUri>,
pub sandbox: Option<FileSystemSandboxContext>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FsReadFilesResponse {
pub files: Vec<FsReadFilesResult>,
}
/// One independently successful or failed entry returned by fs/readFiles.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "camelCase")]
pub enum FsReadFilesResult {
Ok {
path: PathUri,
data_base64: String,
},
Error {
path: PathUri,
error: crate::JSONRPCErrorError,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FsOpenParams {
+2
View File
@@ -351,6 +351,8 @@ for invalid or unavailable paths. Native absolute path strings are rejected;
callers must convert them to `file:` URIs before sending requests:
- `fs/readFile`
- `fs/readFiles` (up to 128 paths; each result succeeds or fails independently,
with at most 64 MiB of decoded file data in one response)
- `fs/open`, `fs/readBlock`, and `fs/close` (internal transport for
`ExecutorFileSystem::read_file_stream`)
- `fs/writeFile`
+10
View File
@@ -58,6 +58,7 @@ use crate::protocol::FS_OPEN_METHOD;
use crate::protocol::FS_READ_BLOCK_METHOD;
use crate::protocol::FS_READ_DIRECTORY_METHOD;
use crate::protocol::FS_READ_FILE_METHOD;
use crate::protocol::FS_READ_FILES_METHOD;
use crate::protocol::FS_REMOVE_METHOD;
use crate::protocol::FS_WALK_METHOD;
use crate::protocol::FS_WRITE_FILE_METHOD;
@@ -79,6 +80,8 @@ use crate::protocol::FsReadDirectoryParams;
use crate::protocol::FsReadDirectoryResponse;
use crate::protocol::FsReadFileParams;
use crate::protocol::FsReadFileResponse;
use crate::protocol::FsReadFilesParams;
use crate::protocol::FsReadFilesResponse;
use crate::protocol::FsRemoveParams;
use crate::protocol::FsRemoveResponse;
use crate::protocol::FsWalkParams;
@@ -577,6 +580,13 @@ impl ExecServerClient {
self.call(FS_READ_FILE_METHOD, &params).await
}
pub async fn fs_read_files(
&self,
params: FsReadFilesParams,
) -> Result<FsReadFilesResponse, ExecServerError> {
self.call(FS_READ_FILES_METHOD, &params).await
}
pub async fn fs_open(&self, params: FsOpenParams) -> Result<FsOpenResponse, ExecServerError> {
self.call(FS_OPEN_METHOD, &params).await
}
+6
View File
@@ -53,7 +53,10 @@ pub use codex_file_system::FileMetadata;
pub use codex_file_system::FileSystemReadStream;
pub use codex_file_system::FileSystemResult;
pub use codex_file_system::FileSystemSandboxContext;
pub use codex_file_system::MAX_BATCH_READ_PATHS;
pub use codex_file_system::MAX_BATCH_READ_RESPONSE_BYTES;
pub use codex_file_system::ReadDirectoryEntry;
pub use codex_file_system::ReadFileResult;
pub use codex_file_system::RemoveOptions;
pub use codex_file_system::WalkEntry;
pub use codex_file_system::WalkEntryKind;
@@ -120,6 +123,9 @@ pub use protocol::FsReadDirectoryParams;
pub use protocol::FsReadDirectoryResponse;
pub use protocol::FsReadFileParams;
pub use protocol::FsReadFileResponse;
pub use protocol::FsReadFilesParams;
pub use protocol::FsReadFilesResponse;
pub use protocol::FsReadFilesResult;
pub use protocol::FsRemoveParams;
pub use protocol::FsRemoveResponse;
pub use protocol::FsWalkParams;
@@ -14,6 +14,7 @@ use crate::FileSystemReadStream;
use crate::FileSystemResult;
use crate::FileSystemSandboxContext;
use crate::ReadDirectoryEntry;
use crate::ReadFileResult;
use crate::RemoveOptions;
use crate::WalkOptions;
use crate::WalkOutcome;
@@ -24,6 +25,8 @@ use crate::protocol::FsCreateDirectoryParams;
use crate::protocol::FsGetMetadataParams;
use crate::protocol::FsReadDirectoryParams;
use crate::protocol::FsReadFileParams;
use crate::protocol::FsReadFilesParams;
use crate::protocol::FsReadFilesResult;
use crate::protocol::FsRemoveParams;
use crate::protocol::FsWalkParams;
use crate::protocol::FsWriteFileParams;
@@ -84,6 +87,75 @@ impl RemoteFileSystem {
})
}
async fn read_files(
&self,
paths: &[PathUri],
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<Vec<ReadFileResult>> {
trace!("remote fs read_files");
let client = self.client.get().await.map_err(map_remote_error)?;
let response = match client
.fs_read_files(FsReadFilesParams {
paths: paths.to_vec(),
sandbox: remote_sandbox_context(sandbox),
})
.await
{
Ok(response) => response,
Err(ExecServerError::Server {
code: METHOD_NOT_FOUND_ERROR_CODE,
..
}) => {
let mut results = Vec::with_capacity(paths.len());
for path in paths {
results.push(ReadFileResult {
path: path.clone(),
result: RemoteFileSystem::read_file(self, path, sandbox).await,
});
}
return Ok(results);
}
Err(error) => return Err(map_remote_error(error)),
};
if response.files.len() != paths.len() {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"remote fs/readFiles returned a different number of results",
));
}
response
.files
.into_iter()
.zip(paths)
.map(|(result, requested_path)| {
let (path, result) = match result {
FsReadFilesResult::Ok { path, data_base64 } => {
let result = STANDARD.decode(data_base64).map_err(|err| {
io::Error::new(
io::ErrorKind::InvalidData,
format!(
"remote fs/readFiles returned invalid base64 dataBase64: {err}"
),
)
});
(path, result)
}
FsReadFilesResult::Error { path, error } => {
(path, Err(map_remote_rpc_error(error)))
}
};
if &path != requested_path {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"remote fs/readFiles returned results out of order",
));
}
Ok(ReadFileResult { path, result })
})
.collect()
}
async fn read_file_stream(
&self,
path: &PathUri,
@@ -277,6 +349,14 @@ impl ExecutorFileSystem for RemoteFileSystem {
Box::pin(RemoteFileSystem::read_file(self, path, sandbox))
}
fn read_files<'a>(
&'a self,
paths: &'a [PathUri],
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<ReadFileResult>> {
Box::pin(RemoteFileSystem::read_files(self, paths, sandbox))
}
fn read_file_stream<'a>(
&'a self,
path: &'a PathUri,
@@ -380,6 +460,16 @@ fn map_remote_error(error: ExecServerError) -> io::Error {
}
}
fn map_remote_rpc_error(error: codex_exec_server_protocol::JSONRPCErrorError) -> io::Error {
if error.code == NOT_FOUND_ERROR_CODE {
io::Error::new(io::ErrorKind::NotFound, error.message)
} else if error.code == INVALID_REQUEST_ERROR_CODE {
io::Error::new(io::ErrorKind::InvalidInput, error.message)
} else {
io::Error::other(error.message)
}
}
#[cfg(all(test, any(unix, windows)))]
#[path = "remote_file_system_path_uri_tests.rs"]
mod path_uri_tests;
@@ -1,5 +1,7 @@
#![allow(clippy::expect_used)]
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use codex_exec_server_protocol::JSONRPCMessage;
use codex_exec_server_protocol::JSONRPCResponse;
use codex_protocol::models::PermissionProfile;
@@ -26,8 +28,12 @@ use super::*;
use crate::client_api::DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT;
use crate::client_api::ExecServerTransportParams;
use crate::protocol::FS_READ_FILE_METHOD;
use crate::protocol::FS_READ_FILES_METHOD;
use crate::protocol::FsReadFileParams;
use crate::protocol::FsReadFileResponse;
use crate::protocol::FsReadFilesParams;
use crate::protocol::FsReadFilesResponse;
use crate::protocol::FsReadFilesResult;
use crate::protocol::INITIALIZE_METHOD;
use crate::protocol::INITIALIZED_METHOD;
use crate::protocol::InitializeResponse;
@@ -82,6 +88,88 @@ async fn remote_file_system_sends_path_and_sandbox_cwd_uris_without_native_conve
server.await.expect("recording server should succeed");
}
#[tokio::test]
async fn remote_file_system_batches_paths_and_keeps_per_path_errors() {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("listener should bind");
let websocket_url = format!("ws://{}", listener.local_addr().expect("listener address"));
let paths = vec![
PathUri::parse("file:///C:/Users/Alice/src/SKILL.md").expect("valid drive URI"),
PathUri::parse("file://server/share/src/agents/openai.yaml").expect("valid UNC URI"),
];
let expected_paths = paths.clone();
let server = tokio::spawn(async move {
let (stream, _) = listener.accept().await.expect("listener should accept");
let mut websocket = accept_async(stream)
.await
.expect("websocket handshake should succeed");
complete_websocket_initialize(&mut websocket).await;
let request = match read_jsonrpc_websocket(&mut websocket).await {
JSONRPCMessage::Request(request) if request.method == FS_READ_FILES_METHOD => request,
other => panic!("expected fs/readFiles request, got {other:?}"),
};
let params: FsReadFilesParams =
serde_json::from_value(request.params.expect("fs/readFiles params should exist"))
.expect("fs/readFiles params should deserialize");
assert_eq!(params.paths, expected_paths);
write_jsonrpc_websocket(
&mut websocket,
JSONRPCMessage::Response(JSONRPCResponse {
id: request.id,
result: serde_json::to_value(FsReadFilesResponse {
files: vec![
FsReadFilesResult::Ok {
path: params.paths[0].clone(),
data_base64: BASE64_STANDARD.encode("skill"),
},
FsReadFilesResult::Error {
path: params.paths[1].clone(),
error: codex_exec_server_protocol::JSONRPCErrorError {
code: -32004,
data: None,
message: "missing metadata".to_string(),
},
},
],
})
.expect("fs/readFiles response should serialize"),
}),
)
.await;
});
let file_system = RemoteFileSystem::new(LazyRemoteExecServerClient::new(
ExecServerTransportParams::websocket_url(
websocket_url,
DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT,
),
));
let results = file_system
.read_files(&paths, /*sandbox*/ None)
.await
.expect("batch read should succeed");
assert_eq!(results.len(), 2);
assert_eq!(
results[0]
.result
.as_ref()
.expect("first read should succeed"),
b"skill"
);
assert_eq!(
results[1]
.result
.as_ref()
.expect_err("second read should fail")
.kind(),
std::io::ErrorKind::NotFound
);
server.await.expect("recording server should succeed");
}
async fn record_read_file_params(
expected_requests: usize,
) -> (
@@ -8,6 +8,8 @@ use crate::CopyOptions;
use crate::CreateDirectoryOptions;
use crate::ExecServerRuntimePaths;
use crate::ExecutorFileSystem;
use crate::MAX_BATCH_READ_PATHS;
use crate::MAX_BATCH_READ_RESPONSE_BYTES;
use crate::RemoveOptions;
use crate::file_read::FileReadHandleManager;
use crate::local_file_system::LocalFileSystem;
@@ -31,6 +33,9 @@ use crate::protocol::FsReadDirectoryParams;
use crate::protocol::FsReadDirectoryResponse;
use crate::protocol::FsReadFileParams;
use crate::protocol::FsReadFileResponse;
use crate::protocol::FsReadFilesParams;
use crate::protocol::FsReadFilesResponse;
use crate::protocol::FsReadFilesResult;
use crate::protocol::FsRemoveParams;
use crate::protocol::FsRemoveResponse;
use crate::protocol::FsWalkParams;
@@ -118,6 +123,60 @@ impl FileSystemHandler {
})
}
pub(crate) async fn read_files(
&self,
params: FsReadFilesParams,
) -> Result<FsReadFilesResponse, JSONRPCErrorError> {
if params.paths.is_empty() || params.paths.len() > MAX_BATCH_READ_PATHS {
return Err(invalid_request(format!(
"fs/readFiles requires 1 to {MAX_BATCH_READ_PATHS} paths"
)));
}
let mut total_bytes = 0usize;
let mut files = Vec::with_capacity(params.paths.len());
for result in self
.file_system
.read_files(&params.paths, params.sandbox.as_ref())
.await
.map_err(map_fs_error)?
{
let path = result.path;
match result.result {
Ok(bytes) => {
let Some(next_total) = total_bytes.checked_add(bytes.len()) else {
files.push(FsReadFilesResult::Error {
path,
error: invalid_request(
"fs/readFiles response is too large".to_string(),
),
});
continue;
};
if next_total > MAX_BATCH_READ_RESPONSE_BYTES {
files.push(FsReadFilesResult::Error {
path,
error: invalid_request(format!(
"fs/readFiles response exceeds {MAX_BATCH_READ_RESPONSE_BYTES} bytes"
)),
});
continue;
}
total_bytes = next_total;
files.push(FsReadFilesResult::Ok {
path,
data_base64: STANDARD.encode(bytes),
});
}
Err(error) => files.push(FsReadFilesResult::Error {
path,
error: map_fs_error(error),
}),
}
}
Ok(FsReadFilesResponse { files })
}
pub(crate) async fn write_file(
&self,
params: FsWriteFileParams,
@@ -275,6 +334,8 @@ mod tests {
use super::*;
use crate::FileSystemSandboxContext;
use crate::protocol::FsReadFileParams;
use crate::protocol::FsReadFilesParams;
use crate::protocol::FsReadFilesResult;
use crate::protocol::FsWriteFileParams;
#[tokio::test]
@@ -342,4 +403,51 @@ mod tests {
assert_eq!(response.data_base64, STANDARD.encode("ok"));
}
}
#[tokio::test]
async fn batched_reads_return_per_path_errors_and_reject_too_many_paths() {
let temp_dir = tempfile::tempdir().expect("tempdir");
let runtime_paths = ExecServerRuntimePaths::new(
std::env::current_exe().expect("current exe"),
/*codex_linux_sandbox_exe*/ None,
)
.expect("runtime paths");
let handler = FileSystemHandler::new(runtime_paths);
let present = temp_dir.path().join("present.txt");
std::fs::write(&present, "present").expect("write fixture");
let paths = vec![
PathUri::from_host_native_path(&present).expect("present URI"),
PathUri::from_host_native_path(temp_dir.path().join("missing.txt"))
.expect("missing URI"),
];
let response = handler
.read_files(FsReadFilesParams {
paths: paths.clone(),
sandbox: None,
})
.await
.expect("batch read should return partial results");
assert_eq!(response.files.len(), 2);
assert!(matches!(
&response.files[0],
FsReadFilesResult::Ok { path, data_base64 }
if path == &paths[0] && data_base64 == &STANDARD.encode("present")
));
assert!(matches!(
&response.files[1],
FsReadFilesResult::Error { path, error }
if path == &paths[1] && error.code == -32004
));
let error = handler
.read_files(FsReadFilesParams {
paths: vec![paths[0].clone(); MAX_BATCH_READ_PATHS + 1],
sandbox: None,
})
.await
.expect_err("oversized batch should fail");
assert_eq!(error.code, -32600);
}
}
@@ -35,6 +35,8 @@ use crate::protocol::FsReadDirectoryParams;
use crate::protocol::FsReadDirectoryResponse;
use crate::protocol::FsReadFileParams;
use crate::protocol::FsReadFileResponse;
use crate::protocol::FsReadFilesParams;
use crate::protocol::FsReadFilesResponse;
use crate::protocol::FsRemoveParams;
use crate::protocol::FsRemoveResponse;
use crate::protocol::FsWalkParams;
@@ -249,6 +251,14 @@ impl ExecServerHandler {
self.file_system.read_file(params).await
}
pub(crate) async fn fs_read_files(
&self,
params: FsReadFilesParams,
) -> Result<FsReadFilesResponse, JSONRPCErrorError> {
self.require_initialized_for("filesystem")?;
self.file_system.read_files(params).await
}
pub(crate) async fn fs_open(
&self,
params: FsOpenParams,
@@ -16,6 +16,7 @@ use crate::protocol::FS_OPEN_METHOD;
use crate::protocol::FS_READ_BLOCK_METHOD;
use crate::protocol::FS_READ_DIRECTORY_METHOD;
use crate::protocol::FS_READ_FILE_METHOD;
use crate::protocol::FS_READ_FILES_METHOD;
use crate::protocol::FS_REMOVE_METHOD;
use crate::protocol::FS_WALK_METHOD;
use crate::protocol::FS_WRITE_FILE_METHOD;
@@ -28,6 +29,7 @@ use crate::protocol::FsOpenParams;
use crate::protocol::FsReadBlockParams;
use crate::protocol::FsReadDirectoryParams;
use crate::protocol::FsReadFileParams;
use crate::protocol::FsReadFilesParams;
use crate::protocol::FsRemoveParams;
use crate::protocol::FsWalkParams;
use crate::protocol::FsWriteFileParams;
@@ -101,6 +103,12 @@ pub(crate) fn build_router() -> RpcRouter<ExecServerHandler> {
handler.fs_read_file(params).await
},
);
router.request(
FS_READ_FILES_METHOD,
|handler: Arc<ExecServerHandler>, params: FsReadFilesParams| async move {
handler.fs_read_files(params).await
},
);
router.request(
FS_OPEN_METHOD,
|handler: Arc<ExecServerHandler>, params: FsOpenParams| async move {
@@ -402,6 +402,7 @@ async fn file_system_walk_returns_a_bounded_tree(
max_directories: 10,
max_entries: 10,
follow_directory_symlinks: false,
skip_hidden_directories: false,
},
/*sandbox*/ None,
)
@@ -413,29 +414,35 @@ async fn file_system_walk_returns_a_bounded_tree(
entries: vec![
WalkEntry {
path: PathUri::from_host_native_path(&nested_dir)?,
canonical_path: None,
kind: WalkEntryKind::Directory,
},
WalkEntry {
path: PathUri::from_host_native_path(source_dir.join("root.txt"))?,
canonical_path: None,
kind: WalkEntryKind::File,
},
WalkEntry {
path: PathUri::from_host_native_path(nested_dir.join("note.txt"))?,
canonical_path: None,
kind: WalkEntryKind::File,
},
],
errors: Vec::new(),
truncated: false,
canonical_paths_complete: true,
}
);
let root_entries = vec![
WalkEntry {
path: PathUri::from_host_native_path(&nested_dir)?,
canonical_path: None,
kind: WalkEntryKind::Directory,
},
WalkEntry {
path: PathUri::from_host_native_path(source_dir.join("root.txt"))?,
canonical_path: None,
kind: WalkEntryKind::File,
},
];
@@ -447,6 +454,7 @@ async fn file_system_walk_returns_a_bounded_tree(
max_directories: 10,
max_entries: 10,
follow_directory_symlinks: false,
skip_hidden_directories: false,
},
/*sandbox*/ None,
)
@@ -458,6 +466,7 @@ async fn file_system_walk_returns_a_bounded_tree(
entries: root_entries.clone(),
errors: Vec::new(),
truncated: false,
canonical_paths_complete: true,
}
);
@@ -469,6 +478,7 @@ async fn file_system_walk_returns_a_bounded_tree(
max_directories: 1,
max_entries: 10,
follow_directory_symlinks: false,
skip_hidden_directories: false,
},
/*sandbox*/ None,
)
@@ -480,6 +490,7 @@ async fn file_system_walk_returns_a_bounded_tree(
entries: root_entries,
errors: Vec::new(),
truncated: true,
canonical_paths_complete: true,
}
);
@@ -491,6 +502,7 @@ async fn file_system_walk_returns_a_bounded_tree(
max_directories: 10,
max_entries: 1,
follow_directory_symlinks: false,
skip_hidden_directories: false,
},
/*sandbox*/ None,
)
@@ -501,13 +513,43 @@ async fn file_system_walk_returns_a_bounded_tree(
WalkOutcome {
entries: vec![WalkEntry {
path: PathUri::from_host_native_path(&nested_dir)?,
canonical_path: None,
kind: WalkEntryKind::Directory,
}],
errors: Vec::new(),
truncated: true,
canonical_paths_complete: true,
}
);
let hidden_dir = source_dir.join(".hidden");
std::fs::create_dir_all(&hidden_dir)?;
std::fs::write(hidden_dir.join("secret.txt"), "secret")?;
let hidden_pruned = file_system
.walk(
&source_uri,
WalkOptions {
max_depth: 4,
max_directories: 10,
max_entries: 10,
follow_directory_symlinks: false,
skip_hidden_directories: true,
},
/*sandbox*/ None,
)
.await
.with_context(|| format!("mode={implementation}"))?;
assert!(hidden_pruned.entries.contains(&WalkEntry {
path: PathUri::from_host_native_path(&hidden_dir)?,
canonical_path: None,
kind: WalkEntryKind::Directory,
}));
assert!(!hidden_pruned.entries.contains(&WalkEntry {
path: PathUri::from_host_native_path(hidden_dir.join("secret.txt"))?,
canonical_path: None,
kind: WalkEntryKind::File,
}));
Ok(())
}
@@ -535,6 +577,7 @@ async fn file_system_walk_honors_read_sandbox(
max_directories: 2,
max_entries: 2,
follow_directory_symlinks: false,
skip_hidden_directories: false,
},
Some(&sandbox),
)
@@ -545,10 +588,12 @@ async fn file_system_walk_honors_read_sandbox(
WalkOutcome {
entries: vec![WalkEntry {
path: PathUri::from_host_native_path(file_path)?,
canonical_path: None,
kind: WalkEntryKind::File,
}],
errors: Vec::new(),
truncated: false,
canonical_paths_complete: true,
}
);
@@ -299,17 +299,22 @@ async fn file_system_walk_handles_directory_symlinks(
max_directories: 4,
max_entries: 8,
follow_directory_symlinks: false,
skip_hidden_directories: false,
},
/*sandbox*/ None,
)
.await
.with_context(|| format!("mode={implementation}"))?;
let canonical_target = std::fs::canonicalize(&target)?;
let canonical_target_file = std::fs::canonicalize(&target_file)?;
let canonical_root = std::fs::canonicalize(&root)?;
assert_eq!(
outcome,
WalkOutcome {
entries: Vec::new(),
errors: Vec::new(),
truncated: false,
canonical_paths_complete: true,
}
);
@@ -321,6 +326,7 @@ async fn file_system_walk_handles_directory_symlinks(
max_directories: 4,
max_entries: 8,
follow_directory_symlinks: true,
skip_hidden_directories: false,
},
/*sandbox*/ None,
)
@@ -332,19 +338,23 @@ async fn file_system_walk_handles_directory_symlinks(
entries: vec![
WalkEntry {
path: PathUri::from_host_native_path(&target_link)?,
canonical_path: Some(PathUri::from_host_native_path(&canonical_target)?),
kind: WalkEntryKind::Directory,
},
WalkEntry {
path: PathUri::from_host_native_path(target_link.join("note.txt"))?,
canonical_path: Some(PathUri::from_host_native_path(&canonical_target_file)?),
kind: WalkEntryKind::File,
},
WalkEntry {
path: PathUri::from_host_native_path(target_link.join("root-link"))?,
canonical_path: Some(PathUri::from_host_native_path(&canonical_root)?),
kind: WalkEntryKind::Directory,
},
],
errors: Vec::new(),
truncated: false,
canonical_paths_complete: true,
}
);
+105 -21
View File
@@ -29,6 +29,17 @@ use std::task::Poll;
/// Maximum chunk size returned by [`ExecutorFileSystem::read_file_stream`].
pub const FILE_READ_CHUNK_SIZE: usize = 1024 * 1024;
/// Maximum number of paths accepted by one batched file-read request.
pub const MAX_BATCH_READ_PATHS: usize = 128;
/// Maximum decoded payload returned by one batched file-read request.
pub const MAX_BATCH_READ_RESPONSE_BYTES: usize = 64 * 1024 * 1024;
fn batch_read_response_too_large_error() -> io::Error {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("batched file read exceeds {MAX_BATCH_READ_RESPONSE_BYTES} bytes"),
)
}
const MAX_WALK_DEPTH: usize = 64;
const MAX_WALK_DIRECTORIES: usize = 10_000;
const MAX_WALK_ENTRIES: usize = 50_000;
@@ -69,6 +80,13 @@ pub struct ReadDirectoryEntry {
pub is_file: bool,
}
/// Result for one path requested through a batched file read.
#[derive(Debug)]
pub struct ReadFileResult {
pub path: PathUri,
pub result: FileSystemResult<Vec<u8>>,
}
/// Bounds for a recursive filesystem walk.
#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
@@ -81,6 +99,9 @@ pub struct WalkOptions {
pub max_entries: usize,
/// Whether directory symlinks should be followed.
pub follow_directory_symlinks: bool,
/// Whether hidden directory entries should be returned without traversing descendants.
#[serde(default)]
pub skip_hidden_directories: bool,
}
/// Type of a filesystem entry returned by a walk.
@@ -96,6 +117,9 @@ pub enum WalkEntryKind {
#[serde(rename_all = "camelCase")]
pub struct WalkEntry {
pub path: PathUri,
/// Canonical identity when it differs from the traversed path.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub canonical_path: Option<PathUri>,
pub kind: WalkEntryKind,
}
@@ -114,6 +138,9 @@ pub struct WalkOutcome {
pub entries: Vec<WalkEntry>,
pub errors: Vec<WalkError>,
pub truncated: bool,
/// Whether every entry includes canonical identity information when its path is an alias.
#[serde(default)]
pub canonical_paths_complete: bool,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
@@ -264,6 +291,41 @@ pub trait ExecutorFileSystem: Send + Sync {
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<u8>>;
/// Reads several files while preserving an independent result for every requested path.
///
/// Implementations with a native batch transport should override this. The fallback keeps
/// the same sandbox and path semantics as repeated single-file reads.
fn read_files<'a>(
&'a self,
paths: &'a [PathUri],
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<ReadFileResult>> {
Box::pin(async move {
let mut results = Vec::with_capacity(paths.len());
let mut total_bytes = 0usize;
for path in paths {
let result = match self.read_file(path, sandbox).await {
Ok(bytes) => {
if let Some(next_total) = total_bytes.checked_add(bytes.len())
&& next_total <= MAX_BATCH_READ_RESPONSE_BYTES
{
total_bytes = next_total;
Ok(bytes)
} else {
Err(batch_read_response_too_large_error())
}
}
Err(error) => Err(error),
};
results.push(ReadFileResult {
path: path.clone(),
result,
});
}
Ok(results)
})
}
/// Reads a file as a stream of chunks no larger than [`FILE_READ_CHUNK_SIZE`].
fn read_file_stream<'a>(
&'a self,
@@ -383,14 +445,17 @@ async fn walk_via_directory_reads<F: ExecutorFileSystem + ?Sized>(
} else {
root.clone()
};
let mut outcome = WalkOutcome::default();
let mut queue = VecDeque::from([(root.clone(), 0usize)]);
let mut outcome = WalkOutcome {
canonical_paths_complete: true,
..Default::default()
};
let mut queue = VecDeque::from([(root.clone(), root_identity.clone(), 0usize)]);
let mut visited_directories = HashSet::from([root_identity]);
let mut directory_count = 1usize;
let mut entry_count = 0usize;
let mut response_bytes = 0usize;
while let Some((directory, depth)) = queue.pop_front() {
while let Some((directory, canonical_directory, depth)) = queue.pop_front() {
let mut entries = match file_system.read_directory(&directory, sandbox).await {
Ok(entries) => entries,
Err(error) => {
@@ -450,20 +515,8 @@ async fn walk_via_directory_reads<F: ExecutorFileSystem + ?Sized>(
} else {
continue;
};
if !reserve_walk_response_bytes(
&mut outcome,
&mut response_bytes,
path.to_string().len(),
) {
return Ok(outcome);
}
outcome.entries.push(WalkEntry {
path: path.clone(),
kind,
});
if kind == WalkEntryKind::Directory && depth < options.max_depth {
let directory_identity = if options.follow_directory_symlinks {
let canonical_path = if options.follow_directory_symlinks {
if metadata.is_symlink {
match file_system.canonicalize(&path, sandbox).await {
Ok(path) => path,
Err(error) => {
@@ -479,16 +532,47 @@ async fn walk_via_directory_reads<F: ExecutorFileSystem + ?Sized>(
}
}
} else {
path.clone()
};
if !visited_directories.insert(directory_identity) {
canonical_directory
.join(&entry.file_name)
.unwrap_or_else(|_| path.clone())
}
} else {
path.clone()
};
let canonical_path = (canonical_path != path).then_some(canonical_path);
if !reserve_walk_response_bytes(
&mut outcome,
&mut response_bytes,
path.to_string().len()
+ canonical_path
.as_ref()
.map_or(0, |path| path.to_string().len()),
) {
return Ok(outcome);
}
outcome.entries.push(WalkEntry {
path: path.clone(),
canonical_path: canonical_path.clone(),
kind,
});
if kind == WalkEntryKind::Directory
&& options.skip_hidden_directories
&& entry.file_name.starts_with('.')
{
continue;
}
if kind == WalkEntryKind::Directory && depth < options.max_depth {
let directory_identity = canonical_path.unwrap_or_else(|| path.clone());
if !visited_directories.insert(directory_identity.clone()) {
continue;
}
if directory_count == options.max_directories {
outcome.truncated = true;
} else {
directory_count += 1;
queue.push_back((path, depth + 1));
queue.push_back((path, directory_identity, depth + 1));
}
}
}