ton_liteapi/layers/
mod.rs

1use std::task::{Context, Poll};
2
3use futures::future::{self, BoxFuture};
4use tower::{Layer, Service};
5
6use crate::tl::common::Int256;
7use crate::tl::request::LiteQuery;
8use crate::tl::response::Error;
9use crate::types::LiteService;
10use crate::{tl::{adnl::Message, request::WrappedRequest, response::Response}, types::LiteError};
11
12pub struct WrapMessagesLayer;
13
14impl<S> Layer<S> for WrapMessagesLayer {
15    type Service = WrapService<S>;
16
17    fn layer(&self, service: S) -> Self::Service {
18        WrapService {
19            service
20        }
21    }
22}
23
24pub struct WrapService<S> {
25    service: S,
26}
27
28impl<S> Service<WrappedRequest> for WrapService<S>
29where
30    S: Service<Message>,
31    S::Error: Into<LiteError>,
32    S::Response: Into<Message>,
33    S::Future: Send + 'static,
34{
35    type Response = Response;
36    type Error = LiteError;
37    type Future = BoxFuture<'static, Result<Response, LiteError>>;
38
39    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
40        self.service.poll_ready(cx).map_err(Into::into)
41    }
42
43    fn call(&mut self, request: WrappedRequest) -> Self::Future {
44        let fut = self.service.call(Message::Query {
45            query_id: Int256::default(), 
46            query: LiteQuery {
47                wrapped_request: request,
48            }
49        });
50        Box::pin(async move {
51            let response = fut.await.map_err(Into::into)?.into();
52
53            match response {
54                Message::Answer { answer, .. } => Ok(answer),
55                _ => Err(LiteError::UnexpectedMessage)
56            }
57        })
58    }
59}
60
61pub struct UnwrapMessagesLayer;
62
63impl<S> Layer<S> for UnwrapMessagesLayer {
64    type Service = UnwrapService<S>;
65
66    fn layer(&self, service: S) -> Self::Service {
67        UnwrapService {
68            service
69        }
70    }
71}
72
73pub struct UnwrapService<S> {
74    service: S,
75}
76
77impl<S> Service<Message> for UnwrapService<S>
78where
79    S: LiteService,
80    S::Future: Send + 'static,
81{
82    type Response = Message;
83    type Error = LiteError;
84    type Future = BoxFuture<'static, Result<Message, LiteError>>;
85
86    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
87        self.service.poll_ready(cx).map_err(Into::into)
88    }
89
90    fn call(&mut self, request: Message) -> Self::Future {
91        let (query_id, request) = match request {
92            Message::Query { query_id, query: LiteQuery { wrapped_request } } => (query_id, wrapped_request),
93            Message::Ping { random_id } => return Box::pin(future::ok(Message::Pong { random_id })),
94            _ => return Box::pin(future::err(LiteError::UnexpectedMessage))
95        };
96        let fut = self.service.call(request);
97        Box::pin(async move {
98            let answer = fut.await.map_err(Into::<LiteError>::into)?.into();
99            Ok(Message::Answer { query_id, answer })
100        })
101    }
102}
103
104pub struct WrapErrorLayer;
105
106impl<S> Layer<S> for WrapErrorLayer {
107    type Service = WrapErrorService<S>;
108
109    fn layer(&self, service: S) -> Self::Service {
110        WrapErrorService {
111            service
112        }
113    }
114}
115
116pub struct WrapErrorService<S> {
117    service: S,
118}
119
120impl<S> Service<WrappedRequest> for WrapErrorService<S>
121where
122    S: Service<WrappedRequest>,
123    S::Error: Into<LiteError>,
124    S::Response: Into<Response>,
125    S::Future: Send + 'static,
126{
127    type Response = Response;
128    type Error = LiteError;
129    type Future = BoxFuture<'static, Result<Response, LiteError>>;
130
131    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
132        self.service.poll_ready(cx).map_err(Into::into)
133    }
134
135    fn call(&mut self, request: WrappedRequest) -> Self::Future {
136        let fut = self.service.call(request);
137        Box::pin(async move {
138            let response = fut.await;
139            match response {
140                Ok(x) => Ok(x.into()),
141                Err(e) => Ok(Response::Error(Error {
142                    code: 500,
143                    message: format!("{:?}", e.into()).as_str().into(),
144                }))
145            }
146        })
147    }
148}
149
150pub struct UnwrapErrorService<S> {
151    service: S,
152}
153
154impl<S> UnwrapErrorService<S> {
155    pub fn new(service: S) -> Self {
156        Self { service }
157    }
158}
159
160impl<S> Service<WrappedRequest> for UnwrapErrorService<S>
161where
162    S: Service<WrappedRequest, Response = Response, Error = LiteError>,
163    S::Future: Send + 'static,
164{
165    type Response = Response;
166    type Error = LiteError;
167    type Future = BoxFuture<'static, Result<Response, LiteError>>;
168
169    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
170        self.service.poll_ready(cx)
171    }
172
173    fn call(&mut self, request: WrappedRequest) -> Self::Future {
174        let fut = self.service.call(request);
175        Box::pin(async move {
176            match fut.await {
177                Ok(Response::Error(error)) => Err(LiteError::from(error)),
178                Ok(response) => Ok(response),
179                Err(e) => Err(e),
180            }
181        })
182    }
183}
184
185// Implement From<Error> for LiteError
186impl From<Error> for LiteError {
187    fn from(error: Error) -> Self {
188        LiteError::ServerError(error)
189    }
190}
191
192pub struct UnwrapErrorLayer;
193
194impl<S> Layer<S> for UnwrapErrorLayer {
195    type Service = UnwrapErrorService<S>;
196
197    fn layer(&self, service: S) -> Self::Service {
198        UnwrapErrorService {
199            service
200        }
201    }
202}