CRDTDocument class

CRDT Document implementation

A CRDTDocument is the main entry point for the CRDT system. It manages the DAG, ChangeStore, and provides methods for creating, applying, exporting, and importing changes.

Identity:

  • documentId: identifies the document/resource. It is useful for routing, persistence, and access control. It does not participate in operation identifiers.
  • peerId: identifies the peer/author generating operations. It is used in OperationId together with the Hybrid Logical Clock.

Example

// Create two documents (simulating different peers)
 final doc1 = CRDTDocument(
   peerId: PeerId.parse('45ee6b65-b393-40b7-9755-8b66dc7d0518'),
 );
 final doc2 = CRDTDocument(
   peerId: PeerId.parse('a90dfced-cbf0-4a49-9c64-f5b7b62fdc18'),
 );

 // Create text handlers
 final fugueTextDoc1 = CRDTFugueTextHandler(doc1, 'text');
 final fugueTextDoc2 = CRDTFugueTextHandler(doc2, 'text');

 // Initial state
 fugueTextDoc1.insert(0, 'Hello');

 // Sync doc1 to doc2
 var changesDoc1 = doc1.exportChanges();
 doc2.importChanges(changesDoc1);

 // Concurrent edits
 fugueTextDoc1.insert(5, ' World'); // doc1: "Hello World"
 fugueTextDoc2.insert(5, ' Dart'); // doc2: "Hello Dart"

 // Sync both ways
 final changes1After = doc1.exportChanges();
 final changes2After = doc2.exportChanges();

 doc2.importChanges(changes1After);
 doc1.importChanges(changes2After);

 // Both documents will have the same final state
 print(fugueTextDoc1.value); // Prints "Hello World Dart" or "Hello Dart World"
 print(fugueTextDoc2.value); // Prints the same as text1

 // Create list handler
 final list1 = CRDTListHandler(doc1, 'list');
 final list2 = CRDTListHandler(doc2, 'list');

 list1
   ..insert(0, 'Hello')
   ..insert(1, 'World')
   ..insert(2, 'Dart');

 print(list1.value); // Prints ["Hello", "World", "Dart"]

 // sync doc1 to doc2
 changesDoc1 = doc1.exportChanges();
 doc2.importChanges(changesDoc1);

 print(list2.value); // Prints ["Hello", "World", "Dart"]

 // history session
 final historySession = doc1.toTimeTravel();
 final viewListHandler =
     historySession.getHandler(
   (doc) => CRDTListHandler(doc, 'list'),
 );
 print(viewListHandler.value); // Prints ["Hello", "World", "Dart"]

 historySession.previous();
 print(viewListHandler.value); // Prints ["Hello", "World"]

 // transaction
 doc1.runInTransaction(() {
   list1
     ..insert(3, 'Flutter')
     ..insert(4, '!');
 });
 // insertions are committed at the end
 print(list1.value); // Prints ["Hello", "World", "Dart", "Flutter", "!"]

 // snapshot
 // save pruning
 var snapshotDoc1 = doc1.takeSnapshot(pruneHistory: false);
 changesDoc1 = doc1.exportChanges();
 doc2.import(
   snapshot: snapshotDoc1,
   changes: changesDoc1,
   pruneHistory: false,
 );

 // changes are read starting from the snapshot then changed are applied
 print(list2.value); // Prints ["Hello", "World", "Dart", "Flutter", "!"]
 // changes are not pruned
 print(doc1.exportChanges().length); // Prints 8

 // aggressive pruning
 snapshotDoc1 = doc1.takeSnapshot(
   pruneHistory: true,
 );
 // changes are pruned
 doc1.garbageCollect(doc1.getVersionVector());
 print(doc1.exportChanges().length); // Prints 0
Inheritance

Constructors

CRDTDocument({PeerId? peerId, String? documentId, HybridLogicalClock? initialClock})
Creates a new CRDTDocument with the given identifiers.

Properties

documentId → String
Gets the document ID of this document
no setteroverride
events → Stream<CRDTDocumentEvent>
A stream of the moves of this document's durable state: the changes it holds, and the snapshot they are replayed on top of.
no setter
hashCode → int
The hash code for this object.
no setterinherited
hlc → HybridLogicalClock
Gets the current timestamp of this document
no setteroverride
isDisposed → bool
Whether the document is disposed
no setterinherited
isEmpty → bool
Whether this document is empty. (no changes and no snapshot)
no setter
isInTransaction → bool
Whether a transaction is currently active.
no setter
localChanges → Stream<Change>
A stream that emits the Changes this document writes, in replay order.
no setter
peerId → PeerId
Gets the peer ID of this document
no setteroverride
registeredHandlers → Map<String, Handler>
All handlers currently registered on this document, keyed by their id.
no setter
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited
snapshot → Snapshot?
The snapshot the history of this document is replayed on top of; null before the first one.
no setter
updates → Stream<void>
A stream that emits when the document state updates.
no setter
version → Set<OperationId>
Gets the current version of this document (the frontiers of the DAG)
no setteroverride

