channel-server 0.1.0

crate request/response topic-publish/subject by channels in multithreads
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
use add_data::{AddData, AddDataEndpoint};
use ahash::AHashMap;
use bytes::Bytes;
use crossbeam::channel::{bounded, Receiver, Sender};
use extensions::Extensions;
use serde::Serialize;
use std::{
    collections::HashMap,
    fmt::{Debug, Formatter},
    ops::Deref,
    sync::{Arc, RwLock},
};

pub mod add_data;
pub mod common;
pub mod extensions;
pub mod request;
pub mod response;

pub mod prelude;

pub use channel_server_derive::handler;

#[derive(Default, Clone)]
pub struct Body(Option<Bytes>);

#[derive(Clone)]
pub struct Param(Option<String>);

impl Body {
    pub fn empty() -> Body {
        Self(None)
    }

    pub fn take(&mut self) -> Result<Bytes, ChannelError> {
        self.0.take().ok_or(ChannelError::BodyNoData)
    }

    pub fn from_string(body: String) -> Body {
        Self(Some(body.into()))
    }

    pub fn from_bytes(body: Bytes) -> Body {
        Self(Some(body))
    }
}

impl Param {
    pub fn empty() -> Self {
        Self(None)
    }

    pub fn from_obj(obj: impl Serialize) -> Self {
        Self(Some(serde_json::to_string(&obj).unwrap()))
    }

    pub fn as_ref(&self) -> Result<&String, ChannelError> {
        if let Some(param) = self.0.as_ref() {
            Ok(param)
        } else {
            Err(ChannelError::ParamNoData)
        }
    }
}

impl Deref for Body {
    type Target = Option<Bytes>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

pub struct Request {
    uri: String,
    /// 用于传递参数, json序列化字符串
    param: Param,
    /// 用于传递大数据
    body: Body,
    /// 主要是 Middleware 使用的
    extensions: Extensions,
}

impl Request {
    pub fn new(uri: impl Into<String>, param: Param, body: Body) -> Request {
        Self {
            uri: uri.into(),
            param,
            body,
            extensions: Extensions::new(),
        }
    }

    pub fn with_param(uri: String, param: Param) -> Request {
        Self::new(uri, param, Body::empty())
    }

    pub fn with_body(uri: String, body: Body) -> Request {
        Self::new(uri, Param::empty(), body)
    }

    /// Returns the parameters used by the extractor.
    pub fn split(mut self) -> (Request, Body) {
        let body = std::mem::take(&mut self.body);
        (self, body)
    }

    #[inline]
    pub fn uri_ref(&self) -> &str {
        &self.uri
    }

    /// Returns a reference to the associated extensions.
    #[inline]
    pub fn extensions(&self) -> &Extensions {
        &self.extensions
    }

    #[inline]
    pub fn param(&self) -> &Param {
        &self.param
    }

    /// Returns a mutable reference to the associated extensions.
    #[inline]
    pub fn extensions_mut(&mut self) -> &mut Extensions {
        &mut self.extensions
    }
}

impl Debug for Request {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Request").field("uri", &self.uri).finish()
    }
}

#[derive(Debug, Clone)]
pub enum StatusCode {
    /// 执行成功
    Ok(String),
    /// 执行失败
    Fail(String),
    /// 准备就绪
    Ready(String),
    /// 执行中
    Pending(String),
    /// 还未开始
    NotStart(String),
}

impl Default for StatusCode {
    fn default() -> Self {
        Self::ready()
    }
}

impl StatusCode {
    pub fn ok() -> Self {
        Self::Ok("执行成功".into())
    }
    pub fn fail() -> Self {
        Self::Fail("执行失败".into())
    }
    pub fn pending() -> Self {
        Self::Pending("正在执行".into())
    }
    pub fn ready() -> Self {
        Self::Ready("准备就绪".into())
    }

    pub fn not_start() -> Self {
        Self::NotStart("未执行".into())
    }

    pub fn is_ok(&self) -> bool {
        matches!(self, StatusCode::Ok(_))
    }
}

#[derive(Default, Clone)]
pub struct Response {
    uri: String,
    status: StatusCode,
    body: Body,
}

impl Response {
    pub fn new() -> Self {
        Self {
            uri: String::new(),
            status: StatusCode::ready(),
            body: Body(None),
        }
    }

    pub fn topic(uri: &str) -> Self {
        Self {
            uri: uri.into(),
            status: StatusCode::ok(),
            body: Body(None),
        }
    }

    pub fn body(mut self, body: Bytes) -> Self {
        self.body = Body(Some(body));
        self
    }

    pub fn status(mut self, status: StatusCode) -> Self {
        self.status = status;
        self
    }

    pub fn status_ref(&self) -> &StatusCode {
        &self.status
    }

    pub fn uri(mut self, uri: String) -> Response {
        self.uri = uri;
        self
    }

    pub fn uri_ref(&self) -> &str {
        &self.uri
    }

