Skip to main content

artifactize_core/tools/human/
log.rs

1//! The Tool log: what Human tools print while a review or an Artifact's Detail shows them, line
2//! by line as it arrives.
3//!
4//! A screen opens a [`channel`]. Each tool run it starts is a [`Run`] of one log [`Key`]: a
5//! review's, or an Artifact's own for the tools run from its Detail. Its output lines and its
6//! end reach the channel as [`Event`]s, a launched program's for as long as it runs. A run keeps
7//! draining its program's output whether or not anyone still receives; what nobody shows is
8//! discarded. Nothing is saved.
9
10use std::{
11    path::PathBuf,
12    sync::{
13        Arc,
14        atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
15    },
16};
17
18use time::OffsetDateTime;
19use tokio::sync::mpsc;
20
21use crate::types::{ArtifactName, RequestId};
22
23/// Whose Tool log a run belongs to.
24#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
25pub enum Key {
26    /// A Human review's: the tools its reviewer ran.
27    Review(RequestId),
28    /// An Artifact's own, in the workspace at `repo`: the tools run from its Detail, for no
29    /// review.
30    Artifact {
31        repo: PathBuf,
32        artifact: ArtifactName,
33    },
34}
35
36impl Key {
37    /// The review this log belongs to, if it is a review's.
38    pub fn request(&self) -> Option<&RequestId> {
39        match self {
40            Self::Review(request) => Some(request),
41            Self::Artifact { .. } => None,
42        }
43    }
44}
45
46impl From<&RequestId> for Key {
47    fn from(request: &RequestId) -> Self {
48        Self::Review(request.clone())
49    }
50}
51
52/// Output bytes one run shows at most: a launched program may print for hours, and the log
53/// is held in memory for as long as the review is open.
54const RUN_BYTES: usize = 1024 * 1024;
55/// A line longer than this is shown in pieces, so output without newlines still appears.
56const LINE_BYTES: usize = 4096;
57/// Shown once, as an error line, when a run printed more than the log keeps.
58const DROPPED: &str = "[more output than the Tool log keeps; the rest is not shown]";
59
60/// Numbers every run of this process, so lines arriving later find their own entry.
61static NEXT_RUN: AtomicU64 = AtomicU64::new(1);
62
63/// One tool run, unique in this process.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
65pub struct RunNo(u64);
66
67impl RunNo {
68    pub fn get(self) -> u64 {
69        self.0
70    }
71}
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum Stream {
75    Stdout,
76    Stderr,
77}
78
79/// How a run ended, as its last log line says.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub enum End {
82    /// The program exited: its exit code, or how it ended without one.
83    Exited {
84        code: Option<i32>,
85        text: String,
86    },
87    /// Handed to the desktop's own opener; its output is not the tool's.
88    Launched,
89    /// A builtin finished.
90    Done,
91    Cancelled,
92    TimedOut,
93    /// The run could not start or failed, and why.
94    Failed(String),
95}
96
97impl End {
98    pub(crate) fn exited(status: &crate::platform::ProcessOutcome) -> Self {
99        Self::Exited {
100            code: status.code(),
101            text: status.to_string(),
102        }
103    }
104
105    /// The end line: `■ exit 0`, `■ launched`, `■ error: …`.
106    pub fn text(&self) -> String {
107        match self {
108            Self::Exited {
109                code: Some(code), ..
110            } => format!("■ exit {code}"),
111            Self::Exited { text, .. } => format!("■ {text}"),
112            Self::Launched => "■ launched".into(),
113            Self::Done => "■ done".into(),
114            Self::Cancelled => "■ cancelled".into(),
115            Self::TimedOut => "■ timed out".into(),
116            Self::Failed(error) => format!("■ error: {error}"),
117        }
118    }
119
120    /// The run did not end well.
121    pub fn error(&self) -> bool {
122        !matches!(
123            self,
124            Self::Exited { code: Some(0), .. } | Self::Launched | Self::Done
125        )
126    }
127}
128
129#[derive(Debug, Clone, PartialEq, Eq)]
130pub enum Kind {
131    Start {
132        at: OffsetDateTime,
133        operation: String,
134        /// The Artifact that declares the tool.
135        artifact: String,
136    },
137    Line {
138        stream: Stream,
139        text: String,
140    },
141    End(End),
142}
143
144/// One thing a run logged, for the log of `key`.
145#[derive(Debug, Clone, PartialEq, Eq)]
146pub struct Event {
147    pub key: Key,
148    pub run: RunNo,
149    pub kind: Kind,
150}
151
152/// Where runs send their events; cloned into each job a review starts.
153#[derive(Debug, Clone)]
154pub struct Sink(mpsc::UnboundedSender<Event>);
155
156/// The review's end of the log. Every run bounds its output, so the channel is unbounded.
157pub type Events = mpsc::UnboundedReceiver<Event>;
158
159pub fn channel() -> (Sink, Events) {
160    let (sender, receiver) = mpsc::unbounded_channel();
161    (Sink(sender), receiver)
162}
163
164impl Sink {
165    /// Start a run of `operation` of `artifact` in the log of `key`: its start line is logged
166    /// now.
167    pub fn start(&self, key: impl Into<Key>, operation: &str, artifact: &str) -> Run {
168        let run = Run::new(Some((self.clone(), key.into())));
169        run.shared.send(Kind::Start {
170            at: OffsetDateTime::now_utc(),
171            operation: operation.to_owned(),
172            artifact: artifact.to_owned(),
173        });
174        run
175    }
176}
177
178struct Shared {
179    /// Where the run's events go and the log they belong to; `None` when nobody watches.
180    watch: Option<(Sink, Key)>,
181    run: RunNo,
182    /// Output bytes this run may still show.
183    left: AtomicUsize,
184    dropped: AtomicBool,
185}
186
187impl Shared {
188    fn send(&self, kind: Kind) {
189        if let Some((sink, key)) = &self.watch {
190            // A closed review discards what its runs still print.
191            let _ = sink.0.send(Event {
192                key: key.clone(),
193                run: self.run,
194                kind,
195            });
196        }
197    }
198
199    fn line(&self, stream: Stream, bytes: &[u8]) {
200        if !self.watched() {
201            return;
202        }
203        let text =
204            String::from_utf8(crate::runtime::clean_output(bytes)).expect("clean output is UTF-8");
205        let size = text.len().max(1);
206        // A compare-and-swap loop rather than `fetch_update`, which newer toolchains
207        // deprecate under another name.
208        let mut left = self.left.load(Ordering::Relaxed);
209        let kept = loop {
210            let Some(next) = left.checked_sub(size) else {
211                break false;
212            };
213            match self
214                .left
215                .compare_exchange_weak(left, next, Ordering::Relaxed, Ordering::Relaxed)
216            {
217                Ok(_) => break true,
218                Err(current) => left = current,
219            }
220        };
221        if kept {
222            self.send(Kind::Line { stream, text });
223        } else if !self.dropped.swap(true, Ordering::Relaxed) {
224            self.send(Kind::Line {
225                stream: Stream::Stderr,
226                text: DROPPED.into(),
227            });
228        }
229    }
230}
231
232/// One tool run's log: lines while it runs, then exactly one end. A run dropped without an
233/// end was cancelled.
234pub struct Run {
235    shared: Arc<Shared>,
236    ended: bool,
237    launch: Option<Box<dyn FnOnce(crate::process::ChildIdentity) + Send + Sync>>,
238}
239
240impl std::fmt::Debug for Run {
241    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
242        f.debug_struct("Run")
243            .field("run", &self.shared.run)
244            .finish()
245    }
246}
247
248impl Run {
249    fn new(watch: Option<(Sink, Key)>) -> Self {
250        Self {
251            shared: Arc::new(Shared {
252                watch,
253                run: RunNo(NEXT_RUN.fetch_add(1, Ordering::Relaxed)),
254                left: AtomicUsize::new(RUN_BYTES),
255                dropped: AtomicBool::new(false),
256            }),
257            ended: false,
258            launch: None,
259        }
260    }
261
262    /// A run nobody shows, such as `tool check`'s: launched programs get no pipes at all.
263    pub fn unwatched() -> Self {
264        Self::new(None)
265    }
266
267    /// Observe the native birth identity at successful spawn, before a detached program's
268    /// own startup protocol. This does not change the log or the launch's lifetime.
269    pub fn observe_launch(
270        mut self,
271        observe: impl FnOnce(crate::process::ChildIdentity) + Send + Sync + 'static,
272    ) -> Self {
273        self.launch = Some(Box::new(observe));
274        self
275    }
276
277    pub(crate) fn launched(&mut self, pid: u32) {
278        if let Some(observe) = self.launch.take()
279            && let Ok(identity) = crate::process::child_identity(pid)
280        {
281            observe(identity);
282        }
283    }
284
285    pub(crate) fn watched(&self) -> bool {
286        self.shared.watched()
287    }
288
289    /// A splitter of one output stream into this run's lines.
290    pub(crate) fn lines(&self, stream: Stream) -> Lines {
291        Lines {
292            shared: self.shared.clone(),
293            stream,
294            pending: Vec::new(),
295        }
296    }
297
298    /// Log `text`, a finished output, line by line.
299    pub fn text(&self, stream: Stream, text: &str) {
300        let mut lines = self.lines(stream);
301        lines.push(text.as_bytes());
302        lines.finish();
303    }
304
305    pub fn end(mut self, end: End) {
306        self.ended = true;
307        self.shared.send(Kind::End(end));
308    }
309}
310
311impl Drop for Run {
312    fn drop(&mut self) {
313        if !self.ended {
314            self.shared.send(Kind::End(End::Cancelled));
315        }
316    }
317}
318
319/// Bytes of one stream cut into lines: at each newline, and in pieces of [`LINE_BYTES`].
320pub(crate) struct Lines {
321    shared: Arc<Shared>,
322    stream: Stream,
323    pending: Vec<u8>,
324}
325
326impl Lines {
327    pub(crate) fn push(&mut self, bytes: &[u8]) {
328        if !self.shared.watched() {
329            return;
330        }
331        self.pending.extend_from_slice(bytes);
332        while let Some(newline) = self.pending.iter().position(|byte| *byte == b'\n') {
333            let line: Vec<u8> = self.pending.drain(..=newline).collect();
334            self.shared
335                .line(self.stream, crate::platform::output_line(&line));
336        }
337        while self.pending.len() >= LINE_BYTES {
338            let end = piece(&self.pending);
339            let piece: Vec<u8> = self.pending.drain(..end).collect();
340            self.shared.line(self.stream, &piece);
341        }
342    }
343
344    /// The stream closed: its last line, if it had no newline.
345    pub(crate) fn finish(&mut self) {
346        if !self.pending.is_empty() {
347            let line = std::mem::take(&mut self.pending);
348            self.shared.line(self.stream, &line);
349        }
350    }
351}
352
353impl Shared {
354    fn watched(&self) -> bool {
355        self.watch.is_some()
356    }
357}
358
359/// Where a long line's first piece ends: [`LINE_BYTES`] in, moved back so that a character
360/// cut in two stays whole for the next piece.
361fn piece(bytes: &[u8]) -> usize {
362    let end = LINE_BYTES.min(bytes.len());
363    match std::str::from_utf8(&bytes[..end]) {
364        Err(error) if error.error_len().is_none() && error.valid_up_to() > 0 => error.valid_up_to(),
365        _ => end,
366    }
367}
368
369/// The Tool log of one review as a screen shows it: one entry per run, in the order they
370/// started, each with its output and, once known, its end.
371#[derive(Debug, Clone, Default, PartialEq, Eq)]
372pub struct ToolLog {
373    entries: Vec<Entry>,
374}
375
376#[derive(Debug, Clone, PartialEq, Eq)]
377pub struct Entry {
378    pub run: RunNo,
379    pub at: OffsetDateTime,
380    pub operation: String,
381    pub artifact: String,
382    pub lines: Vec<(Stream, String)>,
383    pub end: Option<End>,
384}
385
386impl Entry {
387    /// The start line, `▶ HH:MM:SS · operation · Artifact`, at `offset` from UTC.
388    pub fn start_text(&self, offset: time::UtcOffset) -> String {
389        start_text(
390            self.at.to_offset(offset).time(),
391            &self.operation,
392            &self.artifact,
393        )
394    }
395}
396
397/// `▶ HH:MM:SS · operation · Artifact`.
398pub fn start_text(at: time::Time, operation: &str, artifact: &str) -> String {
399    format!(
400        "▶ {:02}:{:02}:{:02} · {operation} · {artifact}",
401        at.hour(),
402        at.minute(),
403        at.second()
404    )
405}
406
407impl ToolLog {
408    /// Take `event` in: a start opens an entry; lines and the end join their run's entry.
409    /// Lines of a run this log never saw start (it was cleared since) are dropped.
410    pub fn apply(&mut self, event: Event) {
411        match event.kind {
412            Kind::Start {
413                at,
414                operation,
415                artifact,
416            } => self.entries.push(Entry {
417                run: event.run,
418                at,
419                operation,
420                artifact,
421                lines: Vec::new(),
422                end: None,
423            }),
424            kind => {
425                let Some(entry) = self.entries.iter_mut().find(|entry| entry.run == event.run)
426                else {
427                    return;
428                };
429                match kind {
430                    Kind::Line { stream, text } => entry.lines.push((stream, text)),
431                    Kind::End(end) => entry.end = Some(end),
432                    Kind::Start { .. } => unreachable!("handled above"),
433                }
434            }
435        }
436    }
437
438    pub fn entries(&self) -> &[Entry] {
439        &self.entries
440    }
441
442    pub fn is_empty(&self) -> bool {
443        self.entries.is_empty()
444    }
445
446    pub fn clear(&mut self) {
447        self.entries.clear();
448    }
449}
450
451#[cfg(test)]
452mod tests {
453    use super::*;
454
455    fn request() -> RequestId {
456        "req-1".parse().unwrap()
457    }
458
459    fn drain(events: &mut Events) -> Vec<Kind> {
460        std::iter::from_fn(|| events.try_recv().ok())
461            .map(|event| event.kind)
462            .collect()
463    }
464
465    fn line(stream: Stream, text: &str) -> Kind {
466        Kind::Line {
467            stream,
468            text: text.into(),
469        }
470    }
471
472    #[test]
473    fn output_arrives_as_lines_of_its_own_stream() {
474        let (sink, mut events) = channel();
475        let run = sink.start(&request(), "open", "notes");
476        let mut out = run.lines(Stream::Stdout);
477        let mut err = run.lines(Stream::Stderr);
478        out.push(b"one\r\ntw");
479        err.push(b"warn\n");
480        out.push(b"o\nthree");
481        out.finish();
482        err.finish();
483        run.end(End::Exited {
484            code: Some(0),
485            text: String::new(),
486        });
487        let kinds = drain(&mut events);
488        assert!(matches!(&kinds[0], Kind::Start { operation, artifact, .. }
489            if operation == "open" && artifact == "notes"));
490        assert_eq!(
491            kinds[1..],
492            [
493                line(Stream::Stdout, "one"),
494                line(Stream::Stderr, "warn"),
495                line(Stream::Stdout, "two"),
496                line(Stream::Stdout, "three"),
497                Kind::End(End::Exited {
498                    code: Some(0),
499                    text: String::new()
500                }),
501            ]
502        );
503    }
504
505    #[test]
506    fn a_line_without_newline_shows_in_pieces_that_keep_characters_whole() {
507        let (sink, mut events) = channel();
508        let run = sink.start(&request(), "dump", "app");
509        let mut out = run.lines(Stream::Stdout);
510        let mut text = "a".repeat(LINE_BYTES - 1);
511        text.push('é');
512        out.push(text.as_bytes());
513        let kinds = drain(&mut events);
514        assert_eq!(
515            kinds[1..],
516            [line(Stream::Stdout, &"a".repeat(LINE_BYTES - 1))]
517        );
518        out.finish();
519        assert_eq!(drain(&mut events), [line(Stream::Stdout, "é")]);
520    }
521
522    #[test]
523    fn a_run_shows_its_output_up_to_its_budget_then_says_the_rest_is_not_shown() {
524        let (sink, mut events) = channel();
525        let run = sink.start(&request(), "spew", "app");
526        let chunk = format!("{}\n", "x".repeat(LINE_BYTES - 1));
527        for _ in 0..(RUN_BYTES / (LINE_BYTES - 1) + 10) {
528            run.lines(Stream::Stdout).push(chunk.as_bytes());
529        }
530        let kinds = drain(&mut events);
531        let shown: usize = kinds
532            .iter()
533            .filter_map(|kind| match kind {
534                Kind::Line {
535                    stream: Stream::Stdout,
536                    text,
537                } => Some(text.len()),
538                _ => None,
539            })
540            .sum();
541        assert!(shown <= RUN_BYTES);
542        assert_eq!(kinds.last(), Some(&line(Stream::Stderr, DROPPED)));
543        assert_eq!(
544            kinds
545                .iter()
546                .filter(|kind| **kind == line(Stream::Stderr, DROPPED))
547                .count(),
548            1
549        );
550    }
551
552    #[test]
553    fn a_run_dropped_without_an_end_was_cancelled_and_a_closed_review_discards_lines() {
554        let (sink, mut events) = channel();
555        drop(sink.start(&request(), "slow", "app"));
556        assert_eq!(drain(&mut events).last(), Some(&Kind::End(End::Cancelled)));
557        let run = sink.start(&request(), "late", "app");
558        drop(events);
559        run.text(Stream::Stdout, "nobody reads this\n");
560        run.end(End::Done);
561    }
562
563    #[test]
564    fn the_log_groups_lines_under_their_run_and_ignores_runs_it_never_saw_start() {
565        let (sink, mut events) = channel();
566        let first = sink.start(&request(), "launch", "app");
567        let second = sink.start(&request(), "check", "lib");
568        second.text(Stream::Stdout, "checked\n");
569        second.end(End::Done);
570        first.text(Stream::Stderr, "app says\n");
571        let mut log = ToolLog::default();
572        for event in std::iter::from_fn(|| events.try_recv().ok()) {
573            log.apply(event);
574        }
575        let [launch, check] = log.entries() else {
576            panic!("two entries: {log:?}");
577        };
578        assert_eq!(launch.lines, [(Stream::Stderr, "app says".to_owned())]);
579        assert_eq!(launch.end, None);
580        assert_eq!(check.lines, [(Stream::Stdout, "checked".to_owned())]);
581        assert_eq!(check.end, Some(End::Done));
582        log.clear();
583        first.end(End::Done);
584        log.apply(events.try_recv().unwrap());
585        assert!(log.is_empty());
586    }
587
588    #[test]
589    fn end_lines_say_how_a_run_ended() {
590        let exit = |code| End::Exited {
591            code: Some(code),
592            text: String::new(),
593        };
594        assert_eq!(exit(0).text(), "■ exit 0");
595        assert!(!exit(0).error());
596        assert_eq!(exit(2).text(), "■ exit 2");
597        assert!(exit(2).error());
598        assert_eq!(End::Launched.text(), "■ launched");
599        assert_eq!(End::TimedOut.text(), "■ timed out");
600        assert_eq!(End::Failed("no".into()).text(), "■ error: no");
601        assert!(End::Cancelled.error());
602        assert_eq!(
603            start_text(time::Time::from_hms(9, 5, 7).unwrap(), "open", "notes"),
604            "▶ 09:05:07 · open · notes"
605        );
606    }
607}