Extracts the three-method remote surface GitHub was reached through into a `RemoteStore` interface, then implements it against Firebase Realtime Database over REST, so apps can move backend with a constructor change. Why REST and not the SDKs: official FlutterFire has no Linux desktop support, and `wake_alarm`'s PC side is a dependency-free systemd job. The RTDB REST endpoints are plain HTTPS and behave identically on Linux, Android and headless. Firebase is a transport, never the datastore -- each app keeps its local log as the source of truth, so offline-first survives. Why RTDB and not Firestore: on the Spark plan RTDB bills only storage and bandwidth with no per-operation quota, so a runaway loop cannot exhaust a daily budget and silently stop syncing mid-day. Two savings make the no-cost tier a guarantee rather than a hope. Measured against the GitHub-backed history this replaces: 4894 of 5542 commits (88.3%) were byte-identical no-ops, and every tick re-downloaded every peer's whole log. Both are now driven by one sha256 revision -- an unchanged log is not re-pushed, and an unchanged peer is not re-fetched. That turns egress from "ticks x log size" (~700 MB/month, and growing with the log) into "edits" (~40 MB/month against a 10 GiB cap). Revisions are one node per device, written only by its owner, rather than one shared map -- a whole-map write would erase every peer's entry, after which those peers would look permanently unchanged and never be fetched again. Per-device keys make that impossible rather than merely avoided. `.` is illegal in an RTDB key and the REST `.json` is a format suffix, so paths get a reversible `~XX` escape (`log.json` -> `log~2Ejson`). Lossy extension-stripping would break `todo`, whose listings return filenames. `MirrorStore` / `MirrorSyncClient` dual-writes during the cutover. Reads consult *both* backends: with primary-only reads a migrated device would never see an un-migrated peer's writes while still mirroring its own back -- silent one-directional convergence with no error raised. Writes are asymmetric on purpose: a primary failure fails the tick, a mirror failure is logged and survived. Auth is Firebase email/password over identitytoolkit REST, with mandatory refresh-token rotation. No service-account key anywhere: it would bypass the security rules and is trivially extractable from an APK. Verified live against a real database, not only mocks: sign-in and refresh, key escaping round-tripping byte-for-byte, an unchanged tick writing nothing, two devices converging, a revoked session throwing rather than returning null, and a log written by the Python client being read by the Dart one. No app is migrated by this commit; every app still runs on GitHub. Dart: 194 tests. Python: 203 tests at 100% branch coverage. No lint suppressions added. |
||
|---|---|---|
| .. | ||
| lib | ||
| test | ||
| tool | ||
| .gitignore | ||
| analysis_options.yaml | ||
| LICENSE | ||
| pubspec.yaml | ||
| README.md | ||
crdt_sync
Shared CRDT merge scheme + GitHub-Contents-API sync transport, extracted for
reuse across four personal apps that each need cross-device sync: todo,
diet_guard's Flutter app, wake_alarm's phone_app, and screen-locker's
workout_app. Pure Dart -- no Flutter SDK dependency (package:http only)
-- so it works in both Flutter apps and plain Dart tooling. Mirrors the
Python crdt-sync package
module-for-module and test-for-test, so the merge algorithm canonically
agrees on both sides of any sync between a Dart client and a Python one.
The merge scheme
See the Python package's README for the full rationale; in short, a generic LWW-map-with-sticky-remove:
Hlc-- a Hybrid Logical Clock(wallTimeMs, counter, nodeId), totally ordered, monotonic even across clock skew.Record-- an id, a per-field last-writer-wins map (fieldName -> (value, Hlc)), and a stickydeletedflag (deleted = a.deleted || b.deleted, never the other way -- a delete can never be silently undone).Log--Map<String, Record>, merged by taking the union of ids and merging shared ones.
All three merges are commutative and idempotent -- see test/log_test.dart
for the concrete convergence-property tests.
Install
Consume via a git dependency on the utils monorepo:
dependencies:
crdt_sync:
git:
url: https://github.com/kuhyx/utils
ref: crdt_sync_dart-v0.2.0
path: crdt_sync_dart
Usage
import 'package:crdt_sync/crdt_sync.dart';
final nodeId = 'phone';
final clock = Hlc.newTick(nodeId);
final record = Record(
id: 'abc123',
fields: {'text': ('buy milk', clock)},
);
final client = GitHubClient(owner: 'kuhyx', repo: 'my-app-sync', token: token);
final merged = await syncLog(
client: client,
deviceId: nodeId,
pathPrefix: 'devices',
localLog: {record.id: record},
encode: (log) => jsonEncode(log.map((k, r) => MapEntry(k, r.toJson()))),
decode: (text) => (jsonDecode(text) as Map<String, dynamic>).map(
(k, v) => MapEntry(k, Record.fromJson(v as Map<String, dynamic>)),
),
);
syncLog pulls every other device's last-pushed log from
<pathPrefix>/<other-device-id>/..., merges each into the local log with
mergeLogs, then pushes this device's own merged result back up.
Local persistence (LogStore)
The merge scheme above is in-memory only. For an app that needs to keep its
Log on disk and drive a live UI off it, this package also ships a
domain-agnostic LogStore:
import 'package:crdt_sync/crdt_sync.dart';
import 'package:crdt_sync/crdt_sync_io.dart'; // FileLogPersistence (dart:io)
final store = LogStore(
persistence: FileLogPersistence(File('$docsDir/notes.json')),
nodeId: 'phone',
);
await store.load();
// Reactive read: re-derive a domain view whenever anything changes. Filtering,
// sorting and search live here, in the app -- the store is field-agnostic.
final Stream<List<Record>> visible = store.changes.map(
(_) => store.values.where((r) => !r.deleted).toList(),
);
await store.upsert(Record(id: 'n1', fields: {'text': ('hi', store.nextHlc())}));
await store.delete('n1'); // sticky tombstone, not a hard remove
// After a sync tick, swap in the merged result:
await store.replaceAll(await syncLog(/* ... */, localLog: store.snapshot()));
LogStore is pure Dart (import it from the main barrel); the filesystem-backed
FileLogPersistence lives behind the separate crdt_sync_io.dart entrypoint so
the core stays web-safe. Querying is deliberately not in the library — a
Record's fields are an opaque map, so the app filters store.values itself.
The Python side mirrors the on-disk format via crdt_sync.dump_log/read_log
(load/save only; no reactive stream — that's a Dart/Flutter convenience).
Development
dart pub get
dart analyze
dart test