-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathprogress.rs
More file actions
620 lines (562 loc) · 21.9 KB
/
progress.rs
File metadata and controls
620 lines (562 loc) · 21.9 KB
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
//! Progress Reporting for Long-Running Operations
//!
//! This module provides progress reporting functionality for multi-step operations
//! that take significant time to complete. It builds on top of `UserOutput` to
//! provide standardized progress updates with timing information.
//!
//! ## Features
//!
//! - **Step Tracking**: Reports progress through numbered steps (e.g., "[1/5] Loading configuration...")
//! - **Timing Information**: Tracks and reports duration for each completed step
//! - **Sub-step Support**: Shows detailed progress within major steps
//! - **Verbosity Aware**: Respects user verbosity settings through `UserOutput`
//! - **Consistent Format**: Standardized output format across all commands
//!
//! ## Example Usage
//!
//! ```rust
//! use std::sync::{Arc, Mutex};
//! use torrust_tracker_deployer_lib::presentation::progress::ProgressReporter;
//! use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let output = Arc::new(Mutex::new(UserOutput::new(VerbosityLevel::Normal)));
//! let mut progress = ProgressReporter::new(output, 3);
//!
//! // Step 1: Load configuration
//! progress.start_step("Loading configuration")?;
//! // ... perform operation ...
//! progress.complete_step(Some("Configuration loaded: test-env"))?;
//!
//! // Step 2: Provision with sub-steps
//! progress.start_step("Provisioning infrastructure")?;
//! progress.sub_step("Creating virtual machine")?;
//! progress.sub_step("Configuring network")?;
//! // ... perform operations ...
//! progress.complete_step(Some("Instance created: test-instance"))?;
//!
//! // Step 3: Finalize
//! progress.start_step("Finalizing environment")?;
//! // ... perform operation ...
//! progress.complete_step(None)?;
//!
//! // Complete with summary
//! progress.complete("Environment 'test-env' created successfully")?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Output Format
//!
//! The progress reporter generates output like:
//!
//! ```text
//! ⏳ [1/3] Loading configuration...
//! ✓ Configuration loaded: test-env (took 150ms)
//! ⏳ [2/3] Provisioning infrastructure...
//! → Creating virtual machine
//! → Configuring network
//! ✓ Instance created: test-instance (took 2.3s)
//! ⏳ [3/3] Finalizing environment...
//! ✓ Done (took 450ms)
//! ✅ Environment 'test-env' created successfully
//! ```
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use thiserror::Error;
use crate::presentation::user_output::UserOutput;
/// Errors that can occur during progress reporting
#[derive(Debug, Error)]
pub enum ProgressReporterError {
/// `UserOutput` mutex was poisoned
///
/// The shared `UserOutput` mutex was poisoned by a panic in another thread.
/// This indicates a critical internal error.
#[error(
"Internal error: UserOutput mutex was poisoned
Tip: This is a critical bug - please report it with full logs using --log-output file-and-stderr"
)]
UserOutputMutexPoisoned,
}
/// Progress reporter for multi-step operations
///
/// Tracks progress through multiple steps of a long-running operation,
/// providing clear feedback with step numbers, descriptions, and timing.
///
/// # Examples
///
/// ```rust
/// use std::sync::{Arc, Mutex};
/// use torrust_tracker_deployer_lib::presentation::progress::ProgressReporter;
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let output = Arc::new(Mutex::new(UserOutput::new(VerbosityLevel::Normal)));
/// let mut progress = ProgressReporter::new(output, 2);
///
/// progress.start_step("Step 1")?;
/// progress.complete_step(Some("Step 1 done"))?;
///
/// progress.start_step("Step 2")?;
/// progress.complete_step(None)?;
///
/// progress.complete("All done!")?;
/// # Ok(())
/// # }
/// ```
pub struct ProgressReporter {
output: Arc<Mutex<UserOutput>>,
total_steps: usize,
current_step: usize,
step_start: Option<Instant>,
}
impl ProgressReporter {
/// Create a new progress reporter
///
/// # Arguments
///
/// * `output` - Shared user output handler for displaying messages
/// * `total_steps` - Total number of steps in the operation
///
/// # Examples
///
/// ```rust
/// use std::sync::{Arc, Mutex};
/// use torrust_tracker_deployer_lib::presentation::progress::ProgressReporter;
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
///
/// let output = Arc::new(Mutex::new(UserOutput::new(VerbosityLevel::Normal)));
/// let progress = ProgressReporter::new(output, 5);
/// ```
#[must_use]
pub fn new(output: Arc<Mutex<UserOutput>>, total_steps: usize) -> Self {
Self {
output,
total_steps,
current_step: 0,
step_start: None,
}
}
/// Start a new step with a description
///
/// Increments the current step counter and displays a progress message
/// in the format `[current/total] description...`.
///
/// # Arguments
///
/// * `description` - Human-readable description of what this step does
///
/// # Errors
///
/// Returns `ProgressReporterError::UserOutputMutexPoisoned` if the mutex is poisoned.
///
/// # Examples
///
/// ```rust
/// use std::sync::{Arc, Mutex};
/// use torrust_tracker_deployer_lib::presentation::progress::ProgressReporter;
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let output = Arc::new(Mutex::new(UserOutput::new(VerbosityLevel::Normal)));
/// let mut progress = ProgressReporter::new(output, 3);
///
/// progress.start_step("Loading configuration")?;
/// // Output: ⏳ [1/3] Loading configuration...
/// # Ok(())
/// # }
/// ```
pub fn start_step(&mut self, description: &str) -> Result<(), ProgressReporterError> {
self.current_step += 1;
self.step_start = Some(Instant::now());
self.output
.lock()
.map_err(|_| ProgressReporterError::UserOutputMutexPoisoned)?
.progress(&format!(
"[{}/{}] {}...",
self.current_step, self.total_steps, description
));
Ok(())
}
/// Complete the current step with optional result message
///
/// Displays a completion message with timing information.
/// The message shows either the provided result or a generic "Done" message.
///
/// # Arguments
///
/// * `result` - Optional description of what was accomplished
///
/// # Errors
///
/// Returns `ProgressReporterError::UserOutputMutexPoisoned` if the mutex is poisoned.
///
/// # Examples
///
/// ```rust
/// use std::sync::{Arc, Mutex};
/// use torrust_tracker_deployer_lib::presentation::progress::ProgressReporter;
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let output = Arc::new(Mutex::new(UserOutput::new(VerbosityLevel::Normal)));
/// let mut progress = ProgressReporter::new(output, 2);
///
/// progress.start_step("Loading data")?;
/// progress.complete_step(Some("Data loaded successfully"))?;
/// // Output: ✓ Data loaded successfully (took 150ms)
///
/// progress.start_step("Processing")?;
/// progress.complete_step(None)?;
/// // Output: ✓ Done (took 2.3s)
/// # Ok(())
/// # }
/// ```
pub fn complete_step(&mut self, result: Option<&str>) -> Result<(), ProgressReporterError> {
if let Some(start) = self.step_start {
let duration = start.elapsed();
let mut output = self
.output
.lock()
.map_err(|_| ProgressReporterError::UserOutputMutexPoisoned)?;
if let Some(msg) = result {
output.result(&format!(" ✓ {} (took {})", msg, format_duration(duration)));
} else {
output.result(&format!(" ✓ Done (took {})", format_duration(duration)));
}
}
self.step_start = None;
Ok(())
}
/// Report a sub-step within the current step
///
/// Displays an indented message indicating progress within the current step.
/// Useful for showing detailed progress without starting a new numbered step.
///
/// # Arguments
///
/// * `description` - What is currently happening within this step
///
/// # Errors
///
/// Returns `ProgressReporterError::UserOutputMutexPoisoned` if the mutex is poisoned.
///
/// # Examples
///
/// ```rust
/// use std::sync::{Arc, Mutex};
/// use torrust_tracker_deployer_lib::presentation::progress::ProgressReporter;
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let output = Arc::new(Mutex::new(UserOutput::new(VerbosityLevel::Normal)));
/// let mut progress = ProgressReporter::new(output.clone(), 1);
///
/// progress.start_step("Provisioning infrastructure")?;
/// progress.sub_step("Creating virtual machine")?;
/// progress.sub_step("Configuring network")?;
/// progress.sub_step("Setting up storage")?;
/// progress.complete_step(Some("Infrastructure ready"))?;
/// # Ok(())
/// # }
/// ```
pub fn sub_step(&mut self, description: &str) -> Result<(), ProgressReporterError> {
self.output
.lock()
.map_err(|_| ProgressReporterError::UserOutputMutexPoisoned)?
.result(&format!(" → {description}"));
Ok(())
}
/// Complete all steps and show summary
///
/// Displays a final success message indicating the entire operation completed.
/// This should be called after all steps are done.
///
/// # Arguments
///
/// * `summary` - Final success message describing what was accomplished
///
/// # Errors
///
/// Returns `ProgressReporterError::UserOutputMutexPoisoned` if the mutex is poisoned.
///
/// # Examples
///
/// ```rust
/// use std::sync::{Arc, Mutex};
/// use torrust_tracker_deployer_lib::presentation::progress::ProgressReporter;
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let output = Arc::new(Mutex::new(UserOutput::new(VerbosityLevel::Normal)));
/// let mut progress = ProgressReporter::new(output.clone(), 1);
///
/// progress.start_step("Creating environment")?;
/// progress.complete_step(None)?;
/// progress.complete("Environment 'test-env' created successfully")?;
/// // Output: ✅ Environment 'test-env' created successfully
/// # Ok(())
/// # }
/// ```
pub fn complete(&mut self, summary: &str) -> Result<(), ProgressReporterError> {
self.output
.lock()
.map_err(|_| ProgressReporterError::UserOutputMutexPoisoned)?
.success(summary);
Ok(())
}
/// Get a reference to the shared `UserOutput`
///
/// This allows using other output methods (like `error`, `warn`)
/// while progress is being tracked.
///
/// # Examples
///
/// ```rust
/// use std::sync::{Arc, Mutex};
/// use torrust_tracker_deployer_lib::presentation::progress::ProgressReporter;
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
///
/// let output = Arc::new(Mutex::new(UserOutput::new(VerbosityLevel::Normal)));
/// let mut progress = ProgressReporter::new(output.clone(), 1);
///
/// progress.start_step("Checking conditions");
/// progress.output().lock().unwrap().warn("Some non-critical warning");
/// progress.complete_step(None);
/// ```
#[must_use]
pub fn output(&self) -> &Arc<Mutex<UserOutput>> {
&self.output
}
}
/// Format duration in a human-readable way
///
/// Converts durations to appropriate units:
/// - Less than 1 second: milliseconds (e.g., "150ms")
/// - 1 second or more: seconds with 1 decimal place (e.g., "2.3s")
///
/// # Arguments
///
/// * `duration` - The duration to format
///
/// # Returns
///
/// A human-readable string representation of the duration
fn format_duration(duration: Duration) -> String {
let millis = duration.as_millis();
if millis < 1000 {
format!("{millis}ms")
} else {
format!("{:.1}s", duration.as_secs_f64())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::presentation::user_output::test_support::TestUserOutput;
use crate::presentation::user_output::VerbosityLevel;
#[test]
fn it_should_create_progress_reporter_with_total_steps() {
let test_output = TestUserOutput::new(VerbosityLevel::Normal);
let (output, _stdout, _stderr) = test_output.into_wrapped();
let progress = ProgressReporter::new(output, 5);
assert_eq!(progress.total_steps, 5);
assert_eq!(progress.current_step, 0);
assert!(progress.step_start.is_none());
}
#[test]
fn it_should_start_step_and_increment_counter() {
let test_output = TestUserOutput::new(VerbosityLevel::Normal);
let (output, _stdout, stderr) = test_output.into_wrapped();
let mut progress = ProgressReporter::new(output, 3);
progress
.start_step("Loading configuration")
.expect("Failed to start step");
assert_eq!(progress.current_step, 1);
assert!(progress.step_start.is_some());
let stderr_content = String::from_utf8(stderr.lock().unwrap().clone()).unwrap();
assert!(stderr_content.contains("[1/3] Loading configuration..."));
}
#[test]
fn it_should_track_multiple_steps() {
let test_output = TestUserOutput::new(VerbosityLevel::Normal);
let (output, _stdout, stderr) = test_output.into_wrapped();
let mut progress = ProgressReporter::new(output, 3);
progress
.start_step("Step 1")
.expect("Failed to start step 1");
assert_eq!(progress.current_step, 1);
progress
.start_step("Step 2")
.expect("Failed to start step 2");
assert_eq!(progress.current_step, 2);
progress
.start_step("Step 3")
.expect("Failed to start step 3");
assert_eq!(progress.current_step, 3);
let stderr_content = String::from_utf8(stderr.lock().unwrap().clone()).unwrap();
assert!(stderr_content.contains("[1/3] Step 1..."));
assert!(stderr_content.contains("[2/3] Step 2..."));
assert!(stderr_content.contains("[3/3] Step 3..."));
}
#[test]
fn it_should_complete_step_with_result_message() {
let test_output = TestUserOutput::new(VerbosityLevel::Normal);
let (output, stdout, _stderr) = test_output.into_wrapped();
let mut progress = ProgressReporter::new(output, 1);
progress
.start_step("Loading data")
.expect("Failed to start step");
progress
.complete_step(Some("Data loaded successfully"))
.expect("Failed to complete step");
let stdout_content = String::from_utf8(stdout.lock().unwrap().clone()).unwrap();
assert!(stdout_content.contains("✓ Data loaded successfully"));
assert!(stdout_content.contains("took"));
assert!(progress.step_start.is_none());
}
#[test]
fn it_should_complete_step_without_result_message() {
let test_output = TestUserOutput::new(VerbosityLevel::Normal);
let (output, stdout, _stderr) = test_output.into_wrapped();
let mut progress = ProgressReporter::new(output, 1);
progress
.start_step("Processing")
.expect("Failed to start step");
progress
.complete_step(None)
.expect("Failed to complete step");
let stdout_content = String::from_utf8(stdout.lock().unwrap().clone()).unwrap();
assert!(stdout_content.contains("✓ Done"));
assert!(stdout_content.contains("took"));
assert!(progress.step_start.is_none());
}
#[test]
fn it_should_report_sub_steps() {
let test_output = TestUserOutput::new(VerbosityLevel::Normal);
let (output, stdout, _stderr) = test_output.into_wrapped();
let mut progress = ProgressReporter::new(output, 1);
progress
.start_step("Provisioning")
.expect("Failed to start step");
progress
.sub_step("Creating VM")
.expect("Failed to report sub-step");
progress
.sub_step("Configuring network")
.expect("Failed to report sub-step");
progress
.complete_step(None)
.expect("Failed to complete step");
let stdout_content = String::from_utf8(stdout.lock().unwrap().clone()).unwrap();
assert!(stdout_content.contains("→ Creating VM"));
assert!(stdout_content.contains("→ Configuring network"));
}
#[test]
fn it_should_display_completion_summary() {
let test_output = TestUserOutput::new(VerbosityLevel::Normal);
let (output, _stdout, stderr) = test_output.into_wrapped();
let mut progress = ProgressReporter::new(output, 1);
progress
.start_step("Creating environment")
.expect("Failed to start step");
progress
.complete_step(None)
.expect("Failed to complete step");
progress
.complete("Environment created successfully")
.expect("Failed to complete");
let stderr_content = String::from_utf8(stderr.lock().unwrap().clone()).unwrap();
assert!(stderr_content.contains("✅ Environment created successfully"));
}
#[test]
fn it_should_provide_access_to_output() {
let test_output = TestUserOutput::new(VerbosityLevel::Normal);
let (output, _stdout, stderr) = test_output.into_wrapped();
let progress = ProgressReporter::new(output, 1);
progress
.output()
.lock()
.expect("UserOutput mutex poisoned")
.warn("Test warning");
let stderr_content = String::from_utf8(stderr.lock().unwrap().clone()).unwrap();
assert!(stderr_content.contains("⚠️ Test warning"));
}
#[test]
fn it_should_respect_verbosity_levels() {
let test_output = TestUserOutput::new(VerbosityLevel::Quiet);
let (output, _stdout, stderr) = test_output.into_wrapped();
let mut progress = ProgressReporter::new(output, 1);
progress.start_step("Step 1").expect("Failed to start step");
progress
.complete_step(Some("Done"))
.expect("Failed to complete step");
// At Quiet level, progress messages should not appear
let stderr_content = String::from_utf8(stderr.lock().unwrap().clone()).unwrap();
assert_eq!(stderr_content, "");
}
#[test]
fn it_should_format_milliseconds_correctly() {
let duration = Duration::from_millis(150);
assert_eq!(format_duration(duration), "150ms");
let duration = Duration::from_millis(999);
assert_eq!(format_duration(duration), "999ms");
}
#[test]
fn it_should_format_seconds_correctly() {
let duration = Duration::from_millis(1000);
assert_eq!(format_duration(duration), "1.0s");
let duration = Duration::from_millis(2345);
assert_eq!(format_duration(duration), "2.3s");
let duration = Duration::from_secs(10);
assert_eq!(format_duration(duration), "10.0s");
}
#[test]
fn it_should_handle_full_workflow() {
let test_output = TestUserOutput::new(VerbosityLevel::Normal);
let (output, stdout, stderr) = test_output.into_wrapped();
let mut progress = ProgressReporter::new(output, 3);
// Step 1
progress
.start_step("Loading configuration")
.expect("Failed to start step 1");
progress
.complete_step(Some("Configuration loaded: test-env"))
.expect("Failed to complete step 1");
// Step 2 with sub-steps
progress
.start_step("Provisioning infrastructure")
.expect("Failed to start step 2");
progress
.sub_step("Creating virtual machine")
.expect("Failed to report sub-step");
progress
.sub_step("Configuring network")
.expect("Failed to report sub-step");
progress
.complete_step(Some("Instance created: test-instance"))
.expect("Failed to complete step 2");
// Step 3
progress
.start_step("Finalizing environment")
.expect("Failed to start step 3");
progress
.complete_step(None)
.expect("Failed to complete step 3");
// Complete
progress
.complete("Environment 'test-env' created successfully")
.expect("Failed to complete");
let stderr_content = String::from_utf8(stderr.lock().unwrap().clone()).unwrap();
assert!(stderr_content.contains("[1/3] Loading configuration..."));
assert!(stderr_content.contains("[2/3] Provisioning infrastructure..."));
assert!(stderr_content.contains("[3/3] Finalizing environment..."));
assert!(stderr_content.contains("✅ Environment 'test-env' created successfully"));
let stdout_content = String::from_utf8(stdout.lock().unwrap().clone()).unwrap();
assert!(stdout_content.contains("✓ Configuration loaded: test-env"));
assert!(stdout_content.contains("→ Creating virtual machine"));
assert!(stdout_content.contains("→ Configuring network"));
assert!(stdout_content.contains("✓ Instance created: test-instance"));
assert!(stdout_content.contains("✓ Done"));
}
}