feat: one bounded sync while off screen, on the app's own engines (notifications, Phase 9)

BackgroundSyncPass activates the default signing profile when no screen
has, holds the connections so the live subscriptions and the foreground
catch-up run as they would on launch, waits for the sync queue to drain
and the outbound queue to stop moving or for its deadline, posts what
arrived, lets go and records the outcome on the ledger.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-22 12:46:23 +02:00
1 parent 74c7a0dd7f
commit 4a6f45aac8
6 files changed
+494 -1

No files matched your search

@@ -76,4 +76,5 @@ object AppLifecycle {
const val KEEP_DESKTOP = "desktop"
const val KEEP_GRACE = "grace"
const val KEEP_STAY_CONNECTED = "stayConnected"
const val KEEP_BACKGROUND_PASS = "backgroundPass"
}
@@ -14,6 +14,9 @@ import kotlinx.coroutines.delay
import kotlin.time.Duration
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import mobi.giza.compose.identity.DefaultIdentity
import mobi.giza.compose.managers.BackgroundSyncPass
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import mobi.giza.compose.notifications.NotificationDispatcher
@@ -161,6 +164,35 @@ class GizaRuntime(
}
}
/**
* One bounded sync while off screen, run by the platform's scheduler: WorkManager, a
* BGTaskScheduler task. docs/notifications-and-background-sync.md, Phase 9.
*/
val backgroundSync: BackgroundSyncPass by lazy {
BackgroundSyncPass(
activeIdentity = activeIdentity,
loadDefaultIdentity = { DefaultIdentity.load(phoenixGlobal) },
startEngines = {
synchronization
notary
notifications
},
syncPending = { publicKey ->
nostrRepository.observePendingNegentropySynchronizeRequests(publicKey).map { it != null }
},
outboundQueued = { publicKey ->
combine(
chatRepository.observeUnsealedGiftWrapPayloads(publicKey).map { it.size },
marmotRepository.observeUnprocessedMarmotInnerEvents(publicKey).map { it.size },
nostrRepository.observeUnsignedNostrEvents(publicKey).map { it.size },
nostrRepository.observePendingBroadcastNostrEventRequests().map { if (it != null) 1 else 0 },
) { seals, inner, unsigned, broadcast -> seals + inner + unsigned + broadcast }
},
dispatcher = notificationDispatcher,
ledger = auxDatabaseManager.auxDatabase.notificationDao(),
)
}
private var graceJob: Job? = null
/**
@@ -0,0 +1,74 @@
package mobi.giza.compose.identity
import co.touchlab.kermit.Logger
import fr.acinq.phoenix.PhoenixGlobal
import fr.acinq.phoenix.data.DecryptNostrCredentialsResult
import fr.acinq.phoenix.data.DecryptSeedResult
import fr.acinq.phoenix.data.WalletId
import fr.acinq.phoenix.managers.DataStoreManager
import fr.acinq.phoenix.managers.NostrCredentialManager
import kotlinx.coroutines.flow.first
import mobi.giza.compose.extensions.getGlobalPrefs
import mobi.giza.compose.ui.view.model.loadAndDecryptSeed
/**
* The profile that opens on launch, read with no screen and no view model: what a background
* sync runs as. docs/notifications-and-background-sync.md, D6 and Phase 9.
*
* The reading half of `SovereignWalletViewModel.listIdentities`, without its two writes -- the
* migration of an old key file and the repair of a seed's missing credential. Both belong to a
* launch somebody is watching; a background job that rewrote a credentials file nobody could see
* fail would be the wrong place for either. A seed whose credential is missing is still found, by
* the derivation the repair would have written.
*
* Null for anything but a signing profile: none chosen, its files unreadable, or a public key
* only -- which can open no gift wrap and so has nothing to sync for.
*/
object DefaultIdentity {
private val logger = Logger.withTag("DefaultIdentity")
suspend fun load(phoenixGlobal: PhoenixGlobal): Identity? {
val defaultId = getGlobalPrefs(phoenixGlobal).getDefaultWallet.first() as? WalletId ?: return null
val wallets = when (val result = loadAndDecryptSeed(phoenixGlobal)) {
is DecryptSeedResult.Success -> result.userWalletsMap
is DecryptSeedResult.Failure.SeedFileNotFound -> emptyMap()
else -> {
logger.w { "Seed file unreadable in the background: $result" }
emptyMap()
}
}
val credentials = when (val result = NostrCredentialManager.loadAndDecrypt(phoenixGlobal)) {
is DecryptNostrCredentialsResult.Success -> result.credentials
is DecryptNostrCredentialsResult.Failure.FileNotFound -> emptyMap()
else -> {
logger.w { "Credentials unreadable in the background: $result" }
emptyMap()
}
}
val stored = StoredIdentity.merge(wallets, credentials)[defaultId]
?: wallets[defaultId]?.let { StoredIdentity.mnemonic(it) }
?: return null
val dataStoreManager = DataStoreManager(ctx = phoenixGlobal.ctx, chain = PROFILE_CHAIN)
return when (stored) {
is StoredIdentity.Mnemonic -> Identity.signing(
id = stored.id,
kind = IdentityKind.Mnemonic,
nostrPrivateKey = stored.privateKey,
userPrefs = dataStoreManager.loadUserPrefsForWallet(stored.id),
internalPrefs = dataStoreManager.loadInternalPrefsForWallet(stored.id),
)
is StoredIdentity.NostrSecret -> Identity.signing(
id = stored.id,
kind = IdentityKind.NostrSecret,
nostrPrivateKey = stored.privateKey,
userPrefs = dataStoreManager.loadUserPrefsForWallet(stored.id),
internalPrefs = dataStoreManager.loadInternalPrefsForWallet(stored.id),
)
is StoredIdentity.NostrPublic -> null
}
}
}
@@ -0,0 +1,154 @@
package mobi.giza.compose.managers
import co.touchlab.kermit.Logger
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlin.time.Clock
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
import kotlin.time.Instant
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.transformLatest
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.withTimeoutOrNull
import mobi.giza.compose.AppLifecycle
import mobi.giza.compose.database.dao.NotificationDao
import mobi.giza.compose.identity.Identity
import mobi.giza.compose.notifications.NotificationDispatcher
/**
* One bounded sync while the app is off screen: what returning to the foreground does, on a
* timer, with a deadline. docs/notifications-and-background-sync.md, D5, D6, D11 and Phase 9.
*
* It runs the app's own engines rather than a copy of them. If no screen has set an identity --
* a worker's process, a background task launched cold -- it activates the default profile in the
* runtime, which starts the same pumps, live subscriptions, notary and dispatcher a launch would;
* it then holds the connections open, which makes `LiveSubscriptionManager` reconnect, open its
* subscriptions (whose `limit` is the quick catch-up) and queue the negentropy reconciliation (the
* full one); and it waits until the sync queue and the outbound queues have both been quiet for a
* while, or the deadline comes. Then it lets go, and the engines it started stop with the identity.
*
* So everything a pass does is something the app already does while open, and the Welcome that
* makes a new room widens the group filter by the same loop the live tier already closes. What the
* pass adds is only the bounds, and the record in the ledger.
*/
class BackgroundSyncPass(
private val activeIdentity: MutableStateFlow<Identity?>,
private val loadDefaultIdentity: suspend () -> Identity?,
/** Touches the runtime's lazy engines, so they are running for the identity once it is set. */
private val startEngines: () -> Unit,
private val syncPending: suspend (HexKey) -> Flow<Boolean>,
/**
* How many things this identity has queued to send. Read for change, not for emptiness: a row
* that can never be sent would otherwise hold every pass to its deadline.
*/
private val outboundQueued: suspend (HexKey) -> Flow<Int>,
private val dispatcher: NotificationDispatcher,
private val ledger: NotificationDao,
private val isVisible: StateFlow<Boolean> = AppLifecycle.isVisible,
private val keepConnected: (String) -> Unit = AppLifecycle::keepConnected,
private val release: (String) -> Unit = AppLifecycle::release,
private val clock: () -> Instant = { Clock.System.now() },
/** How long both queues must stay empty before the pass calls the network quiet. */
private val quietFor: Duration = 5.seconds,
) {
private val logger = Logger.withTag(TAG)
private val mutex = Mutex()
enum class Kind(val wire: String) {
/** For a short budget (iOS app refresh): whatever the subscriptions bring before the deadline. */
Quick("quick"),
/** For a longer one (WorkManager, iOS processing): until the reconciliation drains too. */
Full("full"),
}
enum class Outcome(val wire: String) {
Completed("completed"),
Deadline("deadline"),
/** The app is on screen; its own subscriptions already cover this. */
Visible("visible"),
NoIdentity("noIdentity"),
/** Another pass is running in this process. */
AlreadyRunning("alreadyRunning"),
Failed("failed"),
}
suspend fun run(kind: Kind, deadline: Duration): Outcome {
if (!mutex.tryLock()) return Outcome.AlreadyRunning
try {
if (isVisible.value) return Outcome.Visible
val running = activeIdentity.value?.takeIf { it.nostrPrivateKey != null }
val identity = running ?: loadDefaultIdentity() ?: return Outcome.NoIdentity
val publicKey = identity.nostrPublicKey
val activatedHere = running == null
logger.i { "Background ${kind.wire} pass for $publicKey, deadline $deadline" }
val outcome = try {
startEngines()
if (activatedHere) activeIdentity.value = identity
keepConnected(AppLifecycle.KEEP_BACKGROUND_PASS)
val settled = withTimeoutOrNull(deadline) {
awaitQuiet(publicKey, minimum = if (kind == Kind.Quick) MINIMUM_QUICK else MINIMUM_FULL)
}
// Whatever arrived is filed already; this only makes sure it was decided about before
// the platform suspends us.
dispatcher.dispatchPending(publicKey)
if (settled != null) Outcome.Completed else Outcome.Deadline
} catch (cancelled: CancellationException) {
throw cancelled
} catch (failure: Throwable) {
logger.e("Background pass failed", failure)
Outcome.Failed
} finally {
release(AppLifecycle.KEEP_BACKGROUND_PASS)
// Only what this pass started: a screen that came up meanwhile, or set the identity
// before the pass began, keeps it.
if (activatedHere && !isVisible.value && activeIdentity.value == identity) activeIdentity.value = null
}
runCatching { ledger.recordBackgroundSync(publicKey, clock(), outcome.wire, kind.wire) }
logger.i { "Background ${kind.wire} pass for $publicKey: ${outcome.wire}" }
return outcome
} finally {
mutex.unlock()
}
}
/**
* Waits at least [minimum] -- long enough for subscriptions to reach EOSE, which no queue
* records -- and until the sync queue is empty and the outbound queue has not moved, both for
* [quietFor]. A queue that is draining moves; one that is stuck does not, and is no reason to
* stay awake.
*/
@OptIn(ExperimentalCoroutinesApi::class)
private suspend fun awaitQuiet(publicKey: HexKey, minimum: Duration) {
delay(minimum)
combine(syncPending(publicKey), outboundQueued(publicKey)) { sync, outbound -> sync to outbound }
.distinctUntilChanged()
.transformLatest { (sync, _) ->
if (!sync) {
delay(quietFor)
emit(Unit)
}
}
.first()
}
companion object {
private const val TAG = "BackgroundSyncPass"
private val MINIMUM_QUICK = 8.seconds
private val MINIMUM_FULL = 15.seconds
}
}
@@ -80,7 +80,14 @@ class NotificationDispatcher(
* Decides about every line above the cursor, posts what passes, moves the cursor past all of
* them, and returns what was posted. Does nothing for an identity that is not armed.
*/
suspend fun dispatchPending(userPublicKey: HexKey): List<RoomNotification> {
suspend fun dispatchPending(userPublicKey: HexKey): List<RoomNotification> = dispatchMutex.withLock {
dispatchPendingLocked(userPublicKey)
}
/** The run loop and a background pass both dispatch; one at a time, or a line posts twice. */
private val dispatchMutex = Mutex()
private suspend fun dispatchPendingLocked(userPublicKey: HexKey): List<RoomNotification> {
val posted = mutableListOf<RoomNotification>()
while (true) {
val ledger = dao.getLedger(userPublicKey) ?: return posted
@@ -0,0 +1,225 @@
package mobi.giza.compose.managers
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.room3.Room
import fr.acinq.bitcoin.ByteVector32
import fr.acinq.bitcoin.PrivateKey
import fr.acinq.phoenix.utils.preferences.InternalPrefs
import fr.acinq.phoenix.utils.preferences.UserPrefs
import java.util.Collections
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
import kotlin.time.Clock
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.runBlocking
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.builder.getRoomDatabase
import mobi.giza.compose.database.model.ChatMessage
import mobi.giza.compose.database.model.ChatRoom
import mobi.giza.compose.database.model.NostrEvent
import mobi.giza.compose.database.model.Profile
import mobi.giza.compose.identity.Identity
import mobi.giza.compose.identity.IdentityKind
import mobi.giza.compose.identity.toWalletId
import mobi.giza.compose.notifications.NotificationDispatcher
import mobi.giza.compose.notifications.NotificationStrings
import mobi.giza.compose.notifications.PlatformNotifier
import mobi.giza.compose.notifications.RoomNotification
import okio.Path.Companion.toPath
import org.junit.Rule
import org.junit.rules.TemporaryFolder
/**
* The bounds around the app's own engines: when a pass runs at all, what it activates and puts
* back, when it calls the network quiet, and what it records. docs/notifications-and-background-sync.md, Phase 9.
*
* The engines themselves -- subscriptions, reconciliation, ingest -- are the ones the foreground
* runs and are tested where they live. Here "the relay delivered a message" is a line written while
* the pass is waiting, which is what a delivery is by the time anything here can see it.
*/
class BackgroundSyncPassJvmTest {
@get:Rule
val temporaryFolder = TemporaryFolder()
private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder<GizaDatabase>())
@AfterTest
fun closeDb() = db.close()
private val privateKey = PrivateKey(ByteVector32("02".repeat(32)))
private fun prefsStore(name: String) = PreferenceDataStoreFactory.createWithPath {
temporaryFolder.newFolder().resolve("$name.preferences_pb").path.toPath()
}
private val identity: Identity by lazy {
Identity.signing(
id = privateKey.publicKey().xOnly().toWalletId(),
kind = IdentityKind.NostrSecret,
nostrPrivateKey = privateKey,
userPrefs = UserPrefs(prefsStore("user")),
internalPrefs = InternalPrefs(prefsStore("internal")),
)
}
private val user get() = identity.nostrPublicKey
private val peer = "b".repeat(64)
private val room = "11".repeat(32)
private class FakeNotifier : PlatformNotifier {
val posted: MutableList<RoomNotification> = Collections.synchronizedList(mutableListOf())
override fun post(notification: RoomNotification) { posted += notification }
override fun cancel(key: String) = Unit
override fun canPost() = true
}
private val notifier = FakeNotifier()
private val active = MutableStateFlow<Identity?>(null)
private val visible = MutableStateFlow(false)
private val syncPending = MutableStateFlow(false)
private val outbound = MutableStateFlow(0)
private val kept = Collections.synchronizedSet(mutableSetOf<String>())
private var enginesStarted = 0
private val dispatcher = NotificationDispatcher(
database = db,
notifier = notifier,
strings = { NotificationStrings("New message", "Note to self", "Someone", { "$it more" }) },
appVisible = visible,
visibleChatRoomId = MutableStateFlow(null),
syncPending = { syncPending },
settleFor = 10.milliseconds,
)
private fun pass(defaultIdentity: Identity? = identity) = BackgroundSyncPass(
activeIdentity = active,
loadDefaultIdentity = { defaultIdentity },
startEngines = { enginesStarted++ },
syncPending = { syncPending },
outboundQueued = { outbound },
dispatcher = dispatcher,
ledger = db.notificationDao(),
isVisible = visible,
keepConnected = { kept += it },
release = { kept -= it },
quietFor = 200.milliseconds,
)
private suspend fun seed() {
listOf(user to "me", peer to "alice").forEach { (publicKey, name) ->
val eventId = publicKey.take(32).padEnd(64, 'c')
db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)))
db.profileDao().upsert(Profile(publicKey = publicKey, userName = name, nostrEventId = eventId))
}
db.chatRoomDao().upsert(ChatRoom(id = room, userPublicKey = user, subject = "Hikers", description = null, mlsGroupState = null))
db.notificationDao().arm(user, Clock.System.now())
}
private suspend fun delivered(text: String) = db.chatMessageDao().upsert(
ChatMessage(
senderPublicKey = peer,
isUserMessage = false,
giftWrapPayloadId = null,
marmotGroupEventId = null,
marmotInnerEventId = null,
chatRoomId = room,
content = text,
createdAt = Clock.System.now(),
)
)
@Test
fun `nothing runs while the app is on screen`() = runBlocking {
visible.value = true
assertEquals(BackgroundSyncPass.Outcome.Visible, pass().run(BackgroundSyncPass.Kind.Quick, 5.seconds))
assertEquals(0, enginesStarted)
}
@Test
fun `nothing runs without a profile that can sign`() = runBlocking {
assertEquals(BackgroundSyncPass.Outcome.NoIdentity, pass(defaultIdentity = null).run(BackgroundSyncPass.Kind.Quick, 5.seconds))
assertEquals(0, enginesStarted)
}
/** The pass's whole job, in one: activate, hold, notice the delivery, post it, let go, record. */
@Test
fun `a message delivered during the pass is posted, and the pass puts everything back`() = runBlocking {
seed()
val running = async(Dispatchers.Default) { pass().run(BackgroundSyncPass.Kind.Full, 60.seconds) }
// The engines see the identity and the connections held, as a launch would give them.
while (active.value == null) delay(10)
assertSame(identity, active.value)
assertTrue(mobi.giza.compose.AppLifecycle.KEEP_BACKGROUND_PASS in kept)
// The reconciliation is queued and the relay answers.
syncPending.value = true
delivered("summit at noon")
syncPending.value = false
assertEquals(BackgroundSyncPass.Outcome.Completed, running.await())
assertEquals("summit at noon", notifier.posted.single().lines.single().text)
assertNull(active.value, "the identity the pass activated was left running")
assertTrue(kept.isEmpty(), "the connections were left held")
val ledger = assertNotNull(db.notificationDao().getLedger(user))
assertEquals("completed", ledger.lastBackgroundSyncOutcome)
assertEquals("full", ledger.lastBackgroundSyncKind)
assertEquals(1, enginesStarted)
}
@Test
fun `a pass cut off by its deadline still posts what it filed, and says so`() = runBlocking {
seed()
syncPending.value = true
val running = async(Dispatchers.Default) { pass().run(BackgroundSyncPass.Kind.Quick, 9.seconds) }
delay(200)
delivered("before the cut")
assertEquals(BackgroundSyncPass.Outcome.Deadline, running.await())
assertEquals("before the cut", notifier.posted.single().lines.single().text)
assertEquals("deadline", db.notificationDao().getLedger(user)!!.lastBackgroundSyncOutcome)
}
/** A row that can never be sent does not move, and is no reason to stay up until the deadline. */
@Test
fun `a stuck outbound row does not hold the pass to its deadline`() = runBlocking {
seed()
outbound.value = 3
assertEquals(BackgroundSyncPass.Outcome.Completed, pass().run(BackgroundSyncPass.Kind.Full, 60.seconds))
}
/** A process whose screen set the identity before the pass began keeps it afterwards. */
@Test
fun `an identity a screen set is left as it was`() = runBlocking {
seed()
active.value = identity
assertEquals(BackgroundSyncPass.Outcome.Completed, pass(defaultIdentity = null).run(BackgroundSyncPass.Kind.Full, 60.seconds))
assertSame(identity, active.value)
}
/** WorkManager and a push, say, asking at once: the second finds the first and leaves. */
@Test
fun `two passes at once are one`(): Unit = runBlocking {
seed()
syncPending.value = true
val shared = pass()
val first = async(Dispatchers.Default) { shared.run(BackgroundSyncPass.Kind.Quick, 30.seconds) }
while (active.value == null) delay(10)
assertEquals(BackgroundSyncPass.Outcome.AlreadyRunning, shared.run(BackgroundSyncPass.Kind.Quick, 9.seconds))
syncPending.value = false
assertEquals(BackgroundSyncPass.Outcome.Completed, first.await())
}
}