aws-s3-transfer 1.0.0

Transfer Manager for Amazon S3 - a high-performance data plane client for uploading and downloading objects and directories.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

use crate::error::{self, ErrorKind};
use crate::operation::download::body::{Body, RecvBodyConsumer};
use crate::operation::download::output::DownloadOutput;
use crate::operation::download::transfer::DownloadTransfer;
use crate::operation::download::ObjectMetadata;
use crate::transfer::{StateMachineTerminalReceiver, TransferId};

/// Shared core logic for download handles.
///
/// Contains the transfer and completion state but not the body, allowing
/// reuse across different handle types (e.g. `DownloadHandle`, `ManagedDownloadHandle`).
#[derive(Debug)]
pub(crate) struct DownloadHandleInner {
    pub(crate) transfer: DownloadTransfer,
    pub(crate) completion_rx: Option<StateMachineTerminalReceiver>,
}

impl DownloadHandleInner {
    /// Object metadata
    ///
    /// Waits for discovery to complete if metadata is not yet available.
    pub(crate) async fn object_meta(&self) -> Result<&ObjectMetadata, error::Error> {
        // Fast path: already available
        if let Some(meta) = self.transfer.object_meta() {
            return Ok(meta);
        }

        // Register interest before checking again. `discovery_notify` fires
        // with `notify_waiters`, which stores no permit: a notification sent
        // before this registration is lost.
        let notified = self.transfer.discovery_notify().notified();

        // Double-check after registering
        if let Some(meta) = self.transfer.object_meta() {
            return Ok(meta);
        }

        // Discovery already ended without metadata (failed or cancelled). Its
        // notification may have fired before `notified` was registered; waiting
        // would never return.
        if self.transfer.ctx().is_active() {
            notified.await;
        }

        // Check result
        self.transfer.object_meta().ok_or_else(|| {
            if self.transfer.ctx().is_cancelled() {
                error::from_kind(ErrorKind::OperationCancelled)("download cancelled")
            } else {
                error::from_kind(ErrorKind::ObjectNotDiscoverable)("discovery failed")
            }
        })
    }

    /// Core join logic: wait for completion, handle failure/cancellation/success.
    pub(crate) async fn join(&mut self) -> Result<DownloadOutput, error::Error> {
        // Wait for transfer state machine to reach terminal state
        if let Some(rx) = self.completion_rx.take() {
            // completion_tx is sent when state machine completes (success/failure)
            // RecvError means sender dropped without signaling - treat as failure
            let _ = rx.await;
        }

        let ctx = self.transfer.ctx();
        let id = self.transfer.id();

        if ctx.is_failed() {
            tracing::debug!(
                target: crate::telemetry::TARGET_TRANSFER_DOWNLOAD,
                tid = %ctx.id,
                "join: cancelling and waiting for idle",
            );
            ctx.handle
                .scheduler
                .cancel_transfer(id)
                .wait_for_idle()
                .await;
            tracing::debug!(
                target: crate::telemetry::TARGET_TRANSFER_DOWNLOAD,
                tid = %ctx.id,
                "join: idle, returning error",
            );
            // take the actual error (only we should do this)
            let err = ctx.take_error().expect("error taken outside of join()");
            return Err(err);
        }

        if ctx.is_cancelled() {
            return Err(error::Error::new(
                error::ErrorKind::OperationCancelled,
                "download cancelled",
            ));
        }

        // Success - discovery must have completed
        let object_meta = self
            .transfer
            .object_meta()
            .expect("object_meta must be set on successful completion")
            .clone();
        let integrity_checks = self
            .transfer
            .integrity_checks()
            .expect("integrity_checks must be set on successful completion")
            .clone();
        Ok(DownloadOutput::new(
            object_meta,
            ctx.metrics(),
            integrity_checks,
        ))
    }

    /// Core abort logic: cancel transfer, notify consumer, and wait for idle.
    pub(crate) async fn abort(&self) {
        let ctx = self.transfer.ctx();
        let id = self.transfer.id();

        ctx.set_cancelled();
        self.transfer.writer().notify_consumer();

        // Cancel transfer (purges queued work, interrupts executing work) and
        // wait for executing work to stop.
        ctx.handle
            .scheduler
            .cancel_transfer(id)
            .wait_for_idle()
            .await;
    }

