1#![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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub enum SourceError {
34 Io(ErrorKind),
36 NotRegular,
38 TooLarge,
40 Changed,
42 Invalid(ParseError),
44}
45
46#[derive(Clone, Copy, Debug, PartialEq, Eq)]
48pub enum Observation {
49 Pending,
51 Published,
53 Unchanged,
55}
56
57#[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#[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
104struct Candidate {
106 stamp: Stamp,
107 bytes: Vec<u8>,
108 vocabulary: Arc<Vocabulary>,
109}
110
111pub type Parser = fn(&[u8]) -> Result<Vocabulary, ParseError>;
114
115pub struct Source {
121 current: Option<Arc<Vocabulary>>,
122 staged: Option<Candidate>,
123 parse: Parser,
124}
125
126impl Default for Source {
128 fn default() -> Self {
129 Self::new(Vocabulary::parse)
130 }
131}
132
133impl Source {
134 pub fn new(parse: Parser) -> Self {
136 Self {
137 current: None,
138 staged: None,
139 parse,
140 }
141 }
142
143 pub fn current(&self) -> Option<Arc<Vocabulary>> {
145 self.current.clone()
146 }
147
148 pub fn observe(&mut self, path: &Path) -> Result<Observation, SourceError> {
159 self.observe_at(path, |_, _| {})
160 }
161
162 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 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 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#[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 #[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 #[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 #[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 #[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 #[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 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 #[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 #[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 #[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 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 #[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}