mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-29 19:03:34 +01:00
Compare commits
No commits in common. "e6812f7b4f840b5d5a8bcfa53b29b10ce333c93b" and "06999274d7ca164781db32a54bffd9df9947b58b" have entirely different histories.
e6812f7b4f
...
06999274d7
@ -93,9 +93,6 @@ 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
|
|
||||||
- mcp
|
|
||||||
- pydantic
|
|
||||||
# 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)
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: dart-collect-coverage
|
name: dart-collect-coverage
|
||||||
description: Collect coverage using the coverage package and create an LCOV report
|
description: Collect coverage using the coverage packge and create an LCOV report
|
||||||
metadata:
|
metadata:
|
||||||
model: models/gemini-3.1-pro-preview
|
model: models/gemini-3.1-pro-preview
|
||||||
last_modified: Fri, 24 Apr 2026 15:14:32 GMT
|
last_modified: Fri, 24 Apr 2026 15:14:32 GMT
|
||||||
|
|||||||
@ -98,7 +98,7 @@ void processData() {
|
|||||||
// Suppress for a specific line
|
// Suppress for a specific line
|
||||||
// ignore: invalid_assignment
|
// ignore: invalid_assignment
|
||||||
int x = '';
|
int x = '';
|
||||||
|
|
||||||
const y = 10; // ignore: constant_identifier_names
|
const y = 10; // ignore: constant_identifier_names
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|||||||
@ -281,19 +281,19 @@ Future<File> downloadAsset(
|
|||||||
) async {
|
) async {
|
||||||
final fileName = targetOS.dylibFileName('native_add_${targetOS.name}_${targetArchitecture.name}');
|
final fileName = targetOS.dylibFileName('native_add_${targetOS.name}_${targetArchitecture.name}');
|
||||||
final uri = downloadUri(fileName);
|
final uri = downloadUri(fileName);
|
||||||
|
|
||||||
final client = HttpClient()..findProxy = HttpClient.findProxyFromEnvironment;
|
final client = HttpClient()..findProxy = HttpClient.findProxyFromEnvironment;
|
||||||
final request = await client.getUrl(uri);
|
final request = await client.getUrl(uri);
|
||||||
final response = await request.close();
|
final response = await request.close();
|
||||||
|
|
||||||
if (response.statusCode != 200) {
|
if (response.statusCode != 200) {
|
||||||
throw ArgumentError('Download target $uri failed: Code ${response.statusCode}');
|
throw ArgumentError('Download target $uri failed: Code ${response.statusCode}');
|
||||||
}
|
}
|
||||||
|
|
||||||
final targetFile = File.fromUri(outputDir.uri.resolve(fileName));
|
final targetFile = File.fromUri(outputDir.uri.resolve(fileName));
|
||||||
await targetFile.create(recursive: true);
|
await targetFile.create(recursive: true);
|
||||||
await response.pipe(targetFile.openWrite());
|
await response.pipe(targetFile.openWrite());
|
||||||
|
|
||||||
return targetFile;
|
return targetFile;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -41,7 +41,7 @@ Use the Dart/Flutter MCP server tools to interactively explore and manipulate th
|
|||||||
|
|
||||||
## Test Authoring Guidelines
|
## Test Authoring Guidelines
|
||||||
|
|
||||||
Structure integration tests using the `flutter_test` API paradigm.
|
Structure integration tests using the `flutter_test` API paradigm.
|
||||||
|
|
||||||
- Create a dedicated `integration_test/` directory at the project root.
|
- Create a dedicated `integration_test/` directory at the project root.
|
||||||
- Name all test files using the `<name>_test.dart` convention.
|
- Name all test files using the `<name>_test.dart` convention.
|
||||||
@ -63,7 +63,7 @@ Execute tests using the `flutter drive` command. Require a host driver script lo
|
|||||||
`flutter drive --driver=test_driver/integration_test.dart --target=integration_test/app_test.dart -d chrome`
|
`flutter drive --driver=test_driver/integration_test.dart --target=integration_test/app_test.dart -d chrome`
|
||||||
- **If testing headless web:** Run with `-d web-server`.
|
- **If testing headless web:** Run with `-d web-server`.
|
||||||
- **If testing on Android (Local):** Run `flutter drive --driver=test_driver/integration_test.dart --target=integration_test/app_test.dart`.
|
- **If testing on Android (Local):** Run `flutter drive --driver=test_driver/integration_test.dart --target=integration_test/app_test.dart`.
|
||||||
- **If testing on Firebase Test Lab (Android):**
|
- **If testing on Firebase Test Lab (Android):**
|
||||||
1. Build debug APK: `flutter build apk --debug`
|
1. Build debug APK: `flutter build apk --debug`
|
||||||
2. Build test APK: `./gradlew app:assembleAndroidTest`
|
2. Build test APK: `./gradlew app:assembleAndroidTest`
|
||||||
3. Upload both APKs to the Firebase Test Lab console.
|
3. Upload both APKs to the Firebase Test Lab console.
|
||||||
|
|||||||
@ -15,7 +15,7 @@ metadata:
|
|||||||
|
|
||||||
## Preview Guidelines
|
## Preview Guidelines
|
||||||
|
|
||||||
Use the Flutter Widget Previewer to render widgets in real-time, isolated from the full application context.
|
Use the Flutter Widget Previewer to render widgets in real-time, isolated from the full application context.
|
||||||
|
|
||||||
- **Target Elements:** Apply the `@Preview` annotation to top-level functions, static methods within a class, or public widget constructors/factories that have no required arguments and return a `Widget` or `WidgetBuilder`.
|
- **Target Elements:** Apply the `@Preview` annotation to top-level functions, static methods within a class, or public widget constructors/factories that have no required arguments and return a `Widget` or `WidgetBuilder`.
|
||||||
- **Imports:** Always import `package:flutter/widget_previews.dart` to access the preview annotations.
|
- **Imports:** Always import `package:flutter/widget_previews.dart` to access the preview annotations.
|
||||||
@ -98,7 +98,7 @@ final class TransformativePreview extends Preview {
|
|||||||
Preview transform() {
|
Preview transform() {
|
||||||
final originalPreview = super.transform();
|
final originalPreview = super.transform();
|
||||||
final builder = originalPreview.toBuilder();
|
final builder = originalPreview.toBuilder();
|
||||||
|
|
||||||
builder
|
builder
|
||||||
..name = 'Transformed - ${originalPreview.name}'
|
..name = 'Transformed - ${originalPreview.name}'
|
||||||
..theme = _themeBuilder;
|
..theme = _themeBuilder;
|
||||||
|
|||||||
@ -50,10 +50,10 @@ Copy the following checklist to track progress when implementing a new widget te
|
|||||||
Apply the following conditional logic based on the type of interaction or state change being tested:
|
Apply the following conditional logic based on the type of interaction or state change being tested:
|
||||||
|
|
||||||
* **If testing static rendering:** Call `await tester.pumpWidget()` once, then immediately run `expect()` assertions.
|
* **If testing static rendering:** Call `await tester.pumpWidget()` once, then immediately run `expect()` assertions.
|
||||||
* **If testing standard state changes (e.g., button taps):**
|
* **If testing standard state changes (e.g., button taps):**
|
||||||
1. Call `await tester.tap(finder)`.
|
1. Call `await tester.tap(finder)`.
|
||||||
2. Call `await tester.pump()` to trigger a single frame rebuild.
|
2. Call `await tester.pump()` to trigger a single frame rebuild.
|
||||||
* **If testing animations, transitions, or asynchronous UI updates:**
|
* **If testing animations, transitions, or asynchronous UI updates:**
|
||||||
1. Trigger the action (e.g., `await tester.drag(finder, Offset(500, 0))`).
|
1. Trigger the action (e.g., `await tester.drag(finder, Offset(500, 0))`).
|
||||||
2. Call `await tester.pumpAndSettle()` to repeatedly pump frames until no more frames are scheduled (animation completes).
|
2. Call `await tester.pumpAndSettle()` to repeatedly pump frames until no more frames are scheduled (animation completes).
|
||||||
* **If testing text input:** Call `await tester.enterText(textFieldFinder, 'Input string')`.
|
* **If testing text input:** Call `await tester.enterText(textFieldFinder, 'Input string')`.
|
||||||
|
|||||||
@ -83,13 +83,13 @@ class ApiClient {
|
|||||||
// 2. Repository (Single source of truth, returns Domain Model)
|
// 2. Repository (Single source of truth, returns Domain Model)
|
||||||
class UserRepository {
|
class UserRepository {
|
||||||
UserRepository({required ApiClient apiClient}) : _apiClient = apiClient;
|
UserRepository({required ApiClient apiClient}) : _apiClient = apiClient;
|
||||||
|
|
||||||
final ApiClient _apiClient;
|
final ApiClient _apiClient;
|
||||||
User? _cachedUser;
|
User? _cachedUser;
|
||||||
|
|
||||||
Future<User> getUser(String id) async {
|
Future<User> getUser(String id) async {
|
||||||
if (_cachedUser != null) return _cachedUser!;
|
if (_cachedUser != null) return _cachedUser!;
|
||||||
|
|
||||||
final apiModel = await _apiClient.fetchUser(id);
|
final apiModel = await _apiClient.fetchUser(id);
|
||||||
_cachedUser = User(id: apiModel.id, name: apiModel.fullName); // Transform to Domain Model
|
_cachedUser = User(id: apiModel.id, name: apiModel.fullName); // Transform to Domain Model
|
||||||
return _cachedUser!;
|
return _cachedUser!;
|
||||||
@ -102,7 +102,7 @@ class UserRepository {
|
|||||||
```dart
|
```dart
|
||||||
// 3. ViewModel (State management and presentation logic)
|
// 3. ViewModel (State management and presentation logic)
|
||||||
class ProfileViewModel extends ChangeNotifier {
|
class ProfileViewModel extends ChangeNotifier {
|
||||||
ProfileViewModel({required UserRepository userRepository})
|
ProfileViewModel({required UserRepository userRepository})
|
||||||
: _userRepository = userRepository;
|
: _userRepository = userRepository;
|
||||||
|
|
||||||
final UserRepository _userRepository;
|
final UserRepository _userRepository;
|
||||||
@ -140,7 +140,7 @@ class ProfileView extends StatelessWidget {
|
|||||||
if (viewModel.isLoading) {
|
if (viewModel.isLoading) {
|
||||||
return const Center(child: CircularProgressIndicator());
|
return const Center(child: CircularProgressIndicator());
|
||||||
}
|
}
|
||||||
|
|
||||||
final user = viewModel.user;
|
final user = viewModel.user;
|
||||||
if (user == null) {
|
if (user == null) {
|
||||||
return const Center(child: Text('User not found'));
|
return const Center(child: Text('User not found'));
|
||||||
|
|||||||
@ -14,7 +14,7 @@ metadata:
|
|||||||
|
|
||||||
## Constraint Violation Diagnostics
|
## Constraint Violation Diagnostics
|
||||||
|
|
||||||
Flutter layout operates on a strict rule: **Constraints go down. Sizes go up. Parent sets position.** Layout errors occur when this negotiation fails, typically due to unbounded constraints or unconstrained children.
|
Flutter layout operates on a strict rule: **Constraints go down. Sizes go up. Parent sets position.** Layout errors occur when this negotiation fails, typically due to unbounded constraints or unconstrained children.
|
||||||
|
|
||||||
Diagnose layout failures using the following error signatures:
|
Diagnose layout failures using the following error signatures:
|
||||||
|
|
||||||
@ -85,7 +85,7 @@ Column(
|
|||||||
Row(
|
Row(
|
||||||
children: [
|
children: [
|
||||||
const Icon(Icons.search),
|
const Icon(Icons.search),
|
||||||
TextField(),
|
TextField(),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|||||||
@ -48,7 +48,7 @@ Use this conditional workflow when retrieving and parsing JSON from a network re
|
|||||||
- [ ] Decode and map the JSON to the model.
|
- [ ] Decode and map the JSON to the model.
|
||||||
|
|
||||||
1. **Execute Request**: Use the `http` package to perform the network call.
|
1. **Execute Request**: Use the `http` package to perform the network call.
|
||||||
2. **Validate Response**:
|
2. **Validate Response**:
|
||||||
- If `response.statusCode == 200` (or 201 for POST), proceed to parsing.
|
- If `response.statusCode == 200` (or 201 for POST), proceed to parsing.
|
||||||
- If the status code indicates failure, throw an `Exception`.
|
- If the status code indicates failure, throw an `Exception`.
|
||||||
3. **Determine Parsing Strategy**:
|
3. **Determine Parsing Strategy**:
|
||||||
@ -81,7 +81,7 @@ class User {
|
|||||||
'id': int id,
|
'id': int id,
|
||||||
'name': String name,
|
'name': String name,
|
||||||
'email': String email,
|
'email': String email,
|
||||||
} =>
|
} =>
|
||||||
User(
|
User(
|
||||||
id: id,
|
id: id,
|
||||||
name: name,
|
name: name,
|
||||||
|
|||||||
@ -16,7 +16,7 @@ metadata:
|
|||||||
|
|
||||||
## Core Concepts
|
## Core Concepts
|
||||||
|
|
||||||
Use the `go_router` package for declarative routing in Flutter. It provides a robust API for complex routing scenarios, deep linking, and nested navigation.
|
Use the `go_router` package for declarative routing in Flutter. It provides a robust API for complex routing scenarios, deep linking, and nested navigation.
|
||||||
|
|
||||||
- **GoRouter**: The central configuration object defining the application's route tree.
|
- **GoRouter**: The central configuration object defining the application's route tree.
|
||||||
- **GoRoute**: A standard route mapping a URL path to a Flutter screen.
|
- **GoRoute**: A standard route mapping a URL path to a Flutter screen.
|
||||||
@ -120,7 +120,7 @@ Configure the native platforms to intercept specific URLs and route them into th
|
|||||||
```
|
```
|
||||||
|
|
||||||
### If configuring for iOS:
|
### If configuring for iOS:
|
||||||
1. **Modify `Info.plist`**: Opt-in to Flutter's default deep link handler.
|
1. **Modify `Info.plist`**: Opt-in to Flutter's default deep link handler.
|
||||||
*Note: If using a third-party deep linking plugin (e.g., `app_links`), set this to `NO` to prevent conflicts.*
|
*Note: If using a third-party deep linking plugin (e.g., `app_links`), set this to `NO` to prevent conflicts.*
|
||||||
```xml
|
```xml
|
||||||
<key>FlutterDeepLinkingEnabled</key>
|
<key>FlutterDeepLinkingEnabled</key>
|
||||||
|
|||||||
@ -190,8 +190,8 @@ class GreetingWidget extends StatelessWidget {
|
|||||||
final int notificationCount;
|
final int notificationCount;
|
||||||
|
|
||||||
const GreetingWidget({
|
const GreetingWidget({
|
||||||
super.key,
|
super.key,
|
||||||
required this.userName,
|
required this.userName,
|
||||||
required this.notificationCount,
|
required this.notificationCount,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -43,7 +43,7 @@ Execute HTTP operations and map responses to strongly typed Dart objects.
|
|||||||
* **URIs:** Always parse URL strings using `Uri.parse('your_url')`.
|
* **URIs:** Always parse URL strings using `Uri.parse('your_url')`.
|
||||||
* **Headers:** Inject authorization and content-type headers via the `headers` parameter map. Use `HttpHeaders.authorizationHeader` for auth tokens.
|
* **Headers:** Inject authorization and content-type headers via the `headers` parameter map. Use `HttpHeaders.authorizationHeader` for auth tokens.
|
||||||
* **Payloads:** For POST and PUT requests, encode the body using `jsonEncode()` from `dart:convert`.
|
* **Payloads:** For POST and PUT requests, encode the body using `jsonEncode()` from `dart:convert`.
|
||||||
* **Status Validation:** Evaluate `response.statusCode`. Treat `200 OK` (GET/PUT/DELETE) and `201 CREATED` (POST) as success.
|
* **Status Validation:** Evaluate `response.statusCode`. Treat `200 OK` (GET/PUT/DELETE) and `201 CREATED` (POST) as success.
|
||||||
* **Error Handling:** Throw explicit exceptions for non-success status codes. Never return `null` on failure, as this prevents `FutureBuilder` from triggering its error state and causes infinite loading indicators.
|
* **Error Handling:** Throw explicit exceptions for non-success status codes. Never return `null` on failure, as this prevents `FutureBuilder` from triggering its error state and causes infinite loading indicators.
|
||||||
* **Deserialization:** Parse the raw string using `jsonDecode(response.body)` and map it to a custom Dart object using a factory constructor (e.g., `fromJson`).
|
* **Deserialization:** Parse the raw string using `jsonDecode(response.body)` and map it to a custom Dart object using a factory constructor (e.g., `fromJson`).
|
||||||
|
|
||||||
@ -164,7 +164,7 @@ class _PhotoGalleryState extends State<PhotoGallery> {
|
|||||||
} else if (snapshot.hasError) {
|
} else if (snapshot.hasError) {
|
||||||
return Center(child: Text('Error: ${snapshot.error}'));
|
return Center(child: Text('Error: ${snapshot.error}'));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Default loading state
|
// Default loading state
|
||||||
return const Center(child: CircularProgressIndicator());
|
return const Center(child: CircularProgressIndicator());
|
||||||
},
|
},
|
||||||
|
|||||||
@ -4,7 +4,6 @@ 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';
|
||||||
@ -13,6 +12,7 @@ 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,7 +8,6 @@ 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';
|
||||||
@ -142,7 +141,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 = crdt_sync.GitHubClient(
|
final client = GitHubClient(
|
||||||
owner: settings.owner,
|
owner: settings.owner,
|
||||||
repo: settings.repo,
|
repo: settings.repo,
|
||||||
token: settings.token,
|
token: settings.token,
|
||||||
@ -190,7 +189,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 = crdt_sync.GitHubClient(
|
final client = GitHubClient(
|
||||||
owner: settings.owner,
|
owner: settings.owner,
|
||||||
repo: settings.repo,
|
repo: settings.repo,
|
||||||
token: settings.token,
|
token: settings.token,
|
||||||
|
|||||||
@ -1,179 +1,69 @@
|
|||||||
/// Entry <-> crdt_sync.Record adapters for diet_guard_app's cross-device
|
/// Pure log-merge logic for diet_guard's cross-device sync.
|
||||||
/// sync.
|
|
||||||
///
|
///
|
||||||
/// This app's own local storage format is unchanged -- only the
|
/// No I/O here -- this module is unit-testable purely on in-memory [DayLog]
|
||||||
/// GitHub-synced wire format and the cross-device merge algorithm now go
|
/// values. Mirrored test-for-test against the Python original
|
||||||
/// through `crdt_sync`'s `Record`/`Log`/`Hlc` primitives, the same ones the
|
/// (`diet_guard/_sync_merge.py`), so the merge algorithm canonically agrees
|
||||||
/// PC (`diet_guard/_sync_merge.py`) and every other kuhy app that syncs
|
/// on both sides of the sync.
|
||||||
/// 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';
|
||||||
|
|
||||||
const _syncDeviceId = 'phone';
|
/// A dedup key: `('id', <uuid>)` for any entry with one, else
|
||||||
|
/// `('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);
|
||||||
|
|
||||||
/// Derives a deterministic [Hlc] for [entry] from its own `time` field.
|
_MergeKey _entryKey(FoodEntry entry) {
|
||||||
|
final id = entry.id;
|
||||||
|
if (id != null && id.isNotEmpty) return ('id', id);
|
||||||
|
return ('legacy', (entry.time, entry.desc));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns true if [candidate] should replace [existing] for one key.
|
||||||
///
|
///
|
||||||
/// The same entry always yields the same Hlc regardless of when this runs
|
/// A tombstone always wins over a non-tombstoned copy of the same entry --
|
||||||
/// -- entries are immutable after creation, so there's no real "now" to
|
/// deletion is sticky, so a stale pre-undo copy pulled from another device
|
||||||
/// stamp, just the birth-time already recorded on the entry itself.
|
/// can never resurrect something the user explicitly removed. Otherwise,
|
||||||
/// Malformed/missing `time` still yields a valid (if early-sorting) Hlc
|
/// keep whichever copy was seen first: two copies of the same id are
|
||||||
/// rather than throwing -- this only affects tie-breaking between
|
/// expected to be identical in their macros/desc (the body is never mutated
|
||||||
/// otherwise-identical copies of the same id, never whether the entry
|
/// after creation, only `deleted`/`hmac`), so which one survives does not
|
||||||
/// survives a merge.
|
/// change the merged result's content.
|
||||||
Hlc entryHlc(FoodEntry entry) {
|
bool _tombstoneWins(FoodEntry candidate, FoodEntry existing) =>
|
||||||
final wallTimeMs = DateTime.tryParse(entry.time)?.millisecondsSinceEpoch ?? 0;
|
candidate.deleted && !existing.deleted;
|
||||||
return Hlc.newTick(_syncDeviceId, wallTimeMsOverride: wallTimeMs);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Deterministic id for a pre-`id` legacy entry, from `(time, desc)`.
|
/// Returns the union of [local] and [remote], tombstones winning by id.
|
||||||
///
|
///
|
||||||
/// Two devices holding the same legacy entry independently derive the same
|
/// Commutative and idempotent: `mergeLogs(a, b) == mergeLogs(b, a)` and
|
||||||
/// id without communicating, so they merge as one record instead of two --
|
/// `mergeLogs(x, x) == x` (for an `x` with no duplicate keys), so pull-order
|
||||||
/// the same guarantee the old `(time, desc)` dedup key gave, just expressed
|
/// between devices never matters and a repeated sync tick is a no-op. Each
|
||||||
/// as a real id going forward.
|
/// entry is re-bucketed under its own `time`'s date rather than the date key
|
||||||
String legacyEntryId(FoodEntry entry) {
|
/// it arrived under, so a merge can't silently leave an entry filed under
|
||||||
final key = '${entry.time}|${entry.desc}';
|
/// the wrong day.
|
||||||
final digest = sha256.convert(utf8.encode(key)).toString().substring(0, 32);
|
DayLog mergeLogs(DayLog local, DayLog remote) {
|
||||||
return 'legacy-$digest';
|
final byKey = <_MergeKey, FoodEntry>{};
|
||||||
}
|
for (final dayLog in [local, remote]) {
|
||||||
|
for (final entries in dayLog.values) {
|
||||||
/// Converts one [FoodEntry] to a crdt_sync [Record].
|
for (final entry in entries) {
|
||||||
Record entryToRecord(FoodEntry entry) {
|
final key = _entryKey(entry);
|
||||||
final id = (entry.id != null && entry.id!.isNotEmpty)
|
final existing = byKey[key];
|
||||||
? entry.id!
|
if (existing == null || _tombstoneWins(entry, existing)) {
|
||||||
: legacyEntryId(entry);
|
byKey[key] = entry;
|
||||||
final hlc = entryHlc(entry);
|
}
|
||||||
final body = entry.toSyncJson()
|
}
|
||||||
..remove('id')
|
|
||||||
..remove('deleted');
|
|
||||||
return Record(
|
|
||||||
id: id,
|
|
||||||
fields: {'body': (body, hlc)},
|
|
||||||
deleted: entry.deleted,
|
|
||||||
deletedHlc: entry.deleted ? hlc : null,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Converts a merged crdt_sync [Log] back into [DayLog] shape.
|
final merged = <String, List<FoodEntry>>{};
|
||||||
///
|
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;
|
||||||
daylog.putIfAbsent(dateKey, () => []).add(entry);
|
merged.putIfAbsent(dateKey, () => []).add(entry);
|
||||||
}
|
}
|
||||||
for (final entries in daylog.values) {
|
for (final entries in merged.values) {
|
||||||
entries.sort((a, b) => a.time.compareTo(b.time));
|
entries.sort((a, b) => a.time.compareTo(b.time));
|
||||||
}
|
}
|
||||||
return daylog;
|
return merged;
|
||||||
}
|
|
||||||
|
|
||||||
/// 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,19 +1,21 @@
|
|||||||
/// 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 via
|
/// Pulls every other device's pushed log from GitHub-backed dumb storage
|
||||||
/// crdt_sync's shared transport ([GitHubClient]/[syncLog]), merges with the
|
/// ([GitHubClient]), merges with the local log ([mergeLogs]), rebuilds the
|
||||||
/// local log via crdt_sync's shared CRDT scheme (`sync_merge.dart` adapts
|
/// food bank, and pushes this device's own merged log back up. A **new**
|
||||||
/// [FoodEntry]s to/from [Record]), rebuilds the food bank, and pushes this
|
/// implementation, not a port of `~/todo`'s CRDT-based sync (this app has no
|
||||||
/// device's own merged log back up in the new Record-based wire format. One
|
/// CRDT layer) -- a Dart twin of the same pull-merge-rebuild-push sequence
|
||||||
/// phone-specific step, with no PC-side equivalent: a pulled copy of an
|
/// as `diet_guard/_sync.py`, plus one phone-specific step: a pulled copy of
|
||||||
/// entry never carries `imagePath` (stripped before push, meaningless on
|
/// an 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 'package:crdt_sync/crdt_sync.dart';
|
import 'dart:convert';
|
||||||
|
|
||||||
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';
|
||||||
|
|
||||||
@ -25,35 +27,53 @@ 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
|
||||||
/// [GitHubSyncError] from the client for the caller (auto-sync / the manual
|
/// [GitHubApiException] from the client for the caller (auto-sync / the
|
||||||
/// "Sync now" action) to decide how to report.
|
/// manual "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);
|
||||||
|
|
||||||
final mergedLog = await syncLog(
|
var merged = local;
|
||||||
client: client,
|
for (final deviceId in await client.listEntryNames(_devicesDir)) {
|
||||||
deviceId: phoneDeviceId,
|
if (deviceId == phoneDeviceId) continue;
|
||||||
pathPrefix: _devicesDir,
|
final text = await client.getFileText(_deviceLogPath(deviceId));
|
||||||
localLog: dayLogToLog(local),
|
if (text == null) continue;
|
||||||
encode: encodeLogForPush,
|
final remoteLog = _decodeRemoteLog(text);
|
||||||
decode: parseRemoteLog,
|
if (remoteLog == null) continue;
|
||||||
filename: 'food_log.json',
|
merged = mergeLogs(merged, remoteLog);
|
||||||
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) {
|
||||||
@ -89,3 +109,38 @@ 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,15 +57,6 @@ 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:
|
||||||
@ -75,7 +66,7 @@ packages:
|
|||||||
source: hosted
|
source: hosted
|
||||||
version: "0.3.5+2"
|
version: "0.3.5+2"
|
||||||
crypto:
|
crypto:
|
||||||
dependency: "direct main"
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: crypto
|
name: crypto
|
||||||
sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
|
sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
|
||||||
|
|||||||
@ -8,12 +8,6 @@ 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
|
||||||
|
|||||||
@ -976,7 +976,7 @@ void main() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
testWidgets(
|
testWidgets(
|
||||||
'_formatDay falls back to raw key for an unparsable date (line 245)',
|
'_formatDay falls back to raw key for an unparseable date (line 245)',
|
||||||
(tester) async {
|
(tester) async {
|
||||||
await tester.runAsync(() async {
|
await tester.runAsync(() async {
|
||||||
// The day key is e.time.substring(0, 10). Writing an entry whose
|
// The day key is e.time.substring(0, 10). Writing an entry whose
|
||||||
|
|||||||
@ -65,13 +65,6 @@ 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);
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -94,13 +87,6 @@ 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,13 +150,6 @@ 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 {
|
||||||
@ -334,13 +327,6 @@ 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
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -82,7 +82,7 @@ void main() {
|
|||||||
expect(AppSettingsService.dailyKcalGoal, 2200);
|
expect(AppSettingsService.dailyKcalGoal, 2200);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('keeps default 2200 on unparsable JSON', () async {
|
test('keeps default 2200 on unparseable JSON', () async {
|
||||||
await File(
|
await File(
|
||||||
'${tempDir.path}/app_settings.json',
|
'${tempDir.path}/app_settings.json',
|
||||||
).writeAsString('not json at all');
|
).writeAsString('not json at all');
|
||||||
|
|||||||
@ -1,15 +1,8 @@
|
|||||||
// Table-driven mergeLogs() tests. `union by id` through `algebraic
|
// Table-driven `mergeLogs()` tests mirroring `test_sync_merge.py` exactly
|
||||||
// properties` are the exact same assertions the pre-migration
|
// (same cases, same expected outcomes), so both implementations are provably
|
||||||
// `sync_merge.mergeLogs` had -- routed through `dayLogToLog ->
|
// testing the same algorithm.
|
||||||
// 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';
|
||||||
|
|
||||||
@ -31,9 +24,6 @@ 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', () {
|
||||||
@ -43,13 +33,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 = _mergeDaylogs(a, b);
|
final merged = mergeLogs(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 = _mergeDaylogs(
|
final merged = mergeLogs(
|
||||||
{
|
{
|
||||||
'2026-06-22': [shared],
|
'2026-06-22': [shared],
|
||||||
},
|
},
|
||||||
@ -71,7 +61,7 @@ void main() {
|
|||||||
time: '2026-06-20T08:00:00',
|
time: '2026-06-20T08:00:00',
|
||||||
desc: 'toast',
|
desc: 'toast',
|
||||||
);
|
);
|
||||||
final merged = _mergeDaylogs(
|
final merged = mergeLogs(
|
||||||
{
|
{
|
||||||
'2026-06-20': [legacyA],
|
'2026-06-20': [legacyA],
|
||||||
},
|
},
|
||||||
@ -89,7 +79,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 = _mergeDaylogs(
|
final merged = mergeLogs(
|
||||||
{
|
{
|
||||||
'2026-06-20': [legacy],
|
'2026-06-20': [legacy],
|
||||||
},
|
},
|
||||||
@ -106,7 +96,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 = _mergeDaylogs(
|
final forward = mergeLogs(
|
||||||
{
|
{
|
||||||
'2026-06-22': [normal],
|
'2026-06-22': [normal],
|
||||||
},
|
},
|
||||||
@ -114,7 +104,7 @@ void main() {
|
|||||||
'2026-06-22': [tombstoned],
|
'2026-06-22': [tombstoned],
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
final backward = _mergeDaylogs(
|
final backward = mergeLogs(
|
||||||
{
|
{
|
||||||
'2026-06-22': [tombstoned],
|
'2026-06-22': [tombstoned],
|
||||||
},
|
},
|
||||||
@ -129,7 +119,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 = _mergeDaylogs(
|
final merged = mergeLogs(
|
||||||
{
|
{
|
||||||
'2026-06-22': [tombstoned],
|
'2026-06-22': [tombstoned],
|
||||||
},
|
},
|
||||||
@ -146,7 +136,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 = _mergeDaylogs({
|
final merged = mergeLogs({
|
||||||
'2026-06-22': [misfiled],
|
'2026-06-22': [misfiled],
|
||||||
}, {});
|
}, {});
|
||||||
expect(merged.keys, ['2026-06-21']);
|
expect(merged.keys, ['2026-06-21']);
|
||||||
@ -158,8 +148,10 @@ 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 = _mergeDaylogs({
|
final merged = mergeLogs({
|
||||||
'2026-06-22': [short],
|
'2026-06-22': [short],
|
||||||
}, {});
|
}, {});
|
||||||
expect(merged.keys, ['2026']);
|
expect(merged.keys, ['2026']);
|
||||||
@ -169,7 +161,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 = _mergeDaylogs(
|
final merged = mergeLogs(
|
||||||
{
|
{
|
||||||
'2026-06-22': [late],
|
'2026-06-22': [late],
|
||||||
},
|
},
|
||||||
@ -192,8 +184,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 = _mergeDaylogs(a, b);
|
final ab = mergeLogs(a, b);
|
||||||
final ba = _mergeDaylogs(b, a);
|
final ba = mergeLogs(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(),
|
||||||
@ -204,7 +196,7 @@ void main() {
|
|||||||
final canonical = {
|
final canonical = {
|
||||||
'2026-06-22': [_entry(id: 'a')],
|
'2026-06-22': [_entry(id: 'a')],
|
||||||
};
|
};
|
||||||
final merged = _mergeDaylogs(canonical, canonical);
|
final merged = mergeLogs(canonical, canonical);
|
||||||
expect(merged['2026-06-22']!.map((e) => e.id).toList(), ['a']);
|
expect(merged['2026-06-22']!.map((e) => e.id).toList(), ['a']);
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -212,103 +204,12 @@ void main() {
|
|||||||
final log = {
|
final log = {
|
||||||
'2026-06-22': [_entry(id: 'a')],
|
'2026-06-22': [_entry(id: 'a')],
|
||||||
};
|
};
|
||||||
expect(_mergeDaylogs(log, {}).keys, log.keys);
|
expect(mergeLogs(log, {}).keys, log.keys);
|
||||||
expect(_mergeDaylogs({}, log).keys, log.keys);
|
expect(mergeLogs({}, log).keys, log.keys);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('merging two empty logs is empty', () {
|
test('merging two empty logs is empty', () {
|
||||||
expect(_mergeDaylogs({}, {}), isEmpty);
|
expect(mergeLogs({}, {}), 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,9 +26,8 @@ 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 via crdt_sync's [GitHubClient]: list `devices`,
|
/// the calls [runSync] makes: list `devices`, list a single device's own
|
||||||
/// get a device's file text (which crdt_sync also uses internally to
|
/// directory (for its file's sha), get a device's file text, and put this
|
||||||
/// 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})
|
||||||
@ -37,8 +36,8 @@ class _FakeGitHub {
|
|||||||
final List<String> deviceDirs;
|
final List<String> deviceDirs;
|
||||||
final Map<String, String> files;
|
final Map<String, String> files;
|
||||||
|
|
||||||
/// Every `diet-guard-sync/devices/<id>/food_log.json` path this fake
|
/// Every `devices/<id>/food_log.json` path this fake actually served a
|
||||||
/// actually served a file-content GET for.
|
/// file-content GET for (i.e. a real `getFileText` pull, not a listing).
|
||||||
final List<String> fileGets = [];
|
final List<String> fileGets = [];
|
||||||
|
|
||||||
/// Every PUT this fake received, decoded.
|
/// Every PUT this fake received, decoded.
|
||||||
@ -52,27 +51,33 @@ 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 == 'diet-guard-sync/devices') {
|
if (path == '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',
|
]),
|
||||||
'name': d,
|
200,
|
||||||
'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,
|
||||||
);
|
);
|
||||||
@ -80,20 +85,7 @@ 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]!));
|
||||||
// Real GitHub always returns `sha` alongside `content` for a
|
return http.Response(jsonEncode({'content': content}), 200);
|
||||||
// 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,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -124,10 +116,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 {'diet-guard-sync/devices/pc/food_log.json': '{}'},
|
files: const {'devices/pc/food_log.json': '{}'},
|
||||||
);
|
);
|
||||||
await runSync(fake.buildClient());
|
await runSync(fake.buildClient());
|
||||||
expect(fake.fileGets, ['diet-guard-sync/devices/pc/food_log.json']);
|
expect(fake.fileGets, ['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 {
|
||||||
@ -139,7 +131,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 {'diet-guard-sync/devices/pc/food_log.json': '[]'},
|
files: const {'devices/pc/food_log.json': '[]'},
|
||||||
);
|
);
|
||||||
final merged = await runSync(fake.buildClient());
|
final merged = await runSync(fake.buildClient());
|
||||||
expect(merged, isEmpty);
|
expect(merged, isEmpty);
|
||||||
@ -148,76 +140,36 @@ 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 {
|
files: const {'devices/pc/food_log.json': '{not valid json'},
|
||||||
'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(
|
test("merges in a remote device's entries", () async {
|
||||||
"merges in a remote device's entries (old pre-migration format)",
|
final remoteLog = jsonEncode({
|
||||||
() async {
|
'2026-06-22': [
|
||||||
final remoteLog = jsonEncode({
|
{
|
||||||
'2026-06-22': [
|
'id': 'pc-1',
|
||||||
{
|
'time': '2026-06-22T09:00:00+02:00',
|
||||||
'id': 'pc-1',
|
'desc': 'pc meal',
|
||||||
'time': '2026-06-22T09:00:00+02:00',
|
'kcal': 400.0,
|
||||||
'desc': 'pc meal',
|
'protein_g': 20.0,
|
||||||
'kcal': 400.0,
|
'carbs_g': 40.0,
|
||||||
'protein_g': 20.0,
|
'fat_g': 10.0,
|
||||||
'carbs_g': 40.0,
|
'grams': 300.0,
|
||||||
'fat_g': 10.0,
|
'source': 'manual',
|
||||||
'grams': 300.0,
|
},
|
||||||
'source': 'manual',
|
],
|
||||||
},
|
});
|
||||||
],
|
final fake = _FakeGitHub(
|
||||||
});
|
deviceDirs: const ['pc'],
|
||||||
final fake = _FakeGitHub(
|
files: {'devices/pc/food_log.json': remoteLog},
|
||||||
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();
|
||||||
final merged = await runSync(fake.buildClient());
|
expect(descs, contains('pc meal'));
|
||||||
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);
|
||||||
@ -243,22 +195,9 @@ 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 {'diet-guard-sync/devices/phone/food_log.json': '{}'},
|
files: const {'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');
|
||||||
@ -301,7 +240,7 @@ void main() {
|
|||||||
});
|
});
|
||||||
final fake = _FakeGitHub(
|
final fake = _FakeGitHub(
|
||||||
deviceDirs: const ['pc'],
|
deviceDirs: const ['pc'],
|
||||||
files: {'diet-guard-sync/devices/pc/food_log.json': remoteLog},
|
files: {'devices/pc/food_log.json': remoteLog},
|
||||||
);
|
);
|
||||||
final merged = await runSync(fake.buildClient());
|
final merged = await runSync(fake.buildClient());
|
||||||
|
|
||||||
|
|||||||
@ -10,9 +10,8 @@ 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,11 +1,9 @@
|
|||||||
"""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
|
||||||
(``crdt_sync.GitHubSyncClient``), merges with the local log via
|
(:mod:`diet_guard._sync_github`), merges with the local log
|
||||||
``crdt_sync``'s shared CRDT scheme (:mod:`diet_guard._sync_merge` adapts
|
(:mod:`diet_guard._sync_merge`), re-signs every persisted entry, rebuilds the
|
||||||
diet_guard's entries to/from ``crdt_sync.Record``), re-signs every persisted
|
food bank, and pushes this device's own merged log back up.
|
||||||
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
|
||||||
@ -13,18 +11,16 @@ 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_merge import daylog_to_log, log_to_daylog, parse_remote_log
|
from diet_guard._sync_github import GitHubSyncClient
|
||||||
|
from diet_guard._sync_merge import merge_logs
|
||||||
|
|
||||||
_logger = logging.getLogger(__name__)
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@ -61,16 +57,15 @@ def _read_token() -> str:
|
|||||||
return token
|
return token
|
||||||
|
|
||||||
|
|
||||||
def _pull_remote_logs(client: GitHubSyncClient) -> list[Log]:
|
def _pull_remote_logs(client: GitHubSyncClient) -> list[DayLog]:
|
||||||
"""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, truncated, or otherwise
|
A device whose pushed file is corrupt or truncated (e.g. an interrupted
|
||||||
unparsable (new or old wire format) is logged and skipped, same as one
|
push) is logged and skipped, same as one that has never pushed at all --
|
||||||
that has never pushed at all -- GitHub is an external system boundary,
|
GitHub is an external system boundary, and one bad device's file must
|
||||||
and one bad device's file must not stall merging in every other
|
not stall merging in every other device's.
|
||||||
device's.
|
|
||||||
"""
|
"""
|
||||||
remote_logs: list[Log] = []
|
remote_logs: list[DayLog] = []
|
||||||
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
|
||||||
@ -78,9 +73,12 @@ def _pull_remote_logs(client: GitHubSyncClient) -> list[Log]:
|
|||||||
if text is None:
|
if text is None:
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
remote_logs.append(parse_remote_log(text))
|
remote_log = json.loads(text)
|
||||||
except (TypeError, KeyError, ValueError, json.JSONDecodeError):
|
except 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
|
||||||
|
|
||||||
|
|
||||||
@ -98,35 +96,27 @@ def run_sync() -> DayLog:
|
|||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
SyncError: If the local PAT is missing or empty.
|
SyncError: If the local PAT is missing or empty.
|
||||||
crdt_sync.GitHubSyncError: Propagated from the GitHub client for any
|
diet_guard._sync_github.GitHubSyncError: Propagated from the GitHub
|
||||||
transport failure -- the caller (CLI/timer) decides how to
|
client for any transport failure -- the caller (CLI/timer)
|
||||||
report it.
|
decides how to report it.
|
||||||
"""
|
"""
|
||||||
token = _read_token()
|
token = _read_token()
|
||||||
client = GitHubSyncClient(
|
client = GitHubSyncClient(SYNC_REPO_OWNER, SYNC_REPO_NAME, token)
|
||||||
SYNC_REPO_OWNER, SYNC_REPO_NAME, token, timeout_seconds=SYNC_TIMEOUT_SECONDS
|
|
||||||
)
|
|
||||||
|
|
||||||
merged = daylog_to_log(read_raw_log())
|
merged = 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_daylog.items()
|
for day, entries in merged.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),
|
||||||
push_json,
|
json.dumps(resigned, indent=2),
|
||||||
message="diet_guard sync",
|
message="diet_guard sync",
|
||||||
)
|
)
|
||||||
return resigned
|
return resigned
|
||||||
|
|||||||
190
diet_guard/_sync_github.py
Normal file
190
diet_guard/_sync_github.py
Normal file
@ -0,0 +1,190 @@
|
|||||||
|
"""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,178 +1,81 @@
|
|||||||
"""Entry <-> crdt_sync.Record adapters for diet_guard's cross-device sync.
|
"""Pure log-merge logic for diet_guard's cross-device sync.
|
||||||
|
|
||||||
diet_guard's own on-disk ``food_log.json`` format is unchanged (a
|
No I/O here -- this module is unit-testable purely on in-memory ``DayLog``
|
||||||
:class:`~diet_guard._state.DayLog`: date string -> list of entry dicts) --
|
values, like :mod:`diet_guard._slots`. Mirrored test-for-test by the Dart
|
||||||
only the GitHub-synced wire format and the cross-device merge algorithm now
|
port (``app/lib/services/sync_service.dart``), so the merge algorithm
|
||||||
go through ``crdt_sync``'s ``Record``/``Log``/``Hlc`` primitives, the same
|
canonically agrees on both sides of the sync.
|
||||||
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
|
||||||
|
|
||||||
_EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
|
# A dedup key: ("id", <uuid string>) for any entry with one, else
|
||||||
|
# ("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_hlc(entry: dict[str, object]) -> Hlc:
|
def _entry_key(entry: dict[str, object]) -> _Key:
|
||||||
"""Derive a deterministic Hlc for ``entry`` from its own ``time`` field.
|
"""Return the dedup key for ``entry``."""
|
||||||
|
|
||||||
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 not isinstance(entry_id, str) or not entry_id:
|
if isinstance(entry_id, str) and entry_id:
|
||||||
entry_id = _legacy_entry_id(entry)
|
return ("id", entry_id)
|
||||||
hlc = _entry_hlc(entry)
|
return ("legacy", (entry.get("time"), entry.get("desc")))
|
||||||
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 record_to_entry(record: Record) -> dict[str, object]:
|
def _tombstone_wins(
|
||||||
"""Convert one ``crdt_sync.Record`` back to a diet_guard log entry."""
|
candidate: dict[str, object],
|
||||||
body_value, _hlc = record.fields.get("body", ({}, None))
|
existing: dict[str, object],
|
||||||
entry: dict[str, object] = dict(body_value) if isinstance(body_value, dict) else {}
|
) -> bool:
|
||||||
entry["id"] = record.id
|
"""Return True if ``candidate`` should replace ``existing`` for one key.
|
||||||
if record.deleted:
|
|
||||||
entry["deleted"] = True
|
|
||||||
return entry
|
|
||||||
|
|
||||||
|
A tombstone always wins over a non-tombstoned copy of the same entry --
|
||||||
def daylog_to_log(daylog: DayLog) -> Log:
|
deletion is sticky, so a stale pre-undo copy pulled from another device
|
||||||
"""Convert a full local/remote DayLog into a ``crdt_sync.Log``."""
|
can never resurrect something the user explicitly removed. Otherwise,
|
||||||
log: Log = {}
|
keep whichever copy was seen first: two copies of the same id are
|
||||||
for entries in daylog.values():
|
expected to be byte-identical in their macros/desc (the body is never
|
||||||
for entry in entries:
|
mutated after creation, only ``deleted``/``hmac``), so which one survives
|
||||||
record = entry_to_record(entry)
|
does not change the merged result's content.
|
||||||
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.
|
|
||||||
"""
|
"""
|
||||||
daylog: DayLog = {}
|
return bool(candidate.get("deleted")) and not existing.get("deleted")
|
||||||
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]
|
||||||
daylog.setdefault(date_key, []).append(entry)
|
merged.setdefault(date_key, []).append(entry)
|
||||||
for entries in daylog.values():
|
for entries in merged.values():
|
||||||
entries.sort(key=lambda entry: str(entry.get("time", "")))
|
entries.sort(key=lambda entry: str(entry.get("time", "")))
|
||||||
return daylog
|
return merged
|
||||||
|
|
||||||
|
|
||||||
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,10 +6,9 @@ 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 = resolved_files.get
|
client.get_file_text.side_effect = lambda path: resolved_files.get(path)
|
||||||
return client
|
return client
|
||||||
|
|
||||||
|
|
||||||
@ -81,23 +81,18 @@ 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 == "diet-guard-sync/devices/pc/food_log.json"
|
assert pushed_path == "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={"diet-guard-sync/devices/phone/food_log.json": "{}"},
|
files={"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(
|
||||||
"diet-guard-sync/devices/phone/food_log.json",
|
"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:
|
||||||
@ -111,7 +106,7 @@ class TestRunSync:
|
|||||||
_write_token()
|
_write_token()
|
||||||
client = _mock_client(
|
client = _mock_client(
|
||||||
devices=("phone",),
|
devices=("phone",),
|
||||||
files={"diet-guard-sync/devices/phone/food_log.json": "[]"},
|
files={"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()
|
||||||
@ -124,7 +119,7 @@ class TestRunSync:
|
|||||||
_write_token()
|
_write_token()
|
||||||
client = _mock_client(
|
client = _mock_client(
|
||||||
devices=("phone",),
|
devices=("phone",),
|
||||||
files={"diet-guard-sync/devices/phone/food_log.json": "{not valid json"},
|
files={"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()
|
||||||
@ -151,7 +146,7 @@ class TestRunSync:
|
|||||||
)
|
)
|
||||||
client = _mock_client(
|
client = _mock_client(
|
||||||
devices=("phone",),
|
devices=("phone",),
|
||||||
files={"diet-guard-sync/devices/phone/food_log.json": remote_log_json},
|
files={"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()
|
||||||
@ -186,7 +181,7 @@ class TestRunSync:
|
|||||||
)
|
)
|
||||||
client = _mock_client(
|
client = _mock_client(
|
||||||
devices=("phone",),
|
devices=("phone",),
|
||||||
files={"diet-guard-sync/devices/phone/food_log.json": remote_log_json},
|
files={"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()
|
||||||
|
|||||||
197
diet_guard/tests/test_sync_github.py
Normal file
197
diet_guard/tests/test_sync_github.py
Normal file
@ -0,0 +1,197 @@
|
|||||||
|
"""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,28 +1,8 @@
|
|||||||
"""Tests for diet_guard's entry <-> crdt_sync.Record adapters.
|
"""Tests for the pure cross-device log-merge logic."""
|
||||||
|
|
||||||
``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
|
||||||
|
|
||||||
import json
|
from diet_guard._sync_merge import merge_logs
|
||||||
|
|
||||||
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]:
|
||||||
@ -42,35 +22,30 @@ 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_daylogs(a, b)
|
merged = merge_logs(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_daylogs({"2026-06-22": [shared]}, {"2026-06-22": [shared]})
|
merged = merge_logs({"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_daylogs({"2026-06-20": [legacy_a]}, {"2026-06-20": [legacy_b]})
|
merged = merge_logs({"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_daylogs({"2026-06-20": [legacy]}, {"2026-06-20": [with_id]})
|
merged = merge_logs({"2026-06-20": [legacy]}, {"2026-06-20": [with_id]})
|
||||||
assert len(merged["2026-06-20"]) == 2
|
assert len(merged["2026-06-20"]) == 2
|
||||||
|
|
||||||
|
|
||||||
@ -79,11 +54,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_daylogs(
|
forward = merge_logs(
|
||||||
{"2026-06-22": [normal]},
|
{"2026-06-22": [normal]},
|
||||||
{"2026-06-22": [tombstoned]},
|
{"2026-06-22": [tombstoned]},
|
||||||
)
|
)
|
||||||
backward = _merge_daylogs(
|
backward = merge_logs(
|
||||||
{"2026-06-22": [tombstoned]},
|
{"2026-06-22": [tombstoned]},
|
||||||
{"2026-06-22": [normal]},
|
{"2026-06-22": [normal]},
|
||||||
)
|
)
|
||||||
@ -93,7 +68,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_daylogs(
|
merged = merge_logs(
|
||||||
{"2026-06-22": [tombstoned]},
|
{"2026-06-22": [tombstoned]},
|
||||||
{"2026-06-22": [dict(tombstoned)]},
|
{"2026-06-22": [dict(tombstoned)]},
|
||||||
)
|
)
|
||||||
@ -105,13 +80,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_daylogs({"2026-06-22": [misfiled]}, {})
|
merged = merge_logs({"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_daylogs({"2026-06-22": [late]}, {"2026-06-22": [early]})
|
merged = merge_logs({"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"]
|
||||||
|
|
||||||
|
|
||||||
@ -119,96 +94,16 @@ 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_daylogs(a, b) == _merge_daylogs(b, a)
|
assert merge_logs(a, b) == merge_logs(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_daylogs(canonical, canonical) == canonical
|
assert merge_logs(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_daylogs(log, {}) == log
|
assert merge_logs(log, {}) == log
|
||||||
assert _merge_daylogs({}, log) == log
|
assert merge_logs({}, log) == log
|
||||||
|
|
||||||
def test_merging_two_empty_logs_is_empty(self) -> None:
|
def test_merging_two_empty_logs_is_empty(self) -> None:
|
||||||
assert _merge_daylogs({}, {}) == {}
|
assert merge_logs({}, {}) == {}
|
||||||
|
|
||||||
|
|
||||||
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,7 +5,6 @@ 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",
|
||||||
]
|
]
|
||||||
|
|
||||||
@ -40,8 +39,8 @@ fixable = ["ALL"]
|
|||||||
unfixable = []
|
unfixable = []
|
||||||
|
|
||||||
[tool.ruff.lint.per-file-ignores]
|
[tool.ruff.lint.per-file-ignores]
|
||||||
"**/tests/**/*.py" = ["ARG", "D", "PLC0415", "PLR2004", "S101", "S107", "SLF001"]
|
"**/tests/**/*.py" = ["ARG", "D", "PLC0415", "PLR2004", "S101", "SLF001"]
|
||||||
"**/test_*.py" = ["ARG", "D", "PLC0415", "PLR2004", "S101", "S107", "SLF001"]
|
"**/test_*.py" = ["ARG", "D", "PLC0415", "PLR2004", "S101", "SLF001"]
|
||||||
|
|
||||||
[tool.ruff.lint.pydocstyle]
|
[tool.ruff.lint.pydocstyle]
|
||||||
convention = "google"
|
convention = "google"
|
||||||
@ -127,13 +126,6 @@ min-public-methods = 0
|
|||||||
max-module-lines = 1000
|
max-module-lines = 1000
|
||||||
max-attributes = 10
|
max-attributes = 10
|
||||||
|
|
||||||
[tool.pylint.similarities]
|
|
||||||
# _foodbank's BankRecord and _mcp's response dict both list the same five
|
|
||||||
# nutrition fields (kcal/protein_g/carbs_g/fat_g/grams) because they mirror the
|
|
||||||
# same domain schema, then diverge (desc/count vs source). Raise the threshold
|
|
||||||
# so pylint doesn't flag this intentional structural overlap as duplicate-code.
|
|
||||||
min-similarity-lines = 8
|
|
||||||
|
|
||||||
[tool.pylint.typecheck]
|
[tool.pylint.typecheck]
|
||||||
generated-members = [
|
generated-members = [
|
||||||
".*\\.assert_called_once_with",
|
".*\\.assert_called_once_with",
|
||||||
|
|||||||
@ -3,9 +3,7 @@
|
|||||||
bandit>=1.7.0
|
bandit>=1.7.0
|
||||||
codespell>=2.2.0
|
codespell>=2.2.0
|
||||||
coverage>=7.4.0
|
coverage>=7.4.0
|
||||||
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.1.0#subdirectory=crdt-sync
|
|
||||||
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
|
||||||
mcp>=1.9
|
|
||||||
mypy>=1.8.0
|
mypy>=1.8.0
|
||||||
pre-commit>=3.6.0
|
pre-commit>=3.6.0
|
||||||
pylint>=3.0.0
|
pylint>=3.0.0
|
||||||
|
|||||||
@ -17,10 +17,8 @@
|
|||||||
|
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
readonly SCRIPT_DIR
|
readonly REPO_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
||||||
REPO_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
|
||||||
readonly REPO_DIR
|
|
||||||
readonly VENV_DIR="${HOME}/.venvs/diet-guard-mcp"
|
readonly VENV_DIR="${HOME}/.venvs/diet-guard-mcp"
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user