ProfileSession.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileSession.kt
1package eu.friedcutlet.yokan.app.profiles23import eu.friedcutlet.yokan.app.YokanServices4import eu.friedcutlet.yokan.app.defaultServices5import eu.friedcutlet.yokan.data.DefaultYokanRepository6import eu.friedcutlet.yokan.data.LibraryIndexStore7import eu.friedcutlet.yokan.data.SettingsStore8import eu.friedcutlet.yokan.data.YokanRepository9import eu.friedcutlet.yokan.database.YokanDatabase10import eu.friedcutlet.yokan.database.createProfileDatabase11import eu.friedcutlet.yokan.database.sync.SyncIdentityMigration12import eu.friedcutlet.yokan.services.colorization.LocalColorizationQueue13import eu.friedcutlet.yokan.services.colorization.PanelColorizer14import eu.friedcutlet.yokan.services.download.ChapterDownloads15import eu.friedcutlet.yokan.services.extensions.ChapterPageResolver16import eu.friedcutlet.yokan.services.extensions.ProfileReaderContent17import eu.friedcutlet.yokan.services.extensions.SourceInstallService18import eu.friedcutlet.yokan.services.files.LocalArchiveService19import eu.friedcutlet.yokan.services.files.LocalFileService20import eu.friedcutlet.yokan.services.files.createPlatformLocalArchiveService21import eu.friedcutlet.yokan.services.files.createPlatformLocalFileService22import eu.friedcutlet.yokan.services.http.DohResolver23import eu.friedcutlet.yokan.services.http.createPlatformHttpService24import eu.friedcutlet.yokan.services.library.LibraryUpdateController25import eu.friedcutlet.yokan.services.library.LocalLibraryController26import eu.friedcutlet.yokan.services.logging.LogSink27import eu.friedcutlet.yokan.services.media.AniSkipService28import eu.friedcutlet.yokan.services.media.player.MediaStreamProxy29import eu.friedcutlet.yokan.services.media.player.createPlatformMediaStreamProxy30import eu.friedcutlet.yokan.services.migration.MigrationService31import eu.friedcutlet.yokan.services.notifications.NotificationService32import eu.friedcutlet.yokan.services.notifications.ProfileNotificationService33import eu.friedcutlet.yokan.services.notifications.createPlatformNotificationService34import eu.friedcutlet.yokan.services.scheduling.BackgroundScheduler35import eu.friedcutlet.yokan.services.scheduling.ForegroundScheduler36import eu.friedcutlet.yokan.services.scheduling.PeriodicTaskRunner37import eu.friedcutlet.yokan.services.scheduling.createPlatformBackgroundScheduler38import eu.friedcutlet.yokan.services.runJoined39import eu.friedcutlet.yokan.services.sync.SyncTriggerCoordinator40import eu.friedcutlet.yokan.ui.screens.browse.SourceHomeCache41import eu.friedcutlet.yokan.util.PlatformLock42import kotlin.properties.ReadOnlyProperty43import kotlin.reflect.KProperty44import kotlinx.coroutines.CoroutineDispatcher45import kotlinx.coroutines.CoroutineScope46import kotlinx.coroutines.Dispatchers47import kotlinx.coroutines.Job48import kotlinx.coroutines.NonCancellable49import kotlinx.coroutines.SupervisorJob50import kotlinx.coroutines.cancelAndJoin51import kotlinx.coroutines.currentCoroutineContext52import kotlinx.coroutines.ensureActive53import kotlinx.coroutines.flow.MutableStateFlow54import kotlinx.coroutines.flow.asStateFlow55import kotlinx.coroutines.flow.update56import kotlinx.coroutines.sync.Mutex57import kotlinx.coroutines.sync.withLock58import kotlinx.coroutines.withContext59import kotlinx.coroutines.withTimeout60import eu.friedcutlet.yokan.domain.ProfileId61import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult6263enum class ProfileSessionStatus { Open, Retiring, RetirementFailed, Closed }6465/** Owns captured dependencies. Retirement is terminal; a failed retirement can be retried, not reactivated. */66internal class ProfileSession(67 val id: ProfileId,68 private val databaseFactory: (ProfileId) -> YokanDatabase = ::createProfileDatabase,69 private val filesFactory: (ProfileId) -> LocalFileService = ::createPlatformLocalFileService,70 private val archivesFactory: (ProfileId) -> LocalArchiveService = ::createPlatformLocalArchiveService,71 private val notificationsFactory: (ProfileId) -> NotificationService = ::createPlatformNotificationService,72 private val servicesFactory: (ProfileSession) -> YokanServices = { it.buildServices() },73 private val onScheduleChanged: (ProfileSession) -> Unit = {},74 dispatcher: CoroutineDispatcher = Dispatchers.Default,75 private val joinTimeoutMillis: Long = 15_000,76 private val storageLease: ProfileStorageLease = ProfileStorageLease {},77 private val syncLeases: eu.friedcutlet.yokan.services.sync.SyncAccountLeases = eu.friedcutlet.yokan.services.sync.SyncAccountLeases.None,78) {79 private val resourceLock = PlatformLock()80 private val retirementLock = Mutex()81 private val resources = mutableListOf<OwnedResource<*>>()82 private val _status = MutableStateFlow(ProfileSessionStatus.Open)83 val status = _status.asStateFlow()84 private val job = SupervisorJob()85 val scope = CoroutineScope(job + dispatcher)8687 init {88 require(joinTimeoutMillis > 0)89 ownResource(factory = { storageLease }, close = { it.close() })90 }9192 private val databaseResource = owned<YokanDatabase>(close = { it.close() }) {93 databaseFactory(id)94 .also(SyncIdentityMigration::ensure)95 }96 val database: YokanDatabase by databaseResource97 val localFiles: LocalFileService by owned(close = { it.close() }) { filesFactory(id) }98 val localArchive: LocalArchiveService by owned { archivesFactory(id) }99 val notifications: NotificationService by owned {100 ProfileNotificationService(101 id,102 notificationsFactory(id),103 // Notifications must never open storage: an unopened database has no privacy setting to honour yet.104 hideContent = { databaseResource.peek()?.settings()?.features?.privacy?.hideNotificationContent == true },105 ) { _status.value == ProfileSessionStatus.Open }106 }107 val backup: eu.friedcutlet.yokan.services.backup.BackupService by owned {108 eu.friedcutlet.yokan.services.backup.DefaultBackupService(database, localFiles, eu.friedcutlet.yokan.services.backup.createPlatformBackupCompression(), notifications)109 }110 val services: YokanServices by owned(close = { it.closeAndJoin() }) {111 servicesFactory(this)112 }113 val together by owned(close = { it.closeAndJoin() }) {114 eu.friedcutlet.yokan.services.together.ProfileTogetherSession(id, database, scope)115 }116117 private fun buildServices(): YokanServices = defaultServices(118 database = database,119 files = localFiles,120 archives = localArchive,121 notifications = notifications,122 backup = backup,123 scope = scope,124 profileId = id,125 isOwnerOpen = { _status.value == ProfileSessionStatus.Open },126 syncLeases = syncLeases,127 resolveHost = dohResolver::resolve,128 // Called when a download starts, never while building services (chapterPages needs repository → services).129 resolveDownloadPages = { chapterId, forceRefresh ->130 val chapter = checkNotNull(database.chapter(chapterId)) { "The chapter is no longer in the library" }131 chapterPages.pages(chapter, chapter.mangaId?.let(database::manga)?.sourceId, forceRefresh)132 },133 )134135 /** Runs in services.scope, so session retirement cancels pending triggered syncs. */136 val syncTriggers: SyncTriggerCoordinator by owned {137 SyncTriggerCoordinator(database, services.scope) { periodicTasks.sync() }138 }139 val repository: YokanRepository by owned {140 DefaultYokanRepository(database, services.downloadAutomation, services.trackerAccounts, syncTriggers::onTrigger)141 }142 val chapterPages: ChapterPageResolver by owned {143 ChapterPageResolver(repository, database, services.extensionRuntimeFactory)144 }145 val readerContent by owned(close = { it.closeAndJoin() }) {146 ProfileReaderContent(147 id, database, services.extensionRuntimeFactory, chapterPages, localFiles, localArchive, scope,148 isOwnerOpen = { _status.value == ProfileSessionStatus.Open },149 torrents = services.torrents,150 )151 }152 val automaticUpdateGate by owned { eu.friedcutlet.yokan.services.scheduling.AutomaticUpdateGate() }153 val periodicTasks: PeriodicTaskRunner by owned {154 PeriodicTaskRunner(155 database = database,156 repository = repository,157 metadata = services.metadata,158 libraryUpdater = services.libraryUpdater,159 sync = services.sync,160 backup = services.backup,161 notifications = notifications,162 updateGate = automaticUpdateGate,163 )164 }165 val foregroundScheduler: ForegroundScheduler by owned { ForegroundScheduler(database, periodicTasks, services.scope) }166 val backgroundScheduler: BackgroundScheduler by owned { createPlatformBackgroundScheduler(database, id) }167 /** Uses its own transport, so resolving the DoH provider itself goes through system DNS. */168 val dohResolver: DohResolver by owned { DohResolver(database, createPlatformHttpService(id, scope)) }169 /** Recently closed Source Homes, restored when the same source is reopened in this profile. */170 val sourceHomeCache by owned { SourceHomeCache(capacity = 5) }171 val aniSkip: AniSkipService by owned { AniSkipService(services.http) }172 val mediaStreamProxy: MediaStreamProxy by owned(close = { it.closeAndJoin() }) { createPlatformMediaStreamProxy() }173 val playerServices by owned(close = { it.closeAndJoin() }) {174 eu.friedcutlet.yokan.services.media.player.ProfilePlayerServices(175 id, localFiles, aniSkip, mediaStreamProxy, scope,176 isOwnerOpen = { _status.value == ProfileSessionStatus.Open },177 )178 }179 val cast by owned(close = { it.close() }) { eu.friedcutlet.yokan.services.media.cast.createCastController(scope) }180 val settings: SettingsStore by owned { SettingsStore(repository, scope) { onScheduleChanged(this) } }181 val libraryIndex: LibraryIndexStore by owned { LibraryIndexStore(repository, services.scope,182 trackerScoreRanges = services.trackers.associate { tracker -> tracker.scoreValue().let { tracker.syncId to (it.first..it.second) } }) }183 val libraryUpdates: LibraryUpdateController by owned {184 LibraryUpdateController(services.libraryUpdater, repository, notifications, services.scope)185 }186 val localLibrary: LocalLibraryController by owned {187 val capturedDatabase = database188 LocalLibraryController(189 localLibrary = services.localLibrary,190 entryManagement = services.localEntryManagement,191 repository = repository,192 metadata = services.metadata,193 trackers = services.trackers,194 files = localFiles,195 settings = settings,196 persistSettings = { capturedDatabase.awaitPersistence() },197 importScope = scope,198 isOwnerOpen = { _status.value == ProfileSessionStatus.Open },199 artwork = eu.friedcutlet.yokan.services.library.LocalVideoArtwork(200 capturedDatabase, localFiles, services.localLibrary,201 eu.friedcutlet.yokan.services.media.createPlatformVideoFrameExtractor(),202 ),203 )204 }205 val colorizationQueue: LocalColorizationQueue by owned {206 LocalColorizationQueue(database, localFiles, localArchive, PanelColorizer(), services.localLibrary, services.scope)207 }208 val migration: MigrationService by owned {209 MigrationService(repository, database, services.extensionRuntimeFactory, settings, services.scope)210 }211 val chapterDownloads: ChapterDownloads by owned {212 ChapterDownloads(213 repository = repository,214 database = database,215 downloader = services.downloader,216 notifications = notifications,217 settings = settings,218 localFiles = localFiles,219 scope = scope,220 externalDownloads = services.externalDownloads,221 )222 }223 val sourceInstall: SourceInstallService by owned {224 SourceInstallService(database, repository, services.sourceCatalog, services.extensionRuntimeFactory, settings, chapterPages)225 }226227 private val loggingTarget by owned(close = { LogSink.detach(it) }) {228 val db = database229 LogSink.attach(localFiles) { db.snapshots().value.settings.enableFileLogging }230 }231232 /** Only the active composition root may publish its log target. */233 fun attachLogging() { loggingTarget }234235 /** OS callbacks are children of this owner; caller expiry and session retirement both join them. */236 suspend fun <T> runBackgroundWork(action: suspend (ProfileSession) -> T): ProfileWorkResult<T> {237 currentCoroutineContext().ensureActive()238 if (_status.value != ProfileSessionStatus.Open) return ProfileWorkResult.Skipped239 return ProfileWorkResult.Completed(scope.runJoined { action(this@ProfileSession) })240 }241242 /** Call only after UI/reader progress owners have saved and stopped using this session. */243 suspend fun close() = retirementLock.withLock retirement@{244 val cleanup = resourceLock.withLock snapshot@{245 if (_status.value == ProfileSessionStatus.Closed) return@snapshot null246 _status.update { ProfileSessionStatus.Retiring }247 resources.asReversed().toList()248 } ?: return@retirement249 withContext(NonCancellable) {250 try {251 // No resource is released until cancelled child finalizers have finished their writes.252 withTimeout(joinTimeoutMillis) { job.cancelAndJoin() }253 cleanup.forEach { resource ->254 withTimeout(joinTimeoutMillis) { resource.closeIfInitialized() }255 }256 _status.update { ProfileSessionStatus.Closed }257 } catch (error: Throwable) {258 _status.update { ProfileSessionStatus.RetirementFailed }259 throw error260 }261 }262 }263264 private fun <T> owned(close: suspend (T) -> Unit = {}, factory: () -> T): OwnedResource<T> =265 OwnedResource(close, factory).also { resources += it }266267 /** Register context-dependent resources atomically with retirement, after their captured dependencies. */268 fun <T> ownResource(factory: () -> T, close: suspend (T) -> Unit): T = resourceLock.withLock {269 check(_status.value == ProfileSessionStatus.Open) { "Profile session is retiring or closed" }270 val resource = OwnedResource(close, factory)271 resource.initialize().also { resources += resource }272 }273274 private inner class OwnedResource<T>(private val close: suspend (T) -> Unit, factory: () -> T) : ReadOnlyProperty<ProfileSession, T> {275 private val value = lazy(factory)276 private var released = false277 fun initialize(): T = value.value278 fun peek(): T? = if (value.isInitialized()) value.value else null279 override fun getValue(thisRef: ProfileSession, property: KProperty<*>): T = resourceLock.withLock {280 check(_status.value == ProfileSessionStatus.Open) { "Profile session is retiring or closed" }281 value.value282 }283 suspend fun closeIfInitialized() {284 if (!released && value.isInitialized()) {285 close(value.value)286 released = true287 }288 }289 }290}291292/** Additional profiles remain gated until platform credentials and background jobs are isolated. */293internal fun createPlatformProfileSession(294 id: ProfileId,295 syncLeases: eu.friedcutlet.yokan.services.sync.SyncAccountLeases,296 onScheduleChanged: (ProfileSession) -> Unit = {},297): ProfileSession {298 check(id == ProfileId.Default) { "Additional profile sessions are not enabled yet" }299 return ProfileSession(id, onScheduleChanged = onScheduleChanged, syncLeases = syncLeases)300}301