package eu.friedcutlet.yokan.services.sync import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.DbSyncPreference import eu.friedcutlet.yokan.services.backup.BackupOptions import eu.friedcutlet.yokan.services.runJoined import eu.friedcutlet.yokan.util.PlatformLock import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.withContext import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock /** * Both public sync entry points capture one session. UI callers are joined to that owner, * including direct cloud connect/upload/restore calls that bypass the hybrid router. * [delegate] owns and closes the raw cloud service as part of its provider graph. */ internal class ProfileSyncServices( val profileId: ProfileId, private val delegate: SyncService, cloudDelegate: CloudBackupSyncService, ownerScope: CoroutineScope, ) { private val lock = PlatformLock() private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job]) { "Profile sync requires an owner job" } private val job = SupervisorJob(ownerJob) private val scope = CoroutineScope(ownerScope.coroutineContext + job) private var retired = false private var released = false private var joined = false private val retirementLock = Mutex() val sync: SyncService = BoundSyncService(delegate) val cloud: CloudBackupSyncService = BoundCloudService(cloudDelegate) private fun isOpen() = !retired && ownerJob.isActive && job.isActive private suspend fun runOwned(action: suspend () -> T): T = scope.runJoined( admit = { lock.withLock { if (!isOpen()) throw CancellationException("Profile sync session has ended") } }, ) { action() } private fun retire() { lock.withLock { retired = true } job.cancel() } private fun release() = lock.withLock { if (!released) { delegate.close() released = true } } /** Legacy immediate shutdown; orderly session retirement uses [closeAndJoin]. */ private fun close() { retire(); release() } private suspend fun closeAndJoin() { retire() withContext(NonCancellable) { retirementLock.withLock { job.cancelAndJoin() if (!joined) { delegate.closeAndJoin() lock.withLock { released = true; joined = true } } } } } private open inner class BoundSyncService(private val service: SyncService) : SyncService { override val operationState = service.operationState override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult = runOwned { service.login(syncId, server, email, password) } override fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt? = lock.withLock { if (isOpen()) service.beginBrowserLogin(syncId, server) else null } override suspend fun completeBrowserLogin(attempt: BrowserLoginAttempt, loadedUrl: String): SyncLoginResult? = runOwned { service.completeBrowserLogin(attempt, loadedUrl) } override fun cancelBrowserLogin(attempt: BrowserLoginAttempt) = lock.withLock { if (isOpen()) service.cancelBrowserLogin(attempt) } override suspend fun logout(syncId: Long) = runOwned { service.logout(syncId) } override suspend fun sync(syncId: Long, settings: DbSettings): SyncResult = runOwned { service.sync(syncId, settings) } override suspend fun pushChanges(syncId: Long): SyncResult = runOwned { service.pushChanges(syncId) } override suspend fun pullChanges(syncId: Long): SyncResult = runOwned { service.pullChanges(syncId) } override fun status(syncId: Long): SyncConnectionStatus = lock.withLock { if (isOpen()) service.status(syncId) else SyncConnectionStatus(false, null, null, null) } override fun close() = this@ProfileSyncServices.close() override suspend fun closeAndJoin() = this@ProfileSyncServices.closeAndJoin() } private inner class BoundCloudService(private val service: CloudBackupSyncService) : BoundSyncService(service), CloudBackupSyncService { override fun providers(): List = lock.withLock { if (isOpen()) service.providers() else emptyList() } override fun isCloudPreference(syncPreference: DbSyncPreference?): Boolean = lock.withLock { isOpen() && service.isCloudPreference(syncPreference) } override suspend fun connect(syncId: Long, providerId: String, accountLabel: String?, accessToken: String): SyncLoginResult = runOwned { service.connect(syncId, providerId, accountLabel, accessToken) } override suspend fun uploadBackup(syncId: Long, options: BackupOptions): CloudBackupResult = runOwned { service.uploadBackup(syncId, options) } override suspend fun restoreLatestBackup(syncId: Long): CloudBackupRestoreResult = runOwned { service.restoreLatestBackup(syncId) } } }