Skip to main content

storage_transfer_lib/
copy.rs

1use opendal::options::WriteOptions;
2use opendal::{Metadata, Operator, Reader, Writer};
3use sha2::{Digest, Sha256};
4
5use crate::common::Sha256Digest;
6use crate::config::COPY_BUFFER_SIZE;
7use crate::operator::with_policies;
8use crate::validation::{validate_config, validate_copy, validate_metadata, validate_source};
9use crate::verify::verify_object;
10use crate::{
11    CancellationToken, Error, HttpConcurrencyLimitLayer, ObjectTask, Result, TransferConfig,
12};
13
14// Apply a shared HTTP limiter and retry/timeout policies to this copy.
15pub async fn copy_object(
16    source: &Operator,
17    destination: &Operator,
18    task: &ObjectTask,
19    config: &TransferConfig,
20    cancellation: &CancellationToken,
21) -> Result<()> {
22    validate_config(config)?;
23    let layer = HttpConcurrencyLimitLayer::new(config.limits.max_ongoing_http_requests())?;
24    copy_prepared(
25        &with_policies(source.clone().layer(layer.clone()), config),
26        &with_policies(destination.clone().layer(layer), config),
27        task,
28        cancellation,
29    )
30    .await
31}
32
33pub(crate) async fn copy_prepared(
34    source: &Operator,
35    destination: &Operator,
36    task: &ObjectTask,
37    cancellation: &CancellationToken,
38) -> Result<()> {
39    validate_copy(source, destination, task)?;
40    let mut stat = source.stat_with(&task.path);
41    if let Some(etag) = task.metadata.etag() {
42        stat = stat.if_match(etag);
43    }
44    let metadata = tokio::select! {
45        biased;
46        _ = cancellation.cancelled() => return Err(Error::Cancelled),
47        result = stat => result?,
48    };
49    let etag = validate_source(&metadata, task)?;
50    validate_metadata(&metadata, destination.info().capability())?;
51    let reader = source
52        .reader_with(&task.path)
53        .if_match(etag)
54        .chunk(COPY_BUFFER_SIZE)
55        .concurrent(1)
56        .await?;
57    let mut writer = destination
58        .writer_options(&task.path, write_options(&metadata))
59        .await?;
60    let digest = match write_data(&reader, &mut writer, task, cancellation).await {
61        Ok(digest) => digest,
62        Err(error) => return abort(&mut writer, error).await,
63    };
64
65    // Drain close under the operator's retry/timeout policy before using the writer again.
66    if let Err(error) = writer.close().await {
67        return abort(&mut writer, error.into()).await;
68    }
69    verify_object(destination, &task.path, &metadata, digest, cancellation).await
70}
71
72async fn write_data(
73    reader: &Reader,
74    writer: &mut Writer,
75    task: &ObjectTask,
76    cancellation: &CancellationToken,
77) -> Result<Sha256Digest> {
78    let mut hash = Sha256::new();
79    let size = task.metadata.content_length();
80    let mut offset = 0;
81    while offset < size {
82        let end = (offset + COPY_BUFFER_SIZE as u64).min(size);
83        let buffer = tokio::select! {
84            biased;
85            _ = cancellation.cancelled() => return Err(Error::Cancelled),
86            result = reader.read(offset..end) => result?,
87        };
88        if buffer.len() as u64 != end - offset {
89            return Err(Error::SourceChanged(task.path.clone()));
90        }
91        for chunk in buffer.clone() {
92            hash.update(chunk);
93        }
94        // Let the bounded retry finish so abort retains the underlying writer state.
95        writer.write(buffer).await?;
96        offset = end;
97    }
98    if cancellation.is_cancelled() {
99        return Err(Error::Cancelled);
100    }
101    Ok(hash.finalize().into())
102}
103
104async fn abort(writer: &mut Writer, original: Error) -> Result<()> {
105    let _ = writer.abort().await;
106    Err(original)
107}
108
109fn write_options(metadata: &Metadata) -> WriteOptions {
110    WriteOptions {
111        if_not_exists: true,
112        chunk: Some(COPY_BUFFER_SIZE),
113        concurrent: 1,
114        content_type: metadata.content_type().map(str::to_owned),
115        content_encoding: metadata.content_encoding().map(str::to_owned),
116        content_disposition: metadata.content_disposition().map(str::to_owned),
117        cache_control: metadata.cache_control().map(str::to_owned),
118        user_metadata: metadata.user_metadata().map(|values| {
119            values
120                .into_iter()
121                .map(|(key, value)| (key.to_owned(), value.to_owned()))
122                .collect()
123        }),
124        ..Default::default()
125    }
126}