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
//! A pure rust mqtt client which strives to be robust, efficient and easy to use.
//! * Eventloop is just an async `Stream` which can be polled by tokio
//! * Requests to eventloop is also a `Stream`. Solves both bounded an unbounded usecases
//! * Robustness just a loop away
//! * Flexible access to the state of eventloop to control its behaviour
//!
//! Accepts any stream of Requests
//! ----------------------------
//! Build bounded, unbounded, interruptible or any other stream (that fits your need) to
//! feed the eventloop.
//!
//! **Few of our real world use cases**
//!
//! - A stream which orchestrates data between disk and memory by detecting backpressure and never (practically) loose data
//! - A stream which juggles data between several channels based on priority of the data
//!
//! ```ignore
//! #[tokio::main(core_threads = 1)]
//! async fn main() {
//!     let mut mqttoptions = MqttOptions::new("test-1", "localhost", 1883);
//!     let requests = Vec::new::<Request>();
//!
//!     let mut eventloop = eventloop(mqttoptions, requests_rx);
//!     let mut stream = eventloop.connect().await.unwrap();
//!     while let Some(item) = stream.next().await {
//!         println!("Received = {:?}", item);
//!     }
//! }
//! ```
//! Robustness a loop away
//! ----------------------
//! Networks are unreliable. But robustness is easy
//!
//! - Just create a new stream from the existing eventloop
//! - Resumes from where it left
//! - Access the state of the eventloop to customize the behaviour of the next connection
//!
//! ```ignore
//! #[tokio::main(core_threads = 1)]
//! async fn main() {
//!     let mut mqttoptions = MqttOptions::new("test-1", "localhost", 1883);
//!     let requests = Vec::new::<Request>();
//!
//!     let mut eventloop = eventloop(mqttoptions, requests_rx);
//!
//!     // loop to reconnect and resume
//!     loop {
//!         let mut stream = eventloop.connect().await.unwrap();
//!         while let Some(item) = stream.next().await {
//!             println!("Received = {:?}", item);
//!         }
//!
//!         time::delay_for(Duration::from_secs(1)).await;
//!     }
//! }
//! ```
//!
//! Eventloop is just a stream which can be polled with tokio
//! ----------------------
//! - Plug it into `select!` `join!` to interleave with other streams on the the same thread
//!
//! ```ignore
//! #[tokio::main(core_threads = 1)]
//! async fn main() {
//!     let mut mqttoptions = MqttOptions::new("test-1", "localhost", 1883);
//!     let requests = Vec::new::<Request>();
//!
//!     let mut eventloop = eventloop(mqttoptions, requests_rx);
//!
//!     // plug it into tokio ecosystem
//!     let mut stream = eventloop.connect().await.unwrap();
//! }
//! ```
//!
//! Powerful notification system to control the runtime
//! ----------------------
//! Eventloop stream yields all the interesting event ranging for data on the network to
//! disconnections and reconnections. Use it the way you see fit
//!
//! - Resubscribe after reconnection
//! - Stop after receiving Nth puback
//!
//! ```ignore
//! #[tokio::main(core_threads = 1)]
//! async fn main() {
//!     let mut mqttoptions = MqttOptions::new("test-1", "localhost", 1883);
//!     let (requests_tx, requests_rx) = channel(10);
//!
//!     let mut eventloop = eventloop(mqttoptions, requests_rx);
//!
//!     // loop to reconnect and resume
//!     loop {
//!         let mut stream = eventloop.connect().await.unwrap();
//!         while let Some(notification) = stream.next().await {
//!             println!("Received = {:?}", item);
//!             match notification {
//!                 Notification::Connect => requests_tx.send(subscribe).unwrap(),
//!             }
//!         }
//!
//!         time::delay_for(Duration::from_secs(1)).await;
//!     }
//! }
//! ```

#![recursion_limit = "512"]

#[macro_use]
extern crate log;

use rumq_core::mqtt4::{MqttRead, MqttWrite, Packet};
use std::io::Cursor;
use std::time::Duration;

mod eventloop;
mod network;
mod state;

pub use eventloop::eventloop;
pub use eventloop::{EventLoopError, MqttEventLoop};
pub use state::MqttState;

pub use rumq_core::mqtt4::*;

/// Includes incoming packets from the network and other interesting events happening in the eventloop
#[derive(Debug)]
pub enum Notification {
    /// Incoming publish from the broker
    Publish(Publish),
    /// Incoming puback from the broker
    Puback(PacketIdentifier),
    /// Incoming pubrec from the broker
    Pubrec(PacketIdentifier),
    /// Incoming pubcomp from the broker
    Pubcomp(PacketIdentifier),
    /// Incoming suback from the broker
    Suback(Suback),
    /// Incoming unsuback from the broker
    Unsuback(PacketIdentifier),
    /// Eventloop error
    Abort(EventLoopError),
}

