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 = 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 = listOf(ProfileRecord(ProfileId.Default, "Default")), val lastActive: ProfileId = ProfileId.Default, val retiredIds: List = emptyList(), val syncLeases: List = 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(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.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