A lot happened in November in Sourced and Sidereal, my two libraries to build event-sourced, reactive apps in Ruby. There’s still more to come but here’s a summary.

Sourced

Selectors API

I redesigned the way “reactors” query the event store. A reactor is a Ruby class that consumes messages (commands and events), may run some side-effect, and appends new messages to the store. Most things in Sourced are Reactors (deciders, projectors, state machines).

The new Sourced::Selector is an API for building message queries.

selector = Sourced::Selector[CourseCreated, StudentEnrolled]
  .by(:course_id)
  .bind(course_id: 'c1')

result = store.read(selector)
result.messages # Enumerable<Message>

This is a selector that queries the store for messages of type CourseCreated, StudentEnrolled where their course_id attribute is "c1".

Selectors can be combined into more complex queries.

selector = Selector[CourseCreated].by(:course_id) 
           + Selector[UserRegistered].by(:user_id)

result = store.read(selector.bind(course_id: 'c1', user_id: 'u1'))

Selectors provide an append guard that ensures that no new messages in the same selector have been appended by other writers.

# raises Sourced::ConcurrentAppendError if conflicting messages
store.append(new_events, guard: selector.guard)

This is Sourced’s take on Dynamic Consistency Boundaries.

Why do this? Selectors represent the subset of history that reactors need to collect their state. The built-in reactor classes produce Selectors from their DSLs.

class ShoppingCart < Sourced::Decider
  partitions_by :cart_id

  # This context will be evolved from events
  context { Cart.new }

  # evolve blocks build a Selector
  evolve CartStarted do |cart, evt|
    cart.started = true
  end

  evolve CartPlaced do |cart, evt|
    cart.placed = true
  end

  # command blocks build a separate selector
  command StartCart => CartStarted do |cart, cmd|
    event(CartStarted) unless cart.started? || cart.placed?
  end
end

But many decisions in an event-sourced app don’t even need to collect local state. The event history is the state.

For example, the StartCart decision above only needs to know whether the history already contains CartStarted and CartPlaced. For this, you can now just pass a selector directly to your deciders, and the command handlers will get the event history instead of a blob of state.

class ShoppingCart < Sourced::Decider
  partitions_by :cart_id

  # no context needed. The event history is all the state we need
  evolve Selector[CartStarted, CartPlaced]

  # The command handlers just get the selected history
  command StartCart => CartStarted do |history, cmd|
    return if history.any?(CartStarted) || history.any?(CartPlaced)
    event CartStarted
  end
end

This really makes the point that, in Event Sourcing, it really is all about the events. You only derive state from events if you really need it.

Single-command decisions

This also enables single-command deciders that encapsulate their own little consistency boundary. Example:

AddItem = Sourced::Decider(
  # The history I need for this decision
  Sourced::Selector[CartStarted, ItemAdded, CartCheckedOut].by(:cart_id),
  # What command I accept, and what new event I produce
  AddItemToCart => ItemAdded
) do |history, cmd|
  # The business logic
  event ItemAdded, cart_id: cmd.payload.cart_id, sku: cmd.payload.sku
end

This is fundamentally a self-contained function for each decision in your domain.

Explicit outputs

As shown in the examples above, command handlers now require boot-time declaration of a command’s possible events.

command StartCart => CartStarted | CartRejected

nil can be used to signify no-ops.

command AddItem => ItemAdded | nil

This follows from the work done to support Statecharts, and it lets Sourced build the entire input -> output topology at boot-time. This means that we can “statically” inspect the structure of the program without running it. This is leveraged by the CLI, dashboard, runtime validations, and it just makes the code more explicit.

Store optimisations

There’s a bunch of optimisations to the way the store claims and indexes messages in the background. It made for some significant performance gains as the message volume grows.

Snapshots

Snapshots in Event Sourcing are an optimisation for when you have very long streams of events. To avoid consuming the entire stream every time, you collect events into data blobs and periodically save the blob to some storage. Then next time you first read the blob, and then only read new events after the blob was computed.

An event stream e1 to e7 with a snapshot taken at e4. The reader reads from the last snapshot onwards.
Readers load the latest snapshot, then only the events appended after it.

In your own app, snapshots are usually a design smell (why do the concepts in your domain need such long streams?). But they can be a great optimisation when using Event Sourcing for infrastructure. This is a little custom Reactor that functions as a rate limiter for other reactors. It keeps a long-running, snapshotted stream to orchestrate the work of multiple document-scanning reactors.

class ScanQueue < WorkQueue
  commands Document::StartScan
  def capacity = 3
  def rate = '10/m'
end

It leverages Sourced’s partitioning system to ensure that a single “thread” of this reactor is acting as a global semaphore for all other reactors. This is a live Sidereal UI component for it.

A live Sidereal UI component showing the scan queue rate-limiting document scans

Because it’s an event-sourced reactor, it’s fully durable and will just pick up where it left off on server restarts.

Sidereal

Dependency management

Both Sidereal and Sourced now use a new dependency-components system (still WIP), which I’m creatively calling sourced-component. It’s heavily inspired by the amazing Dry-System on which Hanami is built, but it relies on declarative dependency declarations.

