import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:crypto/crypto.dart'; import 'package:cutdex/errors/app_failure.dart'; import 'package:cutdex/integrations/runtime/processing_resource_repository.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:cutdex/integrations/runtime/processing_resource_state.dart'; void main() { test('disposing the resource owner cancels a pending subtitle bundle without late notifications', () async { final fixture = await _subtitleFixture(); var disposed = false; await expectLater( fixture.repository.ensureSubtitleResources( onProgress: (_, _) { if (!disposed) { disposed = true; fixture.repository.dispose(); } }, ), throwsA(isA()), ); expect(fixture.requests, isEmpty); }); test( 'resource snapshots freeze installed states and observe bundle completion', () async { final fixture = await _subtitleFixture(); final container = ProviderContainer(); addTearDown(container.dispose); final provider = processingResourcesProvider(fixture.repository); final updates = []; container.listen( provider, (_, next) => updates.add(next), fireImmediately: true, ); final before = container.read(provider); await fixture.repository.ensureSubtitleResources(onProgress: (_, _) {}); final after = container.read(provider); expect(updates.any((value) => value.subtitleDownloading), isTrue); expect(after.subtitleDownloading, isFalse); expect(after.subtitleDownloadedBytes, after.subtitleTotalBytes); expect( after.installs.every( (value) => value.state == ProcessingResourceState.installed, ), isTrue, ); expect( before.installs.any( (value) => value.state == ProcessingResourceState.installed, ), isFalse, ); }, ); test( 'subtitle bundle downloads both models with one monotonic byte progress', () async { final fixture = await _subtitleFixture(); final reports = <(ProcessingCapability, double)>[]; expect(fixture.repository.subtitleTotalBytes, 80); await fixture.repository.ensureSubtitleResources( onProgress: (stage, progress) { reports.add((stage, progress)); if (stage == ProcessingCapability.translation && progress == .25) { expect(fixture.repository.subtitleDownloadedBytes, 20); expect(fixture.repository.subtitleDownloading, isTrue); } }, ); expect(fixture.repository.subtitleDownloading, isFalse); expect(fixture.requests, ['transcription', 'translation']); expect(reports.first.$2, 0); expect(reports.last.$2, 1); expect( reports .where((entry) => entry.$1 == ProcessingCapability.translation) .first .$2, 0.25, ); for (var i = 1; i < reports.length; i++) { expect(reports[i].$2, greaterThanOrEqualTo(reports[i - 1].$2)); } expect( fixture.repository.installs.every( (install) => install.state == ProcessingResourceState.installed, ), isTrue, ); await fixture.repository.ensureSubtitleResources(onProgress: (_, _) {}); expect(fixture.requests, ['transcription', 'translation']); }, ); test( 'subtitle bundle skips configured speech and still installs translation', () async { final fixture = await _subtitleFixture(); final reports = <(ProcessingCapability, double)>[]; await fixture.repository.ensureSubtitleResources( available: {ProcessingCapability.transcription}, onProgress: (stage, progress) => reports.add((stage, progress)), ); expect(fixture.requests, ['translation']); expect(reports.first, (ProcessingCapability.translation, 0.25)); expect(reports.last.$2, 1); }, ); test('pausing a subtitle download keeps its bytes and resumes the same request', () async { final root = await Directory.systemTemp.createTemp('subtitle-pause-'); final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); final firstChunk = List.filled(10, 1); final secondChunk = List.filled(10, 2); final speech = [...firstChunk, ...secondChunk]; final translation = List.filled(5, 3); final requests = []; final releaseSecondChunk = Completer(); final secondChunkSent = Completer(); server.listen((request) async { final name = request.uri.pathSegments.single; requests.add(name); if (name == 'transcription') { request.response.bufferOutput = false; request.response.contentLength = speech.length; request.response.add(firstChunk); await request.response.flush(); await releaseSecondChunk.future; request.response.add(secondChunk); await request.response.flush(); secondChunkSent.complete(); } else { request.response.contentLength = translation.length; request.response.add(translation); } await request.response.close(); }); final repository = ProcessingResourceRepository( root: root, catalog: [ for (final (capability, payload) in [ (ProcessingCapability.transcription, speech), (ProcessingCapability.translation, translation), ]) ProcessingResourcePackage( capability: capability, id: capability.name, version: '1', name: capability.name, description: '', artifacts: [ ProcessingResourceArtifact( path: 'model.bin', url: Uri.parse( 'http://127.0.0.1:${server.port}/${capability.name}', ), sha256: sha256.convert(payload).toString(), bytes: payload.length, ), ], ), ], ); addTearDown(() async { if (!releaseSecondChunk.isCompleted) releaseSecondChunk.complete(); repository.dispose(); await server.close(force: true); await root.delete(recursive: true); }); final paused = Completer(); final progress = []; final download = repository.ensureSubtitleResources( onProgress: (stage, value) { progress.add(value); if (stage == ProcessingCapability.transcription && repository.installFor(stage).downloadedBytes == firstChunk.length && !paused.isCompleted) { paused.complete(); repository.pauseSubtitleResources(); } }, ); await paused.future.timeout( const Duration(seconds: 5), onTimeout: () => throw StateError( 'first chunk was not observed: requests=$requests progress=$progress ' 'install=${repository.installFor(ProcessingCapability.transcription).downloadedBytes}', ), ); expect(repository.subtitlePaused, isTrue); final atPause = progress.last; releaseSecondChunk.complete(); await secondChunkSent.future.timeout( const Duration(seconds: 5), onTimeout: () => throw StateError('server did not send the second chunk'), ); await Future.delayed(const Duration(milliseconds: 30)); expect(progress.last, atPause); expect( repository.installFor(ProcessingCapability.transcription).downloadedBytes, firstChunk.length, ); repository.resumeSubtitleResources(); await download.timeout( const Duration(seconds: 5), onTimeout: () => throw StateError('download did not resume'), ); expect(repository.subtitlePaused, isFalse); expect(requests, ['transcription', 'translation']); expect(progress.last, 1); }); test('download speed remains available without a progress widget', () async { final root = await Directory.systemTemp.createTemp('resource-speed-'); final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); final releaseLastChunk = Completer(); final payload = [ ...List.filled(10, 1), ...List.filled(10, 2), ...List.filled(10, 3), ]; server.listen((request) async { request.response.bufferOutput = false; request.response.contentLength = payload.length; request.response.add(payload.sublist(0, 10)); await request.response.flush(); await Future.delayed(const Duration(milliseconds: 550)); request.response.add(payload.sublist(10, 20)); await request.response.flush(); await releaseLastChunk.future; request.response.add(payload.sublist(20)); await request.response.close(); }); final repository = ProcessingResourceRepository( root: root, catalog: [ ProcessingResourcePackage( capability: ProcessingCapability.backgroundRemoval, id: 'speed-test', version: '1', name: 'Speed test', description: '', artifacts: [ ProcessingResourceArtifact( path: 'model.bin', url: Uri.parse('http://127.0.0.1:${server.port}/model'), sha256: sha256.convert(payload).toString(), bytes: payload.length, ), ], ), ], ); addTearDown(() async { if (!releaseLastChunk.isCompleted) releaseLastChunk.complete(); repository.dispose(); await server.close(force: true); await root.delete(recursive: true); }); final secondChunk = Completer(); repository.addListener(() { if (repository .installFor(ProcessingCapability.backgroundRemoval) .downloadedBytes == 20 && !secondChunk.isCompleted) { secondChunk.complete(); } }); final download = repository.ensureAvailable( ProcessingCapability.backgroundRemoval, ); await secondChunk.future.timeout(const Duration(seconds: 5)); expect( repository.downloadBytesPerSecondFor( ProcessingCapability.backgroundRemoval, ), greaterThan(0), ); repository.pauseDownload(ProcessingCapability.backgroundRemoval); expect( repository.downloadPausedFor(ProcessingCapability.backgroundRemoval), isTrue, ); expect( repository.downloadBytesPerSecondFor( ProcessingCapability.backgroundRemoval, ), 0, ); releaseLastChunk.complete(); await Future.delayed(const Duration(milliseconds: 30)); expect( repository .installFor(ProcessingCapability.backgroundRemoval) .downloadedBytes, 20, ); repository.resumeDownload(ProcessingCapability.backgroundRemoval); await download.timeout(const Duration(seconds: 5)); expect( repository.downloadPausedFor(ProcessingCapability.backgroundRemoval), isFalse, ); expect( repository.downloadBytesPerSecondFor( ProcessingCapability.backgroundRemoval, ), 0, ); }); test( 'cancelling between models stops translation and retry reuses speech', () async { final fixture = await _subtitleFixture(); await expectLater( fixture.repository.ensureSubtitleResources( onProgress: (stage, progress) { if (stage == ProcessingCapability.transcription && fixture.repository.installFor(stage).state == ProcessingResourceState.installed) { fixture.repository.cancelSubtitleResources(); } }, ), throwsA(isA()), ); expect(fixture.requests, ['transcription']); await fixture.repository.ensureSubtitleResources(onProgress: (_, _) {}); expect(fixture.requests, ['transcription', 'translation']); }, ); test( 'cancelling a paused subtitle download releases the pause gate', () async { final fixture = await _subtitleFixture(); final paused = Completer(); final download = fixture.repository.ensureSubtitleResources( onProgress: (stage, progress) { if (stage == ProcessingCapability.transcription && progress == 0 && !paused.isCompleted) { paused.complete(); fixture.repository.pauseSubtitleResources(); } }, ); await paused.future.timeout(const Duration(seconds: 5)); fixture.repository.cancel(ProcessingCapability.transcription); await expectLater( download.timeout(const Duration(seconds: 5)), throwsA(isA()), ); expect(fixture.repository.subtitlePaused, isFalse); }, ); test( 'translation verification failure keeps speech and can be retried', () async { final fixture = await _subtitleFixture(corruptTranslationOnce: true); await expectLater( fixture.repository.ensureSubtitleResources(onProgress: (_, _) {}), throwsA( isA().having( (error) => error.failure.code, 'code', AppErrorCode.resourceChecksumFailed, ), ), ); expect( fixture.repository.installFor(ProcessingCapability.transcription).state, ProcessingResourceState.installed, ); expect( fixture.repository.installFor(ProcessingCapability.translation).state, ProcessingResourceState.failed, ); await fixture.repository.ensureSubtitleResources(onProgress: (_, _) {}); expect(fixture.requests, ['transcription', 'translation', 'translation']); }, ); test( 'downloads, verifies and atomically publishes a processing resource', () async { final root = await Directory.systemTemp.createTemp('cutdex-models-'); final payload = utf8.encode('verified model'); final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); server.listen((request) async { request.response.add(payload); await request.response.close(); }); addTearDown(() async { await server.close(force: true); await root.delete(recursive: true); }); final package = ProcessingResourcePackage( capability: ProcessingCapability.transcription, id: 'test-model', version: '7', name: 'Test', description: 'Test model', artifacts: [ ProcessingResourceArtifact( path: 'model.bin', url: Uri.parse('http://127.0.0.1:${server.port}/model'), sha256: sha256.convert(payload).toString(), bytes: payload.length, ), ], ); final repository = ProcessingResourceRepository( root: root, catalog: [package], ); await repository.ensureAvailable(ProcessingCapability.transcription); expect( repository.installs.single.state, ProcessingResourceState.installed, ); expect( File('${root.path}/Transcription/test-model/7/model.bin') .readAsBytesSync(), payload, ); expect( Directory('${root.path}/Transcription/test-model/7.download') .existsSync(), false, ); }, ); test( 'HTTP download failure retains its status code in the install state', () async { final root = await Directory.systemTemp.createTemp('cutdex-http-error-'); final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); server.listen((request) async { request.response.statusCode = 503; await request.response.close(); }); final repository = ProcessingResourceRepository( root: root, catalog: [ ProcessingResourcePackage( capability: ProcessingCapability.transcription, id: 'http-test', version: '1', name: 'Test', description: 'Test', artifacts: [ ProcessingResourceArtifact( path: 'model.bin', url: Uri.parse('http://127.0.0.1:${server.port}/model'), sha256: List.filled(64, '0').join(), bytes: 1, ), ], ), ], ); addTearDown(() async { repository.dispose(); await server.close(force: true); await root.delete(recursive: true); }); await expectLater( repository.ensureAvailable(ProcessingCapability.transcription), throwsA(isA()), ); final install = repository.installs.single; expect(install.state, ProcessingResourceState.failed); expect(install.error?.code, AppErrorCode.resourceDownloadHttpFailed); expect(install.error?.httpStatusCode, 503); expect(await repository.directoryFor(install.package).exists(), isFalse); }, ); test('does not publish a resource with a mismatched checksum', () async { final root = await Directory.systemTemp.createTemp('cutdex-models-'); final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); server.listen((request) async { request.response.write('corrupt'); await request.response.close(); }); addTearDown(() async { await server.close(force: true); await root.delete(recursive: true); }); final package = ProcessingResourcePackage( capability: ProcessingCapability.transcription, id: 'test-model', version: '1', name: 'Test', description: 'Test model', artifacts: [ ProcessingResourceArtifact( path: 'model.bin', url: Uri.parse('http://127.0.0.1:${server.port}/model'), sha256: List.filled(64, '0').join(), bytes: 7, ), ], ); final repository = ProcessingResourceRepository( root: root, catalog: [package], ); await expectLater( repository.ensureAvailable(ProcessingCapability.transcription), throwsA( isA().having( (error) => error.failure.code, 'code', AppErrorCode.resourceChecksumFailed, ), ), ); expect(repository.installs.single.state, ProcessingResourceState.failed); expect( repository.installs.single.error?.code, AppErrorCode.resourceChecksumFailed, ); expect( Directory('${root.path}/Transcription/test-model/1').existsSync(), false, ); expect( Directory('${root.path}/Transcription/test-model/1.download') .existsSync(), false, ); }); } Future<({ProcessingResourceRepository repository, List requests})> _subtitleFixture({bool corruptTranslationOnce = false}) async { final root = await Directory.systemTemp.createTemp('subtitle-bundle-'); final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); final requests = []; final data = { ProcessingCapability.transcription: List.filled(20, 1), ProcessingCapability.translation: List.filled(60, 2), }; final repository = ProcessingResourceRepository( root: root, catalog: [ for (final entry in data.entries) ProcessingResourcePackage( capability: entry.key, id: entry.key.name, version: '1', name: entry.key.name, description: '', artifacts: [ ProcessingResourceArtifact( path: 'model.bin', url: Uri.parse( 'http://127.0.0.1:${server.port}/${entry.key.name}', ), sha256: sha256.convert(entry.value).toString(), bytes: entry.value.length, ), ], ), ], ); server.listen((request) async { final name = request.uri.pathSegments.single; requests.add(name); final payload = data[ProcessingCapability.values.byName(name)]!; if (name == 'translation' && corruptTranslationOnce) { corruptTranslationOnce = false; request.response.add(List.filled(payload.length, 0)); } else { request.response.add(payload); } await request.response.close(); }); addTearDown(() async { repository.dispose(); await server.close(force: true); await root.delete(recursive: true); }); return (repository: repository, requests: requests); }