xmachines-codec
Codecs for the events and snapshots of xmachines-rs machines: what turns an event ({ "type": ..., ... }) or an actor system's snapshot (XState's SystemSnapshot) into bytes and back, for hosts that move them over a wire or keep them in a log (the Kafka service, WASI and Node.js hosts, a broker).
When to use it
Use it in a host that reads events from records or writes snapshots to a log, and wants to choose the encoding by name, as a machine chooses its evaluators by language. The crate uses nothing of a service or of Kafka (of xmachines-runtime, only the snapshot view type), so any host can use it. JSON is built in; MessagePack, protobuf and Avro are crates of their own.
The contract
EventCodec:decode(&[u8]) -> Result<Value, Error>reads an event from a record's bytes, andencode(&Value, &mut Vec<u8>)appends an event's encoding.SnapshotCodec:format()is the first byte of every record it writes,compact()says whether it always takes the compact form of a snapshot,encode(Snapshot, &mut Vec<u8>)appends a record anddecode(&[u8]) -> Result<Value, Error>reads one back to the snapshot's JSON. ASnapshotis the JSON or the runtime's view of an actor system (xmachines_runtime::Actor::persist_viewandpersist_compact), which a codec serializes directly, without building the JSON.Codec: one format, built for a machine: a name, the media types of its records, and optional codecs of input events, emitted events and snapshots. Codecs that follow a machine's schemas (protobuf, Avro) are built from its bundle, so aCodecserves the machines it was built for.Codecs: the codecs a host reads and writes, by name, with JSON (json) registered from the start. A media type and a snapshot format byte each belong to one codec (Error::Conflictotherwise), soby_media_typefinds the codec of a record'scontent-type, anddecode_snapshotreads a record written by any registered codec, by its format byte, whatever codec writes new ones.Error:Decode,Encode,Schema,UnknownFormatandConflict, each with its message.
The format bytes are JSON 1, MessagePack 2, protobuf 3 and Avro 0 (the Schema Registry's magic byte). varint has the varint and zigzag helpers the binary codecs share.
Example
use json;
use Codecs;
let codecs = new;
let json = codecs.by_media_type.unwrap;
let event = json.events.unwrap.decode.unwrap;
assert_eq!;
let mut record = Vecnew;
json.snapshots.unwrap.encode.unwrap;
assert_eq!;
assert_eq!;
Related crates
xmachines-codec-msgpack: MessagePack events and snapshots (msgpack).xmachines-codec-protobuf: Protocol Buffers events and snapshots (protobuf).xmachines-codec-avro: Avro events, emitted events and snapshots in the Schema Registry wire format (avro).xmachines-kafka: the service that reads and writes its records with these codecs.
License
MIT