diff --git a/.github/workflows/ios-shared.yml b/.github/workflows/ios-shared.yml new file mode 100644 index 0000000000..d04f4842ad --- /dev/null +++ b/.github/workflows/ios-shared.yml @@ -0,0 +1,64 @@ +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 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 * * 0,6' + 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 }} + # 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 + # 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..f42eee194b 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -88,6 +88,40 @@ 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 }} + # 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 + # 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 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 24adfcade6..06392697b9 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 2a5fa249e3..19b91c6d23 100644 --- a/app/umbrella/build.gradle.kts +++ b/app/umbrella/build.gradle.kts @@ -9,20 +9,24 @@ plugins { id("com.rickclephas.kmp.nativecoroutines") } +val iosTestHookInFramework = providers.gradleProperty("hedvig.ios.testHook").orNull.toBoolean() + kotlin { sourceSets.configureEach { languageSettings.optIn("kotlin.experimental.ExperimentalObjCName") } 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,7 +52,38 @@ 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) + 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.kotlinx.serialization.json) + implementation(libs.ktor.client.mock) + implementation(projects.dataConversations) + } + } } } +// 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/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/HeaderSnapshotTest.kt b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/HeaderSnapshotTest.kt new file mode 100644 index 0000000000..8f689883e2 --- /dev/null +++ b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/HeaderSnapshotTest.kt @@ -0,0 +1,295 @@ +@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", + "HedvigSharedLogPriority", + "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", + "HedvigSharedLogPriorityNSEnum", + "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 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)); ++ (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 +} 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..365e77c778 --- /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. */ +internal 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/IosGraphTest.kt b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/IosGraphTest.kt new file mode 100644 index 0000000000..960c577737 --- /dev/null +++ b/app/umbrella/src/iosSimulatorArm64Test/kotlin/com/hedvig/android/umbrella/IosGraphTest.kt @@ -0,0 +1,193 @@ +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 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 + +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 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) + 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 + } +} + +/** + * 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/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/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/MockedNetworkIosGraph.kt b/app/umbrella/src/iosTestHook/kotlin/com/hedvig/android/umbrella/MockedNetworkIosGraph.kt new file mode 100644 index 0000000000..2c410c146a --- /dev/null +++ b/app/umbrella/src/iosTestHook/kotlin/com/hedvig/android/umbrella/MockedNetworkIosGraph.kt @@ -0,0 +1,109 @@ +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 { + @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 + } +} 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) + } +} 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..ff4c4d1e87 --- /dev/null +++ b/app/umbrella/src/nativeMain/kotlin/com/hedvig/android/umbrella/IosGraph.kt @@ -0,0 +1,52 @@ +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 +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 +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 { + val apolloClient: ApolloClient + + @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 +} + +/** + * 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}" } + } +}