ds_sync_contract 0.1.1
ds_sync_contract: ^0.1.1 copied to clipboard
Pure type contract for the ds_easy_db sync ecosystem: capabilities, conflict policies, delta and push types, and the remote adapter interface.
// Shows both halves of the contract: a remote adapter as a backend author
// writes it, and the policies an application picks for its collections.
//
// Run with `dart run example/example.dart`.
import 'package:ds_sync_contract/ds_sync_contract.dart';
void main() async {
final backend = InMemoryAdapter();
// 1. A device pushes a new record. Results always come back per record.
final created = await backend.pushBatch([
PushItem(
collection: 'tasks',
id: 't1',
document: {'title': 'Buy milk'},
localUpdatedAt: DateTime.now().toUtc(),
),
]);
final anchor = created.single.newAnchor;
print(
'created t1: ${created.single.status.name}, version ${anchor?.version}');
// 2. Another device pulls everything since the beginning. The cursor it gets
// back is opaque: only this adapter knows it is a sequence number.
final first = await backend.pullSince('tasks', null);
print('pulled ${first.changed.map((r) => r.id).toList()}, '
'cursor ${first.nextCursor}');
// 3. That device edits the record, based on the anchor it pulled.
await backend.pushBatch([
PushItem(
collection: 'tasks',
id: 't1',
document: {'title': 'Buy oat milk'},
localUpdatedAt: DateTime.now().toUtc(),
baseAnchor: first.changed.single.anchor,
),
]);
// 4. The first device still holds the old anchor, so its push is a conflict.
// The engine would now pull the new copy and hand both to the policy.
final stale = await backend.pushBatch([
PushItem(
collection: 'tasks',
id: 't1',
document: {'title': 'Buy milk and bread'},
localUpdatedAt: DateTime.now().toUtc(),
baseAnchor: anchor,
),
]);
print('stale push: ${stale.single.status.name}');
// 5. A delta pull from the earlier cursor only returns what changed since.
final delta = await backend.pullSince('tasks', first.nextCursor);
print('delta: ${delta.changed.map((r) => r.data).toList()}');
// 6. Policies are the application's decision, per collection.
final policies = <String, ConflictPolicy>{
'shopping_list': ConflictPolicy.lastWriteWins,
'cash_book': ConflictPolicy.custom(
(local, remote) => {
...remote,
'entries': {
...?(remote['entries'] as List<Object?>?),
...?(local['entries'] as List<Object?>?),
}.toList(),
},
),
};
final deletePolicy = DeleteConflictPolicy.custom(
(context) =>
context.direction == DeleteConflictDirection.localModifyRemoteDelete
? DeleteConflictOutcome.keep(context.survivingDocument)
: DeleteConflictOutcome.delete,
);
print('configured ${policies.length} content policies and '
'${deletePolicy.runtimeType}');
}
/// A versioned in-memory backend implementing [SyncRemoteAdapter].
///
/// Every write bumps a global sequence number, which doubles as the delta
/// cursor. Deletions are remembered, so delta pulls can report them.
class InMemoryAdapter implements SyncRemoteAdapter {
final Map<String, Map<String, _Entry>> _collections = {};
int _sequence = 0;
@override
SyncCapabilities get capabilities => const SyncCapabilities(
supportsVersioning: true,
supportsTimestamps: true,
supportsDeltaPull: true,
supportsDeltaDeletes: true,
supportsBatchWrite: true,
);
@override
SyncError mapError(Object error, StackTrace stackTrace) {
// A real adapter classifies its native errors here. "Backend
// unreachable" must map to transient: that is the connectivity check.
return SyncError(
SyncErrorKind.transient,
message: '$error',
cause: error,
stackTrace: stackTrace,
);
}
@override
Future<DeltaResult> pullSince(String collection, Object? cursor) async {
final since = cursor is int ? cursor : 0;
final entries = (_collections[collection] ?? const <String, _Entry>{})
.entries
.where((entry) => entry.value.sequence > since);
return DeltaResult(
changed: [
for (final entry in entries)
if (entry.value.data != null)
RemoteRecord(
id: entry.key,
data: Map<String, dynamic>.of(entry.value.data!),
anchor: entry.value.anchor,
),
],
deleted: [
for (final entry in entries)
if (entry.value.data == null) entry.key,
],
nextCursor: _sequence,
);
}
@override
Future<List<PushResult>> pushBatch(List<PushItem> items) async {
return [for (final item in items) _apply(item)];
}
PushResult _apply(PushItem item) {
final records = _collections.putIfAbsent(item.collection, () => {});
final current = records[item.id];
// Optimistic concurrency: the device must have seen the latest version.
final seen = item.baseAnchor?.version;
if (current != null && current.data != null && seen != current.version) {
return PushResult(
id: item.id,
status: PushStatus.conflict,
error: const SyncError(SyncErrorKind.conflict),
);
}
final entry = _Entry(
data: item.isDelete ? null : Map<String, dynamic>.of(item.data!),
version: (current?.version ?? 0) + 1,
sequence: ++_sequence,
updatedAt: DateTime.now().toUtc(),
);
records[item.id] = entry;
return PushResult(
id: item.id,
status: PushStatus.success,
newAnchor: item.isDelete ? null : entry.anchor,
);
}
}
class _Entry {
_Entry({
required this.data,
required this.version,
required this.sequence,
required this.updatedAt,
});
final Map<String, dynamic>? data;
final int version;
final int sequence;
final DateTime updatedAt;
RemoteAnchor get anchor =>
RemoteAnchor(version: version, updatedAt: updatedAt);
}