Skip to content

基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。

fix(sync): reduce startup memory during webdav history sync (#2310)

Predidita11e2069a904
diff --git a/lib/modules/history/history_sync.dart b/lib/modules/history/history_sync.dart
index 9762d310..a2679a2a 100644
--- a/lib/modules/history/history_sync.dart
+++ b/lib/modules/history/history_sync.dart
@@ -473,7 +473,7 @@ class HistorySyncState {
if (entryKind == HistoryEntryKind.online) {
deletedVersions.remove(legacyEntityKey);
}
- if (_shouldApplyLegacyWatchState(event)) {
+ if (_carriesLegacyWatchState(event)) {
_applyUpsertWatchState(event);
}
}
@@ -615,13 +615,6 @@ class HistorySyncState {
return HistorySyncVersion.compare(a, b) >= 0 ? a : b;
}
- bool _shouldApplyLegacyWatchState(HistorySyncEvent event) {
- final hasWatchStatePayload = event.carriesWatchState ||
- event.lastSrc != null ||
- event.lastWatchEpisodeName != null;
- return hasWatchStatePayload && !event.eventId.startsWith('local-state:');
- }
-
static Map<String, String> _canonicalizeVersionMap(
Map<String, String> versions,
String Function(String key) canonicalKey,
@@ -675,6 +668,137 @@ class HistorySyncMerger {
HistorySyncMerger._();
}
+/// Incrementally reduces history events without retaining the full stream.
+///
+/// Only the latest last-write-wins event for each progress slot, watch state,
+/// delete tombstone, and global clear is retained. The bounded set is sorted
+/// when materializing a snapshot so results stay identical even when files
+/// arrive in a different order.
+class HistorySyncStreamMerger {
+ HistorySyncStreamMerger(HistorySyncSnapshot snapshot) : _snapshot = snapshot;
+
+ final HistorySyncSnapshot _snapshot;
+ final Map<String, HistorySyncEvent> _progressEvents = {};
+ final Map<String, HistorySyncEvent> _watchStateEvents = {};
+ final Map<String, HistorySyncEvent> _deleteEvents = {};
+ HistorySyncEvent? _clearEvent;
+
+ void add(HistorySyncEvent event) {
+ _validate(event);
+ 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);
+ if (_carriesLegacyWatchState(event)) {
+ _keepLatest(_watchStateEvents, entityKey, event);
+ }
+ case HistorySyncOp.upsertWatchState:
+ _keepLatest(_watchStateEvents, _upsertEntityKey(event), event);
+ case HistorySyncOp.deleteHistory:
+ _keepLatest(
+ _deleteEvents,
+ event.entityKey ?? 'invalid-delete:${event.eventId}',
+ event,
+ );
+ case HistorySyncOp.clearAll:
+ final current = _clearEvent;
+ if (current == null ||
+ HistorySyncVersion.compare(event.version, current.version) > 0) {
+ _clearEvent = event;
+ }
+ }
+ }
+
+ void addAll(Iterable<HistorySyncEvent> events) {
+ for (final event in events) {
+ add(event);
+ }
+ }
+
+ HistorySyncSnapshot snapshot() {
+ final uniqueEvents = <String, HistorySyncEvent>{};
+ final clearEvent = _clearEvent;
+ if (clearEvent != null) {
+ uniqueEvents[clearEvent.eventId] = clearEvent;
+ }
+ for (final events in [
+ _deleteEvents.values,
+ _watchStateEvents.values,
+ _progressEvents.values,
+ ]) {
+ for (final event in events) {
+ uniqueEvents[event.eventId] = event;
+ }
+ }
+ final sortedEvents = uniqueEvents.values.toList()
+ ..sort((a, b) => HistorySyncVersion.compare(a.version, b.version));
+ final state = HistorySyncState.fromSnapshot(_snapshot);
+ for (final event in sortedEvents) {
+ state.apply(event);
+ }
+ return state.toSnapshot();
+ }
+
+ void _keepLatest(
+ Map<String, HistorySyncEvent> events,
+ String key,
+ HistorySyncEvent candidate,
+ ) {
+ final current = events[key];
+ if (current == null ||
+ HistorySyncVersion.compare(candidate.version, current.version) > 0) {
+ events[key] = candidate;
+ }
+ }
+
+ 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,
+ HistoryEntryKind.normalize(
+ event.entryKind ?? HistoryEntryKind.online,
+ ),
+ );
+ }
+
+ void _validate(HistorySyncEvent event) {
+ switch (event.op) {
+ case HistorySyncOp.upsertProgress:
+ if (event.bangumiItem == null ||
+ event.adapterName == null ||
+ event.episode == null ||
+ event.road == null ||
+ event.progressMs == null) {
+ throw const FormatException('Invalid upsertProgress history event');
+ }
+ case HistorySyncOp.upsertWatchState:
+ if (event.bangumiItem == null ||
+ event.adapterName == null ||
+ event.episode == null) {
+ throw const FormatException('Invalid upsertWatchState history event');
+ }
+ case HistorySyncOp.deleteHistory:
+ case HistorySyncOp.clearAll:
+ }
+ }
+}
+
+bool _carriesLegacyWatchState(HistorySyncEvent event) {
+ final hasWatchStatePayload = event.carriesWatchState ||
+ event.lastSrc != null ||
+ event.lastWatchEpisodeName != null;
+ return hasWatchStatePayload && !event.eventId.startsWith('local-state:');
+}
+
class HistorySyncVersion {
static String of({
required int updatedAt,
diff --git a/lib/pages/webdav_editor/webdav_setting.dart b/lib/pages/webdav_editor/webdav_setting.dart
index 67f6a604..0ce0038e 100644
--- a/lib/pages/webdav_editor/webdav_setting.dart
+++ b/lib/pages/webdav_editor/webdav_setting.dart
@@ -48,7 +48,9 @@ class _PlayerSettingsPageState extends State<WebDavSettingsPage> {
KazumiDialog.showToast(message: '正在同步观看记录');
var webDav = WebDav();
try {
- await webDav.ping();
+ if (!webDav.isHistorySyncing) {
+ await webDav.ping();
+ }
try {
await webDav.syncHistory();
KazumiLogger().i('WebDav: manual history sync completed');
diff --git a/lib/repositories/history_repository.dart b/lib/repositories/history_repository.dart
index 38a4f470..4a6ad9fd 100644
--- a/lib/repositories/history_repository.dart
+++ b/lib/repositories/history_repository.dart
@@ -4,6 +4,7 @@ import 'package:kazumi/modules/bangumi/bangumi_item.dart';
import 'package:kazumi/modules/history/history_module.dart';
import 'package:kazumi/services/sync/history_sync_service.dart';
import 'package:kazumi/services/logging/logger.dart';
+import 'package:kazumi/services/storage/history_storage_coordinator.dart';
typedef HistoryProgressSyncAppender = Future<void> Function({
required History history,
@@ -114,6 +115,8 @@ class HistoryRepository implements IHistoryRepository {
final HistoryProgressSyncAppender _progressSyncAppender;
final HistoryDeleteSyncAppender _deleteSyncAppender;
final HistoryClearSyncAppender _clearSyncAppender;
+ final HistoryStorageCoordinator _storageCoordinator =
+ HistoryStorageCoordinator();
static Future<void> _appendProgressSync({
required History history,
@@ -200,91 +203,93 @@ class HistoryRepository implements IHistoryRepository {
required PlaybackHistoryIdentity identity,
required Duration progress,
}) async {
- try {
- if (!identity.canRecord) {
- return;
- }
- // 检查隐私模式
- if (getPrivateMode()) {
- return;
- }
-
- final episode = identity.episodeNumber;
- final adapterName = identity.pluginName;
- final bangumiItem = identity.bangumiItem;
+ await _storageCoordinator.run(() async {
+ try {
+ if (!identity.canRecord) {
+ return;
+ }
+ // 检查隐私模式
+ if (getPrivateMode()) {
+ return;
+ }
- final now = DateTime.now();
- final nowMs = now.millisecondsSinceEpoch;
- final legacyKey = History.legacyKey(adapterName, bangumiItem);
- final shouldMigrateLegacy =
- HistoryEntryKind.normalize(identity.entryKind) ==
- HistoryEntryKind.online;
+ final episode = identity.episodeNumber;
+ final adapterName = identity.pluginName;
+ final bangumiItem = identity.bangumiItem;
+
+ final now = DateTime.now();
+ final nowMs = now.millisecondsSinceEpoch;
+ final legacyKey = History.legacyKey(adapterName, bangumiItem);
+ final shouldMigrateLegacy =
+ HistoryEntryKind.normalize(identity.entryKind) ==
+ HistoryEntryKind.online;
+
+ // 获取或创建历史记录
+ var history = _findHistory(
+ adapterName,
+ bangumiItem,
+ identity.entryKind,
+ ) ??
+ History(
+ bangumiItem,
+ episode,
+ adapterName,
+ now,
+ identity.onlineBangumiSrc,
+ identity.episodeTitle,
+ entryKind: identity.entryKind,
+ episodePageUrl: identity.episodePageUrl,
+ );
+
+ // 更新历史记录
+ history.lastWatchEpisode = episode;
+ history.lastWatchTime = now;
+ history.entryKind = HistoryEntryKind.normalize(identity.entryKind);
+ if (identity.onlineBangumiSrc.isNotEmpty) {
+ history.lastSrc = identity.onlineBangumiSrc;
+ }
+ if (identity.episodeTitle.isNotEmpty) {
+ history.lastWatchEpisodeName = identity.episodeTitle;
+ }
+ if (identity.episodePageUrl.isNotEmpty) {
+ history.episodePageUrl = identity.episodePageUrl;
+ }
- // 获取或创建历史记录
- var history = _findHistory(
- adapterName,
- bangumiItem,
- identity.entryKind,
- ) ??
- History(
- bangumiItem,
+ // 更新观看进度
+ var prog = history.progresses[episode];
+ if (prog == null) {
+ history.progresses[episode] = Progress(
episode,
- adapterName,
- now,
- identity.onlineBangumiSrc,
- identity.episodeTitle,
- entryKind: identity.entryKind,
- episodePageUrl: identity.episodePageUrl,
+ identity.road,
+ progress.inMilliseconds,
+ updatedAtMs: nowMs,
);
+ } else {
+ prog.road = identity.road;
+ prog.progress = progress;
+ prog.updatedAtMs = nowMs;
+ }
- // 更新历史记录
- history.lastWatchEpisode = episode;
- history.lastWatchTime = now;
- history.entryKind = HistoryEntryKind.normalize(identity.entryKind);
- if (identity.onlineBangumiSrc.isNotEmpty) {
- history.lastSrc = identity.onlineBangumiSrc;
- }
- if (identity.episodeTitle.isNotEmpty) {
- history.lastWatchEpisodeName = identity.episodeTitle;
- }
- if (identity.episodePageUrl.isNotEmpty) {
- history.episodePageUrl = identity.episodePageUrl;
- }
-
- // 更新观看进度
- var prog = history.progresses[episode];
- if (prog == null) {
- history.progresses[episode] = Progress(
- episode,
- identity.road,
- progress.inMilliseconds,
- updatedAtMs: nowMs,
+ // 保存到存储
+ await _historiesBox.put(history.key, history);
+ if (shouldMigrateLegacy && legacyKey != history.key) {
+ await _historiesBox.delete(legacyKey);
+ }
+ await _progressSyncAppender(
+ history: history,
+ episode: episode,
+ road: identity.road,
+ progressMs: progress.inMilliseconds,
+ updatedAt: nowMs,
+ );
+ } catch (e, stackTrace) {
+ KazumiLogger().e(
+ 'GStorage: update history failed. bangumi=${identity.bangumiItem.name}, episode=${identity.episodeNumber}',
+ error: e,
+ stackTrace: stackTrace,
);
- } else {
- prog.road = identity.road;
- prog.progress = progress;
- prog.updatedAtMs = nowMs;
- }
-
- // 保存到存储
- await _historiesBox.put(history.key, history);
- if (shouldMigrateLegacy && legacyKey != history.key) {
- await _historiesBox.delete(legacyKey);
}
- await _progressSyncAppender(
- history: history,
- episode: episode,
- road: identity.road,
- progressMs: progress.inMilliseconds,
- updatedAt: nowMs,
- );
- } catch (e, stackTrace) {
- KazumiLogger().e(
- 'GStorage: update history failed. bangumi=${identity.bangumiItem.name}, episode=${identity.episodeNumber}',
- error: e,
- stackTrace: stackTrace,
- );
- }
+ });
}
@override
@@ -328,22 +333,24 @@ class HistoryRepository implements IHistoryRepository {
@override
Future<void> deleteHistory(History history) async {
- try {
- await _historiesBox.delete(history.key);
- if (HistoryEntryKind.normalize(history.entryKind) ==
- HistoryEntryKind.online) {
- await _historiesBox.delete(
- History.legacyKey(history.adapterName, history.bangumiItem),
+ await _storageCoordinator.run(() async {
+ try {
+ await _historiesBox.delete(history.key);
+ if (HistoryEntryKind.normalize(history.entryKind) ==
+ HistoryEntryKind.online) {
+ await _historiesBox.delete(
+ History.legacyKey(history.adapterName, history.bangumiItem),
+ );
+ }
+ await _deleteSyncAppender(history);
+ } catch (e, stackTrace) {
+ KazumiLogger().e(
+ 'GStorage: delete history failed. bangumi=${history.bangumiItem.name}',
+ error: e,
+ stackTrace: stackTrace,
);
}
- await _deleteSyncAppender(history);
- } catch (e, stackTrace) {
- KazumiLogger().e(
- 'GStorage: delete history failed. bangumi=${history.bangumiItem.name}',
- error: e,
- stackTrace: stackTrace,
- );
- }
+ });
}
@override
@@ -353,42 +360,46 @@ class HistoryRepository implements IHistoryRepository {
int episode, {
String entryKind = HistoryEntryKind.online,
}) async {
- try {
- var history = _findHistory(adapterName, bangumiItem, entryKind);
- if (history != null && history.progresses[episode] != null) {
- final nowMs = DateTime.now().millisecondsSinceEpoch;
- history.progresses[episode]!.progress = Duration.zero;
- history.progresses[episode]!.updatedAtMs = nowMs;
- await _historiesBox.put(history.key, history);
- await _progressSyncAppender(
- history: history,
- episode: episode,
- road: history.progresses[episode]!.road,
- progressMs: 0,
- updatedAt: nowMs,
+ await _storageCoordinator.run(() async {
+ try {
+ var history = _findHistory(adapterName, bangumiItem, entryKind);
+ if (history != null && history.progresses[episode] != null) {
+ final nowMs = DateTime.now().millisecondsSinceEpoch;
+ history.progresses[episode]!.progress = Duration.zero;
+ history.progresses[episode]!.updatedAtMs = nowMs;
+ await _historiesBox.put(history.key, history);
+ await _progressSyncAppender(
+ history: history,
+ episode: episode,
+ road: history.progresses[episode]!.road,
+ progressMs: 0,
+ updatedAt: nowMs,
+ );
+ }
+ } catch (e, stackTrace) {
+ KazumiLogger().e(
+ 'GStorage: clear progress failed. bangumi=${bangumiItem.name}, episode=$episode',
+ error: e,
+ stackTrace: stackTrace,
);
}
- } catch (e, stackTrace) {
- KazumiLogger().e(
- 'GStorage: clear progress failed. bangumi=${bangumiItem.name}, episode=$episode',
- error: e,
- stackTrace: stackTrace,
- );
- }
+ });
}
@override
Future<void> clearAllHistories() async {
- try {
- await _historiesBox.clear();
- await _clearSyncAppender();
- } catch (e, stackTrace) {
- KazumiLogger().e(
- 'GStorage: clear all histories failed',
- error: e,
- stackTrace: stackTrace,
- );
- }
+ await _storageCoordinator.run(() async {
+ try {
+ await _historiesBox.clear();
+ await _clearSyncAppender();
+ } catch (e, stackTrace) {
+ KazumiLogger().e(
+ 'GStorage: clear all histories failed',
+ error: e,
+ stackTrace: stackTrace,
+ );
+ }
+ });
}
@override
diff --git a/lib/services/storage/history_storage_coordinator.dart b/lib/services/storage/history_storage_coordinator.dart
new file mode 100644
index 00000000..3155f082
--- /dev/null
+++ b/lib/services/storage/history_storage_coordinator.dart
@@ -0,0 +1,15 @@
+import 'package:kazumi/utils/async_serial_queue.dart';
+
+/// Serializes mutations to the history Hive box across repositories and sync.
+class HistoryStorageCoordinator {
+ HistoryStorageCoordinator._();
+
+ static final HistoryStorageCoordinator _instance =
+ HistoryStorageCoordinator._();
+
+ factory HistoryStorageCoordinator() => _instance;
+
+ final AsyncSerialQueue _writes = AsyncSerialQueue();
+
+ Future<T> run<T>(Future<T> Function() action) => _writes.run(action);
+}
diff --git a/lib/services/storage/storage.dart b/lib/services/storage/storage.dart
index 7adf3734..98b2449e 100644
--- a/lib/services/storage/storage.dart
+++ b/lib/services/storage/storage.dart
@@ -11,6 +11,7 @@ import 'package:kazumi/modules/collect/collect_change_module.dart';
import 'package:kazumi/modules/collect/collect_sync_merger.dart';
import 'package:kazumi/modules/search/search_history_module.dart';
import 'package:kazumi/modules/download/download_module.dart';
+import 'package:kazumi/services/storage/history_storage_coordinator.dart';
import 'package:kazumi/services/storage/settings_keys.dart';
export 'package:kazumi/services/storage/settings_keys.dart';
@@ -213,9 +214,9 @@ class GStorage {
final hiveBoxFile = File('${appDocumentDir.path}/hive/$boxName.hive');
if (await hiveBoxFile.exists()) {
await hiveBoxFile.copy(backupFilePath);
- print('Backup success: $backupFilePath');
+ KazumiLogger().i('GStorage: backup success: $backupFilePath');
} else {
- print('Hive box not exists');
+ KazumiLogger().w('GStorage: Hive box does not exist: $boxName');
}
}
@@ -223,25 +224,24 @@ class GStorage {
final backupFile = File(backupFilePath);
final backupContent = await backupFile.readAsBytes();
final tempBox = await Hive.openBox('tempHistoryBox', bytes: backupContent);
- final tempBoxItems = tempBox.toMap().entries;
-
- for (var tempBoxItem in tempBoxItems) {
- final tempHistory = tempBoxItem.value as History;
- tempHistory.entryKind = HistoryEntryKind.normalize(tempHistory.entryKind);
- final targetKey = tempHistory.key;
- if (histories.get(targetKey) != null) {
- if (histories
- .get(targetKey)!
- .lastWatchTime
- .isBefore(tempHistory.lastWatchTime)) {
- await histories.delete(targetKey);
- await histories.put(targetKey, tempHistory);
+ try {
+ final tempBoxItems = tempBox.toMap().entries;
+ await HistoryStorageCoordinator().run(() async {
+ for (final tempBoxItem in tempBoxItems) {
+ final tempHistory = tempBoxItem.value as History;
+ tempHistory.entryKind =
+ HistoryEntryKind.normalize(tempHistory.entryKind);
+ final targetKey = tempHistory.key;
+ final existing = histories.get(targetKey);
+ if (existing == null ||
+ existing.lastWatchTime.isBefore(tempHistory.lastWatchTime)) {
+ await histories.put(targetKey, tempHistory);
+ }
}
- } else {
- await histories.put(targetKey, tempHistory);
- }
+ });
+ } finally {
+ await tempBox.close();
}
- await tempBox.close();
}
static Future<void> restoreCollectibles(String backupFilePath) async {
diff --git a/lib/services/sync/history_sync_service.dart b/lib/services/sync/history_sync_service.dart
index 4e85a1cc..4d978805 100644
--- a/lib/services/sync/history_sync_service.dart
+++ b/lib/services/sync/history_sync_service.dart
@@ -1,28 +1,47 @@
+import 'dart:convert';
import 'dart:io';
+import 'dart:isolate';
+import 'package:flutter/foundation.dart';
import 'package:kazumi/modules/history/history_module.dart';
import 'package:kazumi/modules/history/history_sync.dart';
import 'package:kazumi/services/logging/logger.dart';
+import 'package:kazumi/services/storage/history_storage_coordinator.dart';
import 'package:kazumi/services/storage/storage.dart';
+import 'package:kazumi/utils/async_serial_queue.dart';
import 'package:path_provider/path_provider.dart';
class HistorySyncService {
- static const int compactLocalLogThresholdBytes = 1024 * 1024;
+ static const int checkpointLogThresholdBytes = 1024 * 1024;
+ static const String _pendingLogPrefix = 'history.local.pending.';
- HistorySyncService._internal();
+ HistorySyncService._internal()
+ : _applicationSupportDirectoryProvider = getApplicationSupportDirectory;
static final HistorySyncService _instance = HistorySyncService._internal();
factory HistorySyncService() => _instance;
+ @visibleForTesting
+ HistorySyncService.forTesting(Directory applicationSupportDirectory)
+ : _applicationSupportDirectoryProvider =
+ (() async => applicationSupportDirectory);
+
+ final Future<Directory> Function() _applicationSupportDirectoryProvider;
+ final AsyncSerialQueue _localLogQueue = AsyncSerialQueue();
+ final AsyncSerialQueue _sequenceQueue = AsyncSerialQueue();
+ int _captureSequence = 0;
+
Future<String> getDeviceId() async {
- final existing = GStorage.getSetting(SettingsKeys.historySyncDeviceId);
- if (existing.isNotEmpty) {
- return existing;
- }
- final deviceId = HistorySyncDevice.generateDeviceId();
- await GStorage.putSetting(SettingsKeys.historySyncDeviceId, deviceId);
- return deviceId;
+ return _sequenceQueue.run(() async {
+ final existing = GStorage.getSetting(SettingsKeys.historySyncDeviceId);
+ if (existing.isNotEmpty) {
+ return existing;
+ }
+ final deviceId = HistorySyncDevice.generateDeviceId();
+ await GStorage.putSetting(SettingsKeys.historySyncDeviceId, deviceId);
+ return deviceId;
+ });
}
Future<void> appendUpsertProgress({
@@ -63,13 +82,19 @@ class HistorySyncService {
}
Future<void> appendEvents(Iterable<HistorySyncEvent> events) async {
- final file = await localChangeLogFile();
- await file.parent.create(recursive: true);
- await file.writeAsString(
- HistorySyncCodec.eventsToJsonLines(events),
- mode: FileMode.append,
- flush: true,
- );
+ final content = HistorySyncCodec.eventsToJsonLines(events);
+ if (content.isEmpty) {
+ return;
+ }
+ await _localLogQueue.run(() async {
+ final file = await localChangeLogFile();
+ await file.parent.create(recursive: true);
+ await file.writeAsString(
+ content,
+ mode: FileMode.append,
+ flush: true,
+ );
+ });
}
Future<void> appendDeleteHistory(History history) async {
@@ -91,43 +116,18 @@ class HistorySyncService {
await appendEvent(event);
}
- Future<List<HistorySyncEvent>> readLocalEvents() async {
- final file = await localChangeLogFile();
- if (!await file.exists()) {
- return [];
- }
- final content = await file.readAsString();
- return HistorySyncCodec.eventsFromJsonLines(content);
- }
-
- Future<String> readLocalEventLines() async {
- final file = await localChangeLogFile();
- if (!await file.exists()) {
- return '';
- }
- return file.readAsString();
- }
-
- Future<void> replaceLocalEvents(Iterable<HistorySyncEvent> events) async {
- final file = await localChangeLogFile();
- await file.parent.create(recursive: true);
- await file.writeAsString(
- HistorySyncCodec.eventsToJsonLines(events),
- flush: true,
- );
- }
-
- Future<bool> shouldCompactLocalLog() async {
- final file = await localChangeLogFile();
- if (!await file.exists()) {
- return false;
- }
- return file.lengthSync() > compactLocalLogThresholdBytes;
+ Future<HistorySyncSnapshot> buildSnapshotFromLocal() {
+ return HistoryStorageCoordinator().run(() async {
+ return HistorySyncSnapshot.fromHistories(
+ GStorage.histories.values.toList(),
+ );
+ });
}
- HistorySyncSnapshot buildSnapshotFromLocal() {
- return HistorySyncSnapshot.fromHistories(
- GStorage.histories.values.toList());
+ Future<List<HistorySyncEvent>> buildLocalStateEvents() {
+ return HistoryStorageCoordinator().run(() async {
+ return buildStateEventsFromHistories(GStorage.histories.values);
+ });
}
static List<HistorySyncEvent> buildStateEventsFromHistories(
@@ -181,24 +181,199 @@ class HistorySyncService {
return events;
}
- Future<void> applySnapshotToLocal(HistorySyncSnapshot snapshot) async {
- await GStorage.histories.clear();
- for (final history in snapshot.histories) {
- await GStorage.histories.put(history.key, history);
+ Future<HistorySyncSnapshot> reconcileAndApplySnapshot(
+ HistorySyncSnapshot snapshot,
+ ) {
+ return HistoryStorageCoordinator().run(() async {
+ final reconciled = HistorySyncMerger.merge(
+ snapshot: snapshot,
+ events: buildStateEventsFromHistories(GStorage.histories.values),
+ );
+ await _applySnapshotToLocal(reconciled);
+ return reconciled;
+ });
+ }
+
+ Future<void> _applySnapshotToLocal(HistorySyncSnapshot snapshot) async {
+ final historiesByKey = {
+ for (final history in snapshot.histories) history.key: history,
+ };
+ final staleKeys = GStorage.histories.keys
+ .where((key) => !historiesByKey.containsKey(key))
+ .toList();
+
+ if (historiesByKey.isNotEmpty) {
+ await GStorage.histories.putAll(historiesByKey);
+ }
+ if (staleKeys.isNotEmpty) {
+ await GStorage.histories.deleteAll(staleKeys);
}
await GStorage.histories.flush();
}
+ /// Creates a stable set of local logs for one sync attempt.
+ ///
+ /// A checkpoint attempt renames the active log to a pending file, allowing
+ /// playback to continue appending to a fresh log. Pending files survive
+ /// failed or interrupted syncs and are picked up by the next attempt.
+ Future<HistorySyncLogBatch> prepareLocalLogs({
+ required Directory runDirectory,
+ required bool forceCheckpoint,
+ }) {
+ return _localLogQueue.run(() async {
+ final activeFile = await localChangeLogFile();
+ await activeFile.parent.create(recursive: true);
+ await runDirectory.create(recursive: true);
+
+ final pendingFiles = await _pendingLocalLogFiles(activeFile.parent);
+ final activeLength =
+ await activeFile.exists() ? await activeFile.length() : 0;
+ final pendingLength = await _totalFileLength(pendingFiles);
+ final shouldCheckpoint = forceCheckpoint ||
+ pendingFiles.isNotEmpty ||
+ activeLength + pendingLength > checkpointLogThresholdBytes;
+
+ if (shouldCheckpoint) {
+ if (activeLength > 0) {
+ final separator = Platform.pathSeparator;
+ final pendingFile = File(
+ '${activeFile.parent.path}$separator'
+ '$_pendingLogPrefix'
+ '${DateTime.now().microsecondsSinceEpoch}.'
+ '${_captureSequence++}.jsonl',
+ );
+ await activeFile.rename(pendingFile.path);
+ pendingFiles.add(pendingFile);
+ }
+ pendingFiles.sort((a, b) => a.path.compareTo(b.path));
+ return HistorySyncLogBatch(
+ files: pendingFiles,
+ shouldCheckpoint: true,
+ );
+ }
+
+ if (activeLength == 0) {
+ return HistorySyncLogBatch(
+ files: [],
+ shouldCheckpoint: false,
+ );
+ }
+
+ final stableCopy = File(
+ '${runDirectory.path}${Platform.pathSeparator}local-events.jsonl',
+ );
+ await activeFile.copy(stableCopy.path);
+ return HistorySyncLogBatch(
+ files: [stableCopy],
+ shouldCheckpoint: false,
+ );
+ });
+ }
+
+ Future<File?> copyActiveLogForUpload(Directory runDirectory) {
+ return _localLogQueue.run(() async {
+ final activeFile = await localChangeLogFile();
+ if (!await activeFile.exists() || await activeFile.length() == 0) {
+ return null;
+ }
+ final uploadFile = File(
+ '${runDirectory.path}${Platform.pathSeparator}'
+ 'local-events-upload.jsonl',
+ );
+ await activeFile.copy(uploadFile.path);
+ return uploadFile;
+ });
+ }
+
+ Future<void> completeCheckpoint(HistorySyncLogBatch batch) {
+ return _localLogQueue.run(() async {
+ if (!batch.shouldCheckpoint) {
+ return;
+ }
+ for (final file in batch.files) {
+ if (_isPendingLocalLog(file) && await file.exists()) {
+ await file.delete();
+ }
+ }
+ });
+ }
+
+ Future<HistorySyncSnapshot> readSnapshotFile(File file) async {
+ final path = file.path;
+ final json = await Isolate.run(() => _readSnapshotFile(path));
+ return HistorySyncSnapshot.fromJson(json);
+ }
+
+ Future<HistorySyncSnapshot> mergeEventFiles({
+ required HistorySyncSnapshot snapshot,
+ required Iterable<File> eventFiles,
+ required Iterable<HistorySyncEvent> inMemoryEvents,
+ }) async {
+ final request = <String, dynamic>{
+ 'snapshot': snapshot.toJson(),
+ 'eventFiles': eventFiles.map((file) => file.path).toList(),
+ 'events': inMemoryEvents.map((event) => event.toJson()).toList(),
+ };
+ final mergedJson =
+ await Isolate.run(() => _mergeHistoryEventFiles(request));
+ return HistorySyncSnapshot.fromJson(mergedJson);
+ }
+
+ /// Merges independently-owned remote logs without letting one invalid file
+ /// block every device. Each file is transactional: none of its events are
+ /// applied if parsing fails.
+ Future<HistorySyncSnapshot> mergeRemoteEventFiles({
+ required HistorySyncSnapshot snapshot,
+ required Iterable<File> eventFiles,
+ required Future<void> Function(
+ File file,
+ Object error,
+ StackTrace stackTrace,
+ ) onInvalidFile,
+ }) async {
+ var mergedSnapshot = snapshot;
+ for (final file in eventFiles) {
+ try {
+ mergedSnapshot = await mergeEventFiles(
+ snapshot: mergedSnapshot,
+ eventFiles: [file],
+ inMemoryEvents: const [],
+ );
+ } catch (e, stackTrace) {
+ await onInvalidFile(file, e, stackTrace);
+ }
+ }
+ return mergedSnapshot;
+ }
+
+ Future<void> writeSnapshotFile(
+ HistorySyncSnapshot snapshot,
+ File file,
+ ) async {
+ final path = file.path;
+ final snapshotJson = snapshot.toJson();
+ await Isolate.run(() async {
+ final target = File(path);
+ await target.parent.create(recursive: true);
+ await target.writeAsString(
+ jsonEncode(snapshotJson),
+ flush: true,
+ );
+ });
+ }
+
Future<File> localChangeLogFile() async {
- final directory = await getApplicationSupportDirectory();
+ final directory = await _applicationSupportDirectoryProvider();
return File('${directory.path}/webdavTemp/history.local.jsonl');
}
Future<int> _nextSeq() async {
- final value = GStorage.getSetting(SettingsKeys.historySyncSequence);
- final next = value + 1;
- await GStorage.putSetting(SettingsKeys.historySyncSequence, next);
- return next;
+ return _sequenceQueue.run(() async {
+ final value = GStorage.getSetting(SettingsKeys.historySyncSequence);
+ final next = value + 1;
+ await GStorage.putSetting(SettingsKeys.historySyncSequence, next);
+ return next;
+ });
}
Future<void> appendSafely(Future<void> Function() append) async {
@@ -218,4 +393,86 @@ class HistorySyncService {
);
}
}
+
+ Future<List<File>> _pendingLocalLogFiles(Directory directory) async {
+ if (!await directory.exists()) {
+ return [];
+ }
+ final files = <File>[];
+ await for (final entity in directory.list(followLinks: false)) {
+ if (entity is File && _isPendingLocalLog(entity)) {
+ files.add(entity);
+ }
+ }
+ files.sort((a, b) => a.path.compareTo(b.path));
+ return files;
+ }
+
+ bool _isPendingLocalLog(File file) {
+ final name = file.path.split(Platform.pathSeparator).last;
+ return name.startsWith(_pendingLogPrefix) && name.endsWith('.jsonl');
+ }
+
+ Future<int> _totalFileLength(Iterable<File> files) async {
+ var total = 0;
+ for (final file in files) {
+ if (await file.exists()) {
+ total += await file.length();
+ }
+ }
+ return total;
+ }
+}
+
+class HistorySyncLogBatch {
+ HistorySyncLogBatch({
+ required List<File> files,
+ required this.shouldCheckpoint,
+ }) : files = List.unmodifiable(files);
+
+ final List<File> files;
+ final bool shouldCheckpoint;
+}
+
+Future<Map<String, dynamic>> _readSnapshotFile(String path) async {
+ final content = await File(path).openRead().transform(utf8.decoder).join();
+ return Map<String, dynamic>.from(jsonDecode(content) as Map);
+}
+
+Future<Map<String, dynamic>> _mergeHistoryEventFiles(
+ Map<String, dynamic> request,
+) async {
+ final snapshot = HistorySyncSnapshot.fromJson(
+ Map<String, dynamic>.from(request['snapshot'] as Map),
+ );
+ final merger = HistorySyncStreamMerger(snapshot);
+ final eventFiles = (request['eventFiles'] as List).cast<String>();
+
+ for (final path in eventFiles) {
+ final lines = File(path)
+ .openRead()
+ .transform(utf8.decoder)
+ .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),
+ ),
+ );
+ }
+ }
+
+ merger.addAll(
+ (request['events'] as List).map(
+ (eventJson) => HistorySyncEvent.fromJson(
+ Map<String, dynamic>.from(eventJson as Map),
+ ),
+ ),
+ );
+
+ return merger.snapshot().toJson();
}
diff --git a/lib/services/sync/webdav.dart b/lib/services/sync/webdav.dart
index 40dc1e24..5ebe50f5 100644
--- a/lib/services/sync/webdav.dart
+++ b/lib/services/sync/webdav.dart
@@ -1,7 +1,4 @@
import 'dart:io';
-import 'dart:convert';
-import 'dart:async';
-import 'dart:typed_data';
import 'package:webdav_client/webdav_client.dart' as webdav;
import 'package:path_provider/path_provider.dart';
import 'package:kazumi/modules/history/history_sync.dart';
@@ -10,6 +7,8 @@ import 'package:kazumi/services/logging/logger.dart';
import 'package:kazumi/modules/collect/collect_module.dart';
import 'package:kazumi/modules/collect/collect_change_module.dart';
import 'package:kazumi/services/sync/history_sync_service.dart';
+import 'package:kazumi/utils/async_serial_queue.dart';
+import 'package:kazumi/utils/async_single_flight.dart';
class WebDav {
static const String _syncRootPath = '/kazumiSync';
@@ -24,8 +23,13 @@ class WebDav {
late webdav.Client client;
bool initialized = false;
- bool isHistorySyncing = false;
- Future<void> _webDavOperationQueue = Future.value();
+ static const Duration _staleRunDirectoryAge = Duration(hours: 24);
+
+ final AsyncSingleFlight<void> _historySyncSingleFlight =
+ AsyncSingleFlight<void>();
+ final AsyncSerialQueue _webDavOperationQueue = AsyncSerialQueue();
+
+ bool get isHistorySyncing => _historySyncSingleFlight.isRunning;
WebDav._internal();
static final WebDav _instance = WebDav._internal();
@@ -62,19 +66,7 @@ class WebDav {
}
Future<T> _runWebDavExclusive<T>(Future<T> Function() action) {
- final previousOperation = _webDavOperationQueue;
- final completer = Completer<T>();
- _webDavOperationQueue = (() async {
- try {
- await previousOperation;
- } catch (_) {}
- try {
- completer.complete(await action());
- } catch (e, stackTrace) {
- completer.completeError(e, stackTrace);
- }
- })();
- return completer.future;
+ return _webDavOperationQueue.run(action);
}
Future<void> _updateBox(String boxName) async {
@@ -98,20 +90,15 @@ class WebDav {
} catch (_) {}
}
- Future<void> syncHistory() async {
- if (isHistorySyncing) {
- KazumiLogger().w('WebDav: History is currently syncing');
- throw Exception('History is currently syncing');
- }
- isHistorySyncing = true;
- try {
- await _runWebDavExclusive(_syncHistory);
- } catch (e) {
- KazumiLogger().e('WebDav: history sync failed', error: e);
- rethrow;
- } finally {
- isHistorySyncing = false;
- }
+ Future<void> syncHistory() {
+ return _historySyncSingleFlight.run(() async {
+ try {
+ await _runWebDavExclusive(_syncHistory);
+ } catch (e) {
+ KazumiLogger().e('WebDav: history sync failed', error: e);
+ rethrow;
+ }
+ });
}
Future<void> updateCollectibles() async {
@@ -199,48 +186,304 @@ class WebDav {
Future<void> _syncHistory() async {
await _ensureHistoryStorage();
final historySync = HistorySyncService();
- final localEvents = await historySync.readLocalEvents();
- final localStateEvents = await _eventsFromLocalHistories();
- var remoteSnapshot =
- await _readHistorySnapshot() ?? HistorySyncSnapshot.empty();
- final remoteEvents = await _readRemoteHistoryEvents();
-
- if (remoteSnapshot.histories.isEmpty &&
- remoteSnapshot.itemVersions.isEmpty &&
- remoteEvents.isEmpty &&
- await _tryImportLegacyHistory()) {
- remoteSnapshot = historySync.buildSnapshotFromLocal();
- await _writeHistorySnapshot(remoteSnapshot);
+ final deviceId = await historySync.getDeviceId();
+ final runDirectory = await _createHistorySyncRunDirectory();
+
+ try {
+ final downloads = await _downloadHistorySyncFiles(
+ runDirectory: runDirectory,
+ deviceId: deviceId,
+ );
+ final snapshotReadResult = await _readRemoteHistorySnapshot(
+ historySync,
+ downloads.snapshotFile,
+ );
+ var remoteSnapshot = snapshotReadResult.snapshot;
+ var importedLegacyHistory = false;
+
+ if (_isEmptyHistorySnapshot(remoteSnapshot) &&
+ downloads.eventFiles.isEmpty) {
+ importedLegacyHistory = await _tryImportLegacyHistory(runDirectory);
+ if (importedLegacyHistory) {
+ remoteSnapshot = await historySync.buildSnapshotFromLocal();
+ }
+ }
+
+ final snapshotInitialized =
+ GStorage.getSetting(SettingsKeys.historySyncSnapshotInitialized);
+ final localBatch = await historySync.prepareLocalLogs(
+ runDirectory: runDirectory,
+ forceCheckpoint: snapshotInitialized != true ||
+ snapshotReadResult.needsRepair ||
+ downloads.currentDeviceLogOversized ||
+ importedLegacyHistory,
+ );
+ final mergedRemoteSnapshot = await _mergeRemoteHistoryEventFiles(
+ historySync: historySync,
+ snapshot: remoteSnapshot,
+ eventFiles: downloads.eventFiles,
+ );
+ final mergedFromFiles = await historySync.mergeEventFiles(
+ snapshot: mergedRemoteSnapshot,
+ eventFiles: localBatch.files,
+ inMemoryEvents: await historySync.buildLocalStateEvents(),
+ );
+
+ final mergedSnapshot = await historySync.reconcileAndApplySnapshot(
+ mergedFromFiles,
+ );
+
+ if (localBatch.shouldCheckpoint) {
+ final snapshotFile = File(
+ '${runDirectory.path}${Platform.pathSeparator}snapshot.json',
+ );
+ await historySync.writeSnapshotFile(mergedSnapshot, snapshotFile);
+ await _publishHistorySnapshot(
+ snapshotFile: snapshotFile,
+ deviceId: deviceId,
+ );
+ await historySync.completeCheckpoint(localBatch);
+ await _removeDeviceHistoryChanges(deviceId);
+ await GStorage.putSetting(
+ SettingsKeys.historySyncSnapshotInitialized,
+ true,
+ );
+ } else {
+ final uploadFile =
+ await historySync.copyActiveLogForUpload(runDirectory);
+ if (uploadFile != null) {
+ await _publishDeviceHistoryChanges(
+ sourceFile: uploadFile,
+ deviceId: deviceId,
+ );
+ }
+ }
+ } finally {
+ try {
+ if (await runDirectory.exists()) {
+ await runDirectory.delete(recursive: true);
+ }
+ } catch (e) {
+ KazumiLogger().w(
+ 'WebDav: failed to clean history sync temp directory',
+ error: e,
+ );
+ }
+ }
+ }
+
+ bool _isEmptyHistorySnapshot(HistorySyncSnapshot snapshot) {
+ return snapshot.histories.isEmpty &&
+ snapshot.itemVersions.isEmpty &&
+ snapshot.progressVersions.isEmpty &&
+ snapshot.deletedVersions.isEmpty &&
+ snapshot.clearVersion == null;
+ }
+
+ Future<_HistorySnapshotReadResult> _readRemoteHistorySnapshot(
+ HistorySyncService historySync,
+ File? snapshotFile,
+ ) async {
+ if (snapshotFile == null) {
+ return _HistorySnapshotReadResult(
+ snapshot: HistorySyncSnapshot.empty(),
+ needsRepair: false,
+ );
+ }
+
+ try {
+ return _HistorySnapshotReadResult(
+ snapshot: await historySync.readSnapshotFile(snapshotFile),
+ needsRepair: false,
+ );
+ } catch (e, stackTrace) {
+ KazumiLogger().w(
+ 'WebDav: invalid history snapshot, rebuilding from event logs',
+ error: e,
+ stackTrace: stackTrace,
+ );
+ return _HistorySnapshotReadResult(
+ snapshot: HistorySyncSnapshot.empty(),
+ needsRepair: true,
+ );
+ }
+ }
+
+ Future<HistorySyncSnapshot> _mergeRemoteHistoryEventFiles({
+ required HistorySyncService historySync,
+ required HistorySyncSnapshot snapshot,
+ required List<_DownloadedHistoryEventFile> eventFiles,
+ }) async {
+ final eventFilesByPath = {
+ for (final eventFile in eventFiles)
+ eventFile.localFile.path: eventFile.remoteName,
+ };
+ return historySync.mergeRemoteEventFiles(
+ snapshot: snapshot,
+ eventFiles: eventFiles.map((eventFile) => eventFile.localFile),
+ onInvalidFile: (file, error, stackTrace) async {
+ final remoteName = eventFilesByPath[file.path]!;
+ KazumiLogger().w(
+ 'WebDav: invalid remote history event log $remoteName, skipping',
+ error: error,
+ stackTrace: stackTrace,
+ );
+ await _quarantineRemoteHistoryEventFile(remoteName);
+ },
+ );
+ }
+
+ Future<Directory> _createHistorySyncRunDirectory() async {
+ await _cleanupStaleHistorySyncRunDirectories();
+ return webDavLocalTempDirectory.createTemp('history-sync-run-');
+ }
+
+ Future<void> _cleanupStaleHistorySyncRunDirectories() async {
+ await _ensureLocalTempDirectory();
+ final staleBefore = DateTime.now().subtract(_staleRunDirectoryAge);
+ await for (final entity
+ in webDavLocalTempDirectory.list(followLinks: false)) {
+ if (entity is! Directory) {
+ continue;
+ }
+ final name = entity.path.split(Platform.pathSeparator).last;
+ if (!name.startsWith('history-sync-run-')) {
+ continue;
+ }
+ try {
+ final stat = await entity.stat();
+ // A recent directory may belong to another running Kazumi process.
+ if (stat.modified.isAfter(staleBefore)) {
+ continue;
+ }
+ await entity.delete(recursive: true);
+ } catch (e) {
+ KazumiLogger().w(
+ 'WebDav: failed to remove stale history sync directory $name',
+ error: e,
+ );
+ }
+ }
+ }
+
+ Future<_HistorySyncDownloads> _downloadHistorySyncFiles({
+ required Directory runDirectory,
+ required String deviceId,
+ }) async {
+ File? snapshotFile;
+ final historyEntries = await client.readDir(_historyRootPath);
+ final hasSnapshot = historyEntries.any(
+ (file) => file.name == 'snapshot.json',
+ );
+ if (hasSnapshot) {
+ snapshotFile = File(
+ '${runDirectory.path}${Platform.pathSeparator}remote-snapshot.json',
+ );
+ await client.read2File(_historySnapshotPath, snapshotFile.path);
}
- final mergedSnapshot = HistorySyncMerger.merge(
- snapshot: remoteSnapshot,
- events: [
- ...remoteEvents,
- ...localStateEvents,
- ...localEvents,
- ],
+ final eventFiles = <_DownloadedHistoryEventFile>[];
+ var currentDeviceLogOversized = false;
+ final changeEntries = await client.readDir(_historyChangesPath);
+ var index = 0;
+ for (final entry in changeEntries) {
+ final name = entry.name ?? '';
+ if (!name.endsWith('.jsonl') || entry.size == 0) {
+ continue;
+ }
+ final localFile = File(
+ '${runDirectory.path}${Platform.pathSeparator}'
+ 'remote-events-${index++}.jsonl',
+ );
+ await client.read2File(
+ '$_historyChangesPath/$name',
+ localFile.path,
+ );
+ if (name == '$deviceId.jsonl' &&
+ await localFile.length() >
+ HistorySyncService.checkpointLogThresholdBytes) {
+ currentDeviceLogOversized = true;
+ }
+ eventFiles.add(
+ _DownloadedHistoryEventFile(
+ remoteName: name,
+ localFile: localFile,
+ ),
+ );
+ }
+
+ return _HistorySyncDownloads(
+ snapshotFile: snapshotFile,
+ eventFiles: eventFiles,
+ currentDeviceLogOversized: currentDeviceLogOversized,
);
- await historySync.applySnapshotToLocal(mergedSnapshot);
+ }
- if (localEvents.isNotEmpty) {
- await _writeDeviceHistoryChanges(localEvents);
+ Future<void> _publishHistorySnapshot({
+ required File snapshotFile,
+ required String deviceId,
+ }) {
+ return _publishRemoteFile(
+ sourceFile: snapshotFile,
+ destinationPath: _historySnapshotPath,
+ temporaryPath: '$_historySnapshotPath.$deviceId.cache',
+ );
+ }
+
+ Future<void> _publishDeviceHistoryChanges({
+ required File sourceFile,
+ required String deviceId,
+ }) {
+ final destinationPath = '$_historyChangesPath/$deviceId.jsonl';
+ return _publishRemoteFile(
+ sourceFile: sourceFile,
+ destinationPath: destinationPath,
+ temporaryPath: '$destinationPath.cache',
+ );
+ }
+
+ Future<void> _publishRemoteFile({
+ required File sourceFile,
+ required String destinationPath,
+ required String temporaryPath,
+ }) async {
+ try {
+ await client.remove(temporaryPath);
+ } catch (_) {}
+ try {
+ await client.writeFromFile(sourceFile.path, temporaryPath);
+ await client.rename(temporaryPath, destinationPath, true);
+ } catch (_) {
+ try {
+ await client.remove(temporaryPath);
+ } catch (_) {}
+ rethrow;
}
+ }
- final snapshotInitialized =
- GStorage.getSetting(SettingsKeys.historySyncSnapshotInitialized);
- if (snapshotInitialized != true ||
- await historySync.shouldCompactLocalLog()) {
- await _writeHistorySnapshot(mergedSnapshot);
- await historySync.replaceLocalEvents(const []);
- await _writeDeviceHistoryChanges(const []);
- await GStorage.putSetting(
- SettingsKeys.historySyncSnapshotInitialized,
- true,
+ Future<void> _removeDeviceHistoryChanges(String deviceId) async {
+ final remotePath = '$_historyChangesPath/$deviceId.jsonl';
+ try {
+ await client.remove(remotePath);
+ } catch (e) {
+ KazumiLogger().w(
+ 'WebDav: failed to remove checkpointed device history log',
+ error: e,
);
}
}
+ Future<void> _quarantineRemoteHistoryEventFile(String remoteName) {
+ final sourcePath = '$_historyChangesPath/$remoteName';
+ final quarantinePath = '$sourcePath.invalid.'
+ '${DateTime.now().millisecondsSinceEpoch}';
+ return _quarantineRemoteFile(
+ sourcePath: sourcePath,
+ quarantinePath: quarantinePath,
+ description: 'history event log $remoteName',
+ );
+ }
+
Future<void> _ensureHistoryStorage() async {
await _ensureLocalTempDirectory();
await _ensureRemoteDirectory(_syncRootPath);
@@ -279,105 +522,73 @@ class WebDav {
}
}
- Future<HistorySyncSnapshot?> _readHistorySnapshot() async {
- try {
- final content = await _readRemoteText(_historySnapshotPath);
- return HistorySyncSnapshot.fromJson(
- Map<String, dynamic>.from(jsonDecode(content) as Map),
- );
- } catch (e) {
- KazumiLogger().w('WebDav: history snapshot not available', error: e);
- return null;
- }
- }
-
- Future<List<HistorySyncEvent>> _readRemoteHistoryEvents() async {
- final events = <HistorySyncEvent>[];
- final files = await client.readDir(_historyChangesPath);
- for (final file in files) {
- final name = file.name ?? '';
- if (!name.endsWith('.jsonl') || file.size == 0) {
- continue;
- }
- try {
- final content = await _readRemoteText('$_historyChangesPath/$name');
- events.addAll(HistorySyncCodec.eventsFromJsonLines(content));
- } catch (e) {
- KazumiLogger().w(
- 'WebDav: failed to read history change log $name',
- error: e,
- );
- }
+ Future<bool> _tryImportLegacyHistory(Directory runDirectory) async {
+ final syncEntries = await client.readDir(_syncRootPath);
+ if (!syncEntries.any((file) => file.name == 'histories.tmp')) {
+ return false;
}
- return events;
- }
- Future<List<HistorySyncEvent>> _eventsFromLocalHistories() async {
- return HistorySyncService.buildStateEventsFromHistories(
- GStorage.histories.values,
+ const fileName = 'histories.tmp';
+ final existingFile = File(
+ '${runDirectory.path}${Platform.pathSeparator}$fileName',
);
- }
-
- Future<bool> _tryImportLegacyHistory() async {
try {
- final fileName = 'histories.tmp';
- final existingFile = File('${webDavLocalTempDirectory.path}/$fileName');
- if (await existingFile.exists()) {
- await existingFile.delete();
- }
await client.read2File('$_syncRootPath/$fileName', existingFile.path);
+ } catch (e, stackTrace) {
+ KazumiLogger().w(
+ 'WebDav: failed to download legacy history backup, skipping import',
+ error: e,
+ stackTrace: stackTrace,
+ );
+ return false;
+ }
+
+ try {
await GStorage.patchHistory(existingFile.path);
KazumiLogger().i('WebDav: imported legacy history backup');
return true;
- } catch (e) {
- KazumiLogger().w('WebDav: no legacy history backup imported', error: e);
+ } catch (e, stackTrace) {
+ KazumiLogger().w(
+ 'WebDav: invalid legacy history backup, skipping import',
+ error: e,
+ stackTrace: stackTrace,
+ );
+ await _quarantineLegacyHistoryBackup();
return false;
}
}
- Future<void> _writeHistorySnapshot(HistorySyncSnapshot snapshot) async {
- await _writeRemoteText(
- _historySnapshotPath,
- jsonEncode(snapshot.toJson()),
+ Future<void> _quarantineLegacyHistoryBackup() async {
+ final quarantinePath = '$_syncRootPath/histories.invalid.'
+ '${DateTime.now().millisecondsSinceEpoch}.tmp';
+ await _quarantineRemoteFile(
+ sourcePath: '$_syncRootPath/histories.tmp',
+ quarantinePath: quarantinePath,
+ description: 'legacy history backup',
);
}
- Future<void> _writeDeviceHistoryChanges(
- Iterable<HistorySyncEvent> events,
- ) async {
- final deviceId = await HistorySyncService().getDeviceId();
- final remotePath = '$_historyChangesPath/$deviceId.jsonl';
- final content = HistorySyncCodec.eventsToJsonLines(events);
- if (content.isEmpty) {
- try {
- await client.remove(remotePath);
- } catch (_) {}
- return;
- }
- await _writeRemoteText(remotePath, content);
- }
-
- Future<String> _readRemoteText(String remotePath) async {
- final bytes = await client.read(remotePath);
- return utf8.decode(bytes);
- }
-
- Future<void> _writeRemoteText(String remotePath, String content) async {
- final bytes = Uint8List.fromList(utf8.encode(content));
- final response = await client.c.req(
- client,
- 'PUT',
- remotePath,
- data: bytes,
- optionsHandler: (options) {
- options.contentType = 'application/octet-stream';
- },
- );
- final statusCode = response.statusCode;
- if (statusCode == 200 || statusCode == 201 || statusCode == 204) {
- return;
+ Future<void> _quarantineRemoteFile({
+ required String sourcePath,
+ required String quarantinePath,
+ required String description,
+ }) async {
+ try {
+ await client.rename(
+ sourcePath,
+ quarantinePath,
+ false,
+ );
+ KazumiLogger().w(
+ 'WebDav: moved invalid $description to $quarantinePath',
+ );
+ } catch (e, stackTrace) {
+ KazumiLogger().w(
+ 'WebDav: failed to quarantine invalid $description',
+ error: e,
+ stackTrace: stackTrace,
+ );
}
- throw Exception('WebDav: PUT $remotePath failed with $statusCode');
}
Future<void> ping() async {
@@ -389,3 +600,35 @@ class WebDav {
}
}
}
+
+class _HistorySyncDownloads {
+ const _HistorySyncDownloads({
+ required this.snapshotFile,
+ required this.eventFiles,
+ required this.currentDeviceLogOversized,
+ });
+
+ final File? snapshotFile;
+ final List<_DownloadedHistoryEventFile> eventFiles;
+ final bool currentDeviceLogOversized;
+}
+
+class _DownloadedHistoryEventFile {
+ const _DownloadedHistoryEventFile({
+ required this.remoteName,
+ required this.localFile,
+ });
+
+ final String remoteName;
+ final File localFile;
+}
+
+class _HistorySnapshotReadResult {
+ const _HistorySnapshotReadResult({
+ required this.snapshot,
+ required this.needsRepair,
+ });
+
+ final HistorySyncSnapshot snapshot;
+ final bool needsRepair;
+}
diff --git a/lib/utils/async_serial_queue.dart b/lib/utils/async_serial_queue.dart
new file mode 100644
index 00000000..abc65846
--- /dev/null
+++ b/lib/utils/async_serial_queue.dart
@@ -0,0 +1,22 @@
+import 'dart:async';
+
+/// Runs asynchronous operations one at a time in submission order.
+class AsyncSerialQueue {
+ Future<void> _tail = Future.value();
+
+ Future<T> run<T>(Future<T> Function() action) {
+ final previous = _tail;
+ final completer = Completer<T>();
+ _tail = (() async {
+ try {
+ await previous;
+ } catch (_) {}
+ try {
+ completer.complete(await action());
+ } catch (error, stackTrace) {
+ completer.completeError(error, stackTrace);
+ }
+ })();
+ return completer.future;
+ }
+}
diff --git a/lib/utils/async_single_flight.dart b/lib/utils/async_single_flight.dart
new file mode 100644
index 00000000..7a5acf4b
--- /dev/null
+++ b/lib/utils/async_single_flight.dart
@@ -0,0 +1,27 @@
+/// Shares one in-flight operation and clears it after success or failure.
+class AsyncSingleFlight<T> {
+ Future<T>? _active;
+
+ bool get isRunning => _active != null;
+
+ Future<T> run(Future<T> Function() action) {
+ final active = _active;
+ if (active != null) {
+ return active;
+ }
+
+ final future = Future.sync(action);
+ _active = future;
+ future.then<void>(
+ (_) => _clear(future),
+ onError: (Object _, StackTrace __) => _clear(future),
+ );
+ return future;
+ }
+
+ void _clear(Future<T> future) {
+ if (identical(_active, future)) {
+ _active = null;
+ }
+ }
+}
diff --git a/test/async_single_flight_test.dart b/test/async_single_flight_test.dart
new file mode 100644
index 00000000..3a481651
--- /dev/null
+++ b/test/async_single_flight_test.dart
@@ -0,0 +1,61 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:kazumi/utils/async_single_flight.dart';
+
+void main() {
+ group('AsyncSingleFlight', () {
+ test('shares one active operation across concurrent callers', () async {
+ final singleFlight = AsyncSingleFlight<void>();
+ final operation = Completer<void>();
+ var callCount = 0;
+
+ Future<void> action() {
+ callCount++;
+ return operation.future;
+ }
+
+ final first = singleFlight.run(action);
+ final second = singleFlight.run(action);
+
+ expect(identical(first, second), isTrue);
+ expect(callCount, 1);
+ expect(singleFlight.isRunning, isTrue);
+
+ operation.complete();
+ await Future.wait([first, second]);
+ await Future<void>.delayed(Duration.zero);
+
+ expect(singleFlight.isRunning, isFalse);
+ await singleFlight.run(action);
+ expect(callCount, 2);
+ });
+
+ test('shares errors and allows a later retry', () async {
+ final singleFlight = AsyncSingleFlight<void>();
+ final operation = Completer<void>();
+ var callCount = 0;
+
+ Future<void> action() {
+ callCount++;
+ return operation.future;
+ }
+
+ final first = singleFlight.run(action);
+ final second = singleFlight.run(action);
+ operation.completeError(StateError('failed'));
+
+ await expectLater(first, throwsStateError);
+ await expectLater(second, throwsStateError);
+ await Future<void>.delayed(Duration.zero);
+
+ expect(callCount, 1);
+ expect(singleFlight.isRunning, isFalse);
+
+ await singleFlight.run(() async {
+ callCount++;
+ });
+ expect(callCount, 2);
+ });
+ });
+}
diff --git a/test/history_repository_test.dart b/test/history_repository_test.dart
index 21f1bccf..593ccfd3 100644
--- a/test/history_repository_test.dart
+++ b/test/history_repository_test.dart
@@ -1,3 +1,4 @@
+import 'dart:async';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
@@ -6,6 +7,7 @@ import 'package:kazumi/modules/bangumi/bangumi_item.dart';
import 'package:kazumi/modules/bangumi/bangumi_tag.dart';
import 'package:kazumi/modules/history/history_module.dart';
import 'package:kazumi/repositories/history_repository.dart';
+import 'package:kazumi/services/storage/history_storage_coordinator.dart';
void main() {
late Directory tempDir;
@@ -175,6 +177,54 @@ void main() {
expect(historiesBox.values, isEmpty);
expect(repository.getHistory('plugin', item), isNull);
});
+
+ test('serializes repository writes with snapshot reconciliation', () async {
+ final appendStarted = Completer<void>();
+ final allowAppendToFinish = Completer<void>();
+ final repository = HistoryRepository(
+ historiesBox: historiesBox,
+ privateModeReader: () => privateMode,
+ progressSyncAppender: ({
+ required history,
+ required episode,
+ required road,
+ required progressMs,
+ required updatedAt,
+ }) async {
+ appendStarted.complete();
+ await allowAppendToFinish.future;
+ },
+ deleteSyncAppender: _noopDeleteSync,
+ clearSyncAppender: _noopClearSync,
+ );
+ final item = _item(4);
+
+ final update = repository.updateHistory(
+ identity: PlaybackHistoryIdentity.online(
+ bangumiItem: item,
+ pluginName: 'plugin',
+ episodeNumber: 1,
+ episodeTitle: 'EP1',
+ road: 0,
+ onlineBangumiSrc: 'https://example.com/source',
+ episodePageUrl: '/online/1',
+ ),
+ progress: const Duration(seconds: 10),
+ );
+ await appendStarted.future;
+
+ var reconciliationStarted = false;
+ final reconciliation = HistoryStorageCoordinator().run(() async {
+ reconciliationStarted = true;
+ });
+ await Future<void>.delayed(Duration.zero);
+ expect(reconciliationStarted, isFalse);
+
+ allowAppendToFinish.complete();
+ await update;
+ await reconciliation;
+ expect(reconciliationStarted, isTrue);
+ });
});
}
diff --git a/test/history_sync_test.dart b/test/history_sync_test.dart
index bfba626d..f7390070 100644
--- a/test/history_sync_test.dart
+++ b/test/history_sync_test.dart
@@ -1,3 +1,7 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:math';
+
import 'package:flutter_test/flutter_test.dart';
import 'package:kazumi/modules/bangumi/bangumi_item.dart';
import 'package:kazumi/modules/bangumi/bangumi_tag.dart';
@@ -578,6 +582,127 @@ void main() {
expect(mergedHistory.lastWatchEpisode, 9);
expect(mergedHistory.lastWatchEpisodeName, 'EP9');
expect(mergedHistory.progresses[9]!.progress.inSeconds, 9);
+
+ final streamMerger = HistorySyncStreamMerger(HistorySyncSnapshot.empty())
+ ..add(legacyEvent);
+ final streamedHistory = streamMerger.snapshot().histories.single;
+ expect(streamedHistory.lastWatchEpisode, 9);
+ expect(streamedHistory.lastWatchEpisodeName, 'EP9');
+ expect(streamedHistory.progresses[9]!.progress.inSeconds, 9);
+ });
+
+ test('stream merger matches sorted merge for out-of-order events', () {
+ final events = <HistorySyncEvent>[
+ ..._upsertPair(
+ deviceId: 'device-a',
+ seq: 1,
+ updatedAt: 1000,
+ episode: 1,
+ progressMs: 10,
+ ),
+ HistorySyncEvent.deleteHistory(
+ deviceId: 'device-a',
+ seq: 3,
+ entityKey: History.getKey('plugin', _item(1)),
+ updatedAt: 2000,
+ ),
+ ..._upsertPair(
+ deviceId: 'device-b',
+ seq: 1,
+ updatedAt: 2500,
+ episode: 3,
+ progressMs: 30,
+ ),
+ HistorySyncEvent.clearAll(
+ deviceId: 'device-c',
+ seq: 1,
+ updatedAt: 3000,
+ ),
+ ..._upsertPair(
+ deviceId: 'device-a',
+ seq: 4,
+ updatedAt: 3500,
+ episode: 4,
+ progressMs: 40,
+ ),
+ ];
+ final expected = HistorySyncMerger.merge(
+ snapshot: HistorySyncSnapshot.empty(),
+ events: events,
+ );
+ final streamMerger = HistorySyncStreamMerger(HistorySyncSnapshot.empty());
+
+ for (final event in events.reversed) {
+ streamMerger.add(event);
+ }
+
+ expect(
+ _canonicalSnapshot(streamMerger.snapshot()),
+ _canonicalSnapshot(expected),
+ );
+ });
+
+ test('stream merger is permutation-equivalent to sorted merge', () {
+ final events = <HistorySyncEvent>[];
+ for (var index = 0; index < 80; index++) {
+ final updatedAt = 1000 + ((index * 37) % 53);
+ switch (index % 11) {
+ case 0:
+ events.add(
+ HistorySyncEvent.clearAll(
+ deviceId: 'device-c',
+ seq: index + 1,
+ updatedAt: updatedAt,
+ ),
+ );
+ case 1:
+ events.add(
+ HistorySyncEvent.deleteHistory(
+ deviceId: 'device-b',
+ seq: index + 1,
+ entityKey: History.getKey('plugin', _item(1)),
+ updatedAt: updatedAt,
+ ),
+ );
+ case 2:
+ case 3:
+ events.add(
+ _watchState(
+ deviceId: 'device-b',
+ seq: index + 1,
+ updatedAt: updatedAt,
+ episode: (index % 4) + 1,
+ ),
+ );
+ default:
+ events.add(
+ _upsert(
+ deviceId: 'device-a',
+ seq: index + 1,
+ updatedAt: updatedAt,
+ episode: (index % 4) + 1,
+ progressMs: index * 100,
+ ),
+ );
+ }
+ }
+ final expected = _canonicalSnapshot(
+ HistorySyncMerger.merge(
+ snapshot: HistorySyncSnapshot.empty(),
+ events: events,
+ ),
+ );
+
+ for (var seed = 0; seed < 20; seed++) {
+ final shuffled = [...events]..shuffle(Random(seed));
+ final merger = HistorySyncStreamMerger(HistorySyncSnapshot.empty())
+ ..addAll(shuffled);
+ expect(
+ _canonicalSnapshot(merger.snapshot()),
+ expected,
+ reason: 'failed permutation seed $seed',
+ );
+ }
});
});
@@ -656,9 +781,232 @@ void main() {
expect(watchStateEvent.episodePageUrl, '/offline/1');
expect(watchStateEvent.carriesWatchState, isTrue);
});
+
+ test('streams a large event file into bounded history state', () async {
+ final directory =
+ await Directory.systemTemp.createTemp('kazumi_history_stream_');
+ addTearDown(() async {
+ if (await directory.exists()) {
+ await directory.delete(recursive: true);
+ }
+ });
+ final file = File('${directory.path}/events.jsonl');
+ final sink = file.openWrite();
+ const eventCount = 10000;
+ for (var index = 0; index < eventCount; index++) {
+ sink.write(
+ HistorySyncCodec.eventsToJsonLines([
+ _upsert(
+ deviceId: 'device-a',
+ seq: index + 1,
+ updatedAt: index + 1,
+ episode: 1,
+ progressMs: index,
+ ),
+ ]),
+ );
+ }
+ await sink.close();
+
+ final merged = await HistorySyncService().mergeEventFiles(
+ snapshot: HistorySyncSnapshot.empty(),
+ eventFiles: [file],
+ inMemoryEvents: const [],
+ );
+
+ expect(merged.histories, hasLength(1));
+ expect(
+ merged.histories.single.progresses[1]!.progress.inMilliseconds,
+ eventCount - 1,
+ );
+ expect(merged.progressVersions.values.single, hasLength(1));
+ });
+
+ test('fails closed and preserves malformed event files', () async {
+ final directory =
+ await Directory.systemTemp.createTemp('kazumi_history_invalid_');
+ addTearDown(() async {
+ if (await directory.exists()) {
+ await directory.delete(recursive: true);
+ }
+ });
+ final file = File('${directory.path}/events.jsonl');
+ const malformed = '{"eventId":"truncated"';
+ await file.writeAsString(malformed, flush: true);
+
+ await expectLater(
+ HistorySyncService().mergeEventFiles(
+ snapshot: HistorySyncSnapshot.empty(),
+ eventFiles: [file],
+ inMemoryEvents: const [],
+ ),
+ throwsA(isA<FormatException>()),
+ );
+ expect(await file.readAsString(), malformed);
+ });
+
+ test('skips malformed remote files transactionally', () async {
+ final directory = await Directory.systemTemp.createTemp(
+ 'kazumi_history_remote_invalid_',
+ );
+ addTearDown(() async {
+ if (await directory.exists()) {
+ await directory.delete(recursive: true);
+ }
+ });
+ final malformedFile = File('${directory.path}/malformed.jsonl');
+ final validFile = File('${directory.path}/valid.jsonl');
+ final validPrefix = HistorySyncCodec.eventsToJsonLines([
+ _upsert(
+ deviceId: 'device-a',
+ seq: 1,
+ updatedAt: 1000,
+ episode: 1,
+ progressMs: 10,
+ ),
+ ]);
+ await malformedFile.writeAsString(
+ '$validPrefix{"eventId":"truncated"',
+ flush: true,
+ );
+ await validFile.writeAsString(
+ HistorySyncCodec.eventsToJsonLines([
+ _upsert(
+ deviceId: 'device-b',
+ seq: 1,
+ updatedAt: 2000,
+ episode: 2,
+ progressMs: 20,
+ ),
+ ]),
+ flush: true,
+ );
+ final skippedFiles = <File>[];
+
+ final merged = await HistorySyncService().mergeRemoteEventFiles(
+ snapshot: HistorySyncSnapshot.empty(),
+ eventFiles: [malformedFile, validFile],
+ onInvalidFile: (file, error, stackTrace) async {
+ expect(error, isA<FormatException>());
+ skippedFiles.add(file);
+ },
+ );
+
+ expect(skippedFiles, [malformedFile]);
+ expect(merged.histories, hasLength(1));
+ expect(merged.histories.single.progresses, contains(2));
+ expect(merged.histories.single.progresses, isNot(contains(1)));
+ });
+
+ test('checkpoint keeps events appended during an active sync', () async {
+ final directory =
+ await Directory.systemTemp.createTemp('kazumi_history_checkpoint_');
+ 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 batch = await service.prepareLocalLogs(
+ runDirectory: runDirectory,
+ forceCheckpoint: true,
+ );
+ await service.appendEvents([
+ _upsert(
+ deviceId: 'device-a',
+ seq: 2,
+ updatedAt: 2000,
+ episode: 1,
+ progressMs: 20,
+ ),
+ ]);
+ await service.completeCheckpoint(batch);
+
+ expect(batch.shouldCheckpoint, isTrue);
+ expect(batch.files, hasLength(1));
+ expect(await batch.files.single.exists(), isFalse);
+ final activeLog = await service.localChangeLogFile();
+ final activeContent = await activeLog.readAsString();
+ expect(activeContent, contains('device-a:2'));
+ expect(activeContent, isNot(contains('device-a:1')));
+ });
+
+ test('recovers pending logs left by an interrupted checkpoint', () async {
+ final directory =
+ await Directory.systemTemp.createTemp('kazumi_history_recovery_');
+ addTearDown(() async {
+ if (await directory.exists()) {
+ await directory.delete(recursive: true);
+ }
+ });
+ final service = HistorySyncService.forTesting(directory);
+ final firstRun = await directory.createTemp('run-first-');
+ await service.appendEvents([
+ _upsert(
+ deviceId: 'device-a',
+ seq: 1,
+ updatedAt: 1000,
+ episode: 1,
+ progressMs: 10,
+ ),
+ ]);
+ await service.prepareLocalLogs(
+ runDirectory: firstRun,
+ forceCheckpoint: true,
+ );
+ await service.appendEvents([
+ _upsert(
+ deviceId: 'device-a',
+ seq: 2,
+ updatedAt: 2000,
+ episode: 1,
+ progressMs: 20,
+ ),
+ ]);
+
+ final secondRun = await directory.createTemp('run-second-');
+ final recoveredBatch = await service.prepareLocalLogs(
+ runDirectory: secondRun,
+ forceCheckpoint: false,
+ );
+ final merged = await service.mergeEventFiles(
+ snapshot: HistorySyncSnapshot.empty(),
+ eventFiles: recoveredBatch.files,
+ inMemoryEvents: const [],
+ );
+
+ expect(recoveredBatch.shouldCheckpoint, isTrue);
+ expect(recoveredBatch.files, hasLength(2));
+ expect(
+ merged.histories.single.progresses[1]!.progress.inMilliseconds,
+ 20,
+ );
+ });
});
}
+Map<String, dynamic> _canonicalSnapshot(HistorySyncSnapshot snapshot) {
+ final json = snapshot.toJson();
+ json.remove('generatedAt');
+ final histories = (json['histories'] as List)
+ .map((item) => Map<String, dynamic>.from(item as Map))
+ .toList()
+ ..sort((a, b) => jsonEncode(a).compareTo(jsonEncode(b)));
+ json['histories'] = histories;
+ return json;
+}
+
HistorySyncEvent _localStateUpsert({
required History history,
required int episode,