Skip to main content

nibkeep_node/
background.rs

1//! The sync role, held in the background ([technical design](../../../docs/Technical-design.md#105-the-sync-role)),
2//! as the apps hold it while a library is unlocked: a thread that takes the role, or waits
3//! for the program that holds it to let go, and syncs the replica for every program on it
4//! until stopped. And asking the holder, whichever program it is, to sync now.
5
6use std::net::SocketAddr;
7use std::panic::{AssertUnwindSafe, catch_unwind};
8use std::path::{Path, PathBuf};
9use std::sync::atomic::{AtomicBool, Ordering};
10use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
11use std::thread::JoinHandle;
12use std::time::{Duration, Instant};
13
14use nibkeep_base::EntityId;
15use nibkeep_crypto::rand_core::CryptoRng;
16use nibkeep_net::Options;
17
18use crate::{Closed, Held, Holding, NodeError, Pace, Records, Role, hold};
19
20/// How long the thread waits after holding the role failed, as when the library could not
21/// be opened, before it tries again.
22const RETRY: Duration = Duration::from_secs(10);
23
24/// How often an ask looks whether the holder answered.
25const LOOK: Duration = Duration::from_millis(100);
26
27/// How a program holds the sync role in the background: as [`Holding`] says, with what it
28/// keeps of its own.
29#[derive(Clone, Debug)]
30pub struct BackgroundOptions {
31	/// The program, as the records name it, such as `Passwords`.
32	pub program: String,
33	/// How its endpoint starts.
34	pub network: Options,
35	/// Where other replicas are, found other than on the network, as in tests.
36	pub known: Vec<([u8; 32], Vec<SocketAddr>)>,
37	/// How long it waits after new changes before it syncs them.
38	pub quiet: Duration,
39	/// How long it waits at most after another replica appears before it connects.
40	pub appear_wait: Duration,
41	/// How it paces its checks of the replica's copies.
42	pub check: Pace,
43}
44
45impl BackgroundOptions {
46	/// For `program`, with its endpoint as `network` says, the waits of
47	/// [`Holding::QUIET`] and [`Holding::APPEAR_WAIT`], and checks at [`Pace::DEFAULT`].
48	#[must_use]
49	pub fn new(program: &str, network: Options) -> Self {
50		Self {
51			program: program.to_owned(),
52			network,
53			known: Vec::new(),
54			quiet: Holding::QUIET,
55			appear_wait: Holding::APPEAR_WAIT,
56			check: Pace::DEFAULT,
57		}
58	}
59}
60
61/// What the thread that holds the sync role in the background does now.
62#[derive(Clone, Debug, Default, PartialEq, Eq)]
63pub struct BackgroundState {
64	/// Whether it holds the role; if not, another program does, or did a moment ago, which
65	/// it waits for to let go.
66	pub holding: bool,
67	/// Why holding the role failed last, until its endpoint starts again: it tries again a
68	/// while later, but after an error of the keys, as when another program protected the
69	/// library anew, which ends it.
70	pub failed: Option<String>,
71}
72
73/// A thread that holds the sync role of a replica in the background, or waits for it, until
74/// this is stopped or dropped.
75pub struct Background {
76	stop: Arc<AtomicBool>,
77	state: Arc<Mutex<BackgroundState>>,
78	directory: PathBuf,
79	thread: Option<JoinHandle<()>>,
80}
81
82fn locked(state: &Mutex<BackgroundState>) -> MutexGuard<'_, BackgroundState> {
83	state.lock().unwrap_or_else(PoisonError::into_inner)
84}
85
86impl Background {
87	/// Starts a thread that takes the sync role of `closed`'s replica, as soon as no other
88	/// program holds it, and holds it as [`hold`] does, as `options` say, until stopped:
89	/// again after holding it failed, a while later. `now` is the wall clock, and `rng`
90	/// makes randomness for each thread.
91	pub fn start<R: CryptoRng + Send + 'static>(
92		closed: Closed,
93		options: BackgroundOptions,
94		now: impl Fn() -> u64 + Send + Sync + 'static,
95		rng: impl Fn() -> R + Send + Sync + 'static,
96	) -> Self {
97		let stop = Arc::new(AtomicBool::new(false));
98		let state = Arc::new(Mutex::new(BackgroundState::default()));
99		let directory = closed.directory().to_owned();
100		let thread = {
101			let (stop, state) = (Arc::clone(&stop), Arc::clone(&state));
102			std::thread::spawn(move || run(&closed, &options, (&now, &rng), &stop, &state))
103		};
104		Self {
105			stop,
106			state,
107			directory,
108			thread: Some(thread),
109		}
110	}
111
112	/// What it does now.
113	#[must_use]
114	pub fn state(&self) -> BackgroundState {
115		locked(&self.state).clone()
116	}
117
118	/// The folder of the replica whose role it holds.
119	#[must_use]
120	pub fn directory(&self) -> &Path {
121		&self.directory
122	}
123
124	/// Whether its thread ended, as after an error of the keys, or once stopped.
125	#[must_use]
126	pub fn ended(&self) -> bool {
127		self.thread.as_ref().is_none_or(JoinHandle::is_finished)
128	}
129
130	/// Stops it, and waits until it let go of the role: once the syncs under way end.
131	pub fn wait(mut self) {
132		self.stop.store(true, Ordering::SeqCst);
133		if let Some(thread) = self.thread.take() {
134			let _ = thread.join();
135		}
136	}
137}
138
139impl Drop for Background {
140	/// Stops it without waiting: the thread lets go of the role once the syncs under way
141	/// end, and a program that waits for the role, such as another of these on the same
142	/// replica, takes it then.
143	fn drop(&mut self) {
144		self.stop.store(true, Ordering::SeqCst);
145	}
146}
147
148/// The thread of a [`Background`].
149fn run<R: CryptoRng + Send + 'static>(
150	closed: &Closed,
151	options: &BackgroundOptions,
152	(now, rng): (&(dyn Fn() -> u64 + Sync), &(dyn Fn() -> R + Sync)),
153	stop: &AtomicBool,
154	state: &Mutex<BackgroundState>,
155) {
156	let failed = |error: &NodeError| locked(state).failed = Some(error.to_string());
157	while !stop.load(Ordering::SeqCst) {
158		let role = match Role::wait(closed, stop) {
159			Ok(Some(role)) => role,
160			Ok(None) => return,
161			Err(error) => {
162				failed(&error);
163				pause(stop);
164				continue;
165			}
166		};
167		locked(state).holding = true;
168		let holding = Holding {
169			program: &options.program,
170			network: options.network,
171			known: options.known.clone(),
172			quiet: options.quiet,
173			appear_wait: options.appear_wait,
174			check: options.check,
175			stop,
176			now,
177		};
178		let held = catch_unwind(AssertUnwindSafe(|| {
179			hold(closed, role, &holding, rng, &mut |held| {
180				if matches!(held, Held::Started { .. }) {
181					locked(state).failed = None;
182				}
183			})
184		}))
185		.unwrap_or(Err(NodeError::Panicked));
186		locked(state).holding = false;
187		match held {
188			Ok(()) => {}
189			// Another program protected the library anew: its keys here are old.
190			Err(error @ NodeError::Keys(_)) => {
191				failed(&error);
192				return;
193			}
194			Err(error) => {
195				failed(&error);
196				pause(stop);
197			}
198		}
199	}
200}
201
202/// Waits for [`RETRY`], or less if stopped.
203fn pause(stop: &AtomicBool) {
204	let paused = Instant::now();
205	while paused.elapsed() < RETRY && !stop.load(Ordering::SeqCst) {
206		std::thread::sleep(LOOK);
207	}
208}
209
210/// Asks the program that holds the sync role of the replica, whichever it is, to sync with
211/// one other replica, or with all it finds, and waits until it did, for at most `wait`:
212/// waits first for a program to take the role, if none holds it, and for one that just
213/// took it to look for the others on the network, which it connects to at once in its
214/// first while ([`Holding::APPEAR_WAIT`]). Returns when it asked, after which the holder
215/// recorded each sync of the answer ([`crate::ReplicaRecord::synced`]); or `None` if no
216/// program answered in time. `now` is the wall clock, as the holder's is.
217///
218/// # Errors
219///
220/// Returns an error if the records cannot be read or written.
221pub fn ask_to_sync(
222	records: &Records,
223	replica: Option<EntityId>,
224	now: &dyn Fn() -> u64,
225	wait: Duration,
226) -> Result<Option<u64>, NodeError> {
227	ask_to_sync_each(records, &[replica], now, wait)
228}
229
230/// Asks as [`ask_to_sync`] does, for a sync with each of several replicas, as when a file is
231/// fetched from the devices that hold it, and waits until the holder answered them all.
232///
233/// # Errors
234///
235/// Returns an error if the records cannot be read or written.
236pub fn ask_to_sync_each(
237	records: &Records,
238	replicas: &[Option<EntityId>],
239	now: &dyn Fn() -> u64,
240	wait: Duration,
241) -> Result<Option<u64>, NodeError> {
242	let started = Instant::now();
243	let holder = loop {
244		if let Some(holder) = records.holder()? {
245			break holder;
246		}
247		if started.elapsed() > wait {
248			return Ok(None);
249		}
250		std::thread::sleep(LOOK);
251	};
252	let settled = holder
253		.since
254		.saturating_add(u64::try_from(Holding::APPEAR_WAIT.as_millis()).unwrap_or(u64::MAX));
255	if let Some(early) = settled.checked_sub(now()) {
256		std::thread::sleep(Duration::from_millis(early).min(wait));
257	}
258	let asked = now();
259	let asks = replicas
260		.iter()
261		.map(|replica| records.ask(*replica, asked))
262		.collect::<Result<Vec<_>, _>>()?;
263	for ask in asks {
264		while records.answered(ask)?.is_none() {
265			if started.elapsed() > wait {
266				return Ok(None);
267			}
268			std::thread::sleep(LOOK);
269		}
270	}
271	Ok(Some(asked))
272}