134 lines · 5.1 KB · KotlinRaw
package com.cottondb.android.platformimport android.app.job.JobInfoimport android.app.job.JobParametersimport android.app.job.JobSchedulerimport android.app.job.JobServiceimport android.content.ComponentNameimport android.content.Contextimport java.util.concurrent.ConcurrentHashMapimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.CoroutineStartimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.Jobimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.cancelimport kotlinx.coroutines.currentCoroutineContextimport kotlinx.coroutines.launchimport kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.sync.withLockimport kotlinx.coroutines.withContext/** AppRuntime implements this with its existing core and session scope. */interface ScheduledNotificationRuntime { /** Reconciles every notification and alarm row the platform can deliver. */ suspend fun reconcileScheduledNotifications()}/** * Persists an immediate reconciliation and a separate twelve-hour safety pass. The runtime owns * the one core handle; this service only asks that runtime to reconcile its existing rows. */class AlarmDeliveryJob : JobService() { private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private val runs = ConcurrentHashMap<Int, Job>() private val reconcileLock = Mutex() override fun onStartJob(params: JobParameters): Boolean { val jobId = params.jobId val run = serviceScope.launch(start = CoroutineStart.LAZY) { val thisJob = currentCoroutineContext()[Job] var retry = false try { reconcileLock.withLock { val runtime = applicationContext as? ScheduledNotificationRuntime ?: error("Cotton runtime is unavailable for notification reconciliation.") runtime.reconcileScheduledNotifications() } } catch (cancelled: CancellationException) { throw cancelled } catch (failure: Throwable) { retry = true AndroidReminderRuntime.report( "Scheduled notifications could not be reconciled.", failure, ) } finally { withContext(Dispatchers.Main.immediate) { if (thisJob != null && runs.remove(jobId, thisJob)) { jobFinished(params, retry) } } } } runs.put(jobId, run)?.cancel() run.start() return true } override fun onStopJob(params: JobParameters): Boolean { runs.remove(params.jobId)?.cancel() return true } override fun onDestroy() { runs.values.forEach(Job::cancel) runs.clear() serviceScope.cancel() super.onDestroy() } companion object { private const val IMMEDIATE_JOB_ID = 70_101 private const val PERIODIC_JOB_ID = 70_102 private const val PERIODIC_INTERVAL_MILLIS = 12 * 60 * 60 * 1_000L /** Schedules the coalesced immediate reconciliation. */ fun enqueue(context: Context) { val scheduler = context.getSystemService(JobScheduler::class.java) val info = JobInfo.Builder( IMMEDIATE_JOB_ID, ComponentName(context, AlarmDeliveryJob::class.java), ) .setPersisted(true) .setOverrideDeadline(0) .build() check(scheduler.schedule(info) == JobScheduler.RESULT_SUCCESS) { "Notification reconciliation job could not be scheduled." } } /** Compatibility for exact-alarm delivery; reconciliation always reads all rows. */ fun enqueue(context: Context, @Suppress("UNUSED_PARAMETER") delivery: AlarmDelivery) { enqueue(context) } /** Registers the persisted periodic safety reconciliation. */ fun ensurePeriodic(context: Context) { val scheduler = context.getSystemService(JobScheduler::class.java) if (scheduler.getPendingJob(PERIODIC_JOB_ID) != null) return val info = JobInfo.Builder( PERIODIC_JOB_ID, ComponentName(context, AlarmDeliveryJob::class.java), ) .setPersisted(true) .setPeriodic(PERIODIC_INTERVAL_MILLIS) .build() check(scheduler.schedule(info) == JobScheduler.RESULT_SUCCESS) { "Periodic notification reconciliation could not be scheduled." } } fun cancelPeriodic(context: Context) { context.getSystemService(JobScheduler::class.java).cancel(PERIODIC_JOB_ID) } /** Removes both delivery passes when this replica is retired. */ fun cancel(context: Context) { val scheduler = context.getSystemService(JobScheduler::class.java) scheduler.cancel(IMMEDIATE_JOB_ID) scheduler.cancel(PERIODIC_JOB_ID) } }}