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
//! Observational progress and diagnostic events, independent of terminal rendering.
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use crate::diagnostics::Diagnostic;
mod timing;
pub use timing::Phase;
/// Receives synchronous notifications without taking ownership of pipeline work.
///
/// Implementations should return promptly. Events may arrive from different
/// threads, and borrowed event data is valid only during this call.
pub trait Reporter: Send + Sync {
/// Observe one pipeline or command event.
fn report(&self, event: Event<'_>);
}
/// A command, stage, diagnostic, or preview notification.
#[derive(Debug)]
#[non_exhaustive]
pub enum Event<'a> {
/// A result cache was consulted for a package or document.
Cache {
/// Pipeline stage whose result may be reused.
stage: &'static str,
/// Owning package or document identifier.
owner: &'a str,
/// Whether a verified result was restored.
hit: bool,
/// Explanation for a miss or ineligible stage, without local secrets.
reason: Option<&'a str>,
},
/// A timed pipeline phase began. Independent of human-facing progress stages.
PhaseStarted {
/// Identifier paired with exactly one `PhaseFinished` event.
id: u64,
/// Stable activity classification.
phase: Phase,
/// Owning package, absent for workspace-wide work.
package: Option<&'a str>,
/// Package-scoped extraction target, when applicable.
target: Option<&'a str>,
},
/// A timed phase finished, including failure, cancellation, and unwinding.
PhaseFinished {
/// Identifier from `PhaseStarted`.
id: u64,
/// Inclusive wall time; nested phases must not be added to this duration.
elapsed: Duration,
/// Whether the phase completed successfully.
success: bool,
},
/// A completed subphase measured inside a native helper process.
///
/// These durations are contained in the enclosing native-process phase.
/// They exclude interpreter startup and must not be added to host durations.
NativeTiming {
/// Activity measured by the helper.
phase: Phase,
/// Owning package.
package: &'a str,
/// Package-scoped extraction target, when applicable.
target: Option<&'a str>,
/// Helper's monotonic elapsed time.
elapsed: Duration,
},
/// A finite command or one watch attempt began.
CommandStarted {
/// Command name, such as `build` or `extract`.
command: &'static str,
},
/// A finite command or watch attempt returned, or was dropped.
CommandFinished {
/// Name supplied by the corresponding start event.
command: &'static str,
/// Wall-clock time spent in this attempt.
elapsed: Duration,
/// Whether all work, including publication, succeeded.
success: bool,
/// Published destination, when applicable.
output: Option<&'a Path>,
/// Number of generated pages, when applicable.
pages: Option<usize>,
},
/// A nonempty stage began.
StageStarted {
/// Unique identifier used by subsequent stage events.
id: u64,
/// Human-readable activity label.
label: &'static str,
/// Selected work units, or `None` for indeterminate work.
total: Option<usize>,
},
/// A stage selected an item or completed a work unit.
StageProgress {
/// Identifier from the start event.
id: u64,
/// Successfully completed work units.
completed: usize,
/// Current package, target, page, or asset.
item: Option<&'a str>,
},
/// A stage completed, failed, or was dropped during cancellation.
StageFinished {
/// Identifier from the start event.
id: u64,
/// Wall-clock time spent in this stage.
elapsed: Duration,
/// Whether this stage completed successfully.
success: bool,
},
/// A deterministically ordered source diagnostic.
Diagnostic(&'a Diagnostic),
/// A command failure, followed separately by any source diagnostics.
Error(&'a str),
/// A nonfatal operational warning.
Warning(&'a str),
/// The first generation is ready to serve at this browser destination.
Serving {
/// Complete local URL, including the actual bound port.
url: &'a str,
},
/// A preview rebuild has replaced the served generation.
Rebuilt,
/// The watcher is waiting without active work.
Watching {
/// A failed attempt retained the previous published generation.
retained_previous: bool,
},
}
#[derive(Clone)]
pub(crate) struct Reporting(Arc<dyn Reporter>);
impl std::fmt::Debug for Reporting {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Reporting").finish_non_exhaustive()
}
}
impl Default for Reporting {
fn default() -> Self {
Self(Arc::new(LegacyReporter))
}
}
impl Reporting {
pub(crate) fn cache(&self, stage: &'static str, owner: &str, hit: bool, reason: Option<&str>) {
self.emit(Event::Cache {
stage,
owner,
hit,
reason,
});
}
pub(crate) fn new(reporter: Arc<dyn Reporter>) -> Self {
Self(reporter)
}
pub(crate) fn emit(&self, event: Event<'_>) {
self.0.report(event);
}
pub(crate) fn stage(&self, label: &'static str, total: Option<usize>) -> Stage {
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
let active = total != Some(0);
if active {
self.emit(Event::StageStarted { id, label, total });
}
Stage {
reporting: self.clone(),
id,
started: Instant::now(),
completed: 0,
active,
}
}
pub(crate) fn run<T, E>(
&self,
label: &'static str,
work: impl FnOnce() -> Result<T, E>,
) -> Result<T, E> {
let stage = self.stage(label, None);
let result = work()?;
stage.finish();
Ok(result)
}
pub(crate) fn command(&self, command: &'static str) -> Operation {
self.emit(Event::CommandStarted { command });
Operation {
reporting: self.clone(),
command,
started: Instant::now(),
finished: false,
}
}
pub(crate) fn error(&self, error: &crate::commands::CommandError) {
self.emit(Event::Error(&error.to_string()));
for diagnostic in error
.diagnostics()
.iter()
.chain(error.cleanup_diagnostics())
{
self.emit(Event::Diagnostic(diagnostic));
}
}
}
pub(crate) struct Stage {
reporting: Reporting,
id: u64,
started: Instant,
completed: usize,
active: bool,
}
impl Stage {
pub(crate) fn item(&self, item: &str) {
if self.active {
self.reporting.emit(Event::StageProgress {
id: self.id,
completed: self.completed,
item: Some(item),
});
}
}
pub(crate) fn advance(&mut self) {
self.completed += 1;
if self.active {
self.reporting.emit(Event::StageProgress {
id: self.id,
completed: self.completed,
item: None,
});
}
}
pub(crate) fn finish(mut self) {
self.end(true);
}
fn end(&mut self, success: bool) {
if self.active {
self.active = false;
self.reporting.emit(Event::StageFinished {
id: self.id,
elapsed: self.started.elapsed(),
success,
});
}
}
}
impl Drop for Stage {
fn drop(&mut self) {
self.end(false);
}
}
pub(crate) struct Operation {
reporting: Reporting,
command: &'static str,
started: Instant,
finished: bool,
}
impl Operation {
pub(crate) fn finish(mut self, output: Option<&Path>, pages: Option<usize>) {
self.finished = true;
self.reporting.emit(Event::CommandFinished {
command: self.command,
elapsed: self.started.elapsed(),
success: true,
output,
pages,
});
}
}
impl Drop for Operation {
fn drop(&mut self) {
if !self.finished {
self.reporting.emit(Event::CommandFinished {
command: self.command,
elapsed: self.started.elapsed(),
success: false,
output: None,
pages: None,
});
}
}
}
struct LegacyReporter;
impl Reporter for LegacyReporter {
fn report(&self, event: Event<'_>) {
match event {
Event::Diagnostic(diagnostic) => {
eprintln!("{}", crate::commands::format_diagnostic(diagnostic));
}
Event::Error(message) => eprintln!("error: {}", terminal_safe(message)),
Event::Warning(message) => eprintln!("Warning: {}", terminal_safe(message)),
Event::Serving { url } => eprintln!("Serving {}", terminal_safe(url)),
Event::Rebuilt => eprintln!("Rebuilt documentation."),
_ => {}
}
}
}
/// Escape control characters before adding intentional terminal formatting.
pub(crate) fn terminal_safe(text: &str) -> String {
text.chars()
.flat_map(|ch| {
if ch.is_control() {
ch.escape_default().collect::<Vec<_>>()
} else {
vec![ch]
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
#[derive(Default)]
struct Recording(Mutex<Vec<String>>);
impl Reporter for Recording {
fn report(&self, event: Event<'_>) {
self.0.lock().unwrap().push(format!("{event:?}"));
}
}
#[test]
fn empty_stages_are_silent_and_dropped_work_fails_once() {
let recorder = Arc::new(Recording::default());
let reporting = Reporting::new(recorder.clone());
reporting.stage("Empty", Some(0)).finish();
assert!(recorder.0.lock().unwrap().is_empty());
let mut stage = reporting.stage("Pages", Some(2));
stage.item("first.md");
stage.advance();
drop(stage);
let events = recorder.0.lock().unwrap();
assert_eq!(events.len(), 4);
assert!(events[2].contains("completed: 1"));
assert!(events[3].contains("success: false"));
}
#[test]
fn unwinding_finishes_stages_before_the_command() {
let recorder = Arc::new(Recording::default());
let reporting = Reporting::new(recorder.clone());
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _command = reporting.command("build");
let _stage = reporting.stage("Rendering", None);
panic!("test unwind");
}));
let events = recorder.0.lock().unwrap();
assert!(events[2].starts_with("StageFinished"));
assert!(events[3].starts_with("CommandFinished"));
assert!(events[3].contains("success: false"));
}
}