encore-dev 2.0.0-beta.18

Rust SDK for Encore applications
Documentation
//! Protobuf message support for generated gRPC clients, wrapping `prost` to
//! preserve unknown fields across decode/encode round trips.
//!
//! By default, `prost` discards unrecognized fields during decoding, which
//! would drop fields added by a newer schema when a message is modified and
//! sent back. Generated messages instead store unrecognized wire fields in
//! `unknown_fields` and re-emit them on encode.
//!
//! Generated structs derive this module's [`Message`] trait and invoke
//! [`message!`](crate::services::clients::protobuf::message) to implement
//! `prost::Message`, dispatching known tags to `prost`'s generated code and
//! capturing all other tags in [`UnknownFields`].

use std::fmt;

#[doc(no_inline)]
pub use prost::*;

use prost::bytes::{Buf, BufMut};
use prost::encoding::{DecodeContext, WireType};

/// The encoding of the fields a message's schema has, as prost's derive
/// implements it. Not prost's `Message`, which [`message!`] implements with
/// it.
///
/// [`message!`]: crate::services::clients::protobuf::message
pub trait Message {
    /// Encodes the message's fields, as prost's `Message::encode_raw`.
    fn encode_raw(&self, buf: &mut impl BufMut);

    /// Decodes one of the message's fields, as prost's `Message::merge_field`.
    ///
    /// # Errors
    ///
    /// The field's encoding is invalid.
    fn merge_field(
        &mut self,
        tag: u32,
        wire_type: WireType,
        buf: &mut impl Buf,
        ctx: DecodeContext,
    ) -> Result<(), DecodeError>;

    /// The length of the message's fields encoded.
    fn encoded_len(&self) -> usize;

    /// Resets every field to its default.
    fn clear(&mut self);
}

/// Unrecognized protobuf fields preserved in their original wire encoding and
/// order.
#[derive(Clone, Default, PartialEq, Eq, Hash)]
pub struct UnknownFields {
    encoded: Vec<u8>,
}

impl UnknownFields {
    /// Returns the raw wire-encoded bytes of all preserved unknown fields.
    pub fn as_bytes(&self) -> &[u8] {
        &self.encoded
    }

    /// Returns the field numbers of all preserved unknown fields in arrival
    /// order (including duplicates for repeated fields).
    pub fn numbers(&self) -> Vec<u32> {
        let mut numbers = Vec::new();
        let mut buf = self.encoded.as_slice();
        while buf.has_remaining() {
            let Ok((tag, wire_type)) = encoding::decode_key(&mut buf) else {
                break;
            };
            if encoding::skip_field(wire_type, tag, &mut buf, DecodeContext::default()).is_err() {
                break;
            }
            numbers.push(tag);
        }
        numbers
    }

    /// Decodes the field `tag` into `fields`, as it arrived.
    #[doc(hidden)]
    pub fn merge(
        fields: &mut Option<UnknownFields>,
        tag: u32,
        wire_type: WireType,
        buf: &mut impl Buf,
        ctx: DecodeContext,
    ) -> Result<(), DecodeError> {
        let mut field = Vec::new();
        copy_field(tag, wire_type, buf, ctx, &mut field)?;
        fields
            .get_or_insert_with(UnknownFields::default)
            .encoded
            .extend(field);
        Ok(())
    }

    /// Encodes the fields, as prost's derive encodes a oneof.
    #[doc(hidden)]
    pub fn encode(&self, buf: &mut impl BufMut) {
        buf.put_slice(&self.encoded);
    }

    /// The length of the fields encoded, as prost's derive asks a oneof.
    #[doc(hidden)]
    pub fn encoded_len(&self) -> usize {
        self.encoded.len()
    }
}

impl fmt::Debug for UnknownFields {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("UnknownFields")
            .field(&self.numbers())
            .finish()
    }
}

/// A group's fields, every one of them unknown: what [`copy_field`] decodes
/// a group as, with prost's checks of its end and depth.
impl prost::Message for UnknownFields {
    fn encode_raw(&self, buf: &mut impl BufMut) {
        self.encode(buf);
    }

    fn merge_field(
        &mut self,
        tag: u32,
        wire_type: WireType,
        buf: &mut impl Buf,
        ctx: DecodeContext,
    ) -> Result<(), DecodeError> {
        copy_field(tag, wire_type, buf, ctx, &mut self.encoded)
    }

    fn encoded_len(&self) -> usize {
        self.encoded.len()
    }

    fn clear(&mut self) {
        self.encoded.clear();
    }
}

/// Decodes the field `tag`, its key read already, and appends it to `out`
/// encoded again. Each value is decoded with prost's own functions, which
/// fail as prost does on what does not decode.
fn copy_field(
    tag: u32,
    wire_type: WireType,
    buf: &mut impl Buf,
    ctx: DecodeContext,
    out: &mut Vec<u8>,
) -> Result<(), DecodeError> {
    match wire_type {
        WireType::Varint => {
            let mut value = 0u64;
            encoding::uint64::merge(wire_type, &mut value, buf, ctx)?;
            encoding::encode_key(tag, wire_type, out);
            encoding::encode_varint(value, out);
        }
        WireType::SixtyFourBit => {
            let mut value = 0u64;
            encoding::fixed64::merge(wire_type, &mut value, buf, ctx)?;
            encoding::encode_key(tag, wire_type, out);
            out.put_u64_le(value);
        }
        WireType::ThirtyTwoBit => {
            let mut value = 0u32;
            encoding::fixed32::merge(wire_type, &mut value, buf, ctx)?;
            encoding::encode_key(tag, wire_type, out);
            out.put_u32_le(value);
        }
        WireType::LengthDelimited => {
            let mut value = Vec::new();
            encoding::bytes::merge(wire_type, &mut value, buf, ctx)?;
            encoding::encode_key(tag, wire_type, out);
            encoding::encode_varint(value.len() as u64, out);
            out.extend(value);
        }
        WireType::StartGroup => {
            let mut group = UnknownFields::default();
            encoding::group::merge(tag, wire_type, &mut group, buf, ctx)?;
            encoding::encode_key(tag, WireType::StartGroup, out);
            out.extend(group.encoded);
            encoding::encode_key(tag, WireType::EndGroup, out);
        }
        // Fails, as nothing can end here.
        WireType::EndGroup => encoding::skip_field(wire_type, tag, buf, ctx)?,
    }
    Ok(())
}

