userver: userver/ugrpc/protobuf_visit.hpp Source File
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
protobuf_visit.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/ugrpc/protobuf_visit.hpp
4/// @brief Utilities for visiting the fields of protobufs
5
6#include <mutex>
7#include <string_view>
8#include <vector>
9
10#include <google/protobuf/message.h>
11
12#include <userver/engine/shared_mutex.hpp>
13#include <userver/utils/assert.hpp>
14#include <userver/utils/function_ref.hpp>
15#include <userver/utils/impl/internal_tag_fwd.hpp>
16#include <userver/utils/span.hpp>
17
18namespace google::protobuf {
19
20class Descriptor;
21class FieldDescriptor;
22
23} // namespace google::protobuf
24
25USERVER_NAMESPACE_BEGIN
26
27namespace ugrpc {
28
29using MessageVisitCallback = utils::function_ref<void(google::protobuf::Message&)>;
30
31using FieldVisitCallback =
32 utils::function_ref<void(google::protobuf::Message&, const google::protobuf::FieldDescriptor&)>;
33
34/// @brief Execute a callback for all non-empty fields of the message.
35void VisitFields(google::protobuf::Message& message, FieldVisitCallback callback);
36
37/// @brief Execute a callback for the message and its non-empty submessages.
38void VisitMessagesRecursive(google::protobuf::Message& message, MessageVisitCallback callback);
39
40/// @brief Execute a callback for all fields of the message and its non-empty submessages.
41void VisitFieldsRecursive(google::protobuf::Message& message, FieldVisitCallback callback);
42
43/// @brief Execute a callback for the submessage contained in the given field.
45 google::protobuf::Message& message,
46 const google::protobuf::FieldDescriptor& field,
47 MessageVisitCallback callback
48);
49
50using DescriptorList = std::vector<const google::protobuf::Descriptor*>;
51
52using FieldDescriptorList = std::vector<const google::protobuf::FieldDescriptor*>;
53
54/// @brief Get the descriptors of fields in the message.
55FieldDescriptorList GetFieldDescriptors(const google::protobuf::Descriptor& descriptor);
56
57/// @brief Get the descriptors of current and nested messages.
58DescriptorList GetNestedMessageDescriptors(const google::protobuf::Descriptor& descriptor);
59
60/// @brief Find a generated type by name.
61const google::protobuf::Descriptor* FindGeneratedMessage(std::string_view name);
62
63/// @brief Find the field of a generated type by name.
64const google::protobuf::FieldDescriptor*
65FindField(const google::protobuf::Descriptor* descriptor, std::string_view field);
66
67/// @brief Base class for @ref BaseVisitor.
68/// Constructs and manages the descriptor graph to collect the data about the messages
69/// and enable the visitors to find all selected structures.
71public:
72 enum class LockBehavior {
73 /// @brief Do not take shared_mutex locks for any operation on the visitor
74 kNone = 0,
75
76 /// @brief Take shared_lock for all read operations on the visitor
77 /// and unique_lock for all Compile operations
78 kShared = 1
79 };
80
81 VisitorCompiler(VisitorCompiler&&) = delete;
82 VisitorCompiler(const VisitorCompiler&) = delete;
83
84 /// @brief Compiles the visitor for the given message type and its dependent types
85 void Compile(const google::protobuf::Descriptor* descriptor);
86
87 /// @brief Compiles the visitor for the given message types and their dependent types
88 void Compile(const DescriptorList& descriptors);
89
90 /// @brief Compiles the visitor for all message types we can find.
91 /// Not guaranteed to find all message types.
93
94 /// @brief Compiles the visitor for the given generated message type and its dependent types
95 void CompileGenerated(std::string_view message_name);
96
97 /// @brief Compiles the visitor for the given generated message type and their dependent types
98 void CompileGenerated(utils::span<std::string_view> message_names);
99
100 /// @brief Efficiently checks if the message contains any selected structures.
101 ///
102 /// You may want to call this before @ref BaseVisitor::Visit and @ref BaseVisitor::VisitRecursive
103 /// to avoid a copy of the message beforehand if you require one.
104 bool ContainsSelected(const google::protobuf::Descriptor* descriptor);
105
106 /// @cond
107 /// Only for internal use.
108 using Dependencies = std::unordered_map<
109 const google::protobuf::Descriptor*,
110 std::unordered_set<const google::protobuf::FieldDescriptor*>>;
111
112 /// Only for internal use.
113 using DescriptorSet = std::unordered_set<const google::protobuf::Descriptor*>;
114
115 /// Only for internal use.
116 using FieldDescriptorSet = std::unordered_set<const google::protobuf::FieldDescriptor*>;
117
118 /// Only for internal use.
119 const Dependencies& GetFieldsWithSelectedChildren(utils::impl::InternalTag) const;
120
121 /// Only for internal use.
122 const Dependencies& GetReverseEdges(utils::impl::InternalTag) const;
123
124 /// Only for internal use.
125 const DescriptorSet& GetPropagated(utils::impl::InternalTag) const;
126
127 /// Only for internal use.
128 const DescriptorSet& GetCompiled(utils::impl::InternalTag) const;
129
130protected:
131 explicit VisitorCompiler(LockBehavior lock_behavior) : lock_behavior_(lock_behavior) {}
132
133 // Disallow destruction via pointer to base
134 ~VisitorCompiler() = default;
135
136 /// @brief Lock the visitor for read
137 std::shared_lock<engine::SharedMutex> LockRead();
138
139 /// @brief Lock the visitor for write
140 std::unique_lock<engine::SharedMutex> LockWrite();
141
142 const Dependencies& GetFieldsWithSelectedChildren() const { return fields_with_selected_children_; }
143 /// @endcond
144
145 /// @brief Compile one message without nested.
146 virtual void CompileOne(const google::protobuf::Descriptor& descriptor) = 0;
147
148 /// @brief Checks if the message is selected or has anything selected.
149 virtual bool IsSelected(const google::protobuf::Descriptor&) const = 0;
150
151private:
152 /// @brief Gets all submessages of the given messages.
153 DescriptorSet GetFullSubtrees(const DescriptorList& descriptors) const;
154
155 /// @brief Propagate the selection information upwards
156 void PropagateSelected(const google::protobuf::Descriptor* descriptor);
157
158 engine::SharedMutex mutex_;
159 const LockBehavior lock_behavior_;
160
161 Dependencies fields_with_selected_children_;
162 Dependencies reverse_edges_;
163 DescriptorSet propagated_;
164 DescriptorSet compiled_;
165};
166
167/// @brief Base class for @ref FieldsVisitor and @ref MessagesVisitor.
168/// Provides the interface and contains common code to use the data collected in the @ref VisitorCompiler.
169template <typename Callback>
171public:
172 /// @brief Execute a callback without recursion
173 ///
174 /// Equivalent to @ref VisitFields
175 /// but utilizes the precompilation data from @ref Compile
176 void Visit(google::protobuf::Message& message, Callback callback) {
177 // Compile if not yet compiled
178 Compile(message.GetDescriptor());
179
180 const std::shared_lock read_lock = LockRead();
181 DoVisit(message, callback);
182 }
183
184 /// @brief Execute a callback recursively
185 ///
186 /// Equivalent to @ref VisitFieldsRecursive and @ref VisitMessagesRecursive
187 /// but utilizes the precompilation data from @ref Compile
188 void VisitRecursive(google::protobuf::Message& message, Callback callback) {
189 // Compile if not yet compiled
190 Compile(message.GetDescriptor());
191
192 constexpr int kMaxRecursionLimit = 100;
193 const std::shared_lock read_lock = LockRead();
194 VisitRecursiveImpl(message, callback, kMaxRecursionLimit);
195 }
196
197protected:
198 explicit BaseVisitor(LockBehavior lock_behavior) : VisitorCompiler(lock_behavior) {}
199
200 // Disallow destruction via pointer to base
201 ~BaseVisitor() = default;
202
203 /// @brief Execute a callback without recursion
204 virtual void DoVisit(google::protobuf::Message& message, Callback callback) const = 0;
205
206private:
207 /// @brief Safe version with recursion_limit
208 void VisitRecursiveImpl(google::protobuf::Message& message, Callback callback, int recursion_limit) {
209 UINVARIANT(recursion_limit > 0, "Recursion limit reached while traversing protobuf Message.");
210
211 // Loop over this message
212 DoVisit(message, callback);
213
214 // Recurse into nested messages
215 const auto it = GetFieldsWithSelectedChildren().find(message.GetDescriptor());
216 if (it == GetFieldsWithSelectedChildren().end()) return;
217
218 const FieldDescriptorSet& fields = it->second;
219 for (const google::protobuf::FieldDescriptor* field : fields) {
220 UINVARIANT(field, "field is nullptr");
221 VisitNestedMessage(message, *field, [&](google::protobuf::Message& msg) {
222 VisitRecursiveImpl(msg, callback, recursion_limit - 1);
223 });
224 }
225 }
226};
227
228/// @brief Collects knowledge of the structure of the protobuf messages
229/// allowing for efficient loops over fields to apply a callback to the ones
230/// selected by the 'selector' function.
231///
232/// If you do not have static knowledge of the required fields, you should
233/// use @ref VisitFields or @ref VisitFieldsRecursive that are equivalent to
234/// FieldsVisitor with a `return true;` selector.
235///
236/// @warning You should not construct this at runtime as it performs significant
237/// computations in the constructor to precompile the visitors.
238/// You should create these at start-up.
239///
240/// Example usage:
241/// @snippet grpc/tests/protobuf_visit_test.cpp fields visitor
242class FieldsVisitor final : public BaseVisitor<FieldVisitCallback> {
243public:
244 using Selector = utils::function_ref<bool(const google::protobuf::FieldDescriptor& field)>;
245
246 /// @brief Creates the visitor with the given selector
247 /// and compiles it for the message types we can find.
248 explicit FieldsVisitor(Selector selector);
249
250 /// @brief Creates the visitor with the given selector
251 /// and compiles it for the given message types and their fields recursively.
252 FieldsVisitor(Selector selector, const DescriptorList& descriptors);
253
254 /// @brief Creates the visitor with custom thread locking behavior
255 /// and the given selector for runtime compilation.
256 ///
257 /// @warning Do not use this unless you know what you are doing.
258 FieldsVisitor(Selector selector, LockBehavior lock_behavior);
259
260 /// @brief Creates the visitor with custom thread locking behavior
261 /// and the given selector; compiles it for the given message types.
262 ///
263 /// @warning Do not use this unless you know what you are doing.
264 FieldsVisitor(Selector selector, const DescriptorList& descriptors, LockBehavior lock_behavior);
265
266 /// @cond
267 /// Only for internal use.
268 const Dependencies& GetSelectedFields(utils::impl::InternalTag) const;
269 /// @endcond
270
271private:
272 void CompileOne(const google::protobuf::Descriptor& descriptor) override;
273
274 bool IsSelected(const google::protobuf::Descriptor& descriptor) const override {
275 return selected_fields_.find(&descriptor) != selected_fields_.end();
276 }
277
278 void DoVisit(google::protobuf::Message& message, FieldVisitCallback callback) const override;
279
280 Dependencies selected_fields_;
281 const Selector selector_;
282};
283
284/// @brief Collects knowledge of the structure of the protobuf messages
285/// allowing for efficient loops over nested messages to apply a callback
286/// to the ones selected by the 'selector' function.
287///
288/// If you do not have static knowledge of the required messages, you should
289/// use @ref VisitMessagesRecursive that is equivalent to
290/// MessagesVisitor with a 'return true' selector.
291///
292/// @warning You should not construct this at runtime as it performs significant
293/// computations in the constructor to precompile the visitors.
294/// You should create this ones at start-up.
295class MessagesVisitor final : public BaseVisitor<MessageVisitCallback> {
296public:
297 using Selector = utils::function_ref<bool(const google::protobuf::Descriptor& descriptor)>;
298
299 /// @brief Creates the visitor with the given selector for runtime compilation
300 /// and compiles it for the message types we can find.
301 explicit MessagesVisitor(Selector selector);
302
303 /// @brief Creates the visitor with the given selector
304 /// and compiles it for the given message types and their fields recursively.
305 MessagesVisitor(Selector selector, const DescriptorList& descriptors);
306
307 /// @brief Creates the visitor with custom thread locking behavior
308 /// and the given selector for runtime compilation.
309 ///
310 /// @warning Do not use this unless you know what you are doing.
311 MessagesVisitor(Selector selector, LockBehavior lock_behavior);
312
313 /// @brief Creates the visitor with custom thread locking behavior
314 /// and the given selector; compiles it for the given message types.
315 ///
316 /// @warning Do not use this unless you know what you are doing.
317 MessagesVisitor(Selector selector, const DescriptorList& descriptors, LockBehavior lock_behavior);
318
319 /// @cond
320 /// Only for internal use.
321 const DescriptorSet& GetSelectedMessages(utils::impl::InternalTag) const;
322 /// @endcond
323
324private:
325 void CompileOne(const google::protobuf::Descriptor& descriptor) override;
326
327 bool IsSelected(const google::protobuf::Descriptor& descriptor) const override {
328 return selected_messages_.find(&descriptor) != selected_messages_.end();
329 }
330
331 void DoVisit(google::protobuf::Message& message, MessageVisitCallback callback) const override;
332
333 DescriptorSet selected_messages_;
334 const Selector selector_;
335};
336
337} // namespace ugrpc
338
339USERVER_NAMESPACE_END