cloud-copy 0.8.0

A library for copying files to and from cloud storage.
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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
//! Tests for `cloud_copy::copy`.

use std::fs;
use std::path::Path;
use std::path::PathBuf;

use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use cloud_copy::Alphanumeric;
use cloud_copy::AzureConfig;
use cloud_copy::Config;
use cloud_copy::ContentDigest;
use cloud_copy::Error;
use cloud_copy::HashAlgorithm;
use cloud_copy::HttpClient;
use cloud_copy::Location;
use cloud_copy::S3Config;
use cloud_copy::TransferEvent;
use cloud_copy::rewrite_url;
use futures::FutureExt;
use futures::future::LocalBoxFuture;
use pretty_assertions::assert_eq;
use rand::Rng;
use tempfile::NamedTempFile;
use tempfile::tempdir;
use tokio::fs::File;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::io::BufWriter;
use tokio::sync::broadcast;
use tokio::sync::oneshot;
use tokio_util::sync::CancellationToken;
use url::Url;
use walkdir::WalkDir;

/// Represents 1 MiB (in bytes).
const ONE_MEBIBYTE: usize = 1024 * 1024;

/// The test container/bucket name.
const TEST_BUCKET_NAME: &str = "cloud-copy-test";

/// Writes random bytes of the given size to the given file.
async fn write_random_bytes(file: File, mut size: usize) -> Result<()> {
    let mut rng = rand::rng();
    let mut buffer = [0; 4096];

    let mut writer = BufWriter::new(file);
    while size > 0 {
        let to_write = size.min(buffer.len());
        let buffer = &mut buffer[..to_write];
        rng.fill(buffer);
        size -= writer
            .write(buffer)
            .await
            .context("failed to write random file")?;
    }

    writer.flush().await.expect("failed to flush file");
    Ok(())
}

/// Determines if two files have the same content.
async fn same_file_content(first: &Path, second: &Path) -> Result<bool> {
    if first
        .metadata()
        .context("failed to read metadata of first file")?
        .len()
        != second
            .metadata()
            .context("failed to read metadata of second file")?
            .len()
    {
        return Ok(false);
    }

    let mut first = BufReader::new(
        File::open(first)
            .await
            .context("failed to open first file for comparison")?,
    );
    let mut second = BufReader::new(
        File::open(second)
            .await
            .context("failed to open second file for comparison")?,
    );

    let mut first_buffer = [0; 4096];
    let mut second_buffer = [0; 4096];

    loop {
        let read = first
            .read(&mut first_buffer)
            .await
            .context("failed to read first file for comparison")?;
        if read == 0 {
            break;
        }

        second
            .read_exact(&mut second_buffer[0..read])
            .await
            .context("failed to read first file for comparison")?;

        if first_buffer != second_buffer {
            return Ok(false);
        }
    }

    Ok(true)
}

/// Creates random files in a directory.
fn create_random_files<'a>(dir: &'a Path, depth: usize) -> LocalBoxFuture<'a, Result<()>> {
    async move {
        let mut rng = rand::rng();

        for i in 0..5 {
            let file = File::create(dir.join(format!("file-{i}")))
                .await
                .context("failed to create test file")?;
            let size = { rng.random_range(0..ONE_MEBIBYTE) };
            write_random_bytes(file, size).await?;
        }

        if depth > 0 {
            let subdir = dir.join(format!("dir-{depth}"));
            fs::create_dir(&subdir).context("failed to create test directory")?;
            create_random_files(&subdir, depth - 1).await?;
        }

        Ok(())
    }
    .boxed_local()
}

/// Walks a directory and returns a sorted list of its entries.
///
/// The returns paths are relative to the given directory.
fn walk_dir(dir: &Path) -> Result<Vec<PathBuf>> {
    let mut entries = Vec::new();

    for entry in WalkDir::new(dir) {
        let entry = entry.context("failed to walk directory")?;
        entries.push(
            entry
                .path()
                .strip_prefix(dir)
                .context("failed to strip directory prefix")?
                .to_path_buf(),
        );
    }

    entries.sort();
    Ok(entries)
}

