Give each metric the read window its density affords

This commit is contained in:
Roland Geider
2026-08-02 13:08:08 +02:00
parent 78a0d9f3a1
commit 5f158c7ac2
8 changed files with 1157 additions and 49 deletions

View File

@@ -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<HealthDataType> get dataTypes =>
components.isEmpty ? [dataType] : components.map((c) => c.dataType).toList();
@@ -176,6 +201,7 @@ const List<HealthMetric> 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<HealthMetric> healthMetrics = [
unit: 'count',
toCategoryValue: _identity,
disabledReason: 'High-volume cumulative type, parked behind a load test.',
readWindow: highVolumeReadWindow,
),
];

View File

@@ -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<HealthRepository>((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<List<HealthReading>> read({
required List<HealthDataType> types,
required DateTime start,
required DateTime end,
required Duration window,
}) async {
final points = <HealthDataPoint>[];
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');

View File

@@ -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<HealthReading>)> 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) {

View File

@@ -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

View File

@@ -0,0 +1,170 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* 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 <http://www.gnu.org/licenses/>.
*/
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 => <HealthDataPoint>[]);
when(health.removeDuplicates(any)).thenAnswer(
(invocation) => invocation.positionalArguments.first as List<HealthDataPoint>,
);
});
/// 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,
);
});
});
}

View File

