aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
336
akode-rs/file-system/src/environment_accessor.rs
Normal file
336
akode-rs/file-system/src/environment_accessor.rs
Normal file
@@ -0,0 +1,336 @@
|
||||
//! Filesystem access bound to one environment configuration without exposing its authority.
|
||||
|
||||
use crate::CopyOptions;
|
||||
use crate::CreateDirectoryOptions;
|
||||
use crate::ExecutorFileSystem;
|
||||
use crate::ExecutorFileSystemFuture;
|
||||
use crate::FileMetadata;
|
||||
use crate::FileSystemReadStream;
|
||||
use crate::FileSystemResult;
|
||||
use crate::FileSystemSandboxContext;
|
||||
use crate::GetMetadataOptions;
|
||||
use crate::ReadDirectoryEntry;
|
||||
use crate::ReadFileOptions;
|
||||
use crate::RemoveOptions;
|
||||
use crate::WalkOptions;
|
||||
use crate::WalkOutcome;
|
||||
use crate::WriteFileOptions;
|
||||
use bytes::Bytes;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use futures::stream::BoxStream;
|
||||
use std::fmt;
|
||||
use std::hash::Hash;
|
||||
use std::hash::Hasher;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Weak;
|
||||
|
||||
/// Filesystem operations authorized by the environment that supplied this borrowed accessor.
|
||||
///
|
||||
/// Callers cannot extract the underlying filesystem or choose another sandbox. They may retain
|
||||
/// returned data, cache keys, opened read streams, and fixed-path watches after the accessor is gone.
|
||||
pub trait EnvironmentAccess: Send + Sync {
|
||||
/// Identifies the filesystem and captured permissions without granting access to either.
|
||||
fn cache_key(&self) -> EnvironmentAccessKey;
|
||||
|
||||
/// Registers an owned watch for these fixed paths, or returns `None` when unsupported.
|
||||
/// Implementations must preserve captured read permissions when checking the observation.
|
||||
fn watch_missing(
|
||||
&self,
|
||||
_missing: Vec<PathUri>,
|
||||
_present: Option<PathUri>,
|
||||
) -> ExecutorFileSystemFuture<'static, Option<tokio::sync::oneshot::Receiver<()>>> {
|
||||
Box::pin(async { Ok(None) })
|
||||
}
|
||||
|
||||
fn canonicalize<'a>(&'a self, path: &'a PathUri) -> ExecutorFileSystemFuture<'a, PathUri>;
|
||||
|
||||
fn read_file<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: ReadFileOptions,
|
||||
) -> ExecutorFileSystemFuture<'a, Vec<u8>>;
|
||||
|
||||
/// Opens an owned stream; subsequent reads do not borrow or reauthorize through the accessor.
|
||||
fn read_file_stream<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
) -> ExecutorFileSystemFuture<'a, FileSystemReadStream>;
|
||||
|
||||
/// Replaces a file through [`ExecutorFileSystem::write_file_stream`] with captured permissions.
|
||||
fn write_file_stream<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
contents: BoxStream<'a, FileSystemResult<Bytes>>,
|
||||
) -> ExecutorFileSystemFuture<'a, u64>;
|
||||
|
||||
fn write_file<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
contents: Vec<u8>,
|
||||
options: WriteFileOptions,
|
||||
) -> ExecutorFileSystemFuture<'a, ()>;
|
||||
|
||||
fn create_directory<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: CreateDirectoryOptions,
|
||||
) -> ExecutorFileSystemFuture<'a, ()>;
|
||||
|
||||
fn get_metadata<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: GetMetadataOptions,
|
||||
) -> ExecutorFileSystemFuture<'a, FileMetadata>;
|
||||
|
||||
fn read_directory<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
) -> ExecutorFileSystemFuture<'a, Vec<ReadDirectoryEntry>>;
|
||||
|
||||
fn walk<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: WalkOptions,
|
||||
) -> ExecutorFileSystemFuture<'a, WalkOutcome>;
|
||||
|
||||
fn remove<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: RemoveOptions,
|
||||
) -> ExecutorFileSystemFuture<'a, ()>;
|
||||
|
||||
fn copy<'a>(
|
||||
&'a self,
|
||||
source_path: &'a PathUri,
|
||||
destination_path: &'a PathUri,
|
||||
options: CopyOptions,
|
||||
) -> ExecutorFileSystemFuture<'a, ()>;
|
||||
}
|
||||
|
||||
/// Convenience operations available to every implementation of [`EnvironmentAccess`].
|
||||
pub trait EnvironmentAccessExt: EnvironmentAccess {
|
||||
fn read_file_text<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: ReadFileOptions,
|
||||
) -> ExecutorFileSystemFuture<'a, String>;
|
||||
}
|
||||
|
||||
impl<T: EnvironmentAccess + ?Sized> EnvironmentAccessExt for T {
|
||||
fn read_file_text<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: ReadFileOptions,
|
||||
) -> ExecutorFileSystemFuture<'a, String> {
|
||||
Box::pin(async move {
|
||||
let bytes = self.read_file(path, options).await?;
|
||||
String::from_utf8(bytes)
|
||||
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Opaque identity for reusing data discovered with the same filesystem and permissions.
|
||||
///
|
||||
/// Holding this key keeps neither the underlying filesystem nor an accessor alive.
|
||||
#[derive(Clone)]
|
||||
pub struct EnvironmentAccessKey {
|
||||
file_system: Weak<dyn ExecutorFileSystem>,
|
||||
// Cache keys are cloned per root; share the permission and path lists instead of copying them.
|
||||
sandbox: Option<Arc<FileSystemSandboxContext>>,
|
||||
}
|
||||
|
||||
impl EnvironmentAccessKey {
|
||||
/// Compares filesystem identity without comparing captured permissions.
|
||||
pub fn same_file_system(&self, other: &Self) -> bool {
|
||||
self.file_system.ptr_eq(&other.file_system)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for EnvironmentAccessKey {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("EnvironmentAccessKey(..)")
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for EnvironmentAccessKey {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.file_system.ptr_eq(&other.file_system) && self.sandbox == other.sandbox
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for EnvironmentAccessKey {}
|
||||
|
||||
impl Hash for EnvironmentAccessKey {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.file_system.as_ptr().cast::<()>().hash(state);
|
||||
// Sandbox contexts compare by value but are not Hash. Collisions for different policies
|
||||
// on the same filesystem are harmless; equality still compares the complete context.
|
||||
self.sandbox.is_some().hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
/// Borrows a filesystem and forwards every operation with its captured sandbox configuration.
|
||||
/// The underlying filesystem remains responsible for choosing sandboxed or direct access.
|
||||
pub struct FileSystemEnvironmentAccessor<'environment> {
|
||||
file_system: &'environment dyn ExecutorFileSystem,
|
||||
key: EnvironmentAccessKey,
|
||||
}
|
||||
|
||||
impl<'environment> FileSystemEnvironmentAccessor<'environment> {
|
||||
/// Binds operations and cache identity to the captured environment permissions.
|
||||
pub fn new(
|
||||
file_system: &'environment Arc<dyn ExecutorFileSystem>,
|
||||
sandbox: FileSystemSandboxContext,
|
||||
) -> Self {
|
||||
Self {
|
||||
file_system: file_system.as_ref(),
|
||||
key: EnvironmentAccessKey {
|
||||
file_system: Arc::downgrade(file_system),
|
||||
sandbox: Some(Arc::new(sandbox)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Bypasses the filesystem sandbox. Use only for:
|
||||
///
|
||||
/// 1. Tests.
|
||||
/// 2. Callers pending migration to sandboxed access.
|
||||
/// 3. Codex-internal operations that should never be sandboxed and that the model cannot trigger.
|
||||
///
|
||||
/// Model-turn discovery must use the accessor supplied by its selected environment.
|
||||
pub fn unrestricted(file_system: &'environment Arc<dyn ExecutorFileSystem>) -> Self {
|
||||
Self {
|
||||
file_system: file_system.as_ref(),
|
||||
key: EnvironmentAccessKey {
|
||||
file_system: Arc::downgrade(file_system),
|
||||
sandbox: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EnvironmentAccess for FileSystemEnvironmentAccessor<'_> {
|
||||
fn watch_missing(
|
||||
&self,
|
||||
missing: Vec<PathUri>,
|
||||
present: Option<PathUri>,
|
||||
) -> ExecutorFileSystemFuture<'static, Option<tokio::sync::oneshot::Receiver<()>>> {
|
||||
// Executor watches make unsandboxed observations, so restricted reads use live discovery.
|
||||
if self
|
||||
.key
|
||||
.sandbox
|
||||
.as_ref()
|
||||
.is_some_and(|sandbox| sandbox.should_read_from_sandbox())
|
||||
{
|
||||
return Box::pin(async { Ok(None) });
|
||||
}
|
||||
let Some(file_system) = self.key.file_system.upgrade() else {
|
||||
return Box::pin(async { Ok(None) });
|
||||
};
|
||||
Box::pin(async move { file_system.watch_missing(missing, present).await })
|
||||
}
|
||||
|
||||
fn cache_key(&self) -> EnvironmentAccessKey {
|
||||
self.key.clone()
|
||||
}
|
||||
|
||||
fn canonicalize<'a>(&'a self, path: &'a PathUri) -> ExecutorFileSystemFuture<'a, PathUri> {
|
||||
self.file_system
|
||||
.canonicalize(path, self.key.sandbox.as_deref())
|
||||
}
|
||||
|
||||
fn read_file<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: ReadFileOptions,
|
||||
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
|
||||
self.file_system
|
||||
.read_file(path, options, self.key.sandbox.as_deref())
|
||||
}
|
||||
|
||||
fn read_file_stream<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
) -> ExecutorFileSystemFuture<'a, FileSystemReadStream> {
|
||||
self.file_system
|
||||
.read_file_stream(path, self.key.sandbox.as_deref())
|
||||
}
|
||||
|
||||
fn write_file_stream<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
contents: BoxStream<'a, FileSystemResult<Bytes>>,
|
||||
) -> ExecutorFileSystemFuture<'a, u64> {
|
||||
self.file_system
|
||||
.write_file_stream(path, contents, self.key.sandbox.as_deref())
|
||||
}
|
||||
|
||||
fn write_file<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
contents: Vec<u8>,
|
||||
options: WriteFileOptions,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
self.file_system
|
||||
.write_file(path, contents, options, self.key.sandbox.as_deref())
|
||||
}
|
||||
|
||||
fn create_directory<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: CreateDirectoryOptions,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
self.file_system
|
||||
.create_directory(path, options, self.key.sandbox.as_deref())
|
||||
}
|
||||
|
||||
fn get_metadata<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: GetMetadataOptions,
|
||||
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
|
||||
self.file_system
|
||||
.get_metadata(path, options, self.key.sandbox.as_deref())
|
||||
}
|
||||
|
||||
fn read_directory<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
) -> ExecutorFileSystemFuture<'a, Vec<ReadDirectoryEntry>> {
|
||||
self.file_system
|
||||
.read_directory(path, self.key.sandbox.as_deref())
|
||||
}
|
||||
|
||||
fn walk<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: WalkOptions,
|
||||
) -> ExecutorFileSystemFuture<'a, WalkOutcome> {
|
||||
self.file_system
|
||||
.walk(path, options, self.key.sandbox.as_deref())
|
||||
}
|
||||
|
||||
fn remove<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: RemoveOptions,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
self.file_system
|
||||
.remove(path, options, self.key.sandbox.as_deref())
|
||||
}
|
||||
|
||||
fn copy<'a>(
|
||||
&'a self,
|
||||
source_path: &'a PathUri,
|
||||
destination_path: &'a PathUri,
|
||||
options: CopyOptions,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
self.file_system.copy(
|
||||
source_path,
|
||||
destination_path,
|
||||
options,
|
||||
self.key.sandbox.as_deref(),
|
||||
)
|
||||
}
|
||||
}
|
||||
22
akode-rs/file-system/src/exec_permission_profile_serde.rs
Normal file
22
akode-rs/file-system/src/exec_permission_profile_serde.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
//! Uses executor file URIs for sandbox permissions instead of the profile's legacy native paths.
|
||||
|
||||
use crate::ExecPermissionProfile;
|
||||
use akode_protocol::models::PermissionProfile;
|
||||
use serde::Deserialize;
|
||||
use serde::Deserializer;
|
||||
use serde::Serialize;
|
||||
use serde::Serializer;
|
||||
|
||||
pub(crate) fn serialize<S>(value: &PermissionProfile, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
ExecPermissionProfile::from(value.clone()).serialize(serializer)
|
||||
}
|
||||
|
||||
pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<PermissionProfile, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
ExecPermissionProfile::deserialize(deserializer).map(PermissionProfile::from)
|
||||
}
|
||||
126
akode-rs/file-system/src/find_up.rs
Normal file
126
akode-rs/file-system/src/find_up.rs
Normal file
@@ -0,0 +1,126 @@
|
||||
use crate::ExecutorFileSystem;
|
||||
use crate::FileSystemResult;
|
||||
use crate::FileSystemSandboxContext;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use futures::StreamExt;
|
||||
use std::io;
|
||||
|
||||
// Keep enough ordinary metadata calls in flight to cover typical ancestor chains in one remote
|
||||
// round trip, while leaving room for independent startup discovery to run at the same time.
|
||||
const MAX_CONCURRENT_PROBES: usize = 256;
|
||||
|
||||
/// Controls how an upward marker search handles metadata errors other than `NotFound`.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum FindUpErrorPolicy {
|
||||
/// Return the first error in lexical search order.
|
||||
Propagate,
|
||||
/// Treat errors as missing markers and continue searching.
|
||||
Ignore,
|
||||
}
|
||||
|
||||
/// Finds the nearest ancestor containing one of the provided marker names.
|
||||
///
|
||||
/// Marker paths are probed in lexical order from `start` toward the filesystem root. A bounded
|
||||
/// number of ordinary metadata calls are kept in flight so remote filesystems can pipeline them
|
||||
/// without requiring a batch protocol operation.
|
||||
pub async fn find_nearest_ancestor_with_markers(
|
||||
file_system: &dyn ExecutorFileSystem,
|
||||
start: &PathUri,
|
||||
markers: Vec<String>,
|
||||
error_policy: FindUpErrorPolicy,
|
||||
sandbox: Option<&FileSystemSandboxContext>,
|
||||
) -> FileSystemResult<Option<PathUri>> {
|
||||
find_nearest_ancestor(
|
||||
file_system,
|
||||
start.clone(),
|
||||
markers,
|
||||
PathUri::parent,
|
||||
|ancestor, marker| {
|
||||
ancestor
|
||||
.join(marker)
|
||||
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))
|
||||
},
|
||||
error_policy,
|
||||
sandbox,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Finds the nearest native ancestor containing one of the provided marker names.
|
||||
///
|
||||
/// Ancestors and marker paths remain native until each complete probe is converted to a URI. This
|
||||
/// preserves paths that require an opaque [`PathUri`] fallback.
|
||||
pub async fn find_nearest_native_ancestor_with_markers(
|
||||
file_system: &dyn ExecutorFileSystem,
|
||||
start: &AbsolutePathBuf,
|
||||
markers: Vec<String>,
|
||||
error_policy: FindUpErrorPolicy,
|
||||
sandbox: Option<&FileSystemSandboxContext>,
|
||||
) -> FileSystemResult<Option<AbsolutePathBuf>> {
|
||||
find_nearest_ancestor(
|
||||
file_system,
|
||||
start.clone(),
|
||||
markers,
|
||||
AbsolutePathBuf::parent,
|
||||
|ancestor, marker| Ok(PathUri::from_abs_path(&ancestor.join(marker))),
|
||||
error_policy,
|
||||
sandbox,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn find_nearest_ancestor<P, Parent, MarkerPath>(
|
||||
file_system: &dyn ExecutorFileSystem,
|
||||
start: P,
|
||||
markers: Vec<String>,
|
||||
parent: Parent,
|
||||
mut marker_path: MarkerPath,
|
||||
error_policy: FindUpErrorPolicy,
|
||||
sandbox: Option<&FileSystemSandboxContext>,
|
||||
) -> FileSystemResult<Option<P>>
|
||||
where
|
||||
P: Clone + Send,
|
||||
Parent: FnMut(&P) -> Option<P> + Send,
|
||||
MarkerPath: FnMut(&P, &str) -> FileSystemResult<PathUri> + Send,
|
||||
{
|
||||
let mut ancestors = std::iter::successors(Some(start), parent);
|
||||
let mut ancestor = ancestors.next();
|
||||
let mut marker_index = 0;
|
||||
let probes = std::iter::from_fn(move || {
|
||||
let current_ancestor = ancestor.clone()?;
|
||||
let marker = markers.get(marker_index)?;
|
||||
let marker_path = marker_path(¤t_ancestor, marker);
|
||||
|
||||
marker_index += 1;
|
||||
if marker_index == markers.len() {
|
||||
marker_index = 0;
|
||||
ancestor = ancestors.next();
|
||||
}
|
||||
|
||||
Some((current_ancestor, marker_path))
|
||||
});
|
||||
let mut results = futures::stream::iter(probes)
|
||||
.map(|(ancestor, marker_path)| async move {
|
||||
let marker_path = marker_path?;
|
||||
match file_system
|
||||
.get_metadata(&marker_path, crate::GetMetadataOptions::default(), sandbox)
|
||||
.await
|
||||
{
|
||||
Ok(_) => Ok(Some(ancestor)),
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
|
||||
Err(err) => match error_policy {
|
||||
FindUpErrorPolicy::Propagate => Err(err),
|
||||
FindUpErrorPolicy::Ignore => Ok(None),
|
||||
},
|
||||
}
|
||||
})
|
||||
.buffered(MAX_CONCURRENT_PROBES);
|
||||
|
||||
while let Some(result) = results.next().await {
|
||||
if let Some(ancestor) = result? {
|
||||
return Ok(Some(ancestor));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
747
akode-rs/file-system/src/lib.rs
Normal file
747
akode-rs/file-system/src/lib.rs
Normal file
@@ -0,0 +1,747 @@
|
||||
mod environment_accessor;
|
||||
mod exec_permission_profile_serde;
|
||||
mod find_up;
|
||||
mod local_logs;
|
||||
mod nfs;
|
||||
|
||||
use bytes::Bytes;
|
||||
use akode_protocol::config_types::WindowsSandboxLevel;
|
||||
use akode_protocol::config_types::WindowsSandboxProxySettingsMode;
|
||||
use akode_protocol::models::ManagedFileSystemPermissions;
|
||||
use akode_protocol::models::PermissionProfile;
|
||||
use akode_protocol::permissions::FileSystemAccessMode;
|
||||
use akode_protocol::permissions::FileSystemPath;
|
||||
use akode_protocol::permissions::FileSystemSandboxEntry;
|
||||
use akode_protocol::permissions::FileSystemSandboxEntryMissingPathBehavior;
|
||||
use akode_protocol::permissions::FileSystemSandboxPolicyContext;
|
||||
use akode_protocol::permissions::FileSystemSpecialPath;
|
||||
use akode_protocol::permissions::NetworkSandboxPolicy;
|
||||
use akode_protocol::sandbox::SandboxOverride;
|
||||
use akode_utils_path_uri::LegacyAppPathString;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
pub use environment_accessor::EnvironmentAccess;
|
||||
pub use environment_accessor::EnvironmentAccessExt;
|
||||
pub use environment_accessor::EnvironmentAccessKey;
|
||||
pub use environment_accessor::FileSystemEnvironmentAccessor;
|
||||
pub use find_up::FindUpErrorPolicy;
|
||||
pub use find_up::find_nearest_ancestor_with_markers;
|
||||
pub use find_up::find_nearest_native_ancestor_with_markers;
|
||||
use futures::Stream;
|
||||
use futures::stream::BoxStream;
|
||||
pub use local_logs::LocalLogsDir;
|
||||
pub use nfs::is_nfs;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::num::NonZeroUsize;
|
||||
use std::path::Path;
|
||||
use std::pin::Pin;
|
||||
use std::task::Context;
|
||||
use std::task::Poll;
|
||||
|
||||
/// Maximum chunk size returned by [`ExecutorFileSystem::read_file_stream`].
|
||||
pub const FILE_READ_CHUNK_SIZE: usize = 1024 * 1024;
|
||||
/// Maximum decoded chunk size accepted by a streamed filesystem write.
|
||||
pub const FILE_WRITE_CHUNK_SIZE: usize = 1024 * 1024;
|
||||
/// Maximum accepted directory depth for a filesystem walk.
|
||||
pub const MAX_WALK_DEPTH: usize = 64;
|
||||
/// Maximum accepted directory count, including the walk root.
|
||||
pub const MAX_WALK_DIRECTORIES: usize = 10_000;
|
||||
/// Maximum accepted number of directory entries to examine.
|
||||
pub const MAX_WALK_ENTRIES: usize = 50_000;
|
||||
/// Maximum estimated size of a walk response.
|
||||
pub const MAX_WALK_RESPONSE_BYTES: usize = 4 * 1024 * 1024;
|
||||
/// Per-entry or per-error overhead charged to the walk response budget.
|
||||
pub const WALK_RESPONSE_ITEM_OVERHEAD_BYTES: usize = 64;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct ReadFileOptions {
|
||||
pub follow_symlinks: bool,
|
||||
}
|
||||
|
||||
impl Default for ReadFileOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
follow_symlinks: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct WriteFileOptions {
|
||||
pub follow_symlinks: bool,
|
||||
}
|
||||
|
||||
impl Default for WriteFileOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
follow_symlinks: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct GetMetadataOptions {
|
||||
pub follow_symlinks: bool,
|
||||
}
|
||||
|
||||
impl Default for GetMetadataOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
follow_symlinks: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct CreateDirectoryOptions {
|
||||
pub recursive: bool,
|
||||
pub follow_symlinks: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct RemoveOptions {
|
||||
pub recursive: bool,
|
||||
pub force: bool,
|
||||
pub follow_symlinks: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct CopyOptions {
|
||||
pub recursive: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct FileMetadata {
|
||||
pub is_directory: bool,
|
||||
pub is_file: bool,
|
||||
pub is_symlink: bool,
|
||||
/// Size in bytes.
|
||||
pub size: u64,
|
||||
pub created_at_ms: i64,
|
||||
pub modified_at_ms: i64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct ReadDirectoryEntry {
|
||||
pub file_name: String,
|
||||
pub is_directory: bool,
|
||||
pub is_file: bool,
|
||||
}
|
||||
|
||||
/// Bounds for a recursive filesystem walk.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WalkOptions {
|
||||
/// Maximum directory depth below the root that may be traversed.
|
||||
pub max_depth: usize,
|
||||
/// Maximum number of directories that may be traversed, including the root.
|
||||
pub max_directories: usize,
|
||||
/// Maximum number of directory entries that may be examined.
|
||||
pub max_entries: usize,
|
||||
/// Whether directory symlinks should be followed.
|
||||
pub follow_directory_symlinks: bool,
|
||||
/// Whether directories whose names start with `.` should be returned but not traversed.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub prune_hidden_directories: bool,
|
||||
}
|
||||
|
||||
/// Type of a filesystem entry returned by a walk.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum WalkEntryKind {
|
||||
Directory,
|
||||
File,
|
||||
}
|
||||
|
||||
/// One entry returned by a walk.
|
||||
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WalkEntry {
|
||||
pub path: PathUri,
|
||||
pub kind: WalkEntryKind,
|
||||
}
|
||||
|
||||
/// A descendant that could not be inspected during a walk.
|
||||
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WalkError {
|
||||
pub path: PathUri,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// Entries and recoverable errors collected by a bounded walk.
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WalkOutcome {
|
||||
pub entries: Vec<WalkEntry>,
|
||||
pub errors: Vec<WalkError>,
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum ExecFileSystemPath {
|
||||
Path { path: PathUri },
|
||||
GlobPattern { pattern: String },
|
||||
Special { value: FileSystemSpecialPath },
|
||||
}
|
||||
|
||||
impl From<FileSystemPath> for ExecFileSystemPath {
|
||||
fn from(value: FileSystemPath) -> Self {
|
||||
match value {
|
||||
FileSystemPath::Path { path } => Self::Path { path },
|
||||
FileSystemPath::GlobPattern { pattern } => Self::GlobPattern { pattern },
|
||||
FileSystemPath::Special { value } => Self::Special { value },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ExecFileSystemPath> for FileSystemPath {
|
||||
fn from(value: ExecFileSystemPath) -> Self {
|
||||
match value {
|
||||
ExecFileSystemPath::Path { path } => Self::Path { path },
|
||||
ExecFileSystemPath::GlobPattern { pattern } => Self::GlobPattern { pattern },
|
||||
ExecFileSystemPath::Special { value } => Self::Special { value },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ExecFileSystemSandboxEntry {
|
||||
pub path: ExecFileSystemPath,
|
||||
pub access: FileSystemAccessMode,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub missing_path_behavior: Option<FileSystemSandboxEntryMissingPathBehavior>,
|
||||
}
|
||||
|
||||
impl From<FileSystemSandboxEntry> for ExecFileSystemSandboxEntry {
|
||||
fn from(value: FileSystemSandboxEntry) -> Self {
|
||||
Self {
|
||||
path: value.path.into(),
|
||||
access: value.access,
|
||||
missing_path_behavior: value.missing_path_behavior,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ExecFileSystemSandboxEntry> for FileSystemSandboxEntry {
|
||||
fn from(value: ExecFileSystemSandboxEntry) -> Self {
|
||||
Self {
|
||||
path: value.path.into(),
|
||||
access: value.access,
|
||||
missing_path_behavior: value.missing_path_behavior,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum ExecManagedFileSystemPermissions {
|
||||
Restricted {
|
||||
entries: Vec<ExecFileSystemSandboxEntry>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
glob_scan_max_depth: Option<NonZeroUsize>,
|
||||
},
|
||||
Unrestricted,
|
||||
}
|
||||
|
||||
impl From<ManagedFileSystemPermissions> for ExecManagedFileSystemPermissions {
|
||||
fn from(value: ManagedFileSystemPermissions) -> Self {
|
||||
match value {
|
||||
ManagedFileSystemPermissions::Restricted {
|
||||
entries,
|
||||
glob_scan_max_depth,
|
||||
} => Self::Restricted {
|
||||
entries: entries.into_iter().map(Into::into).collect(),
|
||||
glob_scan_max_depth,
|
||||
},
|
||||
ManagedFileSystemPermissions::Unrestricted => Self::Unrestricted,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ExecManagedFileSystemPermissions> for ManagedFileSystemPermissions {
|
||||
fn from(value: ExecManagedFileSystemPermissions) -> Self {
|
||||
match value {
|
||||
ExecManagedFileSystemPermissions::Restricted {
|
||||
entries,
|
||||
glob_scan_max_depth,
|
||||
} => Self::Restricted {
|
||||
entries: entries.into_iter().map(Into::into).collect(),
|
||||
glob_scan_max_depth,
|
||||
},
|
||||
ExecManagedFileSystemPermissions::Unrestricted => Self::Unrestricted,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Executor permission profile whose explicit filesystem paths serialize as file URIs.
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum ExecPermissionProfile {
|
||||
Managed {
|
||||
file_system: ExecManagedFileSystemPermissions,
|
||||
network: NetworkSandboxPolicy,
|
||||
},
|
||||
Disabled,
|
||||
External {
|
||||
network: NetworkSandboxPolicy,
|
||||
},
|
||||
}
|
||||
|
||||
impl From<PermissionProfile> for ExecPermissionProfile {
|
||||
fn from(value: PermissionProfile) -> Self {
|
||||
match value {
|
||||
PermissionProfile::Managed {
|
||||
file_system,
|
||||
network,
|
||||
} => Self::Managed {
|
||||
file_system: file_system.into(),
|
||||
network,
|
||||
},
|
||||
PermissionProfile::Disabled => Self::Disabled,
|
||||
PermissionProfile::External { network } => Self::External { network },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ExecPermissionProfile> for PermissionProfile {
|
||||
fn from(value: ExecPermissionProfile) -> Self {
|
||||
match value {
|
||||
ExecPermissionProfile::Managed {
|
||||
file_system,
|
||||
network,
|
||||
} => Self::Managed {
|
||||
file_system: file_system.into(),
|
||||
network,
|
||||
},
|
||||
ExecPermissionProfile::Disabled => Self::Disabled,
|
||||
ExecPermissionProfile::External { network } => Self::External { network },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Windows sandbox choice encoded in executor RPCs.
|
||||
///
|
||||
/// The serialized field retains its legacy `windowsSandboxLevel` name for compatibility, but MXC
|
||||
/// is a sandbox implementation rather than a RestrictedToken level.
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum WindowsSandboxSelection {
|
||||
#[default]
|
||||
Disabled,
|
||||
RestrictedToken,
|
||||
Elevated,
|
||||
Mxc,
|
||||
}
|
||||
|
||||
impl From<WindowsSandboxLevel> for WindowsSandboxSelection {
|
||||
fn from(level: WindowsSandboxLevel) -> Self {
|
||||
match level {
|
||||
WindowsSandboxLevel::Disabled => Self::Disabled,
|
||||
WindowsSandboxLevel::RestrictedToken => Self::RestrictedToken,
|
||||
WindowsSandboxLevel::Elevated => Self::Elevated,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Filesystem sandbox policy and the selected executor paths needed to interpret it.
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FileSystemSandboxContext {
|
||||
/// Serializes paths as executor file URIs instead of the profile's default native paths.
|
||||
#[serde(with = "exec_permission_profile_serde")]
|
||||
pub permissions: PermissionProfile,
|
||||
/// Controller-selected override for observations, never an authorization to widen permissions.
|
||||
#[serde(default, skip_serializing_if = "SandboxOverride::is_no_override")]
|
||||
pub sandbox_override: SandboxOverride,
|
||||
/// Working directory on the selected executor used to interpret sandbox permissions.
|
||||
/// Required even for absolute permissions; a process may use a different working directory.
|
||||
pub cwd: PathUri,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub workspace_roots: Vec<PathUri>,
|
||||
/// Executor-local user home used to resolve home-relative policy paths.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub user_home_dir: Option<PathUri>,
|
||||
/// Executor-local default directories used to resolve `:tmpdir` policy entries.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub temporary_directories: Option<Vec<PathUri>>,
|
||||
#[serde(rename = "windowsSandboxLevel")]
|
||||
pub windows_sandbox_selection: WindowsSandboxSelection,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub windows_sandbox_proxy_settings_mode: Option<WindowsSandboxProxySettingsMode>,
|
||||
#[serde(default)]
|
||||
pub use_legacy_landlock: bool,
|
||||
}
|
||||
|
||||
impl FileSystemSandboxContext {
|
||||
pub fn from_permission_profile(permissions: PermissionProfile, cwd: PathUri) -> Self {
|
||||
Self {
|
||||
permissions,
|
||||
sandbox_override: SandboxOverride::NoOverride,
|
||||
workspace_roots: vec![cwd.clone()],
|
||||
cwd,
|
||||
user_home_dir: None,
|
||||
temporary_directories: None,
|
||||
windows_sandbox_selection: WindowsSandboxSelection::Disabled,
|
||||
windows_sandbox_proxy_settings_mode: None,
|
||||
use_legacy_landlock: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether filesystem reads need a platform sandbox on the selected executor.
|
||||
pub fn should_read_from_sandbox(&self) -> bool {
|
||||
!self
|
||||
.permissions
|
||||
.file_system_sandbox_policy()
|
||||
.has_full_disk_read_access_for_convention(self.cwd.infer_path_convention())
|
||||
}
|
||||
|
||||
/// Whether filesystem writes need a platform sandbox on the selected executor.
|
||||
pub fn should_write_into_sandbox(&self) -> bool {
|
||||
!self
|
||||
.permissions
|
||||
.file_system_sandbox_policy()
|
||||
.has_full_disk_write_access_for_convention(self.cwd.infer_path_convention())
|
||||
}
|
||||
|
||||
/// Whether this context selects either supported Windows sandbox implementation.
|
||||
pub fn windows_sandbox_is_requested(&self) -> bool {
|
||||
self.windows_sandbox_selection != WindowsSandboxSelection::Disabled
|
||||
}
|
||||
|
||||
/// Checks that explicit permission paths can be enforced by the current host. An
|
||||
/// orchestrator can still construct this context with paths belonging to another executor.
|
||||
pub fn validate_file_system_paths_for_current_host(&self) -> io::Result<()> {
|
||||
if let PermissionProfile::Managed {
|
||||
file_system: ManagedFileSystemPermissions::Restricted { entries, .. },
|
||||
..
|
||||
} = &self.permissions
|
||||
{
|
||||
for entry in entries {
|
||||
if let FileSystemPath::Path { path } = &entry.path {
|
||||
path.to_abs_path().map_err(|error| {
|
||||
io::Error::new(
|
||||
error.kind(),
|
||||
format!("invalid sandbox permission path URI: {error}"),
|
||||
)
|
||||
})?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Borrows the executor-owned paths needed to interpret filesystem policy entries.
|
||||
pub fn policy_context(&self) -> FileSystemSandboxPolicyContext<'_> {
|
||||
FileSystemSandboxPolicyContext {
|
||||
cwd: &self.cwd,
|
||||
workspace_roots: &self.workspace_roots,
|
||||
user_home_dir: self.user_home_dir.as_ref(),
|
||||
temporary_directories: self.temporary_directories.as_deref(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Filesystem RPC wire context; older clients can omit the policy cwd before executor resolution.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WireFileSystemSandboxContext {
|
||||
permissions: ExecPermissionProfile,
|
||||
#[serde(default, skip_serializing_if = "SandboxOverride::is_no_override")]
|
||||
sandbox_override: SandboxOverride,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
cwd: Option<PathUri>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
policy_context: Option<WireFileSystemPolicyContext>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
workspace_roots: Vec<PathUri>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
user_home_dir: Option<PathUri>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
temporary_directories: Option<Vec<PathUri>>,
|
||||
#[serde(rename = "windowsSandboxLevel")]
|
||||
windows_sandbox_selection: WindowsSandboxSelection,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
windows_sandbox_proxy_settings_mode: Option<WindowsSandboxProxySettingsMode>,
|
||||
#[serde(default)]
|
||||
use_legacy_landlock: bool,
|
||||
}
|
||||
|
||||
/// New filesystem clients provide these paths independently of the legacy helper launch cwd.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct WireFileSystemPolicyContext {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
cwd: Option<PathUri>,
|
||||
#[serde(default)]
|
||||
workspace_roots: Vec<PathUri>,
|
||||
}
|
||||
|
||||
impl From<FileSystemSandboxContext> for WireFileSystemSandboxContext {
|
||||
fn from(sandbox: FileSystemSandboxContext) -> Self {
|
||||
let FileSystemSandboxContext {
|
||||
permissions,
|
||||
sandbox_override,
|
||||
cwd,
|
||||
workspace_roots,
|
||||
user_home_dir,
|
||||
temporary_directories,
|
||||
windows_sandbox_selection,
|
||||
windows_sandbox_proxy_settings_mode,
|
||||
use_legacy_landlock,
|
||||
} = sandbox;
|
||||
let permissions = ExecPermissionProfile::from(permissions);
|
||||
// Older filesystem clients sent cwd and roots only when permissions needed them; old
|
||||
// executors also use that cwd to launch their helper. The explicit context is independent.
|
||||
let legacy_needs_cwd = match &permissions {
|
||||
ExecPermissionProfile::Managed {
|
||||
file_system: ExecManagedFileSystemPermissions::Restricted { entries, .. },
|
||||
..
|
||||
} => entries.iter().any(|entry| match &entry.path {
|
||||
ExecFileSystemPath::GlobPattern { pattern } => match cwd.infer_path_convention() {
|
||||
Some(convention) => LegacyAppPathString::from_string(pattern)
|
||||
.to_path_uri(convention)
|
||||
.is_err(),
|
||||
None => true,
|
||||
},
|
||||
ExecFileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::ProjectRoots { .. },
|
||||
} => true,
|
||||
ExecFileSystemPath::Path { .. } | ExecFileSystemPath::Special { .. } => false,
|
||||
}),
|
||||
ExecPermissionProfile::Managed {
|
||||
file_system: ExecManagedFileSystemPermissions::Unrestricted,
|
||||
..
|
||||
}
|
||||
| ExecPermissionProfile::Disabled
|
||||
| ExecPermissionProfile::External { .. } => false,
|
||||
};
|
||||
Self {
|
||||
permissions,
|
||||
sandbox_override,
|
||||
cwd: legacy_needs_cwd.then(|| cwd.clone()),
|
||||
workspace_roots: if legacy_needs_cwd {
|
||||
workspace_roots.clone()
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
policy_context: Some(WireFileSystemPolicyContext {
|
||||
cwd: Some(cwd),
|
||||
workspace_roots,
|
||||
}),
|
||||
user_home_dir,
|
||||
temporary_directories,
|
||||
windows_sandbox_selection,
|
||||
windows_sandbox_proxy_settings_mode,
|
||||
use_legacy_landlock,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WireFileSystemSandboxContext {
|
||||
/// Returns the policy cwd supplied by the client, falling back to the legacy cwd field.
|
||||
pub fn cwd(&self) -> Option<&PathUri> {
|
||||
match &self.policy_context {
|
||||
Some(policy_context) => policy_context.cwd.as_ref().or(self.cwd.as_ref()),
|
||||
None => self.cwd.as_ref(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether a legacy filesystem policy needs the client's cwd to be interpreted.
|
||||
pub fn requires_cwd(&self) -> bool {
|
||||
let ExecPermissionProfile::Managed {
|
||||
file_system: ExecManagedFileSystemPermissions::Restricted { entries, .. },
|
||||
..
|
||||
} = &self.permissions
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
|
||||
entries.iter().any(|entry| match &entry.path {
|
||||
ExecFileSystemPath::GlobPattern { pattern } => !Path::new(pattern).is_absolute(),
|
||||
ExecFileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::ProjectRoots { .. },
|
||||
} => true,
|
||||
ExecFileSystemPath::Path { .. } | ExecFileSystemPath::Special { .. } => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Constructs the strict context after executor ingress has resolved the policy cwd.
|
||||
pub fn into_context(self, cwd: PathUri) -> FileSystemSandboxContext {
|
||||
FileSystemSandboxContext {
|
||||
permissions: self.permissions.into(),
|
||||
sandbox_override: self.sandbox_override,
|
||||
cwd,
|
||||
workspace_roots: match self.policy_context {
|
||||
Some(policy_context) => policy_context.workspace_roots,
|
||||
None => self.workspace_roots,
|
||||
},
|
||||
user_home_dir: self.user_home_dir,
|
||||
temporary_directories: self.temporary_directories,
|
||||
windows_sandbox_selection: self.windows_sandbox_selection,
|
||||
windows_sandbox_proxy_settings_mode: self.windows_sandbox_proxy_settings_mode,
|
||||
use_legacy_landlock: self.use_legacy_landlock,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type FileSystemResult<T> = io::Result<T>;
|
||||
|
||||
/// Future returned by [`ExecutorFileSystem`] operations.
|
||||
pub type ExecutorFileSystemFuture<'a, T> =
|
||||
Pin<Box<dyn Future<Output = FileSystemResult<T>> + Send + 'a>>;
|
||||
|
||||
/// Stream of immutable chunks read from an [`ExecutorFileSystem`].
|
||||
pub struct FileSystemReadStream {
|
||||
inner: Pin<Box<dyn Stream<Item = FileSystemResult<Bytes>> + Send + 'static>>,
|
||||
}
|
||||
|
||||
impl FileSystemReadStream {
|
||||
/// Wraps a filesystem byte stream.
|
||||
pub fn new(stream: impl Stream<Item = FileSystemResult<Bytes>> + Send + 'static) -> Self {
|
||||
Self {
|
||||
inner: Box::pin(stream),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for FileSystemReadStream {
|
||||
type Item = FileSystemResult<Bytes>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
self.inner.as_mut().poll_next(cx)
|
||||
}
|
||||
}
|
||||
|
||||
/// Abstract filesystem access used by components that may operate locally or via
|
||||
/// a remote environment.
|
||||
pub trait ExecutorFileSystem: Send + Sync {
|
||||
/// Watches an unsandboxed observation: every `missing` path is absent and `present`
|
||||
/// (if supplied) exists. Change, disconnection or supersession completes the receiver.
|
||||
/// Unsupported filesystems and observations that cannot be verified return `None`.
|
||||
fn watch_missing(
|
||||
&self,
|
||||
_missing: Vec<PathUri>,
|
||||
_present: Option<PathUri>,
|
||||
) -> ExecutorFileSystemFuture<'_, Option<tokio::sync::oneshot::Receiver<()>>> {
|
||||
Box::pin(async { Ok(None) })
|
||||
}
|
||||
|
||||
/// Resolves a path within this filesystem.
|
||||
fn canonicalize<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, PathUri>;
|
||||
|
||||
fn read_file<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: ReadFileOptions,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, Vec<u8>>;
|
||||
|
||||
/// Reads a file as a stream of chunks no larger than [`FILE_READ_CHUNK_SIZE`].
|
||||
fn read_file_stream<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, FileSystemReadStream>;
|
||||
|
||||
/// Replaces a regular file from a stream of bounded chunks.
|
||||
///
|
||||
/// Accepts any sendable byte stream, boxed to keep this trait object-safe.
|
||||
/// Input chunks must be nonempty and no larger than [`FILE_WRITE_CHUNK_SIZE`].
|
||||
/// Returns the number of bytes written after closing the target. Parents must already exist.
|
||||
/// Failure or cancellation may leave a truncated or partial target.
|
||||
///
|
||||
/// Cancellation is best effort: dropping the future stops consuming input and issuing new
|
||||
/// blocks, but an in-flight open or write may still truncate or modify the target. Dropping
|
||||
/// does not wait for that I/O or remote handle cleanup, so a subsequent replacement may overlap
|
||||
/// with the abandoned operation.
|
||||
///
|
||||
/// Local and streaming-capable remote filesystems write one chunk at a time. For compatibility,
|
||||
/// a remote filesystem may buffer the entire input and send one write to an older executor.
|
||||
/// The default implementation returns `Unsupported` without consuming the input.
|
||||
fn write_file_stream<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
contents: BoxStream<'a, FileSystemResult<Bytes>>,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, u64> {
|
||||
Box::pin(async move {
|
||||
let _ = (path, contents, sandbox);
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"filesystem does not support streaming writes",
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads a file and decodes it as UTF-8 text.
|
||||
fn read_file_text<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: ReadFileOptions,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, String> {
|
||||
Box::pin(async move {
|
||||
let bytes = self.read_file(path, options, sandbox).await?;
|
||||
String::from_utf8(bytes).map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
|
||||
})
|
||||
}
|
||||
|
||||
fn write_file<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
contents: Vec<u8>,
|
||||
options: WriteFileOptions,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()>;
|
||||
|
||||
fn create_directory<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
create_directory_options: CreateDirectoryOptions,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()>;
|
||||
|
||||
fn get_metadata<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: GetMetadataOptions,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, FileMetadata>;
|
||||
|
||||
fn read_directory<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, Vec<ReadDirectoryEntry>>;
|
||||
|
||||
/// Recursively lists descendants, optionally following directory symlinks.
|
||||
fn walk<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: WalkOptions,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, WalkOutcome>;
|
||||
|
||||
fn remove<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
remove_options: RemoveOptions,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()>;
|
||||
|
||||
fn copy<'a>(
|
||||
&'a self,
|
||||
source_path: &'a PathUri,
|
||||
destination_path: &'a PathUri,
|
||||
copy_options: CopyOptions,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()>;
|
||||
}
|
||||
89
akode-rs/file-system/src/local_logs.rs
Normal file
89
akode-rs/file-system/src/local_logs.rs
Normal file
@@ -0,0 +1,89 @@
|
||||
//! Defers diagnostic directory creation and the Unix cleanup lock until initialization.
|
||||
//! The caller selects the path. This module does not search for storage.
|
||||
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::OnceCell;
|
||||
|
||||
/// A diagnostic directory whose clones share deferred setup and a Unix cleanup lock.
|
||||
#[derive(Clone, Debug)]
|
||||
#[must_use = "keep the guard until all log connections close"]
|
||||
pub struct LocalLogsDir {
|
||||
path: PathBuf,
|
||||
initialized: Arc<OnceCell<LocalLogsDirLock>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct LocalLogsDirLock {
|
||||
#[cfg(unix)]
|
||||
_cleanup_lock: std::fs::File,
|
||||
}
|
||||
|
||||
impl LocalLogsDir {
|
||||
/// Select a directory without accessing the filesystem.
|
||||
pub fn new(path: PathBuf) -> Self {
|
||||
Self {
|
||||
path,
|
||||
initialized: Arc::new(OnceCell::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create the directory and acquire its cleanup lock once. Failed attempts remain retryable.
|
||||
/// Keep a clone alive until all log connections close.
|
||||
/// On Unix, newly created directories start with mode 0700. Existing permissions
|
||||
/// are preserved, including on user-created directories or after the user changes
|
||||
/// the mode. We do not enforce or restore private permissions on later calls.
|
||||
pub async fn initialize(&self) -> io::Result<()> {
|
||||
let _ = self
|
||||
.initialized
|
||||
.get_or_try_init(|| async {
|
||||
let path = self.path.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut builder = std::fs::DirBuilder::new();
|
||||
builder.recursive(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt;
|
||||
|
||||
// Set private permissions only at creation; preserve existing permissions.
|
||||
builder.mode(0o700);
|
||||
}
|
||||
builder.create(&path)?;
|
||||
// Protect temporary log directories from cleanup while connections use them.
|
||||
#[cfg(unix)]
|
||||
let directory = {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
|
||||
let directory = std::fs::File::open(&path)?;
|
||||
directory.try_lock_shared()?;
|
||||
let locked = directory.metadata()?;
|
||||
let current = std::fs::metadata(&path)?;
|
||||
if !locked.is_dir()
|
||||
|| (current.dev(), current.ino()) != (locked.dev(), locked.ino())
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
"log directory changed during initialization",
|
||||
));
|
||||
}
|
||||
directory
|
||||
};
|
||||
|
||||
Ok::<_, io::Error>(LocalLogsDirLock {
|
||||
#[cfg(unix)]
|
||||
_cleanup_lock: directory,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(io::Error::other)?
|
||||
})
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
16
akode-rs/file-system/src/nfs.rs
Normal file
16
akode-rs/file-system/src/nfs.rs
Normal file
@@ -0,0 +1,16 @@
|
||||
//! Detects NFS on Linux; other platforms retain their existing filesystem behavior.
|
||||
//! Closing an extra file descriptor could release process-wide POSIX locks on its inode.
|
||||
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
/// On linux we sometimes do a special treatment for NFS related path. We don't support windows NFS
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn is_nfs(path: &Path) -> io::Result<bool> {
|
||||
Ok(rustix::fs::statfs(path)?.f_type == rustix::fs::NFS_SUPER_MAGIC)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub fn is_nfs(_path: &Path) -> io::Result<bool> {
|
||||
Ok(false)
|
||||
}
|
||||
Reference in New Issue
Block a user