    /// Get scheduling controls for this transfer.
    pub(crate) fn scheduling(&self) -> crate::transfer::SchedulingCtl<'_> {
        self.transfer.ctx().scheduling()
    }

    /// Get I/O controls for this transfer.
    pub(crate) fn io_ctl(&self) -> DownloadIoCtl<'_> {
        DownloadIoCtl {
            transfer: &self.transfer,
        }
    }
}

/// Runtime I/O controls for a running download.
///
/// Adjusts how the transfer moves data, as opposed to how it is scheduled relative
/// to other transfers (that is [`SchedulingCtl`](crate::transfer::SchedulingCtl)).
/// Obtained via [`DownloadHandle::io_ctl()`] or [`ManagedDownloadHandle::io_ctl()`].
#[derive(Debug)]
pub struct DownloadIoCtl<'a> {
    transfer: &'a DownloadTransfer,
}

impl<'a> DownloadIoCtl<'a> {
    /// Sets how far this download fetches ahead of the data its consumer has
    /// taken, replacing the value resolved at initiation; takes effect on the
    /// next fetch decision.
    ///
    /// Lowering it limits what a slow consumer's download holds; raising it
    /// restores prefetch once the consumer catches up.
    pub fn set_read_ahead(&self, mode: crate::config::ReadAhead) {
        self.transfer.set_read_ahead(&mode);
    }

    /// Construct directly from a transfer, for exercising the control surface in
    /// transfer-level tests without a full handle.
    #[cfg(test)]
    pub(crate) fn for_test(transfer: &'a DownloadTransfer) -> Self {
        Self { transfer }
    }
}

/// Handle to an in-progress download operation.
///
/// This handle is returned when initiating a download and provides access to the
/// downloaded content ([`body`](Self::body)), object metadata ([`object_meta`](Self::object_meta)),
/// and methods to wait for completion ([`join`](Self::join)) or cancel ([`abort`](Self::abort)).
///
/// # Lifecycle
///
/// **Handles should be kept until the transfer completes or is explicitly cancelled.**
/// Whole-object CRC verification runs after all ranges are collected. Body
/// bytes may reach the caller before that check finishes; [`join`](Self::join)
/// reports its final result. Consume the body before calling `join()`.
///
/// A successful `join()` does not guarantee checksum validation. Callers that
/// require it must inspect the outcome before accepting the downloaded content:
///
/// ```no_run
/// # async fn example(tm: &aws_s3_transfer::Client) -> Result<(), Box<dyn std::error::Error>> {
/// use aws_s3_transfer::types::ChecksumValidation;
///
/// let mut handle = tm.download()
///     .bucket("my-bucket")
///     .key("my-key")
///     .initiate()?;
///
/// while let Some(chunk) = handle.body_mut().next().await {
///     let chunk = chunk?;
///     // Consume the chunk; accept the complete result only after join().
/// }
///
/// let output = handle.join().await?;
/// match output.integrity_checks().checksum_validation() {
///     ChecksumValidation::Validated { .. } => {}
///     ChecksumValidation::NotValidated { reason, .. } => {
///         return Err(format!("download was not checksum-validated: {reason:?}").into());
///     }
///     _ => return Err("unrecognized checksum validation outcome".into()),
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Cancellation
///
/// The operation can be cancelled either by dropping this handle or by calling
/// [`abort`](Self::abort). Both methods stop the transfer, but they differ in behavior:
///
/// ## Dropping the handle
///
/// When the handle is dropped without calling `join()` or `abort()`:
/// - The transfer is marked as cancelled
/// - Queued work is purged from the scheduler
/// - In-flight work is interrupted at its next await point
/// - Drop returns immediately without waiting for in-flight work
///
/// ## Calling `abort()`
///
/// When [`abort`](Self::abort) is called:
/// - The transfer is marked as cancelled
/// - Queued work is purged from the scheduler
/// - In-flight work is interrupted; waits for it to stop
/// - Returns only after all cleanup is complete
///
/// ## Calling `join()` after failure
///
/// If the download fails, [`join`](Self::join) will cancel any remaining work,
/// wait for in-flight work to stop, and return the error.
#[derive(Debug)]
#[non_exhaustive]
pub struct DownloadHandle {
    /// Shared inner state (transfer + completion)
    pub(crate) inner: DownloadHandleInner,

