use std::{
path::PathBuf,
sync::{
Arc,
atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
},
};
use time::OffsetDateTime;
use tokio::sync::mpsc;
use crate::types::{ArtifactName, RequestId};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Key {
Review(RequestId),
Artifact {
repo: PathBuf,
branch: crate::monitor::live::Place,
artifact: ArtifactName,
},
}
impl Key {
pub fn request(&self) -> Option<&RequestId> {
match self {
Self::Review(request) => Some(request),
Self::Artifact { .. } => None,
}
}
}
impl From<&RequestId> for Key {
fn from(request: &RequestId) -> Self {
Self::Review(request.clone())
}
}
const RUN_BYTES: usize = 1024 * 1024;
const LINE_BYTES: usize = 4096;
const DROPPED: &str = "[more output than the Tool log keeps; the rest is not shown]";
static NEXT_RUN: AtomicU64 = AtomicU64::new(1);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RunNo(u64);
impl RunNo {
pub fn get(self) -> u64 {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Stream {
Stdout,
Stderr,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum End {
Exited {
code: Option<i32>,
text: String,
},
Launched,
Done,
Cancelled,
TimedOut,
Failed(String),
}
impl End {
pub(crate) fn exited(status: &crate::platform::ProcessOutcome) -> Self {
Self::Exited {
code: status.code(),
text: status.to_string(),
}
}
pub fn text(&self) -> String {
match self {
Self::Exited {
code: Some(code), ..
} => format!("■ exit {code}"),
Self::Exited { text, .. } => format!("■ {text}"),
Self::Launched => "■ launched".into(),
Self::Done => "■ done".into(),
Self::Cancelled => "■ cancelled".into(),
Self::TimedOut => "■ timed out".into(),
Self::Failed(error) => format!("■ error: {error}"),
}
}
pub fn error(&self) -> bool {
!matches!(
self,
Self::Exited { code: Some(0), .. } | Self::Launched | Self::Done
)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Kind {
Start {
at: OffsetDateTime,
operation: String,
artifact: String,
},
Line {
stream: Stream,
text: String,
},
End(End),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Event {
pub key: Key,
pub run: RunNo,
pub kind: Kind,
}
#[derive(Debug, Clone)]
pub struct Sink {
sender: mpsc::UnboundedSender<Event>,
wait_for_viewer: bool,
}
pub type Events = mpsc::UnboundedReceiver<Event>;
pub fn channel() -> (Sink, Events) {
let (sender, receiver) = mpsc::unbounded_channel();
(
Sink {
sender,
wait_for_viewer: false,
},
receiver,
)
}
impl Sink {
pub fn with_viewer_launch(mut self) -> Self {
self.wait_for_viewer = true;
self
}
pub fn start(&self, key: impl Into<Key>, operation: &str, artifact: &str) -> Run {
let run = Run::new(Some((self.clone(), key.into())));
run.shared.send(Kind::Start {
at: OffsetDateTime::now_utc(),
operation: operation.to_owned(),
artifact: artifact.to_owned(),
});
run
}
}
struct Shared {
watch: Option<(Sink, Key)>,
run: RunNo,
left: AtomicUsize,
dropped: AtomicBool,
}
impl Shared {
fn send(&self, kind: Kind) {
if let Some((sink, key)) = &self.watch {
let _ = sink.sender.send(Event {
key: key.clone(),
run: self.run,
kind,
});
}
}
fn line(&self, stream: Stream, bytes: &[u8]) {
if !self.watched() {
return;
}
let text = crate::platform::clean_program_text(bytes);
let size = text.len().max(1);
let mut left = self.left.load(Ordering::Relaxed);
let kept = loop {
let Some(next) = left.checked_sub(size) else {
break false;
};
match self
.left
.compare_exchange_weak(left, next, Ordering::Relaxed, Ordering::Relaxed)
{
Ok(_) => break true,
Err(current) => left = current,
}
};
if kept {
self.send(Kind::Line { stream, text });
} else if !self.dropped.swap(true, Ordering::Relaxed) {
self.send(Kind::Line {
stream: Stream::Stderr,
text: DROPPED.into(),
});
}
}
}
pub struct Run {
shared: Arc<Shared>,
ended: bool,
launch: Option<Box<dyn FnOnce(crate::process::ChildIdentity) + Send + Sync>>,
}
impl std::fmt::Debug for Run {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Run")
.field("run", &self.shared.run)
.finish()
}
}
impl Run {
fn new(watch: Option<(Sink, Key)>) -> Self {
Self {
shared: Arc::new(Shared {
watch,
run: RunNo(NEXT_RUN.fetch_add(1, Ordering::Relaxed)),
left: AtomicUsize::new(RUN_BYTES),
dropped: AtomicBool::new(false),
}),
ended: false,
launch: None,
}
}
pub fn unwatched() -> Self {
Self::new(None)
}
pub fn observe_launch(
mut self,
observe: impl FnOnce(crate::process::ChildIdentity) + Send + Sync + 'static,
) -> Self {
self.launch = Some(Box::new(observe));
self
}
pub(crate) fn launched(&mut self, pid: u32) {
if let Some(observe) = self.launch.take()
&& let Ok(identity) = crate::process::child_identity(pid)
{
observe(identity);
}
}
pub(crate) fn waits_for_viewer(&self) -> bool {
self.shared
.watch
.as_ref()
.is_some_and(|(sink, _)| sink.wait_for_viewer)
}
pub(crate) fn watched(&self) -> bool {
self.shared.watched()
}
pub(crate) fn lines(&self, stream: Stream) -> Lines {
Lines {
shared: self.shared.clone(),
stream,
pending: Vec::new(),
}
}
pub fn text(&self, stream: Stream, text: &str) {
let mut lines = self.lines(stream);
lines.push(text.as_bytes());
lines.finish();
}
pub fn end(mut self, end: End) {
self.ended = true;
self.shared.send(Kind::End(end));
}
}
impl Drop for Run {
fn drop(&mut self) {
if !self.ended {
self.shared.send(Kind::End(End::Cancelled));
}
}
}
pub(crate) struct Lines {
shared: Arc<Shared>,
stream: Stream,
pending: Vec<u8>,
}
impl Lines {
pub(crate) fn push(&mut self, bytes: &[u8]) {
if !self.shared.watched() {
return;
}
self.pending.extend_from_slice(bytes);
while let Some(newline) = self.pending.iter().position(|byte| *byte == b'\n') {
let line: Vec<u8> = self.pending.drain(..=newline).collect();
self.shared
.line(self.stream, crate::platform::output_line(&line));
}
while self.pending.len() >= LINE_BYTES {
let end = piece(&self.pending);
let piece: Vec<u8> = self.pending.drain(..end).collect();
self.shared.line(self.stream, &piece);
}
}
pub(crate) fn finish(&mut self) {
if !self.pending.is_empty() {
let line = std::mem::take(&mut self.pending);
self.shared.line(self.stream, &line);
}
}
}
impl Shared {
fn watched(&self) -> bool {
self.watch.is_some()
}
}
fn piece(bytes: &[u8]) -> usize {
let end = LINE_BYTES.min(bytes.len());
match std::str::from_utf8(&bytes[..end]) {
Err(error) if error.error_len().is_none() && error.valid_up_to() > 0 => error.valid_up_to(),
_ => end,
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ToolLog {
entries: Vec<Entry>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
pub run: RunNo,
pub at: OffsetDateTime,
pub operation: String,
pub artifact: String,
pub lines: Vec<(Stream, String)>,
pub end: Option<End>,
}
impl Entry {
pub fn start_text(&self, offset: time::UtcOffset) -> String {
start_text(
self.at.to_offset(offset).time(),
&self.operation,
&self.artifact,
)
}
}
pub fn start_text(at: time::Time, operation: &str, artifact: &str) -> String {
format!(
"▶ {:02}:{:02}:{:02} · {operation} · {artifact}",
at.hour(),
at.minute(),
at.second()
)
}
impl ToolLog {
pub fn apply(&mut self, event: Event) {
match event.kind {
Kind::Start {
at,
operation,
artifact,
} => self.entries.push(Entry {
run: event.run,
at,
operation,
artifact,
lines: Vec::new(),
end: None,
}),
kind => {
let Some(entry) = self.entries.iter_mut().find(|entry| entry.run == event.run)
else {
return;
};
match kind {
Kind::Line { stream, text } => entry.lines.push((stream, text)),
Kind::End(end) => entry.end = Some(end),
Kind::Start { .. } => unreachable!("handled above"),
}
}
}
}
pub fn entries(&self) -> &[Entry] {
&self.entries
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn clear(&mut self) {
self.entries.clear();
}
}
#[cfg(test)]
mod tests;