Ниже показан английский оригинал.
Headers and properties
Headers travel as MQTT 5 user properties, and content-type, reply-to and correlation-id take the matching properties of the protocol.
A serde struct is the contract of a message's headers, and each field is one property whose value is a string.
The handler reads them with the Headers extractor, and a publish writes them with with_headers.
A textual content type also sets the payload format indicator, and correlation-id is binary on the wire.
A header whose name or value is not UTF-8 text without control characters is refused with MqttError::Publish, except the correlation id.
The header partition-key (PARTITION_KEY_HEADER) is the key that keyed workers order a subscription's deliveries by.
Example
The state leaves with the trace id the command arrived with.
- Macros
- Manual
/// The state goes out with the trace the command arrived with.
#[subscriber(MqttTopic::new("valves/v1/set"))]
async fn set(
command: &Command,
Headers(trace): Headers<Trace>,
Out(states): Out<impl Publisher<Options = MqttPublishOptions>, States>,
) -> HandlerOutcome {
let state = State { open: command.open };
if states
.message(&state)
.with_headers(&trace)
.publish()
.await
.is_err()
{
return HandlerOutcome::retry();
}
HandlerOutcome::ack()
}
#[ruststream::app(runtime = embassy)]
fn app(broker: MqttBroker) -> EmbeddedApp<impl Mounts> {
EmbeddedApp::new().with_broker(broker, |b| {
b.include(set).out(States, MqttPublish::default())
})
}
/// The state goes out with the trace the command arrived with.
struct Set;
impl<Entry> Handle<Command, (), Outs<(Entry,)>> for Set
where
Entry: OutEntry<States, Wire: Publisher<Options = MqttPublishOptions>>,
{
async fn handle(
&self,
command: &Command,
outs: &Outs<(Entry,)>,
ctx: &mut Context<'_>,
) -> Result<(), HandlerOutcome> {
let Headers(trace) = Headers::<Trace>::from_context(ctx).await?;
let state = State { open: command.open };
outs.get(States)
.message(&state)
.with_headers(&trace)
.publish()
.await
.map_err(|_| HandlerOutcome::retry())
}
}
fn app(broker: MqttBroker) -> EmbeddedApp<impl Mounts> {
EmbeddedApp::new().with_broker(broker, |b| {
b.include(
subscriber("valves/v1/set", Set)
.map_source(|_| MqttTopic::new("valves/v1/set"))
.build(),
)
.out(States, MqttPublish::default())
})
}