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        branch: crate::monitor::live::Place,
33        artifact: ArtifactName,
34    },
35}
36
37impl Key {
38    /// The review this log belongs to, if it is a review's.
39    pub fn request(&self) -> Option<&RequestId> {
40        match self {
41            Self::Review(request) => Some(request),
42            Self::Artifact { .. } => None,
43        }
44    }
45}
46
47impl From<&RequestId> for Key {
48    fn from(request: &RequestId) -> Self {
49        Self::Review(request.clone())
50    }
51}
52
53/// Output bytes one run shows at most: a launched program may print for hours, and the log
54/// is held in memory for as long as the review is open.
55const RUN_BYTES: usize = 1024 * 1024;
56/// A line longer than this is shown in pieces, so output without newlines still appears.
57const LINE_BYTES: usize = 4096;
58/// Shown once, as an error line, when a run printed more than the log keeps.
59const DROPPED: &str = "[more output than the Tool log keeps; the rest is not shown]";
60
61/// Numbers every run of this process, so lines arriving later find their own entry.
62static NEXT_RUN: AtomicU64 = AtomicU64::new(1);
63
64/// One tool run, unique in this process.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
66pub struct RunNo(u64);
67
68impl RunNo {
69    pub fn get(self) -> u64 {
70        self.0
71    }
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum Stream {
76    Stdout,
77    Stderr,
78}
79
80/// How a run ended, as its last log line says.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub enum End {
83    /// The program exited: its exit code, or how it ended without one.
84    Exited {
85        code: Option<i32>,
86        text: String,
87    },
88    /// Handed to the desktop's own opener; its output is not the tool's.
89    Launched,
90    /// A builtin finished.
91    Done,
92    Cancelled,
93    TimedOut,
94    /// The run could not start or failed, and why.
95    Failed(String),
96}
97
98impl End {
99    pub(crate) fn exited(status: &crate::platform::ProcessOutcome) -> Self {
100        Self::Exited {
101            code: status.code(),
102            text: status.to_string(),
103        }
104    }
105
106    /// The end line: `■ exit 0`, `■ launched`, `■ error: …`.
107    pub fn text(&self) -> String {
108        match self {
109            Self::Exited {
110                code: Some(code), ..
111            } => format!("■ exit {code}"),
112            Self::Exited { text, .. } => format!("■ {text}"),
113            Self::Launched => "■ launched".into(),
114            Self::Done => "■ done".into(),
115            Self::Cancelled => "■ cancelled".into(),
116            Self::TimedOut => "■ timed out".into(),
117            Self::Failed(error) => format!("■ error: {error}"),
118        }
119    }
120
121    /// The run did not end well.
122    pub fn error(&self) -> bool {
123        !matches!(
124            self,
125            Self::Exited { code: Some(0), .. } | Self::Launched | Self::Done
126        )
127    }
128}
129
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub enum Kind {
132    Start {
133        at: OffsetDateTime,
134        operation: String,
135        /// The Artifact that declares the tool.
136        artifact: String,
137    },
138    Line {
139        stream: Stream,
140        text: String,
141    },
142    End(End),
143}
144
145/// One thing a run logged, for the log of `key`.
146#[derive(Debug, Clone, PartialEq, Eq)]
147pub struct Event {
148    pub key: Key,
149    pub run: RunNo,
150    pub kind: Kind,
151}
152
153/// Where runs send their events; cloned into each job a review starts.
154#[derive(Debug, Clone)]
155pub struct Sink {
156    sender: mpsc::UnboundedSender<Event>,
157    wait_for_viewer: bool,
158}
159
160/// The review's end of the log. Every run bounds its output, so the channel is unbounded.
161pub type Events = mpsc::UnboundedReceiver<Event>;
162
163pub fn channel() -> (Sink, Events) {
164    let (sender, receiver) = mpsc::unbounded_channel();
165    (
166        Sink {
167            sender,
168            wait_for_viewer: false,
169        },
170        receiver,
171    )
172}
173
174impl Sink {
175    /// The desktop will complete a Viewer run after opening its native window.
176    pub fn with_viewer_launch(mut self) -> Self {
177        self.wait_for_viewer = true;
178        self
179    }
180
181    /// Start a run of `operation` of `artifact` in the log of `key`: its start line is logged
182    /// now.
183    pub fn start(&self, key: impl Into<Key>, operation: &str, artifact: &str) -> Run {
184        let run = Run::new(Some((self.clone(), key.into())));
185        run.shared.send(Kind::Start {
186            at: OffsetDateTime::now_utc(),
187            operation: operation.to_owned(),
188            artifact: artifact.to_owned(),
189        });
190        run
191    }
192}
193
194struct Shared {
195    /// Where the run's events go and the log they belong to; `None` when nobody watches.
196    watch: Option<(Sink, Key)>,
197    run: RunNo,
198    /// Output bytes this run may still show.
199    left: AtomicUsize,
200    dropped: AtomicBool,
201}
202
203impl Shared {
204    fn send(&self, kind: Kind) {
205        if let Some((sink, key)) = &self.watch {
206            // A closed review discards what its runs still print.
207            let _ = sink.sender.send(Event {
208                key: key.clone(),
209                run: self.run,
210                kind,
211            });
212        }
213    }
214
215    fn line(&self, stream: Stream, bytes: &[u8]) {
216        if !self.watched() {
217            return;
218        }
219        let text = crate::platform::clean_program_text(bytes);
220        let size = text.len().max(1);
221        // A compare-and-swap loop rather than `fetch_update`, which newer toolchains
222        // deprecate under another name.
223        let mut left = self.left.load(Ordering::Relaxed);
224        let kept = loop {
225            let Some(next) = left.checked_sub(size) else {
226                break false;
227            };
228            match self
229                .left
230                .compare_exchange_weak(left, next, Ordering::Relaxed, Ordering::Relaxed)
231            {
232                Ok(_) => break true,
233                Err(current) => left = current,
234            }
235        };
236        if kept {
237            self.send(Kind::Line { stream, text });
238        } else if !self.dropped.swap(true, Ordering::Relaxed) {
239            self.send(Kind::Line {
240                stream: Stream::Stderr,
241                text: DROPPED.into(),
242            });
243        }
244    }
245}
246
247/// One tool run's log: lines while it runs, then exactly one end. A run dropped without an
248/// end was cancelled.
249pub struct Run {
250    shared: Arc<Shared>,
251    ended: bool,
252    launch: Option<Box<dyn FnOnce(crate::process::ChildIdentity) + Send + Sync>>,
253}
254
255impl std::fmt::Debug for Run {
256    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
257        f.debug_struct("Run")
258            .field("run", &self.shared.run)
259            .finish()
260    }
261}
262
263impl Run {
264    fn new(watch: Option<(Sink, Key)>) -> Self {
265        Self {
266            shared: Arc::new(Shared {
267                watch,
268                run: RunNo(NEXT_RUN.fetch_add(1, Ordering::Relaxed)),
269                left: AtomicUsize::new(RUN_BYTES),
270                dropped: AtomicBool::new(false),
271            }),
272            ended: false,
273            launch: None,
274        }
275    }
276
277    /// A run nobody shows, such as `tool check`'s: launched programs get no pipes at all.
278    pub fn unwatched() -> Self {
279        Self::new(None)
280    }
281
282    /// Observe the native birth identity at successful spawn, before a detached program's
283    /// own startup protocol. This does not change the log or the launch's lifetime.
284    pub fn observe_launch(
285        mut self,
286        observe: impl FnOnce(crate::process::ChildIdentity) + Send + Sync + 'static,
287    ) -> Self {
288        self.launch = Some(Box::new(observe));
289        self
290    }
291
292    pub(crate) fn launched(&mut self, pid: u32) {
293        if let Some(observe) = self.launch.take()
294            && let Ok(identity) = crate::process::child_identity(pid)
295        {
296            observe(identity);
297        }
298    }
299
300    pub(crate) fn waits_for_viewer(&self) -> bool {
301        self.shared
302            .watch
303            .as_ref()
304            .is_some_and(|(sink, _)| sink.wait_for_viewer)
305    }
306
307    pub(crate) fn watched(&self) -> bool {
308        self.shared.watched()
309    }
310
311    /// A splitter of one output stream into this run's lines.
312    pub(crate) fn lines(&self, stream: Stream) -> Lines {
313        Lines {
314            shared: self.shared.clone(),
315            stream,
316            pending: Vec::new(),
317        }
318    }
319
320    /// Log `text`, a finished output, line by line.
321    pub fn text(&self, stream: Stream, text: &str) {
322        let mut lines = self.lines(stream);
323        lines.push(text.as_bytes());
324        lines.finish();
325    }
326
327    pub fn end(mut self, end: End) {
328        self.ended = true;
329        self.shared.send(Kind::End(end));
330    }
331}
332
333impl Drop for Run {
334    fn drop(&mut self) {
335        if !self.ended {
336            self.shared.send(Kind::End(End::Cancelled));
337        }
338    }
339}
340
341/// Bytes of one stream cut into lines: at each newline, and in pieces of [`LINE_BYTES`].
342pub(crate) struct Lines {
343    shared: Arc<Shared>,
344    stream: Stream,
345    pending: Vec<u8>,
346}
347
348impl Lines {
349    pub(crate) fn push(&mut self, bytes: &[u8]) {
350        if !self.shared.watched() {
351            return;
352        }
353        self.pending.extend_from_slice(bytes);
354        while let Some(newline) = self.pending.iter().position(|byte| *byte == b'\n') {
355            let line: Vec<u8> = self.pending.drain(..=newline).collect();
356            self.shared
357                .line(self.stream, crate::platform::output_line(&line));
358        }
359        while self.pending.len() >= LINE_BYTES {
360            let end = piece(&self.pending);
361            let piece: Vec<u8> = self.pending.drain(..end).collect();
362            self.shared.line(self.stream, &piece);
363        }
364    }
365
366    /// The stream closed: its last line, if it had no newline.
367    pub(crate) fn finish(&mut self) {
368        if !self.pending.is_empty() {
369            let line = std::mem::take(&mut self.pending);
370            self.shared.line(self.stream, &line);
371        }
372    }
373}
374
375impl Shared {
376    fn watched(&self) -> bool {
377        self.watch.is_some()
378    }
379}
380
381/// Where a long line's first piece ends: [`LINE_BYTES`] in, moved back so that a character
382/// cut in two stays whole for the next piece.
383fn piece(bytes: &[u8]) -> usize {
384    let end = LINE_BYTES.min(bytes.len());
385    match std::str::from_utf8(&bytes[..end]) {
386        Err(error) if error.error_len().is_none() && error.valid_up_to() > 0 => error.valid_up_to(),
387        _ => end,
388    }
389}
390
391/// The Tool log of one review as a screen shows it: one entry per run, in the order they
392/// started, each with its output and, once known, its end.
393#[derive(Debug, Clone, Default, PartialEq, Eq)]
394pub struct ToolLog {
395    entries: Vec<Entry>,
396}
397
398#[derive(Debug, Clone, PartialEq, Eq)]
399pub struct Entry {
400    pub run: RunNo,
401    pub at: OffsetDateTime,
402    pub operation: String,
403    pub artifact: String,
404    pub lines: Vec<(Stream, String)>,
405    pub end: Option<End>,
406}
407
408impl Entry {
409    /// The start line, `▶ HH:MM:SS · operation · Artifact`, at `offset` from UTC.
410    pub fn start_text(&self, offset: time::UtcOffset) -> String {
411        start_text(
412            self.at.to_offset(offset).time(),
413            &self.operation,
414            &self.artifact,
415        )
416    }
417}
418
419/// `▶ HH:MM:SS · operation · Artifact`.
420pub fn start_text(at: time::Time, operation: &str, artifact: &str) -> String {
421    format!(
422        "▶ {:02}:{:02}:{:02} · {operation} · {artifact}",
423        at.hour(),
424        at.minute(),
425        at.second()
426    )
427}
428
429impl ToolLog {
430    /// Take `event` in: a start opens an entry; lines and the end join their run's entry.
431    /// Lines of a run this log never saw start (it was cleared since) are dropped.
432    pub fn apply(&mut self, event: Event) {
433        match event.kind {
434            Kind::Start {
435                at,
436                operation,
437                artifact,
438            } => self.entries.push(Entry {
439                run: event.run,
440                at,
441                operation,
442                artifact,
443                lines: Vec::new(),
444                end: None,
445            }),
446            kind => {
447                let Some(entry) = self.entries.iter_mut().find(|entry| entry.run == event.run)
448                else {
449                    return;
450                };
451                match kind {
452                    Kind::Line { stream, text } => entry.lines.push((stream, text)),
453                    Kind::End(end) => entry.end = Some(end),
454                    Kind::Start { .. } => unreachable!("handled above"),
455                }
456            }
457        }
458    }
459
460    pub fn entries(&self) -> &[Entry] {
461        &self.entries
462    }
463
464    pub fn is_empty(&self) -> bool {
465        self.entries.is_empty()
466    }
467
468    pub fn clear(&mut self) {
469        self.entries.clear();
470    }
471}
472
473#[cfg(test)]
474mod tests;