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 78 : || async { download_object(storage, &remote_path, &temp_file_path, cancel, ctx).await },
83 6 : &format!("download {remote_path:?}"),
84 6 : cancel,
85 6 : )
86 78 : .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 6 : .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 6 : 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 24 : 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 39 : .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 4 : .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 39 : .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 174 : async fn list_identifiers<T>(
270 174 : storage: &GenericRemoteStorage,
271 174 : prefix: RemotePath,
272 174 : cancel: CancellationToken,
273 174 : ) -> anyhow::Result<(HashSet<T>, HashSet<String>)>
274 174 : where
275 174 : T: FromStr + Eq + std::hash::Hash,
276 174 : {
277 174 : let listing = download_retry_forever(
278 174 : || storage.list(Some(&prefix), ListingMode::WithDelimiter, None, &cancel),
279 174 : &format!("list identifiers in prefix {prefix}"),
280 174 : &cancel,
281 174 : )
282 683 : .await?;
283 :
284 174 : let mut parsed_ids = HashSet::new();
285 174 : let mut other_prefixes = HashSet::new();
286 :
287 180 : 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 174 : for object in listing.keys {
299 0 : let object_name = object
300 0 : .key
301 0 : .object_name()
302 0 : .ok_or_else(|| anyhow::anyhow!("object name for key {}", object.key))?;
303 0 : other_prefixes.insert(object_name.to_string());
304 : }
305 :
306 174 : Ok((parsed_ids, other_prefixes))
307 174 : }
308 :
309 : /// List shards of given tenant in remote storage
310 0 : pub(crate) async fn list_remote_tenant_shards(
311 0 : storage: &GenericRemoteStorage,
312 0 : tenant_id: TenantId,
313 0 : cancel: CancellationToken,
314 0 : ) -> anyhow::Result<(HashSet<TenantShardId>, HashSet<String>)> {
315 0 : let remote_path = remote_tenant_path(&TenantShardId::unsharded(tenant_id));
316 0 : list_identifiers::<TenantShardId>(storage, remote_path, cancel).await
317 0 : }
318 :
319 : /// List timelines of given tenant shard in remote storage
320 174 : pub async fn list_remote_timelines(
321 174 : storage: &GenericRemoteStorage,
322 174 : tenant_shard_id: TenantShardId,
323 174 : cancel: CancellationToken,
324 174 : ) -> anyhow::Result<(HashSet<TimelineId>, HashSet<String>)> {
325 174 : fail::fail_point!("storage-sync-list-remote-timelines", |_| {
326 0 : anyhow::bail!("storage-sync-list-remote-timelines");
327 174 : });
328 :
329 174 : let remote_path = remote_timelines_path(&tenant_shard_id).add_trailing_slash();
330 683 : list_identifiers::<TimelineId>(storage, remote_path, cancel).await
331 174 : }
332 :
333 34 : async fn do_download_index_part(
334 34 : storage: &GenericRemoteStorage,
335 34 : tenant_shard_id: &TenantShardId,
336 34 : timeline_id: &TimelineId,
337 34 : index_generation: Generation,
338 34 : cancel: &CancellationToken,
339 34 : ) -> Result<(IndexPart, Generation), DownloadError> {
340 34 : let remote_path = remote_index_path(tenant_shard_id, timeline_id, index_generation);
341 :
342 34 : let index_part_bytes = download_retry_forever(
343 34 : || async {
344 52 : let download = storage.download(&remote_path, cancel).await?;
345 34 :
346 34 : let mut bytes = Vec::new();
347 20 :
348 20 : let stream = download.download_stream;
349 20 : let mut stream = StreamReader::new(stream);
350 20 :
351 37 : tokio::io::copy_buf(&mut stream, &mut bytes).await?;
352 34 :
353 34 : Ok(bytes)
354 34 : },
355 34 : &format!("download {remote_path:?}"),
356 34 : cancel,
357 34 : )
358 89 : .await?;
359 :
360 20 : let index_part: IndexPart = serde_json::from_slice(&index_part_bytes)
361 20 : .with_context(|| format!("deserialize index part file at {remote_path:?}"))
362 20 : .map_err(DownloadError::Other)?;
363 :
364 20 : Ok((index_part, index_generation))
365 34 : }
366 :
367 : /// index_part.json objects are suffixed with a generation number, so we cannot
368 : /// directly GET the latest index part without doing some probing.
369 : ///
370 : /// In this function we probe for the most recent index in a generation <= our current generation.
371 : /// See "Finding the remote indices for timelines" in docs/rfcs/025-generation-numbers.md
372 40 : #[tracing::instrument(skip_all, fields(generation=?my_generation))]
373 : pub(crate) async fn download_index_part(
374 : storage: &GenericRemoteStorage,
375 : tenant_shard_id: &TenantShardId,
376 : timeline_id: &TimelineId,
377 : my_generation: Generation,
378 : cancel: &CancellationToken,
379 : ) -> Result<(IndexPart, Generation), DownloadError> {
380 : debug_assert_current_span_has_tenant_and_timeline_id();
381 :
382 : if my_generation.is_none() {
383 : // Operating without generations: just fetch the generation-less path
384 : return do_download_index_part(
385 : storage,
386 : tenant_shard_id,
387 : timeline_id,
388 : my_generation,
389 : cancel,
390 : )
391 : .await;
392 : }
393 :
394 : // Stale case: If we were intentionally attached in a stale generation, there may already be a remote
395 : // index in our generation.
396 : //
397 : // This is an optimization to avoid doing the listing for the general case below.
398 : let res =
399 : do_download_index_part(storage, tenant_shard_id, timeline_id, my_generation, cancel).await;
400 : match res {
401 : Ok(index_part) => {
402 : tracing::debug!(
403 : "Found index_part from current generation (this is a stale attachment)"
404 : );
405 : return Ok(index_part);
406 : }
407 : Err(DownloadError::NotFound) => {}
408 : Err(e) => return Err(e),
409 : };
410 :
411 : // Typical case: the previous generation of this tenant was running healthily, and had uploaded
412 : // and index part. We may safely start from this index without doing a listing, because:
413 : // - We checked for current generation case above
414 : // - generations > my_generation are to be ignored
415 : // - any other indices that exist would have an older generation than `previous_gen`, and
416 : // we want to find the most recent index from a previous generation.
417 : //
418 : // This is an optimization to avoid doing the listing for the general case below.
419 : let res = do_download_index_part(
420 : storage,
421 : tenant_shard_id,
422 : timeline_id,
423 : my_generation.previous(),
424 : cancel,
425 : )
426 : .await;
427 : match res {
428 : Ok(index_part) => {
429 : tracing::debug!("Found index_part from previous generation");
430 : return Ok(index_part);
431 : }
432 : Err(DownloadError::NotFound) => {
433 : tracing::debug!(
434 : "No index_part found from previous generation, falling back to listing"
435 : );
436 : }
437 : Err(e) => {
438 : return Err(e);
439 : }
440 : }
441 :
442 : // General case/fallback: if there is no index at my_generation or prev_generation, then list all index_part.json
443 : // objects, and select the highest one with a generation <= my_generation. Constructing the prefix is equivalent
444 : // to constructing a full index path with no generation, because the generation is a suffix.
445 : let index_prefix = remote_index_path(tenant_shard_id, timeline_id, Generation::none());
446 :
447 : let indices = download_retry(
448 6 : || async {
449 6 : storage
450 6 : .list(Some(&index_prefix), ListingMode::NoDelimiter, None, cancel)
451 6 : .await
452 6 : },
453 : "list index_part files",
454 : cancel,
455 : )
456 : .await?
457 : .keys;
458 :
459 : // General case logic for which index to use: the latest index whose generation
460 : // is <= our own. See "Finding the remote indices for timelines" in docs/rfcs/025-generation-numbers.md
461 : let max_previous_generation = indices
462 : .into_iter()
463 18 : .filter_map(|o| parse_remote_index_path(o.key))
464 12 : .filter(|g| g <= &my_generation)
465 : .max();
466 :
467 : match max_previous_generation {
468 : Some(g) => {
469 : tracing::debug!("Found index_part in generation {g:?}");
470 : do_download_index_part(storage, tenant_shard_id, timeline_id, g, cancel).await
471 : }
472 : None => {
473 : // Migration from legacy pre-generation state: we have a generation but no prior
474 : // attached pageservers did. Try to load from a no-generation path.
475 : tracing::debug!("No index_part.json* found");
476 : do_download_index_part(
477 : storage,
478 : tenant_shard_id,
479 : timeline_id,
480 : Generation::none(),
481 : cancel,
482 : )
483 : .await
484 : }
485 : }
486 : }
487 :
488 2 : pub(crate) async fn download_initdb_tar_zst(
489 2 : conf: &'static PageServerConf,
490 2 : storage: &GenericRemoteStorage,
491 2 : tenant_shard_id: &TenantShardId,
492 2 : timeline_id: &TimelineId,
493 2 : cancel: &CancellationToken,
494 2 : ) -> Result<(Utf8PathBuf, File), DownloadError> {
495 2 : debug_assert_current_span_has_tenant_and_timeline_id();
496 2 :
497 2 : let remote_path = remote_initdb_archive_path(&tenant_shard_id.tenant_id, timeline_id);
498 2 :
499 2 : let remote_preserved_path =
500 2 : remote_initdb_preserved_archive_path(&tenant_shard_id.tenant_id, timeline_id);
501 2 :
502 2 : let timeline_path = conf.timelines_path(tenant_shard_id);
503 2 :
504 2 : if !timeline_path.exists() {
505 0 : tokio::fs::create_dir_all(&timeline_path)
506 0 : .await
507 0 : .with_context(|| format!("timeline dir creation {timeline_path}"))
508 0 : .map_err(DownloadError::Other)?;
509 2 : }
510 2 : let temp_path = timeline_path.join(format!(
511 2 : "{INITDB_PATH}.download-{timeline_id}.{TEMP_FILE_SUFFIX}"
512 2 : ));
513 :
514 2 : let file = download_retry(
515 2 : || async {
516 2 : let file = OpenOptions::new()
517 2 : .create(true)
518 2 : .truncate(true)
519 2 : .read(true)
520 2 : .write(true)
521 2 : .open(&temp_path)
522 2 : .await
523 2 : .with_context(|| format!("tempfile creation {temp_path}"))
524 2 : .map_err(DownloadError::Other)?;
525 2 :
526 4 : let download = match storage.download(&remote_path, cancel).await {
527 2 : Ok(dl) => dl,
528 2 : Err(DownloadError::NotFound) => {
529 2 : storage.download(&remote_preserved_path, cancel).await?
530 2 : }
531 2 : Err(other) => Err(other)?,
532 2 : };
533 2 : let mut download = tokio_util::io::StreamReader::new(download.download_stream);
534 2 : let mut writer = tokio::io::BufWriter::with_capacity(super::BUFFER_SIZE, file);
535 2 :
536 730 : tokio::io::copy_buf(&mut download, &mut writer).await?;
537 2 :
538 2 : let mut file = writer.into_inner();
539 2 :
540 2 : file.seek(std::io::SeekFrom::Start(0))
541 2 : .await
542 2 : .with_context(|| format!("rewinding initdb.tar.zst at: {remote_path:?}"))
543 2 : .map_err(DownloadError::Other)?;
544 2 :
545 2 : Ok(file)
546 2 : },
547 2 : &format!("download {remote_path}"),
548 2 : cancel,
549 2 : )
550 738 : .await
551 2 : .map_err(|e| {
552 : // Do a best-effort attempt at deleting the temporary file upon encountering an error.
553 : // We don't have async here nor do we want to pile on any extra errors.
554 0 : if let Err(e) = std::fs::remove_file(&temp_path) {
555 0 : if e.kind() != std::io::ErrorKind::NotFound {
556 0 : warn!("error deleting temporary file {temp_path}: {e}");
557 0 : }
558 0 : }
559 0 : e
560 2 : })?;
561 :
562 2 : Ok((temp_path, file))
563 2 : }
564 :
565 : /// Helper function to handle retries for a download operation.
566 : ///
567 : /// Remote operations can fail due to rate limits (S3), spurious network
568 : /// problems, or other external reasons. Retry FAILED_DOWNLOAD_RETRIES times,
569 : /// with backoff.
570 : ///
571 : /// (See similar logic for uploads in `perform_upload_task`)
572 14 : pub(super) async fn download_retry<T, O, F>(
573 14 : op: O,
574 14 : description: &str,
575 14 : cancel: &CancellationToken,
576 14 : ) -> Result<T, DownloadError>
577 14 : where
578 14 : O: FnMut() -> F,
579 14 : F: Future<Output = Result<T, DownloadError>>,
580 14 : {
581 14 : backoff::retry(
582 14 : op,
583 14 : DownloadError::is_permanent,
584 14 : FAILED_DOWNLOAD_WARN_THRESHOLD,
585 14 : FAILED_REMOTE_OP_RETRIES,
586 14 : description,
587 14 : cancel,
588 14 : )
589 822 : .await
590 14 : .ok_or_else(|| DownloadError::Cancelled)
591 14 : .and_then(|x| x)
592 14 : }
593 :
594 208 : async fn download_retry_forever<T, O, F>(
595 208 : op: O,
596 208 : description: &str,
597 208 : cancel: &CancellationToken,
598 208 : ) -> Result<T, DownloadError>
599 208 : where
600 208 : O: FnMut() -> F,
601 208 : F: Future<Output = Result<T, DownloadError>>,
602 208 : {
603 208 : backoff::retry(
604 208 : op,
605 208 : DownloadError::is_permanent,
606 208 : FAILED_DOWNLOAD_WARN_THRESHOLD,
607 208 : u32::MAX,
608 208 : description,
609 208 : cancel,
610 208 : )
611 772 : .await
612 208 : .ok_or_else(|| DownloadError::Cancelled)
613 208 : .and_then(|x| x)
614 208 : }
|