Skip to main content

nibkeep_node/
role.rs

1//! The sync role ([technical design](../../../docs/Technical-design.md#105-the-sync-role)): one program
2//! on each replica syncs it for all, the one that holds the lock on `sync.lock` in the
3//! replica's folder. The holder runs the replica's endpoint, answers the replicas that
4//! connect, and connects to them as changes come and replicas appear. The others ask it
5//! through `sync.sqlite`, an encrypted database beside it, where it records what it does.
6//! A program that pairs borrows the network, by locking `sync.lent`.
7
8use std::collections::{BTreeMap, BTreeSet};
9use std::fs::{File, OpenOptions, TryLockError};
10use std::net::SocketAddr;
11use std::panic::{AssertUnwindSafe, catch_unwind};
12use std::path::{Path, PathBuf};
13use std::sync::atomic::{AtomicBool, Ordering};
14use std::sync::{Arc, mpsc};
15use std::time::{Duration, Instant};
16
17use nibkeep_base::{EntityId, Hash};
18use nibkeep_crypto::rand_core::CryptoRng;
19use nibkeep_net::{NetError, Network, Options};
20use nibkeep_store::EncryptedDatabase;
21use rusqlite::{OptionalExtension, params};
22
23use crate::library::backups::{Backup, BackupUpdate};
24use crate::library::checking::{CheckRun, Pace, Part, Round};
25use crate::network::{
26	Answered, RemovalPass, SyncedWith, answer_connection, remove_unkept, retry_in_use,
27	sync_with_found,
28};
29use crate::{Closed, Library, NodeError};
30
31/// The file whose lock is the sync role.
32const ROLE: &str = "sync.lock";
33
34/// The file that a program locks while it borrows the network to pair.
35const LENT: &str = "sync.lent";
36
37/// The database through which programs ask the holder, and read what it did.
38const RECORDS: &str = "sync.sqlite";
39
40/// The context of the key of the records, derived from the replica's storage key.
41const RECORDS_CONTEXT: &str = "nibkeep 2026-10 sync records";
42
43/// How long a step of the holder waits for a connection, between looking at the rest.
44const STEP: Duration = Duration::from_millis(250);
45
46/// How long a program that takes the sync role tries, as another may hold its lock for a
47/// moment only to see whether a program holds the role.
48const LOOKING: Duration = Duration::from_millis(50);
49
50/// How long a program waits to open the library, for a program that has it to itself.
51const OPEN_WAIT: Duration = Duration::from_secs(10);
52
53/// How long a program that borrows the network tries to lock `sync.lent`, which the holder
54/// looks at for a moment now and then, before it takes it that another borrows it.
55const LENT_TRY: Duration = Duration::from_secs(2);
56
57/// How soon a pass of removals that had room for no more is followed by another.
58const REMOVE_SOON: Duration = Duration::from_secs(10);
59
60/// How long a program that borrows the network waits for the holder to stop its endpoint,
61/// once the syncs under way end.
62const LEND_WAIT: Duration = Duration::from_mins(1);
63
64/// The sync role of a replica, held: the lock on its `sync.lock`, which the system lets go
65/// of when the program ends, even by a crash.
66#[derive(Debug)]
67pub struct Role {
68	_lock: File,
69}
70
71fn open_lock(path: &Path) -> Result<File, NodeError> {
72	OpenOptions::new()
73		.read(true)
74		.write(true)
75		.create(true)
76		.truncate(false)
77		.open(path)
78		.map_err(NodeError::file(path))
79}
80
81/// Takes the lock on a file alone, unless another holds it: whether it did.
82fn try_alone(file: &File, path: &Path) -> Result<bool, NodeError> {
83	match file.try_lock() {
84		Ok(()) => Ok(true),
85		Err(TryLockError::WouldBlock) => Ok(false),
86		Err(TryLockError::Error(error)) => Err(NodeError::file(path)(error)),
87	}
88}
89
90impl Role {
91	/// Takes the sync role of a closed library's replica, unless another program, or
92	/// another part of this one, holds it.
93	///
94	/// # Errors
95	///
96	/// Returns an error if the lock's file cannot be opened or locked.
97	pub fn take(closed: &Closed) -> Result<Option<Self>, NodeError> {
98		Self::take_at(closed.directory())
99	}
100
101	/// Takes the sync role of the replica in `directory`, as [`Role::take`] does.
102	fn take_at(directory: &Path) -> Result<Option<Self>, NodeError> {
103		let path = directory.join(ROLE);
104		let file = open_lock(&path)?;
105		let tried = Instant::now();
106		loop {
107			if try_alone(&file, &path)? {
108				return Ok(Some(Self { _lock: file }));
109			}
110			if tried.elapsed() >= LOOKING {
111				return Ok(None);
112			}
113			std::thread::sleep(Duration::from_millis(5));
114		}
115	}
116
117	/// Whether a program holds the sync role of the replica in `directory`: its lock, taken
118	/// for a moment, tells.
119	fn held_at(directory: &Path) -> Result<bool, NodeError> {
120		let path = directory.join(ROLE);
121		let file = open_lock(&path)?;
122		Ok(!try_alone(&file, &path)?)
123	}
124
125	/// Waits for the sync role, taking it as soon as the program that holds it lets go, or
126	/// ends, until `stop` is set.
127	///
128	/// # Errors
129	///
130	/// Returns an error if the lock's file cannot be opened or locked.
131	pub fn wait(closed: &Closed, stop: &AtomicBool) -> Result<Option<Self>, NodeError> {
132		loop {
133			if let Some(role) = Self::take(closed)? {
134				return Ok(Some(role));
135			}
136			if stop.load(Ordering::SeqCst) {
137				return Ok(None);
138			}
139			std::thread::sleep(STEP);
140		}
141	}
142}
143
144/// What the holder of the sync role records of itself.
145#[derive(Clone, Debug, PartialEq, Eq)]
146pub struct HolderRecord {
147	/// The program that holds the role, as it names itself.
148	pub program: String,
149	/// The UDP port its endpoint takes connections on, or `None` while it runs none, as
150	/// while another program borrows the network to pair.
151	pub port: Option<u16>,
152	/// Since when it holds the role.
153	pub since: u64,
154}
155
156/// What the holder of the sync role records of another replica.
157#[derive(Clone, Debug, Default, PartialEq, Eq)]
158pub struct ReplicaRecord {
159	/// Whether it is on the network now.
160	pub present: bool,
161	/// When it was last seen on the network.
162	pub seen: Option<u64>,
163	/// When it last synced, or tried to.
164	pub synced: Option<u64>,
165	/// How many changes that sync brought here.
166	pub received: usize,
167	/// How many it sent there.
168	pub sent: usize,
169	/// Why it failed, if it did.
170	pub error: Option<String>,
171}
172
173/// The records of the sync role, in `sync.sqlite` beside its lock, encrypted under a key of
174/// the replica's: who holds the role, what other programs ask it, and what it did.
175pub struct Records {
176	database: EncryptedDatabase,
177	/// The replica's folder, where the role's lock is.
178	directory: PathBuf,
179}
180
181const TABLES: &str = "
182CREATE TABLE IF NOT EXISTS holder (
183	one INTEGER PRIMARY KEY CHECK (one = 1),
184	program TEXT NOT NULL,
185	port INTEGER,
186	since INTEGER NOT NULL
187);
188CREATE TABLE IF NOT EXISTS asks (
189	n INTEGER PRIMARY KEY,
190	replica BLOB,
191	asked INTEGER NOT NULL,
192	done INTEGER
193);
194CREATE TABLE IF NOT EXISTS replicas (
195	replica BLOB PRIMARY KEY,
196	present INTEGER NOT NULL DEFAULT 0,
197	seen INTEGER,
198	synced INTEGER,
199	received INTEGER NOT NULL DEFAULT 0,
200	sent INTEGER NOT NULL DEFAULT 0,
201	error TEXT
202) WITHOUT ROWID;
203CREATE TABLE IF NOT EXISTS checking (
204	one INTEGER PRIMARY KEY CHECK (one = 1),
205	began INTEGER NOT NULL,
206	blobs_total INTEGER NOT NULL,
207	blobs_read INTEGER NOT NULL,
208	blobs_after BLOB,
209	blobs_done INTEGER NOT NULL,
210	plain_total INTEGER NOT NULL,
211	plain_read INTEGER NOT NULL,
212	plain_after BLOB,
213	plain_done INTEGER NOT NULL,
214	last INTEGER NOT NULL
215);
216CREATE TABLE IF NOT EXISTS holds (
217	sealed BLOB PRIMARY KEY,
218	until INTEGER NOT NULL
219) WITHOUT ROWID;
220CREATE TABLE IF NOT EXISTS removing (
221	sealed BLOB PRIMARY KEY,
222	until INTEGER NOT NULL
223) WITHOUT ROWID;
224CREATE TABLE IF NOT EXISTS unkept (
225	sealed BLOB PRIMARY KEY,
226	since INTEGER NOT NULL
227) WITHOUT ROWID;
228CREATE TABLE IF NOT EXISTS backups (
229	backup BLOB PRIMARY KEY,
230	folder TEXT NOT NULL,
231	updated INTEGER,
232	kept INTEGER
233) WITHOUT ROWID;
234";
235
236/// How long a replica holds a sealed blob that it proved to another, so that it does not
237/// remove it meanwhile, and how long a mark of a blob it is removing stands at most:
238/// 10 minutes ([technical design: the planner]).
239///
240/// [technical design: the planner]: ../../../docs/Technical-design.md#99-the-planner
241pub(crate) const HOLD_FOR: u64 = 600_000;
242
243fn database(error: rusqlite::Error) -> NodeError {
244	NodeError::Store(nibkeep_store::StoreError::Database(error))
245}
246
247fn millis(at: u64) -> i64 {
248	i64::try_from(at).unwrap_or(i64::MAX)
249}
250
251fn unsigned(value: Option<i64>) -> Option<u64> {
252	value.and_then(|value| u64::try_from(value).ok())
253}
254
255impl Library {
256	/// Takes the sync role of the library's replica, as [`Role::take`] does: for a program
257	/// that has it open.
258	///
259	/// # Errors
260	///
261	/// Returns an error if the lock's file cannot be opened or locked.
262	pub fn take_role(&self) -> Result<Option<Role>, NodeError> {
263		Role::take_at(self.directory())
264	}
265
266	/// The records of the replica's sync role, which programs read and write through an
267	/// encrypted database beside its lock; `rng` makes the database's own key and nonces.
268	///
269	/// # Errors
270	///
271	/// Returns an error if the database cannot be opened or made.
272	pub fn sync_records(&self, rng: impl CryptoRng + Send + 'static) -> Result<Records, NodeError> {
273		let key = self.derived_key(RECORDS_CONTEXT);
274		let opened = EncryptedDatabase::open(&self.directory().join(RECORDS), &key, rng)?;
275		opened
276			.connection()
277			.execute_batch(TABLES)
278			.map_err(database)?;
279		Ok(Records {
280			database: opened,
281			directory: self.directory().to_path_buf(),
282		})
283	}
284}
285
286impl Records {
287	/// Who holds the role, as it recorded, if any program does: a record that a program
288	/// left as it ended, as by a crash or as an app quits, says nothing once its lock is
289	/// free.
290	///
291	/// # Errors
292	///
293	/// Returns an error if the database cannot be read, or the lock's file opened.
294	pub fn holder(&self) -> Result<Option<HolderRecord>, NodeError> {
295		if !Role::held_at(&self.directory)? {
296			return Ok(None);
297		}
298		self.database
299			.connection()
300			.query_row(
301				"SELECT program, port, since FROM holder WHERE one = 1",
302				[],
303				|row| {
304					Ok(HolderRecord {
305						program: row.get(0)?,
306						port: row
307							.get::<_, Option<i64>>(1)?
308							.and_then(|port| u16::try_from(port).ok()),
309						since: unsigned(row.get(2)?).unwrap_or(0),
310					})
311				},
312			)
313			.optional()
314			.map_err(database)
315	}
316
317	fn set_holder(&self, program: &str, port: Option<u16>, since: u64) -> Result<(), NodeError> {
318		self.database
319			.connection()
320			.execute(
321				"INSERT INTO holder (one, program, port, since) VALUES (1, ?1, ?2, ?3)
322				 ON CONFLICT (one) DO UPDATE SET program = ?1, port = ?2, since = ?3",
323				params![program, port, millis(since)],
324			)
325			.map(drop)
326			.map_err(database)
327	}
328
329	/// Clears who holds the role, and who is on the network, which only a holder that runs
330	/// knows: as a holder ends, and as another takes the role after one that ended
331	/// without clearing them, as by a crash.
332	fn clear_holder(&self) -> Result<(), NodeError> {
333		self.database
334			.connection()
335			.execute_batch("DELETE FROM holder; UPDATE replicas SET present = 0;")
336			.map_err(database)
337	}
338
339	/// Asks the holder to sync with one replica, or with all it finds: returns the ask,
340	/// whose answer [`Records::answered`] tells.
341	///
342	/// # Errors
343	///
344	/// Returns an error if the database cannot be written.
345	pub fn ask(&self, replica: Option<EntityId>, at: u64) -> Result<i64, NodeError> {
346		let connection = self.database.connection();
347		connection
348			.execute(
349				"INSERT INTO asks (replica, asked) VALUES (?1, ?2)",
350				params![
351					replica.map(|replica| replica.as_bytes().to_vec()),
352					millis(at)
353				],
354			)
355			.map_err(database)?;
356		Ok(connection.last_insert_rowid())
357	}
358
359	/// Where the round of checks under way stands, if one began ([technical design: checking
360	/// and repair]).
361	///
362	/// [technical design: checking and repair]: ../../../docs/Technical-design.md#97-checking-and-repair
363	///
364	/// # Errors
365	///
366	/// Returns an error if the database cannot be read.
367	pub fn round(&self) -> Result<Option<Round>, NodeError> {
368		Ok(self.round_with_last()?.map(|(round, _)| round))
369	}
370
371	/// Where the round of checks under way stands, with when a check last ran.
372	pub(crate) fn round_with_last(&self) -> Result<Option<(Round, Option<u64>)>, NodeError> {
373		let part = |row: &rusqlite::Row<'_>, at: usize| -> rusqlite::Result<Part> {
374			Ok(Part {
375				total: unsigned(row.get(at)?).unwrap_or(0),
376				read: unsigned(row.get(at + 1)?).unwrap_or(0),
377				after: row.get(at + 2)?,
378				done: row.get(at + 3)?,
379			})
380		};
381		self.database
382			.connection()
383			.query_row(
384				"SELECT began, blobs_total, blobs_read, blobs_after, blobs_done,
385					plain_total, plain_read, plain_after, plain_done, last
386				 FROM checking WHERE one = 1",
387				[],
388				|row| {
389					Ok((
390						Round {
391							began: unsigned(row.get(0)?).unwrap_or(0),
392							blobs: part(row, 1)?,
393							plain: part(row, 5)?,
394						},
395						unsigned(row.get(9)?),
396					))
397				},
398			)
399			.optional()
400			.map_err(database)
401	}
402
403	/// Saves where the round of checks stands, as a check that ran until `last` left it.
404	pub(crate) fn save_round(&self, round: &Round, last: u64) -> Result<(), NodeError> {
405		let size = |bytes: u64| i64::try_from(bytes).unwrap_or(i64::MAX);
406		self.database
407			.connection()
408			.execute(
409				"INSERT OR REPLACE INTO checking (one, began, blobs_total, blobs_read, blobs_after,
410					blobs_done, plain_total, plain_read, plain_after, plain_done, last)
411				 VALUES (1, ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
412				params![
413					millis(round.began),
414					size(round.blobs.total),
415					size(round.blobs.read),
416					round.blobs.after,
417					round.blobs.done,
418					size(round.plain.total),
419					size(round.plain.read),
420					round.plain.after,
421					round.plain.done,
422					millis(last),
423				],
424			)
425			.map(drop)
426			.map_err(database)
427	}
428
429	/// When the holder answered an ask, if it did: once the sync with those of the replicas
430	/// asked for that it found on the network ended, whose records then say how it went.
431	///
432	/// # Errors
433	///
434	/// Returns an error if the database cannot be read.
435	pub fn answered(&self, ask: i64) -> Result<Option<u64>, NodeError> {
436		Ok(unsigned(
437			self.database
438				.connection()
439				.query_row("SELECT done FROM asks WHERE n = ?1", [ask], |row| {
440					row.get(0)
441				})
442				.optional()
443				.map_err(database)?
444				.flatten(),
445		))
446	}
447
448	/// The asks not answered yet: each, and the replica it names, or `None` for all.
449	fn open_asks(&self) -> Result<Vec<(i64, Option<EntityId>)>, NodeError> {
450		let connection = self.database.connection();
451		let mut statement = connection
452			.prepare_cached("SELECT n, replica FROM asks WHERE done IS NULL ORDER BY n")
453			.map_err(database)?;
454		let rows = statement
455			.query_map([], |row| {
456				let replica: Option<Vec<u8>> = row.get(1)?;
457				Ok((row.get(0)?, replica))
458			})
459			.map_err(database)?;
460		let mut asks = Vec::new();
461		for row in rows {
462			let (ask, replica) = row.map_err(database)?;
463			let replica = replica
464				.and_then(|bytes| <[u8; 16]>::try_from(bytes).ok())
465				.map(EntityId::from_bytes);
466			asks.push((ask, replica));
467		}
468		Ok(asks)
469	}
470
471	fn answer(&self, ask: i64, at: u64) -> Result<(), NodeError> {
472		self.database
473			.connection()
474			.execute(
475				"UPDATE asks SET done = ?2 WHERE n = ?1",
476				params![ask, millis(at)],
477			)
478			.map(drop)
479			.map_err(database)
480	}
481
482	/// What the holder recorded of each other replica. Only a holder that runs knows which
483	/// are on the network: once its lock is free, none is, whatever it left recorded.
484	///
485	/// # Errors
486	///
487	/// Returns an error if the database cannot be read, or the lock's file opened.
488	pub fn replicas(&self) -> Result<BTreeMap<EntityId, ReplicaRecord>, NodeError> {
489		let held = Role::held_at(&self.directory)?;
490		let connection = self.database.connection();
491		let mut statement = connection
492			.prepare_cached(
493				"SELECT replica, present, seen, synced, received, sent, error FROM replicas",
494			)
495			.map_err(database)?;
496		let rows = statement
497			.query_map([], |row| {
498				let replica: Vec<u8> = row.get(0)?;
499				let present: i64 = row.get(1)?;
500				let received: i64 = row.get(4)?;
501				let sent: i64 = row.get(5)?;
502				Ok((
503					replica,
504					ReplicaRecord {
505						present: held && present != 0,
506						seen: unsigned(row.get(2)?),
507						synced: unsigned(row.get(3)?),
508						received: usize::try_from(received).unwrap_or(0),
509						sent: usize::try_from(sent).unwrap_or(0),
510						error: row.get(6)?,
511					},
512				))
513			})
514			.map_err(database)?;
515		let mut records = BTreeMap::new();
516		for row in rows {
517			let (replica, record) = row.map_err(database)?;
518			if let Ok(replica) = <[u8; 16]>::try_from(replica) {
519				records.insert(EntityId::from_bytes(replica), record);
520			}
521		}
522		Ok(records)
523	}
524
525	/// What the holder recorded of each replica that it synced with at `asked` or later, by
526	/// the wall clock, as in answer to an ask made then: a sync recorded before was not the
527	/// one asked for.
528	///
529	/// # Errors
530	///
531	/// Returns an error if the database cannot be read.
532	pub fn synced_since(&self, asked: u64) -> Result<BTreeMap<EntityId, ReplicaRecord>, NodeError> {
533		let mut records = self.replicas()?;
534		records.retain(|_, record| record.synced.is_some_and(|at| at >= asked));
535		Ok(records)
536	}
537
538	fn record_presence(&self, replica: EntityId, present: bool, at: u64) -> Result<(), NodeError> {
539		self.database
540			.connection()
541			.execute(
542				"INSERT INTO replicas (replica, present, seen) VALUES (?1, ?2, ?3)
543				 ON CONFLICT (replica) DO UPDATE SET present = ?2,
544				 seen = CASE WHEN ?2 THEN ?3 ELSE seen END",
545				params![replica.as_bytes().to_vec(), present, millis(at)],
546			)
547			.map(drop)
548			.map_err(database)
549	}
550
551	fn record_sync(
552		&self,
553		replica: EntityId,
554		at: u64,
555		result: Result<(usize, usize), String>,
556	) -> Result<(), NodeError> {
557		let (received, sent, error) = match result {
558			Ok((received, sent)) => (received, sent, None),
559			Err(error) => (0, 0, Some(error)),
560		};
561		self.database
562			.connection()
563			.execute(
564				"INSERT INTO replicas (replica, present, seen, synced, received, sent, error)
565				 VALUES (?1, 1, ?2, ?2, ?3, ?4, ?5)
566				 ON CONFLICT (replica) DO UPDATE SET present = 1, seen = ?2, synced = ?2,
567				 received = ?3, sent = ?4, error = ?5",
568				params![
569					replica.as_bytes().to_vec(),
570					millis(at),
571					i64::try_from(received).unwrap_or(i64::MAX),
572					i64::try_from(sent).unwrap_or(i64::MAX),
573					error
574				],
575			)
576			.map(drop)
577			.map_err(database)
578	}
579
580	/// Holds these sealed blobs for another replica that is about to remove its copies, as
581	/// this one proves them at `at`: it removes none of them for [`HOLD_FOR`]. Returns those
582	/// held, which are all but those it is removing itself, which it proves to nobody.
583	pub(crate) fn hold(&self, sealed: &[Hash], at: u64) -> Result<BTreeSet<Hash>, NodeError> {
584		self.marking(sealed, at, ("holds", "removing"))
585	}
586
587	/// Marks these sealed blobs as being removed at `at`, so that none of them is proved to
588	/// another replica meanwhile. Returns those marked, which are all but those it holds for
589	/// another replica, which it does not remove.
590	pub(crate) fn begin_removing(
591		&self,
592		sealed: &[Hash],
593		at: u64,
594	) -> Result<BTreeSet<Hash>, NodeError> {
595		self.marking(sealed, at, ("removing", "holds"))
596	}
597
598	/// Clears the marks of blobs that it was removing, once they are gone or stay after all.
599	pub(crate) fn end_removing(&self, sealed: &[Hash]) -> Result<(), NodeError> {
600		let connection = self.database.connection();
601		let transaction = rusqlite::Transaction::new_unchecked(
602			connection,
603			rusqlite::TransactionBehavior::Immediate,
604		)
605		.map_err(database)?;
606		{
607			let mut delete = transaction
608				.prepare_cached("DELETE FROM removing WHERE sealed = ?1")
609				.map_err(database)?;
610			for each in sealed {
611				delete.execute([each.to_multihash()]).map_err(database)?;
612			}
613		}
614		transaction.commit().map_err(database)
615	}
616
617	/// Since when this replica no longer keeps each of these sealed blobs that it holds, as
618	/// its passes of removals first found it so, `at` for those found now: a device that waits
619	/// before purging removes none before its wait has passed since then
620	/// ([technical design: copies that wait]).
621	///
622	/// [technical design: copies that wait]: ../../../docs/Technical-design.md#911-copies-that-wait
623	pub(crate) fn unkept_since(
624		&self,
625		sealed: &[Hash],
626		at: u64,
627	) -> Result<BTreeMap<Hash, u64>, NodeError> {
628		let connection = self.database.connection();
629		let transaction = rusqlite::Transaction::new_unchecked(
630			connection,
631			rusqlite::TransactionBehavior::Immediate,
632		)
633		.map_err(database)?;
634		let mut since = BTreeMap::new();
635		{
636			let mut insert = transaction
637				.prepare_cached("INSERT OR IGNORE INTO unkept (sealed, since) VALUES (?1, ?2)")
638				.map_err(database)?;
639			let mut select = transaction
640				.prepare_cached("SELECT since FROM unkept WHERE sealed = ?1")
641				.map_err(database)?;
642			for each in sealed {
643				insert
644					.execute(rusqlite::params![each.to_multihash(), millis(at)])
645					.map_err(database)?;
646				let found: i64 = select
647					.query_row([each.to_multihash()], |row| row.get(0))
648					.map_err(database)?;
649				since.insert(*each, u64::try_from(found).unwrap_or(0));
650			}
651		}
652		transaction.commit().map_err(database)?;
653		Ok(since)
654	}
655
656	/// Forgets since when blobs were no longer kept, but for those in `still`: a blob kept
657	/// again, or gone, starts anew if it is no longer kept later.
658	pub(crate) fn forget_unkept_but(&self, still: &BTreeSet<Hash>) -> Result<(), NodeError> {
659		let connection = self.database.connection();
660		let mut statement = connection
661			.prepare_cached("SELECT sealed FROM unkept")
662			.map_err(database)?;
663		let rows = statement
664			.query_map([], |row| row.get::<_, Vec<u8>>(0))
665			.map_err(database)?;
666		let mut gone = Vec::new();
667		for row in rows {
668			let bytes = row.map_err(database)?;
669			if Hash::from_multihash(&bytes).map_or(true, |sealed| !still.contains(&sealed)) {
670				gone.push(bytes);
671			}
672		}
673		for bytes in gone {
674			connection
675				.execute("DELETE FROM unkept WHERE sealed = ?1", [bytes])
676				.map_err(database)?;
677		}
678		Ok(())
679	}
680
681	/// The sealed blobs that this replica holds for others at `at`, as it proved them.
682	///
683	/// # Errors
684	///
685	/// Returns an error if the database cannot be read.
686	pub fn holds(&self, at: u64) -> Result<BTreeSet<Hash>, NodeError> {
687		let connection = self.database.connection();
688		let mut statement = connection
689			.prepare_cached("SELECT sealed FROM holds WHERE until > ?1")
690			.map_err(database)?;
691		let rows = statement
692			.query_map([millis(at)], |row| row.get::<_, Vec<u8>>(0))
693			.map_err(database)?;
694		let mut held = BTreeSet::new();
695		for row in rows {
696			if let Ok(sealed) = Hash::from_multihash(&row.map_err(database)?) {
697				held.insert(sealed);
698			}
699		}
700		Ok(held)
701	}
702
703	/// Marks these sealed blobs in the table `(marked, against)`'s first, until [`HOLD_FOR`]
704	/// after `at`, but those that its second marks now, in one transaction that no other
705	/// program's marks come between; marks that ended go. Returns those marked.
706	fn marking(
707		&self,
708		sealed: &[Hash],
709		at: u64,
710		(marked, against): (&str, &str),
711	) -> Result<BTreeSet<Hash>, NodeError> {
712		let connection = self.database.connection();
713		let transaction = rusqlite::Transaction::new_unchecked(
714			connection,
715			rusqlite::TransactionBehavior::Immediate,
716		)
717		.map_err(database)?;
718		let now = millis(at);
719		let until = millis(at.saturating_add(HOLD_FOR));
720		let mut done = BTreeSet::new();
721		{
722			transaction
723				.execute(&format!("DELETE FROM {marked} WHERE until <= ?1"), [now])
724				.map_err(database)?;
725			transaction
726				.execute(&format!("DELETE FROM {against} WHERE until <= ?1"), [now])
727				.map_err(database)?;
728			let mut barred = transaction
729				.prepare_cached(&format!("SELECT 1 FROM {against} WHERE sealed = ?1"))
730				.map_err(database)?;
731			let mut mark = transaction
732				.prepare_cached(&format!(
733					"INSERT INTO {marked} (sealed, until) VALUES (?1, ?2)
734					 ON CONFLICT (sealed) DO UPDATE SET until = max(until, ?2)"
735				))
736				.map_err(database)?;
737			for each in sealed {
738				let bytes = each.to_multihash();
739				if barred.exists([&bytes]).map_err(database)? {
740					continue;
741				}
742				mark.execute(params![bytes, until]).map_err(database)?;
743				done.insert(*each);
744			}
745		}
746		transaction.commit().map_err(database)?;
747		Ok(done)
748	}
749
750	/// The person's backups that the holder found on this computer: where it last found
751	/// each, and when it last updated it here, or tried to.
752	///
753	/// # Errors
754	///
755	/// Returns an error if the database cannot be read.
756	pub fn backup_folders(&self) -> Result<BTreeMap<EntityId, FoundBackup>, NodeError> {
757		let connection = self.database.connection();
758		let mut statement = connection
759			.prepare_cached("SELECT backup, folder, updated, kept FROM backups")
760			.map_err(database)?;
761		let rows = statement
762			.query_map([], |row| {
763				Ok((
764					row.get::<_, Vec<u8>>(0)?,
765					row.get::<_, String>(1)?,
766					row.get::<_, Option<i64>>(2)?,
767					row.get::<_, Option<i64>>(3)?,
768				))
769			})
770			.map_err(database)?;
771		let mut found = BTreeMap::new();
772		for row in rows {
773			let (backup, folder, updated, kept) = row.map_err(database)?;
774			if let Ok(bytes) = <[u8; 16]>::try_from(backup.as_slice()) {
775				found.insert(
776					EntityId::from_bytes(bytes),
777					FoundBackup {
778						folder: PathBuf::from(folder),
779						updated: unsigned(updated),
780						kept: unsigned(kept),
781					},
782				);
783			}
784		}
785		Ok(found)
786	}
787
788	/// Records where the holder found a backup, and, if it updated it now or tried to,
789	/// when, and how many changes the replica kept then.
790	///
791	/// # Errors
792	///
793	/// Returns an error if the database cannot be written.
794	pub fn record_backup(
795		&self,
796		backup: EntityId,
797		folder: &Path,
798		updated: Option<(u64, usize)>,
799	) -> Result<(), NodeError> {
800		self.database
801			.connection()
802			.execute(
803				"INSERT INTO backups (backup, folder, updated, kept) VALUES (?1, ?2, ?3, ?4)
804				 ON CONFLICT (backup) DO UPDATE
805				 SET folder = excluded.folder,
806					updated = coalesce(excluded.updated, updated),
807					kept = coalesce(excluded.kept, kept)",
808				params![
809					backup.as_bytes().as_slice(),
810					folder.to_string_lossy(),
811					updated.map(|(at, _)| millis(at)),
812					updated.map(|(_, kept)| i64::try_from(kept).unwrap_or(i64::MAX))
813				],
814			)
815			.map_err(database)?;
816		Ok(())
817	}
818
819	/// SQLite's count of what other connections committed, which moves when a program asks.
820	fn version(&self) -> Result<i64, NodeError> {
821		self.database
822			.connection()
823			.query_row("PRAGMA data_version", [], |row| row.get(0))
824			.map_err(database)
825	}
826}
827
828/// The network, borrowed from the holder of the sync role to pair, until this goes: the
829/// lock on `sync.lent`, and the role itself if no program held it.
830#[derive(Debug)]
831pub struct Borrowed {
832	_lent: File,
833	_role: Option<Role>,
834}
835
836/// Borrows the network of a library's replica, to pair: locks `sync.lent`, which tells the
837/// holder of the sync role to stop its endpoint, and waits until it records that it runs
838/// none, or `stop` is set; or, if no program holds the role, takes it, so that none starts
839/// an endpoint meanwhile. The endpoint starts again once the borrowed network goes.
840///
841/// # Errors
842///
843/// Returns [`NodeError::NetworkBusy`] if another program borrows it already, or the holder
844/// keeps its endpoint; [`NodeError::PairingExpired`] once `stop` is set, as pairing does;
845/// and an error if the files cannot be read or written.
846pub fn borrow_network(
847	library: &Library,
848	stop: &AtomicBool,
849	rng: impl CryptoRng + Send + 'static,
850) -> Result<Borrowed, NodeError> {
851	let path = library.directory().join(LENT);
852	let lent = open_lock(&path)?;
853	// The holder looks at the lock now and then, for a moment.
854	let tried = Instant::now();
855	while !try_alone(&lent, &path)? {
856		if tried.elapsed() > LENT_TRY {
857			return Err(NodeError::NetworkBusy);
858		}
859		std::thread::sleep(Duration::from_millis(20));
860	}
861	if let Some(role) = library.take_role()? {
862		return Ok(Borrowed {
863			_lent: lent,
864			_role: Some(role),
865		});
866	}
867	let records = library.sync_records(rng)?;
868	let waited = Instant::now();
869	loop {
870		match records.holder()? {
871			Some(holder) if holder.port.is_some() => {}
872			// It stopped its endpoint, or ended without a record, as by a crash.
873			_ => {
874				return Ok(Borrowed {
875					_lent: lent,
876					_role: None,
877				});
878			}
879		}
880		if let Some(role) = library.take_role()? {
881			return Ok(Borrowed {
882				_lent: lent,
883				_role: Some(role),
884			});
885		}
886		if waited.elapsed() > LEND_WAIT {
887			return Err(NodeError::NetworkBusy);
888		}
889		if stop.load(Ordering::SeqCst) {
890			return Err(NodeError::PairingExpired);
891		}
892		std::thread::sleep(STEP);
893	}
894}
895
896/// Whether a program borrows the network of the replica in `closed`.
897fn lent(closed: &Closed) -> Result<bool, NodeError> {
898	let path = closed.directory().join(LENT);
899	let file = open_lock(&path)?;
900	match file.try_lock_shared() {
901		Ok(()) => {
902			let _ = file.unlock();
903			Ok(false)
904		}
905		Err(TryLockError::WouldBlock) => Ok(true),
906		Err(TryLockError::Error(error)) => Err(NodeError::file(&path)(error)),
907	}
908}
909
910/// How the holder of the sync role runs.
911pub struct Holding<'a> {
912	/// The program that holds the role, as the records name it, such as `nib sync --serve`.
913	pub program: &'a str,
914	/// How its endpoint starts: it takes connections on the first free port from
915	/// [`Options::port`], within ten, then on any.
916	pub network: Options,
917	/// Where other replicas are, found other than on the network, as in tests.
918	pub known: Vec<([u8; 32], Vec<SocketAddr>)>,
919	/// How long it waits after new changes before it syncs them, so that the changes of a
920	/// burst travel together.
921	pub quiet: Duration,
922	/// How long it waits at most after another replica appears before it connects, unless
923	/// that one connects meanwhile: a random wait up to this, so that two holders that see
924	/// each other at once seldom connect to each other at once.
925	pub appear_wait: Duration,
926	/// How it paces its checks of the replica's copies.
927	pub check: Pace,
928	/// Set, it lets go of the role, once the syncs under way end.
929	pub stop: &'a AtomicBool,
930	/// The wall clock.
931	pub now: &'a (dyn Fn() -> u64 + Sync),
932}
933
934impl Holding<'_> {
935	/// How long the holder waits after new changes, by default: a few seconds.
936	pub const QUIET: Duration = Duration::from_secs(3);
937
938	/// How long it waits at most after another replica appears, by default.
939	pub const APPEAR_WAIT: Duration = Duration::from_secs(5);
940}
941
942/// What the holder of the sync role did, for the program to show.
943#[derive(Debug)]
944pub enum Held {
945	/// Its endpoint started, on this port, or another than the one asked for, with why.
946	Started {
947		/// The port it takes connections on.
948		port: Option<u16>,
949		/// The port asked for, and why it was not had, if it took another.
950		refused: Option<(u16, String)>,
951	},
952	/// It stopped its endpoint, as another program borrows the network.
953	Lent,
954	/// It answered a sync that another replica started.
955	Answered(Answered),
956	/// It synced with another replica, which it connected to.
957	Synced(SyncedWith),
958	/// It checked a share of the replica's copies.
959	Checked(CheckRun),
960	/// It ran a pass of removals of the copies that the replica no longer keeps, or why it
961	/// could not.
962	Removed(Result<RemovalPass, NodeError>),
963	/// It updated one of the person's backups that it found, or tried to.
964	BackedUp(BackedUp),
965}
966
967/// An update of a backup that the holder of the sync role found.
968#[derive(Debug)]
969pub struct BackedUp {
970	/// The backup.
971	pub backup: Backup,
972	/// Where it found it.
973	pub folder: PathBuf,
974	/// What the update did, or why it failed.
975	pub updated: Result<BackupUpdate, NodeError>,
976}
977
978/// How often the holder looks for the person's backups: every 30 seconds.
979const BACKUPS_LOOK: Duration = Duration::from_secs(30);
980
981/// How long after its last update here the holder updates a backup that stays found, once
982/// new changes came: an hour.
983const BACKUP_AGAIN: u64 = 3_600_000;
984
985/// How long after its last update here the holder updates a backup that stays found, if no
986/// new change came, so that its checks go on: a day.
987const BACKUP_IDLE: u64 = 86_400_000;
988
989/// Where the holder of the sync role found one of the person's backups on this computer.
990#[derive(Clone, Debug, PartialEq, Eq)]
991pub struct FoundBackup {
992	/// The folder where it last found it.
993	pub folder: PathBuf,
994	/// When it last updated it here, or tried to.
995	pub updated: Option<u64>,
996	/// How many changes the replica kept then.
997	pub kept: Option<u64>,
998}
999
1000/// What a look for backups found, and the updates it ran.
1001struct BackupLook {
1002	/// The backups found.
1003	present: BTreeSet<EntityId>,
1004	/// The updates run.
1005	updates: Vec<BackedUp>,
1006}
1007
1008/// A sync that ended, on the thread that ran it, with how many changes the replica kept
1009/// as it began.
1010enum Finished {
1011	/// What was answered, or `None` if answering panicked.
1012	Answered(Option<Box<Answered>>, usize),
1013	/// The syncs with the replicas it connected to, or why none could start, and the asks
1014	/// they answer.
1015	Synced(Result<Vec<SyncedWith>, NodeError>, usize, Vec<i64>),
1016	/// A run of the checks of the replica's copies, or why it could not run.
1017	Checked(Result<CheckRun, NodeError>),
1018	/// A pass of removals, or why it could not run, with how many changes the replica kept
1019	/// as it began.
1020	Removed(Result<RemovalPass, NodeError>, usize),
1021	/// A look for the person's backups, with the updates it ran, or why it could not run.
1022	BackedUp(Result<BackupLook, NodeError>),
1023}
1024
1025/// Holds the sync role of a closed library's replica, and syncs it, as the technical design's section on the sync role
1026/// says, until `holding.stop` is set: runs its endpoint, on which it answers every replica
1027/// that connects, each sync on a thread of its own, with a library of its own; and connects
1028/// to the others, one at a time, as it takes the role, when one appears on the network,
1029/// a while after new changes came, made here or received, and when another program asks.
1030/// Each change sets off at most one sync with each other replica: one it synced with since
1031/// the change came is not synced with again. It runs no endpoint while another program
1032/// borrows the network. Beside the syncs, on a thread of its own, it checks a share of the
1033/// replica's copies whenever one is due, as `holding.check` paces it, and after a check that
1034/// found damage syncs with every replica it finds ([`Library::check_copies`]). `rng` makes
1035/// randomness for each thread. `told` hears what it does.
1036///
1037/// # Errors
1038///
1039/// Returns an error if the library cannot be opened, the records cannot be written, or the
1040/// network cannot start; a sync that fails is in what `told` hears.
1041pub fn hold<R: CryptoRng + Send + 'static>(
1042	closed: &Closed,
1043	role: Role,
1044	holding: &Holding<'_>,
1045	rng: &(dyn Fn() -> R + Sync),
1046	told: &mut dyn FnMut(Held),
1047) -> Result<(), NodeError> {
1048	// Closed at once, so that what it records commits now: the library kept open only reads,
1049	// and never holds a burst of changes, which would hold up the other programs' changes.
1050	retry_in_use(OPEN_WAIT, || closed.open())?.record_own_endpoint((holding.now)(), &mut rng())?;
1051	let watch = retry_in_use(OPEN_WAIT, || closed.open())?;
1052	let records = watch.sync_records(rng())?;
1053	let since = (holding.now)();
1054	let mut state = Holding::state(watch, records, holding, since)?;
1055	state.records.clear_holder()?;
1056	state.records.set_holder(holding.program, None, since)?;
1057	// Set as the holder ends, even by an error, so that a check under way ends too.
1058	let ending_flag = AtomicBool::new(false);
1059	let ending = &ending_flag;
1060	let held = std::thread::scope(|scope| {
1061		let held = (|| -> Result<(), NodeError> {
1062			let (finished, done) = mpsc::channel::<Finished>();
1063			loop {
1064				let stopping = holding.stop.load(Ordering::SeqCst);
1065				if stopping && state.running == 0 && !state.checking && !state.backing_up {
1066					return Ok(());
1067				}
1068				// A look for the person's backups, which updates those found.
1069				if let Some(present) = state.backups_due(stopping) {
1070					let finished = finished.clone();
1071					scope.spawn(move || {
1072						let look = run_backups(closed, holding, ending, &present, rng);
1073						let _ = finished.send(Finished::BackedUp(look));
1074					});
1075				}
1076				// A share of the replica's copies to check, when one is due.
1077				if !stopping && !state.checking && Instant::now() >= state.check_at {
1078					state.checking = true;
1079					let finished = finished.clone();
1080					scope.spawn(move || {
1081						let checked = run_checks(closed, holding, ending, rng);
1082						let _ = finished.send(Finished::Checked(checked));
1083					});
1084				}
1085				let lend = state.tend_network(closed, holding, stopping, told)?;
1086				state.look(holding)?;
1087				// A sync to start, one at a time, while the network is not lent.
1088				if let Some(network) = state
1089					.network
1090					.clone()
1091					.filter(|_| !lend && !stopping && !state.connecting)
1092					&& let Some((due, asked)) = state.due()
1093				{
1094					state.connecting = true;
1095					state.running += 1;
1096					let (finished, kept) = (finished.clone(), state.holder.kept);
1097					let peers = state.holder.peers.clone();
1098					scope.spawn(move || {
1099						let found = due.iter().copied().collect();
1100						let synced = run_syncs(closed, &network, (peers, &found), holding.now, rng);
1101						let _ = finished.send(Finished::Synced(synced, kept, asked));
1102					});
1103				}
1104				// A pass of removals, when one is due and no sync to start is, as a sync of
1105				// its own: the replicas asked to prove their copies are connected to.
1106				if let Some(network) = state
1107					.network
1108					.clone()
1109					.filter(|_| !lend && !stopping && !state.connecting)
1110					&& Instant::now() >= state.remove_at
1111				{
1112					state.connecting = true;
1113					state.running += 1;
1114					let found: BTreeSet<[u8; 32]> = state.holder.present.keys().copied().collect();
1115					let (finished, kept) = (finished.clone(), state.holder.kept);
1116					scope.spawn(move || {
1117						let pass = run_removals(closed, &network, &found, holding.now, rng);
1118						let _ = finished.send(Finished::Removed(pass, kept));
1119					});
1120				}
1121				// A sync that another replica starts.
1122				match state.network.clone().filter(|_| !lend && !stopping) {
1123					Some(network) => {
1124						if let Some(connection) = network.accept(Some(STEP))? {
1125							state.running += 1;
1126							let finished = finished.clone();
1127							let kept = state.holder.kept;
1128							scope.spawn(move || {
1129								let answered = catch_unwind(AssertUnwindSafe(|| {
1130									answer_connection(
1131										Some(closed),
1132										connection,
1133										holding.now,
1134										&mut rng(),
1135									)
1136								}))
1137								.ok()
1138								.map(Box::new);
1139								let _ = finished.send(Finished::Answered(answered, kept));
1140							});
1141						}
1142					}
1143					None => std::thread::sleep(STEP),
1144				}
1145				while let Ok(ended) = done.try_recv() {
1146					state.ended(ended, holding, told)?;
1147				}
1148			}
1149		})();
1150		ending.store(true, Ordering::SeqCst);
1151		held
1152	});
1153	let cleared = state.records.clear_holder();
1154	drop(role);
1155	held.and(cleared)
1156}
1157
1158/// Syncs with each of `peers` that was `found` on the network, one after the other, on a
1159/// library of its own ([`sync_with_found`]).
1160fn run_syncs<R: CryptoRng + Send + 'static>(
1161	closed: &Closed,
1162	network: &Network,
1163	(peers, found): (Vec<crate::Replica>, &BTreeSet<[u8; 32]>),
1164	now: &(dyn Fn() -> u64 + Sync),
1165	rng: &(dyn Fn() -> R + Sync),
1166) -> Result<Vec<SyncedWith>, NodeError> {
1167	catch_unwind(AssertUnwindSafe(|| {
1168		let mut library = retry_in_use(OPEN_WAIT, || closed.open())?;
1169		Ok(sync_with_found(
1170			&mut library,
1171			network,
1172			peers,
1173			found,
1174			now,
1175			&mut rng(),
1176		))
1177	}))
1178	.unwrap_or(Err(NodeError::Panicked))
1179}
1180
1181/// Runs a share of the checks of the replica's copies, on a library of its own, until the
1182/// holder stops or `ending` is set ([`Library::check_copies`]).
1183fn run_checks<R: CryptoRng + Send + 'static>(
1184	closed: &Closed,
1185	holding: &Holding<'_>,
1186	ending: &AtomicBool,
1187	rng: &(dyn Fn() -> R + Sync),
1188) -> Result<CheckRun, NodeError> {
1189	catch_unwind(AssertUnwindSafe(|| {
1190		let mut library = retry_in_use(OPEN_WAIT, || closed.open())?;
1191		let records = library.sync_records(rng())?;
1192		let stop = || holding.stop.load(Ordering::SeqCst) || ending.load(Ordering::SeqCst);
1193		library.check_copies(&records, holding.now, holding.check, &stop)
1194	}))
1195	.unwrap_or(Err(NodeError::Panicked))
1196}
1197
1198/// Looks for the person's backups on this computer, on a library of its own, and updates
1199/// each found that the last look, whose finds are `present`, did not find, or that was last
1200/// updated here an hour ago or more, until the holder stops or `ending` is set
1201/// ([`Library::update_backup`]).
1202fn run_backups<R: CryptoRng + Send + 'static>(
1203	closed: &Closed,
1204	holding: &Holding<'_>,
1205	ending: &AtomicBool,
1206	present: &BTreeSet<EntityId>,
1207	rng: &(dyn Fn() -> R + Sync),
1208) -> Result<BackupLook, NodeError> {
1209	catch_unwind(AssertUnwindSafe(|| {
1210		let mut library = retry_in_use(OPEN_WAIT, || closed.open())?;
1211		let records = library.sync_records(rng())?;
1212		let known = records.backup_folders()?;
1213		let remembered = known
1214			.iter()
1215			.map(|(backup, found)| (*backup, found.folder.clone()))
1216			.collect();
1217		let stop = || holding.stop.load(Ordering::SeqCst) || ending.load(Ordering::SeqCst);
1218		let mut look = BackupLook {
1219			present: BTreeSet::new(),
1220			updates: Vec::new(),
1221		};
1222		for (backup, folder) in library.find_backups(&remembered)? {
1223			look.present.insert(backup.id);
1224			let now = (holding.now)();
1225			let kept = library.changes_kept()?;
1226			let last = known.get(&backup.id);
1227			// Found anew, as when plugged in; an hour after its last update here once new
1228			// changes came, or a day after if none did. One that failed waits as long.
1229			let due = !present.contains(&backup.id)
1230				|| last.is_none_or(|last| {
1231					last.updated.is_none_or(|at| {
1232						let since = now.saturating_sub(at);
1233						since >= BACKUP_IDLE
1234							|| (since >= BACKUP_AGAIN && last.kept != u64::try_from(kept).ok())
1235					})
1236				});
1237			if !due || stop() {
1238				records.record_backup(backup.id, &folder, None)?;
1239				continue;
1240			}
1241			let updated = library.update_backup(&backup, &folder, holding.now, &stop);
1242			if !matches!(updated, Ok(None)) {
1243				records.record_backup(backup.id, &folder, Some(((holding.now)(), kept)))?;
1244			}
1245			match updated {
1246				// Another program updates it: the next look tries again.
1247				Ok(None) => {
1248					look.present.remove(&backup.id);
1249				}
1250				Ok(Some(update)) => look.updates.push(BackedUp {
1251					backup,
1252					folder,
1253					updated: Ok(update),
1254				}),
1255				Err(error) => look.updates.push(BackedUp {
1256					backup,
1257					folder,
1258					updated: Err(error),
1259				}),
1260			}
1261		}
1262		Ok(look)
1263	}))
1264	.unwrap_or(Err(NodeError::Panicked))
1265}
1266
1267/// Runs a pass of removals of the copies that the replica no longer keeps, on a library of
1268/// its own, with the replicas `found` on the network ([`remove_unkept`]).
1269fn run_removals<R: CryptoRng + Send + 'static>(
1270	closed: &Closed,
1271	network: &Network,
1272	found: &BTreeSet<[u8; 32]>,
1273	now: &(dyn Fn() -> u64 + Sync),
1274	rng: &(dyn Fn() -> R + Sync),
1275) -> Result<RemovalPass, NodeError> {
1276	catch_unwind(AssertUnwindSafe(|| {
1277		let mut library = retry_in_use(OPEN_WAIT, || closed.open())?;
1278		let records = library.sync_records(rng())?;
1279		remove_unkept(&mut library, network, &records, found, now, &mut rng())
1280	}))
1281	.unwrap_or(Err(NodeError::Panicked))
1282}
1283
1284/// The holder of the sync role as it runs.
1285struct State {
1286	/// A library of the replica's own, which tells when changes come into it.
1287	watch: Library,
1288	records: Records,
1289	holder: Holder,
1290	/// Its endpoint, while it runs one.
1291	network: Option<Arc<Network>>,
1292	/// Since when it holds the role.
1293	since: u64,
1294	/// How many syncs run, on threads of their own.
1295	running: usize,
1296	/// Whether it connects to replicas now: one sync at a time does.
1297	connecting: bool,
1298	/// The records' count of what other connections committed, as last read.
1299	version: i64,
1300	/// The asks to answer, and those that a sync under way answers.
1301	asks: Vec<(i64, Option<EntityId>)>,
1302	answering: BTreeSet<i64>,
1303	/// Whether a check of the replica's copies runs, on a thread of its own.
1304	checking: bool,
1305	/// When to look next whether checks are due.
1306	check_at: Instant,
1307	/// When to run the next pass of removals.
1308	remove_at: Instant,
1309	/// Whether a look for the person's backups runs, on a thread of its own.
1310	backing_up: bool,
1311	/// When to look for backups next.
1312	backups_at: Instant,
1313	/// The backups that the last look found.
1314	backups_present: BTreeSet<EntityId>,
1315}
1316
1317impl Holding<'_> {
1318	fn state(
1319		watch: Library,
1320		records: Records,
1321		holding: &Self,
1322		since: u64,
1323	) -> Result<State, NodeError> {
1324		Ok(State {
1325			holder: Holder::new(&watch, holding)?,
1326			version: records.version()?,
1327			asks: records.open_asks()?,
1328			watch,
1329			records,
1330			network: None,
1331			since,
1332			running: 0,
1333			connecting: false,
1334			answering: BTreeSet::new(),
1335			checking: false,
1336			check_at: Instant::now() + holding.check.wait,
1337			remove_at: Instant::now() + holding.check.wait,
1338			backing_up: false,
1339			backups_at: Instant::now(),
1340			backups_present: BTreeSet::new(),
1341		})
1342	}
1343}
1344
1345impl State {
1346	/// Whether a look for the person's backups is due, not while the holder stops: if it
1347	/// is, the backups that the last look found, as it begins.
1348	fn backups_due(&mut self, stopping: bool) -> Option<BTreeSet<EntityId>> {
1349		if stopping || self.backing_up || Instant::now() < self.backups_at {
1350			return None;
1351		}
1352		self.backing_up = true;
1353		Some(self.backups_present.clone())
1354	}
1355
1356	/// Stops the endpoint while another program borrows the network, or the role is let
1357	/// go, once the syncs under way end, and starts it again after. Returns whether the
1358	/// network is lent.
1359	fn tend_network(
1360		&mut self,
1361		closed: &Closed,
1362		holding: &Holding<'_>,
1363		stopping: bool,
1364		told: &mut dyn FnMut(Held),
1365	) -> Result<bool, NodeError> {
1366		let lend = lent(closed)?;
1367		if (lend || stopping) && self.network.is_some() && self.running == 0 {
1368			self.network = None;
1369			self.records.set_holder(holding.program, None, self.since)?;
1370			if lend {
1371				told(Held::Lent);
1372			}
1373		}
1374		if !lend && !stopping && self.network.is_none() {
1375			let started = Arc::new(self.watch.network(holding.network)?);
1376			for (peer, addresses) in &holding.known {
1377				started.remember(*peer, addresses, None);
1378			}
1379			self.records
1380				.set_holder(holding.program, started.port(), self.since)?;
1381			// A program that borrowed the network meanwhile may have read the record of
1382			// none, from before: the endpoint goes again before it takes a connection.
1383			if lent(closed)? {
1384				drop(started);
1385				self.records.set_holder(holding.program, None, self.since)?;
1386				return Ok(true);
1387			}
1388			told(Held::Started {
1389				port: started.port(),
1390				refused: started
1391					.port_refused()
1392					.map(|(port, why)| (port, why.to_owned())),
1393			});
1394			self.network = Some(started);
1395			self.holder.taken(Instant::now());
1396		}
1397		Ok(lend)
1398	}
1399
1400	/// Looks at what other programs ask, what came into the replica, and who is on the
1401	/// network.
1402	fn look(&mut self, holding: &Holding<'_>) -> Result<(), NodeError> {
1403		let moved = self.records.version()?;
1404		if moved != self.version {
1405			self.version = moved;
1406			self.asks = self.records.open_asks()?;
1407			let answering = &self.answering;
1408			self.asks.retain(|(ask, _)| !answering.contains(ask));
1409		}
1410		if self.watch.catch_up()? {
1411			self.holder.peers = self.watch.peers()?;
1412			self.holder
1413				.counted(self.watch.changes_kept()?, Instant::now());
1414		}
1415		if let Some(network) = &self.network {
1416			let now = (holding.now)();
1417			for (replica, present) in self.holder.look(network, Instant::now()) {
1418				self.records.record_presence(replica, present, now)?;
1419			}
1420		}
1421		Ok(())
1422	}
1423
1424	/// The replicas to connect to now, and the asks that connecting answers, if there are
1425	/// any: those asked for, or else those that [`Holder::due`] says.
1426	fn due(&mut self) -> Option<(Vec<[u8; 32]>, Vec<i64>)> {
1427		let asked: Option<BTreeSet<EntityId>> = if self.asks.is_empty() {
1428			None
1429		} else if self.asks.iter().any(|(_, replica)| replica.is_none()) {
1430			Some(self.holder.peers.iter().map(|peer| peer.id).collect())
1431		} else {
1432			Some(
1433				self.asks
1434					.iter()
1435					.filter_map(|(_, replica)| *replica)
1436					.collect(),
1437			)
1438		};
1439		let due = self.holder.due(asked.as_ref(), Instant::now());
1440		if due.is_empty() && self.asks.is_empty() {
1441			return None;
1442		}
1443		let asked: Vec<i64> = self.asks.drain(..).map(|(ask, _)| ask).collect();
1444		self.answering.extend(asked.iter().copied());
1445		Some((due, asked))
1446	}
1447
1448	/// Notes a sync that ended: records it, tells the program, and answers the asks it
1449	/// answers.
1450	fn ended(
1451		&mut self,
1452		ended: Finished,
1453		holding: &Holding<'_>,
1454		told: &mut dyn FnMut(Held),
1455	) -> Result<(), NodeError> {
1456		if let Finished::BackedUp(look) = ended {
1457			self.backing_up = false;
1458			self.backups_at = Instant::now() + BACKUPS_LOOK;
1459			if let Ok(look) = look {
1460				self.backups_present = look.present;
1461				for update in look.updates {
1462					told(Held::BackedUp(update));
1463				}
1464			}
1465			return Ok(());
1466		}
1467		if let Finished::Checked(checked) = ended {
1468			self.checking = false;
1469			// After a run that ended at its time, the next waits out the rest it owes.
1470			let wait = match &checked {
1471				Ok(run) if run.more => run.rest,
1472				_ => holding.check.wait,
1473			};
1474			self.check_at = Instant::now() + wait;
1475			if let Ok(run) = checked {
1476				told(Held::Checked(run));
1477			}
1478			return Ok(());
1479		}
1480		self.running -= 1;
1481		let now = (holding.now)();
1482		if let Finished::Removed(pass, kept) = ended {
1483			self.connecting = false;
1484			// A pass that had room for no more is followed by another soon.
1485			let soon = matches!(&pass, Ok(pass) if pass.removed.more && pass.removed.copies > 0);
1486			self.remove_at = Instant::now()
1487				+ if soon {
1488					REMOVE_SOON
1489				} else {
1490					holding.check.wait
1491				};
1492			if let Ok(pass) = &pass {
1493				for with in pass.synced.iter().filter(|with| tried(with)) {
1494					if let Some(endpoint) = with.replica.endpoint {
1495						let counted = counts(&with.synced);
1496						self.holder.synced(endpoint, &counted, kept);
1497						self.records.record_sync(with.replica.id, now, counted)?;
1498					}
1499				}
1500			}
1501			told(Held::Removed(pass));
1502			return Ok(());
1503		}
1504		// What the sync brought counts as having come before its end.
1505		if self.watch.catch_up()? {
1506			self.holder.peers = self.watch.peers()?;
1507		}
1508		self.holder
1509			.counted(self.watch.changes_kept()?, Instant::now());
1510		match ended {
1511			Finished::Answered(None, _)
1512			| Finished::Checked(_)
1513			| Finished::Removed(..)
1514			| Finished::BackedUp(_) => {}
1515			Finished::Answered(Some(answered), kept) => {
1516				if let Some(replica) = &answered.replica {
1517					let synced = counts(&answered.synced);
1518					self.holder.synced(answered.endpoint, &synced, kept);
1519					self.records.record_sync(replica.id, now, synced)?;
1520				}
1521				told(Held::Answered(*answered));
1522			}
1523			Finished::Synced(Err(_), _, asked) => {
1524				// None could start, as the library could not be opened: the asks wait for
1525				// the next sync, as they are read again.
1526				self.connecting = false;
1527				for ask in asked {
1528					self.answering.remove(&ask);
1529				}
1530				self.version = self.version.wrapping_sub(1);
1531			}
1532			Finished::Synced(Ok(synced), kept, asked) => {
1533				self.connecting = false;
1534				for with in synced {
1535					if !tried(&with) {
1536						continue;
1537					}
1538					if let Some(endpoint) = with.replica.endpoint {
1539						let counted = counts(&with.synced);
1540						self.holder.synced(endpoint, &counted, kept);
1541						self.records.record_sync(with.replica.id, now, counted)?;
1542					}
1543					told(Held::Synced(with));
1544				}
1545				for ask in asked {
1546					self.answering.remove(&ask);
1547					self.records.answer(ask, now)?;
1548				}
1549			}
1550		}
1551		Ok(())
1552	}
1553}
1554
1555/// Whether a sync with another replica was tried: those not found are not told of; nor those
1556/// that refused, as a program there only connects, as one that syncs once connects to this
1557/// one itself: no sync failed.
1558#[must_use]
1559pub fn tried(with: &SyncedWith) -> bool {
1560	!matches!(
1561		with.synced,
1562		Err(NodeError::NotFound | NodeError::Network(NetError::Refused))
1563	)
1564}
1565
1566/// What a sync brought and sent, or why it failed.
1567fn counts(synced: &Result<nibkeep_sync::Synced, NodeError>) -> Result<(usize, usize), String> {
1568	match synced {
1569		Ok(synced) => Ok(synced
1570			.spaces
1571			.iter()
1572			.fold((0, 0), |(received, sent), space| {
1573				(received + space.received.changes, sent + space.sent.changes)
1574			})),
1575		Err(error) => Err(error.to_string()),
1576	}
1577}
1578
1579/// What the holder keeps track of, to tell when to connect to whom.
1580struct Holder {
1581	/// The user's other replicas.
1582	peers: Vec<crate::Replica>,
1583	/// How many changes the replica keeps, as last counted.
1584	kept: usize,
1585	/// When the count last grew, if it did since the replicas behind were synced with.
1586	grew: Option<Instant>,
1587	/// How many changes the replica kept after its last sync with each other replica, by
1588	/// endpoint: a replica behind the count now has not seen every change.
1589	synced: BTreeMap<[u8; 32], usize>,
1590	/// The replicas on the network, by endpoint, and when each appeared, until the holder
1591	/// synced with it, or it connected.
1592	present: BTreeMap<[u8; 32], Option<Instant>>,
1593	/// When the holder took the role, until it synced with all it found then.
1594	taken: Option<Instant>,
1595	quiet: Duration,
1596	appear_wait: Duration,
1597	/// A source of jitter for the wait after a replica appears.
1598	jitter: u64,
1599}
1600
1601impl Holder {
1602	fn new(library: &Library, holding: &Holding<'_>) -> Result<Self, NodeError> {
1603		Ok(Self {
1604			peers: library.peers()?,
1605			kept: library.changes_kept()?,
1606			grew: None,
1607			synced: BTreeMap::new(),
1608			present: BTreeMap::new(),
1609			taken: None,
1610			quiet: holding.quiet,
1611			appear_wait: holding.appear_wait,
1612			jitter: u64::from_le_bytes(library.endpoint()[..8].try_into().unwrap_or_default()),
1613		})
1614	}
1615
1616	/// Notes that the holder took the role, and started its endpoint: the replicas it finds
1617	/// in the next while, as discovery finds them, it connects to at once.
1618	fn taken(&mut self, now: Instant) {
1619		self.taken = Some(now);
1620	}
1621
1622	/// Notes how many changes the replica keeps now. Fewer than before, as when changes
1623	/// that waited are rejected, no other replica has seen more.
1624	fn counted(&mut self, kept: usize, now: Instant) {
1625		if kept > self.kept {
1626			self.grew = Some(now);
1627		}
1628		if kept < self.kept {
1629			for seen in self.synced.values_mut() {
1630				*seen = (*seen).min(kept);
1631			}
1632		}
1633		self.kept = kept;
1634	}
1635
1636	/// Notes a sync with the replica at `endpoint`, which began when the replica kept `kept`
1637	/// changes: once it is done, the other has seen those, and what it sent. A change made
1638	/// here meanwhile is not among them; nor one that another sync of the same batch
1639	/// brought, which costs the other replica one more sync, that finds nothing new. The
1640	/// replica is on the network, and is not connected to as one that appears.
1641	fn synced(&mut self, endpoint: [u8; 32], synced: &Result<(usize, usize), String>, kept: usize) {
1642		if let Ok((received, _)) = synced {
1643			let seen = self.synced.entry(endpoint).or_default();
1644			*seen = (*seen).max(kept + received);
1645		}
1646		self.present.insert(endpoint, None);
1647	}
1648
1649	/// Looks who is on the network: returns the replicas that appeared, and those that
1650	/// went, since it last looked.
1651	fn look(&mut self, network: &Network, now: Instant) -> Vec<(EntityId, bool)> {
1652		let endpoints: BTreeSet<[u8; 32]> =
1653			self.peers.iter().filter_map(|peer| peer.endpoint).collect();
1654		let found = network.find(&endpoints, Duration::ZERO);
1655		let mut changed = Vec::new();
1656		for peer in &self.peers {
1657			let Some(endpoint) = peer.endpoint else {
1658				continue;
1659			};
1660			let here = found.contains(&endpoint);
1661			match (here, self.present.contains_key(&endpoint)) {
1662				(true, false) => {
1663					self.jitter = self.jitter.rotate_left(13) ^ 0x9e37_79b9_7f4a_7c15;
1664					// At once in the while after the role is taken.
1665					let just_taken = self
1666						.taken
1667						.is_some_and(|taken| now < taken + self.appear_wait);
1668					let wait = if just_taken {
1669						Duration::ZERO
1670					} else {
1671						self.appear_wait.mul_f64(
1672							f64::from(u32::try_from(self.jitter % 1_000).unwrap_or(0)) / 1_000.0,
1673						)
1674					};
1675					self.present.insert(endpoint, Some(now + wait));
1676					changed.push((peer.id, true));
1677				}
1678				(false, true) => {
1679					self.present.remove(&endpoint);
1680					changed.push((peer.id, false));
1681				}
1682				_ => {}
1683			}
1684		}
1685		changed
1686	}
1687
1688	/// The endpoints to sync with now, among those on the network: those asked for; one
1689	/// that appeared, once its wait is over, which is none in the while after the role is
1690	/// taken; and once the changes have been quiet a while, those that have not seen every
1691	/// change.
1692	fn due(&mut self, asked: Option<&BTreeSet<EntityId>>, now: Instant) -> Vec<[u8; 32]> {
1693		let mut due = BTreeSet::new();
1694		let quiet = self.grew.is_some_and(|grew| now >= grew + self.quiet);
1695		for peer in &self.peers {
1696			let Some(endpoint) = peer.endpoint else {
1697				continue;
1698			};
1699			let Some(appeared) = self.present.get(&endpoint).copied() else {
1700				continue;
1701			};
1702			let behind = self
1703				.synced
1704				.get(&endpoint)
1705				.is_none_or(|kept| *kept < self.kept);
1706			if asked.is_some_and(|asked| asked.contains(&peer.id))
1707				|| appeared.is_some_and(|at| now >= at)
1708				|| (quiet && behind)
1709			{
1710				due.insert(endpoint);
1711			}
1712		}
1713		if quiet {
1714			self.grew = None;
1715		}
1716		for endpoint in &due {
1717			if let Some(appeared) = self.present.get_mut(endpoint) {
1718				*appeared = None;
1719			}
1720		}
1721		due.into_iter().collect()
1722	}
1723}
1724
1725#[cfg(test)]
1726mod tests {
1727	use nibkeep_crypto::PassphraseParams;
1728	use nibkeep_testkit::{TestRng, millis_at};
1729
1730	use super::*;
1731	use crate::{NewLibrary, NewProtection};
1732
1733	/// A directory that goes when the test ends, also when it fails.
1734	struct Removed(PathBuf);
1735
1736	impl Drop for Removed {
1737		fn drop(&mut self) {
1738			let _ = std::fs::remove_dir_all(&self.0);
1739		}
1740	}
1741
1742	/// A library in a directory of its own, protected by a quick passphrase.
1743	fn library(name: &str) -> (Removed, Library) {
1744		let directory = nibkeep_testkit::empty_directory(
1745			std::env::temp_dir(),
1746			&format!("nibkeep-node-role-{name}-{}", std::process::id()),
1747		);
1748		let library = Library::create(
1749			&directory,
1750			&NewLibrary::new("Ada", "laptop", "nib"),
1751			&NewProtection::Passphrase(
1752				"correct horse",
1753				PassphraseParams::new(64, 1, 1).expect("valid"),
1754			),
1755			millis_at("2026-11-01", 10, 0),
1756			&mut TestRng::new(name),
1757		)
1758		.expect("creates");
1759		(Removed(directory), library)
1760	}
1761
1762	#[test]
1763	fn a_holder_that_ended_without_clearing_its_records_holds_nothing() {
1764		let (_removed, library) = library("left-behind");
1765		let records = library
1766			.sync_records(TestRng::new("records"))
1767			.expect("records");
1768		// As an app that quit, or crashed, leaves it.
1769		records
1770			.set_holder("Passwords", Some(53300), millis_at("2026-11-01", 10, 1))
1771			.expect("records");
1772		let phone = EntityId::from_bytes([7; 16]);
1773		records
1774			.record_presence(phone, true, millis_at("2026-11-01", 10, 2))
1775			.expect("records");
1776		assert_eq!(records.holder().expect("reads"), None);
1777		let left = &records.replicas().expect("reads")[&phone];
1778		assert!(!left.present, "nobody knows who is on the network");
1779		assert_eq!(left.seen, Some(millis_at("2026-11-01", 10, 2)));
1780		let _role = library.take_role().expect("takes").expect("free");
1781		assert_eq!(
1782			records
1783				.holder()
1784				.expect("reads")
1785				.map(|holder| holder.program),
1786			Some("Passwords".to_owned()),
1787			"held, the record says who holds it"
1788		);
1789		assert!(records.replicas().expect("reads")[&phone].present);
1790	}
1791
1792	#[test]
1793	fn a_blob_held_for_another_is_not_removed_and_one_being_removed_is_not_proved() {
1794		let (_removed, library) = library("holds");
1795		let records = library
1796			.sync_records(TestRng::new("records"))
1797			.expect("records");
1798		// And two programs at once, each with its own connection.
1799		let other = library
1800			.sync_records(TestRng::new("other records"))
1801			.expect("records");
1802		let (held, removing, free) = (Hash::of(b"held"), Hash::of(b"removing"), Hash::of(b"free"));
1803		let at = millis_at("2026-11-01", 10, 0);
1804		assert_eq!(records.hold(&[held], at).expect("holds"), [held].into());
1805		assert_eq!(
1806			other.begin_removing(&[removing], at).expect("marks"),
1807			[removing].into()
1808		);
1809		// Neither is had the other way while the other stands.
1810		assert_eq!(
1811			other.begin_removing(&[held, free], at + 1).expect("marks"),
1812			[free].into()
1813		);
1814		assert!(records.hold(&[removing], at + 1).expect("holds").is_empty());
1815		assert_eq!(records.holds(at + 1).expect("reads"), [held].into());
1816		// A removal that ends lets its blob be proved again.
1817		other.end_removing(&[removing, free]).expect("ends");
1818		assert_eq!(
1819			records.hold(&[removing], at + 2).expect("holds"),
1820			[removing].into()
1821		);
1822		// A hold ends after 10 minutes.
1823		let later = at + 2 + HOLD_FOR;
1824		assert!(records.holds(later).expect("reads").is_empty());
1825		assert_eq!(
1826			other
1827				.begin_removing(&[held, removing], later)
1828				.expect("marks"),
1829			[held, removing].into()
1830		);
1831	}
1832
1833	#[test]
1834	fn borrowing_the_network_stops_waiting_for_the_holder_once_told() {
1835		let (_removed, library) = library("borrow-stops");
1836		let _role = library.take_role().expect("takes").expect("free");
1837		let records = library
1838			.sync_records(TestRng::new("records"))
1839			.expect("records");
1840		// A holder that keeps its endpoint, as one busy syncing.
1841		records
1842			.set_holder(
1843				"nib sync --serve",
1844				Some(53300),
1845				millis_at("2026-11-01", 10, 1),
1846			)
1847			.expect("records");
1848		let started = Instant::now();
1849		let borrowed = borrow_network(&library, &AtomicBool::new(true), TestRng::new("borrows"));
1850		assert!(matches!(borrowed, Err(NodeError::PairingExpired)));
1851		assert!(started.elapsed() < LEND_WAIT / 2, "stopped at once");
1852	}
1853}