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

Generated by: LCOV version 2.1-beta