Methods

applyChange(Change change, {Object? origin}) → bool
Applies a Change to this document
binaryExportChanges({Set<OperationId>? from}) → Uint8List
Exports Changes as a compact binary format.
binaryImportChanges(Uint8List data, {Object? origin}) → int
Imports Changes from the compact binary format.
changeCountForHandler(String handlerId) → int
Returns the number of Changes produced by the handler with the given handlerId.
override
changesForHandler(String handlerId, {VersionVector? fromVersionVector}) → List<Change>
Returns the Changes produced by the handler with the given handlerId.
override
createChange(Operation operation, {int? physicalTime, Object? origin}) → Change
Creates a new Change with the given operation
deleteHandler(Handler handler) → void
Deletes handler, and every handler reachable from it through references, for every peer.
override
deleteHandlerRef(HandlerRef ref) → void
Deletes the handler ref points at, and every handler reachable from it, for every peer.
override
describeBuildCapabilities() → DocumentCapabilities
What this build can read, by handler kind.
describeDataRequirements() → DocumentRequirements
The formats this document's data is written in, by handler kind.
dispose() → void
Disposes of the document
override
exportChanges({Set<OperationId>? from, VersionVector? fromVersionVector}) → List<Change>
Exports Changes from a specific version.
override
exportChangesNewerThan(VersionVector versionVector) → List<Change>
Exports Changes that are newer than the provided versionVector.
garbageCollect(VersionVector protectUntil, {Object? origin}) → void
Prunes the DAG and the change store. protectUntil represents the stability frontier (minimum common version) until which the history is protected from garbage collection.
getVersionVector() → VersionVector
It represents the latest operation for each peer of this document
handler<T extends Handler>(HandlerSpec<T> spec, String id) → T
The handler spec describes under id, or the one already open there.
inherited
handlerById(String id) → Handler?
The handler open under id; null when none is.
inherited
import({Snapshot? snapshot, List<Change>? changes, bool merge = false, bool pruneHistory = true, Object? origin}) → int
Import snapshot and changes. merge is false by default.
importChanges(List<Change> changes, {Object? origin}) → int
Imports Changes from another document
importSnapshot(Snapshot snapshot, {bool pruneHistory = true, Object? origin}) → bool
Import Snapshot
isDeleted(String handlerId) → bool
Whether the handler with handlerId was deleted with deleteHandler, on this peer or on a peer whose changes this document holds.
inherited
mergeSnapshot(Snapshot snapshot, {bool pruneHistory = true, Object? origin}) → void
Merges a Snapshot with the current snapshot
newHandlerId() → String
Generates a globally-unique id for a handler created dynamically.
inherited
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
prepareMutation() → void
Moves the document's clock forward, as registering an operation would.
override
reconstruct() → void
Rebuilds every handler reachable from the data this document holds.
register<T extends Handler>(HandlerSpec<T> spec) → void
Declares a kind this peer never opens itself, so a reference to one can still be rebuilt.
inherited
registerOperation(Operation operation) → void
Registers an Operation to this document.
override
resolveHandler(HandlerRef ref) → Handler?
Resolves ref to a handler instance.
inherited
revisionForHandler(String handlerId) → int
A monotonically increasing revision for the handler with the given handlerId.
override
roots() → Iterable<Handler>
The handlers that are not referenced by any other container handler, i.e. the entry points of the nested tree.
runInTransaction<T>(T action(), {Object? origin}) → T
Runs action within a transaction, committing at the end.
override
shouldApplySnapshot(Snapshot snapshot) → bool
Whether the given snapshot should be applied.
takeSnapshot({bool pruneHistory = true, Object? origin}) → Snapshot
Takes a snapshot of the document.
toString() → String
Returns a string representation of this document
override
toTimeTravel() → HistorySession
Create a history session from the current state.

Operators

operator ==(Object other) → bool
The equality operator.
inherited

Static Properties

builtInCapabilities → DocumentCapabilities
The kinds every document of this build reads, whatever its handlers.
final