Skip to main content

bynk_driver/
schema_lock.rs

1//! Reading and atomically writing `bynk.schema.lock` — the driver's side of
2//! `CompileOptions::schema_registry` (#1078, R2.3/T0.7 residue).
3//!
4//! Ported verbatim from what used to be `bynk-emit/src/project/schema_registry.rs`'s
5//! `read`/`write` — same crash-safety discipline (temp file + `sync_all` +
6//! rename + best-effort directory fsync), same unchanged-content no-op. Only
7//! the location moved: `bynk-emit` now only ever sees pre-read content (via
8//! `SchemaLock::On`) and hands back serialized content to write (via
9//! `ProjectOutput::schema_lock`) — it touches no disk for this file, same as
10//! it no longer does for `.bynk` sources on the real CLI path (#1077/#1081).
11//!
12//! `bynk-emit`'s own `schema_registry::parse`/`serialize` are the pure
13//! counterparts this module's [`read`]/[`write()`] wrap disk I/O around.
14
15use std::io::{self, Write};
16use std::path::{Path, PathBuf};
17use std::sync::atomic::{AtomicU64, Ordering};
18
19const LOCK_FILE: &str = "bynk.schema.lock";
20
21/// Where the registry lives for a given project root — exposed so callers
22/// reporting a write failure can name the actual file, not just the root.
23pub fn lock_path(project_root: &Path) -> PathBuf {
24    project_root.join(LOCK_FILE)
25}
26
27/// Read `bynk.schema.lock`'s raw content from `project_root`, if it exists.
28/// `Ok(None)` means **verified absent** — no such file — which is the only
29/// thing `CompileOptions`' `SchemaLock::On { existing: None }` is allowed to
30/// mean (see that type's own doc). A present-but-unreadable file is a real
31/// `io::Error`, not folded into `None` — silently treating a permission
32/// error, a non-traversable ancestor, or any other stat/read failure as
33/// "fresh project" would risk re-baselining a real registry's history
34/// exactly as wrongly as never reading it at all.
35///
36/// #1085 review: a prior version checked `path.exists()` first and only then
37/// read — `exists()` maps *every* metadata error to `false`, not just
38/// "not found," so a non-`ENOENT` stat failure (or a dangling symlink, or a
39/// race with another process between the two calls) would have silently
40/// produced `Ok(None)` here. Reading directly and matching on
41/// `ErrorKind::NotFound` is both narrower (only the one error kind degrades)
42/// and race-free (one syscall, not two).
43pub fn read(project_root: &Path) -> io::Result<Option<String>> {
44    match std::fs::read_to_string(lock_path(project_root)) {
45        Ok(content) => Ok(Some(content)),
46        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
47        Err(e) => Err(e),
48    }
49}
50
51/// The committed lock as a **read-only** [`SchemaLock::On`] — how `check` and
52/// `test` reconcile events against `bynk.schema.lock` (#2078). Nothing is
53/// written back: the caller drops `ProjectOutput::schema_lock` (and a
54/// `ProjectCheck` carries none), so a passing additive change leaves the lock
55/// byte-identical for `bynkc compile`, `bynk dev` or `bynk deploy` to record.
56/// A missing lock is a fresh project, which baselines silently, exactly as a
57/// build treats it. A read failure is a message naming the file, for the
58/// caller to report.
59///
60/// [`SchemaLock::On`]: bynk_emit::project::SchemaLock::On
61pub fn read_only(project_root: &Path) -> Result<bynk_emit::project::SchemaLock, String> {
62    read(project_root)
63        .map(|existing| bynk_emit::project::SchemaLock::On { existing })
64        .map_err(|e| format!("could not read {}: {e}", lock_path(project_root).display()))
65}
66
67static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
68
69/// Write `bynk.schema.lock` to `project_root`, atomically (temp file +
70/// `sync_all` + rename + best-effort directory fsync, so a crash mid-write
71/// can only leave the intact old file or the intact new one — `ledger.rs`'s
72/// own discipline). A no-op when `content` is byte-identical to what is
73/// already on disk, so a clean rebuild never touches the file's mtime or
74/// produces a spurious `git diff`.
75pub fn write(project_root: &Path, content: &str) -> io::Result<()> {
76    let path = lock_path(project_root);
77    if let Ok(existing) = std::fs::read_to_string(&path)
78        && existing == content
79    {
80        return Ok(());
81    }
82
83    let dir = project_root;
84    let (tmp, mut file) = loop {
85        let n = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
86        let candidate = dir.join(format!(".{LOCK_FILE}.{}.{n}.tmp", std::process::id()));
87        match std::fs::OpenOptions::new()
88            .write(true)
89            .create_new(true)
90            .open(&candidate)
91        {
92            Ok(f) => break (candidate, f),
93            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
94            Err(e) => return Err(e),
95        }
96    };
97
98    let write_then_sync = file
99        .write_all(content.as_bytes())
100        .and_then(|()| file.sync_all());
101    if let Err(e) = write_then_sync {
102        let _ = std::fs::remove_file(&tmp);
103        return Err(e);
104    }
105    drop(file);
106    if let Err(e) = std::fs::rename(&tmp, &path) {
107        let _ = std::fs::remove_file(&tmp);
108        return Err(e);
109    }
110    if let Ok(dir_handle) = std::fs::File::open(dir) {
111        let _ = dir_handle.sync_all();
112    }
113    Ok(())
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119
120    /// A throwaway on-disk directory, removed on drop (including on panic) —
121    /// mirrors this crate's other test modules' own `Scratch`.
122    struct Scratch(PathBuf);
123    impl Drop for Scratch {
124        fn drop(&mut self) {
125            let _ = std::fs::remove_dir_all(&self.0);
126        }
127    }
128
129    fn scratch_dir(tag: &str) -> Scratch {
130        let dir = std::env::temp_dir().join(format!(
131            "bynk_1078_schema_lock_{tag}_{}_{:?}",
132            std::process::id(),
133            std::thread::current().id()
134        ));
135        let _ = std::fs::remove_dir_all(&dir);
136        std::fs::create_dir_all(&dir).unwrap();
137        Scratch(dir)
138    }
139
140    #[test]
141    fn read_of_an_absent_file_is_verified_absent() {
142        let dir = scratch_dir("absent");
143        assert_eq!(read(&dir.0).unwrap(), None);
144    }
145
146    /// #1085 review: the property `SchemaLock`'s `On { existing }` exists to
147    /// protect — a present-but-unreadable lock file must be a real error, not
148    /// silently degrade to "verified absent" (which would re-baseline a real
149    /// registry's history). Unix-only: `chmod`-based permission denial has no
150    /// portable Windows equivalent, and this crate's other permission-style
151    /// tests are unix-gated the same way.
152    #[cfg(unix)]
153    #[test]
154    fn read_of_an_unreadable_present_file_is_a_real_error_not_absent() {
155        use std::os::unix::fs::PermissionsExt;
156
157        let dir = scratch_dir("unreadable");
158        std::fs::write(lock_path(&dir.0), "version = 1\n").unwrap();
159        std::fs::set_permissions(lock_path(&dir.0), std::fs::Permissions::from_mode(0o000))
160            .unwrap();
161
162        // Skip if the test runs as root (or another privileged context) where
163        // permission bits don't actually block the read.
164        if std::fs::read_to_string(lock_path(&dir.0)).is_ok() {
165            return;
166        }
167        assert!(
168            read(&dir.0).is_err(),
169            "an unreadable-but-present file must not be reported as absent"
170        );
171    }
172
173    #[test]
174    fn write_then_read_round_trips() {
175        let dir = scratch_dir("roundtrip");
176        let content = "version = 1\n";
177        write(&dir.0, content).unwrap();
178        assert_eq!(read(&dir.0).unwrap().as_deref(), Some(content));
179    }
180
181    #[test]
182    fn write_is_a_no_op_when_content_is_unchanged() {
183        let dir = scratch_dir("noop-write");
184        let content = "version = 1\n";
185        write(&dir.0, content).unwrap();
186        let mtime_before = std::fs::metadata(lock_path(&dir.0))
187            .unwrap()
188            .modified()
189            .unwrap();
190        std::thread::sleep(std::time::Duration::from_millis(10));
191        write(&dir.0, content).unwrap();
192        let mtime_after = std::fs::metadata(lock_path(&dir.0))
193            .unwrap()
194            .modified()
195            .unwrap();
196        assert_eq!(
197            mtime_before, mtime_after,
198            "unchanged content must not rewrite the file"
199        );
200    }
201}