LCOV - code coverage report
Current view: top level - libs/remote_storage/src - simulate_failures.rs (source / functions) Coverage Total Hit
Test: 86c536b7fe84b2afe03c3bb264199e9c319ae0f8.info Lines: 30.6 % 144 44
Test Date: 2024-06-24 16:38:41 Functions: 13.8 % 29 4

            Line data    Source code
       1              : //! This module provides a wrapper around a real RemoteStorage implementation that
       2              : //! causes the first N attempts at each upload or download operatio to fail. For
       3              : //! testing purposes.
       4              : use bytes::Bytes;
       5              : use futures::stream::Stream;
       6              : use std::collections::HashMap;
       7              : use std::num::NonZeroU32;
       8              : use std::sync::Mutex;
       9              : use std::time::SystemTime;
      10              : use std::{collections::hash_map::Entry, sync::Arc};
      11              : use tokio_util::sync::CancellationToken;
      12              : 
      13              : use crate::{
      14              :     Download, DownloadError, GenericRemoteStorage, Listing, ListingMode, RemotePath, RemoteStorage,
      15              :     StorageMetadata, TimeTravelError,
      16              : };
      17              : 
      18              : pub struct UnreliableWrapper {
      19              :     inner: GenericRemoteStorage<Arc<VoidStorage>>,
      20              : 
      21              :     // This many attempts of each operation will fail, then we let it succeed.
      22              :     attempts_to_fail: u64,
      23              : 
      24              :     // Tracks how many failed attempts of each operation has been made.
      25              :     attempts: Mutex<HashMap<RemoteOp, u64>>,
      26              : }
      27              : 
      28              : /// Used to identify retries of different unique operation.
      29              : #[derive(Debug, Hash, Eq, PartialEq)]
      30              : enum RemoteOp {
      31              :     ListPrefixes(Option<RemotePath>),
      32              :     Upload(RemotePath),
      33              :     Download(RemotePath),
      34              :     Delete(RemotePath),
      35              :     DeleteObjects(Vec<RemotePath>),
      36              :     TimeTravelRecover(Option<RemotePath>),
      37              : }
      38              : 
      39              : impl UnreliableWrapper {
      40            4 :     pub fn new(inner: crate::GenericRemoteStorage, attempts_to_fail: u64) -> Self {
      41            4 :         assert!(attempts_to_fail > 0);
      42            4 :         let inner = match inner {
      43            0 :             GenericRemoteStorage::AwsS3(s) => GenericRemoteStorage::AwsS3(s),
      44            0 :             GenericRemoteStorage::AzureBlob(s) => GenericRemoteStorage::AzureBlob(s),
      45            4 :             GenericRemoteStorage::LocalFs(s) => GenericRemoteStorage::LocalFs(s),
      46              :             // We could also make this a no-op, as in, extract the inner of the passed generic remote storage
      47            0 :             GenericRemoteStorage::Unreliable(_s) => {
      48            0 :                 panic!("Can't wrap unreliable wrapper unreliably")
      49              :             }
      50              :         };
      51            4 :         UnreliableWrapper {
      52            4 :             inner,
      53            4 :             attempts_to_fail,
      54            4 :             attempts: Mutex::new(HashMap::new()),
      55            4 :         }
      56            4 :     }
      57              : 
      58              :     ///
      59              :     /// Common functionality for all operations.
      60              :     ///
      61              :     /// On the first attempts of this operation, return an error. After 'attempts_to_fail'
      62              :     /// attempts, let the operation go ahead, and clear the counter.
      63              :     ///
      64           48 :     fn attempt(&self, op: RemoteOp) -> anyhow::Result<u64> {
      65           48 :         let mut attempts = self.attempts.lock().unwrap();
      66           48 : 
      67           48 :         match attempts.entry(op) {
      68           24 :             Entry::Occupied(mut e) => {
      69           24 :                 let attempts_before_this = {
      70           24 :                     let p = e.get_mut();
      71           24 :                     *p += 1;
      72           24 :                     *p
      73           24 :                 };
      74           24 : 
      75           24 :                 if attempts_before_this >= self.attempts_to_fail {
      76              :                     // let it succeed
      77           24 :                     e.remove();
      78           24 :                     Ok(attempts_before_this)
      79              :                 } else {
      80            0 :                     let error =
      81            0 :                         anyhow::anyhow!("simulated failure of remote operation {:?}", e.key());
      82            0 :                     Err(error)
      83              :                 }
      84              :             }
      85           24 :             Entry::Vacant(e) => {
      86           24 :                 let error = anyhow::anyhow!("simulated failure of remote operation {:?}", e.key());
      87           24 :                 e.insert(1);
      88           24 :                 Err(error)
      89              :             }
      90              :         }
      91           48 :     }
      92              : 
      93            0 :     async fn delete_inner(
      94            0 :         &self,
      95            0 :         path: &RemotePath,
      96            0 :         attempt: bool,
      97            0 :         cancel: &CancellationToken,
      98            0 :     ) -> anyhow::Result<()> {
      99            0 :         if attempt {
     100            0 :             self.attempt(RemoteOp::Delete(path.clone()))?;
     101            0 :         }
     102            0 :         self.inner.delete(path, cancel).await
     103            0 :     }
     104              : }
     105              : 
     106              : // We never construct this, so the type is not important, just has to not be UnreliableWrapper and impl RemoteStorage.
     107              : type VoidStorage = crate::LocalFs;
     108              : 
     109              : impl RemoteStorage for UnreliableWrapper {
     110            0 :     async fn list(
     111            0 :         &self,
     112            0 :         prefix: Option<&RemotePath>,
     113            0 :         mode: ListingMode,
     114            0 :         max_keys: Option<NonZeroU32>,
     115            0 :         cancel: &CancellationToken,
     116            0 :     ) -> Result<Listing, DownloadError> {
     117            0 :         self.attempt(RemoteOp::ListPrefixes(prefix.cloned()))
     118            0 :             .map_err(DownloadError::Other)?;
     119            0 :         self.inner.list(prefix, mode, max_keys, cancel).await
     120            0 :     }
     121              : 
     122           48 :     async fn upload(
     123           48 :         &self,
     124           48 :         data: impl Stream<Item = std::io::Result<Bytes>> + Send + Sync + 'static,
     125           48 :         // S3 PUT request requires the content length to be specified,
     126           48 :         // otherwise it starts to fail with the concurrent connection count increasing.
     127           48 :         data_size_bytes: usize,
     128           48 :         to: &RemotePath,
     129           48 :         metadata: Option<StorageMetadata>,
     130           48 :         cancel: &CancellationToken,
     131           48 :     ) -> anyhow::Result<()> {
     132           48 :         self.attempt(RemoteOp::Upload(to.clone()))?;
     133           24 :         self.inner
     134           24 :             .upload(data, data_size_bytes, to, metadata, cancel)
     135           76 :             .await
     136           48 :     }
     137              : 
     138            0 :     async fn download(
     139            0 :         &self,
     140            0 :         from: &RemotePath,
     141            0 :         cancel: &CancellationToken,
     142            0 :     ) -> Result<Download, DownloadError> {
     143            0 :         self.attempt(RemoteOp::Download(from.clone()))
     144            0 :             .map_err(DownloadError::Other)?;
     145            0 :         self.inner.download(from, cancel).await
     146            0 :     }
     147              : 
     148            0 :     async fn download_byte_range(
     149            0 :         &self,
     150            0 :         from: &RemotePath,
     151            0 :         start_inclusive: u64,
     152            0 :         end_exclusive: Option<u64>,
     153            0 :         cancel: &CancellationToken,
     154            0 :     ) -> Result<Download, DownloadError> {
     155            0 :         // Note: We treat any download_byte_range as an "attempt" of the same
     156            0 :         // operation. We don't pay attention to the ranges. That's good enough
     157            0 :         // for now.
     158            0 :         self.attempt(RemoteOp::Download(from.clone()))
     159            0 :             .map_err(DownloadError::Other)?;
     160            0 :         self.inner
     161            0 :             .download_byte_range(from, start_inclusive, end_exclusive, cancel)
     162            0 :             .await
     163            0 :     }
     164              : 
     165            0 :     async fn delete(&self, path: &RemotePath, cancel: &CancellationToken) -> anyhow::Result<()> {
     166            0 :         self.delete_inner(path, true, cancel).await
     167            0 :     }
     168              : 
     169            0 :     async fn delete_objects<'a>(
     170            0 :         &self,
     171            0 :         paths: &'a [RemotePath],
     172            0 :         cancel: &CancellationToken,
     173            0 :     ) -> anyhow::Result<()> {
     174            0 :         self.attempt(RemoteOp::DeleteObjects(paths.to_vec()))?;
     175            0 :         let mut error_counter = 0;
     176            0 :         for path in paths {
     177              :             // Dont record attempt because it was already recorded above
     178            0 :             if (self.delete_inner(path, false, cancel).await).is_err() {
     179            0 :                 error_counter += 1;
     180            0 :             }
     181              :         }
     182            0 :         if error_counter > 0 {
     183            0 :             return Err(anyhow::anyhow!(
     184            0 :                 "failed to delete {} objects",
     185            0 :                 error_counter
     186            0 :             ));
     187            0 :         }
     188            0 :         Ok(())
     189            0 :     }
     190              : 
     191            0 :     async fn copy(
     192            0 :         &self,
     193            0 :         from: &RemotePath,
     194            0 :         to: &RemotePath,
     195            0 :         cancel: &CancellationToken,
     196            0 :     ) -> anyhow::Result<()> {
     197            0 :         // copy is equivalent to download + upload
     198            0 :         self.attempt(RemoteOp::Download(from.clone()))?;
     199            0 :         self.attempt(RemoteOp::Upload(to.clone()))?;
     200            0 :         self.inner.copy_object(from, to, cancel).await
     201            0 :     }
     202              : 
     203            0 :     async fn time_travel_recover(
     204            0 :         &self,
     205            0 :         prefix: Option<&RemotePath>,
     206            0 :         timestamp: SystemTime,
     207            0 :         done_if_after: SystemTime,
     208            0 :         cancel: &CancellationToken,
     209            0 :     ) -> Result<(), TimeTravelError> {
     210            0 :         self.attempt(RemoteOp::TimeTravelRecover(prefix.map(|p| p.to_owned())))
     211            0 :             .map_err(TimeTravelError::Other)?;
     212            0 :         self.inner
     213            0 :             .time_travel_recover(prefix, timestamp, done_if_after, cancel)
     214            0 :             .await
     215            0 :     }
     216              : }
        

Generated by: LCOV version 2.1-beta