Skip to main content

storage_transfer_lib/
copy.rs

1use futures_util::TryStreamExt;
2use opendal::options::{ReaderOptions, WriteOptions};
3use opendal::{Capability, Metadata, Operator, Reader, Writer};
4use tokio::sync::watch;
5
6use crate::operator::with_policies;
7use crate::validation::{validate_config, validate_copy};
8use crate::{
9    Error, HttpConcurrencyLimitLayer, ObjectTask, ReadConfig, Result, TransferConfig,
10    TransferProgress,
11};
12
13// Apply a shared HTTP limiter and retry/timeout policies to this copy.
14pub async fn copy_object(
15    source: &Operator,
16    destination: &Operator,
17    task: &ObjectTask,
18    config: &TransferConfig,
19) -> Result<()> {
20    validate_config(config)?;
21    let layer = HttpConcurrencyLimitLayer::new(config.limits.max_ongoing_http_requests())?;
22    copy_prepared(
23        &with_policies(source.clone().layer(layer.clone()), config),
24        &with_policies(destination.clone().layer(layer), config),
25        task,
26        config.read,
27        config.chunk_size,
28        None,
29    )
30    .await
31}
32
33pub(crate) async fn copy_prepared(
34    source: &Operator,
35    destination: &Operator,
36    task: &ObjectTask,
37    read: ReadConfig,
38    chunk_size: usize,
39    progress: Option<&watch::Sender<TransferProgress>>,
40) -> Result<()> {
41    validate_copy(source, destination, task, chunk_size)?;
42    // Listing may omit metadata that needs to be preserved on writes.
43    let metadata = source.stat(&task.path).await?;
44    let reader = source
45        .reader_options(
46            &task.path,
47            ReaderOptions {
48                chunk: Some(chunk_size),
49                concurrent: read.concurrency,
50                prefetch: read.prefetch,
51                ..Default::default()
52            },
53        )
54        .await?;
55    let mut writer = destination
56        .writer_options(
57            &task.path,
58            write_options(&metadata, destination.info().capability(), chunk_size),
59        )
60        .await?;
61    if let Err(error) = write_data(reader, &mut writer, task, progress).await {
62        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    Ok(())
70}
71
72async fn write_data(
73    reader: Reader,
74    writer: &mut Writer,
75    task: &ObjectTask,
76    progress: Option<&watch::Sender<TransferProgress>>,
77) -> Result<()> {
78    let size = task.metadata.content_length();
79    if size == 0 {
80        return Ok(());
81    }
82    // One stream preserves chunk order and keeps read-ahead active during writes.
83    // Drop it before aborting the writer on error, releasing pending read requests.
84    let mut stream = reader.into_stream(0..size).await?;
85    while let Some(buffer) = stream.try_next().await? {
86        if let Some(progress) = progress {
87            progress.send_modify(|progress| progress.read_bytes += buffer.len() as u64);
88        }
89        // Let the bounded retry finish so abort retains the underlying writer state.
90        writer.write(buffer).await?;
91    }
92    Ok(())
93}
94
95async fn abort(writer: &mut Writer, original: Error) -> Result<()> {
96    let _ = writer.abort().await;
97    Err(original)
98}
99
100fn write_options(metadata: &Metadata, capability: Capability, chunk_size: usize) -> WriteOptions {
101    WriteOptions {
102        if_not_exists: true,
103        chunk: Some(chunk_size),
104        concurrent: 1,
105        content_type: metadata
106            .content_type()
107            .filter(|_| capability.write_with_content_type)
108            .map(str::to_owned),
109        content_encoding: metadata
110            .content_encoding()
111            .filter(|_| capability.write_with_content_encoding)
112            .map(str::to_owned),
113        content_disposition: metadata
114            .content_disposition()
115            .filter(|_| capability.write_with_content_disposition)
116            .map(str::to_owned),
117        cache_control: metadata
118            .cache_control()
119            .filter(|_| capability.write_with_cache_control)
120            .map(str::to_owned),
121        user_metadata: metadata
122            .user_metadata()
123            .filter(|_| capability.write_with_user_metadata)
124            .map(|values| {
125                values
126                    .into_iter()
127                    .map(|(key, value)| (key.to_owned(), value.to_owned()))
128                    .collect()
129            }),
130        ..Default::default()
131    }
132}