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
use std::{fmt, future::Future, marker::PhantomData, rc::Rc};
use ntex::io::IoBoxed;
use ntex::router::{IntoPattern, Router, RouterBuilder};
use ntex::service::{boxed, into_service, IntoService, Service};
use ntex::time::{sleep, Millis, Seconds};
use ntex::util::{Either, Ready};
use crate::error::MqttError;
use crate::io::Dispatcher;
use crate::v3::{codec, shared::MqttShared, sink::MqttSink, ControlResult, Publish};
use super::control::ControlMessage;
use super::dispatcher::create_dispatcher;
pub struct Client {
io: IoBoxed,
shared: Rc<MqttShared>,
keepalive: Seconds,
disconnect_timeout: Seconds,
session_present: bool,
max_receive: usize,
}
impl fmt::Debug for Client {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("v3::Client")
.field("keepalive", &self.keepalive)
.field("disconnect_timeout", &self.disconnect_timeout)
.field("session_present", &self.session_present)
.field("max_receive", &self.max_receive)
.finish()
}
}
impl Client {
pub(super) fn new(
io: IoBoxed,
shared: Rc<MqttShared>,
session_present: bool,
keepalive_timeout: Seconds,
disconnect_timeout: Seconds,
max_receive: usize,
) -> Self {
Client {
io,
shared,
session_present,
disconnect_timeout,
max_receive,
keepalive: keepalive_timeout,
}
}
}
impl Client {
#[inline]
pub fn sink(&self) -> MqttSink {
MqttSink::new(self.shared.clone())
}
#[inline]
pub fn session_present(&self) -> bool {
self.session_present
}
pub fn resource<T, F, U>(self, address: T, service: F) -> ClientRouter<U::Error, U::Error>
where
T: IntoPattern,
F: IntoService<U, Publish>,
U: Service<Publish, Response = ()> + 'static,
{
let mut builder = Router::build();
builder.path(address, 0);
let handlers = vec![boxed::service(service.into_service())];
ClientRouter {
builder,
handlers,
io: self.io,
shared: self.shared,
keepalive: self.keepalive,
disconnect_timeout: self.disconnect_timeout,
max_receive: self.max_receive,
_t: PhantomData,
}
}
pub async fn start_default(self) {
if self.keepalive.non_zero() {
ntex::rt::spawn(keepalive(MqttSink::new(self.shared.clone()), self.keepalive));
}
let dispatcher = create_dispatcher(
MqttSink::new(self.shared.clone()),
self.max_receive,
into_service(|pkt| Ready::Ok(Either::Right(pkt))),
into_service(|msg: ControlMessage<()>| Ready::<_, ()>::Ok(msg.disconnect())),
);
let _ = Dispatcher::new(self.io, self.shared.clone(), dispatcher)
.keepalive_timeout(Seconds::ZERO)
.disconnect_timeout(self.disconnect_timeout)
.await;
}
pub async fn start<F, S, E>(self, service: F) -> Result<(), MqttError<E>>
where
E: 'static,
F: IntoService<S, ControlMessage<E>> + 'static,
S: Service<ControlMessage<E>, Response = ControlResult, Error = E> + 'static,
{
if self.keepalive.non_zero() {
ntex::rt::spawn(keepalive(MqttSink::new(self.shared.clone()), self.keepalive));
}
let dispatcher = create_dispatcher(
MqttSink::new(self.shared.clone()),
self.max_receive,
into_service(|pkt| Ready::Ok(Either::Right(pkt))),
service.into_service(),
);
Dispatcher::new(self.io, self.shared.clone(), dispatcher)
.keepalive_timeout(Seconds::ZERO)
.disconnect_timeout(self.disconnect_timeout)
.await
}
pub fn into_inner(self) -> (IoBoxed, codec::Codec) {
(self.io, self.shared.codec.clone())
}
}
type Handler<E> = boxed::BoxService<Publish, (), E>;
pub struct ClientRouter<Err, PErr> {
builder: RouterBuilder<usize>,
handlers: Vec<Handler<PErr>>,
io: IoBoxed,
shared: Rc<MqttShared>,
keepalive: Seconds,
disconnect_timeout: Seconds,
max_receive: usize,
_t: PhantomData<Err>,
}
impl<Err, PErr> fmt::Debug for ClientRouter<Err, PErr> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("v3::ClientRouter")
.field("keepalive", &self.keepalive)
.field("disconnect_timeout", &self.disconnect_timeout)
.field("max_receive", &self.max_receive)
.finish()
}
}
impl<Err, PErr> ClientRouter<Err, PErr>
where
Err: From<PErr> + 'static,
PErr: 'static,
{
pub fn resource<T, F, S>(mut self, address: T, service: F) -> Self
where
T: IntoPattern,
F: IntoService<S, Publish>,
S: Service<Publish, Response = (), Error = PErr> + 'static,
{
self.builder.path(address, self.handlers.len());
self.handlers.push(boxed::service(service.into_service()));
self
}
pub async fn start_default(self) {
if self.keepalive.non_zero() {
ntex::rt::spawn(keepalive(MqttSink::new(self.shared.clone()), self.keepalive));
}
let dispatcher = create_dispatcher(
MqttSink::new(self.shared.clone()),
self.max_receive,
dispatch(self.builder.finish(), self.handlers),
into_service(|msg: ControlMessage<Err>| Ready::<_, Err>::Ok(msg.disconnect())),
);
let _ = Dispatcher::new(self.io, self.shared.clone(), dispatcher)
.keepalive_timeout(Seconds::ZERO)
.disconnect_timeout(self.disconnect_timeout)
.await;
}
pub async fn start<F, S>(self, service: F) -> Result<(), MqttError<Err>>
where
F: IntoService<S, ControlMessage<Err>>,
S: Service<ControlMessage<Err>, Response = ControlResult, Error = Err> + 'static,
{
if self.keepalive.non_zero() {
ntex::rt::spawn(keepalive(MqttSink::new(self.shared.clone()), self.keepalive));
}
let dispatcher = create_dispatcher(
MqttSink::new(self.shared.clone()),
self.max_receive,
dispatch(self.builder.finish(), self.handlers),
service.into_service(),
);
Dispatcher::new(self.io, self.shared.clone(), dispatcher)
.keepalive_timeout(Seconds::ZERO)
.disconnect_timeout(self.disconnect_timeout)
.await
}
}
fn dispatch<Err, PErr>(
router: Router<usize>,
handlers: Vec<Handler<PErr>>,
) -> impl Service<Publish, Response = Either<(), Publish>, Error = Err>
where
PErr: 'static,
Err: From<PErr>,
{
into_service(move |mut req: Publish| {
if let Some((idx, _info)) = router.recognize(req.topic_mut()) {
let fut = call(req, &handlers[*idx]);
Either::Left(async move { fut.await })
} else {
Either::Right(Ready::<_, Err>::Ok(Either::Right(req)))
}
})
}
fn call<S, Err, PErr>(
req: Publish,
srv: &S,
) -> impl Future<Output = Result<Either<(), Publish>, Err>>
where
S: Service<Publish, Response = (), Error = PErr>,
Err: From<PErr>,
{
let fut = srv.call(req);
async move {
match fut.await {
Ok(_) => Ok(Either::Left(())),
Err(err) => Err(err.into()),
}
}
}
async fn keepalive(sink: MqttSink, timeout: Seconds) {
log::debug!("start mqtt client keep-alive task");
let keepalive = Millis::from(timeout);
loop {
sleep(keepalive).await;
if !sink.ping() || !sink.is_open() {
log::debug!("mqtt client connection is closed, stopping keep-alive task");
break;
}
}
}