-
Notifications
You must be signed in to change notification settings - Fork 9
/
local.rs
371 lines (331 loc) · 10.4 KB
/
local.rs
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
//! Module providing an implementation for the [StorageTrait] trait using the local file system.
//!
use std::fmt::Debug;
use std::io::{ErrorKind, SeekFrom};
use std::path::{Path, PathBuf};
use crate::{HeadOptions, StorageMiddleware, StorageTrait, UrlFormatter};
use crate::{Streamable, Url as HtsGetUrl};
use async_trait::async_trait;
use tokio::fs;
use tokio::fs::File;
use tokio::io::AsyncSeekExt;
use tracing::debug;
use tracing::instrument;
use url::Url;
use super::{GetOptions, RangeUrlOptions, Result, StorageError};
/// Implementation for the [StorageTrait] trait using the local file system. [T] is the type of the
/// server struct, which is used for formatting urls.
#[derive(Debug, Clone)]
pub struct FileStorage<T> {
base_path: PathBuf,
url_formatter: T,
}
impl<T: UrlFormatter + Send + Sync> FileStorage<T> {
pub fn new<P: AsRef<Path>>(base_path: P, url_formatter: T) -> Result<Self> {
base_path
.as_ref()
.to_path_buf()
.canonicalize()
.map_err(|_| StorageError::KeyNotFound(base_path.as_ref().to_string_lossy().to_string()))
.map(|canonicalized_base_path| Self {
base_path: canonicalized_base_path,
url_formatter,
})
}
pub fn base_path(&self) -> &Path {
self.base_path.as_path()
}
pub(crate) fn get_path_from_key<K: AsRef<str>>(&self, key: K) -> Result<PathBuf> {
let key: &str = key.as_ref();
self
.base_path
.join(key)
.canonicalize()
.map_err(|err| {
if let ErrorKind::NotFound = err.kind() {
StorageError::KeyNotFound(key.to_string())
} else {
StorageError::InvalidKey(key.to_string())
}
})
.and_then(|path| {
path
.starts_with(&self.base_path)
.then_some(path)
.ok_or_else(|| StorageError::InvalidKey(key.to_string()))
})
.and_then(|path| {
path
.is_file()
.then_some(path)
.ok_or_else(|| StorageError::KeyNotFound(key.to_string()))
})
}
pub async fn get<K: AsRef<str>>(&self, key: K) -> Result<File> {
let path = self.get_path_from_key(&key)?;
File::open(path)
.await
.map_err(|_| StorageError::KeyNotFound(key.as_ref().to_string()))
}
}
#[async_trait]
impl<T: UrlFormatter + Send + Sync + Debug> StorageMiddleware for FileStorage<T> {}
#[async_trait]
impl<T: UrlFormatter + Send + Sync + Debug + Clone + 'static> StorageTrait for FileStorage<T> {
/// Get the file at the location of the key.
#[instrument(level = "debug", skip(self))]
async fn get(&self, key: &str, options: GetOptions<'_>) -> Result<Streamable> {
debug!(calling_from = ?self, key = key, "getting file with key {:?}", key);
// Need to ensure range options are considered for local files.
let mut file = self.get(key).await?;
file
.seek(SeekFrom::Start(options.range.start.unwrap_or(0)))
.await?;
Ok(Streamable::from_async_read(file))
}
/// Get a url for the file at key.
#[instrument(level = "debug", skip(self))]
async fn range_url(&self, key: &str, options: RangeUrlOptions<'_>) -> Result<HtsGetUrl> {
let path = self.get_path_from_key(key)?;
let base_url = Url::from_file_path(&self.base_path)
.map_err(|_| StorageError::UrlParseError("failed to parse base path as url".to_string()))?;
let path_url = Url::from_file_path(path)
.map_err(|_| StorageError::UrlParseError("failed to parse key path as url".to_string()))?;
// Get the difference between the two URLs and strip and leading slashes.
let path = path_url
.path()
.strip_prefix(base_url.path())
.ok_or_else(|| {
StorageError::UrlParseError("failed parse relative component of key path url".to_string())
})?;
let path = path.trim_start_matches('/');
let url = HtsGetUrl::new(self.url_formatter.format_url(path)?);
let url = options.apply(url);
debug!(calling_from = ?self, key = key, ?url, "getting url with key {:?}", key);
Ok(url)
}
/// Get the size of the file.
#[instrument(level = "debug", skip(self))]
async fn head(&self, key: &str, _options: HeadOptions<'_>) -> Result<u64> {
let path = self.get_path_from_key(key)?;
let len = fs::metadata(path)
.await
.map_err(|err| StorageError::KeyNotFound(err.to_string()))?
.len();
debug!(calling_from = ?self, key = key, len, "size of key {:?} is {}", key, len);
Ok(len)
}
}
#[cfg(test)]
pub(crate) mod tests {
use std::future::Future;
use std::matches;
use htsget_config::storage;
use htsget_config::types::Scheme;
use http::uri::Authority;
use tempfile::TempDir;
use tokio::fs::{create_dir, File};
use tokio::io::AsyncWriteExt;
use super::*;
use crate::types::BytesPosition;
use crate::{GetOptions, RangeUrlOptions, StorageError};
use crate::{Headers, Url};
#[tokio::test]
async fn get_non_existing_key() {
with_local_storage(|storage, _| async move {
let result = storage.get("non-existing-key").await;
assert!(matches!(result, Err(StorageError::KeyNotFound(msg)) if msg == "non-existing-key"));
})
.await;
}
#[tokio::test]
async fn get_folder() {
with_local_storage(|storage, _| async move {
let result = StorageTrait::get(
&storage,
"folder",
GetOptions::new_with_default_range(&Default::default()),
)
.await;
assert!(matches!(result, Err(StorageError::KeyNotFound(msg)) if msg == "folder"));
})
.await;
}
#[tokio::test]
async fn get_forbidden_path() {
with_local_storage(|storage, _| async move {
let result = StorageTrait::get(
&storage,
"folder/../../passwords",
GetOptions::new_with_default_range(&Default::default()),
)
.await;
assert!(
matches!(result, Err(StorageError::KeyNotFound(msg)) if msg == "folder/../../passwords")
);
})
.await;
}
#[tokio::test]
async fn get_existing_key() {
with_local_storage(|storage, _| async move {
let result = StorageTrait::get(
&storage,
"folder/../key1",
GetOptions::new_with_default_range(&Default::default()),
)
.await;
assert!(result.is_ok());
})
.await;
}
#[tokio::test]
async fn url_of_non_existing_key() {
with_local_storage(|storage, _| async move {
let result = StorageTrait::range_url(
&storage,
"non-existing-key",
RangeUrlOptions::new_with_default_range(&Default::default()),
)
.await;
assert!(matches!(result, Err(StorageError::KeyNotFound(msg)) if msg == "non-existing-key"));
})
.await;
}
#[tokio::test]
async fn url_of_folder() {
with_local_storage(|storage, _| async move {
let result = StorageTrait::range_url(
&storage,
"folder",
RangeUrlOptions::new_with_default_range(&Default::default()),
)
.await;
assert!(matches!(result, Err(StorageError::KeyNotFound(msg)) if msg == "folder"));
})
.await;
}
#[tokio::test]
async fn url_with_forbidden_path() {
with_local_storage(|storage, _| async move {
let result = StorageTrait::range_url(
&storage,
"folder/../../passwords",
RangeUrlOptions::new_with_default_range(&Default::default()),
)
.await;
assert!(
matches!(result, Err(StorageError::KeyNotFound(msg)) if msg == "folder/../../passwords")
);
})
.await;
}
#[tokio::test]
async fn url_of_existing_key() {
with_local_storage(|storage, _| async move {
let result = StorageTrait::range_url(
&storage,
"folder/../key1",
RangeUrlOptions::new_with_default_range(&Default::default()),
)
.await;
let expected = Url::new("http://127.0.0.1:8081/key1");
assert!(matches!(result, Ok(url) if url == expected));
})
.await;
}
#[tokio::test]
async fn url_of_existing_key_with_specified_range() {
with_local_storage(|storage, _| async move {
let result = StorageTrait::range_url(
&storage,
"folder/../key1",
RangeUrlOptions::new(
BytesPosition::new(Some(7), Some(10), None),
&Default::default(),
),
)
.await;
let expected = Url::new("http://127.0.0.1:8081/key1")
.with_headers(Headers::default().with_header("Range", "bytes=7-9"));
assert!(matches!(result, Ok(url) if url == expected));
})
.await;
}
#[tokio::test]
async fn url_of_existing_key_with_specified_open_ended_range() {
with_local_storage(|storage, _| async move {
let result = StorageTrait::range_url(
&storage,
"folder/../key1",
RangeUrlOptions::new(BytesPosition::new(Some(7), None, None), &Default::default()),
)
.await;
let expected = Url::new("http://127.0.0.1:8081/key1")
.with_headers(Headers::default().with_header("Range", "bytes=7-"));
assert!(matches!(result, Ok(url) if url == expected));
})
.await;
}
#[tokio::test]
async fn file_size() {
with_local_storage(|storage, _| async move {
let result = StorageTrait::head(
&storage,
"folder/../key1",
HeadOptions::new(&Default::default()),
)
.await;
let expected: u64 = 6;
assert!(matches!(result, Ok(size) if size == expected));
})
.await;
}
pub(crate) async fn create_local_test_files() -> (String, TempDir) {
let base_path = TempDir::new().unwrap();
let folder_name = "folder";
let key1 = "key1";
let value1 = b"value1";
let key2 = "key2";
let value2 = b"value2";
File::create(base_path.path().join(key1))
.await
.unwrap()
.write_all(value1)
.await
.unwrap();
create_dir(base_path.path().join(folder_name))
.await
.unwrap();
File::create(base_path.path().join(folder_name).join(key2))
.await
.unwrap()
.write_all(value2)
.await
.unwrap();
(folder_name.to_string(), base_path)
}
pub(crate) fn test_local_storage(base_path: &Path) -> FileStorage<storage::file::File> {
FileStorage::new(
base_path,
storage::file::File::new(
Scheme::Http,
Authority::from_static("127.0.0.1:8081"),
"data".to_string(),
),
)
.unwrap()
}
pub(crate) async fn with_local_storage<F, Fut>(test: F)
where
F: FnOnce(FileStorage<storage::file::File>, PathBuf) -> Fut,
Fut: Future<Output = ()>,
{
let (_, base_path) = create_local_test_files().await;
test(
test_local_storage(base_path.path()),
base_path.path().to_path_buf(),
)
.await
}
}