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 `bynk 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`]: crate::project::SchemaLock::On
67pub fn read_only(project_root: &Path) -> Result<crate::project::SchemaLock, String> {
68 read(project_root)
69 .map(|existing| crate::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()`], then a note naming each agent whose entry the write gave
86/// `paths` it did not record before (#3749). ADR 0682 C fills them in on an
87/// unchanged build, once; saying so is what gets the filled lock committed,
88/// rather than rebuilt and dropped in every throwaway CI checkout.
89pub fn write_reporting(prog: &str, project_root: &Path, content: &str) -> io::Result<()> {
90 let existing = read(project_root).ok().flatten();
91 write(project_root, content)?;
92 let filled = agents_given_paths(project_root, existing.as_deref(), content);
93 if !filled.is_empty() {
94 crate::emsg!(
95 "{prog}: note: {LOCK_FILE}: recorded stored positions for {}; commit it",
96 filled.join(", ")
97 );
98 }
99 Ok(())
100}
101
102/// #3749: the agents (`<unit>.<Agent>`, sorted) whose current snapshot in
103/// `existing` holds a stored field with no recorded `paths` that `content`
104/// records them for. Empty when there is no earlier lock, or either side does
105/// not parse (the build has reported that already).
106pub fn agents_given_paths(
107 project_root: &Path,
108 existing: Option<&str>,
109 content: &str,
110) -> Vec<String> {
111 use bynk_project::schema_registry::parse;
112 let (Some(_), Ok(old), Ok(new)) = (
113 existing,
114 parse(existing, project_root),
115 parse(Some(content), project_root),
116 ) else {
117 return Vec::new();
118 };
119 old.agents()
120 .filter(|(key, entry)| {
121 let Some(before) = entry.current() else {
122 return false;
123 };
124 let Some(after) = new.get_agent(key).and_then(|e| e.shape(before.version)) else {
125 return false;
126 };
127 before.fields.iter().any(|f| {
128 f.paths.is_empty()
129 && after
130 .fields
131 .iter()
132 .any(|n| n.name == f.name && !n.paths.is_empty())
133 })
134 })
135 .map(|(key, _)| key.clone())
136 .collect()
137}
138
139/// [`write()`] for any lock file at the project root (#2554 writes
140/// `bynk.contracts.lock` with the same atomic discipline).
141pub(crate) fn write_named(project_root: &Path, file: &str, content: &str) -> io::Result<()> {
142 let path = project_root.join(file);
143 if let Ok(existing) = std::fs::read_to_string(&path)
144 && existing == content
145 {
146 return Ok(());
147 }
148
149 let dir = project_root;
150 let (tmp, mut file) = loop {
151 let n = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
152 let candidate = dir.join(format!(".{file}.{}.{n}.tmp", std::process::id()));
153 match std::fs::OpenOptions::new()
154 .write(true)
155 .create_new(true)
156 .open(&candidate)
157 {
158 Ok(f) => break (candidate, f),
159 Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
160 Err(e) => return Err(e),
161 }
162 };
163
164 let write_then_sync = file
165 .write_all(content.as_bytes())
166 .and_then(|()| file.sync_all());
167 if let Err(e) = write_then_sync {
168 let _ = std::fs::remove_file(&tmp);
169 return Err(e);
170 }
171 drop(file);
172 if let Err(e) = std::fs::rename(&tmp, &path) {
173 let _ = std::fs::remove_file(&tmp);
174 return Err(e);
175 }
176 if let Ok(dir_handle) = std::fs::File::open(dir) {
177 let _ = dir_handle.sync_all();
178 }
179 Ok(())
180}
181
182#[cfg(test)]
183mod tests {
184 use super::*;
185
186 /// A throwaway on-disk directory, removed on drop (including on panic) —
187 /// mirrors this crate's other test modules' own `Scratch`.
188 struct Scratch(PathBuf);
189 impl Drop for Scratch {
190 fn drop(&mut self) {
191 let _ = std::fs::remove_dir_all(&self.0);
192 }
193 }
194
195 fn scratch_dir(tag: &str) -> Scratch {
196 let dir = std::env::temp_dir().join(format!(
197 "bynk_1078_schema_lock_{tag}_{}_{:?}",
198 std::process::id(),
199 std::thread::current().id()
200 ));
201 let _ = std::fs::remove_dir_all(&dir);
202 std::fs::create_dir_all(&dir).unwrap();
203 Scratch(dir)
204 }
205
206 #[test]
207 fn read_of_an_absent_file_is_verified_absent() {
208 let dir = scratch_dir("absent");
209 assert_eq!(read(&dir.0).unwrap(), None);
210 }
211
212 /// #1085 review: the property `SchemaLock`'s `On { existing }` exists to
213 /// protect — a present-but-unreadable lock file must be a real error, not
214 /// silently degrade to "verified absent" (which would re-baseline a real
215 /// registry's history). Unix-only: `chmod`-based permission denial has no
216 /// portable Windows equivalent, and this crate's other permission-style
217 /// tests are unix-gated the same way.
218 #[cfg(unix)]
219 #[test]
220 fn read_of_an_unreadable_present_file_is_a_real_error_not_absent() {
221 use std::os::unix::fs::PermissionsExt;
222
223 let dir = scratch_dir("unreadable");
224 std::fs::write(lock_path(&dir.0), "version = 1\n").unwrap();
225 std::fs::set_permissions(lock_path(&dir.0), std::fs::Permissions::from_mode(0o000))
226 .unwrap();
227
228 // Skip if the test runs as root (or another privileged context) where
229 // permission bits don't actually block the read.
230 if std::fs::read_to_string(lock_path(&dir.0)).is_ok() {
231 return;
232 }
233 assert!(
234 read(&dir.0).is_err(),
235 "an unreadable-but-present file must not be reported as absent"
236 );
237 }
238
239 #[test]
240 fn write_then_read_round_trips() {
241 let dir = scratch_dir("roundtrip");
242 let content = "version = 1\n";
243 write(&dir.0, content).unwrap();
244 assert_eq!(read(&dir.0).unwrap().as_deref(), Some(content));
245 }
246
247 #[test]
248 fn write_is_a_no_op_when_content_is_unchanged() {
249 let dir = scratch_dir("noop-write");
250 let content = "version = 1\n";
251 write(&dir.0, content).unwrap();
252 let mtime_before = std::fs::metadata(lock_path(&dir.0))
253 .unwrap()
254 .modified()
255 .unwrap();
256 std::thread::sleep(std::time::Duration::from_millis(10));
257 write(&dir.0, content).unwrap();
258 let mtime_after = std::fs::metadata(lock_path(&dir.0))
259 .unwrap()
260 .modified()
261 .unwrap();
262 assert_eq!(
263 mtime_before, mtime_after,
264 "unchanged content must not rewrite the file"
265 );
266 }
267}