Events
On a server, a Soda app stores what happened, not just the current state. Its model lists the
events that can happen, and the state is what they add up to. soda_server::app!(board::Board)
runs an app this way, and soda new starts you with one: a Kanban board (templates/server).
- History. Every change is stored and described, and anyone can view any earlier moment.
- Undo. Each person undoes their own changes, never someone else's.
- Live pages. Every open page, on every server, updates the moment anything changes.
- No migrations. State is rebuilt from the events at startup, so changing it is changing code.
Write a model#
A model has events, commands, and rules written as pure functions. From the template's
src/board.rs, shortened:
use ;
// checked against events.lock as it compiles
// on a server, a change another server got in ahead of is decided again
| Function | Does |
|---|---|
decide | Turns a command into events, or refuses it with a message. The only place a change is judged. |
evolve | Applies one event. It replays every stored event at startup, so it can't fail: it skips anything decide would have refused. |
describe | Describes an event for the history, against the state just before it. |
soda::model has the shared checks: clean and fit for text, valid_id for ids. One command's
events are one change, undone together.
Use it in pages and actions#
pub async cx.act runs decide against the latest state, stores the events, and re-renders every open page.
A refusal comes back as the Err, and ? shows it to the person.
| A page reads | |
|---|---|
cx.app | The model, now or at the moment being viewed in the history |
cx.me | The viewer: id, name, hue, can_edit (false while viewing history) |
cx.here() | Who has the app open, and what each is editing (focus) |
cx.history(), cx.looking_back() | Every change, and how far back the page is viewing, for <History> |
cx.undo(), cx.redo() | What Undo or Redo would do, for button labels |
Pages can also read cx.looking_at() (the time being viewed), cx.name_of(id), cx.timeline()
(every change, for custom views) and cx.kept_in() ("SQLite, data/events.db").
An action also has cx.app() (the current model), cx.me, and
cx.say_with_undo("Deleted “Fix login”."), a message with an Undo button.
Soda's components and shortcuts post to its own routes: /api/undo, /api/redo (⌘Z, ⇧⌘Z),
/api/scrub (<History>), /api/me ({ name }) and /api/focus ({ on, doing }).
History#
<History> draws every change as a stop on a line, in its author's color. Drag it, or use the arrow
keys, to see the app as it was then. Editing is off until you return to now.
The server keeps the latest 1,000 changes in memory to look back on; older ones stay in the store
(soda events log lists them). A model sets how many with const HISTORY: usize. One whose pages
never show the history can keep none.
Undo#
Undo is per person, and is itself a change: stored, and shown in the history ("Ann undid moving “Fix login” to Done"). To support it, say what each change did and how to reverse it:
step records an undoable change (None: not undoable). travel makes the events that undo it,
or redo it when forward, if the state still matches. what names it for "Undo …". The optional
fn gone(step) says what to show when its target no longer exists (by default, "it has been
deleted since").
If someone else has changed the target since, travel returns a Stale (changed_by(id),
gone(), or because("…")) and their change stands: "Can't undo moving “Fix login” to Done: Ben
has changed it since." Undo stacks are rebuilt from stored changes, so they survive restarts.
People#
Each browser is a person, with an id from its session, a color, and a generated name ("Teal Heron") until they pick one. Names are stored as events; presence lives in memory.
The store#
soda-store keeps events in SQLite at data/events.db. Set SODA_STORE=postgres://… to use
Postgres, when several servers share a database or the host has no disk. Every server applies every
change at once (Postgres notifies them with LISTEN soda_events). If two servers decide changes at
the same moment, the second is decided again against the first, as pressing again would (so the
model's Command is Clone): kept, or refused for what's true now ("That card was already
deleted."). Only after three races lost in a row is it "Someone changed this at the same moment.
Try again."
Actions that arrive together on a server are kept together: one turn decides each in the order
asked, against the model with the ones before it, and keeps them all in one trip to the store,
each still its own change (its author, time and place in the log). On Postgres the append is one
call (soda_append), so the turn every server takes is held only inside the database. Measured,
three servers on one database: 8,972 changes a second, none refused, answered in 2 ms.
Several servers#
On a Postgres they share, an app's servers keep what they need of each other there too, with nothing to set:
- Sessions. The key cookies are signed with (
soda_shared, made by the first server), so any server reads any session.SODA_SECRETstill wins if it's set. - Who's here. Every two seconds each server says, per space, how many people it holds and the
first 50 (
soda_servers), and hears the others:cx.here()names its own people, then theirs;cx.here_count()counts everyone (show it for a crowd). A server quiet for 10 s is gone. - The day's bytes (
megabytes_a_day): one count for all of them (soda_sent), so the limit is the app's, however many run.roomstays each server's. - A page's own requests. On Fly.io, the server holding a page's stream says which on
#app(data-server), and soda.js sends what the page says of itself there (Fly-Prefer-Instance-Id); an app's own requests about its page can sendsoda.pageHeaders(). If that server's gone, the request goes to any, and the page's stream starts again on one. Elsewhere, keep each browser on one server (sticky sessions at the load balancer).
Each server holds six connections. To move a server's data/events.db into Postgres, stop it and
run soda events copy --to postgres://…: every event at its place, with its id, the shapes and
checkpoints; then set SODA_STORE and start as many as you need.
Each row of soda_events has the event's log position (seq), id, stream (app or people)
and version in it, change, variant name, JSON data, author, ts, shape and meta
({"kind": "undo"}).
soda_shapes keeps each version of the events' shape.
Checkpoints#
A server starts by folding every event ever kept. Once that's slow (hundreds of thousands of events), save the model as a checkpoint, and the server starts from the latest instead:
The server saves one every 10,000 changes (at most once a minute) and as it stops, into
soda_checkpoints. It starts from the latest and folds only what came after. A big model can save
bytes of its own rather than JSON.
A checkpoint is the model as evolve made it. When you change what events add up to (or how save
writes), change const RULES: u32 too. The next start folds every event again under the new
rules, and saves a checkpoint of its own.
Change an event's shape#
Stored events stay forever, and every later build must read them. So events only grow: add an
event, a variant, or a field that may be missing (Option or #[serde(default)]). Never remove or
reinterpret what's stored, and rename only with #[serde(alias)] (below). Three checks enforce it:
- Compile time.
#[shape(events)]checks the enum againstevents.lock. A removed field or variant, or a new required field, is an error on that line that says how to fix it. - Tests.
events.lock, next toCargo.lock, records every field and variant by its stored name.cargo testadds new lines and fails on anything that would break a stored event. Commit it with the change.app!adds this test for you. - Startup. The store checks the build's shape against the stored one. A grown shape becomes the next version; a breaking one stops the app with the reason. An older build whose shape matches an earlier version still runs, as long as no newer event is stored.
To rename a field or variant, give its old name: #[serde(alias = "title")] name: String. Stored
events read under the new name, and the lock keeps both. For a change in meaning (new units, a
different value), add a new field beside the old one.
Not deployed yet? soda events reset deletes data/events.db. Delete events.lock too, and start
over.
Test a model#
Models are pure functions, so tests need nothing running. soda::scenario::Scenario replays
commands as the server does, undo included:
use Scenario;
| Method | Does |
|---|---|
.given(by, [events]) | Events that already happened, as one change |
.when(by, command) | Runs a command, storing what decide makes |
.undo(by), .redo(by) | Undoes or redoes that person's latest change |
.then([events]), .then_nothing(), .then_refused("…") | Checks the last step's events, or its refusal |
.then_state(|m| …), .then_history(&["…"]) | Checks the state, or the history |
.named(id, "Ann"), .at(ms) | Names a person; sets the clock |
.state(), .history() and .timeline() read the result. templates/server/src/board.rs has a
full set of tests to copy.
Inspect the store#
| Command | Shows |
|---|---|
soda events | Where events are, counts, the shapes beside events.lock, and the latest changes |
soda events log | Every change, oldest first (--last 20, --stream app) |
soda events export | Every event as a CloudEvent, one JSON object per line (--to file) |
soda events reset | Deletes data/events.db, SQLite only (--yes skips the prompt) |
Exports feed systems outside the app. Each CloudEvent's type is <app>.<name>
(kanban.CardAdded), its subject the stream, plus Soda's sodaseq, sodachange, sodaby,
sodashape and sodakind.
Under soda dev, a pill in each page's corner opens a live panel of events. Click one to see the
page as it was just after it.
Local-first#
A model is only rules, so the local-first engine runs it too: each device decides, signs and
encrypts events, and every member's device applies them in the same order. soda new --local
makes the same board, with the same src/board.rs, plus:
app!;The platform owns a space's members, name, keys and sharing; the model owns the rest. A
LocalFirst model is a soda::Model that is also Debug + PartialEq + Serialize + DeserializeOwned, as the template's Board derives. Its state is stored beside the space's, so
its fields must avoid the space's six: name, members, creator, epoch, removed, former
(the board stores its name as title for this). Its events must avoid the platform's names
(BoardCreated, BoardRenamed, MemberJoined, KeyChanged, EpochOpened, HistoryClosed).
Rules that read the space itself need the engine's App instead. See Local-first.
Without events#
To store state your own way (your own database, an API), use
soda_server::app!(plain book::Book). Pages read cx.state, and actions change it. soda new --plain starts one (a checklist in SQLite), and the tutorial builds one.
This page is docs/events.md in the SDK, built into this site as it is.