/// Implements prost's `Message` for `$message`, a generated message whose
/// derive implemented this module's [`Message`]: the fields numbered
/// `$tag` are the derive's to decode, and every other is kept in the field
/// `$unknown`.
#[doc(hidden)]
#[macro_export]
macro_rules! __protobuf_message {
    ($message:ty, $unknown:ident, [$($tag:literal),*]) => {
        impl $crate::services::clients::prost::Message for $message {
            fn encode_raw(
                &self,
                buf: &mut impl $crate::services::clients::prost::bytes::BufMut,
            ) {
                $crate::services::clients::protobuf::Message::encode_raw(self, buf)
            }

            fn merge_field(
                &mut self,
                tag: u32,
                wire_type: $crate::services::clients::prost::encoding::WireType,
                buf: &mut impl $crate::services::clients::prost::bytes::Buf,
                ctx: $crate::services::clients::prost::encoding::DecodeContext,
            ) -> ::core::result::Result<(), $crate::services::clients::prost::DecodeError> {
                const KNOWN: &[u32] = &[$($tag),*];
                if KNOWN.contains(&tag) {
                    $crate::services::clients::protobuf::Message::merge_field(
                        self, tag, wire_type, buf, ctx,
                    )
                } else {
                    $crate::services::clients::protobuf::UnknownFields::merge(
                        &mut self.$unknown,
                        tag,
                        wire_type,
                        buf,
                        ctx,
                    )
                }
            }

            fn encoded_len(&self) -> usize {
                $crate::services::clients::protobuf::Message::encoded_len(self)
            }

            fn clear(&mut self) {
                $crate::services::clients::protobuf::Message::clear(self)
            }
        }
    };
}

#[doc(hidden)]
pub use crate::__protobuf_message as message;

#[cfg(test)]
mod tests {
    use prost::Message as _;

    use super::UnknownFields;

    /// A message as a generated client has it: `Old` knows field 1 of what
    /// `New` sends.
    #[derive(Clone, PartialEq, crate::services::clients::protobuf::Message)]
    #[prost(prost_path = "crate::services::clients::protobuf")]
    struct Old {
        #[prost(string, tag = "1")]
        name: String,
        #[prost(message, optional, tag = "2")]
        inner: Option<Box<Old>>,
        #[prost(
            oneof = "crate::services::clients::protobuf::UnknownFields",
            tags = "19000"
        )]
        unknown_fields: Option<UnknownFields>,
    }
    crate::services::clients::protobuf::message!(Old, unknown_fields, [1, 2]);

    #[derive(Clone, PartialEq, prost::Message)]
    struct New {
        #[prost(string, tag = "1")]
        name: String,
        #[prost(message, optional, tag = "2")]
        inner: Option<Box<New>>,
        #[prost(int64, tag = "3")]
        count: i64,
        #[prost(fixed32, tag = "4")]
        fixed: u32,
        #[prost(double, tag = "5")]
        ratio: f64,
        #[prost(string, repeated, tag = "6")]
        notes: Vec<String>,
    }

    #[test]
    fn fields_the_schema_lacks_are_encoded_again() {
        let new = New {
            name: "a".into(),
            inner: Some(Box::new(New {
                name: "b".into(),
                count: -3,
                ..Default::default()
            })),
            count: 7,
            fixed: 9,
            ratio: 0.5,
            notes: vec!["x".into(), "y".into()],
        };
        let mut old = Old::decode(new.encode_to_vec().as_slice()).unwrap();
        assert_eq!(
            old.unknown_fields.as_ref().map(UnknownFields::numbers),
            Some(vec![3, 4, 5, 6, 6])
        );
        let inner = old.inner.as_ref().unwrap();
        assert_eq!(
            inner.unknown_fields.as_ref().map(UnknownFields::numbers),
            Some(vec![3])
        );
        old.name = "changed".into();
        let again = New::decode(old.encode_to_vec().as_slice()).unwrap();
        assert_eq!(
            again,
            New {
                name: "changed".into(),
                ..new
            }
        );
        assert_eq!(old.encoded_len(), old.encode_to_vec().len());

        old.clear();
        assert!(old.unknown_fields.is_none());
        assert_eq!(Old::default(), old);
    }

    #[test]
    fn groups_are_kept_whole() {
        // Field 7, a group holding field 1 = 5; then field 8 = 1.
        let encoded = [0x3b, 0x08, 0x05, 0x3c, 0x40, 0x01];
        let old = Old::decode(&encoded[..]).unwrap();
        let unknown = old.unknown_fields.as_ref().unwrap();
        assert_eq!(unknown.as_bytes(), encoded);
        assert_eq!(unknown.numbers(), [7, 8]);
        // An end with no start, and a group that does not end, fail.
        assert!(Old::decode(&[0x3c][..]).is_err());
        assert!(Old::decode(&[0x3b, 0x08, 0x05][..]).is_err());
        // As does a value cut short.
        assert!(Old::decode(&[0x1a, 0x05, 0x01][..]).is_err());
    }
}