Cotton code
185 lines · 7.8 KB · KotlinRaw
package com.cottondb.android.platformimport android.content.Contextimport android.provider.Settingsimport android.util.AtomicFileimport com.cottondb.android.day.alarms.AlarmLedgerimport com.cottondb.android.day.alarms.AlarmLedgerEntryimport java.io.Fileimport java.util.concurrent.locks.ReentrantLockimport kotlin.concurrent.withLockimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonNullimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitiveimport kotlinx.serialization.json.booleanOrNullimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.jsonPrimitiveimport kotlinx.serialization.json.longOrNullimport kotlinx.serialization.json.put/** Delivery state is platform-local. Core owns only signature and absolute fire time. */data class AndroidAlarmLedgerEntry(    val signature: String,    val firesAt: Long?,    val delivered: Boolean,)data class AndroidAlarmLedgerSnapshot(    val bootCount: Int,    val entries: Map<String, AndroidAlarmLedgerEntry>,) {    fun coreLedger(): AlarmLedger = entries.mapValues { (_, entry) ->        AlarmLedgerEntry(entry.signature, entry.firesAt)    }    fun withCoreLedger(ledger: AlarmLedger): AndroidAlarmLedgerSnapshot = copy(        entries = ledger.mapValues { (id, entry) ->            AndroidAlarmLedgerEntry(                signature = entry.signature,                firesAt = entry.firesAt,                delivered = entries[id]?.let { old ->                    old.signature == entry.signature && old.firesAt == entry.firesAt && old.delivered                } == true,            )        },    )}sealed interface AlarmLedgerRead {    data object Missing : AlarmLedgerRead    data class Available(val snapshot: AndroidAlarmLedgerSnapshot) : AlarmLedgerRead    data class Unreadable(val message: String) : AlarmLedgerRead}sealed interface BootCountRead {    data class Available(val value: Int) : BootCountRead    data class Unreadable(val message: String) : BootCountRead}/** * A small no-backup ledger. All read-modify-write platform transactions share [lock]; a receiver * and an in-process reconcile therefore cannot accept the same fire token twice. Android has no * supported enumeration API for exact alarms, so this ledger is intentionally not presented as * proof that a PendingIntent is scheduled. */class AndroidAlarmLedgerStore(    context: Context,    private val file: File = File(context.noBackupFilesDir, "android-alarm-ledger.json"),    private val bootCount: () -> BootCountRead = { readBootCount(context) },) {    private val atomicFile = AtomicFile(file)    fun <T> exclusive(block: () -> T): T = lock.withLock(block)    fun read(): AlarmLedgerRead {        if (!file.exists() && !File(file.path + ".bak").exists()) return AlarmLedgerRead.Missing        return runCatching {            val text = atomicFile.openRead().bufferedReader(Charsets.UTF_8).use { reader -> reader.readText() }            require(text.length in 1..MAX_BYTES) { "Alarm ledger has an invalid size." }            parse(text)        }.fold(            onSuccess = { AlarmLedgerRead.Available(it) },            onFailure = { AlarmLedgerRead.Unreadable(it.message ?: "Alarm ledger could not be read.") },        )    }    fun currentBootCount(): BootCountRead = bootCount()    /** Atomic replace. A failed write leaves the prior ledger intact. */    fun write(snapshot: AndroidAlarmLedgerSnapshot): Result<Unit> = runCatching {        val parent = requireNotNull(file.parentFile) { "Alarm ledger has no parent directory." }        require(parent.exists() || parent.mkdirs()) { "Alarm ledger directory could not be created." }        val stream = atomicFile.startWrite()        try {            stream.write(serialize(snapshot).toByteArray(Charsets.UTF_8))            atomicFile.finishWrite(stream)        } catch (failure: Throwable) {            atomicFile.failWrite(stream)            throw failure        }    }    /**     * BOOT_COMPLETED and a foreground boot mismatch call this before reconciliation. Keep prior     * fire history: an already-fired one-shot must still disable rather than become a new alarm.     */    fun invalidateForCurrentBoot(): Result<AndroidAlarmLedgerSnapshot> = exclusive {        when (val generation = currentBootCount()) {            is BootCountRead.Available -> {                val previous = when (val read = read()) {                    AlarmLedgerRead.Missing -> AndroidAlarmLedgerSnapshot(generation.value, emptyMap())                    is AlarmLedgerRead.Available -> read.snapshot.copy(bootCount = generation.value)                    is AlarmLedgerRead.Unreadable -> return@exclusive Result.failure(IllegalStateException(read.message))                }                write(previous).map { previous }            }            is BootCountRead.Unreadable -> Result.failure(IllegalStateException(generation.message))        }    }    private fun parse(text: String): AndroidAlarmLedgerSnapshot {        val root = Json.parseToJsonElement(text).jsonObject        require(root["version"]?.jsonPrimitive?.content == VERSION.toString()) { "Alarm ledger version is unsupported." }        val boot = root["bootCount"]?.jsonPrimitive?.longOrNull            ?: error("Alarm ledger bootCount is missing.")        require(boot in 0..Int.MAX_VALUE) { "Alarm ledger bootCount is invalid." }        val rows = root["entries"]?.jsonObject ?: error("Alarm ledger entries are missing.")        return AndroidAlarmLedgerSnapshot(            bootCount = boot.toInt(),            entries = rows.mapValues { (id, value) ->                require(id.isNotBlank()) { "Alarm ledger entry id is blank." }                val row = value.jsonObject                val signature = row["signature"]?.jsonPrimitive?.content?.takeIf(String::isNotBlank)                    ?: error("Alarm ledger signature is missing.")                val firesAt = when (val item = row["firesAt"]) {                    JsonNull -> null                    is JsonPrimitive -> item.takeIf { !it.isString }?.longOrNull                        ?: error("Alarm ledger firesAt is invalid.")                    else -> error("Alarm ledger firesAt is invalid.")                }                AndroidAlarmLedgerEntry(                    signature = signature,                    firesAt = firesAt,                    delivered = row["delivered"]?.jsonPrimitive?.booleanOrNull                        ?: error("Alarm ledger delivered is missing."),                )            },        )    }    private fun serialize(snapshot: AndroidAlarmLedgerSnapshot): String = Json.encodeToString(        JsonObject.serializer(),        buildJsonObject {            put("version", VERSION)            put("bootCount", snapshot.bootCount)            put("entries", buildJsonObject {                snapshot.entries.toSortedMap().forEach { (id, entry) ->                    put(id, buildJsonObject {                        put("signature", entry.signature)                        if (entry.firesAt == null) {                            put("firesAt", JsonNull)                        } else {                            put("firesAt", entry.firesAt)                        }                        put("delivered", entry.delivered)                    })                }            })        },    )    private companion object {        const val VERSION = 1        const val MAX_BYTES = 256 * 1024L        val lock = ReentrantLock()        fun readBootCount(context: Context): BootCountRead = runCatching {            BootCountRead.Available(Settings.Global.getInt(context.contentResolver, Settings.Global.BOOT_COUNT))        }.getOrElse { failure ->            BootCountRead.Unreadable(failure.message ?: "Android boot generation is unavailable.")        }    }}