userver: /data/code/userver/libraries/grpc-protovalidate/src/grpc-protovalidate/validate.cpp Source File
Loading...
Searching...
No Matches
validate.cpp
1#include <userver/grpc-protovalidate/validate.hpp>
2
3#include <memory>
4#include <stdexcept>
5#include <string>
6#include <utility>
7#include <vector>
8
9#include <algorithm>
10
11#include <fmt/format.h>
12#include <google/protobuf/message.h>
13#include <google/protobuf/repeated_ptr_field.h>
14#include <google/rpc/status.pb.h>
15#include <grpcpp/support/status.h>
16
17#include <grpc-protovalidate/impl/utils.hpp>
18#include <grpc-protovalidate/impl/validation_visitor.hpp>
19#include <userver/compiler/thread_local.hpp>
20#include <userver/engine/task/task_processor_fwd.hpp>
21#include <userver/grpc-protovalidate/buf_validate.hpp>
22#include <userver/protobuf/impl/descriptor_collector.hpp>
23#include <userver/ugrpc/status_utils.hpp>
24#include <userver/utils/assert.hpp>
25
26USERVER_NAMESPACE_BEGIN
27
28namespace grpc_protovalidate {
29
30namespace {
31
32compiler::ThreadLocal kValidationVisitor = [] {
33 auto visitor = std::make_unique<impl::ValidationVisitor>();
34 for (const auto* descriptor : protobuf::impl::GetGeneratedMessages()) {
35 visitor->Compile(*descriptor);
36 }
37 return visitor;
38};
39
40class ValidationVisitorWarmupRegistrator final {
41public:
42 ValidationVisitorWarmupRegistrator() {
43 engine::RegisterThreadStartedHook([] {
44 // Initialize and compile the thread-local visitor before this worker starts processing tasks.
45 const auto visitor = kValidationVisitor.Use();
46 });
47 }
48};
49
50const ValidationVisitorWarmupRegistrator kWarmupRegistrator{};
51
52} // namespace
53
54ValidationError::ValidationError(Type type, std::string description, std::string message_name)
55 : type_(type),
56 description_(fmt::format("Message '{}' validation error: {}", message_name, std::move(description))),
57 result_(std::nullopt),
58 message_name_(std::move(message_name))
59{}
60
61ValidationError::ValidationError(buf::validate::ValidationResult result, std::string message_name)
62 : type_(Type::kRule),
63 description_(fmt::format(
64 "Message '{}' validation error: {} constraint(s) violated",
65 message_name,
66 result.violations_size()
67 )),
68 result_(std::move(result)),
69 message_name_(std::move(message_name))
70{}
71
72ValidationError::Type ValidationError::GetType() const { return type_; }
73
74const std::string& ValidationError::GetMessageName() const { return message_name_; }
75
76const std::string& ValidationError::GetDescription() const { return description_; }
77
78const std::vector<buf::validate::RuleViolation>& ValidationError::GetViolations() const {
79 if (GetType() == Type::kInternal || !result_.has_value()) {
80 static constexpr std::vector<buf::validate::RuleViolation> kNoViolations;
81 return kNoViolations;
82 }
83 return result_->violations();
84}
85
86grpc::Status ValidationError::GetGrpcStatus(bool include_violations, grpc::StatusCode rule_violation_status) const {
87 google::rpc::Status gstatus;
88 gstatus.set_message(GetDescription());
89 switch (GetType()) {
90 case Type::kInternal:
91 gstatus.set_code(grpc::StatusCode::INTERNAL);
92 break;
93 case Type::kRule: {
94 gstatus.set_code(rule_violation_status);
95 break;
96 }
97 }
98 if (include_violations) {
99 gstatus.add_details()->PackFrom(MakeViolationsProto());
100 }
101 return ugrpc::ToGrpcStatus(gstatus);
102}
103
104buf::validate::Violations ValidationError::MakeViolationsProto() const {
105 buf::validate::Violations proto;
106 std::ranges::transform(
107 GetViolations(),
108 RepeatedPtrFieldBackInserter(proto.mutable_violations()),
109 [](const buf::validate::RuleViolation& violation) { return violation.proto(); }
110 );
111 return proto;
112}
113
114logging::LogHelper& operator<<(logging::LogHelper& lh, const ValidationError& error) {
115 lh << error.GetDescription();
116 for (const buf::validate::RuleViolation& violation : error.GetViolations()) {
117 lh << violation.proto();
118 }
119 return lh;
120}
121
122ValidationResult::ValidationResult(ValidationError error)
123 : error_(std::move(error))
124{}
125
126bool ValidationResult::IsSuccess() const { return !error_.has_value(); }
127
128const ValidationError& ValidationResult::GetError() const& {
129 if (IsSuccess()) {
130 throw std::logic_error("Requested error for success validation result");
131 }
132 return error_.value();
133}
134
135ValidationError&& ValidationResult::GetError() && {
136 if (IsSuccess()) {
137 throw std::logic_error("Requested error for success validation result");
138 }
139 return std::move(error_).value();
140}
141
142ValidationResult ValidateMessage(const google::protobuf::Message& message, const ValidationParams& params) {
143 (void)kWarmupRegistrator; // odr-use
144 auto visitor = kValidationVisitor.Use();
145 auto result = (*visitor)->Validate(message, {.fail_fast = params.fail_fast});
146 if (!result.ok()) {
147 return ValidationError(
148 ValidationError::Type::kInternal,
149 fmt::format(
150 "internal protovalidate error (check constraints syntax in the proto file) - {}",
151 result.status().ToString()
152 ),
153 message.GetTypeName()
154 );
155 }
156 if (result->violations_size() != 0) {
157 return ValidationError(result.value(), message.GetTypeName());
158 }
159 return ValidationResult();
160}
161
162} // namespace grpc_protovalidate
163
164USERVER_NAMESPACE_END