Skip to main content

tuwunel_core/error/
mod.rs

1//! Defines shared error and result types.
2//!
3//! Errors retain protocol and transport context across crate boundaries. The
4//! module also provides the macros used to construct and report them.
5
6mod err;
7mod log;
8mod panic;
9mod response;
10mod serde;
11#[cfg(test)]
12mod tests;
13
14use std::{
15	any::Any,
16	borrow::Cow,
17	convert::Infallible,
18	io::ErrorKind as IoErrorKind,
19	sync::{Mutex, PoisonError},
20};
21
22// Aliased so the variants already spelling this path qualified stay clean
23// under unused_qualifications.
24use ruma::api::error::{ErrorKind as MatrixErrorKind, UnknownTokenErrorData};
25
26pub use self::{err::visit, log::*};
27use crate::utils::{assert_ref_unwind_safe, assert_send, assert_sync, assert_unwind_safe};
28
29/// Unifies failures raised by the core crate.
30///
31/// Variants preserve typed causes where available and carry contextual text for
32/// domain-specific failures. Conversion implementations allow callers to
33/// propagate common dependency errors with `?`.
34#[derive(thiserror::Error)]
35pub enum Error {
36	/// Carries an arbitrary panic payload.
37	///
38	/// The payload is protected by a mutex so the error remains shareable
39	/// across unwind boundaries. Use the panic helpers to resume unwinding or
40	/// inspect it.
41	#[error("PANIC!")]
42	PanicAny(Mutex<Box<dyn Any + Send>>),
43
44	/// Carries a panic payload and its extracted static message.
45	///
46	/// The message supports diagnostics without consuming the payload. The
47	/// mutex keeps the payload available across unwind boundaries.
48	#[error("PANIC! {0}")]
49	Panic(&'static str, Mutex<Box<dyn Any + Send + 'static>>),
50
51	// std
52	/// Reports a formatting failure.
53	///
54	/// Automatic conversion preserves the original source error. Its display
55	/// text is forwarded unchanged.
56	#[error(transparent)]
57	Fmt(#[from] std::fmt::Error),
58
59	/// Reports an invalid UTF-8 byte sequence while constructing a string.
60	///
61	/// Automatic conversion preserves the original bytes and source error. Its
62	/// display text is forwarded unchanged.
63	#[error(transparent)]
64	FromUtf8(#[from] std::string::FromUtf8Error),
65
66	/// Reports an input or output failure.
67	///
68	/// Automatic conversion preserves the original I/O error and its kind. HTTP
69	/// response mapping may use the contained error kind.
70	#[error("I/O error: {0}")]
71	Io(#[from] std::io::Error),
72
73	/// Reports a floating-point parsing failure.
74	///
75	/// Automatic conversion preserves the original source error. Its display
76	/// text is forwarded unchanged.
77	#[error(transparent)]
78	ParseFloat(#[from] std::num::ParseFloatError),
79
80	/// Reports an integer parsing failure.
81	///
82	/// Automatic conversion preserves the original source error. Its display
83	/// text is forwarded unchanged.
84	#[error(transparent)]
85	ParseInt(#[from] std::num::ParseIntError),
86
87	/// Carries a dynamically typed standard error.
88	///
89	/// The boxed source must be safe to send and share between threads. Its
90	/// display text and source chain remain available for diagnostics.
91	#[error(transparent)]
92	Std(#[from] Box<dyn std::error::Error + Send + Sync + 'static>),
93
94	/// Reports a system clock value earlier than the requested reference time.
95	///
96	/// Automatic conversion preserves the original source error. Its display
97	/// text is forwarded unchanged.
98	#[error(transparent)]
99	SystemTime(#[from] std::time::SystemTimeError),
100
101	/// Reports failure to access thread-local state.
102	///
103	/// Automatic conversion preserves the original source error. Its display
104	/// text is forwarded unchanged.
105	#[error(transparent)]
106	ThreadAccessError(#[from] std::thread::AccessError),
107
108	/// Reports an integer conversion outside the destination range.
109	///
110	/// Automatic conversion preserves the original source error. Its display
111	/// text is forwarded unchanged.
112	#[error(transparent)]
113	TryFromInt(#[from] std::num::TryFromIntError),
114
115	/// Reports conversion from a slice with an incompatible length.
116	///
117	/// Automatic conversion preserves the original source error. Its display
118	/// text is forwarded unchanged.
119	#[error(transparent)]
120	TryFromSlice(#[from] std::array::TryFromSliceError),
121
122	/// Reports an invalid borrowed UTF-8 byte sequence.
123	///
124	/// Automatic conversion preserves the original source error. Its display
125	/// text is forwarded unchanged.
126	#[error(transparent)]
127	Utf8(#[from] std::str::Utf8Error),
128
129	// third-party
130	/// Reports that a fixed-capacity collection cannot accept another item.
131	///
132	/// Automatic conversion preserves the original capacity error. Its display
133	/// text is forwarded unchanged.
134	#[error(transparent)]
135	CapacityError(#[from] arrayvec::CapacityError),
136
137	/// Reports a command-line parsing or presentation failure.
138	///
139	/// Automatic conversion preserves the original Clap error. Its display text
140	/// is forwarded unchanged.
141	#[error(transparent)]
142	Clap(#[from] clap::error::Error),
143
144	/// Reports a Unix system error number.
145	///
146	/// Automatic conversion preserves the original error number. Its display
147	/// text is forwarded unchanged.
148	#[cfg(unix)]
149	#[error(transparent)]
150	Errno(#[from] nix::errno::Errno),
151
152	/// Reports rejection of a required Axum request extension.
153	///
154	/// Automatic conversion preserves the extractor rejection. Its display text
155	/// is forwarded unchanged.
156	#[error(transparent)]
157	Extension(#[from] axum::extract::rejection::ExtensionRejection),
158
159	/// Reports a configuration extraction failure.
160	///
161	/// The boxed Figment error preserves its complete source and diagnostic
162	/// context. A dedicated conversion boxes it for ordinary `?` propagation.
163	#[error(transparent)]
164	Figment(Box<figment::error::Error>),
165
166	/// Reports failure to deserialize an HTML form.
167	///
168	/// Automatic conversion preserves the original source error. Its display
169	/// text is forwarded unchanged.
170	#[error(transparent)]
171	HtmlFormDe(#[from] serde_html_form::de::Error),
172
173	/// Reports failure to serialize an HTML form.
174	///
175	/// Automatic conversion preserves the original source error. Its display
176	/// text is forwarded unchanged.
177	#[error(transparent)]
178	HtmlFormSer(#[from] serde_html_form::ser::Error),
179
180	/// Reports failure to construct an HTTP value.
181	///
182	/// Automatic conversion preserves the original source error. Its display
183	/// text is forwarded unchanged.
184	#[error(transparent)]
185	Http(#[from] http::Error),
186
187	/// Reports an invalid HTTP header value.
188	///
189	/// Automatic conversion preserves the original source error. Its display
190	/// text is forwarded unchanged.
191	#[error(transparent)]
192	HttpHeader(#[from] http::header::InvalidHeaderValue),
193
194	/// Reports failure of a spawned asynchronous task.
195	///
196	/// The Tokio join error records cancellation and panic state. Panic helpers
197	/// can recover its payload when the task panicked.
198	#[error("Join error: {0}")]
199	JoinError(#[from] tokio::task::JoinError),
200
201	/// Reports failure to serialize or deserialize JSON.
202	///
203	/// Automatic conversion preserves the original source error. Matrix error
204	/// mapping classifies this variant as invalid JSON.
205	#[error(transparent)]
206	Json(#[from] serde_json::Error),
207
208	/// Reports failure to parse a Matrix-compatible JavaScript integer.
209	///
210	/// Automatic conversion preserves the re-exported integer error. Matrix
211	/// response mapping treats it as a bad request.
212	#[error(transparent)]
213	JsParseInt(#[from] ruma::JsParseIntError), // js_int re-export
214
215	/// Reports a value outside the Matrix JavaScript-integer range.
216	///
217	/// Automatic conversion preserves the re-exported conversion error. Matrix
218	/// response mapping treats it as a bad request.
219	#[error(transparent)]
220	JsTryFromInt(#[from] ruma::JsTryFromIntError), // js_int re-export
221
222	/// Reports an object-storage operation failure.
223	///
224	/// Automatic conversion preserves the backend source error. Its display
225	/// text is forwarded unchanged.
226	#[error(transparent)]
227	ObjectStore(#[from] object_store::Error),
228
229	/// Reports rejection of an Axum path parameter.
230	///
231	/// Automatic conversion preserves the extractor rejection. Its display text
232	/// is forwarded unchanged.
233	#[error(transparent)]
234	Path(#[from] axum::extract::rejection::PathRejection),
235
236	/// Reports access to a poisoned synchronization primitive.
237	///
238	/// The stored text reports the poisoning without retaining the guard.
239	/// Poison conversion supplies the originating error text.
240	#[error("{0}")]
241	Poison(Cow<'static, str>),
242
243	/// Reports an invalid regular expression.
244	///
245	/// Automatic conversion preserves the original source error. The formatted
246	/// message identifies the regex failure.
247	#[error("Regex error: {0}")]
248	Regex(#[from] regex::Error),
249
250	/// Reports an HTTP client request failure.
251	///
252	/// Automatic conversion preserves status and transport details from
253	/// Reqwest. HTTP response mapping reuses its status when one is available.
254	#[error("Request error: {0}")]
255	Reqwest(#[from] reqwest::Error),
256
257	/// Reports a custom deserialization failure.
258	///
259	/// The message may borrow static text or own formatted context. It is
260	/// exposed directly as the error display.
261	#[error("{0}")]
262	SerdeDe(Cow<'static, str>),
263
264	/// Reports a custom serialization failure.
265	///
266	/// The message may borrow static text or own formatted context. It is
267	/// exposed directly as the error display.
268	#[error("{0}")]
269	SerdeSer(Cow<'static, str>),
270
271	/// Reports failure to deserialize TOML.
272	///
273	/// Automatic conversion preserves the original source error. Its display
274	/// text is forwarded unchanged.
275	#[error(transparent)]
276	TomlDe(#[from] toml::de::Error),
277
278	/// Reports failure to serialize TOML.
279	///
280	/// Automatic conversion preserves the original source error. Its display
281	/// text is forwarded unchanged.
282	#[error(transparent)]
283	TomlSer(#[from] toml::ser::Error),
284
285	/// Reports an invalid tracing filter directive.
286	///
287	/// Automatic conversion preserves the filter parser's source error. The
288	/// formatted message identifies the tracing subsystem.
289	#[error("Tracing filter error: {0}")]
290	TracingFilter(#[from] tracing_subscriber::filter::ParseError),
291
292	/// Reports failure to reload a tracing layer.
293	///
294	/// Automatic conversion preserves the reload source error. The formatted
295	/// message identifies the tracing subsystem.
296	#[error("Tracing reload error: {0}")]
297	TracingReload(#[from] tracing_subscriber::reload::Error),
298
299	/// Reports rejection of a typed HTTP header.
300	///
301	/// Automatic conversion preserves the extractor rejection. Its display text
302	/// is forwarded unchanged.
303	#[error(transparent)]
304	TypedHeader(#[from] axum_extra::typed_header::TypedHeaderRejection),
305
306	/// Reports failure to parse a URL.
307	///
308	/// Automatic conversion preserves the original source error. Its display
309	/// text is forwarded unchanged.
310	#[error(transparent)]
311	UrlParse(#[from] url::ParseError),
312
313	/// Reports failure to serialize or deserialize YAML.
314	///
315	/// Automatic conversion preserves the original source error. Its display
316	/// text is forwarded unchanged.
317	#[error(transparent)]
318	Yaml(#[from] serde_yaml::Error),
319
320	// ruma/tuwunel
321	/// Reports an arithmetic operation that cannot produce a valid result.
322	///
323	/// The message records contextual conversion, range, overflow, and
324	/// underflow failures. It can supplement lower-level typed numeric source
325	/// errors.
326	#[error("Arithmetic operation failed: {0}")]
327	Arithmetic(Cow<'static, str>),
328
329	/// State-res `auth_check` rejection sentinel.
330	///
331	/// Surfaces to the wire as 403 / M_FORBIDDEN with the Display text
332	/// `Auth check failed: {inner}`. Exists so callers can pattern-match the
333	/// cause without grepping the message text.
334	#[error("Auth check failed: {0}")]
335	AuthCheck(Box<Self>),
336
337	/// Reports a legacy structured Matrix request error.
338	///
339	/// The variant pairs a Matrix error kind with static public text. Response
340	/// mapping derives the appropriate HTTP status from that kind.
341	#[error("{0}: {1}")]
342	BadRequest(ruma::api::error::ErrorKind, &'static str), //TODO: remove
343
344	/// Reports an invalid or unusable response from a remote server.
345	///
346	/// The message carries protocol context suitable for diagnostics. No typed
347	/// remote response is retained.
348	#[error("{0}")]
349	BadServerResponse(Cow<'static, str>),
350
351	/// Reports invalid canonical JSON.
352	///
353	/// Automatic conversion preserves the original canonicalization error.
354	/// Matrix error mapping classifies this variant as invalid JSON.
355	#[error(transparent)]
356	CanonicalJson(#[from] ruma::CanonicalJsonError),
357
358	/// Reports an invalid configuration directive.
359	///
360	/// The static directive name identifies the setting and the accompanying
361	/// message explains why its value cannot be used.
362	#[error("There was a problem with the '{0}' directive in your configuration: {1}")]
363	Config(&'static str, Cow<'static, str>),
364
365	/// Reports a resource conflict, such as an occupied room alias or an action
366	/// on a finalised delayed event, which answers with a conflict status.
367	#[error("{0}")]
368	Conflict(Cow<'static, str>),
369
370	/// Reports an invalid Matrix content-disposition header.
371	///
372	/// Automatic conversion preserves the original parser error. Its display
373	/// text is forwarded unchanged.
374	#[error(transparent)]
375	ContentDisposition(#[from] ruma::http_headers::ContentDispositionParseError),
376
377	/// Reports a database operation or invariant failure.
378	///
379	/// The message carries storage context without exposing it in sanitized
380	/// client-facing output. Database failures default to an internal status.
381	#[error("{0}")]
382	Database(Cow<'static, str>),
383
384	/// Reports use of a feature disabled by server configuration.
385	///
386	/// The stored feature name is included in the public message. Matrix
387	/// response mapping assigns the matching feature-disabled error kind.
388	#[error("Feature '{0}' is not available on this server.")]
389	FeatureDisabled(Cow<'static, str>),
390
391	/// Reports an error response received from a federated server.
392	///
393	/// The variant preserves both the origin and its structured Matrix error,
394	/// so internal callers can dispatch on what the remote said. Response
395	/// mapping does not forward that status and kind unconditionally.
396	#[error("Remote server {0} responded with: {1}")]
397	Federation(ruma::OwnedServerName, ruma::api::error::Error),
398
399	/// Carries a preconstructed HTTP status and JSON response body.
400	///
401	/// Response mapping preserves the caller-selected status. The formatted
402	/// JSON becomes the message of a standard Matrix error response.
403	#[error("{0}: {1:#?}")]
404	HttpJson(http::StatusCode, axum::Json<serde_json::Value>),
405
406	/// Reports an invariant violation in a room's persisted state.
407	///
408	/// The static message names the failed invariant and the room identifier
409	/// locates the affected state.
410	#[error("{0} in {1}")]
411	InconsistentRoomState(&'static str, ruma::OwnedRoomId),
412
413	/// Reports failure to convert a Matrix response into HTTP form.
414	///
415	/// Automatic conversion preserves the original Ruma source error. Its
416	/// display text is forwarded unchanged.
417	#[error(transparent)]
418	IntoHttp(#[from] ruma::api::error::IntoHttpError),
419
420	/// Reports an LDAP operation failure.
421	///
422	/// The message records directory-service context not represented by a
423	/// common typed source. Response mapping treats it as an internal error.
424	#[error("{0}")]
425	Ldap(Cow<'static, str>),
426
427	/// Reports an invalid Matrix content URI.
428	///
429	/// Automatic conversion preserves the original URI error. Its display text
430	/// is forwarded unchanged.
431	#[error(transparent)]
432	Mxc(#[from] ruma::MxcUriError),
433
434	/// Reports an invalid Matrix identifier.
435	///
436	/// Automatic conversion preserves the original identifier parser error. Its
437	/// display text is forwarded unchanged.
438	#[error(transparent)]
439	Mxid(#[from] ruma::IdParseError),
440
441	/// Reports invalid room power-level content or arithmetic.
442	///
443	/// Automatic conversion preserves the original Ruma power-level error. Its
444	/// display text is forwarded unchanged.
445	#[error(transparent)]
446	PowerLevels(#[from] ruma::events::room::power_levels::PowerLevelsError),
447
448	/// Reports failure to redact canonical JSON from a remote server.
449	///
450	/// The variant records the origin alongside the invalid canonical field.
451	/// The formatted message keeps both pieces of context.
452	#[error("from {0}: {1}")]
453	Redaction(ruma::OwnedServerName, ruma::canonical_json::CanonicalJsonFieldError),
454
455	/// Carries a structured Matrix client error response.
456	///
457	/// The variant stores the Matrix error kind, public message, and preferred
458	/// HTTP status. Response mapping may refine the status from the kind.
459	#[error("{0}: {1}")]
460	Request(ruma::api::error::ErrorKind, Cow<'static, str>, http::StatusCode),
461
462	/// Carries a client error whose HTTP status is authoritative.
463	///
464	/// `Request` treats a bad-request status as unset and lets the kind promote
465	/// it. Use this variant where a specification mandates a status the
466	/// promotion table would override.
467	#[error("{0}: {1}")]
468	RequestStatus(MatrixErrorKind, Cow<'static, str>, http::StatusCode),
469
470	/// Reports a structured Matrix API error.
471	///
472	/// Automatic conversion preserves the Ruma status, kind, and message.
473	/// Response mapping forwards those structured fields.
474	#[error(transparent)]
475	Ruma(#[from] ruma::api::error::Error),
476
477	/// Reports a Matrix signature verification failure.
478	///
479	/// Automatic conversion preserves the original verification error. Its
480	/// display text is forwarded unchanged.
481	#[error(transparent)]
482	Signatures(#[from] ruma::signatures::VerificationError),
483
484	/// Reports invalid JSON encountered during signature processing.
485	///
486	/// Automatic conversion preserves the signature library's JSON error. Its
487	/// display text is forwarded unchanged.
488	#[error(transparent)]
489	SignaturesJson(#[from] ruma::signatures::JsonError),
490
491	/// Requests an interactive-authentication challenge response.
492	///
493	/// The contained UIAA information is serialized for the client rather than
494	/// treated as an opaque internal failure.
495	#[error("uiaa")]
496	Uiaa(ruma::api::client::uiaa::UiaaInfo),
497
498	// unique / untyped
499	/// Reports an untyped core failure.
500	///
501	/// The message may borrow static text or own formatted context. This
502	/// fallback is used when no structured variant represents the failure.
503	#[error("{0}")]
504	Err(Cow<'static, str>),
505}
506
507static _IS_SEND: () = assert_send::<Error>();
508static _IS_SYNC: () = assert_sync::<Error>();
509static _IS_UNWIND_SAFE: () = assert_unwind_safe::<Error>();
510static _IS_REF_UNWIND_SAFE: () = assert_ref_unwind_safe::<Error>();
511
512impl Error {
513	/// Captures the operating system's most recent error for the current
514	/// thread.
515	///
516	/// The error is sampled when this function is called and wrapped as
517	/// [`Error::Io`]. Platform-specific code remains available through the
518	/// source.
519	#[inline]
520	#[must_use]
521	pub fn from_errno() -> Self { Self::Io(std::io::Error::last_os_error()) }
522
523	/// Constructs a database error from static diagnostic text.
524	///
525	/// The error helper records the call site while preserving the supplied
526	/// message. Callers exposing it publicly can use
527	/// [`Error::sanitized_message`].
528	//#[deprecated]
529	pub fn bad_database(message: &'static str) -> Self {
530		crate::err!(Database(error!("{message}")))
531	}
532
533	/// Constructs the `M_UNKNOWN_TOKEN` error refusing an access or refresh
534	/// token.
535	///
536	/// `soft_logout` tells the client it may log in again on the same device,
537	/// keeping its session, rather than starting over.
538	#[must_use]
539	pub fn unknown_token(soft_logout: bool, message: &'static str) -> Self {
540		let kind = MatrixErrorKind::UnknownToken(UnknownTokenErrorData { soft_logout });
541
542		Self::BadRequest(kind, message)
543	}
544
545	/// Produces an error message safe for public responses.
546	///
547	/// Database and I/O details are replaced with generic text to avoid leaking
548	/// sensitive context. Other variants retain their normal message.
549	pub fn sanitized_message(&self) -> String {
550		match self {
551			| Self::Database(..) => String::from("Database error occurred."),
552			| Self::Io(..) => String::from("I/O error occurred."),
553			| _ => self.message(),
554		}
555	}
556
557	/// Formats the diagnostic message for this error.
558	///
559	/// Federation errors include their origin and Ruma errors use their Matrix
560	/// response message. Other variants use their
561	/// [`Display`](std::fmt::Display) implementation.
562	pub fn message(&self) -> String {
563		match self {
564			| Self::Federation(origin, error) => format!("Answer from {origin}: {error}"),
565			| Self::Ruma(error) => response::ruma_error_message(error),
566			| _ => format!("{self}"),
567		}
568	}
569
570	/// Returns the Matrix error kind represented by this error.
571	///
572	/// Structured request and federation variants preserve their supplied kind.
573	/// Unclassified internal errors map to `M_UNKNOWN`.
574	#[inline]
575	pub fn kind(&self) -> ruma::api::error::ErrorKind {
576		use ruma::api::error::{
577			ErrorKind,
578			ErrorKind::{FeatureDisabled, InvalidParam, NotJson, Unknown},
579		};
580
581		match self {
582			| Self::FeatureDisabled(..) => FeatureDisabled,
583			| Self::CanonicalJson(..) | Self::Json(..) => NotJson,
584			| Self::AuthCheck(..) => ErrorKind::forbidden(),
585			| Self::BadRequest(kind, ..)
586			| Self::Request(kind, ..)
587			| Self::RequestStatus(kind, ..) => kind.clone(),
588			| Self::Federation(_, error) | Self::Ruma(error) =>
589				response::ruma_error_kind(error).clone(),
590			| Self::Path(rejection) if rejection.status().is_client_error() => InvalidParam,
591			| _ => Unknown,
592		}
593	}
594
595	/// Returns the HTTP status represented by this error.
596	///
597	/// Structured variants preserve or derive their protocol status, while I/O
598	/// and client errors use their available status metadata. Unclassified
599	/// failures map to an internal-server-error status.
600	pub fn status_code(&self) -> http::StatusCode {
601		use http::StatusCode;
602
603		match self {
604			| Self::AuthCheck(..) => StatusCode::FORBIDDEN,
605			| Self::Conflict(_) => StatusCode::CONFLICT,
606			| Self::Federation(_, error) | Self::Ruma(error) => error.status_code,
607			| Self::FeatureDisabled(..)
608			| Self::CanonicalJson(..)
609			| Self::Json(..)
610			| Self::JsParseInt(..)
611			| Self::JsTryFromInt(..) => response::bad_request_code(&self.kind()),
612			| Self::BadRequest(kind, ..) => response::bad_request_code(kind),
613			| Self::Request(kind, _, code) => response::status_code(kind, *code),
614			| Self::Io(error) => response::io_error_code(error.kind()),
615			| Self::HttpJson(code, ..) | Self::RequestStatus(.., code) => *code,
616			| Self::Path(rejection) => rejection.status(),
617			| Self::Reqwest(error) => error
618				.status()
619				.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
620			| _ => StatusCode::INTERNAL_SERVER_ERROR,
621		}
622	}
623
624	/// Tests whether this error maps to an HTTP not-found status.
625	///
626	/// The test includes contained error types whose status mapping yields 404.
627	/// Callers can use it to treat `Err` as the absent case in place of a
628	/// nested `Option`.
629	#[inline]
630	pub fn is_not_found(&self) -> bool { self.status_code() == http::StatusCode::NOT_FOUND }
631
632	/// Tests whether this is a potentially transient I/O failure.
633	///
634	/// Interrupted, busy, timed-out, incomplete, and unclassified I/O failures
635	/// may succeed on retry. Missing data, corruption, and invalid input do not
636	/// qualify.
637	#[inline]
638	pub fn is_transient_io(&self) -> bool {
639		matches!(
640			self,
641			Self::Io(error) if matches!(
642				error.kind(),
643				IoErrorKind::Interrupted
644					| IoErrorKind::ResourceBusy
645					| IoErrorKind::TimedOut
646					| IoErrorKind::WouldBlock
647					| IoErrorKind::Other
648			)
649		)
650	}
651
652	/// Tests whether this error is a missing record rather than any 404.
653	///
654	/// Only `Request` with the `NotFound` kind matches, which is what the
655	/// database returns for an absent key. An I/O not-found and every other
656	/// error mapping to 404 do not, so a storage fault never reads as absence.
657	#[inline]
658	pub fn is_missing(&self) -> bool {
659		matches!(self, Self::Request(MatrixErrorKind::NotFound, ..))
660	}
661
662	/// Tests whether this error reports an interrupted operation.
663	///
664	/// [`Server::check_running`] produces this shape once shutdown begins, so a
665	/// caller can tell work abandoned at a cancellation point from work that
666	/// genuinely failed. It matches the I/O variant only, so a layer that
667	/// rewraps the error into another variant hides the cancellation.
668	///
669	/// [`Server::check_running`]: crate::Server::check_running
670	#[inline]
671	pub fn is_interrupted(&self) -> bool {
672		matches!(self, Self::Io(error) if error.kind() == IoErrorKind::Interrupted)
673	}
674}
675
676impl std::fmt::Debug for Error {
677	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
678		write!(f, "{}", self.message())
679	}
680}
681
682impl<T> From<PoisonError<T>> for Error {
683	#[cold]
684	#[inline(never)]
685	fn from(e: PoisonError<T>) -> Self { Self::Poison(e.to_string().into()) }
686}
687
688impl From<figment::error::Error> for Error {
689	#[cold]
690	#[inline(never)]
691	fn from(e: figment::error::Error) -> Self { Self::Figment(Box::new(e)) }
692}
693
694#[expect(clippy::fallible_impl_from)]
695impl From<Infallible> for Error {
696	#[cold]
697	#[inline(never)]
698	fn from(_e: Infallible) -> Self {
699		panic!("infallible error should never exist");
700	}
701}
702
703/// Marks an impossible [`Infallible`] error path.
704///
705/// The argument cannot be constructed in safe code, so reaching this function
706/// indicates a violated invariant.
707///
708/// # Panics
709///
710/// Always panics because an `Infallible` error cannot legitimately exist.
711#[cold]
712#[inline(never)]
713pub fn infallible(_e: &Infallible) {
714	panic!("infallible error should never exist");
715}
716
717/// Produces a public-safe message from an owned error.
718///
719/// Its by-value signature adapts [`Error::sanitized_message`] for iterator and
720/// future combinators that consume their item. Sanitization behavior is
721/// identical to the method.
722#[inline]
723#[must_use]
724#[expect(clippy::needless_pass_by_value)]
725pub fn sanitized_message(e: Error) -> String { e.sanitized_message() }