Expand description
§xmachines-kafka
XState machines as partition-sharded actors next to a Kafka-API broker (Apache Kafka, Redpanda, …), with exactly-once state.
Each record on the input topic is a chunk of the workflow contract’s record protocol (xmachines-workflow) for the actor named by the record key: an event ({ "type": ..., ... }), a work result ({ "kind": "work", "id", "outcome", "data"? }), or a batch of them, applied all or nothing. Actors live in memory, one engine::Partition per input partition, and their snapshots go to a compacted changelog topic with the same partitioning. With the kafka feature, service::Service runs one worker thread per core, each with its own consumer (in one consumer group) and transactional producer: every batch commits the emitted events, the changelog records and the input offsets in one Kafka transaction, so state, output and progress move together (exactly once). Timers fire from the wall clock and their effects commit the same way.
§When to use it
Use it to run many actors of one machine (an order, a device, a session per key) against a stream of events, close to the broker, with their state kept in Kafka itself. It is meant to run on each broker node and uses only the Kafka protocol, through librdkafka, so it works with any Kafka-API broker.
- The generic binary (
xmachines-kafka, featurekafka) runs a machine without custom implementations from a JSON configuration file. With thejsfeature, which is on in the image, machines with JavaScript code nodes run without any Rust. - A binary of your own calls
service::Service::startwith a machine whose guards, actions, delays or actors are Rust. - The engine (
engine) is deterministic and has no Kafka dependency: records and a time go in, output, changelog records, dead letters and work requests come out. Each actor is a run of the contract’s stepper; a chunk the machine rejects is undone and dead-lettered, as the record protocol’s rejected record with itsrunand the input’s headers. Use it to test a machine against records, or to host actors on another transport.
Besides the core loop it has: restore from the changelog and from pluggable checkpoint stores (local files, or a Git archive pushed to a remote); work published to an effects topic in the contract’s shape ({ "kind": "invoke", "id", "actor", "src", "input"? }, or a host action) and settled by work results on the input topic (effects::run is a ready-made worker loop); deduplication by a per-actor (epoch, sequence) mark; machine upgrades (earlier versions kept, or migrated with xmachines_runtime::Migration); cooperative rebalancing; backpressure that pauses partitions while a worker is busy; TLS and SASL; and health, readiness, consumer lag and Prometheus metrics.
§Example
The engine, with JSON events and snapshots, the defaults:
use std::sync::Arc;
use serde_json::{json, Value};
use xmachines_kafka::{EngineConfig, Partition};
use xmachines_runtime::{Machine, Registry};
let definition = json!({
"id": "order",
"initial": "open",
"context": { "items": 0 },
"states": {
"open": {
"on": {
"add": { "context": { "items": 1 }, "actions": [{ "type": "@xstate.emit", "event": { "type": "added" } }] },
"pay": { "target": "paid" }
}
},
"paid": { "type": "final" }
}
});
let machine: Machine<Value, Value> = Machine::from_json(&definition, &Registry::new()).unwrap();
let mut partition = Partition::new(Arc::new(machine), EngineConfig::default());
// Records by key: each key is an actor.
partition.handle(Some("order-1"), br#"{ "type": "add" }"#, 1000);
partition.handle(Some("order-2"), br#"{ "type": "add" }"#, 1000);
partition.handle(Some("order-2"), br#"{ "type": "pay" }"#, 1001);
// What one transaction commits.
let output = partition.flush();
assert_eq!(output.emitted.len(), 2);
assert_eq!(output.emitted[0].event, json!({ "type": "added" }));
// One changelog record per changed actor; a finished actor leaves a tombstone.
assert!(output.changelog[0].1.is_some());
assert_eq!(output.changelog[1], ("order-2".to_owned(), None));A service of your own, with the kafka feature (this block is not compiled with the docs, which leave out librdkafka):
use std::sync::Arc;
use xmachines_kafka::service::{Service, ServiceConfig};
let mut config = ServiceConfig::new("localhost:9092", "orders", "orders", "orders-out", "orders-changelog");
config.dead_letter_topic = Some("orders-dead".into());
let service = Service::start(config, Arc::new(machine))?; // a machine with Rust implementations
// ... until it is time to stop: workers finish their batch and leave the group.
service.stop()?;The generic binary:
cargo build -p xmachines-kafka --release --features kafka,js,msgpack,protobuf,avro
xmachines-kafka --check service.json # validate the configuration and the machine
xmachines-kafka service.json # run until Ctrl-C / SIGTERM
xmachines-kafka proto events machine.machine.json # the input events' .proto (feature protobuf)
xmachines-kafka avro events machine.machine.json # an Avro schema: events, emitted or snapshot (feature avro)A configuration names the machine (a MachineJSON file or an extract bundle), the brokers, the group, the topics and, optionally, workers, batching, codecs, deduplication, earlier machine versions, librdkafka settings (secrets as { "env": NAME } or { "file": path }), checkpoints and the metrics address:
{
"machine": "machine/sensor.machine.json",
"bootstrapServers": "redpanda:9092",
"groupId": "sensors",
"topics": { "input": "sensor-events", "output": "sensor-out", "changelog": "sensor-changelog", "deadLetter": "sensor-dead" },
"workers": 2,
"dedupe": { "sequence": "seq", "epoch": "boot" },
"stateDir": "/var/lib/xstate",
"metricsAddress": "0.0.0.0:9464"
}The config module (feature kafka) documents every key. deploy/ has a local stack (Redpanda, MQTT through Redpanda Connect, the service) with a smoke test.
§Upgrading to the record protocol (kafka 3.0.0)
Kafka 3.0.0 puts the service on the workflow contract’s record protocol, and the payloads of the input and effects topics change shape: a work request is the contract’s work with its run ({ "kind": "invoke", "id", "actor", "src", "input"?, "run" }, or a host action), and its result is a work result ({ "kind": "work", "id", "outcome", "data"?, "run" }), where 2.x wrote XState’s effect and xstate.system.effect.result. Pending work does not cross the upgrade: a 3.0.0 worker cannot read a 2.x request, a 2.x result is an xstate. event, which 3.0.0 rejects, and a restored actor’s pending work counts as published. So upgrade the service and its workers together, after a quiet period:
- Stop producing events that start work to the input topic.
- Wait until no actor holds pending work: the effects topic is drained and every result is taken (the
effects_totalcounter stops moving and the dead-letter topic shows noxstate.system.effect.result). - Stop the 2.x service and its workers; start 3.0.0’s together.
- Resume the producers.
Changelog records of 2.x restore as they are (3.0.0 writes the run’s seq first, and reads a record without it). Runs are named <group>/<key> now, which work and dead letters carry as run.
There is no way back to 2.x once 3.0.0 has written to the changelog: a 2.x worker cannot read a record of 3.0.0’s format, and under its default onRestoreError: "deadLetter" it tombstones every actor 3.0.0 wrote, deleting their state. Roll forward instead; if a rollback must stay possible, run the 2.x workers with onRestoreError: "fail", so a 2.x worker that meets a 3.0.0 record stops rather than deletes it.
§Codecs
Records are encoded by the codecs of xmachines-codec, chosen by name: JSON is built in and the default of each, so a build without features needs no other codec crate, and the features msgpack, protobuf and avro add the codecs of their crates (codecs). The configuration names the codec of changelog snapshots ("codec"), of input records without a content-type header ("events") and of emitted events ("outputs"). For throughput and smaller changelog records, "codec": "msgpack" writes snapshots as MessagePack (a small order actor’s is 484 bytes and about 1.1 µs to write in the compact form). An input record with a content-type header is read by the codec of that media type, and a changelog record by the codec of its format byte, whatever codec writes new ones.
§Features
None is on by default: the plain build is the engine with JSON.
| Feature | What it adds |
|---|---|
msgpack | MessagePack events and snapshots (xmachines-codec-msgpack) |
protobuf | protobuf events and snapshots (xmachines-codec-protobuf) |
avro | Avro events, outputs and snapshots (xmachines-codec-avro), through the Schema Registry with kafka |
js | JavaScript code nodes (js, ts) in the generic binary’s machines, on an embedded QuickJS (xmachines-eval-quickjs) |
kafka | the Kafka driver (service, config, effects, the binary): librdkafka built from source with TLS, SASL PLAIN / SCRAM / OAUTHBEARER, zstd and gzip |
kafka-gssapi | SASL GSSAPI (Kerberos), through the system’s Cyrus SASL |
§Pins
librdkafka through rdkafka 0.39 (built from source: the kafka feature needs CMake and a C toolchain). It is tested against librdkafka’s in-process mock cluster; a run against a real broker is still to do.
§Related crates
xmachines-runtime: the runtime of every actor.xmachines-codec: the codecs of its records.xmachines-eval-quickjs: JavaScript code nodes.xmachines-docs: thekafkaguide.
§License
MIT
Re-exports§
pub use changelog::Mark;pub use engine::codecs;pub use engine::DeadKind;pub use engine::DeadLetter;pub use engine::Dedupe;pub use engine::Emitted;pub use engine::EngineConfig;pub use engine::Incoming;pub use engine::MachineSet;pub use engine::MarkFrom;pub use engine::Output;pub use engine::Partition;pub use engine::Refused;pub use engine::Rejection;pub use engine::RestoreErrors;pub use engine::SnapshotFormat;pub use engine::WorkRequest;pub use engine::DEFAULT_CODEC;pub use engine::EPOCH_HEADER;pub use engine::PRODUCER_HEADER;pub use engine::SEQUENCE_HEADER;pub use engine::TIME_HEADER;pub use metrics::BatchCounts;pub use metrics::Metrics;pub use metrics::MetricsSnapshot;
Modules§
- changelog
- The changelog’s records: snapshot records of any registered codec
(
xmachines_codec::Codecs), each starting with its codec’s format byte, so records are decoded by their own format byte, whatever the configured codec is. - checkpoint
- Local checkpoints of a partition’s actors, so a restore reads a local file and only the tail of the changelog.
- config
- The service’s configuration file (JSON) and machine loading for the
xmachines-kafkabinary. - effects
- A worker for the work the service publishes to its effects topic, in the
record protocol’s shape: invoked logic (
{ "kind": "invoke", "id", "actor", "src", "input"? }) and host actions ({ "kind": "action", "id", "actor", "type", "params"? }). It reads each piece, runs a handler, and produces the result to the input topic, keyed by the actor, as the work result{ "kind": "work", "id", "outcome", "data"?, "run" }, the run the request named written back:resolvedorrejectedof invoked work,doneof a host action. - engine
- The deterministic part of the service: one
Partitionper input partition, holding one actor per record key. - git
- A Git repository as a checkpoint
Store: the cold path for archive and audit. - metrics
- Service counters, shared by the workers, readable at any time, and renderable in the Prometheus text format.
- service
- The Kafka driver: worker threads that consume the input topic, run each partition’s actors, and commit output, changelog and offsets in one transaction per batch.