LCOV - code coverage report
Current view: top level - pageserver/src/tenant/remote_timeline_client - download.rs (source / functions) Coverage Total Hit
Test: f081ec316c96fa98335efd15ef501745aa4f015d.info Lines: 86.6 % 366 317
Test Date: 2024-06-25 15:11:17 Functions: 54.4 % 79 43

            Line data    Source code
       1              : //! Helper functions to download files from remote storage with a RemoteStorage
       2              : //!
       3              : //! The functions in this module retry failed operations automatically, according
       4              : //! to the FAILED_DOWNLOAD_RETRIES constant.
       5              : 
       6              : use std::collections::HashSet;
       7              : use std::future::Future;
       8              : use std::str::FromStr;
       9              : 
      10              : use anyhow::{anyhow, Context};
      11              : use camino::{Utf8Path, Utf8PathBuf};
      12              : use pageserver_api::shard::TenantShardId;
      13              : use tokio::fs::{self, File, OpenOptions};
      14              : use tokio::io::{AsyncSeekExt, AsyncWriteExt};
      15              : use tokio_util::io::StreamReader;
      16              : use tokio_util::sync::CancellationToken;
      17              : use tracing::warn;
      18              : use utils::backoff;
      19              : 
      20              : use crate::config::PageServerConf;
      21              : use crate::context::RequestContext;
      22              : use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
      23              : use crate::tenant::remote_timeline_client::{remote_layer_path, remote_timelines_path};
      24              : use crate::tenant::storage_layer::LayerName;
      25              : use crate::tenant::Generation;
      26              : use crate::virtual_file::{on_fatal_io_error, MaybeFatalIo, VirtualFile};
      27              : use crate::TEMP_FILE_SUFFIX;
      28              : use remote_storage::{DownloadError, GenericRemoteStorage, ListingMode, RemotePath};
      29              : use utils::crashsafe::path_with_suffix_extension;
      30              : use utils::id::{TenantId, TimelineId};
      31              : use utils::pausable_failpoint;
      32              : 
      33              : use super::index::{IndexPart, LayerFileMetadata};
      34              : use super::{
      35              :     parse_remote_index_path, remote_index_path, remote_initdb_archive_path,
      36              :     remote_initdb_preserved_archive_path, remote_tenant_path, FAILED_DOWNLOAD_WARN_THRESHOLD,
      37              :     FAILED_REMOTE_OP_RETRIES, INITDB_PATH,
      38              : };
      39              : 
      40              : ///
      41              : /// If 'metadata' is given, we will validate that the downloaded file's size matches that
      42              : /// in the metadata. (In the future, we might do more cross-checks, like CRC validation)
      43              : ///
      44              : /// Returns the size of the downloaded file.
      45              : #[allow(clippy::too_many_arguments)]
      46            6 : pub async fn download_layer_file<'a>(
      47            6 :     conf: &'static PageServerConf,
      48            6 :     storage: &'a GenericRemoteStorage,
      49            6 :     tenant_shard_id: TenantShardId,
      50            6 :     timeline_id: TimelineId,
      51            6 :     layer_file_name: &'a LayerName,
      52            6 :     layer_metadata: &'a LayerFileMetadata,
      53            6 :     local_path: &Utf8Path,
      54            6 :     cancel: &CancellationToken,
      55            6 :     ctx: &RequestContext,
      56            6 : ) -> Result<u64, DownloadError> {
      57            6 :     debug_assert_current_span_has_tenant_and_timeline_id();
      58            6 : 
      59            6 :     let timeline_path = conf.timeline_path(&tenant_shard_id, &timeline_id);
      60            6 : 
      61            6 :     let remote_path = remote_layer_path(
      62            6 :         &tenant_shard_id.tenant_id,
      63            6 :         &timeline_id,
      64            6 :         layer_metadata.shard,
      65            6 :         layer_file_name,
      66            6 :         layer_metadata.generation,
      67            6 :     );
      68            6 : 
      69            6 :     // Perform a rename inspired by durable_rename from file_utils.c.
      70            6 :     // The sequence:
      71            6 :     //     write(tmp)
      72            6 :     //     fsync(tmp)
      73            6 :     //     rename(tmp, new)
      74            6 :     //     fsync(new)
      75            6 :     //     fsync(parent)
      76            6 :     // For more context about durable_rename check this email from postgres mailing list:
      77            6 :     // https://www.postgresql.org/message-id/56583BDD.9060302@2ndquadrant.com
      78            6 :     // If pageserver crashes the temp file will be deleted on startup and re-downloaded.
      79            6 :     let temp_file_path = path_with_suffix_extension(local_path, TEMP_DOWNLOAD_EXTENSION);
      80              : 
      81            6 :     let bytes_amount = download_retry(
      82           73 :         || async { download_object(storage, &remote_path, &temp_file_path, cancel, ctx).await },
      83            6 :         &format!("download {remote_path:?}"),
      84            6 :         cancel,
      85            6 :     )
      86           73 :     .await?;
      87              : 
      88            6 :     let expected = layer_metadata.file_size;
      89            6 :     if expected != bytes_amount {
      90            0 :         return Err(DownloadError::Other(anyhow!(
      91            0 :             "According to layer file metadata should have downloaded {expected} bytes but downloaded {bytes_amount} bytes into file {temp_file_path:?}",
      92            0 :         )));
      93            6 :     }
      94            6 : 
      95            6 :     fail::fail_point!("remote-storage-download-pre-rename", |_| {
      96            0 :         Err(DownloadError::Other(anyhow!(
      97            0 :             "remote-storage-download-pre-rename failpoint triggered"
      98            0 :         )))
      99            6 :     });
     100              : 
     101            6 :     fs::rename(&temp_file_path, &local_path)
     102            5 :         .await
     103            6 :         .with_context(|| format!("rename download layer file to {local_path}"))
     104            6 :         .map_err(DownloadError::Other)?;
     105              : 
     106              :     // We use fatal_err() below because the after the rename above,
     107              :     // the in-memory state of the filesystem already has the layer file in its final place,
     108              :     // and subsequent pageserver code could think it's durable while it really isn't.
     109            6 :     let work = {
     110            6 :         let ctx = ctx.detached_child(ctx.task_kind(), ctx.download_behavior());
     111            6 :         async move {
     112            6 :             let timeline_dir = VirtualFile::open(&timeline_path, &ctx)
     113            3 :                 .await
     114            6 :                 .fatal_err("VirtualFile::open for timeline dir fsync");
     115            6 :             timeline_dir
     116            6 :                 .sync_all()
     117            3 :                 .await
     118            6 :                 .fatal_err("VirtualFile::sync_all timeline dir");
     119            6 :         }
     120              :     };
     121            6 :     crate::virtual_file::io_engine::get()
     122            6 :         .spawn_blocking_and_block_on_if_std(work)
     123            9 :         .await;
     124              : 
     125            6 :     tracing::debug!("download complete: {local_path}");
     126              : 
     127            6 :     Ok(bytes_amount)
     128            6 : }
     129              : 
     130              : /// Download the object `src_path` in the remote `storage` to local path `dst_path`.
     131              : ///
     132              : /// If Ok() is returned, the download succeeded and the inode & data have been made durable.
     133              : /// (Note that the directory entry for the inode is not made durable.)
     134              : /// The file size in bytes is returned.
     135              : ///
     136              : /// If Err() is returned, there was some error. The file at `dst_path` has been unlinked.
     137              : /// The unlinking has _not_ been made durable.
     138            6 : async fn download_object<'a>(
     139            6 :     storage: &'a GenericRemoteStorage,
     140            6 :     src_path: &RemotePath,
     141            6 :     dst_path: &Utf8PathBuf,
     142            6 :     cancel: &CancellationToken,
     143            6 :     #[cfg_attr(target_os = "macos", allow(unused_variables))] ctx: &RequestContext,
     144            6 : ) -> Result<u64, DownloadError> {
     145            6 :     let res = match crate::virtual_file::io_engine::get() {
     146            0 :         crate::virtual_file::io_engine::IoEngine::NotSet => panic!("unset"),
     147              :         crate::virtual_file::io_engine::IoEngine::StdFs => {
     148            3 :             async {
     149            3 :                 let destination_file = tokio::fs::File::create(dst_path)
     150            3 :                     .await
     151            3 :                     .with_context(|| format!("create a destination file for layer '{dst_path}'"))
     152            3 :                     .map_err(DownloadError::Other)?;
     153              : 
     154            5 :                 let download = storage.download(src_path, cancel).await?;
     155              : 
     156              :                 pausable_failpoint!("before-downloading-layer-stream-pausable");
     157              : 
     158            3 :                 let mut buf_writer =
     159            3 :                     tokio::io::BufWriter::with_capacity(super::BUFFER_SIZE, destination_file);
     160            3 : 
     161            3 :                 let mut reader = tokio_util::io::StreamReader::new(download.download_stream);
     162              : 
     163           21 :                 let bytes_amount = tokio::io::copy_buf(&mut reader, &mut buf_writer).await?;
     164            3 :                 buf_writer.flush().await?;
     165              : 
     166            3 :                 let mut destination_file = buf_writer.into_inner();
     167            3 : 
     168            3 :                 // Tokio doc here: https://docs.rs/tokio/1.17.0/tokio/fs/struct.File.html states that:
     169            3 :                 // A file will not be closed immediately when it goes out of scope if there are any IO operations
     170            3 :                 // that have not yet completed. To ensure that a file is closed immediately when it is dropped,
     171            3 :                 // you should call flush before dropping it.
     172            3 :                 //
     173            3 :                 // From the tokio code I see that it waits for pending operations to complete. There shouldt be any because
     174            3 :                 // we assume that `destination_file` file is fully written. I e there is no pending .write(...).await operations.
     175            3 :                 // But for additional safety lets check/wait for any pending operations.
     176            3 :                 destination_file
     177            3 :                     .flush()
     178            0 :                     .await
     179            3 :                     .with_context(|| format!("flush source file at {dst_path}"))
     180            3 :                     .map_err(DownloadError::Other)?;
     181              : 
     182              :                 // not using sync_data because it can lose file size update
     183            3 :                 destination_file
     184            3 :                     .sync_all()
     185            3 :                     .await
     186            3 :                     .with_context(|| format!("failed to fsync source file at {dst_path}"))
     187            3 :                     .map_err(DownloadError::Other)?;
     188              : 
     189            3 :                 Ok(bytes_amount)
     190            3 :             }
     191           35 :             .await
     192              :         }
     193              :         #[cfg(target_os = "linux")]
     194              :         crate::virtual_file::io_engine::IoEngine::TokioEpollUring => {
     195              :             use crate::virtual_file::owned_buffers_io::{self, util::size_tracking_writer};
     196              :             use bytes::BytesMut;
     197            3 :             async {
     198            3 :                 let destination_file = VirtualFile::create(dst_path, ctx)
     199            3 :                     .await
     200            3 :                     .with_context(|| format!("create a destination file for layer '{dst_path}'"))
     201            3 :                     .map_err(DownloadError::Other)?;
     202              : 
     203            5 :                 let mut download = storage.download(src_path, cancel).await?;
     204              : 
     205              :                 pausable_failpoint!("before-downloading-layer-stream-pausable");
     206              : 
     207              :                 // TODO: use vectored write (writev) once supported by tokio-epoll-uring.
     208              :                 // There's chunks_vectored() on the stream.
     209            3 :                 let (bytes_amount, destination_file) = async {
     210            3 :                     let size_tracking = size_tracking_writer::Writer::new(destination_file);
     211            3 :                     let mut buffered = owned_buffers_io::write::BufferedWriter::<BytesMut, _>::new(
     212            3 :                         size_tracking,
     213            3 :                         BytesMut::with_capacity(super::BUFFER_SIZE),
     214            3 :                     );
     215           18 :                     while let Some(res) =
     216           21 :                         futures::StreamExt::next(&mut download.download_stream).await
     217              :                     {
     218           18 :                         let chunk = match res {
     219           18 :                             Ok(chunk) => chunk,
     220            0 :                             Err(e) => return Err(e),
     221              :                         };
     222           18 :                         buffered
     223           18 :                             .write_buffered(tokio_epoll_uring::BoundedBuf::slice_full(chunk), ctx)
     224            0 :                             .await?;
     225              :                     }
     226            3 :                     let size_tracking = buffered.flush_and_into_inner(ctx).await?;
     227            3 :                     Ok(size_tracking.into_inner())
     228            3 :                 }
     229           24 :                 .await?;
     230              : 
     231              :                 // not using sync_data because it can lose file size update
     232            3 :                 destination_file
     233            3 :                     .sync_all()
     234            3 :                     .await
     235            3 :                     .with_context(|| format!("failed to fsync source file at {dst_path}"))
     236            3 :                     .map_err(DownloadError::Other)?;
     237              : 
     238            3 :                 Ok(bytes_amount)
     239            3 :             }
     240           38 :             .await
     241              :         }
     242              :     };
     243              : 
     244              :     // in case the download failed, clean up
     245            6 :     match res {
     246            6 :         Ok(bytes_amount) => Ok(bytes_amount),
     247            0 :         Err(e) => {
     248            0 :             if let Err(e) = tokio::fs::remove_file(dst_path).await {
     249            0 :                 if e.kind() != std::io::ErrorKind::NotFound {
     250            0 :                     on_fatal_io_error(&e, &format!("Removing temporary file {dst_path}"));
     251            0 :                 }
     252            0 :             }
     253            0 :             Err(e)
     254              :         }
     255              :     }
     256            6 : }
     257              : 
     258              : const TEMP_DOWNLOAD_EXTENSION: &str = "temp_download";
     259              : 
     260            0 : pub(crate) fn is_temp_download_file(path: &Utf8Path) -> bool {
     261            0 :     let extension = path.extension();
     262            0 :     match extension {
     263            0 :         Some(TEMP_DOWNLOAD_EXTENSION) => true,
     264            0 :         Some(_) => false,
     265            0 :         None => false,
     266              :     }
     267            0 : }
     268              : 
     269          159 : async fn list_identifiers<T>(
     270          159 :     storage: &GenericRemoteStorage,
     271          159 :     prefix: RemotePath,
     272          159 :     cancel: CancellationToken,
     273          159 : ) -> anyhow::Result<(HashSet<T>, HashSet<String>)>
     274          159 : where
     275          159 :     T: FromStr + Eq + std::hash::Hash,
     276          159 : {
     277          159 :     let listing = download_retry_forever(
     278          159 :         || storage.list(Some(&prefix), ListingMode::WithDelimiter, None, &cancel),
     279          159 :         &format!("list identifiers in prefix {prefix}"),
     280          159 :         &cancel,
     281          159 :     )
     282          614 :     .await?;
     283              : 
     284          159 :     let mut parsed_ids = HashSet::new();
     285          159 :     let mut other_prefixes = HashSet::new();
     286              : 
     287          165 :     for id_remote_storage_key in listing.prefixes {
     288            6 :         let object_name = id_remote_storage_key.object_name().ok_or_else(|| {
     289            0 :             anyhow::anyhow!("failed to get object name for key {id_remote_storage_key}")
     290            6 :         })?;
     291              : 
     292            6 :         match object_name.parse::<T>() {
     293            6 :             Ok(t) => parsed_ids.insert(t),
     294            0 :             Err(_) => other_prefixes.insert(object_name.to_string()),
     295              :         };
     296              :     }
     297              : 
     298          159 :     for key in listing.keys {
     299            0 :         let object_name = key
     300            0 :             .object_name()
     301            0 :             .ok_or_else(|| anyhow::anyhow!("object name for key {key}"))?;
     302            0 :         other_prefixes.insert(object_name.to_string());
     303              :     }
     304              : 
     305          159 :     Ok((parsed_ids, other_prefixes))
     306          159 : }
     307              : 
     308              : /// List shards of given tenant in remote storage
     309            0 : pub(crate) async fn list_remote_tenant_shards(
     310            0 :     storage: &GenericRemoteStorage,
     311            0 :     tenant_id: TenantId,
     312            0 :     cancel: CancellationToken,
     313            0 : ) -> anyhow::Result<(HashSet<TenantShardId>, HashSet<String>)> {
     314            0 :     let remote_path = remote_tenant_path(&TenantShardId::unsharded(tenant_id));
     315            0 :     list_identifiers::<TenantShardId>(storage, remote_path, cancel).await
     316            0 : }
     317              : 
     318              : /// List timelines of given tenant shard in remote storage
     319          159 : pub async fn list_remote_timelines(
     320          159 :     storage: &GenericRemoteStorage,
     321          159 :     tenant_shard_id: TenantShardId,
     322          159 :     cancel: CancellationToken,
     323          159 : ) -> anyhow::Result<(HashSet<TimelineId>, HashSet<String>)> {
     324          159 :     fail::fail_point!("storage-sync-list-remote-timelines", |_| {
     325            0 :         anyhow::bail!("storage-sync-list-remote-timelines");
     326          159 :     });
     327              : 
     328          159 :     let remote_path = remote_timelines_path(&tenant_shard_id).add_trailing_slash();
     329          614 :     list_identifiers::<TimelineId>(storage, remote_path, cancel).await
     330          159 : }
     331              : 
     332           34 : async fn do_download_index_part(
     333           34 :     storage: &GenericRemoteStorage,
     334           34 :     tenant_shard_id: &TenantShardId,
     335           34 :     timeline_id: &TimelineId,
     336           34 :     index_generation: Generation,
     337           34 :     cancel: &CancellationToken,
     338           34 : ) -> Result<(IndexPart, Generation), DownloadError> {
     339           34 :     let remote_path = remote_index_path(tenant_shard_id, timeline_id, index_generation);
     340              : 
     341           34 :     let index_part_bytes = download_retry_forever(
     342           34 :         || async {
     343           54 :             let download = storage.download(&remote_path, cancel).await?;
     344           34 : 
     345           34 :             let mut bytes = Vec::new();
     346           20 : 
     347           20 :             let stream = download.download_stream;
     348           20 :             let mut stream = StreamReader::new(stream);
     349           20 : 
     350           39 :             tokio::io::copy_buf(&mut stream, &mut bytes).await?;
     351           34 : 
     352           34 :             Ok(bytes)
     353           34 :         },
     354           34 :         &format!("download {remote_path:?}"),
     355           34 :         cancel,
     356           34 :     )
     357           93 :     .await?;
     358              : 
     359           20 :     let index_part: IndexPart = serde_json::from_slice(&index_part_bytes)
     360           20 :         .with_context(|| format!("deserialize index part file at {remote_path:?}"))
     361           20 :         .map_err(DownloadError::Other)?;
     362              : 
     363           20 :     Ok((index_part, index_generation))
     364           34 : }
     365              : 
     366              : /// index_part.json objects are suffixed with a generation number, so we cannot
     367              : /// directly GET the latest index part without doing some probing.
     368              : ///
     369              : /// In this function we probe for the most recent index in a generation <= our current generation.
     370              : /// See "Finding the remote indices for timelines" in docs/rfcs/025-generation-numbers.md
     371           40 : #[tracing::instrument(skip_all, fields(generation=?my_generation))]
     372              : pub(crate) async fn download_index_part(
     373              :     storage: &GenericRemoteStorage,
     374              :     tenant_shard_id: &TenantShardId,
     375              :     timeline_id: &TimelineId,
     376              :     my_generation: Generation,
     377              :     cancel: &CancellationToken,
     378              : ) -> Result<(IndexPart, Generation), DownloadError> {
     379              :     debug_assert_current_span_has_tenant_and_timeline_id();
     380              : 
     381              :     if my_generation.is_none() {
     382              :         // Operating without generations: just fetch the generation-less path
     383              :         return do_download_index_part(
     384              :             storage,
     385              :             tenant_shard_id,
     386              :             timeline_id,
     387              :             my_generation,
     388              :             cancel,
     389              :         )
     390              :         .await;
     391              :     }
     392              : 
     393              :     // Stale case: If we were intentionally attached in a stale generation, there may already be a remote
     394              :     // index in our generation.
     395              :     //
     396              :     // This is an optimization to avoid doing the listing for the general case below.
     397              :     let res =
     398              :         do_download_index_part(storage, tenant_shard_id, timeline_id, my_generation, cancel).await;
     399              :     match res {
     400              :         Ok(index_part) => {
     401              :             tracing::debug!(
     402              :                 "Found index_part from current generation (this is a stale attachment)"
     403              :             );
     404              :             return Ok(index_part);
     405              :         }
     406              :         Err(DownloadError::NotFound) => {}
     407              :         Err(e) => return Err(e),
     408              :     };
     409              : 
     410              :     // Typical case: the previous generation of this tenant was running healthily, and had uploaded
     411              :     // and index part.  We may safely start from this index without doing a listing, because:
     412              :     //  - We checked for current generation case above
     413              :     //  - generations > my_generation are to be ignored
     414              :     //  - any other indices that exist would have an older generation than `previous_gen`, and
     415              :     //    we want to find the most recent index from a previous generation.
     416              :     //
     417              :     // This is an optimization to avoid doing the listing for the general case below.
     418              :     let res = do_download_index_part(
     419              :         storage,
     420              :         tenant_shard_id,
     421              :         timeline_id,
     422              :         my_generation.previous(),
     423              :         cancel,
     424              :     )
     425              :     .await;
     426              :     match res {
     427              :         Ok(index_part) => {
     428              :             tracing::debug!("Found index_part from previous generation");
     429              :             return Ok(index_part);
     430              :         }
     431              :         Err(DownloadError::NotFound) => {
     432              :             tracing::debug!(
     433              :                 "No index_part found from previous generation, falling back to listing"
     434              :             );
     435              :         }
     436              :         Err(e) => {
     437              :             return Err(e);
     438              :         }
     439              :     }
     440              : 
     441              :     // General case/fallback: if there is no index at my_generation or prev_generation, then list all index_part.json
     442              :     // objects, and select the highest one with a generation <= my_generation.  Constructing the prefix is equivalent
     443              :     // to constructing a full index path with no generation, because the generation is a suffix.
     444              :     let index_prefix = remote_index_path(tenant_shard_id, timeline_id, Generation::none());
     445              : 
     446              :     let indices = download_retry(
     447            6 :         || async {
     448            6 :             storage
     449            6 :                 .list(Some(&index_prefix), ListingMode::NoDelimiter, None, cancel)
     450            6 :                 .await
     451            6 :         },
     452              :         "list index_part files",
     453              :         cancel,
     454              :     )
     455              :     .await?
     456              :     .keys;
     457              : 
     458              :     // General case logic for which index to use: the latest index whose generation
     459              :     // is <= our own.  See "Finding the remote indices for timelines" in docs/rfcs/025-generation-numbers.md
     460              :     let max_previous_generation = indices
     461              :         .into_iter()
     462              :         .filter_map(parse_remote_index_path)
     463           12 :         .filter(|g| g <= &my_generation)
     464              :         .max();
     465              : 
     466              :     match max_previous_generation {
     467              :         Some(g) => {
     468              :             tracing::debug!("Found index_part in generation {g:?}");
     469              :             do_download_index_part(storage, tenant_shard_id, timeline_id, g, cancel).await
     470              :         }
     471              :         None => {
     472              :             // Migration from legacy pre-generation state: we have a generation but no prior
     473              :             // attached pageservers did.  Try to load from a no-generation path.
     474              :             tracing::debug!("No index_part.json* found");
     475              :             do_download_index_part(
     476              :                 storage,
     477              :                 tenant_shard_id,
     478              :                 timeline_id,
     479              :                 Generation::none(),
     480              :                 cancel,
     481              :             )
     482              :             .await
     483              :         }
     484              :     }
     485              : }
     486              : 
     487            2 : pub(crate) async fn download_initdb_tar_zst(
     488            2 :     conf: &'static PageServerConf,
     489            2 :     storage: &GenericRemoteStorage,
     490            2 :     tenant_shard_id: &TenantShardId,
     491            2 :     timeline_id: &TimelineId,
     492            2 :     cancel: &CancellationToken,
     493            2 : ) -> Result<(Utf8PathBuf, File), DownloadError> {
     494            2 :     debug_assert_current_span_has_tenant_and_timeline_id();
     495            2 : 
     496            2 :     let remote_path = remote_initdb_archive_path(&tenant_shard_id.tenant_id, timeline_id);
     497            2 : 
     498            2 :     let remote_preserved_path =
     499            2 :         remote_initdb_preserved_archive_path(&tenant_shard_id.tenant_id, timeline_id);
     500            2 : 
     501            2 :     let timeline_path = conf.timelines_path(tenant_shard_id);
     502            2 : 
     503            2 :     if !timeline_path.exists() {
     504            0 :         tokio::fs::create_dir_all(&timeline_path)
     505            0 :             .await
     506            0 :             .with_context(|| format!("timeline dir creation {timeline_path}"))
     507            0 :             .map_err(DownloadError::Other)?;
     508            2 :     }
     509            2 :     let temp_path = timeline_path.join(format!(
     510            2 :         "{INITDB_PATH}.download-{timeline_id}.{TEMP_FILE_SUFFIX}"
     511            2 :     ));
     512              : 
     513            2 :     let file = download_retry(
     514            2 :         || async {
     515            2 :             let file = OpenOptions::new()
     516            2 :                 .create(true)
     517            2 :                 .truncate(true)
     518            2 :                 .read(true)
     519            2 :                 .write(true)
     520            2 :                 .open(&temp_path)
     521            2 :                 .await
     522            2 :                 .with_context(|| format!("tempfile creation {temp_path}"))
     523            2 :                 .map_err(DownloadError::Other)?;
     524            2 : 
     525            4 :             let download = match storage.download(&remote_path, cancel).await {
     526            2 :                 Ok(dl) => dl,
     527            2 :                 Err(DownloadError::NotFound) => {
     528            2 :                     storage.download(&remote_preserved_path, cancel).await?
     529            2 :                 }
     530            2 :                 Err(other) => Err(other)?,
     531            2 :             };
     532            2 :             let mut download = tokio_util::io::StreamReader::new(download.download_stream);
     533            2 :             let mut writer = tokio::io::BufWriter::with_capacity(super::BUFFER_SIZE, file);
     534            2 : 
     535          713 :             tokio::io::copy_buf(&mut download, &mut writer).await?;
     536            2 : 
     537            2 :             let mut file = writer.into_inner();
     538            2 : 
     539            2 :             file.seek(std::io::SeekFrom::Start(0))
     540            2 :                 .await
     541            2 :                 .with_context(|| format!("rewinding initdb.tar.zst at: {remote_path:?}"))
     542            2 :                 .map_err(DownloadError::Other)?;
     543            2 : 
     544            2 :             Ok(file)
     545            2 :         },
     546            2 :         &format!("download {remote_path}"),
     547            2 :         cancel,
     548            2 :     )
     549          721 :     .await
     550            2 :     .map_err(|e| {
     551              :         // Do a best-effort attempt at deleting the temporary file upon encountering an error.
     552              :         // We don't have async here nor do we want to pile on any extra errors.
     553            0 :         if let Err(e) = std::fs::remove_file(&temp_path) {
     554            0 :             if e.kind() != std::io::ErrorKind::NotFound {
     555            0 :                 warn!("error deleting temporary file {temp_path}: {e}");
     556            0 :             }
     557            0 :         }
     558            0 :         e
     559            2 :     })?;
     560              : 
     561            2 :     Ok((temp_path, file))
     562            2 : }
     563              : 
     564              : /// Helper function to handle retries for a download operation.
     565              : ///
     566              : /// Remote operations can fail due to rate limits (S3), spurious network
     567              : /// problems, or other external reasons. Retry FAILED_DOWNLOAD_RETRIES times,
     568              : /// with backoff.
     569              : ///
     570              : /// (See similar logic for uploads in `perform_upload_task`)
     571           14 : pub(super) async fn download_retry<T, O, F>(
     572           14 :     op: O,
     573           14 :     description: &str,
     574           14 :     cancel: &CancellationToken,
     575           14 : ) -> Result<T, DownloadError>
     576           14 : where
     577           14 :     O: FnMut() -> F,
     578           14 :     F: Future<Output = Result<T, DownloadError>>,
     579           14 : {
     580           14 :     backoff::retry(
     581           14 :         op,
     582           14 :         DownloadError::is_permanent,
     583           14 :         FAILED_DOWNLOAD_WARN_THRESHOLD,
     584           14 :         FAILED_REMOTE_OP_RETRIES,
     585           14 :         description,
     586           14 :         cancel,
     587           14 :     )
     588          800 :     .await
     589           14 :     .ok_or_else(|| DownloadError::Cancelled)
     590           14 :     .and_then(|x| x)
     591           14 : }
     592              : 
     593          193 : async fn download_retry_forever<T, O, F>(
     594          193 :     op: O,
     595          193 :     description: &str,
     596          193 :     cancel: &CancellationToken,
     597          193 : ) -> Result<T, DownloadError>
     598          193 : where
     599          193 :     O: FnMut() -> F,
     600          193 :     F: Future<Output = Result<T, DownloadError>>,
     601          193 : {
     602          193 :     backoff::retry(
     603          193 :         op,
     604          193 :         DownloadError::is_permanent,
     605          193 :         FAILED_DOWNLOAD_WARN_THRESHOLD,
     606          193 :         u32::MAX,
     607          193 :         description,
     608          193 :         cancel,
     609          193 :     )
     610          707 :     .await
     611          193 :     .ok_or_else(|| DownloadError::Cancelled)
     612          193 :     .and_then(|x| x)
     613          193 : }
        

Generated by: LCOV version 2.1-beta