-
Notifications
You must be signed in to change notification settings - Fork 227
/
routing.rs
1854 lines (1622 loc) · 67.7 KB
/
routing.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
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::protocol::{
ConnAck, ConnectReturnCode, Packet, PingResp, PubAck, PubAckReason, PubComp, PubCompReason,
PubRel, PubRelReason, Publish, QoS, SubAck, SubscribeReasonCode, UnsubAck,
};
use crate::router::graveyard::SavedState;
use crate::router::scheduler::{PauseReason, Tracker};
use crate::router::Forward;
use crate::segments::Position;
use crate::*;
use flume::{bounded, Receiver, RecvError, Sender, TryRecvError};
use slab::Slab;
use std::collections::{HashMap, HashSet, VecDeque};
use std::str::Utf8Error;
use std::thread;
use std::time::SystemTime;
use thiserror::Error;
use tracing::{debug, error, info, trace, warn};
use super::graveyard::Graveyard;
use super::iobufs::{Incoming, Outgoing};
use super::logs::{AckLog, DataLog};
use super::scheduler::{ScheduleReason, Scheduler};
use super::{
packetid, Connection, DataRequest, Event, FilterIdx, GetMeter, Meter, MetricsReply,
MetricsRequest, Notification, RouterMeter, ShadowRequest, MAX_CHANNEL_CAPACITY,
MAX_SCHEDULE_ITERATIONS,
};
#[derive(Error, Debug)]
pub enum RouterError {
#[error("Receive error = {0}")]
Recv(#[from] RecvError),
#[error("Try Receive error = {0}")]
TryRecv(#[from] TryRecvError),
#[error("Disconnection")]
Disconnected,
#[error("Topic not utf-8")]
NonUtf8Topic(#[from] Utf8Error),
#[cfg(feature = "validate-tenant-prefix")]
#[error("Bad Tenant")]
BadTenant(String, String),
#[error("No matching filters to topic {0}")]
NoMatchingFilters(String),
#[error("Unsupported QoS {0:?}")]
UnsupportedQoS(QoS),
#[error("Invalid filter prefix {0}")]
InvalidFilterPrefix(Filter),
}
pub struct Router {
id: RouterId,
/// Id of this router. Used to index native commitlog to store data from
/// local connections
config: RouterConfig,
/// Saved state of dead persistent connections
graveyard: Graveyard,
/// List of connections
meters: Slab<Sender<(ConnectionId, Meter)>>,
/// List of connections
connections: Slab<Connection>,
/// Connection map from device id to connection id
connection_map: HashMap<String, ConnectionId>,
/// Subscription map to interested connection ids
subscription_map: HashMap<Filter, HashSet<ConnectionId>>,
/// Incoming data grouped by connection
ibufs: Slab<Incoming>,
/// Outgoing data grouped by connection
obufs: Slab<Outgoing>,
/// Data log of all the subscriptions
datalog: DataLog,
/// Acks log per connection
ackslog: Slab<AckLog>,
/// Scheduler to schedule connections
scheduler: Scheduler,
/// Parked requests that are ready because of new data on the subscription
notifications: VecDeque<(ConnectionId, DataRequest)>,
/// Channel receiver to receive data from all the active connections and
/// replicators. Each connection will have a tx handle which they use
/// to send data and requests to router
router_rx: Receiver<(ConnectionId, Event)>,
/// Channel sender to send data to this router. This is given to active
/// network connections, local connections and replicators to communicate
/// with this router
router_tx: Sender<(ConnectionId, Event)>,
/// Router metrics
router_meters: RouterMeter,
/// Buffer for cache exchange of incoming packets
cache: Option<VecDeque<Packet>>,
}
impl Router {
pub fn new(router_id: RouterId, config: RouterConfig) -> Router {
let (router_tx, router_rx) = bounded(1000);
let meters = Slab::with_capacity(10);
let connections = Slab::with_capacity(config.max_connections);
let ibufs = Slab::with_capacity(config.max_connections);
let obufs = Slab::with_capacity(config.max_connections);
let ackslog = Slab::with_capacity(config.max_connections);
let router_metrics = RouterMeter {
router_id,
..RouterMeter::default()
};
let max_connections = config.max_connections;
Router {
id: router_id,
config: config.clone(),
graveyard: Graveyard::new(),
meters,
connections,
connection_map: Default::default(),
subscription_map: Default::default(),
ibufs,
obufs,
datalog: DataLog::new(config).unwrap(),
ackslog,
scheduler: Scheduler::with_capacity(max_connections),
notifications: VecDeque::with_capacity(1024),
router_rx,
router_tx,
router_meters: router_metrics,
cache: Some(VecDeque::with_capacity(MAX_CHANNEL_CAPACITY)),
}
}
/// Gets handle to the router. This is not a public method to ensure that link
/// is created only after the router starts
fn link(&self) -> Sender<(ConnectionId, Event)> {
self.router_tx.clone()
}
// pub(crate) fn get_replica_handle(&mut self, _replica_id: NodeId) -> (LinkTx, LinkRx) {
// unimplemented!()
// }
/// Starts the router in a background thread and returns link to it. Link
/// to communicate with router should only be returned only after it starts.
/// For that reason, all the public methods should start the router in the
/// background
#[tracing::instrument(skip_all)]
pub fn spawn(mut self) -> Sender<(ConnectionId, Event)> {
let router = thread::Builder::new().name(format!("router-{}", self.id));
let link = self.link();
router
.spawn(move || {
let e = self.run(0);
error!(reason=?e, "Router done!");
})
.unwrap();
link
}
/// Waits on incoming events when ready queue is empty.
/// After pulling 1 event, tries to pull 500 more events
/// before polling ready queue 100 times (connections)
#[tracing::instrument(skip_all)]
fn run(&mut self, count: usize) -> Result<(), RouterError> {
match count {
0 => loop {
self.run_inner()?;
},
n => {
for _ in 0..n {
self.run_inner()?;
}
}
};
Ok(())
}
fn run_inner(&mut self) -> Result<(), RouterError> {
// Block on incoming events if there are no ready connections for consumption
if self.consume().is_none() {
// trace!("{}:: {:20} {:20} {:?}", self.id, "", "done-await", self.readyqueue);
let (id, data) = self.router_rx.recv()?;
self.events(id, data);
}
// Try reading more from connections in a non-blocking
// fashion to accumulate data and handle subscriptions.
// Accumulating more data lets requests retrieve bigger
// bulks which in turn increases efficiency
for _ in 0..500 {
// All these methods will handle state and errors
match self.router_rx.try_recv() {
Ok((id, data)) => self.events(id, data),
Err(TryRecvError::Disconnected) => return Err(RouterError::Disconnected),
Err(TryRecvError::Empty) => break,
}
}
// A connection should not be scheduled multiple times
debug_assert!(self.scheduler.check_readyqueue_duplicates());
// Poll 100 connections which are ready in ready queue
for _ in 0..100 {
self.consume();
}
Ok(())
}
fn events(&mut self, id: ConnectionId, data: Event) {
let span = tracing::info_span!("[>] incoming", connection_id = id);
let _guard = span.enter();
match data {
Event::Connect {
connection,
incoming,
outgoing,
} => self.handle_new_connection(connection, incoming, outgoing),
Event::NewMeter(tx) => self.handle_new_meter(tx),
Event::GetMeter(meter) => self.handle_get_meter(id, meter),
Event::DeviceData => self.handle_device_payload(id),
Event::Disconnect(disconnect) => self.handle_disconnection(id, disconnect.execute_will),
Event::Ready => self.scheduler.reschedule(id, ScheduleReason::Ready),
Event::Shadow(request) => {
retrieve_shadow(&mut self.datalog, &mut self.obufs[id], request)
}
Event::Metrics(metrics) => retrieve_metrics(self, metrics),
}
}
fn handle_new_connection(
&mut self,
mut connection: Connection,
incoming: Incoming,
outgoing: Outgoing,
) {
let client_id = outgoing.client_id.clone();
let span = tracing::info_span!("incoming_connect", client_id);
let _guard = span.enter();
if self.connections.len() >= self.config.max_connections {
error!("no space for new connection");
// let ack = ConnectionAck::Failure("No space for new connection".to_owned());
// let message = Notification::ConnectionAck(ack);
return;
}
// Retrieve previous connection state from graveyard
let saved = self.graveyard.retrieve(&client_id);
let clean_session = connection.clean;
let previous_session = saved.is_some();
let tracker = if !clean_session {
let saved = saved.map_or(SavedState::new(client_id.clone()), |s| s);
connection.subscriptions = saved.subscriptions;
connection.events = saved.metrics;
saved.tracker
} else {
// Only retrieve metrics in clean session
let saved = saved.map_or(SavedState::new(client_id.clone()), |s| s);
connection.events = saved.metrics;
Tracker::new(client_id.clone())
};
let ackslog = AckLog::new();
let time = match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(v) => v.as_millis().to_string(),
Err(e) => format!("Time error = {:?}", e),
};
let event = "connection at ".to_owned() + &time + ", clean = " + &clean_session.to_string();
connection.events.events.push_back(event);
if connection.events.events.len() > 10 {
connection.events.events.pop_front();
}
let connection_id = self.connections.insert(connection);
assert_eq!(self.ibufs.insert(incoming), connection_id);
assert_eq!(self.obufs.insert(outgoing), connection_id);
self.connection_map.insert(client_id.clone(), connection_id);
info!(connection_id, "Client connection registered");
assert_eq!(self.ackslog.insert(ackslog), connection_id);
assert_eq!(self.scheduler.add(tracker), connection_id);
// Check if there are multiple data requests on same filter.
debug_assert!(self.scheduler.check_tracker_duplicates(connection_id));
let ack = ConnAck {
session_present: !clean_session && previous_session,
code: ConnectReturnCode::Success,
};
let ackslog = self.ackslog.get_mut(connection_id).unwrap();
ackslog.connack(connection_id, ack);
self.scheduler
.reschedule(connection_id, ScheduleReason::Init);
self.router_meters.total_connections += 1;
}
fn handle_new_meter(&mut self, tx: Sender<(ConnectionId, Meter)>) {
let meter_id = self.meters.insert(tx);
let tx = &self.meters[meter_id];
let _ = tx.try_send((meter_id, Meter::Router(self.id, self.router_meters.clone())));
}
fn handle_disconnection(&mut self, id: ConnectionId, execute_last_will: bool) {
// Some clients can choose to send Disconnect packet before network disconnection.
// This will lead to double Disconnect packets in router `events`
let client_id = match &self.obufs.get(id) {
Some(v) => v.client_id.clone(),
None => {
error!("no-connection id {} is already gone", id);
return;
}
};
let span = tracing::info_span!("incoming_disconnect", client_id);
let _guard = span.enter();
if execute_last_will {
self.handle_last_will(id);
}
info!("Disconnecting connection");
// Remove connection from router
let mut connection = self.connections.remove(id);
let _incoming = self.ibufs.remove(id);
let outgoing = self.obufs.remove(id);
let mut tracker = self.scheduler.remove(id);
self.connection_map.remove(&client_id);
self.ackslog.remove(id);
// Don't remove connection id from readyqueue with index. This will
// remove wrong connection from readyqueue. Instead just leave diconnected
// connection in readyqueue and allow 'consume()' method to deal with this
// self.readyqueue.remove(id);
let inflight_data_requests = self.datalog.clean(id);
let retransmissions = outgoing.retrasmission_map();
// Remove this connection from subscriptions
for filter in connection.subscriptions.iter() {
if let Some(connections) = self.subscription_map.get_mut(filter) {
connections.remove(&id);
}
}
// Add disconnection event to metrics
let time = match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(v) => v.as_millis().to_string(),
Err(e) => format!("Time error = {:?}", e),
};
let event = "disconnection at ".to_owned() + &time;
connection.events.events.push_back(event);
if connection.events.events.len() > 10 {
connection.events.events.pop_front();
}
// Save state for persistent sessions
if !connection.clean {
// Add inflight data requests back to tracker
inflight_data_requests
.into_iter()
.for_each(|r| tracker.register_data_request(r));
debug!("{:?}, {:?} ", &tracker, retransmissions);
for request in tracker.data_requests.iter_mut() {
if let Some(cursor) = retransmissions.get(&request.filter_idx) {
request.cursor = *cursor;
}
}
debug!("{:?}, {:?} ", &tracker, retransmissions);
self.graveyard
.save(tracker, connection.subscriptions, connection.events);
} else {
// Only save metrics in clean session
self.graveyard
.save(Tracker::new(client_id), HashSet::new(), connection.events);
}
self.router_meters.total_connections -= 1;
}
/// Handles new incoming data on a topic
fn handle_device_payload(&mut self, id: ConnectionId) {
// TODO: Retun errors and move error handling to the caller
let incoming = match self.ibufs.get_mut(id) {
Some(v) => v,
None => {
error!("no-connection id {} is already gone", id);
return;
}
};
let client_id = incoming.client_id.clone();
let span = tracing::info_span!("incoming_payload", client_id);
let _guard = span.enter();
// Instead of exchanging, we should just append new incoming packets inside cache
let mut packets = incoming.exchange(self.cache.take().unwrap());
let mut force_ack = false;
let mut new_data = false;
let mut disconnect = false;
let mut execute_will = true;
// info!("{:15.15}[I] {:20} count = {}", client_id, "packets", packets.len());
for packet in packets.drain(0..) {
match packet {
Packet::Publish(publish, _) => {
let span =
tracing::info_span!("publish", topic = ?publish.topic, pkid = publish.pkid);
let _guard = span.enter();
let size = publish.len();
let qos = publish.qos;
let pkid = publish.pkid;
// Prepare acks for the above publish
// If any of the publish in the batch results in force flush,
// set global force flush flag. Force flush is triggered when the
// router is in instant ack more or connection data is from a replica
//
// TODO: handle multiple offsets
//
// The problem with multiple offsets is that when using replication with the current
// architecture, a single publish might get appended to multiple commit logs, resulting in
// multiple offsets (see `append_to_commitlog` function), meaning replicas will need to
// coordinate using multiple offsets, and we don't have any idea how to do so right now.
// Currently as we don't have replication, we just use a single offset, even when appending to
// multiple commit logs.
match qos {
QoS::AtLeastOnce => {
let puback = PubAck {
pkid,
reason: PubAckReason::Success,
};
let ackslog = self.ackslog.get_mut(id).unwrap();
ackslog.puback(puback);
force_ack = true;
}
QoS::ExactlyOnce => {
error!("QoS::ExactlyOnce is not yet supported");
disconnect = true;
break;
// let pubrec = PubRec {
// pkid,
// reason: PubRecReason::Success,
// };
//
// let ackslog = self.ackslog.get_mut(id).unwrap();
// ackslog.pubrec(publish, pubrec);
// force_ack = true;
// continue;
}
QoS::AtMostOnce => {
// Do nothing
}
};
self.router_meters.total_publishes += 1;
// Try to append publish to commitlog
match append_to_commitlog(
id,
publish,
&mut self.datalog,
&mut self.notifications,
&mut self.connections,
) {
Ok(_offset) => {
// Even if one of the data in the batch is appended to commitlog,
// set new data. This triggers notifications to wake waiters.
// Don't overwrite this flag to false if it is already true.
new_data = true;
}
Err(e) => {
// Disconnect on bad publishes
error!(
reason = ?e, "Failed to append to commitlog"
);
self.router_meters.failed_publishes += 1;
disconnect = true;
break;
}
};
let meter = &mut self.ibufs.get_mut(id).unwrap().meter;
meter.publish_count += 1;
meter.total_size += size;
// println!("{}, {}", self.router_metrics.total_publishes, pkid);
}
Packet::Subscribe(s, _) => {
let mut return_codes = Vec::new();
let pkid = s.pkid;
// let len = s.len();
for f in s.filters {
let span = tracing::info_span!("subscribe", topic = f.path, pkid = s.pkid);
let _guard = span.enter();
info!("Adding subscription on topic {}", f.path);
let connection = self.connections.get_mut(id).unwrap();
if let Err(e) = validate_subscription(connection, &f) {
warn!(reason = ?e,"Subscription cannot be validated: {}", e);
disconnect = true;
break;
}
let filter = f.path;
let qos = f.qos;
let (idx, cursor) = self.datalog.next_native_offset(&filter);
self.prepare_filter(id, cursor, idx, filter.clone(), qos as u8);
self.datalog
.handle_retained_messages(&filter, &mut self.notifications);
let code = match qos {
QoS::AtMostOnce => SubscribeReasonCode::QoS0,
QoS::AtLeastOnce => SubscribeReasonCode::QoS1,
QoS::ExactlyOnce => SubscribeReasonCode::QoS2,
};
return_codes.push(code);
}
// let meter = &mut self.ibufs.get_mut(id).unwrap().meter;
// meter.total_size += len;
let suback = SubAck { pkid, return_codes };
let ackslog = self.ackslog.get_mut(id).unwrap();
ackslog.suback(suback);
force_ack = true;
}
Packet::Unsubscribe(unsubscribe, _) => {
let connection = self.connections.get_mut(id).unwrap();
let pkid = unsubscribe.pkid;
for filter in unsubscribe.filters {
let span = tracing::info_span!("unsubscribe", topic = filter, pkid);
let _guard = span.enter();
debug!("Removing subscription on filter {}", filter);
if let Some(connection_ids) = self.subscription_map.get_mut(&filter) {
let removed = connection_ids.remove(&id);
if !removed {
continue;
}
let meter = &mut self.ibufs.get_mut(id).unwrap().meter;
meter.subscribe_count -= 1;
if !connection.subscriptions.remove(&filter) {
warn!(
pkid = unsubscribe.pkid,
"Unsubscribe failed as filter was not subscribed previously"
);
continue;
}
let unsuback = UnsubAck {
pkid,
// reasons are used in MQTTv5
reasons: vec![],
};
let ackslog = self.ackslog.get_mut(id).unwrap();
ackslog.unsuback(unsuback);
self.scheduler.untrack(id, &filter);
self.datalog.remove_waiters_for_id(id, &filter);
force_ack = true;
}
}
}
Packet::PubAck(puback, _) => {
let span = tracing::info_span!("puback", pkid = puback.pkid);
let _guard = span.enter();
let outgoing = self.obufs.get_mut(id).unwrap();
let pkid = puback.pkid;
if outgoing.register_ack(pkid).is_none() {
error!(pkid, "Unsolicited/ooo ack received for pkid {}", pkid);
disconnect = true;
break;
}
self.scheduler.reschedule(id, ScheduleReason::IncomingAck);
}
Packet::PubRec(pubrec, _) => {
let span = tracing::info_span!("pubrec", pkid = pubrec.pkid);
let _guard = span.enter();
let outgoing = self.obufs.get_mut(id).unwrap();
let pkid = pubrec.pkid;
if outgoing.register_ack(pkid).is_none() {
error!(pkid, "Unsolicited/ooo ack received for pkid {}", pkid);
disconnect = true;
break;
}
let ackslog = self.ackslog.get_mut(id).unwrap();
let pubrel = PubRel {
pkid: pubrec.pkid,
reason: PubRelReason::Success,
};
ackslog.pubrel(pubrel);
self.scheduler.reschedule(id, ScheduleReason::IncomingAck);
}
Packet::PubRel(pubrel, None) => {
let span = tracing::info_span!("pubrel", pkid = pubrel.pkid);
let _guard = span.enter();
let ackslog = self.ackslog.get_mut(id).unwrap();
let pubcomp = PubComp {
pkid: pubrel.pkid,
reason: PubCompReason::Success,
};
let publish = match ackslog.pubcomp(pubcomp) {
Some(v) => v,
None => {
disconnect = true;
break;
}
};
// Try to append publish to commitlog
match append_to_commitlog(
id,
publish,
&mut self.datalog,
&mut self.notifications,
&mut self.connections,
) {
Ok(_offset) => {
// Even if one of the data in the batch is appended to commitlog,
// set new data. This triggers notifications to wake waiters.
// Don't overwrite this flag to false if it is already true.
new_data = true;
}
Err(e) => {
// Disconnect on bad publishes
error!(
reason = ?e, "Failed to append to commitlog"
);
self.router_meters.failed_publishes += 1;
disconnect = true;
break;
}
};
}
Packet::PubComp(_pubcomp, _) => {}
Packet::PingReq(_) => {
let ackslog = self.ackslog.get_mut(id).unwrap();
ackslog.pingresp(PingResp);
force_ack = true;
}
Packet::Disconnect(_, _) => {
let span = tracing::info_span!("disconnect");
let _guard = span.enter();
disconnect = true;
execute_will = false;
break;
}
incoming => {
warn!(packet=?incoming, "Packet not supported by router yet" );
}
}
}
self.cache = Some(packets);
// Prepare AcksRequest in tracker if router is operating in a
// single node mode or force ack request for subscriptions
if force_ack {
self.scheduler.reschedule(id, ScheduleReason::FreshData);
}
// Notify waiting consumers only if there is publish data. During
// subscription, data request is added to data waiter. With out this
// if condition, connection will be woken up even during subscription
if new_data {
// Prepare all the consumers which are waiting for new data
while let Some((id, request)) = self.notifications.pop_front() {
self.scheduler.track(id, request);
self.scheduler.reschedule(id, ScheduleReason::FreshData);
}
}
// Incase BytesMut represents 10 packets, publish error/diconnect event
// on say 5th packet should not block new data notifications for packets
// 1 - 4. Hence we use a flag instead of diconnecting immediately
if disconnect {
self.handle_disconnection(id, execute_will);
}
}
/// Apply filter and prepare this connection to receive subscription data
fn prepare_filter(
&mut self,
id: ConnectionId,
cursor: Offset,
filter_idx: FilterIdx,
filter: String,
qos: u8,
) {
// Add connection id to subscription list
match self.subscription_map.get_mut(&filter) {
Some(connections) => {
connections.insert(id);
}
None => {
let mut connections = HashSet::new();
connections.insert(id);
self.subscription_map.insert(filter.clone(), connections);
}
}
// Prepare consumer to pull data in case of subscription
let connection = self.connections.get_mut(id).unwrap();
if connection.subscriptions.insert(filter.clone()) {
let request = DataRequest {
filter,
filter_idx,
qos,
cursor,
read_count: 0,
max_count: 100,
};
self.scheduler.track(id, request);
self.scheduler.reschedule(id, ScheduleReason::NewFilter);
debug_assert!(self.scheduler.check_tracker_duplicates(id))
}
let meter = &mut self.ibufs.get_mut(id).unwrap().meter;
meter.subscribe_count += 1;
}
/// When a connection is ready, it should sweep native data from 'datalog',
/// send data and notifications to consumer.
/// To activate a connection, first connection's tracker is fetched and
/// all the requests are handled.
fn consume(&mut self) -> Option<()> {
let (id, mut requests) = self.scheduler.poll()?;
let span = tracing::info_span!("[<] outgoing", connection_id = id);
let _guard = span.enter();
let outgoing = match self.obufs.get_mut(id) {
Some(v) => v,
None => {
error!("Connection is already disconnected");
return Some(());
}
};
let ackslog = self.ackslog.get_mut(id).unwrap();
let datalog = &mut self.datalog;
trace!("Consuming requests");
// We always try to ack when ever a connection is scheduled
ack_device_data(ackslog, outgoing);
// A new connection's tracker is always initialized with acks request.
// A subscribe will register data request.
// So a new connection is always scheduled with at least one request
for _ in 0..MAX_SCHEDULE_ITERATIONS {
let mut request = match requests.pop_front() {
// Handle next data or acks request
Some(request) => request,
// No requests in the queue. This implies that consumer data and
// acks are completely caught up. Pending requests are registered
// in waiters and awaiting new notifications (device or replica data)
None => {
self.scheduler.pause(id, PauseReason::Caughtup);
return Some(());
}
};
match forward_device_data(&mut request, datalog, outgoing) {
ConsumeStatus::BufferFull => {
requests.push_back(request);
self.scheduler.pause(id, PauseReason::Busy);
break;
}
ConsumeStatus::InflightFull => {
requests.push_back(request);
self.scheduler.pause(id, PauseReason::InflightFull);
break;
}
ConsumeStatus::FilterCaughtup => {
let filter = &request.filter;
trace!(filter, "Filter caughtup {filter}, parking connection");
// When all the data in the log is caught up, current request is
// registered in waiters and not added back to the tracker. This
// ensures that tracker.next() stops when all the requests are done
datalog.park(id, request);
}
ConsumeStatus::PartialRead => {
requests.push_back(request);
}
}
}
// Add requests back to the tracker if there are any
self.scheduler.trackv(id, requests);
Some(())
}
pub fn handle_last_will(&mut self, id: ConnectionId) {
let connection = self.connections.get_mut(id).unwrap();
let will = match connection.last_will.take() {
Some(v) => v,
None => return,
};
let publish = Publish {
dup: false,
qos: will.qos,
retain: will.retain,
topic: will.topic,
pkid: 0,
payload: will.message,
};
match append_to_commitlog(
id,
publish,
&mut self.datalog,
&mut self.notifications,
&mut self.connections,
) {
Ok(_offset) => {
// Prepare all the consumers which are waiting for new data
while let Some((id, request)) = self.notifications.pop_front() {
self.scheduler.track(id, request);
self.scheduler.reschedule(id, ScheduleReason::FreshData);
}
}
Err(e) => {
// Disconnect on bad publishes
error!(
reason = ?e, "Failed to append to commitlog"
);
self.router_meters.failed_publishes += 1;
// Removed disconnect = true from here because we disconnect anyways
}
};
}
fn handle_get_meter(&self, meter_id: ConnectionId, meter: router::GetMeter) {
let meter_tx = &self.meters[meter_id];
match meter {
GetMeter::Router => {
let router_meters = Meter::Router(self.id, self.router_meters.clone());
let _ = meter_tx.try_send((meter_id, router_meters));
}
GetMeter::Connection(client_id) => {
let connection_id = match self.connection_map.get(&client_id) {
Some(val) => val,
None => {
let meter = Meter::Connection("".to_owned(), None, None);
let _ = meter_tx.try_send((meter_id, meter));
return;
}
};
// Update metrics
let incoming_meter = self.ibufs.get(*connection_id).map(|v| v.meter.clone());
let outgoing_meter = self.obufs.get(*connection_id).map(|v| v.meter.clone());
let meter = Meter::Connection(client_id, incoming_meter, outgoing_meter);
let _ = meter_tx.try_send((meter_id, meter));
}
GetMeter::Subscription(filter) => {
let subscription_meter = self.datalog.meter(&filter);
let meter = Meter::Subscription(filter, subscription_meter);
let _ = meter_tx.try_send((meter_id, meter));
}
};
}
}
fn append_to_commitlog(
id: ConnectionId,
mut publish: Publish,
datalog: &mut DataLog,
notifications: &mut VecDeque<(ConnectionId, DataRequest)>,
connections: &mut Slab<Connection>,
) -> Result<Offset, RouterError> {
let topic = std::str::from_utf8(&publish.topic)?;
// Ensure that only clients associated with a tenant can publish to tenant's topic
#[cfg(feature = "validate-tenant-prefix")]
if let Some(tenant_prefix) = &connections[id].tenant_prefix {
if !topic.starts_with(tenant_prefix) {
return Err(RouterError::BadTenant(
tenant_prefix.to_owned(),
topic.to_owned(),
));
}
}
if publish.payload.is_empty() {
datalog.remove_from_retained_publishes(topic.to_owned());
} else if publish.retain {
datalog.insert_to_retained_publishes(publish.clone(), topic.to_owned());
}
publish.retain = false;
let pkid = publish.pkid;
let filter_idxs = datalog.matches(topic);
// Create a dynamic filter if dynamic_filters are enabled for this connection
let filter_idxs = match filter_idxs {
Some(v) => v,
None if connections[id].dynamic_filters => {
let (idx, _cursor) = datalog.next_native_offset(topic);
vec![idx]
}
None => return Err(RouterError::NoMatchingFilters(topic.to_owned())),
};
let mut o = (0, 0);
for filter_idx in filter_idxs {
let datalog = datalog.native.get_mut(filter_idx).unwrap();
let (offset, filter) = datalog.append(publish.clone(), notifications);
debug!(
pkid,
"Appended to commitlog: {}[{}, {})", filter, offset.0, offset.1,
);
o = offset;
}
// error!("{:15.15}[E] {:20} topic = {}", connections[id].client_id, "no-filter", topic);
Ok(o)
}
/// Sweep ackslog for all the pending acks.
/// We write everything to outgoing buf with out worrying about buffer size
/// because acks most certainly won't cause memory bloat
fn ack_device_data(ackslog: &mut AckLog, outgoing: &mut Outgoing) -> bool {
let span = tracing::info_span!("outgoing_ack", client_id = outgoing.client_id);
let _guard = span.enter();
let acks = ackslog.readv();
if acks.is_empty() {
debug!("No acks pending");
return false;
}
let mut count = 0;
let mut buffer = outgoing.data_buffer.lock();
// Unlike forwards, we are reading all the pending acks for a given connection.
// At any given point of time, there can be a max of connection's buffer size
for ack in acks.drain(..) {
let pkid = packetid(&ack);
trace!(pkid, "Ack added for pkid {}", pkid);
let message = Notification::DeviceAck(ack);
buffer.push_back(message);
count += 1;
}
debug!(acks_count = count, "Acks sent to device");
outgoing.handle.try_send(()).ok();
true
}
enum ConsumeStatus {
/// Limit for publishes on outgoing channel reached
BufferFull,
/// Limit for inflight publishes on outgoing channel reached
InflightFull,
/// All publishes on topic forwarded
FilterCaughtup,
/// Some publishes on topic have been forwarded
PartialRead,
}
/// Sweep datalog from offset in DataRequest and updates DataRequest
/// for next sweep. Returns (busy, caughtup) status
/// Returned arguments: