From 1ac519059f0c87929c0e19fcec5b5cb9ab83b907 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 12:02:06 +0200 Subject: [PATCH] refactor: one runtime per process, owned by the process (notifications, Phase 2) The database, repositories and the sync and notary engines move out of GizaNavHost's remember blocks into GizaRuntime, made by GizaApplication on Android, MainViewController on iOS and main() on desktop. Nothing changes about how they run; there is now one of each, and a process with no activity can reach them. Co-Authored-By: Claude Opus 5.5 --- .../mobi/giza/android/GizaApplication.kt | 22 ++- .../kotlin/mobi/giza/android/MainActivity.kt | 19 +-- .../kotlin/mobi/giza/compose/GizaApp.kt | 7 +- .../kotlin/mobi/giza/compose/GizaRuntime.kt | 151 ++++++++++++++++++ .../ui/composable/navigation/GizaNavHost.kt | 113 +++---------- .../ui/view/model/SovereignWalletViewModel.kt | 14 +- .../mobi/giza/compose/MainViewController.kt | 21 ++- .../jvmMain/kotlin/mobi/giza/desktop/Main.kt | 18 ++- .../mobi/giza/compose/GizaRuntimeJvmTest.kt | 53 ++++++ .../managers/NotificationTodayJvmTest.kt | 9 +- 10 files changed, 299 insertions(+), 128 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/GizaRuntimeJvmTest.kt diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/android/GizaApplication.kt b/composeApp/src/androidMain/kotlin/mobi/giza/android/GizaApplication.kt index d241da89..7b01d78d 100644 --- a/composeApp/src/androidMain/kotlin/mobi/giza/android/GizaApplication.kt +++ b/composeApp/src/androidMain/kotlin/mobi/giza/android/GizaApplication.kt @@ -8,6 +8,8 @@ import androidx.datastore.preferences.preferencesDataStore import fr.acinq.phoenix.PhoenixGlobal import fr.acinq.phoenix.utils.PlatformContext import fr.acinq.phoenix.utils.preferences.GlobalPrefs +import mobi.giza.compose.GizaGlobal +import mobi.giza.compose.GizaRuntime /** This datastore persists preferences across node ids. */ val Context.globalPrefs: DataStore by preferencesDataStore(name = "globalprefs") @@ -16,11 +18,29 @@ class GizaApplication: Application() { private lateinit var globalPrefs: GlobalPrefs private lateinit var phoenixGlobal: PhoenixGlobal + /** + * The process's runtime. Here rather than in `MainActivity` because a process can start with + * no activity -- a background sync, a notification's action -- and every one of those has to + * find the same database and relay pool the screens use. Nothing in it starts until it is read. + * docs/notifications-and-background-sync.md, D4. + */ + lateinit var runtime: GizaRuntime + private set + override fun onCreate() { super.onCreate() phoenixGlobal = PhoenixGlobal(PlatformContext(applicationContext)) globalPrefs = GlobalPrefs(applicationContext.globalPrefs) + + runtime = GizaRuntime.getOrCreate { + GizaRuntime( + gizaGlobal = GizaGlobal( + platformContext = mobi.giza.compose.PlatformContext(applicationContext = applicationContext) + ), + phoenixGlobal = phoenixGlobal, + ) + } } fun getGlobalPrefs(): GlobalPrefs { @@ -30,4 +50,4 @@ class GizaApplication: Application() { fun getPhoenixGlobal(): PhoenixGlobal { return phoenixGlobal } -} \ No newline at end of file +} diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt b/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt index 2658f868..96ff9ca0 100644 --- a/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt +++ b/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt @@ -5,10 +5,7 @@ import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.navigation.compose.rememberNavController -import mobi.giza.compose.PlatformContext import mobi.giza.compose.GizaApp -import mobi.giza.compose.GizaGlobal -import fr.acinq.phoenix.PhoenixGlobal class MainActivity : ComponentActivity() { @@ -16,22 +13,16 @@ class MainActivity : ComponentActivity() { enableEdgeToEdge() super.onCreate(savedInstanceState) + // The application's runtime, not one of our own: an activity recreated over a living + // process used to build a second set of repositories and a second PhoenixGlobal here. + val runtime = (application as GizaApplication).runtime + setContent { val navController = rememberNavController() GizaApp( navController = navController, - gizaGlobal = GizaGlobal( - platformContext = PlatformContext( - applicationContext = applicationContext - ) - ), - phoenixGlobal = PhoenixGlobal( - ctx = fr.acinq.phoenix.utils.PlatformContext( - applicationContext = applicationContext - ) - ) - + runtime = runtime, ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaApp.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaApp.kt index 2c3ceffd..51e35f48 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaApp.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaApp.kt @@ -13,7 +13,6 @@ import mobi.giza.compose.network.platformHttpClientEngineFactory import mobi.giza.compose.ui.composable.navigation.GizaNavHost import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost import mobi.giza.compose.ui.theme.GizaTheme -import fr.acinq.phoenix.PhoenixGlobal /** * Coil's default ktor fetcher builds a bare `HttpClient()`, whose engine is whichever the @@ -26,8 +25,7 @@ private val imageHttpClient by lazy { HttpClient(platformHttpClientEngineFactory @Composable fun GizaApp( navController: NavHostController, - gizaGlobal: GizaGlobal, - phoenixGlobal: PhoenixGlobal + runtime: GizaRuntime, ) { setSingletonImageLoaderFactory { context -> ImageLoader.Builder(context) @@ -48,8 +46,7 @@ fun GizaApp( // every composable between it and the Scaffold. ProvideSnackbarHost { GizaNavHost( - gizaGlobal = gizaGlobal, - phoenixGlobal = phoenixGlobal, + runtime = runtime, navController = navController ) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt new file mode 100644 index 00000000..d72da358 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt @@ -0,0 +1,151 @@ +package mobi.giza.compose + +import co.touchlab.kermit.Logger +import fr.acinq.phoenix.PhoenixGlobal +import kotlin.concurrent.atomics.AtomicReference +import kotlin.concurrent.atomics.ExperimentalAtomicApi +import kotlinx.coroutines.CoroutineExceptionHandler +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.MutableStateFlow +import mobi.giza.compose.database.repository.DatabaseChatRepository +import mobi.giza.compose.database.repository.DatabaseConfederationRepository +import mobi.giza.compose.database.repository.DatabaseDkgRepository +import mobi.giza.compose.database.repository.DatabaseFrostSigningRepository +import mobi.giza.compose.database.repository.DatabaseGroupInboxRepository +import mobi.giza.compose.database.repository.DatabaseMarmotRepository +import mobi.giza.compose.database.repository.DatabaseNostrRepository +import mobi.giza.compose.database.repository.DatabaseSearchRepository +import mobi.giza.compose.identity.Identity +import mobi.giza.compose.managers.AuxDatabaseManager +import mobi.giza.compose.ui.view.model.NotaryViewModel +import mobi.giza.compose.ui.view.model.SynchronizationViewModel + +/** + * Everything the app runs on that is not a screen: the database, the repositories over it, the + * relay pool and the engines that sync and send. One per process. + * + * It used to be built in `remember { }` blocks inside `GizaNavHost`, which meant nothing could run + * without a UI -- a background job had no database or relay pool to use unless it built a second + * one, and a second one is two Room instances on `aux.db` that cannot see each other's writes, two + * sockets per relay, and two writers ratcheting one room's MLS state. It also meant an Android + * activity recreated over a living process built fresh repositories beside the view models that + * held on to the old ones. See docs/notifications-and-background-sync.md, D4. + * + * Created by whatever owns the process: `GizaApplication` on Android, `MainViewController` on iOS, + * `main()` on desktop once the passphrase is in. Everything else asks [current] or [getOrCreate]. + * + * The two engines are still `ViewModel`s by name. Neither ever used `viewModelScope` -- both run on + * the [ioScope] they are given -- so constructing them here rather than through a `ViewModelStore` + * changes nothing about how they run, only that there is one of each. + */ +class GizaRuntime( + val gizaGlobal: GizaGlobal, + val phoenixGlobal: PhoenixGlobal, +) { + private val logger = Logger.withTag(TAG) + + val ioScope: CoroutineScope = CoroutineScope( + Dispatchers.IO + SupervisorJob() + CoroutineExceptionHandler { _, throwable -> + logger.e("Caught exception: ${throwable.message}", throwable) + } + ) + + /** + * The identity the app is running as. Written by `SovereignWalletViewModel`, read by every + * repository and engine below. Owned here rather than by that view model so that the engines, + * which live as long as the process, are not left holding a flow an old activity owned. + */ + val activeIdentity: MutableStateFlow = MutableStateFlow(null) + + val auxDatabaseManager: AuxDatabaseManager = AuxDatabaseManager(gizaGlobal) + + val nostrRepository: DatabaseNostrRepository by lazy { + DatabaseNostrRepository(database = auxDatabaseManager.auxDatabase, ioScope, activeIdentity = activeIdentity) + } + + val chatRepository: DatabaseChatRepository by lazy { + DatabaseChatRepository(database = auxDatabaseManager.auxDatabase, ioScope, activeIdentity = activeIdentity) + } + + val dkgRepository: DatabaseDkgRepository by lazy { + DatabaseDkgRepository(database = auxDatabaseManager.auxDatabase, ioScope) + } + + val frostSigningRepository: DatabaseFrostSigningRepository by lazy { + DatabaseFrostSigningRepository(database = auxDatabaseManager.auxDatabase, ioScope) + } + + val confederationRepository: DatabaseConfederationRepository by lazy { + DatabaseConfederationRepository(database = auxDatabaseManager.auxDatabase, ioScope, activeIdentity = activeIdentity) + } + + val groupInboxRepository: DatabaseGroupInboxRepository by lazy { + DatabaseGroupInboxRepository(database = auxDatabaseManager.auxDatabase, ioScope, activeIdentity = activeIdentity) + } + + val marmotRepository: DatabaseMarmotRepository by lazy { + DatabaseMarmotRepository(database = auxDatabaseManager.auxDatabase, ioScope) + } + + val searchRepository: DatabaseSearchRepository by lazy { + DatabaseSearchRepository(database = auxDatabaseManager.auxDatabase) + } + + /** Sends what this device has queued: seals gift wraps, encrypts Marmot events, signs. */ + val notary: NotaryViewModel by lazy { + NotaryViewModel( + activeIdentityStateFlow = activeIdentity, + nostrRepository = nostrRepository, + chatRepository = chatRepository, + marmotRepository = marmotRepository, + scope = ioScope, + ) + } + + /** The relay pool, the request pumps and the live subscriptions. */ + val synchronization: SynchronizationViewModel by lazy { + SynchronizationViewModel( + activeIdentityStateFlow = activeIdentity, + nostrRepository = nostrRepository, + chatRepository = chatRepository, + relayRepository = nostrRepository, + scope = ioScope, + confederationRepository = confederationRepository, + groupInboxRepository = groupInboxRepository, + ) + } + + companion object { + private const val TAG = "GizaRuntime" + + @OptIn(ExperimentalAtomicApi::class) + private val instance = ProcessSingleton() + + /** The runtime, if whatever owns the process has made it. */ + fun current(): GizaRuntime? = instance.current() + + /** The runtime, made by [create] if nothing has made it yet. [create] runs at most once. */ + fun getOrCreate(create: () -> GizaRuntime): GizaRuntime = instance.getOrCreate(create) + } +} + +/** + * One value per process, made on first ask. A race between two first asks builds two and keeps + * whichever was published first; the loser is dropped before anything has been started on it, which + * is only true because [GizaRuntime] starts nothing in its constructor -- every engine is lazy. + */ +@OptIn(ExperimentalAtomicApi::class) +internal class ProcessSingleton { + private val reference = AtomicReference(null) + + fun current(): T? = reference.load() + + fun getOrCreate(create: () -> T): T { + reference.load()?.let { return it } + val made = create() + return if (reference.compareAndSet(null, made)) made else reference.load()!! + } +} 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 7ea5818b..5aa40afc 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 @@ -59,7 +59,7 @@ import mobi.giza.compose.database.repository.DatabaseFrostSigningRepository import mobi.giza.compose.database.repository.DatabaseMarmotRepository import mobi.giza.compose.database.repository.DatabaseNostrRepository import mobi.giza.compose.database.repository.DatabaseSearchRepository -import mobi.giza.compose.managers.AuxDatabaseManager +import mobi.giza.compose.GizaRuntime import mobi.giza.compose.ui.composable.ActiveProfileScreen import mobi.giza.compose.ui.composable.AddMemberToChatRoomConfirmationScreen import mobi.giza.compose.ui.composable.ChatRoomCreationScreen @@ -168,89 +168,37 @@ import mobi.giza.compose.ui.composable.ProposalListScreen @Composable fun GizaNavHost( - gizaGlobal: GizaGlobal, - phoenixGlobal: PhoenixGlobal, + runtime: GizaRuntime, navController: NavHostController ) { val logger = Logger.withTag("GizaNavHost") - val exceptionHandler = remember { - CoroutineExceptionHandler { _, throwable -> - logger.e("Caught exception: ${throwable.message}", throwable) - } - } + val phoenixGlobal = runtime.phoenixGlobal - val applicationIOScope = remember { CoroutineScope(Dispatchers.IO + SupervisorJob() + exceptionHandler) } + // The process's, not this composition's: a screen's coroutine that outlives the screen is + // the point of using it. docs/notifications-and-background-sync.md, Phase 2. + val applicationIOScope = runtime.ioScope val applicationMainScope = remember { CoroutineScope(Dispatchers.Main) } val lifecycleOwner = LocalLifecycleOwner.current - val auxDatabaseManager = remember { - AuxDatabaseManager(gizaGlobal) - } - - // Before the repositories: the nostr repository stamps every fetch request it queues - // with the active identity, and takes the flow at construction. + // Before the repositories are read: they all follow the identity this view model writes, + // through the flow the runtime owns. val sovereignWalletViewModel: SovereignWalletViewModel = viewModel( factory = SovereignWalletViewModel.factory( - phoenixGlobal = phoenixGlobal + phoenixGlobal = phoenixGlobal, + activeIdentityState = runtime.activeIdentity, ) ) - val databaseNostrRepository = remember { - DatabaseNostrRepository( - database = auxDatabaseManager.auxDatabase, - applicationIOScope, - activeIdentity = sovereignWalletViewModel.activeIdentity, - ) - } - - val databaseChatRepository = remember { - DatabaseChatRepository( - database = auxDatabaseManager.auxDatabase, - applicationIOScope, - activeIdentity = sovereignWalletViewModel.activeIdentity, - ) - } - - val databaseDkgRepository = remember { - DatabaseDkgRepository( - database = auxDatabaseManager.auxDatabase, - applicationIOScope - ) - } - val databaseFrostSigningRepository = remember { - DatabaseFrostSigningRepository( - database = auxDatabaseManager.auxDatabase, - applicationIOScope - ) - } - val databaseConfederationRepository = remember { - DatabaseConfederationRepository( - database = auxDatabaseManager.auxDatabase, - applicationIOScope, - activeIdentity = sovereignWalletViewModel.activeIdentity, - ) - } - val databaseGroupInboxRepository = remember { - DatabaseGroupInboxRepository( - database = auxDatabaseManager.auxDatabase, - applicationIOScope, - activeIdentity = sovereignWalletViewModel.activeIdentity, - ) - } - val databaseMarmotRepository = remember { - DatabaseMarmotRepository( - database = auxDatabaseManager.auxDatabase, - applicationIOScope - ) - } - - val searchRepository = remember { - DatabaseSearchRepository( - database = auxDatabaseManager.auxDatabase - ) - } + val databaseNostrRepository = runtime.nostrRepository + val databaseChatRepository = runtime.chatRepository + val databaseDkgRepository = runtime.dkgRepository + val databaseFrostSigningRepository = runtime.frostSigningRepository + val databaseConfederationRepository = runtime.confederationRepository + val databaseGroupInboxRepository = runtime.groupInboxRepository + val databaseMarmotRepository = runtime.marmotRepository + val searchRepository = runtime.searchRepository val navigationViewModel: NavigationViewModel = viewModel ( factory = NavigationViewModel.factory( @@ -261,28 +209,9 @@ fun GizaNavHost( ) ) - val notaryViewModel: NotaryViewModel = viewModel( - factory = NotaryViewModel.factory( - activeIdentityStateFlow = sovereignWalletViewModel.activeIdentity, - nostrRepository = databaseNostrRepository, - chatRepository = databaseChatRepository, - marmotRepository = databaseMarmotRepository, - scope = applicationIOScope - ) - ) - - // TODO: Produce a notary UI Element... - val synchronizationViewModel: SynchronizationViewModel = viewModel( - factory = SynchronizationViewModel.factory( - activeIdentityStateFlow = sovereignWalletViewModel.activeIdentity, - nostrRepository = databaseNostrRepository, - chatRepository = databaseChatRepository, - relayRepository = databaseNostrRepository, - scope = applicationIOScope, - confederationRepository = databaseConfederationRepository, - groupInboxRepository = databaseGroupInboxRepository, - ) - ) + // One of each per process, started on first read and never cleared. + val notaryViewModel: NotaryViewModel = runtime.notary + val synchronizationViewModel: SynchronizationViewModel = runtime.synchronization // TODO: Produce a synchronization UI element... diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SovereignWalletViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SovereignWalletViewModel.kt index feb1b4c9..9e22ecc4 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SovereignWalletViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SovereignWalletViewModel.kt @@ -65,6 +65,11 @@ expect suspend fun saveAvailableWalletMeta( class SovereignWalletViewModel( val phoenixGlobal: PhoenixGlobal, + /** + * Where [activeIdentity] is kept. The process's `GizaRuntime` passes its own, so the engines + * that outlive this view model follow the identity it sets; a test passes nothing. + */ + activeIdentityState: MutableStateFlow = MutableStateFlow(null), ): ViewModel() { private val log = Logger.withTag("SovereignWalletViewModel") @@ -99,7 +104,7 @@ class SovereignWalletViewModel( * carries the key directly, so a reader no longer needs a node to exist, and an * identity that never has one (a bare nsec) reads the same as one that does. */ - private val _activeIdentity = MutableStateFlow(null) + private val _activeIdentity = activeIdentityState val activeIdentity = _activeIdentity.asStateFlow() var walletUIState: mobi.giza.compose.ui.view.state.SovereignWalletUIState by mutableStateOf( @@ -124,6 +129,11 @@ class SovereignWalletViewModel( init { + // A new view model is a new start: the selector or the default profile, chosen again. + // The flow it writes now outlives it (it is the runtime's), so an activity recreated + // over a living process would otherwise begin with the last activity's identity set + // and skip the startup that decides it. Null first is what every start did before. + _activeIdentity.value = null listIdentities(onDone = {}) } @@ -449,10 +459,12 @@ class SovereignWalletViewModel( private const val TAG = "SovereignWalletViewModel" fun factory( phoenixGlobal: PhoenixGlobal, + activeIdentityState: MutableStateFlow = MutableStateFlow(null), ): ViewModelProvider.Factory = viewModelFactory { initializer { SovereignWalletViewModel( phoenixGlobal = phoenixGlobal, + activeIdentityState = activeIdentityState, ) } } diff --git a/composeApp/src/iosMain/kotlin/mobi/giza/compose/MainViewController.kt b/composeApp/src/iosMain/kotlin/mobi/giza/compose/MainViewController.kt index a4103d3d..be2bc3d0 100644 --- a/composeApp/src/iosMain/kotlin/mobi/giza/compose/MainViewController.kt +++ b/composeApp/src/iosMain/kotlin/mobi/giza/compose/MainViewController.kt @@ -4,16 +4,23 @@ import androidx.compose.ui.window.ComposeUIViewController import androidx.navigation.compose.rememberNavController import fr.acinq.phoenix.PhoenixGlobal +/** + * The process's runtime on iOS. A background task reaches the same one through here, so a + * refresh that runs while the app is in memory shares its database and relay pool with the UI + * rather than opening a second of each. docs/notifications-and-background-sync.md, D4. + */ +fun gizaRuntime(): GizaRuntime = GizaRuntime.getOrCreate { + GizaRuntime( + gizaGlobal = GizaGlobal(platformContext = PlatformContext()), + phoenixGlobal = PhoenixGlobal(ctx = fr.acinq.phoenix.utils.PlatformContext()), + ) +} + fun MainViewController() = ComposeUIViewController { val navController = rememberNavController() GizaApp( navController = navController, - gizaGlobal = GizaGlobal( - platformContext = PlatformContext() - ), - phoenixGlobal = PhoenixGlobal( - ctx = fr.acinq.phoenix.utils.PlatformContext() - ) + runtime = gizaRuntime(), ) -} \ No newline at end of file +} diff --git a/composeApp/src/jvmMain/kotlin/mobi/giza/desktop/Main.kt b/composeApp/src/jvmMain/kotlin/mobi/giza/desktop/Main.kt index 3706c532..4b8fbd2c 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.GizaRuntime import mobi.giza.compose.PlatformContext import mobi.giza.compose.defaultGizaDir import mobi.giza.compose.resources.Res @@ -103,12 +104,21 @@ fun main() = application { GizaTheme { if (unlocked) { val navController = rememberNavController() + // 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 { + GizaRuntime.getOrCreate { + GizaRuntime( + gizaGlobal = GizaGlobal(platformContext = PlatformContext(appDir)), + phoenixGlobal = PhoenixGlobal( + ctx = fr.acinq.phoenix.utils.PlatformContext(applicationDir = appDir), + ), + ) + } + } GizaApp( navController = navController, - gizaGlobal = GizaGlobal(platformContext = PlatformContext(appDir)), - phoenixGlobal = PhoenixGlobal( - ctx = fr.acinq.phoenix.utils.PlatformContext(applicationDir = appDir), - ), + runtime = runtime, ) } else { PassphraseGate(appDir = appDir, onUnlocked = { unlocked = true }) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/GizaRuntimeJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/GizaRuntimeJvmTest.kt new file mode 100644 index 00000000..a485c416 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/GizaRuntimeJvmTest.kt @@ -0,0 +1,53 @@ +package mobi.giza.compose + +import java.util.concurrent.CountDownLatch +import java.util.concurrent.atomic.AtomicInteger +import kotlin.concurrent.thread +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertSame + +/** + * One runtime per process: whatever asks second gets what was made first. + * docs/notifications-and-background-sync.md, Phase 2. + */ +class GizaRuntimeJvmTest { + + @Test + fun `the first value made is the one every later ask gets`() { + val singleton = ProcessSingleton() + assertNull(singleton.current()) + + val made = AtomicInteger() + val first = singleton.getOrCreate { made.incrementAndGet(); Any() } + val second = singleton.getOrCreate { made.incrementAndGet(); Any() } + + assertSame(first, second) + assertSame(first, singleton.current()) + assertEquals(1, made.get()) + } + + /** + * A worker's thread and the main thread can both ask first. Both may build, but every caller + * gets the same one -- which is only safe because nothing is started by building. + */ + @Test + fun `racing first asks all get the same value`() { + val singleton = ProcessSingleton() + val start = CountDownLatch(1) + val results = java.util.Collections.synchronizedList(mutableListOf()) + + val threads = (1..8).map { + thread { + start.await() + results += singleton.getOrCreate { Any() } + } + } + start.countDown() + threads.forEach { it.join() } + + assertEquals(1, results.toSet().size) + assertSame(results.first(), singleton.current()) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/NotificationTodayJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/NotificationTodayJvmTest.kt index 9cc03ba6..a4d10894 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/NotificationTodayJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/NotificationTodayJvmTest.kt @@ -66,17 +66,18 @@ class NotificationTodayJvmTest { File("src").takeIf { it.resolve("commonMain").isDirectory } ?: File("composeApp/src") /** - * The object graph is built inside a composable, so nothing can run without a UI. Phase 2 moves - * it to `GizaRuntime` and flips this to name that file instead. + * The object graph used to be built inside a composable, so nothing could run without a UI. + * Phase 2 moved it to `GizaRuntime`, one per process, and this names that file instead. A + * second construction site is a second database handle and a second relay pool. */ @Test - fun `the repositories are constructed in GizaNavHost and nowhere else`() { + fun `the repositories are constructed in GizaRuntime and nowhere else`() { val builders = source.resolve("commonMain/kotlin").walkTopDown() .filter { it.isFile && it.extension == "kt" } .filter { "DatabaseNostrRepository(" in it.readText().replace("class DatabaseNostrRepository(", "") } .map { it.nameWithoutExtension } .toSet() - assertEquals(setOf("GizaNavHost"), builders) + assertEquals(setOf("GizaRuntime"), builders) } }