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

Generated by: LCOV version 2.1-beta