Skip to main content

Changes and sync

Every edit of a handler becomes an operation. The document turns the operations into changes, adds them to its change graph and hands them out. A change is what travels to the other peers.

Transactions​

Outside a transaction, each write is a change of its own. Inside runInTransaction, the writes are grouped: they become changes together, watchers hear about them once, and they reach the other peers together.

doc.runInTransaction(() {
title.change('Shopping');
items.insert(0, 'milk');
items.insert(1, 'eggs');
}); // one update for the listeners, one undo step
  • runInTransaction returns what the callback returns. A nested call joins the outer transaction.
  • Pass origin to tag the writes. The deltas they produce report it, so a listener can skip its own echo (see Tagging a write).
  • There is no rollback: when the callback throws, what it wrote before the throw is kept.

At the end, consecutive operations can be merged into fewer changes: typing a word inside one transaction can produce one change, not one per letter. How and when: see Transactions.

Where the document is​

  • version is the frontiers: the latest changes, the ones nothing depends on yet.
  • getVersionVector() says, for each peer, the newest of its changes this document holds.
  • revisionForHandler(id) is a number that grows when the handler may read differently. It is cheap: the signal to rebuild a view on.

A sync layer sends its version vector to ask a peer for the changes it is missing.

Exchanging changes​

// Everything, or only what a peer is missing.
final all = alice.exportChanges();
final missing = alice.exportChangesNewerThan(bob.getVersionVector());

bob.importChanges(missing); // returns how many were applied
  • Importing is idempotent. A change the document already holds is skipped, so sending too much is harmless.
  • The order does not matter. A change whose dependencies are missing is skipped, and can be imported again once they arrive.
  • One change at a time is stricter. applyChange throws a CausallyNotReadyException when what the change depends on is missing. importChanges skips that change instead, and returns how many it applied.
  • For a transport of your own, localChanges is the stream of the changes this peer writes, and binaryExportChanges / binaryImportChanges carry them as one compact blob.
  • You rarely call these yourself. A sync client and a persistence adapter do it for you. Use them for a transport of your own, or in tests.

The model behind it (operations, the DAG, frontiers, identity) is in Documents and changes. The bytes are in Binary format.

For handler authors

registerOperation, createChange and prepareMutation are how a handler writes into the document. Your app code goes through the handlers instead. See Custom handlers.