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    read_named(project_root, LOCK_FILE)
45}
46
47/// [`read`] for any lock file at the project root: the contracts lock
48/// (#2554) is read with the same verified-absent discipline.
49pub(crate) fn read_named(project_root: &Path, file: &str) -> io::Result<Option<String>> {
50    match std::fs::read_to_string(project_root.join(file)) {
51        Ok(content) => Ok(Some(content)),
52        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
53        Err(e) => Err(e),
54    }
55}
56
57/// The committed lock as a **read-only** [`SchemaLock::On`] — how `check` and
58/// `test` reconcile events against `bynk.schema.lock` (#2078). Nothing is
59/// written back: the caller drops `ProjectOutput::schema_lock` (and a
60/// `ProjectCheck` carries none), so a passing additive change leaves the lock
61/// byte-identical for `bynkc compile`, `bynk dev` or `bynk deploy` to record.
62/// A missing lock is a fresh project, which baselines silently, exactly as a
63/// build treats it. A read failure is a message naming the file, for the
64/// caller to report.
65///
66/// [`SchemaLock::On`]: bynk_emit::project::SchemaLock::On
67pub fn read_only(project_root: &Path) -> Result<bynk_emit::project::SchemaLock, String> {
68    read(project_root)
69        .map(|existing| bynk_emit::project::SchemaLock::On { existing })
70        .map_err(|e| format!("could not read {}: {e}", lock_path(project_root).display()))
71}
72
73static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
74
75/// Write `bynk.schema.lock` to `project_root`, atomically (temp file +
76/// `sync_all` + rename + best-effort directory fsync, so a crash mid-write
77/// can only leave the intact old file or the intact new one — `ledger.rs`'s
78/// own discipline). A no-op when `content` is byte-identical to what is
79/// already on disk, so a clean rebuild never touches the file's mtime or
80/// produces a spurious `git diff`.
81pub fn write(project_root: &Path, content: &str) -> io::Result<()> {
82    write_named(project_root, LOCK_FILE, content)
83}
84
85/// [`write()`] for any lock file at the project root (#2554 writes
86/// `bynk.contracts.lock` with the same atomic discipline).
87pub(crate) fn write_named(project_root: &Path, file: &str, content: &str) -> io::Result<()> {
88    let path = project_root.join(file);
89    if let Ok(existing) = std::fs::read_to_string(&path)
90        && existing == content
91    {
92        return Ok(());
93    }
94
95    let dir = project_root;
96    let (tmp, mut file) = loop {
97        let n = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
98        let candidate = dir.join(format!(".{file}.{}.{n}.tmp", std::process::id()));
99        match std::fs::OpenOptions::new()
100            .write(true)
101            .create_new(true)
102            .open(&candidate)
103        {
104            Ok(f) => break (candidate, f),
105            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
106            Err(e) => return Err(e),
107        }
108    };
109
110    let write_then_sync = file
111        .write_all(content.as_bytes())
112        .and_then(|()| file.sync_all());
113    if let Err(e) = write_then_sync {
114        let _ = std::fs::remove_file(&tmp);
115        return Err(e);
116    }
117    drop(file);
118    if let Err(e) = std::fs::rename(&tmp, &path) {
119        let _ = std::fs::remove_file(&tmp);
120        return Err(e);
121    }
122    if let Ok(dir_handle) = std::fs::File::open(dir) {
123        let _ = dir_handle.sync_all();
124    }
125    Ok(())
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    /// A throwaway on-disk directory, removed on drop (including on panic) —
133    /// mirrors this crate's other test modules' own `Scratch`.
134    struct Scratch(PathBuf);
135    impl Drop for Scratch {
136        fn drop(&mut self) {
137            let _ = std::fs::remove_dir_all(&self.0);
138        }
139    }
140
141    fn scratch_dir(tag: &str) -> Scratch {
142        let dir = std::env::temp_dir().join(format!(
143            "bynk_1078_schema_lock_{tag}_{}_{:?}",
144            std::process::id(),
145            std::thread::current().id()
146        ));
147        let _ = std::fs::remove_dir_all(&dir);
148        std::fs::create_dir_all(&dir).unwrap();
149        Scratch(dir)
150    }
151
152    #[test]
153    fn read_of_an_absent_file_is_verified_absent() {
154        let dir = scratch_dir("absent");
155        assert_eq!(read(&dir.0).unwrap(), None);
156    }
157
158    /// #1085 review: the property `SchemaLock`'s `On { existing }` exists to
159    /// protect — a present-but-unreadable lock file must be a real error, not
160    /// silently degrade to "verified absent" (which would re-baseline a real
161    /// registry's history). Unix-only: `chmod`-based permission denial has no
162    /// portable Windows equivalent, and this crate's other permission-style
163    /// tests are unix-gated the same way.
164    #[cfg(unix)]
165    #[test]
166    fn read_of_an_unreadable_present_file_is_a_real_error_not_absent() {
167        use std::os::unix::fs::PermissionsExt;
168
169        let dir = scratch_dir("unreadable");
170        std::fs::write(lock_path(&dir.0), "version = 1\n").unwrap();
171        std::fs::set_permissions(lock_path(&dir.0), std::fs::Permissions::from_mode(0o000))
172            .unwrap();
173
174        // Skip if the test runs as root (or another privileged context) where
175        // permission bits don't actually block the read.
176        if std::fs::read_to_string(lock_path(&dir.0)).is_ok() {
177            return;
178        }
179        assert!(
180            read(&dir.0).is_err(),
181            "an unreadable-but-present file must not be reported as absent"
182        );
183    }
184
185    #[test]
186    fn write_then_read_round_trips() {
187        let dir = scratch_dir("roundtrip");
188        let content = "version = 1\n";
189        write(&dir.0, content).unwrap();
190        assert_eq!(read(&dir.0).unwrap().as_deref(), Some(content));
191    }
192
193    #[test]
194    fn write_is_a_no_op_when_content_is_unchanged() {
195        let dir = scratch_dir("noop-write");
196        let content = "version = 1\n";
197        write(&dir.0, content).unwrap();
198        let mtime_before = std::fs::metadata(lock_path(&dir.0))
199            .unwrap()
200            .modified()
201            .unwrap();
202        std::thread::sleep(std::time::Duration::from_millis(10));
203        write(&dir.0, content).unwrap();
204        let mtime_after = std::fs::metadata(lock_path(&dir.0))
205            .unwrap()
206            .modified()
207            .unwrap();
208        assert_eq!(
209            mtime_before, mtime_after,
210            "unchanged content must not rewrite the file"
211        );
212    }
213}