1use std::fmt;
6
7use serde_json::Value;
8
9use crate::operation::ErrorInfo;
10use crate::permissions::{PermissionInfo, ResourceInfo};
11
12pub type Result<T, E = Error> = std::result::Result<T, E>;
13
14pub const MAX_SOURCE_DEPTH: usize = 64;
16
17pub struct Error {
20 inner: Box<dyn std::error::Error + Send + Sync + 'static>,
21}
22
23impl Error {
24 pub fn new(error: impl std::error::Error + Send + Sync + 'static) -> Self {
25 Self {
26 inner: Box::new(error),
27 }
28 }
29
30 pub fn internal(message: impl Into<String>) -> Self {
32 Self::new(Internal(message.into()))
33 }
34
35 pub fn get_ref(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
36 &*self.inner
37 }
38
39 pub fn downcast_ref<E: std::error::Error + 'static>(&self) -> Option<&E> {
40 self.inner.downcast_ref::<E>()
41 }
42
43 pub fn chain(&self) -> String {
46 let mut text = self.inner.to_string();
47 let mut source = self.inner.source();
48 for _ in 0..MAX_SOURCE_DEPTH {
49 let Some(next) = source else { break };
50 text.push_str(": ");
51 text.push_str(&next.to_string());
52 source = next.source();
53 }
54 text
55 }
56}
57
58impl<E: std::error::Error + Send + Sync + 'static> From<E> for Error {
59 fn from(error: E) -> Self {
60 Self::new(error)
61 }
62}
63
64impl fmt::Debug for Error {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 fmt::Debug::fmt(&self.inner, f)
67 }
68}
69
70impl fmt::Display for Error {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 fmt::Display::fmt(&self.inner, f)
73 }
74}
75
76#[derive(Debug)]
77struct Internal(String);
78
79impl fmt::Display for Internal {
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 f.write_str(&self.0)
82 }
83}
84
85impl std::error::Error for Internal {}
86
87pub trait ModelledError: std::error::Error + Send + Sync + 'static {
89 fn info(&self) -> &'static ErrorInfo;
90 fn shape_id(&self) -> &'static str {
92 self.info().name
93 }
94 fn to_json(&self) -> Value;
96
97 fn write_json_to(&self, out: &mut dyn std::io::Write) -> serde_json::Result<()> {
101 serde_json::to_writer(out, &self.to_json())
102 }
103
104 fn write_json(&self, out: &mut Vec<u8>) -> serde_json::Result<Vec<(&'static str, String)>> {
109 let info = self.info();
110 crate::split::write_typed(&self.to_json(), info.members, Some(info.name), out)
111 }
112}
113
114#[doc(hidden)]
117pub fn write_error<E: ModelledError + serde::Serialize>(
118 error: &E,
119 out: &mut Vec<u8>,
120) -> serde_json::Result<Vec<(&'static str, String)>> {
121 let info = error.info();
122 crate::split::write_typed(error, info.members, Some(info.name), out)
123}
124
125#[derive(Debug, Clone, PartialEq, Eq)]
134#[non_exhaustive]
135pub enum FrameworkError {
136 Unauthenticated,
138 Forbidden,
140 Conflict {
144 message: &'static str,
145 },
146 NotFound {
154 resource: &'static ResourceInfo,
155 },
156 PermissionDenied {
163 permission: &'static PermissionInfo,
164 },
165 UnknownOperation,
166 MethodNotAllowed {
167 allowed: Vec<&'static str>,
168 },
169 UnsupportedMediaType,
170 InternalFailure,
171}
172
173impl FrameworkError {
174 pub fn name(&self) -> &'static str {
175 match self {
176 Self::Unauthenticated => "UnauthenticatedException",
177 Self::Forbidden => "ForbiddenException",
178 Self::Conflict { .. } => "ConflictException",
179 Self::NotFound { .. } => "NotFoundException",
180 Self::PermissionDenied { .. } => "ForbiddenException",
181 Self::UnknownOperation => "UnknownOperation",
182 Self::MethodNotAllowed { .. } => "MethodNotAllowed",
183 Self::UnsupportedMediaType => "UnsupportedMediaTypeException",
184 Self::InternalFailure => "InternalFailure",
185 }
186 }
187
188 pub fn status(&self) -> u16 {
189 match self {
190 Self::Unauthenticated => 401,
191 Self::Forbidden => 403,
192 Self::Conflict { .. } => 409,
193 Self::NotFound { .. } => 404,
194 Self::PermissionDenied { .. } => 403,
195 Self::UnknownOperation => 404,
196 Self::MethodNotAllowed { .. } => 405,
197 Self::UnsupportedMediaType => 415,
198 Self::InternalFailure => 500,
199 }
200 }
201
202 pub fn message(&self) -> &'static str {
203 match self {
204 Self::Unauthenticated => "authentication is required",
205 Self::Forbidden => "access is forbidden",
206 Self::Conflict { message } => message,
207 Self::NotFound { resource } => resource.not_found,
208 Self::PermissionDenied { permission } if permission.is_public() => permission.denied,
209 Self::PermissionDenied { .. } => "This principal may not perform this operation.",
210 Self::UnknownOperation => "no operation serves this request",
211 Self::MethodNotAllowed { .. } => "the request method is not allowed for this target",
212 Self::UnsupportedMediaType => "the request content-type is not supported",
213 Self::InternalFailure => "the request failed; quote the request id when reporting it",
214 }
215 }
216}
217
218impl fmt::Display for FrameworkError {
219 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220 f.write_str(self.message())
221 }
222}
223
224impl std::error::Error for FrameworkError {}
225
226#[cfg(test)]
227mod tests {
228 use super::*;
229
230 #[derive(Debug)]
231 struct SimpleError(&'static str);
232
233 impl fmt::Display for SimpleError {
234 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235 f.write_str(self.0)
236 }
237 }
238
239 impl std::error::Error for SimpleError {}
240
241 #[derive(Debug)]
242 struct NestedError {
243 msg: &'static str,
244 source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
245 }
246
247 impl fmt::Display for NestedError {
248 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249 f.write_str(self.msg)
250 }
251 }
252
253 impl std::error::Error for NestedError {
254 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
255 self.source
256 .as_deref()
257 .map(|s| s as &(dyn std::error::Error + 'static))
258 }
259 }
260
261 #[derive(Debug)]
262 struct CyclicError;
263
264 impl fmt::Display for CyclicError {
265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266 f.write_str("loop")
267 }
268 }
269
270 impl std::error::Error for CyclicError {
271 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
272 Some(self)
273 }
274 }
275
276 #[derive(Debug)]
277 struct CycleA;
278 #[derive(Debug)]
279 struct CycleB;
280 static CYCLE_A: CycleA = CycleA;
281 static CYCLE_B: CycleB = CycleB;
282
283 impl fmt::Display for CycleA {
284 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285 f.write_str("node_a")
286 }
287 }
288
289 impl std::error::Error for CycleA {
290 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
291 Some(&CYCLE_B)
292 }
293 }
294
295 impl fmt::Display for CycleB {
296 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
297 f.write_str("node_b")
298 }
299 }
300
301 impl std::error::Error for CycleB {
302 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
303 Some(&CYCLE_A)
304 }
305 }
306
307 #[test]
308 fn not_found_and_permission_denied_name_only_what_they_may() {
309 use crate::permissions::Tier;
310
311 static INBOX: ResourceInfo = ResourceInfo {
312 name: "inbox",
313 identifiers: &["workspaceId", "inboxId"],
314 not_found: "No such inbox.",
315 };
316 static SEND: PermissionInfo = PermissionInfo {
317 resource: &INBOX,
318 symbol: "mailSend",
319 value: "mail:send",
320 aliases: &[],
321 tier: Tier::Public,
322 denied: "This principal does not hold mail:send on that inbox.",
323 };
324 static WATCH: PermissionInfo = PermissionInfo {
325 resource: &INBOX,
326 symbol: "watch",
327 value: "inbox:watch",
328 aliases: &[],
329 tier: Tier::Internal,
330 denied: "This principal does not hold inbox:watch on that inbox.",
331 };
332 let missing = FrameworkError::NotFound { resource: &INBOX };
333 assert_eq!(missing.status(), 404);
334 assert_eq!(missing.name(), "NotFoundException");
335 assert_eq!(missing.message(), "No such inbox.");
336
337 let denied = FrameworkError::PermissionDenied { permission: &SEND };
338 assert_eq!(denied.status(), 403);
339 assert_eq!(denied.name(), "ForbiddenException");
340 assert_eq!(
341 denied.message(),
342 "This principal does not hold mail:send on that inbox."
343 );
344 let internal = FrameworkError::PermissionDenied { permission: &WATCH };
346 assert_eq!(
347 internal.message(),
348 "This principal may not perform this operation."
349 );
350 }
351
352 #[test]
353 fn chain_with_no_source() {
354 let error = Error::internal("standalone");
355 assert_eq!(error.chain(), "standalone");
356 }
357
358 #[test]
359 fn chain_with_sources() {
360 let leaf = SimpleError("leaf");
361 let middle = NestedError {
362 msg: "middle",
363 source: Some(Box::new(leaf)),
364 };
365 let root = NestedError {
366 msg: "root",
367 source: Some(Box::new(middle)),
368 };
369 let error = Error::new(root);
370 assert_eq!(error.chain(), "root: middle: leaf");
371 }
372
373 #[test]
374 fn chain_terminates_on_self_referential_cycle() {
375 let error = Error::new(CyclicError);
376 let chain = error.chain();
377 assert_eq!(chain.matches(": loop").count(), MAX_SOURCE_DEPTH);
378 assert!(chain.starts_with("loop: loop"));
379 }
380
381 #[test]
382 fn chain_terminates_on_mutual_cycle() {
383 let error = Error::new(CycleA);
384 let chain = error.chain();
385 let total_sources = chain.matches(": node_a").count() + chain.matches(": node_b").count();
386 assert_eq!(total_sources, MAX_SOURCE_DEPTH);
387 assert!(chain.starts_with("node_a: node_b: node_a"));
388 }
389
390 #[test]
391 fn chain_bounds_deep_error_hierarchy() {
392 let mut current = NestedError {
393 msg: "leaf",
394 source: None,
395 };
396 for _ in 0..100 {
397 current = NestedError {
398 msg: "step",
399 source: Some(Box::new(current)),
400 };
401 }
402 let error = Error::new(current);
403 let chain = error.chain();
404 assert_eq!(chain.matches(": ").count(), MAX_SOURCE_DEPTH);
405 }
406}