Skip to content

Use the CrumblES SDK

The CrumblES SDK is the Rust library crumbles_sdk. Your application uses it to store domain events and to read them again. This page shows the four things you do with it: create a Store, append, read, and handle a concurrency conflict. After them, diagrams show what happens inside each call.

For your application, CrumblES is an infrastructure component. Your business logic decides which domain events happen, and CrumblES holds them. CrumblES keeps its events in a Git repository. You name that repository once, in the configuration, and after that your code meets no Git term.

flowchart LR
  a["Business logic of the caller"] -->|"append: domain event = event"| b["CrumblES SDK"]
  b -->|"read: sequenced event"| a
Term Meaning
store A named, ordered sequence of events in a repository.
event One thing that happened. It has an event type, tags and data. A domain event of your application is one event.
data The content of an event, as bytes that hold one JSON object. CrumblES does not interpret them.
tag A plain string on an event, such as order:o1. A query selects events by tags.
query A selection of events, by event types and tags.
sequence position The place of an event in the one ordered sequence of a store. The first event has position 1.
sequenced event An event paired with its sequence position, as a read yields it.
append condition A query and a sequence position. The append fails when an event after that position matches the query.
  • You need a Rust toolchain of version 1.88 or newer.
  • You need an existing Git repository. Run git init if you have none. The SDK does not create one.
  • The package is not on crates.io. Add it as a path dependency to your Cargo.toml, with the path to your copy of this repository:
[dependencies]
crumbles_sdk = { path = "../git-event-store/crumbles/sdk" }

Create one Store and keep it. It processes the repository once, so you can use it for many calls.

