qubit-progress 0.4.5

Generic progress reporting abstractions for Qubit Rust libraries
Documentation
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
/*******************************************************************************
 *
 *    Copyright (c) 2025 - 2026 Haixing Hu.
 *
 *    SPDX-License-Identifier: Apache-2.0
 *
 *    Licensed under the Apache License, Version 2.0.
 *
 ******************************************************************************/
use std::{
    thread,
    time::{
        Duration,
        Instant,
    },
};

use crate::{
    model::{
        ProgressCounters,
        ProgressEvent,
        ProgressPhase,
        ProgressStage,
    },
    reporter::ProgressReporter,
    running::{
        RunningProgressGuard,
        RunningProgressLoop,
    },
};

/// Tracks one progress-producing operation and reports lifecycle events.
///
/// `Progress` owns no operation-specific counters. Callers keep their own
/// domain state and pass freshly built [`ProgressCounters`] when reporting.
/// The run only manages elapsed time, periodic running-event throttling,
/// optional stage metadata, and forwarding immutable events to a reporter.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// use qubit_progress::{
///     ProgressCounters,
///     Progress,
///     WriterProgressReporter,
/// };
///
/// let reporter = WriterProgressReporter::from_writer(std::io::stdout());
/// let mut progress = Progress::new(&reporter, Duration::from_secs(5));
///
/// let started = progress.report_started(ProgressCounters::new(Some(2)));
/// assert!(started.elapsed().is_zero());
///
/// let running = ProgressCounters::new(Some(2))
///     .with_completed_count(1)
///     .with_active_count(1);
/// let _reported = progress.report_running_if_due(running);
///
/// let finished = ProgressCounters::new(Some(2))
///     .with_completed_count(2)
///     .with_succeeded_count(2);
/// let finished_event = progress.report_finished(finished);
/// assert!(finished_event.elapsed() >= started.elapsed());
/// ```
pub struct Progress<'a> {
    /// Reporter receiving lifecycle callbacks for this run.
    reporter: &'a dyn ProgressReporter,
    /// Monotonic start time used to compute elapsed durations.
    started_at: Instant,
    /// Minimum interval between due-based running callbacks.
    report_interval: Duration,
    /// Next monotonic instant at which a due-based running callback may fire.
    next_running_at: Instant,
    /// Optional stage metadata attached to every event emitted by this run.
    stage: Option<ProgressStage>,
}

impl<'a> Progress<'a> {
    /// Creates a progress run starting at the current instant.
    ///
    /// # Parameters
    ///
    /// * `reporter` - Reporter receiving progress events.
    /// * `report_interval` - Minimum delay between due-based running events.
    ///
    /// # Returns
    ///
    /// A progress run whose elapsed time is measured from now.
    #[inline]
    pub fn new(reporter: &'a dyn ProgressReporter, report_interval: Duration) -> Self {
        Self::from_start(reporter, report_interval, Instant::now())
    }

    /// Creates a progress run from an explicit start instant.
    ///
    /// # Parameters
    ///
    /// * `reporter` - Reporter receiving progress events.
    /// * `report_interval` - Minimum delay between due-based running events.
    /// * `started_at` - Monotonic instant representing operation start.
    ///
    /// # Returns
    ///
    /// A progress run using `started_at` for elapsed-time calculations.
    #[inline]
    fn from_start(
        reporter: &'a dyn ProgressReporter,
        report_interval: Duration,
        started_at: Instant,
    ) -> Self {
        Self {
            reporter,
            started_at,
            report_interval,
            next_running_at: next_instant(started_at, report_interval),
            stage: None,
        }
    }

    /// Returns a copy configured with stage metadata.
    ///
    /// # Parameters
    ///
    /// * `stage` - Stage metadata attached to subsequently reported events.
    ///
    /// # Returns
    ///
    /// This progress run with `stage` recorded.
    #[inline]
    pub fn with_stage(mut self, stage: ProgressStage) -> Self {
        self.stage = Some(stage);
        self
    }

    /// Returns a copy with stage metadata removed.
    ///
    /// # Returns
    ///
    /// This progress run without stage metadata.
    #[inline]
    pub fn without_stage(mut self) -> Self {
        self.stage = None;
        self
    }

    /// Reports a started lifecycle event.
    ///
    /// # Parameters
    ///
    /// * `counters` - Initial counters for the operation.
    ///
    /// # Panics
    ///
    /// Propagates panics from the configured reporter.
    #[inline]
    pub fn report_started(&self, counters: ProgressCounters) -> ProgressEvent {
        self.report_with_elapsed(ProgressPhase::Started, counters, Duration::ZERO)
    }

