feat(build): allow to specify trait attributes #2348
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Related to #2341
Motivation
Currently, tonic-build generates service traits without any ability to attach additional attributes or proc-macros.
This creates friction when integrating generated traits with tools and frameworks that rely on such attributes.
For example, when using mockall for testing, one cannot simply write:
because the trait is auto-generated and cannot be easily modified.
As a result, mocking requires duplicating the entire trait or writing manual boilerplate, which is error-prone and difficult to maintain.
Solution
This PR adds a new
trait_attributeconfiguration method totonic-build, allowing custom attributes (including proc-macros) to be injected into generated service traits.Example usage:
This will place
#[mockall::automock]directly above the generatedMyServicetrait, avoiding manual trait duplication for testing and enabling other use cases (e.g., tracing or custom derives).I could not find any existing tests in
tonic-buildthat cover this code path, so I have not added automated tests yet.If the maintainers can point me to where such tests should live, I can add them.