Skip to main content

Aggregates

Some data is best described by what happened to it: a car is registered, it changes owner, it gets a service. CRDTAggregateHandler holds one such object (an aggregate). The app writes events, and a function you write, reduce, says how each event moves the state.

This is model C of Which handler do you need?. The todo list recipe is a complete, tested aggregate, with undo.

Defining an aggregate​

A Car has an owner, a license plate set once and never changed, and its most recent maintenance record:

final class CarAggregate extends AggregateDefinition<Car, CarEvent> {
const CarAggregate();


String get handlerType => 'car';

// The license plate is the aggregate's id: no event ever changes it.

Car initial(String id) => Car(licensePlate: id);


Car reduce(Car state, CarEvent event, EventContext context) =>
switch (event) {
OwnerChanged(:final owner) => state.copyWith(owner: owner),
MaintenanceLogged(:final note) =>
state.copyWith(lastMaintenance: note),
};


ValueCodec<CarEvent> get eventCodec => const CarEventCodec();


ValueCodec<Car> get stateCodec => const CarCodec();
}

final car = doc.handler(
CRDTAggregateHandler.spec(const CarAggregate()),
'AB123CD',
);
car.dispatch(const OwnerChanged('Alice'));
car.dispatch(const MaintenanceLogged('Oil change'));
print(car.value.owner); // Alice

CRDTAggregateHandler replays the events of every peer in the same order, (clock, author), through reduce. Peers that hold the same events hold the same state.

What you get​

Compared with a flat value (model A) or a tree of handlers (model B):

  • One handler per aggregate, with a typed value, one watch() stream and one CRDTUndoManager.track. To make it undoable, extend InvertibleAggregateDefinition and give it an invert.
  • Atomic writes. dispatchAll puts its events in one change: a peer receives all of them or none.
  • Stable identities. EventContext.id is the same on every peer, so an entity that an event creates can keep it, and later events name that entity instead of a position that a concurrent insert may shift. dispatch returns that id.

The rules of reduce​

These rules are what keep the peers equal:

  • Pure and deterministic. No clock, no randomness, no iteration over an unordered set. Take the author and the event id from EventContext.
  • Identities, never positions. When an event creates or targets part of the state (an item in a list, say), address it by the id EventContext gives, never by where it sits: a concurrent insert can shift a position, never an id.
  • A new state for every event. The handler keeps the state you return and hands it out as its value.
  • An event on a missing target does nothing. An event addressed to an entity another peer already removed finds nothing, and that is the merged result.
  • Throw to refuse an event. dispatch then throws the same error and writes nothing. A change whose event throws is skipped whole on every peer, so a batch that a concurrent event made invalid leaves no trace.

What it does not do​

It does not merge two concurrent edits of the same field: the event later in the replay order wins, for the whole field. For text that peers type together, keep a CRDTFugueTextHandler next to the aggregate.

An event that arrives older than the newest one already applied makes the next read replay the aggregate's history since the last snapshot. So keep one aggregate small, and take snapshots.

Versions and migrations​

Events and the snapshot state are written in the definition's version. When the bytes of eventCodec or stateCodec change, or an event takes a new meaning in reduce, raise version and add one AggregateMigration from the previous version:

final class CarV1ToV2 extends AggregateMigration {
const CarV1ToV2();


int get from => 1;


List<Uint8List> upEvent(Uint8List event) => /* v1 event → v2 events */;


Uint8List upState(Uint8List state) => /* v1 state bytes → v2 */;
}

final class CarAggregate extends AggregateDefinition<Car, CarEvent> {

int get version => 2;


List<AggregateMigration> get migrations => const [CarV1ToV2()];
// ...
}

The history keeps the bytes each peer wrote, so a migration never rewrites it: it runs every time old data is read. Three rules follow:

  1. Pure and deterministic, like reduce.
  2. Ids never move. upEvent may drop an event or split it into several: the first event keeps the id of the one it came from, and each other one gets an EventId.part of its own.
  3. upState agrees with upEvent. The upgraded snapshot has to equal the state the upgraded events replay to. Otherwise a peer that starts from a snapshot diverges from one that replays the history. Keep the bytes an old build wrote as test fixtures, and check both paths.

Every version travels under its own operation kind and snapshot blob version, so a build that meets a newer version refuses it, and the capability check of the sync reports the mismatch before that. Peers have to upgrade before they write in a new version. A build reads every version its migrations lead up from. A snapshot is always written in the current version: once every replica has taken one that pruned the old events, drop the migrations below it.