/// Gets a set of cloud storage URLs to test given the test name.
fn urls(test: &str) -> Vec<Url> {
    vec![
        // S3 URLs
        format!("s3://{TEST_BUCKET_NAME}/1/{test}").parse().unwrap(),
        format!("http://s3.us-east-1.localhost.localstack.cloud:4566/{TEST_BUCKET_NAME}/2/{test}")
            .parse()
            .unwrap(),
        format!("http://{TEST_BUCKET_NAME}.s3.us-east-1.localhost.localstack.cloud:4566/3/{test}")
            .parse()
            .unwrap(),

        // Azure URLs
        format!("az://devstoreaccount1/{TEST_BUCKET_NAME}/1/{test}").parse().unwrap(),
        format!("http://devstoreaccount1.blob.core.windows.net.localhost:10000/{TEST_BUCKET_NAME}/2/{test}").parse().unwrap(),
    ]
}

fn azure_config() -> AzureConfig {
    AzureConfig::default().with_use_azurite(true).with_auth(
        "devstoreaccount1",
        // This is the Azurite secret key used for testing; it is not a secret
        "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==",
    )
}

fn s3_config() -> S3Config {
    S3Config::default()
        .with_use_localstack(true)
        .with_auth("test", "test")
}

fn config(overwrite: bool) -> Config {
    Config::builder()
        .with_overwrite(overwrite)
        .with_azure(azure_config())
        .with_s3(s3_config())
        .build()
}

/// Round trips a file of a given size by uploading it to cloud storage and then
/// downloading it again.
async fn roundtrip_file(test: &str, size: usize) -> Result<()> {
    let config = config(true);
    let client = HttpClient::default();
    let cancel = CancellationToken::new();

    // Create a new temp file of the specified size
    let (file, source) = NamedTempFile::new()
        .context("failed to create temp file")?
        .into_parts();
    write_random_bytes(file.into(), size)
        .await
        .context("failed to write random bytes into file")?;

    // Create another temporary file path for the download
    let destination = NamedTempFile::new()
        .context("failed to create temp file")?
        .into_temp_path();

    for url in urls(test) {
        // Copy the local file to the cloud
        cloud_copy::copy(
            config.clone(),
            client.clone(),
            &*source,
            &url,
            cancel.clone(),
            None,
        )
        .await
        .context("failed to upload file")?;

        // Copy the file from the cloud to a local file
        cloud_copy::copy(
            config.clone(),
            client.clone(),
            &url,
            &*destination,
            cancel.clone(),
            None,
        )
        .await
        .context("failed to download file")?;

        // Ensure the uploaded file and the downloaded file are the same
        if !same_file_content(&source, &destination)
            .await
            .context("failed to compare files")?
        {
            bail!("the downloaded file is not equal to the uploaded");
        }
    }

    Ok(())
}

/// A test to download a generic URL.
#[tokio::test]
async fn copy_generic_url() -> Result<()> {
    // Create a temporary file path for the download
    let destination = NamedTempFile::new()
        .context("failed to create temp file")?
        .into_temp_path();

    fs::remove_file(&destination).context("failed to delete destination file")?;

    // Copy the URL to the local file
    let cancel = CancellationToken::new();
    cloud_copy::copy(
        config(true),
        Default::default(),
        "https://example.com",
        &*destination,
        cancel.clone(),
        None,
    )
    .await
    .context("failed to download file")?;

    Ok(())
}

