amethystate 0.23.0

A state manager for Rust applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! Why a read would not answer.

use crate::store::StorageError;
use amethystate_core::failure::{Because, spelled};
use amethystate_core::path::{StorePath, StorePathError};
use error_stack::Report;
use std::fmt;
use std::sync::Arc;

/// What stopped a value from being read back.
pub enum ReadValue {
    /// The levels handed in do not make a path.
    NotAPath(StorePathError),

    /// Something is stored there, and it is not the type that was asked for.
    ///
    /// `why` is kept whole because what the codec choked on - the type asked
    /// for, the bytes it found, how many of them - is attached to it.
    WillNotRead { at: StorePath, why: Because },

    /// The store has let go of its file, so it answers nothing.
    ///
    /// No report: every [`StorageError::Closed`] is minted where the refusal
    /// is, so nothing has failed underneath it.
    Closed { at: StorePath },

    /// The disk, in every sense: the file, the engine, the codec.
    Store(Because),
}

impl ReadValue {
    /// What the store said, told apart where a caller would act on it
    /// differently.
    ///
    /// A codec's refusal is a frame *under* the operation's rather than the
    /// outermost one - a read that found the wrong type says `Read` on top and
    /// `Codec` below - so this asks
    /// [`will_not_read`](crate::store::will_not_read), which is the one place
    /// that difference is decided.
    pub fn from_store(at: &StorePath, why: Report<StorageError>) -> Self {
        if *why.current_context() == StorageError::Closed {
            return Self::Closed { at: at.clone() };
        }

        match crate::store::rules::will_not_read(&why) {
            true => Self::WillNotRead {
                at: at.clone(),
                why: why.into(),
            },
            false => Self::Store(why.into()),
        }
    }

    /// The whole report as a string, facts and all.
    pub fn explain(&self) -> String {
        match self {
            Self::Store(why) | Self::WillNotRead { why, .. } => why.explain(),
            other => other.to_string(),
        }
    }
}

impl fmt::Display for ReadValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotAPath(why) => write!(f, "the read was given no path to look at: {why}"),
            Self::WillNotRead { at, .. } => {
                write!(f, "what is stored at {at} will not read back")
            }
            Self::Closed { at } => write!(f, "the store was closed, so {at} was not read"),
            Self::Store(why) => write!(f, "{}", why.current_context()),
        }
    }
}

impl fmt::Debug for ReadValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        spelled(self, f)
    }
}

impl std::error::Error for ReadValue {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::NotAPath(why) => Some(why),
            Self::Store(why) | Self::WillNotRead { why, .. } => {
                why.caused().map(|under| under as &dyn std::error::Error)
            }
            Self::Closed { .. } => None,
        }
    }
}

impl From<StorePathError> for ReadValue {
    fn from(why: StorePathError) -> Self {
        Self::NotAPath(why)
    }
}

impl From<Report<StorageError>> for ReadValue {
    fn from(why: Report<StorageError>) -> Self {
        Self::Store(why.into())
    }
}

impl From<ReadValue> for Report<StorageError> {
    fn from(why: ReadValue) -> Self {
        match why {
            ReadValue::Store(report) | ReadValue::WillNotRead { why: report, .. } => {
                report.into_report()
            }
            ReadValue::NotAPath(why) => Report::new(why).change_context(StorageError::Path),
            ReadValue::Closed { at } => {
                Report::new(StorageError::Closed).attach(amethystate_core::facts::Key(at))
            }
        }
    }
}

/// What stopped a listing from coming back.
pub enum ScanKeys {
    /// The levels handed in do not make a prefix.
    NotAPath(StorePathError),

    /// A key on disk will not read back as a path.
    ///
    /// Reachable only where something other than this library wrote it, so
    /// `why` carries the key as it sits on disk - which is the only state it
    /// is in when the reason for the failure is that it is not a path.
    KeyWillNotRead { under: StorePath, why: Because },

    /// The store has let go of its file, so there is nothing to list.
    ///
    /// No report: every [`StorageError::Closed`] is minted where the refusal
    /// is, so nothing has failed underneath it.
    Closed { under: StorePath },

    /// The disk, in every sense.
    Store(Because),
}

