Skip to main content

storage_transfer_lib/
producer.rs

1use std::sync::Arc;
2
3use futures_util::TryStreamExt;
4use opendal::{EntryMode, Operator};
5use tokio::sync::{mpsc, watch};
6use tokio::task::JoinSet;
7
8use crate::stats::Stats;
9use crate::validation::validate_child;
10use crate::{Error, ObjectTask, Result, TransferLimits, TransferProgress};
11
12pub struct BucketProducer {
13    source: Operator,
14    sender: mpsc::Sender<ObjectTask>,
15    list_page_size: usize,
16    list_concurrency: usize,
17    progress: Option<watch::Sender<TransferProgress>>,
18    stats: Option<Stats>,
19}
20
21impl BucketProducer {
22    pub fn new(source: Operator, limits: TransferLimits) -> (Self, mpsc::Receiver<ObjectTask>) {
23        let (sender, receiver) = mpsc::channel(limits.max_queued_objects());
24        (
25            Self {
26                source,
27                sender,
28                list_page_size: limits.list_page_size(),
29                list_concurrency: limits.list_concurrency(),
30                progress: None,
31                stats: None,
32            },
33            receiver,
34        )
35    }
36
37    pub(crate) fn with_progress(mut self, progress: watch::Sender<TransferProgress>) -> Self {
38        self.progress = Some(progress);
39        self
40    }
41
42    pub(crate) fn with_stats(mut self, stats: Stats) -> Self {
43        self.stats = Some(stats);
44        self
45    }
46
47    // Run alongside the consumer. Queue closure alone does not mean listing succeeded;
48    // the caller must also check this result. Dropping this future stops production.
49    pub async fn run(self) -> Result<()> {
50        let producer = Arc::new(self);
51        tokio::select! {
52            biased;
53            _ = producer.sender.closed() => Err(Error::ConsumerClosed),
54            result = producer.produce() => {
55                if result.is_ok()
56                    && let Some(stats) = &producer.stats
57                {
58                    stats.update(|stats| stats.listing_finished = true);
59                }
60                result
61            },
62        }
63    }
64
65    async fn produce(self: &Arc<Self>) -> Result<()> {
66        // Directory discovery must not wait for task slots or file capacity:
67        // all listing tasks could otherwise block while trying to queue children.
68        let (directories, mut pending) = mpsc::unbounded_channel();
69        let mut tasks = JoinSet::new();
70        tasks.spawn(self.clone().list_directory("/".into(), directories.clone()));
71        while !tasks.is_empty() || !pending.is_empty() {
72            tokio::select! {
73                Some(directory) = pending.recv(), if tasks.len() < self.list_concurrency => {
74                    if let Some(stats) = &self.stats {
75                        stats.update(|stats| stats.list_queue_size -= 1);
76                    }
77                    tasks.spawn(self.clone().list_directory(directory, directories.clone()));
78                }
79                Some(result) = tasks.join_next(), if !tasks.is_empty() => {
80                    result.map_err(Error::Task)??;
81                }
82            }
83        }
84        Ok(())
85    }
86
87    async fn list_directory(
88        self: Arc<Self>,
89        directory: String,
90        directories: mpsc::UnboundedSender<String>,
91    ) -> Result<()> {
92        let _listing = self
93            .stats
94            .as_ref()
95            .map(|stats| stats.track(|stats| &mut stats.active_listings));
96        let mut lister = self
97            .source
98            .lister_with(&directory)
99            .recursive(false)
100            .limit(self.list_page_size)
101            .await?;
102
103        while let Some(entry) = lister.try_next().await? {
104            if entry.path() == directory && entry.metadata().mode().is_dir() {
105                continue;
106            }
107            // OpenDAL can report directory symlinks without the directory suffix.
108            if entry.metadata().mode().is_dir() && !entry.path().ends_with('/') {
109                continue;
110            }
111            validate_child(&directory, &entry)?;
112            let (path, metadata) = entry.into_parts();
113            match metadata.mode() {
114                EntryMode::FILE => {
115                    let permit = self
116                        .sender
117                        .reserve()
118                        .await
119                        .map_err(|_| Error::ConsumerClosed)?;
120                    if let Some(progress) = &self.progress {
121                        progress.send_modify(|progress| {
122                            progress.listed_objects += 1;
123                        });
124                    }
125                    if let Some(stats) = &self.stats {
126                        stats.update(|stats| stats.copy_queue_size += 1);
127                    }
128                    permit.send(ObjectTask { path, metadata });
129                }
130                EntryMode::DIR => {
131                    if let Some(stats) = &self.stats {
132                        stats.update(|stats| stats.list_queue_size += 1);
133                    }
134                    directories.send(path).map_err(|_| Error::ConsumerClosed)?;
135                }
136                EntryMode::Unknown => return Err(Error::UnsupportedEntry(path)),
137            }
138        }
139        Ok(())
140    }
141}