SyncAccountLeases.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/SyncAccountLeases.kt
1package eu.friedcutlet.yokan.services.sync23import eu.friedcutlet.yokan.database.DbSyncPreference4import eu.friedcutlet.yokan.database.SyncServerProvider5import eu.friedcutlet.yokan.database.YokanDatabase6import eu.friedcutlet.yokan.database.sync.normalizeMangayomiServer7import eu.friedcutlet.yokan.services.catchingNonCancellation8import eu.friedcutlet.yokan.services.http.normalizeHubServer9import eu.friedcutlet.yokan.services.logging.AppLogger10import kotlinx.coroutines.CancellationException11import kotlinx.coroutines.CoroutineScope12import kotlinx.coroutines.NonCancellable13import kotlinx.coroutines.launch14import kotlinx.coroutines.withContext1516/**17 * Device-wide ownership of remote sync accounts, so two profiles never sync into one library.18 * [claim] throws with a user-facing message when another profile holds [key].19 */20interface SyncAccountLeases {21 suspend fun claim(key: String)22 suspend fun release(key: String)2324 companion object {25 /** Single-profile hosts and tests: every claim succeeds. */26 val None = object : SyncAccountLeases {27 override suspend fun claim(key: String) = Unit28 override suspend fun release(key: String) = Unit29 }30 }31}3233/**34 * Lease key of a configured account (signed in or not). Account names are trimmed and lowercased, so one35 * account is one key as far as the stored name allows (Mangayomi password logins store the typed email,36 * OAuth the server username: the same account reached both ways yields two keys). A blank account name37 * still leases the server, so only one profile may use an unnamed account there.38 */39internal fun syncLeaseKey(preference: DbSyncPreference?): String? {40 val server = preference?.server ?: return null41 val account = preference.email.orEmpty().trim()42 val key = when {43 // SyncYomi has no account name: the API key selects the account, so lease by its digest, never the raw key.44 preference.serverProvider == SyncServerProvider.SyncYomi -> "syncyomi|${normalizeSyncYomiHost(server) ?: return null}|${syncYomiKeyLabel(preference.authToken)}"45 // Google Drive state sync keeps the user's OAuth client id in `server`.46 preference.serverProvider == SyncServerProvider.GoogleDrive -> "gdrive|${server.trim().takeIf(String::isNotEmpty) ?: return null}|$account"47 server.startsWith(CloudServerPrefix) -> "cloud|${providerIdFromServer(server) ?: return null}|$account"48 preference.serverProvider == SyncServerProvider.Mangayomi -> "mangayomi|${normalizeMangayomiServer(server) ?: return null}|$account"49 else -> "hub|${normalizeHubServer(server) ?: return null}|$account"50 }51 return key.lowercase()52}5354private fun DbSyncPreference?.signedIn() = !this?.authToken.isNullOrBlank() && syncLeaseKey(this) != null5556/** Claims [preference]'s account if signed in; the failure message, or null when this profile may use it. */57internal suspend fun SyncAccountLeases.claimFailure(preference: DbSyncPreference?): String? {58 if (!preference.signedIn()) return null59 val key = syncLeaseKey(preference) ?: return null60 return try {61 claim(key); null62 } catch (cancelled: CancellationException) {63 throw cancelled64 } catch (error: Exception) {65 error.message ?: "Could not reserve this sync account for this profile."66 }67}6869/**70 * Adopts the account a profile already uses (e.g. Default's pre-lease login) as soon as it opens. A conflict71 * is only logged; every sync operation re-checks the lease and reports it as its error.72 */73internal fun adoptConfiguredSyncAccount(leases: SyncAccountLeases, database: YokanDatabase, scope: CoroutineScope) {74 scope.launch {75 catchingNonCancellation { leases.claimFailure(database.syncPreferences().firstOrNull()) }76 .getOrNull()?.let { AppLogger.warn("[sync] $it") }77 }78}7980/** Best effort: a failed release only keeps the account reserved for this profile until its next logout/delete. */81internal suspend fun SyncAccountLeases.releaseQuietly(preference: DbSyncPreference?) {82 val key = syncLeaseKey(preference) ?: return83 try {84 withContext(NonCancellable) { release(key) }85 } catch (_: Exception) {86 }87}8889/**90 * Claims [next]'s account right before the guarded credential [commit]. A rejected commit hands the lease91 * back to [previous]'s account (or releases it). Returns null once committed, else the message to show.92 */93internal suspend fun SyncAccountLeases.commitClaimed(94 previous: DbSyncPreference?,95 next: DbSyncPreference,96 commit: suspend () -> Boolean,97): String? {98 claimFailure(next)?.let { return it }99 var committed = false100 try {101 committed = commit()102 } finally {103 if (!committed) withContext(NonCancellable) {104 if (!previous.signedIn() || claimFailure(previous) != null) releaseQuietly(next)105 }106 }107 return if (committed) null else "Sync configuration changed during login; try again."108}109