#![deny(missing_docs)]
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub struct OperationId(pub u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Stage {
Downloading,
Extracting,
Installing,
Uninstalling,
Enabling,
Disabling,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum StageUpdate {
Started {
total: Option<u64>,
},
Advanced {
done: u64,
total: Option<u64>,
},
Finished,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ProgressEvent {
pub operation: OperationId,
pub package: String,
pub stage: Stage,
pub update: StageUpdate,
}
pub trait ProgressSink: Send + Sync {
fn report(&self, event: ProgressEvent);
}
impl<F> ProgressSink for F
where
F: Fn(ProgressEvent) + Send + Sync,
{
fn report(&self, event: ProgressEvent) {
self(event)
}
}
#[derive(Debug, Clone, Default)]
pub struct CancelToken(Arc<AtomicBool>);
impl CancelToken {
pub fn new() -> Self {
Self::default()
}
pub fn cancel(&self) {
self.0.store(true, Ordering::SeqCst);
}
pub fn is_cancelled(&self) -> bool {
self.0.load(Ordering::SeqCst)
}
}
#[derive(Clone, Default)]
pub struct Operation {
id: OperationId,
sink: Option<Arc<dyn ProgressSink>>,
cancel: CancelToken,
}
impl std::fmt::Debug for Operation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Operation")
.field("id", &self.id)
.field("reports_progress", &self.sink.is_some())
.field("cancel", &self.cancel)
.finish()
}
}
impl Operation {
pub fn new(id: OperationId) -> Self {
Self {
id,
..Self::default()
}
}
pub fn with_progress(mut self, sink: impl ProgressSink + 'static) -> Self {
self.sink = Some(Arc::new(sink));
self
}
pub fn with_cancel(mut self, token: CancelToken) -> Self {
self.cancel = token;
self
}
pub fn id(&self) -> OperationId {
self.id
}
pub fn cancel_token(&self) -> CancelToken {
self.cancel.clone()
}
pub fn is_cancelled(&self) -> bool {
self.cancel.is_cancelled()
}
#[cfg(feature = "io")]
pub(crate) fn stage(&self, package: &str, stage: Stage, total: Option<u64>) -> StageProgress {
let progress = StageProgress {
operation: self.clone(),
package: package.to_string(),
stage,
total,
};
progress.send(StageUpdate::Started { total });
progress
}
#[cfg(feature = "io")]
fn send(&self, package: &str, stage: Stage, update: StageUpdate) {
if let Some(sink) = &self.sink {
sink.report(ProgressEvent {
operation: self.id,
package: package.to_string(),
stage,
update,
});
}
}
}
#[cfg(feature = "io")]
pub(crate) struct StageProgress {
operation: Operation,
package: String,
stage: Stage,
total: Option<u64>,
}
#[cfg(feature = "io")]
impl StageProgress {
pub(crate) fn advance(&self, done: u64) {
self.send(StageUpdate::Advanced {
done,
total: self.total,
});
}
pub(crate) fn set_total(&mut self, total: u64) {
self.total = Some(total);
}
fn send(&self, update: StageUpdate) {
self.operation.send(&self.package, self.stage, update);
}
}
#[cfg(feature = "io")]
impl Drop for StageProgress {
fn drop(&mut self) {
self.send(StageUpdate::Finished);
}
}
#[cfg(feature = "io")]
pub(crate) struct OperationDownloads {
operation: Operation,
inner: Arc<dyn ProgressReporter>,
}
#[cfg(feature = "io")]
impl OperationDownloads {
pub(crate) fn new(operation: Operation, inner: Arc<dyn ProgressReporter>) -> Self {
Self { operation, inner }
}
}
#[cfg(feature = "io")]
impl ProgressReporter for OperationDownloads {
fn begin(&self, label: &str, total: Option<u64>) -> Box<dyn ProgressHandle> {
let package = crate::extract::parse_package_filename(label)
.map(|(full_name, _)| full_name)
.unwrap_or_else(|| label.to_string());
Box::new(OperationDownload {
inner: self.inner.begin(label, total),
stage: std::sync::Mutex::new(Some(DownloadStage {
progress: self.operation.stage(&package, Stage::Downloading, total),
done: 0,
sent: (0, total),
})),
})
}
}
#[cfg(feature = "io")]
const UNSIZED_DOWNLOAD_STEP: u64 = 256 * 1024;
#[cfg(feature = "io")]
struct OperationDownload {
inner: Box<dyn ProgressHandle>,
stage: std::sync::Mutex<Option<DownloadStage>>,
}
#[cfg(feature = "io")]
struct DownloadStage {
progress: StageProgress,
done: u64,
sent: (u64, Option<u64>),
}
#[cfg(feature = "io")]
impl DownloadStage {
fn send_if_moved(&mut self) {
let (sent_done, sent_total) = self.sent;
let total = self.progress.total;
let moved = total != sent_total
|| self.done < sent_done
|| match total {
Some(total) => percent(self.done, total) != percent(sent_done, total),
None => self.done - sent_done >= UNSIZED_DOWNLOAD_STEP,
};
if moved {
self.send();
}
}
fn send(&mut self) {
self.progress.advance(self.done);
self.sent = (self.done, self.progress.total);
}
}
#[cfg(feature = "io")]
fn percent(done: u64, total: u64) -> u128 {
match total {
0 => 100,
total => u128::from(done) * 100 / u128::from(total),
}
}
#[cfg(feature = "io")]
impl OperationDownload {
fn update(&self, change: impl FnOnce(&mut DownloadStage)) {
let mut guard = self
.stage
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(stage) = guard.as_mut() {
change(stage);
stage.send_if_moved();
}
}
}
#[cfg(feature = "io")]
impl ProgressHandle for OperationDownload {
fn inc(&self, delta: u64) {
self.inner.inc(delta);
self.update(|stage| stage.done += delta);
}
fn set_length(&self, total: u64) {
self.inner.set_length(total);
self.update(|stage| stage.progress.set_total(total));
}
fn set_position(&self, position: u64) {
self.inner.set_position(position);
self.update(|stage| stage.done = position);
}
fn set_message(&self, msg: &str) {
self.inner.set_message(msg);
}
fn finish(&self, msg: Option<&str>) {
self.inner.finish(msg);
let stage = self
.stage
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take();
if let Some(mut stage) = stage
&& stage.sent.0 != stage.done
{
stage.send();
}
}
}
pub trait ProgressReporter: Send + Sync {
fn begin(&self, label: &str, total: Option<u64>) -> Box<dyn ProgressHandle>;
}
pub trait ProgressHandle: Send + Sync {
fn inc(&self, delta: u64);
fn set_length(&self, _total: u64) {}
fn set_position(&self, _position: u64) {}
fn set_message(&self, msg: &str);
fn finish(&self, msg: Option<&str>);
}
pub struct NoopProgress;
impl ProgressReporter for NoopProgress {
fn begin(&self, _label: &str, _total: Option<u64>) -> Box<dyn ProgressHandle> {
Box::new(NoopHandle)
}
}
struct NoopHandle;
impl ProgressHandle for NoopHandle {
fn inc(&self, _delta: u64) {}
fn set_message(&self, _msg: &str) {}
fn finish(&self, _msg: Option<&str>) {}
}
#[cfg(all(test, feature = "io"))]
mod tests {
use super::*;
use std::sync::Mutex;
fn advanced_for(total: Option<u64>, chunks: u64, chunk: u64) -> Vec<u64> {
let events = Arc::new(Mutex::new(Vec::new()));
let sink = events.clone();
let operation = Operation::new(OperationId(1))
.with_progress(move |event: ProgressEvent| sink.lock().unwrap().push(event));
let downloads = OperationDownloads::new(operation, Arc::new(NoopProgress));
let handle = downloads.begin("Owner-ModA-1.0.0.zip", None);
if let Some(total) = total {
handle.set_length(total);
}
for _ in 0..chunks {
handle.inc(chunk);
}
handle.finish(None);
let events = events.lock().unwrap();
events
.iter()
.filter_map(|event| match event.update {
StageUpdate::Advanced { done, .. } => Some(done),
_ => None,
})
.collect()
}
#[test]
fn a_download_of_known_length_reports_each_percent_once() {
let advanced = advanced_for(Some(10 * 1024 * 1024), 10 * 1024, 1024);
assert_eq!(advanced.len(), 101, "the length, then 1% through 100%");
assert_eq!(advanced.first(), Some(&0));
assert_eq!(advanced.last(), Some(&(10 * 1024 * 1024)));
}
#[test]
fn a_download_of_unknown_length_reports_every_step_and_the_end() {
let advanced = advanced_for(None, 1000, 1024);
assert_eq!(
advanced,
[256 * 1024, 512 * 1024, 768 * 1024, 1000 * 1024],
"every 256 KiB, then the final position"
);
}
}