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
use std::sync::Arc;
use std::net::SocketAddr;
use std::result::Result as GenResult;
use std::io::{Error, ErrorKind, Result};
use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering};

use futures::future::{FutureExt, LocalBoxFuture};
use futures::StreamExt;
use log::warn;

use pi_atom::Atom;
use pi_gray::GrayVersion;
use pi_handler::{Args, Handler};

use tcp::{Socket,
          utils::{ContextHandle, SocketContext, Hibernate, Ready}};
use mqtt::server::MqttBrokerProtocol;
use mqtt::broker::{MQTT_RESPONSE_SYS_TOPIC, MqttBrokerListener, MqttBrokerService};
use mqtt::session::{MqttSession, MqttConnect};
use mqtt::utils::BrokerSession;

///
/// Mqtt事件
///
pub enum MqttEvent {
    Connect(usize, String, String, u16, bool, Option<String>, Option<String>),  //建立连接
    Disconnect(usize, String, String, Result<()>),                              //关闭连接
    Sub(usize, String, String, Vec<(String, u8)>),                              //订阅主题
    Unsub(usize, String, String, Vec<String>),                                  //退订主题
    Publish(usize, String, String, Option<SocketAddr>, String, Arc<Vec<u8>>),   //发布主题
}

///
/// Mqtt连接句柄
///
pub struct MqttConnectHandle<S: Socket> {
    gray:       AtomicIsize,                //灰度,负数代表无灰度
    client_id:  String,                     //Mqtt客户端id
    protocol:   MqttBrokerProtocol,         //Mqtt代理
    connect:    Arc<dyn MqttConnect<S>>,    //Mqtt连接
    is_closed:  AtomicBool,                 //Mqtt连接是否已关闭
}

unsafe impl<S: Socket> Send for MqttConnectHandle<S> {}
unsafe impl<S: Socket> Sync for MqttConnectHandle<S> {}

impl<S: Socket> GrayVersion for MqttConnectHandle<S> {
    fn get_gray(&self) -> &Option<usize> {
        let gray = self.gray.load(Ordering::Relaxed);
        if gray < 0 {
            return &None;
        }

        &None //TODO 修改GrayVersion后再实现...
    }

    fn set_gray(&mut self, gray: Option<usize>) {
        if let Some(n) = gray {
            self.gray.store(n as isize, Ordering::SeqCst);
        } else {
            self.gray.store(-1, Ordering::SeqCst);
        }
    }

    // 获取连接唯一id
    fn get_id(&self) -> usize {
        if let Some(uid) = self.connect.get_uid() {
            return uid;
        }

        0
    }
}

impl<S: Socket> MqttConnectHandle<S> {
    /// 获取连接的连接令牌
    pub fn get_token(&self) -> Option<usize> {
        self.connect.get_token()
    }

    /// 获取连接的唯一id
    pub fn get_uid(&self) -> Option<usize> {
        self.connect.get_uid()
    }

    /// 获取连接的本地地址
    pub fn get_local_addr(&self) -> Option<SocketAddr> {
        if self.is_closed.load(Ordering::Relaxed) {
            return None;
        }

        self.connect.get_local_addr()
    }

    /// 获取连接的本地ip
    pub fn get_local_ip(&self) -> Option<String> {
        if self.is_closed.load(Ordering::Relaxed) {
            return None;
        }

        if let Some(addr) = self.get_local_addr() {
            return Some(addr.ip().to_string());
        }

        None
    }

    /// 获取连接的本地端口
    pub fn get_local_port(&self) -> Option<u16> {
        if self.is_closed.load(Ordering::Relaxed) {
            return None;
        }

        if let Some(addr) = self.get_local_addr() {
            return Some(addr.port());
        }

        None
    }

    /// 获取连接的对端地址
    pub fn get_remote_addr(&self) -> Option<SocketAddr> {
        if self.is_closed.load(Ordering::Relaxed) {
            return None;
        }

        self.connect.get_remote_addr()
    }

    /// 获取连接的对端ip
    pub fn get_remote_ip(&self) -> Option<String> {
        if self.is_closed.load(Ordering::Relaxed) {
            return None;
        }

        if let Some(addr) = self.get_remote_addr() {
            return Some(addr.ip().to_string());
        }

        None
    }

