LCOV - code coverage report
Current view: top level - libs/remote_storage/src - azure_blob.rs (source / functions) Coverage Total Hit
Test: 691a4c28fe7169edd60b367c52d448a0a6605f1f.info Lines: 19.6 % 424 83
Test Date: 2024-05-10 13:18:37 Functions: 15.7 % 70 11

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

Generated by: LCOV version 2.1-beta