fix(train): the firmware relay's calls to Polar time out, are bounded and limited per person (ADR 0030, D55)

Like BRouter's and Photon's: timeouts on connecting and reading, a check answer up to 64 KB and a file up to 64 MB, no redirect but to https, one fetch per file at a time, and 10 checks and downloads a minute for a person (tooOften). An answer that names no update properly is unreachable, no longer no update. The relay is the pod's, as routing's and search's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Tizian 「ティツィアーン」 <raisondetredev@pm.me>
This commit is contained in:
Tizian 「ティツィアーン」 2026-10-30 12:55:42 +01:00
commit 0240a80faf
Signed by: raisondetredev
GPG key ID: 07F6FCF405488B64
2 changed files with 481 additions and 92 deletions

View file

@ -1,8 +1,8 @@
import 'dart:async';
import 'dart:typed_data';
import 'package:clock/clock.dart';
import 'package:halkyon_train_server/src/firmware/firmware_endpoint.dart';
import 'package:halkyon_train_server/src/firmware/firmware_relay.dart';
import 'package:halkyon_train_server/src/generated/protocol.dart';
import 'package:serverpod/serverpod.dart';
@ -21,6 +21,9 @@ class _FakePolar() implements PolarFirmwareService {
int fetches = 0;
bool down = false;
/// Where set, fetches wait for it.
Completer<void>? fetching;
@override
Future<({String version, Uri file})?> check({
required String uuid,
@ -37,13 +40,18 @@ class _FakePolar() implements PolarFirmwareService {
@override
Future<Uint8List> fetch(Uri file) async {
fetches++;
await fetching?.future;
return Uint8List.fromList([1, 2, 3]);
}
}
Matcher _refused(String reason) => throwsA(
isA<LoopFirmwareRefused>().having((e) => e.reason, 'reason', reason),
);
/// The Loop's firmware through the instance (ADR 0030, D10, D40): for the
/// people signed in, unless the operator turned it off; each file fetched
/// once for every band of its hardware.
/// people signed in, unless the operator turned it off, within a limit a
/// minute (D11); each file fetched once for every band of its hardware.
void main() {
withServerpod('Relaying the Loop firmware', (sessionBuilder, endpoints) {
late _FakePolar polar;
@ -53,11 +61,19 @@ void main() {
{},
),
);
final other = sessionBuilder.copyWith(
authentication: AuthenticationOverride.authenticationInfo(
const Uuid().v7(),
{},
),
);
void useRelay(FirmwareRelay relay) =>
FirmwareRelay.use(sessionBuilder.build().serverpod, relay);
setUp(() {
polar = _FakePolar();
firmwareRelay = FirmwareRelay(polar);
firmwareRelayed = () => true;
useRelay(FirmwareRelay(polar));
});
test('names an update to someone signed in, and hands its file', () async {
@ -91,6 +107,48 @@ void main() {
expect(polar.fetches, 1);
});
test(
'fetches a file once for those downloading it at the same time',
() async {
await endpoints.firmware.check(signedIn, 'uuid-1', '3.0.0', 'HW-1');
polar.fetching = Completer();
final first = endpoints.firmware.download(signedIn, 'HW-1', '3.1.2');
final second = endpoints.firmware.download(other, 'HW-1', '3.1.2');
await pumpEventQueue();
polar.fetching!.complete();
for (final file in await Future.wait([first, second])) {
expect(Uint8List.sublistView(file), [1, 2, 3]);
}
expect(polar.fetches, 1);
},
);
test('refuses a person beyond the checks and downloads of a minute, not '
'others, and relays again a minute later', () async {
var now = DateTime.utc(2026, 10, 28, 12);
await withClock(Clock(() => now), () async {
await endpoints.firmware.check(signedIn, 'uuid-1', '3.0.0', 'HW-1');
for (var i = 1; i < FirmwareRelay.perMinute; i++) {
await endpoints.firmware.download(signedIn, 'HW-1', '3.1.2');
}
await expectLater(
endpoints.firmware.check(signedIn, 'uuid-1', '3.0.0', 'HW-1'),
_refused('tooOften'),
);
await expectLater(
endpoints.firmware.download(signedIn, 'HW-1', '3.1.2'),
_refused('tooOften'),
);
expect(polar.checks, 1);
await endpoints.firmware.check(other, 'uuid-2', '3.0.0', 'HW-1');
now = now.add(const Duration(minutes: 1));
await endpoints.firmware.check(signedIn, 'uuid-1', '3.0.0', 'HW-1');
});
});
test('hands no file a check never named', () async {
await expectLater(
endpoints.firmware.download(signedIn, 'HW-9', '9.9.9'),
@ -120,7 +178,7 @@ void main() {
expect(polar.checks, 0);
});
test("says Polar didn't answer", () async {
test("says Polar didn't answer, or not as it does", () async {
polar.down = true;
await expectLater(
@ -138,7 +196,7 @@ void main() {
test(
'relays nothing where the operator turned it off, and says so',
() async {
firmwareRelayed = () => false;
useRelay(FirmwareRelay(polar, offered: false));
expect(await endpoints.firmware.offered(signedIn), isFalse);
await expectLater(
@ -185,23 +243,26 @@ void main() {
test('a file is kept a day, then fetched again after a new check', () async {
final polar = _FakePolar();
final relay = FirmwareRelay(polar);
final person = const Uuid().v7obj();
var now = DateTime.utc(2026, 10, 28, 9);
await withClock(Clock(() => now), () async {
await relay.check(
person,
uuid: 'uuid-1',
firmwareVersion: '3.0.0',
hardwareCode: 'HW-1',
);
await relay.download(hardwareCode: 'HW-1', version: '3.1.2');
await relay.download(person, hardwareCode: 'HW-1', version: '3.1.2');
now = now.add(const Duration(hours: 25));
// Checked again a day on, before any download: fetched anew.
await relay.check(
person,
uuid: 'uuid-1',
firmwareVersion: '3.0.0',
hardwareCode: 'HW-1',
);
await relay.download(hardwareCode: 'HW-1', version: '3.1.2');
await relay.download(person, hardwareCode: 'HW-1', version: '3.1.2');
});
expect(polar.fetches, 2);

View file

@ -0,0 +1,187 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:halkyon_train_server/src/firmware/firmware_relay.dart';
import 'package:test/test.dart';
/// Polar's firmware service on the loopback, answering each request with
/// [answer].
Future<Uri> _polar(Future<void> Function(HttpRequest request) answer) async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
server.listen(answer);
addTearDown(() => server.close(force: true));
return Uri.parse('http://127.0.0.1:${server.port}/');
}
/// Answers [request] with [status] and [body] as JSON.
Future<void> _json(HttpRequest request, Object? body, {int? status}) async {
request.response
..statusCode = status ?? HttpStatus.ok
..headers.contentType = ContentType.json
..write(jsonEncode(body));
await request.response.close();
}
Future<({String version, Uri file})?> _check(HttpPolarFirmwareService polar) =>
polar.check(uuid: 'uuid-1', firmwareVersion: '3.0.0', hardwareCode: 'HW-1');
final _failed = throwsA(isA<PolarFailed>());
/// Polar's firmware service as Train's server asks it (ADR 0030, D10, D40):
/// an update only where Polar names one in the format it does, every wait
/// and every answer bounded, no file but over `https`.
void main() {
test('asks the check with the SDK client name and the band, and reads '
'the version and the file', () async {
final asked = <(String, Object?)>[];
final base = await _polar((request) async {
asked.add((
request.uri.path,
jsonDecode(await utf8.decodeStream(request)),
));
await _json(request, {
'version': '3.1.2',
'fileUrl': 'https://files.example/loop-3.1.2.zip',
});
});
final update = await _check(HttpPolarFirmwareService(base: base));
expect(update?.version, '3.1.2');
expect(update?.file, Uri.parse('https://files.example/loop-3.1.2.zip'));
expect(asked.single.$1, '/api/v1/firmware-update/check');
expect(asked.single.$2, {
'clientId': 'polar-sensor-data-collector-android',
'uuid': 'uuid-1',
'firmwareVersion': '3.0.0',
'hardwareCode': 'HW-1',
});
});
test('names no update where Polar answers none', () async {
for (final status in [HttpStatus.noContent, HttpStatus.notFound]) {
final base = await _polar((request) async {
request.response.statusCode = status;
await request.response.close();
});
expect(await _check(HttpPolarFirmwareService(base: base)), isNull);
}
});
test('fails, rather than naming no update, on an answer without a '
'version or a file, or with a file not over https', () async {
for (final body in [
{'version': '3.1.2'},
{'fileUrl': 'https://files.example/loop-3.1.2.zip'},
{'version': '3.1.2', 'fileUrl': 'http://files.example/loop-3.1.2.zip'},
'not an update',
]) {
final base = await _polar((request) => _json(request, body));
await expectLater(_check(HttpPolarFirmwareService(base: base)), _failed);
}
});
test(
'fails on another status, and follows no redirect of the check',
() async {
for (final status in [HttpStatus.badGateway, HttpStatus.found]) {
final base = await _polar((request) async {
request.response
..statusCode = status
..headers.set(
HttpHeaders.locationHeader,
'https://elsewhere.example/',
);
await request.response.close();
});
await expectLater(
_check(HttpPolarFirmwareService(base: base)),
_failed,
);
}
},
);
test('fails on a check answer beyond its size', () async {
final base = await _polar((request) async {
// Chunked, so that no length says so beforehand.
request.response
..statusCode = HttpStatus.ok
..write('"${'x' * HttpPolarFirmwareService.maxAnswer}"');
await request.response.close();
});
await expectLater(_check(HttpPolarFirmwareService(base: base)), _failed);
});
test('gives up on a Polar that never answers', () async {
final base = await _polar((request) async {
// Holds the request open, answering nothing.
});
await expectLater(
_check(
HttpPolarFirmwareService(
base: base,
timeout: const Duration(milliseconds: 200),
),
),
throwsA(isA<TimeoutException>()),
);
});
test('fetches a file', () async {
final base = await _polar((request) async {
request.response.add([1, 2, 3]);
await request.response.close();
});
expect(
await HttpPolarFirmwareService().fetch(base.resolve('loop.zip')),
[1, 2, 3],
);
});
test(
'fails on a file whose length is beyond its size, before reading it',
() async {
final base = await _polar((request) async {
request.response
..contentLength = HttpPolarFirmwareService.maxFile + 1
..add([1, 2, 3]);
// The rest never comes: the client goes before it would.
try {
await request.response.close();
} on HttpException {
// The client went first.
}
});
await expectLater(
HttpPolarFirmwareService().fetch(base.resolve('loop.zip')),
_failed,
);
},
);
test('follows no redirect of a file away from https', () async {
final asked = <String>[];
final base = await _polar((request) async {
asked.add(request.uri.path);
request.response
..statusCode = HttpStatus.found
..headers.set(HttpHeaders.locationHeader, '/elsewhere.zip');
await request.response.close();
});
await expectLater(
HttpPolarFirmwareService().fetch(base.resolve('loop.zip')),
_failed,
);
expect(asked, ['/loop.zip']);
});
}