Prerequisites: database and service interfaces. Implement this boundary before real background work. File workbook.
How to write this chapter
Build the owner that makes profile isolation real. A profile is a captured graph of resources and jobs; switching the selected name in a settings screen is only the final visible part of activation.
The 54 assigned entries are integrated below at their implementation steps. Every text listing is complete, including imports, helpers and tests. Create the displayed paths in your new project; dependencies imported from other chapters are linked beside the file. Binary assets have direct downloads.
Read each step’s explanation, write its contracts and implementation, then trace the test assertions. The final application graph has dependencies across chapters: the ordering is a construction plan, and a step is not a promise that the whole app compiles before its referenced contracts exist.
Implementation sequence:
- Step 1: Define stable IDs, storage namespaces and the device registry.
- Step 2: Construct the captured session and service graph.
- Step 3: Implement terminal retirement and awaited UI cleanup.
- Step 4: Serialize switching, storage leases, provisioning and deletion.
- Step 5: Route delayed and inactive-profile work by recorded owner.
- Verification: recreate the full test/fixture listings and run the relevant target tasks. [chapter-content-end]: #
Step 1: build the device registry
Implement stable ProfileId validation: default or p_ followed by 32 lowercase hex digits. Display names are metadata and never paths. Default adopts existing database/files/browser keys in place. Extra profiles use profiles/<id> and their own browser keys. Implement registry persistence and create/provision/ready/delete states, last-active selection, exported backup records and account leases.
Registry writes must survive interruption without replacing a corrupt registry with an empty default. Distinguish invalid IDs, unknown owners and unreadable registry state. Keep Default permanent. Rename changes only metadata.
Follow the code
Begin with ID validation and storage naming before any UI. A display name can change, but directory names, queued work and remote-account leases use the stable ID. The registry records provisioning and deletion rather than assuming every listed profile is ready. Follow the persistence path for create and rename, and preserve the error state for an unreadable registry. Default's legacy storage is adopted in place.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/domain/ProfileId.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.ktcomposeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.android.ktcomposeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.desktop.ktcomposeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.ios.ktcomposeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.wasm.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/domain/ProfileId.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ProfileId, random, ProfileStorageNamespace, ownedRoot.
The source describes its contract as:
Only stable IDs enter paths/keys. Default aliases legacy locations; no adoption copy is needed.
package eu.friedcutlet.yokan.domain
import kotlinx.serialization.Serializable
import kotlin.jvm.JvmInline
import kotlin.random.Random
@Serializable
@JvmInline
value class ProfileId(val value: String) {
init { require(value == "default" || Regex("p_[0-9a-f]{32}").matches(value)) { "Invalid profile ID" } }
companion object {
val Default = ProfileId("default")
fun random(): ProfileId = ProfileId("p_" + Random.nextBytes(16).toHexString())
}
}
/** Only stable IDs enter paths/keys. Default aliases legacy locations; no adoption copy is needed. */
data class ProfileStorageNamespace(val id: ProfileId) {
val relativeRoot: String? get() = if (id == ProfileId.Default) null else "profiles/${id.value}"
val databaseRelativePath: String get() = relativeRoot?.let { "$it/yokan-room.db" } ?: "yokan-room.db"
val browserSnapshotKey: String get() = if (id == ProfileId.Default) "yokan-database-v1" else "yokan-database-v1:${id.value}"
fun ownedRoot(base: String): String = relativeRoot?.let { "${base.trimEnd('/')}/$it" } ?: base.trimEnd('/')
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ProfileStatus, ProfileRecord, ProfileSyncLease, ProfileRegistrySnapshot, available, validateProfileRegistry, profileName, encodeProfileRegistry, decodeProfileRegistry, ProfileRegistryPersistence and 22 further declarations.
The source describes its contract as:
Explicit save destinations are device metadata, never imported from backups.
package eu.friedcutlet.yokan.app.profiles
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.NonCancellable
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.serialization.Serializable
import kotlinx.serialization.json.Json
import eu.friedcutlet.yokan.domain.ProfileId
@Serializable
enum class ProfileStatus { Provisioning, Ready, Deleting }
@Serializable
data class ProfileRecord(
val id: ProfileId,
val name: String,
val status: ProfileStatus = ProfileStatus.Ready,
/** Explicit save destinations are device metadata, never imported from backups. */
val exportedBackups: List<String> = emptyList(),
)
/** Device-wide claim on one remote sync account; see [ProfileRegistry.claimSyncLease]. */
@Serializable
data class ProfileSyncLease(val key: String, val owner: ProfileId)
@Serializable
data class ProfileRegistrySnapshot(
val version: Int = 1,
val profiles: List<ProfileRecord> = listOf(ProfileRecord(ProfileId.Default, "Default")),
val lastActive: ProfileId = ProfileId.Default,
val retiredIds: List<ProfileId> = emptyList(),
val syncLeases: List<ProfileSyncLease> = emptyList(),
) {
val hasAdditionalProfiles: Boolean get() = profiles.any { it.id != ProfileId.Default && it.status == ProfileStatus.Ready }
fun available(id: ProfileId): ProfileRecord? = profiles.singleOrNull { it.id == id && it.status == ProfileStatus.Ready }
}
internal const val MaxProfileRegistryBytes = 262_144
internal const val MaxRetiredProfileIds = 4096
internal const val MaxSyncLeaseKeyLength = 2048
private val RegistryJson = Json { encodeDefaults = true }
internal fun validateProfileRegistry(snapshot: ProfileRegistrySnapshot): ProfileRegistrySnapshot {
require(snapshot.version == 1) { "Unsupported profile registry version" }
require(snapshot.profiles.size in 1..64 && snapshot.retiredIds.size <= MaxRetiredProfileIds) { "Profile registry limit exceeded" }
require(snapshot.profiles.map { it.id }.distinct().size == snapshot.profiles.size) { "Duplicate profile IDs" }
require(snapshot.retiredIds.distinct().size == snapshot.retiredIds.size) { "Duplicate retired profile IDs" }
require(snapshot.retiredIds.none { id -> id == ProfileId.Default || snapshot.profiles.any { it.id == id } }) { "Retired profile reused" }
require(snapshot.profiles.singleOrNull { it.id == ProfileId.Default } == ProfileRecord(ProfileId.Default, "Default")) { "Default profile must remain permanent" }
snapshot.profiles.forEach {
require(it.name == profileName(it.name)) { "Invalid stored profile name" }
require(it.exportedBackups.distinct().size == it.exportedBackups.size && it.exportedBackups.size <= 512) { "Invalid exported backup records" }
it.exportedBackups.forEach { path -> require(path.isNotBlank() && path.length <= 4096 && path.none { c -> c.code < 32 }) { "Invalid export destination" } }
}
require(snapshot.profiles.map { it.name.lowercase() }.distinct().size == snapshot.profiles.size) { "Duplicate profile names" }
require(snapshot.syncLeases.map { it.key }.distinct().size == snapshot.syncLeases.size &&
snapshot.syncLeases.map { it.owner }.distinct().size == snapshot.syncLeases.size) { "Duplicate sync leases" }
snapshot.syncLeases.forEach { lease ->
require(lease.key.isNotEmpty() && lease.key.length <= MaxSyncLeaseKeyLength) { "Invalid sync lease" }
require(snapshot.profiles.any { it.id == lease.owner && it.status != ProfileStatus.Deleting }) { "Sync lease owner is unavailable" }
}
require(snapshot.available(snapshot.lastActive) != null) { "Active profile is unavailable" }
return snapshot
}
private fun profileName(name: String): String = name.trim().also { normalized ->
require(normalized.isNotEmpty() && normalized.length <= 80 && normalized.none { it.code < 32 || it.code in 127..159 }) { "Invalid profile name" }
normalized.encodeToByteArray(throwOnInvalidSequence = true)
}
internal fun encodeProfileRegistry(snapshot: ProfileRegistrySnapshot): String = RegistryJson.encodeToString(validateProfileRegistry(snapshot)).also {
require(it.encodeToByteArray().size <= MaxProfileRegistryBytes) { "Profile registry limit exceeded" }
}
internal fun decodeProfileRegistry(raw: String): ProfileRegistrySnapshot {
require(raw.encodeToByteArray().size <= MaxProfileRegistryBytes) { "Profile registry limit exceeded" }
return validateProfileRegistry(RegistryJson.decodeFromString<ProfileRegistrySnapshot>(raw))
}
/** CAS must be serialized across every process/tab sharing this device registry and atomic on disk. */
interface ProfileRegistryPersistence {
suspend fun read(): String?
suspend fun compareAndSet(expected: String?, replacement: String): Boolean
}
sealed interface ProfileRegistryState {
data object Uninitialized : ProfileRegistryState
data class Ready(val snapshot: ProfileRegistrySnapshot) : ProfileRegistryState
data object Unavailable : ProfileRegistryState
}
/** Metadata only. A session coordinator must provision/close/delete storage before committing stages. */
class ProfileRegistry(private val persistence: ProfileRegistryPersistence) {
private val mutex = Mutex()
private val _state = MutableStateFlow<ProfileRegistryState>(ProfileRegistryState.Uninitialized)
val state = _state.asStateFlow()
suspend fun refresh(): ProfileRegistrySnapshot = edit { it }
suspend fun beginCreate(name: String, id: ProfileId = ProfileId.random()): ProfileRegistrySnapshot = edit { old ->
require(id != ProfileId.Default && id !in old.retiredIds && old.profiles.none { it.id == id }) { "Profile ID unavailable" }
old.copy(profiles = old.profiles + ProfileRecord(id, profileName(name), ProfileStatus.Provisioning))
}
suspend fun markReady(id: ProfileId): ProfileRegistrySnapshot = edit { old ->
val record = requireNotNull(old.profiles.singleOrNull { it.id == id }) { "Unknown profile" }
require(record.status == ProfileStatus.Provisioning) { "Profile is not provisioning" }
old.copy(profiles = old.profiles.map { if (it.id == id) it.copy(status = ProfileStatus.Ready) else it })
}
suspend fun rename(id: ProfileId, name: String): ProfileRegistrySnapshot = edit { old ->
require(id != ProfileId.Default && old.available(id) != null) { "Profile cannot be renamed" }
old.copy(profiles = old.profiles.map { if (it.id == id) it.copy(name = profileName(name)) else it })
}
/** Record a successful explicit export while the target lease is still held. Default is never deleted. */
suspend fun recordExport(id: ProfileId, path: String): ProfileRegistrySnapshot = edit { old ->
if (id == ProfileId.Default) old else {
requireNotNull(old.available(id)) { "Export profile is unavailable" }
old.copy(profiles = old.profiles.map {
if (it.id == id) it.copy(exportedBackups = (it.exportedBackups + path).distinct()) else it
})
}
}
/**
* A profile has one sync preference, so it holds at most one lease: claiming replaces the owner's
* previous lease. Idempotent for the holder; fails while another profile holds [key]. A conflict
* leaves the registry untouched (and [state] Ready) instead of failing the edit.
*/
suspend fun claimSyncLease(owner: ProfileId, key: String) {
require(key.isNotEmpty() && key.length <= MaxSyncLeaseKeyLength) { "This sync account address is too long." }
val next = edit { old ->
val claimable = old.profiles.any { it.id == owner && it.status != ProfileStatus.Deleting } &&
old.syncLeases.none { it.key == key && it.owner != owner }
if (!claimable) old else old.copy(syncLeases = old.syncLeases.filterNot { it.owner == owner } + ProfileSyncLease(key, owner))
}
val held = next.syncLeases.singleOrNull { it.key == key }
if (held?.owner == owner) return
val name = next.profiles.singleOrNull { it.id == held?.owner }?.name
throw IllegalStateException(
if (name == null) "This profile can no longer connect sync accounts."
else "This sync account is already connected to profile ‘$name’. Log out there first.",
)
}
suspend fun releaseSyncLease(owner: ProfileId, key: String): ProfileRegistrySnapshot = edit { old ->
old.copy(syncLeases = old.syncLeases.filterNot { it.owner == owner && it.key == key })
}
fun syncLeases(owner: ProfileId) = object : eu.friedcutlet.yokan.services.sync.SyncAccountLeases {
override suspend fun claim(key: String) = claimSyncLease(owner, key)
override suspend fun release(key: String) { releaseSyncLease(owner, key) }
}
/** Call only after the replacement session is ready and the old session has been retired. */
suspend fun recordActive(id: ProfileId): ProfileRegistrySnapshot = edit { old ->
require(old.available(id) != null) { "Profile is unavailable" }
old.copy(lastActive = id)
}
/** The coordinator must first safely switch away from an active extra profile. */
suspend fun beginDelete(id: ProfileId): ProfileRegistrySnapshot = edit { old ->
require(id != ProfileId.Default && id != old.lastActive) { "Switch away before deleting this profile" }
require(old.profiles.any { it.id == id }) { "Unknown profile" }
require(old.retiredIds.size < MaxRetiredProfileIds) { "Profile deletion capacity reached" }
old.copy(
profiles = old.profiles.map { if (it.id == id) it.copy(status = ProfileStatus.Deleting) else it },
syncLeases = old.syncLeases.filterNot { it.owner == id },
)
}
/** Commit only after app-owned data is gone; interrupted deletions remain recoverable. */
suspend fun finishDelete(id: ProfileId): ProfileRegistrySnapshot = edit { old ->
if (id in old.retiredIds) old else {
require(old.profiles.any { it.id == id && it.status == ProfileStatus.Deleting }) { "Profile is not deleting" }
old.copy(profiles = old.profiles.filterNot { it.id == id }, retiredIds = old.retiredIds + id)
}
}
private suspend fun edit(transform: (ProfileRegistrySnapshot) -> ProfileRegistrySnapshot): ProfileRegistrySnapshot = mutex.withLock {
try {
currentCoroutineContext().ensureActive()
// Once a store commit begins, join its result before publishing metadata. This does not
// make provisioning/switching irreversible: those are separate coordinator operations.
withContext(NonCancellable) {
repeat(16) {
val raw = persistence.read()
val old = raw?.let(::decodeProfileRegistry) ?: ProfileRegistrySnapshot()
val next = validateProfileRegistry(transform(old))
if ((raw != null && next == old) || persistence.compareAndSet(raw, encodeProfileRegistry(next))) {
_state.update { ProfileRegistryState.Ready(next) }
return@withContext next
}
}
error("Profile registry changed repeatedly; retry")
}
} catch (error: CancellationException) {
throw error
} catch (error: Exception) {
_state.update { ProfileRegistryState.Unavailable }
throw error
}
}
}
expect fun createPlatformProfileRegistry(): ProfileRegistry
Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.android.kt
Create this path in your reconstruction project. Source set: androidMain. Exact file download.
The implementation below defines createPlatformProfileRegistry.
Cross-chapter imports used by this file: AndroidAppContext. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app.profiles
import eu.friedcutlet.yokan.AndroidAppContext
import java.io.File
actual fun createPlatformProfileRegistry(): ProfileRegistry {
val context = checkNotNull(AndroidAppContext.appContext) { "Android context unavailable" }
return ProfileRegistry(FileProfileRegistryPersistence(File(context.filesDir, "profiles/registry.json")))
}
Write composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.desktop.kt
Create this path in your reconstruction project. Source set: desktopMain. Exact file download.
The implementation below defines createPlatformProfileRegistry.
package eu.friedcutlet.yokan.app.profiles
import eu.friedcutlet.yokan.services.files.desktopDataRoot
import java.io.File
actual fun createPlatformProfileRegistry(): ProfileRegistry =
ProfileRegistry(FileProfileRegistryPersistence(File(desktopDataRoot, "profiles/registry.json")))
Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.ios.kt
Create this path in your reconstruction project. Source set: iosMain. Exact file download.
The implementation below defines createPlatformProfileRegistry, IosProfileRegistryPersistence, read, compareAndSet, readLocked.
The source describes its contract as:
BGTasks and foreground scenes share this app process. Extensions must not mutate this registry.
Cross-chapter imports used by this file: PlatformLock. Keep those contracts available as you connect this step.
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class, kotlinx.cinterop.BetaInteropApi::class)
package eu.friedcutlet.yokan.app.profiles
import eu.friedcutlet.yokan.util.PlatformLock
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import platform.Foundation.NSDocumentDirectory
import platform.Foundation.NSFileManager
import platform.Foundation.NSNumber
import platform.Foundation.NSSearchPathForDirectoriesInDomains
import platform.Foundation.NSString
import platform.Foundation.NSUTF8StringEncoding
import platform.Foundation.NSUserDomainMask
import platform.Foundation.create
import platform.Foundation.stringWithContentsOfFile
import platform.Foundation.writeToFile
actual fun createPlatformProfileRegistry(): ProfileRegistry {
val documents = checkNotNull(NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true).firstOrNull() as? String)
return ProfileRegistry(IosProfileRegistryPersistence("$documents/profiles/registry.json"))
}
/** BGTasks and foreground scenes share this app process. Extensions must not mutate this registry. */
private class IosProfileRegistryPersistence(private val path: String) : ProfileRegistryPersistence {
override suspend fun read(): String? = withContext(Dispatchers.Default) { lock.withLock { readLocked() } }
override suspend fun compareAndSet(expected: String?, replacement: String): Boolean = withContext(Dispatchers.Default) {
require(replacement.encodeToByteArray().size <= MaxProfileRegistryBytes)
lock.withLock {
if (readLocked() != expected) return@withLock false
check(NSFileManager.defaultManager.createDirectoryAtPath(path.substringBeforeLast('/'), true, null, null))
check(NSString.create(string = replacement).writeToFile(path, true, NSUTF8StringEncoding, null)) { "Profile registry write failed" }
true
}
}
private fun readLocked(): String? {
val fm = NSFileManager.defaultManager
if (!fm.fileExistsAtPath(path)) return null
val size = fm.attributesOfItemAtPath(path, null)?.get(platform.Foundation.NSFileSize) as? NSNumber
check(size != null && size.unsignedLongLongValue <= MaxProfileRegistryBytes.toULong()) { "Profile registry cannot be read safely" }
return checkNotNull(NSString.stringWithContentsOfFile(path, NSUTF8StringEncoding, null)) { "Profile registry read failed" }
}
private companion object { val lock = PlatformLock() }
}
Write composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.wasm.kt
Create this path in your reconstruction project. Source set: wasmJsMain. Exact file download.
The implementation below defines createPlatformProfileRegistry, BrowserProfileRegistryPersistence, read, compareAndSet, resultBoolean, compareRegistry.
@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)
package eu.friedcutlet.yokan.app.profiles
import kotlinx.browser.localStorage
import kotlinx.coroutines.await
import kotlin.js.JsAny
import kotlin.js.Promise
internal const val ProfileRegistryKey = "yokan-profiles-v1"
actual fun createPlatformProfileRegistry(): ProfileRegistry = ProfileRegistry(BrowserProfileRegistryPersistence())
private class BrowserProfileRegistryPersistence : ProfileRegistryPersistence {
override suspend fun read(): String? = localStorage.getItem(ProfileRegistryKey)
override suspend fun compareAndSet(expected: String?, replacement: String): Boolean =
resultBoolean(compareRegistry(ProfileRegistryKey, expected, replacement).await())
}
private fun resultBoolean(value: JsAny): Boolean = js("Boolean(value)")
private fun compareRegistry(key: String, expected: String?, replacement: String): Promise<JsAny> = js(
"""
(async () => {
if (!navigator.locks || !navigator.locks.request) throw new Error('Profile registry requires Web Locks');
return navigator.locks.request('yokan-profile-registry', () => {
if (localStorage.getItem(key) !== expected) return false;
localStorage.setItem(key, replacement);
return true;
});
})()
""",
)
Check your understanding
Rename a profile and check that its database path, background owner and account lease do not change. [chapter-content-end]: #
Step 2: build an owned graph
Implement ProfileSession with a SupervisorJob, immutable captured ID and lazy owned resources. It owns database, file/archive services, settings/index, repository, HTTP/cookies, runtime factory, downloads, backup/sync, local library, reader/player bindings and controllers. Capture dependencies when an operation starts; never look up YokanRuntime.activeSession in a late callback.
Construct YokanServices explicitly. Close the two genuine cycles only in the factory: enhanced HTTP hands challenges to WebView and WebView retries through the enhanced client; download completion calls automation after the downloader is constructed. Reproduce raw-versus-enhanced HTTP choices for sync credentials and user-hosted services.
Follow the code
The session captures its ID and dependencies once. Its lazy resources register cleanup in creation order, allowing reverse-order release. Read the service factory after the contracts: it closes the HTTP/WebView and downloader/automation cycles explicitly. Deferred callbacks capture this graph, rather than consulting whichever profile happens to be active later. Startup checks and the runtime publish the graph only through the coordinator.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileSession.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/ServiceRegistry.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/AppStartup.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/YokanRuntime.ktcomposeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.android.ktcomposeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.desktop.ktcomposeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.ios.ktcomposeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.jvm.ktcomposeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.wasm.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileSession.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
Read owned/ownResource alongside close. Registration checks Open under the resource lock; retirement snapshots resources in reverse order, joins the job before release, and records RetirementFailed when cleanup cannot finish.
The implementation below defines ProfileSessionStatus, ProfileSession, buildServices, attachLogging, runBackgroundWork, close, owned, ownResource, initialize, peek and 3 further declarations.
The source describes its contract as:
Owns captured dependencies. Retirement is terminal; a failed retirement can be retried, not reactivated.
Cross-chapter imports used by this file: DefaultYokanRepository, LibraryIndexStore, SettingsStore, YokanRepository, YokanDatabase, createProfileDatabase. Keep those contracts available as you connect this step.
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<OwnedResource<*>>()
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<YokanDatabase>(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 <T> runBackgroundWork(action: suspend (ProfileSession) -> T): ProfileWorkResult<T> {
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 <T> owned(close: suspend (T) -> Unit = {}, factory: () -> T): OwnedResource<T> =
OwnedResource(close, factory).also { resources += it }
/** Register context-dependent resources atomically with retirement, after their captured dependencies. */
fun <T> 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<T>(private val close: suspend (T) -> Unit, factory: () -> T) : ReadOnlyProperty<ProfileSession, T> {
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)
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/ServiceRegistry.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines YokanServices, closeAndJoin, defaultServices, animeExtractors, trackers.
The source describes its contract as:
Owns background coroutines (download workers, foreground scheduler, startup jobs).
Cross-chapter imports used by this file: DbItemType, DbPageUrl, YokanDatabase, BackupService, DiscoveryService, HttpDiscoveryService. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.backup.BackupService
import eu.friedcutlet.yokan.services.discovery.DiscoveryService
import eu.friedcutlet.yokan.services.discovery.HttpDiscoveryService
import eu.friedcutlet.yokan.services.download.DownloadAutomation
import eu.friedcutlet.yokan.services.download.DownloadService
import eu.friedcutlet.yokan.services.download.ExternalDownloads
import eu.friedcutlet.yokan.services.download.ImageDataSaver
import eu.friedcutlet.yokan.services.download.PersistentDownloadService
import eu.friedcutlet.yokan.services.download.keepDownloadsAlive
import eu.friedcutlet.yokan.services.extensions.DynamicExtensionRuntimeFactory
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory
import eu.friedcutlet.yokan.services.extensions.HttpSourceCatalogService
import eu.friedcutlet.yokan.services.extensions.SourceCatalogService
import eu.friedcutlet.yokan.services.extensions.mergeSourcePageHeaders
import eu.friedcutlet.yokan.services.extensions.mihon.DefaultExtensionServerRuntimeService
import eu.friedcutlet.yokan.services.extensions.mihon.ExtensionServerRuntimeService
import eu.friedcutlet.yokan.services.extensions.mihon.createPlatformExtensionServerAdapter
import eu.friedcutlet.yokan.services.extensions.mihon.resolveMihonProxy
import eu.friedcutlet.yokan.services.extensions.recipe.RecipeCatalogInstallationService
import eu.friedcutlet.yokan.services.extensions.recipe.RecipeInstallationClock
import eu.friedcutlet.yokan.services.extensions.recipe.createPlatformRecipeServices
import eu.friedcutlet.yokan.services.extensions.withSourceRuntime
import eu.friedcutlet.yokan.services.files.LocalArchiveService
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.http.EnhancedHttpService
import eu.friedcutlet.yokan.services.http.HostResolver
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.KtorHttpService
import eu.friedcutlet.yokan.services.http.ProfileHttpService
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import eu.friedcutlet.yokan.services.http.createPlatformHttpClientEngine
import eu.friedcutlet.yokan.services.http.createPlatformHttpService
import eu.friedcutlet.yokan.services.library.DefaultLibraryUpdaterService
import eu.friedcutlet.yokan.services.library.DefaultLocalEntryManagementService
import eu.friedcutlet.yokan.services.library.DefaultLocalLibraryService
import eu.friedcutlet.yokan.services.library.LibraryAiringService
import eu.friedcutlet.yokan.services.library.LibraryUpdaterService
import eu.friedcutlet.yokan.services.library.LocalEntryManagementService
import eu.friedcutlet.yokan.services.library.LocalLibraryService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.media.SubtitleService
import eu.friedcutlet.yokan.services.media.extractors.DoodExtractor
import eu.friedcutlet.yokan.services.media.extractors.FilemoonExtractor
import eu.friedcutlet.yokan.services.media.extractors.GogoCdnExtractor
import eu.friedcutlet.yokan.services.media.extractors.KwikExtractor
import eu.friedcutlet.yokan.services.media.extractors.Mp4UploadExtractor
import eu.friedcutlet.yokan.services.media.extractors.MyStreamExtractor
import eu.friedcutlet.yokan.services.media.extractors.MytvExtractor
import eu.friedcutlet.yokan.services.media.extractors.OkruExtractor
import eu.friedcutlet.yokan.services.media.extractors.QuarkUcExtractor
import eu.friedcutlet.yokan.services.media.extractors.SendvidExtractor
import eu.friedcutlet.yokan.services.media.extractors.SibnetExtractor
import eu.friedcutlet.yokan.services.media.extractors.StreamTapeExtractor
import eu.friedcutlet.yokan.services.media.extractors.StreamWishExtractor
import eu.friedcutlet.yokan.services.media.extractors.StreamlareExtractor
import eu.friedcutlet.yokan.services.media.extractors.VidBomExtractor
import eu.friedcutlet.yokan.services.media.extractors.VoeExtractor
import eu.friedcutlet.yokan.services.media.extractors.YourUploadExtractor
import eu.friedcutlet.yokan.services.metadata.HttpMetadataService
import eu.friedcutlet.yokan.services.metadata.MetadataService
import eu.friedcutlet.yokan.services.metadata.RecommendationService
import eu.friedcutlet.yokan.services.metadata.WatchOrderService
import eu.friedcutlet.yokan.services.notifications.NotificationService
import eu.friedcutlet.yokan.services.sync.CloudBackupSyncService
import eu.friedcutlet.yokan.services.sync.DefaultCloudBackupSyncService
import eu.friedcutlet.yokan.services.sync.GoogleDriveCloudStorageProvider
import eu.friedcutlet.yokan.services.sync.GoogleDriveSyncService
import eu.friedcutlet.yokan.services.sync.HubSyncService
import eu.friedcutlet.yokan.services.sync.HybridSyncService
import eu.friedcutlet.yokan.services.sync.MangayomiSyncService
import eu.friedcutlet.yokan.services.sync.ProfileSyncServices
import eu.friedcutlet.yokan.services.sync.SyncAccountLeases
import eu.friedcutlet.yokan.services.sync.SyncOperationMonitor
import eu.friedcutlet.yokan.services.sync.SyncService
import eu.friedcutlet.yokan.services.sync.SyncYomiSyncService
import eu.friedcutlet.yokan.services.sync.adoptConfiguredSyncAccount
import eu.friedcutlet.yokan.services.system.createNetworkMonitor
import eu.friedcutlet.yokan.services.torrent.TorrentStreams
import eu.friedcutlet.yokan.services.torrent.createPlatformTorrServerHost
import eu.friedcutlet.yokan.services.tracking.AnilistTrackerService
import eu.friedcutlet.yokan.services.tracking.AnilistTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.BangumiTrackerService
import eu.friedcutlet.yokan.services.tracking.BangumiTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.HikkaTrackerService
import eu.friedcutlet.yokan.services.tracking.HikkaTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.JellyfinTrackerService
import eu.friedcutlet.yokan.services.tracking.JellyfinTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.KavitaTrackerService
import eu.friedcutlet.yokan.services.tracking.KavitaTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.KitsuTrackerService
import eu.friedcutlet.yokan.services.tracking.KitsuTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.KomgaTrackerService
import eu.friedcutlet.yokan.services.tracking.KomgaTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.MalTrackerService
import eu.friedcutlet.yokan.services.tracking.MalTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.MangaBakaTrackerService
import eu.friedcutlet.yokan.services.tracking.MangaBakaTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.MangaUpdatesTrackerService
import eu.friedcutlet.yokan.services.tracking.MangaUpdatesTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.MetadataTrackerService
import eu.friedcutlet.yokan.services.tracking.MetadataTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.ShikimoriTrackerService
import eu.friedcutlet.yokan.services.tracking.ShikimoriTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.SimklTrackerService
import eu.friedcutlet.yokan.services.tracking.SimklTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.SuwayomiTrackerService
import eu.friedcutlet.yokan.services.tracking.SuwayomiTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.TmdbTrackerService
import eu.friedcutlet.yokan.services.tracking.TmdbTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.TrackerAccounts
import eu.friedcutlet.yokan.services.tracking.TrackerService
import eu.friedcutlet.yokan.services.tracking.TraktTrackerService
import eu.friedcutlet.yokan.services.tracking.TraktTrackerSyncId
import eu.friedcutlet.yokan.services.translation.LibreTranslateTranslatorService
import eu.friedcutlet.yokan.services.translation.TranslatorService
import eu.friedcutlet.yokan.services.tts.ProfileSpeechService
import eu.friedcutlet.yokan.services.tts.TextToSpeechService
import eu.friedcutlet.yokan.services.tts.createPlatformTextToSpeechService
import eu.friedcutlet.yokan.services.webview.WebViewRequest
import eu.friedcutlet.yokan.services.webview.WebViewService
import eu.friedcutlet.yokan.services.webview.createPlatformWebViewService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
class YokanServices(
val database: YokanDatabase,
val extensionRuntimeFactory: ExtensionRuntimeFactory,
val extensionServer: ExtensionServerRuntimeService,
val trackers: List<TrackerService>,
val trackerAccounts: TrackerAccounts,
val downloader: DownloadService,
val backup: BackupService,
val sync: SyncService,
val cloudSync: CloudBackupSyncService,
val sourceCatalog: SourceCatalogService,
val libraryUpdater: LibraryUpdaterService,
val subtitle: SubtitleService,
val watchOrder: WatchOrderService,
val recommendation: RecommendationService,
val metadata: MetadataService,
val translator: TranslatorService,
val webView: WebViewService,
val http: HttpService,
textToSpeech: TextToSpeechService,
val animeExtractors: List<AnimeExtractorService>,
val localLibrary: LocalLibraryService,
val localEntryManagement: LocalEntryManagementService,
val cookieJar: CookieJar,
val recipeCatalogInstallation: RecipeCatalogInstallationService,
/** Owns background coroutines (download workers, foreground scheduler, startup jobs). */
val scope: CoroutineScope,
val downloadAutomation: DownloadAutomation,
val imageDataSaver: ImageDataSaver,
val externalDownloads: ExternalDownloads,
private val platformHttp: KtorHttpService,
isOwnerOpen: () -> Boolean,
val libraryAirings: LibraryAiringService,
val torrents: TorrentStreams,
) {
val discovery: DiscoveryService by lazy {
HttpDiscoveryService(http, database, extensionRuntimeFactory)
}
val textToSpeech = ProfileSpeechService(textToSpeech, scope, isOwnerOpen)
private val retirementLock = Mutex()
/** Session retirement waits for worker finalizers before releasing captured runtimes. */
suspend fun closeAndJoin() = retirementLock.withLock {
scope.coroutineContext[Job]?.cancelAndJoin()
textToSpeech.closeAndJoin()
extensionServer.stop()
torrents.stop()
extensionRuntimeFactory.clear()
sync.closeAndJoin()
platformHttp.closeAndJoin()
}
}
/**
* Builds the service graph. [files]/[archives]/[notifications]/[backup] are passed in so the whole
* session shares one instance of each (the JVM archive service keeps extraction caches).
* [resolveDownloadPages] resolves a chapter's pages when its download starts.
*/
fun defaultServices(
database: YokanDatabase,
files: LocalFileService,
archives: LocalArchiveService,
notifications: NotificationService,
backup: BackupService,
resolveDownloadPages: suspend (chapterId: Long, forceRefresh: Boolean) -> List<DbPageUrl>,
scope: CoroutineScope,
profileId: ProfileId,
isOwnerOpen: () -> Boolean,
syncLeases: SyncAccountLeases,
/** DNS-over-HTTPS lookup for the main client; must not itself resolve through that client. */
resolveHost: HostResolver?,
): YokanServices {
requireNotNull(scope.coroutineContext[Job]) { "Profile services require an owner job" }
val cookieJar = CookieJar(database, profileId) { scope.coroutineContext[Job]?.isActive == true }
val platformHttp = createPlatformHttpService(profileId, scope, resolveHost)
val rawHttp = ProfileHttpService(profileId, platformHttp, scope)
val enhancedHttp = EnhancedHttpService(rawHttp, database, cookieJar)
val http = ProfileHttpService(profileId, enhancedHttp, scope)
val imageDataSaver = ImageDataSaver(rawHttp, cookieJar)
// Genuine cycle, closed once here: the WebView solver retries through the enhanced client
// (cookie jar + solver-bypass header) and the client hands challenges to the solver.
val webView = createPlatformWebViewService(http, cookieJar, files, scope).also { webView ->
enhancedHttp.cloudflareSolver = { url, headers -> webView.resolveCloudflare(WebViewRequest(url = url, title = "", headers = headers)) }
}
val animeExtractors = animeExtractors(http, cookieJar)
val extensionServer: ExtensionServerRuntimeService = DefaultExtensionServerRuntimeService(
database,
http,
createPlatformExtensionServerAdapter(profileId),
)
val recipeInstallationClock = RecipeInstallationClock { kotlin.time.Clock.System.now().toEpochMilliseconds() / 1_000 }
val recipeServices = createPlatformRecipeServices(database, recipeInstallationClock)
val runtimeFactory = DynamicExtensionRuntimeFactory(
database = database,
http = http,
prepareMihonProxy = { proxy -> extensionServer.resolveMihonProxy(proxy) },
recipeRuntime = recipeServices.runtimeBindings,
archives = archives,
webView = webView,
animeExtractors = animeExtractors,
)
val metadata = HttpMetadataService(http)
val syncOperationMonitor = SyncOperationMonitor()
val cloudSync = DefaultCloudBackupSyncService(
database = database,
backup = backup,
providers = listOf(GoogleDriveCloudStorageProvider(http)),
operationMonitor = syncOperationMonitor,
leases = syncLeases,
)
val serverSync = HubSyncService(
database,
http,
createPlatformHttpClientEngine(profileId),
scope = scope,
operationMonitor = syncOperationMonitor,
leases = syncLeases,
)
// Direct owned transport: the enhanced app client persists Set-Cookie into the profile jar,
// while Mangayomi's id= JWT must remain isolated in the sync preference only.
val mangayomiSync = MangayomiSyncService(database, rawHttp, syncOperationMonitor, syncLeases)
// Same isolation for SyncYomi's API key and Google OAuth tokens.
val syncYomiSync = SyncYomiSyncService(database, backup, rawHttp, syncOperationMonitor, syncLeases)
val googleDriveSync = GoogleDriveSyncService(database, backup, rawHttp, syncOperationMonitor, syncLeases)
val profileSync = ProfileSyncServices(
profileId = profileId,
delegate = HybridSyncService(serverSync, cloudSync, database, syncOperationMonitor, mangayomiSync, syncYomiSync, googleDriveSync),
cloudDelegate = cloudSync,
ownerScope = scope,
)
adoptConfiguredSyncAccount(syncLeases, database, scope)
val localLibrary = DefaultLocalLibraryService(database, files, archives)
// User-hosted/loopback server: direct transport like the self-hosted trackers below.
val torrents = TorrentStreams(database, rawHttp, files, createPlatformTorrServerHost(profileId))
var automationOwner: DownloadAutomation? = null
val downloadPages: suspend (Long, Boolean) -> List<DbPageUrl> = { chapterId, forceRefresh ->
val chapter = checkNotNull(database.chapter(chapterId))
val title = checkNotNull(chapter.mangaId?.let(database::manga))
if (title.itemType == DbItemType.Anime) {
runtimeFactory.withSourceRuntime(database, checkNotNull(title.sourceId)) { runtime ->
runtime.videoList(chapter.url).firstOrNull()?.let { video ->
// Animetail downloads torrent videos through TorrServer's stream URL.
val resolved = torrents.expand(listOf(video), title.name.orEmpty()).first()
mergeSourcePageHeaders(runtime.headers(), listOf(DbPageUrl(url = resolved.url, headers = resolved.headers)))
}.orEmpty()
}
} else resolveDownloadPages(chapterId, forceRefresh)
}
val externalDownloads = ExternalDownloads(database, rawHttp, scope, downloadPages)
val downloader = PersistentDownloadService(
database = database,
http = http,
files = files,
archives = archives,
scope = scope,
resolvePages = downloadPages,
resolveNovelText = { chapterId ->
val chapter = checkNotNull(database.chapter(chapterId))
val title = checkNotNull(chapter.mangaId?.let(database::manga))
runtimeFactory.withSourceRuntime(database, checkNotNull(title.sourceId)) { runtime ->
runtime.cleanHtmlContent(runtime.htmlContent(chapter.name.orEmpty(), chapter.url))
}
},
notifications = notifications,
network = createNetworkMonitor(),
onCompleted = { chapterId -> automationOwner?.downloadCompleted(chapterId) },
imageDataSaver = imageDataSaver,
imageHttp = rawHttp,
).also { keepDownloadsAlive(it, database, scope, profileId) }
val downloadAutomation = DownloadAutomation(database, downloader, scope)
automationOwner = downloadAutomation
val trackers = trackers(database, http, rawHttp, metadata)
return YokanServices(
externalDownloads = externalDownloads,
torrents = torrents,
imageDataSaver = imageDataSaver,
database = database,
extensionRuntimeFactory = runtimeFactory,
extensionServer = extensionServer,
trackers = trackers,
trackerAccounts = TrackerAccounts(database, trackers, scope),
downloader = downloader,
backup = backup,
sync = profileSync.sync,
cloudSync = profileSync.cloud,
sourceCatalog = HttpSourceCatalogService(http, files),
libraryUpdater = DefaultLibraryUpdaterService(database, runtimeFactory, downloadAutomation),
libraryAirings = LibraryAiringService(database, rawHttp, scope),
downloadAutomation = downloadAutomation,
subtitle = SubtitleService(http),
watchOrder = WatchOrderService(http),
recommendation = RecommendationService(http, database),
metadata = metadata,
translator = LibreTranslateTranslatorService(http),
webView = webView,
http = http,
textToSpeech = createPlatformTextToSpeechService(),
animeExtractors = animeExtractors,
localLibrary = localLibrary,
localEntryManagement = DefaultLocalEntryManagementService(database, localLibrary),
cookieJar = cookieJar,
scope = scope,
platformHttp = platformHttp,
recipeCatalogInstallation = recipeServices.installation,
isOwnerOpen = isOwnerOpen,
)
}
// All 16 anime extractors from the Flutter `lib/services/anime_extractors/` directory are ported.
// Sendvid and YourUpload sometimes need source-supplied headers (Referer mostly); those still get
// forwarded through `extract(url, headers)`.
private fun animeExtractors(http: HttpService, cookieJar: CookieJar): List<AnimeExtractorService> = listOf(
StreamTapeExtractor(http),
VoeExtractor(http),
StreamWishExtractor(http),
FilemoonExtractor(http),
GogoCdnExtractor(http),
DoodExtractor(http),
Mp4UploadExtractor(http),
MyStreamExtractor(http),
MytvExtractor(http),
OkruExtractor(http),
SendvidExtractor(http),
SibnetExtractor(http),
StreamlareExtractor(http),
VidBomExtractor(http),
YourUploadExtractor(http),
QuarkUcExtractor(http, cookieJar),
// Kwik / Pahewin — AnimePahe's HLS / MP4 wrapper. HLS path is
// packed-eval; MP4 path is the kwik.cx custom obfuscator + form
// POST. See KwikExtractor.kt for caveats around Cloudflare.
KwikExtractor(http),
)
private fun trackers(
database: YokanDatabase,
http: HttpService,
rawHttp: HttpService,
metadata: MetadataService,
): List<TrackerService> = listOf(
MalTrackerService(MalTrackerSyncId, database, http),
AnilistTrackerService(AnilistTrackerSyncId, database, http),
KitsuTrackerService(KitsuTrackerSyncId, database, http),
SimklTrackerService(SimklTrackerSyncId, database, http),
TraktTrackerService(TraktTrackerSyncId, database, http),
MetadataTrackerService(MetadataTrackerSyncId, database, metadata),
MangaUpdatesTrackerService(MangaUpdatesTrackerSyncId, database, http),
ShikimoriTrackerService(ShikimoriTrackerSyncId, database, http),
BangumiTrackerService(BangumiTrackerSyncId, database, http),
HikkaTrackerService(HikkaTrackerSyncId, database, http),
MangaBakaTrackerService(MangaBakaTrackerSyncId, database, http),
TmdbTrackerService(TmdbTrackerSyncId, database, http),
// User-hosted servers (often LAN addresses) bypass the DoH/cookie layer, like the sync servers.
KomgaTrackerService(KomgaTrackerSyncId, database, rawHttp),
KavitaTrackerService(KavitaTrackerSyncId, database, rawHttp),
SuwayomiTrackerService(SuwayomiTrackerSyncId, database, rawHttp),
JellyfinTrackerService(JellyfinTrackerSyncId, database, rawHttp),
)
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines StartupStatus, StartupCheck, PlatformBootstrapInput, AppBootstrapReport, runStartupChecks, platformBootstrapInput, installPlatformCrashLogger, checkPersistence, checkDownloadWorkers, checkExtensionRuntime and 6 further declarations.
The source describes its contract as:
Runs the startup checks listed in Settings → About and logs each one.
Cross-chapter imports used by this file: DbSettings, DbSourceCodeLanguage, YokanDatabase, DiscordRpcService, isLoopbackProxy, AppLogger. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.discord.DiscordRpcService
import eu.friedcutlet.yokan.services.extensions.mihon.defaultMihonProxyUrl
import eu.friedcutlet.yokan.services.http.isLoopbackProxy
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.runBlockingCompat
enum class StartupStatus {
Ok,
Warning,
Error,
}
data class StartupCheck(
val name: String,
val status: StartupStatus,
val notes: String,
)
data class PlatformBootstrapInput(
val platformName: String,
val initialDeepLink: String? = null,
val appDataPath: String? = null,
)
data class AppBootstrapReport(
val platform: PlatformBootstrapInput,
val checks: List<StartupCheck>,
) {
val initialDeepLink: String? get() = platform.initialDeepLink
val hasErrors: Boolean get() = checks.any { it.status == StartupStatus.Error }
val summary: String get() = "${checks.count { it.status == StartupStatus.Ok }} ok, ${checks.count { it.status == StartupStatus.Warning }} warnings, ${checks.count { it.status == StartupStatus.Error }} errors"
}
/** Runs the startup checks listed in Settings → About and logs each one. */
internal fun runStartupChecks(
input: PlatformBootstrapInput,
services: YokanServices,
discordRpc: DiscordRpcService,
): AppBootstrapReport {
val checks = buildList {
add(startupOk("Platform", "${input.platformName}${input.appDataPath?.let { " data=$it" }.orEmpty()}"))
add(checkPersistence(services.database))
add(checkDownloadWorkers(services))
add(checkExtensionRuntime(services))
add(checkDeepLinks(input))
add(checkLogging())
add(checkDiscordRpc(input, services.database.settings(), discordRpc))
}
checks.forEach { check ->
when (check.status) {
StartupStatus.Ok -> AppLogger.info("${check.name}: ${check.notes}")
StartupStatus.Warning -> AppLogger.warn("${check.name}: ${check.notes}")
StartupStatus.Error -> AppLogger.error("${check.name}: ${check.notes}")
}
}
return AppBootstrapReport(input, checks)
}
expect fun platformBootstrapInput(): PlatformBootstrapInput
expect fun installPlatformCrashLogger(onCrash: (Throwable) -> Unit)
private fun checkPersistence(database: YokanDatabase): StartupCheck {
val snapshot = database.snapshot()
return startupOk(
"Persistence",
"loaded ${snapshot.mangas.size} titles, ${snapshot.chapters.size} chapters, ${snapshot.sources.size} sources",
)
}
private fun checkDownloadWorkers(services: YokanServices): StartupCheck = runCatching {
runBlockingCompat { services.downloader.initialize(services.database.settings().concurrentDownloads) }
startupOk("Download workers", "initialized pool size ${services.database.settings().concurrentDownloads}; recovered ${services.downloader.activeDownloads().size} active tasks")
}.getOrElse { error ->
startupError("Download workers", error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() })
}
private fun checkExtensionRuntime(services: YokanServices): StartupCheck {
val sources = services.database.sources()
val jsCount = sources.count { it.sourceCodeLanguage == DbSourceCodeLanguage.JavaScript }
val mihonCount = sources.count { it.sourceCodeLanguage == DbSourceCodeLanguage.Mihon }
val lnReaderCount = sources.count { it.sourceCodeLanguage == DbSourceCodeLanguage.LnReader }
val proxy = services.database.settings().androidProxyServer ?: defaultMihonProxyUrl
val usesLocalProxy = isLoopbackProxy(proxy)
var serverNote = if (mihonCount > 0 && !usesLocalProxy) "; remote extension server configured" else ""
var serverWarning: String? = null
if (mihonCount > 0 && usesLocalProxy) {
if (!services.extensionServer.isConfigured()) {
serverWarning = "local extension server is not installed or bundled"
} else {
serverNote = "; local server startup scheduled"
}
}
val runtimeFailures = sources.mapNotNull { source ->
runCatching { services.extensionRuntimeFactory.create(source).dispose() }
.exceptionOrNull()
?.let { error -> "${source.name}: ${error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() }}" }
}
val notes = "QuickJS=$jsCount, Mihon=$mihonCount via $proxy, LNReader=$lnReaderCount"
val fullNotes = notes + serverNote
return when {
runtimeFailures.isNotEmpty() -> startupError("Extension runtime", runtimeFailures.joinToString())
serverWarning != null -> startupWarning("Extension runtime", "$fullNotes; $serverWarning")
else -> startupOk("Extension runtime", fullNotes)
}
}
private fun checkDeepLinks(input: PlatformBootstrapInput): StartupCheck =
startupOk("Deep links", input.initialDeepLink?.let { "captured initial link $it" } ?: "initialized; no initial link")
private fun checkLogging(): StartupCheck = startupOk("Logging", "in-memory startup and crash log buffer ready")
private fun checkDiscordRpc(input: PlatformBootstrapInput, settings: DbSettings, service: DiscordRpcService): StartupCheck = when {
!settings.enableDiscordRpc -> startupOk("Discord RPC", "disabled in settings")
else -> {
val status = service.initialize(settings)
if (status.connected) startupOk("Discord RPC", status.message) else startupWarning("Discord RPC", status.message)
}
}
private fun startupOk(name: String, notes: String) = StartupCheck(name, StartupStatus.Ok, notes)
private fun startupWarning(name: String, notes: String) = StartupCheck(name, StartupStatus.Warning, notes)
private fun startupError(name: String, notes: String) = StartupCheck(name, StartupStatus.Error, notes)
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/AppStartup.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines runAppStartup.
The source describes its contract as:
One-shot startup maintenance, run once from the app root after bootstrap. Each task runs concurrently.
Cross-chapter imports used by this file: InAppNotifications, checkForAppUpdate. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app
import coil3.PlatformContext
import coil3.SingletonImageLoader
import eu.friedcutlet.yokan.ui.image.clearCaches
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.notifications.InAppNotifications
import eu.friedcutlet.yokan.services.updates.checkForAppUpdate
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
/** One-shot startup maintenance, run once from the app root after bootstrap. Each task runs concurrently. */
internal suspend fun runAppStartup(imageContext: PlatformContext): Unit = coroutineScope {
val owner = YokanRuntime.activeSession
val settings = owner.settings.db.value
// "Clear chapter/episode cache on app launch": the same chapter cache as the Data and storage
// button — Coil's disk+memory image caches (like Mangayomi's DefaultCacheManager.emptyCache())
// and the saved chapter page lists.
launch(Dispatchers.Default) {
if (!owner.services.database.settings().clearChapterCacheOnAppLaunch) return@launch
runCatching {
SingletonImageLoader.get(imageContext).clearCaches()
owner.repository.clearPageCache()
}
}
// Auto-prune browsed (non-favorite) titles the user never interacted with
// (no history, downloads, or tracking), so cached browse results don't
// pile up until a manual "Clean database".
launch(Dispatchers.Default) {
runCatching { owner.repository.pruneBrowsedTitles() }
}
// Startup extension repo check (Mangayomi's main_screen behavior): when
// "Check for extension updates" is on, fetch every item-type repository
// shortly after launch; the refresh auto-installs updates when
// autoExtensionsUpdates is enabled.
if (settings.checkForExtensionUpdates) {
launch(Dispatchers.Default) {
delay(2_000)
owner.sourceInstall.refreshAllRepositories()
}
}
// Startup app-update check (Mangayomi main_screen): compare the latest
// GitHub release with the installed version and surface a toast.
if (settings.checkForAppUpdates) {
launch {
delay(3_000)
catchingNonCancellation {
checkForAppUpdate(owner.services.http)?.let { release ->
InAppNotifications.post(
"Update available: ${release.tag}",
"Open More → About to download it.",
)
}
}
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/YokanRuntime.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines YokanRuntime, runBackgroundTask, runBackgroundDownloads, bootstrap, bootstrapReport, reschedulePeriodicTasks, startup, startForeground, scheduleExtensionServerStart, PeriodicSchedule.
The source describes its contract as:
Process-wide facade over the currently published session. Mutable dependencies capture that owner; device resources and profile commands survive foreground session retirement.
Cross-chapter imports used by this file: ProfileWorkResult, DownloadService, DbSourceCodeLanguage, AppLockController, createPlatformAppLockController, DiscordRpcService. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app
import eu.friedcutlet.yokan.app.profiles.ProfileBackgroundWork
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult
import eu.friedcutlet.yokan.services.download.DownloadService
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.services.applock.AppLockController
import eu.friedcutlet.yokan.services.applock.createPlatformAppLockController
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.discord.DiscordRpcService
import eu.friedcutlet.yokan.services.discord.createPlatformDiscordRpcService
import eu.friedcutlet.yokan.services.extensions.mihon.ExtensionServerRuntimeMode
import eu.friedcutlet.yokan.services.extensions.mihon.defaultMihonProxyUrl
import eu.friedcutlet.yokan.services.extensions.mihon.extensionServerPortFromUrl
import eu.friedcutlet.yokan.services.http.isLoopbackProxy
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.logging.CrashReportStore
import eu.friedcutlet.yokan.services.scheduling.BackgroundScheduler
import eu.friedcutlet.yokan.services.scheduling.PeriodicTaskOutcome
import eu.friedcutlet.yokan.services.scheduling.PeriodicTaskRunner
import eu.friedcutlet.yokan.services.scheduling.backupFrequencyHours
import eu.friedcutlet.yokan.services.scheduling.periodicMinutes
import eu.friedcutlet.yokan.ui.screens.reader.ReaderSystemUiController
import eu.friedcutlet.yokan.ui.screens.reader.createReaderSystemUiController
import eu.friedcutlet.yokan.util.PlatformLock
import kotlinx.coroutines.launch
import kotlin.concurrent.Volatile
/**
* Process-wide facade over the currently published session. Mutable dependencies capture that owner;
* device resources and profile commands survive foreground session retirement.
*/
object YokanRuntime {
internal val profileUi = eu.friedcutlet.yokan.app.profiles.ProfileUiLifetime()
internal val profileCoordinator: eu.friedcutlet.yokan.app.profiles.ProfileCoordinator by lazy {
eu.friedcutlet.yokan.app.profiles.ProfileCoordinator(
profiles,
eu.friedcutlet.yokan.app.profiles.createPlatformProfileSession(ProfileId.Default, profiles.syncLeases(ProfileId.Default), ::reschedulePeriodicTasks),
openSession = { eu.friedcutlet.yokan.app.profiles.openPlatformProfileSession(it, profiles.syncLeases(it), ::reschedulePeriodicTasks) },
prepare = { owner ->
owner.attachLogging()
reschedulePeriodicTasks(owner)
if (foregroundStarted) startForeground(owner)
},
detach = profileUi::detach,
deleteStorage = { id ->
eu.friedcutlet.yokan.app.profiles.cancelProfileBackgroundWork(id)
val exports = profiles.refresh().profiles.single { it.id == id }.exportedBackups
eu.friedcutlet.yokan.app.profiles.deleteProfileStorage(id, exports)
scheduleLock.withLock { lastSchedules.remove(id) }
},
)
}
internal val activeSession: eu.friedcutlet.yokan.app.profiles.ProfileSession get() = profileCoordinator.currentSession
val database get() = activeSession.database
val localFiles get() = activeSession.localFiles
val notifications get() = activeSession.notifications
val services get() = activeSession.services
internal val together get() = activeSession.together
val repository get() = activeSession.repository
val periodicTasks get() = activeSession.periodicTasks
val settings get() = activeSession.settings
val libraryIndex get() = activeSession.libraryIndex
val libraryUpdates get() = activeSession.libraryUpdates
val localLibrary get() = activeSession.localLibrary
val colorizationQueue get() = activeSession.colorizationQueue
val migration get() = activeSession.migration
val chapterDownloads get() = activeSession.chapterDownloads
val sourceInstall get() = activeSession.sourceInstall
val discordRpc: DiscordRpcService by lazy { createPlatformDiscordRpcService() }
val readerSystemUi: ReaderSystemUiController by lazy { createReaderSystemUiController() }
val profiles by lazy { eu.friedcutlet.yokan.app.profiles.createPlatformProfileRegistry() }
private val backgroundWork by lazy {
ProfileBackgroundWork(profiles, supported = { true }, sessions = profileCoordinator)
}
suspend fun runBackgroundTask(
owner: String?,
allowLegacyDefault: Boolean = false,
task: suspend PeriodicTaskRunner.() -> PeriodicTaskOutcome,
): ProfileWorkResult<PeriodicTaskOutcome> = backgroundWork.run(owner, allowLegacyDefault) { session ->
session.periodicTasks.task()
}
suspend fun runBackgroundDownloads(
owner: String?,
allowLegacyDefault: Boolean = false,
task: suspend DownloadService.() -> Unit,
): ProfileWorkResult<Unit> = backgroundWork.run(owner, allowLegacyDefault) { session ->
session.services.downloader.task()
}
val appIcons by lazy { eu.friedcutlet.yokan.services.appicons.createPlatformAppIconService() }
val appLock: AppLockController by lazy { createPlatformAppLockController() }
// Serializes [bootstrap]: App.kt, desktop main, iOS BGTasks and Android workers can all call it
// concurrently.
private val bootstrapLock = PlatformLock()
@Volatile
private var report: AppBootstrapReport? = null
private var foregroundStarted = false
private val scheduleLock = PlatformLock()
private val lastSchedules = mutableMapOf<ProfileId, PeriodicSchedule>()
/**
* Runs the startup checks once per process; later calls return the same report.
*
* [background] callers (OS workers, BGTasks) only need services: they skip the embedded
* extension server and the in-app [ForegroundScheduler], which start on the first foreground
* call instead. OS task rescheduling runs in both modes because iOS BGTasks must re-submit
* themselves after a cold background launch.
*/
fun bootstrap(
input: PlatformBootstrapInput = platformBootstrapInput(),
background: Boolean = false,
): AppBootstrapReport = bootstrapLock.withLock {
val current = report ?: startup(input).also { started ->
services.scope.launch {
catchingNonCancellation { profiles.refresh() }
.onFailure { AppLogger.warn("Profile registry unavailable; existing Default storage remains available") }
}
report = started
runCatching { reschedulePeriodicTasks() }
.onFailure { AppLogger.warn("Could not schedule periodic tasks: ${it.message.orEmpty()}") }
}
if (!background && !foregroundStarted) {
foregroundStarted = true
startForeground(activeSession)
}
current
}
fun bootstrapReport(): AppBootstrapReport = report ?: bootstrap()
/**
* No-op until [bootstrap] has run, and when the settings-derived schedule is unchanged since
* the last call; [BackgroundScheduler.schedule] itself is idempotent.
*/
fun reschedulePeriodicTasks() = reschedulePeriodicTasks(activeSession)
private fun reschedulePeriodicTasks(owner: eu.friedcutlet.yokan.app.profiles.ProfileSession) {
if (owner.status.value != eu.friedcutlet.yokan.app.profiles.ProfileSessionStatus.Open) return
val db = owner.database.settings()
val syncPreference = owner.database.syncPreferences().firstOrNull()
val syncSeconds = syncPreference
?.takeIf { it.syncOn && !it.authToken.isNullOrBlank() }
?.autoSyncFrequency
?: 0
val schedule = PeriodicSchedule(
metadataRefreshMinutes = periodicMinutes(if (db.metadataServerEnabled) db.metadataRefreshFrequencySeconds else 0),
libraryUpdateMinutes = periodicMinutes(db.libraryUpdateFrequencySeconds),
libraryUpdateDailyAtMinutes = db.libraryUpdateDailyAtMinutes,
autoSyncMinutes = periodicMinutes(syncSeconds),
autoBackupHours = backupFrequencyHours(db.backupFrequency),
requireUnmetered = db.downloadOnlyOnWifi,
libraryConstraints = db.features.library.deviceConstraints,
)
scheduleLock.withLock {
if (schedule == lastSchedules[owner.id]) return@withLock
owner.backgroundScheduler.schedule(
metadataRefreshMinutes = schedule.metadataRefreshMinutes,
libraryUpdateMinutes = schedule.libraryUpdateMinutes,
libraryUpdateDailyAtMinutes = schedule.libraryUpdateDailyAtMinutes,
autoSyncMinutes = schedule.autoSyncMinutes,
autoBackupHours = schedule.autoBackupHours,
requireUnmetered = schedule.requireUnmetered,
libraryConstraints = schedule.libraryConstraints,
)
lastSchedules[owner.id] = schedule
}
}
private fun startup(input: PlatformBootstrapInput): AppBootstrapReport {
val crashFiles = eu.friedcutlet.yokan.services.files.createPlatformLocalFileService(ProfileId.Default)
installPlatformCrashLogger { throwable ->
// Broken pipes are routine when a client (player, WebView resource
// fetch, etc.) disconnects mid-write — drop them to debug so they
// don't masquerade as crashes.
val name = throwable::class.simpleName.orEmpty()
val message = throwable.message.orEmpty()
val isBrokenPipe = name == "SocketException" && message.contains("broken pipe", ignoreCase = true)
if (isBrokenPipe) {
AppLogger.warn("Suppressed $name: $message")
} else {
CrashReportStore.record(crashFiles, throwable)
AppLogger.error("Unhandled $name: ${CrashReportStore.redact(message)}")
}
}
activeSession.attachLogging()
return runStartupChecks(input, services, discordRpc)
}
private fun startForeground(owner: eu.friedcutlet.yokan.app.profiles.ProfileSession) {
scheduleExtensionServerStart(owner)
if (owner.colorizationQueue.supported) owner.colorizationQueue.start()
owner.foregroundScheduler.start()
owner.syncTriggers.onTrigger(eu.friedcutlet.yokan.services.sync.SyncTriggerKind.AppStart)
}
private fun scheduleExtensionServerStart(owner: eu.friedcutlet.yokan.app.profiles.ProfileSession) {
val services = owner.services
val database = owner.database
if (services.extensionServer.mode == ExtensionServerRuntimeMode.IosSideloadedJvm) return
if (database.sources().none { it.sourceCodeLanguage == DbSourceCodeLanguage.Mihon }) return
val proxy = database.settings().androidProxyServer ?: defaultMihonProxyUrl
if (!isLoopbackProxy(proxy) || !services.extensionServer.isConfigured()) return
services.scope.launch {
catchingNonCancellation {
services.extensionServer.startIfConfigured(extensionServerPortFromUrl(proxy))
}.onSuccess { status ->
AppLogger.info(
"Extension runtime: local server ${status?.phase?.name?.lowercase() ?: "not configured"}",
)
}.onFailure { error ->
AppLogger.warn(
"Extension runtime: ${error.message.orEmpty().ifBlank { "local extension server failed to start" }}",
)
}
}
}
}
/** The arguments of [BackgroundScheduler.schedule], compared to skip redundant rescheduling. */
private data class PeriodicSchedule(
val metadataRefreshMinutes: Long,
val libraryUpdateMinutes: Long,
val libraryUpdateDailyAtMinutes: Int,
val autoSyncMinutes: Long,
val autoBackupHours: Long,
val requireUnmetered: Boolean,
val libraryConstraints: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints,
)
Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.android.kt
Create this path in your reconstruction project. Source set: androidMain. Exact file download.
The implementation below defines AndroidBootstrapState, platformBootstrapInput.
Cross-chapter imports used by this file: AndroidAppContext. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app
import eu.friedcutlet.yokan.AndroidAppContext
object AndroidBootstrapState {
var initialDeepLink: String? = null
}
actual fun platformBootstrapInput(): PlatformBootstrapInput = PlatformBootstrapInput(
platformName = "Android",
initialDeepLink = AndroidBootstrapState.initialDeepLink,
appDataPath = AndroidAppContext.appContext?.filesDir?.absolutePath,
)
Write composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.desktop.kt
Create this path in your reconstruction project. Source set: desktopMain. Exact file download.
The implementation below defines DesktopBootstrapState, platformBootstrapInput, desktopLaunchLink.
The source describes its contract as:
--search \<query\>/--search=\<query\>, an app link, or a backup file path (file associations pass the path).
Cross-chapter imports used by this file: searchDeepLink. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app
import eu.friedcutlet.yokan.services.files.desktopDataRoot
import eu.friedcutlet.yokan.ui.navigation.searchDeepLink
import java.io.File
object DesktopBootstrapState {
var args: Array<String> = emptyArray()
}
actual fun platformBootstrapInput(): PlatformBootstrapInput = PlatformBootstrapInput(
platformName = "Desktop",
initialDeepLink = desktopLaunchLink(DesktopBootstrapState.args),
appDataPath = desktopDataRoot.absolutePath,
)
private val linkSchemes = listOf("yokan://", "tachiyomi://", "mihon://", "aniyomi://", "animetail://", "http://", "https://", "file:")
/** `--search <query>` / `--search=<query>`, an app link, or a backup file path (file associations pass the path). */
internal fun desktopLaunchLink(args: Array<String>): String? {
val search = args.indexOf("--search").takeIf { it >= 0 }?.let { args.getOrNull(it + 1) }
?: args.firstOrNull { it.startsWith("--search=") }?.removePrefix("--search=")
if (!search.isNullOrBlank()) return searchDeepLink(search.trim())
return args.firstOrNull { arg -> linkSchemes.any(arg::startsWith) }
?: args.firstOrNull { !it.startsWith("-") && File(it).isFile }?.let { File(it).absoluteFile.toURI().toString() }
}
Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.ios.kt
Create this path in your reconstruction project. Source set: iosMain. Exact file download.
The implementation below defines platformBootstrapInput, installPlatformCrashLogger.
package eu.friedcutlet.yokan.app
actual fun platformBootstrapInput(): PlatformBootstrapInput = PlatformBootstrapInput(
platformName = "iOS",
)
actual fun installPlatformCrashLogger(onCrash: (Throwable) -> Unit) = Unit
Write composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.jvm.kt
Create this path in your reconstruction project. Source set: jvmCommonMain. Exact file download.
The implementation below defines installPlatformCrashLogger.
package eu.friedcutlet.yokan.app
actual fun installPlatformCrashLogger(onCrash: (Throwable) -> Unit) {
val previous = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
onCrash(throwable)
previous?.uncaughtException(thread, throwable)
}
}
Write composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.wasm.kt
Create this path in your reconstruction project. Source set: wasmJsMain. Exact file download.
The implementation below defines platformBootstrapInput, installPlatformCrashLogger, webLaunchLink.
The source describes its contract as:
?search=\<query\>opens global search;?link=\<app link\>(e.g. an add-repo link) goes through the shared handler.
Cross-chapter imports used by this file: parseQueryParameters, searchDeepLink. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app
import eu.friedcutlet.yokan.ui.navigation.parseQueryParameters
import eu.friedcutlet.yokan.ui.navigation.searchDeepLink
import kotlinx.browser.window
actual fun platformBootstrapInput(): PlatformBootstrapInput = PlatformBootstrapInput(
platformName = "Web",
initialDeepLink = webLaunchLink(window.location.search),
)
actual fun installPlatformCrashLogger(onCrash: (Throwable) -> Unit) = Unit
/** `?search=<query>` opens global search; `?link=<app link>` (e.g. an add-repo link) goes through the shared handler. */
internal fun webLaunchLink(locationSearch: String): String? {
val parameters = parseQueryParameters(locationSearch)
parameters["search"]?.firstOrNull()?.trim()?.takeIf(String::isNotEmpty)?.let { return searchDeepLink(it) }
return parameters["link"]?.firstOrNull()?.takeIf(String::isNotBlank)
}
Check your understanding
Find a downloader callback and trace every captured dependency back to the original session. Would changing the active profile alter any of those references? [chapter-content-end]: #
Step 3: implement retirement before switching
Session states are Open, Retiring, RetirementFailed and Closed. Reject new work when retiring. Stop and join UI/reader progress owners, cancel and join the session job and child finalizers, release initialized resources in reverse registration order, then mark Closed. A timeout or cleanup failure remains retryable as retirement failure. A retired owner is never made active again.
Register context-dependent resources atomically with retirement. Expose closeAndJoin/releaseAndJoin when cleanup performs writes or releases native handles; a synchronous flag flip is insufficient. Caller cancellation cancels its child operation and joins cleanup without killing sibling work. Already-cancelled callers must not dispatch side effects.
Follow the code
Retirement first stops admitting work, then asks UI/progress owners to finish, cancels and joins jobs, and releases initialized resources. In ProfileSession.close, the non-cancellable cleanup region protects finalizers after caller cancellation. A timeout or failure keeps retirement retryable; it must not make the old graph active again. UI lifetime helpers let route owners finish final progress before storage disappears.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileUiLifetime.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.ktcomposeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.android.ktcomposeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.desktop.ktcomposeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.ios.ktcomposeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.wasm.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileUiLifetime.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ProfileUiLifetime, mount, detach.
The source describes its contract as:
Composition disposal captures final progress before the navigator begins awaited retirement.
Cross-chapter imports used by this file: PlatformLock. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app.profiles
import eu.friedcutlet.yokan.util.PlatformLock
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.yield
/** Composition disposal captures final progress before the navigator begins awaited retirement. */
internal class ProfileUiLifetime {
private val lock = PlatformLock()
private val mounts = mutableMapOf<ProfileSession, MutableSet<CompletableDeferred<Unit>>>()
fun mount(session: ProfileSession): () -> Unit {
val ticket = CompletableDeferred<Unit>()
lock.withLock { mounts.getOrPut(session) { mutableSetOf() }.add(ticket) }
return {
lock.withLock {
mounts[session]?.let { it.remove(ticket); if (it.isEmpty()) mounts.remove(session) }
ticket.complete(Unit)
}
}
}
suspend fun detach(session: ProfileSession) = withTimeout(15_000) {
val tickets = lock.withLock { mounts[session]?.toList().orEmpty() }
withContext(Dispatchers.Main) {
tickets.forEach { it.await() }
// Resume after the synchronous apply/disposal pass, including child disposers.
yield()
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines cancelProfileBackgroundWork.
The source describes its contract as:
Removes only the selected owner's OS jobs and notifications, without opening its database.
package eu.friedcutlet.yokan.app.profiles
import eu.friedcutlet.yokan.domain.ProfileId
/** Removes only the selected owner's OS jobs and notifications, without opening its database. */
internal expect suspend fun cancelProfileBackgroundWork(id: ProfileId)
Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.android.kt
Create this path in your reconstruction project. Source set: androidMain. Exact file download.
The implementation below defines cancelProfileBackgroundWork.
Cross-chapter imports used by this file: AndroidAppContext, ProfileWorkNamespace. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app.profiles
import android.app.NotificationManager
import android.content.Context
import androidx.work.WorkManager
import androidx.work.await
import eu.friedcutlet.yokan.AndroidAppContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkNamespace
internal actual suspend fun cancelProfileBackgroundWork(id: ProfileId) = withContext(Dispatchers.IO) {
require(id != ProfileId.Default)
val context = checkNotNull(AndroidAppContext.appContext)
val work = WorkManager.getInstance(context)
val names = ProfileWorkNamespace(id)
listOf("yokan.metadata_refresh", "yokan.library_update", "yokan.auto_sync", "yokan.auto_backup", "yokan.download_resume").forEach {
work.cancelUniqueWork(names.uniqueName(it)).await()
}
val notifications = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val prefix = "yokan.profile.${id.value}."
notifications.activeNotifications.filter { it.tag?.startsWith(prefix) == true }.forEach { notifications.cancel(it.tag, it.id) }
}
Write composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.desktop.kt
Create this path in your reconstruction project. Source set: desktopMain. Exact file download.
The implementation below defines cancelProfileBackgroundWork.
package eu.friedcutlet.yokan.app.profiles
import eu.friedcutlet.yokan.domain.ProfileId
internal actual suspend fun cancelProfileBackgroundWork(id: ProfileId) { require(id != ProfileId.Default) }
Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.ios.kt
Create this path in your reconstruction project. Source set: iosMain. Exact file download.
The implementation below defines cancelProfileBackgroundWork.
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
package eu.friedcutlet.yokan.app.profiles
import kotlinx.coroutines.suspendCancellableCoroutine
import platform.UserNotifications.*
import kotlin.coroutines.resume
import eu.friedcutlet.yokan.domain.ProfileId
internal actual suspend fun cancelProfileBackgroundWork(id: ProfileId) {
require(id != ProfileId.Default)
// Fixed permitted BGTask identifiers are Default-owned. Extras have foreground work only.
val center = UNUserNotificationCenter.currentNotificationCenter()
val prefix = "yokan.profile.${id.value}."
suspendCancellableCoroutine<Unit> { continuation ->
center.getDeliveredNotificationsWithCompletionHandler { values ->
val ids = values.orEmpty().filterIsInstance<UNNotification>().map { it.request.identifier }.filter { it.startsWith(prefix) }
center.removeDeliveredNotificationsWithIdentifiers(ids)
continuation.resume(Unit)
}
}
suspendCancellableCoroutine<Unit> { continuation ->
center.getPendingNotificationRequestsWithCompletionHandler { values ->
val ids = values.orEmpty().filterIsInstance<UNNotificationRequest>().map { it.identifier }.filter { it.startsWith(prefix) }
center.removePendingNotificationRequestsWithIdentifiers(ids)
continuation.resume(Unit)
}
}
}
Write composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.wasm.kt
Create this path in your reconstruction project. Source set: wasmJsMain. Exact file download.
The implementation below defines cancelProfileBackgroundWork.
package eu.friedcutlet.yokan.app.profiles
import eu.friedcutlet.yokan.domain.ProfileId
internal actual suspend fun cancelProfileBackgroundWork(id: ProfileId) { require(id != ProfileId.Default) }
Check your understanding
Suspend a final progress write, begin retirement, and verify that database close has not happened yet. Retry a failed cleanup without constructing duplicate native resources. [chapter-content-end]: #
Step 4: implement activation and recovery
ProfileCoordinator serializes activation and storage leases. Define Ready, Switching and RecoveryRequired UI states. Implement create/provision/retry, rename, switch, recover and delete. Clear profile navigation/ViewModel/image state before exposing the new graph. If an owner was retired, recovery opens a fresh session rather than republishing stale objects.
Use storage leases to exclude conflicting activation/background work/deletion; long work must not hold the coordinator mutation mutex for its full duration. Reference-count inactive work sessions and retire them when their last lease ends. Profile storage deletion cancels its jobs and deletes its owned data while preserving external folders and exported backups.
The old createPlatformProfileSession helper explicitly allows Default only. Current additional-profile activation uses openPlatformProfileSession and a storage lease. Do not infer that all extra profiles are unavailable from that legacy helper or older architecture paragraphs. Enforce each actual platform integration's remaining restrictions.
Follow the code
Activation must coordinate both the current UI graph and ownership of target storage. A storage lease outlives database/native writes, preventing another session or deletion from using the same files too early. Follow openPlatformProfileSession's failure path: it closes either the partially created session or the bare lease, retaining the original error. Recovery opens a fresh session after terminal retirement. Deletion removes owned data while preserving external folders and exported backups.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileCoordinator.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfileBackupScreen.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfileBackupsViewModel.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfilesScreen.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfilesViewModel.ktcomposeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.android.ktcomposeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.android.ktcomposeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.desktop.ktcomposeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.desktop.ktcomposeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/IosBackgroundTaskRegistration.ktcomposeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.ios.ktcomposeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.ios.ktcomposeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/profiles/FileProfileRegistryPersistence.ktcomposeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.jvm.ktcomposeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.jvm.ktcomposeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.wasm.ktcomposeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.wasm.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
Acquisition is followed by another cancellation check. If construction/preparation fails, cleanup runs non-cancellably and attaches any closing failure as a suppressed error instead of hiding the original failure.
The implementation below defines interface, acquireProfileStorageLease, openPlatformProfileSession.
The source describes its contract as:
Held until the owner's database and native writes have drained. Lock files live outside its data.
package eu.friedcutlet.yokan.app.profiles
import kotlinx.coroutines.ensureActive
import eu.friedcutlet.yokan.domain.ProfileId
/** Held until the owner's database and native writes have drained. Lock files live outside its data. */
internal fun interface ProfileStorageLease { suspend fun close() }
internal expect suspend fun acquireProfileStorageLease(id: ProfileId): ProfileStorageLease
internal suspend fun openPlatformProfileSession(
id: ProfileId,
syncLeases: eu.friedcutlet.yokan.services.sync.SyncAccountLeases,
onScheduleChanged: (ProfileSession) -> Unit = {},
): ProfileSession {
kotlinx.coroutines.currentCoroutineContext().ensureActive()
val lease = acquireProfileStorageLease(id)
var session: ProfileSession? = null
return try {
kotlinx.coroutines.currentCoroutineContext().ensureActive()
ProfileSession(id, storageLease = lease, onScheduleChanged = onScheduleChanged, syncLeases = syncLeases).also {
session = it
it.localFiles.prepare()
}
}
catch (error: Throwable) {
kotlinx.coroutines.withContext(kotlinx.coroutines.NonCancellable) {
try { session?.close() ?: lease.close() }
catch (closing: Throwable) { error.addSuppressed(closing) }
}
throw error
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileCoordinator.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
This coordinator is the state machine for activation and recovery. Keep long-running session work outside the mutation lock and preserve the distinctions between a registry record, a leased storage directory and a published UI session.
The implementation below defines ProfileActivationState, Ready, Switching, RecoveryRequired, ProfileCoordinator, WorkLease, run, switchTo, recover, create and 16 further declarations.
The source describes its contract as:
Serializes activation and storage leases. A retiring owner is never republished: recovery opens a fresh session only after every failed release succeeds. The UI detach hook must await composition disposal (including its final progress saves) before session retirement begins.
Cross-chapter imports used by this file: ProfileWorkResult. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app.profiles
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.NonCancellable
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 eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult
internal sealed interface ProfileActivationState {
data class Ready(val session: ProfileSession, val recoveryMessage: String? = null) : ProfileActivationState
data class Switching(val from: ProfileId, val to: ProfileId) : ProfileActivationState
data class RecoveryRequired(val profile: ProfileId, val message: String) : ProfileActivationState
}
/**
* Serializes activation and storage leases. A retiring owner is never republished: recovery opens a
* fresh session only after every failed release succeeds. The UI detach hook must await composition
* disposal (including its final progress saves) before session retirement begins.
*/
internal class ProfileCoordinator(
private val registry: ProfileRegistry,
initialSession: ProfileSession,
private val openSession: suspend (ProfileId) -> ProfileSession,
private val prepare: suspend (ProfileSession) -> Unit,
private val detach: suspend (ProfileSession) -> Unit,
private val deleteStorage: suspend (ProfileId) -> Unit,
) : ProfileWorkSessions {
private val mutex = Mutex()
private val _state = MutableStateFlow<ProfileActivationState>(ProfileActivationState.Ready(initialSession))
val state = _state.asStateFlow()
@kotlin.concurrent.Volatile
private var active = initialSession
val currentSession: ProfileSession get() = active
private val pendingRetirements = mutableListOf<ProfileSession>()
private class WorkLease(val session: ProfileSession, var references: Int = 0)
private val workLeases = mutableMapOf<ProfileId, WorkLease>()
/** Long OS jobs do not hold the mutation mutex. Retirement cancels/joins their captured session. */
override suspend fun <T> run(id: ProfileId, action: suspend (ProfileSession) -> T): ProfileWorkResult<T> {
val lease = mutex.withLock {
currentCoroutineContext().ensureActive()
if (_state.value !is ProfileActivationState.Ready) return ProfileWorkResult.Retry
retryReleases()
if (registry.refresh().available(id) == null) return ProfileWorkResult.Skipped
val target = workLeases[id] ?: WorkLease(if (active.id == id) active else checkedOpen(id))
.also { workLeases[id] = it }
target.references++
target
}
return try {
lease.session.runBackgroundWork(action)
} catch (cancelled: CancellationException) {
currentCoroutineContext().ensureActive()
if (lease.session.status.value == ProfileSessionStatus.Open) throw cancelled
ProfileWorkResult.Skipped
} finally {
withContext(NonCancellable) {
mutex.withLock {
lease.references--
if (lease.references == 0) {
if (workLeases[id] === lease) workLeases.remove(id)
if (lease.session !== active) release(lease.session)
}
}
}
}
}
suspend fun switchTo(id: ProfileId) = mutex.withLock {
currentCoroutineContext().ensureActive()
requireNotNull(registry.refresh().available(id)) { "Profile is unavailable" }
retryReleases()
if (_state.value is ProfileActivationState.Ready && active.id == id) return@withLock
switchLocked(id)
}
suspend fun recover() = mutex.withLock {
currentCoroutineContext().ensureActive()
withContext(NonCancellable) {
if (_state.value is ProfileActivationState.Ready) {
retryReleases()
} else {
try {
detach(active)
release(active)
retryReleases()
publishFresh(active.id)
} catch (error: Exception) {
failRecovery(active.id, error, "Profile recovery failed")
throw error
}
}
}
}
suspend fun create(name: String): ProfileId = mutex.withLock {
currentCoroutineContext().ensureActive()
requireReady()
retryReleases()
val id = ProfileId.random()
registry.beginCreate(name, id)
// Provisioning stays visible in metadata if a database/storage commit fails. Retry resumes
// the same ID; abandoning it requires the normal staged deletion path.
provisionLocked(id)
id
}
suspend fun resumeProvisioning(id: ProfileId) = mutex.withLock {
currentCoroutineContext().ensureActive()
requireReady()
retryReleases()
require(registry.refresh().profiles.any { it.id == id && it.status == ProfileStatus.Provisioning }) {
"Profile is not provisioning"
}
provisionLocked(id)
}
suspend fun rename(id: ProfileId, name: String) = mutex.withLock {
currentCoroutineContext().ensureActive()
registry.rename(id, name)
}
suspend fun delete(id: ProfileId) = mutex.withLock {
currentCoroutineContext().ensureActive()
require(id != ProfileId.Default) { "Default cannot be deleted" }
val snapshot = registry.refresh()
if (id in snapshot.retiredIds) return@withLock
require(snapshot.profiles.any { it.id == id }) { "Unknown profile" }
retryReleases()
if (active.id == id) switchLocked(ProfileId.Default)
requireReady()
// Keep the tombstone stage until both scoped scheduler/storage cleanup and its durable
// metadata commit complete. The mutex excludes backups and background storage leases.
registry.beginDelete(id)
withContext(NonCancellable) {
workLeases[id]?.session?.let { release(it) }
deleteStorage(id)
registry.finishDelete(id)
}
}
/** Pins an explicit target through the entire operation; metadata in a backup never selects it. */
suspend fun <T> withProfile(id: ProfileId, action: suspend (ProfileSession) -> T): T = mutex.withLock {
currentCoroutineContext().ensureActive()
requireReady()
retryReleases()
requireNotNull(registry.refresh().available(id)) { "Profile is unavailable" }
if (active.id == id) {
active.runLeasedWork(action)
} else {
val background = workLeases[id]?.session
val session = background ?: checkedOpen(id)
try { session.runLeasedWork(action) }
finally { if (background == null) withContext(NonCancellable) { release(session) } }
}
}
/** Data replacement runs after final UI progress and background finalizers, using a fresh DB owner. */
suspend fun <T> replaceProfileData(id: ProfileId, action: suspend (ProfileSession) -> T): T = mutex.withLock {
currentCoroutineContext().ensureActive()
requireReady()
retryReleases()
requireNotNull(registry.refresh().available(id)) { "Profile is unavailable" }
withContext(NonCancellable) {
workLeases[id]?.session?.takeIf { it !== active }?.let { release(it) }
val foreground = active.id == id
if (foreground) {
_state.update { ProfileActivationState.Switching(id, id) }
try { detach(active); release(active) }
catch (error: Exception) {
failRecovery(id, error, "Profile shutdown failed")
throw error
}
}
try {
val target = checkedOpen(id)
val result = try { target.runLeasedWork(action) } finally { release(target) }
if (foreground) publishFresh(id)
result
} catch (error: Exception) {
if (foreground) {
try { retryReleases(); publishFresh(id, error.message ?: "Restore failed") }
catch (recovery: Exception) { failRecovery(id, recovery, "Profile recovery failed") }
}
throw error
}
}
}
private suspend fun <T> ProfileSession.runLeasedWork(action: suspend (ProfileSession) -> T): T =
when (val result = runBackgroundWork(action)) {
is ProfileWorkResult.Completed -> result.value
ProfileWorkResult.Skipped -> error("Profile retired before the operation started")
ProfileWorkResult.Retry -> error("Profile operation requires retry")
}
private suspend fun provisionLocked(id: ProfileId) {
val session = checkedOpen(id)
try { session.database } finally { withContext(NonCancellable) { release(session) } }
registry.markReady(id)
}
private suspend fun switchLocked(id: ProfileId) = withContext(NonCancellable) {
val previous = active.id
// Reserve and validate only storage before detaching. A foreign owner or broken database
// must not take down the current foreground session. Native services wait until retirement.
workLeases[id]?.session?.let { release(it) }
val candidate = checkedOpen(id)
try { candidate.database }
catch (error: Exception) {
releaseSuppressing(candidate, error)
throw error
}
_state.update { ProfileActivationState.Switching(previous, id) }
try {
detach(active)
release(active)
} catch (error: Exception) {
releaseSuppressing(candidate, error)
failRecovery(previous, error, "Profile shutdown failed")
throw error
}
try {
publish(candidate)
} catch (error: Exception) {
try {
retryReleases()
publishFresh(previous, error.message ?: "Profile activation failed")
} catch (recovery: Exception) {
failRecovery(previous, recovery, "Profile recovery failed")
}
throw error
}
}
private suspend fun publishFresh(id: ProfileId, message: String? = null) = publish(checkedOpen(id), message)
private suspend fun publish(replacement: ProfileSession, message: String? = null) {
try {
prepare(replacement)
registry.recordActive(replacement.id)
} catch (error: Exception) {
releaseSuppressing(replacement, error)
throw error
}
active = replacement
_state.update { ProfileActivationState.Ready(replacement, message) }
}
private suspend fun checkedOpen(id: ProfileId): ProfileSession {
val session = openSession(id)
if (session.id != id || session.status.value != ProfileSessionStatus.Open) {
withContext(NonCancellable) { release(session) }
error("Session factory returned a different or retired profile")
}
return session
}
private suspend fun release(session: ProfileSession) {
if (session !in pendingRetirements) pendingRetirements.add(session)
session.close()
pendingRetirements.remove(session)
workLeases.entries.removeAll { it.value.session === session }
}
/** Releases [session] during [error] handling; a cleanup failure is attached to [error]. */
private suspend fun releaseSuppressing(session: ProfileSession, error: Exception) {
try { release(session) } catch (cleanup: Exception) { error.addSuppressed(cleanup) }
}
private fun failRecovery(id: ProfileId, error: Exception, fallback: String) {
_state.update { ProfileActivationState.RecoveryRequired(id, error.message ?: fallback) }
}
private suspend fun retryReleases() = withContext(NonCancellable) {
pendingRetirements.toList().forEach { release(it) }
}
private fun requireReady() {
check(_state.value is ProfileActivationState.Ready) { "Recover the retiring profile before continuing" }
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines deleteProfileStorage, deletePlatformProfileStorage.
The source describes its contract as:
Call only under the coordinator's deletion lease, after all sessions/work for this ID retire.
package eu.friedcutlet.yokan.app.profiles
import eu.friedcutlet.yokan.domain.ProfileId
/** Call only under the coordinator's deletion lease, after all sessions/work for this ID retire. */
internal suspend fun deleteProfileStorage(id: ProfileId, exportedBackups: List<String> = emptyList()) {
require(id != ProfileId.Default) { "Default storage cannot be deleted" }
val lease = acquireProfileStorageLease(id)
try { deletePlatformProfileStorage(id, exportedBackups) }
finally { kotlinx.coroutines.withContext(kotlinx.coroutines.NonCancellable) { lease.close() } }
}
/** Uses app-owned roots, never settings paths or external-folder grants. */
internal expect suspend fun deletePlatformProfileStorage(id: ProfileId, exportedBackups: List<String>)
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfileBackupScreen.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ProfileBackupControls, ProfileBackupScreen.
Cross-chapter imports used by this file: SettingsScaffold. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.settings.profiles
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.backup.*
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*
internal data class ProfileBackupControls(
val state: ProfileBackupsState,
val select: (ProfileId) -> Unit,
val password: (String) -> Unit,
val format: (BackupFormat) -> Unit,
val mode: (RestoreMode) -> Unit,
val export: () -> Unit,
val chooseFile: () -> Unit,
val unlock: () -> Unit,
val apply: () -> Unit,
val snapshots: () -> Unit,
val rollback: (ProfileId, SafetySnapshot) -> Unit,
)
internal val LocalProfileBackupControls = staticCompositionLocalOf<ProfileBackupControls> { error("Backup controls unavailable") }
@Composable
internal fun ProfileBackupScreen(export: Boolean, onBack: () -> Unit) {
val controls = LocalProfileBackupControls.current
val state = controls.state
val targetName = state.profiles.firstOrNull { it.id == state.target }?.name.orEmpty()
SettingsScaffold(stringResource(if (export) Res.string.profiles_backup_export else Res.string.profiles_backup_restore), onBack) {
if (state.profiles.size > 1) item(key = "backup-profile-selector") {
Column(Modifier.padding(16.dp)) {
Text(stringResource(if (export) Res.string.profiles_backup_source else Res.string.profiles_backup_target), style = MaterialTheme.typography.titleMedium)
state.profiles.forEach { profile -> key(profile.id.value) {
Row { RadioButton(profile.id == state.target, onClick = { controls.select(profile.id) }, enabled = !state.busy); TextButton(onClick = { controls.select(profile.id) }, enabled = !state.busy) { Text(profile.name) } }
} }
}
}
item(key = "backup-guidance") { Text(stringResource(Res.string.profiles_backup_guidance), modifier = Modifier.padding(16.dp)) }
item(key = "backup-password") { OutlinedTextField(state.password, controls.password, label = { Text(stringResource(Res.string.profiles_backup_password)) }, visualTransformation = PasswordVisualTransformation(), singleLine = true, enabled = !state.busy, modifier = Modifier.fillMaxWidth().padding(16.dp)) }
if (export) {
item(key = "backup-formats") { Row(Modifier.padding(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
BackupFormat.entries.forEach { format -> FilterChip(state.format == format, onClick = { controls.format(format) }, label = { Text(format.name) }, enabled = !state.busy && (format == BackupFormat.Yokan || state.password.isEmpty())) }
} }
item(key = "backup-export") { Button(onClick = controls.export, enabled = state.available && !state.busy && (state.format == BackupFormat.Yokan || state.password.isEmpty()), modifier = Modifier.padding(16.dp)) { Text(stringResource(Res.string.profiles_backup_export_named, targetName)) } }
} else {
item(key = "backup-open") { Row(Modifier.padding(16.dp)) {
TextButton(onClick = controls.chooseFile, enabled = state.available && !state.busy) { Text(stringResource(Res.string.profiles_backup_choose)) }
TextButton(onClick = controls.unlock, enabled = state.available && !state.busy && state.password.isNotEmpty()) { Text(stringResource(Res.string.profiles_backup_unlock)) }
} }
state.plan?.let { target ->
item(key = "backup-preview") { Column(Modifier.padding(16.dp)) {
Text(stringResource(Res.string.profiles_backup_preview, targetName, target.plan.preview.itemCount), style = MaterialTheme.typography.titleMedium)
target.plan.preview.warnings.forEach { Text(it, style = MaterialTheme.typography.bodySmall) }
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { RestoreMode.entries.forEach { mode -> FilterChip(state.mode == mode, onClick = { controls.mode(mode) }, label = { Text(mode.name) }, enabled = !state.busy) } }
Button(onClick = controls.apply, enabled = state.available && !state.busy) { Text(stringResource(Res.string.profiles_backup_apply)) }
} }
}
item(key = "backup-snapshots-refresh") { TextButton(onClick = controls.snapshots, enabled = state.available && !state.busy) { Text(stringResource(Res.string.profiles_backup_snapshots)) } }
items(state.snapshots, key = { it.backupPath }, contentType = { "snapshot" }) { snapshot ->
Column(Modifier.padding(16.dp)) {
Text(snapshot.description)
TextButton(onClick = { controls.rollback(state.target, snapshot) }, enabled = !state.busy) { Text(stringResource(Res.string.profiles_backup_rollback)) }
}
}
}
state.error?.let { error -> item(key = "backup-error") { Text(error, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp)) } }
state.message?.let { message -> item(key = "backup-result") { Text(message, modifier = Modifier.padding(16.dp)) } }
if (state.busy) item(key = "backup-busy") { LinearProgressIndicator(Modifier.fillMaxWidth()) }
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfileBackupsViewModel.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ProfileBackupsState, ProfileBackupsViewModel, select, password, format, mode, refreshSnapshots, export, chooseFile, unlock and 4 further declarations.
The source describes its contract as:
Lives in the device store, so an active-target restore survives navigator retirement.
Cross-chapter imports used by this file: pickFile. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.settings.profiles
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.app.profiles.*
import eu.friedcutlet.yokan.services.backup.*
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.files.pickFile
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jetbrains.compose.resources.getString
import yokan.composeapp.generated.resources.*
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.app.profiles.ProfileBackupOperations
import eu.friedcutlet.yokan.app.profiles.TargetedBackupPlan
internal data class ProfileBackupsState(
val profiles: List<ProfileRecord> = emptyList(),
val target: ProfileId = ProfileId.Default,
val available: Boolean = false,
val busy: Boolean = false,
val password: String = "",
val format: BackupFormat = BackupFormat.Yokan,
val mode: RestoreMode = RestoreMode.Merge,
val plan: TargetedBackupPlan? = null,
val snapshots: List<SafetySnapshot> = emptyList(),
val message: String? = null,
val error: String? = null,
)
/** Lives in the device store, so an active-target restore survives navigator retirement. */
internal class ProfileBackupsViewModel(
private val registry: ProfileRegistry,
private val operations: ProfileBackupOperations,
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
private val _state = MutableStateFlow(ProfileBackupsState())
val state = _state.asStateFlow()
private var input: ByteArray? = null
init {
viewModelScope.launch {
registry.state.collect { value ->
val snapshot = (value as? ProfileRegistryState.Ready)?.snapshot
_state.update { current ->
val records = snapshot?.profiles?.filter { it.status == ProfileStatus.Ready }.orEmpty()
val target = if (records.any { it.id == current.target }) current.target else ProfileId.Default
if (target != current.target) input = null
current.copy(profiles = records, available = snapshot != null, target = target,
plan = current.plan.takeIf { target == current.target }, snapshots = current.snapshots.takeIf { target == current.target }.orEmpty())
}
}
}
}
fun select(id: ProfileId) {
if (_state.value.busy || _state.value.profiles.none { it.id == id }) return
input = null
_state.update { it.copy(target = id, plan = null, snapshots = emptyList(), password = "", message = null, error = null) }
refreshSnapshots(id)
}
fun password(value: String) = _state.update { it.copy(password = value, error = null) }
fun format(value: BackupFormat) = _state.update { it.copy(format = value) }
fun mode(value: RestoreMode) = _state.update { it.copy(mode = value) }
fun refreshSnapshots(id: ProfileId = _state.value.target) = command {
val snapshots = operations.snapshots(id)
_state.update { if (it.target == id) it.copy(snapshots = snapshots) else it }
}
fun export() {
val selected = _state.value
command {
val result = operations.export(selected.target, BackupOptions(format = selected.format), selected.password.takeIf { it.isNotEmpty() })
_state.update { it.copy(message = result?.let { result -> result.path }, password = "") }
}
}
fun chooseFile() {
val id = _state.value.target
command {
val path = pickFile(listOf("tachibk", "proto", "json", "gz", "backup", "yokanbak")) ?: return@command
input = operations.read(id, path)
open(id, _state.value.password.takeIf { it.isNotEmpty() })
}
}
fun unlock() {
val selected = _state.value
command { open(selected.target, selected.password.takeIf { it.isNotEmpty() }) }
}
private suspend fun open(id: ProfileId, password: String?) {
val bytes = input ?: return
when (val opened = operations.open(id, bytes, password)) {
is BackupOpenResult.Ready -> _state.update { if (it.target == id) it.copy(plan = TargetedBackupPlan(id, opened.plan), password = "", error = null) else it }
is BackupOpenResult.Failure -> {
val message = getString(Res.string.profiles_backup_open_failed)
_state.update { it.copy(plan = null, error = message) }
}
}
}
fun apply() {
val selected = _state.value
val plan = selected.plan ?: return
command {
val result = operations.apply(plan, selected.mode)
input = null
val snapshots = operations.snapshots(plan.target)
val message = getString(Res.string.profiles_backup_restored, result.itemCount)
_state.update { it.copy(plan = null, password = "", snapshots = snapshots, message = message) }
}
}
fun rollback(id: ProfileId, snapshot: SafetySnapshot) = command {
operations.rollback(id, snapshot)
val snapshots = operations.snapshots(id)
val message = getString(Res.string.profiles_backup_rolled_back)
_state.update { if (it.target == id) it.copy(snapshots = snapshots, message = message) else it }
}
private fun command(action: suspend () -> Unit) {
if (_state.value.busy) return
_state.update { it.copy(busy = true, error = null, message = null) }
viewModelScope.launch {
try {
catchingNonCancellation { withContext(workDispatcher) { action() } }
.onFailure { error -> _state.update { it.copy(error = error.message ?: "Backup operation failed") } }
} finally { _state.update { it.copy(busy = false) } }
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfilesScreen.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ProfileControls, ProfilesScreen, ProfileQuickSwitch.
Cross-chapter imports used by this file: SettingsScaffold. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.settings.profiles
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.app.profiles.*
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*
import eu.friedcutlet.yokan.domain.ProfileId
internal data class ProfileControls(
val state: ProfilesState,
val switchTo: (ProfileId) -> Unit,
val create: () -> Unit,
val rename: (ProfileRecord) -> Unit,
val delete: (ProfileRecord) -> Unit,
val retry: (ProfileId) -> Unit,
val refresh: () -> Unit,
val nameChanged: (String) -> Unit,
val confirm: () -> Unit,
val dismiss: () -> Unit,
)
internal val LocalProfileControls = staticCompositionLocalOf<ProfileControls> { error("Profile controls unavailable") }
@Composable
internal fun ProfilesScreen(onBack: () -> Unit) {
val controls = LocalProfileControls.current
val state = controls.state
SettingsScaffold(stringResource(Res.string.profiles_title), onBack) {
item(key = "profile-guidance") { Text(stringResource(Res.string.profiles_guidance), modifier = Modifier.padding(16.dp)) }
item(key = "profile-capabilities") { Text(stringResource(Res.string.profiles_capabilities), style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding(16.dp)) }
state.error?.let { error -> item(key = "profile-error") { Text(error, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp)) } }
if (!state.available) item(key = "profile-refresh") {
TextButton(onClick = controls.refresh, enabled = !state.busy) { Text(stringResource(Res.string.profiles_retry)) }
}
items(state.registry.profiles, key = { it.id.value }, contentType = { "profile" }) { record ->
Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp)) {
Text(record.name, style = MaterialTheme.typography.titleMedium)
if (record.id == state.activeId) Text(stringResource(Res.string.profiles_active), color = MaterialTheme.colorScheme.primary)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
when (record.status) {
ProfileStatus.Ready -> {
if (record.id != state.activeId) TextButton(onClick = { controls.switchTo(record.id) }, enabled = state.available && !state.busy) { Text(stringResource(Res.string.profiles_switch)) }
if (record.id != ProfileId.Default) TextButton(onClick = { controls.rename(record) }, enabled = !state.busy) { Text(stringResource(Res.string.profiles_rename)) }
}
ProfileStatus.Provisioning -> TextButton(onClick = { controls.retry(record.id) }, enabled = !state.busy) { Text(stringResource(Res.string.profiles_retry)) }
ProfileStatus.Deleting -> Text(stringResource(Res.string.profiles_deletion_pending))
}
if (record.id != ProfileId.Default) TextButton(onClick = { controls.delete(record) }, enabled = !state.busy) { Text(stringResource(Res.string.profiles_delete)) }
}
}
}
item(key = "profile-create") { Button(onClick = controls.create, enabled = state.available && !state.busy, modifier = Modifier.padding(16.dp)) { Text(stringResource(Res.string.profiles_create)) } }
if (state.busy) item(key = "profile-busy") { LinearProgressIndicator(Modifier.fillMaxWidth()) }
}
when (val dialog = state.dialog) {
is ProfileDialog.Name -> AlertDialog(
onDismissRequest = { if (!state.busy) controls.dismiss() },
title = { Text(stringResource(if (dialog.id == null) Res.string.profiles_create else Res.string.profiles_rename)) },
text = { Column { OutlinedTextField(dialog.draft, controls.nameChanged, label = { Text(stringResource(Res.string.profiles_name)) }, singleLine = true, enabled = !state.busy); state.error?.let { Text(it, color = MaterialTheme.colorScheme.error) } } },
confirmButton = { TextButton(onClick = controls.confirm, enabled = !state.busy && dialog.draft.isNotBlank()) { Text(stringResource(Res.string.action_save)) } },
dismissButton = { TextButton(onClick = controls.dismiss, enabled = !state.busy) { Text(stringResource(Res.string.action_cancel)) } },
)
is ProfileDialog.Delete -> AlertDialog(
onDismissRequest = { if (!state.busy) controls.dismiss() },
title = { Text(stringResource(Res.string.profiles_delete_named, dialog.profile.name)) },
text = { Column { Text(stringResource(Res.string.profiles_delete_guidance)); state.error?.let { Text(it, color = MaterialTheme.colorScheme.error) } } },
confirmButton = { TextButton(onClick = controls.confirm, enabled = !state.busy) { Text(stringResource(Res.string.profiles_delete)) } },
dismissButton = { TextButton(onClick = controls.dismiss, enabled = !state.busy) { Text(stringResource(Res.string.action_cancel)) } },
)
null -> Unit
}
}
@Composable
internal fun ProfileQuickSwitch() {
val controls = LocalProfileControls.current
val state = controls.state
if (!state.registry.hasAdditionalProfiles) return
var expanded by remember { mutableStateOf(false) }
Box(Modifier.padding(horizontal = 16.dp)) {
TextButton(onClick = { expanded = true }, enabled = state.available && !state.busy) {
Text(stringResource(Res.string.profiles_current, state.registry.available(state.activeId)?.name.orEmpty()))
}
DropdownMenu(expanded, { expanded = false }) {
state.registry.profiles.filter { it.status == ProfileStatus.Ready }.forEach { record ->
key(record.id.value) { DropdownMenuItem(text = { Text(record.name) }, onClick = { expanded = false; controls.switchTo(record.id) }) }
}
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfilesViewModel.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ProfileDialog, Name, Delete, ProfilesState, ProfilesViewModel, resumeLastProfile, refresh, switchTo, recover, retryProvisioning and 7 further declarations.
The source describes its contract as:
Device-owned: activation must never run in a navigator ViewModel that it is about to retire.
package eu.friedcutlet.yokan.ui.screens.settings.profiles
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.app.profiles.*
import eu.friedcutlet.yokan.services.catchingNonCancellation
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import eu.friedcutlet.yokan.domain.ProfileId
internal sealed interface ProfileDialog {
data class Name(val id: ProfileId? = null, val draft: String = "") : ProfileDialog
data class Delete(val profile: ProfileRecord) : ProfileDialog
}
internal data class ProfilesState(
val registry: ProfileRegistrySnapshot = ProfileRegistrySnapshot(),
val activeId: ProfileId = ProfileId.Default,
val available: Boolean = false,
val busy: Boolean = false,
val error: String? = null,
val dialog: ProfileDialog? = null,
)
/** Device-owned: activation must never run in a navigator ViewModel that it is about to retire. */
internal class ProfilesViewModel(
private val registry: ProfileRegistry,
private val coordinator: ProfileCoordinator,
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
private val _state = MutableStateFlow(ProfilesState(activeId = coordinator.currentSession.id))
val state = _state.asStateFlow()
private var resumed = false
init {
viewModelScope.launch {
registry.state.collect { update -> _state.update {
when (update) {
is ProfileRegistryState.Ready -> it.copy(registry = update.snapshot, available = true)
else -> it.copy(available = false)
}
} }
}
viewModelScope.launch {
coordinator.state.collect { update ->
if (update is ProfileActivationState.Ready) _state.update {
it.copy(activeId = update.session.id, error = update.recoveryMessage ?: it.error)
}
}
}
}
fun resumeLastProfile() {
if (resumed) return
resumed = true
command {
val snapshot = registry.refresh()
if (snapshot.lastActive != coordinator.currentSession.id) coordinator.switchTo(snapshot.lastActive)
}
}
fun refresh() = command { registry.refresh() }
fun switchTo(id: ProfileId) = command { coordinator.switchTo(id) }
fun recover() = command { coordinator.recover() }
fun retryProvisioning(id: ProfileId) = command { coordinator.resumeProvisioning(id) }
fun showCreate() = _state.update { it.copy(dialog = ProfileDialog.Name(), error = null) }
fun showRename(record: ProfileRecord) = _state.update { it.copy(dialog = ProfileDialog.Name(record.id, record.name), error = null) }
fun showDelete(record: ProfileRecord) = _state.update { it.copy(dialog = ProfileDialog.Delete(record), error = null) }
fun dismissDialog() = _state.update { it.copy(dialog = null) }
fun changeName(draft: String) = _state.update {
val dialog = it.dialog as? ProfileDialog.Name ?: return@update it
it.copy(dialog = dialog.copy(draft = draft.take(80)))
}
fun confirm() {
when (val dialog = _state.value.dialog) {
is ProfileDialog.Name -> command {
if (dialog.id == null) coordinator.create(dialog.draft) else coordinator.rename(dialog.id, dialog.draft)
dismissDialog()
}
is ProfileDialog.Delete -> command { coordinator.delete(dialog.profile.id); dismissDialog() }
null -> Unit
}
}
private fun command(action: suspend () -> Unit) {
if (_state.value.busy) return
_state.update { it.copy(busy = true, error = null) }
viewModelScope.launch {
try {
catchingNonCancellation { withContext(workDispatcher) { action() } }
.onFailure { error -> _state.update { it.copy(error = error.message ?: "Profile operation failed") } }
} finally { _state.update { it.copy(busy = false) } }
}
}
}
Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.android.kt
Create this path in your reconstruction project. Source set: androidMain. Exact file download.
The implementation below defines deletePlatformProfileStorage.
Cross-chapter imports used by this file: AndroidAppContext. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app.profiles
import eu.friedcutlet.yokan.AndroidAppContext
import java.io.File
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import eu.friedcutlet.yokan.domain.ProfileId
internal actual suspend fun deletePlatformProfileStorage(id: ProfileId, exportedBackups: List<String>) = withContext(Dispatchers.IO) {
val context = checkNotNull(AndroidAppContext.appContext) { "Android context unavailable" }
deleteOwnedProfileDirectory(context.filesDir, id, exportedBackups)
deleteOwnedProfileDirectory(context.cacheDir, id, exportedBackups)
deleteOwnedProfileDirectory(checkNotNull(context.getDatabasePath("yokan-room.db").parentFile), id, exportedBackups)
// Mihon bridge source preferences live in prefixed shared_prefs files (see mihonBridgePreferencesPrefix).
val prefix = eu.friedcutlet.yokan.services.extensions.mihon.mihonBridgePreferencesPrefix(id)
File(context.dataDir, "shared_prefs").listFiles().orEmpty()
.filter { it.name.startsWith(prefix) && it.name.endsWith(".xml") }
.forEach { context.deleteSharedPreferences(it.name.removeSuffix(".xml")) }
eu.friedcutlet.yokan.services.webview.deleteProfileWebViewStorage(id)
}
Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.android.kt
Create this path in your reconstruction project. Source set: androidMain. Exact file download.
The implementation below defines acquireProfileStorageLease.
Cross-chapter imports used by this file: AndroidAppContext. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app.profiles
import eu.friedcutlet.yokan.AndroidAppContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import eu.friedcutlet.yokan.domain.ProfileId
internal actual suspend fun acquireProfileStorageLease(id: ProfileId): ProfileStorageLease =
if (id == ProfileId.Default) ProfileStorageLease {} else withContext(Dispatchers.IO) {
acquireFileProfileLease(checkNotNull(AndroidAppContext.appContext).filesDir, id)
}
Write composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.desktop.kt
Create this path in your reconstruction project. Source set: desktopMain. Exact file download.
The implementation below defines deletePlatformProfileStorage.
package eu.friedcutlet.yokan.app.profiles
import eu.friedcutlet.yokan.services.files.desktopDataRoot
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import eu.friedcutlet.yokan.domain.ProfileId
internal actual suspend fun deletePlatformProfileStorage(id: ProfileId, exportedBackups: List<String>) = withContext(Dispatchers.IO) {
deleteOwnedProfileDirectory(desktopDataRoot, id, exportedBackups)
}
Write composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.desktop.kt
Create this path in your reconstruction project. Source set: desktopMain. Exact file download.
The implementation below defines acquireProfileStorageLease.
package eu.friedcutlet.yokan.app.profiles
import eu.friedcutlet.yokan.services.files.desktopDataRoot
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import eu.friedcutlet.yokan.domain.ProfileId
internal actual suspend fun acquireProfileStorageLease(id: ProfileId): ProfileStorageLease =
if (id == ProfileId.Default) ProfileStorageLease {} else withContext(Dispatchers.IO) {
acquireFileProfileLease(desktopDataRoot, id)
}
Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/IosBackgroundTaskRegistration.kt
Create this path in your reconstruction project. Source set: iosMain. Exact file download.
The implementation below defines IosBackgroundTaskRegistration, register.
The source describes its contract as:
Registered from UIApplicationDelegate before launch returns.
Cross-chapter imports used by this file: registerIosBackgroundTasks. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app
import eu.friedcutlet.yokan.services.scheduling.registerIosBackgroundTasks
/** Registered from UIApplicationDelegate before launch returns. */
object IosBackgroundTaskRegistration {
fun register() {
registerIosBackgroundTasks { owner, task ->
YokanRuntime.runBackgroundTask(owner.value, task = task)
}
}
}
Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.ios.kt
Create this path in your reconstruction project. Source set: iosMain. Exact file download.
The implementation below defines deletePlatformProfileStorage, remove.
package eu.friedcutlet.yokan.app.profiles
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import platform.Foundation.*
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.domain.ProfileStorageNamespace
@OptIn(ExperimentalForeignApi::class)
internal actual suspend fun deletePlatformProfileStorage(id: ProfileId, exportedBackups: List<String>) = withContext(Dispatchers.Default) {
require(id != ProfileId.Default)
val manager = NSFileManager.defaultManager
val exports = exportedBackups.mapNotNull { NSURL.fileURLWithPath(it.removePrefix("file://")).standardizedURL?.path }
fun remove(path: String) {
val keep = exports.any { it == path || it.startsWith("$path/") }
val attributes = manager.attributesOfItemAtPath(path, null) ?: return
val directory = attributes[NSFileType] == NSFileTypeDirectory
if (keep && directory) {
val children = checkNotNull(manager.contentsOfDirectoryAtPath(path, null)) { "Profile directory unreadable" }
children.forEach { remove("$path/$it") }
} else if (!keep) {
check(manager.removeItemAtPath(path, null)) { "Could not remove profile-owned data" }
}
}
listOf(NSDocumentDirectory, NSCachesDirectory).forEach { directory ->
val base = checkNotNull(NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, true).firstOrNull()?.toString())
remove(ProfileStorageNamespace(id).ownedRoot(base))
}
eu.friedcutlet.yokan.services.webview.deleteProfileDataStore(id)
}
Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.ios.kt
Create this path in your reconstruction project. Source set: iosMain. Exact file download.
The implementation below defines acquireProfileStorageLease.
Cross-chapter imports used by this file: PlatformLock. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app.profiles
import eu.friedcutlet.yokan.util.PlatformLock
import eu.friedcutlet.yokan.domain.ProfileId
// Foreground scenes and BGTasks share the app process. App extensions cannot mutate profile data.
private val reservationLock = PlatformLock()
private val reservations = mutableSetOf<ProfileId>()
internal actual suspend fun acquireProfileStorageLease(id: ProfileId): ProfileStorageLease {
if (id == ProfileId.Default) return ProfileStorageLease {}
reservationLock.withLock { check(reservations.add(id)) { "Profile is already open" } }
return ProfileStorageLease { reservationLock.withLock { reservations.remove(id) } }
}
Write composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/profiles/FileProfileRegistryPersistence.kt
Create this path in your reconstruction project. Source set: jvmCommonMain. Exact file download.
The implementation below defines FileProfileRegistryPersistence, read, compareAndSet, readLocked, locked.
The source describes its contract as:
One lock file remains stable while registry.json is atomically replaced.
package eu.friedcutlet.yokan.app.profiles
import java.io.File
import java.io.RandomAccessFile
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.util.concurrent.ConcurrentHashMap
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/** One lock file remains stable while registry.json is atomically replaced. */
internal class FileProfileRegistryPersistence(private val file: File) : ProfileRegistryPersistence {
private val monitor = locks.computeIfAbsent(file.canonicalPath) { Any() }
override suspend fun read(): String? = withContext(Dispatchers.IO) { locked { readLocked() } }
override suspend fun compareAndSet(expected: String?, replacement: String): Boolean = withContext(Dispatchers.IO) {
require(replacement.encodeToByteArray().size <= MaxProfileRegistryBytes)
locked {
if (readLocked() != expected) return@locked false
val staged = File.createTempFile("registry-", ".tmp", file.parentFile)
try {
staged.outputStream().use { output -> output.write(replacement.encodeToByteArray()); output.fd.sync() }
// Never fall back to deleting the live file or a non-atomic overwrite.
Files.move(staged.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
true
} finally { staged.delete() }
}
}
private fun readLocked(): String? {
if (!file.exists()) return null
check(file.isFile && file.length() <= MaxProfileRegistryBytes) { "Profile registry cannot be read safely" }
return file.readBytes().decodeToString(throwOnInvalidSequence = true)
}
private fun <T> locked(block: () -> T): T = synchronized(monitor) {
val parent = requireNotNull(file.parentFile)
check(parent.isDirectory || parent.mkdirs()) { "Profile registry directory unavailable" }
RandomAccessFile(File(parent, "registry.lock"), "rw").use { lockFile ->
lockFile.channel.lock().use { block() }
}
}
private companion object { val locks = ConcurrentHashMap<String, Any>() }
}
Write composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.jvm.kt
Create this path in your reconstruction project. Source set: jvmCommonMain. Exact file download.
The implementation below defines deleteOwnedProfileDirectory, preserved, visitFile, postVisitDirectory.
The source describes its contract as:
Do not follow symlinks, including a replaced profile root pointing at a user-owned folder.
package eu.friedcutlet.yokan.app.profiles
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.FileVisitResult
import java.nio.file.attribute.BasicFileAttributes
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.domain.ProfileStorageNamespace
/** Do not follow symlinks, including a replaced profile root pointing at a user-owned folder. */
internal fun deleteOwnedProfileDirectory(base: File, id: ProfileId, exportedBackups: List<String>) {
require(id != ProfileId.Default)
val root = File(base, checkNotNull(ProfileStorageNamespace(id).relativeRoot)).toPath().toAbsolutePath().normalize()
val exports = exportedBackups.mapNotNull { runCatching { java.nio.file.Paths.get(it.removePrefix("file://")).toAbsolutePath().normalize() }.getOrNull() }
.filter { it.startsWith(root) }.toSet()
fun preserved(path: Path) = exports.any { it == path || it.startsWith(path) }
if (!Files.exists(root, java.nio.file.LinkOption.NOFOLLOW_LINKS)) return
Files.walkFileTree(root, object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
if (!preserved(file)) Files.deleteIfExists(file)
return FileVisitResult.CONTINUE
}
override fun postVisitDirectory(dir: Path, error: java.io.IOException?): FileVisitResult {
if (error != null) throw error
if (!preserved(dir)) Files.deleteIfExists(dir)
return FileVisitResult.CONTINUE
}
})
}
Write composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.jvm.kt
Create this path in your reconstruction project. Source set: jvmCommonMain. Exact file download.
The implementation below defines acquireFileProfileLease.
package eu.friedcutlet.yokan.app.profiles
import java.io.File
import java.io.RandomAccessFile
import java.nio.channels.OverlappingFileLockException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import eu.friedcutlet.yokan.domain.ProfileId
internal fun acquireFileProfileLease(root: File, id: ProfileId): ProfileStorageLease {
require(id != ProfileId.Default)
val locks = File(root, "profiles/locks")
check(locks.isDirectory || locks.mkdirs()) { "Profile lock directory unavailable" }
val file = RandomAccessFile(File(locks, "${id.value}.lock"), "rw")
val lock = try { file.channel.tryLock() }
catch (_: OverlappingFileLockException) { null }
catch (error: Throwable) { file.close(); throw error }
if (lock == null) { file.close(); error("Profile is open in another window or process") }
// Never unlink the lock file: another process may already have opened the same inode.
return ProfileStorageLease {
withContext(Dispatchers.IO) { try { if (lock.isValid) lock.release() } finally { file.close() } }
}
}
Write composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.wasm.kt
Create this path in your reconstruction project. Source set: wasmJsMain. Exact file download.
The implementation below defines deletePlatformProfileStorage, removeBrowserProfile.
@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)
package eu.friedcutlet.yokan.app.profiles
import kotlinx.browser.localStorage
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.withContext
import kotlinx.coroutines.await
import kotlin.js.JsAny
import kotlin.js.Promise
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.domain.ProfileStorageNamespace
internal actual suspend fun deletePlatformProfileStorage(id: ProfileId, exportedBackups: List<String>) {
require(id != ProfileId.Default)
val namespace = ProfileStorageNamespace(id)
withContext(NonCancellable) { removeBrowserProfile(namespace.ownedRoot("/yokan")).await<JsAny?>() }
localStorage.removeItem(namespace.browserSnapshotKey)
val prefix = "yokan-backup-file:${namespace.ownedRoot("/yokan")}/"
val keys = (0 until localStorage.length).mapNotNull(localStorage::key)
keys.filter { it.startsWith(prefix) && it.removePrefix("yokan-backup-file:") !in exportedBackups }
.forEach(localStorage::removeItem)
}
private fun removeBrowserProfile(root: String): Promise<JsAny?> = js("globalThis.yokanBrowserFiles.deleteProfile(root).then(() => null)")
Write composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.wasm.kt
Create this path in your reconstruction project. Source set: wasmJsMain. Exact file download.
The implementation below defines acquireProfileStorageLease, reserveProfile, releaseProfile.
@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)
package eu.friedcutlet.yokan.app.profiles
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.await
import kotlinx.coroutines.withContext
import kotlin.js.JsAny
import kotlin.js.Promise
import eu.friedcutlet.yokan.domain.ProfileId
internal actual suspend fun acquireProfileStorageLease(id: ProfileId): ProfileStorageLease {
if (id == ProfileId.Default) return ProfileStorageLease {}
var acquired: JsAny? = null
try {
withContext(NonCancellable) { acquired = reserveProfile(id.value).await<JsAny>() }
val handle = checkNotNull(acquired)
return ProfileStorageLease { withContext(NonCancellable) { releaseProfile(handle).await<JsAny?>() } }
} catch (error: Throwable) {
acquired?.let { handle -> withContext(NonCancellable) { releaseProfile(handle).await<JsAny?>() } }
throw error
}
}
private fun reserveProfile(id: String): Promise<JsAny> = js(
"""new Promise((resolve, reject) => {
if (!navigator.locks || !navigator.locks.request) {
reject(new Error('Profile storage requires Web Locks')); return;
}
const handle = { release: null, done: null };
handle.done = navigator.locks.request('yokan-profile-storage:' + id, {ifAvailable: true}, lock => {
if (!lock) throw new Error('Profile is open in another tab');
return new Promise(release => { handle.release = release; resolve(handle); });
});
handle.done.catch(reject);
})""",
)
private fun releaseProfile(handle: JsAny): Promise<JsAny?> = js("(handle.release(), handle.done)")
Check your understanding
Force activation to fail after a lease is acquired. Verify lease release and recovery state, then retry without republishing the retired session. [chapter-content-end]: #
Step 5: bind every delayed operation to its owner
Background requests carry stable profile IDs. Only missing owner fields on explicitly allowed legacy requests adopt Default; malformed explicit owner data never does. Download notification actions additionally carry a live session token so stale actions cannot control a replacement session. Cookies, OAuth attempts, image requests, player surfaces, speech, WebViews, notifications, sync and Together need their own admission/lifetime wrappers.
Follow the code
Background and backup entry points receive an owner ID and may need an inactive work session. Reference-counted leases keep that session alive only while work is admitted. A missing owner can adopt Default only on explicitly permitted legacy paths; a malformed explicit owner is an error. Session tokens further distinguish an old notification from a newly opened session for the same stable profile.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileBackgroundWork.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileBackupOperations.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileBackgroundWork.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ProfileWorkSessions, run, ProfileBackgroundWork.
The source describes its contract as:
Checks fresh metadata before opening any database. No lookup uses lastActive or falls back from an explicit invalid/unavailable owner. Production uses the coordinator's storage lease; retired owners never recreate their data.
Cross-chapter imports used by this file: ProfileWorkResult. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app.profiles
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult
internal interface ProfileWorkSessions {
suspend fun <T> run(id: ProfileId, action: suspend (ProfileSession) -> T): ProfileWorkResult<T>
}
/**
* Checks fresh metadata before opening any database. No lookup uses lastActive or falls back from
* an explicit invalid/unavailable owner. Production uses the coordinator's storage lease; retired owners never recreate their data.
*/
internal class ProfileBackgroundWork(
private val registry: ProfileRegistry,
private val supported: (ProfileId) -> Boolean,
private val sessions: ProfileWorkSessions,
) {
suspend fun <T> run(
serializedOwner: String?,
allowLegacyDefault: Boolean = false,
action: suspend (ProfileSession) -> T,
): ProfileWorkResult<T> {
currentCoroutineContext().ensureActive()
val id = if (serializedOwner == null) {
if (!allowLegacyDefault) return ProfileWorkResult.Skipped
ProfileId.Default
} else {
try { ProfileId(serializedOwner) }
catch (_: IllegalArgumentException) { return ProfileWorkResult.Skipped }
}
val snapshot = try { registry.refresh() }
catch (error: CancellationException) { throw error }
catch (_: Exception) { return ProfileWorkResult.Retry }
currentCoroutineContext().ensureActive()
if (snapshot.available(id) == null || !supported(id)) return ProfileWorkResult.Skipped
return sessions.run(id, action)
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileBackupOperations.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines TargetedBackupPlan, ProfileBackupOperations, export, open, read, apply, snapshots, rollback, profileRestorePlan.
The source describes its contract as:
All stages carry the selected ID. Payload metadata never chooses or creates a destination.
Cross-chapter imports used by this file: DbSettings, exportFile, SafetySnapshot, BackupPlan, BackupOpenResult, RestoreMode. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app.profiles
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.services.files.exportFile
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.backup.SafetySnapshot
import eu.friedcutlet.yokan.services.backup.BackupPlan
import eu.friedcutlet.yokan.services.backup.BackupOpenResult
import eu.friedcutlet.yokan.services.backup.RestoreMode
import eu.friedcutlet.yokan.services.backup.BackupOptions
import eu.friedcutlet.yokan.services.backup.BackupResult
import eu.friedcutlet.yokan.services.backup.BackupSection
import eu.friedcutlet.yokan.services.backup.RestorePreview
internal data class TargetedBackupPlan(val target: ProfileId, val plan: BackupPlan)
/** All stages carry the selected ID. Payload metadata never chooses or creates a destination. */
internal class ProfileBackupOperations(private val registry: ProfileRegistry, private val coordinator: ProfileCoordinator) {
suspend fun export(id: ProfileId, options: BackupOptions, password: String?): BackupResult? = coordinator.withProfile(id) { owner ->
val backup = owner.backup
val exported = if (password.isNullOrEmpty()) backup.exportBackup(options) else backup.exportEncryptedBackup(options, password)
val path = exportFile(exported.bytes, exported.fileName, exported.contentType,
owner.database.settings().autoBackupLocation?.takeIf { it.isNotBlank() } ?: owner.localFiles.backupRoot)
path?.let {
registry.recordExport(id, it)
BackupResult(exported.fileName, exported.bytes.size.toLong(), exported.itemCount, it)
}
}
suspend fun open(id: ProfileId, bytes: ByteArray, password: String?): BackupOpenResult = coordinator.withProfile(id) { owner ->
when (val opened = owner.backup.openBackup(bytes, password)) {
is BackupOpenResult.Ready -> BackupOpenResult.Ready(profileRestorePlan(opened.plan, owner.database.settings()))
is BackupOpenResult.Failure -> opened
}
}
suspend fun read(id: ProfileId, path: String): ByteArray = coordinator.withProfile(id) { it.backup.readBackupFile(path) }
suspend fun apply(target: TargetedBackupPlan, mode: RestoreMode): RestorePreview = coordinator.replaceProfileData(target.target) { owner ->
// Re-read destination device fields after final progress has drained; never adopt imported grants.
val plan = profileRestorePlan(target.plan, owner.database.settings()).withMode(mode)
owner.backup.applyBackup(plan, mode)
}
suspend fun snapshots(id: ProfileId): List<SafetySnapshot> = coordinator.withProfile(id) { it.backup.listSafetySnapshots() }
suspend fun rollback(id: ProfileId, snapshot: SafetySnapshot): RestorePreview = coordinator.replaceProfileData(id) { owner ->
require(snapshot in owner.backup.listSafetySnapshots()) { "Safety snapshot belongs to another target or no longer exists" }
owner.backup.rollbackSafetySnapshot(snapshot)
}
}
/** Profile data can move; OS permissions, native paths and destination credentials stay with their owner. */
internal fun profileRestorePlan(plan: BackupPlan, current: DbSettings): BackupPlan {
val incoming = plan.snapshot
val settings = incoming.settings?.copy(
cookiesList = current.cookiesList,
sourcePreferences = current.sourcePreferences,
downloadLocation = current.downloadLocation,
autoBackupLocation = current.autoBackupLocation,
localFolders = current.localFolders,
namedLocalFolders = current.namedLocalFolders,
downloadLocalFolderName = current.downloadLocalFolderName,
jrePath = current.jrePath,
extensionServerPath = current.extensionServerPath,
androidProxyServer = current.androidProxyServer,
themeSeedImagePath = current.themeSeedImagePath,
lastTrackerLibraryLocation = current.lastTrackerLibraryLocation,
desktopLaunchAtLogin = current.desktopLaunchAtLogin,
backupEncryptionEnabled = current.backupEncryptionEnabled,
backupEncryptionPassword = current.backupEncryptionPassword,
metadataServerUrl = current.metadataServerUrl,
metadataServerToken = current.metadataServerToken,
features = current.features,
btServerAddress = current.btServerAddress,
btServerPort = current.btServerPort,
)
val sections = plan.includedSections - BackupSection.TrackPreferences
val snapshot = incoming.copy(
settings = settings,
includedSections = sections.toList(),
trackPreferences = emptyList(),
chapters = incoming.chapters.map { it.copy(archivePath = "", downloadSize = null) },
mangas = incoming.mangas.map { manga ->
if (manga.isLocalArchive) manga.copy(link = null) else manga
},
)
return BackupPlan(
preview = plan.preview.copy(warnings = (plan.preview.warnings + "Device paths, local file links and login credentials are not imported. Downloaded files require relinking.").distinct()),
snapshot = snapshot,
includedSections = sections,
resolvedPassword = null,
mode = plan.mode,
)
}
Check your understanding
Deliver a delayed request after switching profiles and after reopening its original profile. Check both stable owner identity and the live token before allowing control. [chapter-content-end]: #
Recreate the tests and verify the chapter
Recreate profile registry, coordinator, storage, ownership and retirement tests. Use ./gradlew :composeApp:desktopTest --tests "eu.friedcutlet.yokan.app.profiles.*" for the shared/JVM cases. Repeat platform storage-lease and UI teardown checks on their own targets; successful registry tests do not establish native cleanup.
These are source tests to reproduce and run in your reconstruction. Their inclusion here is not a claim that application/native/device tests were executed while writing the guide.
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileBackgroundWorkTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ProfileBackgroundWorkTest, rejected, read, compareAndSet, openingWork, run, MemoryStore, ClosingDatabase, close.
The source describes its contract as:
Routes work into whatever session [openSession] returns, checking it is the requested owner.
Read the setup, action and assertions in these cases before implementing their production paths:
alreadyExpiredCallerCannotDispatchIntoALiveSessiondelayedWorkUsesRecordedOwnerAfterRenameAndActiveProfileChangefreshRegistryRejectsUnknownProvisioningDeletingAndRetiredWithoutOpeningStoragemalformedExplicitIdsNeverBecomeDefaultAndLegacyAdoptionIsOptInunsupportedReadyOwnerIsSkippedWithoutFallingBackToDefaultunavailableRegistryRetriesWithoutOpeningOrOverwritingMetadatacancellationDuringAdmissionPropagatesRatherThanRetryingproviderCannotRouteWorkToAnotherProfilecallerExpiryCancelsAndJoinsItsWorkWhileSiblingSessionWorkSurvivesretirementJoinsBackgroundFinalProgressBeforeDatabaseCloseAndRejectsLateWorkworkFailureDoesNotRetireOwnerOrCancelSiblingJobsworkNamesPreserveDefaultAndPartitionScheduleCancellationByStableIdonlyRecoverableAdmissionAndTaskFailuresRetry
Cross-chapter imports used by this file: DbManga, InMemoryYokanDatabase, YokanDatabase, PeriodicTaskOutcome, PeriodicTaskStatus, ProfileWorkResult. Keep those contracts available as you connect this step.
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
package eu.friedcutlet.yokan.app.profiles
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.scheduling.PeriodicTaskOutcome
import eu.friedcutlet.yokan.services.scheduling.PeriodicTaskStatus
import eu.friedcutlet.yokan.services.scheduling.shouldRetry
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.cancel
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkNamespace
class ProfileBackgroundWorkTest {
@Test fun alreadyExpiredCallerCannotDispatchIntoALiveSession() = runTest {
val owner = ProfileSession(A, dispatcher = UnconfinedTestDispatcher(testScheduler))
var effects = 0
val caller = launch {
currentCoroutineContext().cancel()
assertFailsWith<CancellationException> { owner.runBackgroundWork { effects++ } }
}
caller.join()
assertEquals(0, effects); assertEquals(ProfileSessionStatus.Open, owner.status.value)
assertEquals(ProfileWorkResult.Completed("Still usable"), owner.runBackgroundWork { "Still usable" })
owner.close()
}
@Test fun delayedWorkUsesRecordedOwnerAfterRenameAndActiveProfileChange() = runTest {
val registry = ProfileRegistry(MemoryStore())
registry.beginCreate("A", A); registry.markReady(A)
registry.beginCreate("B", B); registry.markReady(B)
registry.rename(A, "Renamed A"); registry.recordActive(B)
val a = InMemoryYokanDatabase(); val b = InMemoryYokanDatabase()
val owners = mapOf(
A to ProfileSession(A, databaseFactory = { a }, dispatcher = StandardTestDispatcher(testScheduler)),
B to ProfileSession(B, databaseFactory = { b }, dispatcher = StandardTestDispatcher(testScheduler)),
)
val routing = openingWork(registry, { true }) { owners.getValue(it) }
assertEquals(ProfileWorkResult.Completed(A), routing.run(A.value) {
it.database.upsertManga(DbManga(id = 42, privateNote = "A's progress")); it.id
})
assertEquals("A's progress", a.manga(42)?.privateNote)
assertEquals(null, b.manga(42))
assertEquals(B, registry.refresh().lastActive)
owners.values.forEach { it.close() }
}
@Test fun freshRegistryRejectsUnknownProvisioningDeletingAndRetiredWithoutOpeningStorage() = runTest {
val store = MemoryStore(); val registry = ProfileRegistry(store)
var opens = 0
val routing = openingWork(registry, { true }) { opens++; error("Must not open") }
suspend fun rejected() = assertEquals(ProfileWorkResult.Skipped, routing.run(A.value) { error("Must not execute") })
rejected()
registry.beginCreate("A", A); rejected()
registry.markReady(A)
// Mutate through another instance: admission must refresh rather than trust its cached Ready state.
val other = ProfileRegistry(store)
other.beginDelete(A); rejected()
other.finishDelete(A); rejected()
assertEquals(0, opens)
assertEquals(listOf(A), registry.refresh().retiredIds)
}
@Test fun malformedExplicitIdsNeverBecomeDefaultAndLegacyAdoptionIsOptIn() = runTest {
val registry = ProfileRegistry(MemoryStore())
val owner = ProfileSession(ProfileId.Default, dispatcher = StandardTestDispatcher(testScheduler))
var opens = 0
val routing = openingWork(registry, { true }) { opens++; assertEquals(ProfileId.Default, it); owner }
for (raw in listOf("", "../default", "DEFAULT", "p_123", "default ")) {
assertEquals(ProfileWorkResult.Skipped, routing.run(raw, allowLegacyDefault = true) { error("Invalid owner") })
}
assertEquals(ProfileWorkResult.Skipped, routing.run(null) { error("No recorded owner") })
assertEquals(0, opens)
assertEquals(ProfileWorkResult.Completed(ProfileId.Default), routing.run(null, allowLegacyDefault = true) { it.id })
assertEquals(ProfileWorkResult.Completed(ProfileId.Default), routing.run("default") { it.id })
assertEquals(2, opens)
owner.close()
}
@Test fun unsupportedReadyOwnerIsSkippedWithoutFallingBackToDefault() = runTest {
val registry = ProfileRegistry(MemoryStore())
registry.beginCreate("A", A); registry.markReady(A)
val routing = openingWork(registry, { it == ProfileId.Default }) { error("Unsupported owner opened") }
assertEquals(ProfileWorkResult.Skipped, routing.run(A.value) { error("Unsupported owner executed") })
}
@Test fun unavailableRegistryRetriesWithoutOpeningOrOverwritingMetadata() = runTest {
for (raw in listOf("{broken", "{\"version\":999}")) {
val store = MemoryStore(raw)
val routing = openingWork(ProfileRegistry(store), { true }) { error("Unreadable metadata opened storage") }
assertEquals(ProfileWorkResult.Retry, routing.run("default") { error("Must not execute") })
assertEquals(raw, store.raw)
}
val store = object : ProfileRegistryPersistence {
override suspend fun read(): String? = throw IllegalStateException("Disk unavailable")
override suspend fun compareAndSet(expected: String?, replacement: String) = error("Must not write")
}
val routing = openingWork(ProfileRegistry(store), { true }) { error("Must not open") }
assertEquals(ProfileWorkResult.Retry, routing.run("default") { error("Must not execute") })
}
@Test fun cancellationDuringAdmissionPropagatesRatherThanRetrying() = runTest {
val store = object : ProfileRegistryPersistence {
override suspend fun read(): String? = throw CancellationException("Expired worker")
override suspend fun compareAndSet(expected: String?, replacement: String) = error("Must not write")
}
val routing = openingWork(ProfileRegistry(store), { true }) { error("Must not open") }
assertFailsWith<CancellationException> { routing.run("default") { error("Must not execute") } }
}
@Test fun providerCannotRouteWorkToAnotherProfile() = runTest {
val registry = ProfileRegistry(MemoryStore())
registry.beginCreate("A", A); registry.markReady(A)
val wrong = ProfileSession(ProfileId.Default, dispatcher = StandardTestDispatcher(testScheduler))
val routing = openingWork(registry, { true }) { wrong }
assertFailsWith<IllegalStateException> { routing.run(A.value) { error("Wrong profile executed") } }
wrong.close()
}
@Test fun callerExpiryCancelsAndJoinsItsWorkWhileSiblingSessionWorkSurvives() = runTest {
val owner = ProfileSession(A, dispatcher = StandardTestDispatcher(testScheduler))
val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
var finalized = false
val sibling = owner.scope.launch { awaitCancellation() }
val caller = launch {
owner.runBackgroundWork {
try { entered.complete(Unit); awaitCancellation() }
finally { withContext(NonCancellable) { release.await(); finalized = true } }
}
}
entered.await(); caller.cancel(); testScheduler.runCurrent()
assertFalse(caller.isCompleted); assertFalse(finalized); assertTrue(sibling.isActive)
release.complete(Unit); caller.join()
assertTrue(finalized); assertTrue(sibling.isActive)
assertEquals(ProfileWorkResult.Completed("Next job"), owner.runBackgroundWork { "Next job" })
owner.close()
}
@Test fun retirementJoinsBackgroundFinalProgressBeforeDatabaseCloseAndRejectsLateWork() = runTest {
val db = ClosingDatabase()
val owner = ProfileSession(A, databaseFactory = { db }, dispatcher = StandardTestDispatcher(testScheduler))
val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
val caller = async {
owner.runBackgroundWork {
val captured = it.database
try { entered.complete(Unit); awaitCancellation() }
finally { withContext(NonCancellable) { release.await(); captured.upsertManga(DbManga(id = 42, privateNote = "Final")) } }
}
}
entered.await()
val closing = launch { owner.close() }; testScheduler.runCurrent()
assertFalse(db.closed); assertFalse(closing.isCompleted)
assertEquals(ProfileWorkResult.Skipped, owner.runBackgroundWork { error("Late work") })
release.complete(Unit); closing.join()
assertFailsWith<CancellationException> { caller.await() }
assertTrue(db.closed); assertEquals("Final", db.noteAtClose)
assertEquals(ProfileWorkResult.Skipped, owner.runBackgroundWork { error("Closed work") })
}
@Test fun workFailureDoesNotRetireOwnerOrCancelSiblingJobs() = runTest {
val owner = ProfileSession(A, dispatcher = StandardTestDispatcher(testScheduler))
val sibling = owner.scope.launch { awaitCancellation() }
assertFailsWith<IllegalStateException> { owner.runBackgroundWork { error("Task failed") } }
assertTrue(sibling.isActive)
assertEquals(ProfileSessionStatus.Open, owner.status.value)
assertEquals(ProfileWorkResult.Completed(42), owner.runBackgroundWork { 42 })
sibling.cancelAndJoin(); owner.close()
}
@Test fun workNamesPreserveDefaultAndPartitionScheduleCancellationByStableId() {
for (name in listOf("yokan.metadata_refresh", "yokan.library_update", "yokan.auto_sync", "yokan.auto_backup")) {
val names = listOf(ProfileId.Default, A, B).map { ProfileWorkNamespace(it).uniqueName(name) }
assertEquals(name, names.first()); assertEquals(3, names.distinct().size)
assertEquals("$name.${A.value}", names[1])
}
}
@Test fun onlyRecoverableAdmissionAndTaskFailuresRetry() {
assertFalse((ProfileWorkResult.Skipped as ProfileWorkResult<PeriodicTaskOutcome>).shouldRetry)
assertTrue((ProfileWorkResult.Retry as ProfileWorkResult<PeriodicTaskOutcome>).shouldRetry)
assertFalse(ProfileWorkResult.Completed(PeriodicTaskOutcome(PeriodicTaskStatus.Completed, "Done")).shouldRetry)
assertTrue(ProfileWorkResult.Completed(PeriodicTaskOutcome(PeriodicTaskStatus.Failed, "Retry")).shouldRetry)
}
/** Routes work into whatever session [openSession] returns, checking it is the requested owner. */
private fun openingWork(
registry: ProfileRegistry,
supported: (ProfileId) -> Boolean,
openSession: suspend (ProfileId) -> ProfileSession,
) = ProfileBackgroundWork(registry, supported, object : ProfileWorkSessions {
override suspend fun <T> run(id: ProfileId, action: suspend (ProfileSession) -> T): ProfileWorkResult<T> {
val session = openSession(id)
check(session.id == id) { "Background work opened a different profile" }
return session.runBackgroundWork(action)
}
})
private class MemoryStore(var raw: String? = null) : ProfileRegistryPersistence {
override suspend fun read() = raw
override suspend fun compareAndSet(expected: String?, replacement: String): Boolean {
if (raw != expected) return false
raw = replacement; return true
}
}
private class ClosingDatabase(private val delegate: InMemoryYokanDatabase = InMemoryYokanDatabase()) : YokanDatabase by delegate {
var closed = false
var noteAtClose: String? = null
override suspend fun close() { noteAtClose = delegate.manga(42)?.privateNote; closed = true }
}
private companion object {
val A = ProfileId("p_" + "a".repeat(32))
val B = ProfileId("p_" + "b".repeat(32))
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileCoordinatorTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ProfileCoordinatorTest, Fixture, read, compareAndSet, session, close, ready, readyState.
Read the setup, action and assertions in these cases before implementing their production paths:
switchingValidatesStorageBeforeDetachmentAndDrainsBeforePreparationfailedActivationReopensPreviousOwnerWithoutRepublishingRetiredObjectsfailedRetirementCannotPrepareAnythingUntilSuccessfulRetrycanceledSwitchStillPublishesConsistentOwnerAfterDetachmentinactiveLeasePinsTargetUntilReleaseAndDeletionCannotRaceItdeletionOfActiveProfileSwitchesToDefaultAndPreservesDeletionStageOnFailureprovisioningFailureRetainsStableIdAndCanResumeWithoutAnotherProfileinvalidOrUnavailableTargetsNeverDetachActiveProfileswitchingCanRetireLongActiveBackgroundJobWithoutWaitingForItsLeaseMutexinactiveBackgroundWorkersShareOwnerAndDeletionJoinsBothBeforeRemovingDataactivationRetiresAlreadyRunningTargetWorkerBeforeOpeningItsForegroundDatabaseunavailableReplacementStorageKeepsCurrentOwnerLiveactiveRestoreDetachesAndRetiresForegroundBeforeReplacingDataThenPublishesFreshOwnerfailedActiveRestoreStillPublishesUsableOwnerWithMessageinactiveRestoreUsesTargetStorageWithoutDetachingForeground
Cross-chapter imports used by this file: InMemoryYokanDatabase, YokanDatabase, ProfileWorkResult. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app.profiles
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabase
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.withContext
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import kotlin.test.*
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult
class ProfileCoordinatorTest {
@Test fun switchingValidatesStorageBeforeDetachmentAndDrainsBeforePreparation() = runTest {
val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A)
val gate = CompletableDeferred<Unit>()
f.detachGate = gate
val switching = launch { f.coordinator.switchTo(A) }
testScheduler.runCurrent()
assertIs<ProfileActivationState.Switching>(f.coordinator.state.value)
assertEquals(listOf("open:${A.value}", "detach:default"), f.events)
assertEquals(ProfileId.Default, f.registry.refresh().lastActive)
gate.complete(Unit); switching.join()
assertEquals(listOf("open:${A.value}", "detach:default", "close:default", "prepare:${A.value}"), f.events)
assertEquals(A, f.readyState().session.id)
assertEquals(A, f.registry.refresh().lastActive)
f.coordinator.withProfile(A) { assertSame(f.readyState().session, it) }
f.readyState().session.close()
}
@Test fun failedActivationReopensPreviousOwnerWithoutRepublishingRetiredObjects() = runTest {
val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A); f.rejectPrepare = A
val old = f.readyState().session
assertFailsWith<IllegalStateException> { f.coordinator.switchTo(A) }
assertEquals(ProfileSessionStatus.Closed, old.status.value)
val recovered = f.readyState()
assertEquals(ProfileId.Default, recovered.session.id)
assertNotSame(old, recovered.session)
assertEquals("Prepare failed", recovered.recoveryMessage)
assertEquals(ProfileId.Default, f.registry.refresh().lastActive)
assertTrue(f.events.indexOf("close:${A.value}") < f.events.indexOf("open:default"))
recovered.session.close()
}
@Test fun failedRetirementCannotPrepareAnythingUntilSuccessfulRetry() = runTest {
val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A); f.rejectClose = ProfileId.Default
val old = f.readyState().session
assertFailsWith<IllegalStateException> { f.coordinator.switchTo(A) }
assertIs<ProfileActivationState.RecoveryRequired>(f.coordinator.state.value)
assertEquals(ProfileSessionStatus.RetirementFailed, old.status.value)
assertFalse(f.events.any { it == "prepare:${A.value}" })
assertFailsWith<IllegalStateException> { f.coordinator.withProfile(A) {} }
assertFailsWith<IllegalStateException> { f.coordinator.recover() }
assertFalse(f.events.any { it == "prepare:${A.value}" })
f.rejectClose = null; f.coordinator.recover()
assertNotSame(old, f.readyState().session)
assertEquals(ProfileId.Default, f.readyState().session.id)
f.readyState().session.close()
}
@Test fun canceledSwitchStillPublishesConsistentOwnerAfterDetachment() = runTest {
val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A)
val gate = CompletableDeferred<Unit>(); f.detachGate = gate
val switching = launch { f.coordinator.switchTo(A) }
testScheduler.runCurrent(); switching.cancel(); gate.complete(Unit); switching.join()
assertEquals(A, f.readyState().session.id)
assertEquals(A, f.registry.refresh().lastActive)
f.readyState().session.close()
}
@Test fun inactiveLeasePinsTargetUntilReleaseAndDeletionCannotRaceIt() = runTest {
val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A)
val active = f.readyState().session
val gate = CompletableDeferred<Unit>(); val entered = CompletableDeferred<Unit>()
val operation = launch { f.coordinator.withProfile(A) { target ->
assertEquals(A, target.id); target.database
entered.complete(Unit); gate.await()
} }
entered.await()
val deletion = launch { f.coordinator.delete(A) }
testScheduler.runCurrent()
assertFalse(f.events.any { it.startsWith("delete:") })
gate.complete(Unit); operation.join(); deletion.join()
assertSame(active, f.readyState().session)
assertEquals(ProfileSessionStatus.Open, active.status.value)
assertEquals(listOf(A), f.registry.refresh().retiredIds)
assertTrue(f.events.indexOf("close:${A.value}") < f.events.indexOf("delete:${A.value}"))
assertFailsWith<IllegalArgumentException> { f.coordinator.withProfile(A) {} }
active.close()
}
@Test fun deletionOfActiveProfileSwitchesToDefaultAndPreservesDeletionStageOnFailure() = runTest {
val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A); f.coordinator.switchTo(A); f.rejectDelete = true
assertFailsWith<IllegalStateException> { f.coordinator.delete(A) }
assertEquals(ProfileId.Default, f.readyState().session.id)
assertEquals(ProfileStatus.Deleting, f.registry.refresh().profiles.single { it.id == A }.status)
f.rejectDelete = false; f.coordinator.delete(A); f.coordinator.delete(A)
assertEquals(listOf(A), f.registry.refresh().retiredIds)
assertFailsWith<IllegalArgumentException> { f.coordinator.delete(ProfileId.Default) }
f.readyState().session.close()
}
@Test fun provisioningFailureRetainsStableIdAndCanResumeWithoutAnotherProfile() = runTest {
val f = Fixture(StandardTestDispatcher(testScheduler)); f.rejectNewClose = true
assertFailsWith<IllegalStateException> { f.coordinator.create("Books") }
val staged = f.registry.refresh().profiles.single { it.id != ProfileId.Default }
assertEquals(ProfileStatus.Provisioning, staged.status)
f.rejectNewClose = false; f.coordinator.resumeProvisioning(staged.id)
assertEquals(2, f.registry.refresh().profiles.size)
assertEquals(ProfileStatus.Ready, f.registry.refresh().available(staged.id)?.status)
f.coordinator.rename(staged.id, "Renamed")
assertEquals("Renamed", f.registry.refresh().available(staged.id)?.name)
f.readyState().session.close()
}
@Test fun invalidOrUnavailableTargetsNeverDetachActiveProfile() = runTest {
val f = Fixture(StandardTestDispatcher(testScheduler))
assertFailsWith<IllegalArgumentException> { f.coordinator.switchTo(A) }
assertFailsWith<IllegalArgumentException> { f.coordinator.withProfile(A) {} }
assertTrue(f.events.isEmpty())
f.readyState().session.close()
}
@Test fun switchingCanRetireLongActiveBackgroundJobWithoutWaitingForItsLeaseMutex() = runTest {
val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A)
val started = CompletableDeferred<Unit>(); val finalizing = CompletableDeferred<Unit>(); val finish = CompletableDeferred<Unit>()
var result: ProfileWorkResult<Unit>? = null
val worker = launch { result = f.coordinator.run(ProfileId.Default) {
try { started.complete(Unit); awaitCancellation() }
finally { withContext(NonCancellable) { finalizing.complete(Unit); finish.await() } }
} }
started.await()
val switching = launch { f.coordinator.switchTo(A) }
finalizing.await()
assertFalse(f.events.any { it == "prepare:${A.value}" })
finish.complete(Unit); switching.join(); worker.join()
assertIs<ProfileWorkResult.Skipped>(result)
assertEquals(A, f.readyState().session.id)
f.readyState().session.close()
}
@Test fun inactiveBackgroundWorkersShareOwnerAndDeletionJoinsBothBeforeRemovingData() = runTest {
val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A)
val started = CompletableDeferred<Unit>(); val secondStarted = CompletableDeferred<Unit>()
var firstOwner: ProfileSession? = null; var secondOwner: ProfileSession? = null
val first = launch { f.coordinator.run(A) { firstOwner = it; started.complete(Unit); awaitCancellation() } }
started.await()
val second = launch { f.coordinator.run(A) { secondOwner = it; secondStarted.complete(Unit); awaitCancellation() } }
secondStarted.await()
assertSame(firstOwner, secondOwner)
f.coordinator.delete(A); first.join(); second.join()
assertEquals(ProfileSessionStatus.Closed, firstOwner?.status?.value)
assertEquals(1, f.events.count { it == "open:${A.value}" })
assertTrue(f.events.indexOf("close:${A.value}") < f.events.indexOf("delete:${A.value}"))
assertIs<ProfileWorkResult.Skipped>(f.coordinator.run(A) { error("Deleted storage reopened") })
f.readyState().session.close()
}
@Test fun activationRetiresAlreadyRunningTargetWorkerBeforeOpeningItsForegroundDatabase() = runTest {
val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A)
val started = CompletableDeferred<Unit>(); var workerOwner: ProfileSession? = null
val worker = launch { f.coordinator.run(A) { workerOwner = it; started.complete(Unit); awaitCancellation() } }
started.await()
f.coordinator.switchTo(A); worker.join()
assertNotSame(workerOwner, f.readyState().session)
assertEquals(ProfileSessionStatus.Closed, workerOwner?.status?.value)
val targetEvents = f.events.filter { it.endsWith(A.value) }
assertEquals(listOf("open:${A.value}", "close:${A.value}", "open:${A.value}", "prepare:${A.value}"), targetEvents)
f.readyState().session.close()
}
@Test fun unavailableReplacementStorageKeepsCurrentOwnerLive() = runTest {
val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A); f.rejectOpen = A
val old = f.readyState().session
assertFailsWith<IllegalStateException> { f.coordinator.switchTo(A) }
assertSame(old, f.readyState().session)
assertEquals(ProfileSessionStatus.Open, old.status.value)
assertEquals(listOf("open:${A.value}"), f.events)
assertEquals(ProfileId.Default, f.registry.refresh().lastActive)
old.close()
}
@Test fun activeRestoreDetachesAndRetiresForegroundBeforeReplacingDataThenPublishesFreshOwner() = runTest {
val f = Fixture(StandardTestDispatcher(testScheduler))
val old = f.readyState().session
var restoreOwner: ProfileSession? = null
f.coordinator.replaceProfileData(ProfileId.Default) { restoreOwner = it; f.events.add("restore") }
assertEquals(listOf("detach:default", "close:default", "open:default", "restore", "close:default", "open:default", "prepare:default"), f.events)
assertEquals(ProfileSessionStatus.Closed, old.status.value)
assertEquals(ProfileSessionStatus.Closed, restoreOwner?.status?.value)
val fresh = f.readyState().session
assertNotSame(old, fresh); assertNotSame(restoreOwner, fresh)
assertNull(f.readyState().recoveryMessage)
fresh.close()
}
@Test fun failedActiveRestoreStillPublishesUsableOwnerWithMessage() = runTest {
val f = Fixture(StandardTestDispatcher(testScheduler))
val old = f.readyState().session
assertFailsWith<IllegalStateException> { f.coordinator.replaceProfileData(ProfileId.Default) { error("Corrupt backup") } }
val recovered = f.readyState()
assertNotSame(old, recovered.session)
assertEquals(ProfileSessionStatus.Open, recovered.session.status.value)
assertEquals("Corrupt backup", recovered.recoveryMessage)
recovered.session.close()
}
@Test fun inactiveRestoreUsesTargetStorageWithoutDetachingForeground() = runTest {
val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A)
val active = f.readyState().session
val target = f.coordinator.replaceProfileData(A) { it.id }
assertEquals(A, target)
assertSame(active, f.readyState().session)
assertEquals(ProfileSessionStatus.Open, active.status.value)
assertEquals(listOf("open:${A.value}", "close:${A.value}"), f.events)
active.close()
}
private class Fixture(private val dispatcher: CoroutineDispatcher) {
private var raw: String? = null
val registry = ProfileRegistry(object : ProfileRegistryPersistence {
override suspend fun read() = raw
override suspend fun compareAndSet(expected: String?, replacement: String): Boolean {
if (raw != expected) return false
raw = replacement; return true
}
})
val events = mutableListOf<String>()
var detachGate: CompletableDeferred<Unit>? = null
var rejectOpen: ProfileId? = null
var rejectPrepare: ProfileId? = null
var rejectClose: ProfileId? = null
var rejectNewClose = false
var rejectDelete = false
private fun session(id: ProfileId): ProfileSession = ProfileSession(id, dispatcher = dispatcher, databaseFactory = {
object : YokanDatabase by InMemoryYokanDatabase() {
override suspend fun close() {
events.add("close:${id.value}")
if (id == rejectClose || (id != ProfileId.Default && rejectNewClose)) error("Close failed")
}
}
}).also { it.database }
val coordinator = ProfileCoordinator(registry, session(ProfileId.Default),
openSession = { id -> events.add("open:${id.value}"); if (id == rejectOpen) error("Storage reserved elsewhere"); session(id) },
prepare = { owner -> events.add("prepare:${owner.id.value}"); if (owner.id == rejectPrepare) error("Prepare failed") },
detach = { owner -> events.add("detach:${owner.id.value}"); detachGate?.await() },
deleteStorage = { id -> events.add("delete:${id.value}"); if (rejectDelete) error("Delete failed") },
)
suspend fun ready(id: ProfileId) { registry.beginCreate("Books", id); registry.markReady(id) }
fun readyState() = assertIs<ProfileActivationState.Ready>(coordinator.state.value)
}
companion object { private val A = ProfileId("p_${"a".repeat(32)}") }
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistryTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ProfileRegistryTest, MemoryRegistry, read, compareAndSet.
Read the setup, action and assertions in these cases before implementing their production paths:
adoptionCreatesOnlyDefaultAndKeepsStableMetadataOnRestartprovisionRenameActivateDeleteAndTombstonesSurviveRestartdefaultInvalidNamesDuplicateIdsAndMissingOwnersCannotBeCommittedexportDestinationsSurviveDeletionStagingAndCannotBeAddedToUnavailableOwnersbadOrFutureRegistryIsNeverReplacedByAnEmptyDefaultfailedCommitRetainsThePriorRegistryAndCanBeRetriedconcurrentRegistryInstancesRetryAgainstCurrentMetadataWithoutLosingProfilescancellationAfterCommitStartsJoinsItsResultdeletionCapacityIsCheckedBeforeDataRemovalCanBeginsyncLeasesAreExclusiveIdempotentReleasedAndDroppedWithTheirProfilenamespaceUsesOnlyValidatedIdsAndDefaultKeepsLegacyLocations
package eu.friedcutlet.yokan.app.profiles
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertIs
import kotlin.test.assertTrue
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.domain.ProfileStorageNamespace
class ProfileRegistryTest {
@Test fun adoptionCreatesOnlyDefaultAndKeepsStableMetadataOnRestart() = runTest {
val store = MemoryRegistry()
val registry = ProfileRegistry(store)
assertEquals(ProfileRegistrySnapshot(), registry.refresh())
val firstRaw = store.raw
assertEquals(ProfileRegistrySnapshot(), ProfileRegistry(store).refresh())
assertEquals(firstRaw, store.raw)
assertEquals(1, store.commits)
assertFalse(registry.refresh().hasAdditionalProfiles)
}
@Test fun provisionRenameActivateDeleteAndTombstonesSurviveRestart() = runTest {
val store = MemoryRegistry(); val registry = ProfileRegistry(store)
registry.refresh()
assertEquals(ProfileStatus.Provisioning, registry.beginCreate(" 読書 🌙 ", A).profiles.last().status)
assertFalse(ProfileRegistry(store).refresh().hasAdditionalProfiles)
assertFailsWith<IllegalArgumentException> { registry.recordActive(A) }
registry.markReady(A)
assertTrue(ProfileRegistry(store).refresh().hasAdditionalProfiles)
registry.rename(A, "Renamed")
assertEquals("Renamed", registry.recordActive(A).available(A)?.name)
assertEquals(A, ProfileRegistry(store).refresh().lastActive)
assertFailsWith<IllegalArgumentException> { registry.beginDelete(A) }
registry.recordActive(ProfileId.Default)
val deleting = registry.beginDelete(A)
assertFalse(deleting.hasAdditionalProfiles)
assertEquals(ProfileStatus.Deleting, ProfileRegistry(store).refresh().profiles.last().status)
assertFailsWith<IllegalArgumentException> { registry.recordActive(A) }
val deleted = registry.finishDelete(A)
assertEquals(listOf(A), deleted.retiredIds)
assertEquals(deleted, registry.finishDelete(A))
assertEquals(deleted, ProfileRegistry(store).refresh())
assertFailsWith<IllegalArgumentException> { registry.beginCreate("Reused", A) }
}
@Test fun defaultInvalidNamesDuplicateIdsAndMissingOwnersCannotBeCommitted() = runTest {
val store = MemoryRegistry(); val registry = ProfileRegistry(store)
registry.refresh(); registry.beginCreate("Books", A); registry.markReady(A)
val saved = store.raw
assertFailsWith<IllegalArgumentException> { registry.rename(ProfileId.Default, "Other") }
assertFailsWith<IllegalArgumentException> { registry.beginDelete(ProfileId.Default) }
assertFailsWith<IllegalArgumentException> { registry.finishDelete(ProfileId.Default) }
assertFailsWith<IllegalArgumentException> { registry.beginCreate("Another", A) }
assertFailsWith<IllegalArgumentException> { registry.beginCreate("books", B) }
assertFailsWith<IllegalArgumentException> { registry.beginCreate("default", B) }
assertFailsWith<IllegalArgumentException> { registry.beginCreate("\n\t", B) }
assertFailsWith<IllegalArgumentException> { registry.beginCreate("a\nb", B) }
assertFailsWith<IllegalArgumentException> { registry.beginCreate("a".repeat(81), B) }
assertFailsWith<Exception> { registry.beginCreate("\uD800", B) }
assertFailsWith<IllegalArgumentException> { registry.recordActive(B) }
assertFailsWith<IllegalArgumentException> { registry.rename(B, "Unknown") }
assertEquals(saved, store.raw)
assertEquals(2, registry.refresh().profiles.size)
}
@Test fun exportDestinationsSurviveDeletionStagingAndCannotBeAddedToUnavailableOwners() = runTest {
val store = MemoryRegistry(); val registry = ProfileRegistry(store)
registry.beginCreate("Books", A); registry.markReady(A)
registry.recordExport(A, "/exports/books.json")
registry.recordExport(A, "/exports/books.json")
assertEquals(listOf("/exports/books.json"), ProfileRegistry(store).refresh().available(A)?.exportedBackups)
assertEquals(listOf("/exports/books.json"), registry.beginDelete(A).profiles.single { it.id == A }.exportedBackups)
assertFailsWith<IllegalArgumentException> { registry.recordExport(A, "/another.json") }
registry.recordExport(ProfileId.Default, "/default.json")
assertEquals(ProfileRecord(ProfileId.Default, "Default"), registry.refresh().available(ProfileId.Default))
}
@Test fun badOrFutureRegistryIsNeverReplacedByAnEmptyDefault() = runTest {
for (raw in listOf("{", "{} garbage", "{\"version\":2}",
"{\"profiles\":[]}", "{\"lastActive\":\"p_${"a".repeat(32)}\"}",
"{\"profiles\":[{\"id\":\"../outside\",\"name\":\"Unsafe\"}]}",
"{\"unrecognized\":true}", " ".repeat(MaxProfileRegistryBytes + 1))) {
val store = MemoryRegistry().also { it.raw = raw }
val registry = ProfileRegistry(store)
assertFailsWith<Exception> { registry.refresh() }
assertEquals(raw, store.raw)
assertEquals(0, store.commits)
assertIs<ProfileRegistryState.Unavailable>(registry.state.value)
}
}
@Test fun failedCommitRetainsThePriorRegistryAndCanBeRetried() = runTest {
val store = MemoryRegistry(); val registry = ProfileRegistry(store)
registry.refresh(); val saved = store.raw
store.reject = true
assertFailsWith<IllegalStateException> { registry.beginCreate("New", A) }
assertEquals(saved, store.raw)
assertIs<ProfileRegistryState.Unavailable>(registry.state.value)
store.reject = false
registry.refresh(); registry.beginCreate("New", A)
assertEquals(ProfileStatus.Provisioning, ProfileRegistry(store).refresh().profiles.last().status)
}
@Test fun concurrentRegistryInstancesRetryAgainstCurrentMetadataWithoutLosingProfiles() = runTest {
val store = MemoryRegistry()
val left = ProfileRegistry(store); val right = ProfileRegistry(store)
left.refresh()
store.barrier = CompletableDeferred()
val a = async { left.beginCreate("A", A) }
val b = async { right.beginCreate("B", B) }
a.await(); b.await()
val result = ProfileRegistry(store).refresh()
assertEquals(setOf(ProfileId.Default, A, B), result.profiles.map { it.id }.toSet())
assertTrue(store.conflicts > 0)
}
@Test fun cancellationAfterCommitStartsJoinsItsResult() = runTest {
val store = MemoryRegistry(); val registry = ProfileRegistry(store)
registry.refresh()
val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
store.beforeCommit = { entered.complete(Unit); release.await() }
val writer = launch { registry.beginCreate("Joined", A) }
entered.await(); writer.cancel(); release.complete(Unit); writer.join()
store.beforeCommit = null
assertEquals(A, ProfileRegistry(store).refresh().profiles.last().id)
}
@Test fun deletionCapacityIsCheckedBeforeDataRemovalCanBegin() = runTest {
val store = MemoryRegistry().also {
it.raw = encodeProfileRegistry(ProfileRegistrySnapshot(
profiles = listOf(ProfileRecord(ProfileId.Default, "Default"), ProfileRecord(A, "Books")),
retiredIds = List(MaxRetiredProfileIds) { index -> ProfileId("p_${index.toString(16).padStart(32, '0')}") },
))
}
val saved = store.raw
val registry = ProfileRegistry(store)
registry.refresh()
assertFailsWith<IllegalArgumentException> { registry.beginDelete(A) }
assertEquals(saved, store.raw)
assertEquals(ProfileStatus.Ready, ProfileRegistry(store).refresh().available(A)?.status)
}
@Test fun syncLeasesAreExclusiveIdempotentReleasedAndDroppedWithTheirProfile() = runTest {
val store = MemoryRegistry().also {
// Pre-lease registry JSON (no syncLeases field) still decodes.
it.raw = """{"version":1,"profiles":[{"id":"default","name":"Default"},{"id":"${A.value}","name":"Reader"},""" +
"""{"id":"${B.value}","name":"Other"}],"lastActive":"default","retiredIds":[]}"""
}
val registry = ProfileRegistry(store)
assertEquals(emptyList(), registry.refresh().syncLeases)
registry.claimSyncLease(A, "hub|https://hub.test|a@b")
registry.claimSyncLease(A, "hub|https://hub.test|a@b")
val conflict = assertFailsWith<IllegalStateException> { registry.claimSyncLease(B, "hub|https://hub.test|a@b") }
assertEquals("This sync account is already connected to profile ‘Reader’. Log out there first.", conflict.message)
assertIs<ProfileRegistryState.Ready>(registry.state.value)
// One lease per profile: switching accounts frees the old one.
registry.claimSyncLease(A, "cloud|gdrive|a@b")
registry.claimSyncLease(B, "hub|https://hub.test|a@b")
assertEquals(listOf(ProfileSyncLease("cloud|gdrive|a@b", A), ProfileSyncLease("hub|https://hub.test|a@b", B)),
ProfileRegistry(store).refresh().syncLeases)
registry.releaseSyncLease(A, "hub|https://hub.test|a@b") // not A's: no effect
registry.releaseSyncLease(B, "hub|https://hub.test|a@b")
registry.claimSyncLease(A, "hub|https://hub.test|a@b")
registry.beginDelete(A)
assertEquals(emptyList(), registry.refresh().syncLeases)
assertFailsWith<IllegalStateException> { registry.claimSyncLease(A, "hub|https://hub.test|a@b") }
registry.claimSyncLease(B, "hub|https://hub.test|a@b")
registry.finishDelete(A)
assertEquals(listOf(ProfileSyncLease("hub|https://hub.test|a@b", B)), ProfileRegistry(store).refresh().syncLeases)
}
@Test fun namespaceUsesOnlyValidatedIdsAndDefaultKeepsLegacyLocations() {
val default = ProfileStorageNamespace(ProfileId.Default)
assertEquals("yokan-room.db", default.databaseRelativePath)
assertEquals("yokan-database-v1", default.browserSnapshotKey)
assertEquals("/existing", default.ownedRoot("/existing/"))
val extra = ProfileStorageNamespace(A)
assertEquals("profiles/${A.value}/yokan-room.db", extra.databaseRelativePath)
assertEquals("yokan-database-v1:${A.value}", extra.browserSnapshotKey)
assertEquals("/existing/profiles/${A.value}", extra.ownedRoot("/existing/"))
for (bad in listOf("", "Default", "../outside", "/tmp", "p_ABC", "p_${"a".repeat(31)}", "p_${"a".repeat(33)}")) {
assertFailsWith<IllegalArgumentException> { ProfileId(bad) }
}
assertEquals(100, List(100) { ProfileId.random() }.distinct().size)
}
private class MemoryRegistry : ProfileRegistryPersistence {
var raw: String? = null
var commits = 0
var conflicts = 0
var reject = false
var barrier: CompletableDeferred<Unit>? = null
private var reads = 0
var beforeCommit: (suspend () -> Unit)? = null
override suspend fun read(): String? {
val result = raw
barrier?.let { gate ->
reads++
if (reads == 2) { barrier = null; gate.complete(Unit) }
gate.await()
}
return result
}
override suspend fun compareAndSet(expected: String?, replacement: String): Boolean {
beforeCommit?.invoke()
if (reject) error("Storage unavailable")
if (raw != expected) { conflicts++; return false }
raw = replacement; commits++; return true
}
}
companion object {
val A = ProfileId("p_${"a".repeat(32)}")
val B = ProfileId("p_${"b".repeat(32)}")
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileSessionTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ProfileSessionTest, ProbeDatabase, close.
Read the setup, action and assertions in these cases before implementing their production paths:
unusedSessionClosesWithoutOpeningLazyResourcesindependentOwnersCaptureTheirDatabaseAndRetirementDoesNotTouchAnothercancellationJoinsFinalProgressBeforeClosingDatabasefailedFlushCanBeRetriedWithoutRecreatingResourcesjoinTimeoutKeepsDatabaseUntilFinalizerCompletesAndRetirementRetriesplatformFactoryRejectsExtraProfilesBeforeAllocatingResourcescontextResourceFailureRetainsDatabaseAndRetriesBeforeItsReleaseretiredOwnerRejectsContextResourceBeforeItsFactoryRuns
Cross-chapter imports used by this file: DbManga, InMemoryYokanDatabase, YokanDatabase. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app.profiles
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabase
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertSame
import kotlin.test.assertTrue
import eu.friedcutlet.yokan.domain.ProfileId
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
class ProfileSessionTest {
@Test fun unusedSessionClosesWithoutOpeningLazyResources() = runTest {
var opens = 0
val owner = ProfileSession(ProfileId.Default, databaseFactory = { opens++; error("Unused database") })
owner.close(); owner.close()
assertEquals(0, opens)
assertEquals(ProfileSessionStatus.Closed, owner.status.value)
assertFailsWith<IllegalStateException> { owner.database }
}
@Test fun independentOwnersCaptureTheirDatabaseAndRetirementDoesNotTouchAnother() = runTest {
val a = ProbeDatabase(); val b = ProbeDatabase()
val left = ProfileSession(A, databaseFactory = { assertEquals(A, it); a })
val right = ProfileSession(B, databaseFactory = { assertEquals(B, it); b })
assertSame(a, left.database); assertSame(a, left.database)
assertSame(b, right.database)
a.upsertManga(DbManga(id = 42, privateNote = "A")); b.upsertManga(DbManga(id = 42, privateNote = "B"))
left.close()
assertEquals(1, a.closes); assertEquals(0, b.closes)
assertEquals("B", right.database.manga(42)?.privateNote)
assertFailsWith<IllegalStateException> { left.database }
right.close()
}
@Test fun cancellationJoinsFinalProgressBeforeClosingDatabase() = runTest {
val db = ProbeDatabase()
val owner = ProfileSession(A, databaseFactory = { db }, dispatcher = StandardTestDispatcher(testScheduler))
val captured = owner.database
val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
owner.scope.launch {
try { entered.complete(Unit); awaitCancellation() }
finally {
withContext(NonCancellable) { release.await(); captured.upsertManga(DbManga(id = 42, privateNote = "Final progress")) }
}
}
entered.await()
val retiring = launch { owner.close() }
testScheduler.runCurrent()
assertEquals(ProfileSessionStatus.Retiring, owner.status.value)
assertEquals(0, db.closes)
retiring.cancel(); release.complete(Unit); retiring.join()
assertEquals("Final progress", db.noteAtClose)
assertEquals(ProfileSessionStatus.Closed, owner.status.value)
assertEquals(1, db.closes)
}
@Test fun failedFlushCanBeRetriedWithoutRecreatingResources() = runTest {
val db = ProbeDatabase(); var opens = 0
val owner = ProfileSession(A, databaseFactory = { opens++; db })
owner.database.upsertManga(DbManga(id = 42, privateNote = "Keep"))
db.reject = true
assertFailsWith<IllegalStateException> { owner.close() }
assertEquals(ProfileSessionStatus.RetirementFailed, owner.status.value)
assertFalse(db.released)
assertFailsWith<IllegalStateException> { owner.database }
db.reject = false; owner.close(); owner.close()
assertEquals(1, opens); assertTrue(db.released)
assertEquals("Keep", db.noteAtClose)
}
@Test fun joinTimeoutKeepsDatabaseUntilFinalizerCompletesAndRetirementRetries() = runTest {
val db = ProbeDatabase()
val owner = ProfileSession(A, databaseFactory = { db }, dispatcher = StandardTestDispatcher(testScheduler), joinTimeoutMillis = 100)
owner.database
val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
owner.scope.launch { try { entered.complete(Unit); awaitCancellation() } finally { withContext(NonCancellable) { release.await() } } }
entered.await()
assertFailsWith<kotlinx.coroutines.TimeoutCancellationException> { owner.close() }
assertEquals(0, db.closes)
assertEquals(ProfileSessionStatus.RetirementFailed, owner.status.value)
release.complete(Unit); owner.close()
assertEquals(1, db.closes)
}
@Test fun platformFactoryRejectsExtraProfilesBeforeAllocatingResources() {
assertFailsWith<IllegalStateException> { createPlatformProfileSession(A, eu.friedcutlet.yokan.services.sync.SyncAccountLeases.None) }
}
@Test fun contextResourceFailureRetainsDatabaseAndRetriesBeforeItsRelease() = runTest {
val db = ProbeDatabase(); var releases = 0; var reject = true
val owner = ProfileSession(A, databaseFactory = { db })
val captured = owner.ownResource(factory = { owner.database }, close = {
assertSame(db, it); releases++; if (reject) error("Transport cleanup failed")
})
assertSame(db, captured)
assertFailsWith<IllegalStateException> { owner.close() }
assertEquals(ProfileSessionStatus.RetirementFailed, owner.status.value)
assertEquals(0, db.closes)
reject = false; owner.close(); owner.close()
assertEquals(2, releases); assertEquals(1, db.closes)
}
@Test fun retiredOwnerRejectsContextResourceBeforeItsFactoryRuns() = runTest {
val owner = ProfileSession(A); var allocations = 0
owner.close()
assertFailsWith<IllegalStateException> {
owner.ownResource(factory = { allocations++; Any() }, close = {})
}
assertEquals(0, allocations)
}
private class ProbeDatabase(private val memory: InMemoryYokanDatabase = InMemoryYokanDatabase()) : YokanDatabase by memory {
var closes = 0; var released = false; var reject = false; var noteAtClose: String? = null
override suspend fun close() {
closes++
if (reject) error("Persistence unavailable")
noteAtClose = manga(42)?.privateNote; released = true
}
}
companion object { val A = ProfileId("p_${"a".repeat(32)}"); val B = ProfileId("p_${"b".repeat(32)}") }
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileSnapshotRetirementTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ProfileSnapshotRetirementTest, Store, load, save.
Read the setup, action and assertions in these cases before implementing their production paths:
closeStopsPersistenceThenFlushesAndLateSavesCannotOverwriteStoragefailedClosePreservesDirtySnapshotAndCanRetryAfterQuotaRecoverycancelledCloseStillJoinsPersistenceShutdownAndFinalSave
Cross-chapter imports used by this file: DatabaseSnapshotStore, DbManga, SnapshotYokanDatabase, YokanDatabaseSnapshot. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app.profiles
import eu.friedcutlet.yokan.database.DatabaseSnapshotStore
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.SnapshotYokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class ProfileSnapshotRetirementTest {
@Test fun closeStopsPersistenceThenFlushesAndLateSavesCannotOverwriteStorage() = runTest {
val events = mutableListOf<String>(); val store = Store { events += "save" }
val db = SnapshotYokanDatabase(store, stopPersistence = { events += "stop" })
db.upsertManga(DbManga(id = 42, privateNote = "Saved"))
db.close()
assertEquals(listOf("stop", "save"), events)
assertEquals("Saved", store.saved?.mangas?.single()?.privateNote)
db.close()
// A retained old in-memory reference cannot write through after retirement.
db.upsertManga(DbManga(id = 42, privateNote = "Late"))
assertFalse(db.persistIfDirty()); assertFalse(db.persist())
assertFailsWith<IllegalStateException> { db.awaitPersistence() }
assertFailsWith<IllegalStateException> { db.replaceAllAtomically(db.snapshot(), null, emptySet()) }
assertEquals("Saved", store.saved?.mangas?.single()?.privateNote)
assertEquals(listOf("stop", "save"), events)
}
@Test fun failedClosePreservesDirtySnapshotAndCanRetryAfterQuotaRecovery() = runTest {
val store = Store {}; val db = SnapshotYokanDatabase(store)
db.upsertManga(DbManga(id = 42, privateNote = "Original")); db.awaitPersistence()
db.upsertManga(DbManga(id = 42, privateNote = "Pending")); store.reject = true
assertFailsWith<IllegalStateException> { db.close() }
assertTrue(db.saveFailed.value)
assertEquals("Original", store.saved?.mangas?.single()?.privateNote)
assertEquals("Pending", db.manga(42)?.privateNote)
store.reject = false; db.close()
assertEquals("Pending", store.saved?.mangas?.single()?.privateNote)
assertFalse(db.saveFailed.value)
}
@Test fun cancelledCloseStillJoinsPersistenceShutdownAndFinalSave() = runTest {
val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>(); val store = Store {}
val db = SnapshotYokanDatabase(store, stopPersistence = { entered.complete(Unit); release.await() })
db.upsertManga(DbManga(id = 42, privateNote = "Final"))
val closing = launch { db.close() }
entered.await(); closing.cancel(); release.complete(Unit); closing.join()
assertEquals("Final", store.saved?.mangas?.single()?.privateNote)
assertFalse(db.persistIfDirty())
}
private class Store(private val onSave: () -> Unit) : DatabaseSnapshotStore {
var saved: YokanDatabaseSnapshot? = null; var reject = false
override fun load() = saved
override fun save(snapshot: YokanDatabaseSnapshot) {
if (reject) error("Quota exceeded")
onSave(); saved = snapshot
}
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/DesktopLaunchLinkTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines DesktopLaunchLinkTest, mapsSearchFlagsLinksAndBackupFiles.
Read the setup, action and assertions in these cases before implementing their production paths:
mapsSearchFlagsLinksAndBackupFiles
Cross-chapter imports used by this file: searchDeepLink. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app
import eu.friedcutlet.yokan.ui.navigation.searchDeepLink
import java.io.File
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class DesktopLaunchLinkTest {
@Test
fun mapsSearchFlagsLinksAndBackupFiles() {
assertEquals(searchDeepLink("One Piece"), desktopLaunchLink(arrayOf("--tray", "--search", "One Piece")))
assertEquals(searchDeepLink("Berserk"), desktopLaunchLink(arrayOf("--search=Berserk")))
assertEquals("mihon://add-repo?url=x", desktopLaunchLink(arrayOf("--tray", "mihon://add-repo?url=x")))
val backup = File.createTempFile("library", ".tachibk").apply { deleteOnExit() }
assertEquals(backup.absoluteFile.toURI().toString(), desktopLaunchLink(arrayOf(backup.path)))
assertNull(desktopLaunchLink(arrayOf("--tray", "missing.tachibk")))
assertNull(desktopLaunchLink(arrayOf("--search")))
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileSessionRoomTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines ProfileSessionRoomTest, SilentNotifications, supported, notify, cancel.
Read the setup, action and assertions in these cases before implementing their production paths:
roomCloseDrainsQueuedWritesRejectsStaleMutationsAndReopensIndependentlybusyRoomCloseTimesOutWithoutDroppingWritesAndCanBeRetrieddefaultServiceGraphSharesSessionScopeAndRetiresActualRoomAndObserversstaleLoggingOwnerCannotDetachNewTargetEvenWhenBothUseSameFileService
Cross-chapter imports used by this file: DbManga, RoomYokanDatabase, createDesktopProfileRoomDatabase, createDesktopProfileFileService, JvmLocalArchiveService, NotificationService. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app.profiles
import androidx.sqlite.driver.bundled.BundledSQLiteDriver
import androidx.sqlite.execSQL
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.room.RoomYokanDatabase
import eu.friedcutlet.yokan.database.room.createDesktopProfileRoomDatabase
import eu.friedcutlet.yokan.services.files.createDesktopProfileFileService
import eu.friedcutlet.yokan.services.files.JvmLocalArchiveService
import eu.friedcutlet.yokan.services.notifications.NotificationService
import eu.friedcutlet.yokan.services.notifications.NotificationPayload
import eu.friedcutlet.yokan.services.notifications.NotificationChannel
import eu.friedcutlet.yokan.services.logging.LogSink
import java.nio.file.Files
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.TimeoutCancellationException
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertSame
import kotlin.test.assertTrue
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.domain.ProfileStorageNamespace
class ProfileSessionRoomTest {
@Test fun roomCloseDrainsQueuedWritesRejectsStaleMutationsAndReopensIndependently() = runBlocking {
val root = Files.createTempDirectory("yokan-profile-retire").toFile()
try {
val db = RoomYokanDatabase(createDesktopProfileRoomDatabase(root, A))
(1L..100L).forEach { db.upsertManga(DbManga(id = it, privateNote = "A $it")) }
db.close(); db.close()
val before = db.snapshot()
assertFailsWith<IllegalStateException> { db.upsertManga(DbManga(id = 42, privateNote = "Stale")) }
assertEquals(before, db.snapshot())
assertFailsWith<IllegalStateException> { db.updateSettings(db.settings()) }
assertFailsWith<IllegalStateException> { db.batch { db.removeManga(42) } }
assertFailsWith<IllegalStateException> { db.awaitPersistence() }
val reopened = RoomYokanDatabase(createDesktopProfileRoomDatabase(root, A))
try { assertEquals(100, reopened.mangas().size); assertEquals("A 42", reopened.manga(42)?.privateNote) }
finally { reopened.close() }
val b = RoomYokanDatabase(createDesktopProfileRoomDatabase(root, B))
try { assertTrue(b.mangas().isEmpty()) } finally { b.close() }
} finally { root.deleteRecursively() }
}
@Test fun busyRoomCloseTimesOutWithoutDroppingWritesAndCanBeRetried() = runBlocking {
val root = Files.createTempDirectory("yokan-profile-busy").toFile()
val room = createDesktopProfileRoomDatabase(root, A)
val db = RoomYokanDatabase(room, closeTimeoutMillis = 200)
try {
db.awaitPersistence()
val lock = BundledSQLiteDriver().open(java.io.File(root, ProfileStorageNamespace(A).databaseRelativePath).path)
var transactionStarted = false
try {
// Room's empty flush barrier can still be finishing its transaction.
// Wait for that brief contention before deliberately holding the write lock.
lock.execSQL("PRAGMA busy_timeout = 5000")
lock.execSQL("BEGIN IMMEDIATE")
transactionStarted = true
db.upsertManga(DbManga(id = 42, privateNote = "Queued"))
assertFailsWith<TimeoutCancellationException> { db.close() }
// The failed close has not released Room or discarded its queue.
db.upsertManga(DbManga(id = 43, privateNote = "Retry"))
} finally {
try { if (transactionStarted) lock.execSQL("ROLLBACK") }
finally { lock.close() }
}
db.awaitPersistence(); db.close()
val reopened = RoomYokanDatabase(createDesktopProfileRoomDatabase(root, A))
try { assertEquals("Queued", reopened.manga(42)?.privateNote); assertEquals("Retry", reopened.manga(43)?.privateNote) }
finally { reopened.close() }
} finally { room.close(); root.deleteRecursively() }
}
@Test fun defaultServiceGraphSharesSessionScopeAndRetiresActualRoomAndObservers() = runBlocking {
val root = Files.createTempDirectory("yokan-default-session").toFile()
try {
val owner = ProfileSession(ProfileId.Default,
databaseFactory = { RoomYokanDatabase(createDesktopProfileRoomDatabase(root, it)) },
filesFactory = { createDesktopProfileFileService(root, it) },
archivesFactory = { JvmLocalArchiveService(createDesktopProfileFileService(root, it).cacheRoot) },
notificationsFactory = { SilentNotifications },
)
val db = owner.database
val capturedHttp = owner.services.http
val capturedTogether = owner.together
val capturedReaderContent = owner.readerContent
val capturedSpeech = owner.services.textToSpeech
val capturedSpeechReader = capturedSpeech.reader()
val capturedPlayerServices = owner.playerServices
val capturedPlayerReader = capturedPlayerServices.reader()
assertEquals(ProfileId.Default, capturedPlayerServices.profileId)
assertSame(capturedReaderContent, owner.readerContent)
assertEquals(ProfileId.Default, capturedReaderContent.profileId)
assertEquals("Inline chapter", capturedReaderContent.novelText(null, "Novel", "Inline chapter"))
assertSame(owner.scope, owner.services.scope)
assertSame(db, owner.services.database)
owner.settings; owner.libraryIndex; owner.migration; owner.chapterPages
db.upsertManga(DbManga(id = 42, privateNote = "Default"))
owner.close()
assertEquals(ProfileSessionStatus.Closed, owner.status.value)
assertEquals(false, capturedSpeech.isAvailable)
assertEquals(false, capturedPlayerServices.isAvailable)
assertFailsWith<kotlinx.coroutines.CancellationException> {
capturedPlayerReader.configuration(eu.friedcutlet.yokan.database.DbSettings())
}
assertFailsWith<kotlinx.coroutines.CancellationException> {
capturedPlayerReader.streamProxy.proxyUrl("https://retired.test/video", mapOf("Referer" to "retired"))
}
assertFailsWith<kotlinx.coroutines.CancellationException> { capturedSpeech.voices(null) }
assertFailsWith<kotlinx.coroutines.CancellationException> {
capturedSpeechReader.speak("Retired chapter", eu.friedcutlet.yokan.services.tts.TextToSpeechRequest()) { _, _ ->
error("Retired owner reported speech progress")
}
}
assertEquals(null, capturedTogether.hubSession())
assertEquals(null, capturedTogether.client.value)
assertFailsWith<IllegalStateException> { owner.repository }
assertFailsWith<kotlinx.coroutines.CancellationException> {
capturedReaderContent.novelText(null, "Novel", "Retired chapter")
}
// Stale UI/extension references must fail before settings/cookies or the closed engine.
assertFailsWith<kotlinx.coroutines.CancellationException> {
capturedHttp.request(eu.friedcutlet.yokan.services.http.HttpRequest("https://source.test/"))
}
assertFailsWith<kotlinx.coroutines.CancellationException> {
capturedHttp.stream(eu.friedcutlet.yokan.services.http.HttpRequest("https://source.test/")) {
error("Retired owner wrote bytes")
}
}
val reopened = RoomYokanDatabase(createDesktopProfileRoomDatabase(root, ProfileId.Default))
try { assertEquals("Default", reopened.manga(42)?.privateNote) } finally { reopened.close() }
} finally { root.deleteRecursively() }
}
@Test fun staleLoggingOwnerCannotDetachNewTargetEvenWhenBothUseSameFileService() {
val root = Files.createTempDirectory("yokan-log-owner").toFile()
try {
val files = createDesktopProfileFileService(root, ProfileId.Default)
val old = LogSink.attach(files) { false }; val current = LogSink.attach(files) { false }
LogSink.detach(old)
assertEquals("${files.cacheRoot}/logs/yokan.log", LogSink.logFilePath())
LogSink.detach(current); assertEquals(null, LogSink.logFilePath())
} finally { root.deleteRecursively() }
}
private object SilentNotifications : NotificationService {
override fun supported() = false
override fun notify(payload: NotificationPayload) = Unit
override fun cancel(channel: NotificationChannel, tag: String?) = Unit
}
companion object { val A = ProfileId("p_${"a".repeat(32)}"); val B = ProfileId("p_${"b".repeat(32)}") }
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletionTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines ProfileStorageDeletionTest.
Read the setup, action and assertions in these cases before implementing their production paths:
deletionKeepsOtherOwnersExportsAndSymlinkTargetsreplacedRootSymlinkIsRemovedWithoutTraversingItsDestination
package eu.friedcutlet.yokan.app.profiles
import java.nio.file.Files
import kotlin.test.*
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.domain.ProfileStorageNamespace
class ProfileStorageDeletionTest {
@Test fun deletionKeepsOtherOwnersExportsAndSymlinkTargets() {
val base = Files.createTempDirectory("yokan-profile-delete").toFile()
try {
val namespace = ProfileStorageNamespace(A)
val root = java.io.File(namespace.ownedRoot(base.path)).apply { mkdirs() }
val other = java.io.File(ProfileStorageNamespace(B).ownedRoot(base.path)).apply { mkdirs() }
val exported = java.io.File(root, "backups/export.json").apply { parentFile.mkdirs(); writeText("export") }
java.io.File(root, "yokan-room.db").writeText("A")
java.io.File(root, "downloads/42.cbz").apply { parentFile.mkdirs(); writeText("A pages") }
java.io.File(other, "yokan-room.db").writeText("B")
val external = java.io.File(base, "external").apply { mkdirs() }
val userFile = java.io.File(external, "chapter.cbz").apply { writeText("user") }
Files.createSymbolicLink(java.io.File(root, "linked-folder").toPath(), external.toPath())
java.io.File(base, "yokan-room.db").writeText("Default")
deleteOwnedProfileDirectory(base, A, listOf(exported.path))
assertEquals("export", exported.readText())
assertEquals("user", userFile.readText())
assertFalse(java.io.File(root, "downloads").exists())
assertFalse(java.io.File(root, "yokan-room.db").exists())
assertEquals("B", java.io.File(other, "yokan-room.db").readText())
assertEquals("Default", java.io.File(base, "yokan-room.db").readText())
deleteOwnedProfileDirectory(base, A, listOf(exported.path))
assertEquals("export", exported.readText())
} finally { base.deleteRecursively() }
}
@Test fun replacedRootSymlinkIsRemovedWithoutTraversingItsDestination() {
val base = Files.createTempDirectory("yokan-profile-link").toFile()
try {
val external = java.io.File(base, "external").apply { mkdirs() }
val userFile = java.io.File(external, "file").apply { writeText("keep") }
java.io.File(base, "profiles").mkdirs()
val root = java.io.File(ProfileStorageNamespace(A).ownedRoot(base.path))
Files.createSymbolicLink(root.toPath(), external.toPath())
deleteOwnedProfileDirectory(base, A, emptyList())
assertFalse(Files.exists(root.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS))
assertEquals("keep", userFile.readText())
assertFailsWith<IllegalArgumentException> { deleteOwnedProfileDirectory(base, ProfileId.Default, emptyList()) }
} finally { base.deleteRecursively() }
}
companion object {
private val A = ProfileId("p_${"a".repeat(32)}")
private val B = ProfileId("p_${"b".repeat(32)}")
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLeaseTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines ProfileStorageLeaseTest, close.
Read the setup, action and assertions in these cases before implementing their production paths:
anotherOwnerCannotOpenUntilReleaseAndLockInodeSurvivesDeletionfailedDatabaseRetirementRetainsReservationUntilRetryCompletes
Cross-chapter imports used by this file: InMemoryYokanDatabase, YokanDatabase. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app.profiles
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabase
import java.nio.file.Files
import kotlinx.coroutines.runBlocking
import kotlin.test.*
import eu.friedcutlet.yokan.domain.ProfileId
class ProfileStorageLeaseTest {
@Test fun anotherOwnerCannotOpenUntilReleaseAndLockInodeSurvivesDeletion() = runBlocking {
val root = Files.createTempDirectory("profile-lease").toFile()
val id = ProfileId("p_${"a".repeat(32)}")
try {
val first = acquireFileProfileLease(root, id)
assertFailsWith<IllegalStateException> { acquireFileProfileLease(root, id) }
deleteOwnedProfileDirectory(root, id, emptyList())
assertTrue(root.resolve("profiles/locks/${id.value}.lock").isFile)
assertFailsWith<IllegalStateException> { acquireFileProfileLease(root, id) }
first.close(); first.close()
acquireFileProfileLease(root, id).close()
} finally { root.deleteRecursively() }
}
@Test fun failedDatabaseRetirementRetainsReservationUntilRetryCompletes() = runBlocking {
val root = Files.createTempDirectory("profile-drain").toFile()
val id = ProfileId("p_${"b".repeat(32)}")
var fail = true
val session = ProfileSession(id, storageLease = acquireFileProfileLease(root, id), databaseFactory = {
object : YokanDatabase by InMemoryYokanDatabase() {
override suspend fun close() { if (fail) error("Pending writes") }
}
})
try {
session.database
assertFailsWith<IllegalStateException> { session.close() }
assertFailsWith<IllegalStateException> { acquireFileProfileLease(root, id) }
fail = false; session.close()
acquireFileProfileLease(root, id).close()
} finally { fail = false; session.close(); root.deleteRecursively() }
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines ProfileStorageTest, open, load, save.
Read the setup, action and assertions in these cases before implementing their production paths:
fileRegistryCommitsAtomicallyAndIndependentInstancesDoNotLoseUpdatescorruptAndOversizedFileRegistryPreserveBytesAndDefaultDatatwoNativeDatabasesWithIdenticalIdsRemainIndependentAcrossReopenAndDefaultAdoptionprofileOwnedDownloadBackupAndCacheRootsDoNotTouchDefaultOrExportsexplicitSnapshotFlushPersistsOnlyItsOwningStoreAndFailureCanBeRetried
Cross-chapter imports used by this file: RoomYokanDatabase, createDesktopProfileRoomDatabase, createDesktopProfileFileService. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app.profiles
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.database.room.RoomYokanDatabase
import eu.friedcutlet.yokan.database.room.createDesktopProfileRoomDatabase
import eu.friedcutlet.yokan.services.files.createDesktopProfileFileService
import java.io.File
import java.nio.file.Files
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.runBlocking
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.domain.ProfileStorageNamespace
class ProfileStorageTest {
@Test fun fileRegistryCommitsAtomicallyAndIndependentInstancesDoNotLoseUpdates() = runBlocking {
val root = Files.createTempDirectory("yokan-profile-registry").toFile()
try {
val file = File(root, "profiles/registry.json")
val one = ProfileRegistry(FileProfileRegistryPersistence(file))
val two = ProfileRegistry(FileProfileRegistryPersistence(file))
one.refresh()
coroutineScope { val a = async { one.beginCreate("A", A) }; val b = async { two.beginCreate("B", B) }; a.await(); b.await() }
val registry = ProfileRegistry(FileProfileRegistryPersistence(file))
assertEquals(setOf(ProfileId.Default, A, B), registry.refresh().profiles.map { it.id }.toSet())
assertFalse(file.parentFile.listFiles().orEmpty().any { it.extension == "tmp" })
registry.markReady(A); registry.recordActive(A)
assertEquals(A, ProfileRegistry(FileProfileRegistryPersistence(file)).refresh().lastActive)
// An abandoned staging file never replaces a committed registry on restart.
File(file.parentFile, "registry-abandoned.tmp").writeText("{")
assertEquals(A, ProfileRegistry(FileProfileRegistryPersistence(file)).refresh().lastActive)
} finally { root.deleteRecursively() }
}
@Test fun corruptAndOversizedFileRegistryPreserveBytesAndDefaultData() = runBlocking {
val root = Files.createTempDirectory("yokan-profile-corrupt").toFile()
try {
val original = File(root, "yokan-room.db").apply { writeText("existing default sentinel") }
val file = File(root, "profiles/registry.json").apply { parentFile.mkdirs() }
for (bytes in listOf("{".encodeToByteArray(), byteArrayOf(0xFF.toByte()), ByteArray(MaxProfileRegistryBytes + 1))) {
file.writeBytes(bytes)
assertFailsWith<Exception> { ProfileRegistry(FileProfileRegistryPersistence(file)).refresh() }
assertTrue(file.readBytes().contentEquals(bytes))
assertEquals("existing default sentinel", original.readText())
}
} finally { root.deleteRecursively() }
}
@Test fun twoNativeDatabasesWithIdenticalIdsRemainIndependentAcrossReopenAndDefaultAdoption() = runBlocking {
val root = Files.createTempDirectory("yokan-profile-room").toFile()
try {
val legacy = seedDatabaseSnapshot().copy(mangas = listOf(DbManga(id = 42, name = "Default", favorite = true, privateNote = "Legacy note")))
val defaultRoom = createDesktopProfileRoomDatabase(root, ProfileId.Default)
try {
val default = RoomYokanDatabase(defaultRoom, legacySnapshotProvider = { legacy })
default.awaitPersistence()
assertEquals("Legacy note", default.manga(42)?.privateNote)
} finally { defaultRoom.close() }
assertTrue(File(root, "yokan-room.db").isFile)
val rooms = listOf(A, B).map { createDesktopProfileRoomDatabase(root, it) }
try {
val databases = rooms.map { RoomYokanDatabase(it) }
assertTrue(databases.all { it.mangas().isEmpty() && it.syncPreferences().isEmpty() && it.trackPreferences().isEmpty() })
databases[0].upsertManga(DbManga(id = 42, name = "A", favorite = true, privateNote = "A note"))
databases[1].upsertManga(DbManga(id = 42, name = "B", favorite = true, privateNote = "B note"))
databases[0].updateSettings(databases[0].settings().copy(readerHoldToScroll = true, automaticReaderLayout = true))
databases[1].updateSettings(databases[1].settings().copy(readerHoldToScroll = false, automaticReaderLayout = false))
databases.forEach { it.awaitPersistence() }
} finally { rooms.forEach { it.close() } }
for ((id, name, note) in listOf(Triple(ProfileId.Default, "Default", "Legacy note"), Triple(A, "A", "A note"), Triple(B, "B", "B note"))) {
val room = createDesktopProfileRoomDatabase(root, id)
try {
val db = RoomYokanDatabase(room, legacySnapshotProvider = { error("Existing profile must not load legacy data") })
assertEquals(name, db.manga(42)?.name); assertEquals(note, db.manga(42)?.privateNote)
assertEquals(id == A, db.settings().readerHoldToScroll)
db.awaitPersistence()
} finally { room.close() }
}
} finally { root.deleteRecursively() }
}
@Test fun profileOwnedDownloadBackupAndCacheRootsDoNotTouchDefaultOrExports() {
val root = Files.createTempDirectory("yokan-profile-files").toFile()
try {
val default = createDesktopProfileFileService(root, ProfileId.Default)
val a = createDesktopProfileFileService(root, A)
val b = createDesktopProfileFileService(root, B)
assertEquals(File(root, "Yokan/downloads").path, default.downloadRoot)
assertEquals(File(root, "Yokan/backups").path, default.backupRoot)
assertEquals(File(root, "cache").path, default.cacheRoot)
for ((index, files) in listOf(default, a, b).withIndex()) for (path in listOf(files.downloadRoot, files.backupRoot, files.cacheRoot)) {
files.writeBytes("$path/same-name.txt", "owner $index".encodeToByteArray())
}
val exported = File(root, "exported-backup.zip").apply { writeText("user export") }
assertTrue(File(ProfileStorageNamespace(A).ownedRoot(root.path)).deleteRecursively())
for ((files, index) in listOf(default to 0, b to 2)) {
for (path in listOf(files.downloadRoot, files.backupRoot, files.cacheRoot)) {
assertEquals("owner $index", files.readBytes("$path/same-name.txt").decodeToString())
}
}
assertEquals("user export", exported.readText())
} finally { root.deleteRecursively() }
}
@Test fun explicitSnapshotFlushPersistsOnlyItsOwningStoreAndFailureCanBeRetried() = runBlocking {
val raw = mutableMapOf<String, String>(); var rejected: String? = null
fun open(id: ProfileId): YokanDatabase {
val key = ProfileStorageNamespace(id).browserSnapshotKey
return SnapshotYokanDatabase(object : DatabaseSnapshotStore {
override fun load() = raw[key]?.let(::decodeDatabaseSnapshot)
override fun save(snapshot: YokanDatabaseSnapshot) {
if (key == rejected) error("Quota exceeded")
raw[key] = encodeDatabaseSnapshot(snapshot)
}
})
}
val default = open(ProfileId.Default); default.upsertManga(DbManga(id = 42, privateNote = "Default")); default.awaitPersistence()
val defaultRaw = raw.getValue("yokan-database-v1")
val a = open(A); val b = open(B)
assertTrue(a.mangas().isEmpty()); assertTrue(b.mangas().isEmpty())
a.upsertManga(DbManga(id = 42, privateNote = "A")); b.upsertManga(DbManga(id = 42, privateNote = "B"))
rejected = ProfileStorageNamespace(B).browserSnapshotKey
a.awaitPersistence(); assertFailsWith<IllegalStateException> { b.awaitPersistence() }
assertEquals(defaultRaw, raw.getValue("yokan-database-v1"))
assertEquals("A", open(A).manga(42)?.privateNote)
rejected = null; b.awaitPersistence(); assertEquals("B", open(B).manga(42)?.privateNote)
assertEquals("Default", open(ProfileId.Default).manga(42)?.privateNote)
}
companion object { val A = ProfileId("p_${"a".repeat(32)}"); val B = ProfileId("p_${"b".repeat(32)}") }
}
Write composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/app/WebLaunchLinkTest.kt
Create this path in your reconstruction project. Source set: wasmJsTest. Exact file download.
The implementation below defines WebLaunchLinkTest, mapsSearchAndLinkQueryParameters.
Read the setup, action and assertions in these cases before implementing their production paths:
mapsSearchAndLinkQueryParameters
Cross-chapter imports used by this file: searchDeepLink. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.app
import eu.friedcutlet.yokan.ui.navigation.searchDeepLink
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class WebLaunchLinkTest {
@Test
fun mapsSearchAndLinkQueryParameters() {
assertEquals(searchDeepLink("One Piece"), webLaunchLink("?search=One+Piece"))
assertEquals(
"animetail://add-repo?url=https://example.com/index.min.json",
webLaunchLink("?link=animetail%3A%2F%2Fadd-repo%3Furl%3Dhttps%3A%2F%2Fexample.com%2Findex.min.json"),
)
assertNull(webLaunchLink("?search=%20"))
assertNull(webLaunchLink(""))
}
}
Completion record
- [ ] Every implementation/configuration and required asset shown above is present at its displayed path.
- [ ] Cross-chapter imports resolve against the intended contracts and platform source sets.
- [ ] The tests for this chapter pass in the rebuilt app; record the command, platform and result.
- [ ] Native, device, browser and live-service checks have evidence or an explicit “not run” entry. [chapter-content-end]: #
Gate: start a reader/download/sync operation, switch profiles while it is suspended, then let it finish. It must either complete against its original live owner or be cancelled and joined; it must never write into the new profile. Test failed retirement, concurrent deletion, stale callbacks, inactive backup targets and Default adoption using the profile and ownership test families.