peerswap icon indicating copy to clipboard operation
peerswap copied to clipboard

[Enhancement]Introducing protovalidate for Protobuf Validation

Open shelter2759 opened this issue 1 year ago • 1 comments

Overview

This project uses Go and gRPC with Protocol Buffers (Protobuf). We already have buf set up for code generation and linting. Now, I propose introducing protovalidate to define and enforce validation rules directly in .proto files. This approach reduces duplicated validation logic and ensures data integrity.

Key Steps

  1. Integrate protovalidate
  • Add (buf.validate.field) annotations to .proto files for field-level validation (e.g., numeric ranges, string lengths).
  • Install protovalidate in your Go module (go get github.com/bufbuild/protovalidate-go).
  • In your gRPC handlers or interceptors, call validator.Validate(ctx, message) to check inputs before processing.
  1. Add Unit Tests for Validation
  • Write test cases covering expected valid and invalid inputs.
  • Ensure that fields fail when violating constraints (e.g., out-of-range numeric values, overly long strings).
  • Verify that the server rejects invalid requests and returns appropriate error messages.

Benefits

  • Centralized Validation: Keep validation rules in Protobuf definitions.
  • Consistent Enforcements: Rely on Protobuf’s type system for predictable checks.
  • Efficiency: Streamline code generation and reduce manual validation code.

Request for Feedback

Please share any concerns or suggestions about integrating protovalidate—particularly regarding unit test strategies and the effect on existing logic. Thank you for your input!

shelter2759 avatar Feb 18 '25 14:02 shelter2759

Thank you for the proposal. I agree with your suggestion. To ensure transparent validation, using an interceptor for the validation process seems like the best approach.
In that case, the scope of unit tests might be somewhat limited.

YusukeShimizu avatar Feb 19 '25 01:02 YusukeShimizu