ProfileSyncServices.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/ProfileSyncServices.kt
1package eu.friedcutlet.yokan.services.sync23import eu.friedcutlet.yokan.domain.ProfileId4import eu.friedcutlet.yokan.database.DbSettings5import eu.friedcutlet.yokan.database.DbSyncPreference6import eu.friedcutlet.yokan.services.backup.BackupOptions7import eu.friedcutlet.yokan.services.runJoined8import eu.friedcutlet.yokan.util.PlatformLock9import kotlinx.coroutines.CancellationException10import kotlinx.coroutines.CoroutineScope11import kotlinx.coroutines.Job12import kotlinx.coroutines.NonCancellable13import kotlinx.coroutines.SupervisorJob14import kotlinx.coroutines.cancelAndJoin15import kotlinx.coroutines.withContext16import kotlinx.coroutines.sync.Mutex17import kotlinx.coroutines.sync.withLock1819/**20 * Both public sync entry points capture one session. UI callers are joined to that owner,21 * including direct cloud connect/upload/restore calls that bypass the hybrid router.22 * [delegate] owns and closes the raw cloud service as part of its provider graph.23 */24internal class ProfileSyncServices(25 val profileId: ProfileId,26 private val delegate: SyncService,27 cloudDelegate: CloudBackupSyncService,28 ownerScope: CoroutineScope,29) {30 private val lock = PlatformLock()31 private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job]) { "Profile sync requires an owner job" }32 private val job = SupervisorJob(ownerJob)33 private val scope = CoroutineScope(ownerScope.coroutineContext + job)34 private var retired = false35 private var released = false36 private var joined = false37 private val retirementLock = Mutex()3839 val sync: SyncService = BoundSyncService(delegate)40 val cloud: CloudBackupSyncService = BoundCloudService(cloudDelegate)4142 private fun isOpen() = !retired && ownerJob.isActive && job.isActive4344 private suspend fun <T> runOwned(action: suspend () -> T): T = scope.runJoined(45 admit = { lock.withLock { if (!isOpen()) throw CancellationException("Profile sync session has ended") } },46 ) { action() }4748 private fun retire() {49 lock.withLock { retired = true }50 job.cancel()51 }5253 private fun release() = lock.withLock {54 if (!released) {55 delegate.close()56 released = true57 }58 }5960 /** Legacy immediate shutdown; orderly session retirement uses [closeAndJoin]. */61 private fun close() { retire(); release() }6263 private suspend fun closeAndJoin() {64 retire()65 withContext(NonCancellable) {66 retirementLock.withLock {67 job.cancelAndJoin()68 if (!joined) {69 delegate.closeAndJoin()70 lock.withLock { released = true; joined = true }71 }72 }73 }74 }7576 private open inner class BoundSyncService(private val service: SyncService) : SyncService {77 override val operationState = service.operationState7879 override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult =80 runOwned { service.login(syncId, server, email, password) }8182 override fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt? = lock.withLock {83 if (isOpen()) service.beginBrowserLogin(syncId, server) else null84 }8586 override suspend fun completeBrowserLogin(attempt: BrowserLoginAttempt, loadedUrl: String): SyncLoginResult? =87 runOwned { service.completeBrowserLogin(attempt, loadedUrl) }8889 override fun cancelBrowserLogin(attempt: BrowserLoginAttempt) = lock.withLock {90 if (isOpen()) service.cancelBrowserLogin(attempt)91 }9293 override suspend fun logout(syncId: Long) = runOwned { service.logout(syncId) }94 override suspend fun sync(syncId: Long, settings: DbSettings): SyncResult = runOwned { service.sync(syncId, settings) }95 override suspend fun pushChanges(syncId: Long): SyncResult = runOwned { service.pushChanges(syncId) }96 override suspend fun pullChanges(syncId: Long): SyncResult = runOwned { service.pullChanges(syncId) }9798 override fun status(syncId: Long): SyncConnectionStatus = lock.withLock {99 if (isOpen()) service.status(syncId) else SyncConnectionStatus(false, null, null, null)100 }101102 override fun close() = this@ProfileSyncServices.close()103 override suspend fun closeAndJoin() = this@ProfileSyncServices.closeAndJoin()104 }105106 private inner class BoundCloudService(private val service: CloudBackupSyncService) :107 BoundSyncService(service), CloudBackupSyncService {108 override fun providers(): List<CloudProviderDescriptor> = lock.withLock {109 if (isOpen()) service.providers() else emptyList()110 }111112 override fun isCloudPreference(syncPreference: DbSyncPreference?): Boolean = lock.withLock {113 isOpen() && service.isCloudPreference(syncPreference)114 }115116 override suspend fun connect(syncId: Long, providerId: String, accountLabel: String?, accessToken: String): SyncLoginResult =117 runOwned { service.connect(syncId, providerId, accountLabel, accessToken) }118119 override suspend fun uploadBackup(syncId: Long, options: BackupOptions): CloudBackupResult =120 runOwned { service.uploadBackup(syncId, options) }121122 override suspend fun restoreLatestBackup(syncId: Long): CloudBackupRestoreResult =123 runOwned { service.restoreLatestBackup(syncId) }124 }125}126