diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/compose/BackgroundTime.android.kt b/composeApp/src/androidMain/kotlin/mobi/giza/compose/BackgroundTime.android.kt new file mode 100644 index 00000000..4c32d784 --- /dev/null +++ b/composeApp/src/androidMain/kotlin/mobi/giza/compose/BackgroundTime.android.kt @@ -0,0 +1,8 @@ +package mobi.giza.compose + +import kotlin.time.Duration + +actual val platformBackgroundGrace: Duration = Duration.ZERO + +/** Android's background work is WorkManager's (Phase 10); there is no task to wrap. */ +actual suspend fun inPlatformBackgroundTask(name: String, block: suspend () -> T): T? = block() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/AppLifecycle.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/AppLifecycle.kt index b2eacabb..ef009070 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/AppLifecycle.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/AppLifecycle.kt @@ -3,30 +3,77 @@ package mobi.giza.compose import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update /** - * Whether the app is in the foreground, for the parts of the app that hold network - * connections open. + * Whether the app is on screen, and whether it should hold its relay connections open -- two + * questions that used to be one. docs/notifications-and-background-sync.md, Phase 8. * * A singleton rather than something threaded through the composition, because the consumers * are not composables: they are long-lived coroutines at application scope, started before * any screen exists and outliving all of them. * - * Defaults to foreground. Nothing here can observe a platform that has not wired + * They came apart because the answers differ by platform. A phone that is not on screen is about + * to be suspended, so its subscriptions close; a desktop window that is minimised is still a + * running process with a network, and Compose Desktop reports a minimised window as stopped, so + * the single flag used to close a desktop's subscriptions every time it was minimised. + * + * Both default to true. Nothing here can observe a platform that has not wired * [enteredForeground]/[enteredBackground] up, and on such a platform "always on" is the - * behaviour that predates this file — a subscription that never opens is a far worse failure + * behaviour that predates this file -- a subscription that never opens is a far worse failure * than one that stays open too long. */ object AppLifecycle { - private val _isForeground = MutableStateFlow(true) + private val _isVisible = MutableStateFlow(true) - val isForeground: StateFlow = _isForeground.asStateFlow() + /** Somebody is looking: read by read marks and by the notification policy. */ + val isVisible: StateFlow = _isVisible.asStateFlow() + + /** Reasons, other than being on screen, to keep the connections open. */ + private val keepers = MutableStateFlow>(emptySet()) + + private val _holdConnections = MutableStateFlow(true) + + /** + * Whether the live subscriptions should be open: on screen, or something has asked to keep + * them -- the desktop for as long as it runs, the iOS grace after backgrounding, Android's + * Stay connected service. + */ + val holdConnections: StateFlow = _holdConnections.asStateFlow() fun enteredForeground() { - _isForeground.value = true + _isVisible.value = true + recompute() } fun enteredBackground() { - _isForeground.value = false + _isVisible.value = false + recompute() } + + /** Keeps the connections open for [reason] until [release] is called with it. */ + fun keepConnected(reason: String) { + keepers.update { it + reason } + recompute() + } + + fun release(reason: String) { + keepers.update { it - reason } + recompute() + } + + private fun recompute() { + _holdConnections.value = _isVisible.value || keepers.value.isNotEmpty() + } + + /** For a test, which has to start from a known state. */ + internal fun reset() { + _isVisible.value = true + keepers.value = emptySet() + recompute() + } + + const val KEEP_DESKTOP = "desktop" + const val KEEP_GRACE = "grace" + const val KEEP_STAY_CONNECTED = "stayConnected" } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/BackgroundTime.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/BackgroundTime.kt new file mode 100644 index 00000000..91587f05 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/BackgroundTime.kt @@ -0,0 +1,19 @@ +package mobi.giza.compose + +import kotlin.time.Duration + +/** + * How long the platform lets a backgrounded app keep working before it is suspended, as far as + * this app means to use it: iOS grants a background task about thirty seconds, which is what it + * takes to finish sending what was queued (D11). Zero elsewhere -- Android's cached-app freezer + * stops a backgrounded process within seconds, and a desktop is not suspended at all. + * docs/notifications-and-background-sync.md, Phase 8. + */ +expect val platformBackgroundGrace: Duration + +/** + * Runs [block] as a platform background task, so the platform does not suspend the process under + * it; null when the platform takes the time back first. On a platform with no such thing, runs + * [block] as it is. + */ +expect suspend fun inPlatformBackgroundTask(name: String, block: suspend () -> T): T? diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt index 4ddfc99a..f692b0ba 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt @@ -10,6 +10,8 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlin.time.Duration import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.map @@ -136,7 +138,7 @@ class GizaRuntime( database = auxDatabaseManager.auxDatabase, notifier = notifier, strings = { NotificationResources.strings() }, - appVisible = AppLifecycle.isForeground, + appVisible = AppLifecycle.isVisible, visibleChatRoomId = VisibleConversation.chatRoomId, syncPending = { publicKey -> nostrRepository.observePendingNegentropySynchronizeRequests(publicKey).map { it != null } @@ -159,6 +161,35 @@ class GizaRuntime( } } + private var graceJob: Job? = null + + /** + * The app left the screen. Where the platform grants a moment (iOS), the connections are held + * for it, inside a background task, so what was queued can still be sent. Phase 8. + */ + fun enteredBackground() { + AppLifecycle.enteredBackground() + if (platformBackgroundGrace <= Duration.ZERO) return + graceJob?.cancel() + graceJob = ioScope.launch { + inPlatformBackgroundTask("giza-grace") { + AppLifecycle.keepConnected(AppLifecycle.KEEP_GRACE) + try { + delay(platformBackgroundGrace) + } finally { + AppLifecycle.release(AppLifecycle.KEEP_GRACE) + } + } + } + } + + fun enteredForeground() { + graceJob?.cancel() + graceJob = null + AppLifecycle.release(AppLifecycle.KEEP_GRACE) + AppLifecycle.enteredForeground() + } + companion object { private const val TAG = "GizaRuntime" diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/LiveSubscriptionManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/LiveSubscriptionManager.kt index 5e75d1d7..35cc4d55 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/LiveSubscriptionManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/LiveSubscriptionManager.kt @@ -74,7 +74,8 @@ class LiveSubscriptionManager( private val relaysSocketManager: LiveSubscriptionTransport, private val nostrRepository: NostrRepository, private val chatRepository: ChatRepository, - private val isForeground: StateFlow, + /** `AppLifecycle.holdConnections`: open while true, closed while false. */ + private val holdConnections: StateFlow, /** * Where confederation events heard on a relay are filed, rather than as `NostrEvent` rows * (docs/confederation.md, Phase 5). Null, or the feature off, and nothing is asked for. @@ -267,7 +268,7 @@ class LiveSubscriptionManager( // collectLatest is the whole lifecycle mechanism: going to the background cancels the // block below, and every subscription's `finally` sends its CLOSE on the way out. - isForeground.collectLatest { foreground -> + holdConnections.collectLatest { foreground -> if (!foreground) { logger.i("Backgrounded; live subscriptions closed") return@collectLatest diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/VisibleConversation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/VisibleConversation.kt index 643f368d..a1ecc6d4 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/VisibleConversation.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/VisibleConversation.kt @@ -48,7 +48,7 @@ fun MarkReadWhileVisible( chatRoomId: String, chatRepository: ChatRepository, ) { - val inFront by AppLifecycle.isForeground.collectAsState() + val inFront by AppLifecycle.isVisible.collectAsState() DisposableEffect(chatRoomId) { VisibleConversation.entered(chatRoomId) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt index df886700..4f043e50 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt @@ -228,8 +228,8 @@ fun GizaNavHost( DisposableEffect(lifecycleOwner) { val observer = LifecycleEventObserver { _, event -> when (event) { - Lifecycle.Event.ON_START -> AppLifecycle.enteredForeground() - Lifecycle.Event.ON_STOP -> AppLifecycle.enteredBackground() + Lifecycle.Event.ON_START -> runtime.enteredForeground() + Lifecycle.Event.ON_STOP -> runtime.enteredBackground() else -> Unit } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt index dcdf3bf7..d7f60b90 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt @@ -93,7 +93,7 @@ class SynchronizationViewModel( relaysSocketManager = relaysSocketManager, nostrRepository = nostrRepository, chatRepository = chatRepository, - isForeground = AppLifecycle.isForeground, + holdConnections = AppLifecycle.holdConnections, confederationRepository = confederationRepository, groupInboxRepository = groupInboxRepository, ) diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/AppLifecycleTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/AppLifecycleTest.kt new file mode 100644 index 00000000..092212d4 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/AppLifecycleTest.kt @@ -0,0 +1,40 @@ +package mobi.giza.compose + +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** Visible and connected are two answers now. docs/notifications-and-background-sync.md, Phase 8. */ +class AppLifecycleTest { + + @AfterTest + fun reset() = AppLifecycle.reset() + + @Test + fun `a phone off screen is neither visible nor connected`() { + AppLifecycle.enteredBackground() + assertFalse(AppLifecycle.isVisible.value) + assertFalse(AppLifecycle.holdConnections.value) + AppLifecycle.enteredForeground() + assertTrue(AppLifecycle.holdConnections.value) + } + + /** The bug Phase 0, check 1 found: minimising the desktop window closed its subscriptions. */ + @Test + fun `a minimised desktop is not visible, and stays connected`() { + AppLifecycle.keepConnected(AppLifecycle.KEEP_DESKTOP) + AppLifecycle.enteredBackground() + assertFalse(AppLifecycle.isVisible.value) + assertTrue(AppLifecycle.holdConnections.value) + } + + @Test + fun `a grace holds the connections until it is released`() { + AppLifecycle.enteredBackground() + AppLifecycle.keepConnected(AppLifecycle.KEEP_GRACE) + assertTrue(AppLifecycle.holdConnections.value) + AppLifecycle.release(AppLifecycle.KEEP_GRACE) + assertFalse(AppLifecycle.holdConnections.value) + } +} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ConfederationRelayTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ConfederationRelayTest.kt index b8427194..0a3d6a52 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ConfederationRelayTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ConfederationRelayTest.kt @@ -185,7 +185,7 @@ class ConfederationRelayTest { relaysSocketManager = transport, nostrRepository = nostr, chatRepository = ConfederationRooms(MutableStateFlow(rooms)), - isForeground = MutableStateFlow(true), + holdConnections = MutableStateFlow(true), confederationRepository = repository, ).observe(keyPair) } diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/LiveSubscriptionReconcileTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/LiveSubscriptionReconcileTest.kt index 6f51b00a..56ff51bd 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/LiveSubscriptionReconcileTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/LiveSubscriptionReconcileTest.kt @@ -275,7 +275,7 @@ class LiveSubscriptionReconcileTest { fun `backgrounding closes the subscriptions and foregrounding rebuilds them`() = runTest { val transport = FakeTransport() val foreground = MutableStateFlow(true) - val running = start(transport, MutableStateFlow(emptyList()), isForeground = foreground) + val running = start(transport, MutableStateFlow(emptyList()), holdConnections = foreground) settle() val openedWhileForeground = transport.opened.size @@ -332,13 +332,13 @@ class LiveSubscriptionReconcileTest { transport: FakeTransport, rooms: MutableStateFlow>, nostr: RecordingNostrRepository = RecordingNostrRepository(), - isForeground: MutableStateFlow = MutableStateFlow(true), + holdConnections: MutableStateFlow = MutableStateFlow(true), ) = launch { LiveSubscriptionManager( relaysSocketManager = transport, nostrRepository = nostr, chatRepository = FakeChatRepository(rooms), - isForeground = isForeground, + holdConnections = holdConnections, ).observe(keyPair) } diff --git a/composeApp/src/iosMain/kotlin/mobi/giza/compose/BackgroundTime.ios.kt b/composeApp/src/iosMain/kotlin/mobi/giza/compose/BackgroundTime.ios.kt new file mode 100644 index 00000000..55f5121e --- /dev/null +++ b/composeApp/src/iosMain/kotlin/mobi/giza/compose/BackgroundTime.ios.kt @@ -0,0 +1,39 @@ +package mobi.giza.compose + +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope +import platform.UIKit.UIApplication +import platform.UIKit.UIBackgroundTaskInvalid + +/** Under the thirty seconds iOS grants, so the task is ended by us and not expired by it. */ +actual val platformBackgroundGrace: Duration = 25.seconds + +/** + * `beginBackgroundTask` around [block], ended exactly once: when [block] finishes, or when iOS + * takes the time back, which cancels it. Not compiled on the linux host this was written on. + */ +actual suspend fun inPlatformBackgroundTask(name: String, block: suspend () -> T): T? = coroutineScope { + val work = async { block() } + val application = UIApplication.sharedApplication + var ended = false + var taskId = UIBackgroundTaskInvalid + fun end() { + if (ended || taskId == UIBackgroundTaskInvalid) return + ended = true + application.endBackgroundTask(taskId) + } + taskId = application.beginBackgroundTaskWithName(name) { + work.cancel() + end() + } + try { + work.await() + } catch (expired: CancellationException) { + null + } finally { + end() + } +} diff --git a/composeApp/src/jvmMain/kotlin/mobi/giza/compose/BackgroundTime.jvm.kt b/composeApp/src/jvmMain/kotlin/mobi/giza/compose/BackgroundTime.jvm.kt new file mode 100644 index 00000000..824cf389 --- /dev/null +++ b/composeApp/src/jvmMain/kotlin/mobi/giza/compose/BackgroundTime.jvm.kt @@ -0,0 +1,8 @@ +package mobi.giza.compose + +import kotlin.time.Duration + +/** A desktop process is not suspended; it holds its connections for as long as it runs instead. */ +actual val platformBackgroundGrace: Duration = Duration.ZERO + +actual suspend fun inPlatformBackgroundTask(name: String, block: suspend () -> T): T? = block() diff --git a/composeApp/src/jvmMain/kotlin/mobi/giza/desktop/Main.kt b/composeApp/src/jvmMain/kotlin/mobi/giza/desktop/Main.kt index 4b8fbd2c..2e4e4c1c 100644 --- a/composeApp/src/jvmMain/kotlin/mobi/giza/desktop/Main.kt +++ b/composeApp/src/jvmMain/kotlin/mobi/giza/desktop/Main.kt @@ -38,6 +38,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import mobi.giza.compose.GizaApp import mobi.giza.compose.GizaGlobal +import mobi.giza.compose.AppLifecycle import mobi.giza.compose.GizaRuntime import mobi.giza.compose.PlatformContext import mobi.giza.compose.defaultGizaDir @@ -107,6 +108,10 @@ fun main() = application { // After the passphrase, never before: the runtime's database and engines are // the first things that read the key store. docs/notifications-and-background-sync.md, D4. val runtime = remember { + // A minimised window is reported as stopped, which would close every + // subscription; a desktop process is not suspended, so it keeps them for as + // long as it runs. docs/notifications-and-background-sync.md, Phase 8. + AppLifecycle.keepConnected(AppLifecycle.KEEP_DESKTOP) GizaRuntime.getOrCreate { GizaRuntime( gizaGlobal = GizaGlobal(platformContext = PlatformContext(appDir)),