Line data Source code
1 : //! Local filesystem acting as a remote storage.
2 : //! Multiple API users can use the same "storage" of this kind by using different storage roots.
3 : //!
4 : //! This storage used in tests, but can also be used in cases when a certain persistent
5 : //! volume is mounted to the local FS.
6 :
7 : use std::collections::HashSet;
8 : use std::io::ErrorKind;
9 : use std::num::NonZeroU32;
10 : use std::time::{Duration, SystemTime, UNIX_EPOCH};
11 :
12 : use anyhow::{Context, bail, ensure};
13 : use bytes::Bytes;
14 : use camino::{Utf8Path, Utf8PathBuf};
15 : use futures::stream::Stream;
16 : use tokio::fs;
17 : use tokio::io::{self, AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
18 : use tokio_util::io::ReaderStream;
19 : use tokio_util::sync::CancellationToken;
20 : use utils::crashsafe::path_with_suffix_extension;
21 :
22 : use super::{RemoteStorage, StorageMetadata};
23 : use crate::{
24 : Download, DownloadError, DownloadOpts, Etag, Listing, ListingMode, ListingObject,
25 : REMOTE_STORAGE_PREFIX_SEPARATOR, RemotePath, TimeTravelError, TimeoutOrCancel,
26 : };
27 :
28 : const LOCAL_FS_TEMP_FILE_SUFFIX: &str = "___temp";
29 :
30 : #[derive(Debug, Clone)]
31 : pub struct LocalFs {
32 : storage_root: Utf8PathBuf,
33 : timeout: Duration,
34 : }
35 :
36 : impl LocalFs {
37 : /// Attempts to create local FS storage, along with its root directory.
38 : /// Storage root will be created (if does not exist) and transformed into an absolute path (if passed as relative).
39 502 : pub fn new(mut storage_root: Utf8PathBuf, timeout: Duration) -> anyhow::Result<Self> {
40 502 : if !storage_root.exists() {
41 33 : std::fs::create_dir_all(&storage_root).with_context(|| {
42 0 : format!("Failed to create all directories in the given root path {storage_root:?}")
43 33 : })?;
44 469 : }
45 502 : if !storage_root.is_absolute() {
46 452 : storage_root = storage_root.canonicalize_utf8().with_context(|| {
47 0 : format!("Failed to represent path {storage_root:?} as an absolute path")
48 452 : })?;
49 50 : }
50 :
51 502 : Ok(Self {
52 502 : storage_root,
53 502 : timeout,
54 502 : })
55 502 : }
56 :
57 : // mirrors S3Bucket::s3_object_to_relative_path
58 194 : fn local_file_to_relative_path(&self, key: Utf8PathBuf) -> RemotePath {
59 194 : let relative_path = key
60 194 : .strip_prefix(&self.storage_root)
61 194 : .expect("relative path must contain storage_root as prefix");
62 194 : RemotePath(relative_path.into())
63 194 : }
64 :
65 105 : async fn read_storage_metadata(
66 105 : &self,
67 105 : file_path: &Utf8Path,
68 105 : ) -> anyhow::Result<Option<StorageMetadata>> {
69 105 : let metadata_path = storage_metadata_path(file_path);
70 105 : if metadata_path.exists() && metadata_path.is_file() {
71 6 : let metadata_string = fs::read_to_string(&metadata_path).await.with_context(|| {
72 0 : format!("Failed to read metadata from the local storage at '{metadata_path}'")
73 6 : })?;
74 :
75 6 : serde_json::from_str(&metadata_string)
76 6 : .with_context(|| {
77 0 : format!(
78 0 : "Failed to deserialize metadata from the local storage at '{metadata_path}'",
79 0 : )
80 6 : })
81 6 : .map(|metadata| Some(StorageMetadata(metadata)))
82 : } else {
83 99 : Ok(None)
84 : }
85 33 : }
86 :
87 : #[cfg(test)]
88 9 : async fn list_all(&self) -> anyhow::Result<Vec<RemotePath>> {
89 : use std::future::Future;
90 : use std::pin::Pin;
91 27 : fn get_all_files<'a, P>(
92 27 : directory_path: P,
93 27 : ) -> Pin<Box<dyn Future<Output = anyhow::Result<Vec<Utf8PathBuf>>> + Send + Sync + 'a>>
94 27 : where
95 27 : P: AsRef<Utf8Path> + Send + Sync + 'a,
96 27 : {
97 27 : Box::pin(async move {
98 27 : let directory_path = directory_path.as_ref();
99 27 : if directory_path.exists() {
100 27 : if directory_path.is_dir() {
101 27 : let mut paths = Vec::new();
102 27 : let mut dir_contents = fs::read_dir(directory_path).await?;
103 54 : while let Some(dir_entry) = dir_contents.next_entry().await? {
104 27 : let file_type = dir_entry.file_type().await?;
105 27 : let entry_path =
106 27 : Utf8PathBuf::from_path_buf(dir_entry.path()).map_err(|pb| {
107 0 : anyhow::Error::msg(format!(
108 0 : "non-Unicode path: {}",
109 0 : pb.to_string_lossy()
110 0 : ))
111 27 : })?;
112 27 : if file_type.is_symlink() {
113 0 : tracing::debug!("{entry_path:?} is a symlink, skipping")
114 27 : } else if file_type.is_dir() {
115 18 : paths.extend(get_all_files(&entry_path).await?.into_iter())
116 9 : } else {
117 9 : paths.push(entry_path);
118 9 : }
119 : }
120 27 : Ok(paths)
121 : } else {
122 0 : bail!("Path {directory_path:?} is not a directory")
123 : }
124 : } else {
125 0 : Ok(Vec::new())
126 : }
127 27 : })
128 27 : }
129 :
130 9 : Ok(get_all_files(&self.storage_root)
131 9 : .await?
132 9 : .into_iter()
133 9 : .map(|path| {
134 9 : path.strip_prefix(&self.storage_root)
135 9 : .context("Failed to strip storage root prefix")
136 9 : .and_then(RemotePath::new)
137 9 : .expect(
138 9 : "We list files for storage root, hence should be able to remote the prefix",
139 9 : )
140 9 : })
141 9 : .collect())
142 9 : }
143 :
144 : // recursively lists all files in a directory,
145 : // mirroring the `list_files` for `s3_bucket`
146 934 : async fn list_recursive(&self, folder: Option<&RemotePath>) -> anyhow::Result<Vec<RemotePath>> {
147 934 : let full_path = match folder {
148 928 : Some(folder) => folder.with_base(&self.storage_root),
149 6 : None => self.storage_root.clone(),
150 : };
151 :
152 : // If we were given a directory, we may use it as our starting point.
153 : // Otherwise, we must go up to the first ancestor dir that exists. This is because
154 : // S3 object list prefixes can be arbitrary strings, but when reading
155 : // the local filesystem we need a directory to start calling read_dir on.
156 934 : let mut initial_dir = full_path.clone();
157 934 :
158 934 : // If there's no trailing slash, we have to start looking from one above: even if
159 934 : // `initial_dir` is a directory, we should still list any prefixes in the parent
160 934 : // that start with the same string.
161 934 : if !full_path.to_string().ends_with('/') {
162 479 : initial_dir.pop();
163 479 : }
164 :
165 : loop {
166 : // Did we make it to the root?
167 3154 : if initial_dir.parent().is_none() {
168 0 : anyhow::bail!("list_files: failed to find valid ancestor dir for {full_path}");
169 3154 : }
170 3154 :
171 3154 : match fs::metadata(initial_dir.clone()).await {
172 934 : Ok(meta) if meta.is_dir() => {
173 934 : // We found a directory, break
174 934 : break;
175 : }
176 0 : Ok(_meta) => {
177 0 : // It's not a directory: strip back to the parent
178 0 : initial_dir.pop();
179 0 : }
180 2220 : Err(e) if e.kind() == ErrorKind::NotFound => {
181 2220 : // It's not a file that exists: strip the prefix back to the parent directory
182 2220 : initial_dir.pop();
183 2220 : }
184 0 : Err(e) => {
185 0 : // Unexpected I/O error
186 0 : anyhow::bail!(e)
187 : }
188 : }
189 : }
190 : // Note that Utf8PathBuf starts_with only considers full path segments, but
191 : // object prefixes are arbitrary strings, so we need the strings for doing
192 : // starts_with later.
193 934 : let prefix = full_path.as_str();
194 934 :
195 934 : let mut files = vec![];
196 934 : let mut directory_queue = vec![initial_dir];
197 1931 : while let Some(cur_folder) = directory_queue.pop() {
198 997 : let mut entries = cur_folder.read_dir_utf8()?;
199 1371 : while let Some(Ok(entry)) = entries.next() {
200 374 : let file_name = entry.file_name();
201 374 : let full_file_name = cur_folder.join(file_name);
202 374 : if full_file_name.as_str().starts_with(prefix) {
203 194 : let file_remote_path = self.local_file_to_relative_path(full_file_name.clone());
204 194 : files.push(file_remote_path);
205 194 : if full_file_name.is_dir() {
206 63 : directory_queue.push(full_file_name);
207 63 : }
208 160 : }
209 : }
210 : }
211 :
212 934 : Ok(files)
213 18 : }
214 :
215 6238 : async fn upload0(
216 6238 : &self,
217 6238 : data: impl Stream<Item = std::io::Result<Bytes>> + Send + Sync,
218 6238 : data_size_bytes: usize,
219 6238 : to: &RemotePath,
220 6238 : metadata: Option<StorageMetadata>,
221 6238 : cancel: &CancellationToken,
222 6238 : ) -> anyhow::Result<()> {
223 6238 : let target_file_path = to.with_base(&self.storage_root);
224 6238 : create_target_directory(&target_file_path).await?;
225 : // We need this dance with sort of durable rename (without fsyncs)
226 : // to prevent partial uploads. This was really hit when pageserver shutdown
227 : // cancelled the upload and partial file was left on the fs
228 : // NOTE: Because temp file suffix always the same this operation is racy.
229 : // Two concurrent operations can lead to the following sequence:
230 : // T1: write(temp)
231 : // T2: write(temp) -> overwrites the content
232 : // T1: rename(temp, dst) -> succeeds
233 : // T2: rename(temp, dst) -> fails, temp no longet exists
234 : // This can be solved by supplying unique temp suffix every time, but this situation
235 : // is not normal in the first place, the error can help (and helped at least once)
236 : // to discover bugs in upper level synchronization.
237 6232 : let temp_file_path =
238 6232 : path_with_suffix_extension(&target_file_path, LOCAL_FS_TEMP_FILE_SUFFIX);
239 6215 : let mut destination = io::BufWriter::new(
240 6232 : fs::OpenOptions::new()
241 6232 : .write(true)
242 6232 : .create(true)
243 6232 : .truncate(true)
244 6232 : .open(&temp_file_path)
245 6232 : .await
246 6215 : .with_context(|| {
247 0 : format!("Failed to open target fs destination at '{target_file_path}'")
248 6215 : })?,
249 : );
250 :
251 6215 : let from_size_bytes = data_size_bytes as u64;
252 6215 : let data = tokio_util::io::StreamReader::new(data);
253 6215 : let data = std::pin::pin!(data);
254 6215 : let mut buffer_to_read = data.take(from_size_bytes);
255 6215 :
256 6215 : // alternatively we could just write the bytes to a file, but local_fs is a testing utility
257 6215 : let copy = io::copy_buf(&mut buffer_to_read, &mut destination);
258 :
259 6215 : let bytes_read = tokio::select! {
260 : biased;
261 6215 : _ = cancel.cancelled() => {
262 3 : let file = destination.into_inner();
263 3 : // wait for the inflight operation(s) to complete so that there could be a next
264 3 : // attempt right away and our writes are not directed to their file.
265 3 : file.into_std().await;
266 :
267 : // TODO: leave the temp or not? leaving is probably less racy. enabled truncate at
268 : // least.
269 3 : fs::remove_file(temp_file_path).await.context("remove temp_file_path after cancellation or timeout")?;
270 3 : return Err(TimeoutOrCancel::Cancel.into());
271 : }
272 6215 : read = copy => read,
273 : };
274 :
275 6193 : let bytes_read =
276 6193 : bytes_read.with_context(|| {
277 0 : format!(
278 0 : "Failed to upload file (write temp) to the local storage at '{temp_file_path}'",
279 0 : )
280 6193 : })?;
281 :
282 6193 : if bytes_read < from_size_bytes {
283 3 : bail!(
284 3 : "Provided stream was shorter than expected: {bytes_read} vs {from_size_bytes} bytes"
285 3 : );
286 6190 : }
287 6190 : // Check if there is any extra data after the given size.
288 6190 : let mut from = buffer_to_read.into_inner();
289 6190 : let extra_read = from.read(&mut [1]).await?;
290 6189 : ensure!(
291 6189 : extra_read == 0,
292 6 : "Provided stream was larger than expected: expected {from_size_bytes} bytes",
293 : );
294 :
295 6183 : destination.flush().await.with_context(|| {
296 0 : format!(
297 0 : "Failed to upload (flush temp) file to the local storage at '{temp_file_path}'",
298 0 : )
299 6183 : })?;
300 :
301 6183 : fs::rename(temp_file_path, &target_file_path)
302 6183 : .await
303 6172 : .with_context(|| {
304 0 : format!(
305 0 : "Failed to upload (rename) file to the local storage at '{target_file_path}'",
306 0 : )
307 6172 : })?;
308 :
309 6172 : if let Some(storage_metadata) = metadata {
310 : // FIXME: we must not be using metadata much, since this would forget the old metadata
311 : // for new writes? or perhaps metadata is sticky; could consider removing if it's never
312 : // used.
313 3 : let storage_metadata_path = storage_metadata_path(&target_file_path);
314 3 : fs::write(
315 3 : &storage_metadata_path,
316 3 : serde_json::to_string(&storage_metadata.0)
317 3 : .context("Failed to serialize storage metadata as json")?,
318 : )
319 3 : .await
320 3 : .with_context(|| {
321 0 : format!(
322 0 : "Failed to write metadata to the local storage at '{storage_metadata_path}'",
323 0 : )
324 3 : })?;
325 45 : }
326 :
327 6172 : Ok(())
328 60 : }
329 : }
330 :
331 : impl RemoteStorage for LocalFs {
332 0 : fn list_streaming(
333 0 : &self,
334 0 : prefix: Option<&RemotePath>,
335 0 : mode: ListingMode,
336 0 : max_keys: Option<NonZeroU32>,
337 0 : cancel: &CancellationToken,
338 0 : ) -> impl Stream<Item = Result<Listing, DownloadError>> {
339 0 : let listing = self.list(prefix, mode, max_keys, cancel);
340 0 : futures::stream::once(listing)
341 0 : }
342 :
343 934 : async fn list(
344 934 : &self,
345 934 : prefix: Option<&RemotePath>,
346 934 : mode: ListingMode,
347 934 : max_keys: Option<NonZeroU32>,
348 934 : cancel: &CancellationToken,
349 934 : ) -> Result<Listing, DownloadError> {
350 934 : let op = async {
351 934 : let mut result = Listing::default();
352 :
353 : // Filter out directories: in S3 directories don't exist, only the keys within them do.
354 934 : let keys = self
355 934 : .list_recursive(prefix)
356 934 : .await
357 934 : .map_err(DownloadError::Other)?;
358 934 : let mut objects = Vec::with_capacity(keys.len());
359 1128 : for key in keys {
360 194 : let path = key.with_base(&self.storage_root);
361 194 : let metadata = file_metadata(&path).await;
362 0 : if let Err(DownloadError::NotFound) = metadata {
363 : // Race: if the file is deleted between listing and metadata check, ignore it.
364 0 : continue;
365 102 : }
366 194 : let metadata = metadata?;
367 194 : if metadata.is_dir() {
368 63 : continue;
369 131 : }
370 131 : objects.push(ListingObject {
371 131 : key: key.clone(),
372 131 : last_modified: metadata.modified()?,
373 131 : size: metadata.len(),
374 : });
375 : }
376 934 : let objects = objects;
377 934 :
378 934 : if let ListingMode::NoDelimiter = mode {
379 467 : result.keys = objects;
380 467 : } else {
381 467 : let mut prefixes = HashSet::new();
382 553 : for object in objects {
383 86 : let key = object.key;
384 : // If the part after the prefix includes a "/", take only the first part and put it in `prefixes`.
385 86 : let relative_key = if let Some(prefix) = prefix {
386 77 : let mut prefix = prefix.clone();
387 77 : // We only strip the dirname of the prefix, so that when we strip it from the start of keys we
388 77 : // end up with full file/dir names.
389 77 : let prefix_full_local_path = prefix.with_base(&self.storage_root);
390 77 : let has_slash = prefix.0.to_string().ends_with('/');
391 77 : let strip_prefix = if prefix_full_local_path.is_dir() && has_slash {
392 53 : prefix
393 : } else {
394 24 : prefix.0.pop();
395 24 : prefix
396 : };
397 :
398 77 : RemotePath::new(key.strip_prefix(&strip_prefix).unwrap()).unwrap()
399 : } else {
400 9 : key
401 : };
402 :
403 86 : let relative_key = format!("{}", relative_key);
404 86 : if relative_key.contains(REMOTE_STORAGE_PREFIX_SEPARATOR) {
405 83 : let first_part = relative_key
406 83 : .split(REMOTE_STORAGE_PREFIX_SEPARATOR)
407 83 : .next()
408 83 : .unwrap()
409 83 : .to_owned();
410 83 : prefixes.insert(first_part);
411 83 : } else {
412 3 : result.keys.push(ListingObject {
413 3 : key: RemotePath::from_string(&relative_key).unwrap(),
414 3 : last_modified: object.last_modified,
415 3 : size: object.size,
416 3 : });
417 3 : }
418 : }
419 467 : result.prefixes = prefixes
420 467 : .into_iter()
421 467 : .map(|s| RemotePath::from_string(&s).unwrap())
422 467 : .collect();
423 467 : }
424 :
425 934 : if let Some(max_keys) = max_keys {
426 0 : result.keys.truncate(max_keys.get() as usize);
427 18 : }
428 934 : Ok(result)
429 18 : };
430 :
431 934 : let timeout = async {
432 919 : tokio::time::sleep(self.timeout).await;
433 0 : Err(DownloadError::Timeout)
434 0 : };
435 :
436 934 : let cancelled = async {
437 929 : cancel.cancelled().await;
438 0 : Err(DownloadError::Cancelled)
439 0 : };
440 :
441 934 : tokio::select! {
442 934 : res = op => res,
443 934 : res = timeout => res,
444 934 : res = cancelled => res,
445 : }
446 18 : }
447 :
448 0 : async fn head_object(
449 0 : &self,
450 0 : key: &RemotePath,
451 0 : _cancel: &CancellationToken,
452 0 : ) -> Result<ListingObject, DownloadError> {
453 0 : let target_file_path = key.with_base(&self.storage_root);
454 0 : let metadata = file_metadata(&target_file_path).await?;
455 : Ok(ListingObject {
456 0 : key: key.clone(),
457 0 : last_modified: metadata.modified()?,
458 0 : size: metadata.len(),
459 : })
460 0 : }
461 :
462 6238 : async fn upload(
463 6238 : &self,
464 6238 : data: impl Stream<Item = std::io::Result<Bytes>> + Send + Sync,
465 6238 : data_size_bytes: usize,
466 6238 : to: &RemotePath,
467 6238 : metadata: Option<StorageMetadata>,
468 6238 : cancel: &CancellationToken,
469 6238 : ) -> anyhow::Result<()> {
470 6238 : let cancel = cancel.child_token();
471 6238 :
472 6238 : let op = self.upload0(data, data_size_bytes, to, metadata, &cancel);
473 6238 : let mut op = std::pin::pin!(op);
474 :
475 : // race the upload0 to the timeout; if it goes over, do a graceful shutdown
476 6238 : let (res, timeout) = tokio::select! {
477 6238 : res = &mut op => (res, false),
478 6238 : _ = tokio::time::sleep(self.timeout) => {
479 0 : cancel.cancel();
480 0 : (op.await, true)
481 : }
482 : };
483 :
484 12 : match res {
485 12 : Err(e) if timeout && TimeoutOrCancel::caused_by_cancel(&e) => {
486 0 : // we caused this cancel (or they happened simultaneously) -- swap it out to
487 0 : // Timeout
488 0 : Err(TimeoutOrCancel::Timeout.into())
489 : }
490 6184 : res => res,
491 : }
492 60 : }
493 :
494 1495 : async fn download(
495 1495 : &self,
496 1495 : from: &RemotePath,
497 1495 : opts: &DownloadOpts,
498 1495 : cancel: &CancellationToken,
499 1495 : ) -> Result<Download, DownloadError> {
500 1495 : let target_path = from.with_base(&self.storage_root);
501 :
502 1495 : let file_metadata = file_metadata(&target_path).await?;
503 108 : let etag = mock_etag(&file_metadata);
504 108 :
505 108 : if opts.etag.as_ref() == Some(&etag) {
506 0 : return Err(DownloadError::Unmodified);
507 36 : }
508 :
509 108 : let mut file = fs::OpenOptions::new()
510 108 : .read(true)
511 108 : .open(&target_path)
512 108 : .await
513 108 : .with_context(|| {
514 0 : format!("Failed to open source file {target_path:?} to use in the download")
515 108 : })
516 108 : .map_err(DownloadError::Other)?;
517 :
518 108 : let mut take = file_metadata.len();
519 108 : if let Some((start, end)) = opts.byte_range() {
520 15 : if start > 0 {
521 6 : file.seek(io::SeekFrom::Start(start))
522 6 : .await
523 6 : .context("Failed to seek to the range start in a local storage file")
524 6 : .map_err(DownloadError::Other)?;
525 9 : }
526 15 : if let Some(end) = end {
527 9 : take = end - start;
528 9 : }
529 21 : }
530 :
531 105 : let source = ReaderStream::new(file.take(take));
532 :
533 105 : let metadata = self
534 105 : .read_storage_metadata(&target_path)
535 105 : .await
536 105 : .map_err(DownloadError::Other)?;
537 :
538 105 : let cancel_or_timeout = crate::support::cancel_or_timeout(self.timeout, cancel.clone());
539 105 : let source = crate::support::DownloadStream::new(cancel_or_timeout, source);
540 105 :
541 105 : Ok(Download {
542 105 : metadata,
543 105 : last_modified: file_metadata
544 105 : .modified()
545 105 : .map_err(|e| DownloadError::Other(anyhow::anyhow!(e).context("Reading mtime")))?,
546 105 : etag,
547 105 : download_stream: Box::pin(source),
548 : })
549 36 : }
550 :
551 655 : async fn delete(&self, path: &RemotePath, _cancel: &CancellationToken) -> anyhow::Result<()> {
552 655 : let file_path = path.with_base(&self.storage_root);
553 655 : match fs::remove_file(&file_path).await {
554 641 : Ok(()) => Ok(()),
555 : // The file doesn't exist. This shouldn't yield an error to mirror S3's behaviour.
556 : // See https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObject.html
557 : // > If there isn't a null version, Amazon S3 does not remove any objects but will still respond that the command was successful.
558 3 : Err(e) if e.kind() == ErrorKind::NotFound => Ok(()),
559 0 : Err(e) => Err(anyhow::anyhow!(e)),
560 : }
561 6 : }
562 :
563 12 : async fn delete_objects(
564 12 : &self,
565 12 : paths: &[RemotePath],
566 12 : cancel: &CancellationToken,
567 12 : ) -> anyhow::Result<()> {
568 24 : for path in paths {
569 12 : self.delete(path, cancel).await?
570 : }
571 12 : Ok(())
572 0 : }
573 :
574 16 : fn max_keys_per_delete(&self) -> usize {
575 16 : super::MAX_KEYS_PER_DELETE_S3
576 16 : }
577 :
578 0 : async fn copy(
579 0 : &self,
580 0 : from: &RemotePath,
581 0 : to: &RemotePath,
582 0 : _cancel: &CancellationToken,
583 0 : ) -> anyhow::Result<()> {
584 0 : let from_path = from.with_base(&self.storage_root);
585 0 : let to_path = to.with_base(&self.storage_root);
586 0 : create_target_directory(&to_path).await?;
587 0 : fs::copy(&from_path, &to_path).await.with_context(|| {
588 0 : format!(
589 0 : "Failed to copy file from '{from_path}' to '{to_path}'",
590 0 : from_path = from_path,
591 0 : to_path = to_path
592 0 : )
593 0 : })?;
594 0 : Ok(())
595 0 : }
596 :
597 0 : async fn time_travel_recover(
598 0 : &self,
599 0 : _prefix: Option<&RemotePath>,
600 0 : _timestamp: SystemTime,
601 0 : _done_if_after: SystemTime,
602 0 : _cancel: &CancellationToken,
603 0 : ) -> Result<(), TimeTravelError> {
604 0 : Err(TimeTravelError::Unimplemented)
605 0 : }
606 : }
607 :
608 108 : fn storage_metadata_path(original_path: &Utf8Path) -> Utf8PathBuf {
609 108 : path_with_suffix_extension(original_path, "metadata")
610 108 : }
611 :
612 6238 : async fn create_target_directory(target_file_path: &Utf8Path) -> anyhow::Result<()> {
613 6238 : let target_dir = match target_file_path.parent() {
614 6238 : Some(parent_dir) => parent_dir,
615 0 : None => bail!("File path '{target_file_path}' has no parent directory"),
616 : };
617 6238 : if !target_dir.exists() {
618 882 : fs::create_dir_all(target_dir).await?;
619 54 : }
620 6232 : Ok(())
621 60 : }
622 :
623 1689 : async fn file_metadata(file_path: &Utf8Path) -> Result<std::fs::Metadata, DownloadError> {
624 1689 : tokio::fs::metadata(&file_path).await.map_err(|e| {
625 1387 : if e.kind() == ErrorKind::NotFound {
626 1387 : DownloadError::NotFound
627 : } else {
628 0 : DownloadError::BadInput(e.into())
629 : }
630 1689 : })
631 1689 : }
632 :
633 : // Use mtime as stand-in for ETag. We could calculate a meaningful one by md5'ing the contents of files we
634 : // read, but that's expensive and the local_fs test helper's whole reason for existence is to run small tests
635 : // quickly, with less overhead than using a mock S3 server.
636 108 : fn mock_etag(meta: &std::fs::Metadata) -> Etag {
637 108 : let mtime = meta.modified().expect("Filesystem mtime missing");
638 108 : format!("{}", mtime.duration_since(UNIX_EPOCH).unwrap().as_millis()).into()
639 108 : }
640 :
641 : #[cfg(test)]
642 : mod fs_tests {
643 : use std::collections::HashMap;
644 : use std::io::Write;
645 : use std::ops::Bound;
646 :
647 : use camino_tempfile::tempdir;
648 :
649 : use super::*;
650 :
651 9 : async fn read_and_check_metadata(
652 9 : storage: &LocalFs,
653 9 : remote_storage_path: &RemotePath,
654 9 : expected_metadata: Option<&StorageMetadata>,
655 9 : ) -> anyhow::Result<String> {
656 9 : let cancel = CancellationToken::new();
657 9 : let download = storage
658 9 : .download(remote_storage_path, &DownloadOpts::default(), &cancel)
659 9 : .await
660 9 : .map_err(|e| anyhow::anyhow!("Download failed: {e}"))?;
661 9 : ensure!(
662 9 : download.metadata.as_ref() == expected_metadata,
663 0 : "Unexpected metadata returned for the downloaded file"
664 : );
665 :
666 9 : let contents = aggregate(download.download_stream).await?;
667 :
668 9 : String::from_utf8(contents).map_err(anyhow::Error::new)
669 9 : }
670 :
671 : #[tokio::test]
672 3 : async fn upload_file() -> anyhow::Result<()> {
673 3 : let (storage, cancel) = create_storage()?;
674 3 :
675 3 : let target_path_1 = upload_dummy_file(&storage, "upload_1", None, &cancel).await?;
676 3 : assert_eq!(
677 3 : storage.list_all().await?,
678 3 : vec![target_path_1.clone()],
679 3 : "Should list a single file after first upload"
680 3 : );
681 3 :
682 3 : let target_path_2 = upload_dummy_file(&storage, "upload_2", None, &cancel).await?;
683 3 : assert_eq!(
684 3 : list_files_sorted(&storage).await?,
685 3 : vec![target_path_1.clone(), target_path_2.clone()],
686 3 : "Should list a two different files after second upload"
687 3 : );
688 3 :
689 3 : Ok(())
690 3 : }
691 :
692 : #[tokio::test]
693 3 : async fn upload_file_negatives() -> anyhow::Result<()> {
694 3 : let (storage, cancel) = create_storage()?;
695 3 :
696 3 : let id = RemotePath::new(Utf8Path::new("dummy"))?;
697 3 : let content = Bytes::from_static(b"12345");
698 12 : let content = move || futures::stream::once(futures::future::ready(Ok(content.clone())));
699 3 :
700 3 : // Check that you get an error if the size parameter doesn't match the actual
701 3 : // size of the stream.
702 3 : storage
703 3 : .upload(content(), 0, &id, None, &cancel)
704 3 : .await
705 3 : .expect_err("upload with zero size succeeded");
706 3 : storage
707 3 : .upload(content(), 4, &id, None, &cancel)
708 3 : .await
709 3 : .expect_err("upload with too short size succeeded");
710 3 : storage
711 3 : .upload(content(), 6, &id, None, &cancel)
712 3 : .await
713 3 : .expect_err("upload with too large size succeeded");
714 3 :
715 3 : // Correct size is 5, this should succeed.
716 3 : storage.upload(content(), 5, &id, None, &cancel).await?;
717 3 :
718 3 : Ok(())
719 3 : }
720 :
721 33 : fn create_storage() -> anyhow::Result<(LocalFs, CancellationToken)> {
722 33 : let storage_root = tempdir()?.path().to_path_buf();
723 33 : LocalFs::new(storage_root, Duration::from_secs(120)).map(|s| (s, CancellationToken::new()))
724 33 : }
725 :
726 : #[tokio::test]
727 3 : async fn download_file() -> anyhow::Result<()> {
728 3 : let (storage, cancel) = create_storage()?;
729 3 : let upload_name = "upload_1";
730 3 : let upload_target = upload_dummy_file(&storage, upload_name, None, &cancel).await?;
731 3 :
732 3 : let contents = read_and_check_metadata(&storage, &upload_target, None).await?;
733 3 : assert_eq!(
734 3 : dummy_contents(upload_name),
735 3 : contents,
736 3 : "We should upload and download the same contents"
737 3 : );
738 3 :
739 3 : let non_existing_path = RemotePath::new(Utf8Path::new("somewhere/else"))?;
740 3 : match storage
741 3 : .download(&non_existing_path, &DownloadOpts::default(), &cancel)
742 3 : .await
743 3 : {
744 3 : Err(DownloadError::NotFound) => {} // Should get NotFound for non existing keys
745 3 : other => panic!(
746 0 : "Should get a NotFound error when downloading non-existing storage files, but got: {other:?}"
747 0 : ),
748 3 : }
749 3 : Ok(())
750 3 : }
751 :
752 : #[tokio::test]
753 3 : async fn download_file_range_positive() -> anyhow::Result<()> {
754 3 : let (storage, cancel) = create_storage()?;
755 3 : let upload_name = "upload_1";
756 3 : let upload_target = upload_dummy_file(&storage, upload_name, None, &cancel).await?;
757 3 :
758 3 : let full_range_download_contents =
759 3 : read_and_check_metadata(&storage, &upload_target, None).await?;
760 3 : assert_eq!(
761 3 : dummy_contents(upload_name),
762 3 : full_range_download_contents,
763 3 : "Download full range should return the whole upload"
764 3 : );
765 3 :
766 3 : let uploaded_bytes = dummy_contents(upload_name).into_bytes();
767 3 : let (first_part_local, second_part_local) = uploaded_bytes.split_at(3);
768 3 :
769 3 : let first_part_download = storage
770 3 : .download(
771 3 : &upload_target,
772 3 : &DownloadOpts {
773 3 : byte_end: Bound::Excluded(first_part_local.len() as u64),
774 3 : ..Default::default()
775 3 : },
776 3 : &cancel,
777 3 : )
778 3 : .await?;
779 3 : assert!(
780 3 : first_part_download.metadata.is_none(),
781 3 : "No metadata should be returned for no metadata upload"
782 3 : );
783 3 :
784 3 : let first_part_remote = aggregate(first_part_download.download_stream).await?;
785 3 : assert_eq!(
786 3 : first_part_local, first_part_remote,
787 3 : "First part bytes should be returned when requested"
788 3 : );
789 3 :
790 3 : let second_part_download = storage
791 3 : .download(
792 3 : &upload_target,
793 3 : &DownloadOpts {
794 3 : byte_start: Bound::Included(first_part_local.len() as u64),
795 3 : byte_end: Bound::Excluded(
796 3 : (first_part_local.len() + second_part_local.len()) as u64,
797 3 : ),
798 3 : ..Default::default()
799 3 : },
800 3 : &cancel,
801 3 : )
802 3 : .await?;
803 3 : assert!(
804 3 : second_part_download.metadata.is_none(),
805 3 : "No metadata should be returned for no metadata upload"
806 3 : );
807 3 :
808 3 : let second_part_remote = aggregate(second_part_download.download_stream).await?;
809 3 : assert_eq!(
810 3 : second_part_local, second_part_remote,
811 3 : "Second part bytes should be returned when requested"
812 3 : );
813 3 :
814 3 : let suffix_bytes = storage
815 3 : .download(
816 3 : &upload_target,
817 3 : &DownloadOpts {
818 3 : byte_start: Bound::Included(13),
819 3 : ..Default::default()
820 3 : },
821 3 : &cancel,
822 3 : )
823 3 : .await?
824 3 : .download_stream;
825 3 : let suffix_bytes = aggregate(suffix_bytes).await?;
826 3 : let suffix = std::str::from_utf8(&suffix_bytes)?;
827 3 : assert_eq!(upload_name, suffix);
828 3 :
829 3 : let all_bytes = storage
830 3 : .download(&upload_target, &DownloadOpts::default(), &cancel)
831 3 : .await?
832 3 : .download_stream;
833 3 : let all_bytes = aggregate(all_bytes).await?;
834 3 : let all_bytes = std::str::from_utf8(&all_bytes)?;
835 3 : assert_eq!(dummy_contents("upload_1"), all_bytes);
836 3 :
837 3 : Ok(())
838 3 : }
839 :
840 : #[tokio::test]
841 : #[should_panic(expected = "at or before start")]
842 3 : async fn download_file_range_negative() {
843 3 : let (storage, cancel) = create_storage().unwrap();
844 3 : let upload_name = "upload_1";
845 3 : let upload_target = upload_dummy_file(&storage, upload_name, None, &cancel)
846 3 : .await
847 3 : .unwrap();
848 3 :
849 3 : storage
850 3 : .download(
851 3 : &upload_target,
852 3 : &DownloadOpts {
853 3 : byte_start: Bound::Included(10),
854 3 : byte_end: Bound::Excluded(10),
855 3 : ..Default::default()
856 3 : },
857 3 : &cancel,
858 3 : )
859 3 : .await
860 3 : .unwrap();
861 3 : }
862 :
863 : #[tokio::test]
864 3 : async fn delete_file() -> anyhow::Result<()> {
865 3 : let (storage, cancel) = create_storage()?;
866 3 : let upload_name = "upload_1";
867 3 : let upload_target = upload_dummy_file(&storage, upload_name, None, &cancel).await?;
868 3 :
869 3 : storage.delete(&upload_target, &cancel).await?;
870 3 : assert!(storage.list_all().await?.is_empty());
871 3 :
872 3 : storage
873 3 : .delete(&upload_target, &cancel)
874 3 : .await
875 3 : .expect("Should allow deleting non-existing storage files");
876 3 :
877 3 : Ok(())
878 3 : }
879 :
880 : #[tokio::test]
881 3 : async fn file_with_metadata() -> anyhow::Result<()> {
882 3 : let (storage, cancel) = create_storage()?;
883 3 : let upload_name = "upload_1";
884 3 : let metadata = StorageMetadata(HashMap::from([
885 3 : ("one".to_string(), "1".to_string()),
886 3 : ("two".to_string(), "2".to_string()),
887 3 : ]));
888 3 : let upload_target =
889 3 : upload_dummy_file(&storage, upload_name, Some(metadata.clone()), &cancel).await?;
890 3 :
891 3 : let full_range_download_contents =
892 3 : read_and_check_metadata(&storage, &upload_target, Some(&metadata)).await?;
893 3 : assert_eq!(
894 3 : dummy_contents(upload_name),
895 3 : full_range_download_contents,
896 3 : "We should upload and download the same contents"
897 3 : );
898 3 :
899 3 : let uploaded_bytes = dummy_contents(upload_name).into_bytes();
900 3 : let (first_part_local, _) = uploaded_bytes.split_at(3);
901 3 :
902 3 : let partial_download_with_metadata = storage
903 3 : .download(
904 3 : &upload_target,
905 3 : &DownloadOpts {
906 3 : byte_end: Bound::Excluded(first_part_local.len() as u64),
907 3 : ..Default::default()
908 3 : },
909 3 : &cancel,
910 3 : )
911 3 : .await?;
912 3 : let first_part_remote = aggregate(partial_download_with_metadata.download_stream).await?;
913 3 : assert_eq!(
914 3 : first_part_local,
915 3 : first_part_remote.as_slice(),
916 3 : "First part bytes should be returned when requested"
917 3 : );
918 3 :
919 3 : assert_eq!(
920 3 : partial_download_with_metadata.metadata,
921 3 : Some(metadata),
922 3 : "We should get the same metadata back for partial download"
923 3 : );
924 3 :
925 3 : Ok(())
926 3 : }
927 :
928 : #[tokio::test]
929 3 : async fn list() -> anyhow::Result<()> {
930 3 : // No delimiter: should recursively list everything
931 3 : let (storage, cancel) = create_storage()?;
932 3 : let child = upload_dummy_file(&storage, "grandparent/parent/child", None, &cancel).await?;
933 3 : let child_sibling =
934 3 : upload_dummy_file(&storage, "grandparent/parent/child_sibling", None, &cancel).await?;
935 3 : let uncle = upload_dummy_file(&storage, "grandparent/uncle", None, &cancel).await?;
936 3 :
937 3 : let listing = storage
938 3 : .list(None, ListingMode::NoDelimiter, None, &cancel)
939 3 : .await?;
940 3 : assert!(listing.prefixes.is_empty());
941 3 : assert_eq!(
942 3 : listing
943 3 : .keys
944 3 : .into_iter()
945 9 : .map(|o| o.key)
946 3 : .collect::<HashSet<_>>(),
947 3 : HashSet::from([uncle.clone(), child.clone(), child_sibling.clone()])
948 3 : );
949 3 :
950 3 : // Delimiter: should only go one deep
951 3 : let listing = storage
952 3 : .list(None, ListingMode::WithDelimiter, None, &cancel)
953 3 : .await?;
954 3 :
955 3 : assert_eq!(
956 3 : listing.prefixes,
957 3 : [RemotePath::from_string("timelines").unwrap()].to_vec()
958 3 : );
959 3 : assert!(listing.keys.is_empty());
960 3 :
961 3 : // Delimiter & prefix with a trailing slash
962 3 : let listing = storage
963 3 : .list(
964 3 : Some(&RemotePath::from_string("timelines/some_timeline/grandparent/").unwrap()),
965 3 : ListingMode::WithDelimiter,
966 3 : None,
967 3 : &cancel,
968 3 : )
969 3 : .await?;
970 3 : assert_eq!(
971 3 : listing.keys.into_iter().map(|o| o.key).collect::<Vec<_>>(),
972 3 : [RemotePath::from_string("uncle").unwrap()].to_vec()
973 3 : );
974 3 : assert_eq!(
975 3 : listing.prefixes,
976 3 : [RemotePath::from_string("parent").unwrap()].to_vec()
977 3 : );
978 3 :
979 3 : // Delimiter and prefix without a trailing slash
980 3 : let listing = storage
981 3 : .list(
982 3 : Some(&RemotePath::from_string("timelines/some_timeline/grandparent").unwrap()),
983 3 : ListingMode::WithDelimiter,
984 3 : None,
985 3 : &cancel,
986 3 : )
987 3 : .await?;
988 3 : assert_eq!(listing.keys, vec![]);
989 3 : assert_eq!(
990 3 : listing.prefixes,
991 3 : [RemotePath::from_string("grandparent").unwrap()].to_vec()
992 3 : );
993 3 :
994 3 : // Delimiter and prefix that's partway through a path component
995 3 : let listing = storage
996 3 : .list(
997 3 : Some(&RemotePath::from_string("timelines/some_timeline/grandp").unwrap()),
998 3 : ListingMode::WithDelimiter,
999 3 : None,
1000 3 : &cancel,
1001 3 : )
1002 3 : .await?;
1003 3 : assert_eq!(listing.keys, vec![]);
1004 3 : assert_eq!(
1005 3 : listing.prefixes,
1006 3 : [RemotePath::from_string("grandparent").unwrap()].to_vec()
1007 3 : );
1008 3 :
1009 3 : Ok(())
1010 3 : }
1011 :
1012 : #[tokio::test]
1013 3 : async fn list_part_component() -> anyhow::Result<()> {
1014 3 : // No delimiter: should recursively list everything
1015 3 : let (storage, cancel) = create_storage()?;
1016 3 :
1017 3 : // Imitates what happens in a tenant path when we have an unsharded path and a sharded path, and do a listing
1018 3 : // of the unsharded path: although there is a "directory" at the unsharded path, it should be handled as
1019 3 : // a freeform prefix.
1020 3 : let _child_a =
1021 3 : upload_dummy_file(&storage, "grandparent/tenant-01/child", None, &cancel).await?;
1022 3 : let _child_b =
1023 3 : upload_dummy_file(&storage, "grandparent/tenant/child", None, &cancel).await?;
1024 3 :
1025 3 : // Delimiter and prefix that's partway through a path component
1026 3 : let listing = storage
1027 3 : .list(
1028 3 : Some(
1029 3 : &RemotePath::from_string("timelines/some_timeline/grandparent/tenant").unwrap(),
1030 3 : ),
1031 3 : ListingMode::WithDelimiter,
1032 3 : None,
1033 3 : &cancel,
1034 3 : )
1035 3 : .await?;
1036 3 : assert_eq!(listing.keys, vec![]);
1037 3 :
1038 3 : let mut found_prefixes = listing.prefixes.clone();
1039 3 : found_prefixes.sort();
1040 3 : assert_eq!(
1041 3 : found_prefixes,
1042 3 : [
1043 3 : RemotePath::from_string("tenant").unwrap(),
1044 3 : RemotePath::from_string("tenant-01").unwrap(),
1045 3 : ]
1046 3 : .to_vec()
1047 3 : );
1048 3 :
1049 3 : Ok(())
1050 3 : }
1051 :
1052 : #[tokio::test]
1053 3 : async fn overwrite_shorter_file() -> anyhow::Result<()> {
1054 3 : let (storage, cancel) = create_storage()?;
1055 3 :
1056 3 : let path = RemotePath::new("does/not/matter/file".into())?;
1057 3 :
1058 3 : let body = Bytes::from_static(b"long file contents is long");
1059 3 : {
1060 3 : let len = body.len();
1061 3 : let body =
1062 3 : futures::stream::once(futures::future::ready(std::io::Result::Ok(body.clone())));
1063 3 : storage.upload(body, len, &path, None, &cancel).await?;
1064 3 : }
1065 3 :
1066 3 : let read = aggregate(
1067 3 : storage
1068 3 : .download(&path, &DownloadOpts::default(), &cancel)
1069 3 : .await?
1070 3 : .download_stream,
1071 3 : )
1072 3 : .await?;
1073 3 : assert_eq!(body, read);
1074 3 :
1075 3 : let shorter = Bytes::from_static(b"shorter body");
1076 3 : {
1077 3 : let len = shorter.len();
1078 3 : let body =
1079 3 : futures::stream::once(futures::future::ready(std::io::Result::Ok(shorter.clone())));
1080 3 : storage.upload(body, len, &path, None, &cancel).await?;
1081 3 : }
1082 3 :
1083 3 : let read = aggregate(
1084 3 : storage
1085 3 : .download(&path, &DownloadOpts::default(), &cancel)
1086 3 : .await?
1087 3 : .download_stream,
1088 3 : )
1089 3 : .await?;
1090 3 : assert_eq!(shorter, read);
1091 3 : Ok(())
1092 3 : }
1093 :
1094 : #[tokio::test]
1095 3 : async fn cancelled_upload_can_later_be_retried() -> anyhow::Result<()> {
1096 3 : let (storage, cancel) = create_storage()?;
1097 3 :
1098 3 : let path = RemotePath::new("does/not/matter/file".into())?;
1099 3 :
1100 3 : let body = Bytes::from_static(b"long file contents is long");
1101 3 : {
1102 3 : let len = body.len();
1103 3 : let body =
1104 3 : futures::stream::once(futures::future::ready(std::io::Result::Ok(body.clone())));
1105 3 : let cancel = cancel.child_token();
1106 3 : cancel.cancel();
1107 3 : let e = storage
1108 3 : .upload(body, len, &path, None, &cancel)
1109 3 : .await
1110 3 : .unwrap_err();
1111 3 :
1112 3 : assert!(TimeoutOrCancel::caused_by_cancel(&e));
1113 3 : }
1114 3 :
1115 3 : {
1116 3 : let len = body.len();
1117 3 : let body =
1118 3 : futures::stream::once(futures::future::ready(std::io::Result::Ok(body.clone())));
1119 3 : storage.upload(body, len, &path, None, &cancel).await?;
1120 3 : }
1121 3 :
1122 3 : let read = aggregate(
1123 3 : storage
1124 3 : .download(&path, &DownloadOpts::default(), &cancel)
1125 3 : .await?
1126 3 : .download_stream,
1127 3 : )
1128 3 : .await?;
1129 3 : assert_eq!(body, read);
1130 3 :
1131 3 : Ok(())
1132 3 : }
1133 :
1134 36 : async fn upload_dummy_file(
1135 36 : storage: &LocalFs,
1136 36 : name: &str,
1137 36 : metadata: Option<StorageMetadata>,
1138 36 : cancel: &CancellationToken,
1139 36 : ) -> anyhow::Result<RemotePath> {
1140 36 : let from_path = storage
1141 36 : .storage_root
1142 36 : .join("timelines")
1143 36 : .join("some_timeline")
1144 36 : .join(name);
1145 36 : let (file, size) = create_file_for_upload(&from_path, &dummy_contents(name)).await?;
1146 :
1147 36 : let relative_path = from_path
1148 36 : .strip_prefix(&storage.storage_root)
1149 36 : .context("Failed to strip storage root prefix")
1150 36 : .and_then(RemotePath::new)
1151 36 : .with_context(|| {
1152 0 : format!(
1153 0 : "Failed to resolve remote part of path {:?} for base {:?}",
1154 0 : from_path, storage.storage_root
1155 0 : )
1156 36 : })?;
1157 :
1158 36 : let file = tokio_util::io::ReaderStream::new(file);
1159 36 :
1160 36 : storage
1161 36 : .upload(file, size, &relative_path, metadata, cancel)
1162 36 : .await?;
1163 36 : Ok(relative_path)
1164 36 : }
1165 :
1166 36 : async fn create_file_for_upload(
1167 36 : path: &Utf8Path,
1168 36 : contents: &str,
1169 36 : ) -> anyhow::Result<(fs::File, usize)> {
1170 36 : std::fs::create_dir_all(path.parent().unwrap())?;
1171 36 : let mut file_for_writing = std::fs::OpenOptions::new()
1172 36 : .write(true)
1173 36 : .create_new(true)
1174 36 : .open(path)?;
1175 36 : write!(file_for_writing, "{}", contents)?;
1176 36 : drop(file_for_writing);
1177 36 : let file_size = path.metadata()?.len() as usize;
1178 36 : Ok((
1179 36 : fs::OpenOptions::new().read(true).open(&path).await?,
1180 36 : file_size,
1181 : ))
1182 36 : }
1183 :
1184 54 : fn dummy_contents(name: &str) -> String {
1185 54 : format!("contents for {name}")
1186 54 : }
1187 :
1188 3 : async fn list_files_sorted(storage: &LocalFs) -> anyhow::Result<Vec<RemotePath>> {
1189 3 : let mut files = storage.list_all().await?;
1190 3 : files.sort_by(|a, b| a.0.cmp(&b.0));
1191 3 : Ok(files)
1192 3 : }
1193 :
1194 33 : async fn aggregate(
1195 33 : stream: impl Stream<Item = std::io::Result<Bytes>>,
1196 33 : ) -> anyhow::Result<Vec<u8>> {
1197 : use futures::stream::StreamExt;
1198 33 : let mut out = Vec::new();
1199 33 : let mut stream = std::pin::pin!(stream);
1200 66 : while let Some(res) = stream.next().await {
1201 33 : out.extend_from_slice(&res?[..]);
1202 : }
1203 33 : Ok(out)
1204 33 : }
1205 : }
|