storage-transfer-lib 0.3.0

Bounded S3 and local directory transfers using Apache OpenDAL
Documentation
use futures_util::TryStreamExt;
use opendal::options::{ReaderOptions, WriteOptions};
use opendal::{Capability, Metadata, Operator, Reader, Writer};
use tokio::sync::watch;

use crate::operator::with_policies;
use crate::validation::{validate_config, validate_copy};
use crate::{
    Error, HttpConcurrencyLimitLayer, ObjectTask, ReadConfig, Result, TransferConfig,
    TransferProgress,
};

// Apply a shared HTTP limiter and retry/timeout policies to this copy.
pub async fn copy_object(
    source: &Operator,
    destination: &Operator,
    task: &ObjectTask,
    config: &TransferConfig,
) -> Result<()> {
    validate_config(config)?;
    let layer = HttpConcurrencyLimitLayer::new(config.limits.max_ongoing_http_requests())?;
    copy_prepared(
        &with_policies(source.clone().layer(layer.clone()), config),
        &with_policies(destination.clone().layer(layer), config),
        task,
        config.read,
        config.chunk_size,
        None,
    )
    .await
}

pub(crate) async fn copy_prepared(
    source: &Operator,
    destination: &Operator,
    task: &ObjectTask,
    read: ReadConfig,
    chunk_size: usize,
    progress: Option<&watch::Sender<TransferProgress>>,
) -> Result<()> {
    validate_copy(source, destination, task, chunk_size)?;
    // Listing may omit metadata that needs to be preserved on writes.
    let metadata = source.stat(&task.path).await?;
    let reader = source
        .reader_options(
            &task.path,
            ReaderOptions {
                chunk: Some(chunk_size),
                concurrent: read.concurrency,
                prefetch: read.prefetch,
                ..Default::default()
            },
        )
        .await?;
    let mut writer = destination
        .writer_options(
            &task.path,
            write_options(&metadata, destination.info().capability(), chunk_size),
        )
        .await?;
    if let Err(error) = write_data(reader, &mut writer, task, progress).await {
        return abort(&mut writer, error).await;
    }

    // Drain close under the operator's retry/timeout policy before using the writer again.
    if let Err(error) = writer.close().await {
        return abort(&mut writer, error.into()).await;
    }
    Ok(())
}

async fn write_data(
    reader: Reader,
    writer: &mut Writer,
    task: &ObjectTask,
    progress: Option<&watch::Sender<TransferProgress>>,
) -> Result<()> {
    let size = task.metadata.content_length();
    if size == 0 {
        return Ok(());
    }
    // One stream preserves chunk order and keeps read-ahead active during writes.
    // Drop it before aborting the writer on error, releasing pending read requests.
    let mut stream = reader.into_stream(0..size).await?;
    while let Some(buffer) = stream.try_next().await? {
        if let Some(progress) = progress {
            progress.send_modify(|progress| progress.read_bytes += buffer.len() as u64);
        }
        // Let the bounded retry finish so abort retains the underlying writer state.
        writer.write(buffer).await?;
    }
    Ok(())
}

async fn abort(writer: &mut Writer, original: Error) -> Result<()> {
    let _ = writer.abort().await;
    Err(original)
}

fn write_options(metadata: &Metadata, capability: Capability, chunk_size: usize) -> WriteOptions {
    WriteOptions {
        if_not_exists: true,
        chunk: Some(chunk_size),
        concurrent: 1,
        content_type: metadata
            .content_type()
            .filter(|_| capability.write_with_content_type)
            .map(str::to_owned),
        content_encoding: metadata
            .content_encoding()
            .filter(|_| capability.write_with_content_encoding)
            .map(str::to_owned),
        content_disposition: metadata
            .content_disposition()
            .filter(|_| capability.write_with_content_disposition)
            .map(str::to_owned),
        cache_control: metadata
            .cache_control()
            .filter(|_| capability.write_with_cache_control)
            .map(str::to_owned),
        user_metadata: metadata
            .user_metadata()
            .filter(|_| capability.write_with_user_metadata)
            .map(|values| {
                values
                    .into_iter()
                    .map(|(key, value)| (key.to_owned(), value.to_owned()))
                    .collect()
            }),
        ..Default::default()
    }
}