Bound a reminder's wait for the store and read the shown reminders once per sync (#100)

This commit is contained in:
makiolaj committed 2026-11-20 18:00:01 +01:00
1 parent 96c94eeec3
commit 82bfda2533
8 files changed
+185 -46

No files matched your search

@@ -29,7 +29,7 @@ class BootReceiver : BroadcastReceiver() {
val pending = goAsync()
scope.launch {
try {
runCatching { scheduler.sync(rearmAll = true) }
runCatching { scheduler.syncFromBroadcast(rearmAll = true) }
} finally {
pending.finish()
}
@@ -51,7 +51,7 @@ class BootReceiver : BroadcastReceiver() {
try {
if (afterReboot) runCatching { snoozeScheduler.rearm() }
// Also restores the persistent reminders the reboot took down.
runCatching { scheduler.sync(afterReboot = afterReboot) }
runCatching { scheduler.syncFromBroadcast(afterReboot = afterReboot) }
} finally {
pending.finish()
}
@@ -15,6 +15,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import javax.inject.Inject
import kotlin.time.Instant
@@ -47,10 +48,12 @@ class DueReminderReceiver : BroadcastReceiver() {
}
val settings = settingsPrefs.settings.first()
if (!settings.remindersEnabled) return@launch
runCatching {
startupGate.awaitReady()
notifier.postIfOpen(dataSource, taskId, occurrence)
// Before the gate the store is a guess; past this wait the broadcast's time runs short.
if (withTimeoutOrNull(ReminderScheduler.BROADCAST_GATE_WAIT_MS) { startupGate.awaitReady() } == null) {
runCatching { DueReminderWorker.enqueue(context, taskId, occurrence) }
return@launch
}
runCatching { notifier.postIfOpen(dataSource, taskId, occurrence) }
} finally {
pending.finish()
}
@@ -142,6 +145,7 @@ internal suspend fun TaskNotifier.postIfOpen(
if (missingMeansGone()) forget(taskId, occurrence = occurrenceStart) else missed(taskId, occurrenceStart)
return
}
found(taskId, occurrenceStart)
if (task.isClosed || (exact && !task.isOccurrence(occurrenceStart)) || (restoring != null && task.postponedSince(restoring))) {
forget(taskId, occurrence = occurrenceStart)
if (task.taskId != taskId) forget(task.taskId, occurrence = occurrenceStart)
@@ -0,0 +1,53 @@
package de.jeanlucmakiola.agendula.data.reminders
import android.content.Context
import androidx.hilt.work.HiltWorker
import androidx.work.CoroutineWorker
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.agendula.data.tasks.StartupGate
import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
import kotlinx.coroutines.flow.first
/**
* Posts a reminder whose alarm went off before the store was known, once it
* is: [DueReminderReceiver] can only wait for that within its broadcast.
*/
@HiltWorker
class DueReminderWorker @AssistedInject constructor(
@Assisted context: Context,
@Assisted params: WorkerParameters,
private val dataSource: TasksDataSource,
private val notifier: TaskNotifier,
private val settingsPrefs: SettingsPrefs,
private val startupGate: StartupGate,
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
val taskId = inputData.getLong(KEY_TASK_ID, -1L).takeIf { it >= 0L } ?: return Result.success()
val occurrence = inputData.getLong(KEY_OCCURRENCE, ScheduledReminder.NO_OCCURRENCE)
startupGate.awaitReady()
if (!settingsPrefs.settings.first().remindersEnabled) return Result.success()
runCatching { notifier.postIfOpen(dataSource, taskId, occurrence) }
return Result.success()
}
companion object {
private const val KEY_TASK_ID = "task_id"
private const val KEY_OCCURRENCE = "occurrence"
fun enqueue(context: Context, taskId: Long, occurrence: Long) {
val request = OneTimeWorkRequestBuilder<DueReminderWorker>()
.setInputData(workDataOf(KEY_TASK_ID to taskId, KEY_OCCURRENCE to occurrence))
.build()
WorkManager.getInstance(context)
.enqueueUniqueWork("due-reminder-$taskId-$occurrence", ExistingWorkPolicy.KEEP, request)
}
}
}
@@ -78,6 +78,15 @@ class PersistentReminderStore @Inject constructor(
}
}
/** Notes that [taskId]'s occurrence was found again: an earlier miss no longer counts toward dropping it. */
suspend fun found(store: String, taskId: Long, occurrence: Long) {
val missing = { record: PersistentRecord ->
record.store == store && record.taskId == taskId && record.occurrence == occurrence && record.missingSince != 0L
}
if (all().none(missing)) return
edit { records -> records.map { if (missing(it)) it.copy(missingSince = 0L) else it } }
}
suspend fun clear() {
dataStore.edit { it.remove(KEY) }
}
@@ -44,7 +44,7 @@ class ProviderChangeReceiver : BroadcastReceiver() {
val pending = goAsync()
scope.launch {
try {
scheduler.sync()
scheduler.syncFromBroadcast()
} finally {
pending.finish()
}
@@ -8,6 +8,7 @@ import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
import de.jeanlucmakiola.agendula.data.tasks.StartupGate
import de.jeanlucmakiola.agendula.data.tasks.TaskQuery
import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
import de.jeanlucmakiola.agendula.domain.TaskReminder
@@ -16,6 +17,7 @@ import kotlinx.coroutines.flow.first
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import java.time.ZoneId
import javax.inject.Inject
import javax.inject.Singleton
@@ -37,6 +39,7 @@ class ReminderScheduler @Inject constructor(
private val providerResolver: ProviderResolver,
private val snoozeScheduler: ReminderSnoozeScheduler,
private val notifier: TaskNotifier,
private val startupGate: StartupGate,
@IoDispatcher private val io: CoroutineDispatcher,
) {
private val syncLock = Mutex()
@@ -50,8 +53,20 @@ class ReminderScheduler @Inject constructor(
* the whole truth, leaving the other's alarms armed but unrecorded — never
* cancelled, and firing against the wrong store's task ids.
*/
suspend fun sync(afterReboot: Boolean = false, rearmAll: Boolean = false) =
withContext(io) { syncLock.withLock { syncLocked(afterReboot, rearmAll) } }
suspend fun sync(afterReboot: Boolean = false, rearmAll: Boolean = false) = withContext(io) {
// Outside the lock, which a reminder going off takes to mark itself fired.
startupGate.awaitReady()
syncLock.withLock { syncLocked(afterReboot, rearmAll) }
}
/**
* [sync] from a broadcast, which gives up when the store isn't known within
* [BROADCAST_GATE_WAIT_MS]: the launch sync, once it is, covers the pass.
*/
suspend fun syncFromBroadcast(afterReboot: Boolean = false, rearmAll: Boolean = false) {
if (withTimeoutOrNull(BROADCAST_GATE_WAIT_MS) { startupGate.awaitReady() } == null) return
sync(afterReboot, rearmAll)
}
/** Record that [reminder] went off, so a later pass neither re-arms nor re-fires it. */
suspend fun markFired(reminder: ScheduledReminder) =
@@ -105,8 +120,9 @@ class ReminderScheduler @Inject constructor(
clearAll()
// Switched off, a reminder already up still goes when its task does.
if (readable) {
withdrawStale()
runCatching { notifier.restorePersistent(settings) }
val store = settingsPrefs.storeScope()
val shown = withdrawStale(store)
runCatching { notifier.restorePersistent(settings, store, shown) }
}
return
}
@@ -146,28 +162,31 @@ class ReminderScheduler @Inject constructor(
// exception escaped into BootReceiver's goAsync().
val armed = diff.arm.filter { schedule(it) }
store.replace(diff.keep + armed, fired = fired, exact = canExact)
withdrawStale()
if (runCatching { notifier.hasShownOrRemembered() }.getOrDefault(true)) {
val store = settingsPrefs.storeScope()
val shown = withdrawStale(store)
if (shown?.isNotEmpty() != false || runCatching { notifier.hasRemembered() }.getOrDefault(true)) {
// Catches a task moved to a list that is persistent differently.
runCatching { notifier.restyleActive(tasks.associate { it.taskId to it.listId }) }
runCatching { notifier.restorePersistent(settings) }
runCatching { notifier.restyleActive(tasks.associate { it.taskId to it.listId }, store) }
runCatching { notifier.restorePersistent(settings, store, shown) }
}
}
/**
* A reminder already on screen outlives its alarm: completing the task in
* the list, on a widget or on another device has to take it down too.
* Returns the tasks of [store]'s reminders still shown, null when unknown.
*/
private suspend fun withdrawStale() {
private suspend fun withdrawStale(store: String): Set<Long>? {
val missingMeansGone = notifier.missingMeansGone()
runCatching {
notifier.withdrawStale { taskId, occurrence ->
return runCatching {
notifier.withdrawStale(store) { taskId, occurrence ->
runCatching {
val current = dataSource.occurrence(taskId, occurrence ?: ScheduledReminder.NO_OCCURRENCE)
if (current != null && occurrence != null) notifier.found(taskId, occurrence, store)
reminderIsStale(occurrence, current, missingMeansGone)
}.getOrDefault(false)
}
}
}.getOrNull()
}
/** Whether the system still holds this alarm's PendingIntent. */
@@ -219,6 +238,11 @@ class ReminderScheduler @Inject constructor(
}
}
companion object {
/** How long a broadcast waits for the store to be known: well inside the ten seconds it gets. */
const val BROADCAST_GATE_WAIT_MS = 4_000L
}
private suspend fun clearAll() {
store.all().forEach { cancel(it) }
store.replace(emptySet(), fired = emptySet())
@@ -98,7 +98,7 @@ class TaskNotifier @Inject constructor(
if (!canPost()) return
// A restore yields to a reminder already up and to a Done or Snooze that dropped the record meanwhile.
if (restoring != null) {
if (postedReminders().any { it.taskId == task.taskId }) return
if (postedReminders(restoring.store).any { it.taskId == task.taskId }) return
records.find(restoring.store, restoring.taskId, restoring.occurrence) ?: return
}
post(task, settings, alert, postedAt, persistent)
@@ -189,9 +189,9 @@ class TaskNotifier @Inject constructor(
NotificationManagerCompat.from(context).cancel(taskId.toString(), NOTIFICATION_ID)
}
suspend fun cancel(taskId: Long) {
suspend fun cancel(taskId: Long, store: String? = null) {
dismiss(taskId)
forget(taskId)
forget(taskId, store)
}
/**
@@ -207,18 +207,25 @@ class TaskNotifier @Inject constructor(
suspend fun missed(taskId: Long, occurrence: Long) =
records.missed(settingsPrefs.storeScope(), taskId, occurrence, System.currentTimeMillis())
/** Notes that a remembered reminder's task was read, so an earlier miss no longer counts. */
suspend fun found(taskId: Long, occurrence: Long, store: String? = null) =
records.found(store ?: settingsPrefs.storeScope(), taskId, occurrence)
suspend fun isCurrentStore(store: String?): Boolean = store == settingsPrefs.storeScope()
/** Whether a task the store can't find is really gone; an external provider that fails a read finds nothing too. */
fun missingMeansGone(): Boolean = resolver.mode() == StorageMode.OWN
/**
* Takes down every posted reminder [isStale] says is done with — completed,
* cancelled or deleted since it went off, here or on another device. The
* Takes down every reminder of [store] posted that [isStale] says is done
* with — completed, cancelled or deleted since it went off, here or on
* another device — and returns the tasks of those still shown. The
* occurrence is null for a reminder posted before it was recorded.
*/
suspend fun withdrawStale(isStale: (taskId: Long, occurrenceStart: Long?) -> Boolean) {
postedReminders().filter { isStale(it.taskId, it.occurrence) }.forEach { cancel(it.taskId) }
suspend fun withdrawStale(store: String, isStale: suspend (taskId: Long, occurrenceStart: Long?) -> Boolean): Set<Long> {
val (stale, kept) = postedReminders(store).partition { isStale(it.taskId, it.occurrence) }
stale.forEach { cancel(it.taskId, store) }
return kept.mapTo(HashSet()) { it.taskId }
}
/**
@@ -228,34 +235,36 @@ class TaskNotifier @Inject constructor(
* its occurrence. Reads the settings under the lock, so the latest wins
* however fast they flip. Each goes by its list in [taskLists] when known
* (a sync passes the tasks it read, catching moves), else by the list it
* was posted in; one already styled right is left alone.
* was posted in; one already styled right is left alone. [store] is the
* current store's scope when the caller has it.
*/
suspend fun restyleActive(taskLists: Map<Long, Long> = emptyMap()) = postLock.withLock {
val shown = postedReminders().ifEmpty { return@withLock }
suspend fun restyleActive(taskLists: Map<Long, Long> = emptyMap(), store: String? = null) = postLock.withLock {
val shown = postedReminders(store ?: settingsPrefs.storeScope()).ifEmpty { return@withLock }
val settings = settingsPrefs.settings.first()
val store = settingsPrefs.claimStoreScope()
var claimed: String? = null
shown.forEach { posted ->
val occurrence = posted.occurrence ?: return@forEach
if (!posted.notification.extras.containsKey(EXTRA_DUE)) return@forEach
val listId = taskLists[posted.taskId] ?: posted.listId ?: return@forEach
val persistent = settings.persistentRemindersFor(listId)
if ((posted.notification.deleteIntent != null) == persistent) return@forEach
val scope = claimed ?: settingsPrefs.claimStoreScope().also { claimed = it }
val due = posted.notification.extras.getLong(EXTRA_DUE).takeIf { it != NO_DUE }
val notification = Notification.Builder.recoverBuilder(context, posted.notification)
.setAutoCancel(!persistent)
.setOnlyAlertOnce(true)
.setGroup(groupFor(posted.taskId, persistent, alert = true))
.setDeleteIntent(if (persistent) dismissedIntent(posted.taskId, occurrence, store) else null)
.setDeleteIntent(if (persistent) dismissedIntent(posted.taskId, occurrence, scope) else null)
.build()
manager.notify(posted.taskId.toString(), NOTIFICATION_ID, notification)
remember(store, posted.taskId, occurrence, due, posted.postedAt, persistent)
remember(scope, posted.taskId, occurrence, due, posted.postedAt, persistent)
}
}
/** Re-posts the shown reminders silently, so a changed snooze length or description shows on them. */
suspend fun refreshShown() {
startupGate.awaitReady()
postedReminders().forEach { posted ->
postedReminders(settingsPrefs.storeScope()).forEach { posted ->
val occurrence = posted.occurrence ?: return@forEach
runCatching {
postIfOpen(dataSource, posted.taskId, occurrence, alert = false, exact = true, postedAt = posted.postedAt)
@@ -283,26 +292,28 @@ class TaskNotifier @Inject constructor(
* Brings back, silently and at their old time, the persistent reminders no
* longer shown: taken down by a reboot or a force-stop, or by a swipe whose
* re-post couldn't read the task. Another store's or provider's are dropped:
* their ids name other tasks here.
* their ids name other tasks here. [store] and the tasks [shown] are the
* caller's when it has them.
*/
suspend fun restorePersistent(settings: Settings) {
if (records.all().isEmpty()) return
suspend fun restorePersistent(settings: Settings, store: String? = null, shown: Set<Long>? = null) {
val all = records.all().ifEmpty { return }
if (!settings.anyPersistentReminders) return records.clear()
// Before it, the store is a guess, and a wrong one would drop every record.
startupGate.awaitReady()
// A list deleted elsewhere leaves its setting behind; a read finding no list proves nothing.
val lists = runCatching { dataSource.taskLists().mapTo(HashSet()) { it.id } }.getOrNull()?.takeIf { it.isNotEmpty() }
if (lists != null && !settings.anyPersistentReminders(lists)) return records.clear()
val store = settingsPrefs.storeScope()
records.removeIf { it.store != store }
val scope = store ?: settingsPrefs.storeScope()
val here = all.filter { it.store == scope }
if (here.size != all.size) records.removeIf { it.store != scope }
// Nothing could be shown; trying anyway would re-read every record on each sync.
if (!canPost()) return
val shown = postedReminders().mapTo(HashSet()) { it.taskId }
records.all().filter { it.taskId !in shown }.forEach { runCatching { repost(it) } }
val up = shown ?: postedReminders(scope).mapTo(HashSet()) { it.taskId }
here.filter { it.taskId !in up }.forEach { runCatching { repost(it) } }
}
/** Whether a reminder is shown or a persistent one remembered; without either there is nothing to restyle or restore. */
suspend fun hasShownOrRemembered(): Boolean = postedReminders().isNotEmpty() || records.all().isNotEmpty()
/** Whether a persistent reminder is remembered. */
suspend fun hasRemembered(): Boolean = records.all().isNotEmpty()
private class Posted(
val taskId: Long,
@@ -313,13 +324,11 @@ class TaskNotifier @Inject constructor(
)
/**
* The current store's posted reminders; another store's or provider's ids
* name other tasks. One posted before the provider was recorded is the
* bare store's.
* [store]'s posted reminders; another store's or provider's ids name other
* tasks. One posted before the provider was recorded is the bare store's.
*/
private suspend fun postedReminders(): List<Posted> {
private fun postedReminders(store: String): List<Posted> {
val prefix = "$LIST_CHANNEL_PREFIX${channelStore}_"
val store = settingsPrefs.storeScope()
return manager.activeNotifications
.filter { it.id == NOTIFICATION_ID && it.notification.channelId?.startsWith(prefix) == true }
.filter { (it.notification.extras.getString(EXTRA_STORE) ?: channelStore) == store }
@@ -0,0 +1,40 @@
package de.jeanlucmakiola.agendula.data.reminders
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.emptyPreferences
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Test
class PersistentReminderStoreTest {
private class MemoryDataStore : DataStore<Preferences> {
override val data = MutableStateFlow(emptyPreferences())
override suspend fun updateData(transform: suspend (t: Preferences) -> Preferences) =
transform(data.value).also { data.value = it }
}
private val store = PersistentReminderStore(MemoryDataStore())
private val day = 24 * 60 * 60 * 1000L
@Test
fun `a task read again in between is not dropped for an old miss`() = runBlocking<Unit> {
store.put(PersistentRecord("own", 5, 0, due = null, postedAt = 1))
store.missed("own", 5, 0, now = 1_000)
store.found("own", 5, 0)
assertThat(store.all().single().missingSince).isEqualTo(0L)
store.missed("own", 5, 0, now = 1_000 + day)
assertThat(store.all().single().missingSince).isEqualTo(1_000 + day)
}
@Test
fun `a task missing all along is dropped after the grace`() = runBlocking<Unit> {
store.put(PersistentRecord("own", 5, 0, due = null, postedAt = 1))
store.missed("own", 5, 0, now = 1_000)
store.found("external", 5, 0)
store.missed("own", 5, 0, now = 1_000 + day)
assertThat(store.all()).isEmpty()
}
}