// A test to ensure existing destinations aren't overwritten.
#[tokio::test]
async fn no_overwrite() -> Result<()> {
    let test = format!("{random}", random = Alphanumeric::new(10));
    let config = config(true);
    let client = HttpClient::default();
    let cancel = CancellationToken::new();

    // Create an empty temp file
    let source = NamedTempFile::new()
        .context("failed to create temp file")?
        .into_temp_path();

    // Copy the local file to the cloud
    for url in urls(&test) {
        cloud_copy::copy(
            config.clone(),
            client.clone(),
            &*source,
            &url,
            cancel.clone(),
            None,
        )
        .await
        .context("failed to upload file")?;
    }

    let config = crate::config(false);

    // Attempt to overwrite the destination URLs
    for url in urls(&test) {
        match cloud_copy::copy(
            config.clone(),
            client.clone(),
            &*source,
            &url,
            cancel.clone(),
            None,
        )
        .await
        {
            Ok(_) => panic!("copy operation should fail for `{url}`"),
            Err(Error::RemoteDestinationExists(_)) => {}
            Err(e) => panic!("unexpected error `{e}` for `{url}`"),
        }
    }

    // Attempt to overwrite the source
    for url in urls(&test) {
        match cloud_copy::copy(
            config.clone(),
            client.clone(),
            &url,
            &*source,
            cancel.clone(),
            None,
        )
        .await
        {
            Ok(_) => panic!("copy operation should fail for `{url}`"),
            Err(Error::LocalDestinationExists(_)) => {}
            Err(e) => panic!("unexpected error `{e}` for `{url}`"),
        }
    }

    let config = crate::config(true);

    // Overwrite the destination URLs
    for url in urls(&test) {
        cloud_copy::copy(
            config.clone(),
            client.clone(),
            &*source,
            &url,
            cancel.clone(),
            None,
        )
        .await
        .context("failed to upload file")?;
    }

    // Overwrite the source
    for url in urls(&test) {
        cloud_copy::copy(
            config.clone(),
            client.clone(),
            &url,
            &*source,
            cancel.clone(),
            None,
        )
        .await
        .context("failed to download file")?;
    }

    Ok(())
}

/// A test to roundtrip an empty file.
#[tokio::test]
async fn roundtrip_empty_file() -> Result<()> {
    let test = format!("{random}", random = Alphanumeric::new(10));
    roundtrip_file(&test, 0).await
}

/// A test to roundtrip a small (1 byte to 10 MiB) file.
#[tokio::test]
async fn roundtrip_small_file() -> Result<()> {
    let test = format!("{random}", random = Alphanumeric::new(10));
    roundtrip_file(&test, rand::rng().random_range(1..10 * ONE_MEBIBYTE)).await
}

/// A test to roundtrip a medium (10 MiB to 50 MiB) file.
#[tokio::test]
async fn roundtrip_medium_file() -> Result<()> {
    let test = format!("{random}", random = Alphanumeric::new(10));
    roundtrip_file(
        &test,
        rand::rng().random_range(10 * ONE_MEBIBYTE..50 * ONE_MEBIBYTE),
    )
    .await
}

/// A test to roundtrip a large (50 MiB to 100 MiB) file.
#[tokio::test]
async fn roundtrip_large_file() -> Result<()> {
    let test = format!("{random}", random = Alphanumeric::new(10));
    roundtrip_file(
        &test,
        rand::rng().random_range(50 * ONE_MEBIBYTE..100 * ONE_MEBIBYTE),
    )
    .await
}

/// A test to roundtrip a directory.
#[tokio::test]
async fn roundtrip_directory() -> Result<()> {
    let test = format!("{random}", random = Alphanumeric::new(10));

    let source = tempdir().context("failed to create temporary directory")?;
    let destination = tempdir().context("failed to create temporary directory")?;

    create_random_files(source.path(), 3)
        .await
        .context("failed to populate temporary directory")?;

    let config = config(true);
    let client = HttpClient::default();
    let cancel = CancellationToken::new();

    // Do a test for each URL with and without a trailing slash
    for url in urls(&test)
        .into_iter()
        .chain(urls(&test).into_iter().map(|mut u| {
            {
                let mut segments = u.path_segments_mut().unwrap();
                segments.pop_if_empty();
                segments.push("");
            }
            u
        }))
    {
        // Copy the local directory to the cloud
        cloud_copy::copy(
            config.clone(),
            client.clone(),
            source.path(),
            &url,
            cancel.clone(),
            None,
        )
        .await
        .context("failed to upload directory")?;

        // Copy the directory from the cloud to a local directory (delete it first in
        // case it exists)
        fs::remove_dir_all(destination.path()).context("failed to delete destination directory")?;
        cloud_copy::copy(
            config.clone(),
            client.clone(),
            &url,
            destination.path(),
            cancel.clone(),
            None,
        )
        .await
        .context("failed to download directory")?;

        let source_entries = walk_dir(source.path()).context("failed to walk source directory")?;
        let destination_entries =
            walk_dir(destination.path()).context("failed to walk destination directory")?;

        if source_entries.len() != destination_entries.len() {
            bail!("source directory and download directory have a different number of entries");
        }

        for (orig, new) in source_entries.into_iter().zip(destination_entries) {
            if orig != new {
                bail!(
                    "original entry `{orig}` does not match the new entry `{new}`",
                    orig = orig.display(),
                    new = new.display()
                );
            }

            let source = source.path().join(orig);
            let destination = destination.path().join(new);

            match (source.is_dir(), destination.is_dir()) {
                (true, true) => continue,
                (false, false) => {
                    // Ensure the uploaded file and the downloaded file are the same
                    if !same_file_content(&source, &destination)
                        .await
                        .context("failed to compare files")?
                    {
                        bail!(
                            "contents of uploaded file `{source}` does not match the contents of \
                             downloaded file `{destination}`",
                            source = source.display(),
                            destination = destination.display()
                        );
                    }
                }
                _ => bail!(
                    "source entry `{source}` does not match the type of download entry \
                     `{destination}`",
                    source = source.display(),
                    destination = destination.display()
                ),
            }
        }
    }

    Ok(())
}

