1use 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#[derive(Debug, Clone, PartialEq, Eq)]
19#[non_exhaustive]
20pub enum SourceError {
21 ReadOnly,
23 Invalid(String),
25 Unavailable(String),
27}
28
29impl SourceError {
30 pub fn invalid(reason: impl Into<String>) -> Self {
32 Self::Invalid(reason.into())
33 }
34
35 pub fn unavailable(reason: impl Into<String>) -> Self {
37 Self::Unavailable(reason.into())
38 }
39
40 pub fn reading(&self, table: &str) -> ProviderError {
44 error::internal(&format!("{table}: {self}"))
45 }
46
47 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
75pub struct Revision(u64);
76
77impl Revision {
78 pub const fn new(number: u64) -> Self {
80 Self(number)
81 }
82
83 pub const fn get(self) -> u64 {
85 self.0
86 }
87}
88
89pub trait Keyed {
91 fn key(&self) -> Cow<'_, str>;
94}
95
96#[derive(Debug, Clone, PartialEq, Eq)]
98#[non_exhaustive]
99pub struct Snapshot<T> {
100 pub revision: Revision,
102 pub records: Vec<T>,
104}
105
106impl<T> Snapshot<T> {
107 pub fn new(revision: Revision, records: Vec<T>) -> Self {
109 Self { revision, records }
110 }
111}
112
113pub type Update<'a, T> = dyn FnMut(&[T]) -> Result<Option<T>, SourceError> + 'a;
116
117pub type UpdateOne<'a, T> = dyn FnMut(Option<&T>) -> Result<Option<T>, SourceError> + 'a;
120
121pub trait Table<T>: Send + Sync {
126 fn load(&self) -> Result<Snapshot<T>, SourceError>;
132
133 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 fn put(&self, record: T) -> Result<(), SourceError> {
151 let _ = record;
152 Err(SourceError::ReadOnly)
153 }
154
155 fn remove(&self, key: &str) -> Result<bool, SourceError> {
161 let _ = key;
162 Err(SourceError::ReadOnly)
163 }
164
165 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 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 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 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
248pub 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 pub fn new() -> Self {
271 Self {
272 state: Mutex::new((0, Vec::new())),
273 }
274 }
275
276 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 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
377pub 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 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 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 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 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 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 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 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
533pub 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
539pub 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
549pub 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 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 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 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 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}