ash_domain/error.rs
1//! The framework error type.
2
3/// The result type used throughout `ash-domain`.
4pub type Result<T> = std::result::Result<T, Error>;
5
6/// Everything that can go wrong resolving, authorizing, or executing an action.
7#[derive(Debug, thiserror::Error)]
8pub enum Error {
9 /// No resource is registered under this name in the domain.
10 #[error("unknown resource: {0}")]
11 UnknownResource(String),
12
13 /// The resource has no action with this name and the requested kind.
14 #[error("unknown action `{action}` on resource `{resource}`")]
15 UnknownAction {
16 /// The resource queried.
17 resource: String,
18 /// The action name that was not found.
19 action: String,
20 },
21
22 /// A record was expected but not found.
23 #[error("not found: {0}")]
24 NotFound(String),
25
26 /// A [`Policy`](crate::Policy) forbade the action.
27 #[error("forbidden: {0}")]
28 Forbidden(String),
29
30 /// A policy could not reach a decision — typically an external
31 /// [`PolicyClient`](crate::PolicyClient) backend failed or timed out
32 /// ([`Decision::Error`](crate::Decision::Error)). Distinct from
33 /// [`Forbidden`](Error::Forbidden): the action is aborted **fail-closed**,
34 /// but this signals an authorization *outage*, not a deliberate denial, so a
35 /// caller can retry or alert rather than treat it as "access denied".
36 #[error("policy error: {0}")]
37 PolicyError(String),
38
39 /// A tenant-scoped resource was accessed without a tenant set on the
40 /// [`Context`](crate::Context). Call
41 /// [`set_tenant`](crate::Context::set_tenant) before the action.
42 #[error("resource `{0}` is tenant-scoped but no tenant is set on the context")]
43 MissingTenant(String),
44
45 /// The data layer failed (I/O, database, etc.). `source`, when present, is
46 /// the underlying cause and participates in the [`std::error::Error`] chain
47 /// (`source()` returns it), so a consumer can downcast to their storage error
48 /// rather than parse a flattened string. Build it with
49 /// [`Error::data_layer`](Error::data_layer) /
50 /// [`Error::data_layer_from`](Error::data_layer_from).
51 #[error("data layer error: {message}")]
52 DataLayer {
53 /// Description of the failure.
54 message: String,
55 /// The underlying cause, if the layer supplied one.
56 #[source]
57 source: Option<Box<dyn std::error::Error + Send + Sync>>,
58 },
59
60 /// (De)serialization of a record failed.
61 #[error("serialization error: {0}")]
62 Serialization(String),
63
64 /// Invalid input or a violated domain invariant (also raised by extensions
65 /// such as the state-machine guard). `field` names the offending
66 /// attribute/path when the failure is attributable to one (e.g.
67 /// `"address.city"`), else `None`, so a caller can branch on *what* was
68 /// invalid instead of parsing the message. Build it with
69 /// [`Error::invalid`](Error::invalid) /
70 /// [`Error::invalid_field`](Error::invalid_field).
71 #[error("{message}")]
72 Invalid {
73 /// The attribute/path at fault, when the failure is attributable to one.
74 field: Option<String>,
75 /// Human-readable description of what was invalid.
76 message: String,
77 },
78
79 /// The operation is not supported by this backend — for a consumer data
80 /// layer to signal an operation it does not implement (e.g. a transaction or
81 /// batch method it chose not to support).
82 #[error("unsupported: {0}")]
83 Unsupported(String),
84
85 /// A lock could not be acquired for a contended record — raised by the
86 /// single-writer [`lock`](crate::extension::lock) extension when `ash-lock`
87 /// fails to grant the lease.
88 #[error("lock contention: {0}")]
89 Contention(String),
90
91 /// An **optimistic-concurrency conflict**: the row was modified by someone
92 /// else between the read and the write, so this update was refused rather
93 /// than allowed to overwrite a change it never saw.
94 ///
95 /// Raised only for a resource that declares a
96 /// [`version_attribute`](crate::Resource::version_attribute). It is a
97 /// legitimate control-flow outcome, not a fault — the correct response is to
98 /// re-read the row, re-apply the change to the new state, and retry. Distinct
99 /// from [`Contention`](Error::Contention), which means a *lock* could not be
100 /// taken (the write never attempted); a `Conflict` means the write was
101 /// attempted and lost the race.
102 #[error("update conflict on {resource}: {message}")]
103 Conflict {
104 /// The resource whose row was contended.
105 resource: String,
106 /// What was expected versus what was found.
107 message: String,
108 },
109
110 /// The domain is shutting down and is no longer accepting new work — raised
111 /// once [`Domain::begin_close`](crate::Domain::begin_close) /
112 /// [`close`](crate::Domain::close) has flipped the close gate. It is a
113 /// **lifecycle** signal, not a fault: the action never ran and nothing was
114 /// observed, so a caller draining its own work should stop, not retry. Like
115 /// [`Forbidden`](Error::Forbidden) it is a legitimate control-flow outcome —
116 /// distinct from [`DataLayer`](Error::DataLayer) / [`PolicyError`](Error::PolicyError),
117 /// which signal a genuine fault.
118 #[error("domain is closing: {0}")]
119 Closing(String),
120}
121
122impl Error {
123 /// An [`Invalid`](Error::Invalid) error with no attributable field.
124 pub fn invalid(message: impl Into<String>) -> Self {
125 Error::Invalid {
126 field: None,
127 message: message.into(),
128 }
129 }
130
131 /// An [`Invalid`](Error::Invalid) error attributed to `field` (an attribute
132 /// name or dotted path).
133 pub fn invalid_field(field: impl Into<String>, message: impl Into<String>) -> Self {
134 Error::Invalid {
135 field: Some(field.into()),
136 message: message.into(),
137 }
138 }
139
140 /// A [`DataLayer`](Error::DataLayer) error with no captured cause.
141 pub fn data_layer(message: impl Into<String>) -> Self {
142 Error::DataLayer {
143 message: message.into(),
144 source: None,
145 }
146 }
147
148 /// A [`DataLayer`](Error::DataLayer) error wrapping its underlying `source`,
149 /// which stays reachable through [`std::error::Error::source`].
150 pub fn data_layer_from(
151 message: impl Into<String>,
152 source: impl std::error::Error + Send + Sync + 'static,
153 ) -> Self {
154 Error::DataLayer {
155 message: message.into(),
156 source: Some(Box::new(source)),
157 }
158 }
159}
160
161#[cfg(feature = "lock")]
162impl From<ash_lock::Error> for Error {
163 fn from(e: ash_lock::Error) -> Self {
164 Error::Contention(e.to_string())
165 }
166}
167
168#[cfg(test)]
169mod tests {
170 use super::*;
171 use std::error::Error as _;
172
173 #[test]
174 fn data_layer_from_preserves_the_source_chain() {
175 let cause = std::io::Error::other("boom");
176 let err = Error::data_layer_from("read failed", cause);
177
178 // Display carries the message; the cause stays reachable via source().
179 assert_eq!(err.to_string(), "data layer error: read failed");
180 let source = err.source().expect("source should be present");
181 assert!(source.to_string().contains("boom"));
182 }
183
184 #[test]
185 fn data_layer_without_a_cause_has_no_source() {
186 let err = Error::data_layer("read failed");
187 assert!(err.source().is_none());
188 }
189
190 #[test]
191 fn invalid_field_is_matchable_and_keeps_the_message() {
192 let err = Error::invalid_field("address.city", "`address.city`: is required");
193 match err {
194 Error::Invalid { field, message } => {
195 assert_eq!(field.as_deref(), Some("address.city"));
196 assert!(message.contains("address.city"));
197 }
198 other => panic!("expected Invalid, got {other:?}"),
199 }
200 }
201}