Skip to main content

Client

Struct Client 

pub struct Client<S> {
    state: ConnectionState,
    session: S,
    capabilities: ServerCapabilities,
    keep_alive: u16,
    send_quota: u16,
    recv_quota: u16,
    recv_max: u16,
    next_packet_id: PacketId,
    clean_start: bool,
    inbound_alias_max: Option<NonZeroU16>,
    outbound_aliases_stale: bool,
}
Expand description

State machine for a sans-io MQTT v5 client.

The caller is responsible for:

  • Encoding outgoing packets and writing them to the transport.
  • Decoding incoming packets and feeding them to handle_packet.
  • Driving timers for keep-alive (see keep_alive).

Fields§

§state: ConnectionState§session: S§capabilities: ServerCapabilities§keep_alive: u16

Keep-alive interval in seconds as negotiated.

§send_quota: u16

Number of QoS > 0 publishes we can still send before hitting the server’s Receive Maximum.

§recv_quota: u16

Number of QoS > 0 messages the client can still accept from the server before the server would violate our Receive Maximum.

§recv_max: u16

The Receive Maximum value we advertise in CONNECT (§3.1.2.11.4). u16::MAX (65 535) means we never sent the property.

§next_packet_id: PacketId

Monotonic packet ID counter (1..=65535, wraps around skipping 0).

§clean_start: bool

Whether the last CONNECT used Clean Start = 1.

§inbound_alias_max: Option<NonZeroU16>

The Topic Alias Maximum we advertise in CONNECT (§3.1.2.11.5). None (the default) means inbound topic aliases are not permitted.

§outbound_aliases_stale: bool

Whether the outbound alias table still holds the mappings of an earlier connection (§3.3.2.3.4).

Implementations§

§

impl<S: State> Client<S>

pub fn poll_transmit<B, A>( &mut self, out: &mut PacketWriter<B>, aliases: &mut A, on_event: &mut dyn FnMut(TransmitEvent), ) -> Result<(), DrainError<B::Error, A::Error>>

Drains pending SUBSCRIBE/UNSUBSCRIBE groups, then the outbox and pending PUBRELs, onto out. This is the only outbound transmit path. Subscriptions go first so they precede publishes accepted together with them.

Resolves topic aliases via aliases, enforces the server’s Maximum Packet Size (§3.1.2.11.6), and stays within the send quota. on_event receives the outcome of each packet. An over-large packet (or whole group) is dropped as TooLarge.

§Errors

Returns DrainError::Buffer if out cannot take the next packet, and DrainError::Alias if aliases cannot store an alias. The drain stops there. The session keeps the packets not yet written.

pub fn transmit_qos0<B, A>( &mut self, out: &mut PacketWriter<B>, aliases: &mut A, topic: &Topic, payload: &Payload, retain: bool, properties: &PublishProperties, ) -> Result<(), TransmitError<B::Error, A::Error>>

Encodes a QoS 0 (fire-and-forget) PUBLISH into out.

Resolves the topic alias and enforces the server’s limits, like poll_transmit. QoS 0 has no session state, so the PUBLISH is written immediately.

§Errors

Returns TransmitError::Client with ClientError::InvalidState if not connected, or ClientError::Unsupported for a retained PUBLISH the server does not support. Returns TransmitError::Write if the packet exceeds the server’s Maximum Packet Size or out cannot take it, and TransmitError::Alias if aliases cannot store the alias. The packet is dropped in every case.

fn prepare_outbound_aliases<A: OutboundAliasTable + ?Sized>( &mut self, aliases: &mut A, )

Clears aliases if they still belong to an earlier connection.

fn drain_subscription_groups<B>( &mut self, out: &mut PacketWriter<B>, max_packet_size: Option<NonZeroU32>, on_event: &mut dyn FnMut(TransmitEvent), ) -> Result<(), B::Error>
where B: ByteBuffer,

Sends every pending SUBSCRIBE/UNSUBSCRIBE group not already in flight, oldest first, marking each in flight once written. A group exceeding max_packet_size can never be sent: it is removed and reported as TooLarge so it cannot wedge the queue. Then sends one SUBSCRIBE for each filter waiting to be resubscribed, while packet identifiers are free.

§

