kernable/error.rs
1//! Rejections and errors.
2
3use std::fmt;
4
5use crate::StoredEvent;
6
7/// Any error a listener, query or middleware handler may return; `?` converts most errors
8/// into it, a [`Rejected`] too: `return Err(Rejected::new("no such cart").code("not_found").into())`.
9/// A query or middleware handler that returns a [`Rejected`] (also one wrapped in
10/// [`Error::Rejected`], e.g. by a query it asked) refuses with its code; any other error
11/// refuses with `handler_error` (`middleware_error` from a middleware). An event handler's
12/// error makes the listener reconnect and get the event again; a reactor parks it at once if
13/// it is a [`Rejected`], else after a few attempts (see [`crate::Listener::park_after`]).
14pub type BoxError = Box<dyn std::error::Error + Send + Sync>;
15
16/// A business reason to refuse a command or query: return it from a handler. `code` (default
17/// `rejected`) is what callers act on, `message` what they show.
18///
19/// A command handler returns `Err(Rejected::new("Cart is checked out"))`; a listener's query
20/// or middleware handler returns it as a [`BoxError`] (`.into()` or `?`). Callers see it as
21/// [`crate::Outcome::Rejected`] from `submit` and as [`Error::Rejected`] from `query`.
22#[derive(Clone, Debug, PartialEq, Eq)]
23pub struct Rejected {
24 pub code: String,
25 pub message: String,
26 /// Set by the kernel for `unique_taken`: the name of the key another aggregate holds.
27 pub key: Option<String>,
28 /// Set by the kernel for `requirement_missing`: the first requirement that does not hold.
29 /// Boxed: it keeps every `Result` with an [`Error`] small.
30 pub requirement: Option<Box<crate::Requirement>>,
31}
32
33impl Rejected {
34 /// A rejection with `message` and the code `rejected`.
35 pub fn new(message: impl Into<String>) -> Rejected {
36 Rejected {
37 code: "rejected".into(),
38 message: message.into(),
39 key: None,
40 requirement: None,
41 }
42 }
43
44 /// This rejection with another code, e.g. `Rejected::new("no such cart").code("not_found")`.
45 pub fn code(mut self, code: impl Into<String>) -> Rejected {
46 self.code = code.into();
47 self
48 }
49
50 pub(crate) fn from_wire(r: kernable_core::proto::Rejected) -> Rejected {
51 Rejected {
52 code: r.code,
53 message: r.message,
54 key: Some(r.key).filter(|k| !k.is_empty()),
55 requirement: r
56 .requirement
57 .map(|q| Box::new(crate::Requirement::from_wire(*q))),
58 }
59 }
60
61 pub(crate) fn to_wire(&self) -> kernable_core::proto::Rejected {
62 // The key and requirement are the kernel's to set.
63 kernable_core::proto::Rejected {
64 code: self.code.clone(),
65 message: self.message.clone(),
66 ..Default::default()
67 }
68 }
69
70 /// The rejection a failed handler reports: `err` itself if it is a [`Rejected`] (also one a
71 /// query inside the handler returned), else `code` with the error's text.
72 pub(crate) fn of(err: &BoxError, code: &str) -> Rejected {
73 if let Some(r) = err.downcast_ref::<Rejected>() {
74 return r.clone();
75 }
76 if let Some(Error::Rejected(r)) = err.downcast_ref::<Error>() {
77 return r.clone();
78 }
79 Rejected::new(err.to_string()).code(code)
80 }
81}
82
83impl fmt::Display for Rejected {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 f.write_str(&self.message)
86 }
87}
88
89impl std::error::Error for Rejected {}
90
91/// Why a call to the kernel failed. It implements `std::error::Error`, so `?` turns it into a
92/// [`BoxError`] in handlers and `main`.
93#[derive(Debug)]
94pub enum Error {
95 /// A rejection: the read model or a middleware refused the query
96 /// ([`crate::Kernable::query`]), or a command handler refused the command in
97 /// [`crate::Aggregate::handle`]. A rejected submit is not an error but
98 /// [`crate::Outcome::Rejected`].
99 Rejected(Rejected),
100 /// The command was committed, but not every listener that counts processed its events
101 /// within the kernel's `--settle-timeout-ms`. Read models may not show the change yet; the
102 /// committed events are attached. Submitting again with the same ID returns the same
103 /// outcome.
104 NotSettled(Vec<StoredEvent>),
105 /// The command with this ID is scheduled ([`crate::Submit::at`]) and not due yet: it has no
106 /// outcome to wait for. Submit it again by its ID after its time.
107 NotDue(String),
108 /// The kernel refused the call or could not be reached: the gRPC status, e.g.
109 /// `PERMISSION_DENIED` without a grant (see Errors in the reference).
110 Status(tonic::Status),
111 /// A key, grant or certificate could not be read, or an option is invalid; also a failing
112 /// handler in [`crate::Aggregate::fold`] and [`crate::Aggregate::handle`].
113 Config(String),
114 /// Data could not be encoded or decoded as JSON.
115 Json(serde_json::Error),
116 /// A read model's store failed.
117 Store(rusqlite::Error),
118}
119
120impl Error {
121 /// Whether the kernel refused a membership because it would switch its service to a
122 /// deployment that has not caught up yet (`not_caught_up`), back to one that served before
123 /// while [`crate::Switch::CaughtUp`] (`served_before`), or at all while
124 /// [`crate::Switch::Never`] (`not_serving`): applying it again may succeed later, once
125 /// the deployment caught up or an operator switched to it.
126 pub fn waits_for_switch(&self) -> bool {
127 matches!(self, Error::Status(s) if s.code() == tonic::Code::FailedPrecondition
128 && ["not_caught_up", "not_serving", "served_before"]
129 .iter()
130 .any(|reason| s.message().starts_with(reason)))
131 }
132}
133
134impl fmt::Display for Error {
135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136 match self {
137 Error::Rejected(r) => write!(f, "{} ({})", r.message, r.code),
138 Error::NotSettled(_) => f.write_str(
139 "command committed, but not all listeners have processed its events yet",
140 ),
141 Error::NotDue(id) => write!(
142 f,
143 "command {id} is scheduled and not due yet: ask again after its time"
144 ),
145 Error::Status(s) => write!(f, "{}: {}", s.code(), s.message()),
146 Error::Config(m) => f.write_str(m),
147 Error::Json(e) => write!(f, "JSON: {e}"),
148 Error::Store(e) => write!(f, "store: {e}"),
149 }
150 }
151}
152
153impl std::error::Error for Error {}
154
155impl From<tonic::Status> for Error {
156 fn from(s: tonic::Status) -> Error {
157 Error::Status(s)
158 }
159}
160
161impl From<serde_json::Error> for Error {
162 fn from(e: serde_json::Error) -> Error {
163 Error::Json(e)
164 }
165}
166
167impl From<rusqlite::Error> for Error {
168 fn from(e: rusqlite::Error) -> Error {
169 Error::Store(e)
170 }
171}
172
173impl From<Rejected> for Error {
174 fn from(r: Rejected) -> Error {
175 Error::Rejected(r)
176 }
177}