LCOV - code coverage report
Current view: top level - libs/remote_storage/src - azure_blob.rs (source / functions) Coverage Total Hit
Test: 3eba1babe267649f8cebefc91c236589db030548.info Lines: 81.6 % 570 465
Test Date: 2024-11-22 12:36:12 Functions: 54.5 % 77 42

            Line data    Source code
       1              : //! Azure Blob Storage wrapper
       2              : 
       3              : use std::borrow::Cow;
       4              : use std::collections::HashMap;
       5              : use std::env;
       6              : use std::fmt::Display;
       7              : use std::io;
       8              : use std::num::NonZeroU32;
       9              : use std::pin::Pin;
      10              : use std::str::FromStr;
      11              : use std::sync::Arc;
      12              : use std::time::Duration;
      13              : use std::time::SystemTime;
      14              : 
      15              : use super::REMOTE_STORAGE_PREFIX_SEPARATOR;
      16              : use anyhow::Result;
      17              : use azure_core::request_options::{IfMatchCondition, MaxResults, Metadata, Range};
      18              : use azure_core::{Continuable, RetryOptions};
      19              : use azure_identity::DefaultAzureCredential;
      20              : use azure_storage::StorageCredentials;
      21              : use azure_storage_blobs::blob::CopyStatus;
      22              : use azure_storage_blobs::prelude::ClientBuilder;
      23              : use azure_storage_blobs::{blob::operations::GetBlobBuilder, prelude::ContainerClient};
      24              : use bytes::Bytes;
      25              : use futures::future::Either;
      26              : use futures::stream::Stream;
      27              : use futures_util::StreamExt;
      28              : use futures_util::TryStreamExt;
      29              : use http_types::{StatusCode, Url};
      30              : use scopeguard::ScopeGuard;
      31              : use tokio_util::sync::CancellationToken;
      32              : use tracing::debug;
      33              : use utils::backoff;
      34              : 
      35              : use crate::metrics::{start_measuring_requests, AttemptOutcome, RequestKind};
      36              : use crate::{
      37              :     config::AzureConfig, error::Cancelled, ConcurrencyLimiter, Download, DownloadError,
      38              :     DownloadOpts, Listing, ListingMode, ListingObject, RemotePath, RemoteStorage, StorageMetadata,
      39              :     TimeTravelError, TimeoutOrCancel,
      40              : };
      41              : 
      42              : pub struct AzureBlobStorage {
      43              :     client: ContainerClient,
      44              :     container_name: String,
      45              :     prefix_in_container: Option<String>,
      46              :     max_keys_per_list_response: Option<NonZeroU32>,
      47              :     concurrency_limiter: ConcurrencyLimiter,
      48              :     // Per-request timeout. Accessible for tests.
      49              :     pub timeout: Duration,
      50              : }
      51              : 
      52              : impl AzureBlobStorage {
      53           10 :     pub fn new(azure_config: &AzureConfig, timeout: Duration) -> Result<Self> {
      54           10 :         debug!(
      55            0 :             "Creating azure remote storage for azure container {}",
      56              :             azure_config.container_name
      57              :         );
      58              : 
      59              :         // Use the storage account from the config by default, fall back to env var if not present.
      60           10 :         let account = azure_config.storage_account.clone().unwrap_or_else(|| {
      61           10 :             env::var("AZURE_STORAGE_ACCOUNT").expect("missing AZURE_STORAGE_ACCOUNT")
      62           10 :         });
      63              : 
      64              :         // If the `AZURE_STORAGE_ACCESS_KEY` env var has an access key, use that,
      65              :         // otherwise try the token based credentials.
      66           10 :         let credentials = if let Ok(access_key) = env::var("AZURE_STORAGE_ACCESS_KEY") {
      67           10 :             StorageCredentials::access_key(account.clone(), access_key)
      68              :         } else {
      69            0 :             let token_credential = DefaultAzureCredential::default();
      70            0 :             StorageCredentials::token_credential(Arc::new(token_credential))
      71              :         };
      72              : 
      73              :         // we have an outer retry
      74           10 :         let builder = ClientBuilder::new(account, credentials).retry(RetryOptions::none());
      75           10 : 
      76           10 :         let client = builder.container_client(azure_config.container_name.to_owned());
      77              : 
      78           10 :         let max_keys_per_list_response =
      79           10 :             if let Some(limit) = azure_config.max_keys_per_list_response {
      80              :                 Some(
      81            4 :                     NonZeroU32::new(limit as u32)
      82            4 :                         .ok_or_else(|| anyhow::anyhow!("max_keys_per_list_response can't be 0"))?,
      83              :                 )
      84              :             } else {
      85            6 :                 None
      86              :             };
      87              : 
      88           10 :         Ok(AzureBlobStorage {
      89           10 :             client,
      90           10 :             container_name: azure_config.container_name.to_owned(),
      91           10 :             prefix_in_container: azure_config.prefix_in_container.to_owned(),
      92           10 :             max_keys_per_list_response,
      93           10 :             concurrency_limiter: ConcurrencyLimiter::new(azure_config.concurrency_limit.get()),
      94           10 :             timeout,
      95           10 :         })
      96           10 :     }
      97              : 
      98          237 :     pub fn relative_path_to_name(&self, path: &RemotePath) -> String {
      99          237 :         assert_eq!(std::path::MAIN_SEPARATOR, REMOTE_STORAGE_PREFIX_SEPARATOR);
     100          237 :         let path_string = path.get_path().as_str();
     101          237 :         match &self.prefix_in_container {
     102          237 :             Some(prefix) => {
     103          237 :                 if prefix.ends_with(REMOTE_STORAGE_PREFIX_SEPARATOR) {
     104          237 :                     prefix.clone() + path_string
     105              :                 } else {
     106            0 :                     format!("{prefix}{REMOTE_STORAGE_PREFIX_SEPARATOR}{path_string}")
     107              :                 }
     108              :             }
     109            0 :             None => path_string.to_string(),
     110              :         }
     111          237 :     }
     112              : 
     113          249 :     fn name_to_relative_path(&self, key: &str) -> RemotePath {
     114          249 :         let relative_path =
     115          249 :             match key.strip_prefix(self.prefix_in_container.as_deref().unwrap_or_default()) {
     116          249 :                 Some(stripped) => stripped,
     117              :                 // we rely on Azure to return properly prefixed paths
     118              :                 // for requests with a certain prefix
     119            0 :                 None => panic!(
     120            0 :                     "Key {key} does not start with container prefix {:?}",
     121            0 :                     self.prefix_in_container
     122            0 :                 ),
     123              :             };
     124          249 :         RemotePath(
     125          249 :             relative_path
     126          249 :                 .split(REMOTE_STORAGE_PREFIX_SEPARATOR)
     127          249 :                 .collect(),
     128          249 :         )
     129          249 :     }
     130              : 
     131           11 :     async fn download_for_builder(
     132           11 :         &self,
     133           11 :         builder: GetBlobBuilder,
     134           11 :         cancel: &CancellationToken,
     135           11 :     ) -> Result<Download, DownloadError> {
     136           11 :         let kind = RequestKind::Get;
     137              : 
     138           11 :         let _permit = self.permit(kind, cancel).await?;
     139           11 :         let cancel_or_timeout = crate::support::cancel_or_timeout(self.timeout, cancel.clone());
     140           11 :         let cancel_or_timeout_ = crate::support::cancel_or_timeout(self.timeout, cancel.clone());
     141           11 : 
     142           11 :         let mut etag = None;
     143           11 :         let mut last_modified = None;
     144           11 :         let mut metadata = HashMap::new();
     145           11 : 
     146           11 :         let started_at = start_measuring_requests(kind);
     147           11 : 
     148           11 :         let download = async {
     149           11 :             let response = builder
     150           11 :                 // convert to concrete Pageable
     151           11 :                 .into_stream()
     152           11 :                 // convert to TryStream
     153           11 :                 .into_stream()
     154           11 :                 .map_err(to_download_error);
     155           11 : 
     156           11 :             // apply per request timeout
     157           11 :             let response = tokio_stream::StreamExt::timeout(response, self.timeout);
     158           11 : 
     159           11 :             // flatten
     160           11 :             let response = response.map(|res| match res {
     161           11 :                 Ok(res) => res,
     162            0 :                 Err(_elapsed) => Err(DownloadError::Timeout),
     163           11 :             });
     164           11 : 
     165           11 :             let mut response = Box::pin(response);
     166              : 
     167           58 :             let Some(part) = response.next().await else {
     168            0 :                 return Err(DownloadError::Other(anyhow::anyhow!(
     169            0 :                     "Azure GET response contained no response body"
     170            0 :                 )));
     171              :             };
     172           11 :             let part = part?;
     173            9 :             if etag.is_none() {
     174            9 :                 etag = Some(part.blob.properties.etag);
     175            9 :             }
     176            9 :             if last_modified.is_none() {
     177            9 :                 last_modified = Some(part.blob.properties.last_modified.into());
     178            9 :             }
     179            9 :             if let Some(blob_meta) = part.blob.metadata {
     180            0 :                 metadata.extend(blob_meta.iter().map(|(k, v)| (k.to_owned(), v.to_owned())));
     181            9 :             }
     182              : 
     183              :             // unwrap safety: if these were None, bufs would be empty and we would have returned an error already
     184            9 :             let etag = etag.unwrap();
     185            9 :             let last_modified = last_modified.unwrap();
     186            9 : 
     187            9 :             let tail_stream = response
     188            9 :                 .map(|part| match part {
     189            0 :                     Ok(part) => Either::Left(part.data.map(|r| r.map_err(io::Error::other))),
     190            0 :                     Err(e) => {
     191            0 :                         Either::Right(futures::stream::once(async { Err(io::Error::other(e)) }))
     192              :                     }
     193            9 :                 })
     194            9 :                 .flatten();
     195            9 :             let stream = part
     196            9 :                 .data
     197            9 :                 .map(|r| r.map_err(io::Error::other))
     198            9 :                 .chain(sync_wrapper::SyncStream::new(tail_stream));
     199            9 :             //.chain(SyncStream::from_pin(Box::pin(tail_stream)));
     200            9 : 
     201            9 :             let download_stream = crate::support::DownloadStream::new(cancel_or_timeout_, stream);
     202            9 : 
     203            9 :             Ok(Download {
     204            9 :                 download_stream: Box::pin(download_stream),
     205            9 :                 etag,
     206            9 :                 last_modified,
     207            9 :                 metadata: Some(StorageMetadata(metadata)),
     208            9 :             })
     209           11 :         };
     210              : 
     211           11 :         let download = tokio::select! {
     212           11 :             bufs = download => bufs,
     213           11 :             cancel_or_timeout = cancel_or_timeout => match cancel_or_timeout {
     214            0 :                 TimeoutOrCancel::Timeout => return Err(DownloadError::Timeout),
     215            0 :                 TimeoutOrCancel::Cancel => return Err(DownloadError::Cancelled),
     216              :             },
     217              :         };
     218           11 :         let started_at = ScopeGuard::into_inner(started_at);
     219           11 :         let outcome = match &download {
     220            9 :             Ok(_) => AttemptOutcome::Ok,
     221            2 :             Err(_) => AttemptOutcome::Err,
     222              :         };
     223           11 :         crate::metrics::BUCKET_METRICS
     224           11 :             .req_seconds
     225           11 :             .observe_elapsed(kind, outcome, started_at);
     226           11 :         download
     227           11 :     }
     228              : 
     229          227 :     async fn permit(
     230          227 :         &self,
     231          227 :         kind: RequestKind,
     232          227 :         cancel: &CancellationToken,
     233          227 :     ) -> Result<tokio::sync::SemaphorePermit<'_>, Cancelled> {
     234          227 :         let acquire = self.concurrency_limiter.acquire(kind);
     235          227 : 
     236          227 :         tokio::select! {
     237          227 :             permit = acquire => Ok(permit.expect("never closed")),
     238          227 :             _ = cancel.cancelled() => Err(Cancelled),
     239              :         }
     240          227 :     }
     241              : 
     242            0 :     pub fn container_name(&self) -> &str {
     243            0 :         &self.container_name
     244            0 :     }
     245              : }
     246              : 
     247            0 : fn to_azure_metadata(metadata: StorageMetadata) -> Metadata {
     248            0 :     let mut res = Metadata::new();
     249            0 :     for (k, v) in metadata.0.into_iter() {
     250            0 :         res.insert(k, v);
     251            0 :     }
     252            0 :     res
     253            0 : }
     254              : 
     255            3 : fn to_download_error(error: azure_core::Error) -> DownloadError {
     256            3 :     if let Some(http_err) = error.as_http_error() {
     257            3 :         match http_err.status() {
     258            1 :             StatusCode::NotFound => DownloadError::NotFound,
     259            2 :             StatusCode::NotModified => DownloadError::Unmodified,
     260            0 :             StatusCode::BadRequest => DownloadError::BadInput(anyhow::Error::new(error)),
     261            0 :             _ => DownloadError::Other(anyhow::Error::new(error)),
     262              :         }
     263              :     } else {
     264            0 :         DownloadError::Other(error.into())
     265              :     }
     266            3 : }
     267              : 
     268              : impl RemoteStorage for AzureBlobStorage {
     269           26 :     fn list_streaming(
     270           26 :         &self,
     271           26 :         prefix: Option<&RemotePath>,
     272           26 :         mode: ListingMode,
     273           26 :         max_keys: Option<NonZeroU32>,
     274           26 :         cancel: &CancellationToken,
     275           26 :     ) -> impl Stream<Item = Result<Listing, DownloadError>> {
     276           26 :         // get the passed prefix or if it is not set use prefix_in_bucket value
     277           26 :         let list_prefix = prefix.map(|p| self.relative_path_to_name(p)).or_else(|| {
     278           10 :             self.prefix_in_container.clone().map(|mut s| {
     279           10 :                 if !s.ends_with(REMOTE_STORAGE_PREFIX_SEPARATOR) {
     280            0 :                     s.push(REMOTE_STORAGE_PREFIX_SEPARATOR);
     281           10 :                 }
     282           10 :                 s
     283           10 :             })
     284           26 :         });
     285           26 : 
     286           26 :         async_stream::stream! {
     287           26 :             let _permit = self.permit(RequestKind::List, cancel).await?;
     288           26 : 
     289           26 :             let mut builder = self.client.list_blobs();
     290           26 : 
     291           26 :             if let ListingMode::WithDelimiter = mode {
     292           26 :                 builder = builder.delimiter(REMOTE_STORAGE_PREFIX_SEPARATOR.to_string());
     293           26 :             }
     294           26 : 
     295           26 :             if let Some(prefix) = list_prefix {
     296           26 :                 builder = builder.prefix(Cow::from(prefix.to_owned()));
     297           26 :             }
     298           26 : 
     299           26 :             if let Some(limit) = self.max_keys_per_list_response {
     300           26 :                 builder = builder.max_results(MaxResults::new(limit));
     301           26 :             }
     302           26 : 
     303           26 :             let mut next_marker = None;
     304           26 : 
     305           26 :             'outer: loop {
     306           26 :                 let mut builder = builder.clone();
     307           26 :                 if let Some(marker) = next_marker.clone() {
     308           26 :                     builder = builder.marker(marker);
     309           26 :                 }
     310           26 :                 let response = builder.into_stream();
     311           26 :                 let response = response.into_stream().map_err(to_download_error);
     312           26 :                 let response = tokio_stream::StreamExt::timeout(response, self.timeout);
     313           45 :                 let response = response.map(|res| match res {
     314           45 :                     Ok(res) => res,
     315           26 :                     Err(_elapsed) => Err(DownloadError::Timeout),
     316           45 :                 });
     317           26 : 
     318           26 :                 let mut response = std::pin::pin!(response);
     319           26 : 
     320           26 :                 let mut max_keys = max_keys.map(|mk| mk.get());
     321           26 :                 let next_item = tokio::select! {
     322           26 :                     op = response.next() => Ok(op),
     323           26 :                     _ = cancel.cancelled() => Err(DownloadError::Cancelled),
     324           26 :                 }?;
     325           26 :                 let Some(entry) = next_item else {
     326           26 :                     // The list is complete, so yield it.
     327           26 :                     break;
     328           26 :                 };
     329           26 : 
     330           26 :                 let mut res = Listing::default();
     331           26 :                 let entry = match entry {
     332           26 :                     Ok(entry) => entry,
     333           26 :                     Err(e) => {
     334           26 :                         // The error is potentially retryable, so we must rewind the loop after yielding.
     335           26 :                         yield Err(e);
     336           26 :                         continue;
     337           26 :                     }
     338           26 :                 };
     339           26 :                 next_marker = entry.continuation();
     340           26 :                 let prefix_iter = entry
     341           26 :                     .blobs
     342           26 :                     .prefixes()
     343           52 :                     .map(|prefix| self.name_to_relative_path(&prefix.name));
     344           26 :                 res.prefixes.extend(prefix_iter);
     345           26 : 
     346           26 :                 let blob_iter = entry
     347           26 :                     .blobs
     348           26 :                     .blobs()
     349          197 :                     .map(|k| ListingObject{
     350          197 :                         key: self.name_to_relative_path(&k.name),
     351          197 :                         last_modified: k.properties.last_modified.into(),
     352          197 :                         size: k.properties.content_length,
     353          197 :                     }
     354           26 :                     );
     355           26 : 
     356           26 :                 for key in blob_iter {
     357           26 :                     res.keys.push(key);
     358           26 : 
     359           26 :                     if let Some(mut mk) = max_keys {
     360           26 :                         assert!(mk > 0);
     361           26 :                         mk -= 1;
     362           26 :                         if mk == 0 {
     363           26 :                             yield Ok(res); // limit reached
     364           26 :                             break 'outer;
     365           26 :                         }
     366           26 :                         max_keys = Some(mk);
     367           26 :                     }
     368           26 :                 }
     369           26 :                 yield Ok(res);
     370           26 : 
     371           26 :                 // We are done here
     372           26 :                 if next_marker.is_none() {
     373           26 :                     break;
     374           26 :                 }
     375           26 :             }
     376           26 :         }
     377           26 :     }
     378              : 
     379            3 :     async fn head_object(
     380            3 :         &self,
     381            3 :         key: &RemotePath,
     382            3 :         cancel: &CancellationToken,
     383            3 :     ) -> Result<ListingObject, DownloadError> {
     384            3 :         let kind = RequestKind::Head;
     385            3 :         let _permit = self.permit(kind, cancel).await?;
     386              : 
     387            3 :         let started_at = start_measuring_requests(kind);
     388            3 : 
     389            3 :         let blob_client = self.client.blob_client(self.relative_path_to_name(key));
     390            3 :         let properties_future = blob_client.get_properties().into_future();
     391            3 : 
     392            3 :         let properties_future = tokio::time::timeout(self.timeout, properties_future);
     393              : 
     394            3 :         let res = tokio::select! {
     395            3 :             res = properties_future => res,
     396            3 :             _ = cancel.cancelled() => return Err(TimeoutOrCancel::Cancel.into()),
     397              :         };
     398              : 
     399            3 :         if let Ok(inner) = &res {
     400            3 :             // do not incl. timeouts as errors in metrics but cancellations
     401            3 :             let started_at = ScopeGuard::into_inner(started_at);
     402            3 :             crate::metrics::BUCKET_METRICS
     403            3 :                 .req_seconds
     404            3 :                 .observe_elapsed(kind, inner, started_at);
     405            3 :         }
     406              : 
     407            3 :         let data = match res {
     408            2 :             Ok(Ok(data)) => Ok(data),
     409            1 :             Ok(Err(sdk)) => Err(to_download_error(sdk)),
     410            0 :             Err(_timeout) => Err(DownloadError::Timeout),
     411            1 :         }?;
     412              : 
     413            2 :         let properties = data.blob.properties;
     414            2 :         Ok(ListingObject {
     415            2 :             key: key.to_owned(),
     416            2 :             last_modified: SystemTime::from(properties.last_modified),
     417            2 :             size: properties.content_length,
     418            2 :         })
     419            3 :     }
     420              : 
     421           93 :     async fn upload(
     422           93 :         &self,
     423           93 :         from: impl Stream<Item = std::io::Result<Bytes>> + Send + Sync + 'static,
     424           93 :         data_size_bytes: usize,
     425           93 :         to: &RemotePath,
     426           93 :         metadata: Option<StorageMetadata>,
     427           93 :         cancel: &CancellationToken,
     428           93 :     ) -> anyhow::Result<()> {
     429           93 :         let kind = RequestKind::Put;
     430           93 :         let _permit = self.permit(kind, cancel).await?;
     431              : 
     432           93 :         let started_at = start_measuring_requests(kind);
     433           93 : 
     434           93 :         let op = async {
     435           93 :             let blob_client = self.client.blob_client(self.relative_path_to_name(to));
     436           93 : 
     437           93 :             let from: Pin<Box<dyn Stream<Item = std::io::Result<Bytes>> + Send + Sync + 'static>> =
     438           93 :                 Box::pin(from);
     439           93 : 
     440           93 :             let from = NonSeekableStream::new(from, data_size_bytes);
     441           93 : 
     442           93 :             let body = azure_core::Body::SeekableStream(Box::new(from));
     443           93 : 
     444           93 :             let mut builder = blob_client.put_block_blob(body);
     445              : 
     446           93 :             if let Some(metadata) = metadata {
     447            0 :                 builder = builder.metadata(to_azure_metadata(metadata));
     448           93 :             }
     449              : 
     450           93 :             let fut = builder.into_future();
     451           93 :             let fut = tokio::time::timeout(self.timeout, fut);
     452           93 : 
     453          556 :             match fut.await {
     454           93 :                 Ok(Ok(_response)) => Ok(()),
     455            0 :                 Ok(Err(azure)) => Err(azure.into()),
     456            0 :                 Err(_timeout) => Err(TimeoutOrCancel::Timeout.into()),
     457              :             }
     458           93 :         };
     459              : 
     460           93 :         let res = tokio::select! {
     461           93 :             res = op => res,
     462           93 :             _ = cancel.cancelled() => return Err(TimeoutOrCancel::Cancel.into()),
     463              :         };
     464              : 
     465           93 :         let outcome = match res {
     466           93 :             Ok(_) => AttemptOutcome::Ok,
     467            0 :             Err(_) => AttemptOutcome::Err,
     468              :         };
     469           93 :         let started_at = ScopeGuard::into_inner(started_at);
     470           93 :         crate::metrics::BUCKET_METRICS
     471           93 :             .req_seconds
     472           93 :             .observe_elapsed(kind, outcome, started_at);
     473           93 : 
     474           93 :         res
     475           93 :     }
     476              : 
     477           11 :     async fn download(
     478           11 :         &self,
     479           11 :         from: &RemotePath,
     480           11 :         opts: &DownloadOpts,
     481           11 :         cancel: &CancellationToken,
     482           11 :     ) -> Result<Download, DownloadError> {
     483           11 :         let blob_client = self.client.blob_client(self.relative_path_to_name(from));
     484           11 : 
     485           11 :         let mut builder = blob_client.get();
     486              : 
     487           11 :         if let Some(ref etag) = opts.etag {
     488            3 :             builder = builder.if_match(IfMatchCondition::NotMatch(etag.to_string()))
     489            8 :         }
     490              : 
     491           11 :         if let Some((start, end)) = opts.byte_range() {
     492            5 :             builder = builder.range(match end {
     493            3 :                 Some(end) => Range::Range(start..end),
     494            2 :                 None => Range::RangeFrom(start..),
     495              :             });
     496            6 :         }
     497              : 
     498           58 :         self.download_for_builder(builder, cancel).await
     499           11 :     }
     500              : 
     501           86 :     async fn delete(&self, path: &RemotePath, cancel: &CancellationToken) -> anyhow::Result<()> {
     502           86 :         self.delete_objects(std::array::from_ref(path), cancel)
     503          432 :             .await
     504           86 :     }
     505              : 
     506           93 :     async fn delete_objects<'a>(
     507           93 :         &self,
     508           93 :         paths: &'a [RemotePath],
     509           93 :         cancel: &CancellationToken,
     510           93 :     ) -> anyhow::Result<()> {
     511           93 :         let kind = RequestKind::Delete;
     512           93 :         let _permit = self.permit(kind, cancel).await?;
     513           93 :         let started_at = start_measuring_requests(kind);
     514           93 : 
     515           93 :         let op = async {
     516              :             // TODO batch requests are not supported by the SDK
     517              :             // https://github.com/Azure/azure-sdk-for-rust/issues/1068
     518          205 :             for path in paths {
     519          112 :                 #[derive(Debug)]
     520          112 :                 enum AzureOrTimeout {
     521              :                     AzureError(azure_core::Error),
     522              :                     Timeout,
     523              :                     Cancel,
     524          112 :                 }
     525          112 :                 impl Display for AzureOrTimeout {
     526            0 :                     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     527            0 :                         write!(f, "{self:?}")
     528            0 :                     }
     529              :                 }
     530          112 :                 let warn_threshold = 3;
     531          112 :                 let max_retries = 5;
     532          112 :                 backoff::retry(
     533          112 :                     || async {
     534          112 :                         let blob_client = self.client.blob_client(self.relative_path_to_name(path));
     535          112 : 
     536          112 :                         let request = blob_client.delete().into_future();
     537              : 
     538          563 :                         let res = tokio::time::timeout(self.timeout, request).await;
     539              : 
     540          112 :                         match res {
     541           90 :                             Ok(Ok(_v)) => Ok(()),
     542           22 :                             Ok(Err(azure_err)) => {
     543           22 :                                 if let Some(http_err) = azure_err.as_http_error() {
     544           22 :                                     if http_err.status() == StatusCode::NotFound {
     545           22 :                                         return Ok(());
     546            0 :                                     }
     547            0 :                                 }
     548            0 :                                 Err(AzureOrTimeout::AzureError(azure_err))
     549              :                             }
     550            0 :                             Err(_elapsed) => Err(AzureOrTimeout::Timeout),
     551              :                         }
     552          224 :                     },
     553          112 :                     |err| match err {
     554            0 :                         AzureOrTimeout::AzureError(_) | AzureOrTimeout::Timeout => false,
     555            0 :                         AzureOrTimeout::Cancel => true,
     556          112 :                     },
     557          112 :                     warn_threshold,
     558          112 :                     max_retries,
     559          112 :                     "deleting remote object",
     560          112 :                     cancel,
     561          112 :                 )
     562          563 :                 .await
     563          112 :                 .ok_or_else(|| AzureOrTimeout::Cancel)
     564          112 :                 .and_then(|x| x)
     565          112 :                 .map_err(|e| match e {
     566            0 :                     AzureOrTimeout::AzureError(err) => anyhow::Error::from(err),
     567            0 :                     AzureOrTimeout::Timeout => TimeoutOrCancel::Timeout.into(),
     568            0 :                     AzureOrTimeout::Cancel => TimeoutOrCancel::Cancel.into(),
     569          112 :                 })?;
     570              :             }
     571           93 :             Ok(())
     572           93 :         };
     573              : 
     574           93 :         let res = tokio::select! {
     575           93 :             res = op => res,
     576           93 :             _ = cancel.cancelled() => return Err(TimeoutOrCancel::Cancel.into()),
     577              :         };
     578              : 
     579           93 :         let started_at = ScopeGuard::into_inner(started_at);
     580           93 :         crate::metrics::BUCKET_METRICS
     581           93 :             .req_seconds
     582           93 :             .observe_elapsed(kind, &res, started_at);
     583           93 :         res
     584           93 :     }
     585              : 
     586            1 :     async fn copy(
     587            1 :         &self,
     588            1 :         from: &RemotePath,
     589            1 :         to: &RemotePath,
     590            1 :         cancel: &CancellationToken,
     591            1 :     ) -> anyhow::Result<()> {
     592            1 :         let kind = RequestKind::Copy;
     593            1 :         let _permit = self.permit(kind, cancel).await?;
     594            1 :         let started_at = start_measuring_requests(kind);
     595            1 : 
     596            1 :         let timeout = tokio::time::sleep(self.timeout);
     597            1 : 
     598            1 :         let mut copy_status = None;
     599            1 : 
     600            1 :         let op = async {
     601            1 :             let blob_client = self.client.blob_client(self.relative_path_to_name(to));
     602              : 
     603            1 :             let source_url = format!(
     604            1 :                 "{}/{}",
     605            1 :                 self.client.url()?,
     606            1 :                 self.relative_path_to_name(from)
     607              :             );
     608              : 
     609            1 :             let builder = blob_client.copy(Url::from_str(&source_url)?);
     610            1 :             let copy = builder.into_future();
     611              : 
     612            5 :             let result = copy.await?;
     613              : 
     614            1 :             copy_status = Some(result.copy_status);
     615              :             loop {
     616            1 :                 match copy_status.as_ref().expect("we always set it to Some") {
     617              :                     CopyStatus::Aborted => {
     618            0 :                         anyhow::bail!("Received abort for copy from {from} to {to}.");
     619              :                     }
     620              :                     CopyStatus::Failed => {
     621            0 :                         anyhow::bail!("Received failure response for copy from {from} to {to}.");
     622              :                     }
     623            1 :                     CopyStatus::Success => return Ok(()),
     624            0 :                     CopyStatus::Pending => (),
     625            0 :                 }
     626            0 :                 // The copy is taking longer. Waiting a second and then re-trying.
     627            0 :                 // TODO estimate time based on copy_progress and adjust time based on that
     628            0 :                 tokio::time::sleep(Duration::from_millis(1000)).await;
     629            0 :                 let properties = blob_client.get_properties().into_future().await?;
     630            0 :                 let Some(status) = properties.blob.properties.copy_status else {
     631            0 :                     tracing::warn!("copy_status for copy is None!, from={from}, to={to}");
     632            0 :                     return Ok(());
     633              :                 };
     634            0 :                 copy_status = Some(status);
     635              :             }
     636            1 :         };
     637              : 
     638            1 :         let res = tokio::select! {
     639            1 :             res = op => res,
     640            1 :             _ = cancel.cancelled() => return Err(anyhow::Error::new(TimeoutOrCancel::Cancel)),
     641            1 :             _ = timeout => {
     642            0 :                 let e = anyhow::Error::new(TimeoutOrCancel::Timeout);
     643            0 :                 let e = e.context(format!("Timeout, last status: {copy_status:?}"));
     644            0 :                 Err(e)
     645              :             },
     646              :         };
     647              : 
     648            1 :         let started_at = ScopeGuard::into_inner(started_at);
     649            1 :         crate::metrics::BUCKET_METRICS
     650            1 :             .req_seconds
     651            1 :             .observe_elapsed(kind, &res, started_at);
     652            1 :         res
     653            1 :     }
     654              : 
     655            0 :     async fn time_travel_recover(
     656            0 :         &self,
     657            0 :         _prefix: Option<&RemotePath>,
     658            0 :         _timestamp: SystemTime,
     659            0 :         _done_if_after: SystemTime,
     660            0 :         _cancel: &CancellationToken,
     661            0 :     ) -> Result<(), TimeTravelError> {
     662            0 :         // TODO use Azure point in time recovery feature for this
     663            0 :         // https://learn.microsoft.com/en-us/azure/storage/blobs/point-in-time-restore-overview
     664            0 :         Err(TimeTravelError::Unimplemented)
     665            0 :     }
     666              : }
     667              : 
     668              : pin_project_lite::pin_project! {
     669              :     /// Hack to work around not being able to stream once with azure sdk.
     670              :     ///
     671              :     /// Azure sdk clones streams around with the assumption that they are like
     672              :     /// `Arc<tokio::fs::File>` (except not supporting tokio), however our streams are not like
     673              :     /// that. For example for an `index_part.json` we just have a single chunk of [`Bytes`]
     674              :     /// representing the whole serialized vec. It could be trivially cloneable and "semi-trivially"
     675              :     /// seekable, but we can also just re-try the request easier.
     676              :     #[project = NonSeekableStreamProj]
     677              :     enum NonSeekableStream<S> {
     678              :         /// A stream wrappers initial form.
     679              :         ///
     680              :         /// Mutex exists to allow moving when cloning. If the sdk changes to do less than 1
     681              :         /// clone before first request, then this must be changed.
     682              :         Initial {
     683              :             inner: std::sync::Mutex<Option<tokio_util::compat::Compat<tokio_util::io::StreamReader<S, Bytes>>>>,
     684              :             len: usize,
     685              :         },
     686              :         /// The actually readable variant, produced by cloning the Initial variant.
     687              :         ///
     688              :         /// The sdk currently always clones once, even without retry policy.
     689              :         Actual {
     690              :             #[pin]
     691              :             inner: tokio_util::compat::Compat<tokio_util::io::StreamReader<S, Bytes>>,
     692              :             len: usize,
     693              :             read_any: bool,
     694              :         },
     695              :         /// Most likely unneeded, but left to make life easier, in case more clones are added.
     696              :         Cloned {
     697              :             len_was: usize,
     698              :         }
     699              :     }
     700              : }
     701              : 
     702              : impl<S> NonSeekableStream<S>
     703              : where
     704              :     S: Stream<Item = std::io::Result<Bytes>> + Send + Sync + 'static,
     705              : {
     706           93 :     fn new(inner: S, len: usize) -> NonSeekableStream<S> {
     707              :         use tokio_util::compat::TokioAsyncReadCompatExt;
     708              : 
     709           93 :         let inner = tokio_util::io::StreamReader::new(inner).compat();
     710           93 :         let inner = Some(inner);
     711           93 :         let inner = std::sync::Mutex::new(inner);
     712           93 :         NonSeekableStream::Initial { inner, len }
     713           93 :     }
     714              : }
     715              : 
     716              : impl<S> std::fmt::Debug for NonSeekableStream<S> {
     717            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     718            0 :         match self {
     719            0 :             Self::Initial { len, .. } => f.debug_struct("Initial").field("len", len).finish(),
     720            0 :             Self::Actual { len, .. } => f.debug_struct("Actual").field("len", len).finish(),
     721            0 :             Self::Cloned { len_was, .. } => f.debug_struct("Cloned").field("len", len_was).finish(),
     722              :         }
     723            0 :     }
     724              : }
     725              : 
     726              : impl<S> futures::io::AsyncRead for NonSeekableStream<S>
     727              : where
     728              :     S: Stream<Item = std::io::Result<Bytes>>,
     729              : {
     730           93 :     fn poll_read(
     731           93 :         self: std::pin::Pin<&mut Self>,
     732           93 :         cx: &mut std::task::Context<'_>,
     733           93 :         buf: &mut [u8],
     734           93 :     ) -> std::task::Poll<std::io::Result<usize>> {
     735           93 :         match self.project() {
     736              :             NonSeekableStreamProj::Actual {
     737           93 :                 inner, read_any, ..
     738           93 :             } => {
     739           93 :                 *read_any = true;
     740           93 :                 inner.poll_read(cx, buf)
     741              :             }
     742              :             // NonSeekableStream::Initial does not support reading because it is just much easier
     743              :             // to have the mutex in place where one does not poll the contents, or that's how it
     744              :             // seemed originally. If there is a version upgrade which changes the cloning, then
     745              :             // that support needs to be hacked in.
     746              :             //
     747              :             // including {self:?} into the message would be useful, but unsure how to unproject.
     748            0 :             _ => std::task::Poll::Ready(Err(std::io::Error::new(
     749            0 :                 std::io::ErrorKind::Other,
     750            0 :                 "cloned or initial values cannot be read",
     751            0 :             ))),
     752              :         }
     753           93 :     }
     754              : }
     755              : 
     756              : impl<S> Clone for NonSeekableStream<S> {
     757              :     /// Weird clone implementation exists to support the sdk doing cloning before issuing the first
     758              :     /// request, see type documentation.
     759           93 :     fn clone(&self) -> Self {
     760              :         use NonSeekableStream::*;
     761              : 
     762           93 :         match self {
     763           93 :             Initial { inner, len } => {
     764           93 :                 if let Some(inner) = inner.lock().unwrap().take() {
     765           93 :                     Actual {
     766           93 :                         inner,
     767           93 :                         len: *len,
     768           93 :                         read_any: false,
     769           93 :                     }
     770              :                 } else {
     771            0 :                     Self::Cloned { len_was: *len }
     772              :                 }
     773              :             }
     774            0 :             Actual { len, .. } => Cloned { len_was: *len },
     775            0 :             Cloned { len_was } => Cloned { len_was: *len_was },
     776              :         }
     777           93 :     }
     778              : }
     779              : 
     780              : #[async_trait::async_trait]
     781              : impl<S> azure_core::SeekableStream for NonSeekableStream<S>
     782              : where
     783              :     S: Stream<Item = std::io::Result<Bytes>> + Unpin + Send + Sync + 'static,
     784              : {
     785            0 :     async fn reset(&mut self) -> azure_core::error::Result<()> {
     786              :         use NonSeekableStream::*;
     787              : 
     788            0 :         let msg = match self {
     789            0 :             Initial { inner, .. } => {
     790            0 :                 if inner.get_mut().unwrap().is_some() {
     791            0 :                     return Ok(());
     792              :                 } else {
     793            0 :                     "reset after first clone is not supported"
     794              :                 }
     795              :             }
     796            0 :             Actual { read_any, .. } if !*read_any => return Ok(()),
     797            0 :             Actual { .. } => "reset after reading is not supported",
     798            0 :             Cloned { .. } => "reset after second clone is not supported",
     799              :         };
     800            0 :         Err(azure_core::error::Error::new(
     801            0 :             azure_core::error::ErrorKind::Io,
     802            0 :             std::io::Error::new(std::io::ErrorKind::Other, msg),
     803            0 :         ))
     804            0 :     }
     805              : 
     806              :     // Note: it is not documented if this should be the total or remaining length, total passes the
     807              :     // tests.
     808           93 :     fn len(&self) -> usize {
     809              :         use NonSeekableStream::*;
     810           93 :         match self {
     811           93 :             Initial { len, .. } => *len,
     812            0 :             Actual { len, .. } => *len,
     813            0 :             Cloned { len_was, .. } => *len_was,
     814              :         }
     815           93 :     }
     816              : }
        

Generated by: LCOV version 2.1-beta