mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-28 14:09:05 +01:00
Migrate sync to shared crdt_sync library (Python + Dart)
Replace the bespoke GitHub-Gist sync with the shared crdt-sync / crdt_sync_dart libraries so diet-guard uses the same CRDT transport as the other apps. - Python: delete _sync_github.py (+ its test); rewrite _sync.py, _cli_sync.py, _sync_merge.py against crdt-sync. Add the crdt-sync git dependency (pyproject + pylint deps) and S107 to the test ignore list. - Dart: rewrite app sync_service.dart / sync_merge.dart against crdt_sync_dart (new git dep + crypto); update log_meal and settings screens and their tests. Verification: pytest 347 passed at 100% coverage; flutter analyze clean; flutter test 306 passed. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017RRCdR4D8SaVrN2xraMQxM
This commit is contained in:
parent
06999274d7
commit
59d1c29dd2
@ -93,6 +93,7 @@ repos:
|
|||||||
- pytest
|
- pytest
|
||||||
- requests
|
- requests
|
||||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.1.0#subdirectory=gatelock
|
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.1.0#subdirectory=gatelock
|
||||||
|
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.1.0#subdirectory=crdt-sync
|
||||||
# Test suites intentionally use patterns (protected-access, magic-value
|
# Test suites intentionally use patterns (protected-access, magic-value
|
||||||
# comparisons) that don't belong in the source-code 10/10 gate.
|
# comparisons) that don't belong in the source-code 10/10 gate.
|
||||||
exclude: ^(\.venv/)|(^|/)(tests/|conftest\.py)
|
exclude: ^(\.venv/)|(^|/)(tests/|conftest\.py)
|
||||||
|
|||||||
@ -4,6 +4,7 @@ library;
|
|||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
import 'package:diet_guard_app/models/food_suggestion.dart';
|
import 'package:diet_guard_app/models/food_suggestion.dart';
|
||||||
import 'package:diet_guard_app/models/nutrition.dart';
|
import 'package:diet_guard_app/models/nutrition.dart';
|
||||||
import 'package:diet_guard_app/models/slot.dart';
|
import 'package:diet_guard_app/models/slot.dart';
|
||||||
@ -12,7 +13,6 @@ import 'package:diet_guard_app/screens/history_screen.dart';
|
|||||||
import 'package:diet_guard_app/screens/meal_builder_screen.dart';
|
import 'package:diet_guard_app/screens/meal_builder_screen.dart';
|
||||||
import 'package:diet_guard_app/screens/settings_screen.dart';
|
import 'package:diet_guard_app/screens/settings_screen.dart';
|
||||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||||
import 'package:diet_guard_app/services/github_client.dart';
|
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
import 'package:diet_guard_app/services/sync_service.dart';
|
import 'package:diet_guard_app/services/sync_service.dart';
|
||||||
import 'package:diet_guard_app/services/sync_settings.dart';
|
import 'package:diet_guard_app/services/sync_settings.dart';
|
||||||
|
|||||||
@ -8,6 +8,7 @@ library;
|
|||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart' as crdt_sync;
|
||||||
import 'package:diet_guard_app/screens/log_meal_screen.dart';
|
import 'package:diet_guard_app/screens/log_meal_screen.dart';
|
||||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||||
import 'package:diet_guard_app/services/github_client.dart';
|
import 'package:diet_guard_app/services/github_client.dart';
|
||||||
@ -141,7 +142,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
/// to work immediately, with clear confirmation either way.
|
/// to work immediately, with clear confirmation either way.
|
||||||
Future<void> _syncAfterConnect() async {
|
Future<void> _syncAfterConnect() async {
|
||||||
final settings = _currentSettings();
|
final settings = _currentSettings();
|
||||||
final client = GitHubClient(
|
final client = crdt_sync.GitHubClient(
|
||||||
owner: settings.owner,
|
owner: settings.owner,
|
||||||
repo: settings.repo,
|
repo: settings.repo,
|
||||||
token: settings.token,
|
token: settings.token,
|
||||||
@ -189,7 +190,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
setState(() => _busy = true);
|
setState(() => _busy = true);
|
||||||
final settings = _currentSettings();
|
final settings = _currentSettings();
|
||||||
await settings.save();
|
await settings.save();
|
||||||
final client = GitHubClient(
|
final client = crdt_sync.GitHubClient(
|
||||||
owner: settings.owner,
|
owner: settings.owner,
|
||||||
repo: settings.repo,
|
repo: settings.repo,
|
||||||
token: settings.token,
|
token: settings.token,
|
||||||
|
|||||||
@ -1,69 +1,179 @@
|
|||||||
/// Pure log-merge logic for diet_guard's cross-device sync.
|
/// Entry <-> crdt_sync.Record adapters for diet_guard_app's cross-device
|
||||||
|
/// sync.
|
||||||
///
|
///
|
||||||
/// No I/O here -- this module is unit-testable purely on in-memory [DayLog]
|
/// This app's own local storage format is unchanged -- only the
|
||||||
/// values. Mirrored test-for-test against the Python original
|
/// GitHub-synced wire format and the cross-device merge algorithm now go
|
||||||
/// (`diet_guard/_sync_merge.py`), so the merge algorithm canonically agrees
|
/// through `crdt_sync`'s `Record`/`Log`/`Hlc` primitives, the same ones the
|
||||||
/// on both sides of the sync.
|
/// PC (`diet_guard/_sync_merge.py`) and every other kuhy app that syncs
|
||||||
|
/// this way uses.
|
||||||
|
///
|
||||||
|
/// Each [FoodEntry] maps to one [Record] with a single opaque `body` field
|
||||||
|
/// holding [FoodEntry.toSyncJson] (already excludes `imagePath` and `hmac`
|
||||||
|
/// -- neither belongs in the synced Record: `imagePath` is phone-local and
|
||||||
|
/// reattached by `sync_service.dart` as a separate post-merge step; `hmac`
|
||||||
|
/// is never computed here, since the phone never holds the shared key).
|
||||||
|
/// Entries are immutable after creation (only `deleted` ever changes
|
||||||
|
/// post-write), so there is no benefit to crdt_sync's per-field LWW
|
||||||
|
/// granularity here -- the whole body shares one derived [Hlc].
|
||||||
|
///
|
||||||
|
/// Backward compatible with devices not yet migrated: [parseRemoteLog]
|
||||||
|
/// tries the new Record-based wire format first and falls back to the old
|
||||||
|
/// plain-DayLog format, converting old-format entries through the same
|
||||||
|
/// adapter used for the local log.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:crypto/crypto.dart';
|
||||||
import 'package:diet_guard_app/models/food_entry.dart';
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
|
||||||
/// A dedup key: `('id', <uuid>)` for any entry with one, else
|
const _syncDeviceId = 'phone';
|
||||||
/// `('legacy', (time, desc))` for a pre-id entry written before this field
|
|
||||||
/// existed -- two devices that both already had that same legacy entry would
|
|
||||||
/// otherwise end up with two copies of it after a merge.
|
|
||||||
typedef _MergeKey = (String, Object);
|
|
||||||
|
|
||||||
_MergeKey _entryKey(FoodEntry entry) {
|
/// Derives a deterministic [Hlc] for [entry] from its own `time` field.
|
||||||
final id = entry.id;
|
///
|
||||||
if (id != null && id.isNotEmpty) return ('id', id);
|
/// The same entry always yields the same Hlc regardless of when this runs
|
||||||
return ('legacy', (entry.time, entry.desc));
|
/// -- entries are immutable after creation, so there's no real "now" to
|
||||||
|
/// stamp, just the birth-time already recorded on the entry itself.
|
||||||
|
/// Malformed/missing `time` still yields a valid (if early-sorting) Hlc
|
||||||
|
/// rather than throwing -- this only affects tie-breaking between
|
||||||
|
/// otherwise-identical copies of the same id, never whether the entry
|
||||||
|
/// survives a merge.
|
||||||
|
Hlc entryHlc(FoodEntry entry) {
|
||||||
|
final wallTimeMs = DateTime.tryParse(entry.time)?.millisecondsSinceEpoch ?? 0;
|
||||||
|
return Hlc.newTick(_syncDeviceId, wallTimeMsOverride: wallTimeMs);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns true if [candidate] should replace [existing] for one key.
|
/// Deterministic id for a pre-`id` legacy entry, from `(time, desc)`.
|
||||||
///
|
///
|
||||||
/// A tombstone always wins over a non-tombstoned copy of the same entry --
|
/// Two devices holding the same legacy entry independently derive the same
|
||||||
/// deletion is sticky, so a stale pre-undo copy pulled from another device
|
/// id without communicating, so they merge as one record instead of two --
|
||||||
/// can never resurrect something the user explicitly removed. Otherwise,
|
/// the same guarantee the old `(time, desc)` dedup key gave, just expressed
|
||||||
/// keep whichever copy was seen first: two copies of the same id are
|
/// as a real id going forward.
|
||||||
/// expected to be identical in their macros/desc (the body is never mutated
|
String legacyEntryId(FoodEntry entry) {
|
||||||
/// after creation, only `deleted`/`hmac`), so which one survives does not
|
final key = '${entry.time}|${entry.desc}';
|
||||||
/// change the merged result's content.
|
final digest = sha256.convert(utf8.encode(key)).toString().substring(0, 32);
|
||||||
bool _tombstoneWins(FoodEntry candidate, FoodEntry existing) =>
|
return 'legacy-$digest';
|
||||||
candidate.deleted && !existing.deleted;
|
}
|
||||||
|
|
||||||
/// Returns the union of [local] and [remote], tombstones winning by id.
|
/// Converts one [FoodEntry] to a crdt_sync [Record].
|
||||||
///
|
Record entryToRecord(FoodEntry entry) {
|
||||||
/// Commutative and idempotent: `mergeLogs(a, b) == mergeLogs(b, a)` and
|
final id = (entry.id != null && entry.id!.isNotEmpty)
|
||||||
/// `mergeLogs(x, x) == x` (for an `x` with no duplicate keys), so pull-order
|
? entry.id!
|
||||||
/// between devices never matters and a repeated sync tick is a no-op. Each
|
: legacyEntryId(entry);
|
||||||
/// entry is re-bucketed under its own `time`'s date rather than the date key
|
final hlc = entryHlc(entry);
|
||||||
/// it arrived under, so a merge can't silently leave an entry filed under
|
final body = entry.toSyncJson()
|
||||||
/// the wrong day.
|
..remove('id')
|
||||||
DayLog mergeLogs(DayLog local, DayLog remote) {
|
..remove('deleted');
|
||||||
final byKey = <_MergeKey, FoodEntry>{};
|
return Record(
|
||||||
for (final dayLog in [local, remote]) {
|
id: id,
|
||||||
for (final entries in dayLog.values) {
|
fields: {'body': (body, hlc)},
|
||||||
for (final entry in entries) {
|
deleted: entry.deleted,
|
||||||
final key = _entryKey(entry);
|
deletedHlc: entry.deleted ? hlc : null,
|
||||||
final existing = byKey[key];
|
);
|
||||||
if (existing == null || _tombstoneWins(entry, existing)) {
|
}
|
||||||
byKey[key] = entry;
|
|
||||||
}
|
/// Converts one crdt_sync [Record] back to a [FoodEntry].
|
||||||
}
|
FoodEntry recordToEntry(Record record) {
|
||||||
|
final bodyValue = record.fields['body']?.$1;
|
||||||
|
final body = bodyValue is Map
|
||||||
|
? bodyValue.cast<String, dynamic>()
|
||||||
|
: <String, dynamic>{};
|
||||||
|
return FoodEntry.fromJson({
|
||||||
|
...body,
|
||||||
|
'id': record.id,
|
||||||
|
'deleted': record.deleted,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Converts a full local/remote [DayLog] into a crdt_sync [Log].
|
||||||
|
Log dayLogToLog(DayLog daylog) {
|
||||||
|
final log = <String, Record>{};
|
||||||
|
for (final entries in daylog.values) {
|
||||||
|
for (final entry in entries) {
|
||||||
|
final record = entryToRecord(entry);
|
||||||
|
log[record.id] = record;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return log;
|
||||||
|
}
|
||||||
|
|
||||||
final merged = <String, List<FoodEntry>>{};
|
/// Converts a merged crdt_sync [Log] back into [DayLog] shape.
|
||||||
for (final entry in byKey.values) {
|
///
|
||||||
|
/// Each entry is re-bucketed under its own `time`'s date rather than
|
||||||
|
/// whatever date key it might have arrived under, and each day's entries
|
||||||
|
/// are sorted oldest-first -- matching the existing on-disk convention.
|
||||||
|
DayLog logToDayLog(Log log) {
|
||||||
|
final daylog = <String, List<FoodEntry>>{};
|
||||||
|
for (final record in log.values) {
|
||||||
|
final entry = recordToEntry(record);
|
||||||
final dateKey = entry.time.length >= 10
|
final dateKey = entry.time.length >= 10
|
||||||
? entry.time.substring(0, 10)
|
? entry.time.substring(0, 10)
|
||||||
: entry.time;
|
: entry.time;
|
||||||
merged.putIfAbsent(dateKey, () => []).add(entry);
|
daylog.putIfAbsent(dateKey, () => []).add(entry);
|
||||||
}
|
}
|
||||||
for (final entries in merged.values) {
|
for (final entries in daylog.values) {
|
||||||
entries.sort((a, b) => a.time.compareTo(b.time));
|
entries.sort((a, b) => a.time.compareTo(b.time));
|
||||||
}
|
}
|
||||||
return merged;
|
return daylog;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns true if [raw] is shaped like a crdt_sync Record-keyed Log.
|
||||||
|
///
|
||||||
|
/// An empty object is ambiguous but harmless either way (no entries to
|
||||||
|
/// convert), so it's treated as new format to skip the old-format
|
||||||
|
/// conversion pass for nothing.
|
||||||
|
bool _looksLikeNewFormat(Map<String, dynamic> raw) => raw.values.every(
|
||||||
|
(value) =>
|
||||||
|
value is Map<String, dynamic> &&
|
||||||
|
value.containsKey('fields') &&
|
||||||
|
value.containsKey('id'),
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Parses one device's pushed log text into a crdt_sync [Log].
|
||||||
|
///
|
||||||
|
/// Tries the new Record-based wire format first; falls back to the old
|
||||||
|
/// plain-DayLog format (today's on-the-wire shape) for devices not yet
|
||||||
|
/// migrated onto crdt_sync, converting their entries through the same
|
||||||
|
/// adapter the local log uses. Throwing [FormatException] or [TypeError] is
|
||||||
|
/// treated as unparsable by the caller (`sync_service.dart`'s `syncLog`
|
||||||
|
/// `decode` callback), mirroring `_sync._pull_remote_logs`'s tolerance for a
|
||||||
|
/// corrupt/truncated push.
|
||||||
|
Log parseRemoteLog(String text) {
|
||||||
|
final raw = jsonDecode(text);
|
||||||
|
if (raw is! Map) {
|
||||||
|
throw const FormatException(
|
||||||
|
'top-level sync payload is not a JSON object',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final rawMap = raw.cast<String, dynamic>();
|
||||||
|
if (_looksLikeNewFormat(rawMap)) {
|
||||||
|
return rawMap.map(
|
||||||
|
(id, data) => MapEntry(id, Record.fromJson(data as Map<String, dynamic>)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
final daylog = <String, List<FoodEntry>>{};
|
||||||
|
for (final mapEntry in rawMap.entries) {
|
||||||
|
final entries = mapEntry.value;
|
||||||
|
if (entries is! List) {
|
||||||
|
throw FormatException(
|
||||||
|
'day ${mapEntry.key} is not a JSON array',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
daylog[mapEntry.key] = entries
|
||||||
|
.whereType<Map<String, dynamic>>()
|
||||||
|
.map((m) => FoodEntry.fromJson(m.cast<String, dynamic>()))
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
return dayLogToLog(daylog);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Serializes a merged [Log] for push, in the new Record-based wire format.
|
||||||
|
String encodeLogForPush(Log log) {
|
||||||
|
final encoded = <String, dynamic>{
|
||||||
|
for (final entry in log.entries) entry.key: entry.value.toJson(),
|
||||||
|
};
|
||||||
|
return jsonEncode(encoded);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,21 +1,19 @@
|
|||||||
/// Cross-device log sync orchestration for the diet_guard companion app.
|
/// Cross-device log sync orchestration for the diet_guard companion app.
|
||||||
///
|
///
|
||||||
/// Pulls every other device's pushed log from GitHub-backed dumb storage
|
/// Pulls every other device's pushed log from GitHub-backed dumb storage via
|
||||||
/// ([GitHubClient]), merges with the local log ([mergeLogs]), rebuilds the
|
/// crdt_sync's shared transport ([GitHubClient]/[syncLog]), merges with the
|
||||||
/// food bank, and pushes this device's own merged log back up. A **new**
|
/// local log via crdt_sync's shared CRDT scheme (`sync_merge.dart` adapts
|
||||||
/// implementation, not a port of `~/todo`'s CRDT-based sync (this app has no
|
/// [FoodEntry]s to/from [Record]), rebuilds the food bank, and pushes this
|
||||||
/// CRDT layer) -- a Dart twin of the same pull-merge-rebuild-push sequence
|
/// device's own merged log back up in the new Record-based wire format. One
|
||||||
/// as `diet_guard/_sync.py`, plus one phone-specific step: a pulled copy of
|
/// phone-specific step, with no PC-side equivalent: a pulled copy of an
|
||||||
/// an entry never carries `imagePath` (stripped before push, meaningless on
|
/// entry never carries `imagePath` (stripped before push, meaningless on
|
||||||
/// another device), so it must not null out a local photo attachment for
|
/// another device), so it must not null out a local photo attachment for
|
||||||
/// the same `id` (plan decision 10).
|
/// the same `id` (plan decision 10).
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'dart:convert';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/food_entry.dart';
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||||
import 'package:diet_guard_app/services/github_client.dart';
|
|
||||||
import 'package:diet_guard_app/services/log_storage_service.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_merge.dart';
|
||||||
|
|
||||||
@ -27,53 +25,35 @@ const _devicesDir = 'diet-guard-sync/devices';
|
|||||||
/// design.
|
/// design.
|
||||||
const phoneDeviceId = 'phone';
|
const phoneDeviceId = 'phone';
|
||||||
|
|
||||||
String _deviceLogPath(String deviceId) =>
|
|
||||||
'$_devicesDir/$deviceId/food_log.json';
|
|
||||||
|
|
||||||
/// Runs one full sync tick: pull, merge, preserve photos, persist, push.
|
/// Runs one full sync tick: pull, merge, preserve photos, persist, push.
|
||||||
///
|
///
|
||||||
/// Returns the merged log as it now sits on disk locally. Propagates any
|
/// Returns the merged log as it now sits on disk locally. Propagates any
|
||||||
/// [GitHubApiException] from the client for the caller (auto-sync / the
|
/// [GitHubSyncError] from the client for the caller (auto-sync / the manual
|
||||||
/// manual "Sync now" action) to decide how to report.
|
/// "Sync now" action) to decide how to report.
|
||||||
Future<DayLog> runSync(GitHubClient client) async {
|
Future<DayLog> runSync(GitHubClient client) async {
|
||||||
final logService = LogStorageService.instance;
|
final logService = LogStorageService.instance;
|
||||||
final local = await logService.readLog();
|
final local = await logService.readLog();
|
||||||
final localImagePaths = _imagePathsById(local);
|
final localImagePaths = _imagePathsById(local);
|
||||||
|
|
||||||
var merged = local;
|
final mergedLog = await syncLog(
|
||||||
for (final deviceId in await client.listEntryNames(_devicesDir)) {
|
client: client,
|
||||||
if (deviceId == phoneDeviceId) continue;
|
deviceId: phoneDeviceId,
|
||||||
final text = await client.getFileText(_deviceLogPath(deviceId));
|
pathPrefix: _devicesDir,
|
||||||
if (text == null) continue;
|
localLog: dayLogToLog(local),
|
||||||
final remoteLog = _decodeRemoteLog(text);
|
encode: encodeLogForPush,
|
||||||
if (remoteLog == null) continue;
|
decode: parseRemoteLog,
|
||||||
merged = mergeLogs(merged, remoteLog);
|
filename: 'food_log.json',
|
||||||
}
|
commitMessage: 'diet_guard_app sync',
|
||||||
|
);
|
||||||
|
|
||||||
|
var merged = logToDayLog(mergedLog);
|
||||||
merged = _preserveLocalImagePaths(merged, localImagePaths);
|
merged = _preserveLocalImagePaths(merged, localImagePaths);
|
||||||
|
|
||||||
await logService.writeLog(merged);
|
await logService.writeLog(merged);
|
||||||
await FoodBankService.instance.rebuildAndPersist(merged);
|
await FoodBankService.instance.rebuildAndPersist(merged);
|
||||||
|
|
||||||
await client.putFileText(
|
|
||||||
_deviceLogPath(phoneDeviceId),
|
|
||||||
_encodeForPush(merged),
|
|
||||||
sha: await _ownFileSha(client),
|
|
||||||
message: 'diet_guard_app sync',
|
|
||||||
);
|
|
||||||
return merged;
|
return merged;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns this device's current `food_log.json` sha if it has pushed
|
|
||||||
/// before, so [GitHubClient.putFileText] updates rather than creates.
|
|
||||||
Future<String?> _ownFileSha(GitHubClient client) async {
|
|
||||||
final files = await client.listDirectory('$_devicesDir/$phoneDeviceId');
|
|
||||||
for (final file in files) {
|
|
||||||
if (file.name == 'food_log.json') return file.sha;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
Map<String, String> _imagePathsById(DayLog log) {
|
Map<String, String> _imagePathsById(DayLog log) {
|
||||||
final result = <String, String>{};
|
final result = <String, String>{};
|
||||||
for (final entries in log.values) {
|
for (final entries in log.values) {
|
||||||
@ -109,38 +89,3 @@ FoodEntry _withPreservedImagePath(
|
|||||||
if (preserved == null) return entry;
|
if (preserved == null) return entry;
|
||||||
return entry.copyWithImagePath(preserved);
|
return entry.copyWithImagePath(preserved);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses a device's pushed log, mirroring `_sync._pull_remote_logs`'s
|
|
||||||
/// tolerance for a corrupt/truncated push: an unparsable file is skipped
|
|
||||||
/// (returns null) rather than aborting the whole sync tick.
|
|
||||||
DayLog? _decodeRemoteLog(String text) {
|
|
||||||
Object? decoded;
|
|
||||||
try {
|
|
||||||
decoded = jsonDecode(text);
|
|
||||||
} on FormatException {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (decoded is! Map) return null;
|
|
||||||
final result = <String, List<FoodEntry>>{};
|
|
||||||
for (final mapEntry in decoded.entries) {
|
|
||||||
final key = mapEntry.key;
|
|
||||||
final value = mapEntry.value;
|
|
||||||
if (key is! String || value is! List) continue;
|
|
||||||
result[key] = value
|
|
||||||
.whereType<Map<dynamic, dynamic>>()
|
|
||||||
.map((m) => FoodEntry.fromJson(m.cast<String, dynamic>()))
|
|
||||||
.toList();
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Serializes the full merged log for push via [FoodEntry.toSyncJson],
|
|
||||||
/// which excludes [FoodEntry.imagePath] (phone-local only) and `hmac` (the
|
|
||||||
/// PC re-signs every persisted entry on its own next sync tick regardless).
|
|
||||||
String _encodeForPush(DayLog log) {
|
|
||||||
final encoded = <String, Object?>{
|
|
||||||
for (final mapEntry in log.entries)
|
|
||||||
mapEntry.key: mapEntry.value.map((e) => e.toSyncJson()).toList(),
|
|
||||||
};
|
|
||||||
return jsonEncode(encoded);
|
|
||||||
}
|
|
||||||
|
|||||||
@ -57,6 +57,15 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.19.1"
|
version: "1.19.1"
|
||||||
|
crdt_sync:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
path: crdt_sync_dart
|
||||||
|
ref: "crdt_sync_dart-v0.1.0"
|
||||||
|
resolved-ref: "6b14e6d36d137d90851f00d1e282a2069c13d3a6"
|
||||||
|
url: "https://github.com/kuhyx/utils"
|
||||||
|
source: git
|
||||||
|
version: "0.1.0"
|
||||||
cross_file:
|
cross_file:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -66,7 +75,7 @@ packages:
|
|||||||
source: hosted
|
source: hosted
|
||||||
version: "0.3.5+2"
|
version: "0.3.5+2"
|
||||||
crypto:
|
crypto:
|
||||||
dependency: transitive
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
name: crypto
|
name: crypto
|
||||||
sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
|
sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
|
||||||
|
|||||||
@ -8,6 +8,12 @@ environment:
|
|||||||
sdk: ^3.12.2
|
sdk: ^3.12.2
|
||||||
|
|
||||||
dependencies:
|
dependencies:
|
||||||
|
crdt_sync:
|
||||||
|
git:
|
||||||
|
url: https://github.com/kuhyx/utils
|
||||||
|
ref: crdt_sync_dart-v0.1.0
|
||||||
|
path: crdt_sync_dart
|
||||||
|
crypto: ^3.0.6
|
||||||
flutter:
|
flutter:
|
||||||
sdk: flutter
|
sdk: flutter
|
||||||
flutter_local_notifications: ^22.0.1
|
flutter_local_notifications: ^22.0.1
|
||||||
|
|||||||
@ -65,6 +65,13 @@ void main() {
|
|||||||
var puts = 0;
|
var puts = 0;
|
||||||
final mock = MockClient((req) async {
|
final mock = MockClient((req) async {
|
||||||
if (req.method == 'PUT') puts++;
|
if (req.method == 'PUT') puts++;
|
||||||
|
// A bare `/repos/<owner>/<repo>` GET is crdt_sync's GitHubClient
|
||||||
|
// probing whether the repo itself exists (vs. a content path just
|
||||||
|
// being unused) -- must succeed so an empty/unconfigured repo isn't
|
||||||
|
// mistaken for a missing one.
|
||||||
|
if (req.method == 'GET' && req.url.pathSegments.length == 3) {
|
||||||
|
return http.Response('{}', 200);
|
||||||
|
}
|
||||||
return http.Response('', 404);
|
return http.Response('', 404);
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -87,6 +94,13 @@ void main() {
|
|||||||
var puts = 0;
|
var puts = 0;
|
||||||
final mock = MockClient((req) async {
|
final mock = MockClient((req) async {
|
||||||
if (req.method == 'PUT') puts++;
|
if (req.method == 'PUT') puts++;
|
||||||
|
// A bare `/repos/<owner>/<repo>` GET is crdt_sync's GitHubClient
|
||||||
|
// probing whether the repo itself exists (vs. a content path just
|
||||||
|
// being unused) -- must succeed so an empty/unconfigured repo isn't
|
||||||
|
// mistaken for a missing one.
|
||||||
|
if (req.method == 'GET' && req.url.pathSegments.length == 3) {
|
||||||
|
return http.Response('{}', 200);
|
||||||
|
}
|
||||||
return http.Response('', 404);
|
return http.Response('', 404);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -150,6 +150,13 @@ void main() {
|
|||||||
) async {
|
) async {
|
||||||
final mock = MockClient((req) async {
|
final mock = MockClient((req) async {
|
||||||
if (req.method == 'PUT') return http.Response('{}', 200);
|
if (req.method == 'PUT') return http.Response('{}', 200);
|
||||||
|
// A bare `/repos/<owner>/<repo>` GET is crdt_sync's GitHubClient
|
||||||
|
// probing whether the repo itself exists (vs. a content path just
|
||||||
|
// being unused) -- must succeed so an empty repo isn't mistaken for
|
||||||
|
// a missing one.
|
||||||
|
if (req.method == 'GET' && req.url.pathSegments.length == 3) {
|
||||||
|
return http.Response('{}', 200);
|
||||||
|
}
|
||||||
return http.Response('', 404);
|
return http.Response('', 404);
|
||||||
});
|
});
|
||||||
await tester.runAsync(() async {
|
await tester.runAsync(() async {
|
||||||
@ -327,6 +334,13 @@ void main() {
|
|||||||
return http.Response(jsonEncode({'access_token': 'gho_test'}), 200);
|
return http.Response(jsonEncode({'access_token': 'gho_test'}), 200);
|
||||||
}
|
}
|
||||||
if (req.method == 'PUT') return http.Response('{}', 200);
|
if (req.method == 'PUT') return http.Response('{}', 200);
|
||||||
|
// A bare `/repos/<owner>/<repo>` GET is crdt_sync's GitHubClient
|
||||||
|
// probing whether the repo itself exists (vs. a content path just
|
||||||
|
// being unused) -- must succeed so an empty repo isn't mistaken for
|
||||||
|
// a missing one.
|
||||||
|
if (req.method == 'GET' && req.url.pathSegments.length == 3) {
|
||||||
|
return http.Response('{}', 200);
|
||||||
|
}
|
||||||
return http.Response('', 404); // sync's pull-side list/read calls
|
return http.Response('', 404); // sync's pull-side list/read calls
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -1,8 +1,15 @@
|
|||||||
// Table-driven `mergeLogs()` tests mirroring `test_sync_merge.py` exactly
|
// Table-driven mergeLogs() tests. `union by id` through `algebraic
|
||||||
// (same cases, same expected outcomes), so both implementations are provably
|
// properties` are the exact same assertions the pre-migration
|
||||||
// testing the same algorithm.
|
// `sync_merge.mergeLogs` had -- routed through `dayLogToLog ->
|
||||||
|
// crdt_sync.mergeLogs -> logToDayLog` instead, to prove the migration
|
||||||
|
// preserves the app's merge semantics exactly, mirroring
|
||||||
|
// `test_sync_merge.py`'s equivalent Python-side proof.
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
import 'package:diet_guard_app/models/food_entry.dart';
|
import 'package:diet_guard_app/models/food_entry.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_merge.dart';
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
|
||||||
@ -24,6 +31,9 @@ FoodEntry _entry({
|
|||||||
deleted: deleted,
|
deleted: deleted,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
DayLog _mergeDaylogs(DayLog a, DayLog b) =>
|
||||||
|
logToDayLog(mergeLogs(dayLogToLog(a), dayLogToLog(b)));
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
group('union by id', () {
|
group('union by id', () {
|
||||||
test('disjoint logs union into one', () {
|
test('disjoint logs union into one', () {
|
||||||
@ -33,13 +43,13 @@ void main() {
|
|||||||
final b = {
|
final b = {
|
||||||
'2026-06-22': [_entry(id: 'b', time: '2026-06-22T12:00:00')],
|
'2026-06-22': [_entry(id: 'b', time: '2026-06-22T12:00:00')],
|
||||||
};
|
};
|
||||||
final merged = mergeLogs(a, b);
|
final merged = _mergeDaylogs(a, b);
|
||||||
expect(merged['2026-06-22']!.map((e) => e.id).toSet(), {'a', 'b'});
|
expect(merged['2026-06-22']!.map((e) => e.id).toSet(), {'a', 'b'});
|
||||||
});
|
});
|
||||||
|
|
||||||
test('same id in both logs is not duplicated', () {
|
test('same id in both logs is not duplicated', () {
|
||||||
final shared = _entry(id: 'shared');
|
final shared = _entry(id: 'shared');
|
||||||
final merged = mergeLogs(
|
final merged = _mergeDaylogs(
|
||||||
{
|
{
|
||||||
'2026-06-22': [shared],
|
'2026-06-22': [shared],
|
||||||
},
|
},
|
||||||
@ -61,7 +71,7 @@ void main() {
|
|||||||
time: '2026-06-20T08:00:00',
|
time: '2026-06-20T08:00:00',
|
||||||
desc: 'toast',
|
desc: 'toast',
|
||||||
);
|
);
|
||||||
final merged = mergeLogs(
|
final merged = _mergeDaylogs(
|
||||||
{
|
{
|
||||||
'2026-06-20': [legacyA],
|
'2026-06-20': [legacyA],
|
||||||
},
|
},
|
||||||
@ -79,7 +89,7 @@ void main() {
|
|||||||
desc: 'toast',
|
desc: 'toast',
|
||||||
);
|
);
|
||||||
final withId = _entry(id: 'x', time: '2026-06-20T09:00:00', desc: 'eggs');
|
final withId = _entry(id: 'x', time: '2026-06-20T09:00:00', desc: 'eggs');
|
||||||
final merged = mergeLogs(
|
final merged = _mergeDaylogs(
|
||||||
{
|
{
|
||||||
'2026-06-20': [legacy],
|
'2026-06-20': [legacy],
|
||||||
},
|
},
|
||||||
@ -96,7 +106,7 @@ void main() {
|
|||||||
final normal = _entry(id: 'x');
|
final normal = _entry(id: 'x');
|
||||||
final tombstoned = _entry(id: 'x', deleted: true);
|
final tombstoned = _entry(id: 'x', deleted: true);
|
||||||
|
|
||||||
final forward = mergeLogs(
|
final forward = _mergeDaylogs(
|
||||||
{
|
{
|
||||||
'2026-06-22': [normal],
|
'2026-06-22': [normal],
|
||||||
},
|
},
|
||||||
@ -104,7 +114,7 @@ void main() {
|
|||||||
'2026-06-22': [tombstoned],
|
'2026-06-22': [tombstoned],
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
final backward = mergeLogs(
|
final backward = _mergeDaylogs(
|
||||||
{
|
{
|
||||||
'2026-06-22': [tombstoned],
|
'2026-06-22': [tombstoned],
|
||||||
},
|
},
|
||||||
@ -119,7 +129,7 @@ void main() {
|
|||||||
|
|
||||||
test('two tombstoned copies stay tombstoned', () {
|
test('two tombstoned copies stay tombstoned', () {
|
||||||
final tombstoned = _entry(id: 'x', deleted: true);
|
final tombstoned = _entry(id: 'x', deleted: true);
|
||||||
final merged = mergeLogs(
|
final merged = _mergeDaylogs(
|
||||||
{
|
{
|
||||||
'2026-06-22': [tombstoned],
|
'2026-06-22': [tombstoned],
|
||||||
},
|
},
|
||||||
@ -136,7 +146,7 @@ void main() {
|
|||||||
"entry is filed under its own time's date, not the arrival bucket",
|
"entry is filed under its own time's date, not the arrival bucket",
|
||||||
() {
|
() {
|
||||||
final misfiled = _entry(id: 'x', time: '2026-06-21T23:00:00');
|
final misfiled = _entry(id: 'x', time: '2026-06-21T23:00:00');
|
||||||
final merged = mergeLogs({
|
final merged = _mergeDaylogs({
|
||||||
'2026-06-22': [misfiled],
|
'2026-06-22': [misfiled],
|
||||||
}, {});
|
}, {});
|
||||||
expect(merged.keys, ['2026-06-21']);
|
expect(merged.keys, ['2026-06-21']);
|
||||||
@ -148,10 +158,8 @@ void main() {
|
|||||||
'an entry with a time shorter than a date key buckets under the '
|
'an entry with a time shorter than a date key buckets under the '
|
||||||
'raw time instead of crashing',
|
'raw time instead of crashing',
|
||||||
() {
|
() {
|
||||||
// Dart's substring throws past the string length, unlike Python's
|
|
||||||
// forgiving slice -- this only matters for malformed/legacy data.
|
|
||||||
final short = _entry(id: 'x', time: '2026');
|
final short = _entry(id: 'x', time: '2026');
|
||||||
final merged = mergeLogs({
|
final merged = _mergeDaylogs({
|
||||||
'2026-06-22': [short],
|
'2026-06-22': [short],
|
||||||
}, {});
|
}, {});
|
||||||
expect(merged.keys, ['2026']);
|
expect(merged.keys, ['2026']);
|
||||||
@ -161,7 +169,7 @@ void main() {
|
|||||||
test("a day's entries are sorted oldest-first", () {
|
test("a day's entries are sorted oldest-first", () {
|
||||||
final late = _entry(id: 'late', time: '2026-06-22T20:00:00');
|
final late = _entry(id: 'late', time: '2026-06-22T20:00:00');
|
||||||
final early = _entry(id: 'early', time: '2026-06-22T08:00:00');
|
final early = _entry(id: 'early', time: '2026-06-22T08:00:00');
|
||||||
final merged = mergeLogs(
|
final merged = _mergeDaylogs(
|
||||||
{
|
{
|
||||||
'2026-06-22': [late],
|
'2026-06-22': [late],
|
||||||
},
|
},
|
||||||
@ -184,8 +192,8 @@ void main() {
|
|||||||
final b = {
|
final b = {
|
||||||
'2026-06-22': [_entry(id: 'b', time: '2026-06-22T09:00:00')],
|
'2026-06-22': [_entry(id: 'b', time: '2026-06-22T09:00:00')],
|
||||||
};
|
};
|
||||||
final ab = mergeLogs(a, b);
|
final ab = _mergeDaylogs(a, b);
|
||||||
final ba = mergeLogs(b, a);
|
final ba = _mergeDaylogs(b, a);
|
||||||
expect(
|
expect(
|
||||||
ab['2026-06-22']!.map((e) => e.id).toList(),
|
ab['2026-06-22']!.map((e) => e.id).toList(),
|
||||||
ba['2026-06-22']!.map((e) => e.id).toList(),
|
ba['2026-06-22']!.map((e) => e.id).toList(),
|
||||||
@ -196,7 +204,7 @@ void main() {
|
|||||||
final canonical = {
|
final canonical = {
|
||||||
'2026-06-22': [_entry(id: 'a')],
|
'2026-06-22': [_entry(id: 'a')],
|
||||||
};
|
};
|
||||||
final merged = mergeLogs(canonical, canonical);
|
final merged = _mergeDaylogs(canonical, canonical);
|
||||||
expect(merged['2026-06-22']!.map((e) => e.id).toList(), ['a']);
|
expect(merged['2026-06-22']!.map((e) => e.id).toList(), ['a']);
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -204,12 +212,103 @@ void main() {
|
|||||||
final log = {
|
final log = {
|
||||||
'2026-06-22': [_entry(id: 'a')],
|
'2026-06-22': [_entry(id: 'a')],
|
||||||
};
|
};
|
||||||
expect(mergeLogs(log, {}).keys, log.keys);
|
expect(_mergeDaylogs(log, {}).keys, log.keys);
|
||||||
expect(mergeLogs({}, log).keys, log.keys);
|
expect(_mergeDaylogs({}, log).keys, log.keys);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('merging two empty logs is empty', () {
|
test('merging two empty logs is empty', () {
|
||||||
expect(mergeLogs({}, {}), isEmpty);
|
expect(_mergeDaylogs({}, {}), isEmpty);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('entryHlc', () {
|
||||||
|
test('same entry always yields the same Hlc', () {
|
||||||
|
expect(entryHlc(_entry()), entryHlc(_entry()));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('malformed time still yields a valid Hlc', () {
|
||||||
|
expect(entryHlc(_entry(time: 'not-a-timestamp')).wallTimeMs, 0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('legacyEntryId', () {
|
||||||
|
test('same time and desc yields the same id', () {
|
||||||
|
final a = _entry(time: '2026-06-20T08:00:00', desc: 'toast');
|
||||||
|
final b = _entry(time: '2026-06-20T08:00:00', desc: 'toast');
|
||||||
|
expect(legacyEntryId(a), legacyEntryId(b));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('different desc yields a different id', () {
|
||||||
|
final a = _entry(time: '2026-06-20T08:00:00', desc: 'toast');
|
||||||
|
final b = _entry(time: '2026-06-20T08:00:00', desc: 'eggs');
|
||||||
|
expect(legacyEntryId(a), isNot(legacyEntryId(b)));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('entry <-> Record round trip', () {
|
||||||
|
test('round trip preserves all fields', () {
|
||||||
|
final entry = _entry(id: 'x');
|
||||||
|
final roundTripped = recordToEntry(entryToRecord(entry));
|
||||||
|
expect(roundTripped.toSyncJson(), entry.toSyncJson());
|
||||||
|
});
|
||||||
|
|
||||||
|
test('round trip of a deleted entry preserves the tombstone', () {
|
||||||
|
final entry = _entry(id: 'x', deleted: true);
|
||||||
|
expect(recordToEntry(entryToRecord(entry)).deleted, isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('legacy entry gets a derived id on round trip', () {
|
||||||
|
final entry = _entry(
|
||||||
|
id: null,
|
||||||
|
time: '2026-06-20T08:00:00',
|
||||||
|
desc: 'toast',
|
||||||
|
);
|
||||||
|
final roundTripped = recordToEntry(entryToRecord(entry));
|
||||||
|
expect(roundTripped.id, legacyEntryId(entry));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a Record with no body field falls back to an empty body', () {
|
||||||
|
const record = Record(id: 'x', fields: {});
|
||||||
|
final entry = recordToEntry(record);
|
||||||
|
expect(entry.id, 'x');
|
||||||
|
expect(entry.desc, isEmpty);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('parseRemoteLog', () {
|
||||||
|
test('parses new-format wire content', () {
|
||||||
|
final entry = _entry(id: 'x');
|
||||||
|
final pushed = encodeLogForPush({'x': entryToRecord(entry)});
|
||||||
|
final log = parseRemoteLog(pushed);
|
||||||
|
expect(log['x']!.id, 'x');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('parses old DayLog format for backward compatibility', () {
|
||||||
|
final entry = _entry(id: 'x');
|
||||||
|
final oldFormat = jsonEncode({
|
||||||
|
'2026-06-22': [entry.toSyncJson()],
|
||||||
|
});
|
||||||
|
final log = parseRemoteLog(oldFormat);
|
||||||
|
expect(log['x']!.id, 'x');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('empty object parses as empty log', () {
|
||||||
|
expect(parseRemoteLog('{}'), isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('non-object top level throws FormatException', () {
|
||||||
|
expect(() => parseRemoteLog('[1, 2, 3]'), throwsFormatException);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('old-format day not a list throws FormatException', () {
|
||||||
|
expect(
|
||||||
|
() => parseRemoteLog('{"2026-06-22": "not-a-list"}'),
|
||||||
|
throwsFormatException,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('invalid JSON throws FormatException', () {
|
||||||
|
expect(() => parseRemoteLog('not json{{{'), throwsFormatException);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@ -6,10 +6,10 @@
|
|||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
import 'package:diet_guard_app/models/food_entry.dart';
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
import 'package:diet_guard_app/models/nutrition.dart';
|
import 'package:diet_guard_app/models/nutrition.dart';
|
||||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||||
import 'package:diet_guard_app/services/github_client.dart';
|
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
import 'package:diet_guard_app/services/sync_service.dart';
|
import 'package:diet_guard_app/services/sync_service.dart';
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
@ -26,8 +26,9 @@ const _manual = Nutrition(
|
|||||||
);
|
);
|
||||||
|
|
||||||
/// A tiny in-memory stand-in for the GitHub Contents API, scoped to exactly
|
/// A tiny in-memory stand-in for the GitHub Contents API, scoped to exactly
|
||||||
/// the calls [runSync] makes: list `devices`, list a single device's own
|
/// the calls [runSync] makes via crdt_sync's [GitHubClient]: list `devices`,
|
||||||
/// directory (for its file's sha), get a device's file text, and put this
|
/// get a device's file text (which crdt_sync also uses internally to
|
||||||
|
/// resolve this device's own existing sha before a push), and put this
|
||||||
/// device's file text.
|
/// device's file text.
|
||||||
class _FakeGitHub {
|
class _FakeGitHub {
|
||||||
_FakeGitHub({this.deviceDirs = const [], Map<String, String>? files})
|
_FakeGitHub({this.deviceDirs = const [], Map<String, String>? files})
|
||||||
@ -36,8 +37,8 @@ class _FakeGitHub {
|
|||||||
final List<String> deviceDirs;
|
final List<String> deviceDirs;
|
||||||
final Map<String, String> files;
|
final Map<String, String> files;
|
||||||
|
|
||||||
/// Every `devices/<id>/food_log.json` path this fake actually served a
|
/// Every `diet-guard-sync/devices/<id>/food_log.json` path this fake
|
||||||
/// file-content GET for (i.e. a real `getFileText` pull, not a listing).
|
/// actually served a file-content GET for.
|
||||||
final List<String> fileGets = [];
|
final List<String> fileGets = [];
|
||||||
|
|
||||||
/// Every PUT this fake received, decoded.
|
/// Every PUT this fake received, decoded.
|
||||||
@ -51,33 +52,27 @@ class _FakeGitHub {
|
|||||||
);
|
);
|
||||||
|
|
||||||
Future<http.Response> _handle(http.Request req) async {
|
Future<http.Response> _handle(http.Request req) async {
|
||||||
|
if (req.url.path == '/repos/o/r') {
|
||||||
|
// Repo-existence probe: crdt_sync's GitHubClient calls this to
|
||||||
|
// disambiguate "path unused yet" (still 404, but a real repo) from
|
||||||
|
// "repo missing/inaccessible" whenever a content-path GET 404s.
|
||||||
|
return http.Response('{}', 200);
|
||||||
|
}
|
||||||
final path = req.url.path.replaceFirst('/repos/o/r/contents/', '');
|
final path = req.url.path.replaceFirst('/repos/o/r/contents/', '');
|
||||||
if (req.method == 'PUT') {
|
if (req.method == 'PUT') {
|
||||||
puts.add(jsonDecode(req.body) as Map<String, dynamic>);
|
puts.add(jsonDecode(req.body) as Map<String, dynamic>);
|
||||||
return http.Response('{}', 200);
|
return http.Response('{}', 200);
|
||||||
}
|
}
|
||||||
if (path == 'devices') {
|
if (path == 'diet-guard-sync/devices') {
|
||||||
return http.Response(
|
return http.Response(
|
||||||
jsonEncode([
|
jsonEncode([
|
||||||
for (final d in deviceDirs)
|
for (final d in deviceDirs)
|
||||||
{'type': 'dir', 'name': d, 'path': 'devices/$d', 'sha': 'd-$d'},
|
{
|
||||||
]),
|
'type': 'dir',
|
||||||
200,
|
'name': d,
|
||||||
);
|
'path': 'diet-guard-sync/devices/$d',
|
||||||
}
|
'sha': 'd-$d',
|
||||||
final segments = path.split('/');
|
},
|
||||||
if (segments.length == 2 && segments[0] == 'devices') {
|
|
||||||
final deviceId = segments[1];
|
|
||||||
final filePath = 'devices/$deviceId/food_log.json';
|
|
||||||
if (!files.containsKey(filePath)) return http.Response('', 404);
|
|
||||||
return http.Response(
|
|
||||||
jsonEncode([
|
|
||||||
{
|
|
||||||
'type': 'file',
|
|
||||||
'name': 'food_log.json',
|
|
||||||
'path': filePath,
|
|
||||||
'sha': 'f-$deviceId',
|
|
||||||
},
|
|
||||||
]),
|
]),
|
||||||
200,
|
200,
|
||||||
);
|
);
|
||||||
@ -85,7 +80,20 @@ class _FakeGitHub {
|
|||||||
if (!files.containsKey(path)) return http.Response('', 404);
|
if (!files.containsKey(path)) return http.Response('', 404);
|
||||||
fileGets.add(path);
|
fileGets.add(path);
|
||||||
final content = base64.encode(utf8.encode(files[path]!));
|
final content = base64.encode(utf8.encode(files[path]!));
|
||||||
return http.Response(jsonEncode({'content': content}), 200);
|
// Real GitHub always returns `sha` alongside `content` for a
|
||||||
|
// get-file-contents call -- crdt_sync's GitHubClient reads it back to
|
||||||
|
// resolve this device's own existing sha before a push.
|
||||||
|
final segments = path.split('/');
|
||||||
|
final sha =
|
||||||
|
segments.length == 4 &&
|
||||||
|
segments[0] == 'diet-guard-sync' &&
|
||||||
|
segments[1] == 'devices'
|
||||||
|
? 'f-${segments[2]}'
|
||||||
|
: null;
|
||||||
|
return http.Response(
|
||||||
|
jsonEncode({'content': content, if (sha != null) 'sha': sha}),
|
||||||
|
200,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -116,10 +124,10 @@ void main() {
|
|||||||
test("skips its own device id ('phone') when listing", () async {
|
test("skips its own device id ('phone') when listing", () async {
|
||||||
final fake = _FakeGitHub(
|
final fake = _FakeGitHub(
|
||||||
deviceDirs: const ['pc', 'phone'],
|
deviceDirs: const ['pc', 'phone'],
|
||||||
files: const {'devices/pc/food_log.json': '{}'},
|
files: const {'diet-guard-sync/devices/pc/food_log.json': '{}'},
|
||||||
);
|
);
|
||||||
await runSync(fake.buildClient());
|
await runSync(fake.buildClient());
|
||||||
expect(fake.fileGets, ['devices/pc/food_log.json']);
|
expect(fake.fileGets, ['diet-guard-sync/devices/pc/food_log.json']);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('skips a device with no pushed file yet', () async {
|
test('skips a device with no pushed file yet', () async {
|
||||||
@ -131,7 +139,7 @@ void main() {
|
|||||||
test('ignores a device whose pushed file is not a JSON object', () async {
|
test('ignores a device whose pushed file is not a JSON object', () async {
|
||||||
final fake = _FakeGitHub(
|
final fake = _FakeGitHub(
|
||||||
deviceDirs: const ['pc'],
|
deviceDirs: const ['pc'],
|
||||||
files: const {'devices/pc/food_log.json': '[]'},
|
files: const {'diet-guard-sync/devices/pc/food_log.json': '[]'},
|
||||||
);
|
);
|
||||||
final merged = await runSync(fake.buildClient());
|
final merged = await runSync(fake.buildClient());
|
||||||
expect(merged, isEmpty);
|
expect(merged, isEmpty);
|
||||||
@ -140,36 +148,76 @@ void main() {
|
|||||||
test('skips a device whose pushed file is corrupt json', () async {
|
test('skips a device whose pushed file is corrupt json', () async {
|
||||||
final fake = _FakeGitHub(
|
final fake = _FakeGitHub(
|
||||||
deviceDirs: const ['pc'],
|
deviceDirs: const ['pc'],
|
||||||
files: const {'devices/pc/food_log.json': '{not valid json'},
|
files: const {
|
||||||
|
'diet-guard-sync/devices/pc/food_log.json': '{not valid json',
|
||||||
|
},
|
||||||
);
|
);
|
||||||
final merged = await runSync(fake.buildClient());
|
final merged = await runSync(fake.buildClient());
|
||||||
expect(merged, isEmpty);
|
expect(merged, isEmpty);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("merges in a remote device's entries", () async {
|
test(
|
||||||
final remoteLog = jsonEncode({
|
"merges in a remote device's entries (old pre-migration format)",
|
||||||
'2026-06-22': [
|
() async {
|
||||||
{
|
final remoteLog = jsonEncode({
|
||||||
'id': 'pc-1',
|
'2026-06-22': [
|
||||||
'time': '2026-06-22T09:00:00+02:00',
|
{
|
||||||
'desc': 'pc meal',
|
'id': 'pc-1',
|
||||||
'kcal': 400.0,
|
'time': '2026-06-22T09:00:00+02:00',
|
||||||
'protein_g': 20.0,
|
'desc': 'pc meal',
|
||||||
'carbs_g': 40.0,
|
'kcal': 400.0,
|
||||||
'fat_g': 10.0,
|
'protein_g': 20.0,
|
||||||
'grams': 300.0,
|
'carbs_g': 40.0,
|
||||||
'source': 'manual',
|
'fat_g': 10.0,
|
||||||
},
|
'grams': 300.0,
|
||||||
],
|
'source': 'manual',
|
||||||
});
|
},
|
||||||
final fake = _FakeGitHub(
|
],
|
||||||
deviceDirs: const ['pc'],
|
});
|
||||||
files: {'devices/pc/food_log.json': remoteLog},
|
final fake = _FakeGitHub(
|
||||||
);
|
deviceDirs: const ['pc'],
|
||||||
final merged = await runSync(fake.buildClient());
|
files: {'diet-guard-sync/devices/pc/food_log.json': remoteLog},
|
||||||
final descs = merged.values.expand((e) => e).map((e) => e.desc).toSet();
|
);
|
||||||
expect(descs, contains('pc meal'));
|
final merged = await runSync(fake.buildClient());
|
||||||
});
|
final descs = merged.values.expand((e) => e).map((e) => e.desc).toSet();
|
||||||
|
expect(descs, contains('pc meal'));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test(
|
||||||
|
"merges in a remote device's entries (new Record-based format)",
|
||||||
|
() async {
|
||||||
|
const remoteEntry = FoodEntry(
|
||||||
|
id: 'pc-1',
|
||||||
|
time: '2026-06-22T09:00:00+02:00',
|
||||||
|
desc: 'pc meal',
|
||||||
|
kcal: 400,
|
||||||
|
proteinG: 20,
|
||||||
|
carbsG: 40,
|
||||||
|
fatG: 10,
|
||||||
|
grams: 300,
|
||||||
|
source: 'manual',
|
||||||
|
);
|
||||||
|
final remoteLog = jsonEncode({
|
||||||
|
'pc-1': Record(
|
||||||
|
id: 'pc-1',
|
||||||
|
fields: {
|
||||||
|
'body': (
|
||||||
|
remoteEntry.toSyncJson(),
|
||||||
|
Hlc.newTick('pc', wallTimeMsOverride: 0),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
).toJson(),
|
||||||
|
});
|
||||||
|
final fake = _FakeGitHub(
|
||||||
|
deviceDirs: const ['pc'],
|
||||||
|
files: {'diet-guard-sync/devices/pc/food_log.json': remoteLog},
|
||||||
|
);
|
||||||
|
final merged = await runSync(fake.buildClient());
|
||||||
|
final descs = merged.values.expand((e) => e).map((e) => e.desc).toSet();
|
||||||
|
expect(descs, contains('pc meal'));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
test('rebuilds the food bank after merge', () async {
|
test('rebuilds the food bank after merge', () async {
|
||||||
await LogStorageService.instance.logMeal('oatmeal', _manual);
|
await LogStorageService.instance.logMeal('oatmeal', _manual);
|
||||||
@ -195,9 +243,22 @@ void main() {
|
|||||||
expect(pushedText, isNot(contains('hmac')));
|
expect(pushedText, isNot(contains('hmac')));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('pushes in the new Record-based wire format', () async {
|
||||||
|
await LogStorageService.instance.logMeal('oatmeal', _manual);
|
||||||
|
final fake = _FakeGitHub();
|
||||||
|
await runSync(fake.buildClient());
|
||||||
|
|
||||||
|
final pushed = fake.puts.single;
|
||||||
|
final pushedText = utf8.decode(base64.decode(pushed['content'] as String));
|
||||||
|
final decoded = jsonDecode(pushedText) as Map<String, dynamic>;
|
||||||
|
final record = decoded.values.single as Map<String, dynamic>;
|
||||||
|
expect(record, containsPair('id', isA<String>()));
|
||||||
|
expect(record, contains('fields'));
|
||||||
|
});
|
||||||
|
|
||||||
test("reuses this device's existing sha when it has pushed before", () async {
|
test("reuses this device's existing sha when it has pushed before", () async {
|
||||||
final fake = _FakeGitHub(
|
final fake = _FakeGitHub(
|
||||||
files: const {'devices/phone/food_log.json': '{}'},
|
files: const {'diet-guard-sync/devices/phone/food_log.json': '{}'},
|
||||||
);
|
);
|
||||||
await runSync(fake.buildClient());
|
await runSync(fake.buildClient());
|
||||||
expect(fake.puts.single['sha'], 'f-phone');
|
expect(fake.puts.single['sha'], 'f-phone');
|
||||||
@ -240,7 +301,7 @@ void main() {
|
|||||||
});
|
});
|
||||||
final fake = _FakeGitHub(
|
final fake = _FakeGitHub(
|
||||||
deviceDirs: const ['pc'],
|
deviceDirs: const ['pc'],
|
||||||
files: {'devices/pc/food_log.json': remoteLog},
|
files: {'diet-guard-sync/devices/pc/food_log.json': remoteLog},
|
||||||
);
|
);
|
||||||
final merged = await runSync(fake.buildClient());
|
final merged = await runSync(fake.buildClient());
|
||||||
|
|
||||||
|
|||||||
@ -10,8 +10,9 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from crdt_sync import GitHubSyncError
|
||||||
|
|
||||||
from diet_guard._sync import SyncError, run_sync
|
from diet_guard._sync import SyncError, run_sync
|
||||||
from diet_guard._sync_github import GitHubSyncError
|
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
import argparse
|
import argparse
|
||||||
|
|||||||
@ -1,9 +1,11 @@
|
|||||||
"""Cross-device log sync orchestration for diet_guard.
|
"""Cross-device log sync orchestration for diet_guard.
|
||||||
|
|
||||||
Pulls every other device's pushed log from GitHub-backed dumb storage
|
Pulls every other device's pushed log from GitHub-backed dumb storage
|
||||||
(:mod:`diet_guard._sync_github`), merges with the local log
|
(``crdt_sync.GitHubSyncClient``), merges with the local log via
|
||||||
(:mod:`diet_guard._sync_merge`), re-signs every persisted entry, rebuilds the
|
``crdt_sync``'s shared CRDT scheme (:mod:`diet_guard._sync_merge` adapts
|
||||||
food bank, and pushes this device's own merged log back up.
|
diet_guard's entries to/from ``crdt_sync.Record``), re-signs every persisted
|
||||||
|
entry, rebuilds the food bank, and pushes this device's own merged log back
|
||||||
|
up in the new Record-based wire format.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@ -11,16 +13,18 @@ from __future__ import annotations
|
|||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
|
from crdt_sync import GitHubSyncClient, Log, merge_logs
|
||||||
|
|
||||||
from diet_guard._constants import (
|
from diet_guard._constants import (
|
||||||
SYNC_DEVICE_ID,
|
SYNC_DEVICE_ID,
|
||||||
SYNC_REPO_NAME,
|
SYNC_REPO_NAME,
|
||||||
SYNC_REPO_OWNER,
|
SYNC_REPO_OWNER,
|
||||||
|
SYNC_TIMEOUT_SECONDS,
|
||||||
SYNC_TOKEN_FILE,
|
SYNC_TOKEN_FILE,
|
||||||
)
|
)
|
||||||
from diet_guard._foodbank import rebuild_food_bank
|
from diet_guard._foodbank import rebuild_food_bank
|
||||||
from diet_guard._state import DayLog, read_raw_log, resign_entry, write_raw_log
|
from diet_guard._state import DayLog, read_raw_log, resign_entry, write_raw_log
|
||||||
from diet_guard._sync_github import GitHubSyncClient
|
from diet_guard._sync_merge import daylog_to_log, log_to_daylog, parse_remote_log
|
||||||
from diet_guard._sync_merge import merge_logs
|
|
||||||
|
|
||||||
_logger = logging.getLogger(__name__)
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@ -57,15 +61,16 @@ def _read_token() -> str:
|
|||||||
return token
|
return token
|
||||||
|
|
||||||
|
|
||||||
def _pull_remote_logs(client: GitHubSyncClient) -> list[DayLog]:
|
def _pull_remote_logs(client: GitHubSyncClient) -> list[Log]:
|
||||||
"""Return every other device's last-pushed log, skipping this one.
|
"""Return every other device's last-pushed log, skipping this one.
|
||||||
|
|
||||||
A device whose pushed file is corrupt or truncated (e.g. an interrupted
|
A device whose pushed file is corrupt, truncated, or otherwise
|
||||||
push) is logged and skipped, same as one that has never pushed at all --
|
unparsable (new or old wire format) is logged and skipped, same as one
|
||||||
GitHub is an external system boundary, and one bad device's file must
|
that has never pushed at all -- GitHub is an external system boundary,
|
||||||
not stall merging in every other device's.
|
and one bad device's file must not stall merging in every other
|
||||||
|
device's.
|
||||||
"""
|
"""
|
||||||
remote_logs: list[DayLog] = []
|
remote_logs: list[Log] = []
|
||||||
for device_id in client.list_directory(_DEVICES_DIR):
|
for device_id in client.list_directory(_DEVICES_DIR):
|
||||||
if device_id == SYNC_DEVICE_ID:
|
if device_id == SYNC_DEVICE_ID:
|
||||||
continue
|
continue
|
||||||
@ -73,12 +78,9 @@ def _pull_remote_logs(client: GitHubSyncClient) -> list[DayLog]:
|
|||||||
if text is None:
|
if text is None:
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
remote_log = json.loads(text)
|
remote_logs.append(parse_remote_log(text))
|
||||||
except json.JSONDecodeError:
|
except (TypeError, KeyError, ValueError, json.JSONDecodeError):
|
||||||
_logger.warning("Unparsable log pushed by device %r, skipping", device_id)
|
_logger.warning("Unparsable log pushed by device %r, skipping", device_id)
|
||||||
continue
|
|
||||||
if isinstance(remote_log, dict):
|
|
||||||
remote_logs.append(remote_log)
|
|
||||||
return remote_logs
|
return remote_logs
|
||||||
|
|
||||||
|
|
||||||
@ -96,27 +98,35 @@ def run_sync() -> DayLog:
|
|||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
SyncError: If the local PAT is missing or empty.
|
SyncError: If the local PAT is missing or empty.
|
||||||
diet_guard._sync_github.GitHubSyncError: Propagated from the GitHub
|
crdt_sync.GitHubSyncError: Propagated from the GitHub client for any
|
||||||
client for any transport failure -- the caller (CLI/timer)
|
transport failure -- the caller (CLI/timer) decides how to
|
||||||
decides how to report it.
|
report it.
|
||||||
"""
|
"""
|
||||||
token = _read_token()
|
token = _read_token()
|
||||||
client = GitHubSyncClient(SYNC_REPO_OWNER, SYNC_REPO_NAME, token)
|
client = GitHubSyncClient(
|
||||||
|
SYNC_REPO_OWNER, SYNC_REPO_NAME, token, timeout_seconds=SYNC_TIMEOUT_SECONDS
|
||||||
|
)
|
||||||
|
|
||||||
merged = read_raw_log()
|
merged = daylog_to_log(read_raw_log())
|
||||||
for remote_log in _pull_remote_logs(client):
|
for remote_log in _pull_remote_logs(client):
|
||||||
merged = merge_logs(merged, remote_log)
|
merged = merge_logs(merged, remote_log)
|
||||||
|
|
||||||
|
merged_daylog = log_to_daylog(merged)
|
||||||
resigned: DayLog = {
|
resigned: DayLog = {
|
||||||
day: [resign_entry(entry) for entry in entries]
|
day: [resign_entry(entry) for entry in entries]
|
||||||
for day, entries in merged.items()
|
for day, entries in merged_daylog.items()
|
||||||
}
|
}
|
||||||
write_raw_log(resigned)
|
write_raw_log(resigned)
|
||||||
rebuild_food_bank(resigned)
|
rebuild_food_bank(resigned)
|
||||||
|
|
||||||
|
push_log = daylog_to_log(resigned)
|
||||||
|
push_json = json.dumps(
|
||||||
|
{record_id: record.to_dict() for record_id, record in push_log.items()},
|
||||||
|
indent=2,
|
||||||
|
)
|
||||||
client.put_file_text(
|
client.put_file_text(
|
||||||
_device_log_path(SYNC_DEVICE_ID),
|
_device_log_path(SYNC_DEVICE_ID),
|
||||||
json.dumps(resigned, indent=2),
|
push_json,
|
||||||
message="diet_guard sync",
|
message="diet_guard sync",
|
||||||
)
|
)
|
||||||
return resigned
|
return resigned
|
||||||
|
|||||||
@ -1,190 +0,0 @@
|
|||||||
"""Minimal GitHub Contents API client for diet_guard's dumb-storage sync.
|
|
||||||
|
|
||||||
GitHub is used purely as file storage via the REST Contents API, not a git
|
|
||||||
clone -- ported in spirit from ``~/todo``'s sync transport. There is no
|
|
||||||
working tree and no git-level merge; the only merge is the domain-level one
|
|
||||||
in :mod:`diet_guard._sync_merge`.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import base64
|
|
||||||
import logging
|
|
||||||
|
|
||||||
import requests
|
|
||||||
|
|
||||||
from diet_guard._constants import SYNC_TIMEOUT_SECONDS
|
|
||||||
|
|
||||||
_logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
_API_BASE = "https://api.github.com"
|
|
||||||
_HTTP_NOT_FOUND = 404
|
|
||||||
|
|
||||||
|
|
||||||
class GitHubSyncError(Exception):
|
|
||||||
"""Raised for a GitHub API failure the caller must not silently ignore."""
|
|
||||||
|
|
||||||
|
|
||||||
class RepoNotFoundError(GitHubSyncError):
|
|
||||||
"""Raised when the configured repo itself is unreachable.
|
|
||||||
|
|
||||||
Distinguished from a path-404 (nothing pushed to that path yet, which is
|
|
||||||
benign -- it just means no other device has synced before) so the caller
|
|
||||||
can tell "the repo name is wrong or the PAT isn't scoped to it" apart
|
|
||||||
from "no other device has synced yet".
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
class GitHubSyncClient:
|
|
||||||
"""Thin wrapper around the subset of the Contents API sync needs."""
|
|
||||||
|
|
||||||
def __init__(self, owner: str, repo: str, token: str) -> None:
|
|
||||||
"""Create a client scoped to one repo, authenticated with ``token``.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
owner: The repo owner/org (e.g. ``"kuhyx"``).
|
|
||||||
repo: The repo name (e.g. ``"diet-guard-sync"``).
|
|
||||||
token: A GitHub PAT with contents read/write on that repo.
|
|
||||||
"""
|
|
||||||
self._owner = owner
|
|
||||||
self._repo = repo
|
|
||||||
self._headers = {
|
|
||||||
"Authorization": f"Bearer {token}",
|
|
||||||
"Accept": "application/vnd.github+json",
|
|
||||||
}
|
|
||||||
|
|
||||||
def _contents_url(self, path: str) -> str:
|
|
||||||
return f"{_API_BASE}/repos/{self._owner}/{self._repo}/contents/{path}"
|
|
||||||
|
|
||||||
def _get(self, path: str) -> requests.Response:
|
|
||||||
try:
|
|
||||||
return requests.get(
|
|
||||||
self._contents_url(path),
|
|
||||||
headers=self._headers,
|
|
||||||
timeout=SYNC_TIMEOUT_SECONDS,
|
|
||||||
)
|
|
||||||
except requests.RequestException as exc:
|
|
||||||
msg = f"network error reading {path}"
|
|
||||||
raise GitHubSyncError(msg) from exc
|
|
||||||
|
|
||||||
def _repo_exists(self) -> bool:
|
|
||||||
try:
|
|
||||||
response = requests.get(
|
|
||||||
f"{_API_BASE}/repos/{self._owner}/{self._repo}",
|
|
||||||
headers=self._headers,
|
|
||||||
timeout=SYNC_TIMEOUT_SECONDS,
|
|
||||||
)
|
|
||||||
except requests.RequestException:
|
|
||||||
return False
|
|
||||||
return response.ok
|
|
||||||
|
|
||||||
def _raise_for_missing_path(self, path: str) -> None:
|
|
||||||
"""Raise :class:`RepoNotFoundError` only if the repo is unreachable.
|
|
||||||
|
|
||||||
A 404 on a path within a reachable repo just means nothing has been
|
|
||||||
pushed there yet, which is not an error worth raising on.
|
|
||||||
"""
|
|
||||||
if not self._repo_exists():
|
|
||||||
msg = (
|
|
||||||
f"{self._owner}/{self._repo} not found, private without "
|
|
||||||
f"access, or the token lacks contents permission "
|
|
||||||
f"(while reading {path})"
|
|
||||||
)
|
|
||||||
raise RepoNotFoundError(msg)
|
|
||||||
|
|
||||||
def get_file_text(self, path: str) -> str | None:
|
|
||||||
"""Return the decoded text content at ``path``, or None if unused.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
path: A repo-relative file path, e.g. ``"devices/pc/food_log.json"``.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
The file's text content, or None if nothing has been pushed
|
|
||||||
there yet (but the repo itself is reachable).
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
RepoNotFoundError: If the repo itself is unreachable.
|
|
||||||
GitHubSyncError: For any other non-2xx response or network error.
|
|
||||||
"""
|
|
||||||
response = self._get(path)
|
|
||||||
if response.status_code == _HTTP_NOT_FOUND:
|
|
||||||
self._raise_for_missing_path(path)
|
|
||||||
return None
|
|
||||||
if not response.ok:
|
|
||||||
msg = f"GET {path} failed: {response.status_code}"
|
|
||||||
raise GitHubSyncError(msg)
|
|
||||||
data = response.json()
|
|
||||||
content = data.get("content", "") if isinstance(data, dict) else ""
|
|
||||||
return base64.b64decode(content).decode("utf-8")
|
|
||||||
|
|
||||||
def _existing_sha(self, path: str) -> str | None:
|
|
||||||
response = self._get(path)
|
|
||||||
if response.status_code == _HTTP_NOT_FOUND:
|
|
||||||
self._raise_for_missing_path(path)
|
|
||||||
return None
|
|
||||||
if not response.ok:
|
|
||||||
msg = f"GET {path} (for sha) failed: {response.status_code}"
|
|
||||||
raise GitHubSyncError(
|
|
||||||
msg,
|
|
||||||
)
|
|
||||||
data = response.json()
|
|
||||||
sha = data.get("sha") if isinstance(data, dict) else None
|
|
||||||
return sha if isinstance(sha, str) else None
|
|
||||||
|
|
||||||
def put_file_text(self, path: str, text: str, *, message: str) -> None:
|
|
||||||
"""Create or update the file at ``path`` with ``text``.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
path: A repo-relative file path.
|
|
||||||
text: The full new content (this device's complete merged log).
|
|
||||||
message: The commit message for this push.
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
GitHubSyncError: On any non-2xx response or network error.
|
|
||||||
"""
|
|
||||||
sha = self._existing_sha(path)
|
|
||||||
payload: dict[str, object] = {
|
|
||||||
"message": message,
|
|
||||||
"content": base64.b64encode(text.encode("utf-8")).decode("ascii"),
|
|
||||||
}
|
|
||||||
if sha is not None:
|
|
||||||
payload["sha"] = sha
|
|
||||||
try:
|
|
||||||
response = requests.put(
|
|
||||||
self._contents_url(path),
|
|
||||||
headers=self._headers,
|
|
||||||
json=payload,
|
|
||||||
timeout=SYNC_TIMEOUT_SECONDS,
|
|
||||||
)
|
|
||||||
except requests.RequestException as exc:
|
|
||||||
msg = f"network error pushing {path}"
|
|
||||||
raise GitHubSyncError(msg) from exc
|
|
||||||
if not response.ok:
|
|
||||||
msg = f"PUT {path} failed: {response.status_code}"
|
|
||||||
raise GitHubSyncError(msg)
|
|
||||||
|
|
||||||
def list_directory(self, path: str) -> list[str]:
|
|
||||||
"""Return the entry names directly under ``path`` (empty if unused).
|
|
||||||
|
|
||||||
Args:
|
|
||||||
path: A repo-relative directory path, e.g. ``"devices"``.
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
RepoNotFoundError: If the repo itself is unreachable.
|
|
||||||
GitHubSyncError: For any other non-2xx response or network error.
|
|
||||||
"""
|
|
||||||
response = self._get(path)
|
|
||||||
if response.status_code == _HTTP_NOT_FOUND:
|
|
||||||
self._raise_for_missing_path(path)
|
|
||||||
return []
|
|
||||||
if not response.ok:
|
|
||||||
msg = f"GET {path} (list) failed: {response.status_code}"
|
|
||||||
raise GitHubSyncError(msg)
|
|
||||||
data = response.json()
|
|
||||||
if not isinstance(data, list):
|
|
||||||
return []
|
|
||||||
return [
|
|
||||||
item["name"]
|
|
||||||
for item in data
|
|
||||||
if isinstance(item, dict) and isinstance(item.get("name"), str)
|
|
||||||
]
|
|
||||||
@ -1,81 +1,178 @@
|
|||||||
"""Pure log-merge logic for diet_guard's cross-device sync.
|
"""Entry <-> crdt_sync.Record adapters for diet_guard's cross-device sync.
|
||||||
|
|
||||||
No I/O here -- this module is unit-testable purely on in-memory ``DayLog``
|
diet_guard's own on-disk ``food_log.json`` format is unchanged (a
|
||||||
values, like :mod:`diet_guard._slots`. Mirrored test-for-test by the Dart
|
:class:`~diet_guard._state.DayLog`: date string -> list of entry dicts) --
|
||||||
port (``app/lib/services/sync_service.dart``), so the merge algorithm
|
only the GitHub-synced wire format and the cross-device merge algorithm now
|
||||||
canonically agrees on both sides of the sync.
|
go through ``crdt_sync``'s ``Record``/``Log``/``Hlc`` primitives, the same
|
||||||
|
ones every other kuhy app that syncs this way uses (see ``~/crdt-sync``).
|
||||||
|
|
||||||
|
Each diet_guard entry maps to one ``Record`` with a single opaque ``body``
|
||||||
|
field holding everything except ``id``/``deleted``: entries are immutable
|
||||||
|
after creation (only ``deleted`` ever changes post-write, see
|
||||||
|
:func:`diet_guard._state.resign_entry`), so there is no benefit to
|
||||||
|
``crdt_sync``'s per-field LWW granularity here -- the whole body shares one
|
||||||
|
derived ``Hlc``. ``hmac`` travels inside ``body`` like any other field but
|
||||||
|
is never trusted on read; :func:`diet_guard._sync.run_sync` always re-signs
|
||||||
|
after merging, exactly as before this migration.
|
||||||
|
|
||||||
|
Backward compatible with devices not yet migrated (the phone app, for now):
|
||||||
|
:func:`parse_remote_log` tries the new Record-based wire format first and
|
||||||
|
falls back to the old plain-DayLog format, converting old-format entries
|
||||||
|
through the same adapters used for the local log. Push always writes the
|
||||||
|
new format -- there is no code path left that ever *writes* the old one.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from crdt_sync import Hlc, Record
|
||||||
|
|
||||||
|
from diet_guard._constants import SYNC_DEVICE_ID
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
|
from crdt_sync import Log
|
||||||
|
|
||||||
from diet_guard._state import DayLog
|
from diet_guard._state import DayLog
|
||||||
|
|
||||||
# A dedup key: ("id", <uuid string>) for any entry with one, else
|
_EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
|
||||||
# ("legacy", (time, desc)) for a pre-id entry written before this field
|
|
||||||
# existed -- two devices that both already had that same legacy entry would
|
|
||||||
# otherwise end up with two copies of it after a merge.
|
|
||||||
_Key = tuple[str, object]
|
|
||||||
|
|
||||||
|
|
||||||
def _entry_key(entry: dict[str, object]) -> _Key:
|
def _entry_hlc(entry: dict[str, object]) -> Hlc:
|
||||||
"""Return the dedup key for ``entry``."""
|
"""Derive a deterministic Hlc for ``entry`` from its own ``time`` field.
|
||||||
|
|
||||||
|
The same entry always yields the same Hlc regardless of when this runs
|
||||||
|
-- entries are immutable after creation, so there's no real "now" to
|
||||||
|
stamp, just the birth-time already recorded on the entry itself.
|
||||||
|
Malformed/missing ``time`` still gets a valid (if early-sorting) Hlc
|
||||||
|
rather than raising -- this only affects tie-breaking between
|
||||||
|
otherwise-identical copies of the same id, never whether the entry
|
||||||
|
survives a merge.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
dt = datetime.fromisoformat(str(entry.get("time", "")))
|
||||||
|
except ValueError:
|
||||||
|
dt = _EPOCH
|
||||||
|
wall_time_ms = int(dt.timestamp() * 1000)
|
||||||
|
return Hlc.new_tick(SYNC_DEVICE_ID, wall_time_ms=wall_time_ms)
|
||||||
|
|
||||||
|
|
||||||
|
def _legacy_entry_id(entry: dict[str, object]) -> str:
|
||||||
|
"""Deterministic id for a pre-``id`` legacy entry, from ``(time, desc)``.
|
||||||
|
|
||||||
|
Two devices holding the same legacy entry independently derive the same
|
||||||
|
id without communicating, so they merge as one record instead of two --
|
||||||
|
the same guarantee the old ``(time, desc)`` dedup key gave, just
|
||||||
|
expressed as a real id going forward.
|
||||||
|
"""
|
||||||
|
key = f"{entry.get('time')}|{entry.get('desc')}"
|
||||||
|
digest = hashlib.sha256(key.encode()).hexdigest()[:32]
|
||||||
|
return f"legacy-{digest}"
|
||||||
|
|
||||||
|
|
||||||
|
def entry_to_record(entry: dict[str, object]) -> Record:
|
||||||
|
"""Convert one diet_guard log entry to a ``crdt_sync.Record``."""
|
||||||
entry_id = entry.get("id")
|
entry_id = entry.get("id")
|
||||||
if isinstance(entry_id, str) and entry_id:
|
if not isinstance(entry_id, str) or not entry_id:
|
||||||
return ("id", entry_id)
|
entry_id = _legacy_entry_id(entry)
|
||||||
return ("legacy", (entry.get("time"), entry.get("desc")))
|
hlc = _entry_hlc(entry)
|
||||||
|
body = {k: v for k, v in entry.items() if k not in ("id", "deleted")}
|
||||||
|
deleted = bool(entry.get("deleted", False))
|
||||||
|
return Record(
|
||||||
|
id=entry_id,
|
||||||
|
fields={"body": (body, hlc)},
|
||||||
|
deleted=deleted,
|
||||||
|
deleted_hlc=hlc if deleted else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _tombstone_wins(
|
def record_to_entry(record: Record) -> dict[str, object]:
|
||||||
candidate: dict[str, object],
|
"""Convert one ``crdt_sync.Record`` back to a diet_guard log entry."""
|
||||||
existing: dict[str, object],
|
body_value, _hlc = record.fields.get("body", ({}, None))
|
||||||
) -> bool:
|
entry: dict[str, object] = dict(body_value) if isinstance(body_value, dict) else {}
|
||||||
"""Return True if ``candidate`` should replace ``existing`` for one key.
|
entry["id"] = record.id
|
||||||
|
if record.deleted:
|
||||||
|
entry["deleted"] = True
|
||||||
|
return entry
|
||||||
|
|
||||||
A tombstone always wins over a non-tombstoned copy of the same entry --
|
|
||||||
deletion is sticky, so a stale pre-undo copy pulled from another device
|
def daylog_to_log(daylog: DayLog) -> Log:
|
||||||
can never resurrect something the user explicitly removed. Otherwise,
|
"""Convert a full local/remote DayLog into a ``crdt_sync.Log``."""
|
||||||
keep whichever copy was seen first: two copies of the same id are
|
log: Log = {}
|
||||||
expected to be byte-identical in their macros/desc (the body is never
|
for entries in daylog.values():
|
||||||
mutated after creation, only ``deleted``/``hmac``), so which one survives
|
for entry in entries:
|
||||||
does not change the merged result's content.
|
record = entry_to_record(entry)
|
||||||
|
log[record.id] = record
|
||||||
|
return log
|
||||||
|
|
||||||
|
|
||||||
|
def log_to_daylog(log: Log) -> DayLog:
|
||||||
|
"""Convert a merged ``crdt_sync.Log`` back into DayLog shape.
|
||||||
|
|
||||||
|
Each entry is re-bucketed under its own ``time``'s date rather than
|
||||||
|
whatever date key it might have arrived under, and each day's entries
|
||||||
|
are sorted oldest-first -- matching the existing on-disk convention.
|
||||||
"""
|
"""
|
||||||
return bool(candidate.get("deleted")) and not existing.get("deleted")
|
daylog: DayLog = {}
|
||||||
|
for record in log.values():
|
||||||
|
entry = record_to_entry(record)
|
||||||
def merge_logs(local: DayLog, remote: DayLog) -> DayLog:
|
|
||||||
"""Return the union of ``local`` and ``remote``, tombstones winning by id.
|
|
||||||
|
|
||||||
Commutative and idempotent: ``merge_logs(a, b) == merge_logs(b, a)`` and
|
|
||||||
``merge_logs(x, x) == x`` (for an ``x`` with no duplicate keys), so
|
|
||||||
pull-order between devices never matters and a repeated sync tick is a
|
|
||||||
no-op. Each entry is re-bucketed under its own ``time``'s date rather
|
|
||||||
than the date key it arrived under, so a merge can't silently leave an
|
|
||||||
entry filed under the wrong day.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
local: This device's current full log (including tombstones).
|
|
||||||
remote: Another device's last-pushed full log.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
The merged log, keyed by each entry's own date, each day's entries
|
|
||||||
sorted oldest-first (matching the existing on-disk convention).
|
|
||||||
"""
|
|
||||||
by_key: dict[_Key, dict[str, object]] = {}
|
|
||||||
for day_log in (local, remote):
|
|
||||||
for entries in day_log.values():
|
|
||||||
for entry in entries:
|
|
||||||
key = _entry_key(entry)
|
|
||||||
existing = by_key.get(key)
|
|
||||||
if existing is None or _tombstone_wins(entry, existing):
|
|
||||||
by_key[key] = entry
|
|
||||||
|
|
||||||
merged: DayLog = {}
|
|
||||||
for entry in by_key.values():
|
|
||||||
date_key = str(entry.get("time", ""))[:10]
|
date_key = str(entry.get("time", ""))[:10]
|
||||||
merged.setdefault(date_key, []).append(entry)
|
daylog.setdefault(date_key, []).append(entry)
|
||||||
for entries in merged.values():
|
for entries in daylog.values():
|
||||||
entries.sort(key=lambda entry: str(entry.get("time", "")))
|
entries.sort(key=lambda entry: str(entry.get("time", "")))
|
||||||
return merged
|
return daylog
|
||||||
|
|
||||||
|
|
||||||
|
def _looks_like_new_format(raw: dict[str, object]) -> bool:
|
||||||
|
"""Return True if ``raw`` is shaped like a crdt_sync Record-keyed Log.
|
||||||
|
|
||||||
|
An empty object is ambiguous but harmless either way (no entries to
|
||||||
|
convert), so it's treated as new format to skip the old-format
|
||||||
|
conversion pass for nothing.
|
||||||
|
"""
|
||||||
|
return all(
|
||||||
|
isinstance(value, dict) and "fields" in value and "id" in value
|
||||||
|
for value in raw.values()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_remote_log(text: str) -> Log:
|
||||||
|
"""Parse one device's pushed log text into a ``crdt_sync.Log``.
|
||||||
|
|
||||||
|
Tries the new Record-based wire format first; falls back to the old
|
||||||
|
plain-DayLog format (today's on-the-wire shape) for devices not yet
|
||||||
|
migrated onto crdt_sync, converting their entries through the same
|
||||||
|
adapter the local log uses. Raises on genuinely malformed data, same as
|
||||||
|
the pre-migration behavior -- the caller
|
||||||
|
(:func:`diet_guard._sync._pull_remote_logs`) already logs-and-skips on
|
||||||
|
that.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
TypeError: If the top-level JSON isn't an object, or a "new format"
|
||||||
|
value or an old-format day's entries aren't shaped as expected.
|
||||||
|
KeyError: Via ``Record.from_dict``, if a "new format" record is
|
||||||
|
missing an expected key.
|
||||||
|
ValueError: Via ``json.loads`` on invalid JSON, or ``Hlc.from_str``
|
||||||
|
on a malformed clock string.
|
||||||
|
"""
|
||||||
|
raw = json.loads(text)
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
msg = f"top-level sync payload is not a JSON object: {raw!r}"
|
||||||
|
raise TypeError(msg)
|
||||||
|
if _looks_like_new_format(raw):
|
||||||
|
return {record_id: Record.from_dict(data) for record_id, data in raw.items()}
|
||||||
|
|
||||||
|
daylog: DayLog = {}
|
||||||
|
for date_key, entries in raw.items():
|
||||||
|
if not isinstance(entries, list):
|
||||||
|
msg = f"day {date_key!r} is not a JSON array: {entries!r}"
|
||||||
|
raise TypeError(msg)
|
||||||
|
for entry in entries:
|
||||||
|
if not isinstance(entry, dict):
|
||||||
|
msg = f"entry under day {date_key!r} is not a JSON object: {entry!r}"
|
||||||
|
raise TypeError(msg)
|
||||||
|
daylog[date_key] = entries
|
||||||
|
return daylog_to_log(daylog)
|
||||||
|
|||||||
@ -6,9 +6,10 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from crdt_sync import GitHubSyncError
|
||||||
|
|
||||||
from diet_guard import _cli_sync
|
from diet_guard import _cli_sync
|
||||||
from diet_guard._sync import SyncError
|
from diet_guard._sync import SyncError
|
||||||
from diet_guard._sync_github import GitHubSyncError
|
|
||||||
|
|
||||||
|
|
||||||
class TestCmdSync:
|
class TestCmdSync:
|
||||||
|
|||||||
@ -43,7 +43,7 @@ def _mock_client(
|
|||||||
client = MagicMock()
|
client = MagicMock()
|
||||||
client.list_directory.return_value = list(devices)
|
client.list_directory.return_value = list(devices)
|
||||||
resolved_files = files or {}
|
resolved_files = files or {}
|
||||||
client.get_file_text.side_effect = lambda path: resolved_files.get(path)
|
client.get_file_text.side_effect = resolved_files.get
|
||||||
return client
|
return client
|
||||||
|
|
||||||
|
|
||||||
@ -81,18 +81,23 @@ class TestRunSync:
|
|||||||
assert sum(len(entries) for entries in merged.values()) == 1
|
assert sum(len(entries) for entries in merged.values()) == 1
|
||||||
client.put_file_text.assert_called_once()
|
client.put_file_text.assert_called_once()
|
||||||
pushed_path = client.put_file_text.call_args.args[0]
|
pushed_path = client.put_file_text.call_args.args[0]
|
||||||
assert pushed_path == "devices/pc/food_log.json"
|
assert pushed_path == "diet-guard-sync/devices/pc/food_log.json"
|
||||||
|
pushed_json = client.put_file_text.call_args.args[1]
|
||||||
|
pushed = json.loads(pushed_json)
|
||||||
|
(record,) = pushed.values()
|
||||||
|
assert "fields" in record
|
||||||
|
assert "id" in record
|
||||||
|
|
||||||
def test_skips_its_own_device_id_when_listing(self) -> None:
|
def test_skips_its_own_device_id_when_listing(self) -> None:
|
||||||
_write_token()
|
_write_token()
|
||||||
client = _mock_client(
|
client = _mock_client(
|
||||||
devices=("pc", "phone"),
|
devices=("pc", "phone"),
|
||||||
files={"devices/phone/food_log.json": "{}"},
|
files={"diet-guard-sync/devices/phone/food_log.json": "{}"},
|
||||||
)
|
)
|
||||||
with patch.object(_sync, "GitHubSyncClient", return_value=client):
|
with patch.object(_sync, "GitHubSyncClient", return_value=client):
|
||||||
_sync.run_sync()
|
_sync.run_sync()
|
||||||
client.get_file_text.assert_called_once_with(
|
client.get_file_text.assert_called_once_with(
|
||||||
"devices/phone/food_log.json",
|
"diet-guard-sync/devices/phone/food_log.json",
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_skips_a_device_with_no_pushed_file_yet(self) -> None:
|
def test_skips_a_device_with_no_pushed_file_yet(self) -> None:
|
||||||
@ -106,7 +111,7 @@ class TestRunSync:
|
|||||||
_write_token()
|
_write_token()
|
||||||
client = _mock_client(
|
client = _mock_client(
|
||||||
devices=("phone",),
|
devices=("phone",),
|
||||||
files={"devices/phone/food_log.json": "[]"},
|
files={"diet-guard-sync/devices/phone/food_log.json": "[]"},
|
||||||
)
|
)
|
||||||
with patch.object(_sync, "GitHubSyncClient", return_value=client):
|
with patch.object(_sync, "GitHubSyncClient", return_value=client):
|
||||||
merged = _sync.run_sync()
|
merged = _sync.run_sync()
|
||||||
@ -119,7 +124,7 @@ class TestRunSync:
|
|||||||
_write_token()
|
_write_token()
|
||||||
client = _mock_client(
|
client = _mock_client(
|
||||||
devices=("phone",),
|
devices=("phone",),
|
||||||
files={"devices/phone/food_log.json": "{not valid json"},
|
files={"diet-guard-sync/devices/phone/food_log.json": "{not valid json"},
|
||||||
)
|
)
|
||||||
with patch.object(_sync, "GitHubSyncClient", return_value=client):
|
with patch.object(_sync, "GitHubSyncClient", return_value=client):
|
||||||
merged = _sync.run_sync()
|
merged = _sync.run_sync()
|
||||||
@ -146,7 +151,7 @@ class TestRunSync:
|
|||||||
)
|
)
|
||||||
client = _mock_client(
|
client = _mock_client(
|
||||||
devices=("phone",),
|
devices=("phone",),
|
||||||
files={"devices/phone/food_log.json": remote_log_json},
|
files={"diet-guard-sync/devices/phone/food_log.json": remote_log_json},
|
||||||
)
|
)
|
||||||
with patch.object(_sync, "GitHubSyncClient", return_value=client):
|
with patch.object(_sync, "GitHubSyncClient", return_value=client):
|
||||||
merged = _sync.run_sync()
|
merged = _sync.run_sync()
|
||||||
@ -181,7 +186,7 @@ class TestRunSync:
|
|||||||
)
|
)
|
||||||
client = _mock_client(
|
client = _mock_client(
|
||||||
devices=("phone",),
|
devices=("phone",),
|
||||||
files={"devices/phone/food_log.json": remote_log_json},
|
files={"diet-guard-sync/devices/phone/food_log.json": remote_log_json},
|
||||||
)
|
)
|
||||||
with patch.object(_sync, "GitHubSyncClient", return_value=client):
|
with patch.object(_sync, "GitHubSyncClient", return_value=client):
|
||||||
_sync.run_sync()
|
_sync.run_sync()
|
||||||
|
|||||||
@ -1,197 +0,0 @@
|
|||||||
"""Tests for the GitHub Contents API sync client.
|
|
||||||
|
|
||||||
The HTTP layer is fully mocked (``requests.get``/``requests.put``), so every
|
|
||||||
branch -- success, path-404-but-repo-ok, repo-404, non-2xx, and network
|
|
||||||
exceptions -- is exercised without any network access, mirroring
|
|
||||||
``test_estimator.py``'s mocking style.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import base64
|
|
||||||
from unittest.mock import MagicMock, patch
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
import requests
|
|
||||||
|
|
||||||
from diet_guard import _sync_github
|
|
||||||
from diet_guard._sync_github import (
|
|
||||||
GitHubSyncClient,
|
|
||||||
GitHubSyncError,
|
|
||||||
RepoNotFoundError,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _response(
|
|
||||||
status_code: int = 200,
|
|
||||||
json_data: object = None,
|
|
||||||
) -> MagicMock:
|
|
||||||
"""Build a fake ``requests.Response`` with a fixed status and JSON body."""
|
|
||||||
response = MagicMock()
|
|
||||||
response.status_code = status_code
|
|
||||||
response.ok = 200 <= status_code < 300
|
|
||||||
response.json = MagicMock(return_value=json_data if json_data is not None else {})
|
|
||||||
return response
|
|
||||||
|
|
||||||
|
|
||||||
def _client() -> GitHubSyncClient:
|
|
||||||
return GitHubSyncClient("kuhyx", "diet-guard-sync", "fake-token")
|
|
||||||
|
|
||||||
|
|
||||||
def _patch_get(*responses: MagicMock) -> object:
|
|
||||||
"""Patch ``requests.get`` to return each of ``responses`` in order."""
|
|
||||||
return patch.object(_sync_github.requests, "get", side_effect=list(responses))
|
|
||||||
|
|
||||||
|
|
||||||
def _patch_get_raises() -> object:
|
|
||||||
return patch.object(
|
|
||||||
_sync_github.requests,
|
|
||||||
"get",
|
|
||||||
side_effect=requests.ConnectionError("offline"),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class TestGetFileText:
|
|
||||||
def test_returns_decoded_content_on_success(self) -> None:
|
|
||||||
encoded = base64.b64encode(b"hello world").decode("ascii")
|
|
||||||
with _patch_get(_response(200, {"content": encoded})):
|
|
||||||
assert _client().get_file_text("devices/pc/food_log.json") == (
|
|
||||||
"hello world"
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_returns_none_for_an_unused_path_on_a_real_repo(self) -> None:
|
|
||||||
with _patch_get(_response(404), _response(200)):
|
|
||||||
assert _client().get_file_text("devices/phone/food_log.json") is None
|
|
||||||
|
|
||||||
def test_raises_repo_not_found_when_the_repo_itself_is_missing(self) -> None:
|
|
||||||
with (
|
|
||||||
_patch_get(_response(404), _response(404)),
|
|
||||||
pytest.raises(
|
|
||||||
RepoNotFoundError,
|
|
||||||
),
|
|
||||||
):
|
|
||||||
_client().get_file_text("devices/pc/food_log.json")
|
|
||||||
|
|
||||||
def test_raises_sync_error_on_a_non_2xx_non_404(self) -> None:
|
|
||||||
with _patch_get(_response(500)), pytest.raises(GitHubSyncError):
|
|
||||||
_client().get_file_text("devices/pc/food_log.json")
|
|
||||||
|
|
||||||
def test_raises_sync_error_on_a_network_exception(self) -> None:
|
|
||||||
with _patch_get_raises(), pytest.raises(GitHubSyncError):
|
|
||||||
_client().get_file_text("devices/pc/food_log.json")
|
|
||||||
|
|
||||||
def test_treats_a_network_error_during_the_repo_check_as_repo_missing(
|
|
||||||
self,
|
|
||||||
) -> None:
|
|
||||||
with (
|
|
||||||
patch.object(
|
|
||||||
_sync_github.requests,
|
|
||||||
"get",
|
|
||||||
side_effect=[_response(404), requests.ConnectionError("offline")],
|
|
||||||
),
|
|
||||||
pytest.raises(RepoNotFoundError),
|
|
||||||
):
|
|
||||||
_client().get_file_text("devices/pc/food_log.json")
|
|
||||||
|
|
||||||
|
|
||||||
class TestListDirectory:
|
|
||||||
def test_returns_entry_names(self) -> None:
|
|
||||||
payload = [{"name": "pc"}, {"name": "phone"}, {"not_a_name": "x"}]
|
|
||||||
with _patch_get(_response(200, payload)):
|
|
||||||
assert _client().list_directory("devices") == ["pc", "phone"]
|
|
||||||
|
|
||||||
def test_returns_empty_list_when_response_is_not_a_list(self) -> None:
|
|
||||||
with _patch_get(_response(200, {"unexpected": "shape"})):
|
|
||||||
assert _client().list_directory("devices") == []
|
|
||||||
|
|
||||||
def test_returns_empty_list_for_an_unused_path_on_a_real_repo(self) -> None:
|
|
||||||
with _patch_get(_response(404), _response(200)):
|
|
||||||
assert _client().list_directory("devices") == []
|
|
||||||
|
|
||||||
def test_raises_repo_not_found_when_the_repo_itself_is_missing(self) -> None:
|
|
||||||
with (
|
|
||||||
_patch_get(_response(404), _response(404)),
|
|
||||||
pytest.raises(
|
|
||||||
RepoNotFoundError,
|
|
||||||
),
|
|
||||||
):
|
|
||||||
_client().list_directory("devices")
|
|
||||||
|
|
||||||
def test_raises_sync_error_on_a_non_2xx_non_404(self) -> None:
|
|
||||||
with _patch_get(_response(500)), pytest.raises(GitHubSyncError):
|
|
||||||
_client().list_directory("devices")
|
|
||||||
|
|
||||||
|
|
||||||
class TestPutFileText:
|
|
||||||
def test_creates_a_new_file_with_no_sha_when_none_existed(self) -> None:
|
|
||||||
with (
|
|
||||||
_patch_get(_response(404), _response(200)),
|
|
||||||
patch.object(
|
|
||||||
_sync_github.requests,
|
|
||||||
"put",
|
|
||||||
return_value=_response(201),
|
|
||||||
) as put_mock,
|
|
||||||
):
|
|
||||||
_client().put_file_text("devices/pc/food_log.json", "{}", message="m")
|
|
||||||
assert "sha" not in put_mock.call_args.kwargs["json"]
|
|
||||||
|
|
||||||
def test_updates_an_existing_file_by_including_its_sha(self) -> None:
|
|
||||||
with (
|
|
||||||
_patch_get(_response(200, {"sha": "abc123"})),
|
|
||||||
patch.object(
|
|
||||||
_sync_github.requests,
|
|
||||||
"put",
|
|
||||||
return_value=_response(200),
|
|
||||||
) as put_mock,
|
|
||||||
):
|
|
||||||
_client().put_file_text("devices/pc/food_log.json", "{}", message="m")
|
|
||||||
assert put_mock.call_args.kwargs["json"]["sha"] == "abc123"
|
|
||||||
|
|
||||||
def test_treats_a_non_string_sha_field_as_absent(self) -> None:
|
|
||||||
with (
|
|
||||||
_patch_get(_response(200, {"sha": 12345})),
|
|
||||||
patch.object(
|
|
||||||
_sync_github.requests,
|
|
||||||
"put",
|
|
||||||
return_value=_response(200),
|
|
||||||
) as put_mock,
|
|
||||||
):
|
|
||||||
_client().put_file_text("devices/pc/food_log.json", "{}", message="m")
|
|
||||||
assert "sha" not in put_mock.call_args.kwargs["json"]
|
|
||||||
|
|
||||||
def test_raises_repo_not_found_when_checking_sha_on_a_missing_repo(self) -> None:
|
|
||||||
with (
|
|
||||||
_patch_get(_response(404), _response(404)),
|
|
||||||
pytest.raises(
|
|
||||||
RepoNotFoundError,
|
|
||||||
),
|
|
||||||
):
|
|
||||||
_client().put_file_text("devices/pc/food_log.json", "{}", message="m")
|
|
||||||
|
|
||||||
def test_raises_sync_error_when_the_sha_check_itself_fails(self) -> None:
|
|
||||||
with _patch_get(_response(500)), pytest.raises(GitHubSyncError):
|
|
||||||
_client().put_file_text("devices/pc/food_log.json", "{}", message="m")
|
|
||||||
|
|
||||||
def test_raises_sync_error_on_a_put_network_exception(self) -> None:
|
|
||||||
with (
|
|
||||||
_patch_get(_response(404), _response(200)),
|
|
||||||
patch.object(
|
|
||||||
_sync_github.requests,
|
|
||||||
"put",
|
|
||||||
side_effect=requests.ConnectionError("offline"),
|
|
||||||
),
|
|
||||||
pytest.raises(GitHubSyncError),
|
|
||||||
):
|
|
||||||
_client().put_file_text("devices/pc/food_log.json", "{}", message="m")
|
|
||||||
|
|
||||||
def test_raises_sync_error_on_a_put_non_2xx_response(self) -> None:
|
|
||||||
with (
|
|
||||||
_patch_get(_response(404), _response(200)),
|
|
||||||
patch.object(
|
|
||||||
_sync_github.requests,
|
|
||||||
"put",
|
|
||||||
return_value=_response(422),
|
|
||||||
),
|
|
||||||
pytest.raises(GitHubSyncError),
|
|
||||||
):
|
|
||||||
_client().put_file_text("devices/pc/food_log.json", "{}", message="m")
|
|
||||||
@ -1,8 +1,28 @@
|
|||||||
"""Tests for the pure cross-device log-merge logic."""
|
"""Tests for diet_guard's entry <-> crdt_sync.Record adapters.
|
||||||
|
|
||||||
|
``TestUnionById`` through ``TestAlgebraicProperties`` are the exact same
|
||||||
|
behavioral assertions the pre-migration ``_sync_merge.merge_logs`` had --
|
||||||
|
routed through ``daylog_to_log -> crdt_sync.merge_logs -> log_to_daylog``
|
||||||
|
instead, to prove the migration preserves diet_guard's merge semantics
|
||||||
|
exactly, not just "some CRDT library now does something similar."
|
||||||
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from diet_guard._sync_merge import merge_logs
|
import json
|
||||||
|
|
||||||
|
from crdt_sync import merge_logs
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from diet_guard._sync_merge import (
|
||||||
|
_entry_hlc,
|
||||||
|
_legacy_entry_id,
|
||||||
|
daylog_to_log,
|
||||||
|
entry_to_record,
|
||||||
|
log_to_daylog,
|
||||||
|
parse_remote_log,
|
||||||
|
record_to_entry,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _entry(**overrides: object) -> dict[str, object]:
|
def _entry(**overrides: object) -> dict[str, object]:
|
||||||
@ -22,30 +42,35 @@ def _entry(**overrides: object) -> dict[str, object]:
|
|||||||
return entry
|
return entry
|
||||||
|
|
||||||
|
|
||||||
|
def _merge_daylogs(a: dict, b: dict) -> dict:
|
||||||
|
"""Merge two DayLogs through the new crdt_sync-backed pipeline."""
|
||||||
|
return log_to_daylog(merge_logs(daylog_to_log(a), daylog_to_log(b)))
|
||||||
|
|
||||||
|
|
||||||
class TestUnionById:
|
class TestUnionById:
|
||||||
def test_disjoint_logs_union_into_one(self) -> None:
|
def test_disjoint_logs_union_into_one(self) -> None:
|
||||||
a = {"2026-06-22": [_entry(id="a", time="2026-06-22T08:00:00+02:00")]}
|
a = {"2026-06-22": [_entry(id="a", time="2026-06-22T08:00:00+02:00")]}
|
||||||
b = {"2026-06-22": [_entry(id="b", time="2026-06-22T12:00:00+02:00")]}
|
b = {"2026-06-22": [_entry(id="b", time="2026-06-22T12:00:00+02:00")]}
|
||||||
merged = merge_logs(a, b)
|
merged = _merge_daylogs(a, b)
|
||||||
assert {e["id"] for e in merged["2026-06-22"]} == {"a", "b"}
|
assert {e["id"] for e in merged["2026-06-22"]} == {"a", "b"}
|
||||||
|
|
||||||
def test_same_id_in_both_logs_is_not_duplicated(self) -> None:
|
def test_same_id_in_both_logs_is_not_duplicated(self) -> None:
|
||||||
shared = _entry(id="shared")
|
shared = _entry(id="shared")
|
||||||
merged = merge_logs({"2026-06-22": [shared]}, {"2026-06-22": [shared]})
|
merged = _merge_daylogs({"2026-06-22": [shared]}, {"2026-06-22": [shared]})
|
||||||
assert len(merged["2026-06-22"]) == 1
|
assert len(merged["2026-06-22"]) == 1
|
||||||
|
|
||||||
def test_legacy_entries_without_id_dedup_by_time_and_desc(self) -> None:
|
def test_legacy_entries_without_id_dedup_by_time_and_desc(self) -> None:
|
||||||
legacy_a = _entry(id=None, time="2026-06-20T08:00:00+02:00", desc="toast")
|
legacy_a = _entry(id=None, time="2026-06-20T08:00:00+02:00", desc="toast")
|
||||||
legacy_a.pop("id")
|
legacy_a.pop("id")
|
||||||
legacy_b = dict(legacy_a)
|
legacy_b = dict(legacy_a)
|
||||||
merged = merge_logs({"2026-06-20": [legacy_a]}, {"2026-06-20": [legacy_b]})
|
merged = _merge_daylogs({"2026-06-20": [legacy_a]}, {"2026-06-20": [legacy_b]})
|
||||||
assert len(merged["2026-06-20"]) == 1
|
assert len(merged["2026-06-20"]) == 1
|
||||||
|
|
||||||
def test_legacy_and_id_entries_with_different_keys_both_survive(self) -> None:
|
def test_legacy_and_id_entries_with_different_keys_both_survive(self) -> None:
|
||||||
legacy = _entry(time="2026-06-20T08:00:00+02:00", desc="toast")
|
legacy = _entry(time="2026-06-20T08:00:00+02:00", desc="toast")
|
||||||
legacy.pop("id")
|
legacy.pop("id")
|
||||||
with_id = _entry(id="x", time="2026-06-20T09:00:00+02:00", desc="eggs")
|
with_id = _entry(id="x", time="2026-06-20T09:00:00+02:00", desc="eggs")
|
||||||
merged = merge_logs({"2026-06-20": [legacy]}, {"2026-06-20": [with_id]})
|
merged = _merge_daylogs({"2026-06-20": [legacy]}, {"2026-06-20": [with_id]})
|
||||||
assert len(merged["2026-06-20"]) == 2
|
assert len(merged["2026-06-20"]) == 2
|
||||||
|
|
||||||
|
|
||||||
@ -54,11 +79,11 @@ class TestTombstoneWins:
|
|||||||
normal = _entry(id="x", deleted=False)
|
normal = _entry(id="x", deleted=False)
|
||||||
tombstoned = _entry(id="x", deleted=True)
|
tombstoned = _entry(id="x", deleted=True)
|
||||||
|
|
||||||
forward = merge_logs(
|
forward = _merge_daylogs(
|
||||||
{"2026-06-22": [normal]},
|
{"2026-06-22": [normal]},
|
||||||
{"2026-06-22": [tombstoned]},
|
{"2026-06-22": [tombstoned]},
|
||||||
)
|
)
|
||||||
backward = merge_logs(
|
backward = _merge_daylogs(
|
||||||
{"2026-06-22": [tombstoned]},
|
{"2026-06-22": [tombstoned]},
|
||||||
{"2026-06-22": [normal]},
|
{"2026-06-22": [normal]},
|
||||||
)
|
)
|
||||||
@ -68,7 +93,7 @@ class TestTombstoneWins:
|
|||||||
|
|
||||||
def test_two_tombstoned_copies_stay_tombstoned(self) -> None:
|
def test_two_tombstoned_copies_stay_tombstoned(self) -> None:
|
||||||
tombstoned = _entry(id="x", deleted=True)
|
tombstoned = _entry(id="x", deleted=True)
|
||||||
merged = merge_logs(
|
merged = _merge_daylogs(
|
||||||
{"2026-06-22": [tombstoned]},
|
{"2026-06-22": [tombstoned]},
|
||||||
{"2026-06-22": [dict(tombstoned)]},
|
{"2026-06-22": [dict(tombstoned)]},
|
||||||
)
|
)
|
||||||
@ -80,13 +105,13 @@ class TestRebucketingAndOrdering:
|
|||||||
self,
|
self,
|
||||||
) -> None:
|
) -> None:
|
||||||
misfiled = _entry(id="x", time="2026-06-21T23:00:00+02:00")
|
misfiled = _entry(id="x", time="2026-06-21T23:00:00+02:00")
|
||||||
merged = merge_logs({"2026-06-22": [misfiled]}, {})
|
merged = _merge_daylogs({"2026-06-22": [misfiled]}, {})
|
||||||
assert merged == {"2026-06-21": [misfiled]}
|
assert merged == {"2026-06-21": [misfiled]}
|
||||||
|
|
||||||
def test_a_days_entries_are_sorted_oldest_first(self) -> None:
|
def test_a_days_entries_are_sorted_oldest_first(self) -> None:
|
||||||
late = _entry(id="late", time="2026-06-22T20:00:00+02:00")
|
late = _entry(id="late", time="2026-06-22T20:00:00+02:00")
|
||||||
early = _entry(id="early", time="2026-06-22T08:00:00+02:00")
|
early = _entry(id="early", time="2026-06-22T08:00:00+02:00")
|
||||||
merged = merge_logs({"2026-06-22": [late]}, {"2026-06-22": [early]})
|
merged = _merge_daylogs({"2026-06-22": [late]}, {"2026-06-22": [early]})
|
||||||
assert [e["id"] for e in merged["2026-06-22"]] == ["early", "late"]
|
assert [e["id"] for e in merged["2026-06-22"]] == ["early", "late"]
|
||||||
|
|
||||||
|
|
||||||
@ -94,16 +119,96 @@ class TestAlgebraicProperties:
|
|||||||
def test_merge_is_commutative(self) -> None:
|
def test_merge_is_commutative(self) -> None:
|
||||||
a = {"2026-06-22": [_entry(id="a")]}
|
a = {"2026-06-22": [_entry(id="a")]}
|
||||||
b = {"2026-06-22": [_entry(id="b", time="2026-06-22T09:00:00+02:00")]}
|
b = {"2026-06-22": [_entry(id="b", time="2026-06-22T09:00:00+02:00")]}
|
||||||
assert merge_logs(a, b) == merge_logs(b, a)
|
assert _merge_daylogs(a, b) == _merge_daylogs(b, a)
|
||||||
|
|
||||||
def test_merge_is_idempotent(self) -> None:
|
def test_merge_is_idempotent(self) -> None:
|
||||||
canonical = {"2026-06-22": [_entry(id="a")]}
|
canonical = {"2026-06-22": [_entry(id="a")]}
|
||||||
assert merge_logs(canonical, canonical) == canonical
|
assert _merge_daylogs(canonical, canonical) == canonical
|
||||||
|
|
||||||
def test_merging_with_an_empty_log_is_a_no_op(self) -> None:
|
def test_merging_with_an_empty_log_is_a_no_op(self) -> None:
|
||||||
log = {"2026-06-22": [_entry(id="a")]}
|
log = {"2026-06-22": [_entry(id="a")]}
|
||||||
assert merge_logs(log, {}) == log
|
assert _merge_daylogs(log, {}) == log
|
||||||
assert merge_logs({}, log) == log
|
assert _merge_daylogs({}, log) == log
|
||||||
|
|
||||||
def test_merging_two_empty_logs_is_empty(self) -> None:
|
def test_merging_two_empty_logs_is_empty(self) -> None:
|
||||||
assert merge_logs({}, {}) == {}
|
assert _merge_daylogs({}, {}) == {}
|
||||||
|
|
||||||
|
|
||||||
|
class TestEntryHlc:
|
||||||
|
def test_same_entry_always_yields_the_same_hlc(self) -> None:
|
||||||
|
entry = _entry()
|
||||||
|
assert _entry_hlc(entry) == _entry_hlc(dict(entry))
|
||||||
|
|
||||||
|
def test_malformed_time_still_yields_a_valid_hlc(self) -> None:
|
||||||
|
entry = _entry(time="not-a-timestamp")
|
||||||
|
assert _entry_hlc(entry).wall_time_ms == 0
|
||||||
|
|
||||||
|
def test_missing_time_still_yields_a_valid_hlc(self) -> None:
|
||||||
|
entry = _entry()
|
||||||
|
del entry["time"]
|
||||||
|
assert _entry_hlc(entry).wall_time_ms == 0
|
||||||
|
|
||||||
|
|
||||||
|
class TestLegacyEntryId:
|
||||||
|
def test_same_time_and_desc_yields_the_same_id(self) -> None:
|
||||||
|
a = _entry(time="2026-06-20T08:00:00+02:00", desc="toast")
|
||||||
|
b = _entry(time="2026-06-20T08:00:00+02:00", desc="toast", kcal=999.0)
|
||||||
|
assert _legacy_entry_id(a) == _legacy_entry_id(b)
|
||||||
|
|
||||||
|
def test_different_desc_yields_a_different_id(self) -> None:
|
||||||
|
a = _entry(time="2026-06-20T08:00:00+02:00", desc="toast")
|
||||||
|
b = _entry(time="2026-06-20T08:00:00+02:00", desc="eggs")
|
||||||
|
assert _legacy_entry_id(a) != _legacy_entry_id(b)
|
||||||
|
|
||||||
|
|
||||||
|
class TestEntryRecordRoundTrip:
|
||||||
|
def test_round_trip_preserves_all_fields(self) -> None:
|
||||||
|
entry = _entry(id="x")
|
||||||
|
assert record_to_entry(entry_to_record(entry)) == entry
|
||||||
|
|
||||||
|
def test_round_trip_of_a_deleted_entry_preserves_the_tombstone(self) -> None:
|
||||||
|
entry = _entry(id="x", deleted=True)
|
||||||
|
assert record_to_entry(entry_to_record(entry))["deleted"] is True
|
||||||
|
|
||||||
|
def test_legacy_entry_gets_a_derived_id_on_round_trip(self) -> None:
|
||||||
|
entry = _entry(time="2026-06-20T08:00:00+02:00", desc="toast")
|
||||||
|
entry.pop("id")
|
||||||
|
round_tripped = record_to_entry(entry_to_record(entry))
|
||||||
|
assert round_tripped["id"] == _legacy_entry_id(entry)
|
||||||
|
|
||||||
|
|
||||||
|
class TestParseRemoteLog:
|
||||||
|
def test_parses_new_format_wire_content(self) -> None:
|
||||||
|
entry = _entry(id="x")
|
||||||
|
pushed = {"x": entry_to_record(entry).to_dict()}
|
||||||
|
log = parse_remote_log(_dumps(pushed))
|
||||||
|
assert log["x"].id == "x"
|
||||||
|
|
||||||
|
def test_parses_old_daylog_format_for_backward_compatibility(self) -> None:
|
||||||
|
entry = _entry(id="x")
|
||||||
|
old_format = {"2026-06-22": [entry]}
|
||||||
|
log = parse_remote_log(_dumps(old_format))
|
||||||
|
assert log["x"].id == "x"
|
||||||
|
|
||||||
|
def test_empty_object_parses_as_empty_log(self) -> None:
|
||||||
|
assert parse_remote_log("{}") == {}
|
||||||
|
|
||||||
|
def test_non_object_top_level_raises_type_error(self) -> None:
|
||||||
|
with pytest.raises(TypeError):
|
||||||
|
parse_remote_log("[1, 2, 3]")
|
||||||
|
|
||||||
|
def test_old_format_day_not_a_list_raises_type_error(self) -> None:
|
||||||
|
with pytest.raises(TypeError):
|
||||||
|
parse_remote_log(_dumps({"2026-06-22": "not-a-list"}))
|
||||||
|
|
||||||
|
def test_old_format_entry_not_an_object_raises_type_error(self) -> None:
|
||||||
|
with pytest.raises(TypeError):
|
||||||
|
parse_remote_log(_dumps({"2026-06-22": ["not-a-dict"]}))
|
||||||
|
|
||||||
|
def test_invalid_json_raises(self) -> None:
|
||||||
|
with pytest.raises(json.JSONDecodeError):
|
||||||
|
parse_remote_log("not json{{{")
|
||||||
|
|
||||||
|
|
||||||
|
def _dumps(data: object) -> str:
|
||||||
|
return json.dumps(data)
|
||||||
|
|||||||
@ -5,6 +5,7 @@ description = "Tkinter/systemd log-to-unlock meal gate with calorie/macro budget
|
|||||||
requires-python = ">=3.10"
|
requires-python = ">=3.10"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.1.0#subdirectory=gatelock",
|
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.1.0#subdirectory=gatelock",
|
||||||
|
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.1.0#subdirectory=crdt-sync",
|
||||||
"requests>=2.31.0",
|
"requests>=2.31.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
@ -39,8 +40,8 @@ fixable = ["ALL"]
|
|||||||
unfixable = []
|
unfixable = []
|
||||||
|
|
||||||
[tool.ruff.lint.per-file-ignores]
|
[tool.ruff.lint.per-file-ignores]
|
||||||
"**/tests/**/*.py" = ["ARG", "D", "PLC0415", "PLR2004", "S101", "SLF001"]
|
"**/tests/**/*.py" = ["ARG", "D", "PLC0415", "PLR2004", "S101", "S107", "SLF001"]
|
||||||
"**/test_*.py" = ["ARG", "D", "PLC0415", "PLR2004", "S101", "SLF001"]
|
"**/test_*.py" = ["ARG", "D", "PLC0415", "PLR2004", "S101", "S107", "SLF001"]
|
||||||
|
|
||||||
[tool.ruff.lint.pydocstyle]
|
[tool.ruff.lint.pydocstyle]
|
||||||
convention = "google"
|
convention = "google"
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user