    pub fn is_ok(&self) -> bool {
        self.status.is_ok()
    }

    #[inline]
    pub fn take_body(&mut self) -> Body {
        std::mem::take(&mut self.body)
    }
}

impl Debug for Response {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let len = if let Some(body) = self.body.as_ref() {
            body.len()
        } else {
            0
        };
        f.debug_struct("Response")
            .field("uri", &self.uri)
            .field("status", &self.status)
            .field("body length", &len)
            .finish()
    }
}

pub trait IntoResponse: Send {
    fn into_response(self) -> Response;
}

pub trait Endpoint: Send + Sync {
    /// Represents the response of the endpoint.
    type Output: IntoResponse;

    /// Get the response to the request.
    fn call(&self, req: Request) -> Result<Self::Output, ChannelError>;

    fn get_response(&self, req: Request) -> Response {
        let uri = req.uri_ref().to_string();
        let res = self
            .call(req)
            .map(IntoResponse::into_response)
            .unwrap_or_else(|err| err.into_response());
        res.uri(uri)
    }
}

#[derive(Debug, thiserror::Error)]
pub enum ChannelError {
    #[error("请求已经在队列中")]
    ReqExistInQueue,
    #[error("请求发送失败")]
    ReqSendError,

    /// Io error.
    #[error("io: {0}")]
    Io(#[from] std::io::Error),

    #[error("解析json异常")]
    ParseJsonError,

    /// Body has been taken by other extractors.
    #[error("the request body has no data")]
    BodyNoData,

    #[error("the request param has no data")]
    ParamNoData,

    /// Body is not a valid utf8 string.
    #[error("parse utf8: {0}")]
    NotUtf8(#[from] std::string::FromUtf8Error),

    #[error("路径未找到: {0}")]
    PathNotFoundError(String),

    /// 获取Data异常.
    #[error("Get data 异常: {0}")]
    GetDataError(String),

    #[error("异常: {0}")]
    Custom(String),
}

impl IntoResponse for ChannelError {
    fn into_response(self) -> Response {
        Response::new().status(StatusCode::Fail(self.to_string()))
    }
}

pub trait FromRequest<'a>: Sized {
    fn from_request(req: &'a Request, body: &mut Body) -> Result<Self, ChannelError>;
    fn from_request_without_body(req: &'a Request) -> Result<Self, ChannelError> {
        Self::from_request(req, &mut Default::default())
    }
}

pub type BoxEndpoint<'a, T = Response> = Box<dyn Endpoint<Output = T> + 'a>;

pub trait EndpointExt: IntoEndpoint {
    fn boxed<'a>(self) -> BoxEndpoint<'a, <Self::Endpoint as Endpoint>::Output>
    where
        Self: Sized + 'a,
    {
        Box::new(self.into_endpoint())
    }

    fn data<T>(self, data: T) -> AddDataEndpoint<Self::Endpoint, T>
    where
        T: Clone + Send + Sync + 'static,
        Self: Sized,
    {
        self.with(AddData::new(data))
    }

    fn with<T>(self, middleware: T) -> T::Output
    where
        T: Middleware<Self::Endpoint>,
        Self: Sized,
    {
        middleware.transform(self.into_endpoint())
    }
}

impl<T: IntoEndpoint> EndpointExt for T {}

pub trait IntoEndpoint {
    type Endpoint: Endpoint;
    fn into_endpoint(self) -> Self::Endpoint;
}

impl<T: Endpoint> IntoEndpoint for T {
    type Endpoint = T;

    fn into_endpoint(self) -> Self::Endpoint {
        self
    }
}

pub trait Middleware<E: Endpoint> {
    type Output: Endpoint;

    /// Transform the input [`Endpoint`] to another one.
    fn transform(&self, ep: E) -> Self::Output;
}

// #[handler]
// fn hello(name: String) -> String {
//     format!("hello: {}", name)
// }

#[derive(Clone)]
pub struct Route {
    map: Arc<RwLock<AHashMap<&'static str, BoxEndpoint<'static>>>>,
}

impl Route {
    pub fn new() -> Self {
        Self {
            map: Arc::default(),
        }
    }
}

impl Endpoint for Route {
    type Output = Response;

    fn call(&self, req: Request) -> Result<Self::Output, ChannelError> {
        let map = self.map.read().unwrap();
        if map.contains_key(req.uri_ref()) {
            let ep = &map[req.uri_ref()];
            ep.call(req)
        } else {
            Err(ChannelError::PathNotFoundError(req.uri_ref().into()))
        }
    }
}

impl Route {
    #[must_use]
    pub fn at(self, path: &'static str, ep: impl Endpoint<Output = Response> + 'static) -> Self {
        {
            let mut map = self.map.write().unwrap();
            if map.contains_key(path) {
                panic!("duplicate path: {}", path);
            }
            map.insert(path, ep.boxed());
        }
        self
    }
}

struct ChannelServer {
    res_rx: Receiver<Request>,
    req_tx: Sender<Response>,
}

impl ChannelServer {
    pub(crate) fn new(req_rx: Receiver<Request>, res_tx: Sender<Response>) -> ChannelServer {
        Self {
            res_rx: req_rx,
            req_tx: res_tx,
        }
    }

    pub fn run(self, ep: impl Endpoint + 'static + Clone) {
        std::thread::spawn(move || {
            while let Ok(req) = self.res_rx.recv() {
                let ep = ep.clone();
                let req_tx = self.req_tx.clone();
                std::thread::spawn(move || {
                    let res = ep.get_response(req);
                    req_tx.try_send(res).ok();
                });
            }
        });
    }
}

pub struct ChannelClient {
    req_tx: Sender<Request>,
    res_rx: Receiver<Response>,
    res_queue: Vec<Response>,
    topic_rx: Receiver<Response>,
    topic_queue: HashMap<&'static str, Vec<Response>>,
}

#[derive(Clone)]
pub struct ChannelTopic {
    topic_tx: Sender<Response>,
}

impl ChannelTopic {
    pub fn new(topic_tx: Sender<Response>) -> Self {
        Self { topic_tx }
    }
    pub fn publish(&self, res: Response) {
        // 发送成功还是失败并不重要
        self.topic_tx.send(res).ok();
    }
}

impl ChannelClient {
    pub fn req_with_param(
        &mut self,
        uri: impl Into<String>,
        param: Param,
    ) -> Result<(), ChannelError> {
        let req = Request::new(uri.into(), param, Body::empty());
        self.req(req)
    }

    pub fn req_with_body(
        &mut self,
        uri: impl Into<String>,
        body: Body,
    ) -> Result<(), ChannelError> {
        let req = Request::new(uri.into(), Param::empty(), body);
        self.req(req)
    }

    pub fn req_with_param_body(
        &mut self,
        uri: impl Into<String>,
        param: Param,
        body: Body,
    ) -> Result<(), ChannelError> {
        let req = Request::new(uri.into(), param, body);
        self.req(req)
    }

    /// 发起请求
    pub fn req(&mut self, req: Request) -> Result<(), ChannelError> {
        // 先检查队列中是否有这个请求
        let item = self
            .res_queue
            .iter()
            .find(|res| res.uri_ref() == req.uri_ref());
        if item.is_some() {
            return Err(ChannelError::ReqExistInQueue);
        }

        // 添加 请求状态
        self.res_queue
            .push(Response::new().uri(req.uri_ref().into()));

        // 发送请求
        self.req_tx
            .send(req)
            .map_err(|_e| ChannelError::ReqSendError)
    }

    /// 处理消息队列
    /// 返回值为 true 表示 接收到 响应
    pub fn run_once(&mut self) -> bool {
        let mut recved = false;
        while let Ok(res) = self.res_rx.try_recv() {
            let item = self
                .res_queue
                .iter_mut()
                .find(|r| r.uri_ref() == res.uri_ref());
            if let Some(r) = item {
                *r = res;
                recved = true;
            }
        }
        while let Ok(res) = self.topic_rx.try_recv() {
            // 只有明确订阅的数据才会被添加到队列中
            if let Some(queue) = self.topic_queue.get_mut(res.uri_ref()) {
                queue.push(res);
                recved = true;
            }
        }
        recved
    }

    /// 根据 uri 获得请求结果
    pub fn fetch(&self, uri: &str) -> Option<&Response> {
        self.res_queue.iter().find(|res| res.uri_ref() == uri)
    }

    /// 清除 response
    pub fn clean(&mut self, uri: &str) {
        self.res_queue.retain(|res| res.uri_ref() != uri);
    }

    pub fn subject(&mut self, uri: &'static str) {
        self.topic_queue.insert(uri, Vec::new());
    }

    pub fn fetch_topic(&mut self, uri: &'static str) -> Option<Vec<Response>> {
        if self.topic_queue.contains_key(uri) {
            self.topic_queue.insert(uri, Vec::new())
        } else {
            None
        }
    }

    pub(crate) fn new(
        req_tx: Sender<Request>,
        res_rx: Receiver<Response>,
        topic_rx: Receiver<Response>,
    ) -> ChannelClient {
        Self {
            req_tx,
            res_rx,
            topic_rx,
            res_queue: Vec::new(),
            topic_queue: HashMap::new(),
        }
    }
}

pub struct ChannelService {}

impl ChannelService {
    pub fn start(ep: impl Endpoint + 'static + Clone) -> (ChannelClient, ChannelTopic) {
        let (req_tx, req_rx) = bounded::<Request>(100);
        let (res_tx, res_rx) = bounded::<Response>(100);
        let (topic_tx, topic_rx) = bounded::<Response>(100);
        let client = ChannelClient::new(req_tx, res_rx, topic_rx);
        let server = ChannelServer::new(req_rx, res_tx);
        let topic = ChannelTopic::new(topic_tx);
        server.run(ep);
        (client, topic)
    }
}