Docs Guide
Protify is a Rust-first framework for protobuf that generates packages from rust code, with validation included.
It aims to make working with protobuf feel (almost) as easy as using serde. It flips the logic of the typical proto workflow around, so that all the elements of a package can be defined in rust with a rich set of macros and attributes, and the resulting contracts can be generated from the rust code, rather than the other way around.
It also offers a rich validation framework that can be used to programmatically create highly customizable validators that can also be transposed into protobuf options to provide portability to other systems.
ℹ️ NOTE: This readme is generated from the rust documentation, so most of the links will not show up in Github. Read this in the docs.rs page to ensure that links work correctly.
You can visit the package setup section of the guide to learn more about how to set up protify.
From Rust To Proto
Each element of a protobuf file can be defined with a proc or attribute macro. Options for each element can be composed and assigned programmatically.
Unlike in prost, enums representing protobuf oneofs can be reused for multiple messages (with limitations explained in the reusing oneofs section).
use *;
// Creates a new package
proto_package!;
// Creates a new file
define_proto_file!;
// We can directly plug this into a tonic handler!
// Tags are assigned automatically
// and take the reserved numbers in consideration
For a full guide on how to set up a package, visit the package setup section.
Proxies As A Translation Layer
Messages and oneofs can be proxied. Doing so will generate a new struct/enum with the same name, followed by a Proto suffix (i.e. MyMsg -> MyMsgProto).
Proxied messages/oneofs unlock the following features:
- A field/variant can be missing from the proto struct, but present in the proxy (akin to the
skipattribute withserde) - Enums can be represented with their actual rust enum type, rather than being pure integers
- Oneofs don't need to be wrapped in
Option - Messages don't need to be wrapped in
Option - We can use types that are not supported by prost and map them with custom conversions
By default, the macro will generate a conversion from proxy to proto and vice versa that just calls .into() for each field/variant. So if the field's prost type implements From with the proxy field and vice versa, no additional attributes are required.
To provide custom conversions, you can use the from_proto and into_proto attributes on the container (to replace the automatically generated impl as a whole) or on individual fields/variants.
The proxied structs/enums will also implement ProxiedMessage or ProxiedOneof, whereas the proxies will implement MessageProxy and OneofProxy.
use *;
use Arc;
proto_package!;
define_proto_file!;
// Generates a MsgProto struct that is prost-compatible
// Direct implementation. The prost attributes will be directly
// injected in it
// Generates the `ProxiedOneofProto` enum
Interacting With Databases
An important benefit that comes from having a "rust-first" approach when defining our models is that they can easily be used for operations such as db queries, without needing to create separate structs to map to the generated protos, or injecting the attributes as plain text with the prost-build helper, which can be unergonomic and brittle.
And with proxies, the interactions with a database becomes even easier, because we can have the proto-facing struct with a certain shape, while the proxy can represent the state of a message after its data has been mapped, for example, to an item queried from the database.
You can take a look at the test-server crate in the repo for an example of database interaction in a tonic handler.
use *;
use Timestamp;
use *;
proto_package!;
define_proto_file!;
// If we want to use the message as is for the db model
// If we want to use the proxy as the db model, for example
// to avoid having `created_at` as `Option`
Validating Content
Whenever models or API contracts are defined and used, the need for validation follows close behind.
Because of this, protify ships with a validation framework that integrates validation logic with schema definitions.
The implementors of Validator hold two roles at the same time: on the one hand, they handle the validation logic on the rust side, and on the other hand, they can also produce a schema representation, so that their settings can be represented as options in a protobuf file, so that they can be ported between different applications.
All the provided validators map their options to the protovalidate options, but you can also create customized validators that map to other custom options.
Because every validator is type-safe and comes with an ergonomic builder methods to be built with, defining validators becomes a vastly superior experience than manual composition in protobuf files, where the process is repetitive, rigid, and lacking essential features of modern programming such as type safety and LSP integration, as well as programmatic composition.
Validators can be assigned to oneofs/messages as a whole or to individual fields/variants to be incorporated in thier validation logic.
use *;
use HashMap;
proto_package!;
define_proto_file!;
// We can define logic to programmatically compose validators
// Top level validation using a CEL program
ℹ️ NOTE: Validators that are provided via closures will be cached in a Lazy struct (normally a LazyLock or a wrapper for OnceBox in a no_std environment), so they are only initialized once (except for the OneofValidator which is small enough).
Custom Validators
The Validator trait allows for the construction of custom validators.
A validator can be a struct (stateful) or just a function, wrapped with the from_fn helper.
Each validator only needs to implement a single method, execute_validation, which receives a ValidationCtx and an [Option] of the target type. All the other methods are automatically derived.
The schema and check_consistency methods can be optionally implemented, as described later in this section and in the correctness section.
use *;
proto_package!;
define_proto_file!;
// Function validator
;
// If a validator contains some heavy or complex logic,
// it can be initialized once and then reused.
// This is done by default for validators defined with closures in attributes.
static CACHED_VALIDATOR: = new;
// Using the custom validators at the top level
// Same thing for oneofs
You can have a look at the testing crates in the repo for more complex examples of custom validator usage.
Customizing Error Messages
In order to facilitate things like i18n, every provided validator allows for customization of the error messages, without requiring a whole custom validator to be designed purely for this purpose.
Each builder features a method called with_error_messages, which accepts a BTreeMap that maps the violations that it may produce to error messages.
use *;
use ;
use BTreeMap;
use btreemap;
let validator = builder.min_len.with_error_messages.build;
let violations = validator.validate.unwrap_err.into_violations;
assert_eq!;
Schema Representation
In order to make validation settings portable, each validator can optionally implement the schema method, which outputs a ProtoOption that will be added to the receiving message/oneof in the proto file.
All default validators implement this method and output the options in the protovalidate format.
use indoc;
use *;
proto_package!;
define_proto_file!;
Protovalidate Support
The best way to use protify is to define a schema from scratch using rust code. However, it is also possible to generate validators that are defined in pre-built proto files using the protovalidate syntax. You can learn more about this in the reflection usage section.
Feature Flags
tonic— Enables direct conversion from validation errors to [tonic::Status].serde— Enables serde for all schema representations.inventory(enabled by default) — Enables automatic collection for elements of a package. (Requiredstd)chrono(enabled by default) — Enables timestampnowfeatures in CEL and timestamp validation.chrono-wasm— Enables usage of wasmbind for chrono'snowmethods.std(enabled by default) — Enables the std library features.common-types— Enables schema features forgoogle.typetypes.rpc-types— Enables schema features forgoogle.rpctypes.reflection— Enables usage with reflection, to generate validation logic from pre-built protos with protovalidate annotations.cel(enabled by default) — Enables CEL validation.regex(enabled by default) — Enables regex-based validators.
License
This repository is licensed under the MPL-2.0 license.
The file CREDITS.md contains the licensing details for the external code used in this project.