1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
//! Utility code for CLI implementations.
use std::collections::HashMap;
use std::fmt;
use chrono::TimeDelta;
use tokio::sync::broadcast::error::RecvError;
use tokio::sync::broadcast::{self};
use tokio_util::sync::CancellationToken;
use tracing::Span;
use tracing::warn_span;
use tracing_indicatif::span_ext::IndicatifSpanExt;
use tracing_indicatif::style::ProgressStyle;
use crate::Location;
use crate::TransferEvent;
use crate::UrlExt;
/// Extension methods for [`TimeDelta`].
#[cfg_attr(docsrs, doc(cfg(feature = "cli")))]
pub trait TimeDeltaExt {
/// Returns a display implementation for `TimeDelta` that displays days,
/// hours, minutes, and seconds in english.
fn english(&self) -> impl fmt::Display;
}
impl TimeDeltaExt for TimeDelta {
fn english(&self) -> impl fmt::Display {
struct Display(TimeDelta);
impl fmt::Display for Display {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.0.num_seconds() == 0 {
return write!(f, "0 seconds");
}
let days = self.0.num_days();
let hours = self.0.num_hours() - (days * 24);
let minutes = self.0.num_minutes() - (days * 24 * 60) - (hours * 60);
let seconds = self.0.num_seconds()
- (days * 24 * 60 * 60)
- (hours * 60 * 60)
- (minutes * 60);
if days > 0 {
write!(f, "{days} day{s}", s = if days == 1 { "" } else { "s" })?;
}
if hours > 0 {
if days > 0 {
write!(f, ", ")?;
}
write!(f, "{hours} hour{s}", s = if hours == 1 { "" } else { "s" })?;
}
if minutes > 0 {
if days > 0 || hours > 0 {
write!(f, ", ")?;
}
write!(
f,
"{minutes} minute{s}",
s = if minutes == 1 { "" } else { "s" }
)?;
}
if seconds > 0 {
if days > 0 || hours > 0 || minutes > 0 {
write!(f, ", ")?;
}
write!(
f,
"{seconds} second{s}",
s = if seconds == 1 { "" } else { "s" }
)?;
}
Ok(())
}
}
Display(*self)
}
}
/// Represents statistics from transferring files.
#[cfg(feature = "cli")]
#[cfg_attr(docsrs, doc(cfg(feature = "cli")))]
#[derive(Debug, Clone, Copy, Default)]
pub struct TransferStats {
/// The number of files that were transferred.
pub files: usize,
/// The total number of bytes transferred for all files.
pub bytes: u64,
}
/// Handles events that may occur during a copy operation.
///
/// This is responsible for showing and updating progress bars for files
/// being transferred.
///
/// Used from CLI implementations.
///
/// Returns `None` if the event stream lagged and reliable statistics aren't
/// available.
///
/// Returns `Some` if the event stream did not lag and reliable statistics are
/// available.
#[cfg_attr(docsrs, doc(cfg(feature = "cli")))]
pub async fn handle_events(
mut events: broadcast::Receiver<TransferEvent>,
colorize: bool,
cancel: CancellationToken,
) -> Option<TransferStats> {
struct BlockTransferState {
/// The number of bytes that were transferred for the block.
transferred: u64,
}
struct TransferState {
/// The progress bar to display for a transfer.
bar: Span,
/// The total number of bytes transferred.
transferred: u64,
/// Block transfer state.
block_transfers: HashMap<u64, BlockTransferState>,
}
let mut indeterminate = None;
let mut transfers = HashMap::new();
let mut stats = TransferStats::default();
loop {
tokio::select! {
_ = cancel.cancelled() => break,
event = events.recv() => match event {
Ok(event) if indeterminate.is_none() => match event {
TransferEvent::TransferStarted { id, source, destination, size, .. } => {
let bar = warn_span!("progress");
let style = match size {
Some(size) => {
bar.pb_set_length(size);
ProgressStyle::with_template(
if colorize {
"[{elapsed_precise:.cyan/blue}] {bar:20.cyan/blue} {bytes:.cyan/blue} / {total_bytes:.cyan/blue} ({bytes_per_sec:.cyan/blue}) [ETA {eta_precise:.cyan/blue}]: {msg}"
} else {
"[{elapsed_precise}] {bar:20} {bytes} / {total_bytes} ({bytes_per_sec}) [ETA {eta_precise}]: {msg}"
}
)
.unwrap()
}
None => ProgressStyle::with_template(
if colorize {
"[{elapsed_precise:.cyan/blue}] {spinner:.cyan/blue} {bytes:.cyan/blue} ({bytes_per_sec:.cyan/blue}): {msg}"
} else {
"[{elapsed_precise}] {spinner} {bytes} ({bytes_per_sec}): {msg}"
}
)
.unwrap(),
};
let message = match (&source, &destination) {
// Use the source path for local file copies
(Location::Path(path), Location::Path(_)) => format!("copying `{path}`", path = path.to_str().unwrap_or("<path not UTF-8>")),
// Use the source path for uploads
(Location::Path(path), _) => format!("uploading `{path}`", path = path.to_str().unwrap_or("<path not UTF-8>")),
// Use the remote URL for downloads
(Location::Url(url), _) => format!("downloading `{url}`", url = url.display())
};
bar.pb_set_style(&style);
bar.pb_set_message(&message);
bar.pb_start();
transfers.insert(
id,
TransferState {
bar,
transferred: 0,
block_transfers: HashMap::new(),
},
);
}
TransferEvent::BlockStarted { id, block, .. } => {
if let Some(transfer) = transfers.get_mut(&id) {
transfer
.block_transfers
.insert(block, BlockTransferState { transferred: 0 });
}
}
TransferEvent::BlockProgress {
id,
block,
transferred,
} => {
if let Some(transfer) = transfers.get_mut(&id)
&& let Some(block) = transfer.block_transfers.get_mut(&block)
{
transfer.transferred += transferred - block.transferred;
block.transferred = transferred;
transfer.bar.pb_set_position(transfer.transferred);
}
}
TransferEvent::BlockCompleted { id, block, failed } => {
if let Some(transfer) = transfers.get_mut(&id)
&& let Some(block) = transfer.block_transfers.remove(&block)
{
if failed {
transfer.transferred -= block.transferred;
}
transfer.bar.pb_set_position(transfer.transferred);
}
}
TransferEvent::BlockRestarted { id, block } => {
if let Some(transfer) = transfers.get_mut(&id)
&& let Some(block) = transfer.block_transfers.get_mut(&block)
{
transfer.transferred -= block.transferred;
block.transferred = 0;
transfer.bar.pb_set_position(transfer.transferred);
}
}
TransferEvent::TransferCompleted { id, failed } => {
if let Some(transfer) = transfers.remove(&id)
&& !failed
{
stats.files += 1;
stats.bytes += transfer.transferred;
}
}
},
Ok(_) => continue,
Err(RecvError::Closed) => break,
Err(RecvError::Lagged(_)) => {
// Clear the state to remove existing progress bars
transfers.clear();
// Show a single spinner progress bar for the remainder of the stream
let bar = warn_span!("progress");
bar.pb_set_style(
&ProgressStyle::with_template(
"{spinner:.cyan/blue} transfer progress is unavailable due to missed events",
)
.unwrap(),
);
bar.pb_start();
indeterminate = Some(bar);
}
}
}
}
if indeterminate.is_none() {
Some(stats)
} else {
None
}
}