Skip to main content

tpt_gpu_runtime/
error.rs

1//! Error Handling Framework - Structured error types for the TPT runtime.
2use std::fmt;
3pub type TptrResult<T> = Result<T, TptrError>;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6pub enum ErrorCode {
7    AllocationFailure,
8    OutOfMemory,
9    InvalidAddress,
10    QueueFull,
11    SubmissionFailed,
12    SchedulingFailed,
13    InvalidKernel,
14    LaunchFailure,
15    ArgumentMismatch,
16    ConfigurationError,
17    DeviceNotFound,
18    DeviceLost,
19    UnsupportedFeature,
20    Timeout,
21    SynchronizationError,
22    InternalError,
23}
24
25impl ErrorCode {
26    pub fn code_string(&self) -> &'static str {
27        match self {
28            Self::AllocationFailure => "E0001",
29            Self::OutOfMemory => "E0002",
30            Self::InvalidAddress => "E0003",
31            Self::QueueFull => "E0010",
32            Self::SubmissionFailed => "E0011",
33            Self::SchedulingFailed => "E0012",
34            Self::InvalidKernel => "E0020",
35            Self::LaunchFailure => "E0021",
36            Self::ArgumentMismatch => "E0022",
37            Self::ConfigurationError => "E0023",
38            Self::DeviceNotFound => "E0030",
39            Self::DeviceLost => "E0031",
40            Self::UnsupportedFeature => "E0032",
41            Self::Timeout => "E0040",
42            Self::SynchronizationError => "E0041",
43            Self::InternalError => "E0099",
44        }
45    }
46    pub fn category(&self) -> &'static str {
47        match self {
48            Self::AllocationFailure => "ALLOCATION_FAILURE",
49            Self::OutOfMemory => "OUT_OF_MEMORY",
50            Self::InvalidAddress => "INVALID_ADDRESS",
51            Self::QueueFull => "QUEUE_FULL",
52            Self::SubmissionFailed => "SUBMISSION_FAILED",
53            Self::SchedulingFailed => "SCHEDULING_FAILED",
54            Self::InvalidKernel => "INVALID_KERNEL",
55            Self::LaunchFailure => "LAUNCH_FAILURE",
56            Self::ArgumentMismatch => "ARGUMENT_MISMATCH",
57            Self::ConfigurationError => "CONFIGURATION_ERROR",
58            Self::DeviceNotFound => "DEVICE_NOT_FOUND",
59            Self::DeviceLost => "DEVICE_LOST",
60            Self::UnsupportedFeature => "UNSUPPORTED_FEATURE",
61            Self::Timeout => "TIMEOUT",
62            Self::SynchronizationError => "SYNCHRONIZATION_ERROR",
63            Self::InternalError => "INTERNAL_ERROR",
64        }
65    }
66}
67
68impl fmt::Display for ErrorCode {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        write!(f, "{} ({})", self.category(), self.code_string())
71    }
72}
73
74#[derive(Debug, Clone, Default)]
75pub struct ErrorContext {
76    pub metadata: Vec<(String, String)>,
77}
78
79impl ErrorContext {
80    pub fn new() -> Self {
81        Self::default()
82    }
83    pub fn with<K: Into<String>, V: Into<String>>(mut self, key: K, value: V) -> Self {
84        self.metadata.push((key.into(), value.into()));
85        self
86    }
87    pub fn add<K: Into<String>, V: Into<String>>(&mut self, key: K, value: V) {
88        self.metadata.push((key.into(), value.into()));
89    }
90}
91
92impl fmt::Display for ErrorContext {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        if self.metadata.is_empty() {
95            return write!(f, "");
96        }
97        let pairs: Vec<String> = self
98            .metadata
99            .iter()
100            .map(|(k, v)| format!("{} = {}", k, v))
101            .collect();
102        write!(f, "[{}]", pairs.join(", "))
103    }
104}
105
106#[derive(Debug, Clone)]
107pub struct ErrorSource {
108    pub file: &'static str,
109    pub line: u32,
110}
111
112impl fmt::Display for ErrorSource {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        write!(f, "{}:{}", self.file, self.line)
115    }
116}
117
118#[derive(Debug, Clone)]
119pub struct TptrError {
120    pub code: ErrorCode,
121    pub message: String,
122    pub source: ErrorSource,
123    pub context: ErrorContext,
124    pub cause: Option<String>,
125}
126
127impl TptrError {
128    #[track_caller]
129    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
130        let caller = std::panic::Location::caller();
131        Self {
132            code,
133            message: message.into(),
134            source: ErrorSource {
135                file: caller.file(),
136                line: caller.line(),
137            },
138            context: ErrorContext::new(),
139            cause: None,
140        }
141    }
142    pub fn with_cause(mut self, cause: impl fmt::Display) -> Self {
143        self.cause = Some(cause.to_string());
144        self
145    }
146    pub fn with_context(mut self, context: ErrorContext) -> Self {
147        self.context = context;
148        self
149    }
150    pub fn with<K: Into<String>, V: Into<String>>(mut self, key: K, value: V) -> Self {
151        self.context.add(key, value);
152        self
153    }
154}
155
156impl fmt::Display for TptrError {
157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158        write!(f, "[{}] {} — at {}", self.code, self.message, self.source)?;
159        if !self.context.metadata.is_empty() {
160            write!(f, " {}", self.context)?;
161        }
162        if let Some(ref cause) = self.cause {
163            write!(f, "\n  Caused by: {}", cause)?;
164        }
165        Ok(())
166    }
167}
168
169impl std::error::Error for TptrError {
170    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
171        None
172    }
173}
174
175#[macro_export]
176macro_rules! tptr_err {
177    ($code:expr, $msg:expr) => { $crate::error::TptrError::new($code, $msg) };
178    ($code:expr, $fmt:literal, $($arg:expr),+ $(,)?) => { $crate::error::TptrError::new($code, format!($fmt, $($arg),+)) };
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184    #[test]
185    fn test_error_code_display() {
186        let c = ErrorCode::AllocationFailure;
187        assert_eq!(c.code_string(), "E0001");
188        assert_eq!(c.category(), "ALLOCATION_FAILURE");
189    }
190    #[test]
191    fn test_error_creation() {
192        let e = TptrError::new(ErrorCode::OutOfMemory, "test");
193        assert_eq!(e.code, ErrorCode::OutOfMemory);
194    }
195    #[test]
196    fn test_with_context() {
197        let e = TptrError::new(ErrorCode::AllocationFailure, "fail")
198            .with("dev", "0")
199            .with("bytes", "4096");
200        assert_eq!(e.context.metadata.len(), 2);
201    }
202    #[test]
203    fn test_with_cause() {
204        let inner = TptrError::new(ErrorCode::DeviceNotFound, "no GPU");
205        let e = TptrError::new(ErrorCode::InternalError, "wrap").with_cause(&inner);
206        assert!(e.cause.is_some());
207    }
208    #[test]
209    fn test_tptr_err_macro() {
210        let e = tptr_err!(ErrorCode::Timeout, "timed out after {}ms", 5000u64);
211        assert_eq!(e.code, ErrorCode::Timeout);
212    }
213}