storage-transfer-lib 0.3.0

Bounded S3 and local directory transfers using Apache OpenDAL
Documentation
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use tokio::sync::watch;

/// Latest runtime gauges, separate from cumulative transfer progress.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize)]
pub struct TransferStats {
    /// Discovered directories waiting for a listing task.
    pub list_queue_size: usize,
    /// Files waiting for a copy worker; excludes active copies and listing buffers.
    pub copy_queue_size: usize,
    /// Running directory tasks, including tasks blocked on the copy queue.
    pub active_listings: usize,
    /// Tasks processing a file, including its audit report write.
    pub active_copies: usize,
    /// Admitted HTTP requests, held until their response body finishes or drops.
    pub ongoing_http_requests: usize,
    /// All source directories were listed successfully; copying may still be running.
    pub listing_finished: bool,
}

#[derive(Clone, Debug)]
pub(crate) struct Stats(Arc<Inner>);

#[derive(Debug)]
struct Inner {
    sender: watch::Sender<TransferStats>,
    enabled: AtomicBool,
}

// A separate scope per run prevents cancelled tasks from changing a later run's gauges.
pub(crate) struct StatsRun {
    pub stats: Stats,
}

impl StatsRun {
    pub fn new(sender: watch::Sender<TransferStats>) -> Self {
        sender.send_replace(TransferStats::default());
        Self {
            stats: Stats(Arc::new(Inner {
                sender,
                enabled: AtomicBool::new(true),
            })),
        }
    }
}

impl Drop for StatsRun {
    fn drop(&mut self) {
        self.stats.0.enabled.store(false, Ordering::SeqCst);
        self.stats.0.sender.send_modify(|stats| {
            *stats = TransferStats {
                listing_finished: stats.listing_finished,
                ..TransferStats::default()
            };
        });
    }
}

impl Stats {
    pub fn update(&self, update: impl FnOnce(&mut TransferStats)) {
        self.0.sender.send_if_modified(|stats| {
            if !self.0.enabled.load(Ordering::SeqCst) {
                return false;
            }
            update(stats);
            true
        });
    }

    pub fn track(&self, counter: fn(&mut TransferStats) -> &mut usize) -> Activity {
        self.update(|stats| *counter(stats) += 1);
        Activity {
            stats: self.clone(),
            counter,
        }
    }
}

pub(crate) struct Activity {
    stats: Stats,
    counter: fn(&mut TransferStats) -> &mut usize,
}

impl Drop for Activity {
    fn drop(&mut self) {
        self.stats.update(|stats| *(self.counter)(stats) -= 1);
    }
}