LCOV - code coverage report
Current view: top level - libs/remote_storage/src - local_fs.rs (source / functions) Coverage Total Hit
Test: 49aa928ec5b4b510172d8b5c6d154da28e70a46c.info Lines: 89.5 % 970 868
Test Date: 2024-11-13 18:23:39 Functions: 59.1 % 132 78

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

Generated by: LCOV version 2.1-beta