    /// 获取连接的对端端口
    pub fn get_remote_port(&self) -> Option<u16> {
        if self.is_closed.load(Ordering::Relaxed) {
            return None;
        }

        if let Some(addr) = self.get_remote_addr() {
            return Some(addr.port());
        }

        None
    }

    /// 判断是否是安全的Mqtt连接
    pub fn is_security(&self) -> bool {
        self.connect.is_security()
    }

    /// 判断是否是被动接收消息
    pub fn is_passive(&self) -> bool {
        self.connect.is_passive_receive()
    }

    /// 设置是否被动接收消息
    pub fn set_passive(&self, b: bool) {
        self.connect.passive_receive(b);
    }

    /// 休眠当前连接,直到被唤醒,返回空表示连接已关闭
    pub fn hibernate(&self, ready: Ready) -> Option<Hibernate<S>> {
        self.connect.hibernate(ready)
    }

    /// 唤醒连接
    pub fn wakeup(&self, result: Result<()>) -> bool {
        self.connect.wakeup(result)
    }

    /// 为当前的Mqtt客户端订阅指定的主题
    pub fn sub(&self, topic: String) {
        if self.is_security() {
            //安全的会话
            if let MqttBrokerProtocol::WssMqtt311(broker) = &self.protocol {
                if let Some(session) = broker.get_broker().get_session(&self.client_id) {
                    //客户端的会话存在,则订阅主题
                    let _ = broker.get_broker().subscribe(session.clone(), topic);
                }
            }
        } else {
            //非安全的会主知
            if let MqttBrokerProtocol::WsMqtt311(broker) = &self.protocol {
                if let Some(session) = broker.get_broker().get_session(&self.client_id) {
                    //客户端的会话存在,则订阅主题
                    let _ = broker.get_broker().subscribe(session.clone(), topic);
                }
            }
        }
    }

    /// 为当前的Mqtt客户端退订指定的主题
    pub fn unsub(&self, topic: String) {
        if self.is_security() {
            //安全的会话
            if let MqttBrokerProtocol::WssMqtt311(broker) = &self.protocol {
                if let Some(session) = broker.get_broker().get_session(&self.client_id) {
                    //客户端的会话存在,则退订主题
                    let _ = broker.get_broker().unsubscribe(&session, topic);
                }
            }
        } else {
            //非安全的会主知
            if let MqttBrokerProtocol::WsMqtt311(broker) = &self.protocol {
                if let Some(session) = broker.get_broker().get_session(&self.client_id) {
                    //客户端的会话存在,则退订主题
                    let _ = broker.get_broker().unsubscribe(&session, topic);
                }
            }
        }
    }

    /// 获取连接会话上下文的只读引用
    pub fn get_session(&self) -> Option<ContextHandle<BrokerSession>> {
        if self.is_closed.load(Ordering::Relaxed) {
            return None;
        }

        self.connect.get_session()
    }

    /// 发送指定主题的数据
    pub fn send(&self, topic: &String, bin: Vec<u8>) {
        self.connect.send(topic, Arc::new(bin));
    }

    /// 回应指定请求
    pub fn reply(&self, bin: Vec<u8>) {
        self.send(&MQTT_RESPONSE_SYS_TOPIC, bin);
        if self.is_passive() {
            //是被动接收消息
            while !self.wakeup(Ok(())) {

            }
        }
    }

    /// 关闭当前连接
    pub fn close(&self, reason: Result<()>) -> Result<()> {
        if self.is_closed.load(Ordering::Relaxed) {
            return Ok(());
        }

        self.connect.close(reason)
    }
}

///
/// Mqtt代理监听器
///
pub struct MqttProxyListener {
    connect_handler:    Option<Arc<dyn Handler<
                            A = MqttEvent,
                            B = (),
                            C = (),
                            D = (),
                            E = (),
                            F = (),
                            G = (),
                            H = (),
                            HandleResult = ()>
                        >>,                                                 //连接异步处理器
}

unsafe impl Send for MqttProxyListener {}