impl<S: State> Client<S>

pub fn new(session: S) -> Self

Creates a new client that uses session as its session state backend.

pub const fn connection_state(&self) -> ConnectionState

Current connection state.

pub const fn capabilities(&self) -> &ServerCapabilities

Server capabilities from the most recent CONNACK.

pub const fn keep_alive(&self) -> u16

Effective keep-alive interval in seconds.

pub const fn send_quota(&self) -> u16

Remaining send quota for QoS > 0 publishes.

pub const fn session(&self) -> &S

Shared reference to the session state backend.

pub const fn session_mut(&mut self) -> &mut S

Mutable reference to the session state backend.

pub fn connect_sent(&mut self, connect: &Connect<'_>) -> Result<(), ClientError>

Records that connect has been sent.

Mirrors the Clean Start flag, keep-alive, Receive Maximum (§3.1.2.11.3), and Topic Alias Maximum (§3.1.2.11.5) from the packet that actually went on the wire.

The session is not changed, even with Clean Start set. A retry after a failed connect must keep what was stored in the meantime. To start a new session, apply Modify::Clear to the session once before the first connect.

§Errors

Returns ClientError::InvalidState if the client is not disconnected.

pub fn connection_lost(&mut self)

Notifies the state machine that the transport has been lost.

Resets connection-level state (quotas, capabilities) while preserving session state for reconnection. In-flight SUBSCRIBE/UNSUBSCRIBE entries are kept and re-sent on the next connect: the per-connection in-flight markers are cleared by reset_in_flight when the next CONNACK arrives.

pub fn session_lost(&mut self, on_failed_pubrel: &mut dyn FnMut(PacketId))

Discards the session state the server forgot (§4.1).

Removes every PUBREL-pending QoS 2 flow and reports each id through on_failed_pubrel so the driver can fail its future. Also resets the outbox was_sent flags (DUP = 0) and clears incoming QoS 2 tracking. Confirmed subscriptions become Resubscribing. poll_transmit sends them again as packet identifiers become free.

The I/O driver must call this on a CONNACK with session_present: false, before draining the session onto the new connection.

pub fn handle_packet<'a, A: InboundAliasTable + ?Sized>( &mut self, packet: &Packet<'a>, aliases: &'a mut A, ) -> Result<HandleOutcome<'a>, HandleError<A::Error, S::Error>>

Processes an incoming decoded packet from the server.

aliases holds the inbound topic aliases of the current connection. Protocol violations by the server are reported as a Response::Disconnect to send (§4.13), not as an error.

§Errors

Returns HandleError::Client with ClientError::InvalidState if the packet is not valid in the current connection state (e.g. a CONNACK while not connecting). Returns HandleError::Alias if aliases cannot store an alias the server establishes.

fn handle_connack<'a, A: InboundAliasTable + ?Sized>( &mut self, connack: &Connack<'a>, aliases: &mut A, ) -> Result<HandleOutcome<'a>, ClientError>

fn handle_publish<'a, A: InboundAliasTable + ?Sized>( &mut self, publish: &ReceivedPublish<'a>, aliases: &'a mut A, ) -> Result<HandleOutcome<'a>, HandleError<A::Error, S::Error>>

fn require_connected(&self) -> Result<(), ClientError>

Errors with ClientError::InvalidState unless the client is currently connected.

fn handle_puback<'a>( &mut self, ack: Ack<'_>, ) -> Result<HandleOutcome<'a>, ClientError>

fn handle_pubrec<'a>( &mut self, ack: Ack<'_>, ) -> Result<HandleOutcome<'a>, StoreError<S::Error>>

fn handle_pubrel<'a>( &mut self, ack: Ack<'_>, ) -> Result<HandleOutcome<'a>, ClientError>

fn handle_pubcomp<'a>( &mut self, ack: Ack<'_>, ) -> Result<HandleOutcome<'a>, ClientError>

fn handle_suback<'a>( &mut self, suback: &Suback<'a>, ) -> Result<HandleOutcome<'a>, ClientError>

fn handle_unsuback<'a>( &mut self, unsuback: &Unsuback<'a>, ) -> Result<HandleOutcome<'a>, ClientError>