/// Requests by the client to mqtt event loop. Request are
/// handle one by one
#[derive(Debug)]
pub enum Request {
    Publish(Publish),
    Subscribe(Subscribe),
    Unsubscribe(Unsubscribe),
    Reconnect(Connect),
    Disconnect,
}

impl From<Publish> for Request {
    fn from(publish: Publish) -> Request {
        return Request::Publish(publish);
    }
}

impl From<Subscribe> for Request {
    fn from(subscribe: Subscribe) -> Request {
        return Request::Subscribe(subscribe);
    }
}

impl From<Unsubscribe> for Request {
    fn from(unsubscribe: Unsubscribe) -> Request {
        return Request::Unsubscribe(unsubscribe);
    }
}

/// From implementations for serialized requests
/// TODO Probably implement for io::Result<Vec<u8>> if possible?
impl From<Request> for Vec<u8> {
    fn from(request: Request) -> Vec<u8> {
        let mut packet = Cursor::new(Vec::new());
        let o = match request {
            Request::Reconnect(connect) => packet.mqtt_write(&Packet::Connect(connect)),
            Request::Publish(publish) => packet.mqtt_write(&Packet::Publish(publish)),
            Request::Subscribe(subscribe) => packet.mqtt_write(&Packet::Subscribe(subscribe)),
            _ => unimplemented!(),
        };

        o.unwrap();
        packet.into_inner()
    }
}

impl From<Vec<u8>> for Request {
    fn from(payload: Vec<u8>) -> Request {
        let mut payload = Cursor::new(payload);
        let packet = payload.mqtt_read().unwrap();

        match packet {
            Packet::Connect(connect) => Request::Reconnect(connect),
            Packet::Publish(publish) => Request::Publish(publish),
            Packet::Subscribe(subscribe) => Request::Subscribe(subscribe),
            _ => unimplemented!(),
        }
    }
}

/// Commands sent by the client to mqtt event loop. Commands
/// are of higher priority and will be `select`ed along with
/// [request]s
///
/// request: enum.Request.html
#[derive(Debug)]
pub enum Command {
    Pause,
    Resume,
}

/// Client authentication option for mqtt connect packet
#[derive(Clone, Debug)]
pub enum SecurityOptions {
    /// No authentication.
    None,
    /// Use the specified `(username, password)` tuple to authenticate.
    UsernamePassword(String, String),
}

// TODO: Should all the options be exposed as public? Drawback
// would be loosing the ability to panic when the user options
// are wrong (e.g empty client id) or aggressive (keep alive time)
/// Options to configure the behaviour of mqtt connection
#[derive(Clone, Debug)]
pub struct MqttOptions {
    /// broker address that you want to connect to
    broker_addr: String,
    /// broker port
    port: u16,
    /// keep alive time to send pingreq to broker when the connection is idle
    keep_alive: Duration,
    /// clean (or) persistent session
    clean_session: bool,
    /// client identifier
    client_id: String,
    /// connection method
    ca: Option<Vec<u8>>,
    /// tls client_authentication
    client_auth: Option<(Vec<u8>, Vec<u8>)>,
    /// alpn settings
    alpn: Option<Vec<Vec<u8>>>,
    /// username and password
    credentials: Option<(String, String)>,
    /// maximum packet size
    max_packet_size: usize,
    /// request (publish, subscribe) channel capacity
    request_channel_capacity: usize,
    /// notification channel capacity
    notification_channel_capacity: usize,
    /// Minimum delay time between consecutive outgoing packets
    throttle: Duration,
    /// maximum number of outgoing inflight messages
    inflight: usize,
    /// Last will that will be issued on unexpected disconnect
    last_will: Option<LastWill>,
}

impl MqttOptions {
    /// New mqtt options
    pub fn new<S: Into<String>, T: Into<String>>(id: S, host: T, port: u16) -> MqttOptions {
        let id = id.into();
        if id.starts_with(' ') || id.is_empty() {
            panic!("Invalid client id")
        }

        MqttOptions {
            broker_addr: host.into(),
            port,
            keep_alive: Duration::from_secs(60),
            clean_session: true,
            client_id: id,
            ca: None,
            client_auth: None,
            alpn: None,
            credentials: None,
            max_packet_size: 256 * 1024,
            request_channel_capacity: 10,
            notification_channel_capacity: 10,
            throttle: Duration::from_micros(0),
            inflight: 100,
            last_will: None,
        }
    }

    /// Broker address
    pub fn broker_address(&self) -> (String, u16) {
        (self.broker_addr.clone(), self.port)
    }

    pub fn set_last_will(&mut self, will: LastWill) -> &mut Self {
        self.last_will = Some(will);
        self
    }

    pub fn last_will(&mut self) -> Option<LastWill> {
        self.last_will.clone()
    }

    pub fn set_ca(&mut self, ca: Vec<u8>) -> &mut Self {
        self.ca = Some(ca);
        self
    }

    pub fn ca(&self) -> Option<Vec<u8>> {
        self.ca.clone()
    }

    pub fn set_client_auth(&mut self, cert: Vec<u8>, key: Vec<u8>) -> &mut Self {
        self.client_auth = Some((cert, key));
        self
    }

    pub fn client_auth(&self) -> Option<(Vec<u8>, Vec<u8>)> {
        self.client_auth.clone()
    }

    pub fn set_alpn(&mut self, alpn: Vec<Vec<u8>>) -> &mut Self {
        self.alpn = Some(alpn);
        self
    }

    pub fn alpn(&self) -> Option<Vec<Vec<u8>>> {
        self.alpn.clone()
    }

    /// Set number of seconds after which client should ping the broker
    /// if there is no other data exchange
    pub fn set_keep_alive(&mut self, secs: u16) -> &mut Self {
        if secs < 5 {
            panic!("Keep alives should be >= 5  secs");
        }

        self.keep_alive = Duration::from_secs(u64::from(secs));
        self
    }

    /// Keep alive time
    pub fn keep_alive(&self) -> Duration {
        self.keep_alive
    }

    /// Client identifier
    pub fn client_id(&self) -> String {
        self.client_id.clone()
    }

    /// Set packet size limit (in Kilo Bytes)
    pub fn set_max_packet_size(&mut self, sz: usize) -> &mut Self {
        self.max_packet_size = sz * 1024;
        self
    }

    /// Maximum packet size
    pub fn max_packet_size(&self) -> usize {
        self.max_packet_size
    }

    /// `clean_session = true` removes all the state from queues & instructs the broker
    /// to clean all the client state when client disconnects.
    ///
    /// When set `false`, broker will hold the client state and performs pending
    /// operations on the client when reconnection with same `client_id`
    /// happens. Local queue state is also held to retransmit packets after reconnection.
    pub fn set_clean_session(&mut self, clean_session: bool) -> &mut Self {
        self.clean_session = clean_session;
        self
    }

    /// Clean session
    pub fn clean_session(&self) -> bool {
        self.clean_session
    }

    /// Username and password
    pub fn set_credentials<S: Into<String>>(&mut self, username: S, password: S) -> &mut Self {
        self.credentials = Some((username.into(), password.into()));
        self
    }

    /// Security options
    pub fn credentials(&self) -> Option<(String, String)> {
        self.credentials.clone()
    }

    /// Set notification channel capacity
    pub fn set_notification_channel_capacity(&mut self, capacity: usize) -> &mut Self {
        self.notification_channel_capacity = capacity;
        self
    }

    /// Notification channel capacity
    pub fn notification_channel_capacity(&self) -> usize {
        self.notification_channel_capacity
    }

    /// Set request channel capacity
    pub fn set_request_channel_capacity(&mut self, capacity: usize) -> &mut Self {
        self.request_channel_capacity = capacity;
        self
    }

    /// Request channel capacity
    pub fn request_channel_capacity(&self) -> usize {
        self.request_channel_capacity
    }

    /// Enables throttling and sets outoing message rate to the specified 'rate'
    pub fn set_throttle(&mut self, duration: Duration) -> &mut Self {
        self.throttle = duration;
        self
    }

    /// Outgoing message rate
    pub fn throttle(&self) -> Duration {
        self.throttle
    }

    /// Set number of concurrent in flight messages
    pub fn set_inflight(&mut self, inflight: usize) -> &mut Self {
        if inflight == 0 {
            panic!("zero in flight is not allowed")
        }

        self.inflight = inflight;
        self
    }

    /// Number of concurrent in flight messages
    pub fn inflight(&self) -> usize {
        self.inflight
    }
}

#[cfg(test)]
mod test {
    use super::MqttOptions;

    #[test]
    #[should_panic]
    fn client_id_startswith_space() {
        let _mqtt_opts = MqttOptions::new(" client_a", "127.0.0.1", 1883).set_clean_session(true);
    }

    #[test]
    #[should_panic]
    fn no_client_id() {
        let _mqtt_opts = MqttOptions::new("", "127.0.0.1", 1883).set_clean_session(true);
    }
}