storage-transfer-lib 0.3.0

Bounded S3 and local directory transfers using Apache OpenDAL
Documentation
use std::sync::Arc;

use futures_util::TryStreamExt;
use opendal::{EntryMode, Operator};
use tokio::sync::{mpsc, watch};
use tokio::task::JoinSet;

use crate::stats::Stats;
use crate::validation::validate_child;
use crate::{Error, ObjectTask, Result, TransferLimits, TransferProgress};

pub struct BucketProducer {
    source: Operator,
    sender: mpsc::Sender<ObjectTask>,
    list_page_size: usize,
    list_concurrency: usize,
    progress: Option<watch::Sender<TransferProgress>>,
    stats: Option<Stats>,
}

impl BucketProducer {
    pub fn new(source: Operator, limits: TransferLimits) -> (Self, mpsc::Receiver<ObjectTask>) {
        let (sender, receiver) = mpsc::channel(limits.max_queued_objects());
        (
            Self {
                source,
                sender,
                list_page_size: limits.list_page_size(),
                list_concurrency: limits.list_concurrency(),
                progress: None,
                stats: None,
            },
            receiver,
        )
    }

    pub(crate) fn with_progress(mut self, progress: watch::Sender<TransferProgress>) -> Self {
        self.progress = Some(progress);
        self
    }

    pub(crate) fn with_stats(mut self, stats: Stats) -> Self {
        self.stats = Some(stats);
        self
    }

    // Run alongside the consumer. Queue closure alone does not mean listing succeeded;
    // the caller must also check this result. Dropping this future stops production.
    pub async fn run(self) -> Result<()> {
        let producer = Arc::new(self);
        tokio::select! {
            biased;
            _ = producer.sender.closed() => Err(Error::ConsumerClosed),
            result = producer.produce() => {
                if result.is_ok()
                    && let Some(stats) = &producer.stats
                {
                    stats.update(|stats| stats.listing_finished = true);
                }
                result
            },
        }
    }

    async fn produce(self: &Arc<Self>) -> Result<()> {
        // Directory discovery must not wait for task slots or file capacity:
        // all listing tasks could otherwise block while trying to queue children.
        let (directories, mut pending) = mpsc::unbounded_channel();
        let mut tasks = JoinSet::new();
        tasks.spawn(self.clone().list_directory("/".into(), directories.clone()));
        while !tasks.is_empty() || !pending.is_empty() {
            tokio::select! {
                Some(directory) = pending.recv(), if tasks.len() < self.list_concurrency => {
                    if let Some(stats) = &self.stats {
                        stats.update(|stats| stats.list_queue_size -= 1);
                    }
                    tasks.spawn(self.clone().list_directory(directory, directories.clone()));
                }
                Some(result) = tasks.join_next(), if !tasks.is_empty() => {
                    result.map_err(Error::Task)??;
                }
            }
        }
        Ok(())
    }

    async fn list_directory(
        self: Arc<Self>,
        directory: String,
        directories: mpsc::UnboundedSender<String>,
    ) -> Result<()> {
        let _listing = self
            .stats
            .as_ref()
            .map(|stats| stats.track(|stats| &mut stats.active_listings));
        let mut lister = self
            .source
            .lister_with(&directory)
            .recursive(false)
            .limit(self.list_page_size)
            .await?;

        while let Some(entry) = lister.try_next().await? {
            if entry.path() == directory && entry.metadata().mode().is_dir() {
                continue;
            }
            // OpenDAL can report directory symlinks without the directory suffix.
            if entry.metadata().mode().is_dir() && !entry.path().ends_with('/') {
                continue;
            }
            validate_child(&directory, &entry)?;
            let (path, metadata) = entry.into_parts();
            match metadata.mode() {
                EntryMode::FILE => {
                    let permit = self
                        .sender
                        .reserve()
                        .await
                        .map_err(|_| Error::ConsumerClosed)?;
                    if let Some(progress) = &self.progress {
                        progress.send_modify(|progress| {
                            progress.listed_objects += 1;
                        });
                    }
                    if let Some(stats) = &self.stats {
                        stats.update(|stats| stats.copy_queue_size += 1);
                    }
                    permit.send(ObjectTask { path, metadata });
                }
                EntryMode::DIR => {
                    if let Some(stats) = &self.stats {
                        stats.update(|stats| stats.list_queue_size += 1);
                    }
                    directories.send(path).map_err(|_| Error::ConsumerClosed)?;
                }
                EntryMode::Unknown => return Err(Error::UnsupportedEntry(path)),
            }
        }
        Ok(())
    }
}