package eu.friedcutlet.yokan.app.profiles import eu.friedcutlet.yokan.app.YokanServices import eu.friedcutlet.yokan.app.defaultServices import eu.friedcutlet.yokan.data.DefaultYokanRepository import eu.friedcutlet.yokan.data.LibraryIndexStore import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.data.YokanRepository import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.database.createProfileDatabase import eu.friedcutlet.yokan.database.sync.SyncIdentityMigration import eu.friedcutlet.yokan.services.colorization.LocalColorizationQueue import eu.friedcutlet.yokan.services.colorization.PanelColorizer import eu.friedcutlet.yokan.services.download.ChapterDownloads import eu.friedcutlet.yokan.services.extensions.ChapterPageResolver import eu.friedcutlet.yokan.services.extensions.ProfileReaderContent import eu.friedcutlet.yokan.services.extensions.SourceInstallService import eu.friedcutlet.yokan.services.files.LocalArchiveService import eu.friedcutlet.yokan.services.files.LocalFileService import eu.friedcutlet.yokan.services.files.createPlatformLocalArchiveService import eu.friedcutlet.yokan.services.files.createPlatformLocalFileService import eu.friedcutlet.yokan.services.http.DohResolver import eu.friedcutlet.yokan.services.http.createPlatformHttpService import eu.friedcutlet.yokan.services.library.LibraryUpdateController import eu.friedcutlet.yokan.services.library.LocalLibraryController import eu.friedcutlet.yokan.services.logging.LogSink import eu.friedcutlet.yokan.services.media.AniSkipService import eu.friedcutlet.yokan.services.media.player.MediaStreamProxy import eu.friedcutlet.yokan.services.media.player.createPlatformMediaStreamProxy import eu.friedcutlet.yokan.services.migration.MigrationService import eu.friedcutlet.yokan.services.notifications.NotificationService import eu.friedcutlet.yokan.services.notifications.ProfileNotificationService import eu.friedcutlet.yokan.services.notifications.createPlatformNotificationService import eu.friedcutlet.yokan.services.scheduling.BackgroundScheduler import eu.friedcutlet.yokan.services.scheduling.ForegroundScheduler import eu.friedcutlet.yokan.services.scheduling.PeriodicTaskRunner import eu.friedcutlet.yokan.services.scheduling.createPlatformBackgroundScheduler import eu.friedcutlet.yokan.services.runJoined import eu.friedcutlet.yokan.services.sync.SyncTriggerCoordinator import eu.friedcutlet.yokan.ui.screens.browse.SourceHomeCache import eu.friedcutlet.yokan.util.PlatformLock import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult enum class ProfileSessionStatus { Open, Retiring, RetirementFailed, Closed } /** Owns captured dependencies. Retirement is terminal; a failed retirement can be retried, not reactivated. */ internal class ProfileSession( val id: ProfileId, private val databaseFactory: (ProfileId) -> YokanDatabase = ::createProfileDatabase, private val filesFactory: (ProfileId) -> LocalFileService = ::createPlatformLocalFileService, private val archivesFactory: (ProfileId) -> LocalArchiveService = ::createPlatformLocalArchiveService, private val notificationsFactory: (ProfileId) -> NotificationService = ::createPlatformNotificationService, private val servicesFactory: (ProfileSession) -> YokanServices = { it.buildServices() }, private val onScheduleChanged: (ProfileSession) -> Unit = {}, dispatcher: CoroutineDispatcher = Dispatchers.Default, private val joinTimeoutMillis: Long = 15_000, private val storageLease: ProfileStorageLease = ProfileStorageLease {}, private val syncLeases: eu.friedcutlet.yokan.services.sync.SyncAccountLeases = eu.friedcutlet.yokan.services.sync.SyncAccountLeases.None, ) { private val resourceLock = PlatformLock() private val retirementLock = Mutex() private val resources = mutableListOf>() private val _status = MutableStateFlow(ProfileSessionStatus.Open) val status = _status.asStateFlow() private val job = SupervisorJob() val scope = CoroutineScope(job + dispatcher) init { require(joinTimeoutMillis > 0) ownResource(factory = { storageLease }, close = { it.close() }) } private val databaseResource = owned(close = { it.close() }) { databaseFactory(id) .also(SyncIdentityMigration::ensure) } val database: YokanDatabase by databaseResource val localFiles: LocalFileService by owned(close = { it.close() }) { filesFactory(id) } val localArchive: LocalArchiveService by owned { archivesFactory(id) } val notifications: NotificationService by owned { ProfileNotificationService( id, notificationsFactory(id), // Notifications must never open storage: an unopened database has no privacy setting to honour yet. hideContent = { databaseResource.peek()?.settings()?.features?.privacy?.hideNotificationContent == true }, ) { _status.value == ProfileSessionStatus.Open } } val backup: eu.friedcutlet.yokan.services.backup.BackupService by owned { eu.friedcutlet.yokan.services.backup.DefaultBackupService(database, localFiles, eu.friedcutlet.yokan.services.backup.createPlatformBackupCompression(), notifications) } val services: YokanServices by owned(close = { it.closeAndJoin() }) { servicesFactory(this) } val together by owned(close = { it.closeAndJoin() }) { eu.friedcutlet.yokan.services.together.ProfileTogetherSession(id, database, scope) } private fun buildServices(): YokanServices = defaultServices( database = database, files = localFiles, archives = localArchive, notifications = notifications, backup = backup, scope = scope, profileId = id, isOwnerOpen = { _status.value == ProfileSessionStatus.Open }, syncLeases = syncLeases, resolveHost = dohResolver::resolve, // Called when a download starts, never while building services (chapterPages needs repository → services). resolveDownloadPages = { chapterId, forceRefresh -> val chapter = checkNotNull(database.chapter(chapterId)) { "The chapter is no longer in the library" } chapterPages.pages(chapter, chapter.mangaId?.let(database::manga)?.sourceId, forceRefresh) }, ) /** Runs in services.scope, so session retirement cancels pending triggered syncs. */ val syncTriggers: SyncTriggerCoordinator by owned { SyncTriggerCoordinator(database, services.scope) { periodicTasks.sync() } } val repository: YokanRepository by owned { DefaultYokanRepository(database, services.downloadAutomation, services.trackerAccounts, syncTriggers::onTrigger) } val chapterPages: ChapterPageResolver by owned { ChapterPageResolver(repository, database, services.extensionRuntimeFactory) } val readerContent by owned(close = { it.closeAndJoin() }) { ProfileReaderContent( id, database, services.extensionRuntimeFactory, chapterPages, localFiles, localArchive, scope, isOwnerOpen = { _status.value == ProfileSessionStatus.Open }, torrents = services.torrents, ) } val automaticUpdateGate by owned { eu.friedcutlet.yokan.services.scheduling.AutomaticUpdateGate() } val periodicTasks: PeriodicTaskRunner by owned { PeriodicTaskRunner( database = database, repository = repository, metadata = services.metadata, libraryUpdater = services.libraryUpdater, sync = services.sync, backup = services.backup, notifications = notifications, updateGate = automaticUpdateGate, ) } val foregroundScheduler: ForegroundScheduler by owned { ForegroundScheduler(database, periodicTasks, services.scope) } val backgroundScheduler: BackgroundScheduler by owned { createPlatformBackgroundScheduler(database, id) } /** Uses its own transport, so resolving the DoH provider itself goes through system DNS. */ val dohResolver: DohResolver by owned { DohResolver(database, createPlatformHttpService(id, scope)) } /** Recently closed Source Homes, restored when the same source is reopened in this profile. */ val sourceHomeCache by owned { SourceHomeCache(capacity = 5) } val aniSkip: AniSkipService by owned { AniSkipService(services.http) } val mediaStreamProxy: MediaStreamProxy by owned(close = { it.closeAndJoin() }) { createPlatformMediaStreamProxy() } val playerServices by owned(close = { it.closeAndJoin() }) { eu.friedcutlet.yokan.services.media.player.ProfilePlayerServices( id, localFiles, aniSkip, mediaStreamProxy, scope, isOwnerOpen = { _status.value == ProfileSessionStatus.Open }, ) } val cast by owned(close = { it.close() }) { eu.friedcutlet.yokan.services.media.cast.createCastController(scope) } val settings: SettingsStore by owned { SettingsStore(repository, scope) { onScheduleChanged(this) } } val libraryIndex: LibraryIndexStore by owned { LibraryIndexStore(repository, services.scope, trackerScoreRanges = services.trackers.associate { tracker -> tracker.scoreValue().let { tracker.syncId to (it.first..it.second) } }) } val libraryUpdates: LibraryUpdateController by owned { LibraryUpdateController(services.libraryUpdater, repository, notifications, services.scope) } val localLibrary: LocalLibraryController by owned { val capturedDatabase = database LocalLibraryController( localLibrary = services.localLibrary, entryManagement = services.localEntryManagement, repository = repository, metadata = services.metadata, trackers = services.trackers, files = localFiles, settings = settings, persistSettings = { capturedDatabase.awaitPersistence() }, importScope = scope, isOwnerOpen = { _status.value == ProfileSessionStatus.Open }, artwork = eu.friedcutlet.yokan.services.library.LocalVideoArtwork( capturedDatabase, localFiles, services.localLibrary, eu.friedcutlet.yokan.services.media.createPlatformVideoFrameExtractor(), ), ) } val colorizationQueue: LocalColorizationQueue by owned { LocalColorizationQueue(database, localFiles, localArchive, PanelColorizer(), services.localLibrary, services.scope) } val migration: MigrationService by owned { MigrationService(repository, database, services.extensionRuntimeFactory, settings, services.scope) } val chapterDownloads: ChapterDownloads by owned { ChapterDownloads( repository = repository, database = database, downloader = services.downloader, notifications = notifications, settings = settings, localFiles = localFiles, scope = scope, externalDownloads = services.externalDownloads, ) } val sourceInstall: SourceInstallService by owned { SourceInstallService(database, repository, services.sourceCatalog, services.extensionRuntimeFactory, settings, chapterPages) } private val loggingTarget by owned(close = { LogSink.detach(it) }) { val db = database LogSink.attach(localFiles) { db.snapshots().value.settings.enableFileLogging } } /** Only the active composition root may publish its log target. */ fun attachLogging() { loggingTarget } /** OS callbacks are children of this owner; caller expiry and session retirement both join them. */ suspend fun runBackgroundWork(action: suspend (ProfileSession) -> T): ProfileWorkResult { currentCoroutineContext().ensureActive() if (_status.value != ProfileSessionStatus.Open) return ProfileWorkResult.Skipped return ProfileWorkResult.Completed(scope.runJoined { action(this@ProfileSession) }) } /** Call only after UI/reader progress owners have saved and stopped using this session. */ suspend fun close() = retirementLock.withLock retirement@{ val cleanup = resourceLock.withLock snapshot@{ if (_status.value == ProfileSessionStatus.Closed) return@snapshot null _status.update { ProfileSessionStatus.Retiring } resources.asReversed().toList() } ?: return@retirement withContext(NonCancellable) { try { // No resource is released until cancelled child finalizers have finished their writes. withTimeout(joinTimeoutMillis) { job.cancelAndJoin() } cleanup.forEach { resource -> withTimeout(joinTimeoutMillis) { resource.closeIfInitialized() } } _status.update { ProfileSessionStatus.Closed } } catch (error: Throwable) { _status.update { ProfileSessionStatus.RetirementFailed } throw error } } } private fun owned(close: suspend (T) -> Unit = {}, factory: () -> T): OwnedResource = OwnedResource(close, factory).also { resources += it } /** Register context-dependent resources atomically with retirement, after their captured dependencies. */ fun ownResource(factory: () -> T, close: suspend (T) -> Unit): T = resourceLock.withLock { check(_status.value == ProfileSessionStatus.Open) { "Profile session is retiring or closed" } val resource = OwnedResource(close, factory) resource.initialize().also { resources += resource } } private inner class OwnedResource(private val close: suspend (T) -> Unit, factory: () -> T) : ReadOnlyProperty { private val value = lazy(factory) private var released = false fun initialize(): T = value.value fun peek(): T? = if (value.isInitialized()) value.value else null override fun getValue(thisRef: ProfileSession, property: KProperty<*>): T = resourceLock.withLock { check(_status.value == ProfileSessionStatus.Open) { "Profile session is retiring or closed" } value.value } suspend fun closeIfInitialized() { if (!released && value.isInitialized()) { close(value.value) released = true } } } } /** Additional profiles remain gated until platform credentials and background jobs are isolated. */ internal fun createPlatformProfileSession( id: ProfileId, syncLeases: eu.friedcutlet.yokan.services.sync.SyncAccountLeases, onScheduleChanged: (ProfileSession) -> Unit = {}, ): ProfileSession { check(id == ProfileId.Default) { "Additional profile sessions are not enabled yet" } return ProfileSession(id, onScheduleChanged = onScheduleChanged, syncLeases = syncLeases) }