Skip to main content

protovalidate_buffa/
lib.rs

1//! Runtime companion for `protoc-gen-protovalidate-buffa`.
2//!
3//! Provides the [`Validate`] trait, the [`ValidationError`] /
4//! [`Violation`] / [`FieldPath`] types returned from generated
5//! `validate()` methods, the [`cel`] module of thin helpers that
6//! compile-time-expanded CEL rules call into (scalar widening,
7//! Duration/Timestamp converters, `now`), and the [`rules`] module
8//! of pure-Rust helpers used by generated code (UUID / ULID / IP /
9//! URI / hostname checks and friends, mostly thin wrappers over
10//! `uuid`, `ulid`, `ipnet`, and `fluent-uri`).
11//!
12//! There is **no CEL interpreter at runtime**: the paired
13//! `protoc-gen-protovalidate-buffa` plugin transpiles every CEL rule
14//! to native Rust at codegen time. Generated `validate()` methods are
15//! direct field-access checks without per-call dynamic CEL `Value`
16//! materialization. Rules that need scratch state, such as repeated-value
17//! uniqueness, allocate it directly.
18//!
19//! [`ValidationError`] carries three orthogonal signals:
20//!
21//! - `violations`: list of per-field rule failures (the common case).
22//! - `compile_error`: non-empty when the codegen plugin detected a
23//!   schema-level mismatch (rule type / field type, duplicate / unknown
24//!   fields in `message.oneof`, CEL referencing a non-existent field).
25//! - `runtime_error`: non-empty when a rule's precondition could not be
26//!   evaluated (e.g. `bytes.pattern` on non-UTF-8 input, or a CEL rule
27//!   that compiled-time analysis flagged as always-runtime-error such as
28//!   `dyn(this).<unknown_field>`).
29//!
30//! The full upstream `protovalidate-conformance` suite (2872 cases,
31//! covering proto2, proto3, and editions 2023) passes against code
32//! emitted by the paired plugin.
33
34#[doc(hidden)]
35pub mod __private;
36pub mod cel;
37mod error;
38pub mod rules;
39
40#[cfg(feature = "connect")]
41mod connect;
42
43// Re-export `regex` so generated patterns (`::protovalidate_buffa::regex::Regex`)
44// resolve without each downstream crate having to add a direct `regex` dep.
45// `buffa` is re-exported for convenience but generated code uses the
46// `::buffa::` path directly; downstream crates already depend on buffa for
47// their message types.
48pub use buffa;
49/// IANA timezone database, re-exported so generated code can reference
50/// `::protovalidate_buffa::chrono_tz::Tz` when a CEL rule uses the
51/// timezone-argument form of a timestamp accessor
52/// (`t.getHours("America/New_York")`). Only exported when the `tz`
53/// feature is enabled — rules without tz args don't need this dep.
54#[cfg(feature = "tz")]
55pub use chrono_tz;
56pub use error::{FieldPath, FieldPathElement, FieldType, Subscript, ValidationError, Violation};
57/// `#[connect_impl]` — attribute macro applied to a Connect service `impl`
58/// block that inserts `req.validate()?` at the top of every handler method.
59/// Guarantees protovalidate runs for every RPC without relying on per-handler
60/// discipline.
61///
62/// Only exported when the `connect` feature is enabled (the default), since
63/// the emitted code calls [`ValidationError::into_connect_error`].
64#[cfg(feature = "connect")]
65pub use protovalidate_buffa_macros::connect_impl;
66pub use regex;
67
68pub trait Validate {
69    /// Runs every rule attached to this message (and any nested messages),
70    /// collecting violations rather than short-circuiting on the first.
71    ///
72    /// # Errors
73    ///
74    /// Returns a [`ValidationError`] containing one or more [`Violation`]s
75    /// when any rule fails. Callers typically map this to
76    /// `ConnectError::invalid_argument` via
77    /// [`ValidationError::into_connect_error`] (requires the `connect` feature).
78    fn validate(&self) -> Result<(), ValidationError>;
79}
80
81#[macro_export]
82macro_rules! field_path {
83    ( $( $part:expr ),* $(,)? ) => {{
84        let mut elements = ::std::vec::Vec::new();
85        $(
86            elements.push($crate::FieldPathElement {
87                field_number: None,
88                field_name: Some(::std::borrow::Cow::Borrowed($part)),
89                field_type: None,
90                key_type: None,
91                value_type: None,
92                subscript: None,
93            });
94        )*
95        $crate::FieldPath { elements }
96    }};
97}