1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
//! Filesystem boundary used by app orchestration workflows.
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
/// Boxed async result used by [`FsClient`] trait methods.
pub type FsFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
/// Typed error returned by filesystem infrastructure operations.
///
/// Wraps I/O failures so callers can distinguish filesystem errors without
/// parsing opaque strings.
#[derive(Debug, thiserror::Error)]
pub enum FsError {
/// A filesystem or file I/O operation failed.
#[error("{0}")]
Io(#[from] std::io::Error),
}
/// Async filesystem boundary used by app-layer workflows.
///
/// Production uses [`RealFsClient`], while tests can inject
/// `MockFsClient` to avoid mutating the real filesystem.
#[cfg_attr(test, mockall::automock)]
pub trait FsClient: Send + Sync {
/// Recursively creates `path` and its missing parents.
///
/// # Errors
/// Returns an error when filesystem creation fails.
fn create_dir_all(&self, path: PathBuf) -> FsFuture<Result<(), FsError>>;
/// Recursively removes `path` and its contents.
///
/// # Errors
/// Returns an error when filesystem removal fails.
fn remove_dir_all(&self, path: PathBuf) -> FsFuture<Result<(), FsError>>;
/// Removes one empty directory at `path`.
///
/// Fails with [`std::io::ErrorKind::DirectoryNotEmpty`] when the directory
/// still contains entries, allowing callers to safely prune shared
/// directories only when no sibling files remain.
///
/// # Errors
/// Returns an error when filesystem removal fails for any reason,
/// including the directory still being non-empty.
fn remove_dir(&self, path: PathBuf) -> FsFuture<Result<(), FsError>>;
/// Reads one file into bytes without blocking the async runtime.
///
/// # Errors
/// Returns an error when file read fails.
fn read_file(&self, path: PathBuf) -> FsFuture<Result<Vec<u8>, FsError>>;
/// Writes one byte buffer to `path`, replacing any existing file.
///
/// # Errors
/// Returns an error when file creation or write fails.
fn write_file(&self, path: PathBuf, contents: Vec<u8>) -> FsFuture<Result<(), FsError>>;
/// Removes one file from disk.
///
/// Missing files are treated as a successful no-op.
///
/// # Errors
/// Returns an error when filesystem removal fails for any reason other
/// than the file already being absent.
fn remove_file(&self, path: PathBuf) -> FsFuture<Result<(), FsError>>;
/// Resolves `path` to its canonical absolute filesystem location.
///
/// # Errors
/// Returns an error when path resolution fails.
fn canonicalize(&self, path: PathBuf) -> FsFuture<Result<PathBuf, FsError>>;
/// Returns whether `path` currently resolves to an existing filesystem
/// entry of any kind.
fn exists(&self, path: PathBuf) -> bool;
/// Returns whether `path` currently resolves to an existing directory.
fn is_dir(&self, path: PathBuf) -> bool;
/// Returns whether `path` currently resolves to an existing regular file.
fn is_file(&self, path: PathBuf) -> bool;
}
/// Production [`FsClient`] implementation backed by real filesystem calls.
pub struct RealFsClient;
impl FsClient for RealFsClient {
fn create_dir_all(&self, path: PathBuf) -> FsFuture<Result<(), FsError>> {
Box::pin(async move { tokio::fs::create_dir_all(path).await.map_err(FsError::from) })
}
fn remove_dir_all(&self, path: PathBuf) -> FsFuture<Result<(), FsError>> {
Box::pin(async move { tokio::fs::remove_dir_all(path).await.map_err(FsError::from) })
}
fn remove_dir(&self, path: PathBuf) -> FsFuture<Result<(), FsError>> {
Box::pin(async move { tokio::fs::remove_dir(path).await.map_err(FsError::from) })
}
fn read_file(&self, path: PathBuf) -> FsFuture<Result<Vec<u8>, FsError>> {
Box::pin(async move { tokio::fs::read(path).await.map_err(FsError::from) })
}
fn write_file(&self, path: PathBuf, contents: Vec<u8>) -> FsFuture<Result<(), FsError>> {
Box::pin(async move {
tokio::fs::write(path, contents)
.await
.map_err(FsError::from)
})
}
fn remove_file(&self, path: PathBuf) -> FsFuture<Result<(), FsError>> {
Box::pin(async move {
match tokio::fs::remove_file(path).await {
Ok(()) => Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(FsError::from(error)),
}
})
}
fn canonicalize(&self, path: PathBuf) -> FsFuture<Result<PathBuf, FsError>> {
Box::pin(async move { tokio::fs::canonicalize(path).await.map_err(FsError::from) })
}
fn exists(&self, path: PathBuf) -> bool {
path.exists()
}
fn is_dir(&self, path: PathBuf) -> bool {
path.is_dir()
}
fn is_file(&self, path: PathBuf) -> bool {
path.is_file()
}
}
#[cfg(test)]
mod tests {
use tempfile::tempdir;
use super::*;
/// Verifies `RealFsClient::read_file()` reads bytes through the async
/// filesystem adapter.
#[tokio::test]
async fn test_real_fs_client_read_file_reads_existing_file() {
// Arrange
let temp_dir = tempdir().expect("create temp dir");
let file_path = temp_dir.path().join("example.txt");
tokio::fs::write(&file_path, b"hello world")
.await
.expect("write file");
let fs_client = RealFsClient;
// Act
let content = fs_client
.read_file(file_path)
.await
.expect("read existing file");
// Assert
assert_eq!(content, b"hello world");
}
/// Verifies `RealFsClient::read_file()` surfaces read failures through the
/// async boundary.
#[tokio::test]
async fn test_real_fs_client_read_file_returns_error_for_missing_file() {
// Arrange
let temp_dir = tempdir().expect("create temp dir");
let file_path = temp_dir.path().join("missing.txt");
let fs_client = RealFsClient;
// Act
let error = fs_client
.read_file(file_path)
.await
.expect_err("missing file should error");
// Assert
let message = error.to_string();
assert!(message.contains("No such file") || message.contains("cannot find the path"));
}
/// Verifies `RealFsClient::is_file()` distinguishes files from
/// directories.
#[tokio::test]
async fn test_real_fs_client_is_file_returns_true_only_for_regular_files() {
// Arrange
let temp_dir = tempdir().expect("create temp dir");
let file_path = temp_dir.path().join("example.txt");
tokio::fs::write(&file_path, b"hello world")
.await
.expect("write file");
let fs_client = RealFsClient;
// Act
let file_exists = fs_client.is_file(file_path);
let directory_exists = fs_client.is_file(temp_dir.path().to_path_buf());
// Assert
assert!(file_exists);
assert!(!directory_exists);
}
/// Verifies `RealFsClient::canonicalize()` resolves files to absolute
/// paths through the async filesystem boundary.
#[tokio::test]
async fn test_real_fs_client_canonicalize_returns_absolute_file_path() {
// Arrange
let temp_dir = tempdir().expect("create temp dir");
let file_path = temp_dir.path().join("example.txt");
tokio::fs::write(&file_path, b"hello world")
.await
.expect("write file");
let fs_client = RealFsClient;
// Act
let canonicalized_path = fs_client
.canonicalize(file_path.clone())
.await
.expect("canonicalize file");
// Assert
assert_eq!(
canonicalized_path,
std::fs::canonicalize(file_path).expect("std canonicalize should succeed")
);
}
/// Verifies `RealFsClient::exists()` reports any existing filesystem
/// entry, including directories.
#[tokio::test]
async fn test_real_fs_client_exists_returns_true_for_directories() {
// Arrange
let temp_dir = tempdir().expect("create temp dir");
let fs_client = RealFsClient;
// Act
let directory_exists = fs_client.exists(temp_dir.path().to_path_buf());
let missing_path_exists = fs_client.exists(temp_dir.path().join("missing"));
// Assert
assert!(directory_exists);
assert!(!missing_path_exists);
}
}