findfamily: active location check at least every 15 min, Doze-proof (#895)
- Commit
b79ee0afb0c8f10ddcd3d9f836f0e62dcbc93b5a- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-13 22:15 UTC (22 days ago)
- Parents
56d3faa
Owner requirement: "For findfamily, minimum once every 15 minutes, location should be checked immediately (not get last location, get current location) even if no movement is detected." Before this change the #895 keep-alive could miss that in two ways: - The forced fix (ForcedFixPolicy) only fired when the HELD fix was older than 5/10/15 min. PASSIVE deliveries (other apps' GPS) and the low-power NETWORK request keep the held fix fresh, so a still phone could go hours without ever asking for its current location. - Everything ran from the 30 s heartbeat, a coroutine delay that does not advance while the CPU sleeps. In Doze neither the forced fix nor any publish happened at all. What changed: - ForcedFixPolicy gains an unconditional ceiling. While the phone shares with anyone, an active getCurrentLocation request goes out whenever the last one is 14 min old (due one minute early so alarm latency and heartbeat granularity stay inside 15 min), regardless of held-fix age, power state or the movement detector. Every forced-fix attempt counts as an active request; passive and low-power deliveries never do. The shorter charging (5 min) and battery (10 min) staleness intervals are unchanged. dueReason() returns STALE_HELD_FIX or ACTIVE_CHECK_CEILING; the ceiling wins when both apply. - Power-save GPS: the staleness check still never uses GPS in power-save, but the ceiling does when the network answer is missing or coarser than the 100 m display gate. The requirement is a current location every 15 min and a power-save phone with no usable network fix has no other way to get one; it is bounded by the 30 s GPS timeout, at most once per ceiling (~2 min GPS/hour worst case). - New platform/FixCeilingAlarm.kt keeps one ELAPSED_REALTIME_WAKEUP alarm armed for the next due check while sharing: setExactAndAllowWhileIdle when canScheduleExactAlarms() (manifest now declares USE_EXACT_ALARM, install-granted on 33+, and SCHEDULE_EXACT_ALARM maxSdk 32, same as calendar and todo; the app ships via F-Droid and its own store, so Play's alarm-app-only policy does not apply). Otherwise setAndAllowWhileIdle armed at (time left)/1.75 so even the end of the inexact window is inside the ceiling; an early delivery just re-arms. The alarm moves on every forced-fix attempt and is cancelled when sharing stops or the service is destroyed. Rejected: inexact-only (window can push a 15 min alarm to ~26 min), WorkManager (15 min minimum period plus Doze deferral). - FixCeilingReceiver takes a 60 s partial wake lock and startService()s the already-foreground tracking service with a FIX_CEILING_CHECK command; the service re-reads whether anyone is shared with, runs the normal keep-alive tick, waits for the forced fix and re-arms. - Each forced fix now runs under its own partial wake lock (bounded by the network + GPS timeouts + 30 s) and, when it produced a fix fine enough to display, publishes immediately through the normal path (syncHeartbeat, or publishDirectBoot before first unlock), so the receiver's "last updated" reflects the check even when the phone did not move and the heartbeat is asleep. - Manifest: WAKE_LOCK, USE_EXACT_ALARM, SCHEDULE_EXACT_ALARM (<=32), and the non-exported, direct-boot-aware receiver. User-visible effect: a sharing phone's pin and "last updated" refresh from a real current-location request at least every 15 minutes, also while it sits still in Doze. Verified: new ForcedFixPolicyTest (ceiling vs held-fix freshness in every power state, inexact alarm chain lands inside the ceiling, power-save GPS only for the ceiling) and Robolectric FixCeilingAlarmTest (alarm armed exact+allow-while-idle, re-armed after each check, cancelled on sharing off and on destroy, inexact fallback timing, receiver wake lock + service command, and a ceiling tick calling the current-location source despite a fresh passive fix and "still" motion, with the result published); LocationKeepAliveTest updated for the reason-returning forcedFixDue. :findfamily compileDevKotlin, testDevUnitTest (296 tests, 0 failures) and lint pass. detekt reports only the 10 pre-existing findings in files this change does not touch (FindFamilyRepository, Networking, LocationTrackingInbound, LocationTrackingCrowdFinding, LocationTrackingHeartbeat); none in the changed files.
Diff
findfamily/src/main/AndroidManifest.xml
diff --git a/findfamily/src/main/AndroidManifest.xml b/findfamily/src/main/AndroidManifest.xmlindex ae011a2d27..972092344f 100644--- a/findfamily/src/main/AndroidManifest.xml+++ b/findfamily/src/main/AndroidManifest.xml@@ -15,6 +15,22 @@ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> + <!--+ The 15-minute active location check (#895 follow-up) has to run in Doze, where the+ heartbeat coroutine does not: an exact allow-while-idle alarm wakes the CPU and a short+ partial wake lock covers the fix. USE_EXACT_ALARM is install-granted (non-revocable) on+ API 33+; SCHEDULE_EXACT_ALARM covers 31-32, where it is granted by default.+ FixCeilingAlarm still checks canScheduleExactAlarms() and falls back to an inexact+ allow-while-idle alarm armed early enough to stay inside 15 minutes. Distributed via+ F-Droid and its own store, so Play's alarm-app-only USE_EXACT_ALARM policy does not+ apply (same declaration as calendar and todo).+ -->+ <uses-permission android:name="android.permission.WAKE_LOCK" />+ <uses-permission android:name="android.permission.USE_EXACT_ALARM" />+ <uses-permission+ android:name="android.permission.SCHEDULE_EXACT_ALARM"+ android:maxSdkVersion="32" />+ <!-- Powered-off finding, finder half. Arming a beacon needs BLUETOOTH_PRIVILEGED, which is signature|privileged and so only ever available to a preinstalled build — but *hearing* one@@ -119,6 +135,11 @@ </service> + <receiver+ android:name=".platform.FixCeilingReceiver"+ android:directBootAware="true"+ android:exported="false" />+ <receiver android:name=".util.BootReceiver" android:directBootAware="true"
findfamily/src/main/java/com/vayunmathur/findfamily/domain/ForcedFixPolicy.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/domain/ForcedFixPolicy.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/ForcedFixPolicy.ktindex 8f8755efc9..11ee3e46a7 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/domain/ForcedFixPolicy.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/ForcedFixPolicy.kt@@ -10,6 +10,13 @@ package com.vayunmathur.findfamily.domain * service asks for a current location: network first (cheap), GPS only when * network cannot produce a fix fine enough to display. *+ * On top of that sits an unconditional ceiling (owner requirement, #895+ * follow-up): while the phone is sharing, an ACTIVE current-location request+ * (never a last-known read) goes out at least every [ACTIVE_CHECK_MAX_GAP_MS],+ * however fresh the held fix is and whatever the movement detector says. A held+ * fix kept fresh by PASSIVE or low-power network deliveries no longer counts as+ * a check.+ * * Pure: monotonic millisecond inputs only, no Android types. */ object ForcedFixPolicy {@@ -29,6 +36,27 @@ object ForcedFixPolicy { /** How long a forced GPS fix may take before giving up (bounds the GPS-on time). */ const val GPS_TIMEOUT_MS = 30_000L + /**+ * The ceiling: the longest a sharing phone may go without an active+ * current-location request, in any power state, moving or still.+ */+ const val ACTIVE_CHECK_MAX_GAP_MS = 15 * 60_000L++ /**+ * When the ceiling check becomes due: one minute ahead of the ceiling, so+ * alarm delivery latency and the 30 s heartbeat granularity still land the+ * request inside [ACTIVE_CHECK_MAX_GAP_MS].+ */+ const val ACTIVE_CHECK_DUE_MS = ACTIVE_CHECK_MAX_GAP_MS - 60_000L++ /**+ * AlarmManager's inexact batching window: an inexact alarm set `d` ms ahead+ * may fire as late as `1.75 * d` after it was set (a 75 % window). The+ * inexact fallback arms early enough that even the end of that window is+ * inside the ceiling.+ */+ private const val INEXACT_WINDOW_FACTOR = 1.75+ /** The forced-fix interval for the current power state. Charging wins over power-save. */ fun intervalMs(charging: Boolean, powerSave: Boolean): Long = when { charging -> INTERVAL_CHARGING_MS@@ -47,24 +75,86 @@ object ForcedFixPolicy { return heldStale && attemptGapOk } + /**+ * True when the last active current-location request is old enough for the+ * ceiling check. Every forced-fix attempt is such a request (it calls+ * getCurrentLocation), so [lastAttemptMs] is the same timestamp [isDue] backs+ * off on; passive and low-power deliveries never move it.+ */+ fun isCeilingDue(nowMs: Long, lastAttemptMs: Long?): Boolean =+ lastAttemptMs == null || nowMs - lastAttemptMs >= ACTIVE_CHECK_DUE_MS++ /**+ * Why a forced fix is due now, or null when none is.+ *+ * The ceiling wins over the held-fix staleness check when both apply, because+ * only the ceiling may use GPS in power-save (see [shouldFallBackToGps]).+ * [ceilingEnabled] is false while the phone shares with nobody: there is no+ * one to show the check to, so it is not worth the radio time.+ */+ fun dueReason(+ nowMs: Long,+ heldFixElapsedMs: Long?,+ lastAttemptMs: Long?,+ intervalMs: Long,+ ceilingEnabled: Boolean,+ ): ForcedFixReason? = when {+ ceilingEnabled && isCeilingDue(nowMs, lastAttemptMs) -> ForcedFixReason.ACTIVE_CHECK_CEILING+ isDue(nowMs, heldFixElapsedMs, lastAttemptMs, intervalMs) -> ForcedFixReason.STALE_HELD_FIX+ else -> null+ }++ /**+ * How far ahead to arm the Doze-proof ceiling alarm.+ *+ * Exact alarms fire on time, so they are set for the moment the check becomes+ * due. An inexact alarm may fire anywhere in its window, so it is set at+ * (time left before the ceiling) / [INEXACT_WINDOW_FACTOR]: even its latest+ * delivery is inside the ceiling. When it fires before the check is due the+ * caller just re-arms; the remaining time shrinks geometrically, so the chain+ * reaches a due check in a handful of cheap wake-ups.+ */+ fun ceilingAlarmDelayMs(nowMs: Long, lastAttemptMs: Long?, exact: Boolean): Long {+ if (lastAttemptMs == null) return 0L+ val untilDue = lastAttemptMs + ACTIVE_CHECK_DUE_MS - nowMs+ if (untilDue <= 0L) return 0L+ if (exact) return untilDue+ val untilCeiling = lastAttemptMs + ACTIVE_CHECK_MAX_GAP_MS - nowMs+ return (untilCeiling / INEXACT_WINDOW_FACTOR).toLong()+ }+ /** * Whether to follow the network attempt with GPS. * * GPS runs when there is no network provider at all, or when network gave- * nothing usable for display (no fix, or coarser than the display gate) —- * except in power-save, where the existing policy keeps GPS to the moving- * path only. A coarse network fix still reaches the movement detector- * either way.+ * nothing usable for display (no fix, or coarser than the display gate).+ *+ * Power-save keeps GPS off for the held-fix staleness check (the moving path+ * still has it), but not for the [ceiling] check: the owner's requirement is a+ * current location at least every 15 minutes, and a power-save phone whose+ * network answer is unusable has no other way to produce one. The GPS attempt+ * is bounded by [GPS_TIMEOUT_MS], at most once per ceiling. A coarse network+ * fix still reaches the movement detector either way. */ fun shouldFallBackToGps( hasGps: Boolean, hasNetwork: Boolean, networkAccuracyMeters: Double?, powerSave: Boolean,+ ceiling: Boolean = false, ): Boolean { if (!hasGps) return false if (!hasNetwork) return true- if (powerSave) return false+ if (powerSave && !ceiling) return false return networkAccuracyMeters == null || !NoShowPolicy.isAccurateEnough(networkAccuracyMeters) } }++/** Why the service asks for a one-off current location. */+enum class ForcedFixReason {+ /** The held fix is older than the power-state interval ([ForcedFixPolicy.intervalMs]). */+ STALE_HELD_FIX,++ /** No active request for [ForcedFixPolicy.ACTIVE_CHECK_DUE_MS], however fresh the held fix. */+ ACTIVE_CHECK_CEILING,+}
findfamily/src/main/java/com/vayunmathur/findfamily/platform/FixCeilingAlarm.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FixCeilingAlarm.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FixCeilingAlarm.ktnew file mode 100644index 0000000000..625d387c53--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FixCeilingAlarm.kt@@ -0,0 +1,247 @@+package com.vayunmathur.findfamily.platform++import android.app.AlarmManager+import android.app.PendingIntent+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.os.PowerManager+import android.os.SystemClock+import com.vayunmathur.findfamily.domain.ForcedFixPolicy+import com.vayunmathur.findfamily.util.LocationServiceController+import com.vayunmathur.findfamily.util.LocationTrackingService+import com.vayunmathur.findfamily.util.Networking+import com.vayunmathur.findfamily.util.publishDirectBoot+import com.vayunmathur.findfamily.util.syncHeartbeat+import com.vayunmathur.library.log.Log+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import kotlin.time.Clock++/*+ * The 15-minute active-check ceiling (#895 follow-up), Doze half.+ *+ * Owner requirement: "minimum once every 15 minutes, location should be checked immediately+ * (not get last location, get current location) even if no movement is detected."+ * ForcedFixPolicy decides when that check is due; this file makes sure something is awake to+ * ask. The 30 s heartbeat is a coroutine delay, which does not advance while the CPU sleeps,+ * so on its own a dozing phone would never run the check at all.+ *+ * - While the phone shares with anyone, one AlarmManager ELAPSED_REALTIME_WAKEUP alarm is kept+ * armed for the moment the next check is due. Exact + allow-while-idle when the app may+ * schedule exact alarms (USE_EXACT_ALARM is install-granted on API 33+, SCHEDULE_EXACT_ALARM+ * is granted by default on 31-32): it fires on time in Doze. Otherwise inexact+ * allow-while-idle, armed early enough that the end of its batching window is still inside+ * the ceiling (ForcedFixPolicy.ceilingAlarmDelayMs). This app ships via F-Droid and its own+ * store, so Play's alarm-app-only policy for USE_EXACT_ALARM does not apply; calendar and+ * todo already declare it the same way.+ * - The alarm hits [FixCeilingReceiver], which takes a short wake lock and pokes the running+ * service. The service runs the ordinary keep-alive tick, waits for the forced fix (which+ * holds its own wake lock and publishes its result) and re-arms.+ * - The alarm moves on every forced-fix attempt and is cancelled when sharing stops or the+ * service is destroyed.+ */++private const val TAG_CEILING = "FF-FixCeiling"++/** Arms and cancels the ceiling alarm, and bridges the CPU from the alarm to the service. */+internal object FixCeilingAlarm {++ /** The alarm's broadcast action ([FixCeilingReceiver]). */+ const val ACTION_ALARM = "com.vayunmathur.findfamily.action.FIX_CEILING_ALARM"++ /** The service command the receiver sends ([LocationTrackingService.onStartCommand]). */+ const val ACTION_CHECK = "com.vayunmathur.findfamily.action.FIX_CEILING_CHECK"++ private const val REQUEST_CODE = 895++ /**+ * Holds the CPU from the alarm broadcast until the service has started the forced fix+ * (which then holds its own lock). Released explicitly; the timeout is a backstop.+ */+ private const val BRIDGE_WAKE_LOCK_TIMEOUT_MS = 60_000L++ private const val BRIDGE_WAKE_LOCK_TAG = "findfamily:fix-ceiling"++ @Volatile+ private var bridgeWakeLock: PowerManager.WakeLock? = null++ /**+ * Arms (or moves) the alarm for the next due check, measured from [lastAttemptMs]+ * (elapsedRealtime of the last active current-location request; null = due now).+ * Returns true when the alarm is exact.+ */+ fun arm(context: Context, nowMs: Long, lastAttemptMs: Long?): Boolean {+ val alarmManager = context.getSystemService(AlarmManager::class.java) ?: return false+ val operation = pendingIntent(context)+ if (alarmManager.canScheduleExactAlarms()) {+ val triggerAt = nowMs + ForcedFixPolicy.ceilingAlarmDelayMs(nowMs, lastAttemptMs, exact = true)+ try {+ alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAt, operation)+ return true+ } catch (_: SecurityException) {+ // Revoked between the check and the call: fall through to inexact.+ }+ }+ val triggerAt = nowMs + ForcedFixPolicy.ceilingAlarmDelayMs(nowMs, lastAttemptMs, exact = false)+ alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAt, operation)+ return false+ }++ /** Cancels the alarm, if one is armed. */+ fun cancel(context: Context) {+ val operation = PendingIntent.getBroadcast(+ context,+ REQUEST_CODE,+ alarmIntent(context),+ PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE,+ ) ?: return+ context.getSystemService(AlarmManager::class.java)?.cancel(operation)+ operation.cancel()+ }++ fun acquireWakeLock(context: Context) {+ val lock = bridgeWakeLock ?: synchronized(this) {+ bridgeWakeLock ?: context.applicationContext.getSystemService(PowerManager::class.java)+ ?.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, BRIDGE_WAKE_LOCK_TAG)+ ?.apply { setReferenceCounted(false) }+ ?.also { bridgeWakeLock = it }+ }+ lock?.acquire(BRIDGE_WAKE_LOCK_TIMEOUT_MS)+ }++ fun releaseWakeLock() {+ bridgeWakeLock?.takeIf { it.isHeld }?.release()+ }++ /** Whether the bridge wake lock is held right now (tests and diagnostics). */+ val isWakeLockHeld: Boolean get() = bridgeWakeLock?.isHeld == true++ private fun alarmIntent(context: Context) =+ Intent(context, FixCeilingReceiver::class.java).setAction(ACTION_ALARM)++ private fun pendingIntent(context: Context): PendingIntent = PendingIntent.getBroadcast(+ context,+ REQUEST_CODE,+ alarmIntent(context),+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+ )+}++/**+ * The ceiling alarm's receiver: keeps the CPU up and hands the check to the running service.+ *+ * Plain startService, not startForegroundService: the service is already in the foreground+ * whenever the alarm is armed, so the app is not "in the background" and the start is+ * allowed. If the process lost its service meanwhile the start is refused, and the+ * ServiceRestartWorker brings tracking back as it always has.+ */+class FixCeilingReceiver : BroadcastReceiver() {+ override fun onReceive(context: Context, intent: Intent) {+ if (intent.action != FixCeilingAlarm.ACTION_ALARM) return+ FixCeilingAlarm.acquireWakeLock(context)+ val command = Intent(context, LocationTrackingService::class.java).setAction(FixCeilingAlarm.ACTION_CHECK)+ val started = try {+ context.startService(command) != null+ } catch (_: IllegalStateException) {+ false+ } catch (_: SecurityException) {+ false+ }+ if (!started) {+ Log.status(TAG_CEILING, "ceiling alarm: tracking service not running")+ FixCeilingAlarm.releaseWakeLock()+ }+ }+}++/**+ * The service's half of a ceiling alarm. Re-reads whether anyone is being shared with,+ * runs the keep-alive tick (which starts the forced fix when due), waits for it, and moves+ * the alarm to the next check. The bridge wake lock is released at the end either way.+ */+internal fun LocationTrackingService.onFixCeilingAlarm() {+ serviceScope.launch {+ try {+ refreshFixCeiling()+ withContext(Dispatchers.Main.immediate) { fixCeilingAlarmTick() }?.join()+ // Not in finally: a service destroyed mid-check must not re-arm the alarm.+ withContext(Dispatchers.Main.immediate) { rearmFixCeiling() }+ } finally {+ FixCeilingAlarm.releaseWakeLock()+ }+ }+}++/** Main thread: the synchronous half of a ceiling alarm. Returns the forced fix in flight, if any. */+internal fun LocationTrackingService.fixCeilingAlarmTick(): Job? {+ keepAliveTick()+ return forcedFixJob?.takeIf { it.isActive }+}++/**+ * Re-evaluates whether the phone is sharing and arms or cancels the ceiling to match.+ * Called from every heartbeat (and pre-unlock publish) tick and from each ceiling alarm.+ */+// Broad catch is deliberate: a DAO failure here must not kill the heartbeat loop.+@Suppress("TooGenericExceptionCaught")+internal suspend fun LocationTrackingService.refreshFixCeiling() {+ val sharing = try {+ isSharingOut()+ } catch (e: CancellationException) {+ throw e+ } catch (e: Exception) {+ Log.status(TAG_CEILING, "sharing check failed; ceiling left as is", e)+ return+ }+ withContext(Dispatchers.Main.immediate) { updateFixCeiling(sharing) }+}++/**+ * True when a publish right now would reach someone: global sharing on and at least one+ * person with sending enabled or one live temporary link. Before first unlock only the+ * device-protected roster is readable, so that decides.+ */+internal suspend fun LocationTrackingService.isSharingOut(): Boolean {+ if (directBootJob?.isActive == true) return publishRoster.isNotEmpty()+ if (!LocationServiceController.isGlobalSharingEnabled(this)) return false+ val self = Networking.userid+ if (repository.getAllUsers().any { it.id != self && it.sendingEnabled }) return true+ val now = Clock.System.now()+ return repository.temporaryLinkStore.getAll().any { now < it.deleteAt }+}++/** Main thread. Turns the ceiling on (alarm armed) or off (alarm cancelled) when sharing changes. */+internal fun LocationTrackingService.updateFixCeiling(sharing: Boolean) {+ if (fixCeilingEnabled == sharing) return+ fixCeilingEnabled = sharing+ Log.status(TAG_CEILING, if (sharing) "sharing: 15-min check ceiling on" else "not sharing: ceiling off")+ rearmFixCeiling()+}++/** Main thread. Moves the alarm to the next due check, or cancels it while the ceiling is off. */+internal fun LocationTrackingService.rearmFixCeiling() {+ if (fixCeilingEnabled) {+ FixCeilingAlarm.arm(this, SystemClock.elapsedRealtime(), lastForcedFixAttemptMs)+ } else {+ FixCeilingAlarm.cancel(this)+ }+}++/** The forced fix's own partial wake lock, created once per service. */+internal fun LocationTrackingService.forcedFixWakeLock(): PowerManager.WakeLock? =+ forcedFixWakeLockHolder ?: getSystemService(PowerManager::class.java)+ ?.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "findfamily:forced-fix")+ ?.apply { setReferenceCounted(false) }+ ?.also { forcedFixWakeLockHolder = it }++/**+ * Publishes the held fix now through the normal path: the heartbeat after unlock, the+ * device-protected publish before it. Both stamp the publish with the current time.+ */+internal suspend fun LocationTrackingService.publishCheckedFix() {+ if (directBootJob?.isActive == true) publishDirectBoot(publishRoster) else syncHeartbeat()+}
findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationKeepAlive.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationKeepAlive.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationKeepAlive.ktindex a22a9571ed..ed4fc07982 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationKeepAlive.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationKeepAlive.kt@@ -6,10 +6,13 @@ import android.os.CancellationSignal import android.os.SystemClock import com.vayunmathur.findfamily.domain.FixSample import com.vayunmathur.findfamily.domain.ForcedFixPolicy+import com.vayunmathur.findfamily.domain.ForcedFixReason+import com.vayunmathur.findfamily.domain.NoShowPolicy import com.vayunmathur.findfamily.util.LocationTrackingService import com.vayunmathur.findfamily.util.recordFix import com.vayunmathur.library.log.Log import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext@@ -28,7 +31,9 @@ import kotlin.coroutines.resume * 1. An always-on low-power NETWORK request (minutes apart, displacement-filtered) and a * PASSIVE request, so leaving by any means delivers a fix that flips the phone back to * moving through [onLocationFix].- * 2. A periodic forced fix ([ForcedFixPolicy]) when the held fix gets old.+ * 2. A periodic forced fix ([ForcedFixPolicy]) when the held fix gets old, plus a 15-minute+ * ceiling on active current-location requests while sharing, kept alive through Doze by+ * an AlarmManager wake-up (FixCeilingAlarm.kt). * 3. A single fix intake that lets every fix, however coarse, reach the movement detector * before the display accuracy gate in [recordFix] decides whether it is held. *@@ -50,6 +55,13 @@ internal const val LOW_POWER_INTERVAL_POWER_SAVE_MS = 5 * 60_000L */ internal const val LOW_POWER_MIN_DISTANCE_METERS = 75f +/**+ * Wake-lock bound on one forced fix: the network and GPS timeouts plus time to publish.+ * Released as soon as the fix and the publish finish; the timeout is only a backstop.+ */+internal const val FORCED_FIX_WAKE_LOCK_TIMEOUT_MS =+ ForcedFixPolicy.NETWORK_TIMEOUT_MS + ForcedFixPolicy.GPS_TIMEOUT_MS + 30_000L+ /** PASSIVE costs nothing (other apps' fixes); the interval only bounds callback rate. */ internal const val PASSIVE_MIN_INTERVAL_MS = 30_000L @@ -106,9 +118,9 @@ internal fun LocationTrackingService.onLocationFix(location: Location) { } /**- * Runs on every heartbeat tick (30 s while the CPU is awake) on the main thread:- * re-checks stillness, keeps the low-power requests registered, and starts a forced- * fix when one is due.+ * Runs on every heartbeat tick (30 s while the CPU is awake) and on every ceiling alarm+ * (which also wakes a dozing CPU), on the main thread: re-checks stillness, keeps the+ * low-power requests registered, and starts a forced fix when one is due. */ internal fun LocationTrackingService.keepAliveTick() { applyMotionTransition(motion.onTick(SystemClock.elapsedRealtime()))@@ -173,34 +185,61 @@ internal fun LocationTrackingService.stopLowPowerUpdates() { private fun LocationTrackingService.isCharging(): Boolean = runCatching { bm.isCharging }.getOrDefault(false) /**- * True (and the attempt recorded) when the held fix is stale enough for a forced fix.- * See [ForcedFixPolicy.isDue]; never while a previous forced fix is still running.+ * Why a forced fix is due now (and the attempt recorded), or null when none is. See+ * [ForcedFixPolicy.dueReason]; never while a previous forced fix is still running. */-internal fun LocationTrackingService.forcedFixDue(nowMs: Long): Boolean {- if (forcedFixJob?.isActive == true) return false+internal fun LocationTrackingService.forcedFixDue(nowMs: Long): ForcedFixReason? {+ if (forcedFixJob?.isActive == true) return null val interval = ForcedFixPolicy.intervalMs(isCharging(), powerManager.isPowerSaveMode) val heldMs = lastKnownLocation?.let { it.elapsedRealtimeNanos / NANOS_PER_MILLI }- if (!ForcedFixPolicy.isDue(nowMs, heldMs, lastForcedFixAttemptMs, interval)) return false+ val reason = ForcedFixPolicy.dueReason(nowMs, heldMs, lastForcedFixAttemptMs, interval, fixCeilingEnabled)+ ?: return null lastForcedFixAttemptMs = nowMs- return true+ return reason+}++/**+ * Starts a forced fix in the background when [forcedFixDue], and moves the ceiling alarm+ * to one ceiling after this attempt. Returns the forced fix in flight, if any.+ */+internal fun LocationTrackingService.maybeRequestForcedFix(): Job? {+ val reason = forcedFixDue(SystemClock.elapsedRealtime())+ ?: return forcedFixJob?.takeIf { it.isActive }+ val job = serviceScope.launch { runForcedFix(reason) }+ forcedFixJob = job+ rearmFixCeiling()+ return job } -/** Starts a forced fix in the background when [forcedFixDue]. */-internal fun LocationTrackingService.maybeRequestForcedFix() {- if (!forcedFixDue(SystemClock.elapsedRealtime())) return- forcedFixJob = serviceScope.launch { runForcedFix() }+/**+ * One forced fix, under a partial wake lock so a screen-off CPU cannot sleep halfway+ * through it. When it produced a fix fine enough to display, that fix is published at+ * once through the normal heartbeat path, even if the phone has not moved: the+ * receivers' "last updated" must reflect the check, not wait for the next heartbeat+ * (which does not run while the CPU sleeps).+ */+internal suspend fun LocationTrackingService.runForcedFix(reason: ForcedFixReason = ForcedFixReason.STALE_HELD_FIX) {+ val wakeLock = forcedFixWakeLock()+ wakeLock?.acquire(FORCED_FIX_WAKE_LOCK_TIMEOUT_MS)+ try {+ if (requestCurrentFix(reason)) publishCheckedFix()+ } finally {+ if (wakeLock?.isHeld == true) wakeLock.release()+ } } /**- * One forced fix: network first; GPS after it only when network gave nothing fine- * enough to display ([ForcedFixPolicy.shouldFallBackToGps]). Each result goes through- * [onLocationFix], so a coarse network answer can still wake movement detection.+ * Network first; GPS after it only when network gave nothing fine enough to display+ * ([ForcedFixPolicy.shouldFallBackToGps]). Each result goes through [onLocationFix], so a+ * coarse network answer can still wake movement detection. Always a current-location+ * request, never a last-known read. True when some answer was fine enough to display. */-internal suspend fun LocationTrackingService.runForcedFix() {+private suspend fun LocationTrackingService.requestCurrentFix(reason: ForcedFixReason): Boolean { val source = currentLocationSourceOverride ?: PlatformCurrentLocationSource(locationManager, mainExecutor) val hasNetwork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) val hasGps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) val powerSave = powerManager.isPowerSaveMode+ val ceiling = reason == ForcedFixReason.ACTIVE_CHECK_CEILING val network = if (hasNetwork) { source.current(LocationManager.NETWORK_PROVIDER, ForcedFixPolicy.NETWORK_TIMEOUT_MS) } else {@@ -208,14 +247,18 @@ internal suspend fun LocationTrackingService.runForcedFix() { } network?.let { deliverForcedFix(it) } val networkAccuracy = network?.takeIf { it.hasAccuracy() }?.accuracy?.toDouble()- if (ForcedFixPolicy.shouldFallBackToGps(hasGps, hasNetwork, networkAccuracy, powerSave)) {+ var displayable = networkAccuracy != null && NoShowPolicy.isAccurateEnough(networkAccuracy)+ if (ForcedFixPolicy.shouldFallBackToGps(hasGps, hasNetwork, networkAccuracy, powerSave, ceiling)) { val gps = source.current(LocationManager.GPS_PROVIDER, ForcedFixPolicy.GPS_TIMEOUT_MS) gps?.let { deliverForcedFix(it) }- val gpsResult = if (gps != null) "ok" else "none"- Log.status(TAG_KEEP_ALIVE, "forced fix: network acc=$networkAccuracy, gps $gpsResult")+ val gpsAccuracy = gps?.takeIf { it.hasAccuracy() }?.accuracy?.toDouble()+ displayable = displayable || (gpsAccuracy != null && NoShowPolicy.isAccurateEnough(gpsAccuracy))+ val gpsResult = if (gps != null) "acc=$gpsAccuracy" else "none"+ Log.status(TAG_KEEP_ALIVE, "forced fix ($reason): network acc=$networkAccuracy, gps $gpsResult") } else {- Log.status(TAG_KEEP_ALIVE, "forced fix: network acc=$networkAccuracy")+ Log.status(TAG_KEEP_ALIVE, "forced fix ($reason): network acc=$networkAccuracy") }+ return displayable } private suspend fun LocationTrackingService.deliverForcedFix(location: Location) {
findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingDirectBoot.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingDirectBoot.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingDirectBoot.ktindex ab7893b31d..263279f261 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingDirectBoot.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingDirectBoot.kt@@ -13,6 +13,7 @@ import com.vayunmathur.findfamily.data.Coord import com.vayunmathur.findfamily.data.DirectBootStore import com.vayunmathur.findfamily.data.LocationValue import com.vayunmathur.findfamily.platform.keepAliveTick+import com.vayunmathur.findfamily.platform.refreshFixCeiling import com.vayunmathur.library.util.DataStoreUtils import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers@@ -71,7 +72,8 @@ internal fun LocationTrackingService.startDirectBootTracking() { "running pre-unlock, sharing=$sharing targets=${targets.size}" ) while (isActive) {- // Same sender keep-alive as the unlocked heartbeat (#895).+ // Same sender keep-alive and 15-minute ceiling as the unlocked heartbeat (#895).+ refreshFixCeiling() withContext(Dispatchers.Main) { keepAliveTick() } publishDirectBoot(targets) delay(30.seconds)
findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.ktindex f57eeccf4d..174af76aef 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt@@ -56,6 +56,9 @@ import com.vayunmathur.findfamily.domain.MotionTransition import com.vayunmathur.findfamily.domain.MovementDetector import com.vayunmathur.findfamily.platform.CurrentLocationSource import com.vayunmathur.findfamily.platform.FinalLocationReporter+import com.vayunmathur.findfamily.platform.FixCeilingAlarm+import com.vayunmathur.findfamily.platform.onFixCeilingAlarm+import com.vayunmathur.findfamily.platform.refreshFixCeiling import com.vayunmathur.findfamily.platform.onLocationFix import com.vayunmathur.findfamily.platform.keepAliveTick import com.vayunmathur.findfamily.platform.stopLowPowerUpdates@@ -145,10 +148,25 @@ class LocationTrackingService : Service(), SensorEventListener { internal var lowPowerIntervalMs = 0L internal var passiveRequested = false - /** elapsedRealtime of the last forced-fix attempt, or null before the first one. */+ /**+ * elapsedRealtime of the last forced-fix attempt, or null before the first one. Every+ * attempt is an active getCurrentLocation request, so this is also what the 15-minute+ * ceiling measures from (see ForcedFixPolicy.isCeilingDue).+ */+ @Volatile internal var lastForcedFixAttemptMs: Long? = null internal var forcedFixJob: Job? = null + /**+ * True while the phone shares with someone: the 15-minute active-check ceiling applies+ * and its Doze-proof alarm is armed (platform/FixCeilingAlarm.kt). Main thread writes.+ */+ @Volatile+ internal var fixCeilingEnabled = false++ /** The forced fix's partial wake lock, created on first use. */+ internal var forcedFixWakeLockHolder: PowerManager.WakeLock? = null+ /** Test seam: replaces LocationManager.getCurrentLocation for the forced fix. */ internal var currentLocationSourceOverride: CurrentLocationSource? = null @@ -175,7 +193,7 @@ class LocationTrackingService : Service(), SensorEventListener { internal var networkRequested = false private var networkWatchdogJob: Job? = null private var heartbeatJob: Job? = null- private var trackingInitialized = false+ internal var trackingInitialized = false /** The pre-unlock publish loop; null once the user unlocks and the normal path takes over. */ internal var directBootJob: Job? = null@@ -299,6 +317,16 @@ class LocationTrackingService : Service(), SensorEventListener { } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ // The 15-minute ceiling alarm (#895 follow-up). Only meaningful for a service that+ // is already tracking in the foreground; anything else takes the normal start path.+ if (intent?.action == FixCeilingAlarm.ACTION_CHECK) {+ val tracking = trackingInitialized || directBootJob?.isActive == true+ if (tracking && LocationServiceController.hasFineLocationPermission(this)) {+ onFixCeilingAlarm()+ return START_STICKY+ }+ FixCeilingAlarm.releaseWakeLock()+ } // Defensive: never run location tracking without fine-location permission. // The service can be (re)started by the OS, WorkManager, or BootReceiver, // and the permission may have been revoked since it was scheduled@@ -408,8 +436,10 @@ class LocationTrackingService : Service(), SensorEventListener { withContext(Dispatchers.Main) { stopSelf() } break }- // Stillness re-check, low-power request upkeep and the periodic+ // Arm or cancel the 15-minute ceiling as sharing changes, then the+ // stillness re-check, low-power request upkeep and the periodic // forced fix (#895). Main thread: it owns the motion state.+ refreshFixCeiling() withContext(Dispatchers.Main) { keepAliveTick() } syncHeartbeat() try {@@ -641,6 +671,8 @@ class LocationTrackingService : Service(), SensorEventListener { override fun onDestroy() { super.onDestroy() FinalLocationReporter.stop(this)+ FixCeilingAlarm.cancel(this)+ FixCeilingAlarm.releaseWakeLock() if (unlockReceiverRegistered) { runCatching { unregisterReceiver(unlockReceiver) } unlockReceiverRegistered = false
findfamily/src/test/java/com/vayunmathur/findfamily/domain/ForcedFixPolicyTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/domain/ForcedFixPolicyTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/domain/ForcedFixPolicyTest.ktnew file mode 100644index 0000000000..fbf99c3708--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/domain/ForcedFixPolicyTest.kt@@ -0,0 +1,141 @@+package com.vayunmathur.findfamily.domain++import com.vayunmathur.findfamily.domain.ForcedFixPolicy.ACTIVE_CHECK_DUE_MS+import com.vayunmathur.findfamily.domain.ForcedFixPolicy.ACTIVE_CHECK_MAX_GAP_MS+import com.vayunmathur.findfamily.domain.ForcedFixPolicy.INTERVAL_CHARGING_MS+import com.vayunmathur.findfamily.domain.ForcedFixPolicy.INTERVAL_DEFAULT_MS+import com.vayunmathur.findfamily.domain.ForcedFixPolicy.INTERVAL_POWER_SAVE_MS+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * The 15-minute active-check ceiling (owner requirement on #895) against the existing+ * held-fix staleness intervals, in every power state. Pure: elapsedRealtime-style longs.+ */+class ForcedFixPolicyTest {++ private val minute = 60_000L+ private val t0 = 1_000_000_000L++ @Test+ fun ceilingGuaranteeIsFifteenMinutesAndDueOneMinuteEarly() {+ assertEquals(15 * minute, ACTIVE_CHECK_MAX_GAP_MS)+ assertEquals(14 * minute, ACTIVE_CHECK_DUE_MS)+ }++ @Test+ fun powerStateIntervalsAreUnchanged() {+ assertEquals(5 * minute, ForcedFixPolicy.intervalMs(charging = true, powerSave = false))+ assertEquals(5 * minute, ForcedFixPolicy.intervalMs(charging = true, powerSave = true))+ assertEquals(10 * minute, ForcedFixPolicy.intervalMs(charging = false, powerSave = false))+ assertEquals(15 * minute, ForcedFixPolicy.intervalMs(charging = false, powerSave = true))+ }++ @Test+ fun ceilingIsDueBeforeAnyAttemptAndThenEveryFourteenMinutes() {+ assertTrue(ForcedFixPolicy.isCeilingDue(t0, lastAttemptMs = null))+ assertFalse(ForcedFixPolicy.isCeilingDue(t0 + ACTIVE_CHECK_DUE_MS - 1, lastAttemptMs = t0))+ assertTrue(ForcedFixPolicy.isCeilingDue(t0 + ACTIVE_CHECK_DUE_MS, lastAttemptMs = t0))+ }++ @Test+ fun freshHeldFixNoLongerSuppressesTheCeilingInAnyPowerState() {+ val now = t0 + ACTIVE_CHECK_DUE_MS+ // A passive/low-power fix delivered a second ago keeps the held fix fresh.+ val held = now - 1_000L+ for (interval in listOf(INTERVAL_CHARGING_MS, INTERVAL_DEFAULT_MS, INTERVAL_POWER_SAVE_MS)) {+ assertNull(+ ForcedFixPolicy.dueReason(now, held, lastAttemptMs = t0, interval, ceilingEnabled = false),+ "without the ceiling a fresh held fix suppresses the forced fix (interval $interval)",+ )+ assertEquals(+ ForcedFixReason.ACTIVE_CHECK_CEILING,+ ForcedFixPolicy.dueReason(now, held, lastAttemptMs = t0, interval, ceilingEnabled = true),+ "the ceiling ignores held-fix freshness (interval $interval)",+ )+ }+ }++ @Test+ fun shorterPowerIntervalsStillFireFirstOnAStaleHeldFix() {+ // Charging: a held fix 5 min old with the last attempt 5 min ago is due on staleness,+ // long before the ceiling.+ val now = t0 + INTERVAL_CHARGING_MS+ assertEquals(+ ForcedFixReason.STALE_HELD_FIX,+ ForcedFixPolicy.dueReason(now, heldFixElapsedMs = t0, lastAttemptMs = t0, INTERVAL_CHARGING_MS, true),+ )+ // Battery: 10 min.+ val later = t0 + INTERVAL_DEFAULT_MS+ assertEquals(+ ForcedFixReason.STALE_HELD_FIX,+ ForcedFixPolicy.dueReason(later, heldFixElapsedMs = t0, lastAttemptMs = t0, INTERVAL_DEFAULT_MS, true),+ )+ }++ @Test+ fun ceilingWinsWhenBothAreDue() {+ // Power-save: interval 15 min, ceiling due at 14; at 15 both apply and the ceiling+ // (which may use GPS in power-save) is the reason.+ val now = t0 + INTERVAL_POWER_SAVE_MS+ assertEquals(+ ForcedFixReason.ACTIVE_CHECK_CEILING,+ ForcedFixPolicy.dueReason(now, heldFixElapsedMs = t0, lastAttemptMs = t0, INTERVAL_POWER_SAVE_MS, true),+ )+ }++ @Test+ fun nothingDueRightAfterAnAttempt() {+ val now = t0 + 30_000L+ assertNull(+ ForcedFixPolicy.dueReason(now, heldFixElapsedMs = null, lastAttemptMs = t0, INTERVAL_CHARGING_MS, true),+ )+ }++ @Test+ fun exactAlarmIsArmedForTheMomentTheCheckIsDue() {+ assertEquals(0L, ForcedFixPolicy.ceilingAlarmDelayMs(t0, lastAttemptMs = null, exact = true))+ assertEquals(ACTIVE_CHECK_DUE_MS, ForcedFixPolicy.ceilingAlarmDelayMs(t0, lastAttemptMs = t0, exact = true))+ assertEquals(minute, ForcedFixPolicy.ceilingAlarmDelayMs(t0 + 13 * minute, lastAttemptMs = t0, exact = true))+ assertEquals(0L, ForcedFixPolicy.ceilingAlarmDelayMs(t0 + 20 * minute, lastAttemptMs = t0, exact = true))+ }++ @Test+ fun inexactAlarmChainAlwaysLandsInsideTheCeiling() {+ // Inexact alarms may fire up to 1.75x their delay after being set. Simulate the+ // worst case (every alarm fires at the very end of its window) and the best case+ // (on time) and check the chain reaches a due check before the ceiling.+ for (worstCase in listOf(true, false)) {+ var now = t0+ var wakeUps = 0+ while (!ForcedFixPolicy.isCeilingDue(now, lastAttemptMs = t0)) {+ val delay = ForcedFixPolicy.ceilingAlarmDelayMs(now, lastAttemptMs = t0, exact = false)+ assertTrue(delay > 0L)+ now += if (worstCase) (delay * 1.75).toLong() else delay+ wakeUps+++ assertTrue(now <= t0 + ACTIVE_CHECK_MAX_GAP_MS, "alarm landed after the ceiling (worst=$worstCase)")+ assertTrue(wakeUps < 20, "chain does not converge (worst=$worstCase)")+ }+ }+ }++ @Test+ fun powerSaveUsesGpsOnlyForTheCeiling() {+ // Network answer too coarse to display (500 m > 100 m gate).+ assertFalse(ForcedFixPolicy.shouldFallBackToGps(true, true, 500.0, powerSave = true, ceiling = false))+ assertTrue(ForcedFixPolicy.shouldFallBackToGps(true, true, 500.0, powerSave = true, ceiling = true))+ // No network answer at all.+ assertTrue(ForcedFixPolicy.shouldFallBackToGps(true, true, null, powerSave = true, ceiling = true))+ // A usable network fix never needs GPS.+ assertFalse(ForcedFixPolicy.shouldFallBackToGps(true, true, 30.0, powerSave = true, ceiling = true))+ assertFalse(ForcedFixPolicy.shouldFallBackToGps(true, true, 30.0, powerSave = false, ceiling = true))+ // No GPS provider: nothing to fall back to.+ assertFalse(ForcedFixPolicy.shouldFallBackToGps(false, true, null, powerSave = false, ceiling = true))+ // Off power-save the ceiling behaves like the staleness check.+ assertTrue(ForcedFixPolicy.shouldFallBackToGps(true, true, 500.0, powerSave = false, ceiling = false))+ assertTrue(ForcedFixPolicy.shouldFallBackToGps(true, false, null, powerSave = true, ceiling = false))+ }+}
findfamily/src/test/java/com/vayunmathur/findfamily/platform/FixCeilingAlarmTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/platform/FixCeilingAlarmTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/platform/FixCeilingAlarmTest.ktnew file mode 100644index 0000000000..a4617a526d--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/platform/FixCeilingAlarmTest.kt@@ -0,0 +1,263 @@+package com.vayunmathur.findfamily.platform++import android.Manifest+import android.app.AlarmManager+import android.app.Application+import android.content.Context+import android.content.Intent+import android.location.Location+import android.location.LocationManager+import android.os.BatteryManager+import android.os.Looper+import android.os.SystemClock+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.FFDatabase+import com.vayunmathur.findfamily.data.FindFamilyRepository+import com.vayunmathur.findfamily.data.RequestStatus+import com.vayunmathur.findfamily.data.User+import com.vayunmathur.findfamily.domain.ForcedFixPolicy+import com.vayunmathur.findfamily.util.LocationTrackingService+import com.vayunmathur.findfamily.util.Networking+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.Job+import kotlinx.coroutines.cancel+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.Shadows.shadowOf+import org.robolectric.android.controller.ServiceController+import org.robolectric.shadows.ShadowAlarmManager+import org.robolectric.shadows.ShadowSystemClock+import java.time.Duration+import java.util.Collections+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlin.time.Clock+import kotlin.time.Duration.Companion.seconds++/**+ * The 15-minute active-check ceiling at service level: the Doze-proof alarm is armed while+ * sharing, re-armed after every check, cancelled when sharing stops or the service dies;+ * a ceiling tick asks the current-location source (never last-known) even while a fresh+ * passive fix is held and the movement detector says still; and the result is published+ * through the normal heartbeat path.+ */+@RunWith(AndroidJUnit4::class)+class FixCeilingAlarmTest {++ private lateinit var db: FFDatabase+ private lateinit var repo: FindFamilyRepository+ private lateinit var controller: ServiceController<LocationTrackingService>+ private lateinit var service: LocationTrackingService+ private val ctx: Context get() = ApplicationProvider.getApplicationContext<Application>()+ private val alarms: ShadowAlarmManager get() = shadowOf(service.getSystemService(AlarmManager::class.java))++ private val forcedCalls: MutableList<String> = Collections.synchronizedList(mutableListOf())+ @Volatile private var networkAnswer: Location? = null+ @Volatile private var gpsAnswer: Location? = null++ private fun location(provider: String = LocationManager.GPS_PROVIDER, acc: Float = 10f) =+ Location(provider).apply {+ latitude = 51.5+ longitude = -0.12+ accuracy = acc+ elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos()+ time = System.currentTimeMillis()+ }++ private fun advance(ms: Long) = ShadowSystemClock.advanceBy(Duration.ofMillis(ms))+ private fun now() = SystemClock.elapsedRealtime()++ /** Lets background coroutines that hop onto the (paused) main looper finish. */+ private fun pumpUntil(done: () -> Boolean) {+ val deadline = System.currentTimeMillis() + 10_000L+ while (!done()) {+ check(System.currentTimeMillis() < deadline) { "timed out waiting for the service" }+ shadowOf(Looper.getMainLooper()).idle()+ Thread.sleep(5)+ }+ shadowOf(Looper.getMainLooper()).idle()+ }++ private fun await(job: Job?) {+ assertNotNull(job, "expected a forced fix to start")+ pumpUntil { job.isCompleted }+ }++ @BeforeTest+ fun setup() {+ ShadowAlarmManager.setCanScheduleExactAlarms(true)+ db = Room.inMemoryDatabaseBuilder(ctx, FFDatabase::class.java).allowMainThreadQueries().build()+ repo = FindFamilyRepository(ctx, db)+ controller = Robolectric.buildService(LocationTrackingService::class.java).create()+ service = controller.get()+ service.repositoryOverride = repo+ if (Networking.userid == 0L) {+ runBlocking { Networking.init(repo, DataStoreUtils.getInstance(ctx), "Me") }+ }+ val lm = service.getSystemService(LocationManager::class.java)+ shadowOf(lm).setLocationEnabled(true)+ shadowOf(lm).setProviderEnabled(LocationManager.NETWORK_PROVIDER, true)+ shadowOf(lm).setProviderEnabled(LocationManager.GPS_PROVIDER, true)+ shadowOf(lm).setProviderEnabled(LocationManager.PASSIVE_PROVIDER, true)+ service.currentLocationSourceOverride = CurrentLocationSource { provider, _ ->+ forcedCalls += provider+ if (provider == LocationManager.NETWORK_PROVIDER) networkAnswer else gpsAnswer+ }+ service.lastKnownLocation = location()+ service.registerSensors()+ service.bm = ctx.getSystemService(BatteryManager::class.java)+ }++ @AfterTest+ fun teardown() {+ service.serviceScope.cancel()+ FixCeilingAlarm.releaseWakeLock()+ db.close()+ }++ @Test+ fun sharingArmsAnExactAllowWhileIdleAlarmAndStoppingCancelsIt() {+ assertTrue(alarms.scheduledAlarms.isEmpty(), "no ceiling while sharing with nobody")+ service.updateFixCeiling(true)+ val alarm = assertNotNull(alarms.peekNextScheduledAlarm())+ assertEquals(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarm.getType())+ assertTrue(alarm.isAllowWhileIdle, "must fire in Doze")+ assertEquals(ShadowAlarmManager.WINDOW_EXACT, alarm.windowLengthMs)+ // Never checked yet: due now.+ assertEquals(now(), alarm.triggerAtMs)++ service.updateFixCeiling(false)+ assertTrue(alarms.scheduledAlarms.isEmpty(), "sharing stopped: alarm cancelled")+ }++ @Test+ fun everyCheckMovesTheAlarmToOneCeilingLater() {+ service.updateFixCeiling(true)+ val first = now()+ await(service.fixCeilingAlarmTick())+ assertEquals(listOf(LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER), forcedCalls.toList())+ assertEquals(1, alarms.scheduledAlarms.size)+ assertEquals(first + ForcedFixPolicy.ACTIVE_CHECK_DUE_MS, alarms.peekNextScheduledAlarm()?.triggerAtMs)++ advance(ForcedFixPolicy.ACTIVE_CHECK_DUE_MS)+ val second = now()+ await(service.fixCeilingAlarmTick())+ assertEquals(1, alarms.scheduledAlarms.size, "moved, not duplicated")+ assertEquals(second + ForcedFixPolicy.ACTIVE_CHECK_DUE_MS, alarms.peekNextScheduledAlarm()?.triggerAtMs)+ }++ @Test+ fun ceilingAsksForACurrentFixDespiteAFreshPassiveFixAndStillMotion() = runBlocking {+ service.updateFixCeiling(true)+ networkAnswer = location(LocationManager.NETWORK_PROVIDER, acc = 30f)+ await(service.fixCeilingAlarmTick())+ forcedCalls.clear()+ // Every publish inserts a self row (autogenerated id; timestamps are epoch seconds,+ // so count rows rather than compare stamps).+ val publishesBefore = repo.locationHistory(Networking.userid).first().size+ assertTrue(publishesBefore >= 1, "the first check was published too")++ // Thirteen minutes of passive fixes (another app's GPS) keep the held fix fresh,+ // and the phone does not move: before the ceiling nothing asks for a fix...+ repeat(13) {+ advance(60_000L)+ service.passiveListener.onLocationChanged(location(LocationManager.PASSIVE_PROVIDER, acc = 15f))+ assertEquals(null, service.fixCeilingAlarmTick(), "no check before the ceiling (minute ${it + 1})")+ }+ assertFalse(service.isMoving)+ assertTrue(forcedCalls.isEmpty())++ // ...and at the ceiling the current-location source is asked anyway.+ advance(60_000L)+ service.passiveListener.onLocationChanged(location(LocationManager.PASSIVE_PROVIDER, acc = 15f))+ await(service.fixCeilingAlarmTick())+ assertEquals(listOf(LocationManager.NETWORK_PROVIDER), forcedCalls.toList(), "network was good enough")+ assertFalse(service.isMoving, "the check does not need movement")++ // Same place, but the check is published through the normal path right away.+ val history = repo.locationHistory(Networking.userid).first()+ assertEquals(publishesBefore + 1, history.size, "the checked fix was published")+ assertTrue(Clock.System.now() - history.maxOf { it.timestamp } < 60.seconds)+ }++ @Test+ fun powerSaveCeilingFallsBackToGpsButTheStalenessCheckStillDoesNot() {+ shadowOf(service.powerManager).setIsPowerSaveMode(true)+ networkAnswer = location(LocationManager.NETWORK_PROVIDER, acc = 500f)+ gpsAnswer = location(acc = 8f)++ // Ceiling off (not sharing): a stale held fix in power-save stays network-only.+ advance(ForcedFixPolicy.INTERVAL_POWER_SAVE_MS)+ await(service.fixCeilingAlarmTick())+ assertEquals(listOf(LocationManager.NETWORK_PROVIDER), forcedCalls.toList())++ // Ceiling on: the 15-minute check tries GPS when network is unusable.+ forcedCalls.clear()+ service.updateFixCeiling(true)+ advance(ForcedFixPolicy.ACTIVE_CHECK_DUE_MS)+ await(service.fixCeilingAlarmTick())+ assertEquals(listOf(LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER), forcedCalls.toList())+ }++ @Test+ fun inexactFallbackArmsEarlyEnoughToLandInsideTheCeiling() {+ ShadowAlarmManager.setCanScheduleExactAlarms(false)+ service.updateFixCeiling(true)+ val checkedAt = now()+ await(service.fixCeilingAlarmTick())+ val alarm = assertNotNull(alarms.peekNextScheduledAlarm())+ assertTrue(alarm.isAllowWhileIdle)+ val delay = alarm.triggerAtMs - checkedAt+ // Latest inexact delivery is 1.75x the delay after arming.+ assertTrue(checkedAt + (delay * 1.75).toLong() <= checkedAt + ForcedFixPolicy.ACTIVE_CHECK_MAX_GAP_MS)+ assertTrue(delay > 0L)+ }++ @Test+ fun receiverHoldsTheCpuAndPokesTheRunningService() {+ FixCeilingReceiver().onReceive(ctx, Intent(FixCeilingAlarm.ACTION_ALARM))+ val started = assertNotNull(shadowOf(ctx as Application).nextStartedService)+ assertEquals(FixCeilingAlarm.ACTION_CHECK, started.action)+ assertEquals(LocationTrackingService::class.java.name, started.component?.className)+ assertTrue(FixCeilingAlarm.isWakeLockHeld)+ FixCeilingAlarm.releaseWakeLock()+ assertFalse(FixCeilingAlarm.isWakeLockHeld)+ }++ @Test+ fun alarmCommandChecksReArmsAndReleasesTheCpu() = runBlocking {+ repo.upsertUser(+ User(+ name = "Peer", photo = null, locationName = "Elsewhere", sendingEnabled = true,+ requestStatus = RequestStatus.MUTUAL_CONNECTION, lastLocationChangeTime = Clock.System.now(),+ )+ )+ service.trackingInitialized = true+ shadowOf(ctx as Application).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+ FixCeilingAlarm.acquireWakeLock(ctx)+ val firedAt = now()+ val command = Intent(service, LocationTrackingService::class.java).setAction(FixCeilingAlarm.ACTION_CHECK)+ service.onStartCommand(command, 0, 1)+ pumpUntil { !FixCeilingAlarm.isWakeLockHeld }+ assertTrue(service.fixCeilingEnabled, "a peer with sending on means sharing")+ assertEquals(LocationManager.NETWORK_PROVIDER, forcedCalls.firstOrNull())+ assertEquals(firedAt + ForcedFixPolicy.ACTIVE_CHECK_DUE_MS, alarms.peekNextScheduledAlarm()?.triggerAtMs)+ }++ @Test+ fun destroyingTheServiceCancelsTheAlarm() {+ service.updateFixCeiling(true)+ assertEquals(1, alarms.scheduledAlarms.size)+ controller.destroy()+ assertTrue(alarms.scheduledAlarms.isEmpty())+ }+}
findfamily/src/test/java/com/vayunmathur/findfamily/platform/LocationKeepAliveTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/platform/LocationKeepAliveTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/platform/LocationKeepAliveTest.ktindex 1979486a47..ffeceb8585 100644--- a/findfamily/src/test/java/com/vayunmathur/findfamily/platform/LocationKeepAliveTest.kt+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/platform/LocationKeepAliveTest.kt@@ -12,6 +12,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4 import com.vayunmathur.findfamily.data.FFDatabase import com.vayunmathur.findfamily.data.FindFamilyRepository import com.vayunmathur.findfamily.domain.ForcedFixPolicy+import com.vayunmathur.findfamily.domain.ForcedFixReason import com.vayunmathur.findfamily.domain.MotionTransition import com.vayunmathur.findfamily.domain.MovementDetector import com.vayunmathur.findfamily.util.LocationTrackingService@@ -28,6 +29,7 @@ import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse+import kotlin.test.assertNull import kotlin.test.assertSame import kotlin.test.assertTrue @@ -152,19 +154,19 @@ class LocationKeepAliveTest { @Test fun staleHeldFixRequestsAForcedFixOncePerInterval() {- assertFalse(service.forcedFixDue(SystemClock.elapsedRealtime()), "fresh fix: nothing due")+ assertNull(service.forcedFixDue(SystemClock.elapsedRealtime()), "fresh fix: nothing due") advance(ForcedFixPolicy.INTERVAL_DEFAULT_MS)- assertTrue(service.forcedFixDue(SystemClock.elapsedRealtime()))+ assertEquals(ForcedFixReason.STALE_HELD_FIX, service.forcedFixDue(SystemClock.elapsedRealtime())) // The attempt is recorded: the next heartbeat tick does not retry. advance(30_000L)- assertFalse(service.forcedFixDue(SystemClock.elapsedRealtime()))+ assertNull(service.forcedFixDue(SystemClock.elapsedRealtime())) } @Test fun chargingTightensTheForcedFixInterval() { shadowOf(service.bm).setIsCharging(true) advance(ForcedFixPolicy.INTERVAL_CHARGING_MS)- assertTrue(service.forcedFixDue(SystemClock.elapsedRealtime()))+ assertEquals(ForcedFixReason.STALE_HELD_FIX, service.forcedFixDue(SystemClock.elapsedRealtime())) } @Test