Cotton code
255 lines · 10.5 KB · KotlinRaw
package com.cottondb.android.platformimport android.content.Intentimport android.net.Uriimport androidx.test.ext.junit.runners.AndroidJUnit4import androidx.test.platform.app.InstrumentationRegistryimport com.cottondb.android.day.alarms.Alarmimport com.cottondb.android.reminders.NotificationPermissionimport com.cottondb.android.reminders.NotificationPrefsimport java.io.Fileimport java.time.Clockimport java.time.Instantimport java.time.ZoneIdimport java.time.ZoneOffsetimport java.util.UUIDimport org.junit.Afterimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalseimport org.junit.Assert.assertNotNullimport org.junit.Assert.assertNullimport org.junit.Assert.assertTrueimport org.junit.Testimport org.junit.runner.RunWith@RunWith(AndroidJUnit4::class)class AndroidAlarmSchedulerTest {    private val context = InstrumentationRegistry.getInstrumentation().targetContext    private val directory = File(context.noBackupFilesDir, "alarm-platform-test-${UUID.randomUUID()}")    private val file = File(directory, "ledger.json")    private val clock = Clock.fixed(Instant.parse("2026-09-21T06:00:00Z"), ZoneOffset.UTC)    @After    fun removeFiles() {        directory.deleteRecursively()    }    @Test    fun confirmedDeliverySurvivesClockRollbackAndRevocationThenRetiresItsPendingIdentity() {        val store = store(boot = 71)        val platform = FakePlatform()        val alarm = repeatingAlarm().copy(repeatDays = emptyList())        val signature = com.cottondb.android.day.alarms.alarmSignature(alarm, ZoneId.of("UTC"))        store.write(AndroidAlarmLedgerSnapshot(71, mapOf(            alarm.id to AndroidAlarmLedgerEntry(signature, clock.instant().plusSeconds(3600).toEpochMilli(), true),        ))).getOrThrow()        val scheduler = AndroidAlarmScheduler(store, platform, clock)        val delivered = scheduler.reconcile(listOf(alarm), ZoneId.of("UTC"), NotificationPrefs(), NotificationPermission.Denied)        assertEquals(AlarmScheduleOutcome.Applied(0, 0, listOf(alarm.id)), delivered)        assertTrue(platform.scheduled.isEmpty())        assertTrue((store.read() as AlarmLedgerRead.Available).snapshot.entries.getValue(alarm.id).delivered)        val retired = scheduler.reconcile(listOf(alarm.copy(enabled = false)), ZoneId.of("UTC"), NotificationPrefs(), NotificationPermission.Denied)        assertEquals(AlarmScheduleOutcome.Applied(0, 1, emptyList()), retired)        assertEquals(listOf("cotton:alarm:${alarm.id}"), platform.cancelled)        assertTrue((store.read() as AlarmLedgerRead.Available).snapshot.entries.isEmpty())    }    @Test    fun ledgerRoundTripPreservesNumericAndExplicitNullFireTimes() {        val store = store(boot = 71)        val firesAt = Instant.parse("2026-09-21T07:00:00Z").toEpochMilli()        store.write(            AndroidAlarmLedgerSnapshot(                bootCount = 71,                entries = mapOf(                    "future" to AndroidAlarmLedgerEntry("future-signature", firesAt, delivered = false),                    "unscheduled" to AndroidAlarmLedgerEntry("unscheduled-signature", null, delivered = true),                ),            ),        ).getOrThrow()        val entries = (store.read() as AlarmLedgerRead.Available).snapshot.entries        assertEquals(firesAt, entries.getValue("future").firesAt)        assertNull(entries.getValue("unscheduled").firesAt)    }    @Test    fun acceptedSchedulePersistsOnlyTheAcceptedAbsoluteFire() {        val platform = FakePlatform()        val store = store(boot = 71)        val outcome = AndroidAlarmScheduler(store, platform, clock).reconcile(            alarms = listOf(repeatingAlarm()),            zoneId = ZoneId.of("UTC"),            prefs = NotificationPrefs(),            notificationPermission = NotificationPermission.Granted,        )        assertEquals(AlarmScheduleOutcome.Applied(scheduled = 1, cancelled = 0, firedOnce = emptyList()), outcome)        val schedule = platform.scheduled.single()        assertEquals(Instant.parse("2026-09-21T07:00:00Z"), schedule.nextOccurrence)        val saved = (store.read() as AlarmLedgerRead.Available).snapshot.entries.getValue("alarm-1")        assertEquals(schedule.signature, saved.signature)        assertEquals(schedule.nextOccurrence.toEpochMilli(), saved.firesAt)        assertFalse(saved.delivered)    }    @Test    fun rejectedAlarmManagerCallIsNotEnteredInLedger() {        val platform = FakePlatform(failSchedules = true)        val store = store(boot = 71)        val outcome = AndroidAlarmScheduler(store, platform, clock).reconcile(            listOf(repeatingAlarm()), ZoneId.of("UTC"), NotificationPrefs(), NotificationPermission.Granted,        )        assertTrue(outcome is AlarmScheduleOutcome.Partial)        assertEquals(1, (outcome as AlarmScheduleOutcome.Partial).failed)        assertTrue((store.read() as AlarmLedgerRead.Available).snapshot.entries.isEmpty())    }    @Test    fun unreadableLedgerNeverPretendsThePlatformHoldsNothing() {        directory.mkdirs()        file.writeText("not json")        val platform = FakePlatform()        val outcome = AndroidAlarmScheduler(store(boot = 71), platform, clock).reconcile(            listOf(repeatingAlarm()), ZoneId.of("UTC"), NotificationPrefs(), NotificationPermission.Granted,        )        assertTrue(outcome is AlarmScheduleOutcome.Refused)        assertTrue(platform.scheduled.isEmpty())        assertTrue(platform.cancelled.isEmpty())    }    @Test    fun rebootGenerationMismatchIsInvalidatedBeforeForegroundReconciliation() {        val store = store(boot = 72)        store.write(AndroidAlarmLedgerSnapshot(bootCount = 71, entries = emptyMap())).getOrThrow()        val platform = FakePlatform()        val applied = AndroidAlarmScheduler(store, platform, clock).reconcile(            listOf(repeatingAlarm()), ZoneId.of("UTC"), NotificationPrefs(), NotificationPermission.Granted,        )        assertTrue(applied is AlarmScheduleOutcome.Applied)        assertEquals(1, platform.scheduled.size)        assertEquals(72, ((store.read() as AlarmLedgerRead.Available).snapshot.bootCount))    }    @Test    fun bootInvalidationPreservesFiredOneShotHistory() {        val store = store(boot = 72)        val firesAt = Instant.parse("2026-09-20T07:00:00Z").toEpochMilli()        store.write(            AndroidAlarmLedgerSnapshot(                bootCount = 71,                entries = mapOf("alarm-1" to AndroidAlarmLedgerEntry("one-shot", firesAt, delivered = true)),            ),        ).getOrThrow()        val retained = store.invalidateForCurrentBoot().getOrThrow()        assertEquals(72, retained.bootCount)        assertEquals(firesAt, retained.entries.getValue("alarm-1").firesAt)        assertTrue(retained.entries.getValue("alarm-1").delivered)    }    @Test    fun foregroundBootMismatchReportsPriorOneShotForDurableDisableInsteadOfRearmingIt() {        val store = store(boot = 72)        val oneShot = repeatingAlarm().copy(repeatDays = emptyList())        val firesAt = Instant.parse("2026-09-20T07:00:00Z").toEpochMilli()        store.write(            AndroidAlarmLedgerSnapshot(                bootCount = 71,                entries = mapOf(                    oneShot.id to AndroidAlarmLedgerEntry(                        com.cottondb.android.day.alarms.alarmSignature(oneShot, ZoneId.of("UTC")),                        firesAt,                        delivered = true,                    ),                ),            ),        ).getOrThrow()        val outcome = AndroidAlarmScheduler(store, FakePlatform(), clock).reconcile(            listOf(oneShot), ZoneId.of("UTC"), NotificationPrefs(), NotificationPermission.Granted,        )        assertEquals(AlarmScheduleOutcome.Applied(scheduled = 0, cancelled = 0, firedOnce = listOf("alarm-1")), outcome)    }    @Test    fun staleVersionedFireIsRefusedAndValidFireIsMarkedOnceBeforeWork() {        val store = store(boot = 71)        val firesAt = Instant.parse("2026-09-21T07:00:00Z").toEpochMilli()        store.write(            AndroidAlarmLedgerSnapshot(                bootCount = 71,                entries = mapOf("alarm-1" to AndroidAlarmLedgerEntry("new-signature", firesAt, delivered = false)),            ),        ).getOrThrow()        assertNull(validateAlarmDelivery(store, fireIntent("old-signature", firesAt)))        val accepted = validateAlarmDelivery(store, fireIntent("new-signature", firesAt))        assertNotNull(accepted)        assertNull(validateAlarmDelivery(store, fireIntent("new-signature", firesAt)))        assertTrue((store.read() as AlarmLedgerRead.Available).snapshot.entries.getValue("alarm-1").delivered)    }    private fun store(boot: Int) = AndroidAlarmLedgerStore(        context = context,        file = file,        bootCount = { BootCountRead.Available(boot) },    )    private fun repeatingAlarm() = Alarm(        id = "alarm-1",        label = "Wake up",        hour = 7,        minute = 0,        repeatDays = listOf(1),        enabled = true,        sound = true,        createdAt = null,        updatedAt = null,    )    private fun fireIntent(signature: String, firesAt: Long): Intent {        val key = "cotton:alarm:alarm-1"        val token = alarmFireToken(signature, firesAt)        return Intent(AndroidExactAlarmPlatform.ACTION_FIRE)            .setData(Uri.Builder().scheme("cotton").authority("alarm").appendPath(key).appendPath(token).build())            .putExtra(AndroidExactAlarmPlatform.EXTRA_KEY, key)            .putExtra(AndroidExactAlarmPlatform.EXTRA_FIRE_TOKEN, token)            .putExtra(AndroidExactAlarmPlatform.EXTRA_FIRES_AT, firesAt)            .putExtra(AndroidExactAlarmPlatform.EXTRA_LABEL, "Wake up")            .putExtra(AndroidExactAlarmPlatform.EXTRA_SOUND, true)    }    private class FakePlatform(        private val failSchedules: Boolean = false,    ) : ExactAlarmPlatform {        val scheduled = mutableListOf<com.cottondb.android.day.alarms.AlarmSchedule>()        val cancelled = mutableListOf<String>()        private val held = mutableSetOf<String>()        override fun exactAlarmAllowed(): Boolean = true        override fun held(key: String, entry: AndroidAlarmLedgerEntry): Boolean = key in held        override fun schedule(schedule: com.cottondb.android.day.alarms.AlarmSchedule): Boolean {            if (failSchedules) return false            scheduled += schedule            held += schedule.key            return true        }        override fun cancel(key: String, entry: AndroidAlarmLedgerEntry?) {            cancelled += key            held -= key        }    }}