    /// Reports a running lifecycle event immediately.
    ///
    /// # Parameters
    ///
    /// * `counters` - Current counters for the operation.
    ///
    /// # Panics
    ///
    /// Propagates panics from the configured reporter.
    pub fn report_running(&mut self, counters: ProgressCounters) -> ProgressEvent {
        let now = Instant::now();
        let event = self.report_with_elapsed(
            ProgressPhase::Running,
            counters,
            now.saturating_duration_since(self.started_at),
        );
        self.next_running_at = next_instant(now, self.report_interval);
        event
    }

    /// Reports a running lifecycle event if the configured interval has passed.
    ///
    /// # Parameters
    ///
    /// * `counters` - Current counters for the operation.
    ///
    /// # Returns
    ///
    /// `Some(event)` when a running event was emitted, or `None` when the next
    /// running-event deadline has not been reached.
    ///
    /// This method does not block waiting for the next deadline. It returns
    /// immediately when not due, and when due it synchronously calls the
    /// configured reporter. Any blocking behavior therefore comes from the
    /// reporter implementation.
    ///
    /// # Panics
    ///
    /// Propagates panics from the configured reporter when an event is due.
    pub fn report_running_if_due(&mut self, counters: ProgressCounters) -> Option<ProgressEvent> {
        let now = Instant::now();
        if now < self.next_running_at {
            return None;
        }
        let event = self.report_with_elapsed(
            ProgressPhase::Running,
            counters,
            now.saturating_duration_since(self.started_at),
        );
        self.next_running_at = next_instant(now, self.report_interval);
        Some(event)
    }

    /// Reports a finished lifecycle event.
    ///
    /// # Parameters
    ///
    /// * `counters` - Final counters for a successfully completed operation.
    ///
    /// # Panics
    ///
    /// Propagates panics from the configured reporter.
    #[inline]
    pub fn report_finished(&self, counters: ProgressCounters) -> ProgressEvent {
        self.report_with_elapsed(ProgressPhase::Finished, counters, self.elapsed())
    }

    /// Reports a failed lifecycle event.
    ///
    /// # Parameters
    ///
    /// * `counters` - Final or current counters for a failed operation.
    ///
    /// # Panics
    ///
    /// Propagates panics from the configured reporter.
    #[inline]
    pub fn report_failed(&self, counters: ProgressCounters) -> ProgressEvent {
        self.report_with_elapsed(ProgressPhase::Failed, counters, self.elapsed())
    }

    /// Reports a canceled lifecycle event.
    ///
    /// # Parameters
    ///
    /// * `counters` - Final or current counters for a canceled operation.
    ///
    /// # Panics
    ///
    /// Propagates panics from the configured reporter.
    #[inline]
    pub fn report_canceled(&self, counters: ProgressCounters) -> ProgressEvent {
        self.report_with_elapsed(ProgressPhase::Canceled, counters, self.elapsed())
    }

    /// Spawns a scoped background reporter for periodic running events.
    ///
    /// The background reporter shares this progress run's reporter, start time,
    /// interval, and stage metadata. Worker threads should update their own
    /// domain state first, then call
    /// [`RunningProgressPointHandle::report`](crate::RunningProgressPointHandle::report)
    /// on the handle returned by the guard. The guard must be stopped and
    /// joined before the thread scope exits.
    ///
    /// # Parameters
    ///
    /// * `scope` - Thread scope that owns the background reporter thread.
    /// * `snapshot` - Closure that builds fresh counters from caller-owned
    ///   domain state whenever a running event may be due.
    ///
    /// # Returns
    ///
    /// A guard that owns the background reporter thread and can create
    /// worker-side point handles.
    ///
    /// # Panics
    ///
    /// Panics raised by the reporter thread are propagated by
    /// [`RunningProgressGuard::stop_and_join`].
    ///
    /// # Examples
    ///
    /// ```
    /// use std::{
    ///     sync::{
    ///         Arc,
    ///         atomic::{
    ///             AtomicUsize,
    ///             Ordering,
    ///         },
    ///     },
    ///     thread,
    ///     time::Duration,
    /// };
    ///
    /// use qubit_progress::{
    ///     NoOpProgressReporter,
    ///     Progress,
    ///     ProgressCounters,
    /// };
    ///
    /// let reporter = NoOpProgressReporter;
    /// let completed = Arc::new(AtomicUsize::new(0));
    /// let progress = Progress::new(&reporter, Duration::ZERO);
    ///
    /// thread::scope(|scope| {
    ///     let loop_completed = Arc::clone(&completed);
    ///     let running = progress.spawn_running_reporter(scope, move || {
    ///         ProgressCounters::new(Some(3))
    ///             .with_completed_count(loop_completed.load(Ordering::Acquire))
    ///     });
    ///     let point = running.point_handle();
    ///
    ///     let mut handles = Vec::new();
    ///     for _ in 0..3 {
    ///         let c = Arc::clone(&completed);
    ///         let p = point.clone();
    ///         handles.push(scope.spawn(move || {
    ///             c.fetch_add(1, Ordering::AcqRel);
    ///             assert!(p.report());
    ///         }));
    ///     }
    ///     for h in handles {
    ///         h.join().unwrap();
    ///     }
    ///
    ///     running.stop_and_join();
    /// });
    /// ```
    pub fn spawn_running_reporter<'scope, 'env, F>(
        &self,
        scope: &'scope thread::Scope<'scope, 'env>,
        snapshot: F,
    ) -> RunningProgressGuard<'scope>
    where
        'a: 'scope,
        F: FnMut() -> ProgressCounters + Send + 'scope,
    {
        RunningProgressLoop::spawn_scoped(scope, self.fork_for_running(), snapshot)
    }