    /// The object content
    pub(crate) body: Body,
}

impl DownloadHandle {
    pub(crate) fn new(
        transfer: DownloadTransfer,
        consumer: RecvBodyConsumer,
        completion_rx: StateMachineTerminalReceiver,
    ) -> Self {
        let body = Body::new(consumer, transfer.clone());
        Self {
            inner: DownloadHandleInner {
                transfer,
                completion_rx: Some(completion_rx),
            },
            body,
        }
    }

    /// Object metadata
    ///
    /// Waits for discovery to complete if metadata is not yet available.
    pub async fn object_meta(&self) -> Result<&ObjectMetadata, error::Error> {
        self.inner.object_meta().await
    }

    /// The object content
    pub fn body(&self) -> &Body {
        &self.body
    }

    /// Mutable reference to the body
    pub fn body_mut(&mut self) -> &mut Body {
        &mut self.body
    }

    /// Wait for the download to complete and return the result.
    ///
    /// Checksum mismatches return an error. Success may still report
    /// [`ChecksumValidation::NotValidated`](crate::types::ChecksumValidation::NotValidated);
    /// see the [`DownloadHandle`] example for checking the validation outcome.
    ///
    /// This is the authoritative source for transfer errors. Other methods
    /// (`body.next()`, `object_meta()`) return generic errors; call `join()`
    /// to get the actual error with full context.
    ///
    /// If the body has not been fully consumed, this will cancel the transfer
    /// and wait for outstanding work to complete before returning.
    pub async fn join(mut self) -> Result<DownloadOutput, error::Error> {
        // Close body - we're done consuming (or never started)
        self.body.close();
        self.inner.join().await
    }

    /// Abort the download and cancel any in-progress work.
    ///
    /// When this method returns, all work for this transfer has been
    /// cancelled or completed. No further work will be executed.
    pub async fn abort(mut self) {
        self.body.close();
        self.inner.abort().await;
    }

    /// Get scheduling controls for this transfer.
    ///
    /// See [`SchedulingCtl`](crate::transfer::SchedulingCtl) for available controls.
    ///
    /// <div class="warning">
    /// Scheduling controls are an advanced feature.
    /// </div>
    pub fn scheduling(&self) -> crate::transfer::SchedulingCtl<'_> {
        self.inner.scheduling()
    }

    /// Runtime I/O controls for this download.
    ///
    /// See [`DownloadIoCtl`] for available controls (e.g. adjusting read-ahead on a
    /// running transfer).
    pub fn io_ctl(&self) -> crate::operation::download::DownloadIoCtl<'_> {
        self.inner.io_ctl()
    }

    /// Current status of this transfer.
    pub fn status(&self) -> crate::types::TransferStatus {
        self.inner.transfer.ctx().transfer_status()
    }

    /// Snapshot of current transfer metrics.
    pub fn metrics(&self) -> crate::metrics::TransferMetrics {
        self.inner.transfer.ctx().metrics()
    }
}

impl Drop for DownloadHandle {
    fn drop(&mut self) {
        let ctx = self.inner.transfer.ctx();
        if ctx.is_active() {
            ctx.set_cancelled();
            self.inner.transfer.writer().notify_consumer();
            ctx.handle
                .scheduler
                .cancel_transfer(self.inner.transfer.id());
        }
    }
}

