Skip to main content

fusen_rs/server/
rpc.rs

1use crate::{
2    error::FusenError,
3    filter::{FusenFilter, ProceedingJoinPoint},
4    protocol::fusen::{context::FusenContext, service::ServiceInfo},
5};
6use std::{collections::HashMap, sync::Arc};
7
8pub trait RpcService: Send + Sync + FusenFilter {
9    fn get_service_info(&self) -> ServiceInfo;
10}
11
12#[derive(Clone, Default)]
13pub struct RpcServerHandler {
14    cache: HashMap<String, Arc<Box<dyn FusenFilter>>>,
15}
16
17impl RpcServerHandler {
18    pub fn new(cache: HashMap<String, Box<dyn RpcService>>) -> Self {
19        let mut leak_cache: HashMap<String, Arc<Box<dyn FusenFilter>>> = HashMap::default();
20        for (key, value) in cache {
21            let _ = leak_cache.insert(key, Arc::new(value));
22        }
23        Self { cache: leak_cache }
24    }
25
26    pub async fn call(
27        &self,
28        link: Arc<Vec<Arc<Box<dyn FusenFilter>>>>,
29        context: FusenContext,
30    ) -> Result<FusenContext, FusenError> {
31        let service = self
32            .cache
33            .get(context.method_info.service_desc.get_tag())
34            .cloned();
35        match service {
36            Some(service) => {
37                let join_point = ProceedingJoinPoint::new(link, service, context);
38                join_point.proceed().await
39            }
40            None => Err(FusenError::Impossible),
41        }
42    }
43}