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
use std::marker::PhantomData;
use std::rc::Rc;

use actix_codec::{AsyncRead, AsyncWrite};
use actix_ioframe as ioframe;
use actix_service::{boxed, IntoNewService, IntoService, NewService, Service, ServiceExt};
use bytes::Bytes;
use futures::future::{err, Either};
use futures::{Future, Poll, Sink, Stream};
use mqtt_codec as mqtt;

use crate::cell::Cell;
use crate::default::{SubsNotImplemented, UnsubsNotImplemented};
use crate::dispatcher::{dispatcher, MqttState};
use crate::error::MqttError;
use crate::publish::Publish;
use crate::sink::MqttSink;
use crate::subs::{Subscribe, SubscribeResult, Unsubscribe};
use crate::State;

/// Mqtt client
#[derive(Clone)]
pub struct Client<Io, St> {
    client_id: string::String<Bytes>,
    clean_session: bool,
    protocol: mqtt::Protocol,
    keep_alive: u16,
    last_will: Option<mqtt::LastWill>,
    username: Option<string::String<Bytes>>,
    password: Option<Bytes>,
    inflight: usize,
    _t: PhantomData<(Io, St)>,
}

impl<Io, St> Client<Io, St>
where
    St: 'static,
{
    /// Create new client and provide client id
    pub fn new(client_id: string::String<Bytes>) -> Self {
        Client {
            client_id,
            clean_session: true,
            protocol: mqtt::Protocol::default(),
            keep_alive: 30,
            last_will: None,
            username: None,
            password: None,
            inflight: 15,
            _t: PhantomData,
        }
    }

    /// Mqtt protocol version
    pub fn protocol(mut self, val: mqtt::Protocol) -> Self {
        self.protocol = val;
        self
    }

    /// The handling of the Session state.
    pub fn clean_session(mut self, val: bool) -> Self {
        self.clean_session = val;
        self
    }

    /// A time interval measured in seconds.
    ///
    /// keep-alive is set to 30 seconds by default.
    pub fn keep_alive(mut self, val: u16) -> Self {
        self.keep_alive = val;
        self
    }

    /// Will Message be stored on the Server and associated with the Network Connection.
    ///
    /// by default last will value is not set
    pub fn last_will(mut self, val: mqtt::LastWill) -> Self {
        self.last_will = Some(val);
        self
    }

    /// Username can be used by the Server for authentication and authorization.
    pub fn username(mut self, val: string::String<Bytes>) -> Self {
        self.username = Some(val);
        self
    }

    /// Password can be used by the Server for authentication and authorization.
    pub fn password(mut self, val: Bytes) -> Self {
        self.password = Some(val);
        self
    }

    /// Number of in-flight concurrent messages.
    ///
    /// in-flight is set to 15 messages
    pub fn inflight(mut self, val: usize) -> Self {
        self.inflight = val;
        self
    }

    /// Set state service
    ///
    /// State service verifies connect ack packet and construct connection state.
    pub fn state<C, F>(self, state: F) -> ServiceBuilder<Io, St, C>
    where
        F: IntoService<C>,
        Io: AsyncRead + AsyncWrite,
        C: Service<Request = ConnectAck<Io>, Response = ConnectAckResult<Io, St>>,
        C::Error: 'static,
    {
        ServiceBuilder {
            state: Cell::new(state.into_service()),
            packet: mqtt::Connect {
                client_id: self.client_id,
                clean_session: self.clean_session,
                protocol: self.protocol,
                keep_alive: self.keep_alive,
                last_will: self.last_will,
                username: self.username,
                password: self.password,
            },
            subscribe: Rc::new(boxed::new_service(SubsNotImplemented::default())),
            unsubscribe: Rc::new(boxed::new_service(UnsubsNotImplemented::default())),
            disconnect: None,
            keep_alive: self.keep_alive.into(),
            inflight: self.inflight,
            _t: PhantomData,
        }
    }
}

