From 84fde2a18f0f486d78f3e280e7b169ab484bb97e Mon Sep 17 00:00:00 2001 From: stylianosgakis Date: Thu, 19 Nov 2026 17:10:40 +0100 Subject: [PATCH 1/9] Add the native graph and a holder that builds it on first use IosGraph is the AppScope graph of every module the framework links. The iOS app passes only what Kotlin cannot know: the flavor (typed, required, no default), the token and device id fetchers, the language source and the network log policy. The rest of the build (bundle id, versions, OS version, device model) is read from the bundle and the device, and platformName keeps Kotlin's native default. createIosGraphHolder only keeps those inputs: the graph is built, and the NSLog and RUM fallback loggers installed, on the first call that needs it, which logs the build time. A second holder in the process is a mistake: a debug framework fails it with an IllegalStateException, a release one logs it at ERROR and returns the first holder. The graph leaves out the DataStore the native datastore module offers, since no read stores anything, and takes no demo mode: demo mode is the iOS app's own. No AuthEvent is published on iOS, so no AuthEventListener can read a token it was never given. A production flavor never logs bodies or GraphQL data, whatever policy the iOS app passes; error text follows the policy. Written for this series after the integration branch's native graph (4152719dde, 8b7c0e7faa, 35a377e29a, 70206b77c7), without the claim history screen model, the ViewModel factory, initializables, auth events or demo mode. --- app/umbrella/build.gradle.kts | 21 ++- .../android/umbrella/GraphTestDoubles.kt | 141 +++++++++++++++ .../hedvig/android/umbrella/IosGraphTest.kt | 163 ++++++++++++++++++ .../android/umbrella/IosAppBuildConfig.kt | 49 ++++++ .../com/hedvig/android/umbrella/IosGraph.kt | 43 +++++ .../hedvig/android/umbrella/IosGraphHolder.kt | 89 ++++++++++ .../android/umbrella/LogcatRumLogger.kt | 27 +++ 7 files changed, 530 insertions(+), 3 deletions(-) create mode 100644 app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/GraphTestDoubles.kt create mode 100644 app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/IosGraphTest.kt create mode 100644 app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/IosAppBuildConfig.kt create mode 100644 app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/IosGraph.kt create mode 100644 app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/IosGraphHolder.kt create mode 100644 app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/LogcatRumLogger.kt diff --git a/app/umbrella/build.gradle.kts b/app/umbrella/build.gradle.kts index 2a5fa249e3..eb63b800fd 100644 --- a/app/umbrella/build.gradle.kts +++ b/app/umbrella/build.gradle.kts @@ -15,14 +15,16 @@ kotlin { } val frameworkName = "HedvigShared" val xcf = XCFramework(frameworkName) - // Only what iOS calls: the auth client and the logger. Everything a module here reaches through - // its public API is linked into the framework, so exporting a module iOS does not use only adds - // bytes and header surface (network-clients alone dragged Apollo, Arrow and Okio in, ~2.9 MB). + // Only what iOS calls: the auth client, the logger and the holder with the read failures. A module + // with reads for iOS is added here, and nothing else changes. Everything a module here reaches + // through its public API is linked into the framework, so exporting a module iOS does not use only + // adds bytes and header surface (network-clients alone dragged Apollo, Arrow and Okio in, ~2.9 MB). // Keep this list free of Compose UI: one such export pulls Skiko and ~70 MB of Skia, ICU and // HarfBuzz into the iOS app. iOS builds its UI natively. Every other KMP module keeps compiling // for iOS under the convention plugin, so re-exporting one later is a one-line change here. val projectsToExport: List = listOf( projects.authlib, + projects.iosDataBridge, projects.loggingPublic, ) listOf( @@ -48,6 +50,19 @@ kotlin { api(projectToExport) } } + nativeMain.dependencies { + implementation(libs.apollo.runtime) + implementation(projects.coreBuildConstants) + implementation(projects.coreCommonPublic) + implementation(projects.coreDatastorePublic) + implementation(projects.languageCore) + implementation(projects.networkClients) + implementation(projects.trackingCore) + } + nativeTest.dependencies { + implementation(libs.apollo.normalizedCache) + implementation(libs.assertK) + } } } diff --git a/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/GraphTestDoubles.kt b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/GraphTestDoubles.kt new file mode 100644 index 0000000000..8439f0f46c --- /dev/null +++ b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/GraphTestDoubles.kt @@ -0,0 +1,141 @@ +package com.hedvig.android.umbrella + +import com.hedvig.android.core.buildconstants.Flavor +import com.hedvig.android.core.datastore.DeviceIdFetcher +import com.hedvig.android.iosdata.bridge.IosGraphHolder +import com.hedvig.android.language.IosLanguageSource +import com.hedvig.android.language.Language +import com.hedvig.android.logger.IosLogSink +import com.hedvig.android.logger.LogPriority +import com.hedvig.android.network.clients.AccessTokenFetcher +import com.hedvig.android.network.clients.NetworkLogPolicy +import kotlin.concurrent.AtomicInt +import kotlin.coroutines.suspendCoroutine +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds +import kotlin.time.TimeSource +import platform.Foundation.NSDate +import platform.Foundation.NSLock +import platform.Foundation.NSRunLoop +import platform.Foundation.NSThread +import platform.Foundation.dateWithTimeIntervalSinceNow +import platform.Foundation.runUntilDate + +/** The iOS app's inputs as Kotlin fakes, each recording how often, and on which threads, Kotlin calls it. */ +internal class FakeInputs( + val appFlavor: Flavor = Flavor.Staging, + val accessTokenFetcher: FakeAccessTokenFetcher = FakeAccessTokenFetcher(), + val deviceIdFetcher: FakeDeviceIdFetcher = FakeDeviceIdFetcher(), + val languageSource: FakeLanguageSource = FakeLanguageSource(), + val networkLogPolicy: NetworkLogPolicy = NetworkLogPolicy( + logsHttpBodies = false, + logsGraphqlData = false, + logsGraphqlErrors = false, + ), +) { + /** The real graph, as the iOS app creates it. Its engine is Darwin, so no test lets it send a request. */ + fun realHolder(): IosGraphHolder = createIosGraphHolder( + appFlavor = appFlavor, + accessTokenFetcher = accessTokenFetcher, + deviceIdFetcher = deviceIdFetcher, + languageSource = languageSource, + networkLogPolicy = networkLogPolicy, + ) + + /** How many times Kotlin called any input. */ + fun inputCalls(): Int = accessTokenFetcher.calls.value + deviceIdFetcher.calls.value + languageSource.calls.value +} + +/** Which threads an input was called on. */ +internal open class ThreadRecorder { + private val lock = NSLock() + private val mainThreadCalls = mutableListOf() + val calls = AtomicInt(0) + + protected fun record() { + calls.incrementAndGet() + lock.lock() + try { + mainThreadCalls += NSThread.isMainThread + } finally { + lock.unlock() + } + } + + fun calledOnMainThread(): List { + lock.lock() + try { + return mainThreadCalls.toList() + } finally { + lock.unlock() + } + } +} + +internal class FakeAccessTokenFetcher( + private val throws: Boolean = false, + private val neverAnswers: Boolean = false, +) : ThreadRecorder(), AccessTokenFetcher { + override suspend fun fetch(): String? { + record() + if (throws) throw IllegalStateException("token refresh failed") + // A Swift token fetcher that never calls back: no resume, and Kotlin's cancel does not reach it. + if (neverAnswers) suspendCoroutine { } + return ACCESS_TOKEN + } +} + +internal class FakeDeviceIdFetcher : ThreadRecorder(), DeviceIdFetcher { + override suspend fun fetch(): String? { + record() + return DEVICE_ID + } +} + +internal class FakeLanguageSource(private val language: Language = Language.EN_SE) : + ThreadRecorder(), + IosLanguageSource { + override fun currentLanguage(): Language { + record() + return language + } +} + +/** The iOS app's log sink as a test sees it: every line, from any thread. */ +internal class RecordingSink : IosLogSink { + private val lock = NSLock() + private val lines = mutableListOf>() + + fun entries(): List> { + lock.lock() + try { + return lines.toList() + } finally { + lock.unlock() + } + } + + fun messages(): List = entries().map { it.second } + + override fun log(priority: LogPriority, tag: String?, message: String) { + lock.lock() + try { + lines += priority to message + } finally { + lock.unlock() + } + } +} + +/** Drives the main run loop in 10 ms slices until [condition] holds or [timeout] passes. */ +internal fun pumpMainLoopUntil(timeout: Duration = 10.seconds, condition: () -> Boolean): Boolean { + val start = TimeSource.Monotonic.markNow() + while (!condition()) { + if (start.elapsedNow() > timeout) return false + NSRunLoop.mainRunLoop.runUntilDate(NSDate.dateWithTimeIntervalSinceNow(0.01)) + } + return true +} + +internal const val ACCESS_TOKEN = "test-access-token-5d1c" +internal const val DEVICE_ID = "test-device-id-0b7e" diff --git a/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/IosGraphTest.kt b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/IosGraphTest.kt new file mode 100644 index 0000000000..096507c045 --- /dev/null +++ b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/IosGraphTest.kt @@ -0,0 +1,163 @@ +package com.hedvig.android.umbrella + +import assertk.assertFailure +import assertk.assertThat +import assertk.assertions.containsExactly +import assertk.assertions.isEqualTo +import assertk.assertions.isFalse +import assertk.assertions.isInstanceOf +import assertk.assertions.isTrue +import assertk.assertions.matches +import com.apollographql.cache.normalized.apolloStore +import com.hedvig.android.core.buildconstants.Flavor +import com.hedvig.android.core.tracking.ActionType +import com.hedvig.android.core.tracking.ErrorSource +import com.hedvig.android.core.tracking.RumLogger +import com.hedvig.android.core.tracking.logError +import com.hedvig.android.iosdata.bridge.IosGraphHolder +import com.hedvig.android.iosdata.bridge.component +import com.hedvig.android.logger.IosLogcatLogger +import com.hedvig.android.logger.LogPriority +import com.hedvig.android.logger.LogcatLogger +import com.hedvig.android.network.clients.NetworkLogPolicy +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test + +class IosGraphTest { + private val sink = RecordingSink() + + @BeforeTest + fun installSink() { + forgetProcessHolder() + IosLogcatLogger.install(sink, LogPriority.VERBOSE) + } + + @AfterTest + fun uninstallLoggers() { + forgetProcessHolder() + LogcatLogger.uninstall() + RumLogger.uninstall() + } + + private val IosGraphHolder.accessors: IosGraphAccessors get() = component() + + @Test + fun `creating the holder builds nothing and calls no input and installs no logger`() { + LogcatLogger.uninstall() + val inputs = FakeInputs() + + val holder = inputs.realHolder() + holder.sessionStarted() + holder.sessionEnded() + + assertThat(inputs.inputCalls()).isEqualTo(0) + assertThat(LogcatLogger.isInstalled).isFalse() + assertThat(RumLogger.isInstalled).isFalse() + } + + @Test + fun `the first use installs a log fallback and a RUM logger when the iOS app installed none`() { + LogcatLogger.uninstall() + val holder = FakeInputs().realHolder() + + holder.accessors + + assertThat(LogcatLogger.isInstalled).isTrue() + assertThat(RumLogger.isInstalled).isTrue() + } + + @Test + fun `the first use keeps the iOS app's sink and logs how long the graph took to build`() { + val holder = FakeInputs().realHolder() + + holder.accessors + holder.accessors + + val built = sink.entries().filter { it.second.startsWith("Built the shared Kotlin graph") } + assertThat(built.map { it.first }).containsExactly(LogPriority.INFO) + assertThat(built.single().second).matches(Regex("""Built the shared Kotlin graph in \d+ ms""")) + } + + @Test + fun `a RumLogger installed before the graph is kept`() { + val installed = RecordingRumLogger() + RumLogger.install(installed) + + FakeInputs().realHolder().accessors + logError("an error", ErrorSource.SOURCE) + + assertThat(installed.errors).containsExactly("an error") + } + + @Test + fun `a second holder in a debug framework fails loudly`() { + FakeInputs().realHolder() + + assertFailure { FakeInputs().realHolder() }.isInstanceOf(IllegalStateException::class) + } + + @Test + fun `a production build never logs bodies or GraphQL data whatever the iOS app passes and keeps error text`() { + val inputs = FakeInputs( + appFlavor = Flavor.Production, + networkLogPolicy = NetworkLogPolicy(logsHttpBodies = true, logsGraphqlData = true, logsGraphqlErrors = true), + ) + + val policy = inputs.realHolder().accessors.networkLogPolicy + + assertThat(listOf(policy.logsHttpBodies, policy.logsGraphqlData, policy.logsGraphqlErrors)) + .containsExactly(false, false, true) + } + + @Test + fun `a staging build logs what the iOS app asks for`() { + val inputs = FakeInputs( + networkLogPolicy = NetworkLogPolicy(logsHttpBodies = true, logsGraphqlData = true, logsGraphqlErrors = false), + ) + + val policy = inputs.realHolder().accessors.networkLogPolicy + + assertThat(listOf(policy.logsHttpBodies, policy.logsGraphqlData, policy.logsGraphqlErrors)) + .containsExactly(true, true, false) + } + + @Test + fun `both Apollo clients only log and have no normalized cache`() { + val accessors = FakeInputs().realHolder().accessors + + for (client in listOf(accessors.apolloClient, accessors.publicApolloClient)) { + assertThat(client.interceptors.map { it::class.simpleName }).containsExactly("LoggingInterceptor") + assertFailure { client.apolloStore }.isInstanceOf(IllegalStateException::class) + } + assertThat(accessors.apolloClient === accessors.publicApolloClient).isFalse() + } + + @Test + fun `the build is read from the bundle and the device and only the flavor comes from Swift`() { + val production = IosAppBuildConfig(Flavor.Production) + val staging = IosAppBuildConfig(Flavor.Staging) + + assertThat(listOf(production.buildType, production.debug, production.platformName)) + .containsExactly("release", false, "ios") + assertThat(listOf(staging.buildType, staging.debug)).containsExactly("debug", true) + assertThat(production.osSdkVersion > 0).isTrue() + assertThat(production.model.isNotEmpty()).isTrue() + } +} + +private class RecordingRumLogger : RumLogger { + val errors = mutableListOf() + + override fun logAction(type: ActionType, name: String, attributes: Map) {} + + override fun logError( + message: String, + source: ErrorSource, + attributes: Map, + throwable: Throwable?, + stacktrace: String?, + ) { + errors += message + } +} diff --git a/app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/IosAppBuildConfig.kt b/app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/IosAppBuildConfig.kt new file mode 100644 index 0000000000..8e81267192 --- /dev/null +++ b/app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/IosAppBuildConfig.kt @@ -0,0 +1,49 @@ +@file:OptIn(ExperimentalForeignApi::class) + +package com.hedvig.android.umbrella + +import com.hedvig.android.core.buildconstants.AppBuildConfig +import com.hedvig.android.core.buildconstants.Flavor +import kotlinx.cinterop.ExperimentalForeignApi +import kotlinx.cinterop.alloc +import kotlinx.cinterop.memScoped +import kotlinx.cinterop.ptr +import kotlinx.cinterop.toKString +import kotlinx.cinterop.useContents +import platform.Foundation.NSBundle +import platform.Foundation.NSProcessInfo +import platform.posix.uname +import platform.posix.utsname + +/** + * The build the iOS app is, read from the app's bundle and the device, so only [appFlavor] comes from Swift. A + * production flavor is a release build; every other flavor is a debug build. [platformName] keeps the native default, + * `ios`. + */ +internal class IosAppBuildConfig(override val appFlavor: Flavor) : AppBuildConfig { + override val debug: Boolean = appFlavor != Flavor.Production + override val buildType: String = if (appFlavor == Flavor.Production) "release" else "debug" + override val applicationId: String = NSBundle.mainBundle.bundleIdentifier.orEmpty() + override val versionName: String = infoString("CFBundleShortVersionString") + override val versionCode: Int = infoString("CFBundleVersion").toIntOrNull() ?: 0 + override val osReleaseVersion: String = NSProcessInfo.processInfo.operatingSystemVersion.useContents { + "$majorVersion.$minorVersion.$patchVersion" + } + override val osSdkVersion: Int = NSProcessInfo.processInfo.operatingSystemVersion.useContents { + majorVersion.toInt() + } + override val device: String = machine() + override val model: String = + (NSProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] as? String) ?: device + override val brand: String = "Apple" + override val manufacturer: String = "Apple" +} + +private fun infoString(key: String): String = NSBundle.mainBundle.infoDictionary?.get(key) as? String ?: "" + +/** The hardware identifier, such as `iPhone16,1`, or `arm64` on the simulator. */ +private fun machine(): String = memScoped { + val name = alloc() + uname(name.ptr) + name.machine.toKString() +} diff --git a/app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/IosGraph.kt b/app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/IosGraph.kt new file mode 100644 index 0000000000..6525437fd2 --- /dev/null +++ b/app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/IosGraph.kt @@ -0,0 +1,43 @@ +package com.hedvig.android.umbrella + +import com.apollographql.apollo.ApolloClient +import com.hedvig.android.core.buildconstants.AppBuildConfig +import com.hedvig.android.core.common.di.AppScope +import com.hedvig.android.core.common.di.PublicApolloClient +import com.hedvig.android.core.datastore.DeviceIdFetcher +import com.hedvig.android.core.datastore.di.NativeDataStoreMetroProviders +import com.hedvig.android.iosdata.bridge.IosReadsGraph +import com.hedvig.android.language.IosLanguageSource +import com.hedvig.android.network.clients.AccessTokenFetcher +import com.hedvig.android.network.clients.NetworkLogPolicy +import dev.zacsweers.metro.DependencyGraph +import dev.zacsweers.metro.Provides + +/** What tests read from a graph: [IosGraph], or the test graph with a canned HTTP engine. */ +internal interface IosGraphAccessors : IosReadsGraph { + val apolloClient: ApolloClient + + @PublicApolloClient + val publicApolloClient: ApolloClient + + val networkLogPolicy: NetworkLogPolicy +} + +/** + * The iOS app's graph: the `AppScope` contributions of every module the framework links, with each platform input + * coming from the iOS app through [Factory]. No read stores anything, so the DataStore the native datastore module + * offers is left out. + */ +@DependencyGraph(AppScope::class, excludes = [NativeDataStoreMetroProviders::class]) +internal interface IosGraph : IosGraphAccessors { + @DependencyGraph.Factory + interface Factory { + fun create( + @Provides appBuildConfig: AppBuildConfig, + @Provides accessTokenFetcher: AccessTokenFetcher, + @Provides deviceIdFetcher: DeviceIdFetcher, + @Provides languageSource: IosLanguageSource, + @Provides networkLogPolicy: NetworkLogPolicy, + ): IosGraph + } +} diff --git a/app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/IosGraphHolder.kt b/app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/IosGraphHolder.kt new file mode 100644 index 0000000000..dc047ad392 --- /dev/null +++ b/app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/IosGraphHolder.kt @@ -0,0 +1,89 @@ +package com.hedvig.android.umbrella + +import com.hedvig.android.core.buildconstants.Flavor +import com.hedvig.android.core.datastore.DeviceIdFetcher +import com.hedvig.android.core.tracking.RumLogger +import com.hedvig.android.iosdata.bridge.IosGraphHolder +import com.hedvig.android.iosdata.bridge.iosGraphHolder +import com.hedvig.android.language.IosLanguageSource +import com.hedvig.android.logger.IosLogcatLogger +import com.hedvig.android.logger.LogPriority +import com.hedvig.android.logger.logcat +import com.hedvig.android.network.clients.AccessTokenFetcher +import com.hedvig.android.network.clients.NetworkLogPolicy +import dev.zacsweers.metro.createGraphFactory +import kotlin.concurrent.AtomicReference +import kotlin.experimental.ExperimentalNativeApi +import kotlin.native.Platform +import kotlin.time.TimeSource + +/** + * The shared Kotlin graph for the iOS app, built on first use. Creating the holder only keeps the inputs: it builds + * nothing, calls no input, installs no logger and sends no request, so it is safe to create at launch whether or not + * anything uses it. + * + * Create one per process and keep it. A second call is a mistake: a debug framework fails it with an + * [IllegalStateException]; a release framework logs it at ERROR and returns the first holder, whose inputs stay. + * + * The first call that needs the graph builds it on the calling thread and logs how long that took at INFO. Before + * building, it installs an `NSLog` logger at WARN if the iOS app installed no log sink (see + * `IosLogcatLogger.install(sink:minimumPriority:)`), and a [RumLogger] that writes to the log if none is installed. + * + * [appFlavor] decides the backend and what may be logged: a production flavor never logs HTTP bodies or GraphQL data, + * whatever [networkLogPolicy] says. Everything else about the build comes from the app's bundle and the device. + * [accessTokenFetcher], [deviceIdFetcher] and [languageSource] are called from any thread; Kotlin bounds every wait on + * them inside its reads. + */ +fun createIosGraphHolder( + appFlavor: Flavor, + accessTokenFetcher: AccessTokenFetcher, + deviceIdFetcher: DeviceIdFetcher, + languageSource: IosLanguageSource, + networkLogPolicy: NetworkLogPolicy, +): IosGraphHolder { + val created = iosGraphHolder { + IosLogcatLogger.installFallback(LogPriority.WARN) + if (!RumLogger.isInstalled) { + RumLogger.install(LogcatRumLogger) + } + val start = TimeSource.Monotonic.markNow() + createGraphFactory().create( + appBuildConfig = IosAppBuildConfig(appFlavor), + accessTokenFetcher = accessTokenFetcher, + deviceIdFetcher = deviceIdFetcher, + languageSource = languageSource, + networkLogPolicy = networkLogPolicy.allowedFor(appFlavor), + ).also { + logcat(LogPriority.INFO) { "Built the shared Kotlin graph in ${start.elapsedNow().inWholeMilliseconds} ms" } + } + } + if (processHolder.compareAndSet(null, created)) return created + return secondHolder(processHolder.value!!) +} + +@OptIn(ExperimentalNativeApi::class) +private fun secondHolder(first: IosGraphHolder): IosGraphHolder { + val message = "createIosGraphHolder was called again; create one holder per process and keep it" + check(!Platform.isDebugBinary) { message } + IosLogcatLogger.installFallback(LogPriority.WARN) + logcat(LogPriority.ERROR) { "$message. Returning the first holder." } + return first +} + +private val processHolder = AtomicReference(null) + +/** Lets the next [createIosGraphHolder] call create a holder again, for tests only. */ +internal fun forgetProcessHolder() { + processHolder.value = null +} + +/** [this], or nothing logged beyond error text in a production build. */ +internal fun NetworkLogPolicy.allowedFor(flavor: Flavor): NetworkLogPolicy = when (flavor) { + Flavor.Production -> NetworkLogPolicy( + logsHttpBodies = false, + logsGraphqlData = false, + logsGraphqlErrors = logsGraphqlErrors, + ) + + else -> this +} diff --git a/app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/LogcatRumLogger.kt b/app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/LogcatRumLogger.kt new file mode 100644 index 0000000000..e415e19846 --- /dev/null +++ b/app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/LogcatRumLogger.kt @@ -0,0 +1,27 @@ +package com.hedvig.android.umbrella + +import com.hedvig.android.core.tracking.ActionType +import com.hedvig.android.core.tracking.ErrorSource +import com.hedvig.android.core.tracking.RumLogger +import com.hedvig.android.logger.LogPriority +import com.hedvig.android.logger.logcat + +/** + * Writes RUM actions and errors to [logcat], so they reach the iOS app's log sink. Attribute values can hold response + * data, so only their keys are logged. + */ +internal object LogcatRumLogger : RumLogger { + override fun logAction(type: ActionType, name: String, attributes: Map) { + logcat(LogPriority.DEBUG) { "RUM action $type $name attribute keys: ${attributes.keys}" } + } + + override fun logError( + message: String, + source: ErrorSource, + attributes: Map, + throwable: Throwable?, + stacktrace: String?, + ) { + logcat(LogPriority.WARN, throwable) { "RUM error from $source: $message attribute keys: ${attributes.keys}" } + } +} From 25aa58155a6a816521572c7325350a9667eb5314 Mon Sep 17 00:00:00 2001 From: stylianosgakis Date: Thu, 19 Nov 2026 17:14:07 +0100 Subject: [PATCH 2/9] Test the native graph end to end over a canned HTTP engine MockedNetworkIosGraph has every IosGraph binding with one difference: the Ktor engine is a MockEngine. The base client comes from the app's own buildKtorClient, now public for this, and the token plugin and both Apollo clients from the app's own providers, so a request goes through the iOS app's inputs and the real interceptors and never reaches the network. It lives in src/iosTestHook, which the umbrella's tests always compile and a simulator framework carries only when built with -Phedvig.ios.testHook=true, so no published framework contains it. The tests send a real operation from data-paying-member, from a background thread as reads do, and check the token and the iOS headers, that a public request sends no token and asks for none while a member is logged in, that a cache-first request still goes to the network, that a failing token fetch sends nothing, that UNAUTHENTICATED is an ordinary error, and what the iOS app's sink receives with the policy off, on and in production. (the graph is adapted from commits 20af0318a6 and a354e933e2: it reads the smaller accessor set, both clients and the base HTTP client) --- .../clients/di/NetworkMetroProviders.kt | 7 +- app/umbrella/build.gradle.kts | 13 ++ .../android/umbrella/IosGraphNetworkTest.kt | 200 ++++++++++++++++++ .../android/umbrella/MockedNetworkGraphs.kt | 66 ++++++ .../android/umbrella/MockedNetworkIosGraph.kt | 113 ++++++++++ 5 files changed, 398 insertions(+), 1 deletion(-) create mode 100644 app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/IosGraphNetworkTest.kt create mode 100644 app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/MockedNetworkGraphs.kt create mode 100644 app/umbrella/src/iosTestHook/kotlin/com/hedvig/android/umbrella/MockedNetworkIosGraph.kt diff --git a/app/network/network-clients/src/commonMain/kotlin/com/hedvig/android/network/clients/di/NetworkMetroProviders.kt b/app/network/network-clients/src/commonMain/kotlin/com/hedvig/android/network/clients/di/NetworkMetroProviders.kt index 00f78531e6..a6934c7ba2 100644 --- a/app/network/network-clients/src/commonMain/kotlin/com/hedvig/android/network/clients/di/NetworkMetroProviders.kt +++ b/app/network/network-clients/src/commonMain/kotlin/com/hedvig/android/network/clients/di/NetworkMetroProviders.kt @@ -90,7 +90,12 @@ internal fun buildHedvigApolloClient( .addHedvigInterceptors(platformInterceptors, networkLogPolicy) .build() -internal fun buildKtorClient( +/** + * The app's base Ktor client over [engineFactory]: timeouts, common headers, the device id and, when + * [networkLogPolicy] allows, body logging. Public so a test graph can build it over a fake engine and keep everything + * else real. + */ +fun buildKtorClient( engineFactory: HttpClientEngineFactory<*>, hedvigBuildConstants: HedvigBuildConstants, languageService: LanguageService, diff --git a/app/umbrella/build.gradle.kts b/app/umbrella/build.gradle.kts index eb63b800fd..b75afe19d6 100644 --- a/app/umbrella/build.gradle.kts +++ b/app/umbrella/build.gradle.kts @@ -9,6 +9,8 @@ plugins { id("com.rickclephas.kmp.nativecoroutines") } +val iosTestHookInFramework = providers.gradleProperty("hedvig.ios.testHook").orNull.toBoolean() + kotlin { sourceSets.configureEach { languageSettings.optIn("kotlin.experimental.ExperimentalObjCName") @@ -62,6 +64,17 @@ kotlin { nativeTest.dependencies { implementation(libs.apollo.normalizedCache) implementation(libs.assertK) + implementation(libs.kotlinx.serialization.json) + implementation(projects.dataPayingMember) + } + // The test hook: a graph over a canned HTTP engine for the umbrella's tests and the iOS app's simulator tests. + // Tests always compile it. A simulator framework carries it only when built with -Phedvig.ios.testHook=true, for + // the iOS app's tests in local umbrella mode; the release workflow never sets it, so no published framework does. + getByName(if (iosTestHookInFramework) "iosSimulatorArm64Main" else "iosSimulatorArm64Test") { + kotlin.srcDir("src/iosTestHook/kotlin") + dependencies { + implementation(libs.ktor.client.mock) + } } } } diff --git a/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/IosGraphNetworkTest.kt b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/IosGraphNetworkTest.kt new file mode 100644 index 0000000000..6d9dff6895 --- /dev/null +++ b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/IosGraphNetworkTest.kt @@ -0,0 +1,200 @@ +package com.hedvig.android.umbrella + +import assertk.assertThat +import assertk.assertions.containsExactly +import assertk.assertions.isEmpty +import assertk.assertions.isEqualTo +import assertk.assertions.isInstanceOf +import assertk.assertions.isNotNull +import assertk.assertions.isNull +import assertk.assertions.isTrue +import com.apollographql.apollo.ApolloClient +import com.apollographql.apollo.exception.ApolloNetworkException +import com.apollographql.cache.normalized.FetchPolicy +import com.apollographql.cache.normalized.fetchPolicy +import com.hedvig.android.core.tracking.RumLogger +import com.hedvig.android.logger.IosLogcatLogger +import com.hedvig.android.logger.LogPriority +import com.hedvig.android.logger.LogcatLogger +import com.hedvig.android.network.clients.NetworkLogPolicy +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withContext +import octopus.PayingMemberPhoneNumberQuery + +/** The real bindings over a canned HTTP engine, sent from a background thread as the iOS app's reads are. */ +class IosGraphNetworkTest { + private val sink = RecordingSink() + + @BeforeTest + fun installSink() { + IosLogcatLogger.install(sink, LogPriority.VERBOSE) + RumLogger.install(LogcatRumLogger) + } + + @AfterTest + fun uninstallLoggers() { + LogcatLogger.uninstall() + RumLogger.uninstall() + } + + @Test + fun `a member request carries the token and the iOS headers and calls the inputs from a background thread`() { + val backend = RecordingBackend(mapOf(OPERATION to MEMBER_JSON)) + val inputs = FakeInputs() + val graph = inputs.mockedGraph(backend) + + val response = graph.apolloClient.query() + + assertThat(response.exception).isNull() + val headers = backend.sent().single().headers + assertThat(headers["Authorization"]).isEqualTo("Bearer $ACCESS_TOKEN") + assertThat(headers["apollographql-client-name"]!!.startsWith("iOS:")).isTrue() + assertThat(headers["Accept-Language"]).isEqualTo("en-SE") + assertThat(headers["X-Platform"]).isEqualTo("ios") + assertThat(headers["Hedvig-TimeZone"]).isNotNull() + // Kotlin calls the inputs from any thread; a request made off the main thread calls them off it. + for (input in listOf(inputs.accessTokenFetcher, inputs.languageSource)) { + assertThat(input.calledOnMainThread().any { onMainThread -> !onMainThread }).isTrue() + } + } + + @Test + fun `a public request sends no token and never asks for one even while a member is logged in`() { + val backend = RecordingBackend(mapOf(OPERATION to MEMBER_JSON)) + val inputs = FakeInputs() + val graph = inputs.mockedGraph(backend) + + graph.apolloClient.query() + val tokenCallsAfterMemberRequest = inputs.accessTokenFetcher.calls.value + graph.publicApolloClient.query() + + val sent = backend.sent() + assertThat(sent.map { it.headers["Authorization"] }).containsExactly("Bearer $ACCESS_TOKEN", null) + assertThat(sent.last().headers["hedvig-device-id"]).isEqualTo(DEVICE_ID) + assertThat(inputs.accessTokenFetcher.calls.value).isEqualTo(tokenCallsAfterMemberRequest) + } + + @Test + fun `a fetch policy that asks for the cache is answered from the network every time`() { + val backend = RecordingBackend(mapOf(OPERATION to MEMBER_JSON)) + val graph = FakeInputs().mockedGraph(backend) + + repeat(2) { graph.apolloClient.query(FetchPolicy.CacheFirst) } + repeat(2) { graph.publicApolloClient.query(FetchPolicy.CacheFirst) } + + assertThat(backend.sent().size).isEqualTo(4) + } + + @Test + fun `a throwing token fetcher fails the request without sending it`() { + val backend = RecordingBackend(mapOf(OPERATION to MEMBER_JSON)) + val graph = FakeInputs(accessTokenFetcher = FakeAccessTokenFetcher(throws = true)).mockedGraph(backend) + + val response = graph.apolloClient.query() + + assertThat(response.exception).isNotNull().isInstanceOf() + assertThat(response.data).isNull() + assertThat(backend.sent()).isEmpty() + } + + @Test + fun `an UNAUTHENTICATED answer is an ordinary error`() { + val backend = RecordingBackend(mapOf(OPERATION to UNAUTHENTICATED_JSON)) + val graph = FakeInputs().mockedGraph(backend) + + val response = graph.apolloClient.query() + + assertThat(response.errors.orEmpty().map { it.extensions?.get("errorType") }).containsExactly("UNAUTHENTICATED") + } + + @Test + fun `with the policy off no line the iOS app's sink receives carries a body or GraphQL data or error text`() { + val backend = RecordingBackend(mapOf(OPERATION to SENTINEL_DATA_JSON)) + val graph = FakeInputs().mockedGraph(backend) + + graph.apolloClient.query() + backend.answer(OPERATION, SENTINEL_DATA_AND_ERROR_JSON) + graph.apolloClient.query() + + assertThat(sink.messages().filter { DATA_SENTINEL in it || EXTENSION_SENTINEL in it || ERROR_TEXT in it }) + .isEmpty() + val errorLine = "GraphQL errors for $OPERATION: 1 (error types [null])" + assertThat(sink.messages().filter { "GraphQL" in it }).containsExactly( + "GraphQL request for $OPERATION START.", + "GraphQL request for $OPERATION EMISSION.", + "GraphQL request for $OPERATION END.", + "GraphQL request for $OPERATION START.", + "GraphQL request for $OPERATION EMISSION.", + "$errorLine attributes: {} There was data and errors at the same time!", + "RUM error from NETWORK: $errorLine attribute keys: []", + "GraphQL request for $OPERATION END.", + ) + } + + @Test + fun `in production the error text reaches the iOS app's sink and the data does not`() { + val backend = RecordingBackend(mapOf(OPERATION to SENTINEL_DATA_AND_ERROR_JSON)) + val inputs = FakeInputs( + appFlavor = com.hedvig.android.core.buildconstants.Flavor.Production, + networkLogPolicy = NetworkLogPolicy(logsHttpBodies = true, logsGraphqlData = true, logsGraphqlErrors = true), + ) + val graph = inputs.mockedGraph(backend) + + graph.apolloClient.query() + + assertThat(sink.messages().filter { DATA_SENTINEL in it }).isEmpty() + assertThat(sink.messages().any { ERROR_TEXT in it }).isTrue() + } + + @Test + fun `with the policy on bodies and GraphQL data reach the iOS app's sink`() { + val backend = RecordingBackend(mapOf(OPERATION to SENTINEL_DATA_AND_ERROR_JSON)) + val inputs = FakeInputs( + networkLogPolicy = NetworkLogPolicy(logsHttpBodies = true, logsGraphqlData = true, logsGraphqlErrors = true), + ) + val graph = inputs.mockedGraph(backend) + + graph.apolloClient.query() + + val entries = sink.entries() + assertThat(entries.any { (priority, line) -> priority == LogPriority.VERBOSE && DATA_SENTINEL in line }).isTrue() + assertThat(entries.any { (priority, line) -> priority == LogPriority.DEBUG && DATA_SENTINEL in line }).isTrue() + assertThat(entries.any { (_, line) -> ERROR_TEXT in line }).isTrue() + } +} + +/** Sends the test operation from a background thread, as a read on `Dispatchers.Default` does. */ +private fun ApolloClient.query(fetchPolicy: FetchPolicy = FetchPolicy.NetworkOnly) = runBlocking { + withContext(Dispatchers.Default) { + query(PayingMemberPhoneNumberQuery()).fetchPolicy(fetchPolicy).execute() + } +} + +private const val OPERATION = "PayingMemberPhoneNumber" +private const val DATA_SENTINEL = "member-sentinel-6d0e" +private const val EXTENSION_SENTINEL = "extension-sentinel-a41b" +private const val ERROR_TEXT = "Something went wrong for member-text-93c1" + +private val MEMBER_JSON = """ + {"data": {"currentMember": {"__typename": "Member", "id": "member-1", "phoneNumber": null}}} +""".trimIndent() + +private val UNAUTHENTICATED_JSON = """ + {"errors": [{"message": "Unauthenticated", "extensions": {"errorType": "UNAUTHENTICATED"}}]} +""".trimIndent() + +private val SENTINEL_DATA_JSON = """ + {"data": {"currentMember": {"__typename": "Member", "id": "$DATA_SENTINEL", "phoneNumber": null}}} +""".trimIndent() + +private val SENTINEL_DATA_AND_ERROR_JSON = """ + { + "data": {"currentMember": {"__typename": "Member", "id": "$DATA_SENTINEL", "phoneNumber": null}}, + "errors": [{"message": "$ERROR_TEXT", "extensions": {"detail": "$EXTENSION_SENTINEL"}}], + "extensions": {"trace": "$EXTENSION_SENTINEL"} + } +""".trimIndent() diff --git a/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/MockedNetworkGraphs.kt b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/MockedNetworkGraphs.kt new file mode 100644 index 0000000000..edf183cc42 --- /dev/null +++ b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/MockedNetworkGraphs.kt @@ -0,0 +1,66 @@ +package com.hedvig.android.umbrella + +import dev.zacsweers.metro.createGraphFactory +import io.ktor.client.engine.mock.MockEngine +import io.ktor.client.engine.mock.respond +import io.ktor.client.engine.mock.toByteArray +import io.ktor.http.ContentType +import io.ktor.http.Headers +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.http.headersOf +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import platform.Foundation.NSLock + +/** The real bindings over [backend] instead of the network. */ +internal fun FakeInputs.mockedGraph(backend: RecordingBackend): MockedNetworkIosGraph = + createGraphFactory().create( + appBuildConfig = IosAppBuildConfig(appFlavor), + accessTokenFetcher = accessTokenFetcher, + deviceIdFetcher = deviceIdFetcher, + languageSource = languageSource, + networkLogPolicy = networkLogPolicy.allowedFor(appFlavor), + engine = backend.engine, + ) + +/** One request as the HTTP engine received it. */ +internal class SentRequest(val operation: String, val headers: Headers, val body: String) + +/** + * The backend at the HTTP engine: GraphQL answers by operation name; an operation without one is answered with HTTP + * 500. Records every request. + */ +internal class RecordingBackend(initialAnswers: Map = emptyMap()) { + private val lock = NSLock() + private val answers = initialAnswers.toMutableMap() + private val sent = mutableListOf() + + fun sent(): List = locked { sent.toList() } + + fun answer(operation: String, json: String) = locked { answers[operation] = json } + + val engine = MockEngine { request -> + val body = request.body.toByteArray().decodeToString() + val operation = Json.parseToJsonElement(body).jsonObject["operationName"]!!.jsonPrimitive.content + val json = locked { + sent += SentRequest(operation, request.headers, body) + answers[operation] + } + if (json == null) { + respond("", HttpStatusCode.InternalServerError) + } else { + respond(json, HttpStatusCode.OK, headersOf(HttpHeaders.ContentType, ContentType.Application.Json.toString())) + } + } + + private fun locked(block: () -> T): T { + lock.lock() + try { + return block() + } finally { + lock.unlock() + } + } +} diff --git a/app/umbrella/src/iosTestHook/kotlin/com/hedvig/android/umbrella/MockedNetworkIosGraph.kt b/app/umbrella/src/iosTestHook/kotlin/com/hedvig/android/umbrella/MockedNetworkIosGraph.kt new file mode 100644 index 0000000000..9059013d74 --- /dev/null +++ b/app/umbrella/src/iosTestHook/kotlin/com/hedvig/android/umbrella/MockedNetworkIosGraph.kt @@ -0,0 +1,113 @@ +package com.hedvig.android.umbrella + +import com.apollographql.apollo.ApolloClient +import com.hedvig.android.core.buildconstants.AppBuildConfig +import com.hedvig.android.core.buildconstants.HedvigBuildConstants +import com.hedvig.android.core.common.di.AppScope +import com.hedvig.android.core.common.di.BaseHttpClient +import com.hedvig.android.core.common.di.PublicApolloClient +import com.hedvig.android.core.datastore.DeviceIdFetcher +import com.hedvig.android.core.datastore.di.NativeDataStoreMetroProviders +import com.hedvig.android.language.IosLanguageSource +import com.hedvig.android.language.LanguageService +import com.hedvig.android.network.clients.AccessTokenFetcher +import com.hedvig.android.network.clients.ExtraKtorClientConfiguration +import com.hedvig.android.network.clients.NetworkLogPolicy +import com.hedvig.android.network.clients.di.NativeNetworkMetroProviders +import com.hedvig.android.network.clients.di.NetworkMetroProviders +import com.hedvig.android.network.clients.di.buildKtorClient +import dev.zacsweers.metro.DependencyGraph +import dev.zacsweers.metro.Provides +import dev.zacsweers.metro.SingleIn +import io.ktor.client.HttpClient +import io.ktor.client.HttpClientConfig +import io.ktor.client.engine.HttpClientEngine +import io.ktor.client.engine.HttpClientEngineFactory +import io.ktor.client.engine.mock.MockEngine +import io.ktor.client.engine.mock.MockEngineConfig + +/** + * [IosGraph]'s bindings, every `AppScope` contribution included, with one difference: the HTTP engine is [MockEngine] + * instead of Darwin. The Ktor client is built by the app's own `buildKtorClient` and wrapped by the app's own token + * plugin, and both Apollo clients by the app's own native providers, so every request reaches the iOS app's inputs + * (token, device id, language) as on a device, and nothing reaches the network. + */ +@DependencyGraph( + AppScope::class, + excludes = [NativeNetworkMetroProviders::class, NetworkMetroProviders::class, NativeDataStoreMetroProviders::class], +) +internal interface MockedNetworkIosGraph : IosGraphAccessors { + /** The token-free client every other client is built on. */ + @BaseHttpClient + val baseHttpClient: HttpClient + + @Provides + fun provideExtraKtorClientConfiguration(): ExtraKtorClientConfiguration = object : ExtraKtorClientConfiguration { + override fun configure(config: HttpClientConfig<*>) {} + } + + @Provides + @SingleIn(AppScope::class) + @BaseHttpClient + fun provideBaseHttpClient( + engine: MockEngine, + hedvigBuildConstants: HedvigBuildConstants, + languageService: LanguageService, + deviceIdFetcher: DeviceIdFetcher, + extraKtorClientConfiguration: ExtraKtorClientConfiguration, + networkLogPolicy: NetworkLogPolicy, + ): HttpClient = buildKtorClient( + engineFactory = object : HttpClientEngineFactory { + override fun create(block: MockEngineConfig.() -> Unit): HttpClientEngine = engine + }, + hedvigBuildConstants = hedvigBuildConstants, + languageService = languageService, + deviceIdFetcher = deviceIdFetcher, + extraKtorClientConfiguration = extraKtorClientConfiguration, + networkLogPolicy = networkLogPolicy, + ) + + @Provides + @SingleIn(AppScope::class) + fun provideHttpClient( + @BaseHttpClient baseHttpClient: HttpClient, + accessTokenFetcher: AccessTokenFetcher, + ): HttpClient = object : NetworkMetroProviders {}.provideHttpClient(baseHttpClient, accessTokenFetcher) + + @Provides + @SingleIn(AppScope::class) + fun provideApolloClient( + httpClient: HttpClient, + hedvigBuildConstants: HedvigBuildConstants, + networkLogPolicy: NetworkLogPolicy, + ): ApolloClient = object : NativeNetworkMetroProviders {}.provideApolloClient( + httpClient = httpClient, + hedvigBuildConstants = hedvigBuildConstants, + networkLogPolicy = networkLogPolicy, + ) + + @Provides + @SingleIn(AppScope::class) + @PublicApolloClient + fun providePublicApolloClient( + @BaseHttpClient httpClient: HttpClient, + hedvigBuildConstants: HedvigBuildConstants, + networkLogPolicy: NetworkLogPolicy, + ): ApolloClient = object : NativeNetworkMetroProviders {}.providePublicApolloClient( + httpClient = httpClient, + hedvigBuildConstants = hedvigBuildConstants, + networkLogPolicy = networkLogPolicy, + ) + + @DependencyGraph.Factory + interface Factory { + fun create( + @Provides appBuildConfig: AppBuildConfig, + @Provides accessTokenFetcher: AccessTokenFetcher, + @Provides deviceIdFetcher: DeviceIdFetcher, + @Provides languageSource: IosLanguageSource, + @Provides networkLogPolicy: NetworkLogPolicy, + @Provides engine: MockEngine, + ): MockedNetworkIosGraph + } +} From a841f7e1f8bdfb36de8b783d55c2c604687313d8 Mon Sep 17 00:00:00 2001 From: stylianosgakis Date: Thu, 19 Nov 2026 17:16:20 +0100 Subject: [PATCH 3/9] Add a simulator test hook with an example member and logged-out read The iOS app's tests and the Kotlin tests need to drive the real graph, network clients and read helper without a backend. CannedBackend answers, fails or holds GraphQL operations by name and records what was sent; TestGraphs.create builds the real bindings over it, optionally with a token fetch that never answers, and returns the holder. ExampleReads is written the way a feature writes its reads: an @Inject facade over SessionReads, an accessor interface contributed to the app scope, and an extension on IosGraphHolder that Swift sees as a method. It proves a feature adds reads without touching the holder or the graph. It has a member read and a logged-out read of data-conversations' operation, which links no compose resources, so checkUmbrellaClasspath holds with the hook in the framework too. Like the test graph, the hook is compiled into a simulator framework only with -Phedvig.ios.testHook=true, for the iOS app's tests in local umbrella mode; the published framework never has it. The tests drive the hook the way the iOS app's tests would: a canned answer with the member's token, an HTTP failure with the names the iOS app logs, a login or logout while a member read is held, a token fetch that never answers (TIMEOUT, then STUCK, one fetch), a logged-out read that sends no token while a member is logged in and is not ended by a login or logout, and a cancel that reads as no failure. (adapted from the reads experiment's hook in dcb65db4a0) --- app/umbrella/build.gradle.kts | 2 + .../android/umbrella/TestReadsHookTest.kt | 202 ++++++++++++++++++ .../hedvig/android/umbrella/TestReadsHook.kt | 189 ++++++++++++++++ 3 files changed, 393 insertions(+) create mode 100644 app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/TestReadsHookTest.kt create mode 100644 app/umbrella/src/iosTestHook/kotlin/com/hedvig/android/umbrella/TestReadsHook.kt diff --git a/app/umbrella/build.gradle.kts b/app/umbrella/build.gradle.kts index b75afe19d6..9b5e29a063 100644 --- a/app/umbrella/build.gradle.kts +++ b/app/umbrella/build.gradle.kts @@ -73,7 +73,9 @@ kotlin { getByName(if (iosTestHookInFramework) "iosSimulatorArm64Main" else "iosSimulatorArm64Test") { kotlin.srcDir("src/iosTestHook/kotlin") dependencies { + implementation(libs.kotlinx.serialization.json) implementation(libs.ktor.client.mock) + implementation(projects.dataConversations) } } } diff --git a/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/TestReadsHookTest.kt b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/TestReadsHookTest.kt new file mode 100644 index 0000000000..deaeb44d94 --- /dev/null +++ b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/TestReadsHookTest.kt @@ -0,0 +1,202 @@ +package com.hedvig.android.umbrella + +import assertk.assertThat +import assertk.assertions.containsExactly +import assertk.assertions.isEqualTo +import assertk.assertions.isNotNull +import assertk.assertions.isNull +import assertk.assertions.isTrue +import com.hedvig.android.core.tracking.RumLogger +import com.hedvig.android.iosdata.bridge.ReadFailureKind +import com.hedvig.android.iosdata.bridge.ReadFailureReason +import com.hedvig.android.iosdata.bridge.ReadFailures +import com.hedvig.android.logger.IosLogcatLogger +import com.hedvig.android.logger.LogPriority +import com.hedvig.android.logger.LogcatLogger +import com.rickclephas.kmp.nativecoroutines.NativeSuspend +import kotlin.concurrent.AtomicReference +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds +import platform.Foundation.NSError + +/** + * The hook the iOS app's tests use, driven the way they drive it: canned answers, the real graph, the real reads, the + * example reads reached through the holder as a feature's are. + */ +class TestReadsHookTest { + private val sink = RecordingSink() + + @BeforeTest + fun installSink() { + IosLogcatLogger.install(sink, LogPriority.VERBOSE) + } + + @AfterTest + fun uninstallLoggers() { + LogcatLogger.uninstall() + RumLogger.uninstall() + } + + @Test + fun `a canned answer reaches the member read with the member's token`() { + val backend = CannedBackend().apply { answer(OPERATION, CONVERSATIONS_JSON) } + val test = TestGraphs.create(backend, tokenFetchNeverAnswers = false) + + val read = test.holder.exampleReads().memberConversations().readWithin() + + assertThat(read.value?.openCount).isEqualTo(1) + assertThat(backend.sentAuthorizations()).containsExactly("Bearer test-access-token") + } + + @Test + fun `a failed operation gives a general failure with the names the iOS app logs`() { + val test = TestGraphs.create(CannedBackend(), tokenFetchNeverAnswers = false) + + val failure = test.holder.exampleReads().memberConversations().readWithin().failure!! + + assertThat(listOf(failure.kind, failure.reason, failure.readName, failure.operationName)) + .containsExactly(ReadFailureKind.GENERAL, ReadFailureReason.HTTP, "example.memberConversations", OPERATION) + assertThat(sink.messages().filter { it.startsWith("Read ") }) + .containsExactly("Read example.memberConversations failed: GENERAL HTTP") + } + + @Test + fun `a held operation and the end of a session give a session ended failure`() { + val backend = CannedBackend().apply { hold(OPERATION) } + val test = TestGraphs.create(backend, tokenFetchNeverAnswers = false) + val delivered = test.holder.exampleReads().memberConversations().startRead() + check(pumpMainLoopUntil { backend.sentOperations().isNotEmpty() }) + + test.holder.sessionEnded() + + assertThat(pumpMainLoopUntil { delivered.value != null }).isTrue() + assertThat(delivered.value!!.cancellation).isNull() + assertThat(delivered.value!!.failure?.kind).isEqualTo(ReadFailureKind.SESSION_ENDED) + backend.release(OPERATION) + } + + @Test + fun `the start of a session ends a member read in flight too`() { + val backend = CannedBackend().apply { hold(OPERATION) } + val test = TestGraphs.create(backend, tokenFetchNeverAnswers = false) + val delivered = test.holder.exampleReads().memberConversations().startRead() + check(pumpMainLoopUntil { backend.sentOperations().isNotEmpty() }) + + test.holder.sessionStarted() + + assertThat(pumpMainLoopUntil { delivered.value != null }).isTrue() + assertThat(delivered.value!!.failure?.kind).isEqualTo(ReadFailureKind.SESSION_ENDED) + backend.release(OPERATION) + } + + @Test + fun `a member read waiting on a token fetch that never answers fails within its timeout`() { + val backend = CannedBackend().apply { answer(OPERATION, CONVERSATIONS_JSON) } + val test = TestGraphs.create(backend, tokenFetchNeverAnswers = true) + test.graph.sessionReads.readTimeout = 300.milliseconds + + val first = test.holder.exampleReads().memberConversations().readWithin() + val second = test.holder.exampleReads().memberConversations().readWithin() + + assertThat(first.failure?.reason).isEqualTo(ReadFailureReason.TIMEOUT) + assertThat(second.failure?.reason).isEqualTo(ReadFailureReason.STUCK) + assertThat(test.tokenFetchCount()).isEqualTo(1) + assertThat(backend.sentOperations()).containsExactly() + } + + @Test + fun `a logged-out read sends no token and asks for none while the token fetch hangs`() { + val backend = CannedBackend().apply { answer(OPERATION, CONVERSATIONS_JSON) } + val test = TestGraphs.create(backend, tokenFetchNeverAnswers = true) + test.graph.sessionReads.readTimeout = 300.milliseconds + + val read = test.holder.exampleReads().publicConversations().readWithin() + + assertThat(read.value?.openCount).isEqualTo(1) + assertThat(test.tokenFetchCount()).isEqualTo(0) + assertThat(backend.sentAuthorizations()).containsExactly("") + } + + @Test + fun `a logged-out read sends no token while a member is logged in`() { + val backend = CannedBackend().apply { answer(OPERATION, CONVERSATIONS_JSON) } + val test = TestGraphs.create(backend, tokenFetchNeverAnswers = false) + test.holder.sessionStarted() + + test.holder.exampleReads().memberConversations().readWithin() + test.holder.exampleReads().publicConversations().readWithin() + + assertThat(backend.sentAuthorizations()).containsExactly("Bearer test-access-token", "") + } + + @Test + fun `a login or a logout does not end a logged-out read in flight`() { + val backend = CannedBackend().apply { + answer(OPERATION, CONVERSATIONS_JSON) + hold(OPERATION) + } + val test = TestGraphs.create(backend, tokenFetchNeverAnswers = false) + val delivered = test.holder.exampleReads().publicConversations().startRead() + check(pumpMainLoopUntil { backend.sentOperations().isNotEmpty() }) + + test.holder.sessionStarted() + test.holder.sessionEnded() + backend.release(OPERATION) + + assertThat(pumpMainLoopUntil { delivered.value != null }).isTrue() + assertThat(delivered.value!!.value?.openCount).isEqualTo(1) + } + + @Test + fun `a cancel by the awaiting task reads as no failure`() { + val backend = CannedBackend().apply { hold(OPERATION) } + val test = TestGraphs.create(backend, tokenFetchNeverAnswers = false) + var cancellation: NSError? = null + val cancel = test.holder.exampleReads().memberConversations()( + { _, unit -> unit }, + { _, unit -> unit }, + { error, unit -> + cancellation = error + unit + }, + ) + + cancel() + + assertThat(cancellation).isNotNull() + assertThat(ReadFailures.from(cancellation!!)).isNull() + backend.release(OPERATION) + } +} + +/** What a read delivered to the iOS app: one of a value, an error, or a cancellation. */ +internal class ReadCall(val value: T?, val error: NSError?, val cancellation: NSError?) { + val failure get() = error?.let { ReadFailures.from(it) } +} + +/** Starts the read as `asyncFunction(for:)` does; the reference is set by the first callback. */ +internal fun NativeSuspend.startRead(): AtomicReference?> { + val delivered = AtomicReference?>(null) + this( + { value, unit -> delivered.compareAndSet(null, ReadCall(value, null, null)).let { unit } }, + { error, unit -> delivered.compareAndSet(null, ReadCall(null, error, null)).let { unit } }, + { error, unit -> delivered.compareAndSet(null, ReadCall(null, null, error)).let { unit } }, + ) + return delivered +} + +private fun NativeSuspend.readWithin(): ReadCall { + val delivered = startRead() + check(pumpMainLoopUntil(10.seconds) { delivered.value != null }) { "The read did not call back" } + return delivered.value!! +} + +private const val OPERATION = "CbmNumberOfChatMessages" +private const val CONVERSATIONS_JSON = """ +{"data": {"currentMember": {"__typename": "Member", "id": "member-1", "legacyConversation": null, "conversations": [ + {"__typename": "Conversation", "id": "conversation-1", "isOpen": true, "newestMessage": null}, + {"__typename": "Conversation", "id": "conversation-2", "isOpen": false, "newestMessage": null}]}}} +""" diff --git a/app/umbrella/src/iosTestHook/kotlin/com/hedvig/android/umbrella/TestReadsHook.kt b/app/umbrella/src/iosTestHook/kotlin/com/hedvig/android/umbrella/TestReadsHook.kt new file mode 100644 index 0000000000..bcb4fe08d2 --- /dev/null +++ b/app/umbrella/src/iosTestHook/kotlin/com/hedvig/android/umbrella/TestReadsHook.kt @@ -0,0 +1,189 @@ +package com.hedvig.android.umbrella + +import com.apollographql.apollo.ApolloClient +import com.hedvig.android.core.buildconstants.Flavor +import com.hedvig.android.core.common.ErrorMessage +import com.hedvig.android.core.common.di.AppScope +import com.hedvig.android.core.datastore.DeviceIdFetcher +import com.hedvig.android.iosdata.bridge.IosGraphHolder +import com.hedvig.android.iosdata.bridge.SessionReads +import com.hedvig.android.iosdata.bridge.component +import com.hedvig.android.iosdata.bridge.generalReadFailure +import com.hedvig.android.iosdata.bridge.iosGraphHolder +import com.hedvig.android.language.IosLanguageSource +import com.hedvig.android.language.Language +import com.hedvig.android.network.clients.AccessTokenFetcher +import com.hedvig.android.network.clients.NetworkLogPolicy +import com.rickclephas.kmp.nativecoroutines.NativeSuspend +import dev.zacsweers.metro.ContributesTo +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.createGraphFactory +import io.ktor.client.engine.mock.MockEngine +import io.ktor.client.engine.mock.respond +import io.ktor.client.engine.mock.toByteArray +import io.ktor.http.ContentType +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.http.headersOf +import kotlin.concurrent.AtomicInt +import kotlin.coroutines.suspendCoroutine +import kotlinx.coroutines.CompletableDeferred +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import octopus.CbmNumberOfChatMessagesQuery +import platform.Foundation.NSLock + +/* + * Test hook for the iOS app's tests: the real Kotlin graph, network clients and read helper, with a canned HTTP + * engine. Tests get real failures by driving the backend: a missing answer fails as GENERAL, a held answer and a + * session signal end as SESSION_ENDED, and cancelling the awaiting task is a cancel. + */ + +/** + * The backend as tests describe it: an answer per GraphQL operation name, or an answer held back until released. An + * operation without an answer fails with HTTP 500. + */ +class CannedBackend { + private val lock = NSLock() + private val answers = mutableMapOf() + private val held = mutableMapOf>() + private val sent = mutableListOf() + private val authorizations = mutableListOf() + + /** Answers [operation] with [json], a whole GraphQL response body such as `{"data": {...}}`. */ + fun answer(operation: String, json: String) { + locked { answers[operation] = json } + } + + /** Answers [operation] with HTTP 500. */ + fun fail(operation: String) { + locked { answers.remove(operation) } + } + + /** Holds [operation]'s answer until [release]. */ + fun hold(operation: String) { + locked { held[operation] = CompletableDeferred() } + } + + fun release(operation: String) { + locked { held.remove(operation) }?.complete(Unit) + } + + /** The operation names sent so far, in order. */ + fun sentOperations(): List = locked { sent.toList() } + + /** The `Authorization` header of each request sent so far, in order, "" where there was none. */ + fun sentAuthorizations(): List = locked { authorizations.toList() } + + internal val engine = MockEngine { request -> + val body = Json.parseToJsonElement(request.body.toByteArray().decodeToString()).jsonObject + val operation = body["operationName"]!!.jsonPrimitive.content + val gate = locked { + sent += operation + authorizations += request.headers[HttpHeaders.Authorization].orEmpty() + held[operation] + } + gate?.await() + val json = locked { answers[operation] } + if (json == null) { + respond("", HttpStatusCode.InternalServerError) + } else { + respond(json, HttpStatusCode.OK, headersOf(HttpHeaders.ContentType, ContentType.Application.Json.toString())) + } + } + + private fun locked(block: () -> T): T { + lock.lock() + try { + return block() + } finally { + lock.unlock() + } + } +} + +/** + * An example of a feature's reads, written the way a feature writes them, for tests only: one member read and one + * logged-out read of data-conversations' operation, which needs no feature module. It reaches Swift through + * [ExampleReadsComponent] and the [exampleReads] extension, with no change to the holder or the graph. + */ +@Inject +class ExampleReads internal constructor(private val reads: SessionReads) { + fun memberConversations(): NativeSuspend = reads.read( + "example.memberConversations", + operation = OPERATION, + ) { + conversations(apolloClient) + } + + fun publicConversations(): NativeSuspend = reads.publicRead( + "example.publicConversations", + operation = OPERATION, + ) { + conversations(apolloClient) + } + + private suspend fun conversations(client: ApolloClient): ExampleConversations { + val response = client.query(CbmNumberOfChatMessagesQuery()).execute() + val data = response.data ?: throw generalReadFailure(ErrorMessage(throwable = response.exception)) + return ExampleConversations(openCount = data.currentMember.conversations.count { it.isOpen }) + } + + private companion object { + const val OPERATION = "CbmNumberOfChatMessages" + } +} + +/** What an example read returns: a plain class with a non-null field, as a feature's model would be. */ +class ExampleConversations(val openCount: Int) + +/** The example's accessor, contributed to every graph that links it. */ +@ContributesTo(AppScope::class) +interface ExampleReadsComponent { + val exampleReads: ExampleReads +} + +/** The example reads, as Swift reaches a feature's reads: a method on the holder. */ +fun IosGraphHolder.exampleReads(): ExampleReads = component().exampleReads + +/** A graph over a [CannedBackend] and the holder the iOS app would have over it, already in use. */ +class TestGraph internal constructor( + internal val graph: MockedNetworkIosGraph, + private val tokenFetches: AtomicInt, +) { + val holder: IosGraphHolder = iosGraphHolder { graph }.also { it.graph } + + /** How often the graph asked for a token. */ + fun tokenFetchCount(): Int = tokenFetches.value +} + +object TestGraphs { + /** + * A graph over the real bindings with [backend] as the HTTP engine and staging inputs: a fixed token and device id, + * English, no body logging. With [tokenFetchNeverAnswers] the token fetch suspends forever, as a Swift fetcher that + * never calls back does. + */ + fun create(backend: CannedBackend, tokenFetchNeverAnswers: Boolean): TestGraph { + val tokenFetches = AtomicInt(0) + val graph = createGraphFactory().create( + appBuildConfig = IosAppBuildConfig(Flavor.Staging), + accessTokenFetcher = object : AccessTokenFetcher { + override suspend fun fetch(): String? { + tokenFetches.incrementAndGet() + if (tokenFetchNeverAnswers) suspendCoroutine { } + return "test-access-token" + } + }, + deviceIdFetcher = object : DeviceIdFetcher { + override suspend fun fetch(): String? = "test-device-id" + }, + languageSource = object : IosLanguageSource { + override fun currentLanguage(): Language = Language.EN_SE + }, + networkLogPolicy = NetworkLogPolicy(logsHttpBodies = false, logsGraphqlData = false, logsGraphqlErrors = true), + engine = backend.engine, + ) + return TestGraph(graph, tokenFetches) + } +} From c25388346385d469d42452e9c460f855d37b5992 Mon Sep 17 00:00:00 2001 From: stylianosgakis Date: Thu, 19 Nov 2026 17:19:20 +0100 Subject: [PATCH 4/9] Pin the Swift-visible API of the graph and the test hook in a header snapshot HeaderSnapshotTest reads the simulator debug framework's header and compares the declarations of the holder, its inputs, the log sink and the read failures with a snapshot in the test. A boxed primitive, a renamed or removed member, or a new type reached from the API then shows in the Android pull request that causes it, where the iOS reviewer sees it. Two more checks fail on any reached framework type outside the API and on any boxed primitive. The test hook has its own snapshot when the framework is built with it, and without it the test checks that no line of it is in the header. (adapted from the reads experiment's ReadsHeaderTest and the header parser of TravelCertificateDataHeaderTest; this parser also reads protocols and drops multi-line comments) --- app/umbrella/build.gradle.kts | 5 + .../android/umbrella/HeaderSnapshotTest.kt | 280 ++++++++++++++++++ 2 files changed, 285 insertions(+) create mode 100644 app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/HeaderSnapshotTest.kt diff --git a/app/umbrella/build.gradle.kts b/app/umbrella/build.gradle.kts index 9b5e29a063..19b91c6d23 100644 --- a/app/umbrella/build.gradle.kts +++ b/app/umbrella/build.gradle.kts @@ -81,4 +81,9 @@ kotlin { } } +// HeaderSnapshotTest reads the header of the simulator debug framework. +tasks.named("iosSimulatorArm64Test") { + dependsOn("linkDebugFrameworkIosSimulatorArm64") +} + registerUmbrellaClasspathGuard() diff --git a/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/HeaderSnapshotTest.kt b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/HeaderSnapshotTest.kt new file mode 100644 index 0000000000..4441be0989 --- /dev/null +++ b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/HeaderSnapshotTest.kt @@ -0,0 +1,280 @@ +@file:OptIn(BetaInteropApi::class, ExperimentalForeignApi::class) +@file:Suppress("ktlint:standard:max-line-length") + +package com.hedvig.android.umbrella + +import assertk.assertThat +import assertk.assertions.isEmpty +import assertk.assertions.isEqualTo +import kotlin.test.Test +import kotlinx.cinterop.BetaInteropApi +import kotlinx.cinterop.ExperimentalForeignApi +import platform.Foundation.NSBundle +import platform.Foundation.NSString +import platform.Foundation.NSUTF8StringEncoding +import platform.Foundation.stringWithContentsOfFile + +/** + * The Swift-visible API of the graph, its inputs, the log sink and the read failures, as the header Swift compiles + * against declares it. A changed declaration fails the snapshot, so a boxed primitive, a renamed or removed member, or + * a new type reached from the API shows in the pull request that causes it. Update [API_SNAPSHOT] or [HOOK_SNAPSHOT] + * from the failure message when the change is meant. + * + * The test hook is in the header only when the framework is built with `-Phedvig.ios.testHook=true`; without it, its + * test checks that none of it is there. + */ +class HeaderSnapshotTest { + private val apiTypes = listOf( + "HedvigSharedIosGraphHolderKt", + "HedvigSharedIosGraphHolder", + "HedvigSharedFlavor", + "HedvigSharedAccessTokenFetcher", + "HedvigSharedDeviceIdFetcher", + "HedvigSharedIosLanguageSource", + "HedvigSharedLanguage", + "HedvigSharedNetworkLogPolicy", + "HedvigSharedIosLogSink", + "HedvigSharedIosLogcatLoggerCompanion", + "HedvigSharedReadFailure", + "HedvigSharedReadFailureKind", + "HedvigSharedReadFailureReason", + "HedvigSharedReadFailures", + ) + + private val hookTypes = listOf( + "HedvigSharedCannedBackend", + "HedvigSharedTestGraphs", + "HedvigSharedTestGraph", + "HedvigSharedExampleReads", + "HedvigSharedExampleConversations", + ) + + /** Types the API may name besides its own: the framework's base types and the logger's existing ones. */ + private val baseTypes = setOf( + "HedvigSharedBase", + "HedvigSharedKotlinEnum", + "HedvigSharedKotlinEnumCompanion", + "HedvigSharedKotlinArray", + "HedvigSharedKotlinException", + "HedvigSharedKotlinThrowable", + "HedvigSharedKotlinUnit", + "HedvigSharedLanguageCompanion", + "HedvigSharedLogPriority", + "HedvigSharedLogcatLogger", + "HedvigSharedIosLogcatLogger", + "HedvigSharedReadFailureKindNSEnum", + "HedvigSharedReadFailureReasonNSEnum", + ) + + /** A line of the hook, wherever it is declared, such as the example reads' accessor on the holder. */ + private val hookLine = Regex("""ExampleReads|ExampleConversations|TestGraph|CannedBackend""") + + private val header: String by lazy { + val testBinary = NSBundle.mainBundle.executablePath ?: error("No executable path") + val path = testBinary.substringBeforeLast("/debugTest/") + + "/debugFramework/HedvigShared.framework/Headers/HedvigShared.h" + NSString.stringWithContentsOfFile(path, NSUTF8StringEncoding, null) ?: error("No header at $path") + } + + private val declarations: Map> by lazy { headerDeclarations(header) } + + private fun apiDeclarations(): String = apiTypes + .flatMap { declarations[it] ?: listOf("MISSING $it") } + .filterNot { hookLine.containsMatchIn(it) || it.endsWith("(Extensions)") } + .joinToString("\n") + + private fun hookDeclarations(): String = ( + hookTypes.flatMap { declarations[it] ?: listOf("MISSING $it") } + + declarations.getValue("HedvigSharedIosGraphHolder").filter { hookLine.containsMatchIn(it) } + ).joinToString("\n") + + @Test + fun `the graph API is declared as the snapshot says`() { + assertThat(apiDeclarations()).isEqualTo(API_SNAPSHOT.trimIndent()) + } + + @Test + fun `the test hook is declared as the snapshot says or is absent`() { + if (hookTypes.none { it in declarations }) { + assertThat(header.lines().filter { hookLine.containsMatchIn(it) }).isEmpty() + } else { + assertThat(hookDeclarations()).isEqualTo(HOOK_SNAPSHOT.trimIndent()) + } + } + + @Test + fun `the graph API reaches no other framework type`() { + val reached = Regex("""HedvigShared\w+""").findAll(apiDeclarations()).map { it.value }.toSet() + + assertThat(reached - apiTypes.toSet() - baseTypes).isEmpty() + } + + @Test + fun `no declaration of the graph API boxes a primitive`() { + val boxed = Regex("""HedvigShared(Kotlin(Int|Long|Short|Byte|Boolean|Double|Float|UInt|ULong)\b|Boolean\b|Int\b)""") + + assertThat(apiDeclarations().lines().filter { boxed.containsMatchIn(it) }).isEmpty() + } + + private companion object { + const val API_SNAPSHOT = """ +@interface HedvigSharedIosGraphHolderKt : HedvigSharedBase ++ (HedvigSharedIosGraphHolder *)createIosGraphHolderAppFlavor:(HedvigSharedFlavor *)appFlavor accessTokenFetcher:(id)accessTokenFetcher deviceIdFetcher:(id)deviceIdFetcher languageSource:(id)languageSource networkLogPolicy:(HedvigSharedNetworkLogPolicy *)networkLogPolicy __attribute__((swift_name("createIosGraphHolder(appFlavor:accessTokenFetcher:deviceIdFetcher:languageSource:networkLogPolicy:)"))); +@interface HedvigSharedIosGraphHolder : HedvigSharedBase +- (void)sessionEnded __attribute__((swift_name("sessionEnded()"))); +- (void)sessionStarted __attribute__((swift_name("sessionStarted()"))); +@interface HedvigSharedFlavor : HedvigSharedKotlinEnum ++ (instancetype)alloc __attribute__((unavailable)); ++ (instancetype)allocWithZone:(struct _NSZone *)zone __attribute__((unavailable)); +- (instancetype)initWithName:(NSString *)name ordinal:(int32_t)ordinal __attribute__((swift_name("init(name:ordinal:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable)); +@property (class, readonly) HedvigSharedFlavor *production __attribute__((swift_name("production"))); +@property (class, readonly) HedvigSharedFlavor *staging __attribute__((swift_name("staging"))); +@property (class, readonly) HedvigSharedFlavor *develop __attribute__((swift_name("develop"))); ++ (HedvigSharedKotlinArray *)values __attribute__((swift_name("values()"))); +@property (class, readonly) NSArray *entries __attribute__((swift_name("entries"))); +@protocol HedvigSharedAccessTokenFetcher +@required +- (void)fetchWithCompletionHandler:(void (^)(NSString * _Nullable_result, NSError * _Nullable))completionHandler __attribute__((swift_name("fetch(completionHandler:)"))); +@protocol HedvigSharedDeviceIdFetcher +@required +- (void)fetchWithCompletionHandler:(void (^)(NSString * _Nullable_result, NSError * _Nullable))completionHandler __attribute__((swift_name("fetch(completionHandler:)"))); +@protocol HedvigSharedIosLanguageSource +@required +- (HedvigSharedLanguage *)currentLanguage __attribute__((swift_name("currentLanguage()"))); +@interface HedvigSharedLanguage : HedvigSharedKotlinEnum ++ (instancetype)alloc __attribute__((unavailable)); ++ (instancetype)allocWithZone:(struct _NSZone *)zone __attribute__((unavailable)); +- (instancetype)initWithName:(NSString *)name ordinal:(int32_t)ordinal __attribute__((swift_name("init(name:ordinal:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable)); +@property (class, readonly, getter=companion) HedvigSharedLanguageCompanion *companion __attribute__((swift_name("companion"))); +@property (class, readonly) HedvigSharedLanguage *svSe __attribute__((swift_name("svSe"))); +@property (class, readonly) HedvigSharedLanguage *enSe __attribute__((swift_name("enSe"))); ++ (HedvigSharedKotlinArray *)values __attribute__((swift_name("values()"))); +@property (class, readonly) NSArray *entries __attribute__((swift_name("entries"))); +- (NSString *)toBcp47Format __attribute__((swift_name("toBcp47Format()"))); +- (NSString *)description __attribute__((swift_name("description()"))); +- (NSString *)webPath __attribute__((swift_name("webPath()"))); +@interface HedvigSharedNetworkLogPolicy : HedvigSharedBase +- (instancetype)initWithLogsHttpBodies:(BOOL)logsHttpBodies logsGraphqlData:(BOOL)logsGraphqlData logsGraphqlErrors:(BOOL)logsGraphqlErrors __attribute__((swift_name("init(logsHttpBodies:logsGraphqlData:logsGraphqlErrors:)"))) __attribute__((objc_designated_initializer)); +@property (readonly) BOOL logsGraphqlData __attribute__((swift_name("logsGraphqlData"))); +@property (readonly) BOOL logsGraphqlErrors __attribute__((swift_name("logsGraphqlErrors"))); +@property (readonly) BOOL logsHttpBodies __attribute__((swift_name("logsHttpBodies"))); +@protocol HedvigSharedIosLogSink +@required +- (void)logPriority:(HedvigSharedLogPriority *)priority tag:(NSString * _Nullable)tag message:(NSString *)message __attribute__((swift_name("log(priority:tag:message:)"))); +@interface HedvigSharedIosLogcatLoggerCompanion : HedvigSharedBase ++ (instancetype)alloc __attribute__((unavailable)); ++ (instancetype)allocWithZone:(struct _NSZone *)zone __attribute__((unavailable)); ++ (instancetype)companion __attribute__((swift_name("init()"))); +@property (class, readonly, getter=shared) HedvigSharedIosLogcatLoggerCompanion *shared __attribute__((swift_name("shared"))); +- (void)install __attribute__((swift_name("install()"))); +- (void)installSink:(id)sink minimumPriority:(HedvigSharedLogPriority *)minimumPriority __attribute__((swift_name("install(sink:minimumPriority:)"))); +@interface HedvigSharedReadFailure : HedvigSharedKotlinException +- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable)); ++ (instancetype)new __attribute__((unavailable)); +- (instancetype)initWithMessage:(NSString * _Nullable)message __attribute__((swift_name("init(message:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable)); +- (instancetype)initWithCause:(HedvigSharedKotlinThrowable * _Nullable)cause __attribute__((swift_name("init(cause:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable)); +- (instancetype)initWithMessage:(NSString * _Nullable)message cause:(HedvigSharedKotlinThrowable * _Nullable)cause __attribute__((swift_name("init(message:cause:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable)); +- (NSString *)description __attribute__((swift_name("description()"))); +@property (readonly) HedvigSharedReadFailureKind *kind __attribute__((swift_name("kind"))); +@property (readonly) NSString *operationName __attribute__((swift_name("operationName"))); +@property (readonly) NSString *readName __attribute__((swift_name("readName"))); +@property (readonly) HedvigSharedReadFailureReason *reason __attribute__((swift_name("reason"))); +@interface HedvigSharedReadFailureKind : HedvigSharedKotlinEnum ++ (instancetype)alloc __attribute__((unavailable)); ++ (instancetype)allocWithZone:(struct _NSZone *)zone __attribute__((unavailable)); +- (instancetype)initWithName:(NSString *)name ordinal:(int32_t)ordinal __attribute__((swift_name("init(name:ordinal:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable)); +@property (readonly) HedvigSharedReadFailureKindNSEnum nsEnum; +@property (class, readonly) HedvigSharedReadFailureKind *general __attribute__((swift_name("general"))); +@property (class, readonly) HedvigSharedReadFailureKind *sessionEnded __attribute__((swift_name("sessionEnded"))); ++ (HedvigSharedKotlinArray *)values __attribute__((swift_name("values()"))); +@property (class, readonly) NSArray *entries __attribute__((swift_name("entries"))); +@interface HedvigSharedReadFailureReason : HedvigSharedKotlinEnum ++ (instancetype)alloc __attribute__((unavailable)); ++ (instancetype)allocWithZone:(struct _NSZone *)zone __attribute__((unavailable)); +- (instancetype)initWithName:(NSString *)name ordinal:(int32_t)ordinal __attribute__((swift_name("init(name:ordinal:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable)); +@property (readonly) HedvigSharedReadFailureReasonNSEnum nsEnum; +@property (class, readonly) HedvigSharedReadFailureReason *graphqlErrors __attribute__((swift_name("graphqlErrors"))); +@property (class, readonly) HedvigSharedReadFailureReason *network __attribute__((swift_name("network"))); +@property (class, readonly) HedvigSharedReadFailureReason *http __attribute__((swift_name("http"))); +@property (class, readonly) HedvigSharedReadFailureReason *timeout __attribute__((swift_name("timeout"))); +@property (class, readonly) HedvigSharedReadFailureReason *stuck __attribute__((swift_name("stuck"))); +@property (class, readonly) HedvigSharedReadFailureReason *sessionEnded __attribute__((swift_name("sessionEnded"))); +@property (class, readonly) HedvigSharedReadFailureReason *unexpected __attribute__((swift_name("unexpected"))); ++ (HedvigSharedKotlinArray *)values __attribute__((swift_name("values()"))); +@property (class, readonly) NSArray *entries __attribute__((swift_name("entries"))); +@interface HedvigSharedReadFailures : HedvigSharedBase ++ (instancetype)alloc __attribute__((unavailable)); ++ (instancetype)allocWithZone:(struct _NSZone *)zone __attribute__((unavailable)); ++ (instancetype)readFailures __attribute__((swift_name("init()"))); +@property (class, readonly, getter=shared) HedvigSharedReadFailures *shared __attribute__((swift_name("shared"))); +- (HedvigSharedReadFailure * _Nullable)fromError:(NSError *)error __attribute__((swift_name("from(error:)"))); +""" + + const val HOOK_SNAPSHOT = """ +@interface HedvigSharedCannedBackend : HedvigSharedBase +- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer)); ++ (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead"))); +- (void)answerOperation:(NSString *)operation json:(NSString *)json __attribute__((swift_name("answer(operation:json:)"))); +- (void)failOperation:(NSString *)operation __attribute__((swift_name("fail(operation:)"))); +- (void)holdOperation:(NSString *)operation __attribute__((swift_name("hold(operation:)"))); +- (void)releaseOperation:(NSString *)operation __attribute__((swift_name("release(operation:)"))); +- (NSArray *)sentAuthorizations __attribute__((swift_name("sentAuthorizations()"))); +- (NSArray *)sentOperations __attribute__((swift_name("sentOperations()"))); +@interface HedvigSharedTestGraphs : HedvigSharedBase ++ (instancetype)alloc __attribute__((unavailable)); ++ (instancetype)allocWithZone:(struct _NSZone *)zone __attribute__((unavailable)); ++ (instancetype)testGraphs __attribute__((swift_name("init()"))); +@property (class, readonly, getter=shared) HedvigSharedTestGraphs *shared __attribute__((swift_name("shared"))); +- (HedvigSharedTestGraph *)createBackend:(HedvigSharedCannedBackend *)backend tokenFetchNeverAnswers:(BOOL)tokenFetchNeverAnswers __attribute__((swift_name("create(backend:tokenFetchNeverAnswers:)"))); +@interface HedvigSharedTestGraph : HedvigSharedBase +- (int32_t)tokenFetchCount __attribute__((swift_name("tokenFetchCount()"))); +@property (readonly) HedvigSharedIosGraphHolder *holder __attribute__((swift_name("holder"))); +@interface HedvigSharedExampleReads : HedvigSharedBase +- (HedvigSharedKotlinUnit *(^(^)(HedvigSharedKotlinUnit *(^)(HedvigSharedExampleConversations *, HedvigSharedKotlinUnit *), HedvigSharedKotlinUnit *(^)(NSError *, HedvigSharedKotlinUnit *), HedvigSharedKotlinUnit *(^)(NSError *, HedvigSharedKotlinUnit *)))(void))memberConversations __attribute__((swift_name("memberConversations()"))); +- (HedvigSharedKotlinUnit *(^(^)(HedvigSharedKotlinUnit *(^)(HedvigSharedExampleConversations *, HedvigSharedKotlinUnit *), HedvigSharedKotlinUnit *(^)(NSError *, HedvigSharedKotlinUnit *), HedvigSharedKotlinUnit *(^)(NSError *, HedvigSharedKotlinUnit *)))(void))publicConversations __attribute__((swift_name("publicConversations()"))); +@interface HedvigSharedExampleConversations : HedvigSharedBase +- (instancetype)initWithOpenCount:(int32_t)openCount __attribute__((swift_name("init(openCount:)"))) __attribute__((objc_designated_initializer)); +@property (readonly) int32_t openCount __attribute__((swift_name("openCount"))); +- (HedvigSharedExampleReads *)exampleReads __attribute__((swift_name("exampleReads()"))); +""" + } +} + +/** + * Each class's and protocol's declaration lines, without comments and blank lines, by its Objective-C name. A category + * (`@interface X (Extensions)`) is added to its class's lines, so no declaration of the class goes unread. + */ +internal fun headerDeclarations(header: String): Map> { + val blocks = mutableMapOf>() + var current: String? = null + var lines = mutableListOf() + var inComment = false + for (line in header.lines()) { + val trimmed = line.trim() + if (inComment) { + if (trimmed.endsWith("*/")) inComment = false + continue + } + if (trimmed.startsWith("/**") || trimmed.startsWith("/*")) { + if (!trimmed.endsWith("*/")) inComment = true + continue + } + val opening = Regex("""^@(interface|protocol) (\w+)\b""").find(line) + when { + opening != null && !trimmed.endsWith(";") -> { + current = opening.groupValues[2] + lines = mutableListOf(line) + } + + current != null && line.startsWith("@end") -> { + blocks[current] = blocks[current].orEmpty() + lines + current = null + } + + current != null && trimmed.isNotEmpty() -> { + lines += line + } + } + } + return blocks +} From 10ed5c46d1e1f6fdbab6514d1d9e93b1240df348 Mon Sep 17 00:00:00 2001 From: stylianosgakis Date: Thu, 19 Nov 2026 17:52:48 +0100 Subject: [PATCH 5/9] Compile the iOS source sets on every PR and run the iOS tests daily and before releases pr.yml runs on Linux and compiled nothing for iOS, so a commonMain or nativeMain change that breaks the iOS compile was only found by the nightly umbrella release. Kotlin/Native compiles iOS klibs on Linux, so a new ios_klibs job in pr.yml compiles every module's iOS source sets, main and test, next to the other Linux jobs. What needs macOS stays off normal PRs. ios-shared.yml runs every module's iOS simulator tests, the umbrella's tests with the test hook in the framework, the release device framework link, a check that the hook is not in it and a 20 MB size budget, once a day and as a required job of umbrella.yml, which also checks every slice of the XCFramework it publishes for the hook. A failed scheduled run is emailed by GitHub to whoever last changed its schedule, as for the repo's other scheduled workflows. To confirm before merging: the ios_klibs job's time on the runner, the macOS runner's time for the daily job, and that its Xcode has a simulator the Kotlin test task can boot. --- .github/workflows/ios-shared.yml | 54 ++++++++++++++++++++++++++++++++ .github/workflows/pr.yml | 18 +++++++++++ .github/workflows/umbrella.yml | 16 ++++++++++ CLAUDE.md | 5 +-- 4 files changed, 91 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/ios-shared.yml diff --git a/.github/workflows/ios-shared.yml b/.github/workflows/ios-shared.yml new file mode 100644 index 0000000000..b3d254897e --- /dev/null +++ b/.github/workflows/ios-shared.yml @@ -0,0 +1,54 @@ +name: iOS shared code + +# Normal PRs run on Linux, which compiles the iOS source sets to klibs but cannot run them. This job runs what only +# macOS can: every module's tests on the iOS simulator, the release device framework link, and the checks that the +# test hook stays out of it and the framework stays within its size budget. It runs once a day and as a required step +# of the umbrella release. GitHub emails a failed scheduled run to whoever last changed its schedule. +on: + schedule: + - cron: '0 3 * * *' + workflow_dispatch: + workflow_call: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event_name }} + cancel-in-progress: false + +jobs: + ios_shared: + name: iOS simulator tests and framework link + runs-on: macos-26-xlarge + env: + # The release iosArm64 framework's shipped bytes (__TEXT plus non-zerofill __DATA) may not exceed this. + MAX_SHIPPED_BYTES: 20000000 + steps: + - uses: actions/checkout@v7 + - name: Setup CI + uses: ./.github/actions/common-setup + with: + gradle-cache-read-only: 'false' + download-schema: 'false' + download-strings: 'false' + datadog-api-key: ${{ secrets.DATADOG_API_KEY }} + lokalise-id: ${{ secrets.LOKALISE_ID }} + lokalise-token: ${{ secrets.LOKALISE_TOKEN }} + - name: Tests on the iOS simulator + run: ./gradlew iosSimulatorArm64Test checkUmbrellaClasspath + - name: Umbrella tests with the test hook in the framework + # The header snapshot of the test hook only runs when the simulator framework carries it. + run: ./gradlew :umbrella:iosSimulatorArm64Test -Phedvig.ios.testHook=true + - name: Link the release device framework + run: ./gradlew :umbrella:linkReleaseFrameworkIosArm64 + - name: Check the device framework + run: | + BIN=app/umbrella/build/bin/iosArm64/releaseFramework/HedvigShared.framework/HedvigShared + if nm "$BIN" | grep -E 'CannedBackend|MockedNetworkIosGraph|TestGraphs|ExampleReads'; then + echo "The test hook reached the device framework" + exit 1 + fi + SHIPPED=$(size -m "$BIN" | grep -E 'Section \(__(TEXT|DATA), ' | grep -v zerofill | sed -E 's/.*: ([0-9]+).*/\1/' | paste -sd+ - | bc) + echo "Shipped bytes (__TEXT + non-zerofill __DATA): $SHIPPED, budget $MAX_SHIPPED_BYTES" + if [ "$SHIPPED" -gt "$MAX_SHIPPED_BYTES" ]; then + echo "The device framework is over its size budget" + exit 1 + fi diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 5ac5a460e6..e961ac8079 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -88,6 +88,24 @@ jobs: - name: check commonMain imports if: ${{ !cancelled() }} run: ./gradlew checkCommonMainImports + ios_klibs: + runs-on: ${{ github.event_name == 'push' && 'ubuntu-latest' || 'ubuntu-latest-8-vcpu' }} + steps: + - uses: actions/checkout@v7 + - name: Setup CI + uses: ./.github/actions/common-setup + with: + gradle-cache-read-only: ${{ github.event_name == 'pull_request' }} + download-schema: 'false' + download-strings: 'false' + datadog-api-key: ${{ secrets.DATADOG_API_KEY }} + lokalise-id: ${{ secrets.LOKALISE_ID }} + lokalise-token: ${{ secrets.LOKALISE_TOKEN }} + - name: Compile the iOS source sets + # Kotlin/Native compiles klibs for iOS on Linux, so a commonMain or nativeMain change that does not compile for + # iOS fails here. Linking the framework and running the simulator tests need macOS: ios-shared.yml does that + # once a day and before every umbrella release. + run: ./gradlew compileKotlinIosArm64 compileKotlinIosSimulatorArm64 compileTestKotlinIosSimulatorArm64 build: runs-on: ${{ github.event_name == 'push' && 'ubuntu-latest' || 'ubuntu-latest-8-vcpu' }} steps: diff --git a/.github/workflows/umbrella.yml b/.github/workflows/umbrella.yml index 82baf3a504..7451a703c4 100644 --- a/.github/workflows/umbrella.yml +++ b/.github/workflows/umbrella.yml @@ -17,8 +17,13 @@ concurrency: cancel-in-progress: false jobs: + ios_shared: + name: iOS simulator tests and framework link + uses: ./.github/workflows/ios-shared.yml + secrets: inherit umbrella_release: name: Build and release new umbrella version + needs: ios_shared runs-on: macos-26-xlarge steps: - uses: actions/checkout@v7 @@ -31,6 +36,17 @@ jobs: lokalise-token: ${{ secrets.LOKALISE_TOKEN }} - name: Build umbrella XCFramework run: ./gradlew :umbrella:assembleHedvigSharedReleaseXCFramework + # The test hook is compiled in only with -Phedvig.ios.testHook=true, which this workflow never sets. + - name: Check that no slice carries the test hook + run: | + FOUND=0 + for BIN in app/umbrella/build/XCFrameworks/release/HedvigShared.xcframework/*/HedvigShared.framework/HedvigShared; do + if nm "$BIN" | grep -E 'CannedBackend|MockedNetworkIosGraph|TestGraphs|ExampleReads'; then + echo "$BIN carries the test hook" + FOUND=1 + fi + done + exit $FOUND # The zip overstates what iOS ships by ~3x (debug info, symbol tables, simulator slice). The # number that reaches the app is __TEXT plus non-zerofill __DATA of the device slice. - name: Measure the device slice diff --git a/CLAUDE.md b/CLAUDE.md index e7cdcae7e3..e22478d50a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -668,13 +668,14 @@ other. ## CI/CD GitHub Actions workflows (in `.github/workflows/`): -- **pr.yml** - PR checks (lint, test, build) +- **pr.yml** - PR checks (lint, test, build, the iOS source sets compiled to klibs on Linux) - **staging.yml** - Staging builds - **upload-to-play-store.yml** - Production releases - **graphql-schema.yml** - Schema updates - **strings.yml** - Translation updates - **unused-resources.yml** - Resource cleanup checks -- **umbrella.yml** - Publishes the iOS umbrella framework on weeknights, or on manual trigger +- **umbrella.yml** - Publishes the iOS umbrella framework on weeknights, or on manual trigger, after ios-shared.yml passes +- **ios-shared.yml** - Daily on macOS: iOS simulator tests of every iOS module, the release device framework link and its checks ## Important Files From 85b3b5b4939fb254fe84b7959b03fd688ba8fe0a Mon Sep 17 00:00:00 2001 From: stylianosgakis Date: Thu, 19 Nov 2026 18:38:50 +0100 Subject: [PATCH 6/9] Run the iOS shared code workflow on its own schedule only at weekends, as the umbrella release runs it on weeknights --- .github/workflows/ios-shared.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ios-shared.yml b/.github/workflows/ios-shared.yml index b3d254897e..5da650c868 100644 --- a/.github/workflows/ios-shared.yml +++ b/.github/workflows/ios-shared.yml @@ -2,11 +2,12 @@ name: iOS shared code # Normal PRs run on Linux, which compiles the iOS source sets to klibs but cannot run them. This job runs what only # macOS can: every module's tests on the iOS simulator, the release device framework link, and the checks that the -# test hook stays out of it and the framework stays within its size budget. It runs once a day and as a required step -# of the umbrella release. GitHub emails a failed scheduled run to whoever last changed its schedule. +# test hook stays out of it and the framework stays within its size budget. It runs as a required step of the umbrella +# release on weeknights and on its own schedule at weekends, so once a day. GitHub emails a failed scheduled run to +# whoever last changed its schedule. on: schedule: - - cron: '0 3 * * *' + - cron: '0 3 * * 0,6' workflow_dispatch: workflow_call: From 0f607590ec9b530bfe1c3897b2f6b443773c0783 Mon Sep 17 00:00:00 2001 From: stylianosgakis Date: Thu, 19 Nov 2026 18:38:50 +0100 Subject: [PATCH 7/9] Cache the Kotlin/Native toolchain in the iOS klib job and the iOS shared code workflow --- .github/workflows/ios-shared.yml | 9 +++++++++ .github/workflows/pr.yml | 16 ++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/.github/workflows/ios-shared.yml b/.github/workflows/ios-shared.yml index 5da650c868..d04f4842ad 100644 --- a/.github/workflows/ios-shared.yml +++ b/.github/workflows/ios-shared.yml @@ -33,6 +33,15 @@ jobs: datadog-api-key: ${{ secrets.DATADOG_API_KEY }} lokalise-id: ${{ secrets.LOKALISE_ID }} lokalise-token: ${{ secrets.LOKALISE_TOKEN }} + # setup-gradle does not cache the Kotlin/Native toolchain, which only changes with the Kotlin version. + - name: Read the Kotlin version + id: kotlin + run: echo "version=$(sed -nE 's/^kotlin = "(.*)"/\1/p' gradle/libs.versions.toml)" >> "$GITHUB_OUTPUT" + - name: Cache the Kotlin/Native toolchain + uses: actions/cache@v5 + with: + path: ~/.konan + key: konan-${{ runner.os }}-${{ steps.kotlin.outputs.version }} - name: Tests on the iOS simulator run: ./gradlew iosSimulatorArm64Test checkUmbrellaClasspath - name: Umbrella tests with the test hook in the framework diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index e961ac8079..f42eee194b 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -101,6 +101,22 @@ jobs: datadog-api-key: ${{ secrets.DATADOG_API_KEY }} lokalise-id: ${{ secrets.LOKALISE_ID }} lokalise-token: ${{ secrets.LOKALISE_TOKEN }} + # setup-gradle does not cache the Kotlin/Native toolchain, which only changes with the Kotlin version. + - name: Read the Kotlin version + id: kotlin + run: echo "version=$(sed -nE 's/^kotlin = "(.*)"/\1/p' gradle/libs.versions.toml)" >> "$GITHUB_OUTPUT" + - name: Restore the Kotlin/Native toolchain + if: ${{ github.event_name == 'pull_request' }} + uses: actions/cache/restore@v5 + with: + path: ~/.konan + key: konan-${{ runner.os }}-${{ steps.kotlin.outputs.version }} + - name: Cache the Kotlin/Native toolchain + if: ${{ github.event_name != 'pull_request' }} + uses: actions/cache@v5 + with: + path: ~/.konan + key: konan-${{ runner.os }}-${{ steps.kotlin.outputs.version }} - name: Compile the iOS source sets # Kotlin/Native compiles klibs for iOS on Linux, so a commonMain or nativeMain change that does not compile for # iOS fails here. Linking the framework and running the simulator tests need macOS: ios-shared.yml does that From 72638730f4cdeec815b08e6d9f5fdad8da6c6eb9 Mon Sep 17 00:00:00 2001 From: stylianosgakis Date: Thu, 19 Nov 2026 18:41:51 +0100 Subject: [PATCH 8/9] Test that the real graph's public Apollo client sends no token while a member is logged in --- .../android/umbrella/IosGraphNetworkTest.kt | 2 +- .../hedvig/android/umbrella/IosGraphTest.kt | 30 +++++++++++++++++++ .../android/umbrella/MockedNetworkIosGraph.kt | 4 --- .../com/hedvig/android/umbrella/IosGraph.kt | 9 ++++++ 4 files changed, 40 insertions(+), 5 deletions(-) diff --git a/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/IosGraphNetworkTest.kt b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/IosGraphNetworkTest.kt index 6d9dff6895..365e77c778 100644 --- a/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/IosGraphNetworkTest.kt +++ b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/IosGraphNetworkTest.kt @@ -168,7 +168,7 @@ class IosGraphNetworkTest { } /** Sends the test operation from a background thread, as a read on `Dispatchers.Default` does. */ -private fun ApolloClient.query(fetchPolicy: FetchPolicy = FetchPolicy.NetworkOnly) = runBlocking { +internal fun ApolloClient.query(fetchPolicy: FetchPolicy = FetchPolicy.NetworkOnly) = runBlocking { withContext(Dispatchers.Default) { query(PayingMemberPhoneNumberQuery()).fetchPolicy(fetchPolicy).execute() } diff --git a/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/IosGraphTest.kt b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/IosGraphTest.kt index 096507c045..960c577737 100644 --- a/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/IosGraphTest.kt +++ b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/IosGraphTest.kt @@ -20,6 +20,10 @@ import com.hedvig.android.logger.IosLogcatLogger import com.hedvig.android.logger.LogPriority import com.hedvig.android.logger.LogcatLogger import com.hedvig.android.network.clients.NetworkLogPolicy +import io.ktor.client.HttpClient +import io.ktor.client.plugins.HttpSend +import io.ktor.client.plugins.plugin +import io.ktor.http.HttpHeaders import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test @@ -133,6 +137,19 @@ class IosGraphTest { assertThat(accessors.apolloClient === accessors.publicApolloClient).isFalse() } + @Test + fun `the real public client sends no token while a member is logged in`() { + val accessors = FakeInputs().realHolder().accessors + val memberAuthorizations = accessors.httpClient.authorizationsStoppedBeforeTheNetwork() + val publicAuthorizations = accessors.baseHttpClient.authorizationsStoppedBeforeTheNetwork() + + accessors.apolloClient.query() + accessors.publicApolloClient.query() + + assertThat(memberAuthorizations).containsExactly("Bearer $ACCESS_TOKEN") + assertThat(publicAuthorizations).containsExactly("") + } + @Test fun `the build is read from the bundle and the device and only the flavor comes from Swift`() { val production = IosAppBuildConfig(Flavor.Production) @@ -161,3 +178,16 @@ private class RecordingRumLogger : RumLogger { errors += message } } + +/** + * Records the `Authorization` header of every request [this] sends, "" where there was none, and fails the request + * before it reaches the Darwin engine. The interceptor is the client's last, so it sees the token the client added. + */ +private fun HttpClient.authorizationsStoppedBeforeTheNetwork(): List { + val authorizations = mutableListOf() + plugin(HttpSend).intercept { request -> + authorizations += request.headers[HttpHeaders.Authorization].orEmpty() + throw IllegalStateException("Stopped before the network") + } + return authorizations +} diff --git a/app/umbrella/src/iosTestHook/kotlin/com/hedvig/android/umbrella/MockedNetworkIosGraph.kt b/app/umbrella/src/iosTestHook/kotlin/com/hedvig/android/umbrella/MockedNetworkIosGraph.kt index 9059013d74..2c410c146a 100644 --- a/app/umbrella/src/iosTestHook/kotlin/com/hedvig/android/umbrella/MockedNetworkIosGraph.kt +++ b/app/umbrella/src/iosTestHook/kotlin/com/hedvig/android/umbrella/MockedNetworkIosGraph.kt @@ -37,10 +37,6 @@ import io.ktor.client.engine.mock.MockEngineConfig excludes = [NativeNetworkMetroProviders::class, NetworkMetroProviders::class, NativeDataStoreMetroProviders::class], ) internal interface MockedNetworkIosGraph : IosGraphAccessors { - /** The token-free client every other client is built on. */ - @BaseHttpClient - val baseHttpClient: HttpClient - @Provides fun provideExtraKtorClientConfiguration(): ExtraKtorClientConfiguration = object : ExtraKtorClientConfiguration { override fun configure(config: HttpClientConfig<*>) {} diff --git a/app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/IosGraph.kt b/app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/IosGraph.kt index 6525437fd2..ff4c4d1e87 100644 --- a/app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/IosGraph.kt +++ b/app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/IosGraph.kt @@ -3,6 +3,7 @@ package com.hedvig.android.umbrella import com.apollographql.apollo.ApolloClient import com.hedvig.android.core.buildconstants.AppBuildConfig import com.hedvig.android.core.common.di.AppScope +import com.hedvig.android.core.common.di.BaseHttpClient import com.hedvig.android.core.common.di.PublicApolloClient import com.hedvig.android.core.datastore.DeviceIdFetcher import com.hedvig.android.core.datastore.di.NativeDataStoreMetroProviders @@ -12,6 +13,7 @@ import com.hedvig.android.network.clients.AccessTokenFetcher import com.hedvig.android.network.clients.NetworkLogPolicy import dev.zacsweers.metro.DependencyGraph import dev.zacsweers.metro.Provides +import io.ktor.client.HttpClient /** What tests read from a graph: [IosGraph], or the test graph with a canned HTTP engine. */ internal interface IosGraphAccessors : IosReadsGraph { @@ -20,6 +22,13 @@ internal interface IosGraphAccessors : IosReadsGraph { @PublicApolloClient val publicApolloClient: ApolloClient + /** The member client's HTTP client, which adds the token. */ + val httpClient: HttpClient + + /** The token-free HTTP client the member's is built on. */ + @BaseHttpClient + val baseHttpClient: HttpClient + val networkLogPolicy: NetworkLogPolicy } From 75c8f68cdb90153d6aacd7c49809465b3e9e0c12 Mon Sep 17 00:00:00 2001 From: stylianosgakis Date: Thu, 19 Nov 2026 19:13:22 +0100 Subject: [PATCH 9/9] Pin LogPriority and its nsEnum in the header snapshot The log sink hands Swift a LogPriority, so its declarations are part of the API Swift compiles against. --- .../android/umbrella/HeaderSnapshotTest.kt | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/HeaderSnapshotTest.kt b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/HeaderSnapshotTest.kt index 4441be0989..8f689883e2 100644 --- a/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/HeaderSnapshotTest.kt +++ b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/HeaderSnapshotTest.kt @@ -34,6 +34,7 @@ class HeaderSnapshotTest { "HedvigSharedLanguage", "HedvigSharedNetworkLogPolicy", "HedvigSharedIosLogSink", + "HedvigSharedLogPriority", "HedvigSharedIosLogcatLoggerCompanion", "HedvigSharedReadFailure", "HedvigSharedReadFailureKind", @@ -59,7 +60,7 @@ class HeaderSnapshotTest { "HedvigSharedKotlinThrowable", "HedvigSharedKotlinUnit", "HedvigSharedLanguageCompanion", - "HedvigSharedLogPriority", + "HedvigSharedLogPriorityNSEnum", "HedvigSharedLogcatLogger", "HedvigSharedIosLogcatLogger", "HedvigSharedReadFailureKindNSEnum", @@ -161,6 +162,20 @@ class HeaderSnapshotTest { @protocol HedvigSharedIosLogSink @required - (void)logPriority:(HedvigSharedLogPriority *)priority tag:(NSString * _Nullable)tag message:(NSString *)message __attribute__((swift_name("log(priority:tag:message:)"))); +@interface HedvigSharedLogPriority : HedvigSharedKotlinEnum ++ (instancetype)alloc __attribute__((unavailable)); ++ (instancetype)allocWithZone:(struct _NSZone *)zone __attribute__((unavailable)); +- (instancetype)initWithName:(NSString *)name ordinal:(int32_t)ordinal __attribute__((swift_name("init(name:ordinal:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable)); +@property (readonly) HedvigSharedLogPriorityNSEnum nsEnum; +@property (class, readonly) HedvigSharedLogPriority *verbose __attribute__((swift_name("verbose"))); +@property (class, readonly) HedvigSharedLogPriority *debug __attribute__((swift_name("debug"))); +@property (class, readonly) HedvigSharedLogPriority *info __attribute__((swift_name("info"))); +@property (class, readonly) HedvigSharedLogPriority *warn __attribute__((swift_name("warn"))); +@property (class, readonly) HedvigSharedLogPriority *error __attribute__((swift_name("error"))); +@property (class, readonly) HedvigSharedLogPriority *assert __attribute__((swift_name("assert"))); ++ (HedvigSharedKotlinArray *)values __attribute__((swift_name("values()"))); +@property (class, readonly) NSArray *entries __attribute__((swift_name("entries"))); +- (HedvigSharedLogPriority *)atMostLogPriority:(HedvigSharedLogPriority *)logPriority __attribute__((swift_name("atMost(logPriority:)"))); @interface HedvigSharedIosLogcatLoggerCompanion : HedvigSharedBase + (instancetype)alloc __attribute__((unavailable)); + (instancetype)allocWithZone:(struct _NSZone *)zone __attribute__((unavailable));