1use crate::types::MixLane;
3use crate::{Error, Result};
4use std::fmt;
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8#[non_exhaustive]
9pub enum Operation {
10 Enumerate,
12 Start,
14 Normalize,
16 Flush,
18 Reopen,
20 Rollback,
22 Stop,
24 Join,
26 Link,
28}
29impl fmt::Display for Operation {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 f.write_str(match self {
32 Self::Enumerate => "enumerate",
33 Self::Start => "start",
34 Self::Normalize => "normalize",
35 Self::Flush => "flush",
36 Self::Reopen => "reopen",
37 Self::Rollback => "rollback",
38 Self::Stop => "stop",
39 Self::Join => "join",
40 Self::Link => "link",
41 })
42 }
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47#[non_exhaustive]
48pub enum NativeStatus {
49 HResult {
51 call: &'static str,
53 bits: u32,
55 },
56 OsStatus {
58 call: &'static str,
60 value: i32,
62 },
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67#[non_exhaustive]
68pub struct ErrorContext {
69 operation: Operation,
70 lane: Option<MixLane>,
71 native_status: Option<NativeStatus>,
72}
73impl ErrorContext {
74 pub fn new(operation: Operation) -> Self {
76 Self {
77 operation,
78 lane: None,
79 native_status: None,
80 }
81 }
82 pub fn with_lane(mut self, lane: MixLane) -> Self {
84 self.lane = Some(lane);
85 self
86 }
87 pub fn with_native_status(mut self, status: NativeStatus) -> Self {
89 self.native_status = Some(status);
90 self
91 }
92 pub fn operation(&self) -> Operation {
94 self.operation
95 }
96 pub fn lane(&self) -> Option<MixLane> {
98 self.lane
99 }
100 pub fn native_status(&self) -> Option<NativeStatus> {
102 self.native_status
103 }
104}
105impl fmt::Display for ErrorContext {
106 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107 write!(f, "during {}", self.operation)?;
108 if let Some(lane) = self.lane {
109 f.write_str(match lane {
110 MixLane::Microphone => " (microphone)",
111 MixLane::SystemAudio => " (system audio)",
112 })?;
113 }
114 match self.native_status {
115 Some(NativeStatus::HResult { bits, .. }) => write!(f, " (HRESULT 0x{bits:08X})"),
116 Some(NativeStatus::OsStatus { value, .. }) => write!(f, " (OSStatus {value})"),
117 None => Ok(()),
118 }
119 }
120}
121
122#[derive(Debug, Clone, PartialEq, Eq)]
124#[non_exhaustive]
125pub struct ErrorGroup {
126 primary: Box<Error>,
127 first_secondary: Box<Error>,
128 remaining_secondary: Vec<Error>,
129}
130impl ErrorGroup {
131 pub fn new(primary: Error, first_secondary: Error, remaining_secondary: Vec<Error>) -> Self {
133 Self {
134 primary: Box::new(primary),
135 first_secondary: Box::new(first_secondary),
136 remaining_secondary,
137 }
138 }
139 pub fn primary(&self) -> &Error {
141 &self.primary
142 }
143 pub fn secondary(&self) -> impl Iterator<Item = &Error> {
145 std::iter::once(self.first_secondary.as_ref()).chain(self.remaining_secondary.iter())
146 }
147}
148
149#[derive(Debug, Clone, PartialEq, Eq)]
151#[non_exhaustive]
152pub struct ShutdownReport {
153 primary: Option<Error>,
154 cleanup: Vec<Error>,
155}
156impl ShutdownReport {
157 pub fn new(primary: Option<Error>, cleanup: Vec<Error>) -> Self {
159 Self { primary, cleanup }
160 }
161 pub fn primary(&self) -> Option<&Error> {
163 self.primary.as_ref()
164 }
165 pub fn cleanup(&self) -> &[Error] {
167 &self.cleanup
168 }
169 pub fn result(&self) -> Result<()> {
172 let first = match self.primary.as_ref() {
173 Some(primary) => primary,
174 None => match self.cleanup.iter().find(|error| error.vad_code().is_none()) {
175 Some(error) => error,
176 None => return Ok(()),
177 },
178 };
179 let mut causes = std::iter::once(first.clone()).chain(
180 self.cleanup
181 .iter()
182 .filter(|error| !std::ptr::eq(*error, first))
183 .cloned(),
184 );
185 match (causes.next(), causes.next()) {
186 (None, _) => Ok(()),
187 (Some(error), None) => Err(error),
188 (Some(primary), Some(first)) => Err(Error::Multiple(ErrorGroup::new(
189 primary,
190 first,
191 causes.collect(),
192 ))),
193 }
194 }
195}
196
197#[cfg(test)]
198mod vad_tests {
199 use super::*;
200 use crate::VadErrorCode;
201
202 #[test]
203 fn vad_only_shutdown_succeeds_and_retains_the_typed_cause() {
204 let cause = Error::Vad {
205 code: VadErrorCode::Inference,
206 }
207 .with_context(ErrorContext::new(Operation::Flush));
208 let report = ShutdownReport::new(None, vec![cause.clone()]);
209 assert!(report.result().is_ok());
210 assert!(report.primary().is_none());
211 assert_eq!(report.cleanup(), &[cause]);
212 assert_eq!(
213 report.cleanup()[0].vad_code(),
214 Some(VadErrorCode::Inference)
215 );
216 assert!(report.cleanup()[0]
217 .to_string()
218 .contains("model inference or reset could not complete"));
219 assert!(ShutdownReport::new(None, Vec::new()).result().is_ok());
220 }
221
222 #[test]
223 fn capture_shutdown_message_excludes_isolated_vad_related_causes() {
224 let capture = Error::DeviceLost
225 .with_context(ErrorContext::new(Operation::Stop))
226 .with_context(ErrorContext::new(Operation::Stop));
227 for operation in [Operation::Normalize, Operation::Flush] {
228 let vad = Error::Vad {
229 code: VadErrorCode::Inference,
230 }
231 .with_context(ErrorContext::new(operation));
232 let report = ShutdownReport::new(Some(capture.clone()), vec![vad.clone()]);
233 let error = report
234 .result()
235 .expect_err("capture loss must still fail stop");
236 assert_eq!(error.to_string(), "device lost during stop during stop");
237 assert_eq!(error.root(), &Error::DeviceLost);
238 assert_eq!(report.cleanup(), std::slice::from_ref(&vad));
239 match error {
240 Error::Multiple(group) => {
241 assert_eq!(group.secondary().collect::<Vec<_>>(), [&vad]);
242 assert_eq!(
243 group.secondary().next().and_then(Error::vad_code),
244 Some(VadErrorCode::Inference)
245 );
246 }
247 _ => panic!("the rejecting error must retain typed related failures"),
248 }
249 }
250 }
251
252 #[test]
253 fn capture_shutdown_message_retains_non_vad_related_causes() {
254 let capture = Error::DeviceLost.with_context(ErrorContext::new(Operation::Stop));
255 let cleanup = Error::Backend("the backend could not finish its shutdown".into())
256 .with_context(ErrorContext::new(Operation::Join));
257 let vad = Error::Vad {
258 code: VadErrorCode::Inference,
259 }
260 .with_context(ErrorContext::new(Operation::Flush));
261 let report = ShutdownReport::new(Some(capture), vec![vad, cleanup]);
262 let error = report
263 .result()
264 .expect_err("capture loss must still fail stop");
265 assert_eq!(error.to_string(), "device lost during stop; related failure: backend error: the backend could not finish its shutdown during join");
266 assert!(matches!(error, Error::Multiple(group) if group.secondary().count() == 2));
267 }
268
269 #[test]
270 fn real_shutdown_failures_remain_primary_and_retain_vad_related_causes() {
271 let vad = Error::Vad {
272 code: VadErrorCode::Conversion,
273 };
274 let capture = Error::DeviceLost;
275 let report = ShutdownReport::new(Some(capture.clone()), vec![vad.clone()]);
276 let error = report
277 .result()
278 .expect_err("capture loss must still fail stop");
279 assert_eq!(error.root(), &capture);
280 assert!(
281 matches!(error, Error::Multiple(ref group) if group.secondary().next() == Some(&vad))
282 );
283
284 let cleanup = Error::Backend("the backend could not finish its shutdown".into());
286 let report = ShutdownReport::new(None, vec![vad.clone(), cleanup.clone()]);
287 let error = report
288 .result()
289 .expect_err("backend teardown failure must still fail stop");
290 assert_eq!(error.root(), &cleanup);
291 assert!(
292 matches!(error, Error::Multiple(ref group) if group.secondary().next() == Some(&vad))
293 );
294 }
295}