跳到主要内容
本页尚未翻译

下面显示的是英文原文。

Message sets

An enum deriving InMessages declares several message types on one subscription: a rule picks the variant, and the document lists one message per variant.

The set is an enum whose variants each wrap one model, and the handler takes a reference to the enum: &OrderEvent, or &[OrderEvent] for a batch. Each model derives MessageInfo, because the document lists it by that name. A model decodes through its own path: the codec of the mount for a serde type, its own reader for a type that derives Deserialized, such as a Protobuf message. One set may hold both, so a JSON event and a Protobuf event share a subscription and each shows its own format in the document. The derive is the receiving counterpart of OutMessages, which declares what a slot sends.

The header rule is the one to reach for when the producer can set a header. #[in_messages(header = "event")] on the enum names the header the set reads, and #[in_messages(value = "..")] on each variant names the value that picks it. The chosen variant decodes once; a set costs what a single type costs, plus the header lookup. A delivery without the header, or with a value no variant declares, is a decode failure naming the header and the value seen, settled by the failure policy like any other. The document carries the rule: each message's headers schema lists the header with its const value.

A rule of your own is a function: #[in_messages(discriminate = path)] names one that reads the delivery, its headers and raw payload, and returns which kind to decode. The derive generates the kind enum, OrderUpdateKind for a set OrderUpdate, with one unit variant per model. The function returning None is a decode failure naming the set. This is the form for a rule no attribute states: a schema id, a field of the payload, a shape of the bytes. A broker crate may ship such a function for its own format.

A rule only the decode codec can answer is the codec's frame: #[in_messages(by_codec)] asks the codec of the scope or router which model the frame names. A schema registry is the case: each record carries a schema id, and only the registry codec knows which record the id stands for. The codec declares what it reads from a payload in its Frame and maps the frame to a model with FrameNames, implemented once per model it can name. The set then decodes the first model the frame names; a frame that names none is the same decode failure as a function returning None. A set mounted under a codec that cannot answer, JSON for one, is a compile error at the mount site that names the set, the codec and the model. The frame is read from the payload and the codec's own state, so the rule needs no header and works on every runtime. The call is static, so a delivery pays only for what the codec itself does. A set takes the decode codec as a parameter, InMessages<DecodeCodec>: a bound of your own on a set writes T: InMessages<DecodeCodec>. A broker crate may ship the codec for its own registry.

A set with no rule tries its variants left to right, and the first that decodes wins. The order of the variants is the rule, so put the strictest model first. Every variant failing is one decode failure that carries each variant's error. Each attempt costs one decode of that variant, so a delivery of the last variant pays for every variant before it. Left to right is exact only as far as the formats are strict: a Protobuf reader skips the fields it does not know, so a payload of one Protobuf model may decode as another, and a JSON object with the right fields decodes as any model that has them. For such sets, name a rule, or order the variants from the strictest to the loosest.

The derive checks the declaration: every variant wraps exactly one model, each model implements MessageInfo, a model appears once in a set, the enum takes no generic parameters, and a variant owns its model, so a type that borrows the payload cannot be one. A set is not a message, so MessageInfo is not derived on the set itself. Each of these is a compile error on the variant or the enum it concerns. A serde enum with #[serde(tag = "..")] or #[serde(untagged)] is still an ordinary input type, but it is not a set: it works for serde formats only, the tagged form buffers the whole payload per delivery, the untagged form needs a self-describing format, and the document shows one message for the enum.

Example​

The header rule, on a set of a JSON model and a Protobuf one:

/// Every event of an order on the `orders` subscription: the `event` header names the model.
#[derive(InMessages)]
#[in_messages(header = "event")]
enum OrderEvent {
#[in_messages(value = "created")]
Created(OrderCreated),
#[in_messages(value = "cancelled")]
Cancelled(OrderCancelled),
}

The handler matches on the set.

#[subscriber("orders")]
async fn on_event(event: &OrderEvent) -> HandlerOutcome {
match event {
OrderEvent::Created(created) => tracing::info!(created.id, "created"),
OrderEvent::Cancelled(cancelled) => tracing::info!(cancelled.id, "cancelled"),
}
HandlerOutcome::ack()
}