impl<S: Socket> MqttBrokerListener<S> for MqttProxyListener {
    fn connected(&self,
                 protocol: MqttBrokerProtocol,
                 connect: Arc<dyn MqttConnect<S>>) -> LocalBoxFuture<'static, Result<()>> {
        //Mqtt已连接
        if let Some(handler) = &self.connect_handler {
            let handler = handler.clone();

            async move {
                if let Some(mut handle) = connect.get_session() {
                    if let Some(session) = handle.as_mut() {
                        let connect_handle = MqttConnectHandle {
                            gray: AtomicIsize::new(-1),
                            client_id: session.get_client_id().clone(),
                            protocol,
                            connect,
                            is_closed: AtomicBool::new(false),
                        };

                        //异步处理Mqtt连接
                        let event = MqttEvent::Connect(connect_handle.get_id(),
                                                       connect_handle.protocol.get_broker_name().to_string(),
                                                       session.get_client_id().clone(),
                                                       session.get_keep_alive(),
                                                       session.is_clean_session(),
                                                       session.get_user().cloned(),
                                                       session.get_pwd().cloned());
                        handler.handle(Arc::new(connect_handle),
                                       Atom::from(""),
                                       Args::OneArgs(event)).await;

                    }
                }

                Ok(())
            }.boxed_local()
        } else {
            async move {
                Err(Error::new(ErrorKind::Other,
                               format!("Mqtt proxy connect failed, connect: {:?}, reason: handle connect error",
                                       connect)))
            }.boxed_local()
        }
    }

    fn closed(&self,
              protocol: MqttBrokerProtocol,
              connect: Arc<dyn MqttConnect<S>>,
              mut context: BrokerSession,
              reason: Result<()>) -> LocalBoxFuture<'static, ()> {
        //Mqtt连接已关闭
        if let Err(e) = &reason {
            warn!("Mqtt proxy connect close by error, token: {:?}, remote: {:?}, local: {:?}, reason: {:?}",
                connect.get_token(),
                connect.get_remote_addr(),
                connect.get_local_addr(),
                e);
        }

        if let Some(handler) = &self.connect_handler {
            let connect_handle = MqttConnectHandle {
                gray: AtomicIsize::new(-1),
                client_id: context.get_client_id().clone(),
                protocol,
                connect,
                is_closed: AtomicBool::new(true),
            };

            //异步处理Mqtt连接关闭
            let event = MqttEvent::Disconnect(connect_handle.get_id(),
                                              connect_handle.protocol.get_broker_name().to_string(),
                                              context.get_client_id().clone(),
                                              reason);
            return handler.handle(Arc::new(connect_handle),
                                  Atom::from(""),
                                  Args::OneArgs(event));
        }

        async move {}.boxed_local()
    }
}

impl MqttProxyListener {
    /// 构建Mqtt代理监听器
    pub fn new() -> Self {
        MqttProxyListener {
            connect_handler: None,
        }
    }

    /// 构建指定处理器的Mqtt代理监听器
    pub fn with_handler(connect_handler: Option<Arc<dyn Handler<
            A = MqttEvent,
            B = (),
            C = (),
            D = (),
            E = (),
            F = (),
            G = (),
            H = (),
            HandleResult = ()>>>) -> Self {
        MqttProxyListener {
            connect_handler,
        }
    }

    /// 设置Mqtt代理监听器的连接处理器
    pub fn set_connect_handler(&mut self,
                               handler: Option<Arc<dyn Handler<
                                A = MqttEvent,
                                B = (),
                                C = (),
                                D = (),
                                E = (),
                                F = (),
                                G = (),
                                H = (),
                                HandleResult = ()>>>) {
        self.connect_handler = handler;
    }
}

///
/// Mqtt代理服务
///
pub struct MqttProxyService {
    request_handler:    Option<Arc<dyn Handler<
                            A = MqttEvent,
                            B = (),
                            C = (),
                            D = (),
                            E = (),
                            F = (),
                            G = (),
                            H = (),
                            HandleResult = ()>
                        >>,                                                 //请求服务异步处理器
}

unsafe impl Send for MqttProxyService {}

