From 5f158c7ac290868065317cd72349fa35992bcf5b Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 2 Aug 2026 13:08:08 +0200 Subject: [PATCH] Give each metric the read window its density affords --- lib/features/health/models/health_metric.dart | 27 + .../health/providers/health_repository.dart | 39 +- .../health/providers/health_sync.dart | 58 +- .../health/providers/health_sync.g.dart | 2 +- .../providers/health_repository_test.dart | 170 ++++ .../health_repository_test.mocks.dart | 804 ++++++++++++++++++ .../health/providers/health_sync_test.dart | 104 ++- .../providers/health_sync_test.mocks.dart | 2 + 8 files changed, 1157 insertions(+), 49 deletions(-) create mode 100644 test/features/health/providers/health_repository_test.dart create mode 100644 test/features/health/providers/health_repository_test.mocks.dart diff --git a/lib/features/health/models/health_metric.dart b/lib/features/health/models/health_metric.dart index de910054e..70535e0fe 100644 --- a/lib/features/health/models/health_metric.dart +++ b/lib/features/health/models/health_metric.dart @@ -19,6 +19,20 @@ import 'package:health_bridge/health.dart'; import 'package:wger/features/measurements/models/measurement_category.dart'; +/// Timeline a single platform query covers unless the metric says otherwise, +/// see [HealthMetric.readWindow]. +const defaultReadWindow = Duration(days: 30); + +/// Query window for the metrics a wearable writes continuously. +/// +/// Measured on a Pixel 7 Pro with a watch worn daily: a week of heart rate +/// peaked at 134 MB of a 256 MB heap, i.e. half the budget for a history that +/// is not unusually dense. Three days leave room for someone recording several +/// times as densely, and cost almost nothing: the windows before the first +/// record return in about 6 ms each, and the ones with data take as long as +/// their data does, however it is sliced. +const highVolumeReadWindow = Duration(days: 3); + /// How a day's samples are condensed into the single value stored for it. enum DailyAggregation { /// The day's mean, e.g. heart rate. @@ -45,6 +59,7 @@ class HealthMetric { this.dayRollsOverAtHour, this.enabled = false, this.disabledReason, + this.readWindow = defaultReadWindow, }); /// Metric type stored on the category, e.g. [MetricType.bodyFat]. @@ -89,6 +104,16 @@ class HealthMetric { /// Why a declared metric is not imported yet. final String? disabledReason; + /// How much of the timeline one platform query may cover for this metric. + /// + /// The plugin materialises every record it reads and then serialises the + /// whole batch for the method channel, so the query size decides the peak + /// memory, against an Android app heap capped at 256 MB. A scale writes a + /// handful of values a month, a watch writes heart rate around the clock: + /// measured on a real device, a month of heart rate needs ~240 MB, a week + /// well under a hundred. + final Duration readWindow; + /// All platform types this metric reads (the components' for a group). List get dataTypes => components.isEmpty ? [dataType] : components.map((c) => c.dataType).toList(); @@ -176,6 +201,7 @@ const List healthMetrics = [ toCategoryValue: _identity, dailyAggregation: DailyAggregation.average, enabled: true, + readWindow: highVolumeReadWindow, ), HealthMetric( // Both platforms compute this themselves and write (typically) one value @@ -209,6 +235,7 @@ const List healthMetrics = [ unit: 'count', toCategoryValue: _identity, disabledReason: 'High-volume cumulative type, parked behind a load test.', + readWindow: highVolumeReadWindow, ), ]; diff --git a/lib/features/health/providers/health_repository.dart b/lib/features/health/providers/health_repository.dart index 72d942b3a..93aa2352d 100644 --- a/lib/features/health/providers/health_repository.dart +++ b/lib/features/health/providers/health_repository.dart @@ -23,6 +23,7 @@ import 'package:flutter/services.dart' show PlatformException; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:health_bridge/health.dart'; import 'package:logging/logging.dart'; +import 'package:wger/features/health/models/health_metric.dart'; import 'package:wger/features/health/models/health_reading.dart'; final healthRepositoryProvider = Provider((ref) { @@ -199,10 +200,20 @@ class HealthRepository { /// cost every other type its import too. A failing type is logged by name /// and skipped; only when every type fails does the error propagate, so a /// wholesale denial still surfaces as one. + /// + /// Each type is read in windows of [window]: the plugin turns every record + /// into a map and then serialises the whole batch for the method channel, so + /// one query spanning years of a densely written type fills the Android app + /// heap, which is capped at 256 MB however much RAM the device has, and the + /// process is killed. How large a window a metric can afford is a property + /// of the metric, see [HealthMetric.readWindow]. The windows are contiguous, + /// and a record sitting exactly on a boundary is removed by the + /// deduplication below. Future> read({ required List types, required DateTime start, required DateTime end, + required Duration window, }) async { final points = []; Object? firstError; @@ -210,10 +221,32 @@ class HealthRepository { for (final type in types) { try { - points.addAll( - await _health.getHealthDataFromTypes(types: [type], startTime: start, endTime: end), - ); + var windowStart = start; + var readForType = 0; + while (windowStart.isBefore(end)) { + final windowEnd = windowStart.add(window); + final batch = await _health.getHealthDataFromTypes( + types: [type], + startTime: windowStart, + endTime: windowEnd.isAfter(end) ? end : windowEnd, + ); + // How much a window holds is what decides whether [window] is small + // enough, so it is worth having in a bug report instead of being + // reconstructed from GC lines afterwards + if (batch.isNotEmpty) { + _logger.finer('Read ${batch.length} ${type.name} records from $windowStart'); + readForType += batch.length; + } + points.addAll(batch); + windowStart = windowEnd; + } + if (readForType > 0) { + _logger.fine('Read $readForType ${type.name} records in total'); + } } catch (e) { + // The whole type counts as failed even when earlier windows delivered: + // importing half a type would let the watermark move past the readings + // the failing windows never returned failed++; firstError ??= e; _logger.warning('Reading ${type.name} from the health platform failed: $e'); diff --git a/lib/features/health/providers/health_sync.dart b/lib/features/health/providers/health_sync.dart index ee5efe021..94adddf0c 100644 --- a/lib/features/health/providers/health_sync.dart +++ b/lib/features/health/providers/health_sync.dart @@ -92,6 +92,15 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { /// Minimum pause between the automatic re-syncs on app resume. static const _resumeThrottle = Duration(minutes: 15); + /// Where a full read starts, i.e. when there is no watermark to go from. + /// + /// Not the epoch: every window before the first record is a platform query + /// that returns nothing, and for a metric read in weekly windows those add + /// up. Health Connect shipped in 2022 and HealthKit's own data rarely + /// predates a wearable, so this cuts the empty part without cutting real + /// history in practice. + static final _fullHistoryStart = DateTime(2020); + final _logger = Logger('HealthSyncNotifier'); late final HealthRepository _health; late final MeasurementRepository _measurements; @@ -241,36 +250,32 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { lastSyncStr == null || _missingCategories(metrics, categories).isNotEmpty || await _hasNewlyReadableTypes(readable) - ? DateTime(2000) + ? _fullHistoryStart : DateTime.parse(lastSyncStr).subtract(_syncOverlap); final endTime = DateTime.now(); _logger.info('Syncing health data from $startTime to $endTime'); - final readings = await _health.read( - types: metrics.expand((m) => m.dataTypes).toList(), - start: startTime, - end: endTime, - ); - // Recorded after the read, so a run that never got that far tries again - // rather than remembering an access it did not use - await prefs.setHealthSyncReadableTypes(readable.map((t) => t.name).toList()); - - if (readings.isEmpty) { - _logger.info('No new health data'); - state = state.copyWith(isSyncing: false, lastSyncCount: 0, lastSyncTime: DateTime.now()); - return 0; - } - final source = _health.sourceName; var synced = 0; var skippedMetric = false; var failedMetric = false; + var permissionsMissing = false; DateTime? latest; for (final metric in metrics) { // One bad metric must not cost the others their import, and the // watermark has to stay put for whatever it could not write try { + // Read per metric: how much of the timeline one platform query may + // cover depends on how densely the metric is written, see + // [HealthMetric.readWindow] + final readings = await _health.read( + types: metric.dataTypes, + start: startTime, + end: endTime, + window: metric.readWindow, + ); + // Pair each target category with the readings it receives: the metric's // own category, or one child per component for a group metric. final List<(MeasurementCategory, Iterable)> targets; @@ -311,12 +316,23 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { } } } catch (e, s) { - _logger.severe('Importing ${metric.metricType.name} failed', e, s); skippedMetric = true; - failedMetric = true; + if (HealthRepository.isAuthorizationMissing(e)) { + // The one permission failure iOS reports, and it reports it only + // when the read runs. Worth telling apart, the user can fix it + _logger.warning('No authorization to read ${metric.metricType.name}', e); + permissionsMissing = true; + } else { + _logger.severe('Importing ${metric.metricType.name} failed', e, s); + failedMetric = true; + } } } + // Recorded after the metrics ran, so a sync that died earlier tries + // again rather than remembering an access it never used + await prefs.setHealthSyncReadableTypes(readable.map((t) => t.name).toList()); + // Advancing the watermark past readings a skipped metric could not // import would push them out of the overlap window for good, so keep // the old one until every metric got its category. A reading dated in @@ -337,7 +353,11 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { isSyncing: false, lastSyncCount: synced, lastSyncTime: DateTime.now(), - issue: failedMetric ? HealthSyncIssue.failed : null, + issue: failedMetric + ? HealthSyncIssue.failed + : permissionsMissing + ? HealthSyncIssue.permissionsMissing + : null, ); return synced; } catch (e, s) { diff --git a/lib/features/health/providers/health_sync.g.dart b/lib/features/health/providers/health_sync.g.dart index b0e264c9f..e60a96094 100644 --- a/lib/features/health/providers/health_sync.g.dart +++ b/lib/features/health/providers/health_sync.g.dart @@ -56,7 +56,7 @@ final class HealthSyncNotifierProvider } } -String _$healthSyncNotifierHash() => r'f2ba4b18894edd0160e9c39920787260064abb4b'; +String _$healthSyncNotifierHash() => r'e28b9a62d77961b91e8d1756c8186ba7a2e89c58'; /// Imports body metrics from Apple Health / Health Connect into measurement /// categories. Read-only: reads the platform (via [HealthRepository]), writes to diff --git a/test/features/health/providers/health_repository_test.dart b/test/features/health/providers/health_repository_test.dart new file mode 100644 index 000000000..51b8bb959 --- /dev/null +++ b/test/features/health/providers/health_repository_test.dart @@ -0,0 +1,170 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter_test/flutter_test.dart'; +import 'package:health_bridge/health.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:wger/features/health/models/health_metric.dart'; +import 'package:wger/features/health/providers/health_repository.dart'; + +import 'health_repository_test.mocks.dart'; + +@GenerateMocks([Health]) +void main() { + late MockHealth health; + late HealthRepository repository; + + setUp(() { + health = MockHealth(); + repository = HealthRepository(health); + + when(health.configure()).thenAnswer((_) async {}); + when( + health.getHealthDataFromTypes( + types: anyNamed('types'), + startTime: anyNamed('startTime'), + endTime: anyNamed('endTime'), + ), + ).thenAnswer((_) async => []); + when(health.removeDuplicates(any)).thenAnswer( + (invocation) => invocation.positionalArguments.first as List, + ); + }); + + /// The (start, end) of every query the repository sent, in order + List<(DateTime, DateTime)> capturedWindows() { + final captured = verify( + health.getHealthDataFromTypes( + types: anyNamed('types'), + startTime: captureAnyNamed('startTime'), + endTime: captureAnyNamed('endTime'), + ), + ).captured; + return [ + for (var i = 0; i < captured.length; i += 2) + (captured[i] as DateTime, captured[i + 1] as DateTime), + ]; + } + + group('read', () { + test('a range shorter than the window is one query', () async { + final start = DateTime(2026, 1, 1); + final end = DateTime(2026, 1, 20); + + await repository.read( + types: [HealthDataType.WEIGHT], + start: start, + end: end, + window: defaultReadWindow, + ); + + expect(capturedWindows(), [(start, end)]); + }); + + test('a long range is read in contiguous windows', () async { + // A single query over years of a high-frequency type fills the Android + // app heap, so the platform is asked for one window at a time + final start = DateTime(2026, 1, 1); + final end = DateTime(2026, 4, 10); + + await repository.read( + types: [HealthDataType.HEART_RATE], + start: start, + end: end, + window: highVolumeReadWindow, + ); + + final windows = capturedWindows(); + expect(windows.length, greaterThan(1)); + expect(windows.first.$1, start); + expect(windows.last.$2, end, reason: 'The last window must not read past the end'); + for (var i = 1; i < windows.length; i++) { + expect(windows[i].$1, windows[i - 1].$2, reason: 'Windows must leave no gap'); + } + for (final window in windows) { + expect( + window.$2.difference(window.$1), + lessThanOrEqualTo(highVolumeReadWindow), + ); + } + }); + + test('every type is windowed on its own', () async { + final start = DateTime(2026, 1, 1); + final end = DateTime(2026, 3, 1); + + await repository.read( + types: [HealthDataType.WEIGHT, HealthDataType.HEART_RATE], + start: start, + end: end, + window: defaultReadWindow, + ); + + final windows = capturedWindows(); + // Both types cover the same range, so each window shows up twice + expect(windows.where((w) => w.$1 == start), hasLength(2)); + }); + + test('a failing window does not cost the other types their read', () async { + when( + health.getHealthDataFromTypes( + types: [HealthDataType.HEART_RATE], + startTime: anyNamed('startTime'), + endTime: anyNamed('endTime'), + ), + ).thenThrow(Exception('boom')); + + final readings = await repository.read( + types: [HealthDataType.HEART_RATE, HealthDataType.WEIGHT], + start: DateTime(2026, 1, 1), + end: DateTime(2026, 4, 1), + window: defaultReadWindow, + ); + + expect(readings, isEmpty); + verify( + health.getHealthDataFromTypes( + types: [HealthDataType.WEIGHT], + startTime: anyNamed('startTime'), + endTime: anyNamed('endTime'), + ), + ).called(greaterThan(1)); + }); + + test('a wholesale failure still propagates', () async { + when( + health.getHealthDataFromTypes( + types: anyNamed('types'), + startTime: anyNamed('startTime'), + endTime: anyNamed('endTime'), + ), + ).thenThrow(Exception('boom')); + + expect( + () => repository.read( + types: [HealthDataType.WEIGHT], + start: DateTime(2026, 1, 1), + end: DateTime(2026, 2, 1), + window: defaultReadWindow, + ), + throwsException, + ); + }); + }); +} diff --git a/test/features/health/providers/health_repository_test.mocks.dart b/test/features/health/providers/health_repository_test.mocks.dart new file mode 100644 index 000000000..dfcb215d1 --- /dev/null +++ b/test/features/health/providers/health_repository_test.mocks.dart @@ -0,0 +1,804 @@ +// Mocks generated by Mockito 5.4.6 from annotations +// in wger/test/features/health/providers/health_repository_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i4; + +import 'package:health_bridge/health.dart' as _i2; +import 'package:mockito/mockito.dart' as _i1; +import 'package:mockito/src/dummies.dart' as _i3; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +/// A class which mocks [Health]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockHealth extends _i1.Mock implements _i2.Health { + MockHealth() { + _i1.throwOnMissingStub(this); + } + + @override + _i2.HealthConnectSdkStatus get healthConnectSdkStatus => + (super.noSuchMethod( + Invocation.getter(#healthConnectSdkStatus), + returnValue: _i2.HealthConnectSdkStatus.sdkUnavailable, + ) + as _i2.HealthConnectSdkStatus); + + @override + _i2.HealthPlatformType get platformType => + (super.noSuchMethod( + Invocation.getter(#platformType), + returnValue: _i2.HealthPlatformType.appleHealth, + ) + as _i2.HealthPlatformType); + + @override + String get deviceId => + (super.noSuchMethod( + Invocation.getter(#deviceId), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#deviceId), + ), + ) + as String); + + @override + _i4.Future configure() => + (super.noSuchMethod( + Invocation.method(#configure, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + bool isDataTypeAvailable(_i2.HealthDataType? dataType) => + (super.noSuchMethod( + Invocation.method(#isDataTypeAvailable, [dataType]), + returnValue: false, + ) + as bool); + + @override + _i4.Future hasPermissions( + List<_i2.HealthDataType>? types, { + List<_i2.HealthDataAccess>? permissions, + }) => + (super.noSuchMethod( + Invocation.method( + #hasPermissions, + [types], + {#permissions: permissions}, + ), + returnValue: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future<_i2.HealthAuthorizationSnapshot> getAuthorizationSnapshot( + List<_i2.HealthDataType>? types, + ) => + (super.noSuchMethod( + Invocation.method(#getAuthorizationSnapshot, [types]), + returnValue: _i4.Future<_i2.HealthAuthorizationSnapshot>.value( + _i3.dummyValue<_i2.HealthAuthorizationSnapshot>( + this, + Invocation.method(#getAuthorizationSnapshot, [types]), + ), + ), + ) + as _i4.Future<_i2.HealthAuthorizationSnapshot>); + + @override + _i4.Future revokePermissions() => + (super.noSuchMethod( + Invocation.method(#revokePermissions, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future<_i2.HealthConnectSdkStatus?> getHealthConnectSdkStatus() => + (super.noSuchMethod( + Invocation.method(#getHealthConnectSdkStatus, []), + returnValue: _i4.Future<_i2.HealthConnectSdkStatus?>.value(), + ) + as _i4.Future<_i2.HealthConnectSdkStatus?>); + + @override + _i4.Future isHealthConnectAvailable() => + (super.noSuchMethod( + Invocation.method(#isHealthConnectAvailable, []), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future installHealthConnect() => + (super.noSuchMethod( + Invocation.method(#installHealthConnect, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future isHealthDataHistoryAvailable() => + (super.noSuchMethod( + Invocation.method(#isHealthDataHistoryAvailable, []), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future isHealthDataHistoryAuthorized() => + (super.noSuchMethod( + Invocation.method(#isHealthDataHistoryAuthorized, []), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future requestHealthDataHistoryAuthorization() => + (super.noSuchMethod( + Invocation.method(#requestHealthDataHistoryAuthorization, []), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future isHealthDataInBackgroundAvailable() => + (super.noSuchMethod( + Invocation.method(#isHealthDataInBackgroundAvailable, []), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future isHealthDataInBackgroundAuthorized() => + (super.noSuchMethod( + Invocation.method(#isHealthDataInBackgroundAuthorized, []), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future requestHealthDataInBackgroundAuthorization() => + (super.noSuchMethod( + Invocation.method(#requestHealthDataInBackgroundAuthorization, []), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future isSkinTemperatureAvailable() => + (super.noSuchMethod( + Invocation.method(#isSkinTemperatureAvailable, []), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future requestAuthorization( + List<_i2.HealthDataType>? types, { + List<_i2.HealthDataAccess>? permissions, + }) => + (super.noSuchMethod( + Invocation.method( + #requestAuthorization, + [types], + {#permissions: permissions}, + ), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future writeHealthData({ + required double? value, + _i2.HealthDataUnit? unit, + required _i2.HealthDataType? type, + required DateTime? startTime, + String? clientRecordId, + double? clientRecordVersion, + DateTime? endTime, + _i2.RecordingMethod? recordingMethod = _i2.RecordingMethod.automatic, + }) => + (super.noSuchMethod( + Invocation.method(#writeHealthData, [], { + #value: value, + #unit: unit, + #type: type, + #startTime: startTime, + #clientRecordId: clientRecordId, + #clientRecordVersion: clientRecordVersion, + #endTime: endTime, + #recordingMethod: recordingMethod, + }), + returnValue: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future writeActivityIntensity({ + required _i2.ActivityIntensityLevel? intensityLevel, + required DateTime? startTime, + DateTime? endTime, + _i2.RecordingMethod? recordingMethod = _i2.RecordingMethod.automatic, + String? clientRecordId, + double? clientRecordVersion, + }) => + (super.noSuchMethod( + Invocation.method(#writeActivityIntensity, [], { + #intensityLevel: intensityLevel, + #startTime: startTime, + #endTime: endTime, + #recordingMethod: recordingMethod, + #clientRecordId: clientRecordId, + #clientRecordVersion: clientRecordVersion, + }), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future delete({ + required _i2.HealthDataType? type, + required DateTime? startTime, + DateTime? endTime, + }) => + (super.noSuchMethod( + Invocation.method(#delete, [], { + #type: type, + #startTime: startTime, + #endTime: endTime, + }), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future deleteByUUID({ + required String? uuid, + _i2.HealthDataType? type, + }) => + (super.noSuchMethod( + Invocation.method(#deleteByUUID, [], {#uuid: uuid, #type: type}), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future deleteByClientRecordId({ + required _i2.HealthDataType? dataTypeKey, + required String? clientRecordId, + String? recordId, + }) => + (super.noSuchMethod( + Invocation.method(#deleteByClientRecordId, [], { + #dataTypeKey: dataTypeKey, + #clientRecordId: clientRecordId, + #recordId: recordId, + }), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future writeBloodPressure({ + required int? systolic, + required int? diastolic, + required DateTime? startTime, + String? clientRecordId, + double? clientRecordVersion, + DateTime? endTime, + _i2.RecordingMethod? recordingMethod = _i2.RecordingMethod.automatic, + }) => + (super.noSuchMethod( + Invocation.method(#writeBloodPressure, [], { + #systolic: systolic, + #diastolic: diastolic, + #startTime: startTime, + #clientRecordId: clientRecordId, + #clientRecordVersion: clientRecordVersion, + #endTime: endTime, + #recordingMethod: recordingMethod, + }), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future writeBloodOxygen({ + required double? saturation, + required DateTime? startTime, + DateTime? endTime, + _i2.RecordingMethod? recordingMethod = _i2.RecordingMethod.automatic, + }) => + (super.noSuchMethod( + Invocation.method(#writeBloodOxygen, [], { + #saturation: saturation, + #startTime: startTime, + #endTime: endTime, + #recordingMethod: recordingMethod, + }), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future writeMeal({ + required _i2.MealType? mealType, + required DateTime? startTime, + required DateTime? endTime, + String? clientRecordId, + double? clientRecordVersion, + double? caloriesConsumed, + double? carbohydrates, + double? protein, + double? fatTotal, + String? name, + double? caffeine, + double? vitaminA, + double? b1Thiamin, + double? b2Riboflavin, + double? b3Niacin, + double? b5PantothenicAcid, + double? b6Pyridoxine, + double? b7Biotin, + double? b9Folate, + double? b12Cobalamin, + double? vitaminC, + double? vitaminD, + double? vitaminE, + double? vitaminK, + double? calcium, + double? cholesterol, + double? chloride, + double? chromium, + double? copper, + double? fatUnsaturated, + double? fatMonounsaturated, + double? fatPolyunsaturated, + double? fatSaturated, + double? fatTransMonoenoic, + double? fiber, + double? iodine, + double? iron, + double? magnesium, + double? manganese, + double? molybdenum, + double? phosphorus, + double? potassium, + double? selenium, + double? sodium, + double? sugar, + double? water, + double? zinc, + _i2.RecordingMethod? recordingMethod = _i2.RecordingMethod.automatic, + }) => + (super.noSuchMethod( + Invocation.method(#writeMeal, [], { + #mealType: mealType, + #startTime: startTime, + #endTime: endTime, + #clientRecordId: clientRecordId, + #clientRecordVersion: clientRecordVersion, + #caloriesConsumed: caloriesConsumed, + #carbohydrates: carbohydrates, + #protein: protein, + #fatTotal: fatTotal, + #name: name, + #caffeine: caffeine, + #vitaminA: vitaminA, + #b1Thiamin: b1Thiamin, + #b2Riboflavin: b2Riboflavin, + #b3Niacin: b3Niacin, + #b5PantothenicAcid: b5PantothenicAcid, + #b6Pyridoxine: b6Pyridoxine, + #b7Biotin: b7Biotin, + #b9Folate: b9Folate, + #b12Cobalamin: b12Cobalamin, + #vitaminC: vitaminC, + #vitaminD: vitaminD, + #vitaminE: vitaminE, + #vitaminK: vitaminK, + #calcium: calcium, + #cholesterol: cholesterol, + #chloride: chloride, + #chromium: chromium, + #copper: copper, + #fatUnsaturated: fatUnsaturated, + #fatMonounsaturated: fatMonounsaturated, + #fatPolyunsaturated: fatPolyunsaturated, + #fatSaturated: fatSaturated, + #fatTransMonoenoic: fatTransMonoenoic, + #fiber: fiber, + #iodine: iodine, + #iron: iron, + #magnesium: magnesium, + #manganese: manganese, + #molybdenum: molybdenum, + #phosphorus: phosphorus, + #potassium: potassium, + #selenium: selenium, + #sodium: sodium, + #sugar: sugar, + #water: water, + #zinc: zinc, + #recordingMethod: recordingMethod, + }), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future writeMenstruationFlow({ + required _i2.MenstrualFlow? flow, + required DateTime? startTime, + required DateTime? endTime, + required bool? isStartOfCycle, + _i2.RecordingMethod? recordingMethod = _i2.RecordingMethod.automatic, + }) => + (super.noSuchMethod( + Invocation.method(#writeMenstruationFlow, [], { + #flow: flow, + #startTime: startTime, + #endTime: endTime, + #isStartOfCycle: isStartOfCycle, + #recordingMethod: recordingMethod, + }), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future writeAudiogram({ + required List? frequencies, + required List? leftEarSensitivities, + required List? rightEarSensitivities, + required DateTime? startTime, + DateTime? endTime, + Map? metadata, + }) => + (super.noSuchMethod( + Invocation.method(#writeAudiogram, [], { + #frequencies: frequencies, + #leftEarSensitivities: leftEarSensitivities, + #rightEarSensitivities: rightEarSensitivities, + #startTime: startTime, + #endTime: endTime, + #metadata: metadata, + }), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future writeInsulinDelivery( + double? units, + _i2.InsulinDeliveryReason? reason, + DateTime? startTime, + DateTime? endTime, + ) => + (super.noSuchMethod( + Invocation.method(#writeInsulinDelivery, [ + units, + reason, + startTime, + endTime, + ]), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future<_i2.HealthDataPoint?> getHealthDataByUUID({ + required String? uuid, + required _i2.HealthDataType? type, + }) => + (super.noSuchMethod( + Invocation.method(#getHealthDataByUUID, [], { + #uuid: uuid, + #type: type, + }), + returnValue: _i4.Future<_i2.HealthDataPoint?>.value(), + ) + as _i4.Future<_i2.HealthDataPoint?>); + + @override + _i4.Future> getHealthDataFromTypes({ + required List<_i2.HealthDataType>? types, + Map<_i2.HealthDataType, _i2.HealthDataUnit>? preferredUnits, + required DateTime? startTime, + required DateTime? endTime, + List<_i2.RecordingMethod>? recordingMethodsToFilter = const [], + }) => + (super.noSuchMethod( + Invocation.method(#getHealthDataFromTypes, [], { + #types: types, + #preferredUnits: preferredUnits, + #startTime: startTime, + #endTime: endTime, + #recordingMethodsToFilter: recordingMethodsToFilter, + }), + returnValue: _i4.Future>.value( + <_i2.HealthDataPoint>[], + ), + ) + as _i4.Future>); + + @override + _i4.Future> getHealthIntervalDataFromTypes({ + required DateTime? startDate, + required DateTime? endDate, + required List<_i2.HealthDataType>? types, + required int? interval, + List<_i2.RecordingMethod>? recordingMethodsToFilter = const [], + }) => + (super.noSuchMethod( + Invocation.method(#getHealthIntervalDataFromTypes, [], { + #startDate: startDate, + #endDate: endDate, + #types: types, + #interval: interval, + #recordingMethodsToFilter: recordingMethodsToFilter, + }), + returnValue: _i4.Future>.value( + <_i2.HealthDataPoint>[], + ), + ) + as _i4.Future>); + + @override + _i4.Future> getHealthAggregateDataFromTypes({ + required List<_i2.HealthDataType>? types, + required DateTime? startDate, + required DateTime? endDate, + int? activitySegmentDuration = 1, + bool? includeManualEntry = true, + }) => + (super.noSuchMethod( + Invocation.method(#getHealthAggregateDataFromTypes, [], { + #types: types, + #startDate: startDate, + #endDate: endDate, + #activitySegmentDuration: activitySegmentDuration, + #includeManualEntry: includeManualEntry, + }), + returnValue: _i4.Future>.value( + <_i2.HealthDataPoint>[], + ), + ) + as _i4.Future>); + + @override + _i4.Future getChangesToken({ + required List<_i2.HealthDataType>? types, + }) => + (super.noSuchMethod( + Invocation.method(#getChangesToken, [], {#types: types}), + returnValue: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future<_i2.HealthChangesResponse?> getChanges({ + required String? changesToken, + bool? includeSelf = false, + }) => + (super.noSuchMethod( + Invocation.method(#getChanges, [], { + #changesToken: changesToken, + #includeSelf: includeSelf, + }), + returnValue: _i4.Future<_i2.HealthChangesResponse?>.value(), + ) + as _i4.Future<_i2.HealthChangesResponse?>); + + @override + List<_i2.HealthDataPoint> removeDuplicates( + List<_i2.HealthDataPoint>? points, + ) => + (super.noSuchMethod( + Invocation.method(#removeDuplicates, [points]), + returnValue: <_i2.HealthDataPoint>[], + ) + as List<_i2.HealthDataPoint>); + + @override + _i4.Future getTotalStepsInInterval( + DateTime? startTime, + DateTime? endTime, { + bool? includeManualEntry = true, + }) => + (super.noSuchMethod( + Invocation.method( + #getTotalStepsInInterval, + [startTime, endTime], + {#includeManualEntry: includeManualEntry}, + ), + returnValue: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future<_i2.HealthWorkoutWriteResult> writeWorkoutData({ + required String? workoutClientRecordId, + String? energyClientRecordId, + required int? clientRecordVersion, + required _i2.HealthWorkoutActivityType? activityType, + required DateTime? start, + required DateTime? end, + required int? startZoneOffsetSeconds, + required int? endZoneOffsetSeconds, + double? activeEnergyKcal, + required String? title, + required _i2.HealthRecordingProvenance? recordingProvenance, + required _i2.HealthRecordingDevice? recordingDevice, + }) => + (super.noSuchMethod( + Invocation.method(#writeWorkoutData, [], { + #workoutClientRecordId: workoutClientRecordId, + #energyClientRecordId: energyClientRecordId, + #clientRecordVersion: clientRecordVersion, + #activityType: activityType, + #start: start, + #end: end, + #startZoneOffsetSeconds: startZoneOffsetSeconds, + #endZoneOffsetSeconds: endZoneOffsetSeconds, + #activeEnergyKcal: activeEnergyKcal, + #title: title, + #recordingProvenance: recordingProvenance, + #recordingDevice: recordingDevice, + }), + returnValue: _i4.Future<_i2.HealthWorkoutWriteResult>.value( + _i3.dummyValue<_i2.HealthWorkoutWriteResult>( + this, + Invocation.method(#writeWorkoutData, [], { + #workoutClientRecordId: workoutClientRecordId, + #energyClientRecordId: energyClientRecordId, + #clientRecordVersion: clientRecordVersion, + #activityType: activityType, + #start: start, + #end: end, + #startZoneOffsetSeconds: startZoneOffsetSeconds, + #endZoneOffsetSeconds: endZoneOffsetSeconds, + #activeEnergyKcal: activeEnergyKcal, + #title: title, + #recordingProvenance: recordingProvenance, + #recordingDevice: recordingDevice, + }), + ), + ), + ) + as _i4.Future<_i2.HealthWorkoutWriteResult>); + + @override + _i4.Future<_i2.HealthWorkoutLookupResult> lookupWorkoutData({ + required String? workoutClientRecordId, + String? energyClientRecordId, + required DateTime? start, + required DateTime? end, + }) => + (super.noSuchMethod( + Invocation.method(#lookupWorkoutData, [], { + #workoutClientRecordId: workoutClientRecordId, + #energyClientRecordId: energyClientRecordId, + #start: start, + #end: end, + }), + returnValue: _i4.Future<_i2.HealthWorkoutLookupResult>.value( + _i3.dummyValue<_i2.HealthWorkoutLookupResult>( + this, + Invocation.method(#lookupWorkoutData, [], { + #workoutClientRecordId: workoutClientRecordId, + #energyClientRecordId: energyClientRecordId, + #start: start, + #end: end, + }), + ), + ), + ) + as _i4.Future<_i2.HealthWorkoutLookupResult>); + + @override + _i4.Future<_i2.HealthBodyMassLookupResult> lookupBodyMassData({ + required String? clientRecordId, + required DateTime? measuredAt, + }) => + (super.noSuchMethod( + Invocation.method(#lookupBodyMassData, [], { + #clientRecordId: clientRecordId, + #measuredAt: measuredAt, + }), + returnValue: _i4.Future<_i2.HealthBodyMassLookupResult>.value( + _i3.dummyValue<_i2.HealthBodyMassLookupResult>( + this, + Invocation.method(#lookupBodyMassData, [], { + #clientRecordId: clientRecordId, + #measuredAt: measuredAt, + }), + ), + ), + ) + as _i4.Future<_i2.HealthBodyMassLookupResult>); + + @override + _i4.Future startWorkoutRoute() => + (super.noSuchMethod( + Invocation.method(#startWorkoutRoute, []), + returnValue: _i4.Future.value( + _i3.dummyValue( + this, + Invocation.method(#startWorkoutRoute, []), + ), + ), + ) + as _i4.Future); + + @override + _i4.Future insertWorkoutRouteData({ + required String? builderId, + required List<_i2.WorkoutRouteLocation>? locations, + }) => + (super.noSuchMethod( + Invocation.method(#insertWorkoutRouteData, [], { + #builderId: builderId, + #locations: locations, + }), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); + + @override + _i4.Future finishWorkoutRoute({ + required String? builderId, + required String? workoutUuid, + Map? metadata, + }) => + (super.noSuchMethod( + Invocation.method(#finishWorkoutRoute, [], { + #builderId: builderId, + #workoutUuid: workoutUuid, + #metadata: metadata, + }), + returnValue: _i4.Future.value( + _i3.dummyValue( + this, + Invocation.method(#finishWorkoutRoute, [], { + #builderId: builderId, + #workoutUuid: workoutUuid, + #metadata: metadata, + }), + ), + ), + ) + as _i4.Future); + + @override + _i4.Future discardWorkoutRoute(String? builderId) => + (super.noSuchMethod( + Invocation.method(#discardWorkoutRoute, [builderId]), + returnValue: _i4.Future.value(false), + ) + as _i4.Future); +} diff --git a/test/features/health/providers/health_sync_test.dart b/test/features/health/providers/health_sync_test.dart index 7010ff1a9..5ac348e11 100644 --- a/test/features/health/providers/health_sync_test.dart +++ b/test/features/health/providers/health_sync_test.dart @@ -149,16 +149,30 @@ void main() { return categories; } - /// The start of the window the sync asked the platform for - DateTime capturedReadStart() => - verify( - health.read( - types: anyNamed('types'), - start: captureAnyNamed('start'), - end: anyNamed('end'), - ), - ).captured.single - as DateTime; + /// The start of the window the sync asked the platform for. Every metric is + /// read separately, but all of them over the same range + DateTime capturedReadStart() { + final starts = verify( + health.read( + types: anyNamed('types'), + start: captureAnyNamed('start'), + end: anyNamed('end'), + window: anyNamed('window'), + ), + ).captured.cast(); + expect(starts.toSet(), hasLength(1), reason: 'Every metric reads the same range'); + return starts.first; + } + + /// Every health data type the sync asked the platform for + List capturedReadTypes() => verify( + health.read( + types: captureAnyNamed('types'), + start: anyNamed('start'), + end: anyNamed('end'), + window: anyNamed('window'), + ), + ).captured.cast>().expand((types) => types).toList(); void stubReadings(List readings) { when( @@ -166,6 +180,7 @@ void main() { types: anyNamed('types'), start: anyNamed('start'), end: anyNamed('end'), + window: anyNamed('window'), ), ).thenAnswer((_) async => readings); } @@ -197,7 +212,12 @@ void main() { expect(count, isNull); expect(await PreferenceHelper.instance.getHealthSyncEnabled(), isFalse); verifyNever( - health.read(types: anyNamed('types'), start: anyNamed('start'), end: anyNamed('end')), + health.read( + types: anyNamed('types'), + start: anyNamed('start'), + end: anyNamed('end'), + window: anyNamed('window'), + ), ); }); @@ -273,7 +293,12 @@ void main() { expect(count, 0); expect(container.read(healthSyncProvider).issue, HealthSyncIssue.permissionsMissing); verifyNever( - health.read(types: anyNamed('types'), start: anyNamed('start'), end: anyNamed('end')), + health.read( + types: anyNamed('types'), + start: anyNamed('start'), + end: anyNamed('end'), + window: anyNamed('window'), + ), ); }); @@ -303,15 +328,7 @@ void main() { expect(count, 1); expect(container.read(healthSyncProvider).issue, isNull); // The declined types are not even asked for - final requested = - verify( - health.read( - types: captureAnyNamed('types'), - start: anyNamed('start'), - end: anyNamed('end'), - ), - ).captured.single - as List; + final requested = capturedReadTypes(); expect(requested, isNot(contains(HealthDataType.BLOOD_PRESSURE_SYSTOLIC))); expect(requested, contains(HealthDataType.BODY_FAT_PERCENTAGE)); }); @@ -328,7 +345,7 @@ void main() { await createNotifier().sync(); - expect(capturedReadStart(), DateTime(2000)); + expect(capturedReadStart(), DateTime(2020)); }); test('stays on the watermark while the readable types are unchanged', () async { @@ -349,7 +366,12 @@ void main() { // The one permission problem iOS reports at all, and what a reinstall // leaves behind: the preference says enabled, HealthKit disagrees when( - health.read(types: anyNamed('types'), start: anyNamed('start'), end: anyNamed('end')), + health.read( + types: anyNamed('types'), + start: anyNamed('start'), + end: anyNamed('end'), + window: anyNamed('window'), + ), ).thenThrow( PlatformException( code: 'HEALTH_ERROR', @@ -365,7 +387,12 @@ void main() { test('any other failure is reported as a plain failure', () async { when( - health.read(types: anyNamed('types'), start: anyNamed('start'), end: anyNamed('end')), + health.read( + types: anyNamed('types'), + start: anyNamed('start'), + end: anyNamed('end'), + window: anyNamed('window'), + ), ).thenThrow(Exception('boom')); final count = await createNotifier().sync(); @@ -1242,7 +1269,7 @@ void main() { await createNotifier().sync(); - expect(capturedReadStart(), DateTime(2000)); + expect(capturedReadStart(), DateTime(2020)); }); test('reads the full history when one component of a group was deleted', () async { @@ -1257,7 +1284,31 @@ void main() { await createNotifier().sync(); - expect(capturedReadStart(), DateTime(2000)); + expect(capturedReadStart(), DateTime(2020)); + }); + + test('each metric is read with the window its density affords', () async { + // A month of heart rate does not fit into the Android app heap, a month + // of scale readings is nothing, so the window comes from the metric + stubReadings([]); + + await createNotifier().sync(); + + final calls = verify( + health.read( + types: captureAnyNamed('types'), + start: anyNamed('start'), + end: anyNamed('end'), + window: captureAnyNamed('window'), + ), + ).captured; + final windowByType = { + for (var i = 0; i < calls.length; i += 2) + for (final type in calls[i] as List) type: calls[i + 1] as Duration, + }; + + expect(windowByType[HealthDataType.HEART_RATE], highVolumeReadWindow); + expect(windowByType[HealthDataType.BODY_FAT_PERCENTAGE], defaultReadWindow); }); test('does nothing when sync is disabled', () async { @@ -1270,6 +1321,7 @@ void main() { types: anyNamed('types'), start: anyNamed('start'), end: anyNamed('end'), + window: anyNamed('window'), ), ); }); diff --git a/test/features/health/providers/health_sync_test.mocks.dart b/test/features/health/providers/health_sync_test.mocks.dart index 666c776ac..30272f403 100644 --- a/test/features/health/providers/health_sync_test.mocks.dart +++ b/test/features/health/providers/health_sync_test.mocks.dart @@ -110,12 +110,14 @@ class MockHealthRepository extends _i1.Mock implements _i2.HealthRepository { required List<_i5.HealthDataType>? types, required DateTime? start, required DateTime? end, + required Duration? window, }) => (super.noSuchMethod( Invocation.method(#read, [], { #types: types, #start: start, #end: end, + #window: window, }), returnValue: _i4.Future>.value( <_i6.HealthReading>[],