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