-
Notifications
You must be signed in to change notification settings - Fork 8
/
hook.rs
814 lines (764 loc) · 27.6 KB
/
hook.rs
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
use std::collections::VecDeque;
use std::io;
use std::mem::{self, MaybeUninit};
use std::net::SocketAddr;
use std::sync::Arc;
use async_trait::async_trait;
use bytes::Bytes;
use flume::Receiver;
use mqtt_proto::{
QoS, QosPid, TopicFilter, TopicName, {v3, v5},
};
use thiserror::Error;
use tokio::sync::oneshot;
use crate::protocols::mqtt::v3::{
packet::{
publish::handle_publish as v3_handle_publish,
subscribe::{
handle_subscribe as v3_handle_subscribe, handle_unsubscribe as v3_handle_unsubscribe,
},
},
Session as SessionV3,
};
use crate::protocols::mqtt::v5::{
packet::{
publish::handle_publish as v5_handle_publish,
subscribe::{
handle_subscribe as v5_handle_subscribe, handle_unsubscribe as v5_handle_unsubscribe,
},
},
Session as SessionV5,
};
use crate::protocols::mqtt::{OnlineSession, WritePacket};
use crate::state::{Executor, GlobalState};
// TODO:
// [ ] add timer support
// [ ] handle mqtt v5.0 scram auth
// [ ] handle disconnect event (takenover, by_server, by_client)
#[async_trait]
pub trait Hook {
async fn v5_before_connect(
&self,
peer: SocketAddr,
connect: &v5::Connect,
) -> HookResult<HookConnectCode>;
async fn v5_after_connect(
&self,
session: &SessionV5,
session_present: bool,
) -> HookResult<Vec<HookAction>>;
async fn v5_before_publish(
&self,
session: &SessionV5,
encode_len: usize,
packet_body: &[u8],
publish: &mut v5::Publish,
changed: &mut bool,
) -> HookResult<HookPublishCode>;
async fn v5_after_publish(
&self,
session: &SessionV5,
encode_len: usize,
packet_body: &[u8],
publish: &v5::Publish,
changed: bool,
) -> HookResult<Vec<HookAction>>;
async fn v5_before_subscribe(
&self,
session: &SessionV5,
encode_len: usize,
packet_body: &[u8],
subscribe: &mut v5::Subscribe,
changed: &mut bool,
) -> HookResult<HookSubscribeCode>;
async fn v5_after_subscribe(
&self,
session: &SessionV5,
encode_len: usize,
packet_body: &[u8],
subscribe: &v5::Subscribe,
changed: bool,
codes: Option<Vec<v5::SubscribeReasonCode>>,
) -> HookResult<Vec<HookAction>>;
async fn v5_before_unsubscribe(
&self,
session: &SessionV5,
encode_len: usize,
packet_body: &[u8],
unsubscribe: &mut v5::Unsubscribe,
changed: &mut bool,
) -> HookResult<HookUnsubscribeCode>;
async fn v5_after_unsubscribe(
&self,
session: &SessionV5,
encode_len: usize,
packet_body: &[u8],
unsubscribe: &v5::Unsubscribe,
changed: bool,
) -> HookResult<Vec<HookAction>>;
async fn v3_before_connect(
&self,
peer: SocketAddr,
connect: &v3::Connect,
) -> HookResult<HookConnectCode>;
async fn v3_after_connect(
&self,
session: &SessionV3,
session_present: bool,
) -> HookResult<Vec<HookAction>>;
async fn v3_before_publish(
&self,
session: &SessionV3,
encode_len: usize,
packet_body: &[u8],
publish: &mut v3::Publish,
changed: &mut bool,
) -> HookResult<HookPublishCode>;
async fn v3_after_publish(
&self,
session: &SessionV3,
encode_len: usize,
packet_body: &[u8],
publish: &v3::Publish,
changed: bool,
) -> HookResult<Vec<HookAction>>;
async fn v3_before_subscribe(
&self,
session: &SessionV3,
encode_len: usize,
packet_body: &[u8],
subscribe: &mut v3::Subscribe,
changed: &mut bool,
) -> HookResult<HookSubscribeCode>;
async fn v3_after_subscribe(
&self,
session: &SessionV3,
encode_len: usize,
packet_body: &[u8],
subscribe: &v3::Subscribe,
changed: bool,
codes: Option<Vec<v3::SubscribeReturnCode>>,
) -> HookResult<Vec<HookAction>>;
async fn v3_before_unsubscribe(
&self,
session: &SessionV3,
encode_len: usize,
packet_body: &[u8],
unsubscribe: &mut v3::Unsubscribe,
changed: &mut bool,
) -> HookResult<HookUnsubscribeCode>;
async fn v3_after_unsubscribe(
&self,
session: &SessionV3,
encode_len: usize,
packet_body: &[u8],
unsubscribe: &v3::Unsubscribe,
changed: bool,
) -> HookResult<Vec<HookAction>>;
}
#[derive(Error, Debug, Clone, PartialEq, Eq)]
pub enum HookError {
#[error("internal error")]
Internal,
}
impl From<HookError> for io::Error {
fn from(_err: HookError) -> io::Error {
io::ErrorKind::BrokenPipe.into()
}
}
pub type HookResult<T> = Result<T, HookError>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookConnectCode {
Success,
UnspecifiedError,
ClientIdentifierNotValid,
BadUserNameOrPassword,
NotAuthorized,
ServerUnavailable,
QuotaExceeded,
ConnectionRateExceeded,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookPublishCode {
Success,
UnspecifiedError,
NotAuthorized,
TopicNameInvalid,
QuotaExceeded,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookSubscribeCode {
Success,
UnspecifiedError,
NotAuthorized,
TopicFilterInvalid,
QuotaExceeded,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookUnsubscribeCode {
Success,
UnspecifiedError,
NotAuthorized,
TopicFilterInvalid,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum HookAction {
Publish(PublishAction),
Subscribe(SubscribeAction),
Unsubscribe(UnsubscribeAction),
}
/// Publish a message
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct PublishAction {
pub retain: bool,
pub qos: QoS,
pub topic_name: TopicName,
pub payload: Bytes,
pub payload_is_utf8: Option<bool>,
pub message_expiry_interval: Option<u32>,
pub content_type: Option<Arc<String>>,
}
/// Subscribe to some topic filters (retain message will not send)
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct SubscribeAction(pub Vec<(TopicFilter, QoS)>);
/// Unsubscribe to some topic filters
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct UnsubscribeAction(pub Vec<TopicFilter>);
impl HookConnectCode {
pub fn to_v5_code(self) -> v5::ConnectReasonCode {
match self {
Self::Success => v5::ConnectReasonCode::Success,
Self::UnspecifiedError => v5::ConnectReasonCode::UnspecifiedError,
Self::ClientIdentifierNotValid => v5::ConnectReasonCode::ClientIdentifierNotValid,
Self::BadUserNameOrPassword => v5::ConnectReasonCode::BadUserNameOrPassword,
Self::NotAuthorized => v5::ConnectReasonCode::NotAuthorized,
Self::ServerUnavailable => v5::ConnectReasonCode::ServerUnavailable,
Self::QuotaExceeded => v5::ConnectReasonCode::QuotaExceeded,
Self::ConnectionRateExceeded => v5::ConnectReasonCode::ConnectionRateExceeded,
}
}
pub fn to_v3_code(self) -> v3::ConnectReturnCode {
match self {
Self::Success => v3::ConnectReturnCode::Accepted,
Self::ClientIdentifierNotValid => v3::ConnectReturnCode::IdentifierRejected,
Self::ServerUnavailable => v3::ConnectReturnCode::ServerUnavailable,
Self::BadUserNameOrPassword => v3::ConnectReturnCode::BadUserNameOrPassword,
Self::NotAuthorized => v3::ConnectReturnCode::NotAuthorized,
_ => v3::ConnectReturnCode::ServerUnavailable,
}
}
}
impl HookPublishCode {
pub fn to_v5_puback_code(self) -> v5::PubackReasonCode {
match self {
Self::Success => v5::PubackReasonCode::Success,
Self::UnspecifiedError => v5::PubackReasonCode::UnspecifiedError,
Self::NotAuthorized => v5::PubackReasonCode::NotAuthorized,
Self::TopicNameInvalid => v5::PubackReasonCode::TopicNameInvalid,
Self::QuotaExceeded => v5::PubackReasonCode::QuotaExceeded,
}
}
pub fn to_v5_pubrec_code(self) -> v5::PubrecReasonCode {
match self {
Self::Success => v5::PubrecReasonCode::Success,
Self::UnspecifiedError => v5::PubrecReasonCode::UnspecifiedError,
Self::NotAuthorized => v5::PubrecReasonCode::NotAuthorized,
Self::TopicNameInvalid => v5::PubrecReasonCode::TopicNameInvalid,
Self::QuotaExceeded => v5::PubrecReasonCode::QuotaExceeded,
}
}
}
impl HookSubscribeCode {
pub fn to_v5_code(self) -> v5::SubscribeReasonCode {
match self {
Self::Success => v5::SubscribeReasonCode::GrantedQoS2,
Self::UnspecifiedError => v5::SubscribeReasonCode::UnspecifiedError,
Self::NotAuthorized => v5::SubscribeReasonCode::NotAuthorized,
Self::TopicFilterInvalid => v5::SubscribeReasonCode::TopicFilterInvalid,
Self::QuotaExceeded => v5::SubscribeReasonCode::QuotaExceeded,
}
}
}
impl HookUnsubscribeCode {
pub fn to_v5_code(self) -> v5::UnsubscribeReasonCode {
match self {
Self::Success => v5::UnsubscribeReasonCode::Success,
Self::UnspecifiedError => v5::UnsubscribeReasonCode::UnspecifiedError,
Self::NotAuthorized => v5::UnsubscribeReasonCode::NotAuthorized,
Self::TopicFilterInvalid => v5::UnsubscribeReasonCode::TopicFilterInvalid,
}
}
}
// NOTE: The lock is enforced by OnlineLoop::poll() function.
pub struct LockedHookContext<S: OnlineSession> {
session: *mut S,
write_packets: *mut VecDeque<WritePacket<S::Packet>>,
}
unsafe impl<S: OnlineSession> Send for LockedHookContext<S> {}
unsafe impl<S: OnlineSession> Sync for LockedHookContext<S> {}
impl<S: OnlineSession> LockedHookContext<S> {
pub fn new(
session: &mut S,
write_packets: &mut VecDeque<WritePacket<S::Packet>>,
) -> LockedHookContext<S> {
LockedHookContext {
session: session as *mut S,
write_packets: write_packets as *mut _,
}
}
pub fn session_ref(&self) -> &S {
unsafe { self.session.as_ref().expect("session ref ptr") }
}
pub fn get_mut(&mut self) -> (&mut S, &mut VecDeque<WritePacket<S::Packet>>) {
let LockedHookContext {
session,
write_packets,
} = self;
(
unsafe { session.as_mut().expect("session mut ptr") },
unsafe { write_packets.as_mut().expect("write_packets mut ptr") },
)
}
}
pub type HookReceipt = Result<Vec<HookAction>, Option<io::Error>>;
pub enum HookRequest {
// Shutdown,
V5BeforeConnect {
peer: SocketAddr,
connect: v5::Connect,
sender: oneshot::Sender<io::Result<HookConnectCode>>,
},
V5AfterConnect {
context: LockedHookContext<SessionV5>,
session_present: bool,
sender: oneshot::Sender<io::Result<Vec<HookAction>>>,
},
V5Publish {
context: LockedHookContext<SessionV5>,
encode_len: usize,
packet_body: Vec<MaybeUninit<u8>>,
publish: v5::Publish,
sender: oneshot::Sender<HookReceipt>,
},
V5Subscribe {
context: LockedHookContext<SessionV5>,
encode_len: usize,
packet_body: Vec<MaybeUninit<u8>>,
subscribe: v5::Subscribe,
sender: oneshot::Sender<HookReceipt>,
},
V5Unsubscribe {
context: LockedHookContext<SessionV5>,
encode_len: usize,
packet_body: Vec<MaybeUninit<u8>>,
unsubscribe: v5::Unsubscribe,
sender: oneshot::Sender<HookReceipt>,
},
V3BeforeConnect {
peer: SocketAddr,
connect: v3::Connect,
sender: oneshot::Sender<io::Result<HookConnectCode>>,
},
V3AfterConnect {
context: LockedHookContext<SessionV3>,
session_present: bool,
sender: oneshot::Sender<io::Result<Vec<HookAction>>>,
},
V3Publish {
context: LockedHookContext<SessionV3>,
encode_len: usize,
packet_body: Vec<MaybeUninit<u8>>,
publish: v3::Publish,
sender: oneshot::Sender<HookReceipt>,
},
V3Subscribe {
context: LockedHookContext<SessionV3>,
encode_len: usize,
packet_body: Vec<MaybeUninit<u8>>,
subscribe: v3::Subscribe,
sender: oneshot::Sender<HookReceipt>,
},
V3Unsubscribe {
context: LockedHookContext<SessionV3>,
encode_len: usize,
packet_body: Vec<MaybeUninit<u8>>,
unsubscribe: v3::Unsubscribe,
sender: oneshot::Sender<HookReceipt>,
},
}
#[derive(Clone)]
pub struct HookService<E: Clone, H: Clone> {
executor: E,
handler: H,
requests: Receiver<HookRequest>,
global: Arc<GlobalState>,
}
impl<E, H> HookService<E, H>
where
E: Executor + Clone,
H: Hook + Clone + Send + Sync + 'static,
{
pub fn new(
executor: E,
handler: H,
requests: Receiver<HookRequest>,
global: Arc<GlobalState>,
) -> HookService<E, H> {
HookService {
executor,
handler,
requests,
global,
}
}
pub async fn start(self) {
loop {
let request = match self.requests.recv_async().await {
Ok(request) => request,
Err(err) => {
log::error!(
"[executor#{}] receive hook request failed, error: {:?}",
self.executor.id(),
err
);
break;
}
};
let handler = self.handler.clone();
let global = Arc::clone(&self.global);
self.executor
.spawn_local(handle_request(request, handler, global));
}
}
}
async fn handle_request<H: Hook>(request: HookRequest, handler: H, global: Arc<GlobalState>) {
match request {
HookRequest::V5BeforeConnect {
peer,
connect,
sender,
} => {
log::debug!("got a v5 before connect request: {peer}, {connect:#?}");
let result = handler
.v5_before_connect(peer, &connect)
.await
.map_err(Into::into);
if let Err(_err) = sender.send(result) {
log::debug!("v5 before connect response receiver is closed");
}
}
HookRequest::V5AfterConnect {
context,
session_present,
sender,
} => {
let session = context.session_ref();
log::debug!("got a v5 after connect request: {}", session.client_id());
let result = handler
.v5_after_connect(session, session_present)
.await
.map_err(Into::into);
if let Err(_err) = sender.send(result) {
log::debug!("v5 after connect response receiver is closed");
}
}
HookRequest::V5Publish {
mut context,
encode_len,
packet_body,
mut publish,
sender,
} => {
log::debug!("got a v5 publish request: {publish:#?}");
let (session, write_packets) = context.get_mut();
let body: &[u8] = unsafe { mem::transmute(&packet_body[..]) };
let mut changed = false;
let result = handler
.v5_before_publish(session, encode_len, body, &mut publish, &mut changed)
.await;
log::debug!("v5 before publish return code: {:?}", result);
let receipt = match result {
Ok(HookPublishCode::Success) => {
match v5_handle_publish(session, publish.clone(), &global) {
Ok(packet_opt) => {
if let Some(packet) = packet_opt {
write_packets.push_back(packet.into());
}
handler
.v5_after_publish(session, encode_len, body, &publish, changed)
.await
.map_err(|err| Some(err.into()))
}
Err(err_pkt) => {
write_packets.push_back(err_pkt.into());
Ok(Vec::new())
}
}
}
Ok(code) => {
match publish.qos_pid {
QosPid::Level0 => {}
QosPid::Level1(pid) => {
let pkt: v5::Packet = v5::Puback {
pid,
reason_code: code.to_v5_puback_code(),
properties: v5::PubackProperties::default(),
}
.into();
write_packets.push_back(pkt.into());
}
QosPid::Level2(pid) => {
let pkt: v5::Packet = v5::Pubrec {
pid,
reason_code: code.to_v5_pubrec_code(),
properties: v5::PubrecProperties::default(),
}
.into();
write_packets.push_back(pkt.into());
}
}
Ok(Vec::new())
}
Err(err) => Err(Some(err.into())),
};
if let Err(_err) = sender.send(receipt) {
log::error!("send publish hook ack error");
}
}
HookRequest::V5Subscribe {
mut context,
encode_len,
packet_body,
mut subscribe,
sender,
} => {
let (session, write_packets) = context.get_mut();
let body: &[u8] = unsafe { mem::transmute(&packet_body[..]) };
let mut changed = false;
let result = handler
.v5_before_subscribe(session, encode_len, body, &mut subscribe, &mut changed)
.await;
let receipt = match result {
Ok(HookSubscribeCode::Success) => {
let codes = match v5_handle_subscribe(session, &subscribe, &global) {
Ok(packets) => {
let mut codes = Vec::new();
for packet in packets {
if let v5::Packet::Suback(suback) = &packet {
codes = suback.topics.clone();
}
write_packets.push_back(WritePacket::Packet(packet));
}
Some(codes)
}
Err(err_pkt) => {
write_packets.push_back(err_pkt.into());
None
}
};
handler
.v5_after_subscribe(session, encode_len, body, &subscribe, changed, codes)
.await
.map_err(|err| Some(err.into()))
}
Ok(code) => {
let reason_code = code.to_v5_code();
let topics = vec![reason_code; subscribe.topics.len()];
let pkt: v5::Packet = v5::Suback::new(subscribe.pid, topics).into();
write_packets.push_back(pkt.into());
Ok(Vec::new())
}
Err(err) => Err(Some(err.into())),
};
if let Err(_err) = sender.send(receipt) {
log::error!("send publish hook ack error");
}
}
HookRequest::V5Unsubscribe {
mut context,
encode_len,
packet_body,
mut unsubscribe,
sender,
} => {
let (session, write_packets) = context.get_mut();
let body: &[u8] = unsafe { mem::transmute(&packet_body[..]) };
let mut changed = false;
let result = handler
.v5_before_unsubscribe(session, encode_len, body, &mut unsubscribe, &mut changed)
.await;
let receipt = match result {
Ok(HookUnsubscribeCode::Success) => {
let unsuback = v5_handle_unsubscribe(session, &unsubscribe, &global);
write_packets.push_back(unsuback.into());
handler
.v5_after_unsubscribe(session, encode_len, body, &unsubscribe, changed)
.await
.map_err(|err| Some(err.into()))
}
Ok(code) => {
let reason_code = code.to_v5_code();
let topics = vec![reason_code; unsubscribe.topics.len()];
let pkt: v5::Packet = v5::Unsuback::new(unsubscribe.pid, topics).into();
write_packets.push_back(pkt.into());
Ok(Vec::new())
}
Err(err) => Err(Some(err.into())),
};
if let Err(_err) = sender.send(receipt) {
log::error!("send publish hook ack error");
}
}
HookRequest::V3BeforeConnect {
peer,
connect,
sender,
} => {
log::debug!("got a v3 before connect request: {peer}, {connect:#?}");
let result = handler
.v3_before_connect(peer, &connect)
.await
.map_err(Into::into);
if let Err(_err) = sender.send(result) {
log::debug!("v3 before connect response receiver is closed");
}
}
HookRequest::V3AfterConnect {
context,
session_present,
sender,
} => {
let session = context.session_ref();
log::debug!("got a v3 after connect request: {}", session.client_id());
let result = handler
.v3_after_connect(session, session_present)
.await
.map_err(Into::into);
if let Err(_err) = sender.send(result) {
log::debug!("v3 after connect response receiver is closed");
}
}
HookRequest::V3Publish {
mut context,
encode_len,
packet_body,
mut publish,
sender,
} => {
log::debug!("got a v3 publish request: {publish:#?}");
let (session, write_packets) = context.get_mut();
let body: &[u8] = unsafe { mem::transmute(&packet_body[..]) };
let mut changed = false;
let result = handler
.v3_before_publish(session, encode_len, body, &mut publish, &mut changed)
.await;
log::debug!("v3 before publish return code: {:?}", result);
let receipt = match result {
Ok(HookPublishCode::Success) => {
match v3_handle_publish(session, publish.clone(), &global) {
Ok(packet_opt) => {
if let Some(packet) = packet_opt {
write_packets.push_back(packet.into());
}
handler
.v3_after_publish(session, encode_len, body, &publish, changed)
.await
.map_err(|err| Some(err.into()))
}
Err(err) => Err(Some(err)),
}
}
// TODO: return error or just ignore the packet?
Ok(_) => Err(Some(io::ErrorKind::InvalidData.into())),
Err(err) => Err(Some(err.into())),
};
if let Err(_err) = sender.send(receipt) {
log::error!("send publish hook ack error");
}
}
HookRequest::V3Subscribe {
mut context,
encode_len,
packet_body,
mut subscribe,
sender,
} => {
let (session, write_packets) = context.get_mut();
let body: &[u8] = unsafe { mem::transmute(&packet_body[..]) };
let mut changed = false;
let result = handler
.v3_before_subscribe(session, encode_len, body, &mut subscribe, &mut changed)
.await;
let receipt = match result {
Ok(HookSubscribeCode::Success) => {
match v3_handle_subscribe(session, &subscribe, &global) {
Ok(packets) => {
let mut codes = Vec::new();
for packet in packets {
if let v3::Packet::Suback(suback) = &packet {
codes = suback.topics.clone();
}
write_packets.push_back(WritePacket::Packet(packet));
}
handler
.v3_after_subscribe(
session,
encode_len,
body,
&subscribe,
changed,
Some(codes),
)
.await
.map_err(|err| Some(err.into()))
}
Err(err) => {
let _result = handler
.v3_after_subscribe(
session, encode_len, body, &subscribe, changed, None,
)
.await;
Err(Some(err))
}
}
}
// TODO: return error or just ignore the packet?
Ok(_code) => Err(Some(io::ErrorKind::InvalidData.into())),
Err(err) => Err(Some(err.into())),
};
if let Err(_err) = sender.send(receipt) {
log::error!("send publish hook ack error");
}
}
HookRequest::V3Unsubscribe {
mut context,
encode_len,
packet_body,
mut unsubscribe,
sender,
} => {
let (session, write_packets) = context.get_mut();
let body: &[u8] = unsafe { mem::transmute(&packet_body[..]) };
let mut changed = false;
let result = handler
.v3_before_unsubscribe(session, encode_len, body, &mut unsubscribe, &mut changed)
.await;
let receipt = match result {
Ok(HookUnsubscribeCode::Success) => {
let unsuback = v3_handle_unsubscribe(session, &unsubscribe, &global);
write_packets.push_back(unsuback.into());
handler
.v3_after_unsubscribe(session, encode_len, body, &unsubscribe, changed)
.await
.map_err(|err| Some(err.into()))
}
// TODO: return error or just ignore the packet?
Ok(_code) => Err(Some(io::ErrorKind::InvalidData.into())),
Err(err) => Err(Some(err.into())),
};
if let Err(_err) = sender.send(receipt) {
log::error!("send publish hook ack error");
}
}
}
}