Skip to main content

base/interface/exec/
filesystem.rs

1//! `FileSystem` — reading and writing wherever the tools' files live.
2
3use std::path::{Path, PathBuf};
4
5use super::ExecError;
6
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct Metadata {
9    pub is_dir: bool,
10    pub is_file: bool,
11    pub is_symlink: bool,
12    pub len: u64,
13}
14
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct DirEntry {
17    pub path: PathBuf,
18    pub is_dir: bool,
19}
20
21/// Where a tool's files are.
22///
23/// Whole-value rather than streaming, which is the opposite of [`Process`] and
24/// deliberately so: every call site in the engine reads or writes a whole
25/// file, and a tool result is capped long before a file could be large enough
26/// to need chunking. Designing a streaming interface with no consumer would
27/// oblige every implementation to provide one.
28///
29/// **Path safety is not here.** Whether a path may be written is a policy —
30/// it answers the same question regardless of which machine the file is on,
31/// and a provider that decided its own out-of-bounds rules could cancel them.
32/// It stays in `permissions::path_safety`, above this contract.
33///
34/// One thing does cross: [`canonicalize`](Self::canonicalize). A remote's
35/// symlink graph is the remote's, so resolving one here would answer about the
36/// wrong filesystem. The order is: canonicalize through the provider, check
37/// the resolved path against the policy, then write through the provider.
38///
39/// [`Process`]: super::Process
40#[async_trait::async_trait]
41pub trait FileSystem: Send + Sync {
42    async fn read(&self, path: &Path) -> Result<Vec<u8>, ExecError>;
43    async fn write(&self, path: &Path, bytes: &[u8]) -> Result<(), ExecError>;
44    async fn create_dir_all(&self, path: &Path) -> Result<(), ExecError>;
45    async fn read_dir(&self, path: &Path) -> Result<Vec<DirEntry>, ExecError>;
46    async fn remove_dir_all(&self, path: &Path) -> Result<(), ExecError>;
47    async fn metadata(&self, path: &Path) -> Result<Metadata, ExecError>;
48    async fn canonicalize(&self, path: &Path) -> Result<PathBuf, ExecError>;
49
50    /// Move `from` to `to` on this filesystem. Provided, for a provider
51    /// that cannot: it fails and moves nothing.
52    async fn rename(&self, from: &Path, _to: &Path) -> Result<(), ExecError> {
53        Err(ExecError::failed(format!(
54            "{}: this filesystem does not rename",
55            from.display()
56        )))
57    }
58
59    /// Remove the file at `path` — a symlink itself, never what it points
60    /// at. Provided, for a provider that cannot: it fails and removes nothing.
61    async fn remove_file(&self, path: &Path) -> Result<(), ExecError> {
62        Err(ExecError::failed(format!(
63            "{}: this filesystem does not remove files",
64            path.display()
65        )))
66    }
67
68    /// [`write`](Self::write), refusing when `path` itself is a symlink
69    /// rather than writing where it points. Provided as a check then a write;
70    /// a provider that can do both in one step (`O_NOFOLLOW`) should.
71    async fn write_not_following(&self, path: &Path, bytes: &[u8]) -> Result<(), ExecError> {
72        if self.metadata(path).await.is_ok_and(|m| m.is_symlink) {
73            return Err(ExecError::failed(format!(
74                "{} is a symlink",
75                path.display()
76            )));
77        }
78        self.write(path, bytes).await
79    }
80
81    /// Write `bytes` to `path` — absolute, its symlinks already resolved —
82    /// following no symlink on the way: a component that is one by the time
83    /// it is reached fails the write instead of taking it elsewhere. With
84    /// `create_parents`, missing directories on the way are made.
85    ///
86    /// Provided as checks then a write; a provider that can walk the path
87    /// from directory to directory without following links should.
88    async fn write_resolved(
89        &self,
90        path: &Path,
91        bytes: &[u8],
92        create_parents: bool,
93    ) -> Result<(), ExecError> {
94        for dir in path.ancestors().skip(1) {
95            if self.metadata(dir).await.is_ok_and(|m| m.is_symlink) {
96                return Err(ExecError::failed(format!(
97                    "{}: {} is a symlink",
98                    path.display(),
99                    dir.display()
100                )));
101            }
102        }
103        if let Some(parent) = path.parent().filter(|_| create_parents) {
104            if self.metadata(parent).await.is_err() {
105                self.create_dir_all(parent).await?;
106            }
107        }
108        self.write_not_following(path, bytes).await
109    }
110
111    /// The file's sha256 as lowercase hex, hashed without holding the file.
112    /// `None` for a provider that cannot, which the caller answers by
113    /// reading — and so only for files it can afford to read.
114    async fn sha256(&self, _path: &Path) -> Result<Option<String>, ExecError> {
115        Ok(None)
116    }
117
118    /// What most callers actually want. Provided, so an implementor writes
119    /// `read` and gets this.
120    async fn read_to_string(&self, path: &Path) -> Result<String, ExecError> {
121        let bytes = self.read(path).await?;
122        String::from_utf8(bytes)
123            .map_err(|e| ExecError::failed(format!("{} is not valid UTF-8: {e}", path.display())))
124    }
125
126    /// Convenience with the same relationship to `write`.
127    async fn write_str(&self, path: &Path, text: &str) -> Result<(), ExecError> {
128        self.write(path, text.as_bytes()).await
129    }
130
131    /// Metadata of what `path` points at rather than of `path` itself.
132    ///
133    /// [`metadata`](Self::metadata) reports on the link — that is what its
134    /// `is_symlink` field is for — so a caller asking "how big is this, is it
135    /// a directory" has to resolve first or a symlink to a directory answers
136    /// as a small ordinary file.
137    async fn metadata_following_symlinks(&self, path: &Path) -> Result<Metadata, ExecError> {
138        let resolved = self.canonicalize(path).await?;
139        self.metadata(&resolved).await
140    }
141
142    /// What the symbolic link at `path` points at, as written in the link.
143    /// Provided, for a provider with no links: it fails.
144    async fn read_link(&self, path: &Path) -> Result<PathBuf, ExecError> {
145        Err(ExecError::failed(format!(
146            "{}: this filesystem has no symbolic links",
147            path.display()
148        )))
149    }
150
151    /// The resolved form of a path that may not exist yet: its deepest prefix
152    /// that exists, resolved by [`canonicalize`](Self::canonicalize), with
153    /// the rest put back on.
154    ///
155    /// A write policy has to be checked against where the write lands. The
156    /// rest does not exist, so it has no symlinks — except a link whose
157    /// target does not exist yet, which `canonicalize` cannot resolve and a
158    /// write follows; that one is followed here with
159    /// [`read_link`](Self::read_link).
160    async fn canonicalize_best_effort(&self, path: &Path) -> PathBuf {
161        use crate::path::{first_below, put_back, MAX_LINK_HOPS};
162        let mut wanted = path.to_path_buf();
163        for _ in 0..=MAX_LINK_HOPS {
164            let parts: Vec<std::path::Component> = wanted.components().collect();
165            let mut found = None;
166            for split in (1..=parts.len()).rev() {
167                let prefix: PathBuf = parts[..split].iter().collect();
168                if let Ok(out) = self.canonicalize(&prefix).await {
169                    found = Some((split, out));
170                    break;
171                }
172            }
173            let Some((split, out)) = found else {
174                return wanted;
175            };
176            let rest = &parts[split..];
177            let target = match first_below(&out, rest) {
178                Some((link, after)) => self.read_link(&link).await.ok().map(|t| (t, after)),
179                None => None,
180            };
181            match target {
182                Some((target, after)) => wanted = out.join(target).join(after),
183                None => return put_back(out, rest),
184            }
185        }
186        wanted
187    }
188}