Cotton code
93 lines · 4.5 KB · KotlinRaw
package com.cottondb.android.platformimport android.content.BroadcastReceiverimport android.content.Contextimport android.content.Intentimport android.os.Buildimport com.cottondb.android.day.alarms.ANDROID_ALARM_KEY_PREFIXimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.launch/** * Validates one versioned AlarmManager fire against the durable ledger before playback begins. * The receiver never opens a second Cotton core. Its persisted job is the sole handoff to the * existing runtime, which disables fired one-shots or asks the scheduler to arm a repeat. */class AndroidAlarmReceiver : BroadcastReceiver() {    override fun onReceive(context: Context, intent: Intent) {        if (intent.action != AndroidExactAlarmPlatform.ACTION_FIRE) return        val pending = goAsync()        CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {            try {                val delivery = validateAlarmDelivery(AndroidAlarmLedgerStore(context.applicationContext), intent) ?: return@launch                runCatching {                    val service = AndroidAlarmService.startIntent(                        context,                        AlarmAlert(delivery.id, delivery.label, delivery.sound),                    )                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(service)                    else context.startService(service)                }.onFailure { failure ->                    reportAlarmDeliveryFailure(context, failure.message ?: "Cotton could not start this alarm.")                }                // JobScheduler persists this handoff across process death; do not call AppRuntime here.                runCatching { AlarmDeliveryJob.enqueue(context, delivery) }.onFailure { failure ->                    reportAlarmDeliveryFailure(context, failure.message ?: "Cotton could not reconcile this alarm.")                }            } catch (failure: Exception) {                reportAlarmDeliveryFailure(context, failure.message ?: "Cotton could not deliver this alarm.")            } finally {                pending.finish()            }        }    }}/** Visible to Android tests: validates the versioned payload and marks a delivery exactly once. */internal fun validateAlarmDelivery(store: AndroidAlarmLedgerStore, intent: Intent): AlarmDelivery? {    val key = intent.getStringExtra(AndroidExactAlarmPlatform.EXTRA_KEY) ?: return null    val fireToken = intent.getStringExtra(AndroidExactAlarmPlatform.EXTRA_FIRE_TOKEN) ?: return null    val firesAt = intent.getLongExtra(AndroidExactAlarmPlatform.EXTRA_FIRES_AT, Long.MIN_VALUE)    if (!key.startsWith(ANDROID_ALARM_KEY_PREFIX) || firesAt <= 0L) return null    val uri = intent.data ?: return null    if (uri.scheme != "cotton" || uri.authority != "alarm" || uri.pathSegments != listOf(key, fireToken)) return null    val id = key.removePrefix(ANDROID_ALARM_KEY_PREFIX).takeIf(String::isNotBlank) ?: return null    return store.exclusive {        val boot = (store.currentBootCount() as? BootCountRead.Available)?.value ?: return@exclusive null        val snapshot = (store.read() as? AlarmLedgerRead.Available)?.snapshot ?: return@exclusive null        if (snapshot.bootCount != boot) return@exclusive null        val entry = snapshot.entries[id] ?: return@exclusive null        if (entry.delivered || entry.firesAt != firesAt || alarmFireToken(entry.signature, firesAt) != fireToken) return@exclusive null        val changed = snapshot.copy(entries = snapshot.entries + (id to entry.copy(delivered = true)))        if (store.write(changed).isFailure) return@exclusive null        AlarmDelivery(            id = id,            key = key,            signature = entry.signature,            firesAt = firesAt,            label = intent.getStringExtra(AndroidExactAlarmPlatform.EXTRA_LABEL).orEmpty(),            sound = intent.getBooleanExtra(AndroidExactAlarmPlatform.EXTRA_SOUND, true),        )    }}data class AlarmDelivery(    val id: String,    val key: String,    val signature: String,    val firesAt: Long,    val label: String,    val sound: Boolean,)/** Root exposes this through CottonApplication so a receiver failure is visible, never discarded. */interface AlarmDeliveryFailureReporter {    fun reportAlarmDeliveryFailure(message: String)}private fun reportAlarmDeliveryFailure(context: Context, message: String) {    (context.applicationContext as? AlarmDeliveryFailureReporter)?.reportAlarmDeliveryFailure(message)}