protovalidate/validator

Checking protobuf messages against the buf.validate rules of their descriptors. Messages are checked in their encoded form, described by a FileDescriptorSet that includes buf/validate/validate.proto (protoc --include_imports --descriptor_set_out, or buf build -o), so any protobuf library’s messages can be checked. A message type’s rules are compiled once, and checking a message decodes only the fields its rules read:

let assert Ok(validator) = validator.new(descriptor_set)
let assert Ok(users) = validator.compile(validator, "example.v1.User")
case validator.validate(users, encoded) {
  Ok(Nil) -> "valid"
  Error(validator.Invalid([violation, ..])) -> violation.to_string(violation)
  Error(_) -> "rules that cannot be checked"
}

Patterns run on OTP’s re unless a validator says otherwise: as they often match what a peer sends, new_with_regex(descriptor_set, env.Re2) runs them on RE2, in time linear in what they match, through the re2 package, which an application that wants it depends on.

Types

The compiled rules of a message type, and of the types it contains.

pub type Compiled

Why a message failed its check.

pub type Error {
  Invalid(List(violation.Violation))
  Compilation(String)
  Runtime(String)
}

Constructors

  • Invalid(List(violation.Violation))

    It broke these rules.

  • Compilation(String)

    A rule it reached cannot be compiled, such as a CEL expression that does not parse.

  • Runtime(String)

    A rule failed to evaluate, or the message does not decode.

The rules of the types in a FileDescriptorSet.

pub type Validator

Values

pub fn compile(
  validator: Validator,
  type_name: String,
) -> Result(Compiled, String)

Compiles the rules of the message type type_name, such as example.v1.User, and of the types it contains.

pub fn from_provider(provider: pb.Provider) -> Validator

A validator of a provider’s types, which shares its descriptors with the CEL environments it gives messages to.

pub fn from_provider_with_regex(
  provider: pb.Provider,
  regex: env.Regex,
) -> Result(Validator, String)

A validator of a provider’s types, whose patterns run on regex, as new_with_regex’s do.

pub fn new(descriptor_set: BitArray) -> Result(Validator, String)

A validator of the types in an encoded FileDescriptorSet.

pub fn new_with_regex(
  descriptor_set: BitArray,
  regex: env.Regex,
) -> Result(Validator, String)

A validator of the types in an encoded FileDescriptorSet, whose patterns run on regex. env.Re2 needs the re2 package, without which this fails.

pub fn validate(
  compiled: Compiled,
  encoded: BitArray,
) -> Result(Nil, Error)

Checks an encoded message of a compiled type.

✨ Search Document