Debian Codegraph @

src/core/lib/json/json_object_loader.h

raw
1 // Copyright 2020 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #ifndef GRPC_CORE_LIB_JSON_JSON_OBJECT_LOADER_H
16 #define GRPC_CORE_LIB_JSON_JSON_OBJECT_LOADER_H
17
18 #include <grpc/support/port_platform.h>
19
20 #include <cstdint>
21 #include <cstring>
22 #include <map>
23 #include <memory>
24 #include <string>
25 #include <utility>
26 #include <vector>
27
28 #include "absl/meta/type_traits.h"
29 #include "absl/status/statusor.h"
30 #include "absl/strings/numbers.h"
31 #include "absl/strings/str_cat.h"
32 #include "absl/strings/string_view.h"
33 #include "absl/types/optional.h"
34
35 #include "src/core/lib/gprpp/no_destruct.h"
36 #include "src/core/lib/gprpp/ref_counted_ptr.h"
37 #include "src/core/lib/gprpp/time.h"
38 #include "src/core/lib/gprpp/validation_errors.h"
39 #include "src/core/lib/json/json.h"
40 #include "src/core/lib/json/json_args.h"
41
42 // Provides a means to load JSON objects into C++ objects, with the aim of
43 // minimizing object code size.
44 //
45 // Usage:
46 // Given struct Foo:
47 // struct Foo {
48 // int a;
49 // int b;
50 // };
51 // We add a static JsonLoader() method to Foo to declare how to load the
52 // object from JSON, and an optional JsonPostLoad() method to do any
53 // necessary post-processing:
54 // struct Foo {
55 // int a;
56 // int b;
57 // static const JsonLoaderInterface* JsonLoader(const JsonArgs& args) {
58 // // Note: Field names must be string constants; they are not copied.
59 // static const auto* loader = JsonObjectLoader<Foo>()
60 // .Field("a", &Foo::a)
61 // .Field("b", &Foo::b)
62 // .Finish();
63 // return loader;
64 // }
65 // // Optional; omit if no post-processing needed.
66 // void JsonPostLoad(const Json& source, const JsonArgs& args,
67 // ValidationErrors* errors) {
68 // ++a;
69 // }
70 // };
71 // Now we can load Foo objects from JSON:
72 // absl::StatusOr<Foo> foo = LoadFromJson<Foo>(json);
73 namespace grpc_core {
74
75 namespace json_detail {
76
77 // An un-typed JSON loader.
78 class LoaderInterface {
79 public:
80 // Convert json value to whatever type we're loading at dst.
81 // If errors occur, add them to errors.
82 virtual void LoadInto(const Json& json, const JsonArgs& args, void* dst,
83 ValidationErrors* errors) const = 0;
84
85 protected:
86 ~LoaderInterface() = default;
87 };
88
89 // Loads a scalar (string or number).
90 class LoadScalar : public LoaderInterface {
91 public:
92 void LoadInto(const Json& json, const JsonArgs& args, void* dst,
93 ValidationErrors* errors) const override;
94
95 protected:
96 ~LoadScalar() = default;
97
98 private:
99 // true if we're loading a number, false if we're loading a string.
100 // We use a virtual function to store this decision in a vtable instead of
101 // needing an instance variable.
102 virtual bool IsNumber() const = 0;
103
104 virtual void LoadInto(const std::string& json, void* dst,
105 ValidationErrors* errors) const = 0;
106 };
107
108 // Load a string.
109 class LoadString : public LoadScalar {
110 protected:
111 ~LoadString() = default;
112
113 private:
114 bool IsNumber() const override;
115 void LoadInto(const std::string& value, void* dst,
116 ValidationErrors* errors) const override;
117 };
118
119 // Load a Duration.
120 class LoadDuration : public LoadScalar {
121 protected:
122 ~LoadDuration() = default;
123
124 private:
125 bool IsNumber() const override;
126 void LoadInto(const std::string& value, void* dst,
127 ValidationErrors* errors) const override;
128 };
129
130 // Load a number.
131 class LoadNumber : public LoadScalar {
132 protected:
133 ~LoadNumber() = default;
134
135 private:
136 bool IsNumber() const override;
137 };
138
139 // Load a signed number of type T.
140 template <typename T>
141 class TypedLoadSignedNumber : public LoadNumber {
142 protected:
143 ~TypedLoadSignedNumber() = default;
144
145 private:
146 void LoadInto(const std::string& value, void* dst,
147 ValidationErrors* errors) const override {
148 if (!absl::SimpleAtoi(value, static_cast<T*>(dst))) {
149 errors->AddError("failed to parse number");
150 }
151 }
152 };
153
154 // Load an unsigned number of type T.
155 template <typename T>
156 class TypedLoadUnsignedNumber : public LoadNumber {
157 protected:
158 ~TypedLoadUnsignedNumber() = default;
159
160 private:
161 void LoadInto(const std::string& value, void* dst,
162 ValidationErrors* errors) const override {
163 if (!absl::SimpleAtoi(value, static_cast<T*>(dst))) {
164 errors->AddError("failed to parse non-negative number");
165 }
166 }
167 };
168
169 // Load a float.
170 class LoadFloat : public LoadNumber {
171 protected:
172 ~LoadFloat() = default;
173
174 private:
175 void LoadInto(const std::string& value, void* dst,
176 ValidationErrors* errors) const override {
177 if (!absl::SimpleAtof(value, static_cast<float*>(dst))) {
178 errors->AddError("failed to parse floating-point number");
179 }
180 }
181 };
182
183 // Load a double.
184 class LoadDouble : public LoadNumber {
185 protected:
186 ~LoadDouble() = default;
187
188 private:
189 void LoadInto(const std::string& value, void* dst,
190 ValidationErrors* errors) const override {
191 if (!absl::SimpleAtod(value, static_cast<double*>(dst))) {
192 errors->AddError("failed to parse floating-point number");
193 }
194 }
195 };
196
197 // Load a bool.
198 class LoadBool : public LoaderInterface {
199 public:
200 void LoadInto(const Json& json, const JsonArgs& /*args*/, void* dst,
201 ValidationErrors* errors) const override;
202
203 protected:
204 ~LoadBool() = default;
205 };
206
207 // Loads an unprocessed JSON object value.
208 class LoadUnprocessedJsonObject : public LoaderInterface {
209 public:
210 void LoadInto(const Json& json, const JsonArgs& /*args*/, void* dst,
211 ValidationErrors* errors) const override;
212
213 protected:
214 ~LoadUnprocessedJsonObject() = default;
215 };
216
217 // Load a vector of some type.
218 class LoadVector : public LoaderInterface {
219 public:
220 void LoadInto(const Json& json, const JsonArgs& args, void* dst,
221 ValidationErrors* errors) const override;
222
223 protected:
224 ~LoadVector() = default;
225
226 private:
227 virtual void* EmplaceBack(void* dst) const = 0;
228 virtual const LoaderInterface* ElementLoader() const = 0;
229 };
230
231 // Load a map of string->some type.
232 class LoadMap : public LoaderInterface {
233 public:
234 void LoadInto(const Json& json, const JsonArgs& args, void* dst,
235 ValidationErrors* errors) const override;
236
237 protected:
238 ~LoadMap() = default;
239
240 private:
241 virtual void* Insert(const std::string& name, void* dst) const = 0;
242 virtual const LoaderInterface* ElementLoader() const = 0;
243 };
244
245 // Load an optional of some type.
246 class LoadOptional : public LoaderInterface {
247 public:
248 void LoadInto(const Json& json, const JsonArgs& args, void* dst,
249 ValidationErrors* errors) const override;
250
251 protected:
252 ~LoadOptional() = default;
253
254 private:
255 virtual void* Emplace(void* dst) const = 0;
256 virtual void Reset(void* dst) const = 0;
257 virtual const LoaderInterface* ElementLoader() const = 0;
258 };
259
260 // Fetch a LoaderInterface for some type.
261 template <typename T>
262 const LoaderInterface* LoaderForType();
263
264 // AutoLoader implements LoaderInterface for a type.
265 // The default asks the type for its LoaderInterface and then uses that.
266 // Classes that load from objects should provide a:
267 // static const JsonLoaderInterface* JsonLoader();
268 template <typename T>
269 class AutoLoader final : public LoaderInterface {
270 public:
271 void LoadInto(const Json& json, const JsonArgs& args, void* dst,
272 ValidationErrors* errors) const override {
273 T::JsonLoader(args)->LoadInto(json, args, dst, errors);
274 }
275
276 private:
277 ~AutoLoader() = default;
278 };
279
280 // Specializations of AutoLoader for basic types.
281 template <>
282 class AutoLoader<std::string> final : public LoadString {
283 private:
284 ~AutoLoader() = default;
285 };
286 template <>
287 class AutoLoader<Duration> final : public LoadDuration {
288 private:
289 ~AutoLoader() = default;
290 };
291 template <>
292 class AutoLoader<int32_t> final : public TypedLoadSignedNumber<int32_t> {
293 private:
294 ~AutoLoader() = default;
295 };
296 template <>
297 class AutoLoader<int64_t> final : public TypedLoadSignedNumber<int64_t> {
298 private:
299 ~AutoLoader() = default;
300 };
301 template <>
302 class AutoLoader<uint32_t> final : public TypedLoadUnsignedNumber<uint32_t> {
303 private:
304 ~AutoLoader() = default;
305 };
306 template <>
307 class AutoLoader<uint64_t> final : public TypedLoadUnsignedNumber<uint64_t> {
308 private:
309 ~AutoLoader() = default;
310 };
311 template <>
312 class AutoLoader<float> final : public LoadFloat {
313 private:
314 ~AutoLoader() = default;
315 };
316 template <>
317 class AutoLoader<double> final : public LoadDouble {
318 private:
319 ~AutoLoader() = default;
320 };
321 template <>
322 class AutoLoader<bool> final : public LoadBool {
323 private:
324 ~AutoLoader() = default;
325 };
326 template <>
327 class AutoLoader<Json::Object> final : public LoadUnprocessedJsonObject {
328 private:
329 ~AutoLoader() = default;
330 };
331
332 // Specializations of AutoLoader for vectors.
333 template <typename T>
334 class AutoLoader<std::vector<T>> final : public LoadVector {
335 private:
336 ~AutoLoader() = default;
337 void* EmplaceBack(void* dst) const final {
338 auto* vec = static_cast<std::vector<T>*>(dst);
339 vec->emplace_back();
340 return &vec->back();
341 }
342 const LoaderInterface* ElementLoader() const final {
343 return LoaderForType<T>();
344 }
345 };
346
347 // Specialization of AutoLoader for vector<bool> - we need a different
348 // implementation because, as vector<bool> packs bits in its implementation, the
349 // technique of returning a void* from Emplace() for the generic vector loader
350 // doesn't work.
351 template <>
352 class AutoLoader<std::vector<bool>> final : public LoaderInterface {
353 public:
354 void LoadInto(const Json& json, const JsonArgs& args, void* dst,
355 ValidationErrors* errors) const override;
356
357 private:
358 ~AutoLoader() = default;
359 };
360
361 // Specializations of AutoLoader for maps.
362 template <typename T>
363 class AutoLoader<std::map<std::string, T>> final : public LoadMap {
364 private:
365 void* Insert(const std::string& name, void* dst) const final {
366 return &static_cast<std::map<std::string, T>*>(dst)
367 ->emplace(name, T())
368 .first->second;
369 };
370 const LoaderInterface* ElementLoader() const final {
371 return LoaderForType<T>();
372 }
373
374 private:
375 ~AutoLoader() = default;
376 };
377
378 // Specializations of AutoLoader for absl::optional<>.
379 template <typename T>
380 class AutoLoader<absl::optional<T>> final : public LoadOptional {
381 public:
382 void* Emplace(void* dst) const final {
383 return &static_cast<absl::optional<T>*>(dst)->emplace();
384 }
385 void Reset(void* dst) const final {
386 static_cast<absl::optional<T>*>(dst)->reset();
387 }
388 const LoaderInterface* ElementLoader() const final {
389 return LoaderForType<T>();
390 }
391
392 private:
393 ~AutoLoader() = default;
394 };
395
396 // Specializations of AutoLoader for std::unique_ptr<>.
397 template <typename T>
398 class AutoLoader<std::unique_ptr<T>> final : public LoadOptional {
399 public:
400 void* Emplace(void* dst) const final {
401 auto& p = *static_cast<std::unique_ptr<T>*>(dst);
402 p = std::make_unique<T>();
403 return p.get();
404 }
405 void Reset(void* dst) const final {
406 static_cast<std::unique_ptr<T>*>(dst)->reset();
407 }
408 const LoaderInterface* ElementLoader() const final {
409 return LoaderForType<T>();
410 }
411
412 private:
413 ~AutoLoader() = default;
414 };
415
416 // Implementation of aforementioned LoaderForType.
417 // Simply keeps a static AutoLoader<T> and returns a pointer to that.
418 template <typename T>
419 const LoaderInterface* LoaderForType() {
420 return NoDestructSingleton<AutoLoader<T>>::Get();
421 }
422
423 // Element describes one typed field to be loaded from a JSON object.
424 struct Element {
425 Element() = default;
426 template <typename A, typename B>
427 Element(const char* name, bool optional, B A::*p,
428 const LoaderInterface* loader, const char* enable_key)
429 : loader(loader),
430 member_offset(static_cast<uint16_t>(
431 reinterpret_cast<uintptr_t>(&(static_cast<A*>(nullptr)->*p)))),
432 optional(optional),
433 name(name),
434 enable_key(enable_key) {}
435 // The loader for this field.
436 const LoaderInterface* loader;
437 // Offset into the destination object to store the field.
438 uint16_t member_offset;
439 // Is this field optional?
440 bool optional;
441 // The name of the field.
442 const char* name;
443 // The key to use with JsonArgs to see if this field is enabled.
444 const char* enable_key;
445 };
446
447 // Vec<T, kSize> provides a constant array type that can be appended to by
448 // copying. It's setup so that most compilers can optimize away all of its
449 // operations.
450 template <typename T, size_t kSize>
451 class Vec {
452 public:
453 Vec(const Vec<T, kSize - 1>& other, const T& new_value) {
454 for (size_t i = 0; i < other.size(); i++) values_[i] = other.data()[i];
455 values_[kSize - 1] = new_value;
456 }
457
458 const T* data() const { return values_; }
459 size_t size() const { return kSize; }
460
461 private:
462 T values_[kSize];
463 };
464
465 template <typename T>
466 class Vec<T, 0> {
467 public:
468 const T* data() const { return nullptr; }
469 size_t size() const { return 0; }
470 };
471
472 // Given a list of elements, and a destination object, load the elements into
473 // the object from some parsed JSON.
474 // Returns false if the JSON object was not of type Json::Type::OBJECT.
475 bool LoadObject(const Json& json, const JsonArgs& args, const Element* elements,
476 size_t num_elements, void* dst, ValidationErrors* errors);
477
478 // Adaptor type - takes a compile time computed list of elements and
479 // implements LoaderInterface by calling LoadObject.
480 template <typename T, size_t kElemCount, typename Hidden = void>
481 class FinishedJsonObjectLoader final : public LoaderInterface {
482 public:
483 explicit FinishedJsonObjectLoader(const Vec<Element, kElemCount>& elements)
484 : elements_(elements) {}
485
486 void LoadInto(const Json& json, const JsonArgs& args, void* dst,
487 ValidationErrors* errors) const override {
488 LoadObject(json, args, elements_.data(), elements_.size(), dst, errors);
489 }
490
491 private:
492 GPR_NO_UNIQUE_ADDRESS Vec<Element, kElemCount> elements_;
493 };
494
495 // Specialization for when the object has a JsonPostLoad function exposed.
496 template <typename T, size_t kElemCount>
497 class FinishedJsonObjectLoader<T, kElemCount,
498 absl::void_t<decltype(&T::JsonPostLoad)>>
499 final : public LoaderInterface {
500 public:
501 explicit FinishedJsonObjectLoader(const Vec<Element, kElemCount>& elements)
502 : elements_(elements) {}
503
504 void LoadInto(const Json& json, const JsonArgs& args, void* dst,
505 ValidationErrors* errors) const override {
506 // Call JsonPostLoad() only if json is a JSON object.
507 if (LoadObject(json, args, elements_.data(), elements_.size(), dst,
508 errors)) {
509 static_cast<T*>(dst)->JsonPostLoad(json, args, errors);
510 }
511 }
512
513 private:
514 GPR_NO_UNIQUE_ADDRESS Vec<Element, kElemCount> elements_;
515 };
516
517 // Builder type for JSON object loaders.
518 // Concatenate fields with Field, OptionalField, and then call Finish to
519 // obtain an object that implements LoaderInterface.
520 template <typename T, size_t kElemCount = 0>
521 class JsonObjectLoader final {
522 public:
523 JsonObjectLoader() {
524 static_assert(kElemCount == 0,
525 "Only initial loader step can have kElemCount==0.");
526 }
527
528 FinishedJsonObjectLoader<T, kElemCount>* Finish() const {
529 return new FinishedJsonObjectLoader<T, kElemCount>(elements_);
530 }
531
532 template <typename U>
533 JsonObjectLoader<T, kElemCount + 1> Field(
534 const char* name, U T::*p, const char* enable_key = nullptr) const {
535 return Field(name, false, p, enable_key);
536 }
537
538 template <typename U>
539 JsonObjectLoader<T, kElemCount + 1> OptionalField(
540 const char* name, U T::*p, const char* enable_key = nullptr) const {
541 return Field(name, true, p, enable_key);
542 }
543
544 JsonObjectLoader(const Vec<Element, kElemCount - 1>& elements,
545 Element new_element)
546 : elements_(elements, new_element) {}
547
548 private:
549 template <typename U>
550 JsonObjectLoader<T, kElemCount + 1> Field(const char* name, bool optional,
551 U T::*p,
552 const char* enable_key) const {
553 return JsonObjectLoader<T, kElemCount + 1>(
554 elements_, Element(name, optional, p, LoaderForType<U>(), enable_key));
555 }
556
557 GPR_NO_UNIQUE_ADDRESS Vec<Element, kElemCount> elements_;
558 };
559
560 const Json* GetJsonObjectField(const Json::Object& json,
561 absl::string_view field,
562 ValidationErrors* errors, bool required);
563
564 } // namespace json_detail
565
566 template <typename T>
567 using JsonObjectLoader = json_detail::JsonObjectLoader<T>;
568
569 using JsonLoaderInterface = json_detail::LoaderInterface;
570
571 template <typename T>
572 absl::StatusOr<T> LoadFromJson(
573 const Json& json, const JsonArgs& args = JsonArgs(),
574 absl::string_view error_prefix = "errors validating JSON") {
575 ValidationErrors errors;
576 T result{};
577 json_detail::LoaderForType<T>()->LoadInto(json, args, &result, &errors);
578 if (!errors.ok()) return errors.status(error_prefix);
579 return std::move(result);
580 }
581
582 template <typename T>
583 absl::StatusOr<RefCountedPtr<T>> LoadRefCountedFromJson(
584 const Json& json, const JsonArgs& args = JsonArgs(),
585 absl::string_view error_prefix = "errors validating JSON") {
586 ValidationErrors errors;
587 auto result = MakeRefCounted<T>();
588 json_detail::LoaderForType<T>()->LoadInto(json, args, result.get(), &errors);
589 if (!errors.ok()) return errors.status(error_prefix);
590 return std::move(result);
591 }
592
593 template <typename T>
594 T LoadFromJson(const Json& json, const JsonArgs& args,
595 ValidationErrors* errors) {
596 T result{};
597 json_detail::LoaderForType<T>()->LoadInto(json, args, &result, errors);
598 return result;
599 }
600
601 template <typename T>
602 absl::optional<T> LoadJsonObjectField(const Json::Object& json,
603 const JsonArgs& args,
604 absl::string_view field,
605 ValidationErrors* errors,
606 bool required = true) {
607 ValidationErrors::ScopedField error_field(errors, absl::StrCat(".", field));
608 const Json* field_json =
609 json_detail::GetJsonObjectField(json, field, errors, required);
610 if (field_json == nullptr) return absl::nullopt;
611 T result{};
612 size_t starting_error_size = errors->size();
613 json_detail::LoaderForType<T>()->LoadInto(*field_json, args, &result, errors);
614 if (errors->size() > starting_error_size) return absl::nullopt;
615 return std::move(result);
616 }
617
618 } // namespace grpc_core
619
620 #endif // GRPC_CORE_LIB_JSON_JSON_OBJECT_LOADER_H