impl ScanKeys {
    /// What the store said, told apart where a caller would act on it
    /// differently.
    pub fn from_store(under: &StorePath, why: Report<StorageError>) -> Self {
        match *why.current_context() {
            StorageError::Path => Self::KeyWillNotRead {
                under: under.clone(),
                why: why.into(),
            },
            StorageError::Closed => Self::Closed {
                under: under.clone(),
            },
            _ => Self::Store(why.into()),
        }
    }

    /// The whole report as a string, facts and all.
    pub fn explain(&self) -> String {
        match self {
            Self::Store(why) | Self::KeyWillNotRead { why, .. } => why.explain(),
            other => other.to_string(),
        }
    }
}

impl fmt::Display for ScanKeys {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotAPath(why) => write!(f, "the scan was given no prefix to list: {why}"),
            Self::KeyWillNotRead { under, .. } => {
                write!(f, "a key stored under {under} will not read back as a path")
            }
            Self::Closed { under } => {
                write!(f, "the store was closed, so {under} was not listed")
            }
            Self::Store(why) => write!(f, "{}", why.current_context()),
        }
    }
}

impl fmt::Debug for ScanKeys {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        spelled(self, f)
    }
}

impl std::error::Error for ScanKeys {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::NotAPath(why) => Some(why),
            Self::Store(why) | Self::KeyWillNotRead { why, .. } => {
                why.caused().map(|under| under as &dyn std::error::Error)
            }
            Self::Closed { .. } => None,
        }
    }
}

impl From<StorePathError> for ScanKeys {
    fn from(why: StorePathError) -> Self {
        Self::NotAPath(why)
    }
}

impl From<Report<StorageError>> for ScanKeys {
    fn from(why: Report<StorageError>) -> Self {
        Self::Store(why.into())
    }
}

impl From<ScanKeys> for Report<StorageError> {
    fn from(why: ScanKeys) -> Self {
        match why {
            ScanKeys::Store(report) | ScanKeys::KeyWillNotRead { why: report, .. } => {
                report.into_report()
            }
            ScanKeys::NotAPath(why) => Report::new(why).change_context(StorageError::Path),
            ScanKeys::Closed { under } => {
                Report::new(StorageError::Closed).attach(amethystate_core::facts::Prefix(under))
            }
        }
    }
}

pub type ReadResult<T> = Result<T, ReadValue>;
pub type ScanResult<T> = Result<T, ScanKeys>;

/// What stopped a map from being read back whole.
///
/// Its own set rather than [`OpenStruct`](crate::store::OpenStruct): a map is
/// opened over what is already under it, so it meets two failures nothing else
/// can - a stored key that is not one of its entries, and an entry whose name
/// will not read as its key type.
pub enum LoadMap {
    /// The levels handed in do not make a path.
    NotAPath(StorePathError),

    /// Another declaration already owns that place.
    Taken(Box<crate::store::places::Taken>),

    /// A key under the map is not one of its entries.
    ///
    /// A map owns the level below it and nothing further, so a key deeper than
    /// that belongs to whatever claimed that level. `stored` is the key as it
    /// sits on disk, which is the only state it is in when the reason for the
    /// failure is where it sits.
    KeyIsNotAnEntry {
        under: StorePath,
        stored: Arc<str>,
        said: Arc<str>,
    },

    /// An entry's name will not read back as the map's key type.
    KeyWillNotRead {
        under: StorePath,
        entry: Arc<str>,
        wanted: &'static str,
    },

    /// An entry's value will not read back as the map's value type.
    EntryWillNotRead { at: StorePath, why: Because },

    /// The store has let go of its file.
    ///
    /// No report: every [`StorageError::Closed`] is minted where the refusal
    /// is, so nothing has failed underneath it.
    Closed { under: StorePath },

    /// The disk, in every sense.
    Store(Because),
}

impl LoadMap {
    /// What the store said, told apart where a caller would act on it
    /// differently.
    pub fn from_store(at: &StorePath, why: Report<StorageError>) -> Self {
        if *why.current_context() == StorageError::Closed {
            return Self::Closed { under: at.clone() };
        }

        match crate::store::rules::will_not_read(&why) {
            true => Self::EntryWillNotRead {
                at: at.clone(),
                why: why.into(),
            },
            false => Self::Store(why.into()),
        }
    }