/// Test for linking to cached files.
///
/// This test runs only on Unix operating systems as the requisite [method on
/// Windows][1] is only available on nightly.
///
/// [1]: https://doc.rust-lang.org/std/os/windows/fs/trait.MetadataExt.html#tymethod.number_of_links
#[cfg(unix)]
#[tokio::test]
async fn link_to_cache() -> Result<()> {
    use std::os::unix::fs::MetadataExt;

    let cache_dir = tempdir().context("failed to create temp directory")?;

    let destination = NamedTempFile::new()
        .context("failed to create destination file")?
        .into_temp_path();
    fs::remove_file(&destination).context("failed to delete destination file")?;

    let cancel = CancellationToken::new();

    let config = Config::default();
    let client = HttpClient::new_with_cache(config.clone(), &cache_dir);

    // Download the file (and cache it)
    cloud_copy::copy(
        config,
        client.clone(),
        "https://example.com",
        &*destination,
        cancel.clone(),
        None,
    )
    .await
    .context("failed to download file")?;

    assert!(destination.is_file(), "destination is not a file");

    fs::remove_file(&destination).context("failed to delete destination file")?;

    // Download the file again (it'll copy from the cache)
    cloud_copy::copy(
        Default::default(),
        client.clone(),
        "https://example.com",
        &*destination,
        cancel.clone(),
        None,
    )
    .await
    .context("failed to download file")?;

    assert_eq!(
        destination
            .metadata()
            .context("failed to read metadata of destination")?
            .nlink(),
        1,
        "expected only a single link to the file"
    );

    // Download the file again (it'll link from the cache)
    cloud_copy::copy(
        Config::builder()
            .with_overwrite(true)
            .with_link_to_cache(true)
            .build(),
        client,
        "https://example.com",
        &*destination,
        cancel,
        None,
    )
    .await
    .context("failed to download file")?;

    assert_eq!(
        destination
            .metadata()
            .context("failed to read metadata of destination")?
            .nlink(),
        2,
        "expected two links to the file"
    );

    Ok(())
}

