Skip to main content

syncweb_core/node/
iroh_node.rs

1use anyhow::Result;
2use iroh::protocol::Router;
3use iroh_blobs::BlobsProtocol;
4use iroh_docs::engine::Engine;
5use iroh_gossip::net::Gossip;
6use std::path::PathBuf;
7use std::sync::Arc;
8
9use super::identity::IdentityManager;
10
11pub struct IrohNode {
12    endpoint: iroh::Endpoint,
13    router: Arc<Router>,
14    blobs: iroh_blobs::BlobsProtocol,
15    docs: Arc<Engine>,
16    gossip: Arc<Gossip>,
17}
18
19impl IrohNode {
20    /// Create and start a new IrohNode.
21    pub async fn new(identity: IdentityManager, data_dir: PathBuf) -> Result<Self> {
22        let endpoint = iroh::Endpoint::builder(iroh::endpoint::presets::N0)
23            .secret_key(identity.secret_key().clone())
24            .bind()
25            .await?;
26
27        let blob_store = iroh_blobs::store::fs::FsStore::load(data_dir.join("blobs")).await?;
28        let blobs = BlobsProtocol::new(blob_store.as_ref(), None);
29
30        let gossip = Arc::new(Gossip::builder().spawn(endpoint.clone()));
31
32        let docs_store = iroh_docs::store::Store::persistent(data_dir.join("docs"))?;
33        let downloader = blobs.downloader(&endpoint);
34        let author_storage = iroh_docs::engine::DefaultAuthorStorage::Persistent(data_dir.join("default_author"));
35        let docs = Arc::new(
36            Engine::spawn(
37                endpoint.clone(),
38                (*gossip).clone(),
39                docs_store,
40                blobs.store().clone(),
41                downloader,
42                author_storage,
43                None,
44            )
45            .await?,
46        );
47
48        let router = Router::builder(endpoint.clone())
49            .accept(iroh_blobs::protocol::ALPN, blobs.clone())
50            .accept(iroh_gossip::ALPN, gossip.clone()) // Note: this is not the right ALPN for gossip
51            .spawn();
52
53        Ok(Self {
54            endpoint,
55            router: Arc::new(router),
56            blobs,
57            docs,
58            gossip,
59        })
60    }
61
62    pub fn endpoint(&self) -> &iroh::Endpoint {
63        &self.endpoint
64    }
65
66    pub fn blobs(&self) -> &BlobsProtocol {
67        &self.blobs
68    }
69
70    pub fn docs(&self) -> &Engine {
71        &self.docs
72    }
73
74    pub fn gossip(&self) -> &Gossip {
75        &self.gossip
76    }
77
78    pub async fn shutdown(self) -> Result<()> {
79        self.router.shutdown().await?;
80        self.endpoint.close().await;
81        Ok(())
82    }
83}