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 soda::model::{clean, fit, valid_id};

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, soda::Shape)]
#[serde(tag = "type")]
#[shape(events)] // checked against events.lock as it compiles
pub enum Event {
    Renamed { name: String },
    CardAdded { card: String, title: String, column: Column, pos: f64 },
    CardRenamed { card: String, title: String },
    CardMoved { card: String, column: Column, pos: f64 },
    CardDeleted { card: String },
}

#[derive(Clone)] // on a server, a change another server got in ahead of is decided again
pub enum Command {
    RenameBoard { name: String },
    AddCard { card: String, title: String, column: Column },
    RenameCard { card: String, title: String },
    MoveCard { card: String, column: Column, index: usize },
    DeleteCard { card: String },
}

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
pub struct Board {
    #[serde(rename = "title")]
    pub name: String,
    pub cards: BTreeMap<String, Card>,
}

impl soda::Model for Board {
    type Event = Event;
    type Command = Command;
    type Step = Step; // () for a model without undo

    fn decide(&self, _by: &str, _now: u64, command: Command) -> Result<Vec<Event>, String> {
        match command {
            Command::RenameCard { card, title } => {
                let existing = self.cards.get(&card).ok_or("That card was deleted.")?;
                let title = clean(&title)?;
                Ok(if existing.title == title { vec![] } else { vec![Event::CardRenamed { card, title }] })
            }
            Command::DeleteCard { card } => {
                self.cards.get(&card).ok_or("That card was already deleted.")?;
                Ok(vec![Event::CardDeleted { card }])
            }
            // …
        }
    }

    fn evolve(&mut self, by: &str, at: u64, event: &Event) {
        match event {
            Event::CardRenamed { card, title } => {
                if let Some(c) = self.cards.get_mut(card)
                    && let Some(title) = fit(title)
                {
                    c.title = title;
                    c.changed_by = by.into();
                    c.changed_at = at;
                }
            }
            Event::CardDeleted { card } => {
                self.cards.remove(card);
            }
            // …
        }
    }

    fn describe(&self, who: &str, event: &Event) -> String {
        match event {
            Event::CardAdded { title, column, .. } => format!("{who} added “{title}” to {}", column.label()),
            Event::CardDeleted { card } => format!("{who} deleted {}", self.title(card)),
            // …
        }
    }
}
FunctionDoes
decideTurns a command into events, or refuses it with a message. The only place a change is judged.
evolveApplies one event. It replays every stored event at startup, so it can't fail: it skips anything decide would have refused.
describeDescribes 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 fn page(cx: &Cx) -> View {
    view! {
        <ul>{cx.app.cards.values().map(|c| view! { <li>{&c.title}</li> })}</ul>
        <History stops=&cx.history() at=cx.looking_back() />
    }
}

#[action]
pub async fn add_card(cx: &mut Act, form: NewCard) -> Result {
    cx.act(Command::AddCard { card: new_id(), title: form.title, column: Column::Todo }).await?;
    Ok(())
}

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.appThe model, now or at the moment being viewed in the history
cx.meThe 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:

fn step(&self, _by: &str, events: &[Event]) -> Option<Step> {
    let [event] = events else { return None };
    let (change, what) = match event {
        Event::CardRenamed { card, title } => {
            let c = self.cards.get(card)?;
            (Change::Title { card: card.clone(), before: c.title.clone(), after: title.clone() }, format!("renaming {} to “{title}”", self.title(card)))
        }
        // … one arm per event
    };
    Some(Step { change, what })
}

fn travel(&self, _by: &str, step: &Step, forward: bool) -> Result<Vec<Event>, Stale> {
    let stale = |card: &str| self.cards.get(card).map_or_else(Stale::gone, |c| Stale::changed_by(c.changed_by.clone()));
    let event = match &step.change {
        Change::Title { card, before, after } => {
            let (from, to) = if forward { (before, after) } else { (after, before) };
            if self.cards.get(card).map(|c| &c.title) != Some(from) {
                return Err(stale(card));
            }
            Event::CardRenamed { card: card.clone(), title: to.clone() }
        }
        // … one arm per kind of change
    };
    Ok(vec![event])
}

fn what(step: &Step) -> String {
    step.what.clone()
}

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_SECRET still 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. room stays 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 send soda.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:

impl soda::Model for Board {
    // …
    fn save(&self) -> Option<Vec<u8>> { soda::model::as_json(self) }   // Board: Serialize
    fn load(saved: &[u8]) -> Option<Self> { soda::model::from_json(saved) }
}

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 against events.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 to Cargo.lock, records every field and variant by its stored name. cargo test adds 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 soda::scenario::Scenario;

#[test]
fn someone_else_s_later_change_is_never_overwritten() {
    Scenario::<Board>::new()
        .when("ann", Command::AddCard { card: "c".into(), title: "Fix login".into(), column: Column::Todo })
        .when("ann", Command::MoveCard { card: "c".into(), column: Column::Done, index: 0 })
        .when("bo", Command::MoveCard { card: "c".into(), column: Column::Doing, index: 0 })
        .undo("ann")
        .then_refused("Can't undo moving “Fix login” to Done: bo has changed it since.");
}
MethodDoes
.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#

CommandShows
soda eventsWhere events are, counts, the shapes beside events.lock, and the latest changes
soda events logEvery change, oldest first (--last 20, --stream app)
soda events exportEvery event as a CloudEvent, one JSON object per line (--to file)
soda events resetDeletes 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:

impl soda_local::LocalFirst for Board {
    const NOUN: &'static str = "board";

    // Two people renaming one card at once is reported as a conflict.
    fn target(&self, _by: &str, event: &Event) -> Option<String> {
        match event {
            Event::CardRenamed { card, .. } => Some(format!("card:{card}/title")),
            _ => None,
        }
    }
}

soda_local::app!(board::Board);

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.

Esc