1use 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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
25pub enum Key {
26 Review(RequestId),
28 Artifact {
31 repo: PathBuf,
32 branch: crate::monitor::live::Place,
33 artifact: ArtifactName,
34 },
35}
36
37impl Key {
38 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
53const RUN_BYTES: usize = 1024 * 1024;
56const LINE_BYTES: usize = 4096;
58const DROPPED: &str = "[more output than the Tool log keeps; the rest is not shown]";
60
61static NEXT_RUN: AtomicU64 = AtomicU64::new(1);
63
64#[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#[derive(Debug, Clone, PartialEq, Eq)]
82pub enum End {
83 Exited {
85 code: Option<i32>,
86 text: String,
87 },
88 Launched,
90 Done,
92 Cancelled,
93 TimedOut,
94 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 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 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 artifact: String,
137 },
138 Line {
139 stream: Stream,
140 text: String,
141 },
142 End(End),
143}
144
145#[derive(Debug, Clone, PartialEq, Eq)]
147pub struct Event {
148 pub key: Key,
149 pub run: RunNo,
150 pub kind: Kind,
151}
152
153#[derive(Debug, Clone)]
155pub struct Sink {
156 sender: mpsc::UnboundedSender<Event>,
157 wait_for_viewer: bool,
158}
159
160pub 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 pub fn with_viewer_launch(mut self) -> Self {
177 self.wait_for_viewer = true;
178 self
179 }
180
181 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 watch: Option<(Sink, Key)>,
197 run: RunNo,
198 left: AtomicUsize,
200 dropped: AtomicBool,
201}
202
203impl Shared {
204 fn send(&self, kind: Kind) {
205 if let Some((sink, key)) = &self.watch {
206 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 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
247pub 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 pub fn unwatched() -> Self {
279 Self::new(None)
280 }
281
282 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 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 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
341pub(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 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
381fn 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#[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 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
419pub 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 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;