Cotton code
92 lines · 3.5 KB · KotlinRaw
package com.cottondb.android.platformimport android.content.Contextimport com.cottondb.android.boot.VaultPublishReadimport com.cottondb.android.core.CottonCallingimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.sync.withLockimport kotlinx.coroutines.withContextimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.put/** The public vault key is optional during pairing, but every failure remains observable. */sealed interface VaultPublicationState {    data object Unknown : VaultPublicationState    data object Available : VaultPublicationState    data object Published : VaultPublicationState    data class Unavailable(val message: String) : VaultPublicationState}fun interface VaultPublicKeyProvider {    /** Never prompts. It may mint and cache a public key, or report a named platform failure. */    suspend fun publicKey(): String?}fun interface VaultPublicKeyPublisher {    suspend fun publish(publicKey: String)}/** * The one owner of the optional join fast path and the idempotent post-ready publication. * It retains a named unavailable state for Passwords instead of swallowing platform failures. */class VaultPublication(    private val provider: VaultPublicKeyProvider,    private val publisher: VaultPublicKeyPublisher,) {    private val _state = MutableStateFlow<VaultPublicationState>(VaultPublicationState.Unknown)    val state: StateFlow<VaultPublicationState> = _state.asStateFlow()    private val mutex = Mutex()    /** A join may continue without this optional field, but the reason remains in [state]. */    suspend fun keyForJoin(): String? = mutex.withLock { obtainKey() }    /** Runs only after Boot is ready, when the joined replica can accept `vault.publishKey`. */    suspend fun publishIfAvailable(): Boolean = mutex.withLock {        val key = obtainKey() ?: return@withLock false        try {            publisher.publish(key)            _state.value = VaultPublicationState.Published            true        } catch (failure: CancellationException) {            throw failure        } catch (failure: Throwable) {            _state.value = VaultPublicationState.Unavailable(                failure.message ?: "This device's vault public key could not be published.",            )            false        }    }    private suspend fun obtainKey(): String? = try {        provider.publicKey()?.also { _state.value = VaultPublicationState.Available }            ?: run {                _state.value = VaultPublicationState.Unavailable("This device has no vault public key yet.")                null            }    } catch (failure: CancellationException) {        throw failure    } catch (failure: Throwable) {        _state.value = VaultPublicationState.Unavailable(            failure.message ?: "This device's vault key is unavailable.",        )        null    }}class AndroidVaultPublicKeyProvider(private val context: Context) : VaultPublicKeyProvider {    override suspend fun publicKey(): String? = withContext(Dispatchers.IO) {        VaultKeyring(context).publicKey()    }}class CoreVaultPublicKeyPublisher(private val core: CottonCalling) : VaultPublicKeyPublisher {    override suspend fun publish(publicKey: String) {        VaultPublishRead.parse(core.call("vault.publishKey", buildJsonObject { put("publicKey", publicKey) }))    }}