A rule of your own, over the generated kind enum:

/// The same models under a rule no header states: the first byte of the payload tells JSON
/// from Protobuf. The function reads the delivery and names the kind to decode.
#[derive(InMessages)]
#[in_messages(discriminate = by_payload_shape)]
enum OrderUpdate {
Created(OrderCreated),
Cancelled(OrderCancelled),
}

fn by_payload_shape(message: &impl IncomingMessage) -> Option<OrderUpdateKind> {
match message.payload().first()? {
b'{' => Some(OrderUpdateKind::Created),
_ => Some(OrderUpdateKind::Cancelled),
}
}

#[subscriber("orders.updates")]
async fn on_update(update: &OrderUpdate) -> HandlerOutcome {
match update {
OrderUpdate::Created(created) => tracing::info!(created.id, "created"),
OrderUpdate::Cancelled(cancelled) => tracing::info!(cancelled.id, "cancelled"),
}
HandlerOutcome::ack()
}

A rule the decode codec answers: the codec reads a schema id from the payload, and the set mounts under it through a router.

/// The record a schema id stands for, if the registry knows the id: what the codec reads from a
/// payload before decoding it.
struct Record(Option<&'static str>);

/// JSON behind a one-byte schema id; the registry here is a fixed table. The codec resolves the
/// id to the record it stands for, and that record is the frame.
#[derive(Debug, Clone, Copy)]
struct Registry;

impl Codec for Registry {
type Frame<'a> = Record;

fn frame<'a>(&'a self, payload: &'a [u8]) -> Result<Self::Frame<'a>, CodecError> {
Ok(Record(match payload.first() {
Some(1) => Some("OrderCreated"),
Some(2) => Some("OrderPlaced"),
_ => None,
}))
}

/// The registry is read here, never written: the producer that owns it frames its records.
fn encode<T: Serialize>(&self, _value: &T) -> Result<BytesMut, CodecError> {
Err(CodecError::Encode(
"the registry codec reads records only".into(),
))
}

fn decode<T: DeserializeOwned>(&self, bytes: &[u8]) -> Result<T, CodecError> {
JsonCodec.decode(bytes.get(1..).unwrap_or_default())
}
}

/// A model is named by the frame when its own name is the record the id stands for.
impl<Model: MessageInfo> FrameNames<Model> for Registry {
fn names(frame: &Record) -> bool {
frame.0 == Some(Model::NAME)
}
}

/// An order was placed through the legacy checkout: the same JSON shape as `OrderCreated`, so
/// only the registry tells the two apart.
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema, MessageInfo)]
struct OrderPlaced {
id: u64,
}

/// Records named by the schema id the scope codec resolves. The set mounts only under a codec
/// that implements `FrameNames` for both models.
#[derive(InMessages)]
#[in_messages(by_codec)]
enum OrderRecord {
Created(OrderCreated),
Placed(OrderPlaced),
}

#[subscriber("orders.records")]
async fn on_record(record: &OrderRecord) -> HandlerOutcome {
match record {
OrderRecord::Created(created) => tracing::info!(created.id, "created"),
OrderRecord::Placed(placed) => tracing::info!(placed.id, "placed"),
}
HandlerOutcome::ack()
}

Left to right, the strictest model first:

/// No rule: the variants are tried in their order, and the first that decodes wins. The JSON
/// model comes first because it is the stricter one: a Protobuf reader skips what it does not
/// know, so Protobuf bytes never pass as JSON while the reverse could happen.
#[derive(InMessages)]
enum OrderChange {
Created(OrderCreated),
Cancelled(OrderCancelled),
}

#[subscriber("orders.changes")]
async fn on_change(change: &OrderChange) -> HandlerOutcome {
match change {
OrderChange::Created(created) => tracing::info!(created.id, "created"),
OrderChange::Cancelled(cancelled) => tracing::info!(cancelled.id, "cancelled"),
}
HandlerOutcome::ack()
}