Skip to main content

alpha2_engine/
error_code.rs

1//! The protocol code of an engine failure, decided by the error's variant.
2//!
3//! The native host and the wasm binding share these codes. The code comes from the error variant,
4//! never from message text, which can carry user-chosen IDs and paths. Errors of unknown types
5//! are coded by the binding, defaulting to `ALPHA2_ERROR`.
6
7use std::error::Error;
8
9use alpha2_eval::{EvalError, PlanError};
10use alpha2_media::{DecodeError, EncodeError, GpuFault};
11use alpha2_render::{ColorError, GraphError, LutParseError, RenderError};
12use alpha2_text::TextRasterError;
13
14use crate::{EngineError, TextError};
15
16/// A failure's protocol code.
17#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
18pub enum ErrorCode {
19    /// The project, a range, a rate, a size, or another argument is invalid.
20    InvalidInput,
21    /// An effect resource or font the render needs is absent.
22    MissingInput,
23    /// A composition graph has an unconnected output or input.
24    IncompleteComposition,
25    /// A runtime effect's definition, parameters, or shader failed.
26    EffectError,
27    /// Encoding or muxing failed.
28    EncodeError,
29    /// The GPU device was lost, or no longer runs submitted work.
30    GpuDeviceLost,
31    /// The device was lost to this work: a submission ran for most of the OS GPU watchdog, or the
32    /// platform reported a reset for a long command. Retrying will hang the GPU again.
33    GpuDeviceHung,
34    /// GPU work did not complete within the wait timeout.
35    GpuTimeout,
36    /// A defect in the engine failed the request; the engine stays usable.
37    Internal,
38    /// A failure nothing classified.
39    Alpha2Error,
40}
41
42impl ErrorCode {
43    /// Every code, for tables and tests.
44    pub const ALL: [Self; 10] = [
45        Self::InvalidInput,
46        Self::MissingInput,
47        Self::IncompleteComposition,
48        Self::EffectError,
49        Self::EncodeError,
50        Self::GpuDeviceLost,
51        Self::GpuDeviceHung,
52        Self::GpuTimeout,
53        Self::Internal,
54        Self::Alpha2Error,
55    ];
56
57    /// The code as the protocol spells it.
58    #[must_use]
59    pub const fn as_str(self) -> &'static str {
60        match self {
61            Self::InvalidInput => "INVALID_INPUT",
62            Self::MissingInput => "MISSING_INPUT",
63            Self::IncompleteComposition => "INCOMPLETE_COMPOSITION",
64            Self::EffectError => "EFFECT_ERROR",
65            Self::EncodeError => "ENCODE_ERROR",
66            Self::GpuDeviceLost => "GPU_DEVICE_LOST",
67            Self::GpuDeviceHung => "GPU_DEVICE_HUNG",
68            Self::GpuTimeout => "GPU_TIMEOUT",
69            Self::Internal => "INTERNAL",
70            Self::Alpha2Error => "ALPHA2_ERROR",
71        }
72    }
73
74    /// The code of the first error in `error`'s source chain with a known type.
75    #[must_use]
76    pub fn of(error: &(dyn Error + 'static)) -> Option<Self> {
77        let mut cause = Some(error);
78        while let Some(error) = cause {
79            if let Some(code) = Self::of_one(error) {
80                return Some(code);
81            }
82            cause = error.source();
83        }
84        None
85    }
86
87    fn of_one(error: &(dyn Error + 'static)) -> Option<Self> {
88        if let Some(error) = error.downcast_ref::<EngineError>() {
89            return Some(error.code());
90        }
91        if let Some(error) = error.downcast_ref::<EvalError>() {
92            return Some(eval_code(error));
93        }
94        if let Some(error) = error.downcast_ref::<RenderError>() {
95            return Some(render_code(*error));
96        }
97        if let Some(error) = error.downcast_ref::<TextError>() {
98            return Some(text_error_code(error));
99        }
100        if let Some(error) = error.downcast_ref::<TextRasterError>() {
101            return Some(text_code(error));
102        }
103        if let Some(error) = error.downcast_ref::<GraphError>() {
104            return Some(match error {
105                GraphError::Render(error) => render_code(*error),
106                _ => Self::InvalidInput,
107            });
108        }
109        // GPU call faults are read first by the binding (`gpu_fault_of`).
110        if let Some(error) = error.downcast_ref::<DecodeError>() {
111            return Some(match error {
112                DecodeError::OutOfRange => Self::InvalidInput,
113                _ => Self::Alpha2Error,
114            });
115        }
116        if error.is::<EncodeError>() {
117            return Some(Self::EncodeError);
118        }
119        let invalid = error.is::<alpha2_model::ModelError>()
120            || error.is::<alpha2_model::ProjectLoadError>()
121            || error.is::<alpha2_time::TimeRangeError>()
122            || error.is::<alpha2_time::FrameRateError>()
123            || error.is::<alpha2_media::RateControlError>()
124            || error.is::<ColorError>()
125            || error.is::<LutParseError>();
126        invalid.then_some(Self::InvalidInput)
127    }
128}
129
130/// The GPU error class of the first [`RenderError::Gpu`] in `error`'s source chain. Out of memory
131/// and validation have no protocol code; failure reports classify them with this.
132#[must_use]
133pub fn gpu_error_of(error: &(dyn Error + 'static)) -> Option<alpha2_gpu::GpuErrorKind> {
134    let render = |error: &RenderError| match error {
135        RenderError::Gpu { kind } => Some(*kind),
136        RenderError::FrameExceedsGpuMemory { .. } => Some(alpha2_gpu::GpuErrorKind::OutOfMemory),
137        _ => None,
138    };
139    let mut cause = Some(error);
140    while let Some(error) = cause {
141        let kind = if let Some(error) = error.downcast_ref::<RenderError>() {
142            render(error)
143        } else if let Some(EngineError::Render(error)) = error.downcast_ref::<EngineError>() {
144            render(error)
145        } else if let Some(GraphError::Render(error)) = error.downcast_ref::<GraphError>() {
146            render(error)
147        } else {
148            None
149        };
150        if kind.is_some() {
151            return kind;
152        }
153        cause = error.source();
154    }
155    None
156}
157
158/// The device fault reported for the first failed GPU call in `error`'s source chain (renderer
159/// synchronization, decoder or encoder). Failure reports classify memory faults with this.
160#[must_use]
161pub fn gpu_fault_of(error: &(dyn Error + 'static)) -> Option<GpuFault> {
162    let render = |error: &RenderError| match error {
163        RenderError::ExternalTextureSync(fault) => *fault,
164        _ => None,
165    };
166    let mut cause = Some(error);
167    while let Some(error) = cause {
168        let fault = if let Some(error) = error.downcast_ref::<RenderError>() {
169            render(error)
170        } else if let Some(EngineError::Render(error)) = error.downcast_ref::<EngineError>() {
171            render(error)
172        } else if let Some(GraphError::Render(error)) = error.downcast_ref::<GraphError>() {
173            render(error)
174        } else if let Some(EncodeError::Gpu { fault, .. }) = error.downcast_ref::<EncodeError>() {
175            Some(*fault)
176        } else if let Some(DecodeError::Gpu { fault, .. }) = error.downcast_ref::<DecodeError>() {
177            Some(*fault)
178        } else {
179            None
180        };
181        if fault.is_some() {
182            return fault;
183        }
184        cause = error.source();
185    }
186    None
187}
188
189impl EngineError {
190    /// This failure's protocol code.
191    #[must_use]
192    pub fn code(&self) -> ErrorCode {
193        match self {
194            Self::Evaluate(error) => eval_code(error),
195            Self::Render(error) => render_code(*error),
196            Self::Text(error) => text_error_code(error),
197            Self::InvalidQualityProfile
198            | Self::OutOfRange
199            | Self::EmptyExportRange
200            | Self::ExportTooLarge { .. }
201            | Self::InvalidAudioConfiguration
202            | Self::InvalidNormalizationGain
203            | Self::OddExportDimensions { .. } => ErrorCode::InvalidInput,
204            // The caller's mistake, not the project's.
205            Self::ExportProjectChanged => ErrorCode::Alpha2Error,
206            Self::UnregisteredEffect { .. } => ErrorCode::EffectError,
207        }
208    }
209}
210
211fn text_error_code(error: &TextError) -> ErrorCode {
212    match error {
213        TextError::Raster(error) => text_code(error),
214        TextError::Render(error) => render_code(*error),
215    }
216}
217
218fn text_code(error: &TextRasterError) -> ErrorCode {
219    match error {
220        TextRasterError::NoFonts => ErrorCode::MissingInput,
221        _ => ErrorCode::InvalidInput,
222    }
223}
224
225fn eval_code(error: &EvalError) -> ErrorCode {
226    match error {
227        EvalError::IncompleteComposition { reason, .. } => match reason {
228            PlanError::NoOutput
229            | PlanError::MissingInput { .. }
230            | PlanError::UnboundGroupInput { .. }
231            | PlanError::ClipWithoutClip { .. } => ErrorCode::IncompleteComposition,
232            PlanError::NestedTooDeep { .. } | PlanError::TooLarge => ErrorCode::InvalidInput,
233        },
234        EvalError::InvalidProject(_) | EvalError::UnmappableClip { .. } => ErrorCode::InvalidInput,
235        // An index built for another project is the caller's mistake.
236        _ => ErrorCode::Alpha2Error,
237    }
238}
239
240fn render_code(error: RenderError) -> ErrorCode {
241    match error {
242        RenderError::ZeroDimension
243        | RenderError::DimensionTooLarge
244        | RenderError::InvalidColor
245        | RenderError::InvalidVisual
246        | RenderError::InvalidImageData
247        | RenderError::InvalidGraph
248        | RenderError::UnsupportedHdr
249        | RenderError::UnsupportedOutputColor(_) => ErrorCode::InvalidInput,
250        RenderError::InvalidEffectParameter
251        | RenderError::UnknownEffect
252        | RenderError::InvalidEffectParams
253        | RenderError::InvalidEffectResource
254        | RenderError::EffectResourceKindMismatch
255        | RenderError::MissingEffectInput => ErrorCode::EffectError,
256        RenderError::MissingEffectResource => ErrorCode::MissingInput,
257        RenderError::GpuTimeout | RenderError::ExternalTextureSync(Some(GpuFault::Timeout)) => {
258            ErrorCode::GpuTimeout
259        }
260        RenderError::GpuWorkDropped
261        | RenderError::GpuDeviceLost
262        | RenderError::ExternalTextureSync(Some(GpuFault::DeviceLost)) => ErrorCode::GpuDeviceLost,
263        RenderError::GpuDeviceHung { .. }
264        | RenderError::ExternalTextureSync(Some(GpuFault::DeviceHung)) => ErrorCode::GpuDeviceHung,
265        RenderError::UniformArenaOverrun => ErrorCode::Internal,
266        // A GPU rejection is the engine's failure, not the caller's input.
267        _ => ErrorCode::Alpha2Error,
268    }
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274
275    #[test]
276    fn a_code_is_the_variants_whatever_its_message_says() {
277        let odd = EngineError::OddExportDimensions {
278            width: 65,
279            height: 49,
280            suggested: (64, 48),
281        };
282        assert_eq!(odd.code(), ErrorCode::InvalidInput);
283        assert_eq!(ErrorCode::of(&odd), Some(ErrorCode::InvalidInput));
284        let too_large = EngineError::ExportTooLarge {
285            frames: 2,
286            maximum: 1,
287        };
288        assert_eq!(too_large.code(), ErrorCode::InvalidInput);
289        let no_fonts = EngineError::Text(TextError::Raster(TextRasterError::NoFonts));
290        assert_eq!(no_fonts.code(), ErrorCode::MissingInput);
291        assert_eq!(
292            EngineError::Render(RenderError::GpuWorkDropped).code(),
293            ErrorCode::GpuDeviceLost
294        );
295        assert_eq!(
296            EngineError::Render(RenderError::GpuDeviceLost).code(),
297            ErrorCode::GpuDeviceLost
298        );
299        // A rejected frame is not a lost device, whatever the device said about it.
300        for kind in [
301            alpha2_gpu::GpuErrorKind::OutOfMemory,
302            alpha2_gpu::GpuErrorKind::Validation,
303            alpha2_gpu::GpuErrorKind::Internal,
304        ] {
305            let rejected = EngineError::Render(RenderError::Gpu { kind });
306            assert_eq!(rejected.code(), ErrorCode::Alpha2Error);
307            assert_eq!(gpu_error_of(&rejected), Some(kind));
308            assert_eq!(
309                gpu_error_of(&GraphError::Render(RenderError::Gpu { kind })),
310                Some(kind)
311            );
312        }
313        assert_eq!(gpu_error_of(&RenderError::GpuWorkDropped), None);
314        let oversized = RenderError::FrameExceedsGpuMemory {
315            needed: 2,
316            budget: 1,
317        };
318        assert_eq!(
319            gpu_error_of(&oversized),
320            Some(alpha2_gpu::GpuErrorKind::OutOfMemory)
321        );
322        assert_eq!(ErrorCode::of(&oversized), Some(ErrorCode::Alpha2Error));
323        assert_eq!(
324            ErrorCode::of(&RenderError::GpuTimeout),
325            Some(ErrorCode::GpuTimeout)
326        );
327        assert_eq!(
328            ErrorCode::of(&RenderError::UnsupportedHdr),
329            Some(ErrorCode::InvalidInput)
330        );
331        assert_eq!(
332            ErrorCode::of(&RenderError::UniformArenaOverrun),
333            Some(ErrorCode::Internal)
334        );
335        let wide = alpha2_media::ColorMetadata {
336            primaries: alpha2_media::ColorPrimaries::Bt2020,
337            ..alpha2_media::ColorMetadata::EXPORT
338        };
339        assert_eq!(
340            ErrorCode::of(&RenderError::UnsupportedOutputColor(wide)),
341            Some(ErrorCode::InvalidInput)
342        );
343        let model = alpha2_model::ModelError::UnsupportedSchemaVersion { found: 0 };
344        assert_eq!(ErrorCode::of(&model), Some(ErrorCode::InvalidInput));
345        assert_eq!(ErrorCode::of(&std::io::Error::other("device lost")), None);
346    }
347
348    #[test]
349    fn media_errors_take_the_code_their_variant_names_whatever_their_words() {
350        let words = "missing shader: GPU device lost, invalid encode".to_owned();
351        for (error, code) in [
352            (
353                &DecodeError::Adapter(words.clone()) as &(dyn Error + 'static),
354                ErrorCode::Alpha2Error,
355            ),
356            (
357                &DecodeError::Unsupported(words.clone()),
358                ErrorCode::Alpha2Error,
359            ),
360            (&DecodeError::Cancelled, ErrorCode::Alpha2Error),
361            (&DecodeError::OutOfRange, ErrorCode::InvalidInput),
362            (&EncodeError::Adapter(words.clone()), ErrorCode::EncodeError),
363            (&EncodeError::Cancelled, ErrorCode::EncodeError),
364            (&EncodeError::InvalidTimestamp, ErrorCode::EncodeError),
365        ] {
366            assert_eq!(ErrorCode::of(error), Some(code), "{error}");
367        }
368    }
369
370    #[test]
371    fn every_code_has_its_own_name() {
372        let mut names: Vec<_> = ErrorCode::ALL.iter().map(|code| code.as_str()).collect();
373        names.sort_unstable();
374        names.dedup();
375        assert_eq!(names.len(), ErrorCode::ALL.len());
376    }
377}