App = Sourced::Component.new

# 1. Declare what the component has, and the types values must satisfy
App.declare('db.url', String) { 'sqlite://app.db' } # with a default implementation
App.declare('db', DB)

# 2. Implement components, with dependencies and lifecycle hooks
App.component!('db', ['db.url']) do
  build { |url| DB.new(url) }
  start { |db, _context| db.connect }
  teardown { |db| db.disconnect }
end

# 3. Boot
App.start!

Components can also be “mounted” in other components (Sourced’s configuration is mounted onto Sidereal’s), and we can use dependency resolution to validate the dependency tree at boot-time and also inspect it (it can generate Mermaid diagrams).

Classes in your app can use this configuration for Dependency Injection.

class Things < Sourced::Projector::StateStored
  # a projector that uses the :db dependency
  dep :db

  # now the `db` reader is available
  def store(data)
    db.insert(data)
  end
end

CLI and app generator

Sidereal now has an official CLI, including sid new ./my_app to generate a new reactive Ruby app. You have many options such as --db to include Sqlite/Sequel integration, and --sourced to setup the app with Sourced for event-sourced apps.

The CLI comes with loads of goodies! It leverages the declarative dependency system above to tell you as much as possible about your system. This is the output of running bin/sid system tree on a Sidereal app.

Terminal output of bin/sid system tree, listing each component with its type, lifecycle and description, including the mounted Sourced components
bin/sid system tree describes every component in the app, including Sourced's mounted configuration.

When using Sourced in a Sidereal app, the CLI also lets you inspect and control your Sourced app (stopping and starting consumer groups, inspecting the app’s messaging topology, even dispatching commands from the command line).

Security and sessions

Sidereal apps now ship with a simple secret-management API. It can take a master secret from the ENV or generate a git-ignored one in development. But because of the new dependency system, you can provide your own implementation with the same API.

Generated Sidereal apps rely on the secrets dependency to mint session secrets.

session secret: -> { Sidereal.secrets.derive('session') }

You can provide your own secret generator.

# in your app's configuration, ex config/components/secrets.rb
# Interface is #derive(purpose String, length: Integer) -> String
Sidereal.config.config!('secrets') do
  MySuperSecretGenerator.new
end

The secrets generator is also used to sign channel names for real-time SSE streams (which is how Sidereal UIs react to changes in the backend).

Assets and web layer

Sidereal finally has a (simple) assets management system. Apps can declare what assets they use anywhere in the directory structure.

class MyApp < Sidereal::App
  assets.stylesheet 'app.css', path: Sidereal.root.join('assets/app.css')
  assets.javascript 'app.js', js: "console.log('hello')"
  assets.file 'logo.svg', path: Sidereal.root.join('assets/logo.svg')

  # Or every file in a directory, named by its path in it: .css files are
  # stylesheets, .js files scripts, and the rest files
  assets.directory Sidereal.root.join('assets')
end

Sidereal layouts will automatically generate public URLs for those assets, with content digest suffixes for cache-busting, and long-lived HTTP headers for CDNs. There’s no “precompile to the file-system” mode yet. You can just use a CDN, or write your own adapter! Also no JS build system, but that should also be easy to add, if needed.

But there’s more to this. Pages and Phlex components themselves can register their own assets. This means that you can package up self-contained, server-rendered components that come with their own co-located assets.

class UI::Chat < Sidereal::Components::BaseComponent
  stylesheet 'chat.css', path: 'chat.css'
  javascript 'chat.js', path: 'chat.js'
  file 'chat/avatar.svg', path: 'avatar.svg'

  # Inline, named after the class: ui/chat-1.css, ui/chat-1.js, ui/chat-2.css...
  css <<~CSS
    .chat { border: 1px solid; }
  CSS

  js <<~JS
    console.log('chat')
  JS

  def view_template = # Phlex markup here
end

Sidereal’s asset system will automatically include component-declared assets in the layout’s <head> section as fingerprinted URLs.

Live reloading

Sidereal now leverages the fact that every page opens an SSE stream to also reload selectively when assets are updated in development mode. Update a line in a CSS file, and Sidereal will send a patch to the browser to update the <link> tag for that one stylesheet.

Editing a CSS file and seeing the browser update the stylesheet without a full page reload

Dashboard

There’s a ton more changes, big and small, but one of the main objectives has been to design frameworks that let us build more “inspectable” apps. In the age of AI, I think it’s more important than ever to have abstractions that let us understand how systems work at a high level. I’m still working on a built-in dashboard for Sidereal+Sourced applications that leverages the architecture to tell you (and your agents) as much as possible about your app, deterministically. The fact that everything in these apps is reduced to structured messaging between components lets us go quite far in describing the system visually.

The Sourced dashboard's topology view: a map of deciders, projectors and machines in an Expenses domain, with a detail panel for the CurrencyConverter decider showing the events it reacts to and the commands it dispatches
Work in progress: the dashboard's topology view, generated from the app's declared inputs and outputs.