Skip to main content

cls_eedi/transport/
mqtt.rs

1//! Synchronous MQTT 5 binding. Drive one session from a dedicated blocking loop.
2//! Applications choose their reconnect backoff and reconcile uncertain commands
3//! by reading the device after each new `Ready` event.
4use super::{Role, RouteError, Routes, Target};
5use crate::wire::{Ack, Message, Payload, Status, WireError};
6use futures_util::{stream::BoxStream, StreamExt};
7use rumqttc::mqttbytes::v5::{LastWill, PubAckReason, SubscribeFilter, SubscribeReasonCode};
8use rumqttc::mqttbytes::QoS;
9use rumqttc::tokio_rustls::rustls::{
10    self,
11    pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer},
12    ClientConfig, RootCertStore,
13};
14use rumqttc::{AsyncClient, ConnectionError, Event, Incoming, MqttOptions, PublishOptions};
15use rumqttc::{DisconnectProperties, DisconnectReasonCode, Outgoing, Transport};
16use std::net::IpAddr;
17use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
18use thiserror::Error;
19use uuid::Uuid;
20
21/// Broker settings. Credentials and private keys stay out of Debug output.
22#[derive(Clone)]
23pub struct Broker(MqttOptions);
24
25impl Broker {
26    /// Verify the broker against PEM trust anchors. Supply a PEM certificate chain
27    /// and private key when mutual TLS is required. TLS uses [`crate::CRYPTO_PROVIDER`].
28    pub fn tls(
29        client_id: &str,
30        host: &str,
31        port: u16,
32        ca: Vec<u8>,
33        identity: Option<(Vec<u8>, Vec<u8>)>,
34    ) -> Result<Self, Error> {
35        if ca.is_empty() || host.is_empty() {
36            return Err(Error::Config);
37        }
38        let mut options = Self::options(client_id, host, port)?;
39        let mut roots = RootCertStore::empty();
40        for cert in CertificateDer::pem_slice_iter(&ca) {
41            roots
42                .add(cert.map_err(|_| Error::TrustAnchors)?)
43                .map_err(|_| Error::TrustAnchors)?;
44        }
45        if roots.is_empty() {
46            return Err(Error::TrustAnchors);
47        }
48        // Use the compiled provider; never install or read the process default.
49        #[cfg(feature = "aws-lc-rs")]
50        let provider = rustls::crypto::aws_lc_rs::default_provider();
51        #[cfg(all(feature = "ring", not(feature = "aws-lc-rs")))]
52        let provider = rustls::crypto::ring::default_provider();
53        let config = ClientConfig::builder_with_provider(provider.into())
54            .with_safe_default_protocol_versions()
55            .map_err(|_| Error::Config)?
56            .with_root_certificates(roots);
57        let config = if let Some((cert, key)) = identity {
58            let chain = CertificateDer::pem_slice_iter(&cert)
59                .collect::<Result<Vec<_>, _>>()
60                .map_err(|_| Error::Identity)?;
61            let key = PrivateKeyDer::from_pem_slice(&key).map_err(|_| Error::Identity)?;
62            config
63                .with_client_auth_cert(chain, key)
64                .map_err(|_| Error::Identity)?
65        } else {
66            config.with_no_client_auth()
67        };
68        options.set_transport(Transport::tls_with_config(config.into()));
69        Ok(Self(options))
70    }
71
72    /// Plaintext local testing or a separately protected tunnel ending on loopback.
73    pub fn loopback(client_id: &str, address: IpAddr, port: u16) -> Result<Self, Error> {
74        if !address.is_loopback() {
75            return Err(Error::Config);
76        }
77        Self::options(client_id, &address.to_string(), port).map(Self)
78    }
79
80    fn options(client_id: &str, host: &str, port: u16) -> Result<MqttOptions, Error> {
81        if client_id.is_empty()
82            || client_id.len() > u16::MAX.into()
83            || client_id.contains('\0')
84            || port == 0
85        {
86            return Err(Error::Config);
87        }
88        let mut options = MqttOptions::new(client_id, (host, port));
89        options
90            .set_keep_alive(15)
91            .set_clean_start(true)
92            .set_session_expiry_interval(Some(0))
93            .set_receive_maximum(Some(32))
94            .set_outgoing_inflight_upper_limit(32)
95            .set_max_packet_size(Some(256 * 1024));
96        Ok(options)
97    }
98
99    /// Add broker credentials for deployments using password authentication.
100    pub fn credentials(mut self, username: String, password: String) -> Result<Self, Error> {
101        if username.len() > u16::MAX.into()
102            || password.len() > u16::MAX.into()
103            || username.contains('\0')
104        {
105            return Err(Error::Config);
106        }
107        self.0.set_credentials(username, password);
108        Ok(self)
109    }
110}
111
112#[derive(Debug, Error)]
113pub enum Error {
114    #[error("invalid broker address, credential, client ID or trust settings")]
115    Config,
116    #[error("invalid CA trust anchors; supply PEM certificates")]
117    TrustAnchors,
118    #[error("invalid client identity; supply a PEM certificate chain and matching private key")]
119    Identity,
120    #[error("session is offline or waiting for subscription acknowledgement")]
121    NotReady,
122    #[error("outgoing queue is full")]
123    Busy,
124    #[error("broker connection failed; reconnect and reconcile outstanding commands")]
125    Connection(#[source] Box<rumqttc::ConnectionError>),
126    #[error("broker declined the QoS 1 subscription")]
127    Subscription,
128    #[error("broker rejected publication with packet ID {0} ({1:?})")]
129    Publication(u16, PubAckReason),
130    #[error("graceful MQTT disconnect timed out; pending outcomes are uncertain")]
131    DrainTimeout,
132    #[error("could not initialize the MQTT I/O runtime")]
133    Runtime(#[source] std::io::Error),
134    #[error("MQTT event loop closed")]
135    Closed,
136    #[error("system clock cannot supply a Unix timestamp")]
137    Clock,
138    #[error(transparent)]
139    Route(#[from] RouteError),
140    #[error(transparent)]
141    Wire(#[from] WireError),
142}
143
144/// Events visible to the application. MQTT delivery is distinct from a CLS.EEDI ack.
145#[derive(Debug)]
146pub enum SessionEvent {
147    Ready,
148    Message {
149        target: Target,
150        message: Box<Message>,
151    },
152    /// A bounded, authorized route had an invalid payload. The wire error can
153    /// carry diagnostic context. The binding queues applicable negative acknowledgements.
154    Invalid {
155        target: Target,
156        error: WireError,
157    },
158    /// The broker accepted the publication but found no matching subscriptions.
159    NoSubscribers {
160        packet_id: u16,
161    },
162}
163
164/// One MQTT client for a single provisioned route pair and role.
165pub struct Session {
166    broker: Broker,
167    role: Role,
168    routes: Routes,
169    source: String,
170    client: AsyncClient,
171    events: BoxStream<'static, Result<Event, ConnectionError>>,
172    runtime: tokio::runtime::Runtime,
173    ready: bool,
174    failed: bool,
175}
176
177impl Session {
178    pub fn new(
179        broker: Broker,
180        role: Role,
181        routes: Routes,
182        source: impl Into<String>,
183    ) -> Result<Self, Error> {
184        let source = source.into();
185        let mut options = broker.0.clone();
186        if role == Role::LocalDevice {
187            let topic = routes.topic(role, &Target::Presence)?;
188            let offline = status(&source, None).encode()?;
189            options.set_last_will(LastWill::new(topic, offline, QoS::AtLeastOnce, true, None));
190        }
191        let (client, event_loop) = AsyncClient::builder(options)
192            .capacity(64)
193            .try_build()
194            .map_err(|_| Error::Config)?;
195        Ok(Self {
196            broker,
197            role,
198            routes,
199            source,
200            client,
201            events: event_loop.into_stream().boxed(),
202            runtime: tokio::runtime::Builder::new_current_thread()
203                .enable_all()
204                .build()
205                .map_err(Error::Runtime)?,
206            ready: false,
207            failed: false,
208        })
209    }
210
211    /// Start a clean connection and provision a new last-will ID. Prior queued
212    /// requests have uncertain outcomes. Reconcile them through the role engine.
213    pub fn reconnect(&mut self) -> Result<(), Error> {
214        *self = Self::new(
215            self.broker.clone(),
216            self.role,
217            self.routes.clone(),
218            self.source.clone(),
219        )?;
220        Ok(())
221    }
222
223    /// Drain queued traffic within `timeout` and send MQTT DISCONNECT. A local
224    /// device asks the broker to publish its retained offline will. Dropping a
225    /// live session exercises the broker's unexpected-disconnect handling.
226    pub fn disconnect(mut self, timeout: Duration) -> Result<(), Error> {
227        if !self.ready || self.failed {
228            return Err(Error::NotReady);
229        }
230        let reason = match self.role {
231            Role::Backend => DisconnectReasonCode::NormalDisconnection,
232            Role::LocalDevice => DisconnectReasonCode::DisconnectWithWillMessage,
233        };
234        let properties = DisconnectProperties {
235            session_expiry_interval: None,
236            reason_string: None,
237            user_properties: Vec::new(),
238            server_reference: None,
239        };
240        self.client
241            .try_disconnect_with_properties(reason, properties)
242            .map_err(|_| Error::Busy)?;
243        let start = Instant::now();
244        loop {
245            let remaining = timeout
246                .checked_sub(start.elapsed())
247                .ok_or(Error::DrainTimeout)?;
248            match self.next_event(remaining)? {
249                Some(Event::Outgoing(Outgoing::Disconnect)) => return Ok(()),
250                Some(Event::Incoming(Incoming::PubAck(ack)))
251                    if !matches!(
252                        ack.reason,
253                        PubAckReason::Success | PubAckReason::NoMatchingSubscribers
254                    ) =>
255                {
256                    return Err(Error::Publication(ack.pkid, ack.reason))
257                }
258                Some(_) => {}
259                None => return Err(Error::DrainTimeout),
260            }
261        }
262    }
263
264    /// Enqueue an application message at QoS 1. Only presence is retained.
265    pub fn publish(&self, target: &Target, message: &Message) -> Result<(), Error> {
266        if !self.ready || self.failed {
267            return Err(Error::NotReady);
268        }
269        self.enqueue(target, message)
270    }
271
272    fn enqueue(&self, target: &Target, message: &Message) -> Result<(), Error> {
273        Routes::check_kind(self.role, target, message.payload.kind())?;
274        let topic = self.routes.topic(self.role, target)?;
275        self.client
276            .try_publish(
277                topic,
278                message.encode()?,
279                PublishOptions::at_least_once().retain(target == &Target::Presence),
280            )
281            .map_err(|_| Error::Busy)
282    }
283
284    // The stream owns the in-progress EventLoop::poll future. Timing out a single
285    // next() wait preserves that future, including an outstanding TLS/CONNACK wait.
286    fn next_event(&mut self, budget: Duration) -> Result<Option<Event>, Error> {
287        let result = self
288            .runtime
289            .block_on(async { tokio::time::timeout(budget, self.events.next()).await });
290        match result {
291            Err(_) => Ok(None),
292            Ok(Some(Ok(event))) => Ok(Some(event)),
293            Ok(Some(Err(e))) => {
294                self.failed = true;
295                Err(Error::Connection(Box::new(e)))
296            }
297            Ok(None) => {
298                self.failed = true;
299                Err(Error::Closed)
300            }
301        }
302    }
303
304    /// Advance one MQTT event. `None` means a transport-only event or elapsed timeout.
305    /// A later poll resumes an in-progress connection, including its TLS and MQTT
306    /// handshakes. Route and wire rejections leave the connection usable.
307    pub fn poll(&mut self, timeout: Duration) -> Result<Option<SessionEvent>, Error> {
308        if self.failed {
309            return Err(Error::Closed);
310        }
311        let Some(event) = self.next_event(timeout)? else {
312            return Ok(None);
313        };
314        match event {
315            Event::Incoming(Incoming::ConnAck(_)) => {
316                let path = format!("{}/#", self.routes.base(self.role.peer()));
317                // Retain As Published preserves the live publisher's RETAIN bit
318                // as well as retained messages delivered after subscription.
319                let mut filter = SubscribeFilter::new(path, QoS::AtLeastOnce);
320                filter.preserve_retain = true;
321                self.client
322                    .try_subscribe_many([filter])
323                    .map_err(|_| Error::Busy)?;
324                Ok(None)
325            }
326            Event::Incoming(Incoming::SubAck(ack)) => {
327                if ack.return_codes != [SubscribeReasonCode::Success(QoS::AtLeastOnce)] {
328                    self.failed = true;
329                    return Err(Error::Subscription);
330                }
331                self.ready = true;
332                if self.role == Role::LocalDevice {
333                    let timestamp = SystemTime::now()
334                        .duration_since(UNIX_EPOCH)
335                        .map_err(|_| Error::Clock)?
336                        .as_secs()
337                        .try_into()
338                        .map_err(|_| Error::Clock)?;
339                    self.publish(&Target::Presence, &status(&self.source, Some(timestamp)))?;
340                }
341                Ok(Some(SessionEvent::Ready))
342            }
343            Event::Incoming(Incoming::Publish(packet)) => {
344                let topic =
345                    std::str::from_utf8(&packet.topic).map_err(|_| RouteError::Unprovisioned)?;
346                let target = self.routes.receive(self.role, topic, packet.retain)?;
347                let message = match Message::decode_for_reply(&packet.payload) {
348                    Ok(message) => message,
349                    Err(failure) => {
350                        if let Some(reply) = failure.reply {
351                            Routes::check_kind(self.role.peer(), &target, reply.kind)?;
352                            let ack = Message::new(
353                                Uuid::new_v4().to_string(),
354                                &self.source,
355                                Payload::Ack(Ack {
356                                    error_number: reply.error_number,
357                                }),
358                            )
359                            .related_to(reply.id);
360                            let reply_target = match &target {
361                                Target::Presence => &Target::Local,
362                                other => other,
363                            };
364                            self.enqueue(reply_target, &ack)?;
365                        }
366                        return Ok(Some(SessionEvent::Invalid {
367                            target,
368                            error: failure.error,
369                        }));
370                    }
371                };
372                Routes::check_kind(self.role.peer(), &target, message.payload.kind())?;
373                Ok(Some(SessionEvent::Message {
374                    target,
375                    message: Box::new(message),
376                }))
377            }
378            Event::Incoming(Incoming::PubAck(ack)) => match ack.reason {
379                PubAckReason::Success => Ok(None),
380                PubAckReason::NoMatchingSubscribers => Ok(Some(SessionEvent::NoSubscribers {
381                    packet_id: ack.pkid,
382                })),
383                reason => Err(Error::Publication(ack.pkid, reason)),
384            },
385            _ => Ok(None),
386        }
387    }
388}
389
390fn status(source: &str, timestamp: Option<i64>) -> Message {
391    Message::new(
392        Uuid::new_v4().to_string(),
393        source,
394        Payload::LocalDeviceStatus(Status {
395            connected: timestamp.is_some(),
396            timestamp,
397        }),
398    )
399}