Skip to main content

coqui_access_kit/file/
table.rs

1//! A [`Table`] kept in one private file, in whatever serde format the caller supplies.
2
3use core::cell::Cell;
4use core::fmt;
5use core::marker::PhantomData;
6use std::fs::{File, OpenOptions};
7use std::path::{Path, PathBuf};
8use std::sync::{Mutex, PoisonError};
9
10use coqui_access::guatiao::{FromWalk, Walk};
11use guatiao_serde::{BridgeError, Presentation, Walked, from_deserializer};
12use serde::Serialize;
13use serde::de::{self, DeserializeSeed, Deserializer, MapAccess, SeqAccess, Visitor};
14use serde::ser::{SerializeMap, SerializeSeq, Serializer};
15
16use super::{Stamp, read_bounded, stamp, write_private};
17use crate::table::{Keyed, Revision, Snapshot, SourceError, Table, Update};
18
19/// The most a table file may hold unless [`FileTable::max_bytes`] says otherwise: 1 MiB.
20pub const DEFAULT_MAX_BYTES: usize = 1024 * 1024;
21
22/// How many times a file that changes under a read is read again.
23const READS: usize = 8;
24
25/// A format refused a document. It carries nothing of the document, which may hold secrets.
26#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
27#[non_exhaustive]
28pub struct CodecError;
29
30impl CodecError {
31    /// The error a [`Codec`] answers for any refusal.
32    pub const fn new() -> Self {
33        Self
34    }
35}
36
37impl fmt::Display for CodecError {
38    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
39        formatter.write_str("the format refused the document")
40    }
41}
42
43impl core::error::Error for CodecError {}
44
45/// A serde text format a [`FileTable`] keeps its records in. The kit names no format: the
46/// caller implements this over the format crate it picks.
47///
48/// ```
49/// use coqui_access_kit::file::{Codec, CodecError};
50/// use serde::Serialize;
51/// use serde::de::DeserializeSeed;
52///
53/// struct Json;
54///
55/// impl Codec for Json {
56///     fn name(&self) -> &'static str {
57///         "JSON"
58///     }
59///
60///     fn write<D: Serialize + ?Sized>(&self, document: &D) -> Result<String, CodecError> {
61///         serde_json::to_string_pretty(document).map_err(|_| CodecError::new())
62///     }
63///
64///     fn read<'de, S: DeserializeSeed<'de>>(
65///         &self,
66///         text: &'de str,
67///         seed: S,
68///     ) -> Result<S::Value, CodecError> {
69///         let mut deserializer = serde_json::Deserializer::from_str(text);
70///         let read = seed.deserialize(&mut deserializer).map_err(|_| CodecError::new())?;
71///         deserializer.end().map_err(|_| CodecError::new())?;
72///         Ok(read)
73///     }
74/// }
75/// ```
76pub trait Codec: Send + Sync {
77    /// The format's name, as an error message shows it: `TOML`, `JSON`.
78    fn name(&self) -> &'static str;
79
80    /// How bytes and numbers are spelled in this format. Default [`Presentation::new`].
81    fn presentation(&self) -> Presentation {
82        Presentation::new()
83    }
84
85    /// Writes `document` as text.
86    ///
87    /// # Errors
88    ///
89    /// [`CodecError`] when the format cannot write it.
90    fn write<D: Serialize + ?Sized>(&self, document: &D) -> Result<String, CodecError>;
91
92    /// Reads `text` through `seed`, refusing anything after the document.
93    ///
94    /// # Errors
95    ///
96    /// [`CodecError`] when `text` is not a document of this format or `seed` refuses it.
97    fn read<'de, S: DeserializeSeed<'de>>(
98        &self,
99        text: &'de str,
100        seed: S,
101    ) -> Result<S::Value, CodecError>;
102}
103
104/// A table of `T` kept in one private file: a document with one key, `section`, holding the
105/// list of records, written by codec `C`.
106///
107/// Records cross through their guatiao derives (`ToValue`/`FromValue`, which also stream)
108/// and guatiao-serde's bridge, with no tree in between. A self-describing format reads a
109/// byte string back only as the codec's [`Presentation`] spells it.
110///
111/// A missing file is an empty table. Every read compares the file's [`Stamp`], so a write by
112/// another process is a new revision; a file that is unreadable, oversized or invalid is an
113/// error, never a stale answer. Errors never contain file contents.
114///
115/// A read-modify-write (`put`, `remove`, `update`) holds an exclusive operating-system lock
116/// on a file beside the table, `<path>.lock`, from the read to the write, in this process and
117/// in any other that uses it, so no update is lost and `update` computes its change from the
118/// records it replaces. The lock file is left in place and holds nothing. Reads take no lock:
119/// the file is replaced whole.
120pub struct FileTable<T, C> {
121    path: PathBuf,
122    section: String,
123    codec: C,
124    max_bytes: usize,
125    state: Mutex<State>,
126    _records: PhantomData<fn() -> T>,
127}
128
129struct State {
130    stamp: Option<Stamp>,
131    revision: u64,
132}
133
134impl<T, C: Codec> fmt::Debug for FileTable<T, C> {
135    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
136        formatter
137            .debug_struct("FileTable")
138            .field("path", &self.path)
139            .field("section", &self.section)
140            .field("format", &self.codec.name())
141            .field("max_bytes", &self.max_bytes)
142            .finish_non_exhaustive()
143    }
144}
145
146impl<T, C> FileTable<T, C> {
147    /// The table under `section` in the file at `path`, which need not exist yet, written
148    /// with `codec`. Nothing is read until the table is used.
149    pub fn new(path: impl Into<PathBuf>, section: impl Into<String>, codec: C) -> Self {
150        Self {
151            path: path.into(),
152            section: section.into(),
153            codec,
154            max_bytes: DEFAULT_MAX_BYTES,
155            state: Mutex::new(State {
156                stamp: None,
157                revision: 0,
158            }),
159            _records: PhantomData,
160        }
161    }
162
163    /// The most the file may hold, in bytes, read or written. Default [`DEFAULT_MAX_BYTES`].
164    #[must_use]
165    pub fn max_bytes(mut self, max: usize) -> Self {
166        self.max_bytes = max;
167        self
168    }
169
170    /// The file.
171    pub fn path(&self) -> &Path {
172        &self.path
173    }
174
175    /// Takes the exclusive lock beside the table; it is held until the file returned drops.
176    fn lock(&self) -> Result<File, SourceError> {
177        let mut beside = self.path.as_os_str().to_owned();
178        beside.push(".lock");
179        let mut options = OpenOptions::new();
180        options.read(true).write(true).create(true).truncate(false);
181        #[cfg(unix)]
182        {
183            use std::os::unix::fs::OpenOptionsExt;
184            options.mode(0o600);
185        }
186        let file = options
187            .open(beside)
188            .map_err(|_| SourceError::unavailable("the table's lock file cannot be opened"))?;
189        file.lock()
190            .map_err(|_| SourceError::unavailable("the table cannot be locked"))?;
191        Ok(file)
192    }
193}
194
195impl<T: Walk + FromWalk, C: Codec> FileTable<T, C> {
196    fn decode(&self, text: &str) -> Result<Vec<T>, SourceError> {
197        let refusal = Cell::new(None);
198        let seed = DocumentSeed {
199            section: &self.section,
200            presentation: self.codec.presentation(),
201            refusal: &refusal,
202            _records: PhantomData,
203        };
204        self.codec.read(text, seed).map_err(|_| {
205            SourceError::invalid(match refusal.get() {
206                Some(reason) => reason.to_owned(),
207                None => format!("file is not a valid {} table", self.codec.name()),
208            })
209        })
210    }
211
212    fn encode(&self, records: &[T]) -> Result<String, SourceError> {
213        let document = Document {
214            section: &self.section,
215            records,
216            presentation: self.codec.presentation(),
217        };
218        let text = self
219            .codec
220            .write(&document)
221            .map_err(|_| SourceError::invalid("records cannot be encoded"))?;
222        if text.len() > self.max_bytes {
223            return Err(SourceError::invalid("table would exceed its size limit"));
224        }
225        Ok(text)
226    }
227
228    /// Reads the file and notes a new revision when it is not the one last seen.
229    ///
230    /// A file replaced while it is being read is read again, a few times: the replacement is
231    /// whole, so the next read is a consistent newer version, and only a file that keeps
232    /// changing is an error.
233    fn read(&self, state: &mut State) -> Result<Vec<T>, SourceError> {
234        for _ in 0..READS {
235            let before = stamp(&self.path).map_err(SourceError::unavailable)?;
236            let records =
237                match read_bounded(&self.path, self.max_bytes).map_err(SourceError::unavailable)? {
238                    None => Vec::new(),
239                    Some(text) => self.decode(&text)?,
240                };
241            let after = stamp(&self.path).map_err(SourceError::unavailable)?;
242            if before != after {
243                continue;
244            }
245            if after != state.stamp {
246                state.stamp = after;
247                state.revision += 1;
248            }
249            return Ok(records);
250        }
251        Err(SourceError::unavailable("file changed while it was read"))
252    }
253
254    fn write(&self, state: &mut State, records: &[T]) -> Result<(), SourceError> {
255        let text = self.encode(records)?;
256        write_private(&self.path, text.as_bytes()).map_err(SourceError::unavailable)?;
257        state.stamp = stamp(&self.path).map_err(SourceError::unavailable)?;
258        state.revision += 1;
259        Ok(())
260    }
261}
262
263impl<T, C> Table<T> for FileTable<T, C>
264where
265    T: Keyed + Clone + Send + Walk + FromWalk,
266    C: Codec,
267{
268    fn load(&self) -> Result<Snapshot<T>, SourceError> {
269        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
270        let records = self.read(&mut state)?;
271        Ok(Snapshot::new(Revision::new(state.revision), records))
272    }
273
274    fn changes_since(&self, since: Revision) -> Result<Option<Snapshot<T>>, SourceError> {
275        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
276        let now = stamp(&self.path).map_err(SourceError::unavailable)?;
277        if now == state.stamp && since.get() == state.revision {
278            return Ok(None);
279        }
280        let records = self.read(&mut state)?;
281        Ok(Some(Snapshot::new(Revision::new(state.revision), records)))
282    }
283
284    fn put(&self, record: T) -> Result<(), SourceError> {
285        let mut record = Some(record);
286        self.update(&mut |_| Ok(record.take()))
287    }
288
289    fn update(&self, make: &mut Update<'_, T>) -> Result<(), SourceError> {
290        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
291        let _lock = self.lock()?;
292        let mut records = self.read(&mut state)?;
293        let Some(record) = make(&records)? else {
294            return Ok(());
295        };
296        match records.iter().position(|had| had.key() == record.key()) {
297            Some(at) => records[at] = record,
298            None => records.push(record),
299        }
300        self.write(&mut state, &records)
301    }
302
303    fn remove(&self, key: &str) -> Result<bool, SourceError> {
304        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
305        let _lock = self.lock()?;
306        let mut records = self.read(&mut state)?;
307        let before = records.len();
308        records.retain(|record| record.key() != key);
309        if records.len() == before {
310            return Ok(false);
311        }
312        self.write(&mut state, &records)?;
313        Ok(true)
314    }
315
316    fn remove_where(&self, condition: &mut dyn FnMut(&T) -> bool) -> Result<usize, SourceError> {
317        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
318        let _lock = self.lock()?;
319        let mut records = self.read(&mut state)?;
320        let before = records.len();
321        records.retain(|record| !condition(record));
322        let removed = before - records.len();
323        if removed > 0 {
324            self.write(&mut state, &records)?;
325        }
326        Ok(removed)
327    }
328}
329
330/// The document written: `{ <section>: [record, ..] }`.
331struct Document<'a, T> {
332    section: &'a str,
333    records: &'a [T],
334    presentation: Presentation,
335}
336
337impl<T: Walk> Serialize for Document<'_, T> {
338    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
339        let mut map = serializer.serialize_map(Some(1))?;
340        map.serialize_entry(self.section, &Records(self.records, self.presentation))?;
341        map.end()
342    }
343}
344
345struct Records<'a, T>(&'a [T], Presentation);
346
347impl<T: Walk> Serialize for Records<'_, T> {
348    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
349        let mut list = serializer.serialize_seq(Some(self.0.len()))?;
350        for record in self.0 {
351            list.serialize_element(&Walked::new(record, self.1))?;
352        }
353        list.end()
354    }
355}
356
357/// Reads the document back. Each refusal of its own is noted in `refusal`, since a format's
358/// error may quote the document and is never shown.
359struct DocumentSeed<'a, T> {
360    section: &'a str,
361    presentation: Presentation,
362    refusal: &'a Cell<Option<&'static str>>,
363    _records: PhantomData<fn() -> T>,
364}
365
366impl<T> DocumentSeed<'_, T> {
367    fn refuse<E: de::Error>(&self, reason: &'static str) -> E {
368        self.refusal.set(Some(reason));
369        E::custom(reason)
370    }
371}
372
373impl<'de, T: FromWalk> DeserializeSeed<'de> for DocumentSeed<'_, T> {
374    type Value = Vec<T>;
375
376    fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Vec<T>, D::Error> {
377        deserializer.deserialize_map(self)
378    }
379}
380
381impl<'de, T: FromWalk> Visitor<'de> for DocumentSeed<'_, T> {
382    type Value = Vec<T>;
383
384    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
385        formatter.write_str("a document of records")
386    }
387
388    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Vec<T>, A::Error> {
389        let mut records = None;
390        while let Some(key) = map.next_key::<String>()? {
391            if key != self.section {
392                return Err(self.refuse("file has an unknown top-level key"));
393            }
394            if records.is_some() {
395                return Err(self.refuse("file holds its records twice"));
396            }
397            records = Some(map.next_value_seed(RecordsSeed {
398                presentation: self.presentation,
399                refusal: self.refusal,
400                _records: PhantomData::<fn() -> T>,
401            })?);
402        }
403        Ok(records.unwrap_or_default())
404    }
405}
406
407struct RecordsSeed<'a, T> {
408    presentation: Presentation,
409    refusal: &'a Cell<Option<&'static str>>,
410    _records: PhantomData<fn() -> T>,
411}
412
413impl<'de, T: FromWalk> DeserializeSeed<'de> for RecordsSeed<'_, T> {
414    type Value = Vec<T>;
415
416    fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Vec<T>, D::Error> {
417        deserializer.deserialize_seq(self)
418    }
419}
420
421impl<'de, T: FromWalk> Visitor<'de> for RecordsSeed<'_, T> {
422    type Value = Vec<T>;
423
424    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
425        formatter.write_str("a list of records")
426    }
427
428    fn visit_seq<A: SeqAccess<'de>>(self, mut list: A) -> Result<Vec<T>, A::Error> {
429        let mut records = Vec::new();
430        while let Some(record) = list.next_element_seed(RecordSeed {
431            presentation: self.presentation,
432            refusal: self.refusal,
433            _record: PhantomData::<fn() -> T>,
434        })? {
435            records.push(record);
436        }
437        Ok(records)
438    }
439}
440
441struct RecordSeed<'a, T> {
442    presentation: Presentation,
443    refusal: &'a Cell<Option<&'static str>>,
444    _record: PhantomData<fn() -> T>,
445}
446
447impl<'de, T: FromWalk> DeserializeSeed<'de> for RecordSeed<'_, T> {
448    type Value = T;
449
450    fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<T, D::Error> {
451        from_deserializer::<T, D>(deserializer, self.presentation).map_err(|error| match error {
452            BridgeError::Format(error) => error,
453            BridgeError::Refused(_) => {
454                const REASON: &str = "a record in the file is invalid";
455                self.refusal.set(Some(REASON));
456                de::Error::custom(REASON)
457            }
458        })
459    }
460}
461
462#[cfg(test)]
463mod tests;