AnCH Framework 0.2
Another C++ Hack: C++23 utility libraries
Loading...
Searching...
No Matches
AnCH codec library documentation

Introduction

AnCH codec library associates content types ( MediaType ) with serialization and deserialization of C++ values. anch-rest uses codecs for requests and responses bodies ; they do not depend on HTTP, so that other libraries (messaging) read and write their contents with the same codecs.

Libraries

anch-codec is built with anch-rest (since 0.3, codecs were part of anch-rest in 0.2). The core has no format dependency ; each format is a plugin library built according to its option. Plugins with external dependencies are skipped with a CMake status message when their dependencies are not found.

CMake target Option Content
anch::codec concepts, MediaType and negotiation, limits, Side, Text, Codecs, formats registry
anch::codec-json ANCH_CODEC_JSON (needed by anch-rest) Json (anch-json)
anch::codec-csv ANCH_CODEC_CSV (anch-csv) Csv (lists of described objects)
anch::codec-protobuf ANCH_CODEC_PROTOBUF (Protobuf) Protobuf, ProtobufJson
anch::codec-thrift ANCH_CODEC_THRIFT (Thrift and Boost headers) ThriftBinary, ThriftCompact, ThriftJson
anch::codec-all codec/all.hpp : every plugin built and anch::codec::Available
find_package(Anch REQUIRED)
target_link_libraries(my-app PRIVATE anch::codec-json)

See installation.

Codecs

A codec is a type with static functions: mediaType() and serialize / deserialize , with one of their forms (value and stream ; plus Side ; plus content type and side), see Serializer and Deserializer:

// text/csv codec of a list of numbers: one serialize / deserialize form is enough
struct NumbersCsv {
static std::string_view
mediaType() noexcept {
return "text/csv";
}
static void
serialize(const std::vector<int>& values, std::ostream& out) {
for(std::size_t i = 0; i < values.size(); ++i) {
out << (i == 0 ? "" : ",") << values[i];
}
}
static void
deserialize(std::vector<int>& values, std::istream& input, anch::codec::Side side) {
// Data which is not controlled ( SERVER ) is bounded
std::istringstream content(anch::codec::readBody(input, side));
for(std::string value; std::getline(content, value, ',');) {
values.push_back(std::stoi(value));
}
}
};

contentTypeOf, serialize and deserialize call the richest form a codec defines:

// Content type first (a codec can add parameters), then serialization with the trust policy of the side
const Pet pet{1, "Rex"};
std::ostringstream out;
std::cout << type.toString() << ' ' << out.str() << std::endl; // application/json {"id":1,"name":"Rex"}

Data formats

A data format ( DataFormat: anch::json::JsonFormat , anch::csv::CsvFormat ) serializes values with options, without depending on anch-codec. FormatCodec makes a codec of it: media type, options of each side copied from the format default options and configured by the format FormatPolicy (specialized by its plugin, which also translates errors into ContentTooLarge). Json is FormatCodec<anch::json::JsonFormat> and Csv FormatCodec<anch::csv::CsvFormat> ; a new text format gets its codec without code of its own.

Trust policy

Side is the trust policy of the codec user: SERVER reads data it does not control (checked and bounded) and trusts what it builds ; CLIENT checks what it sends and trusts what it reads. anch-rest servers use SERVER and clients CLIENT ; a message consumer reads with SERVER and a producer writes with CLIENT .

  • Json checks anch-json fields constraints on values read with SERVER and on values written with CLIENT , and has mapping options per side ( options , configured by its policy):
    struct Pet {
    uint64_t id;
    std::string name;
    };
    template<>
    struct anch::Mapping<Pet> {
    static void
    registerObject(anch::ObjectMapper<Pet> auto& mapper) {
    mapper
    .registerField("id", &Pet::id)
    .registerField("name", &Pet::name, anch::val::required, anch::val::minLength(1));
    }
    };
  • codecs without limit of their own read contents with readBody, bounded by maxBodySize (2 MiB for SERVER by default): larger contents raise ContentTooLarge ( 413 in anch-rest servers).

Codecs selection and formats

Codecs is a list of codecs resolved at compilation: it selects the codec of a content type when reading, and negotiates the codec of accepted media ranges ( Accept , q-values) when writing:

// Codecs selected at run time among a list resolved at compilation
std::ostringstream csv;
std::optional<anch::codec::MediaType> selected =
Codecs::serialize(std::vector<int>{1, 2, 3}, csv, anch::codec::MediaType::parseAccept("text/csv, */*;q=0.1"),
std::cout << selected->essence() << ' ' << csv.str() << std::endl; // text/csv 1,2,3
std::vector<int> numbers;
std::istringstream input("4,5");
Codecs::deserialize(numbers, input, *anch::codec::MediaType::parse("text/csv; charset=utf-8"), anch::codec::Side::SERVER);

codec/all.hpp (target anch::codec-all ) is generated with the plugins built: it includes their headers, defines ANCH_CODEC_JSON_ENABLED , ANCH_CODEC_CSV_ENABLED , ANCH_CODEC_PROTOBUF_ENABLED and ANCH_CODEC_THRIFT_ENABLED , and declares anch::codec::Available , the list of their codecs (Json, Csv, Protobuf, ProtobufJson, ThriftBinary, ThriftCompact, ThriftJson, then Text). Types described by an external schema (Protobuf messages, Thrift structures) are not described by anch::Mapping : Json does not handle them ( anch::json::Mappable ), so the list selects the codecs of their format. Each plugin registers its format when its library is loaded ( formats, for introspection: accepted media types, startup logs, ...):

// Codecs of the formats built with the framework (codec/all.hpp, target anch::codec-all)
Pet read;
std::istringstream json(R"({"id":2,"name":"Médor"})");
if(!anch::codec::Available::deserialize(read, json, anch::codec::MediaType("application", "json"), anch::codec::Side::SERVER)) {
std::cerr << "Unsupported media type" << std::endl;
}
// Formats registered by the plugins the program uses
for(const anch::codec::Format& format : anch::codec::formats()) {
std::cout << format.name << ':';
for(const std::string& mediaType : format.mediaTypes) {
std::cout << ' ' << mediaType;
}
std::cout << std::endl;
}

Protocol Buffers and Apache Thrift

protoc messages are read and written by Protobuf ( application/x-protobuf ) and ProtobufJson ( application/json , Protobuf JSON mapping) codecs. Structures generated by thrift –gen cpp are read and written by ThriftBinary ( application/vnd.apache.thrift.binary ), ThriftCompact ( .compact ) and ThriftJson ( .json ). Their RPC (Connect, gRPC-Web, gRPC, Thrift over HTTP) is in anch-rest (see AnCH REST library documentation).