@@ -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<String>(
this,
Invocation.getter(#deviceId),
),
)
as String);
@override
_i4.Future<void> configure() =>
(super.noSuchMethod(
Invocation.method(#configure, []),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i4.Future<void>);
@override
bool isDataTypeAvailable(_i2.HealthDataType? dataType) =>
(super.noSuchMethod(
Invocation.method(#isDataTypeAvailable, [dataType]),
returnValue: false,
)
as bool);
@override
_i4.Future<bool?> hasPermissions(
List<_i2.HealthDataType>? types, {
List<_i2.HealthDataAccess>? permissions,
}) =>
(super.noSuchMethod(
Invocation.method(
#hasPermissions,
[types],
{#permissions: permissions},
),
returnValue: _i4.Future<bool?>.value(),
)
as _i4.Future<bool?>);
@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<void> revokePermissions() =>
(super.noSuchMethod(
Invocation.method(#revokePermissions, []),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i4.Future<void>);
@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<bool> isHealthConnectAvailable() =>
(super.noSuchMethod(
Invocation.method(#isHealthConnectAvailable, []),
returnValue: _i4.Future<bool>.value(false),
)
as _i4.Future<bool>);
@override
_i4.Future<void> installHealthConnect() =>
(super.noSuchMethod(
Invocation.method(#installHealthConnect, []),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i4.Future<void>);
@override
_i4.Future<bool> isHealthDataHistoryAvailable() =>
(super.noSuchMethod(
Invocation.method(#isHealthDataHistoryAvailable, []),
returnValue: _i4.Future<bool>.value(false),
)
as _i4.Future<bool>);
@override
_i4.Future<bool> isHealthDataHistoryAuthorized() =>
(super.noSuchMethod(
Invocation.method(#isHealthDataHistoryAuthorized, []),
returnValue: _i4.Future<bool>.value(false),
)
as _i4.Future<bool>);
@override
_i4.Future<bool> requestHealthDataHistoryAuthorization() =>
(super.noSuchMethod(
Invocation.method(#requestHealthDataHistoryAuthorization, []),
returnValue: _i4.Future<bool>.value(false),
)
as _i4.Future<bool>);
@override
_i4.Future<bool> isHealthDataInBackgroundAvailable() =>
(super.noSuchMethod(
Invocation.method(#isHealthDataInBackgroundAvailable, []),
returnValue: _i4.Future<bool>.value(false),
)
as _i4.Future<bool>);
@override
_i4.Future<bool> isHealthDataInBackgroundAuthorized() =>
(super.noSuchMethod(
Invocation.method(#isHealthDataInBackgroundAuthorized, []),
returnValue: _i4.Future<bool>.value(false),
)
as _i4.Future<bool>);
@override
_i4.Future<bool> requestHealthDataInBackgroundAuthorization() =>
(super.noSuchMethod(
Invocation.method(#requestHealthDataInBackgroundAuthorization, []),
returnValue: _i4.Future<bool>.value(false),
)
as _i4.Future<bool>);
@override
_i4.Future<bool> isSkinTemperatureAvailable() =>
(super.noSuchMethod(
Invocation.method(#isSkinTemperatureAvailable, []),
returnValue: _i4.Future<bool>.value(false),
)
as _i4.Future<bool>);
@override
_i4.Future<bool> requestAuthorization(
List<_i2.HealthDataType>? types, {
List<_i2.HealthDataAccess>? permissions,
}) =>
(super.noSuchMethod(
Invocation.method(
#requestAuthorization,
[types],
{#permissions: permissions},
),
returnValue: _i4.Future<bool>.value(false),
)
as _i4.Future<bool>);
@override
_i4.Future<String?> 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<String?>.value(),
)
as _i4.Future<String?>);
@override
_i4.Future<bool> 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<bool>.value(false),
)
as _i4.Future<bool>);
@override
_i4.Future<bool> delete({
required _i2.HealthDataType? type,
required DateTime? startTime,
DateTime? endTime,
}) =>
(super.noSuchMethod(
Invocation.method(#delete, [], {
#type: type,
#startTime: startTime,
#endTime: endTime,
}),
returnValue: _i4.Future<bool>.value(false),
)
as _i4.Future<bool>);
@override
_i4.Future<bool> deleteByUUID({
required String? uuid,
_i2.HealthDataType? type,
}) =>
(super.noSuchMethod(
Invocation.method(#deleteByUUID, [], {#uuid: uuid, #type: type}),
returnValue: _i4.Future<bool>.value(false),
)
as _i4.Future<bool>);
@override
_i4.Future<bool> deleteByClientRecordId({
required _i2.HealthDataType? dataTypeKey,
required String? clientRecordId,
String? recordId,
}) =>
(super.noSuchMethod(
Invocation.method(#deleteByClientRecordId, [], {
#dataTypeKey: dataTypeKey,
#clientRecordId: clientRecordId,
#recordId: recordId,
}),
returnValue: _i4.Future<bool>.value(false),
)
as _i4.Future<bool>);
@override
_i4.Future<bool> 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<bool>.value(false),
)
as _i4.Future<bool>);
@override
_i4.Future<bool> 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<bool>.value(false),
)
as _i4.Future<bool>);
@override
_i4.Future<bool> 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<bool>.value(false),
)
as _i4.Future<bool>);
@override
_i4.Future<bool> 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<bool>.value(false),
)
as _i4.Future<bool>);
@override
_i4.Future<bool> writeAudiogram({
required List<double>? frequencies,
required List<double>? leftEarSensitivities,
required List<double>? rightEarSensitivities,
required DateTime? startTime,
DateTime? endTime,
Map<String, dynamic>? metadata,
}) =>
(super.noSuchMethod(
Invocation.method(#writeAudiogram, [], {
#frequencies: frequencies,
#leftEarSensitivities: leftEarSensitivities,
#rightEarSensitivities: rightEarSensitivities,
#startTime: startTime,
#endTime: endTime,
#metadata: metadata,
}),
returnValue: _i4.Future<bool>.value(false),
)
as _i4.Future<bool>);
@override
_i4.Future<bool> writeInsulinDelivery(
double? units,
_i2.InsulinDeliveryReason? reason,
DateTime? startTime,
DateTime? endTime,
) =>
(super.noSuchMethod(
Invocation.method(#writeInsulinDelivery, [
units,
reason,
startTime,
endTime,
]),
returnValue: _i4.Future<bool>.value(false),
)
as _i4.Future<bool>);
@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<List<_i2.HealthDataPoint>> 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<List<_i2.HealthDataPoint>>.value(
<_i2.HealthDataPoint>[],
),
)
as _i4.Future<List<_i2.HealthDataPoint>>);
@override
_i4.Future<List<_i2.HealthDataPoint>> 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<List<_i2.HealthDataPoint>>.value(
<_i2.HealthDataPoint>[],
),
)
as _i4.Future<List<_i2.HealthDataPoint>>);
@override
_i4.Future<List<_i2.HealthDataPoint>> 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<List<_i2.HealthDataPoint>>.value(
<_i2.HealthDataPoint>[],
),
)
as _i4.Future<List<_i2.HealthDataPoint>>);
@override
_i4.Future<String?> getChangesToken({
required List<_i2.HealthDataType>? types,
}) =>
(super.noSuchMethod(
Invocation.method(#getChangesToken, [], {#types: types}),
returnValue: _i4.Future<String?>.value(),
)
as _i4.Future<String?>);
@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<int?> getTotalStepsInInterval(
DateTime? startTime,
DateTime? endTime, {
bool? includeManualEntry = true,
}) =>
(super.noSuchMethod(
Invocation.method(
#getTotalStepsInInterval,
[startTime, endTime],
{#includeManualEntry: includeManualEntry},
),
returnValue: _i4.Future<int?>.value(),
)
as _i4.Future<int?>);
@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<String> startWorkoutRoute() =>
(super.noSuchMethod(
Invocation.method(#startWorkoutRoute, []),
returnValue: _i4.Future<String>.value(
_i3.dummyValue<String>(
this,
Invocation.method(#startWorkoutRoute, []),
),
),
)
as _i4.Future<String>);
@override
_i4.Future<bool> insertWorkoutRouteData({
required String? builderId,
required List<_i2.WorkoutRouteLocation>? locations,
}) =>
(super.noSuchMethod(
Invocation.method(#insertWorkoutRouteData, [], {
#builderId: builderId,
#locations: locations,
}),
returnValue: _i4.Future<bool>.value(false),
)
as _i4.Future<bool>);
@override
_i4.Future<String> finishWorkoutRoute({
required String? builderId,
required String? workoutUuid,
Map<String, dynamic>? metadata,
}) =>
(super.noSuchMethod(
Invocation.method(#finishWorkoutRoute, [], {
#builderId: builderId,
#workoutUuid: workoutUuid,
#metadata: metadata,
}),
returnValue: _i4.Future<String>.value(
_i3.dummyValue<String>(
this,
Invocation.method(#finishWorkoutRoute, [], {
#builderId: builderId,
#workoutUuid: workoutUuid,
#metadata: metadata,
}),
),
),
)
as _i4.Future<String>);
@override
_i4.Future<bool> discardWorkoutRoute(String? builderId) =>
(super.noSuchMethod(
Invocation.method(#discardWorkoutRoute, [builderId]),
returnValue: _i4.Future<bool>.value(false),
)
as _i4.Future<bool>);
}

View File

@@ -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<DateTime>();
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<HealthDataType> capturedReadTypes() => verify(
health.read(
types: captureAnyNamed('types'),
start: anyNamed('start'),
end: anyNamed('end'),
window: anyNamed('window'),
),
).captured.cast<List<HealthDataType>>().expand((types) => types).toList();
void stubReadings(List<HealthReading> 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<HealthDataType>;
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 = <HealthDataType, Duration>{
for (var i = 0; i < calls.length; i += 2)
for (final type in calls[i] as List<HealthDataType>) 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'),
),
);
});

View File

@@ -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<List<_i6.HealthReading>>.value(
<_i6.HealthReading>[],