Skip to main content

caretta_sync_core/
server.rs

1use async_trait::async_trait;
2use iroh::discovery::dns::DnsDiscovery;
3use sea_orm_migration::MigratorTrait;
4
5use crate::{
6    config::{IrohConfig, RpcConfig, StorageConfig},
7    error::Error,
8    global::{IROH_ENDPOINT, LOCAL_DATABASE_CONNECTION},
9};
10
11#[async_trait]
12pub trait ServerTrait: Send + Sync {
13    async fn init_database<C, M>(config: &C) -> Result<(), Error>
14    where
15        C: AsRef<StorageConfig> + Send + Sync,
16        M: MigratorTrait,
17    {
18        let _ = LOCAL_DATABASE_CONNECTION
19            .get_or_try_init::<_, M>(&config.as_ref().get_local_database_path())
20            .await?;
21        Ok(())
22    }
23
24    async fn serve_p2p<T>(config: &T) -> Result<(), Error>
25    where
26        T: AsRef<IrohConfig> + Send + Sync,
27    {
28        let endpoint = iroh::Endpoint::builder()
29            .discovery(DnsDiscovery::n0_dns())
30            .bind()
31            .await?;
32        let _ = IROH_ENDPOINT.get_or_init(&endpoint);
33        Ok(())
34    }
35    async fn serve_rpc<T>(config: &T) -> Result<(), Error>
36    where
37        T: AsRef<RpcConfig> + Send + Sync;
38    async fn serve<C, M>(config: &C) -> Result<(), Error>
39    where
40        C: AsRef<IrohConfig> + AsRef<RpcConfig> + AsRef<StorageConfig> + Send + Sync,
41        M: MigratorTrait,
42    {
43        Self::init_database::<_, M>(config).await?;
44        tokio::try_join!(Self::serve_p2p(config), Self::serve_rpc(config))?;
45        Ok(())
46    }
47}