From 81ac4baec0746fd5df328e6af25d88c80c0fef4f Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 7 Dec 2021 15:49:13 +0100 Subject: Add Reactor type Signed-off-by: Matthias Beyer --- lib/src/lib.rs | 1 + lib/src/reactor/mod.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 lib/src/reactor/mod.rs diff --git a/lib/src/lib.rs b/lib/src/lib.rs index 0cccef9..b86077a 100644 --- a/lib/src/lib.rs +++ b/lib/src/lib.rs @@ -5,3 +5,4 @@ pub mod ipfs_client; pub mod profile; pub mod stream; pub mod types; +pub mod reactor; diff --git a/lib/src/reactor/mod.rs b/lib/src/reactor/mod.rs new file mode 100644 index 0000000..70088a3 --- /dev/null +++ b/lib/src/reactor/mod.rs @@ -0,0 +1,46 @@ +use std::sync::Arc; + +use anyhow::Result; +use tokio::sync::RwLock; + +use crate::profile::Profile; + +/// Reactor type, for running the application logic +/// +/// The Reactor runs the whole application logic, that is syncing with other devices, fetching and +/// keeping profile updates of other accounts, communication on the gossipsub topics... etc +#[derive(Debug)] +pub struct Reactor { + profile: Arc>, +} + +impl Reactor { + pub fn new(profile: Profile) -> Self { + Reactor { + profile: Arc::new(RwLock::new(profile)), + } + } + + pub async fn head(&self) -> Option { + self.profile.read().await.head().map(cid::Cid::clone) + } + + pub async fn connect(&self, peer: ipfs::MultiaddrWithPeerId) -> Result<()> { + self.profile.read().await.connect(peer).await + } + + pub fn profile(&self) -> Arc> { + self.profile.clone() + } + + pub async fn exit(self) -> Result<()> { + let mut inner = self.profile; + loop { + match Arc::try_unwrap(inner) { + Err(arc) => inner = arc, + Ok(inner) => return inner.into_inner().exit().await, + } + } + } + +} -- cgit v1.2.3