storage_transfer_lib/
stats.rs1use std::sync::Arc;
2use std::sync::atomic::{AtomicBool, Ordering};
3
4use tokio::sync::watch;
5
6#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize)]
8pub struct TransferStats {
9 pub list_queue_size: usize,
11 pub copy_queue_size: usize,
13 pub active_listings: usize,
15 pub active_copies: usize,
17 pub ongoing_http_requests: usize,
19 pub listing_finished: bool,
21}
22
23#[derive(Clone, Debug)]
24pub(crate) struct Stats(Arc<Inner>);
25
26#[derive(Debug)]
27struct Inner {
28 sender: watch::Sender<TransferStats>,
29 enabled: AtomicBool,
30}
31
32pub(crate) struct StatsRun {
34 pub stats: Stats,
35}
36
37impl StatsRun {
38 pub fn new(sender: watch::Sender<TransferStats>) -> Self {
39 sender.send_replace(TransferStats::default());
40 Self {
41 stats: Stats(Arc::new(Inner {
42 sender,
43 enabled: AtomicBool::new(true),
44 })),
45 }
46 }
47}
48
49impl Drop for StatsRun {
50 fn drop(&mut self) {
51 self.stats.0.enabled.store(false, Ordering::SeqCst);
52 self.stats.0.sender.send_modify(|stats| {
53 *stats = TransferStats {
54 listing_finished: stats.listing_finished,
55 ..TransferStats::default()
56 };
57 });
58 }
59}
60
61impl Stats {
62 pub fn update(&self, update: impl FnOnce(&mut TransferStats)) {
63 self.0.sender.send_if_modified(|stats| {
64 if !self.0.enabled.load(Ordering::SeqCst) {
65 return false;
66 }
67 update(stats);
68 true
69 });
70 }
71
72 pub fn track(&self, counter: fn(&mut TransferStats) -> &mut usize) -> Activity {
73 self.update(|stats| *counter(stats) += 1);
74 Activity {
75 stats: self.clone(),
76 counter,
77 }
78 }
79}
80
81pub(crate) struct Activity {
82 stats: Stats,
83 counter: fn(&mut TransferStats) -> &mut usize,
84}
85
86impl Drop for Activity {
87 fn drop(&mut self) {
88 self.stats.update(|stats| *(self.counter)(stats) -= 1);
89 }
90}