use std::io::{self, Read};
use std::process::ExitStatus;
use std::sync::{Arc, Mutex};
use super::STDERR_TAIL_LIMIT;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ExitKind {
CleanShutdown,
UnhandledError,
UsageError,
ConfigError,
LeaseUnavailable,
SdkSurfaceUnavailable,
Crash,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RetryGuidance {
Never,
FixConfig,
AfterLeaseRelease,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CloseAttribution {
Ours,
Theirs,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ExitClassification {
pub kind: ExitKind,
pub exit_code: Option<i32>,
pub exit_signal: Option<i32>,
pub stderr_tail: Vec<String>,
pub retry: Option<RetryGuidance>,
pub close_attribution: CloseAttribution,
}
#[must_use]
pub fn classify_exit(
exit_code: Option<i32>,
exit_signal: Option<i32>,
stderr_tail: Vec<String>,
close_attribution: CloseAttribution,
) -> ExitClassification {
let (kind, retry) = match exit_code {
Some(0) => (ExitKind::CleanShutdown, None),
Some(1) => (ExitKind::UnhandledError, None),
Some(2) => (ExitKind::UsageError, Some(RetryGuidance::Never)),
Some(3) => (ExitKind::ConfigError, Some(RetryGuidance::FixConfig)),
Some(4) => (
ExitKind::LeaseUnavailable,
Some(RetryGuidance::AfterLeaseRelease),
),
Some(5) => (ExitKind::SdkSurfaceUnavailable, Some(RetryGuidance::Never)),
_ => (ExitKind::Crash, None),
};
ExitClassification {
kind,
exit_code,
exit_signal,
stderr_tail: bounded_stderr_tail(stderr_tail),
retry,
close_attribution,
}
}
pub(super) fn classify_status(
status: ExitStatus,
stderr_tail: Vec<String>,
close_attribution: CloseAttribution,
) -> ExitClassification {
let exit = raw_exit(status);
classify_exit(exit.0, exit.1, stderr_tail, close_attribution)
}
pub(super) fn raw_exit(status: ExitStatus) -> (Option<i32>, Option<i32>) {
#[cfg(unix)]
let signal = std::os::unix::process::ExitStatusExt::signal(&status);
#[cfg(not(unix))]
let signal = None;
(status.code(), signal)
}
#[derive(Debug, Clone, Default)]
pub(super) struct StderrTailBuffer(Arc<Mutex<Vec<u8>>>);
impl StderrTailBuffer {
fn push(&self, bytes: &[u8]) {
let mut tail = self
.0
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let bytes = &bytes[bytes.len().saturating_sub(STDERR_TAIL_LIMIT)..];
let overflow = (tail.len() + bytes.len()).saturating_sub(STDERR_TAIL_LIMIT);
tail.drain(..overflow);
tail.extend(bytes);
}
pub(super) fn snapshot(&self) -> Vec<String> {
let bytes = self
.0
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.clone();
bounded_stderr_tail(
String::from_utf8_lossy(&bytes)
.lines()
.map(str::to_owned)
.collect(),
)
}
#[cfg(test)]
pub(super) fn len(&self) -> usize {
self.0.lock().map_or(usize::MAX, |tail| tail.len())
}
}
pub(super) fn drain_stderr(mut reader: impl Read, tail: StderrTailBuffer) {
let mut chunk = [0_u8; 4096];
loop {
match reader.read(&mut chunk) {
Ok(0) => break,
Ok(read) => tail.push(&chunk[..read]),
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
Err(_) => break,
}
}
}
fn bounded_stderr_tail(lines: Vec<String>) -> Vec<String> {
let mut kept = Vec::new();
let mut kept_bytes = 0;
for line in lines.into_iter().rev() {
let separator = usize::from(!kept.is_empty());
if kept_bytes + separator >= STDERR_TAIL_LIMIT {
break;
}
let remaining = STDERR_TAIL_LIMIT - kept_bytes - separator;
let line = if line.len() <= remaining {
line
} else {
let mut start = line.len() - remaining;
while !line.is_char_boundary(start) {
start += 1;
}
line[start..].to_owned()
};
kept_bytes += separator + line.len();
kept.push(line);
}
kept.reverse();
kept
}