use std::path::Path;
use std::sync::Arc;
use opendal::Operator;
use tokio::sync::{Mutex, watch};
use tokio::task::JoinSet;
use crate::operator::with_policies;
use crate::report::Report;
use crate::stats::StatsRun;
use crate::validation::{validate_config, validate_transfer};
use crate::worker::CopyWorker;
use crate::{
BucketProducer, Error, HttpConcurrencyLimitLayer, Result, TransferConfig, TransferProgress,
TransferStats,
};
pub struct TransferEngine {
source: Operator,
destination: Operator,
config: TransferConfig,
http_limit: HttpConcurrencyLimitLayer,
progress: watch::Sender<TransferProgress>,
stats: watch::Sender<TransferStats>,
}
impl TransferEngine {
pub fn new(source: Operator, destination: Operator, config: TransferConfig) -> Result<Self> {
validate_config(&config)?;
validate_transfer(&source, &destination, config.chunk_size)?;
let http_limit = HttpConcurrencyLimitLayer::new(config.limits.max_ongoing_http_requests())?;
let (progress, _) = watch::channel(TransferProgress::default());
let (stats, _) = watch::channel(TransferStats::default());
Ok(Self {
source,
destination,
config,
http_limit,
progress,
stats,
})
}
pub fn subscribe(&self) -> watch::Receiver<TransferProgress> {
self.progress.subscribe()
}
pub fn subscribe_stats(&self) -> watch::Receiver<TransferStats> {
self.stats.subscribe()
}
pub async fn run(&mut self) -> Result<TransferProgress> {
self.run_inner(None).await
}
pub async fn run_with_report(&mut self, path: &Path) -> Result<TransferProgress> {
let report = Report::create(path).await?;
let result = self.run_inner(Some(report.clone())).await;
let progress = *self.progress.borrow();
let reported = report.finished(progress, &result).await;
let progress = result?;
reported?;
Ok(progress)
}
async fn run_inner(&mut self, report: Option<Report>) -> Result<TransferProgress> {
self.progress.send_replace(TransferProgress::default());
let stats_run = StatsRun::new(self.stats.clone());
let stats = stats_run.stats.clone();
let layer = self.http_limit.clone().with_stats(stats.clone());
let source = with_policies(self.source.clone().layer(layer.clone()), &self.config);
let destination = with_policies(self.destination.clone().layer(layer), &self.config);
let (producer, queue) = BucketProducer::new(source.clone(), self.config.limits);
let producer = producer
.with_progress(self.progress.clone())
.with_stats(stats.clone());
let mut tasks = JoinSet::new();
let producer = tasks.spawn(producer.run());
let queue = Arc::new(Mutex::new(queue));
let worker = CopyWorker {
source,
destination,
queue: queue.clone(),
read: self.config.read,
chunk_size: self.config.chunk_size,
progress: self.progress.clone(),
stats: stats.clone(),
report,
};
for _ in 0..self.config.limits.worker_count() {
tasks.spawn(worker.clone().run());
}
let mut failure = None;
while let Some(result) = tasks.join_next().await {
let result = result.unwrap_or_else(|error| Err(Error::Task(error)));
if let Err(error) = result
&& failure.is_none()
{
failure = Some(error);
producer.abort();
let mut queue = queue.lock().await;
queue.close();
while queue.try_recv().is_ok() {
stats.update(|stats| stats.copy_queue_size -= 1);
}
}
}
if let Some(error) = failure {
return Err(error);
}
Ok(*self.progress.borrow())
}
}