/// Tests that transfer events are sent as expected.
#[tokio::test]
async fn events() -> Result<()> {
    const FILE_SIZE: u64 = 1024;

    let test = format!("{random}", random = Alphanumeric::new(10));

    let config = config(true);
    let client = HttpClient::default();
    let cancel = CancellationToken::new();

    // Create a new temp file
    let (file, source) = NamedTempFile::new()
        .context("failed to create temp file")?
        .into_parts();
    write_random_bytes(file.into(), FILE_SIZE as usize)
        .await
        .context("failed to write random bytes into file")?;

    // Create another temporary file path for the download
    let destination = NamedTempFile::new()
        .context("failed to create temp file")?
        .into_temp_path();

    let (events_tx, mut events_rx) = broadcast::channel(1000);
    let (urls_tx, urls_rx) = oneshot::channel();

    tokio::spawn(async move {
        let mut urls = Vec::new();
        loop {
            match events_rx.recv().await {
                Ok(event) => match event {
                    TransferEvent::TransferStarted {
                        source,
                        destination,
                        blocks,
                        size,
                        ..
                    } => {
                        assert_eq!(blocks, 1, "unexpected number of blocks");
                        assert_eq!(size, Some(FILE_SIZE), "unexpected file size");

                        if let Location::Url(url) = source {
                            urls.push(url);
                        }

                        if let Location::Url(url) = destination {
                            urls.push(url);
                        }
                    }
                    TransferEvent::BlockStarted { block, size, .. } => {
                        assert_eq!(block, 0, "unexpected block id");
                        assert_eq!(size, Some(FILE_SIZE), "unexpected file size");
                    }
                    TransferEvent::BlockProgress { .. } => continue,
                    TransferEvent::BlockCompleted { block, failed, .. } => {
                        assert_eq!(block, 0, "unexpected block id");
                        assert!(!failed, "block failed to transfer");
                    }
                    TransferEvent::TransferCompleted { failed, .. } => {
                        assert!(!failed, "file failed to transfer");
                    }
                },
                Err(broadcast::error::RecvError::Closed) => break,
                Err(broadcast::error::RecvError::Lagged(_)) => panic!("event channel lagged"),
            }
        }

        urls_tx.send(urls).expect("failed to send urls");
    });

    let expected = urls(&test);
    for url in &expected {
        // Copy the local file to the cloud
        cloud_copy::copy(
            config.clone(),
            client.clone(),
            &*source,
            url,
            cancel.clone(),
            Some(events_tx.clone()),
        )
        .await
        .context("failed to upload file")?;

        // Copy the file from the cloud to a local file
        cloud_copy::copy(
            config.clone(),
            client.clone(),
            url,
            &*destination,
            cancel.clone(),
            Some(events_tx.clone()),
        )
        .await
        .context("failed to download file")?;

        // Ensure the uploaded file and the downloaded file are the same
        if !same_file_content(&source, &destination)
            .await
            .context("failed to compare files")?
        {
            bail!("the downloaded file is not equal to the uploaded");
        }
    }

    drop(events_tx);

    // The returned URLs should have two entries per expected
    let urls = urls_rx.await.expect("failed to receive events");
    assert!(!urls.is_empty());
    for (i, expected) in expected.iter().enumerate() {
        let expected = rewrite_url(&config, expected).expect("URL should rewrite");
        assert_eq!(&urls[i * 2], expected.as_ref(), "unexpected upload URL");
        assert_eq!(
            &urls[(i * 2) + 1],
            expected.as_ref(),
            "unexpected download URL"
        );
    }

    Ok(())
}

