From 3e08e5c4e7a9ee96f6ad89183ca9291a295a2230 Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Wed, 11 Nov 2026 14:18:08 +0200 Subject: [PATCH 1/2] =?UTF-8?q?=D7=AA=D7=95=D7=A1=D7=A4=D7=99=D7=9D:=20get?= =?UTF-8?q?BookContent=20=D7=9E=D7=92=D7=91=D7=99=D7=9C=20=D7=98=D7=A2?= =?UTF-8?q?=D7=99=D7=A0=D7=95=D7=AA=20=D7=A1=D7=A4=D7=A8=20=D7=A9=D7=9C?= =?UTF-8?q?=D7=9D=20=D7=91=D7=9E=D7=A7=D7=91=D7=99=D7=9C=20=D7=95=D7=97?= =?UTF-8?q?=D7=95=D7=9C=D7=A7=20=D7=98=D7=A2=D7=99=D7=A0=D7=94=20=D7=9C?= =?UTF-8?q?=D7=90=D7=95=D7=AA=D7=95=20=D7=A1=D7=A4=D7=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit library.getBookContent פטורה ממגביל הקצב, וכל קריאה לספר שאינו במטמון טוענת את הספר כולו. תוסף שמבקש ספרים רבים במקביל החזיק את כולם בזיכרון בבת אחת (300 ספרים של מיליון תווים: ‎+532MB ועצירת UI של 1.9 שניות), וחתיכות מקבילות של אותו ספר טענו אותו מחדש בכל קריאה (200 חתיכות = 200 טעינות). כעת קריאות מקבילות לאותו ספר חולקות טעינה אחת דרך המטמון, ולכל תוסף רצות לכל היותר 4 טעינות ספר שלם בו-זמנית, גם לספר שנטען לפי שם בלבד. הגבול לכל תוסף ולא גלובלי, כדי שטעינות תקועות של תוסף אחד לא יעכבו תוסף אחר או הדפסה, וסגירת התוסף מבטלת טעינות שממתינות בתור. חוזה ה-API לא השתנה. Refs #4865 --- lib/plugins/bridge/plugin_bridge_adapter.dart | 65 +++++-- .../bridge/plugin_bridge_adapter_test.dart | 176 ++++++++++++++++++ 2 files changed, 227 insertions(+), 14 deletions(-) diff --git a/lib/plugins/bridge/plugin_bridge_adapter.dart b/lib/plugins/bridge/plugin_bridge_adapter.dart index 8cad98cf81..54f98262f3 100644 --- a/lib/plugins/bridge/plugin_bridge_adapter.dart +++ b/lib/plugins/bridge/plugin_bridge_adapter.dart @@ -757,10 +757,15 @@ class PluginBridgeAdapter { _networkFetchService ??= PluginNetworkFetchService(); // LRU קצר לכל תוסף; bookUid מפריד ספרים זהים ממסדים מצורפים שונים. - final Map _bookContentCache = {}; + final Map> _bookContentCache = {}; final List<({String raw, Object key, Future content})> _filteredContents = []; static const int _bookContentCacheMaxEntries = 4; + // כל טעינה מחזיקה ספר שלם בזיכרון; תוסף שמבקש אלפי ספרים במקביל מגיע ל-GBs. + // הגבול לכל תוסף, כדי שטעינות תקועות של תוסף אחד לא יעכבו תוסף אחר. + static const int _maxConcurrentBookLoads = 4; + int _activeBookLoads = 0; + final List> _bookLoadWaiters = []; static int _bookContentRevision = 0; int _seenBookContentRevision = 0; @@ -847,6 +852,10 @@ class PluginBridgeAdapter { _networkFetchService?.dispose(); _fileDownloadService?.dispose(); _bookContentCache.clear(); + for (final waiter in _bookLoadWaiters) { + waiter.completeError(StateError('plugin adapter disposed')); + } + _bookLoadWaiters.clear(); _filteredContents.clear(); unawaited(_directBookReportService?.closeHttpClient()); _bookIndexLibrary = null; @@ -907,23 +916,49 @@ class PluginBridgeAdapter { _bookContentCache[key] = cached; // רענון מיקום ב-LRU return cached; } + // קריאות מקבילות לאותו ספר (חתיכות ב-Promise.all) חולקות טעינה אחת. + final load = _withBookLoadSlot(() => _readBookRawText(book)); + _bookContentCache[key] = load; + if (_bookContentCache.length > _bookContentCacheMaxEntries) { + _bookContentCache.remove(_bookContentCache.keys.first); + } + try { + return await load; + } catch (_) { + if (identical(_bookContentCache[key], load)) { + _bookContentCache.remove(key); + } + rethrow; + } + } + + Future _readBookRawText(Book book) async { // ה-TextBook מהקטלוג שומר categoryId/fileType נכונים גם בספרים השמורים רק ב-DB. - final String rawText; if (book is TextBook) { - rawText = - await (_dependencies.textBookRepository ?? - TextBookRepository( - fileSystem: FileSystemData.instance, - )) - .getBookContent(book); + return (_dependencies.textBookRepository ?? + TextBookRepository(fileSystem: FileSystemData.instance)) + .getBookContent(book); + } + return DataRepository.instance.getBookText(book.title); + } + + Future _withBookLoadSlot(Future Function() load) async { + if (_activeBookLoads < _maxConcurrentBookLoads) { + _activeBookLoads++; } else { - rawText = await DataRepository.instance.getBookText(book.title); + final waiter = Completer(); + _bookLoadWaiters.add(waiter); + await waiter.future; // המשבצת מועברת ישירות מהטעינה שהסתיימה } - _bookContentCache[key] = rawText; - if (_bookContentCache.length > _bookContentCacheMaxEntries) { - _bookContentCache.remove(_bookContentCache.keys.first); + try { + return await load(); + } finally { + if (_bookLoadWaiters.isNotEmpty) { + _bookLoadWaiters.removeAt(0).complete(); + } else { + _activeBookLoads--; + } } - return rawText; } /// [request] כפי שהתוסף מקבל אותו. המרת הספר כולו רצה מחוץ ל-UI, ובקשות @@ -1549,7 +1584,9 @@ class PluginBridgeAdapter { await _ensureBookTextAvailable(book ?? TextBook(title: bookId!)); final rawNames = _rawDivineNamesArg(args); final rawText = book == null - ? await DataRepository.instance.getBookText(bookId!) + ? await _withBookLoadSlot( + () => DataRepository.instance.getBookText(bookId!), + ) : await _loadBookRawText(book); final contentBook = book ?? TextBook(title: bookId!); TextDisplayProfile? displayProfile; diff --git a/test/plugins/bridge/plugin_bridge_adapter_test.dart b/test/plugins/bridge/plugin_bridge_adapter_test.dart index 49b0e15997..894fae1506 100644 --- a/test/plugins/bridge/plugin_bridge_adapter_test.dart +++ b/test/plugins/bridge/plugin_bridge_adapter_test.dart @@ -2382,6 +2382,155 @@ Future main() async { expect(result, ''); }); + + group('טעינת ספר שלם בקריאות מקבילות', () { + late _CountingTextBookRepository repository; + late List books; + late PluginBridgeAdapter boundedAdapter; + + PluginBridgeAdapter buildAdapter(TextBookRepository textBooks) { + final adapter = PluginBridgeAdapter( + _buildInstalledPlugin(permissions: const ['library.read']), + dependencies: PluginBridgeDependencies( + historyBloc: _MockHistoryBloc(), + tabsBloc: _StubTabsBloc(), + navigationBloc: _MockNavigationBloc(), + calendarCubit: _StubCalendarCubit( + _buildCalendarState(DateTime(2026, 1, 1), inIsrael: true), + ), + workspaceBloc: _MockWorkspaceBloc(), + searchRepository: _MockSearchRepository(), + personalNotesRepository: _MockPersonalNotesRepository(), + bookOpenCoordinator: _MockBookOpenCoordinator(), + themePayloadBuilder: () => {}, + showConfirmDialog: ({required title, required content}) async => + true, + showWarningDialog: + ({required title, required content, required subtitle}) async => + true, + bookProtectionResolver: (_) async => BookProtection.none, + textBookRepository: textBooks, + ), + pluginRepository: _StubPluginRegistryRepository(), + ); + addTearDown(adapter.dispose); + return adapter; + } + + setUp(() { + books = [ + for (var i = 0; i < 40; i++) + TextBook(title: 'ספר מקביל $i', categoryId: 700, fileType: 'txt'), + ]; + DataRepository.instance.library = Future.value( + Library( + categories: [ + Category( + title: 'מקביל', + description: '', + shortDescription: '', + order: 0, + subCategories: const [], + books: books, + parent: null, + ), + ], + ), + ); + repository = _CountingTextBookRepository(); + boundedAdapter = buildAdapter(repository); + }); + + test('ספרים רבים במקביל — מספר הספרים השלמים בזיכרון חסום', () async { + final results = await Future.wait([ + for (final book in books) + boundedAdapter.execute('library', 'getBookContent', { + 'bookId': book.title, + 'limit': 20, + }), + ]); + + expect(results.first, 'תוכן של ספר מקביל 0'); + expect(results.last, 'תוכן של ספר מקביל 39'); + expect(repository.loads, books.length); + expect(repository.maxInFlight, lessThanOrEqualTo(4)); + }); + + test('חתיכות מקבילות של אותו ספר — טעינה אחת', () async { + final chunks = await Future.wait([ + for (var i = 0; i < 20; i++) + boundedAdapter.execute('library', 'getBookContent', { + 'bookId': books.first.title, + 'offset': i, + 'limit': 1, + }), + ]); + + expect(chunks.join(), 'תוכן של ספר מקביל 0'); + expect(repository.loads, 1); + }); + + test('טעינות שנכשלו משחררות את מקומן בתור', () async { + repository.failures = 6; + for (var i = 0; i < 6; i++) { + await expectLater( + boundedAdapter.execute('library', 'getBookContent', { + 'bookId': books[i].title, + }), + throwsA(isA()), + ); + } + + final result = await boundedAdapter + .execute('library', 'getBookContent', {'bookId': books.first.title}) + .timeout(const Duration(seconds: 5)); + expect(result, 'תוכן של ספר מקביל 0'); + }); + + test('טעינות תקועות של תוסף אחד אינן מעכבות תוסף אחר', () async { + final gate = Completer(); + repository.gate = gate.future; + final stuck = [ + for (var i = 0; i < 6; i++) + boundedAdapter + .execute('library', 'getBookContent', { + 'bookId': books[i].title, + }) + .then((value) => value, onError: (Object e) => e), + ]; + await pumpEventQueue(); + + final other = buildAdapter(_CountingTextBookRepository()); + final result = await other + .execute('library', 'getBookContent', {'bookId': books[10].title}) + .timeout(const Duration(seconds: 5)); + expect(result, 'תוכן של ספר מקביל 10'); + + gate.complete(); + await Future.wait(stuck); + }); + + test('סגירת התוסף מבטלת טעינות שממתינות בתור', () async { + final gate = Completer(); + repository.gate = gate.future; + final pending = [ + for (var i = 0; i < 6; i++) + boundedAdapter + .execute('library', 'getBookContent', { + 'bookId': books[i].title, + }) + .then((value) => value, onError: (Object e) => e), + ]; + await pumpEventQueue(); + + boundedAdapter.dispose(); + gate.complete(); + final outcomes = await Future.wait(pending); + + expect(repository.loads, 4); + expect(outcomes.whereType(), hasLength(2)); + }); + }); }); group('PluginBridgeAdapter.library.resolveCategoryPaths', () { @@ -7914,6 +8063,33 @@ class _TocTextBook extends TextBook { ]; } +/// סופר טעינות ספר שלם, ואת המקסימום שרץ בו-זמנית. +class _CountingTextBookRepository extends Fake implements TextBookRepository { + int loads = 0; + int inFlight = 0; + int maxInFlight = 0; + int failures = 0; + Future? gate; + + @override + Future getBookContent(TextBook book) async { + loads++; + inFlight++; + if (inFlight > maxInFlight) maxInFlight = inFlight; + try { + await Future.delayed(const Duration(milliseconds: 5)); + await gate; + if (failures > 0) { + failures--; + throw StateError('read failed'); + } + return 'תוכן של ${book.title}'; + } finally { + inFlight--; + } + } +} + /// תוכן לפי ספר, למהדורות חלופיות שאינן עוברות דרך הספקים. class _EditionTextBookRepository extends Fake implements TextBookRepository { _EditionTextBookRepository(this.contents); From 15f2186181deac6ef70c97f82dfd4c8ec31c2250 Mon Sep 17 00:00:00 2001 From: ypl <7353755@gmail.com> Date: Wed, 11 Nov 2026 22:34:52 +0200 Subject: [PATCH 2/2] fix(plugins): share book reads without queuing unrelated requests --- lib/plugins/bridge/plugin_bridge_adapter.dart | 103 +++---- lib/plugins/bridge/plugin_bridge_handler.dart | 3 +- lib/plugins/plugin_constants.dart | 3 + .../bridge/plugin_bridge_adapter_test.dart | 278 ++++++++++++------ 4 files changed, 247 insertions(+), 140 deletions(-) diff --git a/lib/plugins/bridge/plugin_bridge_adapter.dart b/lib/plugins/bridge/plugin_bridge_adapter.dart index 54f98262f3..ddb65ad52d 100644 --- a/lib/plugins/bridge/plugin_bridge_adapter.dart +++ b/lib/plugins/bridge/plugin_bridge_adapter.dart @@ -756,16 +756,13 @@ class PluginBridgeAdapter { PluginNetworkFetchService get _fetchService => _networkFetchService ??= PluginNetworkFetchService(); - // LRU קצר לכל תוסף; bookUid מפריד ספרים זהים ממסדים מצורפים שונים. - final Map> _bookContentCache = {}; + // LRU קצר לכל מופע; bookUid מפריד ספרים זהים ממסדים מצורפים שונים. + final Map _bookContentCache = {}; + final Map result, Timer expiry})> _pendingBookLoads = + {}; final List<({String raw, Object key, Future content})> _filteredContents = []; static const int _bookContentCacheMaxEntries = 4; - // כל טעינה מחזיקה ספר שלם בזיכרון; תוסף שמבקש אלפי ספרים במקביל מגיע ל-GBs. - // הגבול לכל תוסף, כדי שטעינות תקועות של תוסף אחד לא יעכבו תוסף אחר. - static const int _maxConcurrentBookLoads = 4; - int _activeBookLoads = 0; - final List> _bookLoadWaiters = []; static int _bookContentRevision = 0; int _seenBookContentRevision = 0; @@ -844,6 +841,7 @@ class PluginBridgeAdapter { } _activeNetworkFetchStreams.clear(); _pendingNetworkFetchCancellations.clear(); + _clearPendingBookLoads(); } void dispose({bool removeRegistrations = true}) { @@ -852,10 +850,6 @@ class PluginBridgeAdapter { _networkFetchService?.dispose(); _fileDownloadService?.dispose(); _bookContentCache.clear(); - for (final waiter in _bookLoadWaiters) { - waiter.completeError(StateError('plugin adapter disposed')); - } - _bookLoadWaiters.clear(); _filteredContents.clear(); unawaited(_directBookReportService?.closeHttpClient()); _bookIndexLibrary = null; @@ -904,31 +898,55 @@ class PluginBridgeAdapter { } } - /// LRU מונע טעינה חוזרת של ספר בקריאות מקוטעות; UID שומר על הפרדת המקורות. - Future _loadBookRawText(Book book) async { - if (_seenBookContentRevision != _bookContentRevision) { + void _clearPendingBookLoads() { + for (final load in _pendingBookLoads.values) { + load.expiry.cancel(); + } + _pendingBookLoads.clear(); + } + + /// משתף טעינות מקבילות לפי UID ושומר טעינות שהסתיימו ב-LRU קצר. + Future _loadBookRawText( + Book book, { + Duration shareFor = kPluginDefaultRpcTimeout, + }) async { + final revision = _bookContentRevision; + if (_seenBookContentRevision != revision) { _bookContentCache.clear(); - _seenBookContentRevision = _bookContentRevision; + _clearPendingBookLoads(); + _seenBookContentRevision = revision; } final key = PluginBookIdentity.uidOf(book); final cached = _bookContentCache.remove(key); if (cached != null) { - _bookContentCache[key] = cached; // רענון מיקום ב-LRU + _bookContentCache[key] = cached; return cached; } - // קריאות מקבילות לאותו ספר (חתיכות ב-Promise.all) חולקות טעינה אחת. - final load = _withBookLoadSlot(() => _readBookRawText(book)); - _bookContentCache[key] = load; - if (_bookContentCache.length > _bookContentCacheMaxEntries) { - _bookContentCache.remove(_bookContentCache.keys.first); - } + final pending = _pendingBookLoads[key]; + if (pending != null) return pending.result; + if (shareFor <= Duration.zero) return _readBookRawText(book); + + final load = _readBookRawText(book); + // ניסיון חוזר אחרי timeout יכול לטעון גם כשהקריאה הקודמת עדיין תקועה. + final expiry = Timer(shareFor, () { + _pendingBookLoads.remove(key); + }); + _pendingBookLoads[key] = (result: load, expiry: expiry); try { - return await load; - } catch (_) { - if (identical(_bookContentCache[key], load)) { - _bookContentCache.remove(key); + final text = await load; + if (identical(_pendingBookLoads[key]?.result, load) && + revision == _bookContentRevision) { + _bookContentCache[key] = text; + if (_bookContentCache.length > _bookContentCacheMaxEntries) { + _bookContentCache.remove(_bookContentCache.keys.first); + } + } + return text; + } finally { + expiry.cancel(); + if (identical(_pendingBookLoads[key]?.result, load)) { + _pendingBookLoads.remove(key); } - rethrow; } } @@ -942,25 +960,6 @@ class PluginBridgeAdapter { return DataRepository.instance.getBookText(book.title); } - Future _withBookLoadSlot(Future Function() load) async { - if (_activeBookLoads < _maxConcurrentBookLoads) { - _activeBookLoads++; - } else { - final waiter = Completer(); - _bookLoadWaiters.add(waiter); - await waiter.future; // המשבצת מועברת ישירות מהטעינה שהסתיימה - } - try { - return await load(); - } finally { - if (_bookLoadWaiters.isNotEmpty) { - _bookLoadWaiters.removeAt(0).complete(); - } else { - _activeBookLoads--; - } - } - } - /// [request] כפי שהתוסף מקבל אותו. המרת הספר כולו רצה מחוץ ל-UI, ובקשות /// מקבילות לאותו טקסט ולאותה תצוגה חולקות אותה. Future _filteredBookContent( @@ -1336,6 +1335,9 @@ class PluginBridgeAdapter { String action, Map args, ) async { + final bookContentClock = action == 'getBookContent' + ? (Stopwatch()..start()) + : null; final library = await DataRepository.instance.library; switch (action) { case 'refreshUserBooks': @@ -1584,10 +1586,11 @@ class PluginBridgeAdapter { await _ensureBookTextAvailable(book ?? TextBook(title: bookId!)); final rawNames = _rawDivineNamesArg(args); final rawText = book == null - ? await _withBookLoadSlot( - () => DataRepository.instance.getBookText(bookId!), - ) - : await _loadBookRawText(book); + ? await DataRepository.instance.getBookText(bookId!) + : await _loadBookRawText( + book, + shareFor: kPluginDefaultRpcTimeout - bookContentClock!.elapsed, + ); final contentBook = book ?? TextBook(title: bookId!); TextDisplayProfile? displayProfile; TextBookLoaded? readerState; diff --git a/lib/plugins/bridge/plugin_bridge_handler.dart b/lib/plugins/bridge/plugin_bridge_handler.dart index 29f22b7454..f030b2bdf9 100644 --- a/lib/plugins/bridge/plugin_bridge_handler.dart +++ b/lib/plugins/bridge/plugin_bridge_handler.dart @@ -8,6 +8,7 @@ import 'package:otzaria/plugins/models/installed_plugin.dart'; import 'package:otzaria/plugins/models/plugin_rpc_request.dart'; import 'package:otzaria/plugins/models/plugin_valid_permissions.dart'; import 'package:otzaria/plugins/models/plugin_rpc_response.dart'; +import 'package:otzaria/plugins/plugin_constants.dart'; import 'package:otzaria/plugins/repository/plugin_registry_repository.dart'; import 'package:otzaria/plugins/bridge/plugin_bridge_adapter.dart'; import 'package:otzaria/plugins/storage/plugin_system_database.dart'; @@ -291,7 +292,7 @@ class PluginBridgeHandler { ); final result = hasOwnTimeout(request.method) ? await execution - : await execution.timeout(const Duration(seconds: 30)); + : await execution.timeout(kPluginDefaultRpcTimeout); return _successResp(result); } on PluginDatabaseException catch (e) { return _errorResp(e.code, e.message); diff --git a/lib/plugins/plugin_constants.dart b/lib/plugins/plugin_constants.dart index 126c7f1044..ac12dd9ef6 100644 --- a/lib/plugins/plugin_constants.dart +++ b/lib/plugins/plugin_constants.dart @@ -1,3 +1,6 @@ +/// מגבלת הזמן של RPC שאינו מגדיר חסם משלו. +const Duration kPluginDefaultRpcTimeout = Duration(seconds: 30); + /// ה-namespace שאליו נעול אחסון ה-KV של תוסף (storage.* בגשר ובמסלול /// הדקלרטיבי). הערך הוא מפתח קיים בדיסק של משתמשים — אסור לשנותו. const String kDefaultStorageNamespace = 'default'; diff --git a/test/plugins/bridge/plugin_bridge_adapter_test.dart b/test/plugins/bridge/plugin_bridge_adapter_test.dart index 894fae1506..2f05bab9f3 100644 --- a/test/plugins/bridge/plugin_bridge_adapter_test.dart +++ b/test/plugins/bridge/plugin_bridge_adapter_test.dart @@ -2386,11 +2386,16 @@ Future main() async { group('טעינת ספר שלם בקריאות מקבילות', () { late _CountingTextBookRepository repository; late List books; - late PluginBridgeAdapter boundedAdapter; + late PluginBridgeAdapter bookAdapter; - PluginBridgeAdapter buildAdapter(TextBookRepository textBooks) { + PluginBridgeAdapter buildAdapter( + TextBookRepository textBooks, { + String instanceId = PluginInstanceIds.defaultForeground, + Future Function(Book)? checkProtection, + }) { final adapter = PluginBridgeAdapter( _buildInstalledPlugin(permissions: const ['library.read']), + instanceId: instanceId, dependencies: PluginBridgeDependencies( historyBloc: _MockHistoryBloc(), tabsBloc: _StubTabsBloc(), @@ -2408,7 +2413,8 @@ Future main() async { showWarningDialog: ({required title, required content, required subtitle}) async => true, - bookProtectionResolver: (_) async => BookProtection.none, + bookProtectionResolver: + checkProtection ?? ((_) async => BookProtection.none), textBookRepository: textBooks, ), pluginRepository: _StubPluginRegistryRepository(), @@ -2419,7 +2425,7 @@ Future main() async { setUp(() { books = [ - for (var i = 0; i < 40; i++) + for (var i = 0; i < 7; i++) TextBook(title: 'ספר מקביל $i', categoryId: 700, fileType: 'txt'), ]; DataRepository.instance.library = Future.value( @@ -2438,97 +2444,199 @@ Future main() async { ), ); repository = _CountingTextBookRepository(); - boundedAdapter = buildAdapter(repository); + bookAdapter = buildAdapter(repository); }); - test('ספרים רבים במקביל — מספר הספרים השלמים בזיכרון חסום', () async { - final results = await Future.wait([ - for (final book in books) - boundedAdapter.execute('library', 'getBookContent', { - 'bookId': book.title, - 'limit': 20, - }), - ]); + Future load( + TextBook book, { + int offset = 0, + int limit = 1000, + PluginBridgeAdapter? adapter, + }) async => + (await (adapter ?? bookAdapter).execute( + 'library', + 'getBookContent', + { + 'bookId': book.title, + 'offset': offset, + 'limit': limit, + 'rawDivineNames': true, + }, + )) + as String; - expect(results.first, 'תוכן של ספר מקביל 0'); - expect(results.last, 'תוכן של ספר מקביל 39'); + test('ספרים אחרים אינם דוחקים טעינה פעילה של אותו ספר', () async { + final gate = Completer(); + addTearDown(() { + if (!gate.isCompleted) gate.complete(); + }); + for (final book in books) { + repository.gates[book.title] = gate.future; + } + final reads = [for (final book in books) load(book)]; + final chunks = [ + for (var offset = 0; offset < 20; offset++) + load(books.first, offset: offset, limit: 1), + ]; + await pumpEventQueue(); + gate.complete(); + + expect(await Future.wait(reads), [ + for (final book in books) 'תוכן של ${book.title}', + ]); + expect((await Future.wait(chunks)).join(), 'תוכן של ספר מקביל 0'); expect(repository.loads, books.length); - expect(repository.maxInFlight, lessThanOrEqualTo(4)); }); - test('חתיכות מקבילות של אותו ספר — טעינה אחת', () async { - final chunks = await Future.wait([ - for (var i = 0; i < 20; i++) - boundedAdapter.execute('library', 'getBookContent', { - 'bookId': books.first.title, - 'offset': i, - 'limit': 1, - }), - ]); + test('בקשה מהירה מתחילה גם כשארבע טעינות אחרות ממתינות', () async { + final gate = Completer(); + final blocked = books.take(4); + for (final book in blocked) { + repository.gates[book.title] = gate.future; + } + final pending = [for (final book in blocked) load(book)]; + await pumpEventQueue(); + String? fastResult; + final fast = load(books.last).then((result) => fastResult = result); + try { + await pumpEventQueue(); + expect(repository.loads, 5); + expect(fastResult, 'תוכן של ${books.last.title}'); + } finally { + gate.complete(); + await Future.wait([...pending, fast]); + } + }); + + test('טעינה משותפת שנכשלה ניתנת לניסיון חוזר', () async { + final book = books.first; + final gate = Completer(); + repository.gates[book.title] = gate.future; + repository.failures = 1; + final failed = [ + expectLater(load(book), throwsStateError), + expectLater(load(book), throwsStateError), + ]; + await pumpEventQueue(); + gate.complete(); + await Future.wait(failed); - expect(chunks.join(), 'תוכן של ספר מקביל 0'); expect(repository.loads, 1); + expect(await load(book), 'תוכן של ${book.title}'); + expect(repository.loads, 2); }); - test('טעינות שנכשלו משחררות את מקומן בתור', () async { - repository.failures = 6; - for (var i = 0; i < 6; i++) { - await expectLater( - boundedAdapter.execute('library', 'getBookContent', { - 'bookId': books[i].title, - }), - throwsA(isA()), - ); + test('כל מופע של התוסף מנהל טעינות משלו', () async { + final book = books.first; + final gate = Completer(); + final otherRepository = _CountingTextBookRepository(); + final other = buildAdapter(otherRepository, instanceId: 'second'); + repository.gates[book.title] = gate.future; + final pending = load(book); + await pumpEventQueue(); + try { + expect(await load(book, adapter: other), 'תוכן של ${book.title}'); + expect(otherRepository.loads, 1); + } finally { + gate.complete(); + await pending; } - - final result = await boundedAdapter - .execute('library', 'getBookContent', {'bookId': books.first.title}) - .timeout(const Duration(seconds: 5)); - expect(result, 'תוכן של ספר מקביל 0'); }); - test('טעינות תקועות של תוסף אחד אינן מעכבות תוסף אחר', () async { + test('טעינה מ-WebView ששוחרר אינה דורסת תוכן של מופע ששוחזר', () async { + final book = books.first; final gate = Completer(); - repository.gate = gate.future; - final stuck = [ - for (var i = 0; i < 6; i++) - boundedAdapter - .execute('library', 'getBookContent', { - 'bookId': books[i].title, - }) - .then((value) => value, onError: (Object e) => e), - ]; + repository.gates[book.title] = gate.future; + repository.contents[book.title] = 'ישן'; + final old = load(book); await pumpEventQueue(); - final other = buildAdapter(_CountingTextBookRepository()); - final result = await other - .execute('library', 'getBookContent', {'bookId': books[10].title}) - .timeout(const Duration(seconds: 5)); - expect(result, 'תוכן של ספר מקביל 10'); + bookAdapter.releaseRuntime(); + repository.gates.remove(book.title); + repository.contents[book.title] = 'חדש'; + final restored = load(book); + try { + await pumpEventQueue(); + expect(repository.loads, 2); + } finally { + gate.complete(); + await Future.wait([old, restored]); + } - gate.complete(); - await Future.wait(stuck); + expect(await old, 'ישן'); + expect(await restored, 'חדש'); + expect(await load(book), 'חדש'); + expect(repository.loads, 2); }); - test('סגירת התוסף מבטלת טעינות שממתינות בתור', () async { + test('תקציב השיתוף כולל בדיקת הרשאה ומאפשר ניסיון חוזר', () async { + const preflightTime = Duration(milliseconds: 20); + final book = books.first; final gate = Completer(); - repository.gate = gate.future; - final pending = [ - for (var i = 0; i < 6; i++) - boundedAdapter - .execute('library', 'getBookContent', { - 'bookId': books[i].title, - }) - .then((value) => value, onError: (Object e) => e), - ]; - await pumpEventQueue(); + final protectionStarted = Completer(); + final protection = Completer(); + bookAdapter = buildAdapter( + repository, + checkProtection: (_) { + if (!protectionStarted.isCompleted) protectionStarted.complete(); + return protection.future; + }, + ); + repository.gates[book.title] = gate.future; + repository.contents[book.title] = 'ישן'; + Duration? sharingBudget; + void Function()? expire; + final old = runZoned( + () => load(book), + zoneSpecification: ZoneSpecification( + createTimer: (self, parent, zone, duration, callback) { + sharingBudget = duration; + expire = callback; + return parent.createTimer(zone, duration, callback); + }, + ), + ); + Future? retried; + try { + await protectionStarted.future; + await Future.delayed(preflightTime); + protection.complete(BookProtection.none); + await pumpEventQueue(); + expect(repository.loads, 1); + expect( + sharingBudget, + lessThanOrEqualTo(kPluginDefaultRpcTimeout - preflightTime), + ); + expire!(); + + repository.gates.remove(book.title); + repository.contents[book.title] = 'חדש'; + retried = load(book); + await pumpEventQueue(); + expect(repository.loads, 2); + } finally { + gate.complete(); + await Future.wait([old, ?retried]); + } - boundedAdapter.dispose(); - gate.complete(); - final outcomes = await Future.wait(pending); + expect(await old, 'ישן'); + expect(await retried, 'חדש'); + expect(await load(book), 'חדש'); + expect(repository.loads, 2); + }); - expect(repository.loads, 4); - expect(outcomes.whereType(), hasLength(2)); + test('המטמון שומר רק את ארבע הטעינות האחרונות', () async { + for (final book in books.take(4)) { + await load(book); + } + await load(books.first); + await load(books[4]); + expect(repository.loads, 5); + + await load(books.first); + expect(repository.loads, 5); + await load(books[1]); + expect(repository.loads, 6); }); }); }); @@ -8063,30 +8171,22 @@ class _TocTextBook extends TextBook { ]; } -/// סופר טעינות ספר שלם, ואת המקסימום שרץ בו-זמנית. class _CountingTextBookRepository extends Fake implements TextBookRepository { + final Map> gates = {}; + final Map contents = {}; int loads = 0; - int inFlight = 0; - int maxInFlight = 0; int failures = 0; - Future? gate; @override Future getBookContent(TextBook book) async { loads++; - inFlight++; - if (inFlight > maxInFlight) maxInFlight = inFlight; - try { - await Future.delayed(const Duration(milliseconds: 5)); - await gate; - if (failures > 0) { - failures--; - throw StateError('read failed'); - } - return 'תוכן של ${book.title}'; - } finally { - inFlight--; + final content = contents[book.title] ?? 'תוכן של ${book.title}'; + await gates[book.title]; + if (failures > 0) { + failures--; + throw StateError('read failed'); } + return content; } }