cyfs_lib/router_handler/
handler.rs

1use super::action::*;
2use super::category::*;
3use super::chain::*;
4use super::request::*;
5use super::ws::*;
6use crate::acl::*;
7use crate::crypto::*;
8use crate::ndn::*;
9use crate::non::*;
10use crate::stack::*;
11use cyfs_base::*;
12use cyfs_util::*;
13
14use async_trait::async_trait;
15use http_types::Url;
16use std::fmt;
17use std::sync::atomic::{AtomicBool, Ordering};
18use std::sync::Arc;
19
20#[async_trait]
21pub(crate) trait RouterHandlerAnyRoutine: Send + Sync {
22    async fn emit(&self, param: String) -> BuckyResult<String>;
23}
24
25pub(crate) struct RouterHandlerRoutineT<REQ, RESP>(
26    pub  Box<
27        dyn EventListenerAsyncRoutine<
28            RouterHandlerRequest<REQ, RESP>,
29            RouterHandlerResponse<REQ, RESP>,
30        >,
31    >,
32)
33where
34    REQ: Send + Sync + 'static + JsonCodec<REQ> + fmt::Display,
35    RESP: Send + Sync + 'static + JsonCodec<RESP> + fmt::Display;
36
37#[async_trait]
38impl<REQ, RESP> RouterHandlerAnyRoutine for RouterHandlerRoutineT<REQ, RESP>
39where
40    REQ: Send + Sync + 'static + JsonCodec<REQ> + fmt::Display,
41    RESP: Send + Sync + 'static + JsonCodec<RESP> + fmt::Display,
42{
43    async fn emit(&self, param: String) -> BuckyResult<String> {
44        let param = RouterHandlerRequest::<REQ, RESP>::decode_string(&param)?;
45        self.0
46            .call(&param)
47            .await
48            .map(|resp| JsonCodec::encode_string(&resp))
49    }
50}
51
52#[derive(Clone)]
53pub struct RouterHandlerManager {
54    dec_id: Option<SharedObjectStackDecID>,
55
56    inner: RouterWSHandlerManager,
57    started: Arc<AtomicBool>,
58}
59
60impl RouterHandlerManager {
61    pub fn new(dec_id: Option<SharedObjectStackDecID>, ws_url: Url) -> Self {
62        let inner = RouterWSHandlerManager::new(ws_url);
63
64        Self {
65            dec_id,
66            inner,
67            started: Arc::new(AtomicBool::new(false)),
68        }
69    }
70
71    fn get_dec_id(&self) -> Option<ObjectId> {
72        self.dec_id.as_ref().map(|v| v.get().cloned()).flatten()
73    }
74
75    pub fn clone_processor(&self) -> RouterHandlerManagerProcessorRef {
76        Arc::new(Box::new(self.clone()))
77    }
78
79    fn try_start(&self) {
80        match self
81            .started
82            .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
83        {
84            Ok(_) => {
85                info!("will start router handler manager!");
86                self.inner.start()
87            }
88            Err(_) => {}
89        }
90    }
91
92    pub fn add_handler<REQ, RESP>(
93        &self,
94        chain: RouterHandlerChain,
95        id: &str,
96        index: i32,
97        filter: Option<String>,
98        req_path: Option<String>,
99        default_action: RouterHandlerAction,
100        routine: Option<
101            Box<
102                dyn EventListenerAsyncRoutine<
103                    RouterHandlerRequest<REQ, RESP>,
104                    RouterHandlerResponse<REQ, RESP>,
105                >,
106            >,
107        >,
108    ) -> BuckyResult<()>
109    where
110        REQ: Send + Sync + 'static + JsonCodec<REQ> + fmt::Display,
111        RESP: Send + Sync + 'static + JsonCodec<RESP> + fmt::Display,
112        RouterHandlerRequest<REQ, RESP>: RouterHandlerCategoryInfo,
113    {
114        info!("will add handler: chain={}, id={}, index={}, filter={:?}, req_path={:?}, default_action={}",
115            chain, id, index, filter, req_path, default_action);
116
117        self.try_start();
118
119        self.inner.add_handler(
120            chain,
121            id,
122            self.get_dec_id(),
123            index,
124            filter,
125            req_path,
126            default_action,
127            routine,
128        )
129    }
130
131    pub async fn remove_handler(
132        &self,
133        chain: RouterHandlerChain,
134        category: RouterHandlerCategory,
135        id: &str,
136    ) -> BuckyResult<bool> {
137        info!(
138            "will remove handler: chain={}, category={}, id={}",
139            chain, id, category
140        );
141
142        self.try_start();
143
144        self.inner
145            .remove_handler(chain, category, id, self.get_dec_id())
146            .await
147    }
148
149    pub async fn stop(&self) {
150        self.inner.stop().await
151    }
152}
153
154use super::processor::*;
155
156#[async_trait::async_trait]
157impl<REQ, RESP> RouterHandlerProcessor<REQ, RESP> for RouterHandlerManager
158where
159    REQ: Send + Sync + 'static + JsonCodec<REQ> + fmt::Display,
160    RESP: Send + Sync + 'static + JsonCodec<RESP> + fmt::Display,
161    RouterHandlerRequest<REQ, RESP>: RouterHandlerCategoryInfo,
162{
163    async fn add_handler(
164        &self,
165        chain: RouterHandlerChain,
166        id: &str,
167        index: i32,
168        filter: Option<String>,
169        req_path: Option<String>,
170        default_action: RouterHandlerAction,
171        routine: Option<
172            Box<
173                dyn EventListenerAsyncRoutine<
174                    RouterHandlerRequest<REQ, RESP>,
175                    RouterHandlerResponse<REQ, RESP>,
176                >,
177            >,
178        >,
179    ) -> BuckyResult<()> {
180        Self::add_handler(
181            &self,
182            chain,
183            id,
184            index,
185            filter,
186            req_path,
187            default_action,
188            routine,
189        )
190    }
191
192    async fn remove_handler(&self, chain: RouterHandlerChain, id: &str) -> BuckyResult<bool> {
193        let category = extract_router_handler_category::<RouterHandlerRequest<REQ, RESP>>();
194        Self::remove_handler(&self, chain, category, id).await
195    }
196}
197
198impl RouterHandlerManagerProcessor for RouterHandlerManager {
199    fn get_object(
200        &self,
201    ) -> &dyn RouterHandlerProcessor<NONGetObjectInputRequest, NONGetObjectInputResponse> {
202        self
203    }
204
205    fn put_object(
206        &self,
207    ) -> &dyn RouterHandlerProcessor<NONPutObjectInputRequest, NONPutObjectInputResponse> {
208        self
209    }
210
211    fn post_object(
212        &self,
213    ) -> &dyn RouterHandlerProcessor<NONPostObjectInputRequest, NONPostObjectInputResponse> {
214        self
215    }
216
217    fn select_object(
218        &self,
219    ) -> &dyn RouterHandlerProcessor<NONSelectObjectInputRequest, NONSelectObjectInputResponse>
220    {
221        self
222    }
223
224    fn delete_object(
225        &self,
226    ) -> &dyn RouterHandlerProcessor<NONDeleteObjectInputRequest, NONDeleteObjectInputResponse>
227    {
228        self
229    }
230
231    fn get_data(
232        &self,
233    ) -> &dyn RouterHandlerProcessor<NDNGetDataInputRequest, NDNGetDataInputResponse> {
234        self
235    }
236    fn put_data(
237        &self,
238    ) -> &dyn RouterHandlerProcessor<NDNPutDataInputRequest, NDNPutDataInputResponse> {
239        self
240    }
241    fn delete_data(
242        &self,
243    ) -> &dyn RouterHandlerProcessor<NDNDeleteDataInputRequest, NDNDeleteDataInputResponse> {
244        self
245    }
246
247    fn sign_object(
248        &self,
249    ) -> &dyn RouterHandlerProcessor<CryptoSignObjectInputRequest, CryptoSignObjectInputResponse>
250    {
251        self
252    }
253    fn verify_object(
254        &self,
255    ) -> &dyn RouterHandlerProcessor<CryptoVerifyObjectInputRequest, CryptoVerifyObjectInputResponse>
256    {
257        self
258    }
259
260    fn encrypt_data(
261        &self,
262    ) -> &dyn RouterHandlerProcessor<CryptoEncryptDataInputRequest, CryptoEncryptDataInputResponse>
263    {
264        self
265    }
266    fn decrypt_data(
267        &self,
268    ) -> &dyn RouterHandlerProcessor<CryptoDecryptDataInputRequest, CryptoDecryptDataInputResponse>
269    {
270        self
271    }
272
273    fn acl(&self) -> &dyn RouterHandlerProcessor<AclHandlerRequest, AclHandlerResponse> {
274        self
275    }
276
277    fn interest(
278        &self,
279    ) -> &dyn RouterHandlerProcessor<InterestHandlerRequest, InterestHandlerResponse> {
280        self
281    }
282}