use std::error::Error;
use crumbles_sdk::{Configuration, DEFAULT_STORE_NAME, Store};
fn open(repository_path: std::path::PathBuf) -> Result<Store, Box<dyn Error>> {
let store = Store::open(&Configuration {
repository_path,
store_name: DEFAULT_STORE_NAME.to_owned(),
})?;
Ok(store)
}
  • repository_path is the repository or a directory inside it.
  • store_name names the store. One repository can hold many stores with different names. Name the store after your application where you can. DEFAULT_STORE_NAME is provisional, and it can change.
  • A store name holds no /, and Git must accept it inside a ref name. So letters, digits, -, _ and a . inside the name work. A space, .., ~, ^, :, ?, *, [, \, a leading . and a final .lock do not.
  • Store::open fails with Error::RepositoryNotOpened when it finds no repository, and with Error::InvalidStoreName when the name is empty or not valid. That error holds the name.
  • A Store cannot move to another thread, because it is not Send. Open one Store in each thread that needs one.

Create each event with Event::new, then pass the list to append. The events are stored as one unit: all of them, or none. append returns the sequence position of the last event.

use crumbles_sdk::{Error, Event, SequencePosition, Store};
fn place_order(store: &mut Store) -> Result<SequencePosition, Error> {
let placed = Event::new(
"OrderPlaced",
vec!["order:o1".to_owned()],
r#"{"total":42}"#,
)?;
store.append(vec![placed], None)
}

Event::new fails with Error::EventDataNotObject when the data is not one JSON object, so such a value cannot reach a store. The bytes of the object stay as you gave them: whitespace inside it, duplicate keys and the spelling of numbers survive. Whitespace around the object does not reach the store.

append checks the rest and fails without writing an event:

Error Cause
Error::EmptyAppend The list holds no event.
Error::Invalid An event type or a tag holds a line break, or starts or ends with whitespace. Or a query item of the append condition constrains nothing.
Error::ConcurrencyConflict A concurrent write invalidated the append. See Handle a concurrency conflict.
Error::Store The store cannot be read or written.

read takes a query and an optional lowest sequence position, and returns a Result that holds an iterator. The events come in ascending sequence position, and from_sequence_position itself is included.

use crumbles_sdk::{Error, Query, QueryItem, SequencePosition, Store};
fn print_order(store: &Store) -> Result<(), Error> {
let order = Query {
items: vec![QueryItem {
types: None,
tags: Some(vec!["order:o1".to_owned()]),
}],
};
for sequenced_event in store.read(order, Some(SequencePosition(1)))? {
let sequenced_event = sequenced_event?;
println!(
"{} {}",
sequenced_event.sequence_position.0, sequenced_event.event_type
);
}
Ok(())
}
  • A query. An event matches a query when it matches any item. An event matches an item when it has one of types and all of tags. None constrains nothing, and an empty types matches no event. Query::all() matches every event. An item must constrain something: an item with no non-empty list fails with Error::Invalid.
  • Memory. The store holds the data of one event at a time. It reads an event when you ask for the next item. So you can read a long sequence without holding all its data.
  • Two places for an error. read itself fails with Error::Invalid or Error::Store before any event. An item fails with Error::Store when that one event cannot be read. The events before it are good, and no item follows it.
  • Other writers. Each call of read sees the appends of other writers, also on a Store you keep.
  • The data of a read. Another writer can store data that is not a JSON object, and a read yields it all the same. Check it before you parse it.

An append condition protects a decision. Your code reads the events that the decision rests on, decides, and appends with a condition: no event that this query matches may exist after the position you read.

Error::ConcurrencyConflict means that a concurrent write invalidated the append, and no event was written. You can tell it apart from every other error. Read again, decide again and append again.

use crumbles_sdk::{AppendCondition, Error, Event, Query, QueryItem, SequencePosition, Store};
fn ship_order(store: &mut Store) -> Result<SequencePosition, Error> {
let tag = "order:o1".to_owned();
let order = Query {
items: vec![QueryItem {
types: None,
tags: Some(vec![tag.clone()]),
}],
};
loop {
let mut last_read = None;
for sequenced_event in store.read(order.clone(), None)? {
let sequenced_event = sequenced_event?;
last_read = Some(sequenced_event.sequence_position);
// Your business logic reads the event here and decides.
}
let shipped = Event::new("OrderShipped", vec![tag.clone()], "{}")?;
let condition = AppendCondition {
fail_if_events_match: order.clone(),
after: last_read,
};
match store.append(vec![shipped], Some(condition)) {
Err(Error::ConcurrencyConflict) => continue,
result => return result,
}
}
}

after: None looks at every event, so the append fails when any event matches the query. An append without a condition can also fail with this error, when another writer moves the store after this call read the newest position and before this call finished its write.

Your application and the command-line program crumbles both use the SDK. The SDK holds the other packages and wires them, so that no caller has to.

flowchart TD
  cli["bin/crumbles"] -->|uses| sdk["crumbles_sdk"]
  bindings["later: language bindings"] -->|uses| sdk
  sdk -->|calls use cases| dcb["ges_dcb"]
  sdk -->|wires| git_store["ges_git"]
  sdk -->|wires| gitoxide["git_gitoxide"]
  git_store -->|implements ports of| dcb
  git_store -->|uses port of| git["git"]
  gitoxide -->|implements port of| git

A use case is one operation of ges_dcb, here append or query. A port is an interface that an inner package defines and an outer package implements. To wire is to create the objects of the packages and connect them.

Package What it holds
crumbles_sdk The public interface: Store, Event, Query and the other types on this page.
bin/crumbles The command-line program crumbles.
ges_dcb The rules of events, queries and append conditions. It touches no file.
ges_git The translation of events into Git commits, and the store that works on them.
git Git as values, and the port that a Git library implements.
git_gitoxide That port, implemented with the Rust library gitoxide.

The next two diagrams start at the outcome and walk backward. An arrow means “requires”. Read each diagram from the top. One path ends where your application calls the SDK, and the other ends where the command-line program starts.

These terms appear in the diagrams and nowhere in your code:

  • A commit holds one event. Each commit points to the one before it, so the commits form a chain.
  • A ref is a name in Git that points to the newest commit of the chain, the tip. It holds the store name, so Git’s rules for ref names decide which store names are valid.
  • The global stream is that chain: the one ordered sequence of all events of a store.
  • An event file is the file in a commit that holds the type, the tags and the data of one event.
  • An event id is a unique id that the store gives each event.
  • GitEventStore and GitoxideRepository are the two inner objects that the SDK wires.
  • Compare-and-swap sets the ref to a new value only if it still holds the old one. This single step makes the events visible.
  • A trailer is a line at the end of a commit message. The event type, the tags and the sequence position stand there too, so a read selects events without opening their data.
flowchart TD
  o["Outcome: the events are in the store"]
  a1["ges_git: ref of the global stream set to the new tip by compare-and-swap"]
  a2["ges_git: commit chain written, not visible to anyone yet"]
  a3["ges_git: timestamp and event id assigned per event"]
  a4["ges_git: sequence positions computed"]
  a5["ges_git: append condition checked"]
  a6["ges_git: tip and its sequence position read"]
  a7["ges_dcb: events and append condition checked"]
  a8["SDK: store.append(events, append_condition) called"]
  s1["SDK: Store exists, GitEventStore wired to GitoxideRepository"]
  s2["SDK: repository found"]
  s3["Caller: configuration passed"]
  e1["SDK: Event::new checked that data is a JSON object"]
  r1["CLI: events and append condition read from JSON"]
  r2["CLI: input read from argument, file or stdin"]
  r3["CLI: arguments parsed"]
  r4["CLI: command started"]
  n1["Application: business logic decided on domain events"]
  o --> a1 --> a2 --> a3 --> a4 --> a5 --> a6 --> a7 --> a8
  a8 --> s1 --> s2 --> s3
  a8 --> e1
  e1 --> r1 --> r2 --> r3 --> r4
  e1 --> n1

A failure before the compare-and-swap changes nothing that a reader can see. Objects that were already written stay unreferenced.

The walk happens inside the call of read. Each event file is read later, at next().

flowchart TD
  o["Outcome: the caller has all matching sequenced events, ascending"]
  i1["Caller: next() called until it answers None"]
  i2["SDK: sequenced event handed to the caller"]
  i3["ges_dcb: event turned into plain values"]
  i4["ges_git: event file of this match read, and no other"]
  q2["ges_git: matches reversed, ascending, each only a position and ids"]
  q4["ges_git: each commit checked against the query through its trailers"]
  q5["ges_git: sequence position checked against the chain, stop below from_sequence_position"]
  q6["ges_git: chain walked backward from the tip"]
  q7["ges_git: tip read"]
  q8["ges_dcb: query checked"]
  q9["SDK: store.read(query, from_sequence_position) called"]
  s1["SDK: Store exists, GitEventStore wired to GitoxideRepository"]
  s2["SDK: repository found"]
  s3["Caller: configuration passed"]
  e1["Caller: query exists"]
  r1["CLI: query read from JSON"]
  r2["CLI: input read"]
  r3["CLI: arguments parsed"]
  r4["CLI: command started"]
  n1["Application: business logic needs earlier domain events"]
  o --> i1 --> i2 --> i3 --> i4 --> q2 --> q4 --> q5 --> q6 --> q7 --> q8 --> q9
  q9 --> s1 --> s2 --> s3
  q9 --> e1
  e1 --> r1 --> r2 --> r3 --> r4
  e1 --> n1

A commit points only to the commit before it, so the ascending order needs the walk first. The walk keeps only the position and the ids of each match, and no data.

  • Language bindings. They will use the SDK as the command-line program does.
  • Read models, which keep data derived from events, decision models, which rebuild the state a decision needs, and a mechanism that calls your code on an append. They will come on the Store.
  • A statement of the durability level, which says how safe a stored event is against a crash. The store does not flush its writes to disk, so a crash of the machine can lose events that an append reported as stored. Do not treat a reported append as safe against such a crash.

Git Event Store is an independent open specification for an event store that uses Git as its storage component. It is not affiliated with or endorsed by the Git Project or Software Freedom Conservancy. Git and the Git logo are either registered trademarks or trademarks of Software Freedom Conservancy, Inc., corporate home of the Git Project, in the United States and/or other countries.

Git Event Store is not affiliated with or endorsed by Kurrent, the maker of KurrentDB (formerly EventStoreDB). "Event store" is used here as the generic name of the event-sourcing storage pattern.