workout_app: offline-first workout sync

A finished workout's record now lands in a local crdt log
(workout_log.json) before any network call. Every sync tick pushes that
log, so a failed or unconfigured push goes out with the next tick (home
open, app resume, a 5-minute WorkoutResync retry). The re-push carries
the same record and clock; the PC credits once per type:date anyway.

Every tick and every live history read merges what it pulled into the
same log, so PC records stay readable offline and after a restart.
History shows local rows plus cached synced rows at once, then refreshes
from the live read in the background. Ticks run one at a time, each
cut off after 2 min so a hung request cannot block the queue.

Bug-class-check: stronglift_replacement/workout_app/test/services/workout_sync_offline_test.dart, test/screens/workout_finish_keeps_record_test.dart, test/screens/history_offline_test.dart
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-27 17:03:51 +01:00
parent 422b1d55e0
commit 74be875900
23 changed files with 977 additions and 121 deletions

View File

@ -14,6 +14,11 @@ Implementing design_v2.md improvements.
workout and shows the status-bar notification; notification presses go workout and shows the status-bar notification; notification presses go
through a durable prefs queue, never straight into sqflite (the CRDT through a durable prefs queue, never straight into sqflite (the CRDT
sync layer owns that database's ordering) sync layer owns that database's ordering)
- Workout sync is offline-first: `push` writes its record to the local log
(`workout_log_store.dart`, `workout_log.json` beside `sync_state.json`)
before any network call; every tick pushes that log (so a failed push goes
out with the next one: home open, resume, `WorkoutResync` timer) and keeps
what it pulled. History shows local + cached rows at once, then the live read.
## GPS runs (foundation, 2026-11-10) ## GPS runs (foundation, 2026-11-10)
- The app records one mode: every GPS activity is a run (25 km/h jump cap, - The app records one mode: every GPS activity is a run (25 km/h jump cap,

View File

@ -33,6 +33,7 @@ import 'package:workout_app/services/shared_storage.dart';
import 'package:workout_app/services/storage_service.dart'; import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/sync_device_id.dart'; import 'package:workout_app/services/sync_device_id.dart';
import 'package:workout_app/services/sync_service.dart'; import 'package:workout_app/services/sync_service.dart';
import 'package:workout_app/services/workout_resync.dart';
import 'package:workout_app/ui/theme.dart'; import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/run_landing.dart'; import 'package:workout_app/widgets/run_landing.dart';
@ -194,15 +195,12 @@ class _WorkoutAppState extends State<WorkoutApp> with WidgetsBindingObserver {
} }
// coverage:ignore-start // coverage:ignore-start
// Platform edge, same shape as storage_service_schema's: the suite runs on // Platform edge, as in storage_service_schema: the suite runs on Linux, where
// Linux, where this returns on the first line, so the switch below is // this returns on the first line. Covering the switch would need a platform
// unreachable from any test this repo can run. Covering it would mean // seam through all nine Platform.isLinux checks, for reachability alone.
// threading a platform seam through the nine Platform.isLinux checks in
// this app purely for test reachability.
@override @override
void didChangeAppLifecycleState(AppLifecycleState state) { void didChangeAppLifecycleState(AppLifecycleState state) {
// The socket is never started on Linux (see main()), so there is nothing // The socket is never started on Linux (see main()): nothing to restart.
// to stop or restart here either.
if (Platform.isLinux || Sandbox.enabled) return; if (Platform.isLinux || Sandbox.enabled) return;
switch (state) { switch (state) {
case AppLifecycleState.paused: case AppLifecycleState.paused:
@ -210,8 +208,10 @@ class _WorkoutAppState extends State<WorkoutApp> with WidgetsBindingObserver {
unawaited(HttpServerService.instance.stop()); unawaited(HttpServerService.instance.stop());
case AppLifecycleState.resumed: case AppLifecycleState.resumed:
unawaited(HttpServerService.instance.start()); unawaited(HttpServerService.instance.start());
// The nearest thing to "connectivity came back" without a plugin. // The nearest thing to "connectivity came back" without a plugin:
// retry pending run uploads and workout pushes.
unawaited(RunUploader.instance.uploadPending()); unawaited(RunUploader.instance.uploadPending());
unawaited(WorkoutResync.instance.syncNow());
case AppLifecycleState.inactive: case AppLifecycleState.inactive:
case AppLifecycleState.hidden: case AppLifecycleState.hidden:
break; break;

View File

@ -29,6 +29,7 @@ import 'package:workout_app/widgets/calendar_widget.dart';
part 'history_screen_charts.dart'; part 'history_screen_charts.dart';
part 'history_screen_data.dart'; part 'history_screen_data.dart';
part 'history_screen_load.dart';
part 'history_screen_painter.dart'; part 'history_screen_painter.dart';
part 'history_screen_planned.dart'; part 'history_screen_planned.dart';
part 'history_screen_runs.dart'; part 'history_screen_runs.dart';
@ -90,56 +91,8 @@ class _HistoryScreenState extends State<HistoryScreen> {
unawaited(_load()); unawaited(_load());
} }
Future<void> _load() async { /// Lets the `_HistoryLoad` extension call the protected [setState].
// Put any of this device's own sessions that only exist remotely back into void _applyState(VoidCallback fn) => setState(fn);
// the local table FIRST, so they show up in this same load. A reinstall
// wipes local history while Firebase/GitHub keep it; without this the app
// silently shows less history than actually happened.
final remote = await _readSyncedPayloads();
await StorageService.instance.restoreSyncedSessions(remote);
final rows = await StorageService.instance.getWorkoutHistory(limit: 200);
final names = <String>[];
final seen = <String>{};
for (final row in rows) {
final json = jsonDecode(row['json'] as String) as Map<String, dynamic>;
for (final ex in (json['exercises'] as List? ?? const [])) {
final name = (ex as Map<String, dynamic>)['name'] as String;
if (seen.add(name)) names.add(name);
}
}
ExerciseState? state;
if (_selected != _kTotal) {
// Unreachable in practice: _load only runs from initState, where
// _selected is still _kTotal; exercise selection goes through
// _pickExercise, which loads its own state.
// coverage:ignore-start
state = await StorageService.instance.getExerciseState(_selected);
// coverage:ignore-end
}
final today = dayKey((widget.clock ?? DateTime.now)());
final runs = await StorageService.instance.listRuns();
// The phone's own copy of a run (it has the map) replaces the PC's entry.
final synced = withoutLocalRuns(_syncedOnly(remote, today), runs);
final planned = _plannedOnly(remote, today);
if (mounted) {
setState(() {
_rows = rows;
_syncedRows = synced;
_plannedRows = planned;
_runs = runs;
_exerciseNames = names;
_selectedState = state;
_loading = false;
});
}
}
/// Every payload the sync backends hold, across all devices.
///
/// Read once per load and used twice: to restore this device's own missing
/// sessions into local history, and to list the PC-only records below them.
Future<List<Map<String, dynamic>>> _readSyncedPayloads() =>
_syncService().readMergedWorkoutPayloads();
Future<void> _pickExercise(String name) async { Future<void> _pickExercise(String name) async {
ExerciseState? state; ExerciseState? state;

View File

@ -0,0 +1,57 @@
// Loading the history: local rows and the cached synced log first, then the
// live read in the background.
//
// A `part` so the extension keeps reaching the private `_HistoryScreenState`
// fields; it mutates them through the `_applyState` shim because `setState`
// is `@protected` and cannot be called from an extension.
part of 'history_screen.dart';
/// Offline-first loading for the history screen.
extension _HistoryLoad on _HistoryScreenState {
/// Shows what this phone already has, then refreshes from the backends.
///
/// The spinner only covers the local reads. The live read used to come
/// first, so an offline or slow network hid even this phone's own sessions
/// behind it.
Future<void> _load() async {
final sync = _syncService();
await _show(await sync.readCachedWorkoutPayloads());
final remote = await sync.readMergedWorkoutPayloads();
// Put any of this device's own sessions that only exist remotely back into
// the local table. A reinstall wipes local history while Firebase/GitHub
// keep it; without this the app silently shows less history than actually
// happened. Only from the live read: the cache holds this phone's own
// pushes, so restoring from it would undo a local delete.
await StorageService.instance.restoreSyncedSessions(remote);
// The live read was merged into the cache, which now holds both.
await _show(await sync.readCachedWorkoutPayloads());
}
/// Puts the local history plus [payloads] (synced records) on screen.
Future<void> _show(List<Map<String, dynamic>> payloads) async {
final rows = await StorageService.instance.getWorkoutHistory(limit: 200);
final names = <String>[];
final seen = <String>{};
for (final row in rows) {
final json = jsonDecode(row['json'] as String) as Map<String, dynamic>;
for (final ex in (json['exercises'] as List? ?? const [])) {
final name = (ex as Map<String, dynamic>)['name'] as String;
if (seen.add(name)) names.add(name);
}
}
final today = dayKey((widget.clock ?? DateTime.now)());
final runs = await StorageService.instance.listRuns();
// The phone's own copy of a run (it has the map) replaces the PC's entry.
final synced = withoutLocalRuns(_syncedOnly(payloads, today), runs);
final planned = _plannedOnly(payloads, today);
if (!mounted) return;
_applyState(() {
_rows = rows;
_syncedRows = synced;
_plannedRows = planned;
_runs = runs;
_exerciseNames = names;
_loading = false;
});
}
}

View File

@ -27,6 +27,7 @@ import 'package:workout_app/services/pc_poke_service.dart';
import 'package:workout_app/services/progression_sync_service.dart'; import 'package:workout_app/services/progression_sync_service.dart';
import 'package:workout_app/services/storage_service.dart'; import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/sync_service.dart'; import 'package:workout_app/services/sync_service.dart';
import 'package:workout_app/services/workout_resync.dart';
import 'package:workout_app/services/workout_sync_service.dart'; import 'package:workout_app/services/workout_sync_service.dart';
import 'package:workout_app/ui/theme.dart'; import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/break_banner.dart'; import 'package:workout_app/widgets/break_banner.dart';

View File

@ -119,14 +119,14 @@ extension _WorkoutScreenFinish on _WorkoutScreenState {
final syncResult = await _sync.writeWorkoutResult(session); final syncResult = await _sync.writeWorkoutResult(session);
// Not awaited: a slow or unreachable backend must not delay the summary // Not awaited: a slow or unreachable backend must not delay the summary
// dialog. But the result is no longer discarded -- a failed push logs at // dialog. push() keeps the record in the local log first, so a failure
// error level inside push(), so an unpushed workout is diagnosable // loses nothing: WorkoutResync retries, and every later tick re-sends it.
// instead of silently absent from every other device.
unawaited( unawaited(
WorkoutSyncService().push(session).then((result) { WorkoutSyncService().push(session).then((result) {
if (!result.pushed) { if (!result.pushed) {
log('Workout not synced: ${result.reason}', level: 1000); log('Workout not synced yet: ${result.reason}', level: 1000);
} }
WorkoutResync.instance.note(result);
}), }),
); );

View File

@ -0,0 +1,57 @@
/// This device's copy of the shared workout log: outbox and cache in one.
///
/// Offline-first (crdt_sync_dart README, "Offline-first contract"): a finished
/// workout's record lands here before any network call, so a failed or
/// unconfigured push keeps it and the next tick sends it. Every tick, and
/// every live history read, merges what it pulled back in, so the PC's
/// records stay readable offline and after a restart.
library;
import 'dart:io';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:crdt_sync/crdt_sync_io.dart';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:workout_app/services/sync_device_id.dart';
/// File holding the log, beside `sync_state.json` (the revisions it backs).
const kWorkoutLogFileName = 'workout_log.json';
/// Replaces the app support directory as the log's home when non-null.
///
/// `test/flutter_test_config.dart` points it at a fresh temp directory for
/// every test; nothing in the app sets it.
@visibleForTesting
String? workoutLogDirOverride;
Future<LogStore>? _shared;
String? _sharedDir;
/// The process-wide store, loaded once.
///
/// One instance on purpose: two stores over one file would each hold a
/// stale copy and the later write would drop the other's records.
Future<LogStore> openWorkoutLogStore() async {
final dir = workoutLogDirOverride ?? await _supportDir();
if (_shared == null || _sharedDir != dir) {
_sharedDir = dir;
_shared = openWorkoutLogStoreIn(dir);
}
return await _shared!;
}
/// Opens and loads a store over [dirPath]/[kWorkoutLogFileName].
Future<LogStore> openWorkoutLogStoreIn(String dirPath) async {
final store = LogStore(
persistence: FileLogPersistence(File(p.join(dirPath, kWorkoutLogFileName))),
nodeId: currentSyncDeviceId,
);
await store.load();
return store;
}
/// The app support directory, where the app keeps its sync state.
Future<String> _supportDir() async =>
(await getApplicationSupportDirectory()).path;

View File

@ -0,0 +1,57 @@
/// Retries a failed workout push by itself, until a sync tick gets through.
library;
import 'dart:async';
import 'dart:developer';
import 'package:workout_app/services/workout_sync_service.dart';
/// How long after a failed tick the next one runs while the app is open.
const Duration kWorkoutResyncAfter = Duration(minutes: 5);
/// Re-runs [WorkoutSyncService.syncNow] after a failure.
///
/// A tick needs no record to re-send: the push wrote its record to the local
/// log first, and every tick pushes that log. So a retry is just a tick.
/// The app also ticks on every home-screen open and on resume; this covers
/// the phone that stays open on the summary with the network down.
class WorkoutResync {
/// Creates a retrier; the arguments are test seams.
WorkoutResync({
Future<PushResult> Function()? syncNow,
Timer Function(Duration, void Function())? scheduler,
}) : _syncNow = syncNow ?? WorkoutSyncService().syncNow,
_schedule = scheduler ?? Timer.new;
/// The app-wide retrier.
static final WorkoutResync instance = WorkoutResync();
final Future<PushResult> Function() _syncNow;
final Timer Function(Duration, void Function()) _schedule;
Timer? _retry;
bool _armed = false;
/// Folds a tick's [result] in: a failure arms one retry, a success or a
/// device with no sync set up (nothing a retry could fix) disarms it.
void note(PushResult result) {
if (result.pushed || result.reason == kSyncNotConfigured) {
_retry?.cancel();
_armed = false;
return;
}
if (_armed) return;
_armed = true;
log(
'WorkoutResync: ${result.reason}; trying again in '
'${kWorkoutResyncAfter.inMinutes} min',
level: 900,
);
_retry = _schedule(kWorkoutResyncAfter, () {
_armed = false;
unawaited(syncNow());
});
}
/// Runs a tick now (e.g. the app came back to the foreground).
Future<void> syncNow() async => note(await _syncNow());
}

View File

@ -12,8 +12,10 @@ import 'package:workout_app/services/firebase_backend.dart';
import 'package:workout_app/services/sync_device_id.dart'; import 'package:workout_app/services/sync_device_id.dart';
import 'package:workout_app/services/sync_settings.dart'; import 'package:workout_app/services/sync_settings.dart';
import 'package:workout_app/services/sync_state_factory.dart'; import 'package:workout_app/services/sync_state_factory.dart';
import 'package:workout_app/services/workout_log_store.dart';
import 'package:workout_app/services/workout_sync_session.dart'; import 'package:workout_app/services/workout_sync_session.dart';
part 'workout_sync_service_local.dart';
part 'workout_sync_service_read.dart'; part 'workout_sync_service_read.dart';
part 'workout_sync_service_transfer.dart'; part 'workout_sync_service_transfer.dart';
@ -82,6 +84,7 @@ class WorkoutSyncService {
http.Client? httpClient, http.Client? httpClient,
this.firebaseFactory, this.firebaseFactory,
this.stateStore, this.stateStore,
this.logStore,
// Dart forbids private named params; assign explicitly (as GitHubClient). // Dart forbids private named params; assign explicitly (as GitHubClient).
// ignore: prefer_initializing_formals // ignore: prefer_initializing_formals
}) : _httpClient = httpClient; }) : _httpClient = httpClient;
@ -93,6 +96,9 @@ class WorkoutSyncService {
/// Revision cache. Injected so tests need no application-support directory. /// Revision cache. Injected so tests need no application-support directory.
final SyncStateStore? stateStore; final SyncStateStore? stateStore;
/// This device's local log (outbox + cache); the shared file by default.
final LogStore? logStore;
/// Firebase when this device is set up for it, else null (a normal state /// Firebase when this device is set up for it, else null (a normal state
/// during the cutover: sync then runs over GitHub exactly as before). /// during the cutover: sync then runs over GitHub exactly as before).
Future<FirebaseRestClient?> _openFirebase() => Future<FirebaseRestClient?> _openFirebase() =>
@ -108,6 +114,9 @@ class WorkoutSyncService {
Future<SyncStateStore> _openStateStore() async => Future<SyncStateStore> _openStateStore() async =>
stateStore ?? await openSyncStateStore(); stateStore ?? await openSyncStateStore();
Future<LogStore> _openLogStore() async =>
logStore ?? await openWorkoutLogStore();
/// The repo owner/org to push to. /// The repo owner/org to push to.
final String owner; final String owner;
@ -122,20 +131,7 @@ class WorkoutSyncService {
/// and why. Failures are logged at error level so an unpushed workout /// and why. Failures are logged at error level so an unpushed workout
/// leaves a trace rather than vanishing. /// leaves a trace rather than vanishing.
Future<PushResult> push(WorkoutSession session) async { Future<PushResult> push(WorkoutSession session) async {
final settings = await SyncSettings.load(); final record = Record(
// Either backend counts. Gating on the GitHub token alone silently
// dropped every push from a device connected only to Firebase -- and
// once the mirror is retired that would be every device.
if (!settings.isConfigured && !await _hasFirebaseAccount()) {
const reason = 'sync not configured (no Firebase account, no token)';
log('WorkoutSyncService.push skipped: $reason', level: 900);
return const PushResult(pushed: false, reason: reason);
}
return await _session(settings.token).run(
operation: 'push',
successReason: 'pushed',
failurePrefix: 'push failed',
addition: Record(
id: workoutRecordId(session), id: workoutRecordId(session),
fields: { fields: {
'payload': ( 'payload': (
@ -143,6 +139,17 @@ class WorkoutSyncService {
Hlc.newTick(currentSyncDeviceId), Hlc.newTick(currentSyncDeviceId),
), ),
}, },
);
// Local first, before even asking whether sync is set up: a workout
// finished offline or before sign-in goes out with a later tick.
await _keepLocally(record);
return await _whenConfigured(
'push',
(token) => _session(token).run(
operation: 'push',
successReason: 'pushed',
failurePrefix: 'push failed',
addition: record,
), ),
); );
} }
@ -158,6 +165,7 @@ class WorkoutSyncService {
decode: _decode, decode: _decode,
openFirebaseClient: _openFirebase, openFirebaseClient: _openFirebase,
openStateStore: _openStateStore, openStateStore: _openStateStore,
openLogStore: _openLogStore,
httpClient: _httpClient, httpClient: _httpClient,
); );
@ -171,39 +179,29 @@ class WorkoutSyncService {
/// answer, with a reason a human can act on, which is why this exists. /// answer, with a reason a human can act on, which is why this exists.
/// ///
/// Same never-throw, always-report contract as [push]. /// Same never-throw, always-report contract as [push].
Future<PushResult> syncNow() async { Future<PushResult> syncNow() => _whenConfigured(
final settings = await SyncSettings.load(); 'syncNow',
if (!settings.isConfigured && !await _hasFirebaseAccount()) { // No addition: the round trip itself, plus whatever the local log holds
const reason = 'sync not configured (no Firebase account, no token)'; // that the remote does not have yet (a workout whose push failed).
log('WorkoutSyncService.syncNow skipped: $reason', level: 900); (token) => _session(token).run(
return const PushResult(pushed: false, reason: reason);
}
// No addition: whatever this device already has, unchanged. The point is
// the round trip, not the payload.
return await _session(settings.token).run(
operation: 'syncNow', operation: 'syncNow',
successReason: 'synced', successReason: 'synced',
failurePrefix: 'sync failed', failurePrefix: 'sync failed',
),
); );
}
/// Pushes a pre-built manual-workout [record] to this device's log. /// Pushes a pre-built manual-workout [record] to this device's log.
/// ///
/// Same never-throw, always-report contract as [push]. /// Same never-throw, always-report contract as [push].
Future<PushResult> pushManual(Record record) async { Future<PushResult> pushManual(Record record) => _whenConfigured(
final settings = await SyncSettings.load(); 'pushManual',
if (!settings.isConfigured && !await _hasFirebaseAccount()) { (token) => _session(token).run(
const reason = 'sync not configured (no Firebase account, no token)';
log('WorkoutSyncService.pushManual skipped: $reason', level: 900);
return const PushResult(pushed: false, reason: reason);
}
return await _session(settings.token).run(
operation: 'pushManual', operation: 'pushManual',
successReason: 'pushed', successReason: 'pushed',
failurePrefix: 'push failed', failurePrefix: 'push failed',
addition: record, addition: record,
),
); );
}
/// Returns every device's manual-workout payloads, merged and deduped by id /// Returns every device's manual-workout payloads, merged and deduped by id
/// (highest HLC wins), for computing the shared budget. Pull-only — unlike /// (highest HLC wins), for computing the shared budget. Pull-only — unlike

View File

@ -0,0 +1,97 @@
// The local half of sync: the outbox a push writes first, the cache every
// read keeps, and the "is sync set up" gate the ticks share.
//
// An `extension` in a `part` -- see storage_service_backup.dart for why.
part of 'workout_sync_service.dart';
/// Why a tick did nothing: no Firebase account and no GitHub token.
const kSyncNotConfigured =
'sync not configured (no Firebase account, no token)';
/// Local-first storage around the network ticks.
extension WorkoutSyncServiceLocal on WorkoutSyncService {
/// Runs [tick] with the GitHub token, or reports that sync is not set up.
///
/// Either backend counts. Gating on the GitHub token alone silently
/// dropped every push from a device connected only to Firebase.
Future<PushResult> _whenConfigured(
String operation,
Future<PushResult> Function(String token) tick,
) async {
final settings = await SyncSettings.load();
if (!settings.isConfigured && !await _hasFirebaseAccount()) {
log(
'WorkoutSyncService.$operation skipped: $kSyncNotConfigured',
level: 900,
);
return const PushResult(pushed: false, reason: kSyncNotConfigured);
}
return await tick(settings.token);
}
/// Writes [record] to the local log, so a failed push loses nothing.
///
/// Never throws: the workout itself is already in the history table, and
/// the push still goes ahead. A failure here is logged at error level,
/// since it means a later tick cannot re-send this record.
Future<void> _keepLocally(Record record) async {
try {
await (await _openLogStore()).upsert(record);
} on Object catch (error, stackTrace) {
log(
'WorkoutSyncService: could not keep ${record.id} locally; if this '
'push fails no later tick re-sends it',
level: 1000,
error: error,
stackTrace: stackTrace,
);
}
}
/// Merges [pulled] into the local log, so it stays readable offline.
///
/// Never throws: the caller already has the live answer; losing the cached
/// copy only costs the next offline read, and is logged at error level.
Future<void> _cacheLocally(Log pulled) async {
try {
final store = await _openLogStore();
await store.replaceAll(mergeLogs(store.snapshot(), pulled));
} on Object catch (error, stackTrace) {
log(
'WorkoutSyncService: could not cache the pulled log; offline reads '
'show the previous copy',
level: 1000,
error: error,
stackTrace: stackTrace,
);
}
}
/// Every workout payload the local log holds: this device's own records
/// plus everything the last ticks pulled. No network, so it answers at
/// once and offline; tombstoned records are left out, as in
/// [readMergedWorkoutPayloads].
///
/// Never throws: an unreadable local log answers empty, logged at error
/// level, and the live read that follows still fills the view.
Future<List<Map<String, dynamic>>> readCachedWorkoutPayloads() async {
try {
final store = await _openLogStore();
return [
for (final record in store.values)
if (!record.deleted)
if (record.fields['payload']?.$1 case final Map<dynamic, dynamic> p)
p.cast<String, dynamic>(),
];
} on Object catch (error, stackTrace) {
log(
'WorkoutSyncService: could not read the local log; history waits '
'for the live read',
level: 1000,
error: error,
stackTrace: stackTrace,
);
return const [];
}
}
}

View File

@ -81,6 +81,7 @@ extension WorkoutSyncServiceRead on WorkoutSyncService {
try { try {
final merged = <String, Record>{}; final merged = <String, Record>{};
final tombstoned = <String>{}; final tombstoned = <String>{};
var pulled = <String, Record>{};
for (final device in await client.listDirectory(_pathPrefix)) { for (final device in await client.listDirectory(_pathPrefix)) {
final text = await client.getFileText( final text = await client.getFileText(
'$_pathPrefix/$device/$_logFilename', '$_pathPrefix/$device/$_logFilename',
@ -89,7 +90,10 @@ extension WorkoutSyncServiceRead on WorkoutSyncService {
final log = _decode(text); final log = _decode(text);
_collectTombstones(log, tombstoned); _collectTombstones(log, tombstoned);
_mergeRecords(log, merged, kind: kind); _mergeRecords(log, merged, kind: kind);
pulled = mergeLogs(pulled, log);
} }
// Every device's records, kept for the next offline read.
await _cacheLocally(pulled);
// Suppression is applied across the whole device union, never per file: // Suppression is applied across the whole device union, never per file:
// one device tombstoning a record while another still holds it live must // one device tombstoning a record while another still holds it live must
// delete it, and a per-file skip would just let the live copy win the // delete it, and a per-file skip would just let the live copy win the

View File

@ -57,20 +57,15 @@ extension WorkoutSyncServiceTransfer on WorkoutSyncService {
/// Merges [records] into this device's log and syncs, in one round trip. /// Merges [records] into this device's log and syncs, in one round trip.
/// ///
/// Same never-throw, always-report contract as [pushManual]. /// Same never-throw, always-report contract as [pushManual].
Future<PushResult> pushManualLog(Log records) async { Future<PushResult> pushManualLog(Log records) => _whenConfigured(
final settings = await SyncSettings.load(); 'pushManualLog',
if (!settings.isConfigured && !await _hasFirebaseAccount()) { (token) => _session(token).run(
const reason = 'sync not configured (no Firebase account, no token)';
log('WorkoutSyncService.pushManualLog skipped: $reason', level: 900);
return const PushResult(pushed: false, reason: reason);
}
return await _session(settings.token).run(
operation: 'pushManualLog', operation: 'pushManualLog',
successReason: 'pushed', successReason: 'pushed',
failurePrefix: 'push failed', failurePrefix: 'push failed',
additions: records, additions: records,
),
); );
}
/// A manual workout, or the tombstone of one: tombstones carry no payload, /// A manual workout, or the tombstone of one: tombstones carry no payload,
/// so the id (`manual:<date>T<HH:MM>`) is what identifies them. /// so the id (`manual:<date>T<HH:MM>`) is what identifies them.

View File

@ -1,9 +1,11 @@
/// One sync round-trip: open the backends, merge a log, close them again. /// One sync round-trip: open the backends, merge a log, close them again.
library; library;
import 'dart:async';
import 'dart:developer'; import 'dart:developer';
import 'package:crdt_sync/crdt_sync.dart'; import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'package:workout_app/services/sync_device_id.dart'; import 'package:workout_app/services/sync_device_id.dart';
import 'package:workout_app/services/workout_sync_service.dart'; import 'package:workout_app/services/workout_sync_service.dart';
@ -34,6 +36,7 @@ class WorkoutSyncSession {
required this.decode, required this.decode,
required this.openFirebaseClient, required this.openFirebaseClient,
required this.openStateStore, required this.openStateStore,
required this.openLogStore,
this.httpClient, this.httpClient,
}); });
@ -65,9 +68,33 @@ class WorkoutSyncSession {
/// Opens the revision cache that lets an unchanged peer be skipped. /// Opens the revision cache that lets an unchanged peer be skipped.
final Future<SyncStateStore> Function() openStateStore; final Future<SyncStateStore> Function() openStateStore;
/// Opens this device's local log: the outbox a tick pushes from and the
/// cache it keeps what it pulled in.
final Future<LogStore> Function() openLogStore;
/// Overrides the HTTP client; tests point this at a mock. /// Overrides the HTTP client; tests point this at a mock.
final http.Client? httpClient; final http.Client? httpClient;
/// The tail of the tick queue, null while no tick runs. Ticks run one
/// after another, never side by side: two overlapping ticks each push
/// their own snapshot, and the one that lands last can drop a record the
/// other just added.
///
/// Null when idle rather than a completed future: a future is bound to the
/// zone that made it, so a long-lived one would tie every later tick to a
/// zone that may be gone (a finished widget test's, for one).
static Future<void>? _tail;
/// How long one tick may take before it is reported failed. Bounded
/// because the queue waits on it: one half-open request would otherwise
/// hold every later tick (and the retry) until the app restarts.
@visibleForTesting
static Duration tickTimeout = const Duration(minutes: 2);
/// Forgets a tick a finished test left in flight; see `_tail`.
@visibleForTesting
static void resetQueueForTesting() => _tail = null;
/// Runs one tick, merging [addition] into this device's log if given. /// Runs one tick, merging [addition] into this device's log if given.
/// ///
/// [additions] merges many records in one round trip (the data import). /// [additions] merges many records in one round trip (the data import).
@ -84,6 +111,41 @@ class WorkoutSyncSession {
required String failurePrefix, required String failurePrefix,
Record? addition, Record? addition,
Log? additions, Log? additions,
}) {
Future<PushResult> tick() =>
_runNow(
operation: operation,
successReason: successReason,
failurePrefix: failurePrefix,
addition: addition,
additions: additions,
).timeout(
tickTimeout,
onTimeout: () {
final reason =
'$failurePrefix: no answer within ${tickTimeout.inSeconds} s';
log('WorkoutSyncService.$operation: $reason', level: 1000);
return PushResult(pushed: false, reason: reason);
},
);
final previous = _tail;
final result = previous == null ? tick() : previous.then((_) => tick());
final done = result.then<void>((_) {}, onError: (Object _) {});
_tail = done;
unawaited(
done.then((_) {
if (identical(_tail, done)) _tail = null;
}),
);
return result;
}
Future<PushResult> _runNow({
required String operation,
required String successReason,
required String failurePrefix,
Record? addition,
Log? additions,
}) async { }) async {
final github = GitHubClient( final github = GitHubClient(
owner: owner, owner: owner,
@ -105,10 +167,15 @@ class WorkoutSyncSession {
...?additions, ...?additions,
?addition?.id: ?addition, ?addition?.id: ?addition,
}; };
final localLog = incoming.isEmpty // The local log holds every record a failed or unconfigured push kept,
? existingLog // so this tick sends them too. The remote own file stays in the merge:
: mergeLogs(existingLog, incoming); // after a reinstall it is the only copy of this device's history.
await syncLog( final local = await openLogStore();
final localLog = mergeLogs(
mergeLogs(existingLog, local.snapshot()),
incoming,
);
final merged = await syncLog(
client: client, client: client,
deviceId: currentSyncDeviceId, deviceId: currentSyncDeviceId,
legacyDeviceId: legacySyncDeviceId, legacyDeviceId: legacySyncDeviceId,
@ -121,6 +188,7 @@ class WorkoutSyncSession {
// Firebase free tier's monthly budget depends on not happening. // Firebase free tier's monthly budget depends on not happening.
stateStore: await openStateStore(), stateStore: await openStateStore(),
); );
await _keepPulled(local, merged, operation);
return PushResult(pushed: true, reason: successReason); return PushResult(pushed: true, reason: successReason);
} on Object catch (error, stackTrace) { } on Object catch (error, stackTrace) {
// Deliberately broad: a GitHubSyncError was the only case handled // Deliberately broad: a GitHubSyncError was the only case handled
@ -141,4 +209,26 @@ class WorkoutSyncSession {
firebase?.close(); firebase?.close();
} }
} }
/// Keeps [merged] in [local] for offline reads. Merged onto the store as
/// it is NOW, not replaced: a workout written while this tick ran must
/// survive it. Never throws: the tick already reached the remote, so a
/// local write failure costs only the offline copy, and is logged.
static Future<void> _keepPulled(
LogStore local,
Log merged,
String operation,
) async {
try {
await local.replaceAll(mergeLogs(local.snapshot(), merged));
} on Object catch (error, stackTrace) {
log(
'WorkoutSyncService.$operation synced, but the local copy was not '
'saved; offline reads show the previous one',
level: 1000,
error: error,
stackTrace: stackTrace,
);
}
}
} }

View File

@ -14,16 +14,23 @@ import 'dart:io';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/desktop_config_dir.dart'; import 'package:workout_app/services/desktop_config_dir.dart';
import 'package:workout_app/services/workout_log_store.dart';
import 'package:workout_app/services/workout_sync_session.dart';
Future<void> testExecutable(FutureOr<void> Function() testMain) async { Future<void> testExecutable(FutureOr<void> Function() testMain) async {
// Also set up front, so code that runs while tests are being declared is // Also set up front, so code that runs while tests are being declared is
// redirected too, not only code inside a test body. // redirected too, not only code inside a test body.
final declarationRoot = _freshRoot(); final declarationRoot = _freshRoot();
desktopConfigRootOverride = declarationRoot.path; desktopConfigRootOverride = declarationRoot.path;
// The workout log (outbox + cache) gets the same per-test root, so no test
// reads another's records or reaches the app support directory.
workoutLogDirOverride = declarationRoot.path;
tearDownAll(() => declarationRoot.deleteSync(recursive: true)); tearDownAll(() => declarationRoot.deleteSync(recursive: true));
setUp(() { setUp(() {
final root = _freshRoot(); final root = _freshRoot();
desktopConfigRootOverride = root.path; desktopConfigRootOverride = root.path;
workoutLogDirOverride = root.path;
WorkoutSyncSession.resetQueueForTesting();
addTearDown(() => root.deleteSync(recursive: true)); addTearDown(() => root.deleteSync(recursive: true));
}); });
await testMain(); await testMain();

View File

@ -0,0 +1,60 @@
/// Offline-first history: local rows show at once, never behind the network.
library;
import 'dart:async';
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:material_ui/material_ui.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/services/storage_service.dart';
import '../fake_secure_storage.dart';
import '_history_test_fixtures.dart';
/// A backend that never answers: the phone is offline, or the network hangs.
http.Client _hangingRemote() =>
MockClient((_) => Completer<http.Response>().future);
void main() {
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
StorageService.resetForTesting();
await StorageService.init();
installFakeSecureStorage(initial: {'sync.token': 'tok'});
});
testWidgets('local sessions show while the remote read hangs', (
tester,
) async {
await seedSession(tester, jsonEncode({'exercises': <Object>[]}));
await pumpHistory(tester, wrapHistory(httpClient: _hangingRemote()));
expect(find.byType(CircularProgressIndicator), findsNothing);
expect(find.text('A · 2024-06-01'), findsWidgets);
});
testWidgets('synced PC rows from the last read show while offline', (
tester,
) async {
final pcRow = find.byKey(const ValueKey('synced-2026-07-13-Run'));
await pumpHistory(tester, wrapHistory(httpClient: historySyncMock()));
await tester.pumpWidget(const SizedBox());
await pumpHistory(tester, wrapHistory(httpClient: _hangingRemote()));
await tester.scrollUntilVisible(
pcRow,
200,
scrollable: find.byType(Scrollable).first,
);
expect(pcRow, findsOneWidget);
});
}

View File

@ -175,8 +175,9 @@ void main() {
final record = _phoneRecord(github.files, 'manual:2026-10-17T10:00'); final record = _phoneRecord(github.files, 'manual:2026-10-17T10:00');
expect(record.deleted, isTrue); expect(record.deleted, isTrue);
expect(record.deletedHlc, isNotNull); expect(record.deletedHlc, isNotNull);
// The tile goes only once the reload has read the tombstone back. // The tile goes only once the reload has read the tombstone back; the
await _settle(tester, 4); // tick keeps its result locally first, which is more real file I/O.
await _settle(tester, 12);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(iconLabeled('PLANNED (not done yet)'), findsNothing); expect(iconLabeled('PLANNED (not done yet)'), findsNothing);
expect(find.text('2026-10-17 10:00'), findsNothing); expect(find.text('2026-10-17 10:00'), findsNothing);

View File

@ -0,0 +1,61 @@
// Finishing a workout keeps its sync record in the local log before any
// network call: this phone has no sync set up, and the record must still be
// there for the first tick after sign-in.
import 'dart:io';
import 'package:material_ui/material_ui.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as p;
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/workout_log_store.dart';
import '../fake_audio_platform.dart';
import '../fake_break_service.dart';
import '../fake_secure_storage.dart';
import '_workout_screen_test_fixtures.dart';
import '../icon_finders.dart';
void main() {
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
StorageService.resetForTesting();
await StorageService.init();
installFakeSecureStorage();
installFakeAudioPlatform();
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
});
testWidgets('a finished workout lands in the local log at once', (
tester,
) async {
await pumpWorkout(
tester,
wrapWorkout(
savedState: completeSaved(),
breakClient: FakeForegroundBreakClient(),
),
);
final logFile = File(p.join(workoutLogDirOverride!, kWorkoutLogFileName));
final text = await tester.runAsync(() async {
await tester.tap(buttonLabeled<TextButton>('Finish'));
await Future<void>.delayed(const Duration(milliseconds: 200));
await tester.pump();
await tester.tap(buttonLabeled<TextButton>('Finish').last);
await Future<void>.delayed(const Duration(milliseconds: 800));
await tester.pump();
return logFile.existsSync() ? logFile.readAsString() : null;
});
// The record id is the session's start time (see workoutRecordId).
expect(text, contains('"payload"'));
expect(text, contains('"workout_type"'));
});
}

View File

@ -0,0 +1,53 @@
// A stateful sync remote for the offline-first tests: PUTs land, later GETs
// see them, and `down` makes every request fail like a dead network.
import 'dart:convert';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart' as http_testing;
import '_sync_test_fixtures.dart';
/// A GitHub Contents API double whose PUTs land, so a later GET sees them.
class FakeRemote {
final files = <String, String>{};
final logPuts = <Map<String, dynamic>>[];
bool down = false;
http.Client client() => http_testing.MockClient((request) async {
if (down) throw http.ClientException('offline');
final path = request.url.path;
if (!path.contains('/contents/')) return syncResponse(200);
final key = path.split('/contents/').last;
if (request.method == 'PUT') {
final body = jsonDecode(request.body) as Map<String, dynamic>;
final text = utf8.decode(base64.decode(body['content'] as String));
files[key] = text;
if (key.endsWith('log.json')) {
logPuts.add(jsonDecode(text) as Map<String, dynamic>);
}
return syncResponse(200, {'content': <String, dynamic>{}});
}
if (key == 'screen-locker-sync/devices') {
final devices = {
for (final k in files.keys)
if (k.startsWith('screen-locker-sync/devices/')) k.split('/')[2],
};
return syncResponse(200, [
for (final d in devices) {'name': d, 'type': 'dir'},
]);
}
final text = files[key];
return text == null ? syncResponse(404) : fileContaining(text);
});
}
Record pcRunRecord() => Record(
id: 'runnerup_verified:2026-07-13',
fields: {
'payload': (
{'kind': 'runnerup_verified', 'date': '2026-07-13'},
Hlc(wallTimeMs: 1000, counter: 0, nodeId: 'pc'),
),
},
);

View File

@ -93,12 +93,14 @@ WorkoutSyncService syncService({
String? owner, String? owner,
String? repo, String? repo,
Future<FirebaseRestClient?> Function()? firebaseFactory, Future<FirebaseRestClient?> Function()? firebaseFactory,
LogStore? logStore,
}) => WorkoutSyncService( }) => WorkoutSyncService(
httpClient: httpClient, httpClient: httpClient,
owner: owner ?? syncRepoOwner, owner: owner ?? syncRepoOwner,
repo: repo ?? syncRepoName, repo: repo ?? syncRepoName,
firebaseFactory: firebaseFactory ?? () async => null, firebaseFactory: firebaseFactory ?? () async => null,
stateStore: InMemorySyncStateStore(), stateStore: InMemorySyncStateStore(),
logStore: logStore,
); );
/// A Firebase client wired to an in-memory mock, for the cutover tests. /// A Firebase client wired to an in-memory mock, for the cutover tests.

View File

@ -0,0 +1,54 @@
/// Where the local workout log lives, and that the app shares one instance.
@TestOn('vm')
library;
import 'dart:io';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as p;
import 'package:workout_app/services/workout_log_store.dart';
import '../fake_path_provider.dart';
Record _record(String id) => Record(
id: id,
fields: {
'payload': (
{'date': '2026-07-05'},
Hlc(wallTimeMs: 1, counter: 0, nodeId: 'phone'),
),
},
);
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('lives in the app support directory, beside sync_state.json', () async {
final support = installFakePathProvider();
addTearDown(() => support.deleteSync(recursive: true));
workoutLogDirOverride = null;
await (await openWorkoutLogStore()).upsert(_record('a'));
expect(
File(p.join(support.path, kWorkoutLogFileName)).existsSync(),
isTrue,
);
});
test('one store per directory, reopened when the directory changes', () {
final first = workoutLogDirOverride!;
final other = Directory.systemTemp.createTempSync('wo_log_');
addTearDown(() => other.deleteSync(recursive: true));
return Future.wait([openWorkoutLogStore(), openWorkoutLogStore()]).then((
same,
) async {
expect(identical(same[0], same[1]), isTrue);
workoutLogDirOverride = other.path;
expect(identical(await openWorkoutLogStore(), same[0]), isFalse);
workoutLogDirOverride = first;
});
});
}

View File

@ -0,0 +1,88 @@
/// A failed workout push is retried by itself until a tick gets through.
library;
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/workout_resync.dart';
import 'package:workout_app/services/workout_sync_service.dart';
/// A scheduler that keeps the callbacks instead of starting real timers.
class _Clock {
final pending = <void Function()>[];
final delays = <Duration>[];
Timer call(Duration after, void Function() fire) {
delays.add(after);
pending.add(fire);
return Timer(Duration.zero, () {})..cancel();
}
Future<void> fireNext() async {
pending.removeAt(0)();
await Future<void>.delayed(Duration.zero);
}
}
const _failed = PushResult(pushed: false, reason: 'push failed: offline');
const _ok = PushResult(pushed: true, reason: 'synced');
void main() {
test('a failed push arms a retry that runs a sync tick', () async {
final clock = _Clock();
var ticks = 0;
WorkoutResync(
syncNow: () async {
ticks++;
return _ok;
},
scheduler: clock.call,
).note(_failed);
expect(clock.delays, [kWorkoutResyncAfter]);
await clock.fireNext();
expect(ticks, 1);
expect(clock.pending, isEmpty);
});
test('a retry that fails again arms the next one', () async {
final clock = _Clock();
WorkoutResync(
syncNow: () async => _failed,
scheduler: clock.call,
).note(_failed);
await clock.fireNext();
expect(clock.pending, hasLength(1));
});
test('no retry while sync is not set up, nor after a success', () {
final clock = _Clock();
WorkoutResync(syncNow: () async => _ok, scheduler: clock.call)
..note(const PushResult(pushed: false, reason: kSyncNotConfigured))
..note(_ok);
expect(clock.pending, isEmpty);
});
test('two failures arm one retry, not two', () {
final clock = _Clock();
WorkoutResync(syncNow: () async => _ok, scheduler: clock.call)
..note(_failed)
..note(_failed);
expect(clock.pending, hasLength(1));
});
test('syncNow runs a tick at once and folds its result in', () async {
final clock = _Clock();
await WorkoutResync(
syncNow: () async => _failed,
scheduler: clock.call,
).syncNow();
expect(clock.pending, hasLength(1));
});
}

View File

@ -0,0 +1,101 @@
/// Offline-first: everything a tick or a live read pulled is kept locally and
/// readable with the network gone.
library;
import 'dart:convert';
import 'dart:io';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/workout_log_store.dart';
import 'package:workout_app/services/workout_sync_service.dart';
import '../fake_secure_storage.dart';
import '_sync_remote_fixture.dart';
import '_sync_test_fixtures.dart';
/// A local log whose disk is gone: reading its records and every write throw.
class _BrokenStore extends LogStore {
_BrokenStore() : super(persistence: _NoPersistence(), nodeId: 'phone');
@override
Iterable<Record> get values => throw const FileSystemException('gone');
@override
Future<void> upsert(Record record) async =>
throw const FileSystemException('gone');
@override
Future<void> replaceAll(Log merged) async =>
throw const FileSystemException('gone');
}
class _NoPersistence implements LogPersistence {
@override
Future<String?> read() async => null;
@override
Future<void> write(String text) async {}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('records a tick pulled stay readable with the network gone', () async {
installFakeSecureStorage(initial: {'sync.token': 'tok'});
final remote = FakeRemote();
remote.files['screen-locker-sync/devices/pc/log.json'] = jsonEncode({
pcRunRecord().id: pcRunRecord().toJson(),
});
await syncService(httpClient: remote.client()).syncNow();
remote.down = true;
// A store reopened from disk: what the next app launch reads.
final cached = await syncService(
httpClient: remote.client(),
logStore: await openWorkoutLogStoreIn(workoutLogDirOverride!),
).readCachedWorkoutPayloads();
expect(cached.map((p) => p['kind']), contains('runnerup_verified'));
});
test('a live history read is kept for the next offline read', () async {
installFakeSecureStorage(initial: {'sync.token': 'tok'});
final remote = FakeRemote();
remote.files['screen-locker-sync/devices/pc/log.json'] = jsonEncode({
pcRunRecord().id: pcRunRecord().toJson(),
});
final live = await syncService(
httpClient: remote.client(),
).readMergedWorkoutPayloads();
expect(live, hasLength(1));
remote.down = true;
final cached = await syncService(
httpClient: remote.client(),
).readCachedWorkoutPayloads();
expect(cached.map((p) => p['date']), ['2026-07-13']);
});
test('a broken local log never breaks a push or a read', () async {
installFakeSecureStorage(initial: {'sync.token': 'tok'});
final remote = FakeRemote();
remote.files['screen-locker-sync/devices/pc/log.json'] = jsonEncode({
pcRunRecord().id: pcRunRecord().toJson(),
});
WorkoutSyncService broken() =>
syncService(httpClient: remote.client(), logStore: _BrokenStore());
// The push still reaches the remote; only the local copy is lost.
final pushed = await broken().push(workoutSession());
final live = await broken().readMergedWorkoutPayloads();
final cached = await broken().readCachedWorkoutPayloads();
expect(pushed.pushed, isTrue);
expect(remote.logPuts, isNotEmpty);
// The PC's run plus the workout just pushed: the remote has both.
expect(live, hasLength(2));
expect(cached, isEmpty);
});
}

View File

@ -0,0 +1,115 @@
/// Offline-first: a finished workout survives a dead network and goes out by
/// itself on the next tick.
///
/// The PC credits a workout once per `{type}:{date}` (see
/// `screen_locker/_log_mixin.py:_derive_workout_id` and
/// `test_session_sync.py::test_is_idempotent_across_repeated_syncs`), so a
/// re-push is safe there; these tests pin the phone half: the re-push carries
/// the very same record (same id, same clock), never a fresh copy.
library;
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart' as http_testing;
import 'package:workout_app/services/workout_sync_service.dart';
import 'package:workout_app/services/workout_sync_session.dart';
import '../fake_secure_storage.dart';
import '_sync_remote_fixture.dart';
import '_sync_test_fixtures.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('a push that failed goes out with the next sync tick', () async {
installFakeSecureStorage(initial: {'sync.token': 'tok'});
final remote = FakeRemote()..down = true;
final session = workoutSession();
final failed = await syncService(httpClient: remote.client()).push(session);
expect(failed.pushed, isFalse);
remote.down = false;
final synced = await syncService(httpClient: remote.client()).syncNow();
expect(synced.pushed, isTrue);
expect(remote.logPuts.last.keys, contains(workoutRecordId(session)));
});
test('a workout finished before sync was set up goes out later', () async {
installFakeSecureStorage();
final remote = FakeRemote();
final session = workoutSession();
final skipped = await syncService(
httpClient: remote.client(),
).push(session);
expect(skipped.reason, contains('not configured'));
installFakeSecureStorage(initial: {'sync.token': 'tok'});
await syncService(httpClient: remote.client()).syncNow();
expect(remote.logPuts.last.keys, contains(workoutRecordId(session)));
});
test('the re-push carries the same record, not a new copy', () async {
installFakeSecureStorage(initial: {'sync.token': 'tok'});
final remote = FakeRemote()..down = true;
final session = workoutSession();
await syncService(httpClient: remote.client()).push(session);
remote.down = false;
await syncService(httpClient: remote.client()).syncNow();
final first = remote.logPuts.last[workoutRecordId(session)];
await syncService(httpClient: remote.client()).syncNow();
// Byte-identical record: one id, one clock. The PC sees nothing new.
final records = remote.logPuts.expand((log) => log.keys).toSet();
expect(records, {workoutRecordId(session)});
expect(remote.logPuts.last[workoutRecordId(session)], first);
});
test('overlapping ticks run one after another, the last one complete', () {
installFakeSecureStorage(initial: {'sync.token': 'tok'});
final remote = FakeRemote();
final session = workoutSession();
return Future.wait([
syncService(httpClient: remote.client()).syncNow(),
syncService(httpClient: remote.client()).push(session),
]).then((results) {
expect(results.every((r) => r.pushed), isTrue);
expect(remote.logPuts.last.keys, contains(workoutRecordId(session)));
});
});
test('a tick that never answers is cut off and frees the queue', () async {
installFakeSecureStorage(initial: {'sync.token': 'tok'});
final saved = WorkoutSyncSession.tickTimeout;
WorkoutSyncSession.tickTimeout = const Duration(milliseconds: 50);
addTearDown(() => WorkoutSyncSession.tickTimeout = saved);
final hanging = http_testing.MockClient(
(_) => Completer<http.Response>().future,
);
final remote = FakeRemote();
final hung = syncService(httpClient: hanging).push(workoutSession());
// Let the push keep its record and take the queue before the next tick.
await Future<void>.delayed(const Duration(milliseconds: 10));
final results = await Future.wait([
hung,
syncService(httpClient: remote.client()).syncNow(),
]);
expect(results.first.pushed, isFalse);
expect(results.first.reason, contains('no answer'));
// The record the hung push kept goes out with the tick queued behind it.
expect(results.last.pushed, isTrue);
expect(
remote.logPuts.last.keys,
contains(workoutRecordId(workoutSession())),
);
});
}