1use 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
25type AiAgent<'a> = (&'a str, &'a [SpaceId]);
28
29const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
31
32const FIRST_SYNC_TIMEOUT: Duration = Duration::from_mins(2);
34
35const ASKING_SYNC_TIMEOUT: Duration = Duration::from_secs(30);
38
39const OPEN_WAIT: Duration = Duration::from_secs(10);
42
43pub const CODE_TRIES: usize = 3;
48
49const ANOTHER_SPONSOR: Duration = Duration::from_secs(2);
53
54pub type WrongTry<'a> = &'a dyn Fn(&NodeError, usize);
58
59#[derive(Clone, Copy)]
62pub struct Showing<'a> {
63 pub timeout: Duration,
65 pub wrong_try: WrongTry<'a>,
67}
68
69impl Showing<'static> {
70 #[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
88const fn tell_nobody(_: &NodeError, _: usize) {}
90
91#[derive(Clone, Copy, Debug)]
95pub struct Waiting<'a> {
96 pub showing: Showing<'a>,
98 pub stop: &'a AtomicBool,
100 pub give_secrets: bool,
102 pub device: &'a NewDevice,
104}
105
106enum TryFailed {
108 Unmatched(NodeError),
110 Spent(NodeError),
113}
114
115impl From<NodeError> for TryFailed {
116 fn from(error: NodeError) -> Self {
117 Self::Spent(error)
118 }
119}
120
121fn 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
142fn 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
187const STOP_CHECK: Duration = Duration::from_millis(250);
189
190impl Library {
191 pub fn network(&self, options: Options) -> Result<Network, NodeError> {
197 start_network(&self.endpoint_secret(), options)
198 }
199}
200
201pub(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#[derive(Debug)]
211pub struct Paired {
212 pub replica: EntityId,
214 pub device: String,
216 pub app: String,
218 pub ai_agent: bool,
220 pub asked_for: AskedFor,
222 pub synced: Synced,
224}
225
226pub 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
260pub 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
297pub 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
317pub 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
351pub 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#[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 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
411pub 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
450pub 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
471fn 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
481fn 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
507fn 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 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 let _ = library.settle_keys(now(), rng);
555 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
583fn 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
606pub struct Joined {
608 pub library: Library,
610 pub synced: Synced,
612 pub refused: usize,
615}
616
617#[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 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 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 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 drop(syncing);
690 connection.close();
691 Ok((synced?, refused))
692 });
693 match synced {
694 Ok((synced, refused)) => {
695 if asks_for_secrets {
700 let _ = library.ask_as_joined(&grant.sponsor, now(), rng);
701 }
702 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
732type Confirm<'a> = &'a mut dyn FnMut(&Invitee) -> bool;
734
735#[derive(Clone, Copy, Debug)]
739pub struct Invitation {
740 pub space: SpaceId,
742 pub role: MemberRole,
744 pub person: Option<EntityId>,
746}
747
748#[derive(Debug)]
750pub struct Invited {
751 pub member: EntityId,
753 pub user_name: String,
755 pub device: String,
757 pub synced: Synced,
759}
760
761#[derive(Debug)]
763pub struct JoinedSpace {
764 pub space: SpaceId,
766 pub name: String,
768 pub member: EntityId,
770 pub role: MemberRole,
772 pub person: Option<(EntityId, String)>,
775 pub synced: Synced,
777 pub refused: usize,
780}
781
782#[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#[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
897fn 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 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 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 Err(error) => Err(NodeError::InvitationFailed(Box::new(error)).into()),
945 }
946}
947
948pub 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 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 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 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 drop(syncing);
1026 connection.close();
1027 Ok((synced?, refused))
1028 });
1029 match synced {
1030 Ok((synced, refused)) => {
1031 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 if back.is_none() {
1051 library.remove_space(space, rng);
1052 }
1053 Err(NodeError::InvitationFailed(Box::new(error)))
1054 }
1055 }
1056}
1057
1058#[derive(Debug)]
1060pub struct SyncedWith {
1061 pub replica: Replica,
1063 pub synced: Result<Synced, NodeError>,
1066 pub refused: usize,
1068 pub deleted: Vec<PathBuf>,
1071}
1072
1073pub 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
1099pub 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
1118fn 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 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 drop(syncing);
1154 connection.close();
1155 let synced = synced?;
1156 library.settle_keys(now(), rng)?;
1157 let _ = library.settle_waiting(now());
1159 deleted = library
1161 .settle_checkouts(&known, now(), rng)
1162 .unwrap_or_default();
1163 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#[derive(Debug)]
1181pub struct RemovalPass {
1182 pub removed: Removed,
1184 pub synced: Vec<SyncedWith>,
1186 pub thumbnails: usize,
1189 pub destroyed: usize,
1192}
1193
1194pub 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 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 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#[derive(Debug)]
1254pub struct Answered {
1255 pub endpoint: [u8; 32],
1257 pub replica: Option<Replica>,
1259 pub synced: Result<Synced, NodeError>,
1261 pub refused: usize,
1263 pub deleted: Vec<PathBuf>,
1266}
1267
1268pub 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
1291pub 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 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 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 let _ = library.settle_waiting(now());
1358 deleted = library
1360 .settle_checkouts(&known, now(), rng)
1361 .unwrap_or_default();
1362 deleted.extend(
1364 library
1365 .settle_moves(&synced, started, now(), rng)
1366 .unwrap_or_default(),
1367 );
1368 Ok(synced)
1369 });
1370 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}