Skip to main content

coqui_access_kit/
table.rs

1//! Typed tables a provider reads and writes through, whatever keeps them.
2//!
3//! A [`Table`] is the source of a provider's records: a [`MemoryTable`] built in code, a file
4//! with a codec, a SQL database or an HTTP API are all tables, and the provider cannot tell
5//! them apart. [`Reloading`] caches the latest [`Snapshot`] and refreshes it through
6//! [`Table::changes_since`].
7
8use std::borrow::Cow;
9use std::collections::BTreeSet;
10use std::fmt;
11use std::sync::{Arc, Mutex, PoisonError};
12use std::time::{SystemTime, UNIX_EPOCH};
13
14use coqui_access::error;
15use coqui_access::guatiao::library::ProviderError;
16
17/// Why a table could not answer. Messages never contain record contents or secrets.
18#[derive(Debug, Clone, PartialEq, Eq)]
19#[non_exhaustive]
20pub enum SourceError {
21    /// The table cannot be written: the default of [`Table::put`] and [`Table::remove`].
22    ReadOnly,
23    /// The records or the request are not acceptable: out of bounds, duplicated, malformed.
24    Invalid(String),
25    /// The table could not be reached or read.
26    Unavailable(String),
27}
28
29impl SourceError {
30    /// An [`Invalid`](SourceError::Invalid) error.
31    pub fn invalid(reason: impl Into<String>) -> Self {
32        Self::Invalid(reason.into())
33    }
34
35    /// An [`Unavailable`](SourceError::Unavailable) error.
36    pub fn unavailable(reason: impl Into<String>) -> Self {
37        Self::Unavailable(reason.into())
38    }
39
40    /// What a provider answers when `table` could not be read: always
41    /// `GUATIAO_ERR_INTERNAL`, "could not find out", whatever the reason. The message is
42    /// `<table>: <reason>`.
43    pub fn reading(&self, table: &str) -> ProviderError {
44        error::internal(&format!("{table}: {self}"))
45    }
46
47    /// What a provider answers when `table` refused a change, or could not be opened from a
48    /// configuration: [`ReadOnly`](SourceError::ReadOnly) is `GUATIAO_ERR_UNSUPPORTED`,
49    /// [`Invalid`](SourceError::Invalid) `GUATIAO_ERR_BAD_VALUE`, anything else
50    /// `GUATIAO_ERR_INTERNAL`. The message is `<table>: <reason>`.
51    pub fn writing(&self, table: &str) -> ProviderError {
52        let message = format!("{table}: {self}");
53        match self {
54            Self::ReadOnly => error::unsupported(&message),
55            Self::Invalid(_) => error::bad_value(&message),
56            Self::Unavailable(_) => error::internal(&message),
57        }
58    }
59}
60
61impl fmt::Display for SourceError {
62    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
63        match self {
64            Self::ReadOnly => formatter.write_str("the table is read only"),
65            Self::Invalid(reason) | Self::Unavailable(reason) => formatter.write_str(reason),
66        }
67    }
68}
69
70impl core::error::Error for SourceError {}
71
72/// Which state of a table a [`Snapshot`] is: opaque, compared only for equality, and chosen
73/// by the table. `0` is what a table that never changes may use for ever.
74#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
75pub struct Revision(u64);
76
77impl Revision {
78    /// A revision with this number.
79    pub const fn new(number: u64) -> Self {
80        Self(number)
81    }
82
83    /// The number.
84    pub const fn get(self) -> u64 {
85        self.0
86    }
87}
88
89/// A record a table can find again by name.
90pub trait Keyed {
91    /// What identifies this record in its table: a put with the same key replaces it.
92    /// Borrowed when the record holds it as text, owned when it is written from a value.
93    fn key(&self) -> Cow<'_, str>;
94}
95
96/// All the records of a table at one [`Revision`], in the table's order.
97#[derive(Debug, Clone, PartialEq, Eq)]
98#[non_exhaustive]
99pub struct Snapshot<T> {
100    /// Which state of the table this is.
101    pub revision: Revision,
102    /// The records.
103    pub records: Vec<T>,
104}
105
106impl<T> Snapshot<T> {
107    /// A snapshot of `records` at `revision`.
108    pub fn new(revision: Revision, records: Vec<T>) -> Self {
109        Self { revision, records }
110    }
111}
112
113/// What [`Table::update`] is given to decide a change: the records read, and the record to
114/// put, if any.
115pub type Update<'a, T> = dyn FnMut(&[T]) -> Result<Option<T>, SourceError> + 'a;
116
117/// What [`Table::update_one`] is given to decide a change to one record: that record as the
118/// table holds it (`None` when there is none), and the record to put, if any.
119pub type UpdateOne<'a, T> = dyn FnMut(Option<&T>) -> Result<Option<T>, SourceError> + 'a;
120
121/// Where a provider's records of type `T` come from, and optionally go to.
122///
123/// Implementations are free to keep records anywhere. They must be cheap to ask for changes:
124/// [`Reloading`] calls [`changes_since`](Table::changes_since) on every use.
125pub trait Table<T>: Send + Sync {
126    /// Every record, with the revision they are at.
127    ///
128    /// # Errors
129    ///
130    /// Returns an error when the table cannot be read or its contents are unacceptable.
131    fn load(&self) -> Result<Snapshot<T>, SourceError>;
132
133    /// The records again when the table is no longer at revision `since`, else `None`.
134    ///
135    /// The default loads and compares revisions; a table that can tell cheaply overrides it.
136    ///
137    /// # Errors
138    ///
139    /// As [`load`](Table::load).
140    fn changes_since(&self, since: Revision) -> Result<Option<Snapshot<T>>, SourceError> {
141        let snapshot = self.load()?;
142        Ok((snapshot.revision != since).then_some(snapshot))
143    }
144
145    /// Adds `record`, or replaces the one with the same [`Keyed::key`].
146    ///
147    /// # Errors
148    ///
149    /// [`SourceError::ReadOnly`] by default.
150    fn put(&self, record: T) -> Result<(), SourceError> {
151        let _ = record;
152        Err(SourceError::ReadOnly)
153    }
154
155    /// Removes the record with this key; `true` when there was one.
156    ///
157    /// # Errors
158    ///
159    /// [`SourceError::ReadOnly`] by default.
160    fn remove(&self, key: &str) -> Result<bool, SourceError> {
161        let _ = key;
162        Err(SourceError::ReadOnly)
163    }
164
165    /// Reads the records, lets `make` decide from them what to put (`None` puts nothing),
166    /// and puts it.
167    ///
168    /// A table shared with another process overrides this to hold a lock from the read to
169    /// the write, so `make` always sees the records its result replaces into. The default
170    /// is a read and a put with nothing between them, which is as safe as the table's own
171    /// `put`.
172    ///
173    /// # Errors
174    ///
175    /// When the table cannot be read, `make` refuses, or the put fails
176    /// ([`SourceError::ReadOnly`] for a read-only table).
177    fn update(&self, make: &mut Update<'_, T>) -> Result<(), SourceError> {
178        let snapshot = self.load()?;
179        match make(&snapshot.records)? {
180            Some(record) => self.put(record),
181            None => Ok(()),
182        }
183    }
184
185    /// The record with this key, or `None`.
186    ///
187    /// The default loads every record and picks one, so a table that can find a record by
188    /// its key (a database, an API, a record per file) overrides it: then a record that
189    /// cannot be read is an error for its own key only, and a caller that serves one
190    /// person at a time pays for one record.
191    ///
192    /// # Errors
193    ///
194    /// When the table, or this record, cannot be read.
195    fn get(&self, key: &str) -> Result<Option<T>, SourceError>
196    where
197        T: Keyed,
198    {
199        let snapshot = self.load()?;
200        Ok(snapshot
201            .records
202            .into_iter()
203            .find(|record| record.key() == key))
204    }
205
206    /// Like [`update`](Table::update), for the one record with this key: `make` is given
207    /// that record (or `None`) as the table holds it under its lock, and what it returns is
208    /// put.
209    ///
210    /// The default is [`update`](Table::update) with the other records left out of
211    /// `make`'s view; override it with [`get`](Table::get) to read one record.
212    ///
213    /// # Errors
214    ///
215    /// When the table or this record cannot be read, `make` refuses, or the put fails.
216    fn update_one(&self, key: &str, make: &mut UpdateOne<'_, T>) -> Result<(), SourceError>
217    where
218        T: Keyed,
219    {
220        self.update(&mut |records| make(records.iter().find(|record| record.key() == key)))
221    }
222
223    /// Removes every record `condition` holds for, and answers how many went.
224    ///
225    /// The default loads the records and removes each through [`remove`](Table::remove), a
226    /// write apiece, so a table that rewrites itself on every write overrides it to remove
227    /// them all in one. Nothing matching writes nothing, so a read-only table answers 0.
228    ///
229    /// # Errors
230    ///
231    /// When the table cannot be read or a removal fails ([`SourceError::ReadOnly`] for a
232    /// read-only table holding a matching record).
233    fn remove_where(&self, condition: &mut dyn FnMut(&T) -> bool) -> Result<usize, SourceError>
234    where
235        T: Keyed,
236    {
237        let snapshot = self.load()?;
238        let mut removed = 0;
239        for record in snapshot.records.iter().filter(|record| condition(record)) {
240            if self.remove(&record.key())? {
241                removed += 1;
242            }
243        }
244        Ok(removed)
245    }
246}
247
248/// A table kept in memory, built in code. It is writable and its revision counts the
249/// changes made to it.
250pub struct MemoryTable<T> {
251    state: Mutex<(u64, Vec<T>)>,
252}
253
254impl<T> fmt::Debug for MemoryTable<T> {
255    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
256        formatter
257            .debug_struct("MemoryTable")
258            .finish_non_exhaustive()
259    }
260}
261
262impl<T> Default for MemoryTable<T> {
263    fn default() -> Self {
264        Self::new()
265    }
266}
267
268impl<T> MemoryTable<T> {
269    /// An empty table.
270    pub fn new() -> Self {
271        Self {
272            state: Mutex::new((0, Vec::new())),
273        }
274    }
275
276    /// A table holding `records`, in this order. A key given twice keeps its last record.
277    pub fn from_records(records: impl IntoIterator<Item = T>) -> Self
278    where
279        T: Keyed,
280    {
281        let table = Self::new();
282        {
283            let mut state = table.state.lock().unwrap_or_else(PoisonError::into_inner);
284            for record in records {
285                upsert(&mut state.1, record);
286            }
287        }
288        table
289    }
290}
291
292fn upsert<T: Keyed>(records: &mut Vec<T>, record: T) {
293    match records.iter().position(|had| had.key() == record.key()) {
294        Some(at) => records[at] = record,
295        None => records.push(record),
296    }
297}
298
299impl<T: Keyed + Clone + Send> Table<T> for MemoryTable<T> {
300    fn load(&self) -> Result<Snapshot<T>, SourceError> {
301        let state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
302        Ok(Snapshot::new(Revision::new(state.0), state.1.clone()))
303    }
304
305    fn changes_since(&self, since: Revision) -> Result<Option<Snapshot<T>>, SourceError> {
306        let state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
307        Ok(
308            (state.0 != since.get())
309                .then(|| Snapshot::new(Revision::new(state.0), state.1.clone())),
310        )
311    }
312
313    fn put(&self, record: T) -> Result<(), SourceError> {
314        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
315        upsert(&mut state.1, record);
316        state.0 += 1;
317        Ok(())
318    }
319
320    fn update(&self, make: &mut Update<'_, T>) -> Result<(), SourceError> {
321        // The table stays locked from the read to the write, so two updates never both
322        // decide from the same records.
323        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
324        if let Some(record) = make(&state.1)? {
325            upsert(&mut state.1, record);
326            state.0 += 1;
327        }
328        Ok(())
329    }
330
331    fn get(&self, key: &str) -> Result<Option<T>, SourceError>
332    where
333        T: Keyed,
334    {
335        let state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
336        Ok(state.1.iter().find(|record| record.key() == key).cloned())
337    }
338
339    fn update_one(&self, key: &str, make: &mut UpdateOne<'_, T>) -> Result<(), SourceError>
340    where
341        T: Keyed,
342    {
343        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
344        let current = state.1.iter().find(|record| record.key() == key);
345        if let Some(record) = make(current)? {
346            upsert(&mut state.1, record);
347            state.0 += 1;
348        }
349        Ok(())
350    }
351
352    fn remove(&self, key: &str) -> Result<bool, SourceError> {
353        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
354        let before = state.1.len();
355        state.1.retain(|record| record.key() != key);
356        let removed = state.1.len() < before;
357        if removed {
358            state.0 += 1;
359        }
360        Ok(removed)
361    }
362
363    fn remove_where(&self, condition: &mut dyn FnMut(&T) -> bool) -> Result<usize, SourceError> {
364        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
365        let before = state.1.len();
366        state.1.retain(|record| !condition(record));
367        let removed = before - state.1.len();
368        if removed > 0 {
369            state.0 += 1;
370        }
371        Ok(removed)
372    }
373}
374
375type Validate<T> = Box<dyn Fn(&[T]) -> Result<(), SourceError> + Send + Sync>;
376
377/// A table with its latest [`Snapshot`] cached, refreshed through
378/// [`Table::changes_since`] on every use, so a write by anyone else is seen without
379/// reopening.
380///
381/// Every snapshot is checked with the validation given to [`new`](Reloading::new); a table
382/// that has become unreadable or invalid is an error, never a stale answer.
383pub struct Reloading<T> {
384    table: Arc<dyn Table<T>>,
385    validate: Validate<T>,
386    latest: Mutex<Snapshot<T>>,
387}
388
389impl<T> fmt::Debug for Reloading<T> {
390    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
391        formatter.debug_struct("Reloading").finish_non_exhaustive()
392    }
393}
394
395impl<T: Keyed + Clone> Reloading<T> {
396    /// Loads `table` once, checking it with `validate`.
397    ///
398    /// # Errors
399    ///
400    /// Returns an error when the table cannot be loaded or `validate` refuses it.
401    pub fn new(
402        table: Arc<dyn Table<T>>,
403        validate: impl Fn(&[T]) -> Result<(), SourceError> + Send + Sync + 'static,
404    ) -> Result<Self, SourceError> {
405        let snapshot = table.load()?;
406        validate(&snapshot.records)?;
407        Ok(Self {
408            table,
409            validate: Box::new(validate),
410            latest: Mutex::new(snapshot),
411        })
412    }
413
414    /// Runs `read` over the current records.
415    ///
416    /// # Errors
417    ///
418    /// Returns an error when the table changed and can no longer be read or is invalid.
419    pub fn read<R>(&self, read: impl FnOnce(&[T]) -> R) -> Result<R, SourceError> {
420        let mut latest = self.latest.lock().unwrap_or_else(PoisonError::into_inner);
421        self.refresh(&mut latest)?;
422        Ok(read(&latest.records))
423    }
424
425    /// Makes one record from the current ones and puts it, or puts nothing when `make`
426    /// refuses or the records with it would be invalid.
427    ///
428    /// # Errors
429    ///
430    /// Returns an error when the table cannot be read, `make` refuses, the result is
431    /// invalid, or the table refuses the put ([`SourceError::ReadOnly`] for a read-only
432    /// table).
433    pub fn put_with<R>(
434        &self,
435        make: impl FnOnce(&[T]) -> Result<(T, R), SourceError>,
436    ) -> Result<R, SourceError> {
437        let mut latest = self.latest.lock().unwrap_or_else(PoisonError::into_inner);
438        let mut make = Some(make);
439        let mut made = None;
440        // `make` runs against the records the table read for this update (a file table reads
441        // them under its lock), not against the last snapshot.
442        self.table.update(&mut |records| {
443            (self.validate)(records)?;
444            let Some(make) = make.take() else {
445                return Err(SourceError::invalid("the table asked twice"));
446            };
447            let (record, result) = make(records)?;
448            let mut candidate = records.to_vec();
449            upsert(&mut candidate, record.clone());
450            (self.validate)(&candidate)?;
451            made = Some(result);
452            Ok(Some(record))
453        })?;
454        self.refresh(&mut latest)?;
455        made.ok_or_else(|| SourceError::invalid("the table did not update"))
456    }
457
458    /// The record with `key`, read from the table itself and checked alone: neither the
459    /// cache nor the other records are touched, so a record that cannot be read or fails
460    /// `validate` is an error for its own key only.
461    ///
462    /// # Errors
463    ///
464    /// Returns an error when the table or the record cannot be read, or the record is
465    /// invalid.
466    pub fn get(&self, key: &str) -> Result<Option<T>, SourceError> {
467        let found = self.table.get(key)?;
468        if let Some(record) = &found {
469            (self.validate)(std::slice::from_ref(record))?;
470        }
471        Ok(found)
472    }
473
474    /// Like [`put_with`](Reloading::put_with), for the one record with `key`: `make` is
475    /// given it (or `None`) as the table reads it under its lock, and returns the record to
476    /// put (`None` puts nothing) and a result. Only that record is read and checked, so
477    /// one that cannot be read is an error for its own key only, and the cost does not
478    /// grow with the table.
479    ///
480    /// # Errors
481    ///
482    /// Returns an error when the table or the record cannot be read, `make` refuses, the
483    /// record or the result is invalid or has another key, or the table refuses the put.
484    pub fn update_one<R>(
485        &self,
486        key: &str,
487        make: impl FnOnce(Option<&T>) -> Result<(Option<T>, R), SourceError>,
488    ) -> Result<R, SourceError> {
489        let mut make = Some(make);
490        let mut made = None;
491        self.table.update_one(key, &mut |current| {
492            if let Some(current) = current {
493                (self.validate)(std::slice::from_ref(current))?;
494            }
495            let Some(make) = make.take() else {
496                return Err(SourceError::invalid("the table asked twice"));
497            };
498            let (record, result) = make(current)?;
499            if let Some(record) = &record {
500                if record.key() != key {
501                    return Err(SourceError::invalid("the record is not the one asked for"));
502                }
503                (self.validate)(std::slice::from_ref(record))?;
504            }
505            made = Some(result);
506            Ok(record)
507        })?;
508        made.ok_or_else(|| SourceError::invalid("the table did not update"))
509    }
510
511    /// Removes the record with `key`; `true` when there was one.
512    ///
513    /// # Errors
514    ///
515    /// Returns an error when the table cannot be read or refuses the removal.
516    pub fn remove(&self, key: &str) -> Result<bool, SourceError> {
517        let mut latest = self.latest.lock().unwrap_or_else(PoisonError::into_inner);
518        self.refresh(&mut latest)?;
519        let removed = self.table.remove(key)?;
520        self.refresh(&mut latest)?;
521        Ok(removed)
522    }
523
524    fn refresh(&self, latest: &mut Snapshot<T>) -> Result<(), SourceError> {
525        if let Some(newer) = self.table.changes_since(latest.revision)? {
526            (self.validate)(&newer.records)?;
527            *latest = newer;
528        }
529        Ok(())
530    }
531}
532
533/// Whether `value` may be a record's field: not empty, at most `max_bytes` long, and free of
534/// control characters (which would let a field forge a line in a log or a file).
535pub fn check_field(value: &str, max_bytes: usize) -> bool {
536    !value.is_empty() && value.len() <= max_bytes && !value.chars().any(char::is_control)
537}
538
539/// Now, in whole seconds since the Unix epoch, as records stamp `made_unix` and compare
540/// `expires_unix`; `0` on a clock set before 1970.
541pub fn unix_now() -> i64 {
542    SystemTime::now()
543        .duration_since(UNIX_EPOCH)
544        .ok()
545        .and_then(|since| i64::try_from(since.as_secs()).ok())
546        .unwrap_or_default()
547}
548
549/// Checks that no key is used twice and that there are at most `max` records. A provider's
550/// own validation calls this first.
551///
552/// # Errors
553///
554/// [`SourceError::Invalid`] naming which bound was broken, never the key.
555pub fn check_keys<T: Keyed>(records: &[T], max: usize) -> Result<(), SourceError> {
556    if records.len() > max {
557        return Err(SourceError::invalid("the table holds too many records"));
558    }
559    let mut seen = BTreeSet::new();
560    if records.iter().any(|record| !seen.insert(record.key())) {
561        return Err(SourceError::invalid("a record is duplicated"));
562    }
563    Ok(())
564}
565
566#[cfg(test)]
567mod tests {
568    use std::sync::atomic::{AtomicUsize, Ordering};
569
570    use super::*;
571
572    #[derive(Debug, Clone, PartialEq, Eq)]
573    struct Name(String);
574
575    impl Keyed for Name {
576        fn key(&self) -> Cow<'_, str> {
577            Cow::Borrowed(&self.0)
578        }
579    }
580
581    fn name(text: &str) -> Name {
582        Name(text.to_owned())
583    }
584
585    fn few(records: &[Name]) -> Result<(), SourceError> {
586        check_keys(records, 2)
587    }
588
589    #[test]
590    fn a_memory_table_counts_its_changes_and_reports_them() {
591        let table = MemoryTable::from_records([name("a"), name("a"), name("b")]);
592        let first = table.load().unwrap();
593        assert_eq!(first.records, [name("a"), name("b")]);
594        assert_eq!(table.changes_since(first.revision), Ok(None));
595        table.put(name("c")).unwrap();
596        let second = table.changes_since(first.revision).unwrap().unwrap();
597        assert_eq!(second.records.len(), 3);
598        assert_ne!(second.revision, first.revision);
599        assert!(table.remove("c").unwrap());
600        assert!(!table.remove("c").unwrap());
601        // Removing nothing is not a change.
602        let third = table.load().unwrap();
603        assert!(!table.remove("missing").unwrap());
604        assert_eq!(table.changes_since(third.revision), Ok(None));
605    }
606
607    #[test]
608    fn a_table_that_implements_only_load_is_read_only() {
609        struct Fixed;
610        impl Table<Name> for Fixed {
611            fn load(&self) -> Result<Snapshot<Name>, SourceError> {
612                Ok(Snapshot::new(Revision::new(7), vec![name("a")]))
613            }
614        }
615        assert_eq!(Fixed.changes_since(Revision::new(7)), Ok(None));
616        assert!(Fixed.changes_since(Revision::new(1)).unwrap().is_some());
617        assert_eq!(Fixed.put(name("b")), Err(SourceError::ReadOnly));
618        assert_eq!(Fixed.remove("a"), Err(SourceError::ReadOnly));
619        let reloading = Reloading::new(Arc::new(Fixed), few).unwrap();
620        assert_eq!(reloading.read(<[Name]>::len).unwrap(), 1);
621        assert_eq!(
622            reloading.put_with(|_| Ok((name("b"), ()))),
623            Err(SourceError::ReadOnly)
624        );
625    }
626
627    #[test]
628    fn reloading_sees_writes_made_through_another_handle() {
629        let table = Arc::new(MemoryTable::<Name>::new());
630        let one = Reloading::new(table.clone(), few).unwrap();
631        let other = Reloading::new(table, few).unwrap();
632        assert_eq!(one.read(<[Name]>::len).unwrap(), 0);
633        other.put_with(|_| Ok((name("a"), ()))).unwrap();
634        assert_eq!(one.read(<[Name]>::len).unwrap(), 1);
635        assert!(one.remove("a").unwrap());
636        assert_eq!(other.read(<[Name]>::len).unwrap(), 0);
637    }
638
639    #[test]
640    fn a_refused_put_leaves_the_table_alone() {
641        let table = Arc::new(MemoryTable::<Name>::new());
642        let reloading = Reloading::new(table.clone(), few).unwrap();
643        for text in ["a", "b"] {
644            reloading.put_with(|_| Ok((name(text), ()))).unwrap();
645        }
646        // Over the bound, and refused by the maker.
647        assert!(reloading.put_with(|_| Ok((name("c"), ()))).is_err());
648        assert!(
649            reloading
650                .put_with(|_| Err::<(Name, ()), _>(SourceError::invalid("no")))
651                .is_err()
652        );
653        assert_eq!(table.load().unwrap().records.len(), 2);
654        // Replacing is not growing.
655        reloading.put_with(|_| Ok((name("a"), ()))).unwrap();
656    }
657
658    #[test]
659    fn a_table_that_goes_bad_is_an_error_not_a_stale_answer() {
660        struct Flaky(AtomicUsize);
661        impl Table<Name> for Flaky {
662            fn load(&self) -> Result<Snapshot<Name>, SourceError> {
663                match self.0.fetch_add(1, Ordering::SeqCst) {
664                    0 => Ok(Snapshot::new(Revision::new(1), vec![name("a")])),
665                    1 => Err(SourceError::unavailable("gone")),
666                    _ => Ok(Snapshot::new(Revision::new(3), vec![name("a"), name("a")])),
667                }
668            }
669        }
670        let reloading = Reloading::new(Arc::new(Flaky(AtomicUsize::new(0))), few).unwrap();
671        assert!(matches!(
672            reloading.read(|_| ()),
673            Err(SourceError::Unavailable(_))
674        ));
675        assert!(matches!(
676            reloading.read(|_| ()),
677            Err(SourceError::Invalid(_))
678        ));
679    }
680
681    #[test]
682    fn a_table_error_becomes_the_status_a_host_acts_on() {
683        use coqui_access::guatiao::Status;
684
685        let read_only = SourceError::ReadOnly;
686        let invalid = SourceError::invalid("a record is duplicated");
687        let gone = SourceError::unavailable("file cannot be read");
688        for error in [&read_only, &invalid, &gone] {
689            let read = error.reading("account table");
690            assert_eq!(read.status, Status::GUATIAO_ERR_INTERNAL);
691            assert_eq!(&*read.message, format!("account table: {error}"));
692        }
693        assert_eq!(
694            read_only.writing("t").status,
695            Status::GUATIAO_ERR_UNSUPPORTED
696        );
697        assert_eq!(invalid.writing("t").status, Status::GUATIAO_ERR_BAD_VALUE);
698        assert_eq!(gone.writing("t").status, Status::GUATIAO_ERR_INTERNAL);
699        assert_eq!(&*invalid.writing("t").message, "t: a record is duplicated");
700    }
701
702    #[test]
703    fn a_field_is_bounded_non_empty_and_has_no_control_characters() {
704        assert!(check_field("alice", 5));
705        assert!(!check_field("alice", 4));
706        assert!(!check_field("", 5));
707        assert!(!check_field("a\nb", 5));
708        assert!(!check_field("a\u{7f}", 5));
709        assert!(check_field("é", 2));
710        assert!(unix_now() > 1_700_000_000);
711    }
712
713    #[test]
714    fn a_table_invalid_at_the_start_is_not_opened() {
715        let table = Arc::new(MemoryTable::from_records([name("a"), name("b"), name("c")]));
716        assert!(Reloading::new(table, few).is_err());
717    }
718
719    #[test]
720    fn one_record_is_read_and_updated_by_its_key() {
721        let table = MemoryTable::from_records([name("a"), name("b")]);
722        assert_eq!(table.get("b").unwrap(), Some(name("b")));
723        assert_eq!(table.get("z").unwrap(), None);
724        let mut seen = Vec::new();
725        table
726            .update_one("a", &mut |current| {
727                seen.push(current.cloned());
728                Ok(Some(name("a")))
729            })
730            .unwrap();
731        assert_eq!(seen, [Some(name("a"))]);
732        assert_eq!(table.load().unwrap().revision, Revision::new(1));
733    }
734
735    #[test]
736    fn the_defaults_find_one_record_through_load_and_update() {
737        struct Plain(MemoryTable<Name>);
738        impl Table<Name> for Plain {
739            fn load(&self) -> Result<Snapshot<Name>, SourceError> {
740                self.0.load()
741            }
742            fn put(&self, record: Name) -> Result<(), SourceError> {
743                self.0.put(record)
744            }
745        }
746        let table = Plain(MemoryTable::from_records([name("a"), name("b")]));
747        assert_eq!(table.get("a").unwrap(), Some(name("a")));
748        let mut seen = None;
749        table
750            .update_one("b", &mut |current| {
751                seen = Some(current.cloned());
752                Ok(Some(name("b")))
753            })
754            .unwrap();
755        assert_eq!(seen, Some(Some(name("b"))));
756    }
757
758    #[test]
759    fn remove_where_takes_every_match_in_one_change_or_one_remove_apiece() {
760        let table = MemoryTable::from_records([name("a1"), name("b"), name("a2")]);
761        let before = table.load().unwrap().revision;
762        let removed = table
763            .remove_where(&mut |record| record.0.starts_with('a'))
764            .unwrap();
765        assert_eq!(removed, 2);
766        let after = table.load().unwrap();
767        assert_eq!(after.records, [name("b")]);
768        assert_eq!(after.revision.get(), before.get() + 1, "one change");
769        assert_eq!(table.remove_where(&mut |_| false).unwrap(), 0);
770        assert_eq!(table.load().unwrap().revision, after.revision);
771
772        // The default removes through `remove`; with nothing matching it writes nothing.
773        struct Removing(MemoryTable<Name>, AtomicUsize);
774        impl Table<Name> for Removing {
775            fn load(&self) -> Result<Snapshot<Name>, SourceError> {
776                self.0.load()
777            }
778            fn remove(&self, key: &str) -> Result<bool, SourceError> {
779                self.1.fetch_add(1, Ordering::SeqCst);
780                self.0.remove(key)
781            }
782        }
783        let table = Removing(
784            MemoryTable::from_records([name("a1"), name("b"), name("a2")]),
785            AtomicUsize::new(0),
786        );
787        assert_eq!(
788            table.remove_where(&mut |record| record.0 == "c").unwrap(),
789            0
790        );
791        assert_eq!(table.1.load(Ordering::SeqCst), 0);
792        let removed = table
793            .remove_where(&mut |record| record.0.starts_with('a'))
794            .unwrap();
795        assert_eq!((removed, table.1.load(Ordering::SeqCst)), (2, 2));
796        assert_eq!(table.load().unwrap().records, [name("b")]);
797    }
798
799    #[test]
800    fn reloading_checks_only_the_one_record_it_reads() {
801        let table = Arc::new(MemoryTable::from_records([name("a"), name("b")]));
802        let reloading = Reloading::new(table.clone(), |records| {
803            if records.iter().any(|record| record.0 == "bad") {
804                Err(SourceError::invalid("a record is invalid"))
805            } else {
806                Ok(())
807            }
808        })
809        .unwrap();
810        table.put(name("bad")).unwrap();
811        assert!(reloading.read(|_| ()).is_err());
812        assert_eq!(reloading.get("a").unwrap(), Some(name("a")));
813        assert!(reloading.get("bad").is_err());
814        let put = reloading
815            .update_one("b", |current| {
816                assert_eq!(current, Some(&name("b")));
817                Ok((Some(name("b")), 7))
818            })
819            .unwrap();
820        assert_eq!(put, 7);
821        assert!(
822            reloading
823                .update_one("b", |_| Ok((Some(name("other")), ())))
824                .is_err()
825        );
826    }
827}