mirror of
https://github.com/zarzet/SpotiFLAC-Mobile.git
synced 2026-11-29 07:34:13 +01:00
perf(backend): migrate selected data jobs to Rust
Route file hashing, AI lyric reply parsing, cache statistics and Autoplay taste training through native workers. Preserve model persistence and isolated compatibility fallbacks, with native parity and full-route performance coverage.
This commit is contained in:
1 parent
6eb4741336
commit
ab7157aa0a
33 files changed
+2862
-62
No files matched your search
@@ -0,0 +1,159 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
import 'package:mornye/services/autoplay_taste.dart';
|
||||
import 'package:mornye/services/backend/ffi_backend_transport.dart';
|
||||
import 'package:mornye/services/backend/rust_ffi_backend.dart';
|
||||
import 'package:mornye/services/cache_maintenance_service.dart';
|
||||
import 'package:mornye/services/platform_bridge.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import '../test/support/autoplay_taste_fixture.dart';
|
||||
import '../test/support/directory_stats_reference.dart';
|
||||
|
||||
Future<Map<String, Object>> _compare<T>(
|
||||
Future<T> Function() baseline,
|
||||
Future<T> Function() native,
|
||||
void Function(T expected, T actual) verify,
|
||||
) async {
|
||||
final expected = await baseline();
|
||||
verify(expected, await native());
|
||||
final samples = <Map<String, Object>>[];
|
||||
for (var pair = 0; pair < 3; pair++) {
|
||||
for (final useNative in pair.isEven ? [false, true] : [true, false]) {
|
||||
final clock = Stopwatch()..start();
|
||||
var lastTick = 0;
|
||||
var maxGap = 0;
|
||||
final heartbeat = Timer.periodic(const Duration(milliseconds: 10), (_) {
|
||||
final now = clock.elapsedMicroseconds;
|
||||
final gap = now - lastTick;
|
||||
if (gap > maxGap) maxGap = gap;
|
||||
lastTick = now;
|
||||
});
|
||||
late T result;
|
||||
try {
|
||||
result = await (useNative ? native() : baseline());
|
||||
} finally {
|
||||
clock.stop();
|
||||
heartbeat.cancel();
|
||||
}
|
||||
final tail = clock.elapsedMicroseconds - lastTick;
|
||||
if (tail > maxGap) maxGap = tail;
|
||||
verify(expected, result);
|
||||
samples.add({
|
||||
'pair': pair,
|
||||
'route': useNative ? 'native' : 'dart',
|
||||
'elapsed_ms': clock.elapsedMicroseconds / 1000,
|
||||
'heartbeat_max_gap_ms': maxGap / 1000,
|
||||
});
|
||||
}
|
||||
}
|
||||
return {'samples': samples, 'parity': true};
|
||||
}
|
||||
|
||||
void _sameTaste(AutoplayTasteModel expected, AutoplayTasteModel actual) {
|
||||
expect(actual.tokens, expected.tokens);
|
||||
expect(actual.positives, expected.positives);
|
||||
expect(actual.through, expected.through);
|
||||
expect(actual.vectors.length, expected.vectors.length);
|
||||
var maxError = 0.0;
|
||||
for (var index = 0; index < actual.vectors.length; index++) {
|
||||
final error = (actual.vectors[index] - expected.vectors[index]).abs();
|
||||
if (error > maxError) maxError = error;
|
||||
}
|
||||
expect(maxError, lessThanOrEqualTo(1e-6));
|
||||
}
|
||||
|
||||
void main() {
|
||||
final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
Directory? desktopSupport;
|
||||
setUpAll(() async {
|
||||
if (Platform.isMacOS || Platform.isWindows || Platform.isLinux) {
|
||||
final root = await Directory.systemTemp.createTemp('backend-profile-');
|
||||
desktopSupport = root;
|
||||
RustFfiBackend.debugShared = RustFfiBackend(
|
||||
openTransport: FfiBackendTransport.open,
|
||||
loadConfig: () async => DesktopBackendConfig(
|
||||
appSupportDir: root.path,
|
||||
documentsDir: root.path,
|
||||
tempDir: root.path,
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
tearDownAll(() async {
|
||||
if (desktopSupport != null) {
|
||||
RustFfiBackend.debugShared = null;
|
||||
await desktopSupport!.delete(recursive: true);
|
||||
}
|
||||
});
|
||||
final results = <String, Object>{
|
||||
'platform': Platform.operatingSystem,
|
||||
'profile': kProfileMode,
|
||||
'measurement':
|
||||
'Full worker route, including DTO, bridge and hydration; '
|
||||
'one warmup then three alternating pairs. Fixtures excluded.',
|
||||
};
|
||||
binding.reportData = {'native_backend_followup': results};
|
||||
|
||||
testWidgets('directory statistics native parity and full-route timings', (
|
||||
tester,
|
||||
) async {
|
||||
final temporary = await getTemporaryDirectory();
|
||||
await temporary.create(recursive: true);
|
||||
final root = await temporary.createTemp('stats-');
|
||||
try {
|
||||
final missing = await PlatformBridge.runNativeDataJob({
|
||||
'operation': 'directory_stats',
|
||||
'path': '${root.path}/missing',
|
||||
'follow_links': false,
|
||||
});
|
||||
expect(missing, {'file_count': 0, 'total_size_bytes': 0});
|
||||
for (final count in [100, 5000]) {
|
||||
final directory = Directory('${root.path}/$count');
|
||||
await createDirectoryStatsFixture(directory, count);
|
||||
for (final follow in [false, true]) {
|
||||
results['stats_${count}_follow_$follow'] = await _compare(
|
||||
() => scanDirectoryReference(directory, followLinks: follow),
|
||||
() => CacheMaintenanceService.scanDirectory(
|
||||
directory,
|
||||
followLinks: follow,
|
||||
),
|
||||
(expected, actual) {
|
||||
expect(actual.fileCount, expected.fileCount);
|
||||
expect(actual.totalSizeBytes, expected.totalSizeBytes);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await root.delete(recursive: true);
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets('native taste training preserves model across full routes', (
|
||||
tester,
|
||||
) async {
|
||||
final empty = await PlatformBridge.runNativeDataJob({
|
||||
'operation': 'train_autoplay_taste',
|
||||
'plays': <Object?>[],
|
||||
});
|
||||
expect(empty['tokens'], isEmpty);
|
||||
final edge = autoplayTasteEdgeFixture();
|
||||
_sameTaste(
|
||||
await trainAutoplayTasteDartInBackground(edge),
|
||||
await trainAutoplayTasteInBackground(edge),
|
||||
);
|
||||
for (final count in [500, 5000]) {
|
||||
final plays = autoplayTasteFixture(count);
|
||||
results['taste_$count'] = await _compare(
|
||||
() => trainAutoplayTasteDartInBackground(plays),
|
||||
() => trainAutoplayTasteInBackground(plays),
|
||||
_sameTaste,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
import 'package:mornye/services/lyrics_ai_client.dart';
|
||||
import 'package:mornye/services/native_file_hash.dart';
|
||||
import 'package:mornye/services/platform_bridge.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
void main() {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
testWidgets('translation reply reaches the real native worker', (
|
||||
tester,
|
||||
) async {
|
||||
const reply =
|
||||
'<think>reasoning</think>```json\n'
|
||||
'{"lines":[{"id":1,"text":"Hello world",'
|
||||
'"alignment":[[0,"Hello "],[1,"world"]],'
|
||||
'"romanization":"Konnichiwa"},'
|
||||
'{"id":2,"text":"Second","alignment":[[512,"Second"]]}]}\n```';
|
||||
// Prove this installed binary has the new operation before testing the
|
||||
// application adapter, which supports hosts without a native plugin.
|
||||
final native = await PlatformBridge.runNativeDataJob({
|
||||
'operation': 'parse_lyrics_translation_reply',
|
||||
'ids': [1, 2],
|
||||
}, bytes: utf8.encode(reply));
|
||||
expect(native['lines'], hasLength(2));
|
||||
final parsed = await parseLyricsTranslationReplyInBackground(reply, {1, 2});
|
||||
expect(parsed[1]!.text, 'Hello world');
|
||||
expect(parsed[1]!.romanization, 'Konnichiwa');
|
||||
expect(parsed[1]!.alignment.map((chunk) => chunk.source), [0, 1]);
|
||||
expect(parsed[2]!.text, 'Second');
|
||||
expect(parsed[2]!.alignment, isEmpty);
|
||||
await expectLater(
|
||||
parseLyricsTranslationReplyInBackground('invalid response', {1}),
|
||||
throwsA(isA<LyricsAiException>()),
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('file hashing reaches the native worker', (tester) async {
|
||||
final root = await (await getTemporaryDirectory()).createTemp(
|
||||
'native-hash-',
|
||||
);
|
||||
try {
|
||||
final bytes = List<int>.generate(200000, (index) => index % 251);
|
||||
final file = await File('${root.path}/input.bin').writeAsBytes(bytes);
|
||||
final native = await PlatformBridge.runNativeDataJob({
|
||||
'operation': 'hash_file',
|
||||
'path': file.path,
|
||||
});
|
||||
expect(native['sha256'], sha256.convert(bytes).toString());
|
||||
expect(await hashFileSha256(file.path), native['sha256']);
|
||||
} finally {
|
||||
await root.delete(recursive: true);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,22 +1,16 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:open_filex/open_filex.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:mornye/services/platform_bridge.dart';
|
||||
import 'package:mornye/services/native_file_hash.dart';
|
||||
import 'package:mornye/utils/logger.dart';
|
||||
|
||||
final _log = AppLogger('ApkDownloader');
|
||||
|
||||
typedef ProgressCallback = void Function(int received, int total);
|
||||
|
||||
Future<String> _hashApkInBackground(String path) async =>
|
||||
(await sha256.bind(File(path).openRead()).first).toString();
|
||||
|
||||
class ApkDownloader {
|
||||
static const _streamIdleTimeout = Duration(seconds: 60);
|
||||
static const _progressInterval = Duration(milliseconds: 500);
|
||||
@@ -171,21 +165,7 @@ class ApkDownloader {
|
||||
}
|
||||
}
|
||||
|
||||
static Future<String> _hashApk(File file) async {
|
||||
try {
|
||||
final result = await PlatformBridge.runNativeDataJob({
|
||||
'operation': 'hash_file',
|
||||
'path': file.path,
|
||||
});
|
||||
final digest = result['sha256'];
|
||||
if (digest is! String || !RegExp(r'^[a-f0-9]{64}$').hasMatch(digest)) {
|
||||
throw const FormatException('Invalid native APK digest');
|
||||
}
|
||||
return digest;
|
||||
} on MissingPluginException {
|
||||
return compute(_hashApkInBackground, file.path);
|
||||
}
|
||||
}
|
||||
static Future<String> _hashApk(File file) => hashFileSha256(file.path);
|
||||
|
||||
static Future<Map<String, dynamic>?> _readResumeMetadata(File file) async {
|
||||
try {
|
||||
|
||||
@@ -3,9 +3,11 @@ import 'dart:math';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter/foundation.dart' show compute, visibleForTesting;
|
||||
import 'package:flutter/services.dart' show MissingPluginException;
|
||||
import 'package:mornye/services/autoplay_personalization.dart';
|
||||
import 'package:mornye/services/autoplay_signal.dart';
|
||||
import 'package:mornye/services/playable_media.dart';
|
||||
import 'package:mornye/services/platform_bridge.dart';
|
||||
import 'package:mornye/services/sqlite_helpers.dart' as sqlite;
|
||||
import 'package:mornye/utils/logger.dart';
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
@@ -222,6 +224,67 @@ _PackedTaste _packTaste(AutoplayTasteModel model) {
|
||||
_PackedTaste _trainPackedTaste(List<AutoplayTastePlay> plays) =>
|
||||
_packTaste(trainAutoplayTaste(plays));
|
||||
|
||||
Map<String, dynamic> _tasteTrainingRequest(List<AutoplayTastePlay> plays) => {
|
||||
'operation': 'train_autoplay_taste',
|
||||
'plays': [
|
||||
for (final play in plays)
|
||||
{
|
||||
'id': play.id,
|
||||
'song': play.song,
|
||||
'artist': play.artist,
|
||||
'atMicros': play.at.microsecondsSinceEpoch,
|
||||
'kind': play.kind.name,
|
||||
'reward': play.reward,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
_PackedTaste _hydrateNativeTaste(Map<String, dynamic> result) {
|
||||
final tokens = (result['tokens'] as List).cast<String>();
|
||||
final values = (result['vectors'] as List).cast<num>();
|
||||
if (tokens.length > _vocabulary ||
|
||||
values.length != tokens.length * AutoplayTasteModel.dimensions ||
|
||||
values.any((value) => !value.isFinite || value.abs() > 1.001)) {
|
||||
throw const FormatException('Invalid native autoplay taste model');
|
||||
}
|
||||
return _packTaste(
|
||||
AutoplayTasteModel(
|
||||
tokens: tokens,
|
||||
vectors: Float32List.fromList([
|
||||
for (final value in values) value.toDouble(),
|
||||
]),
|
||||
positives: result['positives'] as int,
|
||||
through: result['through'] as int,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<_PackedTaste> _trainNativePackedTaste(
|
||||
List<AutoplayTastePlay> plays,
|
||||
) async {
|
||||
try {
|
||||
final request = await compute(_tasteTrainingRequest, plays);
|
||||
final result = await PlatformBridge.runNativeDataJob(request);
|
||||
return await compute(_hydrateNativeTaste, result);
|
||||
} on MissingPluginException {
|
||||
return compute(_trainPackedTaste, plays, debugLabel: 'autoplay-taste');
|
||||
}
|
||||
}
|
||||
|
||||
/// Trains one snapshot on the native worker; persistence stays with Dart.
|
||||
Future<AutoplayTasteModel> trainAutoplayTasteInBackground(
|
||||
List<AutoplayTastePlay> plays,
|
||||
) async => (await _trainNativePackedTaste(plays)).model;
|
||||
|
||||
@visibleForTesting
|
||||
Future<AutoplayTasteModel> trainAutoplayTasteDartInBackground(
|
||||
List<AutoplayTastePlay> plays,
|
||||
) async => (await compute(
|
||||
_trainPackedTaste,
|
||||
plays,
|
||||
debugLabel: 'autoplay-taste',
|
||||
)).model;
|
||||
|
||||
class _Position {
|
||||
_Position(this.song, this.artist, this.weight);
|
||||
final String song, artist;
|
||||
@@ -619,7 +682,7 @@ class AutoplayTaste {
|
||||
);
|
||||
|
||||
static Future<_PackedTaste> _trainOnWorker(List<AutoplayTastePlay> plays) =>
|
||||
compute(_trainPackedTaste, plays, debugLabel: 'autoplay-taste');
|
||||
_trainNativePackedTaste(plays);
|
||||
|
||||
/// The model autoplay uses now, if any.
|
||||
@visibleForTesting
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import 'dart:io';
|
||||
import 'dart:isolate';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:mornye/services/platform_bridge.dart';
|
||||
|
||||
class DirectoryStats {
|
||||
final int fileCount;
|
||||
@@ -9,7 +13,37 @@ class DirectoryStats {
|
||||
|
||||
/// Directory sizing and clearing for the cache management page.
|
||||
abstract final class CacheMaintenanceService {
|
||||
static Future<DirectoryStats> scanDirectory(Directory directory) async {
|
||||
static Future<DirectoryStats> scanDirectory(
|
||||
Directory directory, {
|
||||
bool followLinks = false,
|
||||
}) async {
|
||||
final path = directory.absolute.path;
|
||||
final Map<String, dynamic> result;
|
||||
try {
|
||||
result = await PlatformBridge.runNativeDataJob({
|
||||
'operation': 'directory_stats',
|
||||
'path': path,
|
||||
'follow_links': followLinks,
|
||||
});
|
||||
} on MissingPluginException {
|
||||
return Isolate.run(() => _scanDirectoryFallback(path, followLinks));
|
||||
}
|
||||
final fileCount = result['file_count'];
|
||||
final totalSize = result['total_size_bytes'];
|
||||
if (fileCount is! int ||
|
||||
fileCount < 0 ||
|
||||
totalSize is! int ||
|
||||
totalSize < 0) {
|
||||
throw StateError('Invalid native directory statistics');
|
||||
}
|
||||
return DirectoryStats(fileCount: fileCount, totalSizeBytes: totalSize);
|
||||
}
|
||||
|
||||
static Future<DirectoryStats> _scanDirectoryFallback(
|
||||
String path,
|
||||
bool followLinks,
|
||||
) async {
|
||||
final directory = Directory(path);
|
||||
if (!await directory.exists()) {
|
||||
return const DirectoryStats(fileCount: 0, totalSizeBytes: 0);
|
||||
}
|
||||
@@ -20,7 +54,7 @@ abstract final class CacheMaintenanceService {
|
||||
try {
|
||||
await for (final entity in directory.list(
|
||||
recursive: true,
|
||||
followLinks: false,
|
||||
followLinks: followLinks,
|
||||
)) {
|
||||
if (entity is File) {
|
||||
fileCount++;
|
||||
|
||||
@@ -7,6 +7,7 @@ import 'package:flutter_cache_manager/file.dart' as cache_file;
|
||||
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:mornye/services/cache_maintenance_service.dart';
|
||||
import 'package:mornye/services/cover_cache_info_repository.dart';
|
||||
import 'package:mornye/utils/cache_byte_budget.dart';
|
||||
import 'package:mornye/utils/periodic_async_task.dart';
|
||||
@@ -199,27 +200,14 @@ class CoverCacheManager {
|
||||
return const CacheStats(fileCount: 0, totalSizeBytes: 0);
|
||||
}
|
||||
|
||||
final cacheDir = Directory(cachePath);
|
||||
|
||||
if (!await cacheDir.exists()) {
|
||||
return const CacheStats(fileCount: 0, totalSizeBytes: 0);
|
||||
}
|
||||
|
||||
int fileCount = 0;
|
||||
int totalSize = 0;
|
||||
|
||||
try {
|
||||
await for (final entity in cacheDir.list(recursive: true)) {
|
||||
if (entity is File) {
|
||||
fileCount++;
|
||||
totalSize += await entity.length();
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('CoverCacheManager: Error getting stats: $e');
|
||||
}
|
||||
|
||||
return CacheStats(fileCount: fileCount, totalSizeBytes: totalSize);
|
||||
final stats = await CacheMaintenanceService.scanDirectory(
|
||||
Directory(cachePath),
|
||||
followLinks: true,
|
||||
);
|
||||
return CacheStats(
|
||||
fileCount: stats.fileCount,
|
||||
totalSizeBytes: stats.totalSizeBytes,
|
||||
);
|
||||
}
|
||||
|
||||
static CacheManager _createManager() {
|
||||
|
||||
@@ -7,6 +7,7 @@ import 'dart:isolate';
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:mornye/services/native_file_hash.dart';
|
||||
import 'package:mornye/services/network_storage_service.dart';
|
||||
import 'package:mornye/utils/cover_art_utils.dart';
|
||||
import 'package:mornye/utils/file_access.dart';
|
||||
@@ -417,8 +418,7 @@ class CoverStore {
|
||||
}
|
||||
final head = await file.openRead(0, 12).expand((chunk) => chunk).toList();
|
||||
if (!_isImage(head)) throw const FormatException('Not a cover image');
|
||||
final digest = await sha256.bind(file.openRead()).single;
|
||||
return digest.toString().substring(0, 16);
|
||||
return (await hashFileSha256(file.path)).substring(0, 16);
|
||||
}
|
||||
|
||||
/// Whether [head], the first 12 bytes of a file, starts a JPEG, PNG, GIF,
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:isolate';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:mornye/services/native_file_hash.dart';
|
||||
import 'package:mornye/services/update_checker.dart';
|
||||
import 'package:mornye/utils/logger.dart';
|
||||
|
||||
@@ -19,9 +18,6 @@ class DesktopUpdateException implements Exception {
|
||||
String toString() => 'DesktopUpdateException: $message';
|
||||
}
|
||||
|
||||
Future<String> _hashFile(String path) async =>
|
||||
(await sha256.bind(File(path).openRead()).first).toString();
|
||||
|
||||
/// Downloads a desktop release package, checks it against the release's
|
||||
/// SHA256SUMS.txt (and GitHub's digest when present), and applies it the way
|
||||
/// the running build was installed (see [UpdateInstallKind]).
|
||||
@@ -138,8 +134,7 @@ class DesktopUpdater {
|
||||
throw DesktopUpdateException('Incomplete download: $received/$total');
|
||||
}
|
||||
|
||||
final partPath = partFile.path;
|
||||
final actual = await Isolate.run(() => _hashFile(partPath));
|
||||
final actual = await hashFileSha256(partFile.path);
|
||||
if (actual != expected) {
|
||||
throw const DesktopUpdateException('SHA-256 verification failed');
|
||||
}
|
||||
|
||||
@@ -3,10 +3,10 @@ import 'dart:collection';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:mornye/services/native_file_hash.dart';
|
||||
import 'package:mornye/services/platform_bridge.dart';
|
||||
import 'package:mornye/utils/file_access.dart';
|
||||
|
||||
@@ -788,8 +788,7 @@ class DownloadedEmbeddedCoverResolver {
|
||||
}
|
||||
|
||||
static Future<String> _contentHash(String path) async {
|
||||
final digest = await sha256.bind(File(path).openRead()).first;
|
||||
return digest.toString().substring(0, 16);
|
||||
return (await hashFileSha256(path)).substring(0, 16);
|
||||
}
|
||||
|
||||
/// Two independently mixed 63-bit FNV-1a lanes keep filenames compact.
|
||||
|
||||
@@ -2,8 +2,11 @@ import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:mornye/services/lyrics_translation_alignment.dart';
|
||||
import 'package:mornye/services/platform_bridge.dart';
|
||||
|
||||
/// The services AI lyrics translation can call with the user's own key.
|
||||
enum LyricsAiProvider {
|
||||
@@ -504,6 +507,78 @@ String extractLyricsAiText(LyricsAiProvider provider, Map<String, Object?> j) {
|
||||
|
||||
final _fence = RegExp(r'^```[a-zA-Z0-9_-]*\s*\n?([\s\S]*?)\n?```\s*$');
|
||||
|
||||
Map<int, LyricsAiLine> _parseLyricsTranslationReplyOnWorker(
|
||||
({String reply, Set<int> ids}) input,
|
||||
) => parseLyricsTranslationReply(input.reply, input.ids);
|
||||
|
||||
/// Parses model output on the native worker. Hosts without a native plugin keep
|
||||
/// the compatibility parser in an isolate rather than the Flutter frame.
|
||||
Future<Map<int, LyricsAiLine>> parseLyricsTranslationReplyInBackground(
|
||||
String reply,
|
||||
Set<int> ids,
|
||||
) async {
|
||||
final Map<String, dynamic> result;
|
||||
try {
|
||||
result = await PlatformBridge.runNativeDataJob({
|
||||
'operation': 'parse_lyrics_translation_reply',
|
||||
'ids': ids.toList(growable: false),
|
||||
}, bytes: utf8.encode(reply));
|
||||
} on MissingPluginException {
|
||||
return compute(_parseLyricsTranslationReplyOnWorker, (
|
||||
reply: reply,
|
||||
ids: ids,
|
||||
));
|
||||
}
|
||||
if (result['error'] == 'badResponse') {
|
||||
throw const LyricsAiException(
|
||||
LyricsAiErrorKind.badResponse,
|
||||
detail: 'reply is not a JSON list',
|
||||
);
|
||||
}
|
||||
final lines = result['lines'];
|
||||
if (lines is! List) {
|
||||
throw const LyricsAiException(LyricsAiErrorKind.badResponse);
|
||||
}
|
||||
final parsed = <int, LyricsAiLine>{};
|
||||
for (final value in lines) {
|
||||
if (value is! Map ||
|
||||
value['id'] is! int ||
|
||||
value['text'] is! String ||
|
||||
(value['romanization'] != null && value['romanization'] is! String)) {
|
||||
throw const LyricsAiException(LyricsAiErrorKind.badResponse);
|
||||
}
|
||||
final id = value['id'] as int;
|
||||
if (!ids.contains(id) || parsed.containsKey(id)) {
|
||||
throw const LyricsAiException(LyricsAiErrorKind.badResponse);
|
||||
}
|
||||
parsed[id] = (
|
||||
text: value['text'] as String,
|
||||
romanization: value['romanization'] as String?,
|
||||
alignment: _lyricsTranslationChunksFromNative(value['alignment']),
|
||||
romanizationAlignment: _lyricsTranslationChunksFromNative(
|
||||
value['romanizationAlignment'],
|
||||
),
|
||||
);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
List<LyricsTranslationChunk> _lyricsTranslationChunksFromNative(Object? value) {
|
||||
if (value is! List) {
|
||||
throw const LyricsAiException(LyricsAiErrorKind.badResponse);
|
||||
}
|
||||
final chunks = <LyricsTranslationChunk>[];
|
||||
for (final chunk in value) {
|
||||
if (chunk is! Map || chunk['text'] is! String || chunk['source'] is! int) {
|
||||
throw const LyricsAiException(LyricsAiErrorKind.badResponse);
|
||||
}
|
||||
chunks.add(
|
||||
LyricsTranslationChunk(chunk['text'] as String, chunk['source'] as int),
|
||||
);
|
||||
}
|
||||
return List.unmodifiable(chunks);
|
||||
}
|
||||
|
||||
/// Reads `{id: line}` from a model reply. Accepts the requested
|
||||
/// `{"lines": [...]}` object, a bare array, code fences and leading prose.
|
||||
/// Unknown ids, duplicates and blank texts are dropped; a reply that is
|
||||
@@ -687,7 +762,7 @@ class LyricsAiClient {
|
||||
if (text.trim().isEmpty) {
|
||||
throw const LyricsAiException(LyricsAiErrorKind.badResponse);
|
||||
}
|
||||
return parseLyricsTranslationReply(text, ids);
|
||||
return parseLyricsTranslationReplyInBackground(text, ids);
|
||||
}
|
||||
|
||||
Future<String> _sendTranslation(
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:mornye/services/platform_bridge.dart';
|
||||
|
||||
final _sha256Pattern = RegExp(r'^[a-f0-9]{64}$');
|
||||
|
||||
Future<String> _hashFileInBackground(String path) async =>
|
||||
(await sha256.bind(File(path).openRead()).first).toString();
|
||||
|
||||
/// Streams a file through the native worker without loading it into Dart.
|
||||
/// Unsupported hosts retain a streaming isolate implementation.
|
||||
Future<String> hashFileSha256(String path) async {
|
||||
try {
|
||||
final result = await PlatformBridge.runNativeDataJob({
|
||||
'operation': 'hash_file',
|
||||
'path': path,
|
||||
});
|
||||
final digest = result['sha256'];
|
||||
if (digest is! String || !_sha256Pattern.hasMatch(digest)) {
|
||||
throw const FormatException('Invalid native file digest');
|
||||
}
|
||||
return digest;
|
||||
} on MissingPluginException {
|
||||
return compute(_hashFileInBackground, path);
|
||||
}
|
||||
}
|
||||
@@ -60,6 +60,8 @@ fn execute(
|
||||
let operation = string(request, "operation")?;
|
||||
match operation {
|
||||
"hash_file" => Ok(json!({"sha256": hash_file(string(request, "path")?, check)?})),
|
||||
"directory_stats" => crate::native_directory_stats::execute(request, check),
|
||||
"train_autoplay_taste" => crate::native_autoplay_taste::execute(request, check),
|
||||
"matches_network_upload" => crate::network_tags::matches_upload(request, check),
|
||||
"network_metadata" => {
|
||||
let metadata = crate::network_tags::read_to_cache(
|
||||
@@ -87,6 +89,9 @@ fn execute(
|
||||
crate::native_id3::execute(request, Some(bytes), check)
|
||||
}
|
||||
"parse_lyrics" => crate::native_lyrics::execute(request, Some(bytes), check),
|
||||
"parse_lyrics_translation_reply" => {
|
||||
crate::native_lyrics_translation::execute(request, Some(bytes), check)
|
||||
}
|
||||
"palette" => {
|
||||
let colors = mornye_core::native_palette::quantize_rgba(bytes, check)?;
|
||||
Ok(json!({"colors": colors}))
|
||||
|
||||
@@ -16,13 +16,16 @@ mod logging;
|
||||
mod lyrics;
|
||||
mod manager;
|
||||
mod metadata;
|
||||
mod native_autoplay_taste;
|
||||
mod native_backup;
|
||||
mod native_cache;
|
||||
mod native_collections;
|
||||
mod native_directory_stats;
|
||||
mod native_id3;
|
||||
mod native_library;
|
||||
mod native_listing;
|
||||
mod native_lyrics;
|
||||
mod native_lyrics_translation;
|
||||
mod native_playlist_write;
|
||||
mod native_playlists;
|
||||
mod native_recognition;
|
||||
|
||||
@@ -0,0 +1,476 @@
|
||||
//! Deterministic session skip-gram training, leaving persistence to Flutter.
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::HashMap;
|
||||
|
||||
const DIMENSIONS: usize = 16;
|
||||
const WINDOW: usize = 3;
|
||||
const VOCABULARY: usize = 3000;
|
||||
const RATE: f64 = 0.025;
|
||||
|
||||
/// Matches the pinned Dart VM's seeded multiply-with-carry generator.
|
||||
pub(crate) struct DartRandom(u64);
|
||||
|
||||
impl DartRandom {
|
||||
pub(crate) fn new(mut seed: u64) -> Self {
|
||||
seed = (!seed).wrapping_add(seed << 21);
|
||||
seed ^= seed >> 24;
|
||||
seed = seed.wrapping_mul(265);
|
||||
seed ^= seed >> 14;
|
||||
seed = seed.wrapping_mul(21);
|
||||
seed ^= seed >> 28;
|
||||
seed = seed.wrapping_add(seed << 31);
|
||||
let mut random = Self(if seed == 0 { 0x5a17 } else { seed });
|
||||
for _ in 0..4 {
|
||||
random.next_state();
|
||||
}
|
||||
random
|
||||
}
|
||||
|
||||
fn next_state(&mut self) {
|
||||
self.0 = 0xffffda61_u64.wrapping_mul(self.0 & 0xffffffff) + (self.0 >> 32);
|
||||
}
|
||||
|
||||
pub(crate) fn next_int(&mut self, max: u64) -> u64 {
|
||||
assert!(max > 0 && max <= 1 << 32);
|
||||
loop {
|
||||
self.next_state();
|
||||
let random = self.0 & 0xffffffff;
|
||||
if max.is_power_of_two() {
|
||||
return random & (max - 1);
|
||||
}
|
||||
let result = random % max;
|
||||
if random - result + max <= 1 << 32 {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn next_double(&mut self) -> f64 {
|
||||
(self.next_int(1 << 26) as f64 * (1_u64 << 27) as f64 + self.next_int(1 << 27) as f64)
|
||||
/ (1_u64 << 53) as f64
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Play {
|
||||
id: i64,
|
||||
song: String,
|
||||
artist: String,
|
||||
at_micros: i64,
|
||||
kind: Kind,
|
||||
reward: f64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum Kind {
|
||||
Listened,
|
||||
Replayed,
|
||||
Loved,
|
||||
Playlisted,
|
||||
Skipped,
|
||||
}
|
||||
|
||||
struct Position<'a> {
|
||||
song: &'a str,
|
||||
artist: &'a str,
|
||||
weight: f64,
|
||||
}
|
||||
|
||||
struct Slot {
|
||||
song: i32,
|
||||
artist: i32,
|
||||
weight: f64,
|
||||
}
|
||||
|
||||
struct Skip {
|
||||
song: i32,
|
||||
at: usize,
|
||||
weight: f64,
|
||||
}
|
||||
|
||||
struct Session {
|
||||
plays: Vec<Slot>,
|
||||
skips: Vec<Skip>,
|
||||
}
|
||||
|
||||
pub(crate) fn execute(
|
||||
request: &Value,
|
||||
check: &dyn Fn() -> Result<(), String>,
|
||||
) -> Result<Value, String> {
|
||||
check()?;
|
||||
let plays: Vec<Play> = serde_json::from_value(request["plays"].clone())
|
||||
.map_err(|error| format!("Invalid autoplay taste history: {error}"))?;
|
||||
if plays.len() > 5000 || plays.iter().any(|play| !play.reward.is_finite()) {
|
||||
return Err("Invalid autoplay taste history bounds".into());
|
||||
}
|
||||
let mut sessions = Vec::<Vec<Position<'_>>>::new();
|
||||
let mut endorsed = HashMap::<&str, f64>::new();
|
||||
let mut latest: Option<i64> = None;
|
||||
let mut positives = 0;
|
||||
let mut through = 0;
|
||||
for play in &plays {
|
||||
check()?;
|
||||
if latest.is_none_or(|latest| play.at_micros as i128 - latest as i128 > 1_800_000_000) {
|
||||
finish_session(sessions.last_mut(), &endorsed);
|
||||
endorsed.clear();
|
||||
sessions.push(Vec::new());
|
||||
latest = Some(play.at_micros);
|
||||
}
|
||||
latest = Some(latest.unwrap().max(play.at_micros));
|
||||
through = through.max(play.id);
|
||||
let strength = match play.kind {
|
||||
Kind::Listened => play.reward,
|
||||
Kind::Replayed | Kind::Playlisted => 1.5,
|
||||
Kind::Loved => 2.0,
|
||||
Kind::Skipped => -(1.0 - 2.0 * play.reward).clamp(0.0, 1.0),
|
||||
};
|
||||
if matches!(play.kind, Kind::Loved | Kind::Playlisted) {
|
||||
let value = endorsed.entry(&play.song).or_default();
|
||||
*value = value.max(strength);
|
||||
continue;
|
||||
}
|
||||
if strength > 0.0 {
|
||||
positives += 1;
|
||||
}
|
||||
if strength == 0.0 {
|
||||
continue;
|
||||
}
|
||||
let positions = sessions.last_mut().unwrap();
|
||||
if let Some(last) = positions.last_mut()
|
||||
&& last.song == play.song
|
||||
{
|
||||
last.weight = last.weight.max(strength);
|
||||
} else {
|
||||
positions.push(Position {
|
||||
song: &play.song,
|
||||
artist: &play.artist,
|
||||
weight: strength,
|
||||
});
|
||||
}
|
||||
}
|
||||
finish_session(sessions.last_mut(), &endorsed);
|
||||
let mut counts = HashMap::<String, usize>::new();
|
||||
for session in &sessions {
|
||||
check()?;
|
||||
for position in session {
|
||||
if position.weight <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
*counts.entry(format!("song:{}", position.song)).or_default() += 1;
|
||||
if !position.artist.is_empty() {
|
||||
*counts
|
||||
.entry(format!("artist:{}", position.artist))
|
||||
.or_default() += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut tokens: Vec<_> = counts
|
||||
.iter()
|
||||
.filter(|(_, count)| **count >= 2)
|
||||
.map(|(token, _)| token.clone())
|
||||
.collect();
|
||||
tokens.sort_by(|a, b| {
|
||||
counts[b]
|
||||
.cmp(&counts[a])
|
||||
.then_with(|| a.encode_utf16().cmp(b.encode_utf16()))
|
||||
});
|
||||
tokens.truncate(VOCABULARY);
|
||||
let ids: HashMap<_, _> = tokens
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(id, token)| (token.as_str(), id as i32))
|
||||
.collect();
|
||||
let mut encoded = Vec::new();
|
||||
let mut slots = 0;
|
||||
for session in sessions {
|
||||
check()?;
|
||||
let mut kept = Vec::new();
|
||||
let mut skips = Vec::new();
|
||||
for position in session {
|
||||
let song = *ids
|
||||
.get(format!("song:{}", position.song).as_str())
|
||||
.unwrap_or(&-1);
|
||||
if position.weight < 0.0 {
|
||||
if song >= 0 {
|
||||
skips.push(Skip {
|
||||
song,
|
||||
at: kept.len(),
|
||||
weight: -position.weight,
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let artist = if position.artist.is_empty() {
|
||||
-1
|
||||
} else {
|
||||
*ids.get(format!("artist:{}", position.artist).as_str())
|
||||
.unwrap_or(&-1)
|
||||
};
|
||||
if song >= 0 || artist >= 0 {
|
||||
kept.push(Slot {
|
||||
song,
|
||||
artist,
|
||||
weight: position.weight,
|
||||
});
|
||||
}
|
||||
}
|
||||
if kept.len() > 1 || (kept.len() == 1 && !skips.is_empty()) {
|
||||
slots += kept.len();
|
||||
encoded.push(Session { plays: kept, skips });
|
||||
}
|
||||
}
|
||||
let mut random = DartRandom::new(0x7a57e);
|
||||
let input = (0..tokens.len() * DIMENSIONS)
|
||||
.map(|_| (random.next_double() - 0.5) / DIMENSIONS as f64)
|
||||
.collect();
|
||||
let mut total = 0.0;
|
||||
let cumulative = tokens
|
||||
.iter()
|
||||
.map(|token| {
|
||||
total += (counts[token] as f64).powf(0.75);
|
||||
total
|
||||
})
|
||||
.collect();
|
||||
let mut model = Trainer {
|
||||
input,
|
||||
output: vec![0.0; tokens.len() * DIMENSIONS],
|
||||
error: [0.0; DIMENSIONS],
|
||||
random,
|
||||
cumulative,
|
||||
total,
|
||||
};
|
||||
let epochs = if slots == 0 {
|
||||
0
|
||||
} else {
|
||||
40000_usize.div_ceil(slots).clamp(5, 40)
|
||||
};
|
||||
let steps = (epochs * slots).max(1);
|
||||
let mut step = 0;
|
||||
for _ in 0..epochs {
|
||||
check()?;
|
||||
for session in &encoded {
|
||||
check()?;
|
||||
let kept = &session.plays;
|
||||
let mut alpha = RATE;
|
||||
for (i, here) in kept.iter().enumerate() {
|
||||
if i % 32 == 0 {
|
||||
check()?;
|
||||
}
|
||||
alpha = RATE * (1.0 - step as f64 / steps as f64).max(0.0001);
|
||||
step += 1;
|
||||
model.together(here.song, here.artist, alpha * here.weight);
|
||||
model.together(here.artist, here.song, alpha * here.weight);
|
||||
for (j, there) in kept
|
||||
.iter()
|
||||
.enumerate()
|
||||
.take((i + WINDOW + 1).min(kept.len()))
|
||||
.skip(i.saturating_sub(WINDOW))
|
||||
{
|
||||
if j == i {
|
||||
continue;
|
||||
}
|
||||
let rate = alpha
|
||||
* (here.weight * there.weight).sqrt()
|
||||
* (WINDOW + 1 - i.abs_diff(j)) as f64
|
||||
/ WINDOW as f64;
|
||||
model.together(here.song, there.song, rate);
|
||||
model.together(here.song, there.artist, rate);
|
||||
model.together(here.artist, there.song, rate);
|
||||
model.together(here.artist, there.artist, rate);
|
||||
}
|
||||
}
|
||||
for skip in &session.skips {
|
||||
for (j, there) in kept
|
||||
.iter()
|
||||
.enumerate()
|
||||
.take(kept.len().min(skip.at + WINDOW))
|
||||
.skip(skip.at.saturating_sub(WINDOW))
|
||||
{
|
||||
let distance = if j < skip.at {
|
||||
skip.at - j
|
||||
} else {
|
||||
j - skip.at + 1
|
||||
};
|
||||
let rate = alpha
|
||||
* 0.5
|
||||
* skip.weight
|
||||
* there.weight.sqrt()
|
||||
* (WINDOW + 1 - distance) as f64
|
||||
/ WINDOW as f64;
|
||||
model.apart(skip.song, there.song, rate);
|
||||
model.apart(skip.song, there.artist, rate);
|
||||
model.apart(there.song, skip.song, rate);
|
||||
model.apart(there.artist, skip.song, rate);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut mean = [0.0; DIMENSIONS];
|
||||
for (i, value) in model.input.iter().enumerate() {
|
||||
mean[i % DIMENSIONS] += value / tokens.len() as f64;
|
||||
}
|
||||
let mut vectors = Vec::with_capacity(model.input.len());
|
||||
for row in model.input.chunks_mut(DIMENSIONS) {
|
||||
check()?;
|
||||
let mut norm = 0.0;
|
||||
for (k, value) in row.iter_mut().enumerate() {
|
||||
*value -= mean[k];
|
||||
norm += *value * *value;
|
||||
}
|
||||
norm = norm.sqrt();
|
||||
for value in row {
|
||||
vectors.push(if norm == 0.0 {
|
||||
0.0
|
||||
} else {
|
||||
(*value / norm) as f32 as f64
|
||||
});
|
||||
}
|
||||
}
|
||||
check()?;
|
||||
Ok(json!({"tokens":tokens,"vectors":vectors,"positives":positives,"through":through}))
|
||||
}
|
||||
|
||||
fn finish_session(session: Option<&mut Vec<Position<'_>>>, endorsed: &HashMap<&str, f64>) {
|
||||
if let Some(session) = session {
|
||||
for position in session {
|
||||
if let Some(value) = endorsed.get(position.song) {
|
||||
position.weight = position.weight.max(*value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Trainer {
|
||||
input: Vec<f64>,
|
||||
output: Vec<f64>,
|
||||
error: [f64; DIMENSIONS],
|
||||
random: DartRandom,
|
||||
cumulative: Vec<f64>,
|
||||
total: f64,
|
||||
}
|
||||
|
||||
impl Trainer {
|
||||
fn negative(&mut self) -> i32 {
|
||||
let target = self.random.next_double() * self.total;
|
||||
let mut low = 0;
|
||||
let mut high = self.cumulative.len() - 1;
|
||||
while low < high {
|
||||
let middle = (low + high) >> 1;
|
||||
if self.cumulative[middle] <= target {
|
||||
low = middle + 1;
|
||||
} else {
|
||||
high = middle;
|
||||
}
|
||||
}
|
||||
low as i32
|
||||
}
|
||||
|
||||
fn update(&mut self, center: i32, target: i32, label: f64, rate: f64) {
|
||||
let c = center as usize * DIMENSIONS;
|
||||
let t = target as usize * DIMENSIONS;
|
||||
let mut dot = 0.0;
|
||||
for k in 0..DIMENSIONS {
|
||||
dot += self.input[c + k] * self.output[t + k];
|
||||
}
|
||||
let gradient = (label - 1.0 / (1.0 + (-dot).exp())) * rate;
|
||||
for k in 0..DIMENSIONS {
|
||||
self.error[k] += gradient * self.output[t + k];
|
||||
self.output[t + k] += gradient * self.input[c + k];
|
||||
}
|
||||
}
|
||||
|
||||
fn apply(&mut self, center: i32) {
|
||||
let c = center as usize * DIMENSIONS;
|
||||
for k in 0..DIMENSIONS {
|
||||
self.input[c + k] += self.error[k];
|
||||
self.error[k] = 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
fn together(&mut self, center: i32, context: i32, rate: f64) {
|
||||
if center < 0 || context < 0 || center == context {
|
||||
return;
|
||||
}
|
||||
self.update(center, context, 1.0, rate);
|
||||
for _ in 0..5 {
|
||||
let other = self.negative();
|
||||
if other != center && other != context {
|
||||
self.update(center, other, 0.0, rate);
|
||||
}
|
||||
}
|
||||
self.apply(center);
|
||||
}
|
||||
|
||||
fn apart(&mut self, center: i32, context: i32, rate: f64) {
|
||||
if center < 0 || context < 0 || center == context {
|
||||
return;
|
||||
}
|
||||
self.update(center, context, 0.0, rate);
|
||||
self.apply(center);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
|
||||
#[test]
|
||||
fn seeded_rng_matches_pinned_dart_vm() {
|
||||
let expected = [
|
||||
0.9667509138757331,
|
||||
0.37868351564893676,
|
||||
0.2873468299514055,
|
||||
0.5329176123040603,
|
||||
0.8553088058196988,
|
||||
0.6080254671138047,
|
||||
0.30687412066389064,
|
||||
0.27364317178817865,
|
||||
0.2886725186936596,
|
||||
0.8754835561891346,
|
||||
0.23683893544521994,
|
||||
0.8949821982072496,
|
||||
];
|
||||
let mut random = DartRandom::new(0x7a57e);
|
||||
for value in expected {
|
||||
assert_eq!(random.next_double(), value);
|
||||
}
|
||||
let mut random = DartRandom::new(0x7a57e);
|
||||
for value in [21, 80, 59, 59, 4, 71, 52, 84, 20, 25, 48, 84] {
|
||||
assert_eq!(random.next_int(97), value);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_history_preserves_empty_model() {
|
||||
assert_eq!(
|
||||
execute(&json!({"plays":[]}), &|| Ok(())).unwrap(),
|
||||
json!({"tokens":[],"vectors":[],"positives":0,"through":0})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endorsements_are_not_counted_as_listens() {
|
||||
let result = execute(&json!({"plays":[{"id":9,"song":"a|song","artist":"a","atMicros":1,"kind":"loved","reward":1.0}]}), &||Ok(())).unwrap();
|
||||
assert_eq!(result["through"], 9);
|
||||
assert_eq!(result["positives"], 0);
|
||||
assert_eq!(result["tokens"], json!([]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_stops_training() {
|
||||
let count = Cell::new(0);
|
||||
let result = execute(&json!({"plays":[]}), &|| {
|
||||
count.set(count.get() + 1);
|
||||
if count.get() > 1 {
|
||||
Err("cancelled".into())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
});
|
||||
assert_eq!(result.unwrap_err(), "cancelled");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
//! Read-only cache statistics. Counters are accumulated on the native worker
|
||||
//! without retaining a list of files or following recursive link cycles.
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
fs::{self, ReadDir},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Stats {
|
||||
files: u64,
|
||||
bytes: u64,
|
||||
}
|
||||
|
||||
struct DirectoryFrame {
|
||||
entries: ReadDir,
|
||||
followed_link: Option<PathBuf>,
|
||||
}
|
||||
|
||||
pub(crate) fn execute(
|
||||
request: &Value,
|
||||
check: &dyn Fn() -> Result<(), String>,
|
||||
) -> Result<Value, String> {
|
||||
check()?;
|
||||
let path = Path::new(crate::data_jobs::string(request, "path")?);
|
||||
if !path.is_absolute() {
|
||||
return Err("Directory statistics require an absolute path".into());
|
||||
}
|
||||
let follow_links = request["follow_links"]
|
||||
.as_bool()
|
||||
.ok_or("Directory statistics require follow_links")?;
|
||||
let stats = scan(path, follow_links, check)?;
|
||||
Ok(json!({"file_count": stats.files, "total_size_bytes": stats.bytes}))
|
||||
}
|
||||
|
||||
fn scan(
|
||||
path: &Path,
|
||||
follow_links: bool,
|
||||
check: &dyn Fn() -> Result<(), String>,
|
||||
) -> Result<Stats, String> {
|
||||
let mut stats = Stats::default();
|
||||
// Directory.exists in the compatibility path follows a root link even
|
||||
// when links encountered inside the directory are excluded.
|
||||
if !path.is_dir() {
|
||||
return Ok(stats);
|
||||
}
|
||||
let Ok(entries) = fs::read_dir(path) else {
|
||||
return Ok(stats);
|
||||
};
|
||||
let mut followed_links = HashSet::new();
|
||||
let mut stack = vec![DirectoryFrame {
|
||||
entries,
|
||||
followed_link: None,
|
||||
}];
|
||||
while let Some(frame) = stack.last_mut() {
|
||||
check()?;
|
||||
let Some(entry) = frame.entries.next() else {
|
||||
if let Some(link) = stack.pop().and_then(|frame| frame.followed_link) {
|
||||
followed_links.remove(&link);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let Ok(entry) = entry else {
|
||||
return Ok(stats);
|
||||
};
|
||||
let Ok(file_type) = entry.file_type() else {
|
||||
return Ok(stats);
|
||||
};
|
||||
let path = entry.path();
|
||||
let metadata = if file_type.is_symlink() {
|
||||
if !follow_links {
|
||||
continue;
|
||||
}
|
||||
// Dangling links are listed as links by Dart, not regular files.
|
||||
let Ok(metadata) = fs::metadata(&path) else {
|
||||
continue;
|
||||
};
|
||||
Some(metadata)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let kind = metadata.as_ref().map_or(file_type, fs::Metadata::file_type);
|
||||
if kind.is_file() {
|
||||
stats.files = stats.files.checked_add(1).ok_or("File count overflow")?;
|
||||
check()?;
|
||||
// Keep the counted entry if it disappears before its size can be
|
||||
// read, matching the existing partial-result contract.
|
||||
let metadata = match metadata {
|
||||
Some(metadata) => metadata,
|
||||
None => match entry.metadata() {
|
||||
Ok(metadata) => metadata,
|
||||
Err(_) => return Ok(stats),
|
||||
},
|
||||
};
|
||||
stats.bytes = stats
|
||||
.bytes
|
||||
.checked_add(metadata.len())
|
||||
.ok_or("Directory size overflow")?;
|
||||
} else if kind.is_dir() {
|
||||
let followed_link = if file_type.is_symlink() {
|
||||
// Dart visits a link once per recursive descent. Tracking
|
||||
// target directories instead would undercount ordinary paths
|
||||
// reached through a link back to an ancestor.
|
||||
let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else {
|
||||
return Ok(stats);
|
||||
};
|
||||
let Ok(parent) = parent.canonicalize() else {
|
||||
return Ok(stats);
|
||||
};
|
||||
let link = parent.join(name);
|
||||
if followed_links.contains(&link) {
|
||||
continue;
|
||||
}
|
||||
Some(link)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let Ok(entries) = fs::read_dir(&path) else {
|
||||
return Ok(stats);
|
||||
};
|
||||
followed_links.extend(followed_link.iter().cloned());
|
||||
stack.push(DirectoryFrame {
|
||||
entries,
|
||||
followed_link,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(stats)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
|
||||
fn request(path: &Path, follow_links: bool) -> Value {
|
||||
json!({"path": path, "follow_links": follow_links})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_nested_unicode_files_including_empty_files() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
fs::create_dir(root.path().join("nested")).unwrap();
|
||||
fs::write(root.path().join("first"), b"1234").unwrap();
|
||||
fs::write(root.path().join("nested/音楽"), b"123456").unwrap();
|
||||
fs::write(root.path().join("empty"), b"").unwrap();
|
||||
for follow in [false, true] {
|
||||
assert_eq!(
|
||||
execute(&request(root.path(), follow), &|| Ok(())).unwrap(),
|
||||
json!({"file_count": 3, "total_size_bytes": 10})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_directories_and_file_roots_have_zero_stats() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let file = root.path().join("file");
|
||||
fs::write(&file, b"123").unwrap();
|
||||
for path in [root.path().join("missing"), file] {
|
||||
assert_eq!(
|
||||
execute(&request(&path, false), &|| Ok(())).unwrap(),
|
||||
json!({"file_count": 0, "total_size_bytes": 0})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_requests_and_cancellation_are_not_partial_successes() {
|
||||
assert!(
|
||||
execute(&json!({"path": "relative", "follow_links": false}), &|| Ok(
|
||||
()
|
||||
))
|
||||
.is_err()
|
||||
);
|
||||
assert!(execute(&json!({"path": "/tmp"}), &|| Ok(())).is_err());
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
fs::write(root.path().join("file"), b"123").unwrap();
|
||||
let calls = Cell::new(0);
|
||||
let result = execute(&request(root.path(), false), &|| {
|
||||
calls.set(calls.get() + 1);
|
||||
if calls.get() > 2 {
|
||||
Err("cancelled".into())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
});
|
||||
assert_eq!(result.unwrap_err(), "cancelled");
|
||||
assert!(root.path().join("file").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_file_removed_before_size_lookup_preserves_partial_counts() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let file = root.path().join("removed");
|
||||
fs::write(&file, b"123").unwrap();
|
||||
let calls = Cell::new(0);
|
||||
let result = execute(&request(root.path(), false), &|| {
|
||||
calls.set(calls.get() + 1);
|
||||
if calls.get() == 3 {
|
||||
fs::remove_file(&file).unwrap();
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
assert_eq!(
|
||||
result.unwrap(),
|
||||
json!({"file_count": 1, "total_size_bytes": 0})
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn links_follow_requested_policy_and_cycles_do_not_hide_aliases() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
fs::create_dir(root.path().join("nested")).unwrap();
|
||||
fs::write(root.path().join("nested/file"), b"123").unwrap();
|
||||
symlink("nested/file", root.path().join("file_link")).unwrap();
|
||||
symlink("nested", root.path().join("directory_link")).unwrap();
|
||||
symlink("..", root.path().join("nested/cycle")).unwrap();
|
||||
symlink("missing", root.path().join("dangling")).unwrap();
|
||||
assert_eq!(
|
||||
execute(&request(root.path(), false), &|| Ok(())).unwrap(),
|
||||
json!({"file_count": 1, "total_size_bytes": 3})
|
||||
);
|
||||
assert_eq!(
|
||||
execute(&request(root.path(), true), &|| Ok(())).unwrap(),
|
||||
json!({"file_count": 8, "total_size_bytes": 24})
|
||||
);
|
||||
let alias = root.path().with_extension("alias");
|
||||
symlink(root.path(), &alias).unwrap();
|
||||
let actual = execute(&request(&alias, false), &|| Ok(()));
|
||||
fs::remove_file(alias).unwrap();
|
||||
assert_eq!(
|
||||
actual.unwrap(),
|
||||
json!({"file_count": 1, "total_size_bytes": 3})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,478 @@
|
||||
//! Model reply validation on the data worker, with the Dart parser's wire contract.
|
||||
use crate::native_library::path_keys::dart_trim;
|
||||
use regex::Regex;
|
||||
use serde::de::{DeserializeOwned, MapAccess, Visitor};
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use serde_json::{Value, json, value::RawValue};
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
fmt,
|
||||
sync::LazyLock,
|
||||
};
|
||||
|
||||
static THOUGHTS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?s)<think>.*?</think>").unwrap());
|
||||
static FENCE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
let whitespace = r"[\t\n\v\f\r \u{00a0}\u{1680}\u{2000}-\u{200a}\u{2028}\u{2029}\u{202f}\u{205f}\u{3000}\u{feff}]";
|
||||
Regex::new(&format!(
|
||||
r"(?s)^```[a-zA-Z0-9_-]*{whitespace}*\n?(.*?)\n?```{whitespace}*$"
|
||||
))
|
||||
.unwrap()
|
||||
});
|
||||
|
||||
// Dart retains insertion order when selecting the first array of an object.
|
||||
// Duplicate keys replace the value without moving the original position.
|
||||
struct OrderedObject(Vec<(String, Box<RawValue>)>);
|
||||
|
||||
impl OrderedObject {
|
||||
fn get(&self, name: &str) -> Option<&RawValue> {
|
||||
self.0
|
||||
.iter()
|
||||
.find(|(key, _)| key == name)
|
||||
.map(|(_, value)| value.as_ref())
|
||||
}
|
||||
|
||||
fn read<T: DeserializeOwned>(&self, name: &str) -> Option<T> {
|
||||
serde_json::from_str(self.get(name)?.get()).ok()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for OrderedObject {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
struct ObjectVisitor;
|
||||
impl<'de> Visitor<'de> for ObjectVisitor {
|
||||
type Value = OrderedObject;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str("a JSON object")
|
||||
}
|
||||
|
||||
fn visit_map<M: MapAccess<'de>>(self, mut map: M) -> Result<Self::Value, M::Error> {
|
||||
let mut fields: Vec<(String, Box<RawValue>)> = Vec::new();
|
||||
let mut positions = HashMap::<String, usize>::new();
|
||||
while let Some((key, value)) = map.next_entry::<String, Box<RawValue>>()? {
|
||||
if let Some(&index) = positions.get(&key) {
|
||||
fields[index].1 = value;
|
||||
} else {
|
||||
positions.insert(key.clone(), fields.len());
|
||||
fields.push((key, value));
|
||||
}
|
||||
}
|
||||
Ok(OrderedObject(fields))
|
||||
}
|
||||
}
|
||||
deserializer.deserialize_map(ObjectVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn execute(
|
||||
request: &Value,
|
||||
bytes: Option<&[u8]>,
|
||||
check: &dyn Fn() -> Result<(), String>,
|
||||
) -> Result<Value, String> {
|
||||
check()?;
|
||||
let reply = match bytes.filter(|bytes| !bytes.is_empty()) {
|
||||
Some(bytes) => std::str::from_utf8(bytes).map_err(|error| error.to_string())?,
|
||||
None => request["reply"].as_str().unwrap_or_default(),
|
||||
};
|
||||
let ids = request["ids"]
|
||||
.as_array()
|
||||
.ok_or("Missing native translation field: ids")?
|
||||
.iter()
|
||||
.map(|id| id.as_i64().ok_or("Invalid native translation id"))
|
||||
.collect::<Result<HashSet<_>, _>>()?;
|
||||
let stripped = THOUGHTS.replace_all(dart_trim(reply), "");
|
||||
let text = dart_trim(&stripped);
|
||||
let fence = FENCE.captures(text);
|
||||
let text = fence
|
||||
.as_ref()
|
||||
.map_or(text, |capture| dart_trim(capture.get(1).unwrap().as_str()));
|
||||
check()?;
|
||||
let decoded = serde_json::from_str::<Box<RawValue>>(text).ok();
|
||||
let decoded = match decoded.filter(|value| value.get() != "null") {
|
||||
Some(value) => Some(value),
|
||||
None => match (text.find(['[', '{']), text.rfind([']', '}'])) {
|
||||
(Some(start), Some(end)) if end > start => {
|
||||
serde_json::from_str::<Box<RawValue>>(&text[start..=end]).ok()
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
};
|
||||
let entries = decoded.and_then(|value| reply_entries(&value));
|
||||
let Some(entries) = entries else {
|
||||
return Ok(json!({"error": "badResponse", "detail": "reply is not a JSON list"}));
|
||||
};
|
||||
let mut seen = HashSet::new();
|
||||
let mut lines = Vec::new();
|
||||
for entry in entries {
|
||||
check()?;
|
||||
let Ok(entry) = serde_json::from_str::<OrderedObject>(entry.get()) else {
|
||||
continue;
|
||||
};
|
||||
let Some(id) = entry.read::<Value>("id").as_ref().and_then(reply_id) else {
|
||||
continue;
|
||||
};
|
||||
let text = entry
|
||||
.get("text")
|
||||
.filter(|value| value.get() != "null")
|
||||
.or_else(|| entry.get("translation"))
|
||||
.and_then(|value| serde_json::from_str::<String>(value.get()).ok());
|
||||
let Some(text) = text
|
||||
.as_deref()
|
||||
.map(dart_trim)
|
||||
.filter(|text| !text.is_empty())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if !ids.contains(&id) || !seen.insert(id) {
|
||||
continue;
|
||||
}
|
||||
let reading = entry.read::<String>("romanization");
|
||||
let romanization = reading
|
||||
.as_deref()
|
||||
.map(dart_trim)
|
||||
.filter(|text| !text.is_empty());
|
||||
lines.push(json!({
|
||||
"id": id,
|
||||
"text": text,
|
||||
"romanization": romanization,
|
||||
"alignment": chunks(entry.get("alignment"), text, check)?.unwrap_or_default(),
|
||||
"romanizationAlignment": chunks(
|
||||
entry.get("romanizationAlignment"), romanization.unwrap_or_default(), check
|
||||
)?.unwrap_or_default(),
|
||||
}));
|
||||
}
|
||||
check()?;
|
||||
Ok(json!({"lines": lines}))
|
||||
}
|
||||
|
||||
fn reply_entries(value: &RawValue) -> Option<Vec<Box<RawValue>>> {
|
||||
let raw = value.get();
|
||||
if raw.starts_with('[') {
|
||||
return serde_json::from_str(raw).ok();
|
||||
}
|
||||
let OrderedObject(fields) = serde_json::from_str(raw).ok()?;
|
||||
let selected = ["lines", "translations"]
|
||||
.into_iter()
|
||||
.find_map(|name| {
|
||||
fields
|
||||
.iter()
|
||||
.find(|(key, value)| key == name && value.get() != "null")
|
||||
.map(|(_, value)| value)
|
||||
})
|
||||
.or_else(|| {
|
||||
fields
|
||||
.iter()
|
||||
.find(|(_, value)| value.get().starts_with('['))
|
||||
.map(|(_, value)| value)
|
||||
})?;
|
||||
serde_json::from_str(selected.get()).ok()
|
||||
}
|
||||
|
||||
fn reply_id(value: &Value) -> Option<i64> {
|
||||
match value {
|
||||
Value::Number(number) => number
|
||||
.as_i64()
|
||||
.or_else(|| number.as_f64().map(|value| value as i64)),
|
||||
Value::String(value) => {
|
||||
let value = dart_trim(value);
|
||||
let (negative, digits) = if let Some(digits) = value.strip_prefix('-') {
|
||||
(true, digits)
|
||||
} else {
|
||||
(false, value.strip_prefix('+').unwrap_or(value))
|
||||
};
|
||||
if let Some(hex) = digits
|
||||
.strip_prefix("0x")
|
||||
.or_else(|| digits.strip_prefix("0X"))
|
||||
{
|
||||
if !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
let unsigned = u64::from_str_radix(hex, 16).ok()?;
|
||||
let signed = unsigned as i64;
|
||||
Some(if negative {
|
||||
signed.wrapping_neg()
|
||||
} else {
|
||||
signed
|
||||
})
|
||||
} else {
|
||||
value.parse().ok()
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn chunks(
|
||||
value: Option<&RawValue>,
|
||||
text: &str,
|
||||
check: &dyn Fn() -> Result<(), String>,
|
||||
) -> Result<Option<Vec<Value>>, String> {
|
||||
let Some(value) = value.filter(|value| value.get() != "null") else {
|
||||
return Ok(Some(Vec::new()));
|
||||
};
|
||||
let Some(values) = serde_json::from_str::<Vec<Box<RawValue>>>(value.get())
|
||||
.ok()
|
||||
.filter(|values| values.len() <= 256)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut previous = 0;
|
||||
let mut length = 0;
|
||||
let mut joined = String::new();
|
||||
let mut chunks = Vec::with_capacity(values.len());
|
||||
for value in &values {
|
||||
check()?;
|
||||
let (part, source) = match value.get().as_bytes().first() {
|
||||
Some(b'[') => {
|
||||
let Ok(pair) = serde_json::from_str::<Vec<Box<RawValue>>>(value.get()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
if pair.len() != 2 {
|
||||
return Ok(None);
|
||||
}
|
||||
(
|
||||
serde_json::from_str::<String>(pair[1].get()).ok(),
|
||||
serde_json::from_str::<i64>(pair[0].get()).ok(),
|
||||
)
|
||||
}
|
||||
Some(b'{') => {
|
||||
let Ok(map) = serde_json::from_str::<OrderedObject>(value.get()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
(map.read::<String>("text"), map.read::<i64>("source"))
|
||||
}
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let (Some(part), Some(source)) = (part, source) else {
|
||||
return Ok(None);
|
||||
};
|
||||
if part.is_empty() || source < previous || source >= 512 {
|
||||
return Ok(None);
|
||||
}
|
||||
length += part.encode_utf16().count();
|
||||
if length > 4000 {
|
||||
return Ok(None);
|
||||
}
|
||||
joined.push_str(&part);
|
||||
chunks.push(json!({"text": part, "source": source}));
|
||||
previous = source;
|
||||
}
|
||||
if !chunks.is_empty() && joined != text {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(chunks))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
|
||||
fn parse(reply: &str, ids: &[i64]) -> Value {
|
||||
execute(&json!({"reply": reply, "ids": ids}), None, &|| Ok(())).unwrap()
|
||||
}
|
||||
|
||||
fn line(id: i64, text: &str) -> Value {
|
||||
json!({
|
||||
"id": id, "text": text, "romanization": null,
|
||||
"alignment": [], "romanizationAlignment": [],
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_reply_wrappers_and_string_ids() {
|
||||
for reply in [
|
||||
r#"{"lines":[{"id":"0","text":" Uno "}]}"#,
|
||||
r#"[{"id":0,"translation":" Uno "}]"#,
|
||||
"```json\n[{\"id\":0,\"text\":\"Uno\"}]\n```",
|
||||
"<think>one\ntwo</think>Here: {\"translations\":[{\"id\":0,\"text\":\"Uno\"}]}",
|
||||
] {
|
||||
assert_eq!(parse(reply, &[0]), json!({"lines": [line(0, "Uno")]}));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_non_null_named_list_precedes_insertion_order_fallback() {
|
||||
assert_eq!(
|
||||
parse(
|
||||
r#"{"z":[{"id":1,"text":"first"}],"a":[{"id":0,"text":"last"}]}"#,
|
||||
&[0, 1]
|
||||
),
|
||||
json!({"lines": [line(1, "first")]})
|
||||
);
|
||||
assert_eq!(
|
||||
parse(
|
||||
r#"{"z":[],"z":[{"id":1,"text":"first"}],"a":[{"id":0,"text":"last"}]}"#,
|
||||
&[0, 1]
|
||||
),
|
||||
json!({"lines": [line(1, "first")]})
|
||||
);
|
||||
assert_eq!(
|
||||
parse(
|
||||
r#"{"lines":null,"z":[],"translations":[{"id":0,"text":"named"}]}"#,
|
||||
&[0]
|
||||
),
|
||||
json!({"lines": [line(0, "named")]})
|
||||
);
|
||||
assert!(
|
||||
parse(r#"{"lines":false,"translations":[]}"#, &[0])
|
||||
.get("error")
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drops_invalid_unknown_blank_and_duplicate_lines() {
|
||||
let reply = r#"[null,[],{"id":0,"text":" "},{"id":0,"text":"first"},{"id":0,"text":"second"},{"id":9,"text":"unknown"},{"text":"missing"},{"id":1,"text":false,"translation":"ignored"},{"id":2,"text":null,"translation":"fallback"}]"#;
|
||||
assert_eq!(
|
||||
parse(reply, &[0, 1, 2]),
|
||||
json!({"lines": [line(0, "first"), line(2, "fallback")]})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_response_order_and_numeric_id_semantics() {
|
||||
let reply = r#"[{"id":2.9,"text":"two"},{"id":" +0x1 ","text":"one"},{"id":-0.9,"text":"zero"},{"id":"-1","text":"negative"},{"id":true,"text":"ignored"}]"#;
|
||||
assert_eq!(
|
||||
parse(reply, &[-1, 0, 1, 2]),
|
||||
json!({"lines": [line(2, "two"), line(1, "one"), line(0, "zero"), line(-1, "negative")]})
|
||||
);
|
||||
assert_eq!(reply_id(&json!("0xffffffffffffffff")), Some(-1));
|
||||
assert_eq!(reply_id(&json!("9223372036854775808")), None);
|
||||
assert_eq!(reply_id(&json!(1e40)), Some(i64::MAX));
|
||||
assert_eq!(reply_id(&json!(-1e40)), Some(i64::MIN));
|
||||
assert_eq!(reply_id(&json!("1.0")), None);
|
||||
assert_eq!(reply_id(&json!("0x+1")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trims_dart_whitespace_including_bom_and_next_line_control() {
|
||||
let reply = "\u{feff} [{\"id\":0,\"text\":\"\\ufefftext\\ufeff\",\"romanization\":\" read \"},{\"id\":1,\"text\":\"\\u0085kept\\u0085\"}] \u{feff}";
|
||||
let mut expected = line(0, "text");
|
||||
expected["romanization"] = json!("read");
|
||||
assert_eq!(
|
||||
parse(reply, &[0, 1]),
|
||||
json!({"lines": [expected, line(1, "kept")]})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_valid_phrase_and_romanization_alignment() {
|
||||
let reply = r#"[{"id":0,"text":" A B ","romanization":" read it ","alignment":[[0,"A "],{"source":0,"text":"B"}],"romanizationAlignment":[[0,"read "],[511,"it"]]}]"#;
|
||||
let expected = json!({"id": 0, "text": "A B", "romanization": "read it", "alignment": [{"source":0,"text":"A "},{"source":0,"text":"B"}], "romanizationAlignment": [{"source":0,"text":"read "},{"source":511,"text":"it"}]});
|
||||
assert_eq!(parse(reply, &[0]), json!({"lines":[expected]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_alignment_preserves_translated_text() {
|
||||
for alignment in [
|
||||
json!(false),
|
||||
json!({}),
|
||||
json!([[0, "wrong"]]),
|
||||
json!([[0.0, "text"]]),
|
||||
json!([["0", "text"]]),
|
||||
json!([[-1, "text"]]),
|
||||
json!([[512, "text"]]),
|
||||
json!([[0, ""]]),
|
||||
json!([[1, "te"], [0, "xt"]]),
|
||||
json!([[0, "text", "extra"]]),
|
||||
] {
|
||||
let reply = json!([{"id":0,"text":"text","alignment":alignment}]).to_string();
|
||||
assert_eq!(parse(&reply, &[0]), json!({"lines":[line(0, "text")]}));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alignment_limits_count_utf16_units_and_chunks() {
|
||||
let check = || Ok(());
|
||||
let at_limit = "😀".repeat(2000);
|
||||
let valid = RawValue::from_string(json!([[0, at_limit]]).to_string()).unwrap();
|
||||
assert!(chunks(Some(&valid), &at_limit, &check).unwrap().is_some());
|
||||
let too_long = "😀".repeat(2001);
|
||||
let invalid = RawValue::from_string(json!([[0, too_long]]).to_string()).unwrap();
|
||||
assert!(chunks(Some(&invalid), &too_long, &check).unwrap().is_none());
|
||||
for count in [256, 257] {
|
||||
let value = Value::Array((0..count).map(|_| json!([0, "a"])).collect());
|
||||
let value = RawValue::from_string(value.to_string()).unwrap();
|
||||
assert_eq!(
|
||||
chunks(Some(&value), &"a".repeat(count), &check)
|
||||
.unwrap()
|
||||
.is_some(),
|
||||
count == 256
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_dart_fixtures_match_native_contract() {
|
||||
let fixtures: Vec<Value> = serde_json::from_str(include_str!(
|
||||
"../../../../test/fixtures/native_lyrics_translation_replies.json"
|
||||
))
|
||||
.unwrap();
|
||||
for fixture in fixtures {
|
||||
assert_eq!(
|
||||
execute(&fixture["request"], None, &|| Ok(())).unwrap(),
|
||||
fixture["expected"],
|
||||
"{}",
|
||||
fixture["name"]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deeply_nested_unknown_fields_do_not_discard_usable_lines() {
|
||||
let nested = format!("{}null{}", "[".repeat(200), "]".repeat(200));
|
||||
let reply = format!(
|
||||
r#"{{"ignored":{nested},"lines":[{{"id":0,"text":"kept","extra":{nested},"alignment":[{{"source":0,"text":"kept","extra":{nested}}}]}}]}}"#
|
||||
);
|
||||
let mut expected = line(0, "kept");
|
||||
expected["alignment"] = json!([{"source":0,"text":"kept"}]);
|
||||
assert_eq!(parse(&reply, &[0]), json!({"lines":[expected]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_documents_return_typed_bad_response() {
|
||||
for reply in [
|
||||
"",
|
||||
"Sorry, I cannot.",
|
||||
"null",
|
||||
"42",
|
||||
"{}",
|
||||
r#"{"lines":"none"}"#,
|
||||
"[{broken}]",
|
||||
] {
|
||||
assert_eq!(
|
||||
parse(reply, &[0]),
|
||||
json!({"error":"badResponse", "detail":"reply is not a JSON list"})
|
||||
);
|
||||
}
|
||||
assert_eq!(parse("[]", &[0]), json!({"lines":[]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bytes_take_precedence_and_invalid_utf8_is_an_error() {
|
||||
let request = json!({"ids":[0], "reply":"not a list"});
|
||||
assert_eq!(
|
||||
execute(&request, Some(b"[]"), &|| Ok(())).unwrap(),
|
||||
json!({"lines":[]})
|
||||
);
|
||||
assert!(execute(&request, Some(&[0xff]), &|| Ok(())).is_err());
|
||||
assert!(execute(&json!({}), None, &|| Ok(())).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_interrupts_validation_without_a_partial_result() {
|
||||
let calls = Cell::new(0);
|
||||
let request =
|
||||
json!({"reply": r#"[{"id":0,"text":"one"},{"id":1,"text":"two"}]"#, "ids":[0,1]});
|
||||
let result = execute(&request, None, &|| {
|
||||
calls.set(calls.get() + 1);
|
||||
if calls.get() == 4 {
|
||||
Err("cancelled".into())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
});
|
||||
assert_eq!(result.unwrap_err(), "cancelled");
|
||||
}
|
||||
}
|
||||
@@ -127,6 +127,7 @@ R _captureTraining<R>(List<_TrainingTimer> timers, R Function() action) =>
|
||||
);
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
test(
|
||||
'a feedback burst schedules one training outside the track change',
|
||||
() async {
|
||||
|
||||
@@ -2,10 +2,10 @@ import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:audio_service/audio_service.dart' show MediaItem;
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mornye/services/cover_store.dart';
|
||||
import 'package:mornye/services/network_storage_service.dart';
|
||||
@@ -34,10 +34,13 @@ void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
HttpOverrides.global = null;
|
||||
late Directory directory;
|
||||
const channel = MethodChannel('com.zarz.mornye/backend');
|
||||
setUp(() async {
|
||||
directory = await Directory.systemTemp.createTemp('cover-store-test-');
|
||||
});
|
||||
tearDown(() async {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(channel, null);
|
||||
await directory.delete(recursive: true);
|
||||
});
|
||||
|
||||
@@ -72,6 +75,35 @@ void main() {
|
||||
}
|
||||
}
|
||||
|
||||
test(
|
||||
'native cover digest preserves the content-addressed filename',
|
||||
() async {
|
||||
final bytes = _jpeg(2);
|
||||
final digest = sha256.convert(bytes).toString();
|
||||
var hashes = 0;
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(channel, (call) async {
|
||||
expect(call.method, 'runNativeDataJob');
|
||||
final request =
|
||||
jsonDecode((call.arguments as Map)['request_json'] as String)
|
||||
as Map;
|
||||
expect(request['operation'], 'hash_file');
|
||||
expect(await File(request['path'] as String).readAsBytes(), bytes);
|
||||
hashes++;
|
||||
return {'sha256': digest};
|
||||
});
|
||||
final covers = store(
|
||||
fetch: (_, output) async {
|
||||
await output.writeAsBytes(bytes);
|
||||
},
|
||||
);
|
||||
final path = await covers.file('network://library/cover.image');
|
||||
expect(path, endsWith('_${digest.substring(0, 16)}.image'));
|
||||
expect(hashes, 1);
|
||||
expect(await File(path!).readAsBytes(), bytes);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'a network cover keeps one path while resolve answers a new URL',
|
||||
() async {
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart';
|
||||
@@ -312,11 +313,14 @@ void main() {
|
||||
final payload = utf8.encode('verified package bytes');
|
||||
final payloadSha = sha256.convert(payload).toString();
|
||||
const assetName = 'Mornye-$_version-linux-x86_64.AppImage';
|
||||
const channel = MethodChannel('com.zarz.mornye/backend');
|
||||
|
||||
setUp(() async {
|
||||
temp = await Directory.systemTemp.createTemp('mornye-updater-test');
|
||||
});
|
||||
tearDown(() async {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(channel, null);
|
||||
if (await temp.exists()) await temp.delete(recursive: true);
|
||||
});
|
||||
|
||||
@@ -351,6 +355,36 @@ void main() {
|
||||
expect(File('${file.path}.part').existsSync(), isFalse);
|
||||
});
|
||||
|
||||
test(
|
||||
'uses the native digest and rejects its mismatch before publishing',
|
||||
() async {
|
||||
var hashes = 0;
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(channel, (call) async {
|
||||
expect(call.method, 'runNativeDataJob');
|
||||
final arguments = call.arguments as Map;
|
||||
final request =
|
||||
jsonDecode(arguments['request_json'] as String) as Map;
|
||||
expect(request['operation'], 'hash_file');
|
||||
final file = File(request['path'] as String);
|
||||
expect(file.path, endsWith('.part'));
|
||||
expect(await file.readAsBytes(), payload);
|
||||
hashes++;
|
||||
return {'sha256': '0' * 64};
|
||||
});
|
||||
final updater = DesktopUpdater(
|
||||
client: client('$payloadSha $assetName\n'),
|
||||
downloadDirectory: temp,
|
||||
);
|
||||
await expectLater(
|
||||
updater.download(info()),
|
||||
throwsA(isA<DesktopUpdateException>()),
|
||||
);
|
||||
expect(hashes, 1);
|
||||
expect(temp.listSync(), isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test('rejects a package whose digest does not match', () async {
|
||||
final updater = DesktopUpdater(
|
||||
client: client('${List.filled(64, 'c').join()} $assetName\n'),
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
@@ -132,8 +133,23 @@ void main() {
|
||||
'a preview without a source timestamp stays on disk after memory eviction',
|
||||
() async {
|
||||
const untimed = 'content://example.documents/tree/nas/document/u.flac';
|
||||
var hashes = 0;
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(backendChannel, (call) async {
|
||||
if (call.method == 'runNativeDataJob') {
|
||||
final request =
|
||||
jsonDecode((call.arguments as Map)['request_json'] as String)
|
||||
as Map;
|
||||
expect(request['operation'], 'hash_file');
|
||||
expect(await File(request['path'] as String).readAsBytes(), [
|
||||
7,
|
||||
8,
|
||||
]);
|
||||
hashes++;
|
||||
return {
|
||||
'sha256': sha256.convert([7, 8]).toString(),
|
||||
};
|
||||
}
|
||||
if (call.method == 'getSafFileModTimes') {
|
||||
final uris = jsonDecode(
|
||||
(call.arguments as Map)['uris'] as String,
|
||||
@@ -153,6 +169,11 @@ void main() {
|
||||
untimed,
|
||||
);
|
||||
expect(preview, isNotNull);
|
||||
expect(hashes, 1);
|
||||
expect(
|
||||
preview,
|
||||
endsWith('_${sha256.convert([7, 8]).toString().substring(0, 16)}.jpg'),
|
||||
);
|
||||
expect(p.isWithin(persistentCacheDirectory.path, preview!), isTrue);
|
||||
// 180 newer previews push the first one out of the memory cache.
|
||||
for (var index = 0; index < 180; index++) {
|
||||
@@ -177,6 +198,14 @@ void main() {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(backendChannel, (call) async {
|
||||
if (call.method == 'getSafFileModTimes') return jsonEncode({});
|
||||
if (call.method == 'runNativeDataJob') {
|
||||
final request =
|
||||
jsonDecode((call.arguments as Map)['request_json'] as String)
|
||||
as Map;
|
||||
expect(request['operation'], 'hash_file');
|
||||
final bytes = await File(request['path'] as String).readAsBytes();
|
||||
return {'sha256': sha256.convert(bytes).toString()};
|
||||
}
|
||||
expect(call.method, 'extractCoverToFile');
|
||||
final args = call.arguments as Map<Object?, Object?>;
|
||||
await File(args['output_path']! as String).writeAsBytes(cover);
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
[
|
||||
{
|
||||
"name": "fences thoughts filtering and compact alignment",
|
||||
"request": {
|
||||
"ids": [7, 9],
|
||||
"reply": "<think>notes</think>\n```json\n{\"lines\":[{\"id\":\"7\",\"text\":\" Hello world \",\"romanization\":\" hi \",\"alignment\":[[0,\"Hello \"],[1,\"world\"]],\"romanizationAlignment\":[[0,\"hi\"]]},{\"id\":7,\"text\":\"duplicate\"},{\"id\":9,\"text\":\" \"},{\"id\":99,\"text\":\"unknown\"}]}\n```"
|
||||
},
|
||||
"expected": {
|
||||
"lines": [
|
||||
{"id": 7, "text": "Hello world", "romanization": "hi", "alignment": [{"text": "Hello ", "source": 0}, {"text": "world", "source": 1}], "romanizationAlignment": [{"text": "hi", "source": 0}]}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "first array uses original object order",
|
||||
"request": {
|
||||
"ids": [2],
|
||||
"reply": "Here is the result: {\"z\":[{\"id\":2,\"translation\":\"first\"}],\"a\":[{\"id\":2,\"text\":\"second\"}]} End."
|
||||
},
|
||||
"expected": {"lines": [{"id": 2, "text": "first", "romanization": null, "alignment": [], "romanizationAlignment": []}]}
|
||||
},
|
||||
{
|
||||
"name": "numeric ids and invalid alignment preserve translations",
|
||||
"request": {
|
||||
"ids": [-1, 2, 16],
|
||||
"reply": "[{\"id\":2,\"text\":\" \"},{\"id\":-1.9,\"text\":\"negative\",\"alignment\":[[-1,\"negative\"]]},{\"id\":2.9,\"text\":\"fraction\",\"alignment\":[[0,\"different\"]]},{\"id\":\"0x10\",\"translation\":\"hex\",\"romanization\":false},{\"id\":2,\"text\":\"duplicate\"}]"
|
||||
},
|
||||
"expected": {"lines": [{"id": -1, "text": "negative", "romanization": null, "alignment": [], "romanizationAlignment": []}, {"id": 2, "text": "fraction", "romanization": null, "alignment": [], "romanizationAlignment": []}, {"id": 16, "text": "hex", "romanization": null, "alignment": [], "romanizationAlignment": []}]}
|
||||
},
|
||||
{
|
||||
"name": "legacy chunks and unicode text",
|
||||
"request": {
|
||||
"ids": [1],
|
||||
"reply": "{\"translations\":[{\"id\":1,\"text\":\"🌙 malam\",\"alignment\":[{\"text\":\"🌙 \",\"source\":0},{\"text\":\"malam\",\"source\":1}]}]}"
|
||||
},
|
||||
"expected": {"lines": [{"id": 1, "text": "🌙 malam", "romanization": null, "alignment": [{"text": "🌙 ", "source": 0}, {"text": "malam", "source": 1}], "romanizationAlignment": []}]}
|
||||
},
|
||||
{
|
||||
"name": "an empty list is a usable partial reply",
|
||||
"request": {"ids": [1], "reply": "[]"},
|
||||
"expected": {"lines": []}
|
||||
},
|
||||
{
|
||||
"name": "preferred invalid lines is not replaced by another array",
|
||||
"request": {"ids": [1], "reply": "{\"lines\":false,\"translations\":[{\"id\":1,\"text\":\"ignored\"}]}"},
|
||||
"expected": {"error": "badResponse", "detail": "reply is not a JSON list"}
|
||||
},
|
||||
{
|
||||
"name": "malformed reply has a typed error",
|
||||
"request": {"ids": [1], "reply": "not JSON"},
|
||||
"expected": {"error": "badResponse", "detail": "reply is not a JSON list"}
|
||||
}
|
||||
]
|
||||
@@ -30,6 +30,8 @@ String _openAiReply(String content, {String finish = 'stop'}) => jsonEncode({
|
||||
});
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
group('request building', () {
|
||||
test(
|
||||
'all providers keep song context separate from requested line ids',
|
||||
|
||||
@@ -87,6 +87,8 @@ const _chunks = [
|
||||
];
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
test(
|
||||
'AI pronunciation uses original timing and preserves provider readings',
|
||||
() {
|
||||
|
||||
@@ -48,6 +48,8 @@ Future<void> _until(bool Function() done) async {
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
test('compact alignment preserves timing and rejects invalid pairs', () {
|
||||
final compact = readLyricsTranslationChunks(
|
||||
[
|
||||
@@ -399,7 +401,14 @@ void main() {
|
||||
.whenComplete(() => finished = true);
|
||||
var completed = 0, rounds = 0;
|
||||
while (!finished) {
|
||||
await _until(() => finished || completed < gates.length);
|
||||
// Native parsing may finish each response on a different worker.
|
||||
// Fill each simulated network wave before releasing its responses.
|
||||
await _until(
|
||||
() =>
|
||||
finished ||
|
||||
gates.length - completed == workers ||
|
||||
(gates.length == 4 && completed < gates.length),
|
||||
);
|
||||
if (finished) break;
|
||||
rounds++;
|
||||
final wave = gates.sublist(completed);
|
||||
|
||||
@@ -75,6 +75,8 @@ LyricsAiClient _client(
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
group('source', () {
|
||||
test('strips timing tags and skips instrumental lines', () {
|
||||
expect(
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'dart:convert';
|
||||
|
||||
import 'package:audio_service/audio_service.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_riverpod/misc.dart' show Override;
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
@@ -16,6 +17,7 @@ import 'package:mornye/providers/lyrics_translation_provider.dart';
|
||||
import 'package:mornye/providers/music_player_provider.dart';
|
||||
import 'package:mornye/providers/settings_provider.dart';
|
||||
import 'package:mornye/screens/settings/lyrics_ai_translation_page.dart';
|
||||
import 'package:mornye/services/lyrics_ai_client.dart';
|
||||
import 'package:mornye/services/lyrics_translation.dart';
|
||||
import 'package:mornye/services/lyrics_translation_sharing.dart';
|
||||
import 'package:mornye/theme/app_theme.dart';
|
||||
@@ -124,7 +126,45 @@ Widget _app({
|
||||
);
|
||||
|
||||
void main() {
|
||||
setUp(() => SharedPreferences.setMockInitialValues({}));
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
const channel = MethodChannel('com.zarz.mornye/backend');
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
var parsedReplies = 0;
|
||||
setUp(() {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
parsedReplies = 0;
|
||||
// Widget tests fake the worker boundary. Real native parser parity is
|
||||
// covered separately, without spawning an isolate under the fake clock.
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
if (call.method != 'runNativeDataJob') throw MissingPluginException();
|
||||
final arguments = call.arguments as Map;
|
||||
final request = jsonDecode(arguments['request_json'] as String) as Map;
|
||||
expect(request['operation'], 'parse_lyrics_translation_reply');
|
||||
final reply = utf8.decode(arguments['bytes'] as Uint8List);
|
||||
final ids = (request['ids'] as List).cast<int>().toSet();
|
||||
final parsed = parseLyricsTranslationReply(reply, ids);
|
||||
parsedReplies++;
|
||||
return jsonEncode({
|
||||
'lines': [
|
||||
for (final entry in parsed.entries)
|
||||
{
|
||||
'id': entry.key,
|
||||
'text': entry.value.text,
|
||||
'romanization': entry.value.romanization,
|
||||
'alignment': [
|
||||
for (final chunk in entry.value.alignment) chunk.toJson(),
|
||||
],
|
||||
'romanizationAlignment': [
|
||||
for (final chunk in entry.value.romanizationAlignment)
|
||||
chunk.toJson(),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
tearDown(() => messenger.setMockMethodCallHandler(channel, null));
|
||||
|
||||
for (final desktop in [false, true]) {
|
||||
for (final mornye in [false, true]) {
|
||||
@@ -307,6 +347,7 @@ void main() {
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(requests, hasLength(1));
|
||||
expect(parsedReplies, 1);
|
||||
expect(
|
||||
find.textContaining('de:Hello there', findRichText: true),
|
||||
findsWidgets,
|
||||
@@ -419,6 +460,7 @@ void main() {
|
||||
await tester.tap(find.byKey(const ValueKey('lyrics-ai-test')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('The connection works'), findsOneWidget);
|
||||
expect(parsedReplies, 1);
|
||||
|
||||
await tester.pump(const Duration(seconds: 5));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mornye/services/autoplay_taste.dart';
|
||||
import 'package:mornye/services/backend/ffi_backend_transport.dart';
|
||||
import 'package:mornye/services/backend/rust_ffi_backend.dart';
|
||||
import 'package:mornye/services/platform_bridge.dart';
|
||||
import 'package:mornye/utils/desktop_platform.dart';
|
||||
|
||||
import 'support/autoplay_taste_fixture.dart';
|
||||
|
||||
Map<String, Object?> _model(AutoplayTasteModel model) => {
|
||||
'tokens': model.tokens,
|
||||
'vectors': model.vectors.toList(),
|
||||
'positives': model.positives,
|
||||
'through': model.through,
|
||||
};
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
const channel = MethodChannel('com.zarz.mornye/backend');
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
|
||||
tearDown(() => messenger.setMockMethodCallHandler(channel, null));
|
||||
|
||||
test(
|
||||
'native training forwards history and preserves stored model shape',
|
||||
() async {
|
||||
final plays = autoplayTasteFixture(12);
|
||||
final expected = trainAutoplayTaste(plays);
|
||||
var called = false;
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
expect(call.method, 'runNativeDataJob');
|
||||
final arguments = call.arguments as Map;
|
||||
expect(
|
||||
jsonDecode(arguments['request_json'] as String),
|
||||
autoplayTasteFixtureRequest(plays),
|
||||
);
|
||||
called = true;
|
||||
return jsonEncode(_model(expected));
|
||||
});
|
||||
expect(
|
||||
_model(await trainAutoplayTasteInBackground(plays)),
|
||||
_model(expected),
|
||||
);
|
||||
expect(called, isTrue);
|
||||
},
|
||||
);
|
||||
|
||||
test('missing native host retains isolated compatibility trainer', () async {
|
||||
final plays = autoplayTasteFixture(12);
|
||||
expect(
|
||||
_model(await trainAutoplayTasteInBackground(plays)),
|
||||
_model(trainAutoplayTaste(plays)),
|
||||
);
|
||||
});
|
||||
|
||||
test('native errors are not silently retrained by Dart', () async {
|
||||
messenger.setMockMethodCallHandler(channel, (_) async {
|
||||
throw PlatformException(code: 'data_job_error', message: 'cancelled');
|
||||
});
|
||||
await expectLater(
|
||||
trainAutoplayTasteInBackground([]),
|
||||
throwsA(isA<PlatformException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('invalid native vectors are rejected', () async {
|
||||
messenger.setMockMethodCallHandler(
|
||||
channel,
|
||||
(_) async => jsonEncode({
|
||||
'tokens': ['artist:a'],
|
||||
'vectors': [0.0],
|
||||
'positives': 1,
|
||||
'through': 1,
|
||||
}),
|
||||
);
|
||||
await expectLater(
|
||||
trainAutoplayTasteInBackground([]),
|
||||
throwsA(isA<FormatException>()),
|
||||
);
|
||||
});
|
||||
|
||||
final enabled =
|
||||
Platform.environment[desktopBackendLibraryEnvironmentKey]?.isNotEmpty ??
|
||||
false;
|
||||
group('actual native autoplay taste', () {
|
||||
late Directory directory;
|
||||
setUpAll(() async {
|
||||
directory = await Directory.systemTemp.createTemp('mornye-taste-ffi-');
|
||||
debugDesktopPlatformOverride = true;
|
||||
RustFfiBackend.debugShared = RustFfiBackend(
|
||||
openTransport: FfiBackendTransport.open,
|
||||
loadConfig: () async => DesktopBackendConfig(
|
||||
appSupportDir: directory.path,
|
||||
documentsDir: directory.path,
|
||||
tempDir: directory.path,
|
||||
),
|
||||
);
|
||||
});
|
||||
tearDownAll(() async {
|
||||
RustFfiBackend.debugShared = null;
|
||||
debugDesktopPlatformOverride = null;
|
||||
await directory.delete(recursive: true);
|
||||
});
|
||||
for (final count in [-1, 0, 12, 500]) {
|
||||
test('training fixture $count matches Dart baseline', () async {
|
||||
final plays = count < 0
|
||||
? autoplayTasteEdgeFixture()
|
||||
: autoplayTasteFixture(count);
|
||||
final baseline = trainAutoplayTaste(plays);
|
||||
final raw = await PlatformBridge.runNativeDataJob(
|
||||
autoplayTasteFixtureRequest(plays),
|
||||
);
|
||||
expect(raw['tokens'], baseline.tokens);
|
||||
final actual = await trainAutoplayTasteInBackground(plays);
|
||||
expect(actual.tokens, baseline.tokens);
|
||||
expect(actual.positives, baseline.positives);
|
||||
expect(actual.through, baseline.through);
|
||||
expect(actual.vectors.length, baseline.vectors.length);
|
||||
for (var i = 0; i < actual.vectors.length; i++) {
|
||||
expect(
|
||||
actual.vectors[i],
|
||||
closeTo(baseline.vectors[i], 1e-6),
|
||||
reason: 'vector $i',
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}, skip: !enabled);
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mornye/services/backend/ffi_backend_transport.dart';
|
||||
import 'package:mornye/services/backend/rust_ffi_backend.dart';
|
||||
import 'package:mornye/services/lyrics_ai_client.dart';
|
||||
import 'package:mornye/services/native_file_hash.dart';
|
||||
import 'package:mornye/services/platform_bridge.dart';
|
||||
import 'package:mornye/utils/desktop_platform.dart';
|
||||
|
||||
Map<String, Object?> _lines(Map<int, LyricsAiLine> lines) => {
|
||||
for (final entry in lines.entries)
|
||||
'${entry.key}': {
|
||||
'text': entry.value.text,
|
||||
'romanization': entry.value.romanization,
|
||||
'alignment': entry.value.alignment
|
||||
.map((chunk) => chunk.toJson())
|
||||
.toList(),
|
||||
'romanizationAlignment': entry.value.romanizationAlignment
|
||||
.map((chunk) => chunk.toJson())
|
||||
.toList(),
|
||||
},
|
||||
};
|
||||
|
||||
/// Run against a freshly built desktop library with MORNYE_DESKTOP_LIB set.
|
||||
/// Unlike mock channel tests, these cases cross the actual Dart C ABI worker.
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
final enabled =
|
||||
Platform.environment[desktopBackendLibraryEnvironmentKey]?.isNotEmpty ??
|
||||
false;
|
||||
|
||||
group('actual Rust backend migration', () {
|
||||
late Directory root;
|
||||
|
||||
setUpAll(() async {
|
||||
root = await Directory.systemTemp.createTemp('mornye-migration-ffi-');
|
||||
debugDesktopPlatformOverride = true;
|
||||
RustFfiBackend.debugShared = RustFfiBackend(
|
||||
openTransport: FfiBackendTransport.open,
|
||||
loadConfig: () async => DesktopBackendConfig(
|
||||
appSupportDir: root.path,
|
||||
documentsDir: root.path,
|
||||
tempDir: root.path,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
tearDownAll(() async {
|
||||
RustFfiBackend.debugShared = null;
|
||||
debugDesktopPlatformOverride = null;
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
|
||||
test('translation reply matches Dart compatibility semantics', () async {
|
||||
final replies = <String>[
|
||||
'[{"id":1,"text":"First"},{"id":2,"translation":"Second"}]',
|
||||
'<think>discard reasoning</think>\n```json\n'
|
||||
'{"lines":[{"id":1,"text":" Hello "}]}\n```',
|
||||
'Here is the result: [{"id":1,"text":"Hello"}] Done.',
|
||||
'{"z":[{"id":1,"text":"First list"}],'
|
||||
'"a":[{"id":1,"text":"Wrong list"}]}',
|
||||
'{"lines":null,"translations":[{"id":1,"text":"Fallback"}]}',
|
||||
'[{"id":"0x1","text":"Hex"},{"id":2.9,"text":"Fraction"},'
|
||||
'{"id":"3","text":"Third"},{"id":3,"text":"Duplicate"},'
|
||||
'{"id":999,"text":"Unknown"},{"id":1,"text":"Later"}]',
|
||||
'[{"id":1,"text":" "},{"id":1,"text":"Usable"}]',
|
||||
jsonEncode({
|
||||
'lines': [
|
||||
{
|
||||
'id': 1,
|
||||
'text': 'Hello world',
|
||||
'alignment': [
|
||||
[0, 'Hello '],
|
||||
[1, 'world'],
|
||||
],
|
||||
'romanization': 'Konnichiwa',
|
||||
'romanizationAlignment': [
|
||||
{'source': 0, 'text': 'Konnichiwa'},
|
||||
],
|
||||
},
|
||||
{
|
||||
'id': 2,
|
||||
'text': 'Still usable',
|
||||
'alignment': [
|
||||
[0, 'Does not match'],
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
jsonEncode([
|
||||
{
|
||||
'id': 1,
|
||||
'text': '😀' * 2001,
|
||||
'alignment': [
|
||||
[0, '😀' * 2001],
|
||||
],
|
||||
},
|
||||
{'id': 2, 'text': '\uFEFF hello \uFEFF'},
|
||||
]),
|
||||
'[]',
|
||||
];
|
||||
for (final reply in replies) {
|
||||
// This direct call makes a missing/stale native job fail instead of
|
||||
// allowing the compatibility parser to make the test pass.
|
||||
final native = await PlatformBridge.runNativeDataJob({
|
||||
'operation': 'parse_lyrics_translation_reply',
|
||||
'ids': [1, 2, 3],
|
||||
}, bytes: utf8.encode(reply));
|
||||
expect(native['lines'], isA<List<dynamic>>(), reason: reply);
|
||||
final expected = parseLyricsTranslationReply(reply, {1, 2, 3});
|
||||
final actual = await parseLyricsTranslationReplyInBackground(reply, {
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
});
|
||||
expect(_lines(actual), _lines(expected), reason: reply);
|
||||
expect(actual.keys.toList(), expected.keys.toList(), reason: reply);
|
||||
}
|
||||
});
|
||||
|
||||
test('invalid reply remains a typed error', () async {
|
||||
for (final reply in ['not JSON', '{}', 'null', '{"lines":false}']) {
|
||||
await expectLater(
|
||||
parseLyricsTranslationReplyInBackground(reply, {1}),
|
||||
throwsA(
|
||||
isA<LyricsAiException>().having(
|
||||
(error) => error.kind,
|
||||
'kind',
|
||||
LyricsAiErrorKind.badResponse,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('native file hashes preserve streamed digest', () async {
|
||||
final bytes = List<int>.generate(200000, (index) => index % 251);
|
||||
final file = await File('${root.path}/hash.bin').writeAsBytes(bytes);
|
||||
final native = await PlatformBridge.runNativeDataJob({
|
||||
'operation': 'hash_file',
|
||||
'path': file.path,
|
||||
});
|
||||
expect(native['sha256'], sha256.convert(bytes).toString());
|
||||
expect(await hashFileSha256(file.path), native['sha256']);
|
||||
});
|
||||
}, skip: !enabled);
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mornye/services/backend/ffi_backend_transport.dart';
|
||||
import 'package:mornye/services/backend/rust_ffi_backend.dart';
|
||||
import 'package:mornye/services/cache_maintenance_service.dart';
|
||||
import 'package:mornye/services/cover_cache_manager.dart';
|
||||
import 'package:mornye/services/platform_bridge.dart';
|
||||
import 'package:mornye/utils/desktop_platform.dart';
|
||||
|
||||
import 'support/directory_stats_reference.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
const channel = MethodChannel('com.zarz.mornye/backend');
|
||||
const paths = MethodChannel('plugins.flutter.io/path_provider');
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
late Directory root;
|
||||
setUp(() async {
|
||||
root = await Directory.systemTemp.createTemp('directory-stats-');
|
||||
});
|
||||
tearDown(() async {
|
||||
messenger.setMockMethodCallHandler(channel, null);
|
||||
messenger.setMockMethodCallHandler(paths, null);
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
|
||||
test(
|
||||
'native statistics receive a path and link policy without reading Dart files',
|
||||
() async {
|
||||
var calls = 0;
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
expect(call.method, 'runNativeDataJob');
|
||||
final request = jsonDecode(
|
||||
(call.arguments as Map)['request_json'] as String,
|
||||
);
|
||||
expect(request, {
|
||||
'operation': 'directory_stats',
|
||||
'path': root.absolute.path,
|
||||
'follow_links': false,
|
||||
});
|
||||
calls++;
|
||||
return {'file_count': 12, 'total_size_bytes': 345};
|
||||
});
|
||||
final actual = await CacheMaintenanceService.scanDirectory(root);
|
||||
expect(actual.fileCount, 12);
|
||||
expect(actual.totalSizeBytes, 345);
|
||||
expect(calls, 1);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'cover cache shares the native scan and retains link-following policy',
|
||||
() async {
|
||||
messenger.setMockMethodCallHandler(paths, (_) async => root.path);
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
expect(call.method, 'runNativeDataJob');
|
||||
final request = jsonDecode(
|
||||
(call.arguments as Map)['request_json'] as String,
|
||||
);
|
||||
expect(request, {
|
||||
'operation': 'directory_stats',
|
||||
'path': '${root.absolute.path}/cover_cache',
|
||||
'follow_links': true,
|
||||
});
|
||||
return {'file_count': 2, 'total_size_bytes': 10};
|
||||
});
|
||||
final actual = await CoverCacheManager.getStats();
|
||||
expect(actual.fileCount, 2);
|
||||
expect(actual.totalSizeBytes, 10);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'missing plugin uses isolated traversal with unchanged counts',
|
||||
() async {
|
||||
await createDirectoryStatsFixture(root, 100);
|
||||
for (final follow in [false, true]) {
|
||||
final expected = await scanDirectoryReference(
|
||||
root,
|
||||
followLinks: follow,
|
||||
);
|
||||
final actual = await CacheMaintenanceService.scanDirectory(
|
||||
root,
|
||||
followLinks: follow,
|
||||
);
|
||||
expect(actual.fileCount, expected.fileCount);
|
||||
expect(actual.totalSizeBytes, expected.totalSizeBytes);
|
||||
}
|
||||
final missing = await CacheMaintenanceService.scanDirectory(
|
||||
Directory('${root.path}/missing'),
|
||||
);
|
||||
expect(missing.fileCount, 0);
|
||||
expect(missing.totalSizeBytes, 0);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'symlink policy and cycles match the original traversal',
|
||||
() async {
|
||||
await Directory('${root.path}/nested').create();
|
||||
await File('${root.path}/nested/file').writeAsString('123');
|
||||
await Link('${root.path}/alias').create('${root.path}/nested');
|
||||
await Link('${root.path}/file-link').create('${root.path}/nested/file');
|
||||
await Link('${root.path}/nested/cycle').create(root.path);
|
||||
await Link('${root.path}/dangling').create('${root.path}/absent');
|
||||
for (final follow in [false, true]) {
|
||||
final expected = await scanDirectoryReference(
|
||||
root,
|
||||
followLinks: follow,
|
||||
);
|
||||
final actual = await CacheMaintenanceService.scanDirectory(
|
||||
root,
|
||||
followLinks: follow,
|
||||
);
|
||||
expect(actual.fileCount, expected.fileCount);
|
||||
expect(actual.totalSizeBytes, expected.totalSizeBytes);
|
||||
}
|
||||
},
|
||||
skip: Platform.isWindows
|
||||
? 'Creating symlinks requires Windows developer permissions'
|
||||
: false,
|
||||
);
|
||||
|
||||
test(
|
||||
'native errors are not hidden by the Dart compatibility route',
|
||||
() async {
|
||||
messenger.setMockMethodCallHandler(
|
||||
channel,
|
||||
(_) async => throw PlatformException(code: 'CANCELLED'),
|
||||
);
|
||||
await expectLater(
|
||||
CacheMaintenanceService.scanDirectory(root),
|
||||
throwsA(
|
||||
isA<PlatformException>().having(
|
||||
(error) => error.code,
|
||||
'code',
|
||||
'CANCELLED',
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
for (final invalid in [
|
||||
<String, Object>{},
|
||||
{'file_count': -1, 'total_size_bytes': 0},
|
||||
{'file_count': 0, 'total_size_bytes': -1},
|
||||
{'file_count': 1.5, 'total_size_bytes': 1},
|
||||
{'file_count': 1, 'total_size_bytes': '1'},
|
||||
]) {
|
||||
test('rejects malformed native statistics: $invalid', () async {
|
||||
messenger.setMockMethodCallHandler(channel, (_) async => invalid);
|
||||
await expectLater(
|
||||
CacheMaintenanceService.scanDirectory(root),
|
||||
throwsStateError,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
final enabled =
|
||||
Platform.environment[desktopBackendLibraryEnvironmentKey]?.isNotEmpty ??
|
||||
false;
|
||||
group('actual native directory statistics', () {
|
||||
late Directory support;
|
||||
setUpAll(() async {
|
||||
support = await Directory.systemTemp.createTemp('mornye-stats-ffi-');
|
||||
debugDesktopPlatformOverride = true;
|
||||
RustFfiBackend.debugShared = RustFfiBackend(
|
||||
openTransport: FfiBackendTransport.open,
|
||||
loadConfig: () async => DesktopBackendConfig(
|
||||
appSupportDir: support.path,
|
||||
documentsDir: support.path,
|
||||
tempDir: support.path,
|
||||
),
|
||||
);
|
||||
});
|
||||
tearDownAll(() async {
|
||||
RustFfiBackend.debugShared = null;
|
||||
debugDesktopPlatformOverride = null;
|
||||
await support.delete(recursive: true);
|
||||
});
|
||||
|
||||
Future<void> checkParity(Directory directory) async {
|
||||
for (final follow in [false, true]) {
|
||||
final expected = await scanDirectoryReference(
|
||||
directory,
|
||||
followLinks: follow,
|
||||
);
|
||||
final raw = await PlatformBridge.runNativeDataJob({
|
||||
'operation': 'directory_stats',
|
||||
'path': directory.absolute.path,
|
||||
'follow_links': follow,
|
||||
});
|
||||
expect(raw, {
|
||||
'file_count': expected.fileCount,
|
||||
'total_size_bytes': expected.totalSizeBytes,
|
||||
});
|
||||
final actual = await CacheMaintenanceService.scanDirectory(
|
||||
directory,
|
||||
followLinks: follow,
|
||||
);
|
||||
expect(actual.fileCount, expected.fileCount);
|
||||
expect(actual.totalSizeBytes, expected.totalSizeBytes);
|
||||
}
|
||||
}
|
||||
|
||||
test('nested and empty directories match the original Dart scan', () async {
|
||||
await checkParity(root);
|
||||
await createDirectoryStatsFixture(root, 100);
|
||||
await checkParity(root);
|
||||
});
|
||||
|
||||
test('missing and regular-file roots retain zero statistics', () async {
|
||||
await checkParity(Directory('${root.path}/missing'));
|
||||
await File('${root.path}/file').writeAsString('123');
|
||||
await checkParity(Directory('${root.path}/file'));
|
||||
});
|
||||
|
||||
test(
|
||||
'directory aliases cycles dangling links and root links preserve counts',
|
||||
() async {
|
||||
await Directory('${root.path}/contents/nested').create(recursive: true);
|
||||
final contents = Directory('${root.path}/contents');
|
||||
await File('${contents.path}/nested/file').writeAsString('123');
|
||||
await Link('${contents.path}/alias').create('${contents.path}/nested');
|
||||
await Link(
|
||||
'${contents.path}/file-link',
|
||||
).create('${contents.path}/nested/file');
|
||||
await Link('${contents.path}/nested/cycle').create(contents.path);
|
||||
await Link(
|
||||
'${contents.path}/dangling',
|
||||
).create('${contents.path}/absent');
|
||||
await Link('${root.path}/root-link').create(contents.path);
|
||||
final baseline = await scanDirectoryReference(
|
||||
contents,
|
||||
followLinks: true,
|
||||
);
|
||||
expect(baseline.fileCount, 8);
|
||||
expect(baseline.totalSizeBytes, 24);
|
||||
await checkParity(contents);
|
||||
await checkParity(Directory('${root.path}/root-link'));
|
||||
},
|
||||
skip: Platform.isWindows
|
||||
? 'Creating symlinks requires Windows developer permissions'
|
||||
: false,
|
||||
);
|
||||
}, skip: !enabled);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mornye/services/native_file_hash.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
const channel = MethodChannel('com.zarz.mornye/backend');
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
late Directory directory;
|
||||
|
||||
setUp(() async {
|
||||
directory = await Directory.systemTemp.createTemp('native-file-hash-');
|
||||
});
|
||||
tearDown(() async {
|
||||
messenger.setMockMethodCallHandler(channel, null);
|
||||
await directory.delete(recursive: true);
|
||||
});
|
||||
|
||||
test(
|
||||
'sends the path to the worker without opening the file in Dart',
|
||||
() async {
|
||||
final digest = sha256.convert([1, 2, 3]).toString();
|
||||
final path = '${directory.path}/native-only.file';
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
expect(call.method, 'runNativeDataJob');
|
||||
final arguments = call.arguments as Map;
|
||||
expect(jsonDecode(arguments['request_json'] as String), {
|
||||
'operation': 'hash_file',
|
||||
'path': path,
|
||||
});
|
||||
expect(arguments.containsKey('bytes'), isFalse);
|
||||
return {'sha256': digest};
|
||||
});
|
||||
expect(await hashFileSha256(path), digest);
|
||||
expect(await File(path).exists(), isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test('unsupported hosts stream empty and multichunk files', () async {
|
||||
messenger.setMockMethodCallHandler(channel, (_) async {
|
||||
throw MissingPluginException();
|
||||
});
|
||||
for (final bytes in [
|
||||
<int>[],
|
||||
List<int>.generate(1024 * 1024 + 7, (index) => index % 256),
|
||||
]) {
|
||||
final file = await File('${directory.path}/input').writeAsBytes(bytes);
|
||||
expect(await hashFileSha256(file.path), sha256.convert(bytes).toString());
|
||||
}
|
||||
await expectLater(
|
||||
hashFileSha256('${directory.path}/missing'),
|
||||
throwsA(isA<FileSystemException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('native failure or cancellation never falls back to Dart', () async {
|
||||
final file = await File('${directory.path}/input').writeAsString('valid');
|
||||
for (final code in ['ERROR', 'CANCELLED', 'backend_unavailable']) {
|
||||
messenger.setMockMethodCallHandler(channel, (_) async {
|
||||
throw PlatformException(code: code, message: 'Cannot hash file');
|
||||
});
|
||||
await expectLater(
|
||||
hashFileSha256(file.path),
|
||||
throwsA(isA<PlatformException>().having((e) => e.code, 'code', code)),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test(
|
||||
'malformed native digests fail closed even when a file exists',
|
||||
() async {
|
||||
final file = await File('${directory.path}/input').writeAsString('valid');
|
||||
for (final value in [null, 1, '', 'abcdef', 'A' * 64, '0' * 65]) {
|
||||
messenger.setMockMethodCallHandler(
|
||||
channel,
|
||||
(_) async => {'sha256': value},
|
||||
);
|
||||
await expectLater(
|
||||
hashFileSha256(file.path),
|
||||
throwsA(isA<FormatException>()),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart';
|
||||
import 'package:mornye/services/lyrics_ai_client.dart';
|
||||
|
||||
Map<String, dynamic> _line(
|
||||
int id,
|
||||
String text, {
|
||||
String? romanization,
|
||||
List<Map<String, Object>> alignment = const [],
|
||||
List<Map<String, Object>> romanizationAlignment = const [],
|
||||
}) => {
|
||||
'id': id,
|
||||
'text': text,
|
||||
'romanization': romanization,
|
||||
'alignment': alignment,
|
||||
'romanizationAlignment': romanizationAlignment,
|
||||
};
|
||||
|
||||
List<Map<String, dynamic>> _dto(Map<int, LyricsAiLine> lines) => [
|
||||
for (final entry in lines.entries)
|
||||
_line(
|
||||
entry.key,
|
||||
entry.value.text,
|
||||
romanization: entry.value.romanization,
|
||||
alignment: entry.value.alignment.map((chunk) => chunk.toJson()).toList(),
|
||||
romanizationAlignment: entry.value.romanizationAlignment
|
||||
.map((chunk) => chunk.toJson())
|
||||
.toList(),
|
||||
),
|
||||
];
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
const channel = MethodChannel('com.zarz.mornye/backend');
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
tearDown(() => messenger.setMockMethodCallHandler(channel, null));
|
||||
|
||||
final fixtures =
|
||||
(jsonDecode(
|
||||
File(
|
||||
'test/fixtures/native_lyrics_translation_replies.json',
|
||||
).readAsStringSync(),
|
||||
)
|
||||
as List)
|
||||
.cast<Map<String, dynamic>>();
|
||||
for (final fixture in fixtures) {
|
||||
test('shared parser contract: ${fixture['name']}', () async {
|
||||
final request = fixture['request'] as Map;
|
||||
final reply = request['reply'] as String;
|
||||
final ids = (request['ids'] as List).cast<int>().toSet();
|
||||
final expected = fixture['expected'] as Map;
|
||||
if (expected['error'] != null) {
|
||||
final matcher = throwsA(
|
||||
isA<LyricsAiException>().having(
|
||||
(error) => error.kind,
|
||||
'kind',
|
||||
LyricsAiErrorKind.badResponse,
|
||||
),
|
||||
);
|
||||
expect(() => parseLyricsTranslationReply(reply, ids), matcher);
|
||||
await expectLater(
|
||||
parseLyricsTranslationReplyInBackground(reply, ids),
|
||||
matcher,
|
||||
);
|
||||
messenger.setMockMethodCallHandler(
|
||||
channel,
|
||||
(_) async => jsonEncode(expected),
|
||||
);
|
||||
await expectLater(
|
||||
parseLyricsTranslationReplyInBackground(reply, ids),
|
||||
matcher,
|
||||
);
|
||||
} else {
|
||||
expect(
|
||||
_dto(parseLyricsTranslationReply(reply, ids)),
|
||||
expected['lines'],
|
||||
);
|
||||
expect(
|
||||
_dto(await parseLyricsTranslationReplyInBackground(reply, ids)),
|
||||
expected['lines'],
|
||||
);
|
||||
messenger.setMockMethodCallHandler(
|
||||
channel,
|
||||
(_) async => jsonEncode(expected),
|
||||
);
|
||||
expect(
|
||||
_dto(await parseLyricsTranslationReplyInBackground(reply, ids)),
|
||||
expected['lines'],
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test(
|
||||
'translation client sends only reply bytes and requested ids to Rust',
|
||||
() async {
|
||||
const reply = 'provider output parsed only by the native worker';
|
||||
final expected = [
|
||||
_line(
|
||||
7,
|
||||
'Hello world',
|
||||
romanization: 'konnichiwa',
|
||||
alignment: [
|
||||
{'text': 'Hello ', 'source': 0},
|
||||
{'text': 'world', 'source': 1},
|
||||
],
|
||||
romanizationAlignment: [
|
||||
{'text': 'konnichiwa', 'source': 0},
|
||||
],
|
||||
),
|
||||
];
|
||||
var nativeCalls = 0;
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
expect(call.method, 'runNativeDataJob');
|
||||
final args = call.arguments as Map;
|
||||
expect(jsonDecode(args['request_json'] as String), {
|
||||
'operation': 'parse_lyrics_translation_reply',
|
||||
'ids': [7, 9],
|
||||
});
|
||||
expect(args['bytes'] as Uint8List, utf8.encode(reply));
|
||||
nativeCalls++;
|
||||
return jsonEncode({'lines': expected});
|
||||
});
|
||||
final client = LyricsAiClient(
|
||||
const LyricsAiConfig(
|
||||
provider: LyricsAiProvider.custom,
|
||||
model: 'test-model',
|
||||
apiKey: 'never-forward-this-key',
|
||||
baseUrl: 'https://translator.example/v1',
|
||||
),
|
||||
client: MockClient((_) async {
|
||||
return http.Response(
|
||||
jsonEncode({
|
||||
'choices': [
|
||||
{
|
||||
'message': {'content': reply},
|
||||
'finish_reason': 'stop',
|
||||
},
|
||||
],
|
||||
}),
|
||||
200,
|
||||
);
|
||||
}),
|
||||
);
|
||||
addTearDown(client.close);
|
||||
|
||||
final actual = await client.translate(const [
|
||||
LyricsAiItem(7, 'original line'),
|
||||
LyricsAiItem(9, 'missing translation'),
|
||||
], systemPrompt: 'private preference');
|
||||
expect(_dto(actual), expected);
|
||||
expect(nativeCalls, 1);
|
||||
expect(() => actual[7]!.alignment.clear(), throwsUnsupportedError);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'missing native plugin preserves compatibility parsing and alignment',
|
||||
() async {
|
||||
const reply = '''<think>omit these notes</think>
|
||||
```json
|
||||
{"lines":[{"id":"7","text":" Hello world ","romanization":" hi ","alignment":[[0,"Hello "],[1,"world"]],"romanizationAlignment":[[0,"hi"]]},
|
||||
{"id":7,"text":"duplicate"},{"id":9,"text":" "},{"id":99,"text":"unknown"}]}
|
||||
```''';
|
||||
final expected = parseLyricsTranslationReply(reply, {7, 9});
|
||||
expect(
|
||||
_dto(await parseLyricsTranslationReplyInBackground(reply, {7, 9})),
|
||||
_dto(expected),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('native parse rejection maps to the existing typed error', () async {
|
||||
messenger.setMockMethodCallHandler(channel, (_) async {
|
||||
return jsonEncode({
|
||||
'error': 'badResponse',
|
||||
'detail': 'reply is not a JSON list',
|
||||
});
|
||||
});
|
||||
await expectLater(
|
||||
parseLyricsTranslationReplyInBackground('[{"id":7,"text":"valid"}]', {7}),
|
||||
throwsA(
|
||||
isA<LyricsAiException>()
|
||||
.having(
|
||||
(error) => error.kind,
|
||||
'kind',
|
||||
LyricsAiErrorKind.badResponse,
|
||||
)
|
||||
.having(
|
||||
(error) => error.detail,
|
||||
'detail',
|
||||
'reply is not a JSON list',
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'native system failures propagate instead of rerunning Dart parsing',
|
||||
() async {
|
||||
final failure = PlatformException(
|
||||
code: 'CANCELLED',
|
||||
message: 'cancelled',
|
||||
);
|
||||
messenger.setMockMethodCallHandler(channel, (_) async => throw failure);
|
||||
await expectLater(
|
||||
parseLyricsTranslationReplyInBackground('[{"id":7,"text":"valid"}]', {
|
||||
7,
|
||||
}),
|
||||
throwsA(
|
||||
isA<PlatformException>().having(
|
||||
(error) => error.code,
|
||||
'code',
|
||||
'CANCELLED',
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
for (final malformed in [
|
||||
<String, Object>{},
|
||||
{'lines': 'invalid'},
|
||||
{
|
||||
'lines': [false],
|
||||
},
|
||||
{
|
||||
'lines': [_line(99, 'unexpected id')],
|
||||
},
|
||||
{
|
||||
'lines': [_line(7, 'one'), _line(7, 'duplicate')],
|
||||
},
|
||||
{
|
||||
'lines': [
|
||||
{..._line(7, 'text'), 'alignment': false},
|
||||
],
|
||||
},
|
||||
{
|
||||
'lines': [
|
||||
{..._line(7, 'text'), 'romanization': 1},
|
||||
],
|
||||
},
|
||||
]) {
|
||||
test(
|
||||
'malformed native DTO remains a typed response error: $malformed',
|
||||
() async {
|
||||
messenger.setMockMethodCallHandler(
|
||||
channel,
|
||||
(_) async => jsonEncode(malformed),
|
||||
);
|
||||
await expectLater(
|
||||
parseLyricsTranslationReplyInBackground('reply', {7}),
|
||||
throwsA(
|
||||
isA<LyricsAiException>().having(
|
||||
(error) => error.kind,
|
||||
'kind',
|
||||
LyricsAiErrorKind.badResponse,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import 'package:mornye/services/autoplay_personalization.dart';
|
||||
import 'package:mornye/services/autoplay_taste.dart';
|
||||
|
||||
/// Deterministic, bounded histories for native parity and full-route timings.
|
||||
List<AutoplayTastePlay> autoplayTasteFixture(int count) {
|
||||
final start = DateTime.utc(2026, 1, 1);
|
||||
return [
|
||||
for (var i = 0; i < count; i++)
|
||||
AutoplayTastePlay(
|
||||
id: i + 1,
|
||||
song:
|
||||
'artist ${(i * 17 + i ~/ 13) % 192 ~/ 8}|song ${(i * 17 + i ~/ 13) % 192}',
|
||||
artist: 'artist ${(i * 17 + i ~/ 13) % 192 ~/ 8}',
|
||||
at: start.add(Duration(hours: (i ~/ 24) * 3, minutes: (i % 24) * 4)),
|
||||
kind: i % 29 == 0
|
||||
? AutoplayFeedbackKind.loved
|
||||
: i % 23 == 0
|
||||
? AutoplayFeedbackKind.playlisted
|
||||
: i % 11 == 0
|
||||
? AutoplayFeedbackKind.skipped
|
||||
: i % 17 == 0
|
||||
? AutoplayFeedbackKind.replayed
|
||||
: AutoplayFeedbackKind.listened,
|
||||
reward: i % 11 == 0 ? 0.1 : 0.7 + (i % 4) * 0.1,
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/// Includes session boundaries, backwards feedback times and UTF-16 ordering.
|
||||
List<AutoplayTastePlay> autoplayTasteEdgeFixture() {
|
||||
final start = DateTime.utc(2026, 1, 1);
|
||||
final events = <(String, int, AutoplayFeedbackKind, double)>[
|
||||
('𐐀', 0, AutoplayFeedbackKind.listened, 1),
|
||||
('𐐀', 1000000, AutoplayFeedbackKind.replayed, 1),
|
||||
('\uE000', 600000000, AutoplayFeedbackKind.listened, 0.7),
|
||||
('𐐀', 500000000, AutoplayFeedbackKind.loved, 1),
|
||||
('𐐀', 2400000000, AutoplayFeedbackKind.listened, 1),
|
||||
('\uE000', 2400000001, AutoplayFeedbackKind.skipped, 0.1),
|
||||
('𐐀', 4200000002, AutoplayFeedbackKind.listened, 0.8),
|
||||
('\uE000', 4200000003, AutoplayFeedbackKind.listened, 1),
|
||||
('', 4200000004, AutoplayFeedbackKind.listened, 1),
|
||||
('𐐀', 4200000005, AutoplayFeedbackKind.playlisted, 1),
|
||||
('', 4200000006, AutoplayFeedbackKind.skipped, 0.5),
|
||||
('\uE000', 4200000007, AutoplayFeedbackKind.listened, 1),
|
||||
('', 4200000008, AutoplayFeedbackKind.listened, 1),
|
||||
];
|
||||
return [
|
||||
for (final (i, event) in events.indexed)
|
||||
AutoplayTastePlay(
|
||||
id: i + 1,
|
||||
song: '${event.$1}|same',
|
||||
artist: event.$1,
|
||||
at: start.add(Duration(microseconds: event.$2)),
|
||||
kind: event.$3,
|
||||
reward: event.$4,
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
Map<String, dynamic> autoplayTasteFixtureRequest(
|
||||
List<AutoplayTastePlay> plays,
|
||||
) => {
|
||||
'operation': 'train_autoplay_taste',
|
||||
'plays': [
|
||||
for (final play in plays)
|
||||
{
|
||||
'id': play.id,
|
||||
'song': play.song,
|
||||
'artist': play.artist,
|
||||
'atMicros': play.at.microsecondsSinceEpoch,
|
||||
'kind': play.kind.name,
|
||||
'reward': play.reward,
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,38 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:mornye/services/cache_maintenance_service.dart';
|
||||
|
||||
/// Original Dart traversal retained for parity and paired performance checks.
|
||||
Future<DirectoryStats> scanDirectoryReference(
|
||||
Directory directory, {
|
||||
bool followLinks = false,
|
||||
}) async {
|
||||
if (!await directory.exists()) {
|
||||
return const DirectoryStats(fileCount: 0, totalSizeBytes: 0);
|
||||
}
|
||||
var fileCount = 0;
|
||||
var totalSize = 0;
|
||||
try {
|
||||
await for (final entity in directory.list(
|
||||
recursive: true,
|
||||
followLinks: followLinks,
|
||||
)) {
|
||||
if (entity is File) {
|
||||
fileCount++;
|
||||
totalSize += await entity.length();
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
return DirectoryStats(fileCount: fileCount, totalSizeBytes: totalSize);
|
||||
}
|
||||
|
||||
Future<void> createDirectoryStatsFixture(Directory root, int count) async {
|
||||
for (var folder = 0; folder < 10; folder++) {
|
||||
await Directory('${root.path}/$folder').create(recursive: true);
|
||||
}
|
||||
for (var i = 0; i < count; i++) {
|
||||
await File(
|
||||
'${root.path}/${i % 10}/file-$i',
|
||||
).writeAsBytes(List.filled(i % 256, i % 256));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user