package eu.friedcutlet.yokan.services.sync import eu.friedcutlet.yokan.database.DbSyncPreference import eu.friedcutlet.yokan.database.SnapshotReplacementConflictException import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.services.backup.BackupOpenResult import eu.friedcutlet.yokan.services.backup.BackupRestoreTargetChangedException import eu.friedcutlet.yokan.services.backup.BackupService import eu.friedcutlet.yokan.services.backup.RestoreMode import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpResponse import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.util.nowMillis import kotlinx.coroutines.CancellationException import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock /* * Shared by the whole-backup state sync providers (SyncYomi, Google Drive): each run captures the exact account, * merges remote data through a guarded restore, and commits its watermark only while that account is still selected. */ /** A user-facing failure; the message is shown as the sync error. */ internal class StateSyncException(message: String) : Exception(message) internal const val SyncAccountChangedMessage = "Sync configuration changed during the operation." /** The captured account was replaced mid-run; distinct from cancellation so a live caller gets a failure result. */ internal class SyncAccountChangedException : IllegalStateException(SyncAccountChangedMessage) /** Same account as [captured]: settings toggles may change mid-run, the identity may not. */ internal fun sameSyncAccount(captured: DbSyncPreference, current: DbSyncPreference?): Boolean = current != null && current.syncId == captured.syncId && current.serverProvider == captured.serverProvider && current.server == captured.server && current.email == captured.email && current.authToken == captured.authToken && current.deviceId == captured.deviceId internal fun YokanDatabase.checkSyncAccount(captured: DbSyncPreference) { if (!sameSyncAccount(captured, syncPreferences().firstOrNull { it.syncId == captured.syncId })) { throw SyncAccountChangedException() } } /** * Merges remote backup [bytes] into the library; the predicate runs on the snapshot the atomic commit expects. * Returns the merged item count, or null when [bytes] is not a readable backup (callers then overwrite it). */ internal suspend fun BackupService.mergeRemoteState(bytes: ByteArray, captured: DbSyncPreference, label: String): Int? = when (val opened = openBackup(bytes)) { is BackupOpenResult.Ready -> try { applyBackupIf(opened.plan, RestoreMode.Merge) { snapshot -> sameSyncAccount(captured, snapshot.syncPreferences.firstOrNull { it.syncId == captured.syncId }) }.itemCount } catch (_: BackupRestoreTargetChangedException) { throw SyncAccountChangedException() } is BackupOpenResult.Failure -> { AppLogger.warn("[sync] $label remote data is not a readable backup (${opened.error})") null } } /** Records a completed run, unless the account changed meanwhile. */ internal suspend fun YokanDatabase.recordStateSync(captured: DbSyncPreference) { currentCoroutineContext().ensureActive() val now = nowMillis() val accepted = upsertSyncPreferenceIf( syncId = requireNotNull(captured.syncId), accepts = { sameSyncAccount(captured, it) }, transform = { requireNotNull(it).copy(lastSyncManga = now, lastSyncHistory = now, lastSyncUpdate = now) }, ) if (!accepted) throw SyncAccountChangedException() } /** One tracked, serialized run; failures become [SyncResult.errors], a cancelled caller still cancels. */ internal suspend fun runStateSync( monitor: SyncOperationMonitor, mutex: Mutex, stage: SyncOperationStage, label: String, block: suspend () -> SyncResult, ): SyncResult { val operationId = monitor.begin(stage) var outcome = SyncOperationOutcome.Failed try { val result = try { mutex.withLock { block() } } catch (cancelled: CancellationException) { outcome = SyncOperationOutcome.Cancelled throw cancelled } catch (_: SyncAccountChangedException) { stateSyncFailure(SyncAccountChangedMessage) } catch (_: SnapshotReplacementConflictException) { stateSyncFailure("Library changed while applying $label data; sync again.") } catch (error: StateSyncException) { stateSyncFailure(error.message ?: "$label sync failed.") } catch (error: Exception) { AppLogger.warn("[sync] $label sync failed: ${error::class.simpleName}") stateSyncFailure("$label sync failed.") } if (result.errors.isEmpty()) outcome = SyncOperationOutcome.Succeeded else AppLogger.warn("[sync] $label ${stage.name.lowercase()}: ${result.errors.joinToString("; ")}") return result } finally { monitor.finish(operationId, outcome) } } internal fun stateSyncFailure(message: String) = SyncResult(0, 0, false, listOf(message)) /** Null when the server is unreachable; cancellation still propagates. */ internal suspend fun HttpService.requestOrNull(request: HttpRequest): HttpResponse? = try { request(request) } catch (cancelled: CancellationException) { throw cancelled } catch (_: Exception) { null }