/// Handle to an in-progress download that writes to a file.
///
/// Returned by
/// [`write_to_path`](crate::operation::download::builders::DownloadFluentBuilder::write_to_path)
/// and
/// [`write_to_file`](crate::operation::download::builders::DownloadFluentBuilder::write_to_file).
/// Unlike [`DownloadHandle`], this handle does not expose a body; the transfer
/// manager writes the data to the file.
///
/// For a path destination, data is written to a temporary file named
/// `{file name}.s3tmp.{suffix}` in the destination's directory, where
/// `{file name}` is the destination's file name and `{suffix}` is 8 random
/// hexadecimal digits. A successful [`join`](Self::join) renames the temporary
/// file to the destination path. On failure, cancellation, or drop, the
/// temporary file is deleted.
///
/// Success means the operating system accepted every byte and, for a managed
/// path, completed the rename. The transfer manager does not call `sync_data`,
/// `sync_all`, or synchronize the parent directory, so success is not a
/// persistence guarantee across a system crash or power loss.
#[derive(Debug)]
pub struct ManagedDownloadHandle {
    inner: DownloadHandleInner,
    /// The temporary file this handle still owns, for a download to a path.
    ///
    /// Whatever renames or removes the file takes the path first:
    /// [`finalize`](Self::finalize) and [`cleanup`](Self::cleanup) for `join`
    /// and `abort`, otherwise drop. Each name is therefore renamed or removed
    /// once, even if the caller stops awaiting `join` partway. After that the
    /// name is free, and another download may have created its own file there.
    temp_path: Option<std::path::PathBuf>,
    dest_path: Option<std::path::PathBuf>,
}

impl ManagedDownloadHandle {
    pub(crate) fn new(
        inner: DownloadHandleInner,
        temp_path: std::path::PathBuf,
        dest_path: std::path::PathBuf,
    ) -> Self {
        Self {
            inner,
            temp_path: Some(temp_path),
            dest_path: Some(dest_path),
        }
    }

    #[cfg(any(unix, windows, target_os = "wasi"))]
    pub(crate) fn new_unmanaged(inner: DownloadHandleInner) -> Self {
        Self {
            inner,
            temp_path: None,
            dest_path: None,
        }
    }

    /// The transfer ID for this child download.
    pub(crate) fn transfer_id(&self) -> TransferId {
        self.inner.transfer.id()
    }

    /// Object metadata.
    ///
    /// Waits for discovery to complete if metadata is not yet available.
    pub async fn object_meta(&self) -> Result<&ObjectMetadata, error::Error> {
        self.inner.object_meta().await
    }

    /// Wait for the download to complete.
    ///
    /// On success, atomically renames the temporary file to the destination
    /// path. On failure or cancellation, deletes the temporary file. This does
    /// not add a filesystem durability barrier.
    ///
    /// Checksum mismatches return an error. Success may still report
    /// [`ChecksumValidation::NotValidated`](crate::types::ChecksumValidation::NotValidated).
    /// Check [`DownloadOutput::integrity_checks`] before accepting the contents;
    /// a successful path download has already published its destination.
    pub async fn join(
        mut self,
    ) -> Result<crate::operation::download::output::DownloadOutput, error::Error> {
        let result = self.inner.join().await;

        match &result {
            Ok(_) => self.finalize().await?,
            Err(_) => {
                self.cleanup().await;
            }
        }

        result
    }

    /// Abort the download and cancel any in-progress work.
    ///
    /// Deletes the temporary file. When this method returns, all work for
    /// this transfer has been cancelled or completed.
    pub async fn abort(mut self) {
        self.inner.abort().await;
        self.cleanup().await;
    }

    /// Get scheduling controls for this transfer.
    pub fn scheduling(&self) -> crate::transfer::SchedulingCtl<'_> {
        self.inner.scheduling()
    }

    /// Runtime I/O controls for this download.
    ///
    /// See [`DownloadIoCtl`] for available controls (e.g. adjusting read-ahead on a
    /// running transfer).
    pub fn io_ctl(&self) -> crate::operation::download::DownloadIoCtl<'_> {
        self.inner.io_ctl()
    }

    /// Current status of this transfer.
    pub fn status(&self) -> crate::types::TransferStatus {
        self.inner.transfer.ctx().transfer_status()
    }

    /// Snapshot of current transfer metrics.
    pub fn metrics(&self) -> crate::metrics::TransferMetrics {
        self.inner.transfer.ctx().metrics()
    }

    /// Renames the temporary file to the destination, if this handle has one,
    /// and removes the temporary file if the rename fails.
    ///
    /// Takes the temporary path before renaming, so neither
    /// [`cleanup`](Self::cleanup) nor drop acts on that name afterwards.
    async fn finalize(&mut self) -> Result<(), error::Error> {
        if let (Some(temp), Some(dest)) = (self.temp_path.take(), &self.dest_path) {
            // TODO(vnext): consider an opt-in download durability policy. Managed
            // path downloads would sync file data before rename and the parent
            // directory after rename where supported. The latency and cross-platform
            // semantics make this a client/API policy rather than the default.
            if let Err(e) = crate::io::fs::rename_async(&temp, dest).await {
                let _ = crate::io::fs::remove_file_async(&temp).await;
                return Err(error::io_at("renaming temporary file to", dest, e));
            }
        }
        Ok(())
    }

    /// Removes the temporary file, if this handle still owns one.
    ///
    /// Takes the temporary path before removing it, so drop doesn't remove
    /// that name again.
    async fn cleanup(&mut self) {
        if let Some(temp) = self.temp_path.take() {
            let _ = crate::io::fs::remove_file_async(&temp).await;
        }
    }
}