    /// The whole report as a string, facts and all.
    pub fn explain(&self) -> String {
        match self {
            Self::Store(why) | Self::EntryWillNotRead { why, .. } => why.explain(),
            other => other.to_string(),
        }
    }
}

impl fmt::Display for LoadMap {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotAPath(why) => write!(f, "the map was given no path to sit at: {why}"),
            Self::Taken(taken) => write!(f, "{taken}"),
            Self::KeyIsNotAnEntry {
                under,
                stored,
                said,
            } => write!(f, "`{stored}` is not an entry of {under}: {said}"),
            Self::KeyWillNotRead {
                under,
                entry,
                wanted,
            } => write!(f, "`{entry}` under {under} will not read as a {wanted}"),
            Self::EntryWillNotRead { at, .. } => {
                write!(f, "the entry at {at} will not read back")
            }
            Self::Closed { under } => {
                write!(f, "the store was closed, so {under} was not read")
            }
            Self::Store(why) => write!(f, "{}", why.current_context()),
        }
    }
}

impl fmt::Debug for LoadMap {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        spelled(self, f)
    }
}

impl std::error::Error for LoadMap {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::NotAPath(why) => Some(why),
            Self::Store(why) | Self::EntryWillNotRead { why, .. } => {
                why.caused().map(|under| under as &dyn std::error::Error)
            }
            Self::Taken(_)
            | Self::KeyIsNotAnEntry { .. }
            | Self::KeyWillNotRead { .. }
            | Self::Closed { .. } => None,
        }
    }
}

impl From<StorePathError> for LoadMap {
    fn from(why: StorePathError) -> Self {
        Self::NotAPath(why)
    }
}

impl From<Report<StorageError>> for LoadMap {
    fn from(why: Report<StorageError>) -> Self {
        Self::Store(why.into())
    }
}

impl From<Box<crate::store::places::Taken>> for LoadMap {
    fn from(taken: Box<crate::store::places::Taken>) -> Self {
        Self::Taken(taken)
    }
}

/// A write that would not land while the map was being built - seeding its
/// declared defaults is the one that reaches here.
impl From<amethystate_core::primitives::error::WriteValue> for LoadMap {
    fn from(why: amethystate_core::primitives::error::WriteValue) -> Self {
        Self::Store(Report::<StorageError>::from(why).into())
    }
}

impl From<LoadMap> for Report<StorageError> {
    fn from(why: LoadMap) -> Self {
        match why {
            LoadMap::Store(report) | LoadMap::EntryWillNotRead { why: report, .. } => {
                report.into_report()
            }
            LoadMap::NotAPath(why) => Report::new(why).change_context(StorageError::Path),
            LoadMap::Taken(taken) => crate::store::places::refused(&taken),
            LoadMap::KeyIsNotAnEntry {
                under,
                stored,
                said,
            } => Report::new(StorageError::Path)
                .attach(amethystate_core::facts::Prefix(under))
                .attach(amethystate_core::facts::RawKey(stored.to_string()))
                .attach(said.to_string()),
            LoadMap::KeyWillNotRead {
                under,
                entry,
                wanted,
            } => Report::new(StorageError::Codec)
                .attach(amethystate_core::facts::Prefix(under))
                .attach(amethystate_core::facts::Entry(entry.to_string()))
                .attach(format!("key type: {wanted}")),
            LoadMap::Closed { under } => {
                Report::new(StorageError::Closed).attach(amethystate_core::facts::Prefix(under))
            }
        }
    }
}

/// A map that would not load stopped a struct from opening.
impl From<LoadMap> for crate::store::OpenStruct {
    fn from(why: LoadMap) -> Self {
        match why {
            LoadMap::NotAPath(why) => Self::NotAPath(why),
            LoadMap::Taken(taken) => Self::Taken(taken),
            LoadMap::EntryWillNotRead { at, why } => Self::WillNotRead { at, why },
            other => Self::Store(Report::<StorageError>::from(other).into()),
        }
    }
}

pub type LoadMapResult<T> = Result<T, LoadMap>;