Add run recorder, upload queue, saver

State machine over PositionSource + GpsFilter with pause segments, pending-run WebDAV PUT queue, dufs login import.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
This commit is contained in:
Krzysztof Rudnicki 2026-11-10 16:00:31 +01:00
parent 63caf9dee9
commit 8a26387396
11 changed files with 1633 additions and 0 deletions

View File

@ -76,6 +76,7 @@ class GpsFilter {
final List<RunPoint> _points = [];
int _jumps = 0;
bool _segmentBreak = false;
/// Accepted points so far, in time order.
List<RunPoint> get points => List.unmodifiable(_points);
@ -83,6 +84,14 @@ class GpsFilter {
/// Cumulative credited distance in metres.
double get distanceM => _points.isEmpty ? 0 : _points.last.distanceM;
/// Marks a pause: the next accepted fix starts a new segment, credited with
/// nothing, whatever distance separates it from the last point.
///
/// Without this, a short pause (under [kMaxCreditGapSeconds]) would credit
/// the walk across the paused stretch, and a long one could trip the jump
/// cap on the first fix after resuming.
void breakSegment() => _segmentBreak = true;
/// Judges [fix]; an accepted fix is appended to [points].
FixVerdict add(GpsFix fix) {
if (fix.isMocked) return FixVerdict.mocked;
@ -101,6 +110,11 @@ class GpsFilter {
final last = _points.last;
final gap = time.difference(last.time).inSeconds;
if (gap <= 0) return FixVerdict.outOfOrder;
if (_segmentBreak) {
_segmentBreak = false;
_accept(fix, time, 0);
return FixVerdict.accepted;
}
final step = haversineM(
last.latitude,
last.longitude,

View File

@ -0,0 +1,40 @@
/// Number formatting for the live run screen and its notification.
///
/// Numbers only (textgate): the digits are the whole display.
library;
/// Distance below which a pace means nothing (GPS noise at the start line).
const double kMinPaceDistanceM = 20;
/// `m:ss`, or `h:mm:ss` from one hour on.
String formatDuration(int seconds) {
final s = seconds < 0 ? 0 : seconds;
String two(int v) => v.toString().padLeft(2, '0');
final h = s ~/ 3600;
final m = s % 3600 ~/ 60;
return h > 0 ? '$h:${two(m)}:${two(s % 60)}' : '$m:${two(s % 60)}';
}
/// Kilometres with two decimals, e.g. `3.52`.
String formatKm(double metres) => (metres / 1000).toStringAsFixed(2);
/// Average pace in seconds per km, or null while the run is too short.
double? paceSecPerKm(int movingSeconds, double metres) =>
metres < kMinPaceDistanceM ? null : movingSeconds / (metres / 1000);
/// `m:ss` per km, or `--:--` while there is no pace yet.
String formatPace(double? secPerKm) =>
secPerKm == null || secPerKm.isInfinite || secPerKm.isNaN
? '--:--'
: formatDuration(secPerKm.round());
/// The two notification lines: distance, then time and pace.
({String title, String body}) runNotificationCopy({
required double metres,
required int movingSeconds,
}) => (
title: formatKm(metres),
body:
'${formatDuration(movingSeconds)} '
'${formatPace(paceSecPerKm(movingSeconds, metres))}',
);

View File

@ -0,0 +1,275 @@
/// The GPS run/walk state machine: idle, recording, paused, finished.
library;
import 'dart:async';
import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox_log.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_format.dart';
import 'package:workout_app/services/run_math.dart';
/// Where a recording stands.
enum RunPhase {
/// Nothing recorded yet; the sport can still be chosen.
idle,
/// Fixes are being kept and credited.
recording,
/// Fixes are ignored; nothing is credited until [RunRecorder.resume].
paused,
/// Over; [RunRecorder.finish] has returned the track.
finished,
}
/// What is wrong with the recording right now (shown as an icon, logged).
enum RunIssue {
/// Nothing.
none,
/// Location permission refused; asking again may work.
denied,
/// Location permission refused for good; only system settings can fix it.
deniedForever,
/// The device's location switch is off.
serviceOff,
/// The newest fix came from a mock-location provider and was dropped.
mockedLocation,
/// The location stream reported an error.
streamError,
/// Finished with too few usable fixes to make a track; nothing was saved.
tooShort,
}
/// Records one run or walk from a [PositionSource].
///
/// A pause ignores fixes and breaks the filter's segment, so the stretch
/// walked while paused and the first fix after it credit nothing. Moving time
/// is the PC's rule ([movingSeconds]) applied as fixes arrive, so the number
/// on screen is the number the PC will credit.
class RunRecorder extends ChangeNotifier {
/// Creates a recorder; [sourceFor] builds the fix stream for the chosen
/// sport when [start] is called (the sandbox's replay speed follows it).
RunRecorder({required this.sourceFor, this.onKilometre});
/// Builds the source for one recording.
final PositionSource Function(RunSport sport) sourceFor;
/// Called with 1, 2, 3 ... as each whole kilometre is credited.
final void Function(int km)? onKilometre;
RunSport _sport = RunSport.running;
RunPhase _phase = RunPhase.idle;
RunIssue _issue = RunIssue.none;
GpsFilter? _filter;
StreamSubscription<GpsFix>? _sub;
bool _starting = false;
int _moving = 0;
int _km = 0;
final _live = ValueNotifier<List<RunPoint>>(const []);
final _seenVerdicts = <FixVerdict>{};
/// Running or walking.
RunSport get sport => _sport;
/// The state machine's phase.
RunPhase get phase => _phase;
/// The current problem, or [RunIssue.none].
RunIssue get issue => _issue;
/// Accepted points so far, for the live map.
ValueListenable<List<RunPoint>> get livePoints => _live;
/// Credited moving time in seconds.
int get seconds => _moving;
/// Credited distance in metres.
double get distanceM => _filter?.distanceM ?? 0;
/// Average pace in seconds per km, or null while the run is too short.
double? get pace => paceSecPerKm(_moving, distanceM);
/// Picks the sport; only possible while [RunPhase.idle].
bool selectSport(RunSport sport) {
if (_phase != RunPhase.idle) return false;
_sport = sport;
notifyListeners();
return true;
}
/// Asks for location access, runs [afterAccess] (where the caller starts the
/// foreground service, which Android 14 only allows once access is held),
/// then begins recording. False when access was refused or a start is
/// already under way; [issue] says why.
Future<bool> start({Future<void> Function()? afterAccess}) async {
if (_phase != RunPhase.idle || _starting) return false;
_starting = true;
try {
final source = sourceFor(_sport);
final access = await source.requestAccess();
if (!access.isGranted) {
_refuse(access);
return false;
}
await afterAccess?.call();
_filter = GpsFilter(sport: _sport);
_sub = source
.fixes() // the source's default 2 s, far under kMaxCreditGapSeconds
.listen(_onFix, onError: _onError, onDone: _onDone);
_issue = RunIssue.none;
_phase = RunPhase.recording;
SandboxLog.event('run started', {'sport': _sport.tcxName});
notifyListeners();
return true;
} finally {
_starting = false;
}
}
/// Stops crediting until [resume].
void pause() {
if (_phase != RunPhase.recording) return;
_filter!.breakSegment();
_phase = RunPhase.paused;
SandboxLog.event('run paused', {'km': formatKm(distanceM)});
notifyListeners();
}
/// Continues after [pause].
void resume() {
if (_phase != RunPhase.paused) return;
_phase = RunPhase.recording;
SandboxLog.event('run resumed', {'km': formatKm(distanceM)});
notifyListeners();
}
/// Ends the recording and returns the track, or null when there were too
/// few usable fixes (then [issue] is [RunIssue.tooShort]).
Future<RunTrack?> finish() async {
if (_phase != RunPhase.recording && _phase != RunPhase.paused) return null;
await _sub?.cancel();
_sub = null;
_phase = RunPhase.finished;
final points = _filter!.points;
_moving = movingSeconds(points, _sport);
RunTrack? track;
if (points.length < 2) {
_issue = RunIssue.tooShort;
log(
'RunRecorder: finished with ${points.length} usable GPS fix(es) '
'-- not enough for a track, so nothing is saved.',
level: 1000,
);
} else {
track = RunTrack.started(
sport: _sport,
startedAt: points.first.time,
points: points,
totalSeconds: _moving,
distanceM: _filter!.distanceM,
);
}
SandboxLog.event('run finished', {
'km': formatKm(distanceM),
'secs': _moving,
'points': points.length,
'saved': track != null,
});
notifyListeners();
return track;
}
void _refuse(LocationAccess access) {
_issue = switch (access) {
LocationAccess.deniedForever => RunIssue.deniedForever,
LocationAccess.serviceOff => RunIssue.serviceOff,
_ => RunIssue.denied,
};
final fix = access == LocationAccess.serviceOff
? 'Switch location on'
: 'Grant location to the app in system settings';
log(
'RunRecorder: not recording -- location access is ${access.name}. '
'$fix and start again.',
level: 1000,
);
notifyListeners();
}
void _onFix(GpsFix fix) {
if (_phase != RunPhase.recording) return;
final verdict = _filter!.add(fix);
if (verdict != FixVerdict.accepted) {
_noteDropped(verdict);
return;
}
_issue = RunIssue.none;
final points = _filter!.points;
final n = points.length;
if (n >= 2 &&
isMovingStep(points[n - 2], points[n - 1], maxSpeedMps(_sport))) {
_moving += points[n - 1].time.difference(points[n - 2].time).inSeconds;
}
_live.value = points;
while (distanceM ~/ 1000 > _km) {
_km++;
SandboxLog.event('run km', {'km': _km, 'secs': _moving});
onKilometre?.call(_km);
}
notifyListeners();
}
void _noteDropped(FixVerdict verdict) {
if (verdict == FixVerdict.mocked) {
_issue = RunIssue.mockedLocation;
notifyListeners();
}
// Said once per kind and run: a bad tunnel would otherwise flood the log.
if (!_seenVerdicts.add(verdict)) return;
log(
'RunRecorder: dropped a GPS fix (${verdict.name}); further drops of '
'this kind are not logged. Mock fixes never count towards a run.',
level: 900,
);
}
void _onError(Object error, StackTrace stack) {
_issue = RunIssue.streamError;
log(
'RunRecorder: the location stream failed ($error) -- fixes may have '
'stopped; time and distance are not crediting until they resume.',
level: 1000,
error: error,
stackTrace: stack,
);
notifyListeners();
}
void _onDone() {
if (_phase != RunPhase.recording && _phase != RunPhase.paused) return;
log(
'RunRecorder: the location stream ended while still recording; '
'finish the run to save what was captured.',
level: 900,
);
SandboxLog.event('run stream ended', {'km': formatKm(distanceM)});
}
@override
void dispose() {
unawaited(_sub?.cancel());
_live.dispose();
super.dispose();
}
}

View File

@ -0,0 +1,52 @@
/// Stores a finished recording and queues it for upload.
library;
import 'dart:async';
import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:workout_app/models/run_record.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox_log.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/tcx_codec.dart';
/// What [saveRecordedRun] did.
@immutable
class RunSaveResult {
/// Creates a result.
const RunSaveResult({required this.stored, required this.reason});
/// Whether a new row was written.
final bool stored;
/// A sentence saying what happened.
final String reason;
}
/// Writes [track] to the `runs` table as an app-recorded, pending-upload run
/// and calls [enqueue] (without awaiting it) so the upload starts now.
Future<RunSaveResult> saveRecordedRun(
RunTrack track, {
required StorageService storage,
required Future<Object?> Function() enqueue,
}) async {
final tcx = encodeTcx(track);
final name = tcxFilename(track);
final stored = await storage.insertRun(
track,
tcxFilename: name,
tcxSha256: tcxSha256(tcx),
uploadState: RunUploadState.pending,
);
if (!stored) {
final reason =
'run ${track.id} is already stored (same id or same TCX), so '
'nothing new was saved or queued.';
log('RunSaver: $reason', level: 1000);
return RunSaveResult(stored: false, reason: reason);
}
SandboxLog.event('run saved', {'id': track.id, 'file': name});
unawaited(enqueue());
return RunSaveResult(stored: true, reason: 'saved $name');
}

View File

@ -0,0 +1,163 @@
/// Where finished runs are uploaded, and the login for it.
///
/// The login is a dufs account scoped to the PC's `/RunnerUp` folder. It is
/// never typed on the phone: `scripts/provision_run_upload.sh` pushes a
/// `dufs_login.json` into the app's external files directory, and
/// [RunCredentialStore.importProvisionFile] moves it into secure storage and
/// deletes the file.
library;
import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:path_provider/path_provider.dart';
/// File name the provisioning script pushes.
const String kProvisionFileName = 'dufs_login.json';
/// A dufs login.
@immutable
class RunUploadCredentials {
/// Creates a login; [baseUrl] has no trailing slash.
const RunUploadCredentials({
required this.baseUrl,
required this.user,
required this.password,
});
/// The dufs server, e.g. `https://host`.
final String baseUrl;
/// The dufs user.
final String user;
/// The dufs password.
final String password;
/// The `Authorization` header value.
String get basicAuth =>
'Basic ${base64.encode(utf8.encode('$user:$password'))}';
}
/// What an import attempt found.
enum ProvisionStatus {
/// No file: the normal case on every start after the first.
absent,
/// Login stored and the file deleted.
imported,
/// A file was there but unusable; it was left in place.
invalid,
}
/// Result of [RunCredentialStore.importProvisionFile].
@immutable
class ProvisionOutcome {
/// Creates an outcome.
const ProvisionOutcome(this.status, this.reason);
/// What happened.
final ProvisionStatus status;
/// A sentence saying why.
final String reason;
}
Future<Directory?> _externalFilesDir() async {
// coverage:ignore-start
// Android-only plugin call; path_provider throws on every other platform.
if (Platform.isAndroid) return await getExternalStorageDirectory();
// coverage:ignore-end
return null;
}
/// Reads and writes the upload login in secure storage.
class RunCredentialStore {
/// Creates a store; the arguments are test seams.
RunCredentialStore({
this._secure = const FlutterSecureStorage(),
this._externalDir = _externalFilesDir,
});
static const _urlKey = 'run_upload_url';
static const _userKey = 'run_upload_user';
static const _passwordKey = 'run_upload_password';
final FlutterSecureStorage _secure;
final Future<Directory?> Function() _externalDir;
/// The stored login, or null when none was provisioned yet.
Future<RunUploadCredentials?> read() async {
final url = await _secure.read(key: _urlKey);
final user = await _secure.read(key: _userKey);
final password = await _secure.read(key: _passwordKey);
if (url == null || user == null || password == null) return null;
return RunUploadCredentials(baseUrl: url, user: user, password: password);
}
/// Moves `<external files dir>/dufs_login.json` into secure storage and
/// deletes it. An unusable file stays put and is reported, so a typo in the
/// script's output cannot silently leave uploads switched off.
Future<ProvisionOutcome> importProvisionFile() async {
final dir = await _externalDir();
if (dir == null) {
return const ProvisionOutcome(
ProvisionStatus.absent,
'no external files directory on this platform',
);
}
final file = File('${dir.path}/$kProvisionFileName');
if (!file.existsSync()) {
return const ProvisionOutcome(ProvisionStatus.absent, 'no login file');
}
final login = _parse(await file.readAsString());
if (login == null) {
const reason =
'$kProvisionFileName is not {"url","user","password"} with an '
'http(s) url, so run uploads stay switched off. Re-run '
'scripts/provision_run_upload.sh.';
log('RunCredentialStore: $reason', level: 1000);
return const ProvisionOutcome(ProvisionStatus.invalid, reason);
}
await _secure.write(key: _urlKey, value: login.baseUrl);
await _secure.write(key: _userKey, value: login.user);
await _secure.write(key: _passwordKey, value: login.password);
await file.delete();
log('RunCredentialStore: imported the run-upload login for ${login.user}.');
return ProvisionOutcome(
ProvisionStatus.imported,
'imported the login for ${login.user}',
);
}
RunUploadCredentials? _parse(String text) {
final Object? decoded;
try {
decoded = jsonDecode(text);
} on FormatException catch (error) {
log('RunCredentialStore: $kProvisionFileName is not JSON ($error)');
return null;
}
if (decoded is! Map) return null;
final url = decoded['url'];
final user = decoded['user'];
final password = decoded['password'];
if (url is! String || user is! String || password is! String) return null;
final uri = Uri.tryParse(url.trim());
if (uri == null ||
!uri.hasAuthority ||
!const {'http', 'https'}.contains(uri.scheme)) {
return null;
}
if (user.isEmpty || password.isEmpty) return null;
return RunUploadCredentials(
baseUrl: url.trim().replaceFirst(RegExp(r'/+$'), ''),
user: user,
password: password,
);
}
}

View File

@ -0,0 +1,241 @@
/// Uploads recorded runs to the PC's dufs inbox.
///
/// The PC credits a run from the TCX it finds in `/RunnerUp`; the credit is
/// anchored on the run's own time, so a late upload still counts in full. The
/// queue is the `runs` table itself (upload_state `pending`), so nothing here
/// can lose a run: a failure just leaves the row pending for the next try.
library;
import 'dart:async';
import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:workout_app/models/run_record.dart';
import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/sandbox/sandbox_log.dart';
import 'package:workout_app/services/run_upload_credentials.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/tcx_codec.dart';
/// Server folder the PC watches.
const String kRunInboxFolder = 'RunnerUp';
/// How long one PUT may take.
const Duration kUploadTimeout = Duration(seconds: 30);
/// How long after a failure the queue tries again while the app is open.
const Duration kUploadRetryAfter = Duration(minutes: 1);
/// Where the queue stands (shown as an icon).
enum UploadHealth {
/// Nothing waiting, or everything went through.
idle,
/// A pass is running.
uploading,
/// The last pass failed; a retry is scheduled.
retrying,
/// Runs are waiting but no login was provisioned.
notConfigured,
/// The sandbox flavor: runs are kept, nothing is ever sent.
sandbox,
}
/// A snapshot of the queue.
@immutable
class RunUploadStatus {
/// Creates a status.
const RunUploadStatus(this.health, this.pending, [this.reason = '']);
/// What the queue is doing.
final UploadHealth health;
/// Runs still waiting.
final int pending;
/// A sentence for the log.
final String reason;
}
/// The pending-run upload queue.
class RunUploader {
/// Creates a queue; the arguments are test seams.
RunUploader({
RunCredentialStore? credentials,
this._client,
this._storage,
Timer Function(Duration, void Function())? scheduler,
}) : _credentials = credentials ?? RunCredentialStore(),
_schedule = scheduler ?? Timer.new;
/// The app-wide queue.
static final RunUploader instance = RunUploader();
final RunCredentialStore _credentials;
final http.Client? _client;
final StorageService? _storage;
final Timer Function(Duration, void Function()) _schedule;
final _status = ValueNotifier<RunUploadStatus>(
const RunUploadStatus(UploadHealth.idle, 0),
);
Future<RunUploadStatus>? _inFlight;
Timer? _retry;
/// The queue's state, for the badge.
ValueListenable<RunUploadStatus> get status => _status;
StorageService get _db => _storage ?? StorageService.instance;
/// Uploads every pending run, oldest first. One pass at a time: a call
/// while one runs joins it instead of racing it.
Future<RunUploadStatus> uploadPending() =>
_inFlight ??= _guarded().whenComplete(() => _inFlight = null);
/// A pass that cannot throw: callers fire it and forget it, and an error
/// nobody awaits would vanish. It is logged loudly and retried instead.
Future<RunUploadStatus> _guarded() async {
try {
return await _pass();
} on Exception catch (error, stack) {
log(
'RunUploader: the upload pass threw',
level: 1000,
error: error,
stackTrace: stack,
);
return _fail(
UploadHealth.retrying,
_status.value.pending,
'the upload pass crashed ($error); runs stay pending and are retried.',
);
}
}
Future<RunUploadStatus> _pass() async {
_retry?.cancel();
final pending = (await _db.listRuns(
uploadState: RunUploadState.pending,
)).reversed.toList();
if (pending.isEmpty) return _set(UploadHealth.idle, 0);
if (Sandbox.enabled) {
SandboxLog.event('upload skipped', {'pending': pending.length});
return _set(UploadHealth.sandbox, pending.length, 'sandbox: no uploads');
}
final login = await _credentials.read();
if (login == null) {
return _fail(
UploadHealth.notConfigured,
pending.length,
'${pending.length} run(s) wait for upload but no login is '
'provisioned. Run scripts/provision_run_upload.sh.',
retry: false,
);
}
_set(UploadHealth.uploading, pending.length);
var left = pending.length;
final client = _client ?? http.Client();
try {
for (final record in pending) {
final problem = await _upload(client, login, record);
if (problem != null) {
return _fail(UploadHealth.retrying, left, problem);
}
left--;
}
} finally {
if (_client == null) client.close();
}
return _set(UploadHealth.idle, 0);
}
/// A sentence naming the failure, or null once the run is uploaded.
Future<String?> _upload(
http.Client client,
RunUploadCredentials login,
RunRecord record,
) async {
final full = await _db.getRun(record.track.id);
if (full == null) return null;
final tcx = encodeTcx(full.track);
if (tcxSha256(tcx) != record.tcxSha256) {
log(
'RunUploader: ${record.tcxFilename} re-encodes to different bytes '
'than were stored (the encoder changed since recording). Uploading '
'the current encoding; the PC dedupes on the run id.',
level: 900,
);
}
final url = Uri.parse(
'${login.baseUrl}/$kRunInboxFolder/${record.tcxFilename}',
);
final http.Response response;
try {
response = await client
.put(
url,
headers: {
'Authorization': login.basicAuth,
'Content-Type': 'application/vnd.garmin.tcx+xml',
},
body: tcx,
)
.timeout(kUploadTimeout);
} on Exception catch (error, stack) {
log(
'RunUploader: PUT ${record.tcxFilename} threw',
level: 1000,
error: error,
stackTrace: stack,
);
return 'PUT ${record.tcxFilename} failed ($error); the run stays '
'pending and is retried.';
}
if (response.statusCode < 200 || response.statusCode > 299) {
return 'PUT ${record.tcxFilename} was answered ${response.statusCode}'
'${response.statusCode == 401 ? ' (login rejected: re-run '
'scripts/provision_run_upload.sh)' : ''}; the run stays '
'pending and is retried.';
}
if (!await _db.setRunUploadState(
record.track.id,
RunUploadState.uploaded,
)) {
log(
'RunUploader: ${record.tcxFilename} was uploaded but its row is '
'gone, so it could not be marked uploaded.',
level: 900,
);
}
return null;
}
RunUploadStatus _set(UploadHealth health, int pending, [String why = '']) {
final status = RunUploadStatus(health, pending, why);
_status.value = status;
return status;
}
RunUploadStatus _fail(
UploadHealth health,
int pending,
String reason, {
bool retry = true,
}) {
log('RunUploader: $reason', level: 1000);
if (retry) {
_retry = _schedule(kUploadRetryAfter, () => unawaited(uploadPending()));
}
return _set(health, pending, reason);
}
/// Stops the retry timer.
void dispose() {
_retry?.cancel();
_status.dispose();
}
}

View File

@ -0,0 +1,77 @@
/// Shared fakes for the run recorder, controller and screen tests.
library;
import 'dart:async';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/position_source.dart';
/// One degree of latitude in metres, so tests place fixes by distance.
const double kDegM = 111194.9;
/// A fix [seconds] after 12:00:00 UTC, [northM] metres north of the origin.
GpsFix fixAt(
int seconds,
double northM, {
double accuracy = 5,
bool mocked = false,
}) => GpsFix(
time: DateTime.utc(2026, 11, 9, 12).add(Duration(seconds: seconds)),
latitude: 48.8584 + northM / kDegM,
longitude: 2.2945,
altitudeM: 30,
accuracyM: accuracy,
isMocked: mocked,
);
/// [count] fixes 2 s apart moving north at 3 m/s (a 10.8 km/h run).
List<GpsFix> straightRun(int count, {int startSecond = 0}) => [
for (var i = 0; i < count; i++)
fixAt(startSecond + i * 2, (startSecond + i * 2) * 3.0),
];
/// A source the test feeds by hand, so a pause can fall between two fixes.
class ManualPositionSource implements PositionSource {
/// Creates a source answering [access].
ManualPositionSource({this.access = LocationAccess.granted});
/// What [requestAccess] answers.
final LocationAccess access;
/// The stream the recorder listens to.
final controller = StreamController<GpsFix>();
/// How many times [fixes] was called.
int subscriptions = 0;
@override
Future<LocationAccess> requestAccess() async => access;
@override
Stream<GpsFix> fixes({Duration interval = const Duration(seconds: 2)}) {
subscriptions++;
return controller.stream;
}
}
/// A small stored-run shaped track starting at [start] (UTC).
RunTrack sampleTrack({String start = '2026-11-09T12:00:00Z'}) {
final t = DateTime.parse(start);
return RunTrack.started(
sport: RunSport.running,
startedAt: t,
totalSeconds: 20,
distanceM: 60,
points: [
for (var i = 0; i < 3; i++)
RunPoint(
time: t.add(Duration(seconds: i * 10)),
latitude: 48.8584 + i * 0.00027,
longitude: 2.2945,
altitudeM: 31,
distanceM: i * 30.0,
),
],
);
}

View File

@ -128,4 +128,26 @@ void main() {
expect(movingSeconds(f.points, RunSport.walking), 260);
});
});
group('breakSegment', () {
test('the fix after a pause earns nothing, then crediting resumes', () {
final f = GpsFilter(sport: RunSport.walking)
..add(_fix(0, 0))
..add(_fix(10, 14))
..breakSegment();
// 20 s later and 28 m further: a moving step if not for the pause.
expect(f.add(_fix(30, 42)), FixVerdict.accepted);
expect(f.distanceM, closeTo(14, 0.5));
expect(f.add(_fix(40, 56)), FixVerdict.accepted);
expect(f.distanceM, closeTo(28, 0.5));
});
test('a pause jump is re-anchored, not rejected as a GPS jump', () {
final f = GpsFilter(sport: RunSport.walking)
..add(_fix(0, 0))
..breakSegment();
expect(f.add(_fix(5, 5000)), FixVerdict.accepted);
expect(f.distanceM, 0);
});
});
}

View File

@ -0,0 +1,36 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/run_format.dart';
void main() {
test('durations are m:ss, then h:mm:ss, never negative', () {
expect(formatDuration(0), '0:00');
expect(formatDuration(723), '12:03');
expect(formatDuration(3600), '1:00:00');
expect(formatDuration(3725), '1:02:05');
expect(formatDuration(-4), '0:00');
});
test('distance is kilometres with two decimals', () {
expect(formatKm(0), '0.00');
expect(formatKm(3524), '3.52');
});
test('pace needs 20 m and is m:ss per km', () {
expect(paceSecPerKm(10, 19.9), isNull);
expect(paceSecPerKm(312, 1000), 312);
expect(formatPace(312), '5:12');
expect(formatPace(null), '--:--');
expect(formatPace(double.infinity), '--:--');
expect(formatPace(double.nan), '--:--');
});
test('the notification is numbers only', () {
final copy = runNotificationCopy(metres: 3524, movingSeconds: 723);
expect(copy.title, '3.52');
expect(copy.body, '12:03 3:25');
expect(
runNotificationCopy(metres: 0, movingSeconds: 0).body,
'0:00 --:--',
);
});
}

View File

@ -0,0 +1,283 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/position_source_scripted.dart';
import 'package:workout_app/services/run_recorder.dart';
import '../run_test_fixtures.dart';
RunRecorder _recorder(ManualPositionSource source, {List<int>? km}) =>
RunRecorder(sourceFor: (_) => source, onKilometre: km?.add);
void main() {
group('a scripted run', () {
test('records points, moving time and distance, then finishes', () async {
final kms = <int>[];
final recorder = RunRecorder(
sourceFor: (_) => ScriptedPositionSource(straightRun(340)),
onKilometre: kms.add,
);
expect(await recorder.start(), isTrue);
await pumpEventQueue();
expect(recorder.phase, RunPhase.recording);
expect(kms, [1, 2]);
expect(recorder.livePoints.value, hasLength(340));
expect(recorder.distanceM, closeTo(2034, 5));
expect(recorder.seconds, 678);
expect(recorder.pace, closeTo(333, 3));
final track = (await recorder.finish())!;
expect(recorder.phase, RunPhase.finished);
expect(track.sport, RunSport.running);
expect(track.points, hasLength(340));
expect(track.totalSeconds, 678);
expect(track.distanceM, closeTo(2034, 5));
expect(track.startedAt, DateTime.utc(2026, 11, 9, 12));
expect(track.id, '2026-11-09T12:00:00Z');
expect(track.source, RunSource.app);
recorder.dispose();
});
test(
'a stream that ends early is logged, the run is still savable',
() async {
final recorder = RunRecorder(
sourceFor: (_) => ScriptedPositionSource(straightRun(5)),
);
await recorder.start();
await pumpEventQueue();
expect(recorder.phase, RunPhase.recording);
expect(await recorder.finish(), isNotNull);
recorder.dispose();
},
);
test('a stream closing after finish is ignored', () async {
final source = ManualPositionSource();
final recorder = _recorder(source);
await recorder.start();
source.controller
..add(fixAt(0, 0))
..add(fixAt(2, 6));
await pumpEventQueue();
await recorder.finish();
await source.controller.close();
await pumpEventQueue();
expect(recorder.phase, RunPhase.finished);
recorder.dispose();
});
});
group('filtering', () {
test('a mock fix is dropped and flagged until a real one lands', () async {
final source = ManualPositionSource();
final recorder = _recorder(source);
await recorder.start();
source.controller
..add(fixAt(0, 0))
..add(fixAt(2, 6, mocked: true))
..add(fixAt(4, 12, mocked: true));
await pumpEventQueue();
expect(recorder.issue, RunIssue.mockedLocation);
expect(recorder.livePoints.value, hasLength(1));
source.controller.add(fixAt(6, 18));
await pumpEventQueue();
expect(recorder.issue, RunIssue.none);
expect(recorder.livePoints.value, hasLength(2));
recorder.dispose();
});
test('a GPS jump is dropped without crediting the leap', () async {
final source = ManualPositionSource();
final recorder = _recorder(source);
await recorder.start();
source.controller
..add(fixAt(0, 0))
..add(fixAt(2, 6))
..add(fixAt(4, 5000))
..add(fixAt(6, 18));
await pumpEventQueue();
expect(recorder.livePoints.value, hasLength(3));
expect(recorder.distanceM, closeTo(18, 0.5));
expect(recorder.seconds, 6);
recorder.dispose();
});
test('an inaccurate fix is dropped', () async {
final source = ManualPositionSource();
final recorder = _recorder(source);
await recorder.start();
source.controller
..add(fixAt(0, 0, accuracy: 80))
..add(fixAt(2, 6, accuracy: 90));
await pumpEventQueue();
expect(recorder.livePoints.value, isEmpty);
expect(recorder.issue, RunIssue.none);
recorder.dispose();
});
});
group('pause', () {
test('credits nothing while paused or across the resume', () async {
final source = ManualPositionSource();
final recorder = _recorder(source);
await recorder.start();
source.controller
..add(fixAt(0, 0))
..add(fixAt(2, 6))
..add(fixAt(4, 12));
await pumpEventQueue();
expect(recorder.seconds, 4);
recorder.pause();
expect(recorder.phase, RunPhase.paused);
source.controller
..add(fixAt(6, 18))
..add(fixAt(8, 24));
await pumpEventQueue();
expect(recorder.livePoints.value, hasLength(3));
recorder.resume();
expect(recorder.phase, RunPhase.recording);
source.controller
..add(fixAt(10, 30))
..add(fixAt(12, 36));
await pumpEventQueue();
expect(recorder.livePoints.value, hasLength(5));
// 4 s before the pause, 2 s after the first post-resume fix.
expect(recorder.seconds, 6);
expect(recorder.distanceM, closeTo(18, 0.5));
expect(source.subscriptions, 1);
final track = (await recorder.finish())!;
expect(track.totalSeconds, 6);
recorder.dispose();
});
test(
'finish works from paused; pause and resume elsewhere are no-ops',
() async {
final source = ManualPositionSource();
final recorder = _recorder(source)
..pause()
..resume();
expect(recorder.phase, RunPhase.idle);
await recorder.start();
recorder.resume();
expect(recorder.phase, RunPhase.recording);
source.controller
..add(fixAt(0, 0))
..add(fixAt(2, 6));
await pumpEventQueue();
recorder.pause();
expect(await recorder.finish(), isNotNull);
recorder.pause();
expect(recorder.phase, RunPhase.finished);
expect(await recorder.finish(), isNull);
recorder.dispose();
},
);
});
group('start', () {
test('refusals stay idle and say why', () async {
for (final (access, issue) in [
(LocationAccess.denied, RunIssue.denied),
(LocationAccess.deniedForever, RunIssue.deniedForever),
(LocationAccess.serviceOff, RunIssue.serviceOff),
]) {
var served = false;
final recorder = _recorder(ManualPositionSource(access: access));
expect(
await recorder.start(afterAccess: () async => served = true),
isFalse,
);
expect(recorder.phase, RunPhase.idle);
expect(recorder.issue, issue);
expect(served, isFalse);
recorder.dispose();
}
});
test(
'afterAccess runs once access is held, and a retry can succeed',
() async {
final order = <String>[];
final recorder = _recorder(ManualPositionSource());
expect(
await recorder.start(afterAccess: () async => order.add('service')),
isTrue,
);
expect(order, ['service']);
expect(recorder.issue, RunIssue.none);
recorder.dispose();
},
);
test('a double tap starts one recording', () async {
final source = ManualPositionSource();
final recorder = _recorder(source);
final first = recorder.start();
final second = recorder.start();
expect(await first, isTrue);
expect(await second, isFalse);
expect(await recorder.start(), isFalse);
expect(source.subscriptions, 1);
recorder.dispose();
});
test('the sport is chosen while idle only, and picks the source', () async {
final seen = <RunSport>[];
final recorder = RunRecorder(
sourceFor: (sport) {
seen.add(sport);
return ManualPositionSource();
},
);
expect(recorder.selectSport(RunSport.walking), isTrue);
await recorder.start();
expect(recorder.selectSport(RunSport.running), isFalse);
expect(recorder.sport, RunSport.walking);
expect(seen, [RunSport.walking]);
recorder.dispose();
});
});
group('trouble', () {
test('a stream error is flagged and clears with the next fix', () async {
final source = ManualPositionSource();
final recorder = _recorder(source);
await recorder.start();
source.controller
..add(fixAt(0, 0))
..addError(StateError('gps off'));
await pumpEventQueue();
expect(recorder.issue, RunIssue.streamError);
source.controller.add(fixAt(2, 6));
await pumpEventQueue();
expect(recorder.issue, RunIssue.none);
recorder.dispose();
});
test('finishing with under two fixes saves nothing', () async {
final source = ManualPositionSource();
final recorder = _recorder(source);
await recorder.start();
source.controller.add(fixAt(0, 0));
await pumpEventQueue();
expect(await recorder.finish(), isNull);
expect(recorder.issue, RunIssue.tooShort);
recorder.dispose();
});
test('finish before any start is a no-op', () async {
final recorder = _recorder(ManualPositionSource());
expect(await recorder.finish(), isNull);
expect(recorder.distanceM, 0);
expect(recorder.pace, isNull);
recorder.dispose();
});
});
}

View File

@ -0,0 +1,430 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/models/run_record.dart';
import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/services/run_saver.dart';
import 'package:workout_app/services/run_upload_credentials.dart';
import 'package:workout_app/services/run_uploader.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/tcx_codec.dart';
import '../fake_secure_storage.dart';
import '../run_test_fixtures.dart';
const _login = RunUploadCredentials(
baseUrl: 'https://cloud.example',
user: 'workout_app',
password: 'pw',
);
/// A store that already holds [_login] (or fails like a broken keystore).
class _FixedStore implements RunCredentialStore {
_FixedStore(this._login, {this.onRead, this.throwing = false});
final RunUploadCredentials? _login;
final Future<void> Function()? onRead;
final bool throwing;
@override
Future<RunUploadCredentials?> read() async {
await onRead?.call();
if (throwing) throw PlatformException(code: 'keystore');
return _login;
}
@override
Future<ProvisionOutcome> importProvisionFile() => throw UnimplementedError();
}
StorageService get _db => StorageService.instance;
Future<RunRecord> _save(String start) async {
final track = sampleTrack(start: start);
await saveRecordedRun(track, storage: _db, enqueue: () async => null);
return (await _db.listRuns()).firstWhere((r) => r.track.id == track.id);
}
Future<RunUploadState> _stateOf(String id) async =>
(await _db.getRun(id))!.uploadState;
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
StorageService.resetForTesting();
await StorageService.init();
});
tearDown(() {
Sandbox.enabled = false;
StorageService.resetForTesting();
});
RunUploader uploader(
http.Client client, {
RunCredentialStore? store,
List<Duration>? delays,
List<void Function()>? timers,
}) => RunUploader(
credentials: store ?? _FixedStore(_login),
client: client,
scheduler: (d, f) {
delays?.add(d);
timers?.add(f);
return Timer(const Duration(days: 1), f);
},
);
test('a 201 marks the run uploaded after a Basic-auth PUT', () async {
final run = await _save('2026-11-09T12:00:00Z');
late http.Request seen;
final up = uploader(
MockClient((r) async {
seen = r;
return http.Response('', 201);
}),
);
final status = await up.uploadPending();
expect(seen.method, 'PUT');
expect(
seen.url.toString(),
'https://cloud.example/RunnerUp/${run.tcxFilename}',
);
expect(
seen.headers['Authorization'],
'Basic ${base64.encode(utf8.encode('workout_app:pw'))}',
);
expect(seen.body, encodeTcx((await _db.getRun(run.track.id))!.track));
expect(status.health, UploadHealth.idle);
expect(status.pending, 0);
expect(await _stateOf(run.track.id), RunUploadState.uploaded);
up.dispose();
});
test('a 401 keeps the run pending and retries on a timer', () async {
final run = await _save('2026-11-09T12:00:00Z');
final delays = <Duration>[];
final timers = <void Function()>[];
var code = 401;
final up = uploader(
MockClient((_) async => http.Response('', code)),
delays: delays,
timers: timers,
);
final status = await up.uploadPending();
expect(status.health, UploadHealth.retrying);
expect(status.pending, 1);
expect(status.reason, contains('401'));
expect(up.status.value, same(status));
expect(delays, [kUploadRetryAfter]);
expect(await _stateOf(run.track.id), RunUploadState.pending);
code = 201;
timers.single();
// Joins the pass the timer just started (single flight).
await up.uploadPending();
expect(await _stateOf(run.track.id), RunUploadState.uploaded);
up.dispose();
});
test('a network error or server fault stays pending', () async {
final run = await _save('2026-11-09T12:00:00Z');
final broken = uploader(
MockClient((_) async => throw http.ClientException('no route')),
);
final first = await broken.uploadPending();
expect(first.health, UploadHealth.retrying);
expect(first.reason, contains('no route'));
final faulty = uploader(MockClient((_) async => http.Response('', 503)));
final second = await faulty.uploadPending();
expect(second.reason, contains('503'));
expect(second.reason, isNot(contains('provision')));
expect(await _stateOf(run.track.id), RunUploadState.pending);
broken.dispose();
faulty.dispose();
});
test('runs go oldest first and a failure stops the pass', () async {
final older = await _save('2026-11-08T12:00:00Z');
final newer = await _save('2026-11-09T12:00:00Z');
final urls = <String>[];
final up = uploader(
MockClient((r) async {
urls.add(r.url.pathSegments.last);
return http.Response('', 500);
}),
);
final status = await up.uploadPending();
expect(urls, [older.tcxFilename]);
expect(status.pending, 2);
expect(await _stateOf(newer.track.id), RunUploadState.pending);
up.dispose();
});
test(
'without a provisioned login nothing is sent and no retry runs',
() async {
await _save('2026-11-09T12:00:00Z');
final timers = <void Function()>[];
var calls = 0;
final up = uploader(
MockClient((_) async {
calls++;
return http.Response('', 201);
}),
store: _FixedStore(null),
timers: timers,
);
final status = await up.uploadPending();
expect(status.health, UploadHealth.notConfigured);
expect(status.reason, contains('provision_run_upload.sh'));
expect(calls, 0);
expect(timers, isEmpty);
up.dispose();
},
);
test('the sandbox keeps runs and never opens a connection', () async {
Sandbox.enabled = true;
final run = await _save('2026-11-09T12:00:00Z');
final up = uploader(
MockClient((_) async => fail('the sandbox must never PUT')),
store: _FixedStore(_login),
);
final status = await up.uploadPending();
expect(status.health, UploadHealth.sandbox);
expect(status.pending, 1);
expect(await _stateOf(run.track.id), RunUploadState.pending);
up.dispose();
});
test('an empty queue is idle', () async {
final up = uploader(MockClient((_) async => fail('nothing to send')));
final status = await up.uploadPending();
expect(status.health, UploadHealth.idle);
expect(status.pending, 0);
up.dispose();
});
test('concurrent calls share one pass', () async {
await _save('2026-11-09T12:00:00Z');
var calls = 0;
final up = uploader(
MockClient((_) async {
calls++;
return http.Response('', 201);
}),
);
final both = await Future.wait([up.uploadPending(), up.uploadPending()]);
expect(calls, 1);
expect(both.first, same(both.last));
up.dispose();
});
test('a stored hash that no longer matches still uploads', () async {
final track = sampleTrack();
await _db.insertRun(
track,
tcxFilename: tcxFilename(track),
tcxSha256: 'stale',
uploadState: RunUploadState.pending,
);
var calls = 0;
final up = uploader(
MockClient((_) async {
calls++;
return http.Response('', 200);
}),
);
await up.uploadPending();
expect(calls, 1);
expect(await _stateOf(track.id), RunUploadState.uploaded);
up.dispose();
});
test(
'a run deleted mid-pass is skipped; one deleted mid-PUT is logged',
() async {
final first = await _save('2026-11-08T12:00:00Z');
final second = await _save('2026-11-09T12:00:00Z');
final seen = <String>[];
final up = uploader(
MockClient((r) async {
seen.add(r.url.pathSegments.last);
await _db.deleteRun(second.track.id);
return http.Response('', 201);
}),
store: _FixedStore(
_login,
onRead: () async {
await _db.deleteRun(first.track.id);
},
),
);
final status = await up.uploadPending();
expect(seen, [second.tcxFilename]);
expect(status.health, UploadHealth.idle);
up.dispose();
},
);
test('a crashing keystore is reported, not thrown', () async {
await _save('2026-11-09T12:00:00Z');
final timers = <void Function()>[];
final up = uploader(
MockClient((_) async => fail('no login, no PUT')),
store: _FixedStore(_login, throwing: true),
timers: timers,
);
final status = await up.uploadPending();
expect(status.health, UploadHealth.retrying);
expect(status.reason, contains('crashed'));
expect(timers, hasLength(1));
up.dispose();
});
test('a queue with no injected client opens and closes its own', () async {
await _save('2026-11-09T12:00:00Z');
final up = RunUploader(
credentials: _FixedStore(
const RunUploadCredentials(
baseUrl: 'http://127.0.0.1:1',
user: 'u',
password: 'p',
),
),
);
final status = await up.uploadPending();
expect(status.health, UploadHealth.retrying);
expect(RunUploader.instance.status.value.health, UploadHealth.idle);
up.dispose();
});
group('provisioning', () {
late Directory dir;
setUp(() {
installFakeSecureStorage();
dir = Directory.systemTemp.createTempSync('provision_test_');
addTearDown(() => dir.deleteSync(recursive: true));
});
RunCredentialStore store() =>
RunCredentialStore(externalDir: () async => dir);
File file() => File('${dir.path}/$kProvisionFileName');
test('a login file is imported into secure storage and deleted', () async {
file().writeAsStringSync(
jsonEncode({
'url': 'https://cloud.example/',
'user': 'workout_app',
'password': 'secret',
}),
);
final s = store();
expect(await s.read(), isNull);
final outcome = await s.importProvisionFile();
expect(outcome.status, ProvisionStatus.imported);
expect(file().existsSync(), isFalse);
final login = (await s.read())!;
expect(login.baseUrl, 'https://cloud.example');
expect(login.user, 'workout_app');
expect(login.password, 'secret');
expect(
login.basicAuth,
'Basic ${base64.encode(utf8.encode('workout_app:secret'))}',
);
});
test('no file, or no directory, is a quiet no-op', () async {
expect(
(await store().importProvisionFile()).status,
ProvisionStatus.absent,
);
final none = RunCredentialStore(externalDir: () async => null);
expect((await none.importProvisionFile()).status, ProvisionStatus.absent);
// The default directory lookup answers null off Android.
expect(
(await RunCredentialStore().importProvisionFile()).status,
ProvisionStatus.absent,
);
});
test('an unusable file is kept and reported', () async {
final bad = <String>[
'not json',
'[]',
jsonEncode({'url': 'https://x', 'user': 'u'}),
jsonEncode({'url': 'ftp://x', 'user': 'u', 'password': 'p'}),
jsonEncode({'url': 'nonsense', 'user': 'u', 'password': 'p'}),
jsonEncode({'url': 'https://x', 'user': '', 'password': 'p'}),
jsonEncode({'url': 'https://x', 'user': 'u', 'password': ''}),
];
for (final text in bad) {
file().writeAsStringSync(text);
final s = store();
final outcome = await s.importProvisionFile();
expect(outcome.status, ProvisionStatus.invalid, reason: text);
expect(outcome.reason, contains('provision_run_upload.sh'));
expect(file().existsSync(), isTrue);
expect(await s.read(), isNull);
}
});
});
group('saveRecordedRun', () {
test('stores a pending app run and starts the upload', () async {
var enqueued = 0;
final track = sampleTrack();
final result = await saveRecordedRun(
track,
storage: _db,
enqueue: () async {
enqueued++;
return null;
},
);
expect(result.stored, isTrue);
expect(enqueued, 1);
final record = (await _db.getRun(track.id))!;
expect(record.uploadState, RunUploadState.pending);
expect(record.track.points, hasLength(3));
expect(record.tcxFilename, endsWith('_Running.tcx'));
});
test('a run already stored is reported and not queued twice', () async {
var enqueued = 0;
Future<Object?> enqueue() async {
enqueued++;
return null;
}
final track = sampleTrack();
await saveRecordedRun(track, storage: _db, enqueue: enqueue);
final again = await saveRecordedRun(
track,
storage: _db,
enqueue: enqueue,
);
expect(again.stored, isFalse);
expect(again.reason, contains('already stored'));
expect(enqueued, 1);
});
});
}