mirror of
https://codeberg.org/DawnMagnet/reflect-cpp
synced 2026-12-06 18:56:19 +08:00
Added support for Apache Avro, and thus for schemaful formats (#303)
This commit is contained in:
@@ -12,6 +12,9 @@ If you want your class to be supported by reflect-cpp, it needs to have the foll
|
||||
If you class fulfills these three conditions, then it is fully supported by all serialization and deserialization
|
||||
routines in reflect-cpp.
|
||||
|
||||
Please be aware that due to limitations of the Avro format, it is a good idea to always have a struct as your
|
||||
`ReflectionType` when using Avro to avoid infinite recursions.
|
||||
|
||||
If you absolutely do not want to make any changes to your original class, you can implement a [custom parser](https://github.com/getml/reflect-cpp/blob/main/docs/custom_parser.md).
|
||||
|
||||
## Example 1: Using an Impl struct
|
||||
|
||||
@@ -5,6 +5,8 @@ reflect-cpp is intended to be used to directly parse into structs. Doing this is
|
||||
But in some cases, we simply cannot anticipate the complete structure of the data at compile time. For these cases, we
|
||||
have `rfl::Generic`.
|
||||
|
||||
Note that generics are not supported for Avro.
|
||||
|
||||
`rfl::Generic` is a convenience wrapper around the following type:
|
||||
|
||||
```cpp
|
||||
|
||||
+1
-11
@@ -18,17 +18,7 @@ hide:
|
||||
[](https://shields.io/)
|
||||
[](https://conan.io/center/recipes/reflect-cpp)
|
||||
|
||||
**📖 Documentation**: [https://rfl.getml.com](https://rfl.getml.com) — **👨💻 Source Code**: [https://github.com/getml/reflect-cpp](https://github.com/getml/reflect-cpp)
|
||||
|
||||
</div>
|
||||
|
||||
><br> **📣 From the Author (01.11.2024):** Hi everyone, Patrick ([liuzicheng1987](https://github.com/liuzicheng1987)) here. With reflect-cpp reaching the 1k-star milestone, we’re excited to roll out an overhauled documentation site at [https://rfl.getml.com](https://rfl.getml.com/), giving it a permanent place in our company. Initially developed as an internal tool for our machine learning library, [getML](https://getml.com), reflect-cpp has grown into something much larger.
|
||||
<br> A big thank you to all contributors for helping us reach this point! Your feedback, ideas, and dedication have been invaluable.
|
||||
<br> As we look to the project’s future, I would like to hear your thoughts on potential new directions, discuss ideas to expand our user base, or learn more about what you’re building with it. For the next month, I am opening a few slots in my calendar for anyone who wants to [connect (link)](https://calendar.app.google/AaeziooCNierbwAZ8).
|
||||
<br> *— Best, Patrick*
|
||||
<br>
|
||||
|
||||
<br>
|
||||
**💻 Source Code**: [https://github.com/getml/reflect-cpp](https://github.com/getml/reflect-cpp)
|
||||
|
||||
**reflect-cpp** is a C++-20 library for **fast serialization, deserialization and validation** using reflection, similar to [pydantic](https://github.com/pydantic/pydantic) in Python, [serde](https://github.com/serde-rs) in Rust, [encoding](https://github.com/golang/go/tree/master/src/encoding) in Go or [aeson](https://github.com/haskell/aeson/tree/master) in Haskell.
|
||||
|
||||
|
||||
+2
-1
@@ -68,6 +68,7 @@ To use reflect-cpp in your project:
|
||||
```cmake
|
||||
add_subdirectory(reflect-cpp) # Add this project as a subdirectory
|
||||
|
||||
set(REFLECTCPP_AVRO ON) # Optional
|
||||
set(REFLECTCPP_BSON ON) # Optional
|
||||
set(REFLECTCPP_CBOR ON) # Optional
|
||||
set(REFLECTCPP_FLEXBUFFERS ON) # Optional
|
||||
@@ -110,7 +111,7 @@ conan build . --build=missing -s compiler.cppstd=gnu20
|
||||
|
||||
You can call `conan inspect .` to get an overview of the supported options.
|
||||
|
||||
If you want to include all supported formats, do the following:
|
||||
If you want to include all formats supported on Conan, do the following:
|
||||
|
||||
```bash
|
||||
conan build . --build=missing -s compiler.cppstd=gnu20 -o *:with_cbor=True -o *:with_flatbuffers=True -o *:with_msgpack=True -o *:with_toml=True -o *:with_ubjson=True -o *:with_xml=True -o *:with_yaml=True
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
It is possible to skip the serialization and deserialization of fields using `rfl::Skip`.
|
||||
|
||||
Note that `rfl::Skip` is unsupported by all schemaful formats, like Avro.
|
||||
|
||||
```cpp
|
||||
struct Person {
|
||||
rfl::Rename<"firstName", std::string> first_name;
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
# Avro
|
||||
|
||||
For Avro support, you must also include the header `<rfl/avro.hpp>` and link to the `avro-c` library (https://avro.apache.org/docs/1.6.3/api/c/index.html).
|
||||
|
||||
Avro is a schemaful binary format. This sets it apart from most other formats supported by reflect-cpp, which are schemaless.
|
||||
|
||||
## Reading and writing
|
||||
|
||||
Suppose you have a struct like this:
|
||||
|
||||
```cpp
|
||||
struct Person {
|
||||
std::string first_name;
|
||||
std::string last_name;
|
||||
rfl::Timestamp<"%Y-%m-%d"> birthday;
|
||||
std::vector<Person> children;
|
||||
};
|
||||
```
|
||||
|
||||
A `Person` struct can be serialized to a bytes vector like this:
|
||||
|
||||
```cpp
|
||||
const auto person = Person{...};
|
||||
const std::vector<char> bytes = rfl::avro::write(person);
|
||||
```
|
||||
|
||||
You can parse bytes like this:
|
||||
|
||||
```cpp
|
||||
const rfl::Result<Person> result = rfl::avro::read<Person>(bytes);
|
||||
```
|
||||
|
||||
## The schema
|
||||
|
||||
However, Avro is a schemaful format, so before you serialize or
|
||||
deserialize, you have to declare a schema. In the two function calls
|
||||
above, this is abstracted away.
|
||||
|
||||
But if you are repeated serializing or deserializing the same struct,
|
||||
it is more efficient to generate the schema explicitly:
|
||||
|
||||
```cpp
|
||||
const auto schema = rfl::avro::to_schema<Person>();
|
||||
|
||||
const auto person = Person{...};
|
||||
const std::vector<char> bytes = rfl::avro::write(person, schema);
|
||||
|
||||
const rfl::Result<Person> result = rfl::avro::read<Person>(bytes, schema);
|
||||
```
|
||||
|
||||
Avro schemas are created using a JSON-based schema language. You can
|
||||
retrieve the JSON representation like this:
|
||||
|
||||
```cpp
|
||||
// Both calls are equivalent.
|
||||
schema.json_str();
|
||||
schema.str();
|
||||
```
|
||||
|
||||
In this case, the resulting JSON schema representation looks like this:
|
||||
|
||||
```json
|
||||
{"type":"record","name":"Person","fields":[{"name":"first_name","type":{"type":"string"}},{"name":"last_name","type":{"type":"string"}},{"name":"birthday","type":{"type":"string"}},{"name":"children","type":{"type":"array","items":{"type":"Person"},"default":[]}}]}
|
||||
```
|
||||
|
||||
## Loading and saving
|
||||
|
||||
You can also load and save to disc using a very similar syntax:
|
||||
|
||||
```cpp
|
||||
const rfl::Result<Person> result = rfl::avro::load<Person>("/path/to/file.avro");
|
||||
|
||||
const auto person = Person{...};
|
||||
rfl::avro::save("/path/to/file.avro", person);
|
||||
```
|
||||
|
||||
## Reading from and writing into streams
|
||||
|
||||
You can also read from and write into any `std::istream` and `std::ostream` respectively.
|
||||
|
||||
```cpp
|
||||
const rfl::Result<Person> result = rfl::avro::read<Person>(my_istream);
|
||||
|
||||
const auto person = Person{...};
|
||||
rfl::avro::write(person, my_ostream);
|
||||
```
|
||||
|
||||
Note that `std::cout` is also an ostream, so this works as well:
|
||||
|
||||
```cpp
|
||||
rfl::avro::write(person, std::cout) << std::endl;
|
||||
```
|
||||
|
||||
(Since Avro is a binary format, the readability of this will be limited, but it might be useful for debugging).
|
||||
|
||||
## Custom constructors
|
||||
|
||||
One of the great things about C++ is that it gives you control over
|
||||
when and how you code is compiled.
|
||||
|
||||
For large and complex systems of structs, it is often a good idea to split up
|
||||
your code into smaller compilation units. You can do so using custom constructors.
|
||||
|
||||
For the Avro format, these must be a static function on your struct or class called
|
||||
`from_avro` that take a `rfl::avro::Reader::InputVarType` as input and return
|
||||
the class or the class wrapped in `rfl::Result`.
|
||||
|
||||
In your header file you can write something like this:
|
||||
|
||||
```cpp
|
||||
struct Person {
|
||||
rfl::Rename<"firstName", std::string> first_name;
|
||||
rfl::Rename<"lastName", std::string> last_name;
|
||||
rfl::Timestamp<"%Y-%m-%d"> birthday;
|
||||
|
||||
using InputVarType = typename rfl::avro::Reader::InputVarType;
|
||||
static rfl::Result<Person> from_avro(const InputVarType& _obj);
|
||||
};
|
||||
```
|
||||
|
||||
And in your source file, you implement `from_avro` as follows:
|
||||
|
||||
```cpp
|
||||
rfl::Result<Person> Person::from_avro(const InputVarType& _obj) {
|
||||
const auto from_nt = [](auto&& _nt) {
|
||||
return rfl::from_named_tuple<Person>(std::move(_nt));
|
||||
};
|
||||
return rfl::avro::read<rfl::named_tuple_t<Person>>(_obj)
|
||||
.transform(from_nt);
|
||||
}
|
||||
```
|
||||
|
||||
This will force the compiler to only compile the Avro parsing when the source file is compiled.
|
||||
@@ -181,11 +181,13 @@ struct Reader {
|
||||
|
||||
/// Retrieves a particular field from an array.
|
||||
/// Returns an rfl::Error if the index is out of bounds.
|
||||
/// If your format is schemaful, you do not need this.
|
||||
rfl::Result<InputVarType> get_field_from_array(
|
||||
const size_t _idx, const InputArrayType _arr) const noexcept {...}
|
||||
|
||||
/// Retrieves a particular field from an object.
|
||||
/// Returns an rfl::Error if the field cannot be found.
|
||||
/// If your format is schemaful, you do not need this.
|
||||
rfl::Result<InputVarType> get_field_from_object(
|
||||
const std::string& _name, const InputObjectType& _obj) const noexcept {...}
|
||||
|
||||
@@ -261,3 +263,178 @@ void read(const std::string_view& _name,
|
||||
|
||||
Within your implementation of `read_object`, you must iterate through the object passed
|
||||
to the function and then insert the resulting key-value-pairs into `object_reader.read`.
|
||||
|
||||
## Additional requirements for schemaful formats
|
||||
|
||||
Schemaful formats, like Apache Avro or Cap'n Proto,
|
||||
are somewhat more complicated than schemaless ones. There are additional factors
|
||||
to consider which do not apply schemaless formats:
|
||||
|
||||
1. Schemaful formats needs to differentiate between *objects*, for which
|
||||
the field names are known at compile time and *maps*, for which the
|
||||
field names are not known at compile time. In schemaless formats, there
|
||||
is no differentiation.
|
||||
|
||||
2. Schemaful formats needs an explicit union types. This also means that
|
||||
many of the problems we have with serializing `std::variant` which
|
||||
requires us to develop concepts like `rfl::TaggedUnion` simply do not
|
||||
apply to schemaful formats - the problem is already solved.
|
||||
|
||||
### Additional requirements for schemaful writers
|
||||
|
||||
Any schemaful reader additionally needs to define the following:
|
||||
|
||||
1) An `OutputMapType`, which must contain key-value pairs.
|
||||
2) An `OutputUnionType`, which represents an explicit union.
|
||||
|
||||
```cpp
|
||||
struct Writer {
|
||||
using OutputArrayType = ...;
|
||||
using OutputMapType = ...;
|
||||
using OutputObjectType = ...;
|
||||
using OutputUnionType = ...;
|
||||
using OutputVarType = ...;
|
||||
|
||||
/// Sets an empty map as the root element of the document.
|
||||
/// Some serialization formats require you to pass the expected size in
|
||||
/// advance. If you are not working with such a format, you can ignore the
|
||||
/// parameter `size`. Returns the new array for further modification.
|
||||
OutputMapType map_as_root(const size_t _size) const noexcept;
|
||||
|
||||
/// Sets an empty union as the root element of the document.
|
||||
OutputUnionType union_as_root() const noexcept;
|
||||
|
||||
/// Adds an empty array to an existing map. Returns the new
|
||||
/// array for further modification.
|
||||
OutputArrayType add_array_to_map(const std::string_view& _name,
|
||||
const size_t _size,
|
||||
OutputMapType* _parent) const noexcept;
|
||||
|
||||
/// Adds an empty array to an existing union.
|
||||
/// The index refers to the index of the element in the union.
|
||||
/// Returns the new array for further modification.
|
||||
OutputArrayType add_array_to_union(const size_t _index, const size_t _size,
|
||||
OutputUnionType* _parent) const noexcept;
|
||||
|
||||
/// Adds an empty map to an existing array. Returns the new
|
||||
/// map for further modification.
|
||||
OutputMapType add_map_to_array(const size_t _size,
|
||||
OutputArrayType* _parent) const noexcept;
|
||||
|
||||
/// Adds an empty map to an existing map. The key or name of the field
|
||||
/// is signified by `name`. Returns the new map for further modification.
|
||||
OutputMapType add_map_to_map(const std::string_view& _name,
|
||||
const size_t _size,
|
||||
OutputMapType* _parent) const noexcept;
|
||||
|
||||
/// Adds an empty map to an existing object. The key or name of the field
|
||||
/// is signified by `name`. Returns the new map for further modification.
|
||||
OutputMapType add_map_to_object(const std::string_view& _name,
|
||||
const size_t _size,
|
||||
OutputObjectType* _parent) const noexcept;
|
||||
|
||||
/// Adds an empty map to an existing union.
|
||||
/// The index refers to the index of the element in the union.
|
||||
/// Returns the new map for further modification.
|
||||
OutputMapType add_map_to_union(const size_t _index, const size_t _size,
|
||||
OutputUnionType* _parent) const noexcept;
|
||||
|
||||
/// Adds an empty object to an existing map. The key or name of the field
|
||||
/// is signified by `name`. Returns the new object for further modification.
|
||||
OutputObjectType add_object_to_map(const std::string_view& _name,
|
||||
const size_t _size,
|
||||
OutputMapType* _parent) const noexcept;
|
||||
|
||||
/// Adds an empty object to an existing union.
|
||||
/// The index refers to the index of the element in the union.
|
||||
/// Returns the new object for further modification.
|
||||
OutputObjectType add_object_to_union(const size_t _index, const size_t _size,
|
||||
OutputUnionType* _parent) const noexcept;
|
||||
|
||||
/// Adds an empty union to an existing array. Returns the new
|
||||
/// union for further modification.
|
||||
OutputUnionType add_union_to_array(OutputArrayType* _parent) const noexcept;
|
||||
|
||||
/// Adds an empty union to an existing map. The key or name of the field
|
||||
/// is signified by `name`. Returns the new union for further modification.
|
||||
OutputUnionType add_union_to_map(const std::string_view& _name,
|
||||
OutputMapType* _parent) const noexcept;
|
||||
|
||||
/// Adds an empty union to an existing object. The key or name of the field
|
||||
/// is signified by `name`. Returns the new union for further modification.
|
||||
OutputUnionType add_union_to_object(const std::string_view& _name,
|
||||
OutputObjectType* _parent) const noexcept;
|
||||
|
||||
/// Adds an empty union to an existing union.
|
||||
/// The index refers to the index of the element in the union.
|
||||
/// Returns the new union for further modification.
|
||||
OutputUnionType add_union_to_union(const size_t _index,
|
||||
OutputUnionType* _parent) const noexcept;
|
||||
|
||||
/// Adds a null value to a map. Returns an
|
||||
/// OutputVarType containing the null value.
|
||||
OutputVarType add_null_to_map(const std::string_view& _name,
|
||||
OutputMapType* _parent) const noexcept;
|
||||
|
||||
/// Adds a null value to a union. Returns an
|
||||
/// OutputVarType containing the null value.
|
||||
OutputVarType add_null_to_union(const size_t _index,
|
||||
OutputUnionType* _parent) const noexcept;
|
||||
|
||||
/// Adds a basic value (bool, numeric, string) to an existing map. The key
|
||||
/// or name of the field is signified by `name`. Returns an
|
||||
/// OutputVarType containing the new value.
|
||||
template <class T>
|
||||
OutputVarType add_value_to_map(const std::string_view& _name, const T& _var,
|
||||
OutputMapType* _parent) const noexcept;
|
||||
|
||||
/// Adds a basic value (bool, numeric, string) to an existing union. The key
|
||||
/// or name of the field is signified by `name`. Returns an
|
||||
/// OutputVarType containing the new value.
|
||||
template <class T>
|
||||
OutputVarType add_value_to_union(const size_t _index, const T& _var,
|
||||
OutputUnionType* _parent) const noexcept;
|
||||
|
||||
/// Signifies to the writer that we do not want to add any further elements to
|
||||
/// this map. Some serialization formats require this. If you are working
|
||||
/// with a serialization format that doesn't, just leave the function empty.
|
||||
void end_map(OutputMapType* _obj) const noexcept;
|
||||
|
||||
};
|
||||
```
|
||||
|
||||
### Additional requirements for schemaful readers
|
||||
|
||||
Any schemaful reader additionally needs to define the following:
|
||||
|
||||
1) An `InputMapType`, which must contain key-value pairs.
|
||||
2) An `InputUnionType`, which represents an explicit union.
|
||||
|
||||
```cpp
|
||||
struct Reader {
|
||||
using InputArrayType = ...;
|
||||
using InputObjectType = ...;
|
||||
using InputMapType = ...;
|
||||
using InputUnionType = ...;
|
||||
using InputVarType = ...;
|
||||
|
||||
/// A schemaful reader needs to differentiate between objects, for which
|
||||
/// the field names are known at compile time and maps, for which the
|
||||
/// field names are not known at compile time.
|
||||
rfl::Result<InputMapType> to_map(const InputVarType& _var) const noexcept;
|
||||
|
||||
/// read_map works exactly the same as read_object in schemaless formats.
|
||||
template <class MapReader>
|
||||
std::optional<Error> read_map(const MapReader& _map_reader,
|
||||
const InputMapType& _map) const noexcept;
|
||||
|
||||
/// A schemaful reader needs an explicit union type.
|
||||
rfl::Result<InputUnionType> to_union(const InputVarType& _var) const noexcept;
|
||||
|
||||
/// read_union needs to be able to take an InputUnionType and return the corresponding
|
||||
/// variant (like std::variant or rfl::Variant).
|
||||
template <class VariantType, class UnionReaderType>
|
||||
rfl::Result<VariantType> read_union(
|
||||
const InputUnionType& _union) const noexcept;
|
||||
};
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user