chord_rs/
lib.rs

1
2#[cfg(all(feature = "capnp", feature = "grpc"))]
3compile_error!("feature \"capnp\" and feature \"grpc\" cannot be enabled at the same time");
4
5use std::net::SocketAddr;
6
7#[cfg(feature = "grpc")]
8pub use grpc::Server;
9
10#[cfg(feature = "capnp")]
11pub use capnp::Server;
12
13pub struct Config {
14    pub addr: SocketAddr,
15    pub ring: Option<SocketAddr>,
16
17    pub max_connections: usize,
18}
19
20#[cfg(feature = "capnp")]
21mod capnp {
22    use std::net::SocketAddr;
23
24    use crate::Config;
25    use chord_capnp::Server as CapnpServer;
26
27    pub struct Server {
28        server: CapnpServer,
29        config: Config,
30    }
31
32    impl Server {
33        pub async fn new(addr: SocketAddr, config: impl Into<Config>) -> Server {
34            let config: Config = config.into();
35            let chord = CapnpServer::new(addr, config.ring).await;
36
37            Server {
38                server: chord,
39                config
40            }
41        }
42
43        pub async fn run(self) {
44            self.server.run(self.config.max_connections).await;
45        }
46    }
47}
48
49#[cfg(feature = "grpc")]
50mod grpc {
51    use std::net::SocketAddr;
52    use chord_grpc::server::ChordNodeServer;
53    use chord_grpc::server::Server as GrpcServer;
54    use chord_grpc::server::ChordService;
55
56    use crate::Config;
57
58    pub struct Server {
59        addr: SocketAddr,
60        router: tonic::transport::server::Router,
61    }
62
63    impl Server {
64        pub async fn new(addr: SocketAddr, config: impl Into<Config>) -> Server {
65            let config: Config = config.into();
66            let chord = ChordService::new(addr, config.ring).await;
67    
68            let router = GrpcServer::builder()
69                .add_service(ChordNodeServer::new(chord));
70    
71            Server {
72                addr,
73                router
74            }
75        }
76    
77        pub async fn run(self) {
78            match self.router.serve(self.addr).await {
79                Ok(_) => log::info!("Server stopped"),
80                Err(e) => log::error!("Server error: {}", e),
81            }
82        }    
83    }
84}