    /// Reports a lifecycle event with an explicit elapsed duration.
    ///
    /// # Parameters
    ///
    /// * `phase` - Lifecycle phase to report.
    /// * `counters` - Counters carried by the event.
    /// * `elapsed` - Elapsed duration carried by the event.
    ///
    /// # Returns
    ///
    /// The event sent to the configured reporter.
    ///
    /// # Panics
    ///
    /// Propagates panics from the configured reporter.
    fn report_with_elapsed(
        &self,
        phase: ProgressPhase,
        counters: ProgressCounters,
        elapsed: Duration,
    ) -> ProgressEvent {
        let event = self.event_with_elapsed(phase, counters, elapsed);
        self.reporter.report(&event);
        event
    }

    /// Returns the elapsed duration since this run started.
    ///
    /// # Returns
    ///
    /// The monotonic elapsed duration for this progress run.
    #[inline]
    pub fn elapsed(&self) -> Duration {
        self.started_at.elapsed()
    }

    /// Returns the start instant for this run.
    ///
    /// # Returns
    ///
    /// The monotonic instant used as this run's start time.
    #[inline]
    pub const fn started_at(&self) -> Instant {
        self.started_at
    }

    /// Returns the configured running-event interval.
    ///
    /// # Returns
    ///
    /// The minimum delay between due-based running events.
    #[inline]
    pub const fn report_interval(&self) -> Duration {
        self.report_interval
    }

    /// Returns the optional stage metadata attached to events.
    ///
    /// # Returns
    ///
    /// `Some(stage)` when stage metadata is configured, otherwise `None`.
    #[inline]
    pub const fn stage(&self) -> Option<&ProgressStage> {
        self.stage.as_ref()
    }

    /// Creates a background-thread copy that reports running events for this run.
    ///
    /// # Returns
    ///
    /// A progress run with the same reporter, start time, interval, stage, and
    /// next running deadline as this run.
    fn fork_for_running(&self) -> Self {
        Self {
            reporter: self.reporter,
            started_at: self.started_at,
            report_interval: self.report_interval,
            next_running_at: self.next_running_at,
            stage: self.stage.clone(),
        }
    }

    /// Builds a progress event with optional stage metadata.
    ///
    /// # Parameters
    ///
    /// * `phase` - Lifecycle phase for the event.
    /// * `counters` - Counters carried by the event.
    /// * `elapsed` - Elapsed duration carried by the event.
    ///
    /// # Returns
    ///
    /// A progress event ready to be sent to the reporter.
    fn event_with_elapsed(
        &self,
        phase: ProgressPhase,
        counters: ProgressCounters,
        elapsed: Duration,
    ) -> ProgressEvent {
        let event = ProgressEvent::from_phase(phase, counters, elapsed);
        match self.stage.clone() {
            Some(stage) => event.with_stage(stage),
            None => event,
        }
    }
}

/// Computes the next reporting instant while avoiding overflow panics.
///
/// # Parameters
///
/// * `base` - Base instant for the deadline.
/// * `interval` - Duration added to `base`.
///
/// # Returns
///
/// `base + interval`, or `base` when the addition overflows.
fn next_instant(base: Instant, interval: Duration) -> Instant {
    base.checked_add(interval).unwrap_or(base)
}