Skip to main content

nibkeep_node/
network.rs

1//! Pairing and syncing with the user's other replicas over the home network
2//! ([Sync](../../../docs/spec/sync.md)): a [`Network`] runs this replica's endpoint, and
3//! the functions here run one exchange each over it.
4
5use std::collections::BTreeSet;
6use std::fmt;
7use std::path::{Path, PathBuf};
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::time::{Duration, Instant};
10
11use nibkeep_base::{EntityId, SpaceId};
12use nibkeep_crypto::rand_core::CryptoRng;
13use nibkeep_governance::PairingCode;
14use nibkeep_keys::NewProtection;
15use nibkeep_net::{Connection, NetError, Network, Options, Protocol};
16use nibkeep_sync::{Reason, SyncError, Synced};
17
18use crate::library::members::{Acceptor, Invitee, Inviter};
19use crate::library::removal::{Removals, Removed};
20use crate::library::sync::{AskedFor, Joining, Replica, Sponsor, Syncing};
21use crate::library::taking::NewDevice;
22use crate::role::Records;
23use crate::{Closed, Library, MemberRole, NodeError};
24
25/// An AI agent that pairing adds a replica of: its name, and the spaces besides the personal
26/// one chosen for it.
27type AiAgent<'a> = (&'a str, &'a [SpaceId]);
28
29/// How long connecting to a replica found on the network may take.
30const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
31
32/// How long a sponsor waits for the new replica's first sync, after pairing.
33const FIRST_SYNC_TIMEOUT: Duration = Duration::from_mins(2);
34
35/// How long a sponsor waits for the second sync of a new replica that asked for the secrets,
36/// which follows the first at once.
37const ASKING_SYNC_TIMEOUT: Duration = Duration::from_secs(30);
38
39/// How long pairing with a closed library waits for another program to close it, once a
40/// new replica connects: the code may be spent, so it is worth a wait.
41const OPEN_WAIT: Duration = Duration::from_secs(10);
42
43/// How many tries a code takes ([Sync](../../../docs/spec/sync.md#2-pairing)): the one in
44/// which it matches spends it, and so does the last of those that fail before it matches,
45/// whatever made them fail. Two pairings at once whose codes share their first two digits
46/// may each reach the other's device first, and a person may mistype a code.
47pub const CODE_TRIES: usize = 3;
48
49/// How long a new replica that tried every device that announces the first two digits of its
50/// code, and failed with each, waits for another before it gives up: one that announces them
51/// too may not have been heard yet.
52const ANOTHER_SPONSOR: Duration = Duration::from_secs(2);
53
54/// What a device that shows a code is told of each try that failed before the code matched,
55/// but the last, which ends the pairing or the invitation with its error instead: why it
56/// failed, and how many tries the code has left.
57pub type WrongTry<'a> = &'a dyn Fn(&NodeError, usize);
58
59/// How a code that this device shows waits for the device that types it: for up to `timeout`
60/// from when it is shown, telling `wrong_try` of each try that fails before it matches.
61#[derive(Clone, Copy)]
62pub struct Showing<'a> {
63	/// How long the code works.
64	pub timeout: Duration,
65	/// What is told of each try that failed before the code matched, but the last.
66	pub wrong_try: WrongTry<'a>,
67}
68
69impl Showing<'static> {
70	/// A code that works for `timeout`, whose wrong tries nobody is told of.
71	#[must_use]
72	pub fn new(timeout: Duration) -> Self {
73		Self {
74			timeout,
75			wrong_try: &tell_nobody,
76		}
77	}
78}
79
80impl fmt::Debug for Showing<'_> {
81	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82		f.debug_struct("Showing")
83			.field("timeout", &self.timeout)
84			.finish_non_exhaustive()
85	}
86}
87
88/// Tells nobody of a wrong try.
89const fn tell_nobody(_: &NodeError, _: usize) {}
90
91/// How pairing with a closed library waits: as `showing` says, until `stop` is set; whether
92/// it gives the secrets to a new replica that asks for them, and what the new device is, a
93/// computer or a phone, and which spaces it gets, as the person chose.
94#[derive(Clone, Copy, Debug)]
95pub struct Waiting<'a> {
96	/// How long the code works, and what is told of its wrong tries.
97	pub showing: Showing<'a>,
98	/// Set, it stops waiting.
99	pub stop: &'a AtomicBool,
100	/// Whether it gives the secrets, which the closed library keeps.
101	pub give_secrets: bool,
102	/// What the new device is, and which spaces it gets.
103	pub device: &'a NewDevice,
104}
105
106/// Why a try at a code failed.
107enum TryFailed {
108	/// Before the code matched: the code takes another try, unless this was its last.
109	Unmatched(NodeError),
110	/// Once it matched, or for a reason that ends the wait, such as the code's expiry: it is
111	/// spent.
112	Spent(NodeError),
113}
114
115impl From<NodeError> for TryFailed {
116	fn from(error: NodeError) -> Self {
117		Self::Spent(error)
118	}
119}
120
121/// Takes the tries at a code that this device shows, as `showing` says: each calls `attempt`
122/// with the time left, until one succeeds, the code is spent, or [`CODE_TRIES`] failed before
123/// it matched.
124fn take_tries<T>(
125	showing: Showing<'_>,
126	mut attempt: impl FnMut(Duration) -> Result<T, TryFailed>,
127) -> Result<T, NodeError> {
128	let deadline = Instant::now() + showing.timeout;
129	let mut left = CODE_TRIES;
130	loop {
131		match attempt(deadline.saturating_duration_since(Instant::now())) {
132			Ok(done) => return Ok(done),
133			Err(TryFailed::Unmatched(error)) if left > 1 => {
134				left -= 1;
135				(showing.wrong_try)(&error, left);
136			}
137			Err(TryFailed::Unmatched(error) | TryFailed::Spent(error)) => return Err(error),
138		}
139	}
140}
141
142/// Calls `attempt` with each device that announces `announcement` on the network, one after
143/// the other, as the device that typed a code, until one succeeds or its code is spent: two
144/// pairings at once whose codes share their first two digits announce the same. It waits up
145/// to `timeout` for the first, and [`ANOTHER_SPONSOR`] for each after one failed. A device
146/// that answered that it is busy has matched another's code, which it spent, so it is not
147/// tried again.
148///
149/// # Errors
150///
151/// Returns [`NodeError::NoSponsor`] if none was found, the error of the attempt that spent
152/// the code, and otherwise the error of the attempts that failed: that the code did not
153/// match, if one said so, as it is the one a person can act on.
154fn try_each<T>(
155	network: &Network,
156	announcement: &str,
157	timeout: Duration,
158	mut attempt: impl FnMut([u8; 32]) -> Result<T, TryFailed>,
159) -> Result<T, NodeError> {
160	let deadline = Instant::now() + timeout;
161	let mut tried = BTreeSet::new();
162	let mut failed: Option<NodeError> = None;
163	loop {
164		let left = deadline.saturating_duration_since(Instant::now());
165		let wait = if failed.is_some() {
166			left.min(ANOTHER_SPONSOR)
167		} else {
168			left
169		};
170		let Ok(device) = network.find_announcing(announcement, &tried, wait) else {
171			return Err(failed.unwrap_or(NodeError::NoSponsor));
172		};
173		match attempt(device) {
174			Ok(done) => return Ok(done),
175			Err(TryFailed::Spent(error)) => return Err(error),
176			Err(TryFailed::Unmatched(error)) => {
177				tried.insert(device);
178				failed = Some(match failed {
179					Some(wrong) if wrong.is_wrong_code() => wrong,
180					_ => error,
181				});
182			}
183		}
184	}
185}
186
187/// How often pairing with a closed library checks whether to stop waiting.
188const STOP_CHECK: Duration = Duration::from_millis(250);
189
190impl Library {
191	/// Starts this replica's endpoint, as `options` say.
192	///
193	/// # Errors
194	///
195	/// Returns an error if networking cannot start.
196	pub fn network(&self, options: Options) -> Result<Network, NodeError> {
197		start_network(&self.endpoint_secret(), options)
198	}
199}
200
201/// Starts the endpoint whose key has this secret.
202pub(crate) fn start_network(
203	secret: &nibkeep_crypto::Key,
204	options: Options,
205) -> Result<Network, NodeError> {
206	Ok(Network::start(secret.expose_bytes(), options)?)
207}
208
209/// A replica that pairing added.
210#[derive(Debug)]
211pub struct Paired {
212	/// The new replica.
213	pub replica: EntityId,
214	/// The name of its device.
215	pub device: String,
216	/// The name of its app, or of the AI agent whose replica it is.
217	pub app: String,
218	/// Whether it is an AI agent's replica.
219	pub ai_agent: bool,
220	/// What it asked for besides the library: the secrets, and whether it was given them.
221	pub asked_for: AskedFor,
222	/// Its first sync, which it starts right after pairing.
223	pub synced: Synced,
224}
225
226/// Pairs a new replica, as the sponsor: announces the code's first two digits on the
227/// network, waits as `showing` says for a replica to pair with the code, records it once it
228/// says it made its library, and answers its first sync. `network` must take connections.
229/// The code takes [`CODE_TRIES`] tries: the one in which it matches spends it, and so does
230/// the last of those that fail before it matches; `showing` is told of the others. If the
231/// first sync fails, the new replica's records are deleted again, as the new replica
232/// removes its library: the pairing failed. Changes are made at the time `now` gives when
233/// they are made.
234///
235/// # Errors
236///
237/// Returns [`NodeError::PairingExpired`] if no replica paired in time, the error of the
238/// last try if each failed before the code matched, such as [`NodeError::Sync`] with
239/// [`SyncError::WrongCode`] if one typed another code, [`NodeError::PairingFailed`] if the
240/// first sync failed, and other errors if the network or the library fails.
241pub fn pair(
242	library: &mut Library,
243	network: &Network,
244	code: &PairingCode,
245	showing: Showing<'_>,
246	now: &dyn Fn() -> u64,
247	rng: &mut impl CryptoRng,
248) -> Result<Paired, NodeError> {
249	pair_device(
250		library,
251		network,
252		code,
253		(&NewDevice::computer(), false),
254		showing,
255		now,
256		rng,
257	)
258}
259
260/// Pairs a new device of the person's, as [`pair`] does, as they chose: a computer, which
261/// gets every space of this device's, or the spaces chosen, and takes those given to it
262/// later; or a phone, which gets the personal space alone, or the spaces chosen, and asks
263/// before it takes a space given to it later
264/// ([technical design](../../../docs/Technical-design.md#1310-devices-that-choose-their-spaces)).
265/// With `give_secrets`, it gives the new device the secrets, as [`pair_giving_secrets`]
266/// does.
267///
268/// # Errors
269///
270/// Returns the errors of [`pair`]; and, before the code is shown,
271/// [`NodeError::SecretsLocked`] if the secrets are to be given and are not unlocked, and
272/// [`NodeError::NoSpace`] or [`NodeError::NotListed`] for a space chosen that this device
273/// does not hold, or is not listed in.
274pub fn pair_device(
275	library: &mut Library,
276	network: &Network,
277	code: &PairingCode,
278	(device, give_secrets): (&NewDevice, bool),
279	showing: Showing<'_>,
280	now: &dyn Fn() -> u64,
281	rng: &mut impl CryptoRng,
282) -> Result<Paired, NodeError> {
283	if give_secrets && !library.secrets_unlocked(library.personal_space()) {
284		return Err(NodeError::SecretsLocked);
285	}
286	library.check_new_device(device)?;
287	pair_as(
288		library,
289		network,
290		(code, Pairing::Device(device), give_secrets),
291		showing,
292		now,
293		rng,
294	)
295}
296
297/// Pairs a new replica of an AI agent named `name`, as [`pair`] pairs one of the user's:
298/// the change that lists its key marks it as an AI agent's, for good, and it is named after
299/// the AI agent ([technical design](../../../docs/Technical-design.md#14-ai-agents)).
300///
301/// # Errors
302///
303/// Returns the errors of [`pair`], and [`NodeError::AiAgentMayNot`] if this replica is an
304/// AI agent's itself.
305pub fn pair_ai_agent(
306	library: &mut Library,
307	network: &Network,
308	code: &PairingCode,
309	name: &str,
310	showing: Showing<'_>,
311	now: &dyn Fn() -> u64,
312	rng: &mut impl CryptoRng,
313) -> Result<Paired, NodeError> {
314	pair_ai_agent_in(library, network, code, (name, &[]), showing, now, rng)
315}
316
317/// Pairs a new replica of an AI agent as [`pair_ai_agent`] does, and lists it in `spaces`
318/// too, besides the personal one, as the person chose ([technical design: sharing]): its key
319/// signs its listing in each as it joins, and it takes each from the personal space, which
320/// gives it their first keys. A shared space must allow AI agents, which an admin's replica
321/// says, if it does not yet, once the AI agent's replica has joined. The AI agent's replica gets no other space; it is paired anew
322/// to change them.
323///
324/// [technical design: sharing]: ../../../docs/Technical-design.md#13-sharing
325///
326/// # Errors
327///
328/// Returns the errors of [`pair_ai_agent`]; and, before the code is shown,
329/// [`NodeError::NeverShared`] for a space without members, [`NodeError::NotListed`] for one
330/// this replica is not listed in, and [`NodeError::AiAgentsNotAllowed`] for one that allows
331/// no AI agents, where this replica's member is no admin.
332pub fn pair_ai_agent_in(
333	library: &mut Library,
334	network: &Network,
335	code: &PairingCode,
336	(name, spaces): (&str, &[SpaceId]),
337	showing: Showing<'_>,
338	now: &dyn Fn() -> u64,
339	rng: &mut impl CryptoRng,
340) -> Result<Paired, NodeError> {
341	pair_as(
342		library,
343		network,
344		(code, Pairing::AiAgent((name, spaces)), false),
345		showing,
346		now,
347		rng,
348	)
349}
350
351/// Pairs a new replica as [`pair`] does, and gives it the secrets, if it asks for them: the
352/// person chose to, and they are unlocked.
353///
354/// # Errors
355///
356/// Returns the errors of [`pair`], and [`NodeError::SecretsLocked`] if the secrets are not
357/// unlocked, before the code is shown.
358pub fn pair_giving_secrets(
359	library: &mut Library,
360	network: &Network,
361	code: &PairingCode,
362	showing: Showing<'_>,
363	now: &dyn Fn() -> u64,
364	rng: &mut impl CryptoRng,
365) -> Result<Paired, NodeError> {
366	pair_device(
367		library,
368		network,
369		code,
370		(&NewDevice::computer(), true),
371		showing,
372		now,
373		rng,
374	)
375}
376
377/// Whom pairing adds: a device of the person's, as they chose, or an AI agent's replica,
378/// with its name and the spaces chosen for it.
379#[derive(Clone, Copy)]
380enum Pairing<'a> {
381	Device(&'a NewDevice),
382	AiAgent(AiAgent<'a>),
383}
384
385fn pair_as(
386	library: &mut Library,
387	network: &Network,
388	(code, pairing, give_secrets): (&PairingCode, Pairing<'_>, bool),
389	showing: Showing<'_>,
390	now: &dyn Fn() -> u64,
391	rng: &mut impl CryptoRng,
392) -> Result<Paired, NodeError> {
393	library.check_not_ai_agent("add devices")?;
394	if let Pairing::AiAgent((name, spaces)) = pairing {
395		if name.trim().is_empty() {
396			return Err(NodeError::EmptyName);
397		}
398		// Before the code is shown: each space chosen can list the AI agent.
399		library.check_ai_spaces(spaces)?;
400	}
401	network.announce(Some(&code.announcement()))?;
402	let paired = take_tries(showing, |left| {
403		let connection = accept_pairing(network, left, None)?;
404		let pairing = (code, pairing, give_secrets);
405		sponsor_connected(library, network, connection, pairing, now, rng)
406	});
407	network.announce(None)?;
408	paired
409}
410
411/// Pairs a new replica as [`pair`] does, with the library closed while it waits for one, so
412/// that other programs, and the app itself, can use the library in between: it is opened
413/// once a new replica connects to pair, waiting a little for another program to close it,
414/// and closed again after a try that failed before the code matched. It stops waiting, as
415/// if the time were up, once `stop` is set, and gives the secrets as [`pair_giving_secrets`]
416/// does if `waiting` says so. The caller checks first that this replica may add devices,
417/// with [`Library::check_not_ai_agent`], before it shows the code.
418///
419/// # Errors
420///
421/// Returns the errors of [`pair`]; [`NodeError::SecretsLocked`] if the secrets are to be
422/// given, and `closed` kept none, before the code is shown; and [`NodeError::Store`] with
423/// [`StoreError::InUse`] if another program kept the library open after a new replica
424/// connected.
425///
426/// [`StoreError::InUse`]: nibkeep_store::StoreError::InUse
427pub fn pair_closed(
428	closed: &Closed,
429	network: &Network,
430	code: &PairingCode,
431	waiting: &Waiting<'_>,
432	now: &dyn Fn() -> u64,
433	rng: &mut impl CryptoRng,
434) -> Result<Paired, NodeError> {
435	if waiting.give_secrets && !closed.secrets_kept() {
436		return Err(NodeError::SecretsLocked);
437	}
438	network.announce(Some(&code.announcement()))?;
439	let paired = take_tries(waiting.showing, |left| {
440		let connection = accept_pairing(network, left, Some(waiting.stop))?;
441		let mut library = retry_in_use(OPEN_WAIT, || closed.open())?;
442		library.check_new_device(waiting.device)?;
443		let pairing = (code, Pairing::Device(waiting.device), waiting.give_secrets);
444		sponsor_connected(&mut library, network, connection, pairing, now, rng)
445	});
446	network.announce(None)?;
447	paired
448}
449
450/// Calls `open`, which opens a library, again while another program has the library open,
451/// for up to `wait`: [`NodeError::in_use`] says so.
452///
453/// # Errors
454///
455/// Returns the error of the last call.
456pub fn retry_in_use<T>(
457	wait: Duration,
458	mut open: impl FnMut() -> Result<T, NodeError>,
459) -> Result<T, NodeError> {
460	let deadline = Instant::now() + wait;
461	loop {
462		match open() {
463			Err(error) if error.in_use() && Instant::now() < deadline => {
464				std::thread::sleep(Duration::from_millis(50));
465			}
466			opened => return opened,
467		}
468	}
469}
470
471/// Waits up to `timeout` for a new replica to connect to pair, or until `stop` is set;
472/// other connections are refused meanwhile.
473fn accept_pairing(
474	network: &Network,
475	timeout: Duration,
476	stop: Option<&AtomicBool>,
477) -> Result<Connection, NodeError> {
478	accept_first(network, Protocol::Pair, timeout, stop)?.ok_or(NodeError::PairingExpired)
479}
480
481/// Waits up to `timeout` for a connection of `protocol`, or until `stop` is set; other
482/// connections are refused meanwhile. `None` if none came.
483fn accept_first(
484	network: &Network,
485	protocol: Protocol,
486	timeout: Duration,
487	stop: Option<&AtomicBool>,
488) -> Result<Option<Connection>, NodeError> {
489	let deadline = Instant::now() + timeout;
490	loop {
491		let until = match stop {
492			Some(_) => deadline.min(Instant::now() + STOP_CHECK),
493			None => deadline,
494		};
495		let wanted = accept_until(network, until, |connection| {
496			connection.protocol() == protocol
497		})?;
498		if let Some(connection) = wanted {
499			return Ok(Some(connection));
500		}
501		if Instant::now() >= deadline || stop.is_some_and(|stop| stop.load(Ordering::Relaxed)) {
502			return Ok(None);
503		}
504	}
505}
506
507/// Pairs the new replica that connected, and answers its first sync.
508fn sponsor_connected(
509	library: &mut Library,
510	network: &Network,
511	mut connection: Connection,
512	(code, pairing, give_secrets): (&PairingCode, Pairing<'_>, bool),
513	now: &dyn Fn() -> u64,
514	rng: &mut impl CryptoRng,
515) -> Result<Paired, TryFailed> {
516	let joiner = connection.peer();
517	let ai_agent = match pairing {
518		Pairing::AiAgent(chosen) => Some(chosen),
519		Pairing::Device(_) => None,
520	};
521	let mut sponsor = match pairing {
522		Pairing::AiAgent(chosen) => Sponsor::ai_agent_in(library, chosen, now),
523		Pairing::Device(device) if give_secrets => Sponsor::new(library, now)
524			.giving_secrets()
525			.for_device(device.clone()),
526		Pairing::Device(device) => Sponsor::new(library, now).for_device(device.clone()),
527	};
528	let sponsored = nibkeep_sync::sponsor(&mut connection, &mut sponsor, code, rng);
529	let (asked_for, matched) = (sponsor.asked_for(), sponsor.matched());
530	connection.close();
531	let sponsored = sponsored.map_err(|error| {
532		if matched {
533			TryFailed::Spent(error.into())
534		} else {
535			TryFailed::Unmatched(error.into())
536		}
537	})?;
538	// The new replica syncs next, from the endpoint it paired from.
539	let deadline = Instant::now() + FIRST_SYNC_TIMEOUT;
540	let synced = match accept_until(network, deadline, |connection| {
541		connection.protocol() == Protocol::Sync && connection.peer() == joiner
542	}) {
543		Ok(Some(mut connection)) => {
544			let synced = nibkeep_sync::respond(&mut connection, &mut Syncing::new(library, now));
545			connection.close();
546			synced.map_err(NodeError::from)
547		}
548		Ok(None) => Err(NodeError::Network(NetError::Timeout)),
549		Err(error) => Err(error),
550	};
551	match synced {
552		Ok(synced) => {
553			// The pairing is done. If settling the keys fails, the next sync tries again.
554			let _ = library.settle_keys(now(), rng);
555			// A new replica that asks for the secrets says so itself after its first sync, and
556			// syncs once more; if it does not, the next sync tells.
557			if sponsored.request.secrets.is_some() {
558				let deadline = Instant::now() + ASKING_SYNC_TIMEOUT;
559				if let Ok(Some(mut connection)) = accept_until(network, deadline, |connection| {
560					connection.protocol() == Protocol::Sync && connection.peer() == joiner
561				}) {
562					let _ = nibkeep_sync::respond(&mut connection, &mut Syncing::new(library, now));
563					connection.close();
564					let _ = library.settle_keys(now(), rng);
565				}
566			}
567			Ok(Paired {
568				replica: sponsored.grant.replica,
569				device: sponsored.request.device,
570				app: ai_agent.map_or(sponsored.request.app, |(name, _)| name.to_owned()),
571				ai_agent: ai_agent.is_some(),
572				asked_for,
573				synced,
574			})
575		}
576		Err(error) => {
577			library.forget_replica(&sponsored.grant, &sponsored.request.signing, now(), rng)?;
578			Err(NodeError::PairingFailed(Box::new(error)).into())
579		}
580	}
581}
582
583/// Takes connections until one that `wanted` wants arrives, or `deadline` passes. The
584/// others are refused.
585fn accept_until(
586	network: &Network,
587	deadline: Instant,
588	wanted: impl Fn(&Connection) -> bool,
589) -> Result<Option<Connection>, NodeError> {
590	loop {
591		let left = deadline.saturating_duration_since(Instant::now());
592		if left.is_zero() {
593			return Ok(None);
594		}
595		let Some(mut connection) = network.accept(Some(left))? else {
596			return Ok(None);
597		};
598		if wanted(&connection) {
599			return Ok(Some(connection));
600		}
601		let _ = nibkeep_sync::refuse(&mut connection, Reason::Busy);
602		connection.close();
603	}
604}
605
606/// A library made by pairing with a sponsor, and its first sync.
607pub struct Joined {
608	/// The new library.
609	pub library: Library,
610	/// Its first sync.
611	pub synced: Synced,
612	/// How many blobs and changes its first sync refused, as the disk would have had less than 1 GiB
613	/// free.
614	pub refused: usize,
615}
616
617/// Makes a library in a directory that holds none by pairing a new replica with the
618/// replica that shows `code` on the network, and syncs with it: it tries each that announces
619/// the code's first two digits in turn, waiting up to `timeout` to find the first.
620/// `network` is the new replica's, started with [`Joining::network`]. The keys are protected
621/// as `protection` says. If the first sync fails, the library is removed again, as the
622/// sponsor deletes the new replica's records: the pairing failed.
623///
624/// # Errors
625///
626/// Returns [`NodeError::NoSponsor`] if no replica announces the code in time,
627/// [`NodeError::Sync`] with [`SyncError::WrongCode`] if the code matched with none,
628/// [`NodeError::PairingFailed`] if the first sync failed, and other errors if the network
629/// or the files fail.
630#[expect(
631	clippy::too_many_arguments,
632	reason = "one exchange, with what it needs"
633)]
634pub fn join(
635	directory: &Path,
636	joining: Joining,
637	network: &Network,
638	code: &PairingCode,
639	protection: &NewProtection<'_>,
640	timeout: Duration,
641	now: &dyn Fn() -> u64,
642	rng: &mut impl CryptoRng,
643) -> Result<Joined, NodeError> {
644	// Before the code is spent. Copies of replicas made elsewhere stay, and the new one
645	// goes beside them.
646	match Library::replica_folder(directory) {
647		Err(NodeError::NoLibrary | NodeError::Copied) => {}
648		_ => return Err(NodeError::Exists),
649	}
650	joining.check_secrets_protection(protection)?;
651	let mut joining = joining;
652	joining.seal_secrets(rng)?;
653	let asks_for_secrets = joining.asks_for_secrets();
654	let request = joining.request();
655	let announcement = code.announcement();
656	let (sponsor, mut connection, grant) = try_each(network, &announcement, timeout, |sponsor| {
657		let mut connection = network
658			.connect(sponsor, Protocol::Pair, CONNECT_TIMEOUT)
659			.map_err(|error| TryFailed::Unmatched(error.into()))?;
660		match nibkeep_sync::join(&mut connection, &request, code, rng) {
661			Ok(grant) => Ok((sponsor, connection, grant)),
662			Err(error) => {
663				// So that what this side said reaches the other.
664				connection.close();
665				Err(TryFailed::Unmatched(error.into()))
666			}
667		}
668	})?;
669	let mut library = match joining.make(directory, &grant, protection, rng) {
670		Ok(library) => library,
671		Err(error) => {
672			let _ = nibkeep_sync::refuse(&mut connection, Reason::Failed);
673			connection.close();
674			return Err(error);
675		}
676	};
677	// Its key signs its listing in the personal space, and an AI agent's in the spaces
678	// chosen for it.
679	let listings = library.pairing_listings(&grant);
680	let synced = nibkeep_sync::joined(&mut connection, grant.clone(), listings)
681		.map_err(NodeError::from)
682		.and_then(|_| {
683			connection.close();
684			let mut connection = network.connect(sponsor, Protocol::Sync, CONNECT_TIMEOUT)?;
685			let mut syncing = Syncing::new(&mut library, now).trusting(grant.sponsor);
686			let synced = nibkeep_sync::initiate(&mut connection, &mut syncing);
687			let refused = syncing.refused();
688			// Saves what a sync that failed received.
689			drop(syncing);
690			connection.close();
691			Ok((synced?, refused))
692		});
693	match synced {
694		Ok((synced, refused)) => {
695			// The pairing is done. Only its own key says that it asks for the secrets, and
696			// with which key: it says so first, takes what was given, and syncs once more,
697			// so that the sponsor knows. If it cannot say so, its compartment, which holds
698			// nothing, is removed the next time its secrets are unlocked, and it asks anew.
699			if asks_for_secrets {
700				let _ = library.ask_as_joined(&grant.sponsor, now(), rng);
701			}
702			// If settling the keys fails, the next sync tries again. It takes the spaces
703			// given to it as it paired, then says, as the person chose there, whether it
704			// takes those given to it later; if it cannot say so, it takes them.
705			let _ = library.settle_keys(now(), rng);
706			let _ = library.take_paired_spaces(now(), rng);
707			if grant.asks_first {
708				let _ = library.set_takes_new_spaces(false, now(), rng);
709			}
710			if asks_for_secrets
711				&& let Ok(mut connection) =
712					network.connect(sponsor, Protocol::Sync, CONNECT_TIMEOUT)
713			{
714				let _ =
715					nibkeep_sync::initiate(&mut connection, &mut Syncing::new(&mut library, now));
716				connection.close();
717				let _ = library.settle_keys(now(), rng);
718			}
719			Ok(Joined {
720				library,
721				synced,
722				refused,
723			})
724		}
725		Err(error) => {
726			library.remove_unsynced();
727			Err(NodeError::PairingFailed(Box::new(error)))
728		}
729	}
730}
731
732/// What says whether to add the one who asks to join a space.
733type Confirm<'a> = &'a mut dyn FnMut(&Invitee) -> bool;
734
735/// What an invitation is to: a shared space, the role it gives, and the person in the space
736/// whom it names the new user, which the user agrees to after joining
737/// ([`Library::link_member`]).
738#[derive(Clone, Copy, Debug)]
739pub struct Invitation {
740	/// The space.
741	pub space: SpaceId,
742	/// The role it gives: viewer, editor or admin.
743	pub role: MemberRole,
744	/// The person in the space whom it names the new user, if any.
745	pub person: Option<EntityId>,
746}
747
748/// A member that an invitation added.
749#[derive(Debug)]
750pub struct Invited {
751	/// The member's new record in the space.
752	pub member: EntityId,
753	/// The user's name, as their library has it.
754	pub user_name: String,
755	/// The name of the device that joined.
756	pub device: String,
757	/// Its first sync of the space, which it starts right after the invitation.
758	pub synced: Synced,
759}
760
761/// A space that this library joined by an invitation, and its first sync.
762#[derive(Debug)]
763pub struct JoinedSpace {
764	/// The space.
765	pub space: SpaceId,
766	/// Its name, as the admin's device has it.
767	pub name: String,
768	/// The user's member record there.
769	pub member: EntityId,
770	/// The role it gave.
771	pub role: MemberRole,
772	/// The person in the space whom the admin names the user, by ID and name, if any: the
773	/// link holds once the user agrees, with [`Library::link_member`].
774	pub person: Option<(EntityId, String)>,
775	/// The first sync of the space, with the admin's replica.
776	pub synced: Synced,
777	/// How many blobs and changes its first sync refused, as the disk would have had less
778	/// than 1 GiB free.
779	pub refused: usize,
780}
781
782/// Invites a user to a shared space, as a replica of an admin of it: announces the code's
783/// first two digits on the network, waits as `showing` says for a replica to join with the
784/// code, shows `confirm` who asks, and, once it says yes, adds them as a member with the
785/// role given, lists the replica that joined, and answers its first sync of the space.
786/// `network` must take connections. The code takes tries as in [`pair`]. If the first sync
787/// fails, the joiner removes the space while the member stays, and a new invitation of the
788/// same device makes it that member again; a device listed already comes back so too.
789/// Changes are made at the time `now` gives when they are made.
790///
791/// # Errors
792///
793/// Returns [`NodeError::NeverShared`] for the personal space, [`NodeError::AdminsOnly`]
794/// if this replica's member is no admin, [`NodeError::NoRole`] for the role none,
795/// before the code is shown; [`NodeError::InvitationExpired`] if nobody joined in time, the
796/// error of the last try if each failed before the code matched, such as
797/// [`NodeError::Sync`] with [`SyncError::WrongCode`] if one typed another code,
798/// [`NodeError::Declined`] if `confirm` said no, [`NodeError::Sync`] with
799/// [`SyncError::Ended`] and [`Reason::HoldsSpace`] if the joiner holds the space already,
800/// [`NodeError::InvitationFailed`] if the first sync failed, and other errors if the
801/// network or the library fails.
802///
803/// [`Reason::HoldsSpace`]: nibkeep_sync::Reason::HoldsSpace
804#[expect(
805	clippy::too_many_arguments,
806	reason = "one exchange, with what it needs"
807)]
808pub fn invite(
809	library: &mut Library,
810	network: &Network,
811	invitation: &Invitation,
812	code: &PairingCode,
813	confirm: Confirm<'_>,
814	showing: Showing<'_>,
815	now: &dyn Fn() -> u64,
816	rng: &mut impl CryptoRng,
817) -> Result<Invited, NodeError> {
818	if invitation.role == MemberRole::None {
819		return Err(NodeError::NoRole);
820	}
821	library.check_admin(invitation.space, "invite")?;
822	if let Some(person) = invitation.person {
823		library.check_person(invitation.space, person)?;
824	}
825	network.announce(Some(&code.invitation_announcement()))?;
826	let invited = take_tries(showing, |left| {
827		let connection = accept_first(network, Protocol::Invite, left, None)?
828			.ok_or(NodeError::InvitationExpired)?;
829		invite_connected(
830			library,
831			network,
832			connection,
833			(invitation, code, &mut *confirm),
834			now,
835			rng,
836		)
837	});
838	network.announce(None)?;
839	invited
840}
841
842/// Invites a user to a shared space, as [`invite`] does, as a replica of an admin of it whose
843/// library is closed: it checks the role before the code is shown, waits as `showing` says,
844/// until `stop` is set, without the library open, so that other programs use it meanwhile,
845/// and opens it once a replica connects, closing it again after a try that failed before the
846/// code matched.
847///
848/// # Errors
849///
850/// Returns the errors of [`invite`], [`NodeError::InvitationExpired`] also once `stop` is
851/// set, and [`NodeError::Store`] with [`StoreError::InUse`] if another program kept
852/// the library to itself after a replica connected.
853///
854/// [`StoreError::InUse`]: nibkeep_store::StoreError::InUse
855#[expect(
856	clippy::too_many_arguments,
857	reason = "one exchange, with what it needs"
858)]
859pub fn invite_closed(
860	closed: &Closed,
861	network: &Network,
862	invitation: &Invitation,
863	code: &PairingCode,
864	confirm: Confirm<'_>,
865	(showing, stop): (Showing<'_>, &AtomicBool),
866	now: &dyn Fn() -> u64,
867	rng: &mut impl CryptoRng,
868) -> Result<Invited, NodeError> {
869	if invitation.role == MemberRole::None {
870		return Err(NodeError::NoRole);
871	}
872	{
873		let library = retry_in_use(OPEN_WAIT, || closed.open())?;
874		library.check_admin(invitation.space, "invite")?;
875		if let Some(person) = invitation.person {
876			library.check_person(invitation.space, person)?;
877		}
878	}
879	network.announce(Some(&code.invitation_announcement()))?;
880	let invited = take_tries(showing, |left| {
881		let connection = accept_first(network, Protocol::Invite, left, Some(stop))?
882			.ok_or(NodeError::InvitationExpired)?;
883		let mut library = retry_in_use(OPEN_WAIT, || closed.open())?;
884		invite_connected(
885			&mut library,
886			network,
887			connection,
888			(invitation, code, &mut *confirm),
889			now,
890			rng,
891		)
892	});
893	network.announce(None)?;
894	invited
895}
896
897/// Invites the joiner that connected, and answers its first sync.
898fn invite_connected(
899	library: &mut Library,
900	network: &Network,
901	mut connection: Connection,
902	(invitation, code, confirm): (&Invitation, &PairingCode, Confirm<'_>),
903	now: &dyn Fn() -> u64,
904	rng: &mut impl CryptoRng,
905) -> Result<Invited, TryFailed> {
906	let joiner = connection.peer();
907	let mut admin = Inviter::new(library, invitation, confirm, now);
908	let invited = nibkeep_sync::invite(&mut connection, &mut admin, code, rng);
909	let matched = admin.matched();
910	connection.close();
911	let invited = invited.map_err(|error| match error {
912		SyncError::Declined => TryFailed::Spent(NodeError::Declined),
913		error if matched => TryFailed::Spent(error.into()),
914		error => TryFailed::Unmatched(error.into()),
915	})?;
916	// The joiner syncs the space next, from the endpoint it joined from.
917	let started = now();
918	let deadline = Instant::now() + FIRST_SYNC_TIMEOUT;
919	let synced = match accept_until(network, deadline, |connection| {
920		connection.protocol() == Protocol::Sync && connection.peer() == joiner
921	}) {
922		Ok(Some(mut connection)) => {
923			let synced = nibkeep_sync::respond(&mut connection, &mut Syncing::new(library, now));
924			connection.close();
925			synced.map_err(NodeError::from)
926		}
927		Ok(None) => Err(NodeError::Network(NetError::Timeout)),
928		Err(error) => Err(error),
929	};
930	match synced {
931		Ok(synced) => {
932			// The invitation is done. If settling the keys fails, the next sync tries again.
933			let _ = library.settle_keys(now(), rng);
934			let _ = library.settle_moves(&synced, started, now(), rng);
935			Ok(Invited {
936				member: invited.offer.member,
937				user_name: invited.request.user_name,
938				device: invited.request.device,
939				synced,
940			})
941		}
942		// The member stays, so that both sides agree whichever saw the sync fail: a joiner
943		// that removed the space comes back as that member when invited again.
944		Err(error) => Err(NodeError::InvitationFailed(Box::new(error)).into()),
945	}
946}
947
948/// Joins a shared space by the invitation of the replica that shows `code` on the network,
949/// and syncs the space with it: it tries each that announces the code's first two digits in
950/// turn, waiting up to `timeout` to find the first. `network` is this replica's. If the
951/// first sync fails, the space is removed again, and a new invitation makes this replica the
952/// same member. The user's other replicas get the space through the personal space, after
953/// their next syncs with this one.
954///
955/// # Errors
956///
957/// Returns [`NodeError::NoSponsor`] if no replica announces the code in time,
958/// [`NodeError::Sync`] with [`SyncError::WrongCode`] if the code matched with none,
959/// [`NodeError::HoldsSpace`] if this library holds the space already, [`NodeError::Sync`]
960/// with [`SyncError::Ended`] and [`Reason::Declined`] if the person who invites declined,
961/// [`NodeError::InvitationFailed`] if the first sync failed, and other errors if the
962/// network or the files fail.
963///
964/// [`Reason::Declined`]: nibkeep_sync::Reason::Declined
965pub fn join_space(
966	library: &mut Library,
967	network: &Network,
968	code: &PairingCode,
969	timeout: Duration,
970	now: &dyn Fn() -> u64,
971	rng: &mut impl CryptoRng,
972) -> Result<JoinedSpace, NodeError> {
973	library.check_not_ai_agent("join spaces")?;
974	library.check_not_revoked(library.personal_space())?;
975	let request = library.invitation_request()?;
976	let announcement = code.invitation_announcement();
977	let (admin, invitation, back) = try_each(network, &announcement, timeout, |admin| {
978		let mut connection = network
979			.connect(admin, Protocol::Invite, CONNECT_TIMEOUT)
980			.map_err(|error| TryFailed::Unmatched(error.into()))?;
981		let mut acceptor = Acceptor::new(library);
982		let accepted = nibkeep_sync::accept(&mut connection, &request, &mut acceptor, code, rng);
983		let (held, taken, back) = (acceptor.held, acceptor.taken, acceptor.back);
984		let matched = acceptor.matched;
985		// So that what this side said reaches the other.
986		connection.close();
987		match accepted {
988			Ok(invitation) => Ok((admin, invitation, back)),
989			Err(SyncError::HoldsSpace) => Err(TryFailed::Spent(held.map_or(
990				NodeError::Sync(SyncError::HoldsSpace),
991				NodeError::HoldsSpace,
992			))),
993			// The admin's device took the code, and the person declined.
994			Err(error @ SyncError::Ended(Reason::Declined)) => Err(TryFailed::Spent(error.into())),
995			Err(error) => {
996				if let Some(space) = taken {
997					library.remove_space(space, rng);
998				}
999				// What this side refused, it says itself.
1000				let error = match error {
1001					SyncError::Holder(inner) => match inner.downcast::<NodeError>() {
1002						Ok(refused) => *refused,
1003						Err(inner) => NodeError::Sync(SyncError::Holder(inner)),
1004					},
1005					error => error.into(),
1006				};
1007				Err(if matched {
1008					TryFailed::Spent(error)
1009				} else {
1010					TryFailed::Unmatched(error)
1011				})
1012			}
1013		}
1014	})?;
1015	let space = invitation.offer.space;
1016	let started = now();
1017	let synced = network
1018		.connect(admin, Protocol::Sync, CONNECT_TIMEOUT)
1019		.map_err(NodeError::from)
1020		.and_then(|mut connection| {
1021			let mut syncing = Syncing::new(library, now).trusting(invitation.grant.admin);
1022			let synced = nibkeep_sync::initiate(&mut connection, &mut syncing);
1023			let refused = syncing.refused();
1024			// Saves what a sync that failed received.
1025			drop(syncing);
1026			connection.close();
1027			Ok((synced?, refused))
1028		});
1029	match synced {
1030		Ok((synced, refused)) => {
1031			// The invitation is done. The user's devices that take new spaces get it, and
1032			// the others ask for it; if settling the keys fails, the next sync tries again.
1033			let _ = library.settle_keys(now(), rng);
1034			let _ = library.give_new_space(space, &[], now(), rng);
1035			let _ = library.settle_space_names(now(), rng);
1036			library.end_bursts();
1037			let _ = library.settle_moves(&synced, started, now(), rng);
1038			Ok(JoinedSpace {
1039				space,
1040				name: invitation.offer.space_name,
1041				member: invitation.offer.member,
1042				role: MemberRole::from_text(&invitation.offer.role).unwrap_or(MemberRole::Viewer),
1043				person: invitation.offer.person,
1044				synced,
1045				refused,
1046			})
1047		}
1048		Err(error) => {
1049			// A replica that came back keeps the space it held, as it was.
1050			if back.is_none() {
1051				library.remove_space(space, rng);
1052			}
1053			Err(NodeError::InvitationFailed(Box::new(error)))
1054		}
1055	}
1056}
1057
1058/// A sync with one of the user's other replicas.
1059#[derive(Debug)]
1060pub struct SyncedWith {
1061	/// The replica.
1062	pub replica: Replica,
1063	/// What the sync did, or why it failed; [`NodeError::NotFound`] if the replica was not
1064	/// found on the network.
1065	pub synced: Result<Synced, NodeError>,
1066	/// How many blobs and changes it refused, as the disk would have had less than 1 GiB free.
1067	pub refused: usize,
1068	/// The copies of checkouts on this device that it deleted, as it brought purges of
1069	/// their content.
1070	pub deleted: Vec<PathBuf>,
1071}
1072
1073/// Syncs once with each of the user's other replicas that it finds on the network within
1074/// `timeout`, one after the other. `network` need not take connections. What is received
1075/// is checked against the time `now` gives when it arrives.
1076///
1077/// # Errors
1078///
1079/// Returns [`NodeError::NoOtherReplicas`] if the library has no other replica to sync
1080/// with, and an error if the library cannot be read or written; a sync that fails is in
1081/// its result.
1082pub fn sync_with_others(
1083	library: &mut Library,
1084	network: &Network,
1085	timeout: Duration,
1086	now: &dyn Fn() -> u64,
1087	rng: &mut impl CryptoRng,
1088) -> Result<Vec<SyncedWith>, NodeError> {
1089	library.record_own_endpoint(now(), rng)?;
1090	let peers = library.peers()?;
1091	if peers.is_empty() {
1092		return Err(NodeError::NoOtherReplicas);
1093	}
1094	let endpoints = peers.iter().filter_map(|peer| peer.endpoint).collect();
1095	let found = network.find(&endpoints, timeout);
1096	Ok(sync_with_found(library, network, peers, &found, now, rng))
1097}
1098
1099/// Syncs once with each of `peers` whose endpoint is among those `found` on the network,
1100/// one after the other, as [`sync_with_others`] does once it found them: so that a program
1101/// can look for the others with the library closed, with [`Library::peers`] and
1102/// [`Network::find`]. A peer that was not found is in the result as
1103/// [`NodeError::NotFound`].
1104pub fn sync_with_found(
1105	library: &mut Library,
1106	network: &Network,
1107	peers: Vec<Replica>,
1108	found: &BTreeSet<[u8; 32]>,
1109	now: &dyn Fn() -> u64,
1110	rng: &mut impl CryptoRng,
1111) -> Vec<SyncedWith> {
1112	peers
1113		.into_iter()
1114		.map(|replica| sync_one(library, network, replica, found, (now, rng), None))
1115		.collect()
1116}
1117
1118/// Syncs once with `replica`, if its endpoint is among those `found`, putting to it the
1119/// challenges that `removals` has for it, if a pass is given.
1120fn sync_one(
1121	library: &mut Library,
1122	network: &Network,
1123	replica: Replica,
1124	found: &BTreeSet<[u8; 32]>,
1125	(now, rng): (&dyn Fn() -> u64, &mut impl CryptoRng),
1126	removals: Option<&mut Removals>,
1127) -> SyncedWith {
1128	let Some(endpoint) = replica.endpoint.filter(|endpoint| found.contains(endpoint)) else {
1129		return SyncedWith {
1130			replica,
1131			synced: Err(NodeError::NotFound),
1132			refused: 0,
1133			deleted: Vec::new(),
1134		};
1135	};
1136	let mut refused = 0;
1137	let mut deleted = Vec::new();
1138	let started = now();
1139	let result = network
1140		.connect(endpoint, Protocol::Sync, CONNECT_TIMEOUT)
1141		.map_err(NodeError::from)
1142		.and_then(|mut connection| {
1143			// What the checkouts held before, to tell whether purges that arrive leave
1144			// their copies unchanged.
1145			let known = library.checkout_contents().unwrap_or_default();
1146			let mut syncing = Syncing::new(library, now);
1147			if let Some(removals) = removals {
1148				syncing = syncing.proving(removals);
1149			}
1150			let synced = nibkeep_sync::initiate(&mut connection, &mut syncing);
1151			refused = syncing.refused();
1152			// Saves what a sync that failed received.
1153			drop(syncing);
1154			connection.close();
1155			let synced = synced?;
1156			library.settle_keys(now(), rng)?;
1157			// What a restore that came brought back, and a wait that the marks changed.
1158			let _ = library.settle_waiting(now());
1159			// The sync is done; a later one settles what this one could not.
1160			deleted = library
1161				.settle_checkouts(&known, now(), rng)
1162				.unwrap_or_default();
1163			// What moves left behind, now that another device holds what moved.
1164			deleted.extend(
1165				library
1166					.settle_moves(&synced, started, now(), rng)
1167					.unwrap_or_default(),
1168			);
1169			Ok(synced)
1170		});
1171	SyncedWith {
1172		replica,
1173		synced: result,
1174		refused,
1175		deleted,
1176	}
1177}
1178
1179/// A pass of removals, and the syncs that it ran for proofs.
1180#[derive(Debug)]
1181pub struct RemovalPass {
1182	/// What it removed, and what waits.
1183	pub removed: Removed,
1184	/// The syncs with the replicas asked to prove their copies.
1185	pub synced: Vec<SyncedWith>,
1186	/// How many thumbnails made twice it purged, those this replica made of contents that
1187	/// show another ([`Library::purge_thumbnails_made_twice`]).
1188	pub thumbnails: usize,
1189	/// How many parts of what purges destroyed went for good, as their wait ended
1190	/// ([`Library::destroy_due`]).
1191	pub destroyed: usize,
1192}
1193
1194/// Removes, a little at a time, the copies that this replica no longer keeps, once other
1195/// disks have proven theirs ([technical design: the planner]): plans a pass
1196/// ([`Library::plan_removals`]) among the replicas whose endpoints were `found` on the
1197/// network, syncs with each that is to prove its copies, one after the other, putting the
1198/// challenges to it, and removes the copies whose proofs came in time
1199/// ([`Library::remove_proven`]), marked in `records` while they go; then purges the
1200/// thumbnails that it made twice ([`Library::purge_thumbnails_made_twice`]). First, it
1201/// destroys what purges destroyed whose wait has ended ([`Library::destroy_due`]).
1202///
1203/// [technical design: the planner]: ../../../docs/Technical-design.md#99-the-planner
1204///
1205/// # Errors
1206///
1207/// Returns an error if the library cannot be read, the records cannot be written, or a copy
1208/// cannot be removed; a sync that fails is in the result, and the copies it was to prove
1209/// stay.
1210pub fn remove_unkept(
1211	library: &mut Library,
1212	network: &Network,
1213	records: &Records,
1214	found: &BTreeSet<[u8; 32]>,
1215	now: &dyn Fn() -> u64,
1216	rng: &mut impl CryptoRng,
1217) -> Result<RemovalPass, NodeError> {
1218	// What purges destroyed goes for good once the wait for it ends, network or not.
1219	let destroyed = library.destroy_due(now());
1220	let mut removals = library.plan_removals(records, found, now(), rng)?;
1221	let mut synced = Vec::new();
1222	for replica in removals.provers().to_vec() {
1223		synced.push(sync_one(
1224			library,
1225			network,
1226			replica,
1227			found,
1228			(now, rng),
1229			Some(&mut removals),
1230		));
1231	}
1232	let mut removed = library.remove_proven(&removals, records, now(), rng)?;
1233	// A purge that fails waits for the next pass, and what the pass did stands.
1234	let thumbnails = library
1235		.purge_thumbnails_made_twice(now(), rng)
1236		.unwrap_or_else(|error| {
1237			removed.failed.push(error.to_string());
1238			0
1239		});
1240	let destroyed = destroyed.unwrap_or_else(|error| {
1241		removed.failed.push(error.to_string());
1242		0
1243	});
1244	Ok(RemovalPass {
1245		removed,
1246		synced,
1247		thumbnails,
1248		destroyed,
1249	})
1250}
1251
1252/// A sync that another replica started.
1253#[derive(Debug)]
1254pub struct Answered {
1255	/// The other replica's endpoint ID.
1256	pub endpoint: [u8; 32],
1257	/// The other replica, as the library lists it after the sync, if it does.
1258	pub replica: Option<Replica>,
1259	/// What the sync did, or why it failed.
1260	pub synced: Result<Synced, NodeError>,
1261	/// How many blobs and changes it refused, as the disk would have had less than 1 GiB free.
1262	pub refused: usize,
1263	/// The copies of checkouts on this device that it deleted, as it brought purges of
1264	/// their content.
1265	pub deleted: Vec<PathBuf>,
1266}
1267
1268/// Waits up to `timeout`, or for as long as it takes, for another replica to sync, and
1269/// answers it, on a `network` that takes connections: the library is opened for the sync
1270/// and closed after it, so that other programs can use it in between. A replica that
1271/// connects while another program has the library open is told to try again later. After a
1272/// sync, the keys of the spaces are settled, as [`Library::settle_keys`] says, and then the
1273/// checkouts, as [`Library::settle_checkouts`] says. `None` if none came in time.
1274///
1275/// # Errors
1276///
1277/// Returns an error if the network fails; a sync that fails is in its result.
1278pub fn answer(
1279	closed: &Closed,
1280	network: &Network,
1281	timeout: Option<Duration>,
1282	now: &dyn Fn() -> u64,
1283	rng: &mut impl CryptoRng,
1284) -> Result<Option<Answered>, NodeError> {
1285	let Some(connection) = network.accept(timeout)? else {
1286		return Ok(None);
1287	};
1288	Ok(Some(answer_connection(Some(closed), connection, now, rng)))
1289}
1290
1291/// Answers a connection that another replica opened, as [`answer`] does once it accepted
1292/// one: so that a program can wait for connections without holding its library, and answer
1293/// each with the library it holds then. Without a library, as when it is locked, the other
1294/// replica is told to try again later.
1295pub fn answer_connection(
1296	closed: Option<&Closed>,
1297	mut connection: Connection,
1298	now: &dyn Fn() -> u64,
1299	rng: &mut impl CryptoRng,
1300) -> Answered {
1301	let endpoint = connection.peer();
1302	let Some(closed) = closed else {
1303		let _ = nibkeep_sync::refuse(&mut connection, Reason::Busy);
1304		connection.close();
1305		return Answered {
1306			endpoint,
1307			replica: None,
1308			synced: Err(NodeError::Locked),
1309			refused: 0,
1310			deleted: Vec::new(),
1311		};
1312	};
1313	if connection.protocol() != Protocol::Sync {
1314		let _ = nibkeep_sync::refuse(&mut connection, Reason::Busy);
1315		connection.close();
1316		return Answered {
1317			endpoint,
1318			replica: None,
1319			synced: Err(NodeError::Sync(SyncError::NotAReplica)),
1320			refused: 0,
1321			deleted: Vec::new(),
1322		};
1323	}
1324	let mut library = match closed.open() {
1325		Ok(library) => library,
1326		Err(error) => {
1327			let reason = if error.in_use() {
1328				Reason::Busy
1329			} else {
1330				Reason::Failed
1331			};
1332			let _ = nibkeep_sync::refuse(&mut connection, reason);
1333			connection.close();
1334			return Answered {
1335				endpoint,
1336				replica: None,
1337				synced: Err(error),
1338				refused: 0,
1339				deleted: Vec::new(),
1340			};
1341		}
1342	};
1343	// What the checkouts held before, to tell whether purges that arrive leave their copies
1344	// unchanged.
1345	let known = library.checkout_contents().unwrap_or_default();
1346	let started = now();
1347	let mut syncing = Syncing::new(&mut library, now);
1348	let synced = nibkeep_sync::respond(&mut connection, &mut syncing);
1349	let refused = syncing.refused();
1350	// Saves what a sync that failed received.
1351	drop(syncing);
1352	connection.close();
1353	let mut deleted = Vec::new();
1354	let synced = synced.map_err(NodeError::from).and_then(|synced| {
1355		library.settle_keys(now(), rng)?;
1356		// What a restore that came brought back, and a wait that the marks changed.
1357		let _ = library.settle_waiting(now());
1358		// The sync is done; a later one settles what this one could not.
1359		deleted = library
1360			.settle_checkouts(&known, now(), rng)
1361			.unwrap_or_default();
1362		// What moves left behind, now that another device holds what moved.
1363		deleted.extend(
1364			library
1365				.settle_moves(&synced, started, now(), rng)
1366				.unwrap_or_default(),
1367		);
1368		Ok(synced)
1369	});
1370	// The user's own, or another member's, as a shared space lists it.
1371	let replica = library
1372		.replicas()
1373		.unwrap_or_default()
1374		.into_iter()
1375		.chain(library.other_members_replicas())
1376		.find(|replica| replica.endpoint == Some(endpoint));
1377	drop(library);
1378	Answered {
1379		endpoint,
1380		replica,
1381		synced,
1382		refused,
1383		deleted,
1384	}
1385}