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
use std::{
collections::HashMap,
fs::OpenOptions,
future::Future,
io::{Cursor, Error, ErrorKind},
path::{Component, Path, PathBuf},
pin::Pin,
task::{Context, Poll},
time::SystemTime,
};
use futures_util::future::{ready, Ready};
use hyper::body::Bytes;
use tokio::{
fs::{self, File},
task::{spawn_blocking, JoinHandle},
};
#[cfg(windows)]
use std::os::windows::fs::OpenOptionsExt;
#[cfg(windows)]
use winapi::um::winbase::FILE_FLAG_BACKUP_SEMANTICS;
#[derive(Debug)]
pub struct FileWithMetadata<F = File> {
pub handle: F,
pub size: u64,
pub modified: Option<SystemTime>,
pub is_dir: bool,
}
pub trait FileOpener {
type File;
type Future: Future<Output = Result<FileWithMetadata<Self::File>, Error>>;
fn open(&self, path: &Path) -> Self::Future;
}
pub struct TokioFileOpener {
pub root: PathBuf,
}
impl TokioFileOpener {
pub fn new(root: impl Into<PathBuf>) -> Self {
Self { root: root.into() }
}
}
impl FileOpener for TokioFileOpener {
type File = File;
type Future = TokioFileFuture;
fn open(&self, path: &Path) -> Self::Future {
let mut full_path = self.root.clone();
full_path.extend(path);
let inner = spawn_blocking(move || {
let mut opts = OpenOptions::new();
opts.read(true);
#[cfg(windows)]
opts.custom_flags(FILE_FLAG_BACKUP_SEMANTICS);
let handle = opts.open(full_path)?;
let metadata = handle.metadata()?;
Ok(FileWithMetadata {
handle: File::from_std(handle),
size: metadata.len(),
modified: metadata.modified().ok(),
is_dir: metadata.is_dir(),
})
});
TokioFileFuture { inner }
}
}
pub struct TokioFileFuture {
inner: JoinHandle<Result<FileWithMetadata<File>, Error>>,
}
impl Future for TokioFileFuture {
type Output = Result<FileWithMetadata<File>, Error>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match Pin::new(&mut self.inner).poll(cx) {
Poll::Ready(Ok(res)) => Poll::Ready(res),
Poll::Ready(Err(_)) => {
Poll::Ready(Err(Error::new(ErrorKind::Other, "background task failed")))
}
Poll::Pending => Poll::Pending,
}
}
}
type MemoryFileMap = HashMap<PathBuf, FileWithMetadata<Bytes>>;
#[derive(Default)]
pub struct MemoryFs {
files: MemoryFileMap,
}
impl MemoryFs {
pub async fn from_dir(path: impl AsRef<Path>) -> Result<Self, Error> {
let mut fs = Self::default();
let mut dirs = vec![(path.as_ref().to_path_buf(), PathBuf::new())];
while let Some((dir, base)) = dirs.pop() {
let mut iter = fs::read_dir(dir).await?;
while let Some(entry) = iter.next_entry().await? {
let metadata = entry.metadata().await?;
let mut out_path = base.to_path_buf();
out_path.push(entry.file_name());
if metadata.is_dir() {
dirs.push((entry.path(), out_path));
} else if metadata.is_file() {
let data = fs::read(entry.path()).await?;
fs.add(out_path, data.into(), metadata.modified().ok());
}
}
}
Ok(fs)
}
pub fn add(
&mut self,
path: impl Into<PathBuf>,
data: Bytes,
modified: Option<SystemTime>,
) -> &mut Self {
let path = path.into();
let mut components: Vec<_> = path.components().collect();
components.pop();
let mut dir_path = PathBuf::new();
for component in components {
if let Component::Normal(x) = component {
dir_path.push(x);
self.files.insert(
dir_path.clone(),
FileWithMetadata {
handle: Bytes::new(),
size: 0,
modified: None,
is_dir: true,
},
);
}
}
let size = data.len() as u64;
self.files.insert(
path,
FileWithMetadata {
handle: data,
size,
modified,
is_dir: false,
},
);
self
}
}
impl FileOpener for MemoryFs {
type File = Cursor<Bytes>;
type Future = Ready<Result<FileWithMetadata<Self::File>, Error>>;
fn open(&self, path: &Path) -> Self::Future {
ready(
self.files
.get(path)
.map(|file| FileWithMetadata {
handle: Cursor::new(file.handle.clone()),
size: file.size,
modified: file.modified,
is_dir: file.is_dir,
})
.ok_or_else(|| Error::new(ErrorKind::NotFound, "Not found")),
)
}
}