fn lacks_reason_codes(&self, packet_id: PacketId, len: usize) -> bool

Whether an ack with len reason codes lacks the code of a filter still pending under packet_id. Every filter of the request needs one (§3.9.3, §3.11.3).

fn handle_pingresp<'a>(&self) -> Result<HandleOutcome<'a>, ClientError>

const fn handle_disconnect<'a>( &mut self, disconnect: &Disconnect<'a>, ) -> HandleOutcome<'a>

const fn handle_auth<'a>() -> HandleOutcome<'a>

pub fn prepare_publish( &mut self, qos: AckQoS, topic: &Topic, payload: &Payload, retain: bool, properties: &PublishProperties, ) -> Result<PacketId, StoreError<S::Error>>

Allocates a packet identifier and stores an outgoing QoS 1 or QoS 2 publish in the session for potential retransmission.

Returns the allocated packet_id. The caller must construct and send the PUBLISH packet using this ID. The packet_id is also the stable handle the driver uses to correlate the eventual PUBACK/PUBCOMP with the user-facing completion future (§4.4).

§Errors

Returns ClientError::InvalidState if not connected, ClientError::Unsupported if the server does not support the request, or ClientError::PacketIdExhausted if all packet identifiers are in use.

This does not consume send quota: the message is stored in the outbox and the send quota is consumed only when it is drained onto the wire by poll_transmit. The Receive Maximum limits in-flight messages. It does not limit how many may be queued.

pub fn store_offline_publish( &mut self, qos: AckQoS, topic: &Topic, payload: &Payload, retain: bool, properties: &PublishProperties, ) -> Result<PacketId, StoreError<S::Error>>

Stores an outgoing QoS 1 or QoS 2 publish while not connected, so it can be drained when a connection is next established.

Unlike prepare_publish, this works in any connection state and does not apply capability checks, because the server’s capabilities are unknown while offline. The message is recorded as durable session state immediately.

§Errors

Returns ClientError::PacketIdExhausted if all packet identifiers are in use.

fn store_publish_entry( &mut self, qos: AckQoS, topic: &Topic, payload: &Payload, retain: bool, properties: &PublishProperties, ) -> Result<PacketId, StoreError<S::Error>>

Allocates a packet id and records an outbox entry, the shared core of the connected and offline publish-store paths.

pub fn prepare_subscribe<'a, I>( &mut self, filters: I, subscription_id: Option<NonZeroVbi>, ) -> Result<PacketId, StoreError<S::Error>>

Allocates a packet identifier for a SUBSCRIBE and records each filter as an in-flight subscription under it.

filters are the topic filters and their options; subscription_id is the optional SUBSCRIBE-level identifier. The caller builds and sends the SUBSCRIBE using the returned id. The entries resolve when handle_packet sees the matching SUBACK.

§Errors

Returns ClientError::InvalidState if not connected, an error from ServerCapabilities::check_subscribe if the server does not support the subscription, or ClientError::PacketIdExhausted if all identifiers are in use.

pub fn store_offline_subscribe<'a, I>( &mut self, filters: I, subscription_id: Option<NonZeroVbi>, ) -> Result<PacketId, StoreError<S::Error>>

Records an in-flight SUBSCRIBE while not connected, so it is sent when a connection is next established.

Like prepare_subscribe but works in any connection state. The server’s capabilities are unknown while offline, so they are checked when the SUBSCRIBE is sent. A group the server does not support is then dropped and reported as TransmitEvent::Unsupported.

§Errors

Returns ClientError::PacketIdExhausted if all identifiers are in use.

fn record_subscribe<'a>( &mut self, filters: impl Iterator<Item = (&'a TopicFilter, SubscriptionOptions)> + Clone, subscription_id: Option<NonZeroVbi>, ) -> Result<PacketId, StoreError<S::Error>>

Allocates a packet id and records each filter as an in-flight SUBSCRIBE. This is the shared core of the connected (prepare_subscribe) and offline (store_offline_subscribe) paths.

pub fn prepare_unsubscribe<'a, I>( &mut self, filters: I, ) -> Result<PacketId, StoreError<S::Error>>
where I: IntoIterator<Item = &'a TopicFilter>, I::IntoIter: Clone,

