mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-26 01:47:24 +01:00
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.
200 lines
7.6 KiB
Dart
200 lines
7.6 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:crypto/crypto.dart';
|
|
|
|
import 'log.dart';
|
|
import 'record.dart';
|
|
import 'remote_store.dart';
|
|
|
|
const _defaultFilename = 'log.json';
|
|
|
|
/// What one device remembers between ticks so it can skip needless traffic.
|
|
///
|
|
/// Two facts, both cheap:
|
|
/// * [pushedRev] -- the hash of what this device last pushed, so an unchanged
|
|
/// log is not re-uploaded. 88% of the pushes in the GitHub-backed history
|
|
/// were byte-identical no-ops.
|
|
/// * [peerRevs] -- the hash each peer had last time we downloaded it, so an
|
|
/// unchanged peer is not re-downloaded.
|
|
///
|
|
/// **Must be stored next to the log itself and cleared with it.** Skipping an
|
|
/// unchanged peer is only sound because that peer's records are already
|
|
/// merged into the local log; a cache that outlived its log would skip peers
|
|
/// whose data had been lost.
|
|
class SyncState {
|
|
const SyncState({this.pushedRev, this.peerRevs = const {}});
|
|
|
|
factory SyncState.fromJson(Map<String, dynamic> json) => SyncState(
|
|
pushedRev: json['pushed_rev'] as String?,
|
|
peerRevs: {
|
|
for (final entry
|
|
in (json['peer_revs'] as Map<String, dynamic>? ?? {}).entries)
|
|
if (entry.value is String) entry.key: entry.value as String,
|
|
},
|
|
);
|
|
|
|
final String? pushedRev;
|
|
final Map<String, String> peerRevs;
|
|
|
|
Map<String, dynamic> toJson() => {
|
|
'pushed_rev': pushedRev,
|
|
'peer_revs': peerRevs,
|
|
};
|
|
}
|
|
|
|
/// Where [syncLog] persists its [SyncState] between runs.
|
|
///
|
|
/// Persistence is what makes the saving real for the short-lived callers:
|
|
/// `wake_alarm` PC is a fresh process every minute and `diet_guard` PC a
|
|
/// fresh process every 15 minutes, so an in-memory cache would save nothing.
|
|
abstract interface class SyncStateStore {
|
|
Future<SyncState> load();
|
|
Future<void> save(SyncState state);
|
|
}
|
|
|
|
/// A [SyncStateStore] that forgets everything, for tests and one-shot runs.
|
|
///
|
|
/// Correct but pessimistic: every tick re-downloads every peer and re-pushes
|
|
/// the local log, which is exactly the old behaviour.
|
|
class InMemorySyncStateStore implements SyncStateStore {
|
|
SyncState _state = const SyncState();
|
|
|
|
@override
|
|
Future<SyncState> load() async => _state;
|
|
|
|
@override
|
|
Future<void> save(SyncState state) async => _state = state;
|
|
}
|
|
|
|
/// The revision of a serialized log: a content hash, not a clock reading.
|
|
///
|
|
/// A hash rather than the log's maximum HLC because merging a peer's *older*
|
|
/// record changes the content without raising the maximum -- with three
|
|
/// devices in one namespace (diet-guard has `pc`, `phone` and `desktop`) a
|
|
/// clock-based revision can miss a peer's merged state. It is also the same
|
|
/// value used to suppress no-op pushes, so the two optimisations share one
|
|
/// mechanism.
|
|
String revisionOf(String encodedLog) =>
|
|
sha256.convert(utf8.encode(encodedLog)).toString();
|
|
|
|
/// Runs one full sync tick: pull every other device's log, merge, push.
|
|
///
|
|
/// Pulls from `<pathPrefix>/<other-device-id>/<filename>` for every device
|
|
/// directory the remote reports under [pathPrefix], merges each into
|
|
/// [localLog] with [mergeLogs], then pushes this device's own merged result
|
|
/// to `<pathPrefix>/<deviceId>/<filename>`.
|
|
///
|
|
/// [encode] serializes a merged log for pushing. [decode] parses a remote
|
|
/// device's pushed text back into a log; throwing [FormatException] (bad
|
|
/// JSON syntax) or [TypeError] (valid JSON, wrong shape -- e.g. a missing
|
|
/// or mistyped field during [Record.fromJson]) is treated as a
|
|
/// corrupt/unparsable push, and that device is skipped for this tick
|
|
/// rather than aborting the whole sync. Mirrors the Python `sync_log`'s
|
|
/// `(ValueError, KeyError, TypeError)` catch for the same reason.
|
|
///
|
|
/// Pass [stateStore] to enable revision tracking, which skips downloading
|
|
/// peers that have not changed and skips pushing a log that has not changed.
|
|
/// Without it the tick behaves exactly as it always did: fetch everything,
|
|
/// push unconditionally.
|
|
///
|
|
/// Revisions live at `<revsPath>/<deviceId>` -- one small text node per
|
|
/// device, each written only by its owner. Deliberately *not* one shared map
|
|
/// per namespace: a whole-map write would erase every other device's entry,
|
|
/// after which those peers would look permanently unchanged and never be
|
|
/// fetched again. Per-device keys make that failure impossible rather than
|
|
/// merely avoided.
|
|
Future<Log> syncLog({
|
|
required RemoteStore client,
|
|
required String deviceId,
|
|
required String pathPrefix,
|
|
required Log localLog,
|
|
required String Function(Log log) encode,
|
|
required Log Function(String text) decode,
|
|
String filename = _defaultFilename,
|
|
String commitMessage = 'crdt_sync: update log',
|
|
SyncStateStore? stateStore,
|
|
String? revsPath,
|
|
}) async {
|
|
final revs = revsPath ?? defaultRevsPath(pathPrefix);
|
|
final state = await stateStore?.load() ?? const SyncState();
|
|
final remoteRevs = stateStore == null
|
|
? const <String, String>{}
|
|
: await _remoteRevs(client, revs);
|
|
|
|
var mergedLog = Map<String, Record>.from(localLog);
|
|
final seenRevs = <String, String>{};
|
|
for (final otherDeviceId in await client.listDirectory(pathPrefix)) {
|
|
if (otherDeviceId == deviceId) continue;
|
|
final remoteRev = remoteRevs[otherDeviceId];
|
|
if (remoteRev != null && remoteRev == state.peerRevs[otherDeviceId]) {
|
|
// Unchanged since we last merged it, and that merge is already part of
|
|
// localLog -- so the (potentially hundreds of KB) download is pure
|
|
// waste. Carry the revision forward so it stays skipped next tick.
|
|
seenRevs[otherDeviceId] = remoteRev;
|
|
continue;
|
|
}
|
|
final text = await client.getFileText(
|
|
'$pathPrefix/$otherDeviceId/$filename',
|
|
);
|
|
if (text == null) continue;
|
|
try {
|
|
mergedLog = mergeLogs(mergedLog, decode(text));
|
|
} on FormatException {
|
|
continue;
|
|
} on TypeError {
|
|
continue;
|
|
}
|
|
// Only remembered once the merge succeeded: a corrupt push must be
|
|
// retried next tick, not marked as seen.
|
|
seenRevs[otherDeviceId] = remoteRev ?? revisionOf(text);
|
|
}
|
|
|
|
final encoded = encode(mergedLog);
|
|
final rev = revisionOf(encoded);
|
|
final unchanged = stateStore != null && rev == state.pushedRev;
|
|
if (!unchanged) {
|
|
await client.putFileText(
|
|
'$pathPrefix/$deviceId/$filename',
|
|
encoded,
|
|
message: commitMessage,
|
|
);
|
|
if (stateStore != null) {
|
|
// Published after the log, never before: a peer that cached "seen rev
|
|
// X" against a log it never received would skip it forever.
|
|
await client.putFileText(
|
|
'$revs/$deviceId',
|
|
rev,
|
|
message: commitMessage,
|
|
);
|
|
}
|
|
}
|
|
await stateStore?.save(SyncState(pushedRev: rev, peerRevs: seenRevs));
|
|
return mergedLog;
|
|
}
|
|
|
|
/// Where revisions live for a given [pathPrefix]: a `revs` sibling of the
|
|
/// device directory, e.g. `diet-guard-sync/devices` -> `diet-guard-sync/revs`
|
|
/// and `todo-sync/notes` -> `todo-sync/revs`.
|
|
String defaultRevsPath(String pathPrefix) {
|
|
final cut = pathPrefix.lastIndexOf('/');
|
|
return cut < 0 ? '$pathPrefix/revs' : '${pathPrefix.substring(0, cut)}/revs';
|
|
}
|
|
|
|
/// Reads every peer's published revision, cheaply where the backend allows.
|
|
///
|
|
/// Degrades to an empty map -- meaning "fetch everything", the old behaviour
|
|
/// -- on any backend without [BulkMapReader], so correctness never depends on
|
|
/// the optimisation being available.
|
|
Future<Map<String, String>> _remoteRevs(
|
|
RemoteStore client,
|
|
String revsPath,
|
|
) async {
|
|
// A pattern bind rather than `is!` + promotion: BulkMapReader is not a
|
|
// subtype of RemoteStore, and Dart only promotes to subtypes of the
|
|
// declared type -- so the intersection has to be named explicitly.
|
|
if (client case final BulkMapReader reader) {
|
|
return reader.getStringMap(revsPath);
|
|
}
|
|
return const {};
|
|
}
|