impl Drop for ManagedDownloadHandle {
    fn drop(&mut self) {
        let ctx = self.inner.transfer.ctx();
        if ctx.is_active() {
            ctx.set_cancelled();
            self.inner.transfer.writer().notify_consumer();
            ctx.handle
                .scheduler
                .cancel_transfer(self.inner.transfer.id());
        }
        if let Some(temp) = &self.temp_path {
            let _ = std::fs::remove_file(temp);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{DownloadHandle, DownloadHandleInner, ManagedDownloadHandle};
    use crate::error::ErrorKind;
    use crate::operation::download::body::{new_recv_body, RecvBodyConsumer};
    use crate::operation::download::transfer::DownloadTransfer;
    use crate::operation::download::DownloadInput;
    use crate::transfer::TransferContext;
    use crate::types::BucketType;

    fn is_send<T: Send>() {}
    fn is_sync<T: Sync>() {}

    #[test]
    fn test_handle_properties() {
        is_send::<DownloadHandle>();
        is_sync::<DownloadHandle>();
        is_send::<ManagedDownloadHandle>();
        is_sync::<ManagedDownloadHandle>();
    }

    /// Build a `DownloadHandleInner` whose `TransferContext` is already at
    /// a `Cancelled` terminal state. Callers assemble either a
    /// `DownloadHandle` or `ManagedDownloadHandle` around it to test the
    /// post-cancel `join()` contract.
    fn make_cancelled_download_inner() -> (DownloadHandleInner, RecvBodyConsumer) {
        let handle = crate::client::Handle::test_handle_tokio(
            crate::Config::builder()
                .sdk_client(aws_smithy_mocks::mock_client!(
                    aws_sdk_s3,
                    aws_smithy_mocks::RuleMode::MatchAny,
                    &[]
                ))
                .build()
                .expect("valid config"),
        );
        let input = DownloadInput::builder()
            .bucket("test-bucket")
            .key("test-key")
            .build()
            .unwrap();
        let (writer, consumer) = new_recv_body();
        let (ctx, completion_rx) = TransferContext::new(handle);
        let transfer = DownloadTransfer::new(ctx.clone(), BucketType::Standard, input, writer);

        ctx.set_cancelled();
        ctx.signal_terminal();

        let inner = DownloadHandleInner {
            transfer,
            completion_rx: Some(completion_rx),
        };
        (inner, consumer)
    }

    /// Regression: if the transfer reaches a `Cancelled` terminal state
    /// before `join()` is awaited, `DownloadHandle::join()` must return
    /// `Err(OperationCancelled)`. Previously this path panicked through
    /// `object_meta().expect("object_meta must be set on successful completion")`
    /// (or silently returned `Ok` if discovery had run before cancel).
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_download_join_returns_cancelled_error_when_transfer_cancelled() {
        let (inner, consumer) = make_cancelled_download_inner();
        let body = super::Body::new(consumer, inner.transfer.clone());
        let handle = DownloadHandle { inner, body };
        let err = handle
            .join()
            .await
            .expect_err("join on cancelled transfer must return Err");
        assert_eq!(err.kind(), &ErrorKind::OperationCancelled);
    }

    /// Regression: `ManagedDownloadHandle::join()` on a cancelled transfer
    /// must return `Err(OperationCancelled)` and delete the temp file.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_managed_download_join_returns_cancelled_and_cleans_up() {
        let dir = tempfile::tempdir().unwrap();
        let dest = dir.path().join("out.dat");
        let temp = dir.path().join("out.dat.s3tmp.abcdefgh");
        std::fs::write(&temp, b"partial").unwrap();

        let (inner, _consumer) = make_cancelled_download_inner();
        let managed = ManagedDownloadHandle::new(inner, temp.clone(), dest.clone());

        let err = managed
            .join()
            .await
            .expect_err("join on cancelled transfer must return Err");
        assert_eq!(err.kind(), &ErrorKind::OperationCancelled);
        assert!(
            !temp.exists(),
            "temp file must be cleaned up on cancellation"
        );
        assert!(
            !dest.exists(),
            "dest file must not be created on cancellation"
        );
    }

    /// Once `finalize` has renamed the temporary file, dropping the handle
    /// must not remove a file another download has since created under the
    /// same temporary name. `join` consumes the handle right after
    /// `finalize`, so this drives `finalize` and the drop directly.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_managed_download_drop_after_rename_keeps_file_at_temp_path() {
        let dir = tempfile::tempdir().unwrap();
        let dest = dir.path().join("out.dat");
        let temp = dir.path().join("out.dat.s3tmp.0000abcd");
        std::fs::write(&temp, b"object").unwrap();

        let (inner, _consumer) = make_cancelled_download_inner();
        let mut managed = ManagedDownloadHandle::new(inner, temp.clone(), dest.clone());
        managed.finalize().await.unwrap();
        assert_eq!(std::fs::read(&dest).unwrap(), b"object");

        std::fs::write(&temp, b"another download").unwrap();
        drop(managed);

        assert_eq!(std::fs::read(&temp).unwrap(), b"another download");
        assert_eq!(std::fs::read(&dest).unwrap(), b"object");
    }

