package com.cottondb.android.platform import android.content.Context import android.provider.Settings import android.util.AtomicFile import com.cottondb.android.day.alarms.AlarmLedger import com.cottondb.android.day.alarms.AlarmLedgerEntry import java.io.File import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.booleanOrNull import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.longOrNull import 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, ) { 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 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 = 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 = 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.") } } }