tokio-rs / prost

PROST! a Protocol Buffers implementation for the Rust Language
Apache License 2.0
3.86k stars 500 forks source link

Feature Request: Automatically Implement a ProtobufSrcInfo Trait to provide i.e. the original full protobuf name #1092

Closed BaxHugh closed 2 months ago

BaxHugh commented 3 months ago

Description:

I would like to request a new feature for prost-build to automatically implement a ProtobufSrcInfo trait for each generated struct. Currently, the only info I would like in the trait at the moment would be a constant PROTOBUF_FULL_NAME to return the full protobuf name of the struct (i.e. the protobuf package + message name), similar to the DESCRIPTOR.full_name attribute in Python's protoc generated code. I'm sure there would be additional information people might want later.

Rationale:

In many cases, it would be useful to have access to the full protobuf name of a message in Rust code, for purposes such as debugging, logging, or interfacing with systems that use the same protobuf API and potentially require the full protobuf names. Currently, prost-build does not generate this information, and users need to manually add it somewhere in their code.

My Specific Use Case

My specific use case for this feature is cross-language interoperability. Specifically for implementing pyo3 conversion traits on prost generated types. If I can extract the original protobuf path on the rust side at the struct level, I can derive implementations of pyo3 conversion traits as the protobuf path can be used to find the full python path for the equivalent python class that needs to be returned from pyo3 trait implementations.

Some details of my proposed solution

Add a trait in prost.

pub trait ProtobufSrcInfo {
    const PROTOBUF_FULL_NAME: &'static str;
}

Add a method to tonic_build::prost::Builder

builder.impl_protobuf_src_info()

or if we need to support the option to only implement this on some messages, we could have a path argument, as we do with Builder::message_attribute

builder.impl_protof_src_info(my_specific_protos_path)
romac commented 2 months ago

Isn't this already provided by the prost::Name trait, which can be enabled with prost_build::Config::enable_type_names?

BaxHugh commented 2 months ago

Thanks @romac I'm not sure how I missed this, nothing jumped out of the docs to me, and I failed to find it when grepping around the source code. But yes, this is exactly what I was looking for, so I'll close this.

caspermeijn commented 2 months ago

prost_build::Config::enable_type_names could use some extra documentation to make it more discoverable.

@BaxHugh Are you willing to add an example to the documentation?