    /// Once `cleanup` has removed the temporary file, dropping the handle must
    /// not remove a file another download has since created under the same
    /// temporary name. `join` and `abort` consume the handle right after
    /// `cleanup`, so this drives `cleanup` and the drop directly.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_managed_download_drop_after_cleanup_keeps_file_at_temp_path() {
        let dir = tempfile::tempdir().unwrap();
        let dest = dir.path().join("out.dat");
        let temp = dir.path().join("out.dat.s3tmp.0000abcd");
        std::fs::write(&temp, b"partial").unwrap();

        let (inner, _consumer) = make_cancelled_download_inner();
        let mut managed = ManagedDownloadHandle::new(inner, temp.clone(), dest.clone());
        managed.cleanup().await;
        assert!(!temp.exists(), "cleanup must remove the temp file");

        std::fs::write(&temp, b"another download").unwrap();
        drop(managed);

        assert_eq!(std::fs::read(&temp).unwrap(), b"another download");
        assert!(!dest.exists(), "cleanup must not create the destination");
    }

    /// A rename that fails removes the temporary file and leaves the
    /// destination absent. Dropping the handle afterwards must not remove a
    /// file another download has since created under the same temporary name.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_managed_download_failed_rename_removes_temp_file_once() {
        let dir = tempfile::tempdir().unwrap();
        // The destination's directory does not exist, so the rename fails.
        let dest = dir.path().join("missing").join("out.dat");
        let temp = dir.path().join("out.dat.s3tmp.0000abcd");
        std::fs::write(&temp, b"object").unwrap();

        let (inner, _consumer) = make_cancelled_download_inner();
        let mut managed = ManagedDownloadHandle::new(inner, temp.clone(), dest.clone());
        let err = managed
            .finalize()
            .await
            .expect_err("renaming into a missing directory must fail");
        assert_eq!(err.kind(), &ErrorKind::IOError);
        assert_eq!(
            err.to_string(),
            format!(
                "I/O error renaming temporary file to \"{}\"",
                dest.display()
            )
        );
        let source = std::error::Error::source(&err)
            .and_then(|s| s.downcast_ref::<std::io::Error>())
            .expect("the rename's error is the source");
        assert_eq!(source.kind(), std::io::ErrorKind::NotFound);
        assert!(!temp.exists(), "a failed rename must remove the temp file");
        assert!(
            !dest.exists(),
            "a failed rename must not create the destination"
        );

        std::fs::write(&temp, b"another download").unwrap();
        drop(managed);

        assert_eq!(std::fs::read(&temp).unwrap(), b"another download");
    }
}