amethystate_core/primitives/error.rs
1use crate::failure::{Because, StorageError};
2use crate::path::{SmolStr, StorePath, StorePathError};
3use error_stack::Report;
4use std::fmt;
5
6/// Writes the two halves every write-error model spells the same way, for an
7/// enum carrying `TooDeep`, `WillNotEncode`, `Closed` and `Store`.
8///
9/// The four are shared because the decision is: a caller acts differently on a
10/// depth budget, on a codec, and on a store that has let go of its file, and
11/// everything else travels whole so the facts attached along the way survive.
12/// Only the outermost context is read, and it becomes a type rather than
13/// something to downcast.
14///
15/// A model's own variants sit beside these and are not touched - a path that
16/// would not parse, a place a declaration owns, a source that is gone. What
17/// this settles is that a new [`StorageError`] cannot be told apart in one
18/// model and not in the other.
19///
20/// The caller needs `Report`, `StorageError`, `StorePath` and `Because` in
21/// scope, which is what any such model already imports.
22#[macro_export]
23macro_rules! what_the_store_said {
24 ($ty:ident) => {
25 impl $ty {
26 /// What the store said, told apart where a caller would act on it
27 /// differently.
28 pub fn from_store(
29 at: &$crate::path::StorePath,
30 why: ::error_stack::Report<$crate::failure::StorageError>,
31 ) -> Self {
32 match *why.current_context() {
33 $crate::failure::StorageError::Depth => Self::TooDeep {
34 at: at.clone(),
35 why: why.into(),
36 },
37 $crate::failure::StorageError::Codec => Self::WillNotEncode {
38 at: at.clone(),
39 why: why.into(),
40 },
41 $crate::failure::StorageError::Closed => Self::Closed { at: at.clone() },
42 _ => Self::Store(why.into()),
43 }
44 }
45
46 /// The whole report as a string, facts and all, for a caller
47 /// handing this to `anyhow`: `.context(why.explain())`.
48 ///
49 /// The chain [`source`](std::error::Error::source) walks is the
50 /// readable half and is usually enough. This is the rest of it -
51 /// every frame, every attachment, laid out the way the report
52 /// renders itself - for a log record that has to carry everything.
53 pub fn explain(&self) -> String {
54 match self {
55 Self::Store(why)
56 | Self::TooDeep { why, .. }
57 | Self::WillNotEncode { why, .. } => why.explain(),
58 other => other.to_string(),
59 }
60 }
61 }
62 };
63}
64
65/// Everything a write through a reactive primitive can fail with, and nothing
66/// else.
67///
68/// Fields, cells and maps fail in the same ways, so they share one set; the
69/// per-primitive names below are aliases kept for readability at call sites.
70///
71/// Ordinary [`std::error::Error`], so a caller who does not want to look can
72/// `?` it into `anyhow`, `eyre` or a `Box<dyn Error>` and be done - and get the
73/// whole diagnosis out of it. [`Display`](fmt::Display) says what this write
74/// was and where; [`source`](std::error::Error::source) descends through the
75/// contexts under it, each carrying what was attached to it, so a
76/// `{:?}` of an `anyhow::Error` names the operation, the key, the file and the
77/// engine's own words without a `match` anywhere.
78///
79/// A caller who wants a fact as a type rather than as a sentence reads it back
80/// with [`facts::all`](crate::facts::all) over the report the variant carries -
81/// `facts::all::<StoreFile, _>(why)` for the file, `Key` for the key. That is
82/// the typed way in; the chain is the readable one.
83///
84/// `{:?}` prints the same thing `anyhow` prints, because that is the shape a
85/// reader has learnt: `fn main() -> anyhow::Result<()>` renders with `Debug`,
86/// and so does every `tracing::error!("{err:?}")`. What the report holds beyond
87/// the chain - the frame each context was raised at - is in
88/// [`explain`](Self::explain), which is where a dump belongs.
89pub enum WriteValue {
90 /// An interceptor turned the change down, in its own words.
91 Intercepted { at: StorePath, said: SmolStr },
92
93 /// Interceptors wrote back into the value they guard, nested deeper than
94 /// a write may go, and the guard stopped them.
95 ///
96 /// Nothing turned the change down - a rule that refuses is
97 /// [`Intercepted`](Self::Intercepted). This is a loop in the interceptors
98 /// themselves.
99 Recursed { at: StorePath },
100
101 /// Nothing is stored where the write was aimed, and this write only
102 /// changes what is already there.
103 Absent { at: StorePath },
104
105 /// The name handed in cannot be a level, so nothing can sit under it.
106 NotAPath(StorePathError),
107
108 /// The path or the value nests deeper than this store reads back.
109 ///
110 /// `why` is kept whole because the numbers are the diagnosis: which budget
111 /// ran out, what it was, and how much the path had already spent are
112 /// attached to it.
113 TooDeep { at: StorePath, why: Because },
114
115 /// The value will not turn into what the store keeps, with what the codec
116 /// said kept whole.
117 WillNotEncode { at: StorePath, why: Because },
118
119 /// The store has let go of its file, so nothing lands.
120 ///
121 /// No report, because there is never one to keep: every
122 /// [`StorageError::Closed`] is minted fresh at the refusal - the store
123 /// checks whether it is closed and answers - so nothing has failed
124 /// underneath. What the report did carry is the store's own file, and that
125 /// is dropped here rather than lost from somewhere deeper.
126 Closed { at: StorePath },
127
128 /// The field or map this cell views has been dropped. `into_cell` is the
129 /// form that keeps it alive.
130 SourceGone,
131
132 /// The disk, in every sense: the file, the engine, the codec.
133 ///
134 /// Carries the report whole, so the facts attached along the way - the
135 /// key, the table, how many bytes - are still there for whoever wants
136 /// them.
137 Store(Because),
138}
139
140what_the_store_said!(WriteValue);
141
142impl WriteValue {
143 /// The same, for a backend whose failures are its own rather than the
144 /// store's - a client talking to one over a wire. `doing` is the operation
145 /// the wire was carrying, and what the transport said is the frame below.
146 pub fn from_backend<E>(at: &StorePath, doing: StorageError, why: Report<E>) -> Self
147 where
148 E: std::error::Error + Send + Sync + 'static,
149 {
150 Self::from_store(at, why.change_context(doing))
151 }
152
153 /// The refusal an interceptor gave.
154 pub fn intercepted(at: &StorePath, said: impl AsRef<str>) -> Self {
155 Self::Intercepted {
156 at: at.clone(),
157 said: SmolStr::new(said.as_ref()),
158 }
159 }
160
161 /// What running a change past its interceptors refused, as a write's
162 /// failure.
163 pub fn refused(at: &StorePath, refusal: crate::primitives::intercept::Refusal) -> Self {
164 use crate::primitives::intercept::Refusal;
165
166 match refusal {
167 Refusal::Said(said) => Self::intercepted(at, said),
168 Refusal::Recursed => Self::Recursed { at: at.clone() },
169 }
170 }
171}
172
173impl fmt::Display for WriteValue {
174 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175 match self {
176 Self::Intercepted { at, said } => {
177 write!(f, "an interceptor turned down the write to {at}: {said}")
178 }
179 Self::Recursed { at } => write!(
180 f,
181 "interceptors wrote back into {at} deeper than a write may nest, so nothing was \
182 written"
183 ),
184 Self::Absent { at } => write!(f, "nothing is stored at {at}"),
185 Self::NotAPath(why) => write!(f, "the write was given no path to land at: {why}"),
186 Self::TooDeep { at, .. } => write!(f, "{at} is deeper than this store reads back"),
187 Self::WillNotEncode { at, .. } => {
188 write!(f, "what was written to {at} will not encode")
189 }
190 Self::Closed { at } => {
191 write!(f, "the store was closed, so nothing was written to {at}")
192 }
193 Self::SourceGone => f.write_str(
194 "the value this cell views is gone: the field or map it came from was dropped",
195 ),
196 Self::Store(why) => write!(f, "{}", why.current_context()),
197 }
198 }
199}
200
201impl fmt::Debug for WriteValue {
202 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
203 crate::failure::spelled(self, f)
204 }
205}
206
207impl std::error::Error for WriteValue {
208 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
209 match self {
210 Self::NotAPath(why) => Some(why),
211 Self::Store(why) | Self::TooDeep { why, .. } | Self::WillNotEncode { why, .. } => {
212 why.caused().map(|under| under as &dyn std::error::Error)
213 }
214 Self::Intercepted { .. }
215 | Self::Recursed { .. }
216 | Self::Absent { .. }
217 | Self::Closed { .. }
218 | Self::SourceGone => None,
219 }
220 }
221}
222
223impl From<StorePathError> for WriteValue {
224 fn from(why: StorePathError) -> Self {
225 Self::NotAPath(why)
226 }
227}
228
229impl From<Report<StorageError>> for WriteValue {
230 fn from(why: Report<StorageError>) -> Self {
231 Self::Store(why.into())
232 }
233}
234
235/// Back into a report, for the plumbing under the boundary.
236///
237/// The sets are what a caller outside the library meets; inside it, everything
238/// still travels as a report, and this is what lets a `?` cross from one to
239/// the other without a `map_err` at every line.
240impl From<WriteValue> for Report<StorageError> {
241 fn from(why: WriteValue) -> Self {
242 match why {
243 WriteValue::Store(report)
244 | WriteValue::TooDeep { why: report, .. }
245 | WriteValue::WillNotEncode { why: report, .. } => report.into_report(),
246 WriteValue::NotAPath(why) => Report::new(why).change_context(StorageError::Path),
247 WriteValue::Closed { at } => {
248 Report::new(StorageError::Closed).attach(crate::facts::Key(at))
249 }
250 WriteValue::Absent { at } => Report::new(StorageError::Read)
251 .attach(crate::facts::Key(at))
252 .attach("nothing is stored there"),
253 WriteValue::Intercepted { at, said } => Report::new(StorageError::Write)
254 .attach(crate::facts::Key(at))
255 .attach(format!("an interceptor turned it down: {said}")),
256 WriteValue::Recursed { at } => Report::new(StorageError::Write)
257 .attach(crate::facts::Key(at))
258 .attach("interceptors wrote back into it deeper than a write may nest"),
259 WriteValue::SourceGone => Report::new(StorageError::Write)
260 .attach("the field or map this cell viewed was dropped"),
261 }
262 }
263}
264
265pub type WriteResult<T> = Result<T, WriteValue>;
266
267pub type FieldError = WriteValue;
268pub type ReactiveMapError = WriteValue;
269
270pub type ReactiveFieldResult<T> = WriteResult<T>;
271pub type ReactiveMapResult<T> = WriteResult<T>;