Skip to main content

ssh_browser/fs/
mod.rs

1//! Filesystem access shaped so that latency optimisation survives a backend swap.
2//!
3//! The operations are batch-first on purpose. A per-path interface — `stat(p)`,
4//! `read(p)` — forces O(N) round trips no matter which backend implements it, so
5//! the abstraction would defeat the invariant it sits beneath. A single read is
6//! the n=1 case of `read_batch`, not the other way round.
7
8use anyhow::{Result, anyhow};
9
10use crate::sftp::wire::{Attrs, STATUS_NO_SUCH_FILE};
11
12pub mod sftp;
13
14/// A refusal from the remote, carrying the reason it gave.
15///
16/// The reason has to survive the trip. Without it every failed listing looks alike, and a
17/// caller that wants to treat "there is no such directory" as an ordinary empty answer ends
18/// up treating a dead session and a permission problem that way too — which is how a
19/// document's annotations come to read as "nobody has annotated this".
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub struct Refused {
22    pub status: u32,
23}
24
25impl std::fmt::Display for Refused {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        let name = match self.status {
28            1 => "end of file",
29            2 => "no such file",
30            3 => "permission denied",
31            4 => "failure",
32            5 => "bad message",
33            6 => "no connection",
34            7 => "connection lost",
35            8 => "operation unsupported",
36            _ => "unrecognised status",
37        };
38        write!(f, "the remote refused: {name} ({})", self.status)
39    }
40}
41
42impl std::error::Error for Refused {}
43
44/// Did this failure mean "there is nothing there", as opposed to anything else at all?
45///
46/// Anything that cannot be established as absence is not treated as absence. Guessing the
47/// other way turns every transport problem into an empty answer, which is the failure this
48/// project has already shipped once.
49pub fn is_absent(e: &anyhow::Error) -> bool {
50    e.chain()
51        .filter_map(|c| c.downcast_ref::<Refused>())
52        .any(|r| r.status == STATUS_NO_SUCH_FILE)
53}
54
55#[derive(Debug, Clone)]
56pub struct Entry {
57    pub name: String,
58    pub attrs: Attrs,
59    /// The owner's account name, when the listing reported one legibly.
60    ///
61    /// `None` means the remote did not say, or said it in a shape not worth guessing at —
62    /// not that the file is unowned. Callers have to keep those two apart, because the one
63    /// thing this feeds is the check on who wrote an annotation log.
64    pub owner: Option<String>,
65}
66
67/// One byte range of one file.
68#[derive(Debug, Clone)]
69pub struct RangeReq {
70    pub path: String,
71    pub offset: u64,
72    /// Bytes wanted. Fewer may come back at end of file, which is not an error.
73    pub len: u64,
74}
75
76#[allow(async_fn_in_trait)]
77pub trait RemoteFs {
78    /// Read whole files. Implementations must issue every request before awaiting
79    /// any reply; doing otherwise silently reintroduces O(N) round trips.
80    async fn read_batch(&self, paths: &[String]) -> Vec<Result<Vec<u8>>>;
81
82    /// Read byte ranges. Chunking is the implementation's business; what matters
83    /// here is that the whole set is issued together, so a one-megabyte range costs
84    /// one round trip rather than the thirty-two its chunks would suggest.
85    async fn read_ranges(&self, reqs: &[RangeReq]) -> Vec<Result<Vec<u8>>>;
86
87    /// List several directories at once. One listing carries every entry's attrs,
88    /// which is what removes per-file stat from the page path; batching the
89    /// listings is what holds a symlink check over a deep path at one round trip
90    /// rather than one per path component.
91    async fn list_dirs(&self, paths: &[String]) -> Vec<Result<Vec<Entry>>>;
92
93    /// The n=1 case, defined in terms of the batch so that no implementation can
94    /// quietly make the single listing the cheap path and the batch a loop.
95    async fn list_dir(&self, path: &str) -> Result<Vec<Entry>> {
96        let one = [path.to_string()];
97        self.list_dirs(&one)
98            .await
99            .into_iter()
100            .next()
101            .unwrap_or_else(|| Err(anyhow!("list_dirs returned no result for {path}")))
102    }
103
104    /// The absolute path a fresh session starts in — the account's home directory.
105    ///
106    /// The one question about the remote that cannot be answered from a path, and the
107    /// reason an alias can be written without a base at all. `~` is shell syntax and
108    /// the transport never runs a shell, so expanding it locally would produce this
109    /// machine's home rather than the remote one.
110    ///
111    /// Asked once per alias at startup, never on a page path, so it costs no round trip
112    /// that a reader waits for.
113    async fn home(&self) -> Result<String>;
114
115    /// Append bytes to a file, creating it if absent.
116    ///
117    /// Append rather than write, and single rather than batched, because that is the
118    /// only write this design needs and the only one that is safe without a lock. A log
119    /// has exactly one writer by construction, so an append cannot interleave with
120    /// anyone else's — which is precisely why the annotation format is per-author logs
121    /// and not one shared file.
122    async fn append(&self, path: &str, bytes: &[u8]) -> Result<()>;
123
124    /// Create a directory and every missing parent.
125    ///
126    /// Every level is issued at once and per-level failures are ignored: a level that
127    /// already exists reports one, and the only outcome that matters is whether the
128    /// deepest level is there afterwards. Walking down a level per round trip would
129    /// cost depth round trips for something that happens once per document.
130    async fn mkdirs(&self, path: &str) -> Result<()>;
131
132    /// Flushes issued so far. One flush is one remote round trip, so this is the
133    /// invariant made observable, and assertable in tests.
134    fn round_trips(&self) -> u64;
135}