/// Tests that we can walk cloud URLs.
#[tokio::test]
async fn walk() -> Result<()> {
    const FILE_SIZE: u64 = 1024;

    let test = format!("{random}", random = Alphanumeric::new(10));

    let config = config(true);
    let client = HttpClient::default();
    let cancel = CancellationToken::new();

    // Create a new temp file
    let (file, source) = NamedTempFile::new()
        .context("failed to create temp file")?
        .into_parts();
    write_random_bytes(file.into(), FILE_SIZE as usize)
        .await
        .context("failed to write random bytes into file")?;

    for url in urls(&test) {
        for i in 0..10 {
            let mut url = url.clone();
            url.path_segments_mut().unwrap().push(&i.to_string());

            // Copy the local file to the cloud
            cloud_copy::copy(
                config.clone(),
                client.clone(),
                &*source,
                url,
                cancel.clone(),
                None,
            )
            .await
            .context("failed to upload file")?;
        }

        let files = cloud_copy::walk(config.clone(), client.clone(), url.clone())
            .await
            .expect("should walk");
        assert_eq!(
            files,
            &["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
            "unexpected walk output for URL `{url}`"
        );
    }

    Ok(())
}

/// Tests that we store and retrieve content digests
#[tokio::test]
async fn digests() -> Result<()> {
    const FILE_SIZE: u64 = 1024;

    let test = format!("{random}", random = Alphanumeric::new(10));

    let client = HttpClient::default();
    let cancel = CancellationToken::new();

    // Create a new temp file
    let (file, source) = NamedTempFile::new()
        .context("failed to create temp file")?
        .into_parts();
    write_random_bytes(file.into(), FILE_SIZE as usize)
        .await
        .context("failed to write random bytes into file")?;

    // Upload for each supported hash algorithm
    for algorithm in [
        HashAlgorithm::None,
        HashAlgorithm::Sha256,
        HashAlgorithm::Blake3,
    ] {
        let config = Config::builder()
            .with_overwrite(true)
            .with_hash_algorithm(algorithm)
            .with_azure(azure_config())
            .with_s3(s3_config())
            .build();

        // Calculate an expected digest for the file's contents
        let expected_digest = algorithm
            .calculate_content_digest(&source, &cancel)
            .await
            .unwrap()
            .map(|v| ContentDigest::parse_header(&v).unwrap());

        for url in urls(&test) {
            // Copy the local file to the cloud
            cloud_copy::copy(
                config.clone(),
                client.clone(),
                &*source,
                url.clone(),
                cancel.clone(),
                None,
            )
            .await
            .context("failed to upload file")?;

            let digest =
                cloud_copy::get_content_digest(config.clone(), client.clone(), url.clone()).await?;
            match (&expected_digest, &digest) {
                (None, Some(ContentDigest::ETag(v))) => {
                    // The emulators return an `ETag` header for the objects; ensure it is always a
                    // strong validator
                    assert!(!v.starts_with("W/"));
                }
                (Some(expected), Some(actual)) => {
                    assert_eq!(expected, actual, "digest mismatch");
                }
                _ => panic!("unexpected content digest `{digest:?}` for `{url}`"),
            }
        }
    }

    Ok(())
}

/// Tests that we correctly determine if URLs exist.
#[tokio::test]
async fn exists() -> Result<()> {
    let test = format!("{random}", random = Alphanumeric::new(10));
    let source = tempdir().context("failed to create temporary directory")?;

    create_random_files(source.path(), 2)
        .await
        .context("failed to populate temporary directory")?;

    // Upload the source directory
    let config = config(true);
    let client = HttpClient::default();
    let cancel = CancellationToken::new();
    for url in urls(&test) {
        // Copy the local directory to the cloud
        cloud_copy::copy(
            config.clone(),
            client.clone(),
            source.path(),
            &url,
            cancel.clone(),
            None,
        )
        .await
        .context("failed to upload directory")?;
    }

    // Walk each directory entry (including sub directories) and check for existence
    for entry in WalkDir::new(source.path()) {
        let entry = entry.context("walk should succeed")?;
        let path = entry
            .path()
            .strip_prefix(source.path())
            .context("should be relative")?;

        for mut url in urls(&test) {
            url.path_segments_mut()
                .expect("missing path segments")
                .pop_if_empty()
                .push("");

            let url = url
                .join(path.as_os_str().to_str().context("should be UTF-8")?)
                .context("url should join")?;

            let exists = cloud_copy::exists(config.clone(), client.clone(), url.clone())
                .await
                .context("checking for existence")?;
            assert!(exists, "URL `{url}` should exist");

            let url = url.join("does-not-exist").context("url should join")?;
            let exists = cloud_copy::exists(config.clone(), client.clone(), url.clone())
                .await
                .context("checking for existence")?;
            assert!(!exists, "URL `{url}` should not exist");
        }
    }

    // Check for generic backend
    assert!(
        cloud_copy::exists(
            config.clone(),
            client.clone(),
            "https://google.com".parse().context("should parse")?
        )
        .await
        .context("checking for existence")?
    );
    assert!(
        !cloud_copy::exists(
            config.clone(),
            client.clone(),
            "https://google.com/404".parse().context("should parse")?
        )
        .await
        .context("checking for existence")?
    );

    Ok(())
}

/// Tests that we correctly determine sizes of files.
#[tokio::test]
async fn size() -> Result<()> {
    const FILE_SIZE: u64 = 1024;

    let test = format!("{random}", random = Alphanumeric::new(10));

    // Create a new temp file
    let (file, source) = NamedTempFile::new()
        .context("failed to create temp file")?
        .into_parts();
    write_random_bytes(file.into(), FILE_SIZE as usize)
        .await
        .context("failed to write random bytes into file")?;

    // Upload the file
    let config = config(true);
    let client = HttpClient::default();
    let cancel = CancellationToken::new();
    for url in urls(&test) {
        // Copy the local file to the cloud
        cloud_copy::copy(
            config.clone(),
            client.clone(),
            source.as_ref() as &Path,
            &url,
            cancel.clone(),
            None,
        )
        .await
        .context("failed to upload directory")?;

        // Check the file size matches
        let size = cloud_copy::size(config.clone(), client.clone(), url).await?;
        assert_eq!(size, Some(FILE_SIZE));
    }

    Ok(())
}