impl<S: Socket> MqttBrokerService<S> for MqttProxyService {
    fn subscribe(&self,
                 protocol: MqttBrokerProtocol,
                 connect: Arc<dyn MqttConnect<S>>,
                 topics: Vec<(String, u8)>) -> LocalBoxFuture<'static, Result<()>> {
        //Mqtt订阅主题
        if let Some(handler) = &self.request_handler {
            let handler = handler.clone();

            async move {
                if let Some(mut handle) = connect.get_session() {
                    if let Some(session) = handle.as_mut() {
                        let connect_handle = MqttConnectHandle {
                            gray: AtomicIsize::new(-1),
                            client_id: session.get_client_id().clone(),
                            protocol,
                            connect,
                            is_closed: AtomicBool::new(false),
                        };

                        //异步处理Mqtt订阅主题
                        let event = MqttEvent::Sub(connect_handle.get_id(),
                                                   connect_handle.protocol.get_broker_name().to_string(),
                                                   session.get_client_id().clone(),
                                                   topics);
                        handler.handle(Arc::new(connect_handle),
                                       Atom::from(""), Args::
                                       OneArgs(event)).await;

                    }
                }

                Ok(())
            }.boxed_local()
        } else {
            async move {
                Err(Error::new(ErrorKind::Other,
                               format!("Mqtt proxy subscribe failed, connect: {:?}, reason: handle subscribe error",
                                       connect)))
            }.boxed_local()
        }
    }

    fn unsubscribe(&self,
                   protocol: MqttBrokerProtocol,
                   connect: Arc<dyn MqttConnect<S>>,
                   topics: Vec<String>) -> LocalBoxFuture<'static, Result<()>> {
        if let Some(mut handle) = connect.get_session() {
            if let Some(session) = handle.as_mut() {
                if let Some(handler) = &self.request_handler {
                    let connect_handle = MqttConnectHandle {
                        gray: AtomicIsize::new(-1),
                        client_id: session.get_client_id().clone(),
                        protocol,
                        connect,
                        is_closed: AtomicBool::new(false),
                    };

                    //异步处理Mqtt连接关闭
                    let event = MqttEvent::Unsub(connect_handle.get_id(),
                                                 connect_handle.protocol.get_broker_name().to_string(),
                                                 session.get_client_id().clone(),
                                                 topics);

                    let handler = handler.clone();
                    return async move {
                        handler.handle(Arc::new(connect_handle),
                                       Atom::from(""),
                                       Args::OneArgs(event)).await;

                        Ok(())
                    }.boxed_local();
                }
            }
        }

        async move {
            Err(Error::new(ErrorKind::Other,
                           format!("Mqtt proxy request failed, connect: {:?}, reason: handle unsubscribe error",
                                   connect)))
        }.boxed_local()
    }

    fn publish(&self,
               protocol: MqttBrokerProtocol,
               connect: Arc<dyn MqttConnect<S>>,
               topic: String,
               payload: Arc<Vec<u8>>) -> LocalBoxFuture<'static, Result<()>> {
        if let Some(mut handle) = connect.get_session() {
            if let Some(session) = handle.as_mut() {
                if let Some(handler) = &self.request_handler {
                    let connect_handle = MqttConnectHandle {
                        gray: AtomicIsize::new(-1),
                        client_id: session.get_client_id().clone(),
                        protocol,
                        connect,
                        is_closed: AtomicBool::new(false),
                    };

                    //异步处理Mqtt连接关闭
                    let event = MqttEvent::Publish(connect_handle.get_id(),
                                                   connect_handle.protocol.get_broker_name().to_string(),
                                                   session.get_client_id().clone(),
                                                   connect_handle.get_remote_addr(),
                                                   topic,
                                                   payload);

                    let handler = handler.clone();
                    return async move {
                        handler.handle(Arc::new(connect_handle),
                                       Atom::from(""),
                                       Args::OneArgs(event)).await;
                        Ok(())
                    }.boxed_local();
                }
            }
        }

        async move {
            Err(Error::new(ErrorKind::Other,
                           format!("Mqtt proxy publish failed, connect: {:?}, reason: handle publish error",
                                   connect)))
        }.boxed_local()
    }
}

impl MqttProxyService {
    /// 构建Mqtt代理服务
    pub fn new() -> Self {
        MqttProxyService {
            request_handler: None,
        }
    }

    /// 构建指定处理器的Mqtt代理服务
    pub fn with_handler(request_handler: Option<Arc<dyn Handler<
            A = MqttEvent,
            B = (),
            C = (),
            D = (),
            E = (),
            F = (),
            G = (),
            H = (),
            HandleResult = ()>>>) -> Self {
        MqttProxyService {
            request_handler,
        }
    }

    /// 设置Mqtt代理监听器的请求处理器
    pub fn set_handler(&mut self,
                       handler: Option<Arc<dyn Handler<
                       A = MqttEvent,
                       B = (),
                       C = (),
                       D = (),
                       E = (),
                       F = (),
                       G = (),
                       H = (),
                       HandleResult = ()>>>) {
        self.request_handler = handler;
    }
}