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

Generated by: LCOV version 2.1-beta