amethystate_core/primitives/error.rs
1use crate::failure::{Because, StorageError};
2use crate::path::{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 /// Nothing is stored where the write was aimed, and this write only
91 /// changes what is already there.
92 Absent { at: StorePath },
93
94 /// The name handed in cannot be a level, so nothing can sit under it.
95 NotAPath(StorePathError),
96
97 /// The path or the value nests deeper than this store reads back.
98 ///
99 /// `why` is kept whole because the numbers are the diagnosis: which budget
100 /// ran out, what it was, and how much the path had already spent are
101 /// attached to it.
102 TooDeep { at: StorePath, why: Because },
103
104 /// The value will not turn into what the store keeps, with what the codec
105 /// said kept whole.
106 WillNotEncode { at: StorePath, why: Because },
107
108 /// The store has let go of its file, so nothing lands.
109 ///
110 /// No report, because there is never one to keep: every
111 /// [`StorageError::Closed`] is minted fresh at the refusal - the store
112 /// checks whether it is closed and answers - so nothing has failed
113 /// underneath. What the report did carry is the store's own file, and that
114 /// is dropped here rather than lost from somewhere deeper.
115 Closed { at: StorePath },
116
117 /// The field or map this cell views has been dropped. `into_cell` is the
118 /// form that keeps it alive.
119 SourceGone,
120
121 /// The disk, in every sense: the file, the engine, the codec.
122 ///
123 /// Carries the report whole, so the facts attached along the way - the
124 /// key, the table, how many bytes - are still there for whoever wants
125 /// them.
126 Store(Because),
127}
128
129what_the_store_said!(WriteValue);
130
131impl WriteValue {
132 /// The same, for a backend whose failures are its own rather than the
133 /// store's - a client talking to one over a wire. `doing` is the operation
134 /// the wire was carrying, and what the transport said is the frame below.
135 pub fn from_backend<E>(at: &StorePath, doing: StorageError, why: Report<E>) -> Self
136 where
137 E: std::error::Error + Send + Sync + 'static,
138 {
139 Self::from_store(at, why.change_context(doing))
140 }
141}
142
143impl fmt::Display for WriteValue {
144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145 match self {
146 Self::Absent { at } => write!(f, "nothing is stored at {at}"),
147 Self::NotAPath(why) => write!(f, "the write was given no path to land at: {why}"),
148 Self::TooDeep { at, .. } => write!(f, "{at} is deeper than this store reads back"),
149 Self::WillNotEncode { at, .. } => {
150 write!(f, "what was written to {at} will not encode")
151 }
152 Self::Closed { at } => {
153 write!(f, "the store was closed, so nothing was written to {at}")
154 }
155 Self::SourceGone => f.write_str(
156 "the value this cell views is gone: the field or map it came from was dropped",
157 ),
158 Self::Store(why) => write!(f, "{}", why.current_context()),
159 }
160 }
161}
162
163impl fmt::Debug for WriteValue {
164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165 crate::failure::spelled(self, f)
166 }
167}
168
169impl std::error::Error for WriteValue {
170 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
171 match self {
172 Self::NotAPath(why) => Some(why),
173 Self::Store(why) | Self::TooDeep { why, .. } | Self::WillNotEncode { why, .. } => {
174 why.caused().map(|under| under as &dyn std::error::Error)
175 }
176 Self::Absent { .. } | Self::Closed { .. } | Self::SourceGone => None,
177 }
178 }
179}
180
181impl From<StorePathError> for WriteValue {
182 fn from(why: StorePathError) -> Self {
183 Self::NotAPath(why)
184 }
185}
186
187impl From<Report<StorageError>> for WriteValue {
188 fn from(why: Report<StorageError>) -> Self {
189 Self::Store(why.into())
190 }
191}
192
193/// Back into a report, for the plumbing under the boundary.
194///
195/// The sets are what a caller outside the library meets; inside it, everything
196/// still travels as a report, and this is what lets a `?` cross from one to
197/// the other without a `map_err` at every line.
198impl From<WriteValue> for Report<StorageError> {
199 fn from(why: WriteValue) -> Self {
200 match why {
201 WriteValue::Store(report)
202 | WriteValue::TooDeep { why: report, .. }
203 | WriteValue::WillNotEncode { why: report, .. } => report.into_report(),
204 WriteValue::NotAPath(why) => Report::new(why).change_context(StorageError::Path),
205 WriteValue::Closed { at } => {
206 Report::new(StorageError::Closed).attach(crate::facts::Key(at))
207 }
208 WriteValue::Absent { at } => Report::new(StorageError::Read)
209 .attach(crate::facts::Key(at))
210 .attach("nothing is stored there"),
211 WriteValue::SourceGone => Report::new(StorageError::Write)
212 .attach("the field or map this cell viewed was dropped"),
213 }
214 }
215}
216
217pub type WriteResult<T> = Result<T, WriteValue>;
218
219pub type FieldError = WriteValue;
220pub type ReactiveMapError = WriteValue;
221
222pub type ReactiveFieldResult<T> = WriteResult<T>;
223pub type ReactiveMapResult<T> = WriteResult<T>;