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: u16Keep-alive interval in seconds as negotiated.
send_quota: u16Number of QoS > 0 publishes we can still send before hitting the
server’s Receive Maximum.
recv_quota: u16Number of QoS > 0 messages the client can still accept from the
server before the server would violate our Receive Maximum.
recv_max: u16The 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: PacketIdMonotonic packet ID counter (1..=65535, wraps around skipping 0).
clean_start: boolWhether 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: boolWhether the outbound alias table still holds the mappings of an earlier connection (§3.3.2.3.4).
Implementations§
§impl<S: State> Client<S>
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>>
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>>
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,
)
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,
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>
impl<S: State> Client<S>
pub fn new(session: S) -> Self
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
pub const fn connection_state(&self) -> ConnectionState
Current connection state.
pub const fn capabilities(&self) -> &ServerCapabilities
pub const fn capabilities(&self) -> &ServerCapabilities
Server capabilities from the most recent CONNACK.
pub const fn keep_alive(&self) -> u16
pub const fn keep_alive(&self) -> u16
Effective keep-alive interval in seconds.
pub const fn send_quota(&self) -> u16
pub const fn send_quota(&self) -> u16
Remaining send quota for QoS > 0 publishes.
pub const fn session_mut(&mut self) -> &mut S
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>
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)
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))
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>>
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>
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
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>>
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>>
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>>
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>>
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>>
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>>
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>>
pub fn prepare_unsubscribe<'a, I>( &mut self, filters: I, ) -> Result<PacketId, StoreError<S::Error>>
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>>
pub fn store_offline_unsubscribe<'a, I>( &mut self, filters: I, ) -> Result<PacketId, StoreError<S::Error>>
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>>
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>>
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)
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)
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)
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)
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)
pub fn drain_pubrel<F>(&mut self, send: F)
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§
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> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
impl<T> ErasedDestructor for Twhere
T: 'static,
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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