Stream the health import one read window at a time

This commit is contained in:
Roland Geider
2026-08-25 13:04:49 +02:00
parent ed65a0e42c
commit d3b71d6d89
8 changed files with 670 additions and 279 deletions

View File

@@ -198,69 +198,65 @@ class HealthImporter {
// One bad metric must not cost the others their import, and its own
// 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(
var delivered = false;
DateTime? latest;
// The categories the metric imports into, resolved on the first
// batch that delivers: a metric the platform has nothing for must
// not create them
List<_ImportTarget>? targets;
// Read per metric, one window at a time: how much of the timeline
// one platform query may cover depends on how densely the metric is
// written, see [HealthMetric.readWindow]. Windows already written
// stay written when a later one fails; the watermark below then
// holds, and the re-read is deduplicated via the external ids
await _health.read(
types: metric.dataTypes,
start: _windowStartFor(startTime, metric),
end: endTime,
window: metric.readWindow,
onBatch: (batch, windowEnd) async {
final readings = batch.where((r) => metric.dataTypes.contains(r.type)).toList();
if (readings.isEmpty) {
return;
}
delivered = true;
targets ??= await _resolveTargets(metric, categories, userId);
for (final target in targets!) {
final routed = readings.where((r) => target.dataTypes.contains(r.type));
synced += metric.dailyAggregation != null
? await _collectDailyAggregates(metric, routed, target, windowEnd, source)
: await _importReadings(metric, routed, target, source);
}
for (final reading in readings) {
if (latest == null || reading.date.isAfter(latest!)) {
latest = reading.date;
}
}
},
);
// 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;
if (metric.components.isEmpty) {
final metricReadings = readings.where((r) => metric.dataTypes.contains(r.type));
if (metricReadings.isEmpty) {
if (readsFullHistory && withoutCategory.contains(name)) {
knownEmpty.add(name);
}
watermarks[name] = endTime;
continue;
}
knownEmpty.remove(name);
final category = await _findOrCreateCategory(metric, categories, userId);
if (category == null) {
continue;
}
targets = [(category, metricReadings)];
} else {
final byComponent = [
for (final component in metric.components)
readings.where((r) => component.dataTypes.contains(r.type)),
];
if (byComponent.every((r) => r.isEmpty)) {
if (readsFullHistory && withoutCategory.contains(name)) {
knownEmpty.add(name);
}
watermarks[name] = endTime;
continue;
}
knownEmpty.remove(name);
final children = await _findOrCreateGroupChildren(metric, categories, userId);
if (children == null) {
continue;
}
targets = [for (var i = 0; i < children.length; i++) (children[i], byComponent[i])];
// The newest day can still be growing, so it is only written once
// no window can add to it anymore
for (final target in targets ?? const <_ImportTarget>[]) {
synced += await _flushPendingDays(metric, target, source);
}
DateTime? latest;
for (final (category, metricReadings) in targets) {
final (importedCount, newest) = metric.dailyAggregation != null
? await _importDailyAggregates(metric, metricReadings, category, source)
: await _importReadings(metric, metricReadings, category, source);
synced += importedCount;
if (newest != null && (latest == null || newest.isAfter(latest))) {
latest = newest;
if (!delivered) {
if (readsFullHistory && withoutCategory.contains(name)) {
knownEmpty.add(name);
}
watermarks[name] = endTime;
continue;
}
knownEmpty.remove(name);
// A reading dated in the future (a device with a wrong clock) must
// not drag the watermark along with it, or everything recorded until
// that date is skipped on the next run
watermarks[name] = latest == null || latest.isAfter(endTime) ? endTime : latest;
watermarks[name] = latest == null || latest!.isAfter(endTime) ? endTime : latest!;
} on _SkipMetric {
// Nothing was written and the watermark holds; the cause is logged
// where the metric was skipped
} catch (e, s) {
if (HealthRepository.isAuthorizationMissing(e)) {
// The one permission failure iOS reports, and it reports it only
@@ -320,18 +316,18 @@ class HealthImporter {
}
}
/// Imports [metricReadings] into [category], deduplicating against the
/// entries already present via their externalId. Returns the number of
/// imported entries and the newest imported reading date.
Future<(int, DateTime?)> _importReadings(
/// Imports [metricReadings] into [target]'s category, deduplicating against
/// the entries already present via their externalId. Returns the number of
/// imported entries.
Future<int> _importReadings(
HealthMetric metric,
Iterable<HealthReading> metricReadings,
MeasurementCategory category,
_ImportTarget target,
String source,
) async {
final seen = await _measurements.getExternalIds(category.id!);
final category = target.category;
final seen = target.seen!;
var synced = 0;
DateTime? latest;
for (final reading in metricReadings) {
final uuid = _externalIdFor(reading.externalId, category.id!);
@@ -379,95 +375,122 @@ class HealthImporter {
}
synced++;
}
// Also for a dropped reading: it will never become importable, so
// holding the watermark back would only mean reading it again forever
if (latest == null || reading.date.isAfter(latest)) {
latest = reading.date;
}
}
return (synced, latest);
return synced;
}
/// Imports [metricReadings] as one entry per day, condensed per the metric's
/// Sorts [metricReadings] into the days they belong to and writes every day
/// no later window can add samples to; the rest waits in [target]'s pending
/// days until [_flushPendingDays]. Returns the number of written entries.
Future<int> _collectDailyAggregates(
HealthMetric metric,
Iterable<HealthReading> metricReadings,
_ImportTarget target,
DateTime windowEnd,
String source,
) async {
for (final reading in metricReadings) {
target.pending.putIfAbsent(_dayOf(reading.date, metric), () => []).add(reading);
}
var synced = 0;
// The windows only move forward, so a day that ends at or before this
// window's end is complete and can stop holding its samples
for (final day in target.pending.keys.toList()) {
if (!_dayEnd(day, metric).isAfter(windowEnd)) {
synced += await _writeDailyAggregate(
metric,
day,
target.pending.remove(day)!,
target,
source,
);
}
}
return synced;
}
/// Writes the days still pending once the metric's read is complete: the
/// newest one is usually among them, still growing while its day runs.
Future<int> _flushPendingDays(HealthMetric metric, _ImportTarget target, String source) async {
var synced = 0;
for (final day in target.pending.keys.toList()) {
synced += await _writeDailyAggregate(
metric,
day,
target.pending.remove(day)!,
target,
source,
);
}
return synced;
}
/// Writes [samples] as the one entry of [day], condensed per the metric's
/// [HealthMetric.dailyAggregation]. Days are keyed by
/// [dailyAggregateExternalId], so a re-read within the overlap window updates
/// the aggregate in place when late samples change it (the current day keeps
/// growing until it ends). The entry's date is the start of that day; for
/// metrics that roll over (sleep) the samples' real window is kept in
/// extra_data. Returns the number of written entries and the newest
/// processed sample date.
Future<(int, DateTime?)> _importDailyAggregates(
/// extra_data. Returns the number of written entries.
Future<int> _writeDailyAggregate(
HealthMetric metric,
Iterable<HealthReading> metricReadings,
MeasurementCategory category,
DateTime day,
List<HealthReading> samples,
_ImportTarget target,
String source,
) async {
var synced = 0;
DateTime? latest;
final byDay = groupBy(metricReadings, (r) => _dayOf(r.date, metric));
// Read once for the whole category: a day is looked up by its key below,
// and a full history holds one aggregate per day
final stored = await _measurements.getEntriesByExternalId(category.id!);
final category = target.category;
final values = samples.map((r) => metric.toCategoryValue(r.value)).toList();
final aggregate = switch (metric.dailyAggregation!) {
DailyAggregation.average => values.average,
DailyAggregation.sum => values.sum,
DailyAggregation.mergedDuration => _mergedDurationMinutes(samples),
};
// Round like the raw import: the server stores Decimal with 2 places
final value = (aggregate * 100).roundToDouble() / 100;
final extraData = <String, dynamic>{
if (metric.dailyAggregation == DailyAggregation.average) ...{
'min': values.min,
'max': values.max,
},
'sample_count': values.length,
// The types actually seen, not the metric's own: a component can roll
// several of them up (total sleep)
'record_type': (samples.map((r) => r.type.name).toSet().toList()..sort()).join(','),
// A rolled-over day is not the samples' calendar day, so keep the
// window they actually cover
if (metric.dayRollsOverAtHour != null) ...{
'date_from': samples.map((r) => r.date).reduce(_earlier).toIso8601String(),
'date_to': samples.map((r) => r.dateTo ?? r.date).reduce(_later).toIso8601String(),
},
};
for (final MapEntry(key: day, value: samples) in byDay.entries) {
final values = samples.map((r) => metric.toCategoryValue(r.value)).toList();
final aggregate = switch (metric.dailyAggregation!) {
DailyAggregation.average => values.average,
DailyAggregation.sum => values.sum,
DailyAggregation.mergedDuration => _mergedDurationMinutes(samples),
};
// Round like the raw import: the server stores Decimal with 2 places
final value = (aggregate * 100).roundToDouble() / 100;
final extraData = <String, dynamic>{
if (metric.dailyAggregation == DailyAggregation.average) ...{
'min': values.min,
'max': values.max,
},
'sample_count': values.length,
// The types actually seen, not the metric's own: a component can roll
// several of them up (total sleep)
'record_type': (samples.map((r) => r.type.name).toSet().toList()..sort()).join(','),
// A rolled-over day is not the samples' calendar day, so keep the
// window they actually cover
if (metric.dayRollsOverAtHour != null) ...{
'date_from': samples.map((r) => r.date).reduce(_earlier).toIso8601String(),
'date_to': samples.map((r) => r.dateTo ?? r.date).reduce(_later).toIso8601String(),
},
};
if (_isInRange(value, category, metric)) {
final externalId = dailyAggregateExternalId(category.id!, day);
final existing = stored[externalId];
if (existing == null) {
await _measurements.addLocalDrift(
MeasurementEntry(
categoryId: category.id!,
date: day,
value: value,
notes: '',
source: source,
externalId: externalId,
extraData: extraData,
),
);
synced++;
} else if (existing.value != value ||
!const MapEquality<String, dynamic>().equals(existing.extraData, extraData)) {
await _measurements.updateLocalDrift(
existing.copyWith(value: value, extraData: extraData),
);
synced++;
}
}
for (final sample in samples) {
if (latest == null || sample.date.isAfter(latest)) {
latest = sample.date;
}
}
if (!_isInRange(value, category, metric)) {
return 0;
}
return (synced, latest);
final externalId = dailyAggregateExternalId(category.id!, day);
final existing = target.stored![externalId];
if (existing == null) {
await _measurements.addLocalDrift(
MeasurementEntry(
categoryId: category.id!,
date: day,
value: value,
notes: '',
source: source,
externalId: externalId,
extraData: extraData,
),
);
return 1;
}
if (existing.value != value ||
!const MapEquality<String, dynamic>().equals(existing.extraData, extraData)) {
await _measurements.updateLocalDrift(existing.copyWith(value: value, extraData: extraData));
return 1;
}
return 0;
}
/// How far each metric has been imported.
@@ -554,6 +577,15 @@ class HealthImporter {
return DateTime(date.year, date.month, date.day + (rollsOver ? 1 : 0));
}
/// The first instant no longer attributed to [day], i.e. from when on no
/// later read window can add samples to it.
DateTime _dayEnd(DateTime day, HealthMetric metric) {
final rollover = metric.dayRollsOverAtHour;
return rollover == null
? DateTime(day.year, day.month, day.day + 1)
: DateTime(day.year, day.month, day.day, rollover);
}
static DateTime _earlier(DateTime a, DateTime b) => a.isBefore(b) ? a : b;
static DateTime _later(DateTime a, DateTime b) => a.isAfter(b) ? a : b;
@@ -704,6 +736,50 @@ class HealthImporter {
return missing;
}
/// The categories [metric] imports into, paired with the state their import
/// carries across the read windows.
///
/// Throws [_SkipMetric] when the metric cannot be imported right now (no
/// official body weight category yet, or a group conflict); the cause is
/// logged where it is decided.
Future<List<_ImportTarget>> _resolveTargets(
HealthMetric metric,
List<MeasurementCategory> categories,
String userId,
) async {
if (metric.components.isEmpty) {
final category = await _findOrCreateCategory(metric, categories, userId);
if (category == null) {
throw const _SkipMetric();
}
return [await _targetFor(metric, category, metric.dataTypes)];
}
final children = await _findOrCreateGroupChildren(metric, categories, userId);
if (children == null) {
throw const _SkipMetric();
}
return [
for (final (i, component) in metric.components.indexed)
await _targetFor(metric, children[i], component.dataTypes),
];
}
Future<_ImportTarget> _targetFor(
HealthMetric metric,
MeasurementCategory category,
List<HealthDataType> dataTypes,
) async => _ImportTarget(
category: category,
dataTypes: dataTypes,
// Loaded once per run: a full history holds one row per record or day,
// and every batch of the run deduplicates against the same state
seen: metric.dailyAggregation == null ? await _measurements.getExternalIds(category.id!) : null,
stored: metric.dailyAggregation != null
? await _measurements.getEntriesByExternalId(category.id!)
: null,
);
/// Finds the category for [metric] by its `metric_type`, or creates it. The
/// created category is appended to [categories] so a later metric in the same
/// run reuses it.
@@ -807,3 +883,31 @@ class HealthImporter {
return result;
}
}
/// One category a metric imports into, with the state the import carries
/// across the read windows.
class _ImportTarget {
_ImportTarget({required this.category, required this.dataTypes, this.seen, this.stored});
final MeasurementCategory category;
/// The readings this target receives, matched by their platform type.
final List<HealthDataType> dataTypes;
/// External ids already imported; raw metrics only.
final Set<String>? seen;
/// Stored aggregates by external id; aggregating metrics only.
final Map<String, MeasurementEntry>? stored;
/// Days still collecting samples, until no read window can add to them
/// anymore. Never more than the newest day per window boundary, which is
/// what keeps the peak memory at one window plus one day.
final pending = <DateTime, List<HealthReading>>{};
}
/// Stops reading a metric that cannot be imported right now; its watermark
/// then stays put and the readings are retried on the next sync.
class _SkipMetric implements Exception {
const _SkipMetric();
}

View File

@@ -193,75 +193,113 @@ class HealthRepository {
}
/// Reads all [types] between [start] and [end], platform-deduplicated and
/// reduced to numeric [HealthReading]s.
/// reduced to numeric [HealthReading]s, handing each window over via
/// [onBatch] as soon as it returned.
///
/// Types are read one by one: a single type the platform refuses (an
/// unauthorized type throws rather than coming back empty) would otherwise
/// 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
/// The range 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({
/// of the metric, see [HealthMetric.readWindow]. Handing every window over
/// keeps the peak at one window: holding the full history until the end
/// would fill the same heap the window protects.
///
/// The windows are contiguous and move forward, so everything a later batch
/// delivers starts at or after the previous batch's `windowEnd`; a record
/// on a boundary or spanning one is delivered exactly once, in its first
/// window. What [onBatch] wrote stays written when a later window fails,
/// which the caller has to keep harmless (the importer's writes are
/// idempotent via their external ids).
///
/// Within a window the types are read one by one: a single type the
/// platform refuses (an unauthorized type throws rather than coming back
/// empty) would otherwise cost every other type its import too. A failing
/// type is logged by name and dropped from the remaining windows; only when
/// every type fails does the error propagate, so a wholesale denial still
/// surfaces as one.
Future<void> read({
required List<HealthDataType> types,
required DateTime start,
required DateTime end,
required Duration window,
required Future<void> Function(List<HealthReading> batch, DateTime windowEnd) onBatch,
}) async {
final points = <HealthDataPoint>[];
final failed = <HealthDataType>{};
final counts = {for (final type in types) type: 0};
// Records that can reappear in a later window because their interval
// reaches the current window's end, per type: dedup key -> interval end
final carried = {for (final type in types) type: <String, DateTime>{}};
Object? firstError;
var failed = 0;
for (final type in types) {
try {
// Collected per type and only handed over once every window of it
// returned, see the catch below
final readForType = <HealthDataPoint>[];
var windowStart = start;
while (windowStart.isBefore(end)) {
final windowEnd = windowStart.add(window);
final batch = await _health.getHealthDataFromTypes(
var windowStart = start;
while (windowStart.isBefore(end) && failed.length < types.length) {
final next = windowStart.add(window);
final windowEnd = next.isAfter(end) ? end : next;
final batch = <HealthReading>[];
for (final type in types) {
if (failed.contains(type)) {
continue;
}
final List<HealthDataPoint> points;
try {
points = await _health.getHealthDataFromTypes(
types: [type],
startTime: windowStart,
endTime: windowEnd.isAfter(end) ? end : windowEnd,
endTime: 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');
} catch (e) {
failed.add(type);
firstError ??= e;
_logger.warning('Reading ${type.name} from the health platform failed: $e');
continue;
}
if (points.isEmpty) {
continue;
}
// 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
_logger.finer('Read ${points.length} ${type.name} records from $windowStart');
final carry = carried[type]!;
for (final point in _health.removeDuplicates(points)) {
final reading = HealthReading.fromDataPoint(point);
if (reading == null) {
continue;
}
if (carry.containsKey(_dedupKey(reading))) {
continue;
}
batch.add(reading);
counts[type] = counts[type]! + 1;
final intervalEnd = reading.dateTo ?? reading.date;
if (!intervalEnd.isBefore(windowEnd)) {
carry[_dedupKey(reading)] = intervalEnd;
}
readForType.addAll(batch);
windowStart = windowEnd;
}
if (readForType.isNotEmpty) {
_logger.fine('Read ${readForType.length} ${type.name} records in total');
}
points.addAll(readForType);
} catch (e) {
// The whole type is dropped 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');
// A record whose interval ended inside this window cannot come back
carry.removeWhere((_, intervalEnd) => intervalEnd.isBefore(windowEnd));
}
if (batch.isNotEmpty) {
await onBatch(batch, windowEnd);
}
windowStart = next;
}
if (firstError != null && failed == types.length) {
for (final MapEntry(key: type, value: count) in counts.entries) {
if (count > 0) {
_logger.fine('Read $count ${type.name} records in total');
}
}
if (firstError != null && failed.length == types.length) {
throw firstError;
}
return _health
.removeDuplicates(points)
.map(HealthReading.fromDataPoint)
.whereType<HealthReading>()
.toList();
}
static String _dedupKey(HealthReading reading) =>
reading.externalId ??
'${reading.type.name}|${reading.date}|${reading.dateTo}|${reading.value}';
}

View File

@@ -181,6 +181,7 @@ void main() {
start: captureAnyNamed('start'),
end: anyNamed('end'),
window: anyNamed('window'),
onBatch: anyNamed('onBatch'),
),
).captured;
@@ -205,9 +206,12 @@ void main() {
start: anyNamed('start'),
end: anyNamed('end'),
window: anyNamed('window'),
onBatch: anyNamed('onBatch'),
),
).captured.cast<List<HealthDataType>>().expand((types) => types).toList();
/// Stubs the platform read to hand [readings] over as one batch whose
/// window ends at the end of the read.
void stubReadings(List<HealthReading> readings) {
when(
health.read(
@@ -215,8 +219,42 @@ void main() {
start: anyNamed('start'),
end: anyNamed('end'),
window: anyNamed('window'),
onBatch: anyNamed('onBatch'),
),
).thenAnswer((_) async => readings);
).thenAnswer((invocation) async {
if (readings.isEmpty) {
return;
}
final onBatch =
invocation.namedArguments[#onBatch]
as Future<void> Function(List<HealthReading>, DateTime);
await onBatch(readings, invocation.namedArguments[#end] as DateTime);
});
}
/// Stubs the platform read to hand the metric reading [type] its
/// [batches] in order, each with its window end; a null window end means
/// the end of the read. Every other metric reads empty.
void stubBatchesFor(HealthDataType type, List<(List<HealthReading>, DateTime?)> batches) {
when(
health.read(
types: anyNamed('types'),
start: anyNamed('start'),
end: anyNamed('end'),
window: anyNamed('window'),
onBatch: anyNamed('onBatch'),
),
).thenAnswer((invocation) async {
if (!(invocation.namedArguments[#types] as List<HealthDataType>).contains(type)) {
return;
}
final onBatch =
invocation.namedArguments[#onBatch]
as Future<void> Function(List<HealthReading>, DateTime);
for (final (readings, windowEnd) in batches) {
await onBatch(readings, windowEnd ?? invocation.namedArguments[#end] as DateTime);
}
});
}
group('run', () {
@@ -242,6 +280,7 @@ void main() {
start: anyNamed('start'),
end: anyNamed('end'),
window: anyNamed('window'),
onBatch: anyNamed('onBatch'),
),
);
});
@@ -335,6 +374,7 @@ void main() {
start: anyNamed('start'),
end: anyNamed('end'),
window: anyNamed('window'),
onBatch: anyNamed('onBatch'),
),
).thenThrow(
PlatformException(
@@ -356,6 +396,7 @@ void main() {
start: anyNamed('start'),
end: anyNamed('end'),
window: anyNamed('window'),
onBatch: anyNamed('onBatch'),
),
).thenThrow(Exception('boom'));
@@ -776,6 +817,101 @@ void main() {
);
});
test('aggregates a day split across two read windows once', () async {
// The batches arrive per window, but a day whose samples straddle a
// window boundary must still become a single aggregate of all of them
when(measurements.getCategoriesOnce()).thenAnswer((_) async => <MeasurementCategory>[]);
stubBatchesFor(HealthDataType.HEART_RATE, [
(
[
HealthReading(
type: HealthDataType.HEART_RATE,
value: 60,
date: DateTime(2026, 1, 1, 8),
externalId: _idHr1,
),
],
DateTime(2026, 1, 1, 12),
),
(
[
HealthReading(
type: HealthDataType.HEART_RATE,
value: 70,
date: DateTime(2026, 1, 1, 20),
externalId: _idHr2,
),
HealthReading(
type: HealthDataType.HEART_RATE,
value: 64,
date: DateTime(2026, 1, 2, 9),
externalId: _idHr3,
),
],
null,
),
]);
final count = await runImport();
expect(count, 2);
final entries = verify(
measurements.addLocalDrift(captureAny),
).captured.cast<MeasurementEntry>();
expect(entries, hasLength(2));
final categoryId =
(verify(measurements.addLocalDriftCategory(captureAny)).captured.single
as MeasurementCategory)
.id!;
final day1 = entries.firstWhere(
(e) => e.externalId == dailyAggregateExternalId(categoryId, DateTime(2026, 1, 1)),
);
expect(day1.value, 65); // (60 + 70) / 2, across the boundary
expect(day1.extraData?['sample_count'], 2);
});
test('a raw metric imports every window into one category', () async {
when(measurements.getCategoriesOnce()).thenAnswer((_) async => <MeasurementCategory>[]);
stubBatchesFor(HealthDataType.BODY_FAT_PERCENTAGE, [
(
[
HealthReading(
type: HealthDataType.BODY_FAT_PERCENTAGE,
value: 0.2,
date: DateTime(2026, 1, 1),
externalId: _idBf1,
),
],
DateTime(2026, 2, 1),
),
(
[
HealthReading(
type: HealthDataType.BODY_FAT_PERCENTAGE,
value: 0.22,
date: DateTime(2026, 2, 10),
externalId: _idBf2,
),
],
null,
),
]);
final count = await runImport();
expect(count, 2);
// The category is resolved on the first delivering batch and reused
final created = verify(
measurements.addLocalDriftCategory(captureAny),
).captured.cast<MeasurementCategory>();
expect(created.single.metricType, MetricType.bodyFat);
expect(
await watermarkOf(MetricType.bodyFat),
DateTime(2026, 2, 10).toIso8601String(),
);
});
test('keeps resting heart rate in its own category, imported raw', () async {
when(measurements.getCategoriesOnce()).thenAnswer((_) async => <MeasurementCategory>[]);
stubReadings([
@@ -1465,6 +1601,7 @@ void main() {
start: anyNamed('start'),
end: anyNamed('end'),
window: captureAnyNamed('window'),
onBatch: anyNamed('onBatch'),
),
).captured;
final windowByType = <HealthDataType, Duration>{

View File

@@ -107,11 +107,12 @@ class MockHealthRepository extends _i1.Mock implements _i2.HealthRepository {
as _i4.Future<bool>);
@override
_i4.Future<List<_i6.HealthReading>> read({
_i4.Future<void> read({
required List<_i5.HealthDataType>? types,
required DateTime? start,
required DateTime? end,
required Duration? window,
required _i4.Future<void> Function(List<_i6.HealthReading>, DateTime)? onBatch,
}) =>
(super.noSuchMethod(
Invocation.method(#read, [], {
@@ -119,12 +120,12 @@ class MockHealthRepository extends _i1.Mock implements _i2.HealthRepository {
#start: start,
#end: end,
#window: window,
#onBatch: onBatch,
}),
returnValue: _i4.Future<List<_i6.HealthReading>>.value(
<_i6.HealthReading>[],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i4.Future<List<_i6.HealthReading>>);
as _i4.Future<void>);
}
/// A class which mocks [MeasurementRepository].

View File

@@ -21,17 +21,23 @@ 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/models/health_reading.dart';
import 'package:wger/features/health/providers/health_repository.dart';
import 'health_repository_test.mocks.dart';
HealthDataPoint dataPoint(HealthDataType type) => HealthDataPoint(
uuid: '${type.name}-1',
HealthDataPoint dataPoint(
HealthDataType type, {
String? uuid,
DateTime? dateFrom,
DateTime? dateTo,
}) => HealthDataPoint(
uuid: uuid ?? '${type.name}-1',
value: NumericHealthValue(numericValue: 60),
type: type,
unit: HealthDataUnit.MINUTE,
dateFrom: DateTime(2026, 1, 2),
dateTo: DateTime(2026, 1, 2, 1),
dateFrom: dateFrom ?? DateTime(2026, 1, 2),
dateTo: dateTo ?? dateFrom ?? DateTime(2026, 1, 2, 1),
sourcePlatform: HealthPlatformType.googleHealthConnect,
sourceDeviceId: 'device',
sourceId: 'source',
@@ -75,12 +81,30 @@ void main() {
];
}
/// Runs a read and collects everything the batches delivered.
Future<List<HealthReading>> readAll({
required List<HealthDataType> types,
required DateTime start,
required DateTime end,
required Duration window,
}) async {
final readings = <HealthReading>[];
await repository.read(
types: types,
start: start,
end: end,
window: window,
onBatch: (batch, _) async => readings.addAll(batch),
);
return readings;
}
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(
await readAll(
types: [HealthDataType.WEIGHT],
start: start,
end: end,
@@ -96,7 +120,7 @@ void main() {
final start = DateTime(2026, 1, 1);
final end = DateTime(2026, 4, 10);
await repository.read(
await readAll(
types: [HealthDataType.HEART_RATE],
start: start,
end: end,
@@ -122,7 +146,7 @@ void main() {
final start = DateTime(2026, 1, 1);
final end = DateTime(2026, 3, 1);
await repository.read(
await readAll(
types: [HealthDataType.WEIGHT, HealthDataType.HEART_RATE],
start: start,
end: end,
@@ -134,6 +158,88 @@ void main() {
expect(windows.where((w) => w.$1 == start), hasLength(2));
});
test('hands each window over before the next one is read', () async {
// Holding the whole history until the end would fill the same Android
// heap the windowing exists to protect
final events = <String>[];
var window = 0;
when(
health.getHealthDataFromTypes(
types: anyNamed('types'),
startTime: anyNamed('startTime'),
endTime: anyNamed('endTime'),
),
).thenAnswer((_) async {
window++;
events.add('read window $window');
return [dataPoint(HealthDataType.WEIGHT, uuid: 'w-$window')];
});
await repository.read(
types: [HealthDataType.WEIGHT],
start: DateTime(2026, 1, 1),
end: DateTime(2026, 3, 1),
window: defaultReadWindow,
onBatch: (batch, _) async => events.add('batch of ${batch.length}'),
);
expect(events, ['read window 1', 'batch of 1', 'read window 2', 'batch of 1']);
});
test('a record on the window boundary is delivered once', () async {
// Both windows of a contiguous pair contain their shared boundary, so a
// record sitting exactly on it comes back from both queries
final boundary = DateTime(2026, 1, 1).add(defaultReadWindow);
when(
health.getHealthDataFromTypes(
types: anyNamed('types'),
startTime: anyNamed('startTime'),
endTime: anyNamed('endTime'),
),
).thenAnswer(
(_) async => [dataPoint(HealthDataType.WEIGHT, uuid: 'w-1', dateFrom: boundary)],
);
final readings = await readAll(
types: [HealthDataType.WEIGHT],
start: DateTime(2026, 1, 1),
end: DateTime(2026, 2, 15),
window: defaultReadWindow,
);
expect(readings, hasLength(1));
});
test('an interval spanning several windows is delivered once', () async {
// A duration record overlaps every window it reaches into and comes
// back from each of their queries
when(
health.getHealthDataFromTypes(
types: anyNamed('types'),
startTime: anyNamed('startTime'),
endTime: anyNamed('endTime'),
),
).thenAnswer(
(_) async => [
dataPoint(
HealthDataType.SLEEP_ASLEEP,
uuid: 's-1',
dateFrom: DateTime(2026, 1, 2),
dateTo: DateTime(2026, 1, 8),
),
],
);
final readings = await readAll(
types: [HealthDataType.SLEEP_ASLEEP],
start: DateTime(2026, 1, 1),
end: DateTime(2026, 1, 10),
window: highVolumeReadWindow,
);
expect(readings, hasLength(1));
});
test('a failing window does not cost the other types their read', () async {
when(
health.getHealthDataFromTypes(
@@ -143,7 +249,7 @@ void main() {
),
).thenThrow(Exception('boom'));
final readings = await repository.read(
final readings = await readAll(
types: [HealthDataType.HEART_RATE, HealthDataType.WEIGHT],
start: DateTime(2026, 1, 1),
end: DateTime(2026, 4, 1),
@@ -160,9 +266,10 @@ void main() {
).called(greaterThan(1));
});
test('a type that fails halfway is dropped whole, windows it did read included', () async {
// The watermark moves with what was imported, so half a type would put
// the windows that never returned out of reach for good
test('a type that fails halfway keeps its delivered windows and stops', () async {
// What a batch delivered is already written; the failing type is only
// dropped from the remaining windows, and the caller's unchanged
// watermark makes the re-read harmless
var call = 0;
when(
health.getHealthDataFromTypes(
@@ -170,11 +277,16 @@ void main() {
startTime: anyNamed('startTime'),
endTime: anyNamed('endTime'),
),
).thenAnswer((_) async {
).thenAnswer((invocation) async {
if (call++ > 0) {
throw Exception('boom');
}
return [dataPoint(HealthDataType.SLEEP_DEEP)];
return [
dataPoint(
HealthDataType.SLEEP_DEEP,
dateFrom: invocation.namedArguments[#startTime] as DateTime,
),
];
});
when(
health.getHealthDataFromTypes(
@@ -182,16 +294,35 @@ void main() {
startTime: anyNamed('startTime'),
endTime: anyNamed('endTime'),
),
).thenAnswer((_) async => [dataPoint(HealthDataType.SLEEP_REM)]);
).thenAnswer(
(invocation) async => [
dataPoint(
HealthDataType.SLEEP_REM,
uuid: 'rem-${invocation.namedArguments[#startTime]}',
dateFrom: invocation.namedArguments[#startTime] as DateTime,
),
],
);
final readings = await repository.read(
final readings = await readAll(
types: [HealthDataType.SLEEP_DEEP, HealthDataType.SLEEP_REM],
start: DateTime(2026, 1, 1),
end: DateTime(2026, 4, 1),
window: defaultReadWindow,
);
expect(readings.map((r) => r.type).toSet(), {HealthDataType.SLEEP_REM});
// The first window of the failing type was handed over; the other type
// delivered every window
expect(readings.where((r) => r.type == HealthDataType.SLEEP_DEEP), hasLength(1));
expect(readings.where((r) => r.type == HealthDataType.SLEEP_REM), hasLength(3));
// After the failure the type is not asked again
verify(
health.getHealthDataFromTypes(
types: [HealthDataType.SLEEP_DEEP],
startTime: anyNamed('startTime'),
endTime: anyNamed('endTime'),
),
).called(2);
});
test('a wholesale failure still propagates', () async {
@@ -204,7 +335,7 @@ void main() {
).thenThrow(Exception('boom'));
expect(
() => repository.read(
() => readAll(
types: [HealthDataType.WEIGHT],
start: DateTime(2026, 1, 1),
end: DateTime(2026, 2, 1),

View File

@@ -97,8 +97,17 @@ void main() {
start: anyNamed('start'),
end: anyNamed('end'),
window: anyNamed('window'),
onBatch: anyNamed('onBatch'),
),
).thenAnswer((_) async => readings);
).thenAnswer((invocation) async {
if (readings.isEmpty) {
return;
}
final onBatch =
invocation.namedArguments[#onBatch]
as Future<void> Function(List<HealthReading>, DateTime);
await onBatch(readings, invocation.namedArguments[#end] as DateTime);
});
}
group('HealthSyncState', () {
@@ -133,6 +142,7 @@ void main() {
start: anyNamed('start'),
end: anyNamed('end'),
window: anyNamed('window'),
onBatch: anyNamed('onBatch'),
),
);
});

View File

@@ -107,11 +107,12 @@ class MockHealthRepository extends _i1.Mock implements _i2.HealthRepository {
as _i4.Future<bool>);
@override
_i4.Future<List<_i6.HealthReading>> read({
_i4.Future<void> read({
required List<_i5.HealthDataType>? types,
required DateTime? start,
required DateTime? end,
required Duration? window,
required _i4.Future<void> Function(List<_i6.HealthReading>, DateTime)? onBatch,
}) =>
(super.noSuchMethod(
Invocation.method(#read, [], {
@@ -119,12 +120,12 @@ class MockHealthRepository extends _i1.Mock implements _i2.HealthRepository {
#start: start,
#end: end,
#window: window,
#onBatch: onBatch,
}),
returnValue: _i4.Future<List<_i6.HealthReading>>.value(
<_i6.HealthReading>[],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i4.Future<List<_i6.HealthReading>>);
as _i4.Future<void>);
}
/// A class which mocks [MeasurementRepository].

View File

@@ -13,39 +13,29 @@ import 'package:wger/core/language.dart' as _i42;
import 'package:wger/core/network/base_provider.dart' as _i8;
import 'package:wger/core/search_options.dart' as _i21;
import 'package:wger/features/account/models/user_profile.dart' as _i27;
import 'package:wger/features/account/providers/user_profile_repository.dart'
as _i26;
import 'package:wger/features/account/providers/user_profile_repository.dart' as _i26;
import 'package:wger/features/exercises/models/category.dart' as _i38;
import 'package:wger/features/exercises/models/equipment.dart' as _i40;
import 'package:wger/features/exercises/models/exercise_filters.dart' as _i37;
import 'package:wger/features/exercises/models/muscle.dart' as _i41;
import 'package:wger/features/exercises/providers/exercise_repository.dart'
as _i36;
import 'package:wger/features/exercises/providers/exercises_notifier.dart'
as _i39;
import 'package:wger/features/exercises/providers/exercise_repository.dart' as _i36;
import 'package:wger/features/exercises/providers/exercises_notifier.dart' as _i39;
import 'package:wger/features/gallery/models/image.dart' as _i2;
import 'package:wger/features/gallery/providers/gallery_repository.dart'
as _i10;
import 'package:wger/features/gallery/providers/gallery_repository.dart' as _i10;
import 'package:wger/features/health/models/health_reading.dart' as _i45;
import 'package:wger/features/health/providers/health_repository.dart' as _i43;
import 'package:wger/features/measurements/models/measurement_bucket.dart'
as _i25;
import 'package:wger/features/measurements/models/measurement_category.dart'
as _i23;
import 'package:wger/features/measurements/models/measurement_entry.dart'
as _i24;
import 'package:wger/features/measurements/providers/measurement_repository.dart'
as _i22;
import 'package:wger/features/measurements/models/measurement_bucket.dart' as _i25;
import 'package:wger/features/measurements/models/measurement_category.dart' as _i23;
import 'package:wger/features/measurements/models/measurement_entry.dart' as _i24;
import 'package:wger/features/measurements/providers/measurement_repository.dart' as _i22;
import 'package:wger/features/nutrition/models/ingredient.dart' as _i19;
import 'package:wger/features/nutrition/models/ingredient_filters.dart' as _i20;
import 'package:wger/features/nutrition/models/log.dart' as _i17;
import 'package:wger/features/nutrition/models/meal.dart' as _i15;
import 'package:wger/features/nutrition/models/meal_item.dart' as _i16;
import 'package:wger/features/nutrition/models/nutritional_plan.dart' as _i14;
import 'package:wger/features/nutrition/providers/ingredient_repository.dart'
as _i18;
import 'package:wger/features/nutrition/providers/nutrition_repository.dart'
as _i13;
import 'package:wger/features/nutrition/providers/ingredient_repository.dart' as _i18;
import 'package:wger/features/nutrition/providers/nutrition_repository.dart' as _i13;
import 'package:wger/features/routines/models/base_config.dart' as _i7;
import 'package:wger/features/routines/models/day.dart' as _i4;
import 'package:wger/features/routines/models/repetition_unit.dart' as _i30;
@@ -54,16 +44,12 @@ import 'package:wger/features/routines/models/session.dart' as _i9;
import 'package:wger/features/routines/models/slot.dart' as _i5;
import 'package:wger/features/routines/models/slot_entry.dart' as _i6;
import 'package:wger/features/routines/models/weight_unit.dart' as _i29;
import 'package:wger/features/routines/providers/routines_repository.dart'
as _i28;
import 'package:wger/features/routines/providers/workout_session_repository.dart'
as _i46;
import 'package:wger/features/routines/providers/routines_repository.dart' as _i28;
import 'package:wger/features/routines/providers/workout_session_repository.dart' as _i46;
import 'package:wger/features/trophies/models/trophy.dart' as _i33;
import 'package:wger/features/trophies/models/user_trophy.dart' as _i34;
import 'package:wger/features/trophies/models/user_trophy_progression.dart'
as _i35;
import 'package:wger/features/trophies/providers/trophy_repository.dart'
as _i31;
import 'package:wger/features/trophies/models/user_trophy_progression.dart' as _i35;
import 'package:wger/features/trophies/providers/trophy_repository.dart' as _i31;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
@@ -81,43 +67,35 @@ import 'package:wger/features/trophies/providers/trophy_repository.dart'
// ignore_for_file: invalid_use_of_internal_member
class _FakeGalleryImage_0 extends _i1.SmartFake implements _i2.GalleryImage {
_FakeGalleryImage_0(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
_FakeGalleryImage_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
class _FakeRoutine_1 extends _i1.SmartFake implements _i3.Routine {
_FakeRoutine_1(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
_FakeRoutine_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
class _FakeDay_2 extends _i1.SmartFake implements _i4.Day {
_FakeDay_2(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
_FakeDay_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
class _FakeSlot_3 extends _i1.SmartFake implements _i5.Slot {
_FakeSlot_3(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
_FakeSlot_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
class _FakeSlotEntry_4 extends _i1.SmartFake implements _i6.SlotEntry {
_FakeSlotEntry_4(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
_FakeSlotEntry_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
class _FakeBaseConfig_5 extends _i1.SmartFake implements _i7.BaseConfig {
_FakeBaseConfig_5(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
_FakeBaseConfig_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
class _FakeWgerBaseProvider_6 extends _i1.SmartFake
implements _i8.WgerBaseProvider {
class _FakeWgerBaseProvider_6 extends _i1.SmartFake implements _i8.WgerBaseProvider {
_FakeWgerBaseProvider_6(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
class _FakeWorkoutSession_7 extends _i1.SmartFake
implements _i9.WorkoutSession {
class _FakeWorkoutSession_7 extends _i1.SmartFake implements _i9.WorkoutSession {
_FakeWorkoutSession_7(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
@@ -187,8 +165,7 @@ class MockGalleryRepository extends _i1.Mock implements _i10.GalleryRepository {
/// A class which mocks [NutritionRepository].
///
/// See the documentation for Mockito's code generation for more information.
class MockNutritionRepository extends _i1.Mock
implements _i13.NutritionRepository {
class MockNutritionRepository extends _i1.Mock implements _i13.NutritionRepository {
MockNutritionRepository() {
_i1.throwOnMissingStub(this);
}
@@ -320,8 +297,7 @@ class MockNutritionRepository extends _i1.Mock
/// A class which mocks [IngredientRepository].
///
/// See the documentation for Mockito's code generation for more information.
class MockIngredientRepository extends _i1.Mock
implements _i18.IngredientRepository {
class MockIngredientRepository extends _i1.Mock implements _i18.IngredientRepository {
MockIngredientRepository() {
_i1.throwOnMissingStub(this);
}
@@ -445,8 +421,7 @@ class MockIngredientRepository extends _i1.Mock
/// A class which mocks [MeasurementRepository].
///
/// See the documentation for Mockito's code generation for more information.
class MockMeasurementRepository extends _i1.Mock
implements _i22.MeasurementRepository {
class MockMeasurementRepository extends _i1.Mock implements _i22.MeasurementRepository {
MockMeasurementRepository() {
_i1.throwOnMissingStub(this);
}
@@ -503,8 +478,7 @@ class MockMeasurementRepository extends _i1.Mock
_i11.Stream<Map<String, _i24.MeasurementEntry>> watchLatestEntries() =>
(super.noSuchMethod(
Invocation.method(#watchLatestEntries, []),
returnValue:
_i11.Stream<Map<String, _i24.MeasurementEntry>>.empty(),
returnValue: _i11.Stream<Map<String, _i24.MeasurementEntry>>.empty(),
)
as _i11.Stream<Map<String, _i24.MeasurementEntry>>);
@@ -544,8 +518,7 @@ class MockMeasurementRepository extends _i1.Mock
[parentId],
{#since: since, #level: level, #maxPoints: maxPoints},
),
returnValue:
_i11.Stream<Map<String, List<_i25.MeasurementBucket>>>.empty(),
returnValue: _i11.Stream<Map<String, List<_i25.MeasurementBucket>>>.empty(),
)
as _i11.Stream<Map<String, List<_i25.MeasurementBucket>>>);
@@ -553,8 +526,7 @@ class MockMeasurementRepository extends _i1.Mock
_i11.Stream<Map<String, List<_i25.MeasurementBucket>>> watchDailyBuckets() =>
(super.noSuchMethod(
Invocation.method(#watchDailyBuckets, []),
returnValue:
_i11.Stream<Map<String, List<_i25.MeasurementBucket>>>.empty(),
returnValue: _i11.Stream<Map<String, List<_i25.MeasurementBucket>>>.empty(),
)
as _i11.Stream<Map<String, List<_i25.MeasurementBucket>>>);
@@ -703,8 +675,7 @@ class MockMeasurementRepository extends _i1.Mock
/// A class which mocks [UserProfileRepository].
///
/// See the documentation for Mockito's code generation for more information.
class MockUserProfileRepository extends _i1.Mock
implements _i26.UserProfileRepository {
class MockUserProfileRepository extends _i1.Mock implements _i26.UserProfileRepository {
MockUserProfileRepository() {
_i1.throwOnMissingStub(this);
}
@@ -739,8 +710,7 @@ class MockUserProfileRepository extends _i1.Mock
/// A class which mocks [RoutinesRepository].
///
/// See the documentation for Mockito's code generation for more information.
class MockRoutinesRepository extends _i1.Mock
implements _i28.RoutinesRepository {
class MockRoutinesRepository extends _i1.Mock implements _i28.RoutinesRepository {
MockRoutinesRepository() {
_i1.throwOnMissingStub(this);
}
@@ -1051,8 +1021,7 @@ class MockTrophyRepository extends _i1.Mock implements _i31.TrophyRepository {
/// A class which mocks [ExerciseRepository].
///
/// See the documentation for Mockito's code generation for more information.
class MockExerciseRepository extends _i1.Mock
implements _i36.ExerciseRepository {
class MockExerciseRepository extends _i1.Mock implements _i36.ExerciseRepository {
MockExerciseRepository() {
_i1.throwOnMissingStub(this);
}
@@ -1212,11 +1181,12 @@ class MockHealthRepository extends _i1.Mock implements _i43.HealthRepository {
as _i11.Future<bool>);
@override
_i11.Future<List<_i45.HealthReading>> read({
_i11.Future<void> read({
required List<_i44.HealthDataType>? types,
required DateTime? start,
required DateTime? end,
required Duration? window,
required _i11.Future<void> Function(List<_i45.HealthReading>, DateTime)? onBatch,
}) =>
(super.noSuchMethod(
Invocation.method(#read, [], {
@@ -1224,19 +1194,18 @@ class MockHealthRepository extends _i1.Mock implements _i43.HealthRepository {
#start: start,
#end: end,
#window: window,
#onBatch: onBatch,
}),
returnValue: _i11.Future<List<_i45.HealthReading>>.value(
<_i45.HealthReading>[],
),
returnValue: _i11.Future<void>.value(),
returnValueForMissingStub: _i11.Future<void>.value(),
)
as _i11.Future<List<_i45.HealthReading>>);
as _i11.Future<void>);
}
/// A class which mocks [WorkoutSessionRepository].
///
/// See the documentation for Mockito's code generation for more information.
class MockWorkoutSessionRepository extends _i1.Mock
implements _i46.WorkoutSessionRepository {
class MockWorkoutSessionRepository extends _i1.Mock implements _i46.WorkoutSessionRepository {
MockWorkoutSessionRepository() {
_i1.throwOnMissingStub(this);
}