diff --git a/lib/services/link/desktop/link_desktop_host.dart b/lib/services/link/desktop/link_desktop_host.dart index 3b14f584d..d62484d3b 100644 --- a/lib/services/link/desktop/link_desktop_host.dart +++ b/lib/services/link/desktop/link_desktop_host.dart @@ -209,6 +209,7 @@ class LinkDesktopHost extends Notifier { Timer? _stateTimer; Timer? _heartbeat; Timer? _downloadsTimer; + LinkDownloadUpdates? _downloadUpdates; Future _transition = Future.value(); bool _exporting = false; bool _exportAgain = false; @@ -664,6 +665,11 @@ class LinkDesktopHost extends Notifier { } void _listenApp() { + final updates = _downloadUpdates = LinkDownloadUpdates( + items: () => ref.read(linkDownloadItemsProvider), + send: (message, id) => _send(message, deviceId: id), + )..keepConnected(state.clients); + unawaited(updates.publish(snapshotsOnly: true)); _lyricsTranslations = LinkLyricsTranslations( sharing: ref.read(lyricsTranslationSharingProvider), send: (message, deviceId) async { @@ -690,6 +696,8 @@ class LinkDesktopHost extends Notifier { } void _cancelApp() { + _downloadUpdates?.dispose(); + _downloadUpdates = null; _lyricsTranslations?.dispose(); _lyricsTranslations = null; for (final subscription in _appSubscriptions) { @@ -741,6 +749,13 @@ class LinkDesktopHost extends Notifier { } void _onMessage(LinkMessageEvent event) { + if (event.type == LinkMessageTypes.downloadsSubscribe) { + final updates = _downloadUpdates; + if (updates?.subscribe(event.deviceId, event.message['deltas']) == true) { + unawaited(updates!.publish(snapshotsOnly: true)); + } + return; + } if (state.clients.any((client) => client.deviceId == event.deviceId) && (_lyricsTranslations?.handle(event.message, deviceId: event.deviceId) ?? false)) { @@ -883,6 +898,9 @@ class LinkDesktopHost extends Notifier { ); _phoneSources?.keepConnected(ids); _transfers?.keepConnected(ids); + final updates = _downloadUpdates; + updates?.keepConnected(clients); + if (updates != null) unawaited(updates.publish(snapshotsOnly: true)); _updateHeartbeat(); // A phone that just connected gets the desktop's state right away. if (!known.containsAll(ids)) { @@ -963,12 +981,8 @@ class LinkDesktopHost extends Notifier { _downloadsTimer = Timer(downloadsDelay, () { _downloadsTimer = null; if (!ref.mounted || !state.running || state.clients.isEmpty) return; - unawaited( - _send({ - 'type': LinkMessageTypes.downloadsChanged, - ...linkDownloadsPayload(ref.read(linkDownloadItemsProvider)), - }), - ); + final updates = _downloadUpdates; + if (updates != null) unawaited(updates.publish()); }); } diff --git a/lib/services/link/desktop/link_downloads.dart b/lib/services/link/desktop/link_downloads.dart index 7c5dbefa7..f1d9445d3 100644 --- a/lib/services/link/desktop/link_downloads.dart +++ b/lib/services/link/desktop/link_downloads.dart @@ -1,3 +1,4 @@ +import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:mornye/models/download_item.dart'; import 'package:mornye/models/track.dart'; @@ -55,6 +56,121 @@ Map linkDownloadsPayload( ], }; +/// Negotiated queue updates, with a full snapshot for older phones and each +/// new subscription. Only the newest send request waits behind an active send. +class LinkDownloadUpdates { + LinkDownloadUpdates({ + required List Function() items, + required Future Function(Map, String) send, + }) : _items = items, + _send = send; + + final List Function() _items; + final Future Function(Map, String) _send; + final _peers = {}; + Future? _sending; + bool _pending = false; + bool _updatesPending = false; + bool _disposed = false; + + void keepConnected(List clients) { + final ids = {for (final client in clients) client.deviceId}; + _peers.removeWhere((id, _) => !ids.contains(id)); + for (final client in clients) { + if (_peers[client.deviceId]?.connectedMs != client.connectedMs) { + _peers[client.deviceId] = _DownloadPeer(client.connectedMs); + } + } + } + + bool subscribe(String deviceId, Object? version) { + final peer = _peers[deviceId]; + if (_disposed || peer == null || version != 1) return false; + peer.deltas = true; + peer.full = true; + return true; + } + + Future publish({bool snapshotsOnly = false}) { + if (_disposed) return Future.value(); + _pending = true; + _updatesPending |= !snapshotsOnly; + return _sending ??= _drain().whenComplete(() { + _sending = null; + if (_pending && !_disposed) return publish(snapshotsOnly: true); + }); + } + + Future _drain() async { + while (_pending && !_disposed) { + _pending = false; + final updates = _updatesPending; + _updatesPending = false; + if (_peers.isEmpty) continue; + final items = (linkDownloadsPayload(_items())['items'] as List) + .cast>(); + for (final MapEntry(key: id, value: peer) in Map.of(_peers).entries) { + if (_disposed) return; + if (_peers[id] != peer) continue; + if (!updates && !peer.full) continue; + final before = peer.items; + final delta = before == null ? null : _delta(before, items); + if (!peer.full && before != null && delta == null) continue; + final message = peer.deltas && !peer.full && before != null + ? {'type': LinkMessageTypes.downloadsDelta, ...delta!} + : {'type': LinkMessageTypes.downloadsChanged, 'items': items}; + peer.full = false; + var sent = 0; + try { + sent = await _send(message, id); + } catch (_) { + // The next successful send must establish a complete baseline. + } + if (_peers[id] == peer) peer.items = sent > 0 ? items : null; + } + } + } + + static Map? _delta( + List> before, + List> items, + ) { + final old = {for (final item in before) item['id']: item}; + final ids = [for (final item in items) item['id'] as String]; + final changed = [ + for (final item in items) + if (!mapEquals(old[item['id']], item)) item, + ]; + final removed = [ + for (final id in old.keys) + if (!ids.contains(id)) id, + ]; + final orderChanged = !listEquals(old.keys.toList(), ids); + if (changed.isEmpty && removed.isEmpty && !orderChanged) return null; + return { + 'items': changed, + 'removed': removed, + if (orderChanged) 'order': ids, + }; + } + + void dispose() { + _disposed = true; + _pending = false; + _updatesPending = false; + _peers.clear(); + } +} + +class _DownloadPeer { + _DownloadPeer(this.connectedMs); + + final int connectedMs; + bool deltas = false; + bool full = true; + List>? items; +} + class AppLinkDownloadsPort implements LinkDownloadsPort { AppLinkDownloadsPort(this._ref); diff --git a/lib/services/link/features/link_desktop_remote.dart b/lib/services/link/features/link_desktop_remote.dart index c6656c75b..215091ba1 100644 --- a/lib/services/link/features/link_desktop_remote.dart +++ b/lib/services/link/features/link_desktop_remote.dart @@ -85,18 +85,29 @@ class LinkDesktopRemote extends Notifier { final int Function() _nowMs; LinkClientApi? _client; + int _generation = 0; + int _refreshRequest = 0; + int _downloadPushes = 0; + bool _downloadsReady = false; @override LinkRemoteState build() { + _generation++; + _downloadsReady = false; final client = _client = ref.watch(linkPhoneClientProvider); if (client == null) return const LinkRemoteState(); - final messages = client.messages.listen(_onMessage); + final messages = client.messages.listen((message) { + if (_client == client) _onMessage(message); + }); final connections = client.connectionStates.listen((connection) { if (!ref.mounted || _client != client) return; + _generation++; + _downloadsReady = false; state = state.copyWith(connection: connection); if (connection == LinkConnectionState.connected) unawaited(refresh()); }); ref.onDispose(() { + _generation++; unawaited(messages.cancel()); unawaited(connections.cancel()); }); @@ -120,7 +131,19 @@ class LinkDesktopRemote extends Notifier { final player = LinkPlayerState.fromJson(message['state']); if (player != null) state = state.copyWith(player: _received(player)); case LinkMessageTypes.downloadsChanged: + _downloadPushes++; + _downloadsReady = true; state = state.copyWith(downloads: linkParseDownloads(message)); + case LinkMessageTypes.downloadsDelta: + if (!_downloadsReady) return; + final downloads = linkApplyDownloadDelta(state.downloads, message); + if (downloads == null) { + _downloadsReady = false; + _subscribeDownloads(); + return; + } + _downloadPushes++; + state = state.copyWith(downloads: downloads); } } @@ -128,24 +151,43 @@ class LinkDesktopRemote extends Notifier { Future refresh() async { final client = _client; if (client == null || !ref.mounted) return; + final generation = _generation; + final request = ++_refreshRequest; + bool current() => + ref.mounted && + _client == client && + _generation == generation && + _refreshRequest == request; try { final player = LinkPlayerState.fromJson(await client.get(LinkOps.state)); - if (!ref.mounted || _client != client) return; + if (!current()) return; state = LinkRemoteState( connection: state.connection, player: player == null ? null : _received(player), downloads: state.downloads, ); } on Object catch (error) { - if (!ref.mounted || _client != client) return; + if (!current()) return; state = state.copyWith(loading: false, error: error); } + final pushes = _downloadPushes; try { final downloads = linkParseDownloads(await client.get(LinkOps.downloads)); - if (!ref.mounted || _client != client) return; - state = state.copyWith(downloads: downloads); + if (!current()) return; + if (_downloadPushes == pushes) { + state = state.copyWith(downloads: downloads); + } } on Object { // The player stays usable when the download queue is unavailable. + } finally { + if (current()) _subscribeDownloads(); + } + } + + void _subscribeDownloads() { + final client = _client; + if (client?.connectionState == LinkConnectionState.connected) { + client!.send({'type': LinkMessageTypes.downloadsSubscribe, 'deltas': 1}); } } diff --git a/lib/services/link/features/link_downloads.dart b/lib/services/link/features/link_downloads.dart index 65cbae409..39946131b 100644 --- a/lib/services/link/features/link_downloads.dart +++ b/lib/services/link/features/link_downloads.dart @@ -54,6 +54,45 @@ List linkParseDownloads(Object? json) { return [for (final item in items) ?LinkDesktopDownload.fromJson(item)]; } +/// Applies a negotiated update to the newest 200 queue entries. A malformed +/// update needs a fresh snapshot instead of leaving a partial queue visible. +List? linkApplyDownloadDelta( + List before, + Map message, +) { + final items = message['items']; + final removed = message['removed']; + final order = message['order']; + if (items is! List || + removed is! List || + items.length > 200 || + removed.length > 200 || + (order != null && (order is! List || order.length > 200))) { + return null; + } + final byId = {for (final item in before) item.id: item}; + for (final id in removed) { + if (id is! String) return null; + byId.remove(id); + } + for (final value in items) { + final item = LinkDesktopDownload.fromJson(value); + if (item == null) return null; + byId[item.id] = item; + } + if (byId.length > 200) return null; + if (order == null) return byId.values.toList(); + final ordered = []; + final seen = {}; + for (final id in order as List) { + if (id is! String || !seen.add(id)) return null; + final item = byId[id]; + if (item == null) return null; + ordered.add(item); + } + return ordered.length == byId.length ? ordered : null; +} + /// The `POST downloads` body that queues [tracks] on the desktop. Map linkDownloadTracksBody( List tracks, { diff --git a/lib/services/link/link_protocol.dart b/lib/services/link/link_protocol.dart index 1395fb9a5..b7c2a22f4 100644 --- a/lib/services/link/link_protocol.dart +++ b/lib/services/link/link_protocol.dart @@ -133,6 +133,8 @@ abstract final class LinkMessageTypes { static const command = 'command'; static const open = 'open'; static const downloadsChanged = 'downloads.changed'; + static const downloadsSubscribe = 'downloads.subscribe'; + static const downloadsDelta = 'downloads.delta'; static const collectionsChanged = 'collections.changed'; static const catalogChanged = 'catalog.changed'; static const lyricsTranslation = 'lyrics.translation'; diff --git a/test/link_desktop_host_test.dart b/test/link_desktop_host_test.dart index 58c95507b..9bf7df231 100644 --- a/test/link_desktop_host_test.dart +++ b/test/link_desktop_host_test.dart @@ -375,6 +375,74 @@ void main() { await shutdown(tester); }); + testWidgets( + 'negotiated download pushes target deltas and reconnect snapshots', + (tester) async { + await boot(tester); + DownloadItem item(int id, double progress) => DownloadItem( + id: 'q$id', + track: Track( + id: 't$id', + name: 'Song $id', + artistName: 'Artist', + albumName: 'Album', + duration: 100, + ), + service: 'example-service', + status: DownloadStatus.downloading, + progress: progress, + createdAt: DateTime(2024), + ); + final queue = container.read(fakeDownloadItemsProvider.notifier); + queue.replace(List.generate(200, (i) => item(i, 0.1))); + backend.connect([_phone, _tablet]); + await flush(tester); + expect( + backend.sentOfType(LinkMessageTypes.downloadsChanged), + hasLength(2), + ); + backend.message('p1', { + 'type': LinkMessageTypes.downloadsSubscribe, + 'deltas': 1, + }); + await flush(tester); + expect( + backend.sentOfType(LinkMessageTypes.downloadsChanged), + hasLength(3), + ); + backend.sent.clear(); + queue.replace(List.generate(200, (i) => item(i, i == 0 ? 0.9 : 0.1))); + await tester.pump(const Duration(milliseconds: 999)); + expect(backend.sentOfType(LinkMessageTypes.downloadsDelta), isEmpty); + await tester.pump(const Duration(milliseconds: 1)); + await flush(tester); + final deltas = backend.sent + .where( + (entry) => entry.message['type'] == LinkMessageTypes.downloadsDelta, + ) + .toList(); + expect(deltas, hasLength(1)); + final delta = deltas.single; + expect(delta.deviceId, 'p1'); + expect(delta.message['items'], hasLength(1)); + final legacy = backend.sent.singleWhere( + (entry) => entry.message['type'] == LinkMessageTypes.downloadsChanged, + ); + expect(legacy.deviceId, 'p2'); + expect(legacy.message['items'], hasLength(200)); + + backend.connect([_tablet]); + await flush(tester); + backend.sent.clear(); + backend.connect([_phone, _tablet]); + await flush(tester); + final reconnect = backend.sentOfType(LinkMessageTypes.downloadsChanged); + expect(reconnect, hasLength(1)); + expect(reconnect.single['items'], hasLength(200)); + await shutdown(tester); + }, + ); + testWidgets('keeps each phone state until the phone disconnects', ( tester, ) async { diff --git a/test/link_desktop_remote_test.dart b/test/link_desktop_remote_test.dart index ba264a119..0149bcb62 100644 --- a/test/link_desktop_remote_test.dart +++ b/test/link_desktop_remote_test.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mornye/services/link/features/link_desktop_remote.dart'; @@ -247,4 +249,139 @@ void main() { expect(read().loading, isFalse); expect(read().error, isA()); }); + + test( + 'negotiates deltas after a full GET and again after reconnect', + () async { + await start(); + expect(client.sent, [ + {'type': LinkMessageTypes.downloadsSubscribe, 'deltas': 1}, + ]); + client.setConnection(LinkConnectionState.disconnected); + client.setConnection(LinkConnectionState.connected); + await pumpEventQueue(); + expect(client.sent, hasLength(2)); + expect(client.gets, [ + LinkOps.state, + LinkOps.downloads, + LinkOps.state, + LinkOps.downloads, + ]); + expect(read().downloads.single.id, 'd1'); + }, + ); + + test( + 'applies changed rows, removals and ordering after a WS baseline', + () async { + await start(); + client.push({ + 'type': LinkMessageTypes.downloadsChanged, + 'items': [ + {'id': 'd1', 'title': 'Original', 'progress': 0.4}, + ], + }); + final retained = read().downloads.single; + client.push({ + 'type': LinkMessageTypes.downloadsDelta, + 'items': [ + {'id': 'd2', 'title': 'New'}, + ], + 'removed': [], + 'order': ['d2', 'd1'], + }); + expect(read().downloads.map((item) => item.id), ['d2', 'd1']); + expect(read().downloads.last, same(retained)); + client.push({ + 'type': LinkMessageTypes.downloadsDelta, + 'items': [ + {'id': 'd2', 'title': 'Renamed', 'status': 'completed'}, + ], + 'removed': ['d1'], + 'order': ['d2'], + }); + expect(read().downloads.single.title, 'Renamed'); + expect(read().downloads.single.finished, isTrue); + }, + ); + + test( + 'ignores deltas before a baseline and requests recovery for invalid data', + () async { + await start(); + client.push({ + 'type': LinkMessageTypes.downloadsDelta, + 'items': [], + 'removed': ['d1'], + 'order': [], + }); + expect(read().downloads.single.id, 'd1'); + client.push({ + 'type': LinkMessageTypes.downloadsChanged, + 'items': [ + {'id': 'd1', 'title': 'Original'}, + ], + }); + client.push({ + 'type': LinkMessageTypes.downloadsDelta, + 'items': [], + 'removed': [], + 'order': ['missing'], + }); + expect(read().downloads.single.title, 'Original'); + expect(client.sent, hasLength(2)); + client.push({ + 'type': LinkMessageTypes.downloadsChanged, + 'items': [], + }); + expect(read().downloads, isEmpty); + }, + ); + + test('a late GET cannot replace newer download pushes', () async { + final remote = await start(); + final reply = Completer(); + client.onGet = (op, _) => + op == LinkOps.state ? _desktopState() : reply.future; + final refresh = remote.refresh(); + await pumpEventQueue(); + client.push({ + 'type': LinkMessageTypes.downloadsChanged, + 'items': [ + {'id': 'new', 'title': 'Newer'}, + ], + }); + reply.complete({'items': []}); + await refresh; + expect(read().downloads.single.id, 'new'); + }); + + test( + 'a previous connection GET cannot overwrite the reconnect snapshot', + () async { + final remote = await start(); + final old = Completer(); + client.onGet = (op, _) => + op == LinkOps.state ? _desktopState() : old.future; + final stale = remote.refresh(); + await pumpEventQueue(); + client.setConnection(LinkConnectionState.disconnected); + client.onGet = (op, _) => op == LinkOps.state + ? _desktopState() + : { + 'items': [ + {'id': 'reconnected'}, + ], + }; + client.setConnection(LinkConnectionState.connected); + await pumpEventQueue(); + old.complete({ + 'items': [ + {'id': 'obsolete'}, + ], + }); + await stale; + expect(read().downloads.single.id, 'reconnected'); + }, + ); } diff --git a/test/link_download_updates_test.dart b/test/link_download_updates_test.dart new file mode 100644 index 000000000..fb69dd114 --- /dev/null +++ b/test/link_download_updates_test.dart @@ -0,0 +1,264 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mornye/models/download_item.dart'; +import 'package:mornye/models/track.dart'; +import 'package:mornye/services/link/desktop/link_downloads.dart'; +import 'package:mornye/services/link/features/link_downloads.dart' as phone; +import 'package:mornye/services/link/link_protocol.dart'; + +DownloadItem _item(String id, {double progress = 0.5}) => DownloadItem( + id: id, + track: Track( + id: id, + name: 'Song $id', + artistName: 'Example artist', + albumName: 'Album', + duration: 100, + ), + service: 'example-service', + status: DownloadStatus.downloading, + progress: progress, + createdAt: DateTime(2024), +); + +const _phone = LinkClientInfo( + deviceId: 'phone', + name: 'Phone', + platform: 'ios', +); +const _legacy = LinkClientInfo( + deviceId: 'legacy', + name: 'Other', + platform: 'android', +); + +void main() { + late List items; + late LinkDownloadUpdates updates; + late List<({String peer, Map message})> sent; + late Future Function() deliver; + + setUp(() { + items = List.generate(200, (i) => _item('q$i')); + sent = []; + deliver = () async => 1; + updates = LinkDownloadUpdates( + items: () => items, + send: (message, peer) { + sent.add((peer: peer, message: message)); + return deliver(); + }, + )..keepConnected([_phone]); + }); + tearDown(() => updates.dispose()); + + Future subscribe() async { + expect(updates.subscribe('phone', 1), isTrue); + await updates.publish(); + expect(sent.single.message['type'], LinkMessageTypes.downloadsChanged); + sent.clear(); + } + + test( + 'legacy phones keep full snapshots, unchanged queues send nothing', + () async { + await updates.publish(); + expect(sent.single.message['items'], hasLength(200)); + expect(sent.single.message['type'], LinkMessageTypes.downloadsChanged); + sent.clear(); + await updates.publish(); + expect(sent, isEmpty); + items[50] = _item('q50', progress: 0.8); + await updates.publish(); + expect(sent.single.message['type'], LinkMessageTypes.downloadsChanged); + expect(sent.single.message['items'], hasLength(200)); + }, + ); + + test( + 'one changed row replaces a 200-row push only for opted-in peers', + () async { + updates.keepConnected([_phone, _legacy]); + expect(updates.subscribe('phone', 1), isTrue); + await updates.publish(); + sent.clear(); + items[50] = _item('q50', progress: 0.8); + await updates.publish(); + final delta = sent.singleWhere((entry) => entry.peer == 'phone').message; + final full = sent.singleWhere((entry) => entry.peer == 'legacy').message; + expect(delta['type'], LinkMessageTypes.downloadsDelta); + expect(delta['items'], [linkDownloadSummary(items[50])]); + expect(delta['removed'], isEmpty); + expect(delta.containsKey('order'), isFalse); + expect(full['type'], LinkMessageTypes.downloadsChanged); + expect(full['items'], hasLength(200)); + final deltaBytes = utf8.encode(jsonEncode(delta)).length; + final fullBytes = utf8.encode(jsonEncode(full)).length; + expect(deltaBytes, lessThan(fullBytes ~/ 20)); + debugPrint( + '200-row progress push: $fullBytes bytes full, $deltaBytes bytes delta', + ); + }, + ); + + test( + 'window rollover, reordering and clearing match a fresh full list', + () async { + final before = phone.linkParseDownloads(linkDownloadsPayload(items)); + await subscribe(); + items = [...items, for (var i = 200; i < 205; i++) _item('q$i')]; + await updates.publish(); + final rollover = sent.single.message; + expect(rollover['items'], hasLength(5)); + expect(rollover['removed'], ['q0', 'q1', 'q2', 'q3', 'q4']); + expect(rollover['order'], hasLength(200)); + var merged = phone.linkApplyDownloadDelta(before, rollover)!; + expect(merged.map((item) => item.id), [ + for (var i = 5; i < 205; i++) 'q$i', + ]); + sent.clear(); + items = items.skip(5).toList().reversed.toList(); + await updates.publish(); + expect(sent.single.message['items'], isEmpty); + expect(sent.single.message['removed'], isEmpty); + merged = phone.linkApplyDownloadDelta(merged, sent.single.message)!; + expect(merged.map((item) => item.id), items.map((item) => item.id)); + sent.clear(); + items = []; + await updates.publish(); + expect(sent.single.message['removed'], hasLength(200)); + expect( + phone.linkApplyDownloadDelta(merged, sent.single.message), + isEmpty, + ); + }, + ); + + test( + 'a new peer snapshot does not flush another peer progress window', + () async { + await subscribe(); + items[0] = _item('q0', progress: 0.9); + updates.keepConnected([_phone, _legacy]); + await updates.publish(snapshotsOnly: true); + expect(sent, hasLength(1)); + expect(sent.single.peer, 'legacy'); + sent.clear(); + await updates.publish(); + expect(sent, hasLength(1)); + expect(sent.single.peer, 'phone'); + expect(sent.single.message['type'], LinkMessageTypes.downloadsDelta); + }, + ); + + test( + 'only connected peers can negotiate the supported delta version', + () async { + expect(updates.subscribe('absent', 1), isFalse); + expect(updates.subscribe('phone', 2), isFalse); + await updates.publish(); + sent.clear(); + items[0] = _item('q0', progress: 0.9); + await updates.publish(); + expect(sent.single.peer, 'phone'); + expect(sent.single.message['type'], LinkMessageTypes.downloadsChanged); + }, + ); + + test( + 'reconnect and repeated subscriptions always establish a full baseline', + () async { + await subscribe(); + items[0] = _item('q0', progress: 0.9); + updates.keepConnected([]); + await updates.publish(); + expect(sent, isEmpty); + updates.keepConnected([_phone]); + await updates.publish(); + expect(sent.single.message['type'], LinkMessageTypes.downloadsChanged); + sent.clear(); + expect(updates.subscribe('phone', 1), isTrue); + await updates.publish(); + expect(sent.single.message['type'], LinkMessageTypes.downloadsChanged); + }, + ); + + test('a slow send coalesces to the newest update in wire order', () async { + await subscribe(); + final gate = Completer(); + deliver = () => gate.future; + items[0] = _item('q0', progress: 0.6); + final first = updates.publish(); + items[0] = _item('q0', progress: 0.7); + updates.publish(); + items[0] = _item('q0', progress: 0.8); + updates.publish(); + expect(sent, hasLength(1)); + deliver = () async => 1; + gate.complete(1); + await first; + expect(sent, hasLength(2)); + expect( + ((sent.last.message['items'] as List).single + as Map)['progress'], + 0.8, + ); + }); + + test('failed sends force a full snapshot on the next update', () async { + await subscribe(); + deliver = () async => 0; + items[0] = _item('q0', progress: 0.6); + await updates.publish(); + sent.clear(); + deliver = () async => 1; + items[0] = _item('q0', progress: 0.7); + await updates.publish(); + expect(sent.single.message['type'], LinkMessageTypes.downloadsChanged); + expect(sent.single.message['items'], hasLength(200)); + }); + + test( + 'a replacement connection cannot inherit an in-flight baseline', + () async { + await subscribe(); + final gate = Completer(); + deliver = () => gate.future; + items[0] = _item('q0', progress: 0.6); + final first = updates.publish(); + updates.keepConnected([ + const LinkClientInfo( + deviceId: 'phone', + name: 'Phone', + platform: 'ios', + connectedMs: 10, + ), + ]); + updates.subscribe('phone', 1); + items[0] = _item('q0', progress: 0.8); + updates.publish(); + deliver = () async => 1; + gate.complete(1); + await first; + expect(sent, hasLength(2)); + expect(sent.last.message['type'], LinkMessageTypes.downloadsChanged); + }, + ); + + test('disposal stops pending peers and coalesced updates', () async { + updates.keepConnected([_phone, _legacy]); + final gate = Completer(); + deliver = () => gate.future; + final pending = updates.publish(); + updates.publish(); + updates.dispose(); + gate.complete(1); + await pending; + expect(sent, hasLength(1)); + await updates.publish(); + expect(sent, hasLength(1)); + }); +} diff --git a/test/link_downloads_test.dart b/test/link_downloads_test.dart index 62b489162..fe90c7515 100644 --- a/test/link_downloads_test.dart +++ b/test/link_downloads_test.dart @@ -77,4 +77,41 @@ void main() { expect(linkParseDownloads(null), isEmpty); expect(linkParseDownloads({'items': 'none'}), isEmpty); }); + + test('delta validation never partially replaces the visible queue', () { + final before = linkParseDownloads({ + 'items': [ + {'id': 'a', 'title': 'A'}, + ], + }); + for (final message in >[ + {'items': [], 'removed': 'a'}, + { + 'items': ['bad'], + 'removed': [], + }, + { + 'items': [], + 'removed': [1], + }, + { + 'items': [], + 'removed': [], + 'order': ['missing'], + }, + { + 'items': [], + 'removed': [], + 'order': ['a', 'a'], + }, + {'items': [], 'removed': [], 'order': []}, + { + 'items': List.filled(201, {'id': 'b'}), + 'removed': [], + }, + ]) { + expect(linkApplyDownloadDelta(before, message), isNull); + expect(before.single.title, 'A'); + } + }); }