diet-guard/app/lib/services/sync_service.dart
Krzysztof kuhy Rudnicki da0b54d886
Some checks are pending
pre-commit / pre-commit (push) Waiting to run
Tests / test (3.10) (push) Waiting to run
Tests / test (3.11) (push) Waiting to run
Tests / test (3.12) (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Sync meals and the food bank through Firebase, mirroring to GitHub
The largest consumer moves last on purpose: diet_guard was 71% of all sync
traffic, and both its surfaces (the PC timer and the phone app) share one
prefix, so they move together.

Firebase becomes the primary backend when it is set up, with GitHub kept as a
mirror so a device that has not moved yet still converges. An unconfigured
device keeps syncing exactly as before, which is also the rollback.

Revision tracking is new here. The PC hand-rolled its own pull-merge-push
instead of calling sync_log, so it had none: every tick re-downloaded every
peer's whole food log -- hundreds of KB, 96 times a day -- and re-pushed its
own regardless of change. It now reads one small revision map first, skips any
peer whose hash is unchanged, and suppresses a no-op push. Every sub-sync
(log, budget, food bank, manual bank) takes the client as a parameter, so one
swap covers all four.

The app could not have reached Firebase at all: nothing called saveAccount(),
so loadAccount() always returned null and openFirebase() always returned null.
Settings now has a Firebase section that stores the account in the OS keystore
and signs in immediately, so a typo surfaces on the screen where it can be
fixed rather than as a silently failed background sync hours later. The email
and password never touch the repo -- it is public.

Platform reaches now degrade instead of failing: an unavailable keystore or
application-support directory costs one tick of extra traffic, where before it
would have taken sync down entirely. Caught by `on Object` rather than
`on Exception`, because an uninitialised binding raises an Error.

Verified end to end against the real database, not just in tests: a live PC
sync merged 57 days / 339 entries and put 221 KB of food log plus 97 food-bank
records into Firebase; a second unchanged tick issued zero pushes; and the
Dart client signed in and read back all 339 meals and 97 foods, then completed
a push / publish-revision / suppress-no-op round trip under a throwaway prefix.

diet_guard: 618 tests at 100% branch coverage.
diet_guard_app: 477 tests. Two assertions moved from 4 pushes to 5 -- the
extra one is this device's revision, published after the log so a peer can
never cache "seen rev X" against a log it never received.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SJ9sxEw3ymzXNjL7SHNpJc
2026-08-05 08:35:21 +02:00

149 lines
5.8 KiB
Dart

/// Cross-device log sync orchestration for the diet_guard companion app.
///
/// Pulls every other device's pushed log from GitHub-backed dumb storage via
/// crdt_sync's shared transport ([GitHubClient]/[syncLog]), merges with the
/// local log via crdt_sync's shared CRDT scheme (`sync_merge.dart` adapts
/// [FoodEntry]s to/from [Record]), rebuilds the food bank, and pushes this
/// device's own merged log back up in the new Record-based wire format.
///
/// The daily budget syncs alongside the food log in the same tick (see
/// [_syncBudget]): a sibling `budget.json` per device, merged
/// last-writer-wins by edit time rather than union-of-immutable-entries,
/// since a budget (unlike a food-log entry) can be edited repeatedly.
library;
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/github_client_factory.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/sync_merge.dart';
import 'package:diet_guard_app/services/sync_state_factory.dart';
const _devicesDir = 'diet-guard-sync/devices';
/// Runs one full sync tick: pull, merge, persist, push.
///
/// Returns the merged log as it now sits on disk locally. Propagates any
/// [GitHubSyncError] from the client for the caller (auto-sync / the manual
/// "Sync now" action) to decide how to report.
Future<DayLog> runSync(RemoteStore client, {SyncStateStore? stateStore}) async {
final logService = LogStorageService.instance;
final local = await logService.readLog();
final mergedLog = await syncLog(
client: client,
deviceId: syncDeviceId,
pathPrefix: _devicesDir,
localLog: dayLogToLog(local),
encode: encodeLogForPush,
decode: parseRemoteLog,
filename: 'food_log.json',
commitMessage: 'diet_guard_app sync',
// Without this every sync re-downloads every peer's whole food log --
// hundreds of KB -- whether or not anything changed, and re-pushes an
// unchanged one. That is the traffic the Firebase free tier's monthly
// budget depends on not happening.
stateStore: stateStore ?? await openSyncStateStore(),
);
final merged = logToDayLog(mergedLog);
await logService.writeLog(merged);
await FoodBankService.instance.rebuildAndPersist(merged);
await _syncBudget(client);
await _syncFoodBank(client);
await _syncManualBank(client);
return merged;
}
/// Pulls, merges, persists and pushes the log-derived food bank.
///
/// Runs after the local rebuild above, so this device's records already
/// reflect the merged log; the merge then unions in whatever another device
/// knows, max-count winning per food. Mirrors `_sync._sync_food_bank`.
Future<void> _syncFoodBank(RemoteStore client) async {
final merged = await syncLog(
client: client,
deviceId: syncDeviceId,
pathPrefix: _devicesDir,
localLog: foodBankToLog(await FoodBankService.instance.readBank()),
encode: encodeFoodBankForPush,
decode: parseRemoteFoodBank,
filename: 'food_bank.json',
commitMessage: 'diet_guard_app sync',
);
await FoodBankService.instance.writeBank(logToFoodBank(merged));
}
/// Pulls, merges, persists and pushes the hand-curated food bank.
///
/// Curated entries are the one part of the bank that is not derivable from
/// the food log, so unlike `food_bank.json` they need a real merge:
/// last-writer-wins per food name by edit time, union across devices. Mirrors
/// `_sync._sync_manual_bank`.
Future<void> _syncManualBank(RemoteStore client) async {
final local = await FoodBankService.instance.readManualBank();
final merged = await syncLog(
client: client,
deviceId: syncDeviceId,
pathPrefix: _devicesDir,
localLog: manualBankToLog(local),
encode: encodeManualBankForPush,
decode: parseRemoteManualBank,
filename: 'food_bank_manual.json',
commitMessage: 'diet_guard_app sync',
);
await FoodBankService.instance.applyMergedManualBank(logToManualBank(merged));
}
/// Pulls other devices' budgets, merges, applies the winner locally, pushes.
///
/// Reuses [syncLog] (it always pushes the merged result, even an empty
/// one -- harmless and consistent with the food-log sync above). This
/// device contributes nothing to the merge until the goal has been
/// explicitly set at least once (see
/// [AppSettingsService.dailyKcalGoalUpdatedAt]), so a fresh install's
/// unset 2200 default can never spuriously outrank a real budget synced
/// from elsewhere.
Future<void> _syncBudget(RemoteStore client) async {
final updatedAt = AppSettingsService.dailyKcalGoalUpdatedAt;
final localRecord = updatedAt == null
? null
: <String, dynamic>{
'v': 2,
'b': AppSettingsService.dailyKcalGoal,
't': updatedAt.toIso8601String(),
};
final mergedBudgetLog = await syncLog(
client: client,
deviceId: syncDeviceId,
pathPrefix: _devicesDir,
localLog: budgetToLog(
localRecord,
BudgetHistoryService.schedule.entries,
),
encode: encodeBudgetForPush,
decode: parseRemoteBudget,
filename: 'budget.json',
commitMessage: 'diet_guard_app sync',
);
// The history merges by field union, so it is applied unconditionally --
// independently of whether the scalar budget resolved to anything.
await BudgetHistoryService.instance.applyMerged(
logToHistory(mergedBudgetLog),
);
final merged = logToBudget(mergedBudgetLog);
final mergedKcal = merged?['b'];
if (merged == null || mergedKcal is! int) return;
await AppSettingsService.instance.applySyncedBudget(
mergedKcal,
updatedAt: DateTime.tryParse(merged['t'] as String? ?? ''),
);
}