mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-19 06:34:35 +01:00
Split wrapper_server and sync_merge into siblings
Two Dart files whose contents were already cleanly separable. wrapper_server.dart (254 -> 228): contentTypeFor is a pure function of the path with no server state, so it moves to content_types.dart as a plain library. WrapperServer.contentTypeFor stays as a static forwarder because the test reaches for it by that name. sync_merge.dart (475 -> 190): three near-independent blocks -- daylog, banks, budget -- split along the seams the tests already use. The banks and budget adapters move to siblings and are re-exported, so sync_service.dart and both test files import exactly what they did before and needed no edits. Flutter 555 tests unchanged; analyze clean; gate 52 -> 49. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MK3HCZrM75sRHL1gL8usve
This commit is contained in:
parent
17a2c62f26
commit
fef140d970
44
app/lib/desktop/content_types.dart
Normal file
44
app/lib/desktop/content_types.dart
Normal file
@ -0,0 +1,44 @@
|
||||
/// Content types for the files the desktop wrapper serves.
|
||||
///
|
||||
/// Split out of `wrapper_server.dart` for file size. A pure function of the
|
||||
/// path with no server state, so it lives as a plain sibling library rather
|
||||
/// than a `part`.
|
||||
library;
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
/// Content type for [filePath].
|
||||
///
|
||||
/// Flutter web is strict here: CanvasKit refuses to instantiate a `.wasm`
|
||||
/// served as anything but `application/wasm`, and the app then renders
|
||||
/// nothing at all.
|
||||
ContentType contentTypeFor(String filePath) {
|
||||
switch (p.extension(filePath).toLowerCase()) {
|
||||
case '.html':
|
||||
return ContentType.html;
|
||||
case '.js' || '.mjs':
|
||||
return ContentType('text', 'javascript', charset: 'utf-8');
|
||||
case '.json':
|
||||
return ContentType.json;
|
||||
case '.wasm':
|
||||
return ContentType('application', 'wasm');
|
||||
case '.css':
|
||||
return ContentType('text', 'css', charset: 'utf-8');
|
||||
case '.png':
|
||||
return ContentType('image', 'png');
|
||||
case '.jpg' || '.jpeg':
|
||||
return ContentType('image', 'jpeg');
|
||||
case '.svg':
|
||||
return ContentType('image', 'svg+xml');
|
||||
case '.ttf':
|
||||
return ContentType('font', 'ttf');
|
||||
case '.otf':
|
||||
return ContentType('font', 'otf');
|
||||
case '.woff2':
|
||||
return ContentType('font', 'woff2');
|
||||
default:
|
||||
return ContentType.binary;
|
||||
}
|
||||
}
|
||||
@ -23,6 +23,7 @@ import 'dart:io';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
|
||||
import 'package:diet_guard_app/desktop/content_types.dart' as content_types;
|
||||
import 'package:diet_guard_app/desktop/github_proxy.dart';
|
||||
import 'package:diet_guard_app/services/desktop_wrapper.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
@ -218,37 +219,10 @@ class WrapperServer {
|
||||
await request.response.addStream(file.openRead());
|
||||
}
|
||||
|
||||
/// Content type for [filePath].
|
||||
/// Content type for [filePath]. See `content_types.dart`.
|
||||
///
|
||||
/// Flutter web is strict here: CanvasKit refuses to instantiate a `.wasm`
|
||||
/// served as anything but `application/wasm`, and the app then renders
|
||||
/// nothing at all.
|
||||
static ContentType contentTypeFor(String filePath) {
|
||||
switch (p.extension(filePath).toLowerCase()) {
|
||||
case '.html':
|
||||
return ContentType.html;
|
||||
case '.js' || '.mjs':
|
||||
return ContentType('text', 'javascript', charset: 'utf-8');
|
||||
case '.json':
|
||||
return ContentType.json;
|
||||
case '.wasm':
|
||||
return ContentType('application', 'wasm');
|
||||
case '.css':
|
||||
return ContentType('text', 'css', charset: 'utf-8');
|
||||
case '.png':
|
||||
return ContentType('image', 'png');
|
||||
case '.jpg' || '.jpeg':
|
||||
return ContentType('image', 'jpeg');
|
||||
case '.svg':
|
||||
return ContentType('image', 'svg+xml');
|
||||
case '.ttf':
|
||||
return ContentType('font', 'ttf');
|
||||
case '.otf':
|
||||
return ContentType('font', 'otf');
|
||||
case '.woff2':
|
||||
return ContentType('font', 'woff2');
|
||||
default:
|
||||
return ContentType.binary;
|
||||
}
|
||||
}
|
||||
/// Kept as a static forwarder so callers and tests that reach for
|
||||
/// `WrapperServer.contentTypeFor` keep working after the split.
|
||||
static ContentType contentTypeFor(String filePath) =>
|
||||
content_types.contentTypeFor(filePath);
|
||||
}
|
||||
|
||||
@ -29,16 +29,19 @@
|
||||
/// adapters field-for-field.
|
||||
library;
|
||||
|
||||
|
||||
import 'dart:convert';
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/services/budget_schedule.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:diet_guard_app/services/sync_device_id.dart';
|
||||
|
||||
// The bank and budget adapters moved out for file size. Re-exported here so
|
||||
// `import 'services/sync_merge.dart'` still reaches every adapter, which is
|
||||
// what sync_service.dart and both test files expect.
|
||||
export 'package:diet_guard_app/services/sync_merge_banks.dart';
|
||||
export 'package:diet_guard_app/services/sync_merge_budget.dart';
|
||||
|
||||
/// Derives a deterministic [Hlc] for [entry] from its own `time` field.
|
||||
///
|
||||
/// The same entry always yields the same Hlc regardless of when this runs
|
||||
@ -185,291 +188,3 @@ String encodeLogForPush(Log log) {
|
||||
};
|
||||
return jsonEncode(encoded);
|
||||
}
|
||||
|
||||
/// Converts the log-derived food bank into a crdt_sync [Log].
|
||||
///
|
||||
/// The bank is *derived* -- both devices replay the same synced log and
|
||||
/// compute the same records -- so this exists to make them agree
|
||||
/// **immediately** rather than only after each has replayed.
|
||||
///
|
||||
/// The clock is the record's own `count`, not a wall time, so
|
||||
/// last-writer-wins means *max-count-wins*: the device that has seen more of
|
||||
/// the log has the higher count, and re-merging is idempotent because the
|
||||
/// count does not move unless the log did. Mirrors
|
||||
/// `_sync_merge.food_bank_to_log`.
|
||||
Log foodBankToLog(Map<String, FoodBankRecord> bank) {
|
||||
final log = <String, Record>{};
|
||||
for (final mapEntry in bank.entries) {
|
||||
log[mapEntry.key] = Record(
|
||||
id: mapEntry.key,
|
||||
fields: {
|
||||
'body': (
|
||||
mapEntry.value.toJson(),
|
||||
Hlc.newTick(
|
||||
currentSyncDeviceId,
|
||||
wallTimeMsOverride: mapEntry.value.count.toInt(),
|
||||
),
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
return log;
|
||||
}
|
||||
|
||||
/// Converts a merged food-bank [Log] back into bank shape.
|
||||
Map<String, FoodBankRecord> logToFoodBank(Log log) {
|
||||
final bank = <String, FoodBankRecord>{};
|
||||
for (final mapEntry in log.entries) {
|
||||
if (mapEntry.value.deleted) continue;
|
||||
final body = mapEntry.value.fields['body']?.$1;
|
||||
if (body is! Map) continue;
|
||||
bank[mapEntry.key] = FoodBankRecord.fromJson(
|
||||
Map<String, dynamic>.from(body.cast<String, dynamic>()),
|
||||
);
|
||||
}
|
||||
return bank;
|
||||
}
|
||||
|
||||
/// Parses one device's pushed `food_bank.json` into a crdt_sync [Log].
|
||||
Log parseRemoteFoodBank(String text) {
|
||||
final raw = jsonDecode(text);
|
||||
if (raw is! Map) {
|
||||
throw const FormatException(
|
||||
'top-level food-bank payload is not a JSON object',
|
||||
);
|
||||
}
|
||||
return raw.cast<String, dynamic>().map(
|
||||
(id, data) => MapEntry(id, Record.fromJson(data as Map<String, dynamic>)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Serializes a merged food-bank [Log] for push.
|
||||
String encodeFoodBankForPush(Log log) => jsonEncode({
|
||||
for (final entry in log.entries) entry.key: entry.value.toJson(),
|
||||
});
|
||||
|
||||
/// Converts the hand-curated food bank into a crdt_sync [Log].
|
||||
///
|
||||
/// One record per normalized food name, carrying the whole bank record as an
|
||||
/// opaque `body` -- the same shape food-log entries use. Unlike an entry a
|
||||
/// curated food is editable, so its [Hlc] comes from the record's own
|
||||
/// `editedAt` stamp rather than a fixed birth time. Mirrors
|
||||
/// `_sync_merge.manual_bank_to_log`.
|
||||
Log manualBankToLog(Map<String, FoodBankRecord> bank) {
|
||||
final log = <String, Record>{};
|
||||
for (final mapEntry in bank.entries) {
|
||||
final wallTimeMs =
|
||||
DateTime.tryParse(
|
||||
mapEntry.value.editedAt ?? '',
|
||||
)?.toUtc().millisecondsSinceEpoch ??
|
||||
0;
|
||||
final body = Map<String, dynamic>.from(mapEntry.value.toJson())
|
||||
..remove('t');
|
||||
log[mapEntry.key] = Record(
|
||||
id: mapEntry.key,
|
||||
fields: {
|
||||
'body': (
|
||||
body,
|
||||
Hlc.newTick(currentSyncDeviceId, wallTimeMsOverride: wallTimeMs),
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
return log;
|
||||
}
|
||||
|
||||
/// Converts a merged curated-bank [Log] back into bank shape.
|
||||
///
|
||||
/// Each record's `editedAt` is reconstructed from its field [Hlc], so the
|
||||
/// stored stamp and the clock the merge compared can never drift apart.
|
||||
/// Mirrors `_sync_merge.log_to_manual_bank`.
|
||||
Map<String, FoodBankRecord> logToManualBank(Log log) {
|
||||
final bank = <String, FoodBankRecord>{};
|
||||
for (final mapEntry in log.entries) {
|
||||
if (mapEntry.value.deleted) continue;
|
||||
final field = mapEntry.value.fields['body'];
|
||||
final body = field?.$1;
|
||||
if (body is! Map) continue;
|
||||
final json = Map<String, dynamic>.from(body.cast<String, dynamic>());
|
||||
final hlc = field?.$2;
|
||||
if (hlc != null) {
|
||||
json['t'] = DateTime.fromMillisecondsSinceEpoch(
|
||||
hlc.wallTimeMs,
|
||||
isUtc: true,
|
||||
).toLocal().toIso8601String();
|
||||
}
|
||||
bank[mapEntry.key] = FoodBankRecord.fromJson(json);
|
||||
}
|
||||
return bank;
|
||||
}
|
||||
|
||||
/// Parses one device's pushed curated-bank text into a crdt_sync [Log].
|
||||
Log parseRemoteManualBank(String text) {
|
||||
final raw = jsonDecode(text);
|
||||
if (raw is! Map) {
|
||||
throw const FormatException(
|
||||
'top-level curated-bank payload is not a JSON object',
|
||||
);
|
||||
}
|
||||
return raw.cast<String, dynamic>().map(
|
||||
(id, data) => MapEntry(id, Record.fromJson(data as Map<String, dynamic>)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Serializes a merged curated-bank [Log] for push.
|
||||
String encodeManualBankForPush(Log log) => jsonEncode({
|
||||
for (final entry in log.entries) entry.key: entry.value.toJson(),
|
||||
});
|
||||
|
||||
/// Stable id: exactly one budget record per device-pushed `budget.json`.
|
||||
const budgetRecordId = 'budget';
|
||||
|
||||
/// Derives a deterministic [Hlc] for a raw budget record from its `t` field.
|
||||
///
|
||||
/// Mirrors [entryHlc]'s determinism -- the same unedited record always
|
||||
/// yields the same Hlc, so re-syncing an unchanged budget is a no-op -- but
|
||||
/// reads `t` (bumped on every explicit edit) rather than a fixed birth
|
||||
/// time, since a budget can be edited repeatedly and the *edit* time is
|
||||
/// what last-writer-wins must compare.
|
||||
Hlc budgetHlc(Map<String, dynamic> record) {
|
||||
final wallTimeMs =
|
||||
DateTime.tryParse(
|
||||
record['t'] as String? ?? '',
|
||||
)?.toUtc().millisecondsSinceEpoch ??
|
||||
0;
|
||||
return Hlc.newTick(currentSyncDeviceId, wallTimeMsOverride: wallTimeMs);
|
||||
}
|
||||
|
||||
/// Field-name prefix for the effective-from budget history, one field per
|
||||
/// date. A separate *field* rather than a separate document, because
|
||||
/// `mergeRecord` unions field names -- see [budgetToLog].
|
||||
const budgetHistoryFieldPrefix = 'hist:';
|
||||
|
||||
/// Derives a deterministic [Hlc] for one history entry from its edit time.
|
||||
///
|
||||
/// Same trick as [budgetHlc]: identical inputs always yield the same clock,
|
||||
/// so re-syncing unchanged history is a no-op. Two devices that seed the
|
||||
/// history independently derive the same wall time and the same value and
|
||||
/// differ only in node id, so whichever side wins the field-level LWW, the
|
||||
/// value is identical and the merge converges in one round.
|
||||
Hlc historyHlc(BudgetEntry entry) {
|
||||
final wallTimeMs =
|
||||
DateTime.tryParse(entry.editedAt)?.toUtc().millisecondsSinceEpoch ?? 0;
|
||||
return Hlc.newTick(currentSyncDeviceId, wallTimeMsOverride: wallTimeMs);
|
||||
}
|
||||
|
||||
/// Converts a raw local budget record plus its history into a [Log].
|
||||
///
|
||||
/// Returns an empty [Log] when [record] is null (this device has never
|
||||
/// explicitly set a budget), so it contributes nothing to the merge rather
|
||||
/// than clobbering another device's real value with the unset default.
|
||||
///
|
||||
/// The history rides along as one `hist:<YYYY-MM-DD>` field per entry on the
|
||||
/// *same* record. crdt_sync's `mergeRecord` is per-field LWW over the union
|
||||
/// of field names, so a device that predates the history neither clobbers
|
||||
/// those fields nor blocks them: it merges them in from the remote and
|
||||
/// pushes them straight back out (both sides push the *merged* log). That is
|
||||
/// what makes this safe to roll out without a coordinated release.
|
||||
///
|
||||
/// `w` (body weight) is stripped from `value` for the same reason the
|
||||
/// history is not stored there: inside the shared map it was collateral
|
||||
/// damage of whole-map LWW, since this device rebuilds that map without it.
|
||||
/// Python carries it as its own `weight` field instead, and this device
|
||||
/// relays that field untouched through the merged log even though it has no
|
||||
/// weight of its own to contribute -- so both devices still see one value.
|
||||
Log budgetToLog(
|
||||
Map<String, dynamic>? record, [
|
||||
List<BudgetEntry> entries = const [],
|
||||
]) {
|
||||
if (record == null) return {};
|
||||
final hlc = budgetHlc(record);
|
||||
final value = Map<String, dynamic>.from(record)
|
||||
..remove('t')
|
||||
..remove('w');
|
||||
final fields = <String, (dynamic, Hlc)>{'value': (value, hlc)};
|
||||
for (final entry in entries) {
|
||||
fields['$budgetHistoryFieldPrefix${entry.effectiveFrom}'] = (
|
||||
entry.kcal,
|
||||
historyHlc(entry),
|
||||
);
|
||||
}
|
||||
return {budgetRecordId: Record(id: budgetRecordId, fields: fields)};
|
||||
}
|
||||
|
||||
/// Extracts the effective-from history from a merged budget [Log].
|
||||
///
|
||||
/// Each entry's `editedAt` is reconstructed from its field Hlc rather than
|
||||
/// carried separately, so the stored timestamp and the clock the merge
|
||||
/// compared can never drift apart.
|
||||
List<BudgetEntry> logToHistory(Log log) {
|
||||
final record = log[budgetRecordId];
|
||||
if (record == null) return const [];
|
||||
final entries = <BudgetEntry>[];
|
||||
for (final field in record.fields.entries) {
|
||||
if (!field.key.startsWith(budgetHistoryFieldPrefix)) continue;
|
||||
final kcal = field.value.$1;
|
||||
if (kcal is! int) continue;
|
||||
entries.add(
|
||||
BudgetEntry(
|
||||
effectiveFrom: field.key.substring(budgetHistoryFieldPrefix.length),
|
||||
kcal: kcal,
|
||||
editedAt: DateTime.fromMillisecondsSinceEpoch(
|
||||
field.value.$2.wallTimeMs,
|
||||
isUtc: true,
|
||||
).toLocal().toIso8601String(),
|
||||
),
|
||||
);
|
||||
}
|
||||
entries.sort((a, b) => a.effectiveFrom.compareTo(b.effectiveFrom));
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// Converts a merged budget [Log] back into a raw budget record.
|
||||
///
|
||||
/// Returns null when the log has no budget record at all (neither device
|
||||
/// has ever set one yet) -- callers treat that as "nothing to apply
|
||||
/// locally", not an error.
|
||||
Map<String, dynamic>? logToBudget(Log log) {
|
||||
final record = log[budgetRecordId];
|
||||
if (record == null) return null;
|
||||
final field = record.fields['value'];
|
||||
final value = field?.$1;
|
||||
final result = value is Map
|
||||
? Map<String, dynamic>.from(value.cast<String, dynamic>())
|
||||
: <String, dynamic>{};
|
||||
final hlc = field?.$2;
|
||||
if (hlc != null) {
|
||||
result['t'] = DateTime.fromMillisecondsSinceEpoch(
|
||||
hlc.wallTimeMs,
|
||||
isUtc: true,
|
||||
).toLocal().toIso8601String();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Parses one device's pushed `budget.json` text into a crdt_sync [Log].
|
||||
///
|
||||
/// Throwing [FormatException] or [TypeError] is treated as unparsable by
|
||||
/// the caller (`syncLog`'s `decode` callback), matching [parseRemoteLog]'s
|
||||
/// tolerance for a corrupt/truncated push. There is no legacy plain-format
|
||||
/// fallback here -- `budget.json` is a brand-new sync payload.
|
||||
Log parseRemoteBudget(String text) {
|
||||
final raw = jsonDecode(text);
|
||||
if (raw is! Map) {
|
||||
throw const FormatException(
|
||||
'top-level budget payload is not a JSON object',
|
||||
);
|
||||
}
|
||||
final rawMap = raw.cast<String, dynamic>();
|
||||
return rawMap.map(
|
||||
(id, data) => MapEntry(id, Record.fromJson(data as Map<String, dynamic>)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Serializes a merged budget [Log] for push.
|
||||
String encodeBudgetForPush(Log log) {
|
||||
final encoded = <String, dynamic>{
|
||||
for (final entry in log.entries) entry.key: entry.value.toJson(),
|
||||
};
|
||||
return jsonEncode(encoded);
|
||||
}
|
||||
|
||||
151
app/lib/services/sync_merge_banks.dart
Normal file
151
app/lib/services/sync_merge_banks.dart
Normal file
@ -0,0 +1,151 @@
|
||||
/// Food-bank <-> crdt_sync.Record adapters, for both halves of the bank.
|
||||
///
|
||||
/// Split out of `sync_merge.dart` for file size; that file re-exports these
|
||||
/// so existing importers keep working.
|
||||
///
|
||||
/// The derived bank's merge clock is the record's own `count`, not a wall
|
||||
/// time: last-writer-wins therefore means *max-count-wins*, which is the
|
||||
/// correct merge for a derived counter and is idempotent. The curated
|
||||
/// (manual) bank is one record per normalized name, LWW by `editedAt`.
|
||||
library;
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||
import 'package:diet_guard_app/services/sync_device_id.dart';
|
||||
|
||||
/// Converts the log-derived food bank into a crdt_sync [Log].
|
||||
///
|
||||
/// The bank is *derived* -- both devices replay the same synced log and
|
||||
/// compute the same records -- so this exists to make them agree
|
||||
/// **immediately** rather than only after each has replayed.
|
||||
///
|
||||
/// The clock is the record's own `count`, not a wall time, so
|
||||
/// last-writer-wins means *max-count-wins*: the device that has seen more of
|
||||
/// the log has the higher count, and re-merging is idempotent because the
|
||||
/// count does not move unless the log did. Mirrors
|
||||
/// `_sync_merge.food_bank_to_log`.
|
||||
Log foodBankToLog(Map<String, FoodBankRecord> bank) {
|
||||
final log = <String, Record>{};
|
||||
for (final mapEntry in bank.entries) {
|
||||
log[mapEntry.key] = Record(
|
||||
id: mapEntry.key,
|
||||
fields: {
|
||||
'body': (
|
||||
mapEntry.value.toJson(),
|
||||
Hlc.newTick(
|
||||
currentSyncDeviceId,
|
||||
wallTimeMsOverride: mapEntry.value.count.toInt(),
|
||||
),
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
return log;
|
||||
}
|
||||
|
||||
/// Converts a merged food-bank [Log] back into bank shape.
|
||||
Map<String, FoodBankRecord> logToFoodBank(Log log) {
|
||||
final bank = <String, FoodBankRecord>{};
|
||||
for (final mapEntry in log.entries) {
|
||||
if (mapEntry.value.deleted) continue;
|
||||
final body = mapEntry.value.fields['body']?.$1;
|
||||
if (body is! Map) continue;
|
||||
bank[mapEntry.key] = FoodBankRecord.fromJson(
|
||||
Map<String, dynamic>.from(body.cast<String, dynamic>()),
|
||||
);
|
||||
}
|
||||
return bank;
|
||||
}
|
||||
|
||||
/// Parses one device's pushed `food_bank.json` into a crdt_sync [Log].
|
||||
Log parseRemoteFoodBank(String text) {
|
||||
final raw = jsonDecode(text);
|
||||
if (raw is! Map) {
|
||||
throw const FormatException(
|
||||
'top-level food-bank payload is not a JSON object',
|
||||
);
|
||||
}
|
||||
return raw.cast<String, dynamic>().map(
|
||||
(id, data) => MapEntry(id, Record.fromJson(data as Map<String, dynamic>)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Serializes a merged food-bank [Log] for push.
|
||||
String encodeFoodBankForPush(Log log) => jsonEncode({
|
||||
for (final entry in log.entries) entry.key: entry.value.toJson(),
|
||||
});
|
||||
|
||||
/// Converts the hand-curated food bank into a crdt_sync [Log].
|
||||
///
|
||||
/// One record per normalized food name, carrying the whole bank record as an
|
||||
/// opaque `body` -- the same shape food-log entries use. Unlike an entry a
|
||||
/// curated food is editable, so its [Hlc] comes from the record's own
|
||||
/// `editedAt` stamp rather than a fixed birth time. Mirrors
|
||||
/// `_sync_merge.manual_bank_to_log`.
|
||||
Log manualBankToLog(Map<String, FoodBankRecord> bank) {
|
||||
final log = <String, Record>{};
|
||||
for (final mapEntry in bank.entries) {
|
||||
final wallTimeMs =
|
||||
DateTime.tryParse(
|
||||
mapEntry.value.editedAt ?? '',
|
||||
)?.toUtc().millisecondsSinceEpoch ??
|
||||
0;
|
||||
final body = Map<String, dynamic>.from(mapEntry.value.toJson())
|
||||
..remove('t');
|
||||
log[mapEntry.key] = Record(
|
||||
id: mapEntry.key,
|
||||
fields: {
|
||||
'body': (
|
||||
body,
|
||||
Hlc.newTick(currentSyncDeviceId, wallTimeMsOverride: wallTimeMs),
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
return log;
|
||||
}
|
||||
|
||||
/// Converts a merged curated-bank [Log] back into bank shape.
|
||||
///
|
||||
/// Each record's `editedAt` is reconstructed from its field [Hlc], so the
|
||||
/// stored stamp and the clock the merge compared can never drift apart.
|
||||
/// Mirrors `_sync_merge.log_to_manual_bank`.
|
||||
Map<String, FoodBankRecord> logToManualBank(Log log) {
|
||||
final bank = <String, FoodBankRecord>{};
|
||||
for (final mapEntry in log.entries) {
|
||||
if (mapEntry.value.deleted) continue;
|
||||
final field = mapEntry.value.fields['body'];
|
||||
final body = field?.$1;
|
||||
if (body is! Map) continue;
|
||||
final json = Map<String, dynamic>.from(body.cast<String, dynamic>());
|
||||
final hlc = field?.$2;
|
||||
if (hlc != null) {
|
||||
json['t'] = DateTime.fromMillisecondsSinceEpoch(
|
||||
hlc.wallTimeMs,
|
||||
isUtc: true,
|
||||
).toLocal().toIso8601String();
|
||||
}
|
||||
bank[mapEntry.key] = FoodBankRecord.fromJson(json);
|
||||
}
|
||||
return bank;
|
||||
}
|
||||
|
||||
/// Parses one device's pushed curated-bank text into a crdt_sync [Log].
|
||||
Log parseRemoteManualBank(String text) {
|
||||
final raw = jsonDecode(text);
|
||||
if (raw is! Map) {
|
||||
throw const FormatException(
|
||||
'top-level curated-bank payload is not a JSON object',
|
||||
);
|
||||
}
|
||||
return raw.cast<String, dynamic>().map(
|
||||
(id, data) => MapEntry(id, Record.fromJson(data as Map<String, dynamic>)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Serializes a merged curated-bank [Log] for push.
|
||||
String encodeManualBankForPush(Log log) => jsonEncode({
|
||||
for (final entry in log.entries) entry.key: entry.value.toJson(),
|
||||
});
|
||||
170
app/lib/services/sync_merge_budget.dart
Normal file
170
app/lib/services/sync_merge_budget.dart
Normal file
@ -0,0 +1,170 @@
|
||||
/// Budget and budget-history <-> crdt_sync.Record adapters.
|
||||
///
|
||||
/// Split out of `sync_merge.dart` for file size; that file re-exports these
|
||||
/// so existing importers keep working.
|
||||
///
|
||||
/// A budget record is edited repeatedly rather than immutable-after-creation
|
||||
/// like a food-log entry, so its [Hlc] derives from a `t` edit timestamp
|
||||
/// rather than a birth time that never changes. History rides along as
|
||||
/// `hist:<YYYY-MM-DD>` fields on the same record, so a device predating the
|
||||
/// feature relays them untouched. Mirrors `diet_guard/_sync_merge.py`.
|
||||
library;
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/services/budget_schedule.dart';
|
||||
import 'package:diet_guard_app/services/sync_device_id.dart';
|
||||
|
||||
/// Stable id: exactly one budget record per device-pushed `budget.json`.
|
||||
const budgetRecordId = 'budget';
|
||||
|
||||
/// Derives a deterministic [Hlc] for a raw budget record from its `t` field.
|
||||
///
|
||||
/// Mirrors [entryHlc]'s determinism -- the same unedited record always
|
||||
/// yields the same Hlc, so re-syncing an unchanged budget is a no-op -- but
|
||||
/// reads `t` (bumped on every explicit edit) rather than a fixed birth
|
||||
/// time, since a budget can be edited repeatedly and the *edit* time is
|
||||
/// what last-writer-wins must compare.
|
||||
Hlc budgetHlc(Map<String, dynamic> record) {
|
||||
final wallTimeMs =
|
||||
DateTime.tryParse(
|
||||
record['t'] as String? ?? '',
|
||||
)?.toUtc().millisecondsSinceEpoch ??
|
||||
0;
|
||||
return Hlc.newTick(currentSyncDeviceId, wallTimeMsOverride: wallTimeMs);
|
||||
}
|
||||
|
||||
/// Field-name prefix for the effective-from budget history, one field per
|
||||
/// date. A separate *field* rather than a separate document, because
|
||||
/// `mergeRecord` unions field names -- see [budgetToLog].
|
||||
const budgetHistoryFieldPrefix = 'hist:';
|
||||
|
||||
/// Derives a deterministic [Hlc] for one history entry from its edit time.
|
||||
///
|
||||
/// Same trick as [budgetHlc]: identical inputs always yield the same clock,
|
||||
/// so re-syncing unchanged history is a no-op. Two devices that seed the
|
||||
/// history independently derive the same wall time and the same value and
|
||||
/// differ only in node id, so whichever side wins the field-level LWW, the
|
||||
/// value is identical and the merge converges in one round.
|
||||
Hlc historyHlc(BudgetEntry entry) {
|
||||
final wallTimeMs =
|
||||
DateTime.tryParse(entry.editedAt)?.toUtc().millisecondsSinceEpoch ?? 0;
|
||||
return Hlc.newTick(currentSyncDeviceId, wallTimeMsOverride: wallTimeMs);
|
||||
}
|
||||
|
||||
/// Converts a raw local budget record plus its history into a [Log].
|
||||
///
|
||||
/// Returns an empty [Log] when [record] is null (this device has never
|
||||
/// explicitly set a budget), so it contributes nothing to the merge rather
|
||||
/// than clobbering another device's real value with the unset default.
|
||||
///
|
||||
/// The history rides along as one `hist:<YYYY-MM-DD>` field per entry on the
|
||||
/// *same* record. crdt_sync's `mergeRecord` is per-field LWW over the union
|
||||
/// of field names, so a device that predates the history neither clobbers
|
||||
/// those fields nor blocks them: it merges them in from the remote and
|
||||
/// pushes them straight back out (both sides push the *merged* log). That is
|
||||
/// what makes this safe to roll out without a coordinated release.
|
||||
///
|
||||
/// `w` (body weight) is stripped from `value` for the same reason the
|
||||
/// history is not stored there: inside the shared map it was collateral
|
||||
/// damage of whole-map LWW, since this device rebuilds that map without it.
|
||||
/// Python carries it as its own `weight` field instead, and this device
|
||||
/// relays that field untouched through the merged log even though it has no
|
||||
/// weight of its own to contribute -- so both devices still see one value.
|
||||
Log budgetToLog(
|
||||
Map<String, dynamic>? record, [
|
||||
List<BudgetEntry> entries = const [],
|
||||
]) {
|
||||
if (record == null) return {};
|
||||
final hlc = budgetHlc(record);
|
||||
final value = Map<String, dynamic>.from(record)
|
||||
..remove('t')
|
||||
..remove('w');
|
||||
final fields = <String, (dynamic, Hlc)>{'value': (value, hlc)};
|
||||
for (final entry in entries) {
|
||||
fields['$budgetHistoryFieldPrefix${entry.effectiveFrom}'] = (
|
||||
entry.kcal,
|
||||
historyHlc(entry),
|
||||
);
|
||||
}
|
||||
return {budgetRecordId: Record(id: budgetRecordId, fields: fields)};
|
||||
}
|
||||
|
||||
/// Extracts the effective-from history from a merged budget [Log].
|
||||
///
|
||||
/// Each entry's `editedAt` is reconstructed from its field Hlc rather than
|
||||
/// carried separately, so the stored timestamp and the clock the merge
|
||||
/// compared can never drift apart.
|
||||
List<BudgetEntry> logToHistory(Log log) {
|
||||
final record = log[budgetRecordId];
|
||||
if (record == null) return const [];
|
||||
final entries = <BudgetEntry>[];
|
||||
for (final field in record.fields.entries) {
|
||||
if (!field.key.startsWith(budgetHistoryFieldPrefix)) continue;
|
||||
final kcal = field.value.$1;
|
||||
if (kcal is! int) continue;
|
||||
entries.add(
|
||||
BudgetEntry(
|
||||
effectiveFrom: field.key.substring(budgetHistoryFieldPrefix.length),
|
||||
kcal: kcal,
|
||||
editedAt: DateTime.fromMillisecondsSinceEpoch(
|
||||
field.value.$2.wallTimeMs,
|
||||
isUtc: true,
|
||||
).toLocal().toIso8601String(),
|
||||
),
|
||||
);
|
||||
}
|
||||
entries.sort((a, b) => a.effectiveFrom.compareTo(b.effectiveFrom));
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// Converts a merged budget [Log] back into a raw budget record.
|
||||
///
|
||||
/// Returns null when the log has no budget record at all (neither device
|
||||
/// has ever set one yet) -- callers treat that as "nothing to apply
|
||||
/// locally", not an error.
|
||||
Map<String, dynamic>? logToBudget(Log log) {
|
||||
final record = log[budgetRecordId];
|
||||
if (record == null) return null;
|
||||
final field = record.fields['value'];
|
||||
final value = field?.$1;
|
||||
final result = value is Map
|
||||
? Map<String, dynamic>.from(value.cast<String, dynamic>())
|
||||
: <String, dynamic>{};
|
||||
final hlc = field?.$2;
|
||||
if (hlc != null) {
|
||||
result['t'] = DateTime.fromMillisecondsSinceEpoch(
|
||||
hlc.wallTimeMs,
|
||||
isUtc: true,
|
||||
).toLocal().toIso8601String();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Parses one device's pushed `budget.json` text into a crdt_sync [Log].
|
||||
///
|
||||
/// Throwing [FormatException] or [TypeError] is treated as unparsable by
|
||||
/// the caller (`syncLog`'s `decode` callback), matching [parseRemoteLog]'s
|
||||
/// tolerance for a corrupt/truncated push. There is no legacy plain-format
|
||||
/// fallback here -- `budget.json` is a brand-new sync payload.
|
||||
Log parseRemoteBudget(String text) {
|
||||
final raw = jsonDecode(text);
|
||||
if (raw is! Map) {
|
||||
throw const FormatException(
|
||||
'top-level budget payload is not a JSON object',
|
||||
);
|
||||
}
|
||||
final rawMap = raw.cast<String, dynamic>();
|
||||
return rawMap.map(
|
||||
(id, data) => MapEntry(id, Record.fromJson(data as Map<String, dynamic>)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Serializes a merged budget [Log] for push.
|
||||
String encodeBudgetForPush(Log log) {
|
||||
final encoded = <String, dynamic>{
|
||||
for (final entry in log.entries) entry.key: entry.value.toJson(),
|
||||
};
|
||||
return jsonEncode(encoded);
|
||||
}
|
||||
@ -2,7 +2,7 @@ name: diet_guard_app
|
||||
description: "Companion phone app for diet_guard: log meals on the go."
|
||||
publish_to: 'none'
|
||||
|
||||
version: 1.0.13+1
|
||||
version: 1.0.14+1
|
||||
|
||||
environment:
|
||||
sdk: ^3.12.2
|
||||
|
||||
Loading…
Reference in New Issue
Block a user