1mod handler;
2use std::sync::atomic::{AtomicUsize, Ordering};
3
4use handler::*;
5
6mod session;
7use session::ServiceSession;
8
9use serde::{Deserialize, Serialize};
10
11use crate::{channel::TransportChannel, RPCResult};
12
13#[derive(Default, Clone)]
16pub struct Server {
17 tag: String,
18 methods: HandlerClonerRegister<ServerHandler>,
19 async_methods: HandlerClonerRegister<AsyncServerHandler>,
20}
21
22impl Server {
23 pub fn new<S>(tag: S) -> Self
24 where
25 S: Into<String>,
26 {
27 Self {
28 tag: tag.into(),
29 ..Default::default()
30 }
31 }
32 pub fn handle<P, R, F>(&mut self, method: &'static str, f: F) -> &mut Self
34 where
35 F: FnMut(P) -> RPCResult<Option<R>> + 'static + Clone + Sync + Send,
36 for<'a> P: Deserialize<'a> + Serialize,
37 R: Serialize + Default,
38 {
39 self.methods.register_handler(method, to_handler(method, f));
40
41 self
42 }
43
44 pub fn async_handle<P, R, F, FR>(&mut self, method: &'static str, f: F) -> &mut Self
50 where
51 F: FnMut(P) -> FR + 'static + Sync + Send + Clone,
52 FR: std::future::Future<Output = RPCResult<Option<R>>> + Sync + Send + 'static,
53 for<'a> P: Deserialize<'a> + Serialize + Send,
54 R: Serialize + Default,
55 {
56 self.async_methods
57 .register_handler(method, to_async_handler(method, f));
58
59 self
60 }
61
62 pub fn accept<C: TransportChannel>(&mut self, channel: C) {
63 static INSTANCE: AtomicUsize = AtomicUsize::new(1);
64
65 let id = format!("{}_{}", self.tag, INSTANCE.fetch_add(1, Ordering::SeqCst));
66
67 let (input, output) = channel.framed();
68
69 let mut session = ServiceSession::<C>::new(
70 id,
71 input,
72 output,
73 self.methods.clone(),
74 self.async_methods.clone(),
75 );
76
77 C::spawn(async move { session.run().await });
78 }
79}