muse_code_sdk/spawn/
exit.rs1use std::io::{self, Read};
2use std::process::ExitStatus;
3use std::sync::{Arc, Mutex};
4
5use super::STDERR_TAIL_LIMIT;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9#[non_exhaustive]
10pub enum ExitKind {
11 CleanShutdown,
13 UnhandledError,
16 UsageError,
18 ConfigError,
21 LeaseUnavailable,
24 SdkSurfaceUnavailable,
27 Crash,
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34#[non_exhaustive]
35pub enum RetryGuidance {
36 Never,
38 FixConfig,
40 AfterLeaseRelease,
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52#[non_exhaustive]
53pub enum CloseAttribution {
54 Ours,
58 Theirs,
62}
63
64#[derive(Debug, Clone, PartialEq, Eq)]
66#[non_exhaustive]
67pub struct ExitClassification {
68 pub kind: ExitKind,
70 pub exit_code: Option<i32>,
72 pub exit_signal: Option<i32>,
74 pub stderr_tail: Vec<String>,
77 pub retry: Option<RetryGuidance>,
79 pub close_attribution: CloseAttribution,
81}
82
83#[must_use]
85pub fn classify_exit(
86 exit_code: Option<i32>,
87 exit_signal: Option<i32>,
88 stderr_tail: Vec<String>,
89 close_attribution: CloseAttribution,
90) -> ExitClassification {
91 let (kind, retry) = match exit_code {
92 Some(0) => (ExitKind::CleanShutdown, None),
93 Some(1) => (ExitKind::UnhandledError, None),
94 Some(2) => (ExitKind::UsageError, Some(RetryGuidance::Never)),
95 Some(3) => (ExitKind::ConfigError, Some(RetryGuidance::FixConfig)),
96 Some(4) => (
97 ExitKind::LeaseUnavailable,
98 Some(RetryGuidance::AfterLeaseRelease),
99 ),
100 Some(5) => (ExitKind::SdkSurfaceUnavailable, Some(RetryGuidance::Never)),
101 _ => (ExitKind::Crash, None),
102 };
103 ExitClassification {
104 kind,
105 exit_code,
106 exit_signal,
107 stderr_tail: bounded_stderr_tail(stderr_tail),
108 retry,
109 close_attribution,
110 }
111}
112
113pub(super) fn classify_status(
114 status: ExitStatus,
115 stderr_tail: Vec<String>,
116 close_attribution: CloseAttribution,
117) -> ExitClassification {
118 let exit = raw_exit(status);
119 classify_exit(exit.0, exit.1, stderr_tail, close_attribution)
120}
121
122pub(super) fn raw_exit(status: ExitStatus) -> (Option<i32>, Option<i32>) {
123 #[cfg(unix)]
124 let signal = std::os::unix::process::ExitStatusExt::signal(&status);
125 #[cfg(not(unix))]
126 let signal = None;
127 (status.code(), signal)
128}
129
130#[derive(Debug, Clone, Default)]
131pub(super) struct StderrTailBuffer(Arc<Mutex<Vec<u8>>>);
132
133impl StderrTailBuffer {
134 fn push(&self, bytes: &[u8]) {
135 let mut tail = self
136 .0
137 .lock()
138 .unwrap_or_else(|poisoned| poisoned.into_inner());
139 let bytes = &bytes[bytes.len().saturating_sub(STDERR_TAIL_LIMIT)..];
140 let overflow = (tail.len() + bytes.len()).saturating_sub(STDERR_TAIL_LIMIT);
141 tail.drain(..overflow);
142 tail.extend(bytes);
143 }
144
145 pub(super) fn snapshot(&self) -> Vec<String> {
146 let bytes = self
147 .0
148 .lock()
149 .unwrap_or_else(|poisoned| poisoned.into_inner())
150 .clone();
151 bounded_stderr_tail(
152 String::from_utf8_lossy(&bytes)
153 .lines()
154 .map(str::to_owned)
155 .collect(),
156 )
157 }
158
159 #[cfg(test)]
160 pub(super) fn len(&self) -> usize {
161 self.0.lock().map_or(usize::MAX, |tail| tail.len())
162 }
163}
164
165pub(super) fn drain_stderr(mut reader: impl Read, tail: StderrTailBuffer) {
166 let mut chunk = [0_u8; 4096];
167 loop {
168 match reader.read(&mut chunk) {
169 Ok(0) => break,
170 Ok(read) => tail.push(&chunk[..read]),
171 Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
172 Err(_) => break,
173 }
174 }
175}
176
177fn bounded_stderr_tail(lines: Vec<String>) -> Vec<String> {
178 let mut kept = Vec::new();
179 let mut kept_bytes = 0;
180 for line in lines.into_iter().rev() {
181 let separator = usize::from(!kept.is_empty());
182 if kept_bytes + separator >= STDERR_TAIL_LIMIT {
183 break;
184 }
185 let remaining = STDERR_TAIL_LIMIT - kept_bytes - separator;
186 let line = if line.len() <= remaining {
187 line
188 } else {
189 let mut start = line.len() - remaining;
190 while !line.is_char_boundary(start) {
191 start += 1;
192 }
193 line[start..].to_owned()
194 };
195 kept_bytes += separator + line.len();
196 kept.push(line);
197 }
198 kept.reverse();
199 kept
200}