mirror of
https://github.com/zarzet/SpotiFLAC-Mobile.git
synced 2026-11-21 20:00:49 +01:00
perf(link): send negotiated download queue deltas
Keep full queue snapshots for older phones and after reconnect, while subscribed phones receive changed rows, removals and bounded ordering. Serialize and coalesce sends so each delta follows a delivered baseline, and reject stale HTTP refreshes after pushes or connection changes. A 200-row progress fixture sends 145 bytes instead of 19,418, with the legacy peer still receiving all 200 rows. Targeted compatibility, race, ordering, failure and lifecycle regressions pass.
This commit is contained in:
1 parent
652cd1736b
commit
3efb32ba2e
9 files changed
+730
-11
No files matched your search
@@ -209,6 +209,7 @@ class LinkDesktopHost extends Notifier<LinkDesktopHostState> {
|
||||
Timer? _stateTimer;
|
||||
Timer? _heartbeat;
|
||||
Timer? _downloadsTimer;
|
||||
LinkDownloadUpdates? _downloadUpdates;
|
||||
Future<void> _transition = Future.value();
|
||||
bool _exporting = false;
|
||||
bool _exportAgain = false;
|
||||
@@ -664,6 +665,11 @@ class LinkDesktopHost extends Notifier<LinkDesktopHostState> {
|
||||
}
|
||||
|
||||
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<LinkDesktopHostState> {
|
||||
}
|
||||
|
||||
void _cancelApp() {
|
||||
_downloadUpdates?.dispose();
|
||||
_downloadUpdates = null;
|
||||
_lyricsTranslations?.dispose();
|
||||
_lyricsTranslations = null;
|
||||
for (final subscription in _appSubscriptions) {
|
||||
@@ -741,6 +749,13 @@ class LinkDesktopHost extends Notifier<LinkDesktopHostState> {
|
||||
}
|
||||
|
||||
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<LinkDesktopHostState> {
|
||||
);
|
||||
_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<LinkDesktopHostState> {
|
||||
_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());
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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<String, dynamic> 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<DownloadItem> Function() items,
|
||||
required Future<int> Function(Map<String, dynamic>, String) send,
|
||||
}) : _items = items,
|
||||
_send = send;
|
||||
|
||||
final List<DownloadItem> Function() _items;
|
||||
final Future<int> Function(Map<String, dynamic>, String) _send;
|
||||
final _peers = <String, _DownloadPeer>{};
|
||||
Future<void>? _sending;
|
||||
bool _pending = false;
|
||||
bool _updatesPending = false;
|
||||
bool _disposed = false;
|
||||
|
||||
void keepConnected(List<LinkClientInfo> 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<void> 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<void> _drain() async {
|
||||
while (_pending && !_disposed) {
|
||||
_pending = false;
|
||||
final updates = _updatesPending;
|
||||
_updatesPending = false;
|
||||
if (_peers.isEmpty) continue;
|
||||
final items = (linkDownloadsPayload(_items())['items'] as List)
|
||||
.cast<Map<String, dynamic>>();
|
||||
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<String, dynamic>? _delta(
|
||||
List<Map<String, dynamic>> before,
|
||||
List<Map<String, dynamic>> 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<Map<String, dynamic>>? items;
|
||||
}
|
||||
|
||||
class AppLinkDownloadsPort implements LinkDownloadsPort {
|
||||
AppLinkDownloadsPort(this._ref);
|
||||
|
||||
|
||||
@@ -85,18 +85,29 @@ class LinkDesktopRemote extends Notifier<LinkRemoteState> {
|
||||
|
||||
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<LinkRemoteState> {
|
||||
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<LinkRemoteState> {
|
||||
Future<void> 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});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -54,6 +54,45 @@ List<LinkDesktopDownload> 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<LinkDesktopDownload>? linkApplyDownloadDelta(
|
||||
List<LinkDesktopDownload> before,
|
||||
Map<String, dynamic> 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 = <LinkDesktopDownload>[];
|
||||
final seen = <String>{};
|
||||
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<String, dynamic> linkDownloadTracksBody(
|
||||
List<Track> tracks, {
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<LinkException>());
|
||||
});
|
||||
|
||||
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': <String>[],
|
||||
'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': <Object?>[],
|
||||
'removed': ['d1'],
|
||||
'order': <String>[],
|
||||
});
|
||||
expect(read().downloads.single.id, 'd1');
|
||||
client.push({
|
||||
'type': LinkMessageTypes.downloadsChanged,
|
||||
'items': [
|
||||
{'id': 'd1', 'title': 'Original'},
|
||||
],
|
||||
});
|
||||
client.push({
|
||||
'type': LinkMessageTypes.downloadsDelta,
|
||||
'items': <Object?>[],
|
||||
'removed': <String>[],
|
||||
'order': ['missing'],
|
||||
});
|
||||
expect(read().downloads.single.title, 'Original');
|
||||
expect(client.sent, hasLength(2));
|
||||
client.push({
|
||||
'type': LinkMessageTypes.downloadsChanged,
|
||||
'items': <Object?>[],
|
||||
});
|
||||
expect(read().downloads, isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test('a late GET cannot replace newer download pushes', () async {
|
||||
final remote = await start();
|
||||
final reply = Completer<Object?>();
|
||||
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': <Object?>[]});
|
||||
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<Object?>();
|
||||
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');
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -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<DownloadItem> items;
|
||||
late LinkDownloadUpdates updates;
|
||||
late List<({String peer, Map<String, dynamic> message})> sent;
|
||||
late Future<int> 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<void> 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<int>();
|
||||
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<String, dynamic>)['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<int>();
|
||||
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<int>();
|
||||
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));
|
||||
});
|
||||
}
|
||||
@@ -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 <Map<String, dynamic>>[
|
||||
{'items': <Object?>[], 'removed': 'a'},
|
||||
{
|
||||
'items': ['bad'],
|
||||
'removed': <String>[],
|
||||
},
|
||||
{
|
||||
'items': <Object?>[],
|
||||
'removed': [1],
|
||||
},
|
||||
{
|
||||
'items': <Object?>[],
|
||||
'removed': <String>[],
|
||||
'order': ['missing'],
|
||||
},
|
||||
{
|
||||
'items': <Object?>[],
|
||||
'removed': <String>[],
|
||||
'order': ['a', 'a'],
|
||||
},
|
||||
{'items': <Object?>[], 'removed': <String>[], 'order': <String>[]},
|
||||
{
|
||||
'items': List.filled(201, {'id': 'b'}),
|
||||
'removed': <String>[],
|
||||
},
|
||||
]) {
|
||||
expect(linkApplyDownloadDelta(before, message), isNull);
|
||||
expect(before.single.title, 'A');
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user