Skip to main content

oa/core/
error.rs

1use std::{error::Error as StdError, fmt};
2
3/// Stable category for an OA failure.
4#[non_exhaustive]
5#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6pub enum ErrorKind {
7	/// A caller supplied an invalid value, shape, range, or combination.
8	InvalidArgument,
9	/// A value or operation has not reached the required completion state.
10	NotReady,
11	/// The selected execution backend could not be loaded.
12	BackendUnavailable,
13	/// An execution-backend operation failed.
14	BackendFailure,
15	/// The execution backend is older than OA's minimum supported version.
16	UnsupportedBackendVersion,
17	/// No device satisfies the requested execution contract.
18	NoSuitableDevice,
19	/// A required device or runtime capability is unavailable.
20	MissingCapability,
21	/// A finite runtime identity, counter, or address space was exhausted.
22	ResourceExhausted,
23	/// An operation was requested in an incompatible lifecycle state.
24	FailedPrecondition,
25	/// A referenced index or range lies outside its owning object.
26	OutOfRange,
27	/// A requested object or provenance record does not exist.
28	NotFound,
29	/// An object with the same identity already exists.
30	AlreadyExists,
31	/// Optimistic concurrency rejected work against a stale revision.
32	Aborted,
33	/// Application callback policy failed at an explicit lifecycle hook.
34	CallbackFailure,
35	/// A persisted OA model/checkpoint failed its wire-format integrity contract.
36	CheckpointCorrupt,
37	/// External encoded data is truncated, malformed, or internally inconsistent.
38	DataLoss,
39	/// OA detected an invalid invariant in its own state.
40	Internal,
41	/// A host filesystem or stream operation failed.
42	Io,
43	/// The operation was cancelled before producing a result.
44	Cancelled,
45	/// The caller or peer lacks permission for the requested action.
46	PermissionDenied,
47	/// The requested operation is not implemented by this endpoint.
48	Unimplemented,
49	/// The endpoint or transport is currently unavailable.
50	Unavailable,
51	/// Peer authentication failed.
52	Unauthenticated,
53	/// A serialized or exchanged shape contract does not match its consumer.
54	ShapeMismatch,
55	/// A serialized or exchanged dtype contract does not match its consumer.
56	DtypeMismatch,
57}
58
59/// Error returned by fallible OA operations.
60///
61/// Backend and dependency errors are retained as sources without exposing their
62/// concrete types through OA's public API.
63pub struct Error {
64	inner: Box<ErrorData>,
65}
66
67struct ErrorData {
68	kind: ErrorKind,
69	message: String,
70	source: Option<Box<dyn StdError + Send + Sync + 'static>>,
71}
72
73impl Error {
74	fn new(data: ErrorData) -> Self {
75		Self {
76			inner: Box::new(data),
77		}
78	}
79
80	/// Return the stable category for this failure.
81	pub const fn kind(&self) -> ErrorKind {
82		self.inner.kind
83	}
84
85	/// Return the contextual failure message.
86	pub fn message(&self) -> &str {
87		&self.inner.message
88	}
89
90	/// Construct an application callback failure without losing its message.
91	///
92	/// Callback implementations may use this when their failure does not already
93	/// originate from another OA operation.
94	pub fn callback(message: impl Into<String>) -> Self {
95		Self::new(ErrorData {
96			kind: ErrorKind::CallbackFailure,
97			message: message.into(),
98			source: None,
99		})
100	}
101
102	pub(crate) fn backend_unavailable<E>(backend: &'static str, source: E) -> Self
103	where
104		E: StdError + Send + Sync + 'static,
105	{
106		Self::new(ErrorData {
107			kind: ErrorKind::BackendUnavailable,
108			message: format!("{backend} backend is unavailable"),
109			source: Some(Box::new(source)),
110		})
111	}
112
113	pub fn invalid_argument(message: impl Into<String>) -> Self {
114		Self::new(ErrorData {
115			kind: ErrorKind::InvalidArgument,
116			message: message.into(),
117			source: None,
118		})
119	}
120
121	pub fn not_ready(message: impl Into<String>) -> Self {
122		Self::new(ErrorData {
123			kind: ErrorKind::NotReady,
124			message: message.into(),
125			source: None,
126		})
127	}
128
129	pub(crate) fn backend_failure<E>(
130		backend: &'static str,
131		operation: &'static str,
132		source: E,
133	) -> Self
134	where
135		E: StdError + Send + Sync + 'static,
136	{
137		Self::new(ErrorData {
138			kind: ErrorKind::BackendFailure,
139			message: format!("{backend} {operation} failed"),
140			source: Some(Box::new(source)),
141		})
142	}
143
144	/// Converts a generated dispatch outcome into a backend failure: a call
145	/// error is propagated directly, and a non-success Vulkan status carries
146	/// its result code.
147	pub(crate) fn backend_dispatch_failure(
148		backend: &'static str,
149		operation: &'static str,
150		result: std::result::Result<vk::Result, vk::CallError>,
151	) -> Self {
152		match result {
153			Err(source) => Self::backend_failure(backend, operation, source),
154			Ok(code) => Self::backend_failure(
155				backend,
156				operation,
157				std::io::Error::other(format!("{code:?}")),
158			),
159		}
160	}
161
162	pub(crate) fn unsupported_backend_version(
163		backend: &'static str,
164		required: &'static str,
165		available: String,
166	) -> Self {
167		Self::new(ErrorData {
168			kind: ErrorKind::UnsupportedBackendVersion,
169			message: format!(
170				"{backend} {required} or newer is required; the loader provides {available}"
171			),
172			source: None,
173		})
174	}
175
176	pub(crate) fn no_suitable_device(message: impl Into<String>) -> Self {
177		Self::new(ErrorData {
178			kind: ErrorKind::NoSuitableDevice,
179			message: message.into(),
180			source: None,
181		})
182	}
183
184	pub(crate) fn missing_capability(message: impl Into<String>) -> Self {
185		Self::new(ErrorData {
186			kind: ErrorKind::MissingCapability,
187			message: message.into(),
188			source: None,
189		})
190	}
191
192	pub fn resource_exhausted(message: impl Into<String>) -> Self {
193		Self::new(ErrorData {
194			kind: ErrorKind::ResourceExhausted,
195			message: message.into(),
196			source: None,
197		})
198	}
199
200	pub fn failed_precondition(message: impl Into<String>) -> Self {
201		Self::new(ErrorData {
202			kind: ErrorKind::FailedPrecondition,
203			message: message.into(),
204			source: None,
205		})
206	}
207
208	pub fn out_of_range(message: impl Into<String>) -> Self {
209		Self::new(ErrorData {
210			kind: ErrorKind::OutOfRange,
211			message: message.into(),
212			source: None,
213		})
214	}
215
216	pub fn not_found(message: impl Into<String>) -> Self {
217		Self::new(ErrorData {
218			kind: ErrorKind::NotFound,
219			message: message.into(),
220			source: None,
221		})
222	}
223
224	pub fn already_exists(message: impl Into<String>) -> Self {
225		Self::new(ErrorData {
226			kind: ErrorKind::AlreadyExists,
227			message: message.into(),
228			source: None,
229		})
230	}
231
232	pub fn internal(message: impl Into<String>) -> Self {
233		Self::new(ErrorData {
234			kind: ErrorKind::Internal,
235			message: message.into(),
236			source: None,
237		})
238	}
239
240	pub fn checkpoint_corrupt(message: impl Into<String>) -> Self {
241		Self::new(ErrorData {
242			kind: ErrorKind::CheckpointCorrupt,
243			message: format!("corrupt .oam: {}", message.into()),
244			source: None,
245		})
246	}
247
248	pub fn data_loss(message: impl Into<String>) -> Self {
249		Self::new(ErrorData {
250			kind: ErrorKind::DataLoss,
251			message: message.into(),
252			source: None,
253		})
254	}
255
256	pub fn io(operation: &'static str, source: std::io::Error) -> Self {
257		Self::new(ErrorData {
258			kind: ErrorKind::Io,
259			message: format!("{operation} failed"),
260			source: Some(Box::new(source)),
261		})
262	}
263
264	pub fn aborted(message: impl Into<String>) -> Self {
265		Self::new(ErrorData {
266			kind: ErrorKind::Aborted,
267			message: message.into(),
268			source: None,
269		})
270	}
271
272	pub fn cancelled(message: impl Into<String>) -> Self {
273		Self::new(ErrorData {
274			kind: ErrorKind::Cancelled,
275			message: message.into(),
276			source: None,
277		})
278	}
279
280	pub fn permission_denied(message: impl Into<String>) -> Self {
281		Self::new(ErrorData {
282			kind: ErrorKind::PermissionDenied,
283			message: message.into(),
284			source: None,
285		})
286	}
287
288	pub fn unimplemented(message: impl Into<String>) -> Self {
289		Self::new(ErrorData {
290			kind: ErrorKind::Unimplemented,
291			message: message.into(),
292			source: None,
293		})
294	}
295
296	pub fn unavailable(message: impl Into<String>) -> Self {
297		Self::new(ErrorData {
298			kind: ErrorKind::Unavailable,
299			message: message.into(),
300			source: None,
301		})
302	}
303
304	pub fn unauthenticated(message: impl Into<String>) -> Self {
305		Self::new(ErrorData {
306			kind: ErrorKind::Unauthenticated,
307			message: message.into(),
308			source: None,
309		})
310	}
311
312	pub fn shape_mismatch(message: impl Into<String>) -> Self {
313		Self::new(ErrorData {
314			kind: ErrorKind::ShapeMismatch,
315			message: message.into(),
316			source: None,
317		})
318	}
319
320	pub fn dtype_mismatch(message: impl Into<String>) -> Self {
321		Self::new(ErrorData {
322			kind: ErrorKind::DtypeMismatch,
323			message: message.into(),
324			source: None,
325		})
326	}
327
328	pub(crate) fn with_kind(kind: ErrorKind, message: impl Into<String>) -> Self {
329		Self::new(ErrorData {
330			kind,
331			message: message.into(),
332			source: None,
333		})
334	}
335}
336
337impl fmt::Debug for Error {
338	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
339		formatter
340			.debug_struct("Error")
341			.field("kind", &self.inner.kind)
342			.field("message", &self.inner.message)
343			.field("source", &self.inner.source)
344			.finish()
345	}
346}
347
348impl fmt::Display for Error {
349	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
350		formatter.write_str(&self.inner.message)
351	}
352}
353
354impl StdError for Error {
355	fn source(&self) -> Option<&(dyn StdError + 'static)> {
356		self
357			.inner
358			.source
359			.as_deref()
360			.map(|source| source as &(dyn StdError + 'static))
361	}
362}
363
364/// Result returned by fallible OA operations.
365pub type Result<T> = std::result::Result<T, Error>;
366
367impl From<vk::CallError> for Error {
368	fn from(source: vk::CallError) -> Self {
369		Self::backend_failure("Vulkan", "command dispatch", source)
370	}
371}
372
373impl From<vk::ConstructionError> for Error {
374	fn from(source: vk::ConstructionError) -> Self {
375		Self::backend_failure("Vulkan", "create-info construction", source)
376	}
377}
378
379impl From<vk::mem::AllocError> for Error {
380	fn from(source: vk::mem::AllocError) -> Self {
381		Self::backend_failure("Vulkan", "memory allocation", source)
382	}
383}