rmcp/service/
tower.rs

1use std::{future::poll_fn, marker::PhantomData};
2
3use tower_service::Service as TowerService;
4
5use super::NotificationContext;
6use crate::service::{RequestContext, Service, ServiceRole};
7
8pub struct TowerHandler<S, R: ServiceRole> {
9    pub service: S,
10    pub info: R::Info,
11    role: PhantomData<R>,
12}
13
14impl<S, R: ServiceRole> TowerHandler<S, R> {
15    pub fn new(service: S, info: R::Info) -> Self {
16        Self {
17            service,
18            role: PhantomData,
19            info,
20        }
21    }
22}
23
24impl<S, R: ServiceRole> Service<R> for TowerHandler<S, R>
25where
26    S: TowerService<R::PeerReq, Response = R::Resp> + Sync + Send + Clone + 'static,
27    S::Error: Into<crate::ErrorData>,
28    S::Future: Send,
29{
30    async fn handle_request(
31        &self,
32        request: R::PeerReq,
33        _context: RequestContext<R>,
34    ) -> Result<R::Resp, crate::ErrorData> {
35        let mut service = self.service.clone();
36        poll_fn(|cx| service.poll_ready(cx))
37            .await
38            .map_err(Into::into)?;
39        let resp = service.call(request).await.map_err(Into::into)?;
40        Ok(resp)
41    }
42
43    fn handle_notification(
44        &self,
45        _notification: R::PeerNot,
46        _context: NotificationContext<R>,
47    ) -> impl Future<Output = Result<(), crate::ErrorData>> + Send + '_ {
48        std::future::ready(Ok(()))
49    }
50
51    fn get_info(&self) -> R::Info {
52        self.info.clone()
53    }
54}