Skip to main content

keyrill_ffi/
vocabulary_source.rs

1//! Bounded reading of one dictionary file into an immutable vocabulary, outside input callbacks.
2//!
3//! A personal dictionary is a file that another program, Vim or the OS spell checker, rewrites
4//! whenever it likes, so a read can meet a half-written file, a file replaced in the middle of
5//! the read, or something at the path that is not a file at all. One observation is:
6//!
7//! ```text
8//!   stat the path          a regular file of at most 1 MiB; remember its stamp
9//!   open, fstat            nonblocking; still a regular file with the same stamp
10//!   read at most 1 MiB+1   more than 1 MiB is TooLarge
11//!   fstat, stat the path   the same stamp through both, and as many bytes as the stamp says
12//!   compare with staged    same stamp and bytes: publish; otherwise parse and stage
13//! ```
14//!
15//! A candidate is published only when two consecutive observations read it identically. That
16//! settles the usual save patterns but cannot prove a writer finished. Every failure discards
17//! the staged candidate and keeps the last published vocabulary, so protection never drops
18//! because of one bad read.
19#![forbid(unsafe_code)]
20
21use keyrill_core::vocabulary::{MAX_SOURCE_BYTES, ParseError, Vocabulary};
22use std::fs::{self, File, Metadata, OpenOptions};
23use std::io::{ErrorKind, Read};
24#[cfg(unix)]
25use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
26use std::path::Path;
27use std::sync::Arc;
28#[cfg(not(unix))]
29use std::time::SystemTime;
30
31/// Content-free reason an observation failed. The last-good vocabulary remains available.
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub enum SourceError {
34    /// The source could not be opened, read or inspected.
35    Io(ErrorKind),
36    /// Only regular files, including symlinks resolving to regular files, are eligible.
37    NotRegular,
38    /// The source exceeds the byte bound.
39    TooLarge,
40    /// Identity, size or timestamps changed during acquisition.
41    Changed,
42    /// The complete candidate is outside the supported word-list format.
43    Invalid(ParseError),
44}
45
46/// Result of one explicitly requested observation; no timer or background task is created.
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
48pub enum Observation {
49    /// A valid candidate awaits another equal observation.
50    Pending,
51    /// Two equal observations published a new immutable snapshot.
52    Published,
53    /// The already-published candidate is unchanged.
54    Unchanged,
55}
56
57// What must not change during one observation or between two: identity, length, and the
58// modification and status-change times. A writer can restore the modification time but not the
59// status-change time, so a rewrite that hides behind an old mtime still changes the stamp.
60#[cfg(unix)]
61#[derive(Clone, Copy, PartialEq, Eq)]
62struct Stamp {
63    device: u64,
64    inode: u64,
65    length: u64,
66    modified: (i64, i64),
67    changed: (i64, i64),
68}
69
70#[cfg(unix)]
71impl Stamp {
72    fn of(metadata: &Metadata) -> Self {
73        Self {
74            device: metadata.dev(),
75            inode: metadata.ino(),
76            length: metadata.len(),
77            modified: (metadata.mtime(), metadata.mtime_nsec()),
78            changed: (metadata.ctime(), metadata.ctime_nsec()),
79        }
80    }
81}
82
83// Stable std exposes no file identity on Windows, so a replacement with the same length and
84// timestamps keeps its stamp; the exact byte comparison between observations still catches it
85#[cfg(not(unix))]
86#[derive(Clone, Copy, PartialEq, Eq)]
87struct Stamp {
88    length: u64,
89    modified: Option<SystemTime>,
90    created: Option<SystemTime>,
91}
92
93#[cfg(not(unix))]
94impl Stamp {
95    fn of(metadata: &Metadata) -> Self {
96        Self {
97            length: metadata.len(),
98            modified: metadata.modified().ok(),
99            created: metadata.created().ok(),
100        }
101    }
102}
103
104// A parsed file waiting for a second equal observation, with the bytes it was parsed from
105struct Candidate {
106    stamp: Stamp,
107    bytes: Vec<u8>,
108    vocabulary: Arc<Vocabulary>,
109}
110
111/// Parses a complete candidate in the source's word-list format: Vim's, or a plain list for
112/// learned words.
113pub type Parser = fn(&[u8]) -> Result<Vocabulary, ParseError>;
114
115/// The last published vocabulary of one file plus one staged candidate. It reads only the path
116/// it is given and knows no default or home path.
117///
118/// Two equal observations are a settling heuristic: a writer paused across both can still
119/// expose an incomplete but valid file. This does not prove that an editor save completed.
120pub struct Source {
121    current: Option<Arc<Vocabulary>>,
122    staged: Option<Candidate>,
123    parse: Parser,
124}
125
126/// A source that parses Vim word lists.
127impl Default for Source {
128    fn default() -> Self {
129        Self::new(Vocabulary::parse)
130    }
131}
132
133impl Source {
134    /// An empty source whose candidates `parse` reads.
135    pub fn new(parse: Parser) -> Self {
136        Self {
137            current: None,
138            staged: None,
139            parse,
140        }
141    }
142
143    /// Share the last published vocabulary; `None` until the first publication.
144    pub fn current(&self) -> Option<Arc<Vocabulary>> {
145        self.current.clone()
146    }
147
148    /// Read a bounded candidate without writing the source. Call on a serialized reload path,
149    /// outside input callbacks. The first valid read stages a candidate and returns
150    /// [`Observation::Pending`]; a second read with equal metadata and bytes publishes it. An
151    /// initial valid empty file also requires two equal observations.
152    ///
153    /// # Errors
154    ///
155    /// A [`SourceError`] if the file can't be read, isn't a regular file, exceeds the bound,
156    /// changes during the read or doesn't parse. Staging is discarded; the published snapshot
157    /// stays.
158    pub fn observe(&mut self, path: &Path) -> Result<Observation, SourceError> {
159        self.observe_at(path, |_, _| {})
160    }
161
162    // `checkpoint` lets tests change the file at fixed steps of one observation
163    fn observe_at(
164        &mut self,
165        path: &Path,
166        checkpoint: impl FnMut(Step, Option<&File>),
167    ) -> Result<Observation, SourceError> {
168        let result = self.acquire(path, checkpoint);
169        if result.is_err() {
170            self.staged = None;
171        }
172        result
173    }
174
175    fn acquire(
176        &mut self,
177        path: &Path,
178        mut checkpoint: impl FnMut(Step, Option<&File>),
179    ) -> Result<Observation, SourceError> {
180        let io = |error: std::io::Error| SourceError::Io(error.kind());
181        let before = fs::metadata(path).map_err(io)?;
182        if !before.is_file() {
183            return Err(SourceError::NotRegular);
184        }
185        if before.len() > MAX_SOURCE_BYTES as u64 {
186            return Err(SourceError::TooLarge);
187        }
188        let stamp = Stamp::of(&before);
189        checkpoint(Step::CheckedPath, None);
190
191        // Pre-stat narrows device exposure; nonblocking open also avoids waiting on a raced FIFO,
192        // and O_NOCTTY keeps a raced terminal from becoming the controlling terminal. Windows
193        // needs no flag: a named-pipe client open fails at once when no instance is free.
194        // Follow symlinks because normal dotfile arrangements use them. std sets close-on-exec.
195        let mut options = OpenOptions::new();
196        options.read(true);
197        #[cfg(unix)]
198        options.custom_flags(libc::O_NONBLOCK | libc::O_NOCTTY);
199        let mut file = options.open(path).map_err(io)?;
200        let opened = file.metadata().map_err(io)?;
201        if !opened.is_file() {
202            return Err(SourceError::NotRegular);
203        }
204        if Stamp::of(&opened) != stamp {
205            return Err(SourceError::Changed);
206        }
207        checkpoint(Step::Opened, Some(&file));
208        let mut bytes = Vec::new();
209        (&mut file)
210            .take(MAX_SOURCE_BYTES as u64 + 1)
211            .read_to_end(&mut bytes)
212            .map_err(io)?;
213        if bytes.len() > MAX_SOURCE_BYTES {
214            return Err(SourceError::TooLarge);
215        }
216        checkpoint(Step::Read, None);
217        let after = file.metadata().map_err(io)?;
218        let resolved = fs::metadata(path).map_err(io)?;
219        if !resolved.is_file()
220            || Stamp::of(&after) != stamp
221            || Stamp::of(&resolved) != stamp
222            || bytes.len() as u64 != stamp.length
223        {
224            return Err(SourceError::Changed);
225        }
226
227        // Comparing bytes as well as stamps catches a rewrite that keeps size and timestamps
228        if let Some(staged) = &self.staged
229            && staged.stamp == stamp
230            && staged.bytes == bytes
231        {
232            if self
233                .current
234                .as_ref()
235                .is_some_and(|current| Arc::ptr_eq(current, &staged.vocabulary))
236            {
237                return Ok(Observation::Unchanged);
238            }
239            self.current = Some(staged.vocabulary.clone());
240            return Ok(Observation::Published);
241        }
242        let vocabulary = (self.parse)(&bytes).map_err(SourceError::Invalid)?;
243        self.staged = Some(Candidate {
244            stamp,
245            bytes,
246            vocabulary: Arc::new(vocabulary),
247        });
248        Ok(Observation::Pending)
249    }
250}
251
252// Deterministic barriers exercise replacement and in-place writes without timing assumptions
253#[derive(Clone, Copy, PartialEq, Eq)]
254enum Step {
255    CheckedPath,
256    Opened,
257    Read,
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263    use keyrill_core::vocabulary::Membership;
264    // Symlink, FIFO and permission tests are Unix-only; Windows symlinks need a privilege
265    #[cfg(unix)]
266    use std::os::unix::fs::{DirBuilderExt, symlink};
267    use std::path::PathBuf;
268    use std::sync::atomic::{AtomicUsize, Ordering};
269
270    struct Directory(PathBuf);
271
272    impl Directory {
273        fn new() -> Self {
274            static NEXT: AtomicUsize = AtomicUsize::new(0);
275            let path = std::env::temp_dir().join(format!(
276                "keyrill-source-{}-{}",
277                std::process::id(),
278                NEXT.fetch_add(1, Ordering::Relaxed)
279            ));
280            #[cfg(unix)]
281            fs::DirBuilder::new().mode(0o700).create(&path).unwrap();
282            #[cfg(not(unix))]
283            fs::create_dir(&path).unwrap();
284            Self(path)
285        }
286        fn path(&self, name: &str) -> PathBuf {
287            self.0.join(name)
288        }
289    }
290
291    impl Drop for Directory {
292        fn drop(&mut self) {
293            let _ = fs::remove_dir_all(&self.0);
294        }
295    }
296
297    fn published(source: &mut Source, path: &Path) -> Arc<Vocabulary> {
298        assert_eq!(source.observe(path), Ok(Observation::Pending));
299        assert_eq!(source.observe(path), Ok(Observation::Published));
300        source.current().unwrap()
301    }
302
303    // A reader holding the old snapshot keeps it across a reload, and the file is never written
304    #[cfg(unix)]
305    #[test]
306    fn symlink_reload_settles_and_retains_immutable_readers() {
307        let directory = Directory::new();
308        let target = directory.path("target");
309        let path = directory.path("source");
310        fs::write(&target, b"hello\n").unwrap();
311        symlink(&target, &path).unwrap();
312        let mut source = Source::default();
313        assert!(source.current().is_none());
314        assert_eq!(source.observe(&path), Ok(Observation::Pending));
315        assert!(source.current().is_none());
316        assert_eq!(source.observe(&path), Ok(Observation::Published));
317        let old = source.current().unwrap();
318        assert_eq!(source.observe(&path), Ok(Observation::Unchanged));
319        assert!(Arc::ptr_eq(&old, &source.current().unwrap()));
320        fs::write(&target, b"world\n").unwrap();
321        assert_eq!(source.observe(&path), Ok(Observation::Pending));
322        assert!(Arc::ptr_eq(&old, &source.current().unwrap()));
323        assert_eq!(source.observe(&path), Ok(Observation::Published));
324        assert_eq!(
325            old.lookup(&[104, 101, 108, 108, 111]),
326            Membership::Recognized
327        );
328        assert_eq!(
329            source.current().unwrap().lookup(&[119, 111, 114, 108, 100]),
330            Membership::Recognized
331        );
332        assert_eq!(fs::read(&target).unwrap(), b"world\n");
333    }
334
335    // Each kind of failure drops the staged candidate and keeps last good; an empty file is a
336    // valid source and still takes two observations
337    #[test]
338    fn failures_drop_staging_and_preserve_last_good() {
339        let directory = Directory::new();
340        let path = directory.path("source");
341        fs::write(&path, b"hello").unwrap();
342        let mut source = Source::default();
343        let good = published(&mut source, &path);
344        for bytes in [b"a\0b".as_slice(), b"/encoding=latin1\nhello"] {
345            fs::write(&path, bytes).unwrap();
346            assert!(matches!(
347                source.observe(&path),
348                Err(SourceError::Invalid(_))
349            ));
350            assert!(source.staged.is_none());
351            assert!(Arc::ptr_eq(&good, &source.current().unwrap()));
352        }
353        fs::write(&path, vec![b'a'; MAX_SOURCE_BYTES + 1]).unwrap();
354        assert_eq!(source.observe(&path), Err(SourceError::TooLarge));
355        fs::remove_file(&path).unwrap();
356        assert_eq!(
357            source.observe(&path),
358            Err(SourceError::Io(ErrorKind::NotFound))
359        );
360        fs::create_dir(&path).unwrap();
361        assert_eq!(source.observe(&path), Err(SourceError::NotRegular));
362        assert!(Arc::ptr_eq(&good, &source.current().unwrap()));
363        fs::remove_dir(&path).unwrap();
364        fs::write(&path, b"").unwrap();
365        assert_eq!(source.observe(&path), Ok(Observation::Pending));
366        assert!(Arc::ptr_eq(&good, &source.current().unwrap()));
367        fs::remove_file(&path).unwrap();
368        assert!(source.observe(&path).is_err());
369        fs::write(&path, b"").unwrap();
370        assert!(published(&mut source, &path).is_empty());
371        let mut initial = Source::default();
372        assert_eq!(initial.observe(&path), Ok(Observation::Pending));
373        assert!(initial.current().is_none());
374        assert_eq!(initial.observe(&path), Ok(Observation::Published));
375        assert!(initial.current().unwrap().is_empty());
376    }
377
378    // A write at any step of one observation is caught as Changed and never staged
379    #[test]
380    fn deterministic_mutations_during_acquisition_never_publish() {
381        for step in [Step::CheckedPath, Step::Opened, Step::Read] {
382            let directory = Directory::new();
383            let path = directory.path("source");
384            fs::write(&path, b"hello").unwrap();
385            let mut source = Source::default();
386            let good = published(&mut source, &path);
387            assert_eq!(
388                source.observe_at(&path, |at, _| {
389                    if at == step {
390                        fs::write(&path, b"different length").unwrap();
391                    }
392                }),
393                Err(SourceError::Changed)
394            );
395            assert!(source.staged.is_none());
396            assert!(Arc::ptr_eq(&good, &source.current().unwrap()));
397        }
398    }
399
400    // A rename over the file during the read is caught. A truncate-then-write save is staged
401    // twice with different bytes, so the empty intermediate never publishes.
402    #[cfg(unix)]
403    #[test]
404    fn replacement_and_truncate_then_write_require_new_observations() {
405        let directory = Directory::new();
406        let target = directory.path("target");
407        let path = directory.path("source");
408        let replacement = directory.path("replacement");
409        fs::write(&target, b"hello").unwrap();
410        symlink(&target, &path).unwrap();
411        let mut source = Source::default();
412        let good = published(&mut source, &path);
413        fs::write(&replacement, b"world").unwrap();
414        assert_eq!(
415            source.observe_at(&path, |at, _| {
416                if at == Step::Read {
417                    fs::rename(&replacement, &target).unwrap();
418                }
419            }),
420            Err(SourceError::Changed)
421        );
422        assert!(Arc::ptr_eq(&good, &source.current().unwrap()));
423        let good = published(&mut source, &path);
424        assert_eq!(
425            good.lookup(&[119, 111, 114, 108, 100]),
426            Membership::Recognized
427        );
428        fs::write(&target, b"").unwrap();
429        assert_eq!(source.observe(&path), Ok(Observation::Pending));
430        assert!(Arc::ptr_eq(&good, &source.current().unwrap()));
431        fs::write(&target, b"complete\n").unwrap();
432        assert_eq!(source.observe(&path), Ok(Observation::Pending));
433        assert!(Arc::ptr_eq(&good, &source.current().unwrap()));
434        assert_eq!(source.observe(&path), Ok(Observation::Published));
435        assert_eq!(source.current().unwrap().len(), 1);
436        assert_eq!(fs::read(&target).unwrap(), b"complete\n");
437    }
438
439    #[test]
440    fn growth_and_nonregular_descriptor_races_are_rejected() {
441        let directory = Directory::new();
442        let path = directory.path("source");
443        fs::write(&path, b"hello").unwrap();
444        let mut source = Source::default();
445        let good = published(&mut source, &path);
446        assert_eq!(
447            source.observe_at(&path, |at, _| {
448                if at == Step::Opened {
449                    fs::write(&path, vec![b'a'; MAX_SOURCE_BYTES + 1]).unwrap();
450                }
451            }),
452            Err(SourceError::TooLarge)
453        );
454        fs::write(&path, b"hello").unwrap();
455        // Windows refuses to open a directory as a file, so the race fails at the open instead
456        let expected = if cfg!(windows) {
457            SourceError::Io(ErrorKind::PermissionDenied)
458        } else {
459            SourceError::NotRegular
460        };
461        assert_eq!(
462            source.observe_at(&path, |at, _| {
463                if at == Step::CheckedPath {
464                    fs::remove_file(&path).unwrap();
465                    fs::create_dir(&path).unwrap();
466                }
467            }),
468            Err(expected)
469        );
470        assert!(source.staged.is_none());
471        assert!(Arc::ptr_eq(&good, &source.current().unwrap()));
472    }
473
474    // Retargeting or removing the symlink during a read is caught, and the dropped stage makes
475    // the next read start over at Pending
476    #[cfg(unix)]
477    #[test]
478    fn symlink_retarget_and_disappearance_discard_staging() {
479        let directory = Directory::new();
480        let first = directory.path("first");
481        let second = directory.path("second");
482        let path = directory.path("source");
483        fs::write(&first, b"hello").unwrap();
484        fs::write(&second, b"world").unwrap();
485        symlink(&first, &path).unwrap();
486        let mut source = Source::default();
487        let good = published(&mut source, &path);
488        assert_eq!(
489            source.observe_at(&path, |at, _| {
490                if at == Step::Read {
491                    fs::remove_file(&path).unwrap();
492                    symlink(&second, &path).unwrap();
493                }
494            }),
495            Err(SourceError::Changed)
496        );
497        assert!(source.staged.is_none());
498        assert!(Arc::ptr_eq(&good, &source.current().unwrap()));
499        assert_eq!(source.observe(&path), Ok(Observation::Pending));
500        assert_eq!(
501            source.observe_at(&path, |at, _| {
502                if at == Step::Read {
503                    fs::remove_file(&path).unwrap();
504                }
505            }),
506            Err(SourceError::Io(ErrorKind::NotFound))
507        );
508        assert!(source.staged.is_none());
509        assert!(Arc::ptr_eq(&good, &source.current().unwrap()));
510        symlink(&second, &path).unwrap();
511        assert_eq!(source.observe(&path), Ok(Observation::Pending));
512    }
513
514    // Without O_NONBLOCK, opening a FIFO swapped in after the stat would block the acquisition
515    // queue until a writer appeared; with it the open returns and the swap is NotRegular
516    #[cfg(unix)]
517    #[test]
518    fn nonblocking_flag_is_checked_before_the_fifo_race() {
519        let directory = Directory::new();
520        let path = directory.path("source");
521        fs::write(&path, b"hello").unwrap();
522        let mut source = Source::default();
523        let good = published(&mut source, &path);
524        let mut checked = false;
525        assert_eq!(
526            source.observe_at(&path, |at, file| {
527                if at == Step::Opened {
528                    let flags = crate::descriptor_flags(file.unwrap());
529                    assert!(flags >= 0);
530                    assert_ne!(flags & libc::O_NONBLOCK, 0);
531                    checked = true;
532                }
533            }),
534            Ok(Observation::Unchanged)
535        );
536        assert!(checked);
537        assert_eq!(
538            source.observe_at(&path, |at, _| {
539                if at == Step::CheckedPath {
540                    fs::remove_file(&path).unwrap();
541                    assert!(
542                        std::process::Command::new("/usr/bin/mkfifo")
543                            .arg(&path)
544                            .status()
545                            .unwrap()
546                            .success()
547                    );
548                }
549            }),
550            Err(SourceError::NotRegular)
551        );
552        assert!(source.staged.is_none());
553        assert!(Arc::ptr_eq(&good, &source.current().unwrap()));
554    }
555
556    // The known limit of the settling heuristic: a writer paused across both observations
557    // publishes its partial file, here an empty one
558    #[test]
559    fn paused_writer_across_both_observations_can_publish_empty() {
560        let directory = Directory::new();
561        let path = directory.path("source");
562        fs::write(&path, b"hello").unwrap();
563        let mut source = Source::default();
564        let good = published(&mut source, &path);
565        fs::write(&path, b"").unwrap();
566        assert_eq!(source.observe(&path), Ok(Observation::Pending));
567        assert!(Arc::ptr_eq(&good, &source.current().unwrap()));
568        assert_eq!(source.observe(&path), Ok(Observation::Published));
569        assert!(source.current().unwrap().is_empty());
570        assert!(!good.is_empty());
571    }
572
573    #[test]
574    fn equal_metadata_does_not_replace_exact_byte_comparison() {
575        let directory = Directory::new();
576        let path = directory.path("source");
577        fs::write(&path, b"hello").unwrap();
578        let mut source = Source::default();
579        let good = published(&mut source, &path);
580        fs::write(&path, b"world").unwrap();
581        // Model a filesystem whose timestamp granularity hides a same-length rewrite
582        source.staged.as_mut().unwrap().stamp = Stamp::of(&fs::metadata(&path).unwrap());
583        assert_eq!(source.observe(&path), Ok(Observation::Pending));
584        assert!(Arc::ptr_eq(&good, &source.current().unwrap()));
585        assert_eq!(source.observe(&path), Ok(Observation::Published));
586        assert_eq!(
587            source.current().unwrap().lookup(&[119, 111, 114, 108, 100]),
588            Membership::Recognized
589        );
590    }
591
592    // Root ignores mode 000, so this test needs an ordinary user
593    #[cfg(unix)]
594    #[test]
595    fn permission_failure_preserves_last_good() {
596        use std::os::unix::fs::PermissionsExt;
597
598        let directory = Directory::new();
599        let path = directory.path("source");
600        fs::write(&path, b"hello").unwrap();
601        let mut source = Source::default();
602        let good = published(&mut source, &path);
603        fs::set_permissions(&path, fs::Permissions::from_mode(0o000)).unwrap();
604        assert_eq!(
605            source.observe(&path),
606            Err(SourceError::Io(ErrorKind::PermissionDenied))
607        );
608        assert!(source.staged.is_none());
609        assert!(Arc::ptr_eq(&good, &source.current().unwrap()));
610        fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
611        assert_eq!(source.observe(&path), Ok(Observation::Pending));
612    }
613}