Cotton code
131 lines · 5.1 KB · KotlinRaw
package com.cottondb.android.platformimport android.app.AlarmManagerimport android.content.BroadcastReceiverimport android.content.Contextimport android.content.Intentimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.launchimport kotlinx.coroutines.withTimeout/** The runtime handoff for a platform schedule change. */internal interface ScheduleChangeBoundary {    /** Clears only requests Android loses at boot; alarm delivery history remains intact. */    suspend fun clearBootClaims()    /** Cancels every currently held local reminder before timezone-specific IDs are recomputed. */    suspend fun cancelRemindersForTimeZoneChange()    /** Cancels surviving exact-alarm PendingIntent identities without changing ledger history. */    suspend fun cancelAlarmClaimsForAccessChange()    /** Persists immediate and periodic reconciliation through the app-owned core runtime. */    suspend fun enqueueReconciliation()}/** * Runs the required platform cleanup before requesting the one runtime-owned reconciliation pass. * It deliberately propagates failures: retrying with stale held rows would leave duplicate alerts. */internal suspend fun handleScheduleChange(    action: String,    boundary: ScheduleChangeBoundary,) {    when (action) {        Intent.ACTION_BOOT_COMPLETED -> boundary.clearBootClaims()        Intent.ACTION_TIMEZONE_CHANGED -> boundary.cancelRemindersForTimeZoneChange()        AlarmManager.ACTION_SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED -> {            boundary.cancelAlarmClaimsForAccessChange()        }    }    boundary.enqueueReconciliation()}/** * Hands platform schedule changes to the runtime-owned reconciliation job. It never opens core. * A timezone change cancels all reminder requests first because identifiers carry a local stamp; * their absolute moments can change while their identifiers do not. An exact-alarm access change * similarly clears surviving PendingIntent identities before reconciliation observes them as held. */class ScheduleChangeReceiver : BroadcastReceiver() {    override fun onReceive(context: Context, intent: Intent) {        val action = intent.action ?: return        if (action !in SCHEDULE_CHANGE_ACTIONS) return        val pending = goAsync()        receiverScope.launch {            try {                withTimeout(RECEIVER_TIMEOUT_MILLIS) {                    handleScheduleChange(action, AndroidScheduleChangeBoundary(context.applicationContext))                }            } catch (failure: Throwable) {                AndroidReminderRuntime.report(                    "Scheduled notifications could not be reconciled after a system schedule change.",                    failure,                )            } finally {                pending.finish()            }        }    }    companion object {        private const val RECEIVER_TIMEOUT_MILLIS = 8_000L        private val receiverScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)        private val SCHEDULE_CHANGE_ACTIONS = setOf(            Intent.ACTION_BOOT_COMPLETED,            Intent.ACTION_TIME_CHANGED,            Intent.ACTION_TIMEZONE_CHANGED,            Intent.ACTION_MY_PACKAGE_REPLACED,            AlarmManager.ACTION_SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED,        )    }}private class AndroidScheduleChangeBoundary(    private val context: Context,) : ScheduleChangeBoundary {    private val reminders = AndroidReminderCentre(context)    override suspend fun clearBootClaims() {        check(reminders.clearAfterBoot()) {            "The reminder ledger could not be cleared after boot."        }        // This advances the boot generation but preserves signature, fire time and delivery state.        AndroidAlarmLedgerStore(context).invalidateForCurrentBoot().getOrThrow()    }    override suspend fun cancelRemindersForTimeZoneChange() {        val held = reminders.heldIdentifiers()        reminders.cancel(held)    }    override suspend fun cancelAlarmClaimsForAccessChange() {        val ledger = AndroidAlarmLedgerStore(context)        ledger.exclusive {            when (val read = ledger.read()) {                AlarmLedgerRead.Missing -> Unit                is AlarmLedgerRead.Available -> {                    val platform = AndroidExactAlarmPlatform(context)                    read.snapshot.entries.forEach { (id, entry) ->                        // An entry without a fire time is historical only; it has no PendingIntent.                        if (entry.firesAt != null) {                            platform.cancel(                                com.cottondb.android.day.alarms.androidAlarmKey(id),                                entry,                            )                        }                    }                }                is AlarmLedgerRead.Unreadable -> error(read.message)            }        }    }    override suspend fun enqueueReconciliation() {        AlarmDeliveryJob.ensurePeriodic(context)        AlarmDeliveryJob.enqueue(context)    }}