workers: guard every doWork against crashing the work loop
- Commit
7bb7ea540746541ce7b774d67c25d0842c5f8c00- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-20 19:00 UTC (15 days ago)
- Parents
df45138
Eight CoroutineWorkers let exceptions escape doWork (flashcards review reminders, contacts calendar sync, music sync, shop order tracking, email snooze, library model downloads, library daily puzzle reminders, maps overlay fetch). An escaped throw fails the WorkManager loop with no Result, so a transient IO hiccup could kill a periodic chain instead of backing off. Each now follows the everysync pattern split by failure class: CancellationException rethrows, IOException (plus provider SQLException in contacts) retries within the worker's existing backoff/attempt caps, everything else fails cleanly with a log. The music worker's self re-enqueue now only runs on success - WorkManager owns the rerun. Scheduling and triggers unchanged. securemail BootReceiver now uses goAsync like its sibling boot receivers instead of fire-and-forget on the main thread. Verified: compile for all touched modules; flashcards, email, downloadservice and a securemail service test suite pass.
Diff
contacts/src/main/java/com/vayunmathur/contacts/sync/CalendarWorker.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/sync/CalendarWorker.kt b/contacts/src/main/java/com/vayunmathur/contacts/sync/CalendarWorker.ktindex f1b47348fc..6d839227d7 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/sync/CalendarWorker.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/sync/CalendarWorker.kt@@ -8,24 +8,46 @@ import androidx.work.NetworkType import androidx.work.PeriodicWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkerParameters+import com.vayunmathur.library.log.Log import com.vayunmathur.library.util.DataStoreUtils+import java.io.IOException import java.util.concurrent.TimeUnit+import kotlinx.coroutines.CancellationException /** Periodic worker that re-syncs contact events to the calendar while calendar sync is enabled. */ class CalendarWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {+ // WorkManager contract (everysync pattern): return a Result, never throw.+ // Cancellation rethrows; transient provider/DataStore I/O retries with+ // WorkManager backoff; a revoked permission or bad data fails this run —+ // the hourly period runs again with whatever state exists then.+ @Suppress("TooGenericExceptionCaught") override suspend fun doWork(): Result {- val dataStore = DataStoreUtils.getInstance(applicationContext)- val isEnabled = dataStore.getBoolean("calendar_sync_enabled", false)- - if (isEnabled) {- CalendarSyncHelper.syncAll(applicationContext)+ return try {+ val dataStore = DataStoreUtils.getInstance(applicationContext)+ val isEnabled = dataStore.getBoolean("calendar_sync_enabled", false)++ if (isEnabled) {+ CalendarSyncHelper.syncAll(applicationContext)+ }++ Result.success()+ } catch (e: CancellationException) {+ throw e+ } catch (e: IOException) {+ Log.error(TAG, "calendar sync failed; will retry", e)+ Result.retry()+ } catch (e: android.database.SQLException) {+ Log.error(TAG, "calendar sync failed; will retry", e)+ Result.retry()+ } catch (e: Exception) {+ Log.error(TAG, "calendar sync failed", e)+ Result.failure() }- - return Result.success() } /** Unique work name and scheduling entry points for [CalendarWorker]. */ companion object {+ private const val TAG = "CalendarWorker" private const val WORK_NAME = "CalendarSyncWorker" fun schedule(context: Context) {
email/src/main/java/com/vayunmathur/email/data/SnoozeWorker.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/SnoozeWorker.kt b/email/src/main/java/com/vayunmathur/email/data/SnoozeWorker.ktindex 517d80811a..dd627bfa9a 100644--- a/email/src/main/java/com/vayunmathur/email/data/SnoozeWorker.kt+++ b/email/src/main/java/com/vayunmathur/email/data/SnoozeWorker.kt@@ -5,7 +5,10 @@ import androidx.work.CoroutineWorker import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkerParameters+import com.vayunmathur.library.log.Log+import java.io.IOException import java.util.concurrent.TimeUnit+import kotlinx.coroutines.CancellationException /** * Wakes snoozed messages whose time has arrived: clears their `snoozedUntil`@@ -17,14 +20,30 @@ class SnoozeWorker( params: WorkerParameters, ) : CoroutineWorker(appContext, params) { + // WorkManager contract (everysync pattern): return a Result, never throw.+ // Cancellation rethrows; transient DB I/O retries (this one-shot would+ // otherwise lose the wake-up); anything else fails rather than retrying+ // a corrupt row set forever.+ @Suppress("TooGenericExceptionCaught") override suspend fun doWork(): Result {- val dao = EmailRepository.get(applicationContext).getDatabase().messageDao()- dao.wakeDueSnoozed(System.currentTimeMillis())- return Result.success()+ return try {+ val dao = EmailRepository.get(applicationContext).getDatabase().messageDao()+ dao.wakeDueSnoozed(System.currentTimeMillis())+ Result.success()+ } catch (e: CancellationException) {+ throw e+ } catch (e: IOException) {+ Log.error(TAG, "snooze wake-up failed; will retry", e)+ Result.retry()+ } catch (e: Exception) {+ Log.error(TAG, "snooze wake-up failed", e)+ Result.failure()+ } } /** Schedules the one-shot worker that un-snoozes messages at the requested time. */ companion object {+ private const val TAG = "SnoozeWorker" fun scheduleNext(context: Context, atMillis: Long) { val delay = (atMillis - System.currentTimeMillis()).coerceAtLeast(1_000L) val request = OneTimeWorkRequestBuilder<SnoozeWorker>()
flashcards/src/main/java/com/vayunmathur/flashcards/platform/ReviewReminderWorker.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/platform/ReviewReminderWorker.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/platform/ReviewReminderWorker.ktindex c3c9fe42d9..160d5c15c3 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/platform/ReviewReminderWorker.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/platform/ReviewReminderWorker.kt@@ -19,7 +19,9 @@ import com.vayunmathur.flashcards.R import com.vayunmathur.flashcards.data.CardState import com.vayunmathur.flashcards.data.FlashcardsRepository import com.vayunmathur.flashcards.data.getAllCardsImpl+import com.vayunmathur.library.log.Log import com.vayunmathur.library.util.ensureNotificationChannel+import java.io.IOException import java.util.Calendar import java.util.concurrent.TimeUnit @@ -63,15 +65,29 @@ class ReviewReminderWorker( params: WorkerParameters, ) : CoroutineWorker(appContext, params) { + // WorkManager contract (everysync pattern): return a Result, never throw.+ // Cancellation rethrows, transient I/O retries with WorkManager backoff,+ // and anything else fails this run — the daily period runs again tomorrow.+ @Suppress("TooGenericExceptionCaught") override suspend fun doWork(): Result {- val now = System.currentTimeMillis()- val repository = FlashcardsRepository.get(applicationContext)- val cards = repository.getAllCardsImpl()- val due = cards.count {- !it.isSuspended && ((it.state != CardState.NEW && it.dueDate <= now) || it.state == CardState.NEW)+ return try {+ val now = System.currentTimeMillis()+ val repository = FlashcardsRepository.get(applicationContext)+ val cards = repository.getAllCardsImpl()+ val due = cards.count {+ !it.isSuspended && ((it.state != CardState.NEW && it.dueDate <= now) || it.state == CardState.NEW)+ }+ if (due > 0) notify(due)+ Result.success()+ } catch (e: kotlinx.coroutines.CancellationException) {+ throw e+ } catch (e: IOException) {+ Log.error(TAG, "review reminder failed; will retry", e)+ Result.retry()+ } catch (e: Exception) {+ Log.error(TAG, "review reminder failed", e)+ Result.failure() }- if (due > 0) notify(due)- return Result.success() } private fun notify(due: Int) {@@ -107,6 +123,7 @@ class ReviewReminderWorker( /** Notification id for the review reminder. */ companion object {+ private const val TAG = "ReviewReminderWorker" private const val REMINDER_NOTIFICATION_ID = 4201 } }
library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.kt
diff --git a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.kt b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.ktindex 09f5bf34c6..748be0b967 100644--- a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.kt+++ b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.kt@@ -35,6 +35,7 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.work.WorkInfo import androidx.work.WorkManager@@ -666,7 +667,8 @@ fun FileProgressItem( label, style = MaterialTheme.typography.titleSmall, modifier = Modifier.weight(1.0f),- maxLines = 1+ maxLines = 1,+ overflow = TextOverflow.Ellipsis ) if (!isDone && progress > 0) {
library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.kt
diff --git a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.kt b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.ktindex e15c578784..4d1eec2577 100644--- a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.kt+++ b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.kt@@ -10,9 +10,12 @@ import androidx.work.NetworkType import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkerParameters+import com.vayunmathur.library.log.Log import com.vayunmathur.library.util.DataStoreUtils import java.io.File+import java.io.IOException import java.util.concurrent.TimeUnit+import kotlinx.coroutines.CancellationException /** * Runs the model download outside any composition.@@ -31,23 +34,39 @@ import java.util.concurrent.TimeUnit class ModelDownloadWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) { + // WorkManager contract (everysync pattern): return a Result, never throw.+ // Cancellation rethrows (runDownloadsCore keeps the `.part` for resume);+ // a thrown transient I/O error takes the same capped-retry path as a+ // `false` return below, and anything else fails at once.+ @Suppress("TooGenericExceptionCaught") override suspend fun doWork(): Result { val specs = readSpecs(inputData) if (specs.isEmpty()) return Result.failure() val targetDir = inputData.getString(KEY_TARGET_DIR)?.let(::File) val ds = DataStoreUtils.getInstance(applicationContext)- return when {- runDownloadsCore(applicationContext, ds, specs, targetDir) -> Result.success()- // Keep retrying transient problems (flaky network, mirror hiccup) but eventually stop so- // the screen can offer a retry rather than backing off forever.- runAttemptCount + 1 >= MAX_RUN_ATTEMPTS -> Result.failure()- else -> Result.retry()+ return try {+ when {+ runDownloadsCore(applicationContext, ds, specs, targetDir) -> Result.success()+ // Keep retrying transient problems (flaky network, mirror hiccup) but eventually stop so+ // the screen can offer a retry rather than backing off forever.+ runAttemptCount + 1 >= MAX_RUN_ATTEMPTS -> Result.failure()+ else -> Result.retry()+ }+ } catch (e: CancellationException) {+ throw e+ } catch (e: IOException) {+ Log.error(TAG, "model download failed; will retry", e)+ if (runAttemptCount + 1 >= MAX_RUN_ATTEMPTS) Result.failure() else Result.retry()+ } catch (e: Exception) {+ Log.error(TAG, "model download failed", e)+ Result.failure() } } /** WorkManager input keys, enqueue entry points and spec decoding for [ModelDownloadWorker]. */ companion object {+ private const val TAG = "ModelDownloadWorker" private const val KEY_URLS = "urls" private const val KEY_FILE_NAMES = "fileNames" private const val KEY_DESCRIPTIONS = "descriptions"
library/work/src/main/java/com/vayunmathur/library/work/DailyPuzzleReminder.kt
diff --git a/library/work/src/main/java/com/vayunmathur/library/work/DailyPuzzleReminder.kt b/library/work/src/main/java/com/vayunmathur/library/work/DailyPuzzleReminder.ktindex a216aa6538..b0a52605fe 100644--- a/library/work/src/main/java/com/vayunmathur/library/work/DailyPuzzleReminder.kt+++ b/library/work/src/main/java/com/vayunmathur/library/work/DailyPuzzleReminder.kt@@ -18,7 +18,10 @@ import androidx.work.WorkManager import androidx.work.WorkerParameters import androidx.work.workDataOf import com.vayunmathur.library.R+import com.vayunmathur.library.log.Log import com.vayunmathur.library.util.DailyChallengeStore+import java.io.IOException+import kotlinx.coroutines.CancellationException import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.ensureNotificationChannel import kotlinx.coroutines.flow.Flow@@ -126,14 +129,33 @@ class DailyPuzzleReminderWorker( params: WorkerParameters, ) : CoroutineWorker(appContext, params) { + // WorkManager contract (everysync pattern): return a Result, never throw.+ // Cancellation rethrows; transient DataStore I/O retries with WorkManager+ // backoff; anything else fails this run — the daily period nudges tomorrow.+ @Suppress("TooGenericExceptionCaught") override suspend fun doWork(): Result {- val keyPrefix = DailyPuzzleReminder.keyPrefixOf(inputData) ?: return Result.success()- val store = DailyChallengeStore(applicationContext, keyPrefix)- // Games only record the day once every puzzle in it is solved, so "not today" is- // exactly "not finished today" — no per-game logic needed here.- if (store.lastCompletedDay() == store.todayEpochDay()) return Result.success()- notify(DailyPuzzleReminder.notificationIdOf(inputData))- return Result.success()+ return try {+ val keyPrefix = DailyPuzzleReminder.keyPrefixOf(inputData) ?: return Result.success()+ val store = DailyChallengeStore(applicationContext, keyPrefix)+ // Games only record the day once every puzzle in it is solved, so "not today" is+ // exactly "not finished today" — no per-game logic needed here.+ if (store.lastCompletedDay() == store.todayEpochDay()) return Result.success()+ notify(DailyPuzzleReminder.notificationIdOf(inputData))+ Result.success()+ } catch (e: CancellationException) {+ throw e+ } catch (e: IOException) {+ Log.error(TAG, "daily puzzle reminder failed; will retry", e)+ Result.retry()+ } catch (e: Exception) {+ Log.error(TAG, "daily puzzle reminder failed", e)+ Result.failure()+ }+ }++ /** Logging tag for [DailyPuzzleReminderWorker]. */+ companion object {+ private const val TAG = "DailyPuzzleReminder" } // Lint cannot follow the guard below: it does not model an early return whose condition
maps/src/main/java/com/vayunmathur/maps/platform/MapOverlayWorker.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/platform/MapOverlayWorker.kt b/maps/src/main/java/com/vayunmathur/maps/platform/MapOverlayWorker.ktindex daf374e332..f6ab7b784c 100644--- a/maps/src/main/java/com/vayunmathur/maps/platform/MapOverlayWorker.kt+++ b/maps/src/main/java/com/vayunmathur/maps/platform/MapOverlayWorker.kt@@ -21,7 +21,9 @@ import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.TrustBundle import com.vayunmathur.library.util.DataStoreUtils import java.io.File+import java.io.IOException import java.util.concurrent.TimeUnit+import kotlinx.coroutines.CancellationException /** * Checks for and fetches incremental map updates (Phase 2: download + store).@@ -43,28 +45,44 @@ import java.util.concurrent.TimeUnit class MapOverlayWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) { + // WorkManager contract (everysync pattern): return a Result, never throw.+ // Cancellation rethrows; a thrown transient I/O error takes the same+ // capped retry as the manifest/download paths below (the requests already+ // carry exponential backoff, and MAX_RUN_ATTEMPTS bounds the total), and+ // anything else fails this check — the periodic/manual entry runs again.+ @Suppress("TooGenericExceptionCaught") override suspend fun doWork(): Result {- val manifestUrl = inputData.getString(KEY_MANIFEST_URL) ?: MapOverlay.MANIFEST_URL- // WorkManager can cold-start the process without MainActivity's TLS- // init; without it the pinned manifest fetch below has no trust store.- NetworkClient.init(applicationContext, TrustBundle.FIRST_PARTY)- val root = applicationContext.getExternalFilesDir(null) ?: return Result.failure()- recoverRebaseCrash(root)- // No base, no overlay: the startup gate owns the full download.- if (!File(root, MapTileCache.BASEMAP_ARCHIVE_FILE).exists()) {- Log.status(TAG, "no base archive; skipping overlay check")- return Result.success()- }- val text = manifestFetcher(manifestUrl) ?: return Result.retry()- val manifest = MapOverlay.parse(text)- if (manifest == null) {- Log.status(TAG, "manifest unparseable or too new; skipping")- return Result.success()+ return try {+ val manifestUrl = inputData.getString(KEY_MANIFEST_URL) ?: MapOverlay.MANIFEST_URL+ // WorkManager can cold-start the process without MainActivity's TLS+ // init; without it the pinned manifest fetch below has no trust store.+ NetworkClient.init(applicationContext, TrustBundle.FIRST_PARTY)+ val root = applicationContext.getExternalFilesDir(null) ?: return Result.failure()+ recoverRebaseCrash(root)+ // No base, no overlay: the startup gate owns the full download.+ if (!File(root, MapTileCache.BASEMAP_ARCHIVE_FILE).exists()) {+ Log.status(TAG, "no base archive; skipping overlay check")+ return Result.success()+ }+ val text = manifestFetcher(manifestUrl) ?: return Result.retry()+ val manifest = MapOverlay.parse(text)+ if (manifest == null) {+ Log.status(TAG, "manifest unparseable or too new; skipping")+ return Result.success()+ }+ val ds = DataStoreUtils.getInstance(applicationContext)+ ds.setString(KEY_LAST_MANIFEST, text.take(MANIFEST_TEXT_CAP))+ ds.setLong(KEY_LAST_CHECK, System.currentTimeMillis())+ applyManifest(root, ds, manifest, text)+ } catch (e: CancellationException) {+ throw e+ } catch (e: IOException) {+ Log.error(TAG, "overlay check failed; will retry", e)+ if (runAttemptCount + 1 >= MAX_RUN_ATTEMPTS) Result.failure() else Result.retry()+ } catch (e: Exception) {+ Log.error(TAG, "overlay check failed", e)+ Result.failure() }- val ds = DataStoreUtils.getInstance(applicationContext)- ds.setString(KEY_LAST_MANIFEST, text.take(MANIFEST_TEXT_CAP))- ds.setLong(KEY_LAST_CHECK, System.currentTimeMillis())- return applyManifest(root, ds, manifest, text) } private suspend fun applyManifest(
music/src/main/java/com/vayunmathur/music/platform/SyncWorker.kt
diff --git a/music/src/main/java/com/vayunmathur/music/platform/SyncWorker.kt b/music/src/main/java/com/vayunmathur/music/platform/SyncWorker.ktindex 15690ebf60..04a693c0c3 100644--- a/music/src/main/java/com/vayunmathur/music/platform/SyncWorker.kt+++ b/music/src/main/java/com/vayunmathur/music/platform/SyncWorker.kt@@ -8,7 +8,10 @@ import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkerParameters import androidx.work.ListenableWorker.Result as WorkResult+import com.vayunmathur.library.log.Log import com.vayunmathur.music.data.MusicRepository+import java.io.IOException+import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.util.concurrent.TimeUnit@@ -23,16 +26,34 @@ import java.util.concurrent.TimeUnit * It re-enqueues itself because a content-URI trigger is one-shot. */ class SyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {- override suspend fun doWork(): WorkResult = withContext(Dispatchers.IO) {- val repo = MusicRepository.get(applicationContext)- repo.refresh()- repo.backfillTags()- enqueue(applicationContext)- WorkResult.success()+ // WorkManager contract (everysync pattern): return a Result, never throw.+ // Cancellation rethrows; transient MediaStore/DB I/O retries (WorkManager,+ // not the self re-enqueue below, owns that rerun); a revoked permission or+ // bad data fails — a later MediaStore change or app open re-enqueues anyway.+ @Suppress("TooGenericExceptionCaught")+ override suspend fun doWork(): WorkResult {+ return try {+ withContext(Dispatchers.IO) {+ val repo = MusicRepository.get(applicationContext)+ repo.refresh()+ repo.backfillTags()+ enqueue(applicationContext)+ }+ WorkResult.success()+ } catch (e: CancellationException) {+ throw e+ } catch (e: IOException) {+ Log.error(TAG, "music sync failed; will retry", e)+ WorkResult.retry()+ } catch (e: Exception) {+ Log.error(TAG, "music sync failed", e)+ WorkResult.failure()+ } } /** Shared constants and helpers for SyncWorker. */ companion object {+ private const val TAG = "MusicSyncWorker" private const val WORK_NAME = "MusicSyncWorker" fun enqueue(context: Context) {
securemail/src/main/java/com/vayunmathur/securemail/platform/BootReceiver.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/platform/BootReceiver.kt b/securemail/src/main/java/com/vayunmathur/securemail/platform/BootReceiver.ktindex 4a7b6d386a..f5b8084bc2 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/platform/BootReceiver.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/BootReceiver.kt@@ -3,15 +3,21 @@ package com.vayunmathur.securemail.platform import android.content.BroadcastReceiver import android.content.Context import android.content.Intent+import com.vayunmathur.library.log.Log import com.vayunmathur.securemail.data.MailConfig import com.vayunmathur.securemail.service.MailSocketService import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch /** Restarts the relay socket after boot/package-replace when an identity exists. */ class BootReceiver : BroadcastReceiver() {+ // Broad catch is deliberate: onReceive must not throw (calendar/email boot+ // receivers use the same shape), and starting a foreground service from+ // boot throws undocumented RuntimeExceptions on some platform versions.+ @Suppress("TooGenericExceptionCaught") override fun onReceive(context: Context, intent: Intent) { // Only system protected broadcasts restart the socket; any other action is ignored. if (intent.action != Intent.ACTION_BOOT_COMPLETED &&@@ -20,9 +26,27 @@ class BootReceiver : BroadcastReceiver() { ) { return }- CoroutineScope(Dispatchers.IO).launch {- val settings = MailConfig(context).settings.first()- if (settings.address.isNotBlank()) MailSocketService.start(context)+ // goAsync keeps the broadcast (and process) alive until the settings+ // read + service start below have actually run; without it the system+ // may kill the process as soon as onReceive returns.+ val pendingResult = goAsync()+ val appContext = context.applicationContext+ CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {+ try {+ val settings = MailConfig(appContext).settings.first()+ if (settings.address.isNotBlank()) MailSocketService.start(appContext)+ } catch (e: Exception) {+ Log.error(TAG, "could not restart the relay socket after ${intent.action}", e)+ } finally {+ // goAsync() can return null (e.g. when not dispatched by the+ // system, as in host tests); finishing is best-effort.+ pendingResult?.finish()+ } } }++ /** Logging tag for [BootReceiver]. */+ companion object {+ private const val TAG = "SecureMailBoot"+ } }
shop/src/main/java/com/vayunmathur/shop/platform/OrderTrackingWorker.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/platform/OrderTrackingWorker.kt b/shop/src/main/java/com/vayunmathur/shop/platform/OrderTrackingWorker.ktindex 6a996c00e3..e34b888227 100644--- a/shop/src/main/java/com/vayunmathur/shop/platform/OrderTrackingWorker.kt+++ b/shop/src/main/java/com/vayunmathur/shop/platform/OrderTrackingWorker.kt@@ -11,8 +11,11 @@ import androidx.core.content.ContextCompat import androidx.work.CoroutineWorker import androidx.work.WorkManager import androidx.work.WorkerParameters+import com.vayunmathur.library.log.Log import com.vayunmathur.library.util.MaNotifications import com.vayunmathur.library.work.startRepeatedTask+import java.io.IOException+import kotlinx.coroutines.CancellationException import com.vayunmathur.shop.MainActivity import com.vayunmathur.shop.R import com.vayunmathur.shop.data.OrderStore@@ -98,13 +101,33 @@ class OrderTrackingWorker( appContext: Context, params: WorkerParameters, ) : CoroutineWorker(appContext, params) {+ // WorkManager contract (everysync pattern): return a Result, never throw.+ // Cancellation rethrows; transient store/network I/O retries with the+ // repeated task's WorkManager backoff; bad local data or a revoked+ // notification permission fails this poll — the hourly period polls again.+ @Suppress("TooGenericExceptionCaught") override suspend fun doWork(): Result {- AppInit.start(applicationContext)- AppInit.awaitReady()- val result = OrderTrackingSync.refresh(applicationContext)- OrderTrackingSync.notifyChanges(applicationContext, result.changed)- // Never re-enqueue from here: the immediate request would chain forever.- if (result.orders.none(OrderTrackingUpdates::needsTracking)) OrderTrackingSync.cancel(applicationContext)- return Result.success()+ return try {+ AppInit.start(applicationContext)+ AppInit.awaitReady()+ val result = OrderTrackingSync.refresh(applicationContext)+ OrderTrackingSync.notifyChanges(applicationContext, result.changed)+ // Never re-enqueue from here: the immediate request would chain forever.+ if (result.orders.none(OrderTrackingUpdates::needsTracking)) OrderTrackingSync.cancel(applicationContext)+ Result.success()+ } catch (e: CancellationException) {+ throw e+ } catch (e: IOException) {+ Log.error(TAG, "order tracking poll failed; will retry", e)+ Result.retry()+ } catch (e: Exception) {+ Log.error(TAG, "order tracking poll failed", e)+ Result.failure()+ }+ }++ /** Logging tag for [OrderTrackingWorker]. */+ companion object {+ private const val TAG = "OrderTrackingWorker" } }