Yokan / rebuild
Course 1 8624561

StateSyncSupport.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/StateSyncSupport.kt

implementation114 lines
1package eu.friedcutlet.yokan.services.sync23import eu.friedcutlet.yokan.database.DbSyncPreference4import eu.friedcutlet.yokan.database.SnapshotReplacementConflictException5import eu.friedcutlet.yokan.database.YokanDatabase6import eu.friedcutlet.yokan.services.backup.BackupOpenResult7import eu.friedcutlet.yokan.services.backup.BackupRestoreTargetChangedException8import eu.friedcutlet.yokan.services.backup.BackupService9import eu.friedcutlet.yokan.services.backup.RestoreMode10import eu.friedcutlet.yokan.services.http.HttpRequest11import eu.friedcutlet.yokan.services.http.HttpResponse12import eu.friedcutlet.yokan.services.http.HttpService13import eu.friedcutlet.yokan.services.logging.AppLogger14import eu.friedcutlet.yokan.util.nowMillis15import kotlinx.coroutines.CancellationException16import kotlinx.coroutines.currentCoroutineContext17import kotlinx.coroutines.ensureActive18import kotlinx.coroutines.sync.Mutex19import kotlinx.coroutines.sync.withLock2021/*22 * Shared by the whole-backup state sync providers (SyncYomi, Google Drive): each run captures the exact account,23 * merges remote data through a guarded restore, and commits its watermark only while that account is still selected.24 */2526/** A user-facing failure; the message is shown as the sync error. */27internal class StateSyncException(message: String) : Exception(message)2829internal const val SyncAccountChangedMessage = "Sync configuration changed during the operation."3031/** The captured account was replaced mid-run; distinct from cancellation so a live caller gets a failure result. */32internal class SyncAccountChangedException : IllegalStateException(SyncAccountChangedMessage)3334/** Same account as [captured]: settings toggles may change mid-run, the identity may not. */35internal fun sameSyncAccount(captured: DbSyncPreference, current: DbSyncPreference?): Boolean = current != null &&36    current.syncId == captured.syncId && current.serverProvider == captured.serverProvider && current.server == captured.server &&37    current.email == captured.email && current.authToken == captured.authToken && current.deviceId == captured.deviceId3839internal fun YokanDatabase.checkSyncAccount(captured: DbSyncPreference) {40    if (!sameSyncAccount(captured, syncPreferences().firstOrNull { it.syncId == captured.syncId })) {41        throw SyncAccountChangedException()42    }43}4445/**46 * Merges remote backup [bytes] into the library; the predicate runs on the snapshot the atomic commit expects.47 * Returns the merged item count, or null when [bytes] is not a readable backup (callers then overwrite it).48 */49internal suspend fun BackupService.mergeRemoteState(bytes: ByteArray, captured: DbSyncPreference, label: String): Int? =50    when (val opened = openBackup(bytes)) {51        is BackupOpenResult.Ready -> try {52            applyBackupIf(opened.plan, RestoreMode.Merge) { snapshot ->53                sameSyncAccount(captured, snapshot.syncPreferences.firstOrNull { it.syncId == captured.syncId })54            }.itemCount55        } catch (_: BackupRestoreTargetChangedException) {56            throw SyncAccountChangedException()57        }58        is BackupOpenResult.Failure -> {59            AppLogger.warn("[sync] $label remote data is not a readable backup (${opened.error})")60            null61        }62    }6364/** Records a completed run, unless the account changed meanwhile. */65internal suspend fun YokanDatabase.recordStateSync(captured: DbSyncPreference) {66    currentCoroutineContext().ensureActive()67    val now = nowMillis()68    val accepted = upsertSyncPreferenceIf(69        syncId = requireNotNull(captured.syncId),70        accepts = { sameSyncAccount(captured, it) },71        transform = { requireNotNull(it).copy(lastSyncManga = now, lastSyncHistory = now, lastSyncUpdate = now) },72    )73    if (!accepted) throw SyncAccountChangedException()74}7576/** One tracked, serialized run; failures become [SyncResult.errors], a cancelled caller still cancels. */77internal suspend fun runStateSync(78    monitor: SyncOperationMonitor,79    mutex: Mutex,80    stage: SyncOperationStage,81    label: String,82    block: suspend () -> SyncResult,83): SyncResult {84    val operationId = monitor.begin(stage)85    var outcome = SyncOperationOutcome.Failed86    try {87        val result = try {88            mutex.withLock { block() }89        } catch (cancelled: CancellationException) {90            outcome = SyncOperationOutcome.Cancelled91            throw cancelled92        } catch (_: SyncAccountChangedException) {93            stateSyncFailure(SyncAccountChangedMessage)94        } catch (_: SnapshotReplacementConflictException) {95            stateSyncFailure("Library changed while applying $label data; sync again.")96        } catch (error: StateSyncException) {97            stateSyncFailure(error.message ?: "$label sync failed.")98        } catch (error: Exception) {99            AppLogger.warn("[sync] $label sync failed: ${error::class.simpleName}")100            stateSyncFailure("$label sync failed.")101        }102        if (result.errors.isEmpty()) outcome = SyncOperationOutcome.Succeeded103        else AppLogger.warn("[sync] $label ${stage.name.lowercase()}: ${result.errors.joinToString("; ")}")104        return result105    } finally {106        monitor.finish(operationId, outcome)107    }108}109110internal fun stateSyncFailure(message: String) = SyncResult(0, 0, false, listOf(message))111112/** Null when the server is unreachable; cancellation still propagates. */113internal suspend fun HttpService.requestOrNull(request: HttpRequest): HttpResponse? =114    try { request(request) } catch (cancelled: CancellationException) { throw cancelled } catch (_: Exception) { null }115

Search chapters, reference and source filenames.