Skip to main content

flm_core/progress/
sheet.rs

1//! The sheet: its rows, the host's half and the snapshot.
2
3use std::fmt;
4use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
5use std::sync::{Arc, Mutex, OnceLock, PoisonError};
6use std::time::Duration;
7
8use super::handles::Task;
9use super::kind::{Kind, SharedText};
10use super::log::LogSink;
11
12/// The id of a row: a number given when the row is declared, in the order of
13/// declaration, starting at 0 for the root row.
14#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]
15#[serde(transparent)]
16pub struct RowId(pub u64);
17
18/// The state of a row.
19///
20/// A state only moves forward: `Pending` to `Running` to `Finished` or
21/// `Failed`, or `Pending` to `NotRun`.
22#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
23#[serde(rename_all = "snake_case")]
24pub enum RowState {
25    /// Declared, not started.
26    Pending,
27    /// Started, not ended.
28    Running,
29    /// Ended, its work completed.
30    Finished,
31    /// Ended without completing its work: an error, a panic or a
32    /// cancellation.
33    Failed,
34    /// Declared and never started.
35    NotRun,
36}
37
38impl RowState {
39    fn from_u8(value: u8) -> RowState {
40        match value {
41            0 => RowState::Pending,
42            1 => RowState::Running,
43            2 => RowState::Finished,
44            3 => RowState::Failed,
45            _ => RowState::NotRun,
46        }
47    }
48
49    fn as_u8(self) -> u8 {
50        match self {
51            RowState::Pending => 0,
52            RowState::Running => 1,
53            RowState::Finished => 2,
54            RowState::Failed => 3,
55            RowState::NotRun => 4,
56        }
57    }
58}
59
60/// What the count of a row counts. A display names no unit; the estimate of a
61/// percentage keeps the units of different kinds apart.
62#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
63#[derive(schemars::JsonSchema)]
64#[serde(rename_all = "snake_case")]
65pub enum Unit {
66    /// Things: trees, images, files, formulas.
67    Items,
68    /// Bytes.
69    Bytes,
70}
71
72/// The count of a row: its unit, its total and the number done.
73///
74/// The total is given when the row starts and never changes; the number done
75/// only grows, and never exceeds the total.
76#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
77#[derive(schemars::JsonSchema)]
78pub struct Count {
79    /// What is counted.
80    pub unit: Unit,
81    /// How many units the row's work holds.
82    pub total: u64,
83    /// How many of them are done.
84    pub done: u64,
85}
86
87/// One row of a [`Snapshot`], as plain data.
88#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
89pub struct RowSnapshot {
90    /// The row's id.
91    pub id: RowId,
92    /// The id of the row under which it was declared; `None` for the root
93    /// row.
94    pub parent: Option<RowId>,
95    /// The name of the row's kind.
96    pub kind: SharedText,
97    /// The title of the row's kind, if it has one.
98    pub title: Option<SharedText>,
99    /// The row's label, if its owner gave one.
100    pub label: Option<SharedText>,
101    /// The row's state.
102    pub state: RowState,
103    /// The row's count, for a row started with one.
104    pub count: Option<Count>,
105    /// The time at which the row started, as the host's observer returned it.
106    pub started: Option<Duration>,
107    /// The time at which the row ended, as the host's observer returned it.
108    pub ended: Option<Duration>,
109}
110
111/// The rows of a sheet at one moment, as plain data, from
112/// [`Sheet::snapshot`].
113///
114/// The list of rows is taken at one moment, and the counts are then read one
115/// after the other: a snapshot is for a display and for an estimate, never for
116/// a decision of the work.
117#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
118pub struct Snapshot {
119    /// Whether the build was asked to stop.
120    pub cancelled: bool,
121    /// The rows, in the order of their ids; the first is the root row.
122    pub rows: Vec<RowSnapshot>,
123}
124
125/// The function of an [`Observer`] that tells of a row starting or ending, and
126/// returns the time to store on it.
127pub type RowFn = dyn Fn(&RowSnapshot) -> Option<Duration> + Send + Sync;
128
129/// The function of an [`Observer`] called before each question about the
130/// cancellation.
131pub type CheckpointFn = dyn Fn() + Send + Sync;
132
133/// The host's three functions, which a sheet calls while the work runs.
134///
135/// Each is optional: a function the host did not set costs one test where it
136/// would be called, and no call. These are the only functions of the host's
137/// that a sheet calls, besides its [`LogSink`].
138///
139/// ```
140/// use std::time::Duration;
141/// use flm_core::progress::Observer;
142///
143/// // A host with a clock of its own stamps the rows, and sets no checkpoint.
144/// let clock = || Some(Duration::from_millis(0)); // the host's clock
145/// let observer = Observer {
146///     row_started: Some(Box::new(move |_row| clock())),
147///     row_ended: Some(Box::new(move |_row| clock())),
148///     ..Observer::default()
149/// };
150/// # let _ = observer;
151/// ```
152///
153/// The contract of the three functions:
154///
155/// - They are called on the thread doing the work, possibly from several
156///   threads at once, and hold the work up until they return.
157/// - They are called outside any lock of the sheet. Inside one, the host may
158///   take a [`Sheet::snapshot`] and may call [`Sheet::cancel`]; a cancellation
159///   asked for inside `checkpoint` is seen by the question that follows it.
160/// - Each row that starts gives exactly one call of `row_started` and, when it
161///   ends, one call of `row_ended`. A row that is only declared, or that ends
162///   as [`RowState::NotRun`], gives none.
163/// - No function is called when a count advances.
164///
165/// A host with one thread (the library run as WebAssembly) does its display
166/// inside these functions: in `checkpoint` it reads its own clock and, when
167/// enough time has passed, takes a snapshot and shows it, and it may decide
168/// there to cancel.
169#[derive(Default)]
170pub struct Observer {
171    /// A row has started. The time returned, if any, is stored on the row as
172    /// the time it started: the time elapsed since an origin the host chooses.
173    pub row_started: Option<Box<RowFn>>,
174    /// A row that had started has ended, as [`RowState::Finished`] or
175    /// [`RowState::Failed`]. The time returned, if any, is stored as the time
176    /// it ended.
177    pub row_ended: Option<Box<RowFn>>,
178    /// The work is about to ask whether the build is cancelled
179    /// ([`Scope::cancelled`](super::Scope::cancelled)).
180    pub checkpoint: Option<Box<CheckpointFn>>,
181}
182
183impl fmt::Debug for Observer {
184    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185        f.debug_struct("Observer")
186            .field("row_started", &self.row_started.is_some())
187            .field("row_ended", &self.row_ended.is_some())
188            .field("checkpoint", &self.checkpoint.is_some())
189            .finish()
190    }
191}
192
193/// One row, shared by its handle and the sheet.
194pub(super) struct Row {
195    pub(super) id: RowId,
196    parent: Option<RowId>,
197    pub(super) kind: Kind,
198    pub(super) label: Option<SharedText>,
199    state: AtomicU8,
200    count: OnceLock<(Unit, u64)>,
201    pub(super) done: AtomicU64,
202    started: OnceLock<Duration>,
203    ended: OnceLock<Duration>,
204}
205
206impl Row {
207    pub(super) fn state(&self) -> RowState {
208        RowState::from_u8(self.state.load(Ordering::Acquire))
209    }
210
211    fn set_state(&self, state: RowState) {
212        self.state.store(state.as_u8(), Ordering::Release);
213    }
214
215    fn snapshot(&self) -> RowSnapshot {
216        RowSnapshot {
217            id: self.id,
218            parent: self.parent,
219            kind: self.kind.shared_name().clone(),
220            title: self.kind.shared_title().cloned(),
221            label: self.label.clone(),
222            state: self.state(),
223            count: self.count.get().map(|&(unit, total)| Count {
224                unit,
225                total,
226                done: self.done.load(Ordering::Relaxed).min(total),
227            }),
228            started: self.started.get().copied(),
229            ended: self.ended.get().copied(),
230        }
231    }
232}
233
234/// What the two halves of a sheet share.
235pub(super) struct Shared {
236    cancelled: AtomicBool,
237    pub(super) observer: Observer,
238    pub(super) log_sink: Option<Arc<dyn LogSink>>,
239    rows: Mutex<Vec<Arc<Row>>>,
240}
241
242impl Shared {
243    pub(super) fn cancelled(&self) -> bool {
244        self.cancelled.load(Ordering::Acquire)
245    }
246
247    /// Declares a row as `Pending`.
248    pub(super) fn declare(&self, parent: Option<RowId>, kind: &Kind, label: Option<&str>) -> Arc<Row> {
249        let label = label.map(|label| SharedText::from(Arc::<str>::from(label)));
250        let mut rows = self.rows.lock().unwrap_or_else(PoisonError::into_inner);
251        let row = Arc::new(Row {
252            id: RowId(rows.len() as u64),
253            parent,
254            kind: kind.clone(),
255            label,
256            state: AtomicU8::new(RowState::Pending.as_u8()),
257            count: OnceLock::new(),
258            done: AtomicU64::new(0),
259            started: OnceLock::new(),
260            ended: OnceLock::new(),
261        });
262        rows.push(Arc::clone(&row));
263        row
264    }
265
266    /// Starts a `Pending` row, with its count if it has one.
267    pub(super) fn start(&self, row: &Row, count: Option<(Unit, u64)>) {
268        if let Some(count) = count {
269            let _ = row.count.set(count);
270        }
271        row.set_state(RowState::Running);
272        if let Some(row_started) = &self.observer.row_started {
273            if let Some(time) = row_started(&row.snapshot()) {
274                let _ = row.started.set(time);
275            }
276        }
277    }
278
279    /// Ends a `Running` row as `Finished` or `Failed`.
280    pub(super) fn end(&self, row: &Row, state: RowState) {
281        row.set_state(state);
282        if let Some(row_ended) = &self.observer.row_ended {
283            if let Some(time) = row_ended(&row.snapshot()) {
284                let _ = row.ended.set(time);
285            }
286        }
287    }
288
289    /// Ends a `Pending` row as `NotRun`.
290    pub(super) fn not_run(&self, row: &Row) {
291        row.set_state(RowState::NotRun);
292    }
293}
294
295/// The progress sheet of one build, as the host holds it: it reads the rows
296/// and asks the build to stop.
297///
298/// [`Sheet::start`] creates a sheet and gives its two halves: this one, and
299/// the root row as a [`Task`], which the host lends to the work and ends when
300/// the build is over. A `Sheet` is cheap to clone and may be read from any
301/// thread.
302#[derive(Clone)]
303pub struct Sheet {
304    shared: Arc<Shared>,
305}
306
307impl Sheet {
308    /// Creates a sheet whose root row, of kind `root` and labeled `label`, is
309    /// running, and returns the sheet and that row.
310    ///
311    /// `observer` holds the host's functions that the sheet calls while the
312    /// work runs, and `log_sink` the sink of the log lines that the work
313    /// writes through its scopes (none: the lines go nowhere). The root row's
314    /// start is told to the observer before this returns.
315    pub fn start(
316        root: &Kind,
317        label: Option<&str>,
318        observer: Observer,
319        log_sink: Option<Arc<dyn LogSink>>,
320    ) -> (Sheet, Task) {
321        let shared = Arc::new(Shared {
322            cancelled: AtomicBool::new(false),
323            observer,
324            log_sink,
325            rows: Mutex::new(Vec::new()),
326        });
327        let row = shared.declare(None, root, label);
328        shared.start(&row, None);
329        let task = Task::running(Arc::clone(&shared), row);
330        (Sheet { shared }, task)
331    }
332
333    /// The rows of the sheet, as plain data.
334    pub fn snapshot(&self) -> Snapshot {
335        let rows: Vec<Arc<Row>> =
336            self.shared.rows.lock().unwrap_or_else(PoisonError::into_inner).clone();
337        Snapshot {
338            cancelled: self.shared.cancelled(),
339            rows: rows.iter().map(|row| row.snapshot()).collect(),
340        }
341    }
342
343    /// Asks the build to stop. The work sees it the next time it asks
344    /// ([`Scope::cancelled`](super::Scope::cancelled)), and ends what it was
345    /// doing as [`RowState::Failed`].
346    pub fn cancel(&self) {
347        self.shared.cancelled.store(true, Ordering::Release);
348    }
349
350    /// Whether the build was asked to stop.
351    pub fn cancelled(&self) -> bool {
352        self.shared.cancelled()
353    }
354}
355
356impl fmt::Debug for Sheet {
357    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
358        f.debug_struct("Sheet").field("cancelled", &self.cancelled()).finish_non_exhaustive()
359    }
360}