Skip to main content

nibkeep_node/
engines.rs

1//! The engines file: the version of a replica's stored files, and the programs that open the
2//! replica, each with the latest version its engine reads, so that programs whose engines
3//! are of different versions share one replica ([storage](../../../docs/spec/storage.md#16-engines-of-different-versions)).
4//!
5//! A program reads the file before any other of the replica but the place files, and opens
6//! nothing if the replica is of a later version than its engine reads. It records itself
7//! as it opens the replica, so that a later engine knows which programs still read only
8//! the versions before its own.
9
10use std::fs;
11use std::io;
12use std::path::Path;
13use std::sync::OnceLock;
14
15use nibkeep_base::cbor::{self, FromCbor, ToCbor, Value};
16
17use crate::info::write_file;
18use crate::{DAY, NodeError};
19
20/// The engines file, in a replica's folder.
21pub(crate) const ENGINES: &str = "engines.cbor";
22
23/// The file that a program locks while it records itself in the engines file.
24const ENGINES_LOCK: &str = "engines.lock";
25
26/// The version of a replica's stored files that this engine reads and writes: those of
27/// version 1 of the storage specification.
28pub const REPLICA_VERSION: u64 = 1;
29
30/// The engine's version, which the engines file records of each program, and a copy of
31/// `nibkeep-sync` tells, so that the newest runs.
32pub const ENGINE_VERSION: &str = env!("CARGO_PKG_VERSION");
33
34/// The name that this program gave itself.
35static PROGRAM: OnceLock<String> = OnceLock::new();
36
37/// Names this program, as the engines file of each replica that it opens records it, such
38/// as `Passwords`: once, before it opens a library. A later name, or an empty one, is
39/// ignored. A program that names itself nothing is named by its executable's file name.
40pub fn name_program(name: &str) {
41	// The apps name themselves on every request.
42	if !name.is_empty() && PROGRAM.get().is_none() {
43		let _ = PROGRAM.set(name.to_owned());
44	}
45}
46
47/// This program's name.
48fn program() -> String {
49	PROGRAM.get().cloned().unwrap_or_else(|| {
50		std::env::current_exe()
51			.ok()
52			.and_then(|executable| {
53				executable
54					.file_stem()
55					.map(|stem| stem.to_string_lossy().into_owned())
56			})
57			.unwrap_or_else(|| "unnamed".to_owned())
58	})
59}
60
61/// Checks that this engine reads the replica in `folder`: that its engines file, if it has
62/// one, holds a version no later than [`REPLICA_VERSION`]. Writes nothing.
63///
64/// # Errors
65///
66/// Returns [`NodeError::NewerFormats`] if the replica is of a later version, and
67/// [`NodeError::Damaged`] if its engines file does not read.
68pub(crate) fn check(folder: &Path) -> Result<(), NodeError> {
69	read(folder).map(drop)
70}
71
72/// Writes the engines file of a new replica into its folder, before the folder goes in
73/// place: of this engine's version, recording this program as having opened it at `now`.
74pub(crate) fn create(folder: &Path, now: u64) -> Result<(), NodeError> {
75	let items = vec![
76		REPLICA_VERSION.to_cbor(),
77		Value::Array(vec![entry(&program(), now)]),
78	];
79	write_file(&folder.join(ENGINES), &cbor::encode(&Value::Array(items)))
80}
81
82/// Records this program in the engines file of the replica in `folder`, as having opened it
83/// at `now`: replaces its entry, or adds one, and keeps the other entries, and what the file
84/// holds after the items it knows, as they are. Writes the file only if its entry changes,
85/// or was written on another day, once a day at most, so that opening mostly writes nothing.
86///
87/// # Errors
88///
89/// As [`check`], and returns an error if the lock or the file cannot be written.
90pub(crate) fn record(folder: &Path, now: u64) -> Result<(), NodeError> {
91	record_as(folder, &program(), now)
92}
93
94/// Records `name` in the engines file, as [`record`] does.
95fn record_as(folder: &Path, name: &str, now: u64) -> Result<(), NodeError> {
96	let own = entry(name, now);
97	// Most openings find their entry as it is to be, and take no lock.
98	if let Some(items) = read(folder)?
99		&& entry_of(&items, name).is_some_and(|found| same_day(found, &own))
100	{
101		return Ok(());
102	}
103	let lock_path = folder.join(ENGINES_LOCK);
104	let lock = fs::OpenOptions::new()
105		.create(true)
106		.truncate(false)
107		.write(true)
108		.open(&lock_path)
109		.map_err(NodeError::file(&lock_path))?;
110	// Held until the file is written, so that two programs never record over each other;
111	// the file is read again under it, as another may have written it meanwhile.
112	lock.lock().map_err(NodeError::file(&lock_path))?;
113	let mut items =
114		read(folder)?.unwrap_or_else(|| vec![REPLICA_VERSION.to_cbor(), Value::Array(Vec::new())]);
115	let Some(Value::Array(programs)) = items.get_mut(1) else {
116		return Err(damaged());
117	};
118	match programs
119		.iter_mut()
120		.find(|program| name_of(program) == Some(name))
121	{
122		Some(found) if same_day(found, &own) => return Ok(()),
123		Some(found) => *found = own,
124		None => programs.push(own),
125	}
126	write_file(&folder.join(ENGINES), &cbor::encode(&Value::Array(items)))
127}
128
129/// Reads the engines file of the replica in `folder`: its items, the version first, then
130/// the programs, then any that a later version adds; or `None` if it has none.
131fn read(folder: &Path) -> Result<Option<Vec<Value>>, NodeError> {
132	let path = folder.join(ENGINES);
133	let bytes = match fs::read(&path) {
134		Ok(bytes) => bytes,
135		Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
136		Err(error) => return Err(NodeError::file(&path)(error)),
137	};
138	let Ok(Value::Array(items)) = cbor::decode(&bytes) else {
139		return Err(damaged());
140	};
141	// The version first: of a later one, this engine needs to know nothing more.
142	let version = items
143		.first()
144		.and_then(|version| u64::from_cbor(version).ok())
145		.filter(|&version| version > 0)
146		.ok_or_else(damaged)?;
147	if version > REPLICA_VERSION {
148		return Err(NodeError::NewerFormats);
149	}
150	match items.get(1) {
151		Some(Value::Array(programs)) if programs.iter().all(is_entry) => Ok(Some(items)),
152		_ => Err(damaged()),
153	}
154}
155
156/// The error of an engines file that does not read.
157fn damaged() -> NodeError {
158	NodeError::Damaged("the replica's engines file does not read".to_owned())
159}
160
161/// A program's entry, `[name, reads, engine, opened]`: of this engine, opened at `now`.
162fn entry(name: &str, now: u64) -> Value {
163	Value::Array(vec![
164		name.to_cbor(),
165		REPLICA_VERSION.to_cbor(),
166		ENGINE_VERSION.to_cbor(),
167		now.to_cbor(),
168	])
169}
170
171/// Whether a value is a program's entry: `[name, reads, engine, opened]`, with perhaps items
172/// after them that a later version adds.
173fn is_entry(entry: &Value) -> bool {
174	let Value::Array(items) = entry else {
175		return false;
176	};
177	matches!(
178		items.as_slice(),
179		[Value::Text(_), reads, Value::Text(_), opened, ..]
180			if u64::from_cbor(reads).is_ok() && u64::from_cbor(opened).is_ok()
181	)
182}
183
184/// The entry of the program `name` in the engines file's items, if it has one.
185fn entry_of<'a>(items: &'a [Value], name: &str) -> Option<&'a Value> {
186	match items.get(1) {
187		Some(Value::Array(programs)) => programs
188			.iter()
189			.find(|program| name_of(program) == Some(name)),
190		_ => None,
191	}
192}
193
194/// The name of a program's entry.
195fn name_of(entry: &Value) -> Option<&str> {
196	match entry {
197		Value::Array(items) => match items.first() {
198			Some(Value::Text(name)) => Some(name),
199			_ => None,
200		},
201		_ => None,
202	}
203}
204
205/// Whether an entry says what `own` says, with a time of the same day (UTC), and nothing
206/// more.
207fn same_day(entry: &Value, own: &Value) -> bool {
208	let (Value::Array(entry), Value::Array(own)) = (entry, own) else {
209		return false;
210	};
211	let day = |items: &[Value]| {
212		items
213			.get(3)
214			.and_then(|opened| u64::from_cbor(opened).ok())
215			.map(|opened| opened / DAY)
216	};
217	entry.len() == own.len() && entry[..3] == own[..3] && day(entry) == day(own)
218}
219
220#[cfg(test)]
221mod tests {
222	use super::*;
223
224	fn folder(name: &str) -> std::path::PathBuf {
225		nibkeep_testkit::empty_directory(std::env::temp_dir(), &format!("engines {name}"))
226	}
227
228	fn names(folder: &Path) -> Vec<String> {
229		let items = read(folder).expect("reads").expect("a file");
230		let Value::Array(programs) = &items[1] else {
231			panic!("the programs");
232		};
233		programs
234			.iter()
235			.map(|program| name_of(program).expect("a name").to_owned())
236			.collect()
237	}
238
239	#[test]
240	fn each_program_records_an_entry_of_its_own() {
241		let folder = folder("two programs");
242		record_as(&folder, "nib", 1_000).expect("records");
243		record_as(&folder, "Passwords", 2_000).expect("records");
244		record_as(&folder, "nib", 3_000).expect("records again");
245		assert_eq!(names(&folder), ["nib", "Passwords"]);
246		check(&folder).expect("reads");
247	}
248
249	#[test]
250	fn a_record_of_the_same_day_writes_nothing_and_of_another_day_does() {
251		let folder = folder("days");
252		record_as(&folder, "nib", DAY + 1).expect("records");
253		let first = fs::read(folder.join(ENGINES)).expect("reads");
254		record_as(&folder, "nib", 2 * DAY - 1).expect("records");
255		assert_eq!(fs::read(folder.join(ENGINES)).expect("reads"), first);
256		record_as(&folder, "nib", 2 * DAY).expect("records");
257		assert_ne!(fs::read(folder.join(ENGINES)).expect("reads"), first);
258	}
259
260	#[test]
261	fn a_program_named_nothing_takes_its_executables_name() {
262		name_program("");
263		let executable = std::env::current_exe().expect("an executable");
264		assert_eq!(
265			Some(program().as_str()),
266			executable.file_stem().and_then(|stem| stem.to_str())
267		);
268	}
269}