Allocates a packet identifier for an UNSUBSCRIBE and records each filter as in-flight unsubscribing under it.

The entries resolve when handle_packet sees the matching UNSUBACK.

§Errors

Returns ClientError::InvalidState if not connected, or ClientError::PacketIdExhausted if all identifiers are in use.

pub fn store_offline_unsubscribe<'a, I>( &mut self, filters: I, ) -> Result<PacketId, StoreError<S::Error>>
where I: IntoIterator<Item = &'a TopicFilter>, I::IntoIter: Clone,

Records an in-flight UNSUBSCRIBE while not connected.

§Errors

Returns ClientError::PacketIdExhausted if all identifiers are in use.

fn record_unsubscribe<'a>( &mut self, filters: impl Iterator<Item = &'a TopicFilter> + Clone, ) -> Result<PacketId, StoreError<S::Error>>

Allocates a packet id and records each filter as an in-flight UNSUBSCRIBE, the shared core of the connected (prepare_unsubscribe) and offline (store_offline_unsubscribe) paths.

fn record_group<'a, T: Copy>( &mut self, filters: impl Iterator<Item = (&'a TopicFilter, T)> + Clone, state: impl Fn(PacketId, T, Option<FilterState>) -> FilterState, ) -> Result<PacketId, StoreError<S::Error>>

Allocates a packet id and records filters under it, each in the state state returns for its request data and current state.

A filter named twice is recorded once, with the data of its last occurrence. The session is unchanged if it has no room. Filters new to the session are stored first. Existing filters then only change state, which never needs new storage.

pub fn forget_received(&mut self, delivery: Delivery)

Forgets a received message the caller could not deliver.

Call it instead of sending the acknowledgement from handle_packet. For QoS 2 the session then no longer records the packet id, so the server’s retransmission is delivered as a new message.

pub fn cancel_outgoing_qos1(&mut self, packet_id: PacketId)

Cancels a QoS 1 publish previously prepared by prepare_publish.

Removes the session entry. Send quota is restored only if the entry had already been put on the wire, since a prepared-but-never-drained publish did not consume a slot. Crediting it would let the in-flight window exceed the server’s Receive Maximum (§4.9). Use it to release the reservation of a publish that failed to be enqueued/transmitted, without going through the wire/PUBACK round trip.

pub fn cancel_outgoing_qos2(&mut self, packet_id: PacketId)

Cancels a QoS 2 publish previously prepared by prepare_publish.

Removes the session entry. As with cancel_outgoing_qos1, send quota is restored only if the entry had already been put on the wire.

pub fn drain_outbox<F>(&mut self, send: F)

Drains every outbox publish not yet on the wire this connection through send, in packet-id order, consuming one unit of send quota per DrainAction::Sent and stopping when the quota is exhausted (§4.9).

This is the lower-level primitive behind poll_transmit. Fresh publishes and retransmits (after a resume or in the post-reconnect flush) all go through it. This keeps the in-flight window within the server’s Receive Maximum. The caller’s send does the wire work and returns a DrainAction: Sent consumes quota and marks the entry in flight, Discard drops it (the caller has failed its future), and Stop leaves it for a later drain (e.g. the output buffer is full). The client owns the quota, the DUP flag, and the in-flight marker.

pub fn drain_pubrel<F>(&mut self, send: F)
where F: FnMut(PacketId) -> DrainAction,

Resends PUBREL for every QoS 2 publish awaiting PUBCOMP that has not gone out this connection (only relevant after a session resume), through send, consuming send quota like drain_outbox.

fn alloc_packet_id(&mut self) -> Result<PacketId, ClientError>

const fn increment_send_quota(&mut self)

Trait Implementations§

§

impl<S: Debug> Debug for Client<S>

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<S> Freeze for Client<S>
where S: Freeze,

§

impl<S> RefUnwindSafe for Client<S>
where S: RefUnwindSafe,

§

impl<S> Send for Client<S>
where S: Send,

§

impl<S> Sync for Client<S>
where S: Sync,

§

impl<S> Unpin for Client<S>
where S: Unpin,

§

impl<S> UnsafeUnpin for Client<S>
where S: UnsafeUnpin,

§

impl<S> UnwindSafe for Client<S>
where S: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more