occams_rpc/server/
dispatch.rs1use super::service::ServiceStatic;
4use super::task::{APIServerReq, APIServerResp};
5use captains_log::*;
6use razor_stream::{
7 Codec,
8 proto::RpcAction,
9 server::{RpcSvrReq, dispatch::Dispatch, task::RespNoti},
10};
11use std::marker::PhantomData;
12use std::sync::Arc;
13
14pub trait APIDispatchTrait: Send + Sync + 'static + Clone {
16 type Codec: Codec;
17
18 fn dispatch(
19 &self, req: APIServerReq<Self::Codec>,
20 ) -> impl Future<Output = Result<(), ()>> + Send;
21}
22
23#[derive(Clone)]
27pub struct APIDispatch<D: APIDispatchTrait>(D);
28
29impl<D: APIDispatchTrait> Dispatch for APIDispatch<D> {
30 type RespTask = APIServerResp;
31
32 type Codec = D::Codec;
33
34 #[inline]
35 async fn dispatch_req<'a>(
36 &'a self, codec: &Arc<Self::Codec>, req: RpcSvrReq<'a>, noti: RespNoti<Self::RespTask>,
37 ) -> Result<(), ()> {
38 if let RpcAction::Str(action) = req.action {
39 if let Some((service, method)) = action.split_once('.') {
40 return self
41 .0
42 .dispatch(APIServerReq::<Self::Codec> {
43 seq: req.seq,
44 service: service.to_string(),
45 method: method.to_string(),
46 req: Some(req.msg.to_vec()),
47 codec: codec.clone(),
48 noti,
49 })
50 .await;
51 }
52 }
53 warn!("{:?} invalid action", req);
54 return Err(());
55 }
56}
57
58pub type DispatchInline<C, S> = APIDispatch<Inline<C, S>>;
59
60pub struct Inline<C: Codec, S: ServiceStatic<C> + Clone> {
64 service: S,
65 _phan: PhantomData<fn(&C)>,
66}
67
68impl<C: Codec, S: ServiceStatic<C> + Clone> Inline<C, S> {
69 #[inline]
70 pub fn new(s: S) -> DispatchInline<C, S> {
71 APIDispatch(Inline { service: s, _phan: Default::default() })
72 }
73}
74
75impl<C: Codec, S: ServiceStatic<C> + Clone> Clone for Inline<C, S> {
76 #[inline]
77 fn clone(&self) -> Self {
78 Self { service: self.service.clone(), _phan: Default::default() }
79 }
80}
81
82impl<C: Codec, S: ServiceStatic<C> + Clone> APIDispatchTrait for Inline<C, S> {
83 type Codec = C;
84
85 #[inline]
86 async fn dispatch(&self, req: APIServerReq<C>) -> Result<(), ()> {
87 self.service.serve(req).await;
88 return Ok(());
89 }
90}