package com.cottondb.android.platform import android.app.job.JobInfo import android.app.job.JobParameters import android.app.job.JobScheduler import android.app.job.JobService import android.content.ComponentName import android.content.Context import java.util.concurrent.ConcurrentHashMap import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import 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() 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) } } }