ProfileRegistry.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.kt
1package eu.friedcutlet.yokan.app.profiles23import kotlinx.coroutines.CancellationException4import kotlinx.coroutines.NonCancellable5import kotlinx.coroutines.currentCoroutineContext6import kotlinx.coroutines.ensureActive7import kotlinx.coroutines.flow.MutableStateFlow8import kotlinx.coroutines.flow.asStateFlow9import kotlinx.coroutines.flow.update10import kotlinx.coroutines.sync.Mutex11import kotlinx.coroutines.sync.withLock12import kotlinx.coroutines.withContext13import kotlinx.serialization.Serializable14import kotlinx.serialization.json.Json15import eu.friedcutlet.yokan.domain.ProfileId161718@Serializable19enum class ProfileStatus { Provisioning, Ready, Deleting }20@Serializable21data class ProfileRecord(22 val id: ProfileId,23 val name: String,24 val status: ProfileStatus = ProfileStatus.Ready,25 /** Explicit save destinations are device metadata, never imported from backups. */26 val exportedBackups: List<String> = emptyList(),27)28/** Device-wide claim on one remote sync account; see [ProfileRegistry.claimSyncLease]. */29@Serializable30data class ProfileSyncLease(val key: String, val owner: ProfileId)31@Serializable32data class ProfileRegistrySnapshot(33 val version: Int = 1,34 val profiles: List<ProfileRecord> = listOf(ProfileRecord(ProfileId.Default, "Default")),35 val lastActive: ProfileId = ProfileId.Default,36 val retiredIds: List<ProfileId> = emptyList(),37 val syncLeases: List<ProfileSyncLease> = emptyList(),38) {39 val hasAdditionalProfiles: Boolean get() = profiles.any { it.id != ProfileId.Default && it.status == ProfileStatus.Ready }40 fun available(id: ProfileId): ProfileRecord? = profiles.singleOrNull { it.id == id && it.status == ProfileStatus.Ready }41}4243internal const val MaxProfileRegistryBytes = 262_14444internal const val MaxRetiredProfileIds = 409645internal const val MaxSyncLeaseKeyLength = 204846private val RegistryJson = Json { encodeDefaults = true }4748internal fun validateProfileRegistry(snapshot: ProfileRegistrySnapshot): ProfileRegistrySnapshot {49 require(snapshot.version == 1) { "Unsupported profile registry version" }50 require(snapshot.profiles.size in 1..64 && snapshot.retiredIds.size <= MaxRetiredProfileIds) { "Profile registry limit exceeded" }51 require(snapshot.profiles.map { it.id }.distinct().size == snapshot.profiles.size) { "Duplicate profile IDs" }52 require(snapshot.retiredIds.distinct().size == snapshot.retiredIds.size) { "Duplicate retired profile IDs" }53 require(snapshot.retiredIds.none { id -> id == ProfileId.Default || snapshot.profiles.any { it.id == id } }) { "Retired profile reused" }54 require(snapshot.profiles.singleOrNull { it.id == ProfileId.Default } == ProfileRecord(ProfileId.Default, "Default")) { "Default profile must remain permanent" }55 snapshot.profiles.forEach {56 require(it.name == profileName(it.name)) { "Invalid stored profile name" }57 require(it.exportedBackups.distinct().size == it.exportedBackups.size && it.exportedBackups.size <= 512) { "Invalid exported backup records" }58 it.exportedBackups.forEach { path -> require(path.isNotBlank() && path.length <= 4096 && path.none { c -> c.code < 32 }) { "Invalid export destination" } }59 }60 require(snapshot.profiles.map { it.name.lowercase() }.distinct().size == snapshot.profiles.size) { "Duplicate profile names" }61 require(snapshot.syncLeases.map { it.key }.distinct().size == snapshot.syncLeases.size &&62 snapshot.syncLeases.map { it.owner }.distinct().size == snapshot.syncLeases.size) { "Duplicate sync leases" }63 snapshot.syncLeases.forEach { lease ->64 require(lease.key.isNotEmpty() && lease.key.length <= MaxSyncLeaseKeyLength) { "Invalid sync lease" }65 require(snapshot.profiles.any { it.id == lease.owner && it.status != ProfileStatus.Deleting }) { "Sync lease owner is unavailable" }66 }67 require(snapshot.available(snapshot.lastActive) != null) { "Active profile is unavailable" }68 return snapshot69}70private fun profileName(name: String): String = name.trim().also { normalized ->71 require(normalized.isNotEmpty() && normalized.length <= 80 && normalized.none { it.code < 32 || it.code in 127..159 }) { "Invalid profile name" }72 normalized.encodeToByteArray(throwOnInvalidSequence = true)73}74internal fun encodeProfileRegistry(snapshot: ProfileRegistrySnapshot): String = RegistryJson.encodeToString(validateProfileRegistry(snapshot)).also {75 require(it.encodeToByteArray().size <= MaxProfileRegistryBytes) { "Profile registry limit exceeded" }76}77internal fun decodeProfileRegistry(raw: String): ProfileRegistrySnapshot {78 require(raw.encodeToByteArray().size <= MaxProfileRegistryBytes) { "Profile registry limit exceeded" }79 return validateProfileRegistry(RegistryJson.decodeFromString<ProfileRegistrySnapshot>(raw))80}8182/** CAS must be serialized across every process/tab sharing this device registry and atomic on disk. */83interface ProfileRegistryPersistence {84 suspend fun read(): String?85 suspend fun compareAndSet(expected: String?, replacement: String): Boolean86}87sealed interface ProfileRegistryState {88 data object Uninitialized : ProfileRegistryState89 data class Ready(val snapshot: ProfileRegistrySnapshot) : ProfileRegistryState90 data object Unavailable : ProfileRegistryState91}9293/** Metadata only. A session coordinator must provision/close/delete storage before committing stages. */94class ProfileRegistry(private val persistence: ProfileRegistryPersistence) {95 private val mutex = Mutex()96 private val _state = MutableStateFlow<ProfileRegistryState>(ProfileRegistryState.Uninitialized)97 val state = _state.asStateFlow()9899 suspend fun refresh(): ProfileRegistrySnapshot = edit { it }100 suspend fun beginCreate(name: String, id: ProfileId = ProfileId.random()): ProfileRegistrySnapshot = edit { old ->101 require(id != ProfileId.Default && id !in old.retiredIds && old.profiles.none { it.id == id }) { "Profile ID unavailable" }102 old.copy(profiles = old.profiles + ProfileRecord(id, profileName(name), ProfileStatus.Provisioning))103 }104 suspend fun markReady(id: ProfileId): ProfileRegistrySnapshot = edit { old ->105 val record = requireNotNull(old.profiles.singleOrNull { it.id == id }) { "Unknown profile" }106 require(record.status == ProfileStatus.Provisioning) { "Profile is not provisioning" }107 old.copy(profiles = old.profiles.map { if (it.id == id) it.copy(status = ProfileStatus.Ready) else it })108 }109 suspend fun rename(id: ProfileId, name: String): ProfileRegistrySnapshot = edit { old ->110 require(id != ProfileId.Default && old.available(id) != null) { "Profile cannot be renamed" }111 old.copy(profiles = old.profiles.map { if (it.id == id) it.copy(name = profileName(name)) else it })112 }113 /** Record a successful explicit export while the target lease is still held. Default is never deleted. */114 suspend fun recordExport(id: ProfileId, path: String): ProfileRegistrySnapshot = edit { old ->115 if (id == ProfileId.Default) old else {116 requireNotNull(old.available(id)) { "Export profile is unavailable" }117 old.copy(profiles = old.profiles.map {118 if (it.id == id) it.copy(exportedBackups = (it.exportedBackups + path).distinct()) else it119 })120 }121 }122123 /**124 * A profile has one sync preference, so it holds at most one lease: claiming replaces the owner's125 * previous lease. Idempotent for the holder; fails while another profile holds [key]. A conflict126 * leaves the registry untouched (and [state] Ready) instead of failing the edit.127 */128 suspend fun claimSyncLease(owner: ProfileId, key: String) {129 require(key.isNotEmpty() && key.length <= MaxSyncLeaseKeyLength) { "This sync account address is too long." }130 val next = edit { old ->131 val claimable = old.profiles.any { it.id == owner && it.status != ProfileStatus.Deleting } &&132 old.syncLeases.none { it.key == key && it.owner != owner }133 if (!claimable) old else old.copy(syncLeases = old.syncLeases.filterNot { it.owner == owner } + ProfileSyncLease(key, owner))134 }135 val held = next.syncLeases.singleOrNull { it.key == key }136 if (held?.owner == owner) return137 val name = next.profiles.singleOrNull { it.id == held?.owner }?.name138 throw IllegalStateException(139 if (name == null) "This profile can no longer connect sync accounts."140 else "This sync account is already connected to profile ‘$name’. Log out there first.",141 )142 }143 suspend fun releaseSyncLease(owner: ProfileId, key: String): ProfileRegistrySnapshot = edit { old ->144 old.copy(syncLeases = old.syncLeases.filterNot { it.owner == owner && it.key == key })145 }146 fun syncLeases(owner: ProfileId) = object : eu.friedcutlet.yokan.services.sync.SyncAccountLeases {147 override suspend fun claim(key: String) = claimSyncLease(owner, key)148 override suspend fun release(key: String) { releaseSyncLease(owner, key) }149 }150151 /** Call only after the replacement session is ready and the old session has been retired. */152 suspend fun recordActive(id: ProfileId): ProfileRegistrySnapshot = edit { old ->153 require(old.available(id) != null) { "Profile is unavailable" }154 old.copy(lastActive = id)155 }156 /** The coordinator must first safely switch away from an active extra profile. */157 suspend fun beginDelete(id: ProfileId): ProfileRegistrySnapshot = edit { old ->158 require(id != ProfileId.Default && id != old.lastActive) { "Switch away before deleting this profile" }159 require(old.profiles.any { it.id == id }) { "Unknown profile" }160 require(old.retiredIds.size < MaxRetiredProfileIds) { "Profile deletion capacity reached" }161 old.copy(162 profiles = old.profiles.map { if (it.id == id) it.copy(status = ProfileStatus.Deleting) else it },163 syncLeases = old.syncLeases.filterNot { it.owner == id },164 )165 }166 /** Commit only after app-owned data is gone; interrupted deletions remain recoverable. */167 suspend fun finishDelete(id: ProfileId): ProfileRegistrySnapshot = edit { old ->168 if (id in old.retiredIds) old else {169 require(old.profiles.any { it.id == id && it.status == ProfileStatus.Deleting }) { "Profile is not deleting" }170 old.copy(profiles = old.profiles.filterNot { it.id == id }, retiredIds = old.retiredIds + id)171 }172 }173174 private suspend fun edit(transform: (ProfileRegistrySnapshot) -> ProfileRegistrySnapshot): ProfileRegistrySnapshot = mutex.withLock {175 try {176 currentCoroutineContext().ensureActive()177 // Once a store commit begins, join its result before publishing metadata. This does not178 // make provisioning/switching irreversible: those are separate coordinator operations.179 withContext(NonCancellable) {180 repeat(16) {181 val raw = persistence.read()182 val old = raw?.let(::decodeProfileRegistry) ?: ProfileRegistrySnapshot()183 val next = validateProfileRegistry(transform(old))184 if ((raw != null && next == old) || persistence.compareAndSet(raw, encodeProfileRegistry(next))) {185 _state.update { ProfileRegistryState.Ready(next) }186 return@withContext next187 }188 }189 error("Profile registry changed repeatedly; retry")190 }191 } catch (error: CancellationException) {192 throw error193 } catch (error: Exception) {194 _state.update { ProfileRegistryState.Unavailable }195 throw error196 }197 }198}199200expect fun createPlatformProfileRegistry(): ProfileRegistry201202