1#![deny(missing_docs)]
16
17use std::sync::Arc;
18use std::sync::atomic::{AtomicBool, Ordering};
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
25pub struct OperationId(pub u64);
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29#[non_exhaustive]
30pub enum Stage {
31 Downloading,
33 Extracting,
35 Installing,
37 Uninstalling,
40 Enabling,
42 Disabling,
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48#[non_exhaustive]
49pub enum StageUpdate {
50 Started {
52 total: Option<u64>,
54 },
55 Advanced {
57 done: u64,
59 total: Option<u64>,
61 },
62 Finished,
65}
66
67#[derive(Debug, Clone, PartialEq, Eq)]
69#[non_exhaustive]
70pub struct ProgressEvent {
71 pub operation: OperationId,
73 pub package: String,
75 pub stage: Stage,
77 pub update: StageUpdate,
79}
80
81pub trait ProgressSink: Send + Sync {
87 fn report(&self, event: ProgressEvent);
89}
90
91impl<F> ProgressSink for F
92where
93 F: Fn(ProgressEvent) + Send + Sync,
94{
95 fn report(&self, event: ProgressEvent) {
96 self(event)
97 }
98}
99
100#[derive(Debug, Clone, Default)]
105pub struct CancelToken(Arc<AtomicBool>);
106
107impl CancelToken {
108 pub fn new() -> Self {
110 Self::default()
111 }
112
113 pub fn cancel(&self) {
115 self.0.store(true, Ordering::SeqCst);
116 }
117
118 pub fn is_cancelled(&self) -> bool {
120 self.0.load(Ordering::SeqCst)
121 }
122}
123
124#[derive(Clone, Default)]
146pub struct Operation {
147 id: OperationId,
148 sink: Option<Arc<dyn ProgressSink>>,
149 cancel: CancelToken,
150}
151
152impl std::fmt::Debug for Operation {
153 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154 f.debug_struct("Operation")
155 .field("id", &self.id)
156 .field("reports_progress", &self.sink.is_some())
157 .field("cancel", &self.cancel)
158 .finish()
159 }
160}
161
162impl Operation {
163 pub fn new(id: OperationId) -> Self {
165 Self {
166 id,
167 ..Self::default()
168 }
169 }
170
171 pub fn with_progress(mut self, sink: impl ProgressSink + 'static) -> Self {
173 self.sink = Some(Arc::new(sink));
174
175 self
176 }
177
178 pub fn with_cancel(mut self, token: CancelToken) -> Self {
181 self.cancel = token;
182
183 self
184 }
185
186 pub fn id(&self) -> OperationId {
188 self.id
189 }
190
191 pub fn cancel_token(&self) -> CancelToken {
193 self.cancel.clone()
194 }
195
196 pub fn is_cancelled(&self) -> bool {
198 self.cancel.is_cancelled()
199 }
200
201 #[cfg(feature = "io")]
205 pub(crate) fn stage(&self, package: &str, stage: Stage, total: Option<u64>) -> StageProgress {
206 let progress = StageProgress {
207 operation: self.clone(),
208 package: package.to_string(),
209 stage,
210 total,
211 };
212
213 progress.send(StageUpdate::Started { total });
214
215 progress
216 }
217
218 #[cfg(feature = "io")]
219 fn send(&self, package: &str, stage: Stage, update: StageUpdate) {
220 if let Some(sink) = &self.sink {
221 sink.report(ProgressEvent {
222 operation: self.id,
223 package: package.to_string(),
224 stage,
225 update,
226 });
227 }
228 }
229}
230
231#[cfg(feature = "io")]
233pub(crate) struct StageProgress {
234 operation: Operation,
235 package: String,
236 stage: Stage,
237 total: Option<u64>,
238}
239
240#[cfg(feature = "io")]
241impl StageProgress {
242 pub(crate) fn advance(&self, done: u64) {
244 self.send(StageUpdate::Advanced {
245 done,
246 total: self.total,
247 });
248 }
249
250 pub(crate) fn set_total(&mut self, total: u64) {
252 self.total = Some(total);
253 }
254
255 fn send(&self, update: StageUpdate) {
256 self.operation.send(&self.package, self.stage, update);
257 }
258}
259
260#[cfg(feature = "io")]
261impl Drop for StageProgress {
262 fn drop(&mut self) {
263 self.send(StageUpdate::Finished);
264 }
265}
266
267#[cfg(feature = "io")]
270pub(crate) struct OperationDownloads {
271 operation: Operation,
272 inner: Arc<dyn ProgressReporter>,
273}
274
275#[cfg(feature = "io")]
276impl OperationDownloads {
277 pub(crate) fn new(operation: Operation, inner: Arc<dyn ProgressReporter>) -> Self {
278 Self { operation, inner }
279 }
280}
281
282#[cfg(feature = "io")]
283impl ProgressReporter for OperationDownloads {
284 fn begin(&self, label: &str, total: Option<u64>) -> Box<dyn ProgressHandle> {
285 let package = crate::extract::parse_package_filename(label)
286 .map(|(full_name, _)| full_name)
287 .unwrap_or_else(|| label.to_string());
288
289 Box::new(OperationDownload {
290 inner: self.inner.begin(label, total),
291 stage: std::sync::Mutex::new(Some(DownloadStage {
292 progress: self.operation.stage(&package, Stage::Downloading, total),
293 done: 0,
294 sent: (0, total),
295 })),
296 })
297 }
298}
299
300#[cfg(feature = "io")]
302const UNSIZED_DOWNLOAD_STEP: u64 = 256 * 1024;
303
304#[cfg(feature = "io")]
311struct OperationDownload {
312 inner: Box<dyn ProgressHandle>,
313 stage: std::sync::Mutex<Option<DownloadStage>>,
314}
315
316#[cfg(feature = "io")]
317struct DownloadStage {
318 progress: StageProgress,
319 done: u64,
320 sent: (u64, Option<u64>),
322}
323
324#[cfg(feature = "io")]
325impl DownloadStage {
326 fn send_if_moved(&mut self) {
327 let (sent_done, sent_total) = self.sent;
328 let total = self.progress.total;
329 let moved = total != sent_total
330 || self.done < sent_done
331 || match total {
332 Some(total) => percent(self.done, total) != percent(sent_done, total),
333 None => self.done - sent_done >= UNSIZED_DOWNLOAD_STEP,
334 };
335
336 if moved {
337 self.send();
338 }
339 }
340
341 fn send(&mut self) {
342 self.progress.advance(self.done);
343 self.sent = (self.done, self.progress.total);
344 }
345}
346
347#[cfg(feature = "io")]
348fn percent(done: u64, total: u64) -> u128 {
349 match total {
350 0 => 100,
351 total => u128::from(done) * 100 / u128::from(total),
352 }
353}
354
355#[cfg(feature = "io")]
356impl OperationDownload {
357 fn update(&self, change: impl FnOnce(&mut DownloadStage)) {
358 let mut guard = self
359 .stage
360 .lock()
361 .unwrap_or_else(std::sync::PoisonError::into_inner);
362
363 if let Some(stage) = guard.as_mut() {
364 change(stage);
365 stage.send_if_moved();
366 }
367 }
368}
369
370#[cfg(feature = "io")]
371impl ProgressHandle for OperationDownload {
372 fn inc(&self, delta: u64) {
373 self.inner.inc(delta);
374 self.update(|stage| stage.done += delta);
375 }
376
377 fn set_length(&self, total: u64) {
378 self.inner.set_length(total);
379 self.update(|stage| stage.progress.set_total(total));
380 }
381
382 fn set_position(&self, position: u64) {
383 self.inner.set_position(position);
384 self.update(|stage| stage.done = position);
385 }
386
387 fn set_message(&self, msg: &str) {
388 self.inner.set_message(msg);
389 }
390
391 fn finish(&self, msg: Option<&str>) {
392 self.inner.finish(msg);
393
394 let stage = self
395 .stage
396 .lock()
397 .unwrap_or_else(std::sync::PoisonError::into_inner)
398 .take();
399
400 if let Some(mut stage) = stage
401 && stage.sent.0 != stage.done
402 {
403 stage.send();
404 }
405 }
406}
407
408pub trait ProgressReporter: Send + Sync {
413 fn begin(&self, label: &str, total: Option<u64>) -> Box<dyn ProgressHandle>;
418}
419
420pub trait ProgressHandle: Send + Sync {
431 fn inc(&self, delta: u64);
433
434 fn set_length(&self, _total: u64) {}
439
440 fn set_position(&self, _position: u64) {}
448
449 fn set_message(&self, msg: &str);
451
452 fn finish(&self, msg: Option<&str>);
455}
456
457pub struct NoopProgress;
462
463impl ProgressReporter for NoopProgress {
464 fn begin(&self, _label: &str, _total: Option<u64>) -> Box<dyn ProgressHandle> {
465 Box::new(NoopHandle)
466 }
467}
468
469struct NoopHandle;
471
472impl ProgressHandle for NoopHandle {
473 fn inc(&self, _delta: u64) {}
474 fn set_message(&self, _msg: &str) {}
475 fn finish(&self, _msg: Option<&str>) {}
476}
477
478#[cfg(all(test, feature = "io"))]
479mod tests {
480 use super::*;
481 use std::sync::Mutex;
482
483 fn advanced_for(total: Option<u64>, chunks: u64, chunk: u64) -> Vec<u64> {
487 let events = Arc::new(Mutex::new(Vec::new()));
488 let sink = events.clone();
489 let operation = Operation::new(OperationId(1))
490 .with_progress(move |event: ProgressEvent| sink.lock().unwrap().push(event));
491 let downloads = OperationDownloads::new(operation, Arc::new(NoopProgress));
492 let handle = downloads.begin("Owner-ModA-1.0.0.zip", None);
493
494 if let Some(total) = total {
495 handle.set_length(total);
496 }
497
498 for _ in 0..chunks {
499 handle.inc(chunk);
500 }
501
502 handle.finish(None);
503
504 let events = events.lock().unwrap();
505
506 events
507 .iter()
508 .filter_map(|event| match event.update {
509 StageUpdate::Advanced { done, .. } => Some(done),
510 _ => None,
511 })
512 .collect()
513 }
514
515 #[test]
516 fn a_download_of_known_length_reports_each_percent_once() {
517 let advanced = advanced_for(Some(10 * 1024 * 1024), 10 * 1024, 1024);
518
519 assert_eq!(advanced.len(), 101, "the length, then 1% through 100%");
520 assert_eq!(advanced.first(), Some(&0));
521 assert_eq!(advanced.last(), Some(&(10 * 1024 * 1024)));
522 }
523
524 #[test]
525 fn a_download_of_unknown_length_reports_every_step_and_the_end() {
526 let advanced = advanced_for(None, 1000, 1024);
527
528 assert_eq!(
529 advanced,
530 [256 * 1024, 512 * 1024, 768 * 1024, 1000 * 1024],
531 "every 256 KiB, then the final position"
532 );
533 }
534}