LCOV - code coverage report
Current view: top level - libs/remote_storage/src - local_fs.rs (source / functions) Coverage Total Hit
Test: b4ae4c4857f9ef3e144e982a35ee23bc84c71983.info Lines: 89.5 % 973 871
Test Date: 2024-10-22 22:13:45 Functions: 59.4 % 133 79

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

Generated by: LCOV version 2.1-beta