基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。
fix(sync): keep history sync alive when local event logs are damaged
Predidit15e7135e4deb
diff --git a/lib/modules/history/history_sync.dart b/lib/modules/history/history_sync.dartindex a2679a2a..d3ec0622 100644--- a/lib/modules/history/history_sync.dart+++ b/lib/modules/history/history_sync.dart@@ -688,11 +688,7 @@ class HistorySyncStreamMerger {switch (event.op) {case HistorySyncOp.upsertProgress:final entityKey = _upsertEntityKey(event);- final episode = event.episode;- final progressKey = episode == null- ? 'invalid-progress:${event.eventId}'- : '$entityKey:$episode';- _keepLatest(_progressEvents, progressKey, event);+ _keepLatest(_progressEvents, '$entityKey:${event.episode!}', event);if (_carriesLegacyWatchState(event)) {_keepLatest(_watchStateEvents, entityKey, event);}@@ -755,15 +751,12 @@ class HistorySyncStreamMerger {}}+ /// Callers must run [_validate] first: upsert events always carry+ /// [HistorySyncEvent.adapterName] and [HistorySyncEvent.bangumiItem].String _upsertEntityKey(HistorySyncEvent event) {- final bangumiItem = event.bangumiItem;- final adapterName = event.adapterName;- if (bangumiItem == null || adapterName == null) {- return event.entityKey ?? 'invalid-upsert:${event.eventId}';- }return History.scopedKey(- adapterName,- bangumiItem,+ event.adapterName!,+ event.bangumiItem!,HistoryEntryKind.normalize(event.entryKind ?? HistoryEntryKind.online,),diff --git a/lib/services/sync/history_sync_service.dart b/lib/services/sync/history_sync_service.dartindex 4d978805..ea2a0395 100644--- a/lib/services/sync/history_sync_service.dart+++ b/lib/services/sync/history_sync_service.dart@@ -270,6 +270,10 @@ class HistorySyncService {});}+ /// Copies the active log for upload, dropping lines other devices could+ /// not merge. When malformed lines are found the active log itself is+ /// rewritten from the sanitized copy so the damage does not resurface on+ /// every following sync. Returns null when nothing valid is left to upload.Future<File?> copyActiveLogForUpload(Directory runDirectory) {return _localLogQueue.run(() async {final activeFile = await localChangeLogFile();@@ -280,11 +284,45 @@ class HistorySyncService {'${runDirectory.path}${Platform.pathSeparator}''local-events-upload.jsonl',);- await activeFile.copy(uploadFile.path);+ final result = await _sanitizeEventLogCopy(+ sourcePath: activeFile.path,+ targetPath: uploadFile.path,+ );+ final malformedLines = result['malformedLines']!;+ if (malformedLines > 0) {+ KazumiLogger().w(+ 'HistorySync: dropped $malformedLines malformed line(s) '+ 'from local event log upload',+ );+ await _repairActiveLog(activeFile, uploadFile);+ }+ if (result['validLines'] == 0) {+ return null;+ }return uploadFile;});}+ /// Replaces the active log with its sanitized copy. Must be called while+ /// holding [_localLogQueue] so no append interleaves. Best-effort: on+ /// failure the damaged log stays and the next sync retries.+ Future<void> _repairActiveLog(File activeFile, File sanitizedFile) async {+ try {+ final tempFile = File('${activeFile.path}.repair');+ await sanitizedFile.copy(tempFile.path);+ await tempFile.rename(activeFile.path);+ KazumiLogger().w(+ 'HistorySync: rewrote local event log without malformed lines',+ );+ } catch (e, stackTrace) {+ KazumiLogger().w(+ 'HistorySync: failed to repair local event log',+ error: e,+ stackTrace: stackTrace,+ );+ }+ }+Future<void> completeCheckpoint(HistorySyncLogBatch batch) {return _localLogQueue.run(() async {if (!batch.shouldCheckpoint) {@@ -304,19 +342,36 @@ class HistorySyncService {return HistorySyncSnapshot.fromJson(json);}+ /// Merges event files into [snapshot].+ ///+ /// With [tolerateMalformedLines] each unparsable line is skipped and+ /// reported through a warning log instead of failing the whole merge. This+ /// keeps sync alive when a crash mid-append leaves a truncated line in a+ /// locally-owned log; the local Hive box remains the source of truth for+ /// anything a skipped line described.Future<HistorySyncSnapshot> mergeEventFiles({required HistorySyncSnapshot snapshot,required Iterable<File> eventFiles,required Iterable<HistorySyncEvent> inMemoryEvents,+ bool tolerateMalformedLines = false,}) async {final request = <String, dynamic>{'snapshot': snapshot.toJson(),'eventFiles': eventFiles.map((file) => file.path).toList(),'events': inMemoryEvents.map((event) => event.toJson()).toList(),+ 'tolerateMalformedLines': tolerateMalformedLines,};- final mergedJson =- await Isolate.run(() => _mergeHistoryEventFiles(request));- return HistorySyncSnapshot.fromJson(mergedJson);+ final response = await Isolate.run(() => _mergeHistoryEventFiles(request));+ final skippedLines = Map<String, int>.from(response['skippedLines'] as Map);+ for (final entry in skippedLines.entries) {+ KazumiLogger().w(+ 'HistorySync: skipped ${entry.value} malformed line(s) '+ 'in local event log ${entry.key}',+ );+ }+ return HistorySyncSnapshot.fromJson(+ Map<String, dynamic>.from(response['snapshot'] as Map),+ );}/// Merges independently-owned remote logs without letting one invalid file@@ -447,22 +502,32 @@ Future<Map<String, dynamic>> _mergeHistoryEventFiles();final merger = HistorySyncStreamMerger(snapshot);final eventFiles = (request['eventFiles'] as List).cast<String>();+ final tolerateMalformedLines =+ request['tolerateMalformedLines'] as bool? ?? false;+ final skippedLines = <String, int>{};for (final path in eventFiles) {final lines = File(path).openRead()- .transform(utf8.decoder)+ .transform(Utf8Decoder(allowMalformed: tolerateMalformedLines)).transform(const LineSplitter());await for (final rawLine in lines) {final line = rawLine.trim();if (line.isEmpty) {continue;}- merger.add(- HistorySyncEvent.fromJson(- Map<String, dynamic>.from(jsonDecode(line) as Map),- ),- );+ try {+ merger.add(+ HistorySyncEvent.fromJson(+ Map<String, dynamic>.from(jsonDecode(line) as Map),+ ),+ );+ } catch (_) {+ if (!tolerateMalformedLines) {+ rethrow;+ }+ skippedLines[path] = (skippedLines[path] ?? 0) + 1;+ }}}@@ -474,5 +539,61 @@ Future<Map<String, dynamic>> _mergeHistoryEventFiles(),);- return merger.snapshot().toJson();+ return <String, dynamic>{+ 'snapshot': merger.snapshot().toJson(),+ 'skippedLines': skippedLines,+ };+}++/// Runs [_copyValidEventLines] in an isolate. Top-level so the isolate+/// closure captures only the paths, not the service instance.+Future<Map<String, int>> _sanitizeEventLogCopy({+ required String sourcePath,+ required String targetPath,+}) {+ final request = <String, String>{+ 'sourcePath': sourcePath,+ 'targetPath': targetPath,+ };+ return Isolate.run(() => _copyValidEventLines(request));+}++/// Copies only the lines other devices can merge, so one corrupt local line+/// cannot get this device's remote log quarantined by every peer.+Future<Map<String, int>> _copyValidEventLines(+ Map<String, String> request,+) async {+ final sourcePath = request['sourcePath']!;+ final targetPath = request['targetPath']!;+ final probe = HistorySyncStreamMerger(HistorySyncSnapshot.empty());+ final sink = File(targetPath).openWrite();+ var validLines = 0;+ var malformedLines = 0;+ try {+ final lines = File(sourcePath)+ .openRead()+ .transform(const Utf8Decoder(allowMalformed: true))+ .transform(const LineSplitter());+ await for (final rawLine in lines) {+ final line = rawLine.trim();+ if (line.isEmpty) {+ continue;+ }+ try {+ probe.add(+ HistorySyncEvent.fromJson(+ Map<String, dynamic>.from(jsonDecode(line) as Map),+ ),+ );+ } catch (_) {+ malformedLines++;+ continue;+ }+ sink.writeln(line);+ validLines++;+ }+ } finally {+ await sink.close();+ }+ return {'validLines': validLines, 'malformedLines': malformedLines};}diff --git a/lib/services/sync/webdav.dart b/lib/services/sync/webdav.dartindex 28b0cdb8..b2b7367f 100644--- a/lib/services/sync/webdav.dart+++ b/lib/services/sync/webdav.dart@@ -220,10 +220,15 @@ class WebDav {snapshot: remoteSnapshot,eventFiles: downloads.eventFiles,);+ // Locally-owned logs tolerate malformed lines: a crash mid-append must+ // not permanently block sync, and the Hive box still holds the state a+ // damaged line described. Remote logs above stay fail-closed so an+ // invalid file is quarantined as a whole.final mergedFromFiles = await historySync.mergeEventFiles(snapshot: mergedRemoteSnapshot,eventFiles: localBatch.files,inMemoryEvents: await historySync.buildLocalStateEvents(),+ tolerateMalformedLines: true,);final mergedSnapshot = await historySync.reconcileAndApplySnapshot(diff --git a/test/history_sync_test.dart b/test/history_sync_test.dartindex f7390070..22dcbfa3 100644--- a/test/history_sync_test.dart+++ b/test/history_sync_test.dart@@ -845,6 +845,124 @@ void main() {expect(await file.readAsString(), malformed);});+ test('salvages valid lines from a corrupted local event log', () async {+ final directory =+ await Directory.systemTemp.createTemp('kazumi_history_salvage_');+ addTearDown(() async {+ if (await directory.exists()) {+ await directory.delete(recursive: true);+ }+ });+ final file = File('${directory.path}/events.jsonl');+ final beforeCrash = HistorySyncCodec.eventsToJsonLines([+ _upsert(+ deviceId: 'device-a',+ seq: 1,+ updatedAt: 1000,+ episode: 1,+ progressMs: 10,+ ),+ ]);+ final afterCrash = HistorySyncCodec.eventsToJsonLines([+ _upsert(+ deviceId: 'device-a',+ seq: 2,+ updatedAt: 2000,+ episode: 2,+ progressMs: 20,+ ),+ ]);+ await file.writeAsString(+ '$beforeCrash{"eventId":"truncated"\n$afterCrash',+ flush: true,+ );++ final merged = await HistorySyncService().mergeEventFiles(+ snapshot: HistorySyncSnapshot.empty(),+ eventFiles: [file],+ inMemoryEvents: const [],+ tolerateMalformedLines: true,+ );++ expect(merged.histories, hasLength(1));+ expect(merged.histories.single.progresses, contains(1));+ expect(merged.histories.single.progresses, contains(2));+ });++ test('upload copy drops malformed lines but keeps valid events', () async {+ final directory =+ await Directory.systemTemp.createTemp('kazumi_history_upload_');+ addTearDown(() async {+ if (await directory.exists()) {+ await directory.delete(recursive: true);+ }+ });+ final service = HistorySyncService.forTesting(directory);+ final runDirectory = await directory.createTemp('run-');+ await service.appendEvents([+ _upsert(+ deviceId: 'device-a',+ seq: 1,+ updatedAt: 1000,+ episode: 1,+ progressMs: 10,+ ),+ ]);+ final activeFile = await service.localChangeLogFile();+ await activeFile.writeAsString(+ '{"eventId":"truncated"\n',+ mode: FileMode.append,+ flush: true,+ );+ await service.appendEvents([+ _upsert(+ deviceId: 'device-a',+ seq: 2,+ updatedAt: 2000,+ episode: 2,+ progressMs: 20,+ ),+ ]);++ final uploadFile = await service.copyActiveLogForUpload(runDirectory);++ expect(uploadFile, isNotNull);+ final content = await uploadFile!.readAsString();+ expect(content, contains('device-a:1'));+ expect(content, contains('device-a:2'));+ expect(content, isNot(contains('truncated')));+ expect(HistorySyncCodec.eventsFromJsonLines(content), hasLength(2));++ // The damaged active log converges: malformed lines are gone for good+ // instead of being re-skipped on every following sync.+ final repairedContent = await activeFile.readAsString();+ expect(repairedContent, isNot(contains('truncated')));+ expect(HistorySyncCodec.eventsFromJsonLines(repairedContent),+ hasLength(2));+ });++ test('upload copy returns null when log has no valid events', () async {+ final directory = await Directory.systemTemp.createTemp(+ 'kazumi_history_upload_invalid_',+ );+ addTearDown(() async {+ if (await directory.exists()) {+ await directory.delete(recursive: true);+ }+ });+ final service = HistorySyncService.forTesting(directory);+ final runDirectory = await directory.createTemp('run-');+ final activeFile = await service.localChangeLogFile();+ await activeFile.parent.create(recursive: true);+ await activeFile.writeAsString('{"eventId":"truncated"\n', flush: true);++ final uploadFile = await service.copyActiveLogForUpload(runDirectory);++ expect(uploadFile, isNull);+ // Fully-damaged log converges to empty instead of lingering.+ expect(await activeFile.readAsString(), isEmpty);+ });+test('skips malformed remote files transactionally', () async {final directory = await Directory.systemTemp.createTemp('kazumi_history_remote_invalid_',