Skip to main content

flm_core/progress/
handles.rs

1//! The work's four handles: `Scope`, `Pending`, `Task` and `Counted`.
2
3use std::fmt;
4use std::mem;
5use std::sync::Arc;
6
7use super::kind::Kind;
8use super::log::{LogLevel, LogRecord};
9use super::sheet::{Row, RowState, Shared, Unit};
10
11/// What a handle has behind it. Every operation of a handle is one match on
12/// this value.
13#[derive(Clone)]
14enum Behind {
15    /// No sheet: the build reports nowhere.
16    Nothing,
17    /// A sheet but no row of the handle's own: the handle is past a depth
18    /// limit, or was declared under a row that had ended. `nearest` is the
19    /// nearest row that exists, to which log lines are attributed.
20    Above { sheet: Arc<Shared>, nearest: Arc<Row> },
21    /// The handle's own row. `below` is how many levels of rows may exist
22    /// below it (`None`: no limit).
23    Row { sheet: Arc<Shared>, row: Arc<Row>, below: Option<u32> },
24}
25
26impl Behind {
27    /// The same handle, with no more than `levels` levels of rows below its
28    /// row.
29    fn limited(mut self, levels: u32) -> Behind {
30        if let Behind::Row { below, .. } = &mut self {
31            *below = Some(below.map_or(levels, |below| below.min(levels)));
32        }
33        self
34    }
35
36    fn fmt_row(&self, name: &str, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        match self {
38            Behind::Row { row, .. } => write!(f, "{name}({})", row.id.0),
39            _ => write!(f, "{name}(no row)"),
40        }
41    }
42}
43
44/// The handle lent to the code that works under a running row.
45///
46/// Through a scope the work declares rows under that row
47/// ([`child`](Scope::child)), asks whether the build is cancelled
48/// ([`cancelled`](Scope::cancelled)), and writes log lines
49/// ([`log`](Scope::log)). It cannot start, count or end anything: the owner of
50/// the row does that through its [`Task`] or [`Counted`].
51///
52/// A scope is cheap to clone, so that a value that outlives a call can keep
53/// one. [`Scope::none()`] is the scope of a build that reports nowhere; the
54/// work calls the same methods on it, and each does nothing.
55#[derive(Clone)]
56pub struct Scope(Behind);
57
58impl Scope {
59    /// The scope of a build that reports nowhere: it declares no row,
60    /// [`cancelled`](Scope::cancelled) is `false`, and a log line goes
61    /// nowhere.
62    pub fn none() -> Scope {
63        Scope(Behind::Nothing)
64    }
65
66    /// Declares a row of kind `kind`, labeled `label`, under this scope's row,
67    /// and returns it, not started.
68    ///
69    /// The returned handle has no row behind it, and does nothing, when this
70    /// scope has none, when the depth limit allows no row below this scope's
71    /// row ([`Pending::with_depth_limit`]), or when this scope's row has
72    /// ended.
73    ///
74    /// The row declared stands for a part of this row's work; under a row
75    /// that has a count, it stands for one of the counted units, shown in
76    /// detail, and the owner of the counted row advances it when that unit is
77    /// done.
78    pub fn child(&self, kind: &Kind, label: Option<&str>) -> Pending {
79        match &self.0 {
80            Behind::Nothing => Pending(Behind::Nothing),
81            Behind::Above { sheet, nearest } => {
82                Pending(Behind::Above { sheet: Arc::clone(sheet), nearest: Arc::clone(nearest) })
83            }
84            Behind::Row { sheet, row, below } => {
85                if *below == Some(0) || row.state() != RowState::Running {
86                    Pending(Behind::Above { sheet: Arc::clone(sheet), nearest: Arc::clone(row) })
87                } else {
88                    let child = sheet.declare(Some(row.id), kind, label);
89                    Pending(Behind::Row {
90                        sheet: Arc::clone(sheet),
91                        row: child,
92                        below: below.map(|below| below - 1),
93                    })
94                }
95            }
96        }
97    }
98
99    /// The same scope, with no more than `levels` levels of rows declared
100    /// below its row through it: 0 for none. A limit already in place that is
101    /// lower stays.
102    pub fn with_depth_limit(&self, levels: u32) -> Scope {
103        Scope(self.0.clone().limited(levels))
104    }
105
106    /// Whether the build was asked to stop.
107    ///
108    /// The host's [`checkpoint`](super::Observer::checkpoint) function is
109    /// called first, when it set one, and the flag is read after it. The work
110    /// asks at the grain of its units (once for a tree, an image, a formula),
111    /// not inside an inner loop. A build that was asked to stop produces
112    /// nothing from the step under way, so the work that sees `true` returns
113    /// as soon as it can, and what it returns need not be meaningful.
114    pub fn cancelled(&self) -> bool {
115        let sheet = match &self.0 {
116            Behind::Nothing => return false,
117            Behind::Above { sheet, .. } | Behind::Row { sheet, .. } => sheet,
118        };
119        if let Some(checkpoint) = &sheet.observer.checkpoint {
120            checkpoint();
121        }
122        sheet.cancelled()
123    }
124
125    /// Whether the build was asked to stop, read from the flag alone, without
126    /// a call of the host's checkpoint: the run reads it to choose the state in
127    /// which it ends a stage's row, which is not a question about the
128    /// cancellation.
129    pub(crate) fn cancel_requested(&self) -> bool {
130        match &self.0 {
131            Behind::Nothing => false,
132            Behind::Above { sheet, .. } | Behind::Row { sheet, .. } => sheet.cancelled(),
133        }
134    }
135
136    /// Whether the host's log sink wants the lines of `level`: a caller tests
137    /// it before building the text of a line.
138    pub fn log_enabled(&self, level: LogLevel) -> bool {
139        match &self.0 {
140            Behind::Nothing => false,
141            Behind::Above { sheet, .. } | Behind::Row { sheet, .. } => {
142                sheet.log_sink.as_ref().is_some_and(|sink| sink.enabled(level))
143            }
144        }
145    }
146
147    /// Writes the log line `text` at `level` to the host's log sink.
148    ///
149    /// The line is attributed to this scope's row, or, for a scope past a
150    /// depth limit, to the nearest row that exists: the record holds that
151    /// row's id and label, and the name of its kind as the source.
152    pub fn log(&self, level: LogLevel, text: &str) {
153        let (sheet, row) = match &self.0 {
154            Behind::Nothing => return,
155            Behind::Above { sheet, nearest: row } | Behind::Row { sheet, row, .. } => (sheet, row),
156        };
157        if let Some(sink) = &sheet.log_sink {
158            sink.log(&LogRecord {
159                level,
160                source: row.kind.name(),
161                text,
162                row: Some(row.id),
163                label: row.label.as_deref(),
164            });
165        }
166    }
167}
168
169impl fmt::Debug for Scope {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        self.0.fmt_row("Scope", f)
172    }
173}
174
175/// A declared row, not started, owned by the code that declared it.
176///
177/// The owner starts it with [`start`](Pending::start) or, for a row with a
178/// count, [`start_counted`](Pending::start_counted). A `Pending` that is
179/// dropped ends as [`RowState::NotRun`]: an owner declares a piece of work
180/// that may be needed before it knows, and drops the handle when the work is
181/// not needed.
182#[must_use = "a declared row that is dropped ends as not run"]
183pub struct Pending(Behind);
184
185impl Pending {
186    /// The same row, with no more than `levels` levels of rows below it: 0 for
187    /// none. A handle past the limit has no row behind it; it still answers
188    /// [`Scope::cancelled`], and its log lines are attributed to the nearest
189    /// row that exists. A limit already in place that is lower stays.
190    pub fn with_depth_limit(mut self, levels: u32) -> Pending {
191        let behind = mem::replace(&mut self.0, Behind::Nothing);
192        Pending(behind.limited(levels))
193    }
194
195    /// Starts the row, with nothing to count.
196    pub fn start(mut self) -> Task {
197        let behind = mem::replace(&mut self.0, Behind::Nothing);
198        if let Behind::Row { sheet, row, .. } = &behind {
199            sheet.start(row, None);
200        }
201        Task(behind)
202    }
203
204    /// Starts the row with a count of `total` units of `unit`. The total is
205    /// fixed: it never changes after the row starts.
206    pub fn start_counted(mut self, unit: Unit, total: u64) -> Counted {
207        let behind = mem::replace(&mut self.0, Behind::Nothing);
208        if let Behind::Row { sheet, row, .. } = &behind {
209            sheet.start(row, Some((unit, total)));
210        }
211        Counted(behind)
212    }
213
214    /// Starts the row with a count of units of `unit`, whose total `total`
215    /// computes. `total` is called only when a row is behind the handle.
216    pub fn start_counted_with(mut self, unit: Unit, total: impl FnOnce() -> u64) -> Counted {
217        let behind = mem::replace(&mut self.0, Behind::Nothing);
218        if let Behind::Row { sheet, row, .. } = &behind {
219            sheet.start(row, Some((unit, total())));
220        }
221        Counted(behind)
222    }
223}
224
225impl Drop for Pending {
226    fn drop(&mut self) {
227        if let Behind::Row { sheet, row, .. } = &self.0 {
228            sheet.not_run(row);
229        }
230    }
231}
232
233impl fmt::Debug for Pending {
234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235        self.0.fmt_row("Pending", f)
236    }
237}
238
239/// A running row with nothing to count, owned by the code that started it.
240///
241/// The owner lends its [`scope`](Task::scope) to the work under it and ends
242/// it with [`finish`](Task::finish). A `Task` dropped without it, by an early
243/// return or a panic, ends as [`RowState::Failed`].
244#[must_use = "a running row that is dropped ends as failed"]
245pub struct Task(Behind);
246
247impl Task {
248    /// The task of the root row of a sheet, which has just started.
249    pub(super) fn running(sheet: Arc<Shared>, row: Arc<Row>) -> Task {
250        Task(Behind::Row { sheet, row, below: None })
251    }
252
253    /// The scope of the row, for the work under it.
254    pub fn scope(&self) -> Scope {
255        Scope(self.0.clone())
256    }
257
258    /// Ends the row as [`RowState::Finished`].
259    pub fn finish(mut self) {
260        end(&mut self.0, RowState::Finished);
261    }
262}
263
264impl Drop for Task {
265    fn drop(&mut self) {
266        end(&mut self.0, RowState::Failed);
267    }
268}
269
270impl fmt::Debug for Task {
271    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272        self.0.fmt_row("Task", f)
273    }
274}
275
276/// A running row with a count, owned by the code that started it.
277///
278/// [`advance`](Counted::advance) adds to the number done; the rest is as for
279/// a [`Task`]. Several threads may advance one `Counted` at the same time.
280#[must_use = "a running row that is dropped ends as failed"]
281pub struct Counted(Behind);
282
283impl Counted {
284    /// Adds `n` to the number done: one atomic addition. The number done never
285    /// goes past the total: an owner that advances further has miscounted,
286    /// and the count stays at the total.
287    pub fn advance(&self, n: u64) {
288        if let Behind::Row { row, .. } = &self.0 {
289            row.done.fetch_add(n, std::sync::atomic::Ordering::Relaxed);
290        }
291    }
292
293    /// The scope of the row, for the work under it.
294    pub fn scope(&self) -> Scope {
295        Scope(self.0.clone())
296    }
297
298    /// Ends the row as [`RowState::Finished`].
299    pub fn finish(mut self) {
300        end(&mut self.0, RowState::Finished);
301    }
302}
303
304impl Drop for Counted {
305    fn drop(&mut self) {
306        end(&mut self.0, RowState::Failed);
307    }
308}
309
310impl fmt::Debug for Counted {
311    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312        self.0.fmt_row("Counted", f)
313    }
314}
315
316/// Ends the running row behind a handle as `state`, once: the handle is left
317/// with nothing behind it.
318fn end(behind: &mut Behind, state: RowState) {
319    if let Behind::Row { sheet, row, .. } = mem::replace(behind, Behind::Nothing) {
320        sheet.end(&row, state);
321    }
322}
323
324// Every handle may be sent to and shared between threads.
325const _: () = {
326    const fn send_sync<T: Send + Sync>() {}
327    send_sync::<Scope>();
328    send_sync::<Pending>();
329    send_sync::<Task>();
330    send_sync::<Counted>();
331    send_sync::<super::Sheet>();
332};