diff --git a/lib/plugins/bridge/plugin_bridge_adapter.dart b/lib/plugins/bridge/plugin_bridge_adapter.dart index 8cad98cf81..ddb65ad52d 100644 --- a/lib/plugins/bridge/plugin_bridge_adapter.dart +++ b/lib/plugins/bridge/plugin_bridge_adapter.dart @@ -756,8 +756,10 @@ class PluginBridgeAdapter { PluginNetworkFetchService get _fetchService => _networkFetchService ??= PluginNetworkFetchService(); - // LRU קצר לכל תוסף; bookUid מפריד ספרים זהים ממסדים מצורפים שונים. + // 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; @@ -839,6 +841,7 @@ class PluginBridgeAdapter { } _activeNetworkFetchStreams.clear(); _pendingNetworkFetchCancellations.clear(); + _clearPendingBookLoads(); } void dispose({bool removeRegistrations = true}) { @@ -895,35 +898,66 @@ 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; } + 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 { + 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); + } + } + } + + 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); - } else { - rawText = await DataRepository.instance.getBookText(book.title); - } - _bookContentCache[key] = rawText; - if (_bookContentCache.length > _bookContentCacheMaxEntries) { - _bookContentCache.remove(_bookContentCache.keys.first); + return (_dependencies.textBookRepository ?? + TextBookRepository(fileSystem: FileSystemData.instance)) + .getBookContent(book); } - return rawText; + return DataRepository.instance.getBookText(book.title); } /// [request] כפי שהתוסף מקבל אותו. המרת הספר כולו רצה מחוץ ל-UI, ובקשות @@ -1301,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': @@ -1550,7 +1587,10 @@ class PluginBridgeAdapter { final rawNames = _rawDivineNamesArg(args); final rawText = book == null ? await DataRepository.instance.getBookText(bookId!) - : await _loadBookRawText(book); + : 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 49b0e15997..2f05bab9f3 100644 --- a/test/plugins/bridge/plugin_bridge_adapter_test.dart +++ b/test/plugins/bridge/plugin_bridge_adapter_test.dart @@ -2382,6 +2382,263 @@ Future main() async { expect(result, ''); }); + + group('טעינת ספר שלם בקריאות מקבילות', () { + late _CountingTextBookRepository repository; + late List books; + late PluginBridgeAdapter bookAdapter; + + 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(), + 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: + checkProtection ?? ((_) async => BookProtection.none), + textBookRepository: textBooks, + ), + pluginRepository: _StubPluginRegistryRepository(), + ); + addTearDown(adapter.dispose); + return adapter; + } + + setUp(() { + books = [ + for (var i = 0; i < 7; 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(); + bookAdapter = buildAdapter(repository); + }); + + 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; + + 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); + }); + + 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(repository.loads, 1); + expect(await load(book), 'תוכן של ${book.title}'); + expect(repository.loads, 2); + }); + + 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; + } + }); + + test('טעינה מ-WebView ששוחרר אינה דורסת תוכן של מופע ששוחזר', () async { + final book = books.first; + final gate = Completer(); + repository.gates[book.title] = gate.future; + repository.contents[book.title] = 'ישן'; + final old = load(book); + await pumpEventQueue(); + + 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]); + } + + expect(await old, 'ישן'); + expect(await restored, 'חדש'); + expect(await load(book), 'חדש'); + expect(repository.loads, 2); + }); + + test('תקציב השיתוף כולל בדיקת הרשאה ומאפשר ניסיון חוזר', () async { + const preflightTime = Duration(milliseconds: 20); + final book = books.first; + final gate = Completer(); + 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]); + } + + expect(await old, 'ישן'); + expect(await retried, 'חדש'); + expect(await load(book), 'חדש'); + expect(repository.loads, 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); + }); + }); }); group('PluginBridgeAdapter.library.resolveCategoryPaths', () { @@ -7914,6 +8171,25 @@ class _TocTextBook extends TextBook { ]; } +class _CountingTextBookRepository extends Fake implements TextBookRepository { + final Map> gates = {}; + final Map contents = {}; + int loads = 0; + int failures = 0; + + @override + Future getBookContent(TextBook book) async { + loads++; + final content = contents[book.title] ?? 'תוכן של ${book.title}'; + await gates[book.title]; + if (failures > 0) { + failures--; + throw StateError('read failed'); + } + return content; + } +} + /// תוכן לפי ספר, למהדורות חלופיות שאינן עוברות דרך הספקים. class _EditionTextBookRepository extends Fake implements TextBookRepository { _EditionTextBookRepository(this.contents);