pub struct ServiceBuilder<Io, St, C: Service> {
    state: Cell<C>,
    packet: mqtt::Connect,
    subscribe: Rc<
        boxed::BoxedNewService<
            St,
            Subscribe<St>,
            SubscribeResult,
            MqttError<C::Error>,
            MqttError<C::Error>,
        >,
    >,
    unsubscribe: Rc<
        boxed::BoxedNewService<
            St,
            Unsubscribe<St>,
            (),
            MqttError<C::Error>,
            MqttError<C::Error>,
        >,
    >,
    disconnect: Option<Cell<boxed::BoxedService<State<St>, (), MqttError<C::Error>>>>,
    keep_alive: u64,
    inflight: usize,

    _t: PhantomData<(Io, St, C)>,
}

impl<Io, St, C> ServiceBuilder<Io, St, C>
where
    St: 'static,
    Io: AsyncRead + AsyncWrite + 'static,
    C: Service<Request = ConnectAck<Io>, Response = ConnectAckResult<Io, St>> + 'static,
    C::Error: 'static,
{
    /// Service to execute for subscribe packet
    pub fn subscribe<F, Srv>(mut self, subscribe: F) -> Self
    where
        F: IntoNewService<Srv>,
        Srv: NewService<
                Config = St,
                Request = Subscribe<St>,
                Response = SubscribeResult,
                InitError = C::Error,
                Error = C::Error,
            > + 'static,
        Srv::Service: 'static,
    {
        self.subscribe = Rc::new(boxed::new_service(
            subscribe
                .into_new_service()
                .map_err(MqttError::Service)
                .map_init_err(MqttError::Service),
        ));
        self
    }

    /// Service to execute for unsubscribe packet
    pub fn unsubscribe<F, Srv>(mut self, unsubscribe: F) -> Self
    where
        F: IntoNewService<Srv>,
        Srv: NewService<
                Config = St,
                Request = Unsubscribe<St>,
                Response = (),
                InitError = C::Error,
                Error = C::Error,
            > + 'static,
        Srv::Service: 'static,
    {
        self.unsubscribe = Rc::new(boxed::new_service(
            unsubscribe
                .into_new_service()
                .map_err(MqttError::Service)
                .map_init_err(MqttError::Service),
        ));
        self
    }

    /// Service to execute on disconnect
    pub fn disconnect<UF, U>(mut self, srv: UF) -> Self
    where
        UF: IntoService<U>,
        U: Service<Request = State<St>, Response = (), Error = C::Error> + 'static,
    {
        self.disconnect = Some(Cell::new(boxed::service(
            srv.into_service().map_err(MqttError::Service),
        )));
        self
    }

    pub fn finish<F, T>(
        self,
        service: F,
    ) -> impl Service<Request = Io, Response = (), Error = MqttError<C::Error>>
    where
        F: IntoNewService<T>,
        T: NewService<
                Config = St,
                Request = Publish<St>,
                Response = (),
                Error = C::Error,
                InitError = C::Error,
            > + 'static,
    {
        ioframe::Builder::new()
            .service(ConnectService {
                connect: self.state,
                packet: self.packet,
                _t: PhantomData,
            })
            .finish(dispatcher(
                service
                    .into_new_service()
                    .map_err(MqttError::Service)
                    .map_init_err(MqttError::Service),
                self.subscribe,
                self.unsubscribe,
                self.keep_alive,
                self.inflight,
            ))
            .map_err(|e| match e {
                ioframe::ServiceError::Service(e) => e,
                ioframe::ServiceError::Encoder(e) => MqttError::Protocol(e),
                ioframe::ServiceError::Decoder(e) => MqttError::Protocol(e),
            })
    }
}

struct ConnectService<Io, St, C> {
    connect: Cell<C>,
    packet: mqtt::Connect,
    _t: PhantomData<(Io, St)>,
}

impl<Io, St, C> Service for ConnectService<Io, St, C>
where
    St: 'static,
    Io: AsyncRead + AsyncWrite + 'static,
    C: Service<Request = ConnectAck<Io>, Response = ConnectAckResult<Io, St>> + 'static,
    C::Error: 'static,
{
    type Request = ioframe::Connect<Io>;
    type Response = ioframe::ConnectResult<Io, MqttState<St>, mqtt::Codec>;
    type Error = MqttError<C::Error>;
    type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error>>;

    fn poll_ready(&mut self) -> Poll<(), Self::Error> {
        self.connect
            .get_mut()
            .poll_ready()
            .map_err(MqttError::Service)
    }

    fn call(&mut self, req: Self::Request) -> Self::Future {
        let mut srv = self.connect.clone();

        // send Connect packet
        Box::new(
            req.codec(mqtt::Codec::new())
                .send(mqtt::Packet::Connect(self.packet.clone()))
                .map_err(MqttError::Protocol)
                .and_then(|framed| {
                    framed
                        .into_future()
                        .map_err(|(e, _)| MqttError::Protocol(e))
                })
                .and_then(move |(packet, framed)| match packet {
                    Some(mqtt::Packet::ConnectAck {
                        session_present,
                        return_code,
                    }) => {
                        let sink = MqttSink::new(framed.sink().clone());
                        let ack = ConnectAck {
                            sink,
                            session_present,
                            return_code,
                            io: framed,
                        };
                        Either::A(
                            srv.get_mut()
                                .call(ack)
                                .map_err(MqttError::Service)
                                .map(|ack| ack.io.state(ack.state)),
                        )
                    }
                    Some(p) => {
                        Either::B(err(MqttError::Unexpected(p, "Expected CONNECT-ACK packet")))
                    }
                    None => Either::B(err(MqttError::Disconnected)),
                }),
        )
    }
}

pub struct ConnectAck<Io> {
    io: ioframe::ConnectResult<Io, (), mqtt::Codec>,
    sink: MqttSink,
    session_present: bool,
    return_code: mqtt::ConnectCode,
}

impl<Io> ConnectAck<Io> {
    #[inline]
    /// Indicates whether there is already stored Session state
    pub fn session_present(&self) -> bool {
        self.session_present
    }

    #[inline]
    /// Connect return code
    pub fn return_code(&self) -> mqtt::ConnectCode {
        self.return_code
    }

    #[inline]
    /// Mqtt client sink object
    pub fn sink(&self) -> &MqttSink {
        &self.sink
    }

    #[inline]
    /// Set connection state and create result object
    pub fn state<St>(self, state: St) -> ConnectAckResult<Io, St> {
        ConnectAckResult {
            io: self.io,
            state: MqttState::new(state, self.sink),
        }
    }
}

impl<Io> futures::Stream for ConnectAck<Io>
where
    Io: AsyncRead + AsyncWrite,
{
    type Item = mqtt::Packet;
    type Error = mqtt::ParseError;

    fn poll(&mut self) -> futures::Poll<Option<Self::Item>, Self::Error> {
        self.io.poll()
    }
}

impl<Io> futures::Sink for ConnectAck<Io>
where
    Io: AsyncRead + AsyncWrite,
{
    type SinkItem = mqtt::Packet;
    type SinkError = mqtt::ParseError;

    fn start_send(
        &mut self,
        item: Self::SinkItem,
    ) -> futures::StartSend<Self::SinkItem, Self::SinkError> {
        self.io.start_send(item)
    }

    fn poll_complete(&mut self) -> futures::Poll<(), Self::SinkError> {
        self.io.poll_complete()
    }

    fn close(&mut self) -> futures::Poll<(), Self::SinkError> {
        self.io.close()
    }
}

pub struct ConnectAckResult<Io, St> {
    state: MqttState<St>,
    io: ioframe::ConnectResult<Io, (), mqtt::Codec>,
}

impl<Io, St> futures::Stream for ConnectAckResult<Io, St>
where
    Io: AsyncRead + AsyncWrite,
{
    type Item = mqtt::Packet;
    type Error = mqtt::ParseError;

    fn poll(&mut self) -> futures::Poll<Option<Self::Item>, Self::Error> {
        self.io.poll()
    }
}

impl<Io, St> futures::Sink for ConnectAckResult<Io, St>
where
    Io: AsyncRead + AsyncWrite,
{
    type SinkItem = mqtt::Packet;
    type SinkError = mqtt::ParseError;

    fn start_send(
        &mut self,
        item: Self::SinkItem,
    ) -> futures::StartSend<Self::SinkItem, Self::SinkError> {
        self.io.start_send(item)
    }

    fn poll_complete(&mut self) -> futures::Poll<(), Self::SinkError> {
        self.io.poll_complete()
    }

    fn close(&mut self) -> futures::Poll<(), Self::SinkError> {
        self.io.close()
    }
}