diff --git a/app/core/core-build-constants/src/commonMain/kotlin/com/hedvig/android/core/buildconstants/AppBuildConfig.kt b/app/core/core-build-constants/src/commonMain/kotlin/com/hedvig/android/core/buildconstants/AppBuildConfig.kt index 9c13853421..4a05ee1e12 100644 --- a/app/core/core-build-constants/src/commonMain/kotlin/com/hedvig/android/core/buildconstants/AppBuildConfig.kt +++ b/app/core/core-build-constants/src/commonMain/kotlin/com/hedvig/android/core/buildconstants/AppBuildConfig.kt @@ -1,5 +1,10 @@ +@file:OptIn(ExperimentalObjCName::class) + package com.hedvig.android.core.buildconstants +import kotlin.experimental.ExperimentalObjCName +import kotlin.native.ObjCName + interface AppBuildConfig { val debug: Boolean val applicationId: String @@ -23,6 +28,7 @@ interface AppBuildConfig { get() = defaultPlatformName } +@ObjCName(name = "HedvigSharedFlavor", swiftName = "Flavor", exact = true) enum class Flavor { Production, Staging, diff --git a/app/core/core-common-public/src/commonMain/kotlin/com/hedvig/android/core/common/di/Qualifiers.kt b/app/core/core-common-public/src/commonMain/kotlin/com/hedvig/android/core/common/di/Qualifiers.kt index c00a50c008..6fb2d909e1 100644 --- a/app/core/core-common-public/src/commonMain/kotlin/com/hedvig/android/core/common/di/Qualifiers.kt +++ b/app/core/core-common-public/src/commonMain/kotlin/com/hedvig/android/core/common/di/Qualifiers.kt @@ -17,6 +17,11 @@ annotation class IoDispatcher @Retention(AnnotationRetention.RUNTIME) annotation class BaseHttpClient +/** Apollo client that never sends an access token, for requests made before login. */ +@Qualifier +@Retention(AnnotationRetention.RUNTIME) +annotation class PublicApolloClient + /** Ktor engine for the auth client, carrying the app's network observability hooks. */ @Qualifier @Retention(AnnotationRetention.RUNTIME) diff --git a/app/core/core-datastore-public/src/commonMain/kotlin/com/hedvig/android/core/datastore/DeviceIdFetcher.kt b/app/core/core-datastore-public/src/commonMain/kotlin/com/hedvig/android/core/datastore/DeviceIdFetcher.kt index 26b331ab10..ac1e1e6c1c 100644 --- a/app/core/core-datastore-public/src/commonMain/kotlin/com/hedvig/android/core/datastore/DeviceIdFetcher.kt +++ b/app/core/core-datastore-public/src/commonMain/kotlin/com/hedvig/android/core/datastore/DeviceIdFetcher.kt @@ -1,9 +1,18 @@ +@file:OptIn(ExperimentalObjCName::class) + package com.hedvig.android.core.datastore +import kotlin.experimental.ExperimentalObjCName +import kotlin.native.ObjCName + /** * Fetch the unique ID which identifies this device across logins but not across new app installations. - * Wraps [DeviceIdDataStore] for Android/Jvm but delegates to an iOS implementation for the native target + * Wraps [DeviceIdDataStore] for Android/Jvm but delegates to an iOS implementation for the native target. + * + * Kotlin calls [fetch] from any thread, usually a background one. An iOS implementation must complete it exactly once: + * Kotlin cannot cancel it, so one that never completes holds its caller until that caller's own time limit. */ +@ObjCName(name = "HedvigSharedDeviceIdFetcher", swiftName = "DeviceIdFetcher", exact = true) interface DeviceIdFetcher { suspend fun fetch(): String? } diff --git a/app/core/ios-data-bridge/build.gradle.kts b/app/core/ios-data-bridge/build.gradle.kts new file mode 100644 index 0000000000..302600d9ee --- /dev/null +++ b/app/core/ios-data-bridge/build.gradle.kts @@ -0,0 +1,24 @@ +plugins { + id("hedvig.multiplatform.library.ios") + id("hedvig.gradle.plugin") +} + +kotlin { + sourceSets { + commonMain.dependencies { + implementation(libs.apollo.api) + implementation(libs.apollo.runtime) + implementation(libs.atomicfu) + implementation(libs.coroutines.core) + implementation(projects.coreCommonPublic) + implementation(projects.loggingPublic) + } + commonTest.dependencies { + implementation(libs.assertK) + implementation(libs.kotlin.test) + } + nativeMain.dependencies { + implementation(libs.kmpNativeCoroutines.core) + } + } +} diff --git a/app/core/ios-data-bridge/src/commonMain/kotlin/com/hedvig/android/iosdata/bridge/ReadFailure.kt b/app/core/ios-data-bridge/src/commonMain/kotlin/com/hedvig/android/iosdata/bridge/ReadFailure.kt new file mode 100644 index 0000000000..fa7af8fdd7 --- /dev/null +++ b/app/core/ios-data-bridge/src/commonMain/kotlin/com/hedvig/android/iosdata/bridge/ReadFailure.kt @@ -0,0 +1,80 @@ +@file:OptIn(ExperimentalObjCRefinement::class, ExperimentalObjCEnum::class) + +package com.hedvig.android.iosdata.bridge + +import com.apollographql.apollo.exception.ApolloHttpException +import com.apollographql.apollo.exception.ApolloNetworkException +import com.hedvig.android.core.common.ErrorMessage +import kotlin.experimental.ExperimentalObjCEnum +import kotlin.experimental.ExperimentalObjCRefinement +import kotlin.native.HiddenFromObjC +import kotlin.native.ObjCEnum + +/** + * Why a read made through [SessionReads] failed. Every failure of such a read arrives as one of these, a Kotlin bug + * included. It carries no member data and no exception text, so the iOS app may log every field. + */ +class ReadFailure internal constructor( + val kind: ReadFailureKind, + val reason: ReadFailureReason, + /** The read's name, such as `insurances.contracts`. */ + val readName: String, + /** The GraphQL operation the read sends, such as `InsuranceContracts`. */ + val operationName: String, +) : Exception(kind.name) { + internal fun within(readName: String, operationName: String) = ReadFailure(kind, reason, readName, operationName) + + override fun toString(): String = "ReadFailure($kind, $reason, $readName, $operationName)" +} + +/** What the caller can do about a [ReadFailure]. */ +@ObjCEnum +enum class ReadFailureKind { + /** The read failed and may be retried. */ + GENERAL, + + /** + * A login or logout ended the session the read ran in while the caller was still waiting. The caller's own cancel + * never arrives as a failure. + */ + SESSION_ENDED, +} + +/** What went wrong, for logs. */ +@ObjCEnum +enum class ReadFailureReason { + /** The backend answered with GraphQL errors. */ + GRAPHQL_ERRORS, + + /** No answer arrived. */ + NETWORK, + + /** The backend answered with an HTTP error status. */ + HTTP, + + /** The caller waited as long as a read may take. */ + TIMEOUT, + + /** The same read is still waiting on an iOS app input, so this one was refused at once. */ + STUCK, + + /** A login or logout ended the read's session. */ + SESSION_ENDED, + + /** Anything else, a Kotlin bug included. */ + UNEXPECTED, +} + +/** The failure a read raises when its data could not be loaded; [error] decides the reason. */ +@HiddenFromObjC +fun generalReadFailure(error: ErrorMessage? = null): ReadFailure = + ReadFailure(ReadFailureKind.GENERAL, reasonOf(error), "", "") + +internal fun failure(kind: ReadFailureKind, reason: ReadFailureReason) = ReadFailure(kind, reason, "", "") + +private fun reasonOf(error: ErrorMessage?): ReadFailureReason = when (val throwable = error?.throwable) { + null -> if (error == null) ReadFailureReason.UNEXPECTED else ReadFailureReason.GRAPHQL_ERRORS + is ApolloNetworkException -> ReadFailureReason.NETWORK + is ApolloHttpException -> ReadFailureReason.HTTP + else -> ReadFailureReason.UNEXPECTED +} diff --git a/app/core/ios-data-bridge/src/commonMain/kotlin/com/hedvig/android/iosdata/bridge/ReadSessions.kt b/app/core/ios-data-bridge/src/commonMain/kotlin/com/hedvig/android/iosdata/bridge/ReadSessions.kt new file mode 100644 index 0000000000..3c99a6677e --- /dev/null +++ b/app/core/ios-data-bridge/src/commonMain/kotlin/com/hedvig/android/iosdata/bridge/ReadSessions.kt @@ -0,0 +1,175 @@ +@file:OptIn(ExperimentalAtomicApi::class, ExperimentalObjCRefinement::class) + +package com.hedvig.android.iosdata.bridge + +import com.apollographql.apollo.ApolloClient +import com.hedvig.android.logger.LogPriority +import com.hedvig.android.logger.logcat +import kotlin.concurrent.atomics.AtomicReference +import kotlin.concurrent.atomics.ExperimentalAtomicApi +import kotlin.coroutines.cancellation.CancellationException +import kotlin.experimental.ExperimentalObjCRefinement +import kotlin.native.HiddenFromObjC +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.CompletableJob +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.selects.select + +/** What a member read may use: the client that sends the member's token. */ +@HiddenFromObjC +class MemberReadScope internal constructor(val apolloClient: ApolloClient) + +/** What a logged-out read may use: the client that never sends a token and never asks for one. */ +@HiddenFromObjC +class PublicReadScope internal constructor(val apolloClient: ApolloClient) + +/** + * The suspend core of every read the iOS app makes, the same for every feature: + * - Every failure is a [ReadFailure]; the caller's own cancel stays a cancel. + * - A caller waits at most [readTimeout], also when an iOS app input (the token or device id fetch) never answers, + * then fails as `TIMEOUT`. While a read is stuck in such an input, which Kotlin's cancel cannot reach, the same read + * (name, arguments and session) fails at once as `STUCK` instead of starting another, so at most one coroutine per + * read and session is stuck. + * - Equal reads in flight are joined. + * - Failures are logged with the read's name and the failure kind and reason only. + * + * A member read ([read]) gets only the member client and belongs to the session it started in: [sessionChanged] ends + * it as `SESSION_ENDED`. A logged-out read ([publicRead]) gets only the token-free client, belongs to no session and is + * never ended by one. + */ +internal class ReadSessions( + private val member: MemberReadScope, + private val public: PublicReadScope, +) { + private class Session(val number: Long, val job: CompletableJob) { + val scope: CoroutineScope = CoroutineScope(job + Dispatchers.Default) + } + + private data class ReadKey(val name: String, val arguments: List, val session: Long) + + private val current = AtomicReference(Session(0, SupervisorJob())) + private val flights = SingleFlight( + stillCurrent = { it.session == NO_SESSION || it.session == current.load().number }, + ) + + /** Where logged-out reads run; nothing cancels it. */ + private val publicScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + /** How long a caller waits for a read. */ + var readTimeout: Duration = 60.seconds + + /** The member read [block] in the session current at this call. See [SessionReads.read] for the parameters. */ + suspend fun read( + name: String, + arguments: List, + operation: String, + block: suspend MemberReadScope.() -> T, + ): T { + val session = current.load() + return failingAsReadFailure(name, operation, session.job) { + untilSessionEnds(session.job) { + @Suppress("UNCHECKED_CAST") + flights.await(ReadKey(name, arguments, session.number), session.scope, readTimeout) { member.block() } as T + } + } + } + + /** The logged-out read [block]. See [SessionReads.publicRead] for the parameters. */ + suspend fun publicRead( + name: String, + arguments: List, + operation: String, + block: suspend PublicReadScope.() -> T, + ): T = failingAsReadFailure(name, operation, session = null) { + @Suppress("UNCHECKED_CAST") + flights.await(ReadKey(name, arguments, NO_SESSION), publicScope, readTimeout) { public.block() } as T + } + + /** How many reads are stuck in an iOS app input now. */ + fun stuckReads(): Int = flights.stuckCount() + + /** How many callers wait on reads in flight now. */ + fun waitingCallers(): Int = flights.waiterCount() + + /** Ends the member reads in flight, synchronously, so no read started after this call runs in the previous session. */ + fun sessionChanged() { + while (true) { + val old = current.load() + val new = Session(old.number + 1, SupervisorJob()) + if (current.compareAndSet(old, new)) { + old.job.cancel() + flights.forgetStuck { it.session != NO_SESSION && it.session != new.number } + return + } + } + } +} + +/** The session number of a logged-out read. Member sessions count up from 0. */ +private const val NO_SESSION = -1L + +/** + * Runs [block] until it ends or [session] is cancelled, whichever is first; a session that ends first is + * `SESSION_ENDED` at once, also when [block] waits on a call stuck in an iOS app input, which never completes. + */ +private suspend fun untilSessionEnds(session: Job, block: suspend () -> T): T = coroutineScope { + // A child of the session, without children of its own, ends the moment the session is cancelled. + val sessionWatch = Job(session) + try { + val work = async { block() } + select { + work.onAwait { it } + sessionWatch.onJoin { + work.cancel() + throw failure(ReadFailureKind.SESSION_ENDED, ReadFailureReason.SESSION_ENDED) + } + } + } finally { + sessionWatch.complete() + } +} + +/** + * Runs [block], turning anything it throws into a [ReadFailure]. Only the caller's cancel ends it as cancelled; the end + * of [session] is `SESSION_ENDED`, and any other cancellation raised inside the read is a general failure. + */ +private suspend fun failingAsReadFailure( + name: String, + operation: String, + session: Job?, + block: suspend () -> T, +): T = try { + block() +} catch (e: CancellationException) { + currentCoroutineContext().ensureActive() + if (session != null && session.isCancelled) { + logcat(LogPriority.INFO) { "Read $name ended with its session" } + throw failure(ReadFailureKind.SESSION_ENDED, ReadFailureReason.SESSION_ENDED).within(name, operation) + } + logcat(LogPriority.ERROR) { "Read $name raised a cancellation nobody asked for" } + throw failure(ReadFailureKind.GENERAL, ReadFailureReason.UNEXPECTED).within(name, operation) +} catch (e: ReadFailure) { + currentCoroutineContext().ensureActive() + logcat(LogPriority.WARN) { "Read $name failed: ${e.kind} ${e.reason}" } + throw e.within(name, operation) +} catch (e: CallStuck) { + currentCoroutineContext().ensureActive() + logcat(LogPriority.WARN) { "Read $name refused: the same read is stuck waiting on an iOS app input" } + throw failure(ReadFailureKind.GENERAL, ReadFailureReason.STUCK).within(name, operation) +} catch (e: CallTimedOut) { + currentCoroutineContext().ensureActive() + logcat(LogPriority.WARN) { "Read $name timed out" } + throw failure(ReadFailureKind.GENERAL, ReadFailureReason.TIMEOUT).within(name, operation) +} catch (e: Throwable) { + currentCoroutineContext().ensureActive() + logcat(LogPriority.ERROR) { "Read $name failed unexpectedly: ${e::class.simpleName}" } + throw failure(ReadFailureKind.GENERAL, ReadFailureReason.UNEXPECTED).within(name, operation) +} diff --git a/app/core/ios-data-bridge/src/commonMain/kotlin/com/hedvig/android/iosdata/bridge/SingleFlight.kt b/app/core/ios-data-bridge/src/commonMain/kotlin/com/hedvig/android/iosdata/bridge/SingleFlight.kt new file mode 100644 index 0000000000..f1c538cc14 --- /dev/null +++ b/app/core/ios-data-bridge/src/commonMain/kotlin/com/hedvig/android/iosdata/bridge/SingleFlight.kt @@ -0,0 +1,113 @@ +package com.hedvig.android.iosdata.bridge + +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds +import kotlinx.atomicfu.locks.reentrantLock +import kotlinx.atomicfu.locks.withLock +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.async +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull + +/** + * At most one call per key at a time: a call with the key of one in flight waits for that one. The call is cancelled + * when its last waiter leaves, by its own cancel or by its timeout; a waiter's timeout throws [CallTimedOut]. A call that + * does not end on that cancel, because it is suspended in a Swift-implemented suspend function, which Kotlin's cancel + * does not reach, keeps its key as stuck: until it ends, a caller of that key gets [CallStuck] at once instead of + * starting another call that could stick too. So at most one coroutine per key is ever stuck. + * + * The lock is recursive because a call of a cancelled scope completes, and runs its completion handler, inside [await]. + */ +internal class SingleFlight( + /** Whether a key is still worth keeping as stuck; a key that is not is never marked stuck. */ + private val stillCurrent: (K) -> Boolean = { true }, +) { + private val lock = reentrantLock() + private val inFlight = mutableMapOf>() + private val stuck = mutableSetOf() + + private class Entry(val call: Deferred) { + var waiters = 0 + } + + suspend fun await(key: K, scope: CoroutineScope, timeout: Duration, block: suspend () -> V): V { + val entry = locked { + // A finished call's completion handler can run after its waiters already saw the result, so drop it here too; + // joining it would hand this caller that old result or failure instead of running the call again. + if (inFlight[key]?.call?.isCompleted == true) { + inFlight.remove(key) + stuck.remove(key) + } + if (key in stuck) throw CallStuck() + val entry = inFlight[key] ?: Entry(scope.async(start = CoroutineStart.LAZY) { block() }).also { entry -> + inFlight[key] = entry + entry.call.invokeOnCompletion { + locked { + if (inFlight[key] === entry) { + inFlight.remove(key) + stuck.remove(key) + } + } + } + entry.call.start() + } + entry.waiters++ + entry + } + var left = false + try { + return awaitWithin(entry.call, timeout) { + left = true + leave(key, entry) + } + } finally { + if (!left) withContext(NonCancellable) { leave(key, entry) } + } + } + + /** Forgets the stuck keys [predicate] matches; their coroutines stay suspended where Swift left them. */ + fun forgetStuck(predicate: (K) -> Boolean) { + locked { stuck.removeAll(predicate) } + } + + /** How many keys are stuck now. */ + fun stuckCount(): Int = locked { stuck.size } + + /** How many callers wait on calls in flight now. */ + fun waiterCount(): Int = locked { inFlight.values.sumOf { it.waiters } } + + /** One waiter left; the last one cancels the call, which counts as stuck if it does not end within a moment. */ + private suspend fun leave(key: K, entry: Entry) { + val last = locked { --entry.waiters == 0 && !entry.call.isCompleted } + if (!last) return + entry.call.cancel() + withTimeoutOrNull(CANCEL_GRACE) { entry.call.join() } + locked { + if (inFlight[key] === entry && !entry.call.isCompleted && entry.waiters == 0 && stillCurrent(key)) stuck += key + } + } + + private inline fun locked(block: () -> T): T = lock.withLock(block) +} + +/** How long a cancelled call may take to end before it counts as stuck. */ +private val CANCEL_GRACE = 200.milliseconds + +/** A caller stopped waiting after its timeout; the work may still be running. Not a cancellation. */ +internal open class CallTimedOut(message: String = "The call did not finish in time") : Exception(message) + +/** A caller was refused at once because an equal call is stuck waiting on a Swift input. */ +internal class CallStuck : CallTimedOut("An equal call is stuck") + +/** Waits for [call] at most [timeout]; on timeout runs [onTimeout] and throws [CallTimedOut]. */ +private suspend fun awaitWithin(call: Deferred, timeout: Duration, onTimeout: suspend () -> Unit): T { + val result = withTimeoutOrNull(timeout) { Result.success(call.await()) } + if (result == null) { + onTimeout() + throw CallTimedOut() + } + return result.getOrThrow() +} diff --git a/app/core/ios-data-bridge/src/commonTest/kotlin/com/hedvig/android/iosdata/bridge/ReadSessionsTest.kt b/app/core/ios-data-bridge/src/commonTest/kotlin/com/hedvig/android/iosdata/bridge/ReadSessionsTest.kt new file mode 100644 index 0000000000..b718183d6e --- /dev/null +++ b/app/core/ios-data-bridge/src/commonTest/kotlin/com/hedvig/android/iosdata/bridge/ReadSessionsTest.kt @@ -0,0 +1,369 @@ +@file:OptIn(ExperimentalAtomicApi::class) + +package com.hedvig.android.iosdata.bridge + +import assertk.assertFailure +import assertk.assertThat +import assertk.assertions.containsExactly +import assertk.assertions.isEqualTo +import assertk.assertions.isInstanceOf +import assertk.assertions.isSameInstanceAs +import assertk.assertions.isTrue +import com.apollographql.apollo.ApolloClient +import com.hedvig.android.logger.LogPriority +import com.hedvig.android.logger.LogcatLogger +import kotlin.concurrent.atomics.AtomicInt +import kotlin.concurrent.atomics.ExperimentalAtomicApi +import kotlin.concurrent.atomics.incrementAndFetch +import kotlin.coroutines.cancellation.CancellationException +import kotlin.coroutines.suspendCoroutine +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds +import kotlin.time.TimeSource +import kotlinx.atomicfu.locks.reentrantLock +import kotlinx.atomicfu.locks.withLock +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout + +/** The read contract on its own, on every platform: no Swift, no `NativeSuspend`. */ +class ReadSessionsTest { + private val logs = CapturingLogger() + private val memberClient = ApolloClient.Builder().serverUrl("https://member.test").build() + private val publicClient = ApolloClient.Builder().serverUrl("https://public.test").build() + private val reads = ReadSessions(MemberReadScope(memberClient), PublicReadScope(publicClient)) + private val callers = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + @BeforeTest + fun install() { + LogcatLogger.install(logs) + } + + @AfterTest + fun uninstall() { + LogcatLogger.uninstall() + memberClient.close() + publicClient.close() + } + + private fun start(block: suspend () -> T): Deferred = callers.async { block() } + + private fun member(name: String, vararg arguments: Any?, block: suspend MemberReadScope.() -> T): T = + runBlocking { withTimeout(WAIT) { reads.read(name, arguments.toList(), "TestOperation", block) } } + + private fun public(name: String, vararg arguments: Any?, block: suspend PublicReadScope.() -> T): T = + runBlocking { withTimeout(WAIT) { reads.publicRead(name, arguments.toList(), "PublicOperation", block) } } + + private fun failureOf(block: () -> Any?): ReadFailure { + try { + block() + } catch (e: ReadFailure) { + return e + } + error("The read did not fail") + } + + @Test + fun `a member read gets the member client and a logged-out read the public one`() { + assertThat(member("test.clients") { apolloClient }).isSameInstanceAs(memberClient) + assertThat(public("test.clients") { apolloClient }).isSameInstanceAs(publicClient) + } + + @Test + fun `a read failure arrives as a general failure whose message is its kind`() { + val failure = failureOf { member("test.failure") { throw generalReadFailure() } } + + assertThat(failure.kind).isEqualTo(ReadFailureKind.GENERAL) + assertThat(failure.message).isEqualTo("GENERAL") + } + + @Test + fun `any other exception arrives as a general failure without its text`() { + val failure = failureOf { member("test.bug") { throw IllegalStateException("member-sentinel-91c2") } } + + assertThat(failure.kind).isEqualTo(ReadFailureKind.GENERAL) + assertThat(failure.message).isEqualTo("GENERAL") + assertThat(logs.messages().none { "member-sentinel-91c2" in it }).isTrue() + } + + @Test + fun `a failure is logged with the read name and the kind only`() { + failureOf { member("test.logged") { throw IllegalStateException("member-sentinel-3e1f") } } + failureOf { member("test.kind") { throw generalReadFailure() } } + + assertThat(logs.entries()).containsExactly( + LogPriority.ERROR to "Read test.logged failed unexpectedly: IllegalStateException", + LogPriority.WARN to "Read test.kind failed: GENERAL UNEXPECTED", + ) + } + + @Test + fun `a failure carries the read and the operation and the reason for the iOS app to log`() { + reads.readTimeout = 200.milliseconds + + val failed = failureOf { member("test.telemetry") { throw generalReadFailure() } } + val timedOut = failureOf { member("test.slow") { awaitCancellation() } } + + assertThat(listOf(failed.kind, failed.reason, failed.readName, failed.operationName)) + .containsExactly(ReadFailureKind.GENERAL, ReadFailureReason.UNEXPECTED, "test.telemetry", "TestOperation") + assertThat(timedOut.reason).isEqualTo(ReadFailureReason.TIMEOUT) + } + + @Test + fun `a cancellation raised inside a read nobody cancelled is a general failure`() { + val failure = failureOf { member("test.inner") { throw CancellationException("inner") } } + + assertThat(failure.kind).isEqualTo(ReadFailureKind.GENERAL) + } + + @Test + fun `the caller's own cancel stays a cancel and is no failure`() = runBlocking { + val started = CompletableDeferred() + val caller = start { + reads.read("test.cancel", emptyList(), "TestOperation") { + started.complete(Unit) + awaitCancellation() + } + } + started.await() + + caller.cancel() + + assertFailure { caller.await() }.isInstanceOf(CancellationException::class) + assertThat(logs.messages().none { "test.cancel" in it }).isTrue() + } + + @Test + fun `a read stuck in an iOS app input makes the same read fail at once until it ends but no other read`() { + reads.readTimeout = 200.milliseconds + val calls = AtomicInt(0) + + val stuck = failureOf { + member("test.stuck") { + calls.incrementAndFetch() + suspendCoroutine { } + } + } + val mark = TimeSource.Monotonic.markNow() + val again = failureOf { + member("test.stuck") { + calls.incrementAndFetch() + 1 + } + } + val againTook = mark.elapsedNow() + val other = member("test.stuck", "other-argument") { 2 } + + assertThat(stuck.reason).isEqualTo(ReadFailureReason.TIMEOUT) + assertThat(again.reason).isEqualTo(ReadFailureReason.STUCK) + assertThat(againTook < 150.milliseconds).isTrue() + assertThat(calls.load()).isEqualTo(1) + assertThat(other).isEqualTo(2) + } + + @Test + fun `a read refused because it is stuck logs that it is stuck and not that it timed out`() { + reads.readTimeout = 200.milliseconds + + failureOf { member("test.stucklog") { suspendCoroutine { } } } + failureOf { member("test.stucklog") { 1 } } + + assertThat(logs.entries()).containsExactly( + LogPriority.WARN to "Read test.stucklog timed out", + LogPriority.WARN to "Read test.stucklog refused: the same read is stuck waiting on an iOS app input", + ) + } + + @Test + fun `a session change ends a member read in flight as a session ended failure`() = runBlocking { + val started = CompletableDeferred() + val caller = start { + runCatching { + reads.read("test.session", emptyList(), "TestOperation") { + started.complete(Unit) + awaitCancellation() + } + } + } + started.await() + + reads.sessionChanged() + + val failure = withTimeout(WAIT) { caller.await() }.exceptionOrNull() as ReadFailure + assertThat(failure.kind).isEqualTo(ReadFailureKind.SESSION_ENDED) + } + + @Test + fun `a session change ends a read stuck in an iOS app input at once and its key is not stuck`() = runBlocking { + reads.readTimeout = 60.seconds + val started = CompletableDeferred() + val caller = start { + runCatching { + reads.read("test.stuckend", emptyList(), "TestOperation") { + started.complete(Unit) + suspendCoroutine { } + } + } + } + started.await() + val mark = TimeSource.Monotonic.markNow() + + reads.sessionChanged() + + val failure = withTimeout(WAIT) { caller.await() }.exceptionOrNull() as ReadFailure + assertThat(mark.elapsedNow() < 2.seconds).isTrue() + assertThat(failure.kind).isEqualTo(ReadFailureKind.SESSION_ENDED) + assertThat(reads.stuckReads()).isEqualTo(0) + assertThat(member("test.stuckend") { 1 }).isEqualTo(1) + } + + @Test + fun `a session change forgets the stuck reads of the old session`() { + reads.readTimeout = 200.milliseconds + failureOf { member("test.forget") { suspendCoroutine { } } } + assertThat(reads.stuckReads()).isEqualTo(1) + + reads.sessionChanged() + + assertThat(reads.stuckReads()).isEqualTo(0) + } + + @Test + fun `a read started right after a session change runs in the new session`() = runBlocking { + val oldSession = CompletableDeferred() + start { + runCatching { + reads.read("test.joined", emptyList(), "TestOperation") { + oldSession.complete(Unit) + suspendCoroutine { } + } + } + } + oldSession.await() + + reads.sessionChanged() + + assertThat(member("test.joined") { 3 }).isEqualTo(3) + } + + @Test + fun `equal reads in flight are joined`() = runBlocking { + val gate = CompletableDeferred() + val runs = AtomicInt(0) + val read: suspend () -> Int = { + reads.read("test.join", emptyList(), "TestOperation") { + runs.incrementAndFetch() + gate.await() + } + } + val first = start(read) + val second = start(read) + waitUntil { reads.waitingCallers() == 2 } + gate.complete(5) + + assertThat(listOf(first.await(), second.await())).containsExactly(5, 5) + assertThat(runs.load()).isEqualTo(1) + } + + @Test + fun `reads with several arguments are joined only when every argument is equal`() = runBlocking { + val gate = CompletableDeferred() + val runs = AtomicInt(0) + + fun read(a: String, b: Int) = start { + reads.read("test.args", listOf(a, b), "TestOperation") { + runs.incrementAndFetch() + gate.await() + "$a-$b" + } + } + val first = read("x", 1) + val sameAgain = read("x", 1) + val otherSecond = read("x", 2) + // All three callers wait before the gate opens, so the second "x-1" can only join the first. + waitUntil { reads.waitingCallers() == 3 } + gate.complete(Unit) + + assertThat(listOf(first.await(), sameAgain.await(), otherSecond.await())).containsExactly("x-1", "x-1", "x-2") + assertThat(runs.load()).isEqualTo(2) + } + + @Test + fun `a logged-out read is not ended by a session change`() = runBlocking { + val started = CompletableDeferred() + val gate = CompletableDeferred() + val caller = start { + reads.publicRead("test.public", emptyList(), "PublicOperation") { + started.complete(Unit) + gate.await() + } + } + started.await() + + reads.sessionChanged() + gate.complete(9) + + assertThat(withTimeout(WAIT) { caller.await() }).isEqualTo(9) + } + + @Test + fun `a logged-out read stuck in an iOS app input is bounded and stays refused across a session change`() { + reads.readTimeout = 200.milliseconds + + val stuck = failureOf { public("test.publicstuck") { suspendCoroutine { } } } + reads.sessionChanged() + val again = failureOf { public("test.publicstuck") { 1 } } + val memberRead = member("test.publicstuck") { 2 } + + assertThat(stuck.reason).isEqualTo(ReadFailureReason.TIMEOUT) + assertThat(again.reason).isEqualTo(ReadFailureReason.STUCK) + assertThat(memberRead).isEqualTo(2) + } + + @Test + fun `a logged-out read fails like a member read with its name and operation`() { + val failed = failureOf { public("test.publicfail") { throw generalReadFailure() } } + + assertThat(listOf(failed.kind, failed.readName, failed.operationName)) + .containsExactly(ReadFailureKind.GENERAL, "test.publicfail", "PublicOperation") + } + + private companion object { + val WAIT: Duration = 5.seconds + } +} + +internal fun waitUntil(timeout: Duration = 5.seconds, condition: () -> Boolean) { + val mark = TimeSource.Monotonic.markNow() + runBlocking { + while (!condition()) { + check(mark.elapsedNow() < timeout) { "Condition not met within $timeout" } + delay(5.milliseconds) + } + } +} + +internal class CapturingLogger : LogcatLogger { + private val lock = reentrantLock() + private val captured = mutableListOf>() + + fun entries(): List> = lock.withLock { captured.toList() } + + fun messages(): List = entries().map { it.second } + + override fun log(priority: LogPriority, throwable: Throwable?, tag: String?, message: () -> String) { + val text = message() + lock.withLock { captured += priority to text } + } +} diff --git a/app/core/ios-data-bridge/src/commonTest/kotlin/com/hedvig/android/iosdata/bridge/SingleFlightTest.kt b/app/core/ios-data-bridge/src/commonTest/kotlin/com/hedvig/android/iosdata/bridge/SingleFlightTest.kt new file mode 100644 index 0000000000..91bc401ca9 --- /dev/null +++ b/app/core/ios-data-bridge/src/commonTest/kotlin/com/hedvig/android/iosdata/bridge/SingleFlightTest.kt @@ -0,0 +1,175 @@ +@file:OptIn(ExperimentalAtomicApi::class) + +package com.hedvig.android.iosdata.bridge + +import assertk.assertFailure +import assertk.assertThat +import assertk.assertions.isEqualTo +import assertk.assertions.isFalse +import assertk.assertions.isInstanceOf +import assertk.assertions.isTrue +import kotlin.concurrent.atomics.AtomicInt +import kotlin.concurrent.atomics.ExperimentalAtomicApi +import kotlin.concurrent.atomics.incrementAndFetch +import kotlin.coroutines.suspendCoroutine +import kotlin.test.Test +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.cancel +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout + +/** + * A block that never resumes and ignores cancellation is what a Swift-implemented suspend function that never calls + * back looks like from Kotlin (`kit/swift-suspend-cancel-probe/RESULT.txt`): `suspendCoroutine` without a resume. + */ +private suspend fun neverResumesIgnoringCancel(): Int = suspendCoroutine { } + +class SingleFlightTest { + private val scope = CoroutineScope(SupervisorJob()) + + @Test + fun `an equal call while one is in flight joins it`() = runBlocking { + val flight = SingleFlight() + val gate = CompletableDeferred() + val runs = AtomicInt(0) + + val first = scope.async { + flight.await("key", scope, 1.minutes) { + runs.incrementAndFetch() + gate.await() + } + } + val second = scope.async { + flight.await("key", scope, 1.minutes) { + runs.incrementAndFetch() + gate.await() + } + } + // Both callers wait before the gate opens, so the second can only join the first. + waitUntil { flight.waiterCount() == 2 } + gate.complete(7) + + assertThat(first.await()).isEqualTo(7) + assertThat(second.await()).isEqualTo(7) + assertThat(runs.load()).isEqualTo(1) + } + + @Test + fun `a call after a finished one runs again`() = runBlocking { + val flight = SingleFlight() + var runs = 0 + flight.await("key", scope, 1.minutes) { ++runs } + flight.await("key", scope, 1.minutes) { ++runs } + + assertThat(runs).isEqualTo(2) + } + + @Test + fun `a failure reaches the caller and the next call runs again`() = runBlocking { + val flight = SingleFlight() + assertFailure { flight.await("key", scope, 1.minutes) { error("boom") } } + + assertThat(flight.await("key", scope, 1.minutes) { 3 }).isEqualTo(3) + } + + @Test + fun `a call that never resumes holds its key as stuck and later callers fail at once without a new call`() = + runBlocking { + val flight = SingleFlight() + val runs = AtomicInt(0) + + assertFailure { + flight.await("key", scope, 50.milliseconds) { + runs.incrementAndFetch() + neverResumesIgnoringCancel() + } + } + .isInstanceOf(CallTimedOut::class) + val start = kotlin.time.TimeSource.Monotonic.markNow() + assertFailure { + flight.await("key", scope, 1.minutes) { + runs.incrementAndFetch() + 5 + } + }.isInstanceOf(CallStuck::class) + + assertThat(start.elapsedNow() < 1.seconds).isTrue() + assertThat(runs.load()).isEqualTo(1) + assertThat(flight.await("other", scope, 1.minutes) { 6 }).isEqualTo(6) + } + + @Test + fun `a call that ends on the cancel frees its key at its timeout`() = runBlocking { + val flight = SingleFlight() + + assertFailure { + flight.await("key", scope, 50.milliseconds) { awaitCancellation() } + }.isInstanceOf(CallTimedOut::class) + assertThat(flight.await("key", scope, 1.minutes) { 5 }).isEqualTo(5) + } + + @Test + fun `a stuck call that finally resumes frees its key`() = runBlocking { + val flight = SingleFlight() + val parked = CompletableDeferred>() + + assertFailure { + flight.await("key", scope, 50.milliseconds) { kotlin.coroutines.suspendCoroutine { parked.complete(it) } } + }.isInstanceOf(CallTimedOut::class) + parked.await().resumeWith(Result.success(1)) + kotlinx.coroutines.delay(50) + + assertThat(flight.await("key", scope, 1.minutes) { 7 }).isEqualTo(7) + } + + @Test + fun `a waiter that joined a stuck call times out too`() = runBlocking { + val flight = SingleFlight() + val first = scope.async { runCatching { flight.await("key", scope, 1.minutes) { neverResumesIgnoringCancel() } } } + kotlinx.coroutines.delay(50) + + assertFailure { flight.await("key", scope, 50.milliseconds) { 1 } }.isInstanceOf(CallTimedOut::class) + first.cancelAndJoin() + } + + @Test + fun `a call in a scope that is already cancelled fails without blocking the next one`() = runBlocking { + val flight = SingleFlight() + val cancelled = CoroutineScope(Job()).apply { cancel() } + + assertFailure { flight.await("key", cancelled, 1.minutes) { 1 } } + assertThat(flight.await("key", scope, 1.minutes) { 2 }).isEqualTo(2) + } + + @Test + fun `the call is cancelled when its last waiter leaves and not before`() = runBlocking { + val flight = SingleFlight() + val cancelled = CompletableDeferred() + val block: suspend () -> Int = { + try { + awaitCancellation() + } finally { + cancelled.complete(Unit) + } + } + val first = scope.async { flight.await("key", scope, 1.minutes, block) } + kotlinx.coroutines.delay(20) + val second = scope.async { flight.await("key", scope, 1.minutes, block) } + kotlinx.coroutines.delay(20) + + first.cancel() + kotlinx.coroutines.delay(50) + assertThat(cancelled.isCompleted).isFalse() + second.cancel() + assertThat(withTimeout(5_000) { cancelled.await() }).isEqualTo(Unit) + } +} diff --git a/app/core/ios-data-bridge/src/nativeMain/kotlin/com/hedvig/android/iosdata/bridge/IosGraphHolder.kt b/app/core/ios-data-bridge/src/nativeMain/kotlin/com/hedvig/android/iosdata/bridge/IosGraphHolder.kt new file mode 100644 index 0000000000..a494f080db --- /dev/null +++ b/app/core/ios-data-bridge/src/nativeMain/kotlin/com/hedvig/android/iosdata/bridge/IosGraphHolder.kt @@ -0,0 +1,66 @@ +@file:OptIn(ExperimentalObjCRefinement::class) + +package com.hedvig.android.iosdata.bridge + +import kotlin.experimental.ExperimentalObjCRefinement +import kotlin.native.HiddenFromObjC + +/** What [IosGraphHolder] needs from the graph it holds. */ +@HiddenFromObjC +interface IosReadsGraph { + val sessionReads: SessionReads +} + +/** + * The shared Kotlin graph the iOS app holds, built on first use. + * + * A feature's reads reach Swift without a change here: the feature declares a facade with an `@Inject` constructor + * taking [SessionReads], contributes an accessor interface to the app scope, and adds an extension on this class, which + * Swift sees as a method: + * + * ``` + * @ContributesTo(AppScope::class) + * interface ForeverReadsComponent { val foreverReads: ForeverReads } + * + * fun IosGraphHolder.foreverReads(): ForeverReads = component().foreverReads + * ``` + * + * and the umbrella exports the feature's module. + */ +class IosGraphHolder internal constructor( + createGraph: () -> IosReadsGraph, +) { + private val built: Lazy = lazy(createGraph) + + /** The graph, built on first use. Read it through [component]. */ + @HiddenFromObjC + val graph: Any get() = built.value + + /** + * A member logged in. Kotlin ends the member reads still in flight as `SESSION_ENDED`; a member read started after + * this call runs for the new member. Logged-out reads carry on. No token passes through this call: Kotlin asks the + * iOS app for one when it needs it. Callable from any thread, returns when done, and does nothing when the graph was + * never used. + */ + fun sessionStarted() { + endMemberReads() + } + + /** The member logged out. Kotlin ends their reads, as [sessionStarted] does. */ + fun sessionEnded() { + endMemberReads() + } + + private fun endMemberReads() { + if (!built.isInitialized()) return + built.value.sessionReads.sessionChanged() + } +} + +/** A holder over the graph [createGraph] builds on first use. */ +@HiddenFromObjC +fun iosGraphHolder(createGraph: () -> IosReadsGraph): IosGraphHolder = IosGraphHolder(createGraph) + +/** The part [T] of the holder's graph, for a feature's accessor extension on [IosGraphHolder]. */ +@HiddenFromObjC +inline fun IosGraphHolder.component(): T = graph as T diff --git a/app/core/ios-data-bridge/src/nativeMain/kotlin/com/hedvig/android/iosdata/bridge/NativeSuspendOnce.kt b/app/core/ios-data-bridge/src/nativeMain/kotlin/com/hedvig/android/iosdata/bridge/NativeSuspendOnce.kt new file mode 100644 index 0000000000..fc54edaa85 --- /dev/null +++ b/app/core/ios-data-bridge/src/nativeMain/kotlin/com/hedvig/android/iosdata/bridge/NativeSuspendOnce.kt @@ -0,0 +1,38 @@ +package com.hedvig.android.iosdata.bridge + +import com.rickclephas.kmp.nativecoroutines.NativeCancellable +import com.rickclephas.kmp.nativecoroutines.NativeSuspend +import kotlin.concurrent.AtomicInt +import kotlinx.coroutines.CancellationException +import platform.Foundation.NSError + +/** + * Passes on only the first callback, and makes the caller's cancel final: cancelling delivers the cancellation at once + * when nothing was delivered yet, and drops whatever the call delivers after it. `nativeSuspend` alone can call back + * twice when a cancel lands as a call finishes. + */ +internal fun NativeSuspend.deliveringOnce(): NativeSuspend = { onResult, onError, onCancelled -> + val delivered = AtomicInt(0) + val cancelCall = this( + { value, unit -> if (delivered.compareAndSet(0, 1)) onResult(value, unit) else unit }, + { error, unit -> if (delivered.compareAndSet(0, 1)) onError(error, unit) else unit }, + { error, unit -> if (delivered.compareAndSet(0, 1)) onCancelled(error, unit) else unit }, + ) + val cancel: NativeCancellable = { + if (delivered.compareAndSet(0, 1)) onCancelled(callerCancellation(), Unit) + cancelCall() + } + cancel +} + +/** The Kotlin throwable inside an `NSError` that a `NativeSuspend` call delivered, if there is one. */ +internal fun NSError.kotlinThrowable(): Throwable? = userInfo[KOTLIN_EXCEPTION_KEY] as? Throwable + +private fun callerCancellation(): NSError = NSError.errorWithDomain( + domain = KOTLIN_EXCEPTION_KEY, + code = 0, + userInfo = mapOf(KOTLIN_EXCEPTION_KEY to CancellationException("Cancelled by the caller")), +) + +/** Where `kmp-nativecoroutines-core` puts the Kotlin throwable in the `NSError` it delivers. */ +private const val KOTLIN_EXCEPTION_KEY = "KotlinException" diff --git a/app/core/ios-data-bridge/src/nativeMain/kotlin/com/hedvig/android/iosdata/bridge/ReadFailures.kt b/app/core/ios-data-bridge/src/nativeMain/kotlin/com/hedvig/android/iosdata/bridge/ReadFailures.kt new file mode 100644 index 0000000000..0cf9c79c6d --- /dev/null +++ b/app/core/ios-data-bridge/src/nativeMain/kotlin/com/hedvig/android/iosdata/bridge/ReadFailures.kt @@ -0,0 +1,11 @@ +package com.hedvig.android.iosdata.bridge + +import platform.Foundation.NSError + +object ReadFailures { + /** + * The failure inside [error], an error a [SessionReads] read delivered, or null when the awaiting task cancelled the + * read itself. + */ + fun from(error: NSError): ReadFailure? = error.kotlinThrowable() as? ReadFailure +} diff --git a/app/core/ios-data-bridge/src/nativeMain/kotlin/com/hedvig/android/iosdata/bridge/SessionReads.kt b/app/core/ios-data-bridge/src/nativeMain/kotlin/com/hedvig/android/iosdata/bridge/SessionReads.kt new file mode 100644 index 0000000000..46db8cb416 --- /dev/null +++ b/app/core/ios-data-bridge/src/nativeMain/kotlin/com/hedvig/android/iosdata/bridge/SessionReads.kt @@ -0,0 +1,85 @@ +@file:OptIn(ExperimentalObjCRefinement::class) + +package com.hedvig.android.iosdata.bridge + +import com.apollographql.apollo.ApolloClient +import com.hedvig.android.core.common.di.AppScope +import com.hedvig.android.core.common.di.PublicApolloClient +import com.rickclephas.kmp.nativecoroutines.NativeSuspend +import com.rickclephas.kmp.nativecoroutines.nativeSuspend +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlin.experimental.ExperimentalObjCRefinement +import kotlin.native.HiddenFromObjC +import kotlin.time.Duration +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob + +/** + * Turns a suspend read into the `NativeSuspend` the iOS app awaits with `asyncFunction(for:)`. Every read of every + * feature goes through here, with the contract of [ReadSessions]: exactly one callback, a cancel by the awaiting task + * delivered at once with nothing after it, every failure a [ReadFailure] that [ReadFailures.from] reads, a bounded wait + * even when an iOS app input never answers. + * + * The block of a read starts when the iOS app starts awaiting, so a read built before a session change and awaited after + * it runs in the new session. A member read's block receives only the member client and a logged-out read's block only + * the token-free one, so the receiver never hands a block the wrong client. + */ +@HiddenFromObjC +@SingleIn(AppScope::class) +@Inject +class SessionReads( + memberClient: ApolloClient, + @PublicApolloClient publicClient: ApolloClient, +) { + internal val core = ReadSessions(MemberReadScope(memberClient), PublicReadScope(publicClient)) + + /** Where callers wait; only a caller's own cancel cancels a waiter. */ + private val waiters = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + /** How long a caller waits for a read. */ + var readTimeout: Duration + get() = core.readTimeout + set(value) { + core.readTimeout = value + } + + /** + * The member read [block] under [name], a stable dotted name that logs show (`forever.referrals`), sending + * [operation], the GraphQL operation the iOS app may log on failure, and [arguments], every value that makes two + * reads of the same name different (a contract id, a page cursor); reads are joined only when all of them are equal. + * A login or logout while it runs ends it as `SESSION_ENDED`. + */ + fun read( + name: String, + vararg arguments: Any?, + operation: String, + block: suspend MemberReadScope.() -> T, + ): NativeSuspend { + val key = arguments.toList() + return nativeSuspend(waiters) { core.read(name, key, operation, block) }.deliveringOnce() + } + + /** + * A read made before login, as [read] in everything but the client and the session, which never ends it. + * + * Only the receiver's client is token-free. The unqualified `ApolloClient` in the graph is the member client and sends + * the member's token whenever one exists, so code that [block] calls, a shared use case included, must inject + * `@PublicApolloClient ApolloClient` when it needs a client. + */ + fun publicRead( + name: String, + vararg arguments: Any?, + operation: String, + block: suspend PublicReadScope.() -> T, + ): NativeSuspend { + val key = arguments.toList() + return nativeSuspend(waiters) { core.publicRead(name, key, operation, block) }.deliveringOnce() + } + + /** Ends the member reads in flight, synchronously, so no read started after this call runs in the previous session. */ + fun sessionChanged() { + core.sessionChanged() + } +} diff --git a/app/core/ios-data-bridge/src/nativeTest/kotlin/com/hedvig/android/iosdata/bridge/NativeSuspendOnceTest.kt b/app/core/ios-data-bridge/src/nativeTest/kotlin/com/hedvig/android/iosdata/bridge/NativeSuspendOnceTest.kt new file mode 100644 index 0000000000..3d8fa99fe4 --- /dev/null +++ b/app/core/ios-data-bridge/src/nativeTest/kotlin/com/hedvig/android/iosdata/bridge/NativeSuspendOnceTest.kt @@ -0,0 +1,72 @@ +package com.hedvig.android.iosdata.bridge + +import assertk.assertThat +import assertk.assertions.containsExactly +import com.rickclephas.kmp.nativecoroutines.NativeSuspend +import kotlin.test.Test +import platform.Foundation.NSError + +class NativeSuspendOnceTest { + @Test + fun `a result that arrives after the caller cancelled is dropped for the cancellation`() { + var deliverLateResult: () -> Unit = {} + val slowCall: NativeSuspend = { onResult, _, _ -> + deliverLateResult = { onResult("late", Unit) } + ({}) + } + val delivered = mutableListOf() + + val cancel = slowCall.deliveringOnce()( + { _, unit -> + delivered += "result" + unit + }, + { _, unit -> + delivered += "error" + unit + }, + { _, unit -> + delivered += "cancelled" + unit + }, + ) + cancel() + deliverLateResult() + + assertThat(delivered).containsExactly("cancelled") + } + + @Test + fun `a call delivers one callback even when the library would deliver two`() { + val errorThenCancellation: NativeSuspend = { _, onError, onCancelled -> + onError(NSError.errorWithDomain("KotlinException", 0, null), Unit) + onCancelled(NSError.errorWithDomain("KotlinException", 0, null), Unit) + ({}) + } + val resultThenCancellation: NativeSuspend = { onResult, _, onCancelled -> + onResult("value", Unit) + onCancelled(NSError.errorWithDomain("KotlinException", 0, null), Unit) + ({}) + } + val delivered = mutableListOf() + + for (call in listOf(errorThenCancellation, resultThenCancellation)) { + call.deliveringOnce()( + { _, unit -> + delivered += "result" + unit + }, + { _, unit -> + delivered += "error" + unit + }, + { _, unit -> + delivered += "cancelled" + unit + }, + ) + } + + assertThat(delivered).containsExactly("error", "result") + } +} diff --git a/app/core/ios-data-bridge/src/nativeTest/kotlin/com/hedvig/android/iosdata/bridge/SessionReadsTest.kt b/app/core/ios-data-bridge/src/nativeTest/kotlin/com/hedvig/android/iosdata/bridge/SessionReadsTest.kt new file mode 100644 index 0000000000..9458d139f0 --- /dev/null +++ b/app/core/ios-data-bridge/src/nativeTest/kotlin/com/hedvig/android/iosdata/bridge/SessionReadsTest.kt @@ -0,0 +1,149 @@ +package com.hedvig.android.iosdata.bridge + +import assertk.assertThat +import assertk.assertions.isEqualTo +import assertk.assertions.isNotNull +import assertk.assertions.isNull +import com.apollographql.apollo.ApolloClient +import com.hedvig.android.logger.LogcatLogger +import com.rickclephas.kmp.nativecoroutines.NativeCancellable +import com.rickclephas.kmp.nativecoroutines.NativeSuspend +import kotlin.concurrent.AtomicInt +import kotlin.concurrent.AtomicReference +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import platform.Foundation.NSError + +/** What only the Objective-C adapter adds to the read contract: the callbacks the iOS app receives. */ +class SessionReadsTest { + private val memberClient = ApolloClient.Builder().serverUrl("https://member.test").build() + private val publicClient = ApolloClient.Builder().serverUrl("https://public.test").build() + private val reads = SessionReads(memberClient, publicClient) + + @BeforeTest + fun install() { + LogcatLogger.install(CapturingLogger()) + } + + @AfterTest + fun uninstall() { + LogcatLogger.uninstall() + memberClient.close() + publicClient.close() + } + + @Test + fun `a read delivers its value once`() { + val started = reads.read("test.value", operation = "TestOperation") { 7 }.begin() + + waitUntil { started.result.value != null } + runBlocking { delay(50.milliseconds) } + + assertThat(started.result.value?.value).isEqualTo(7) + assertThat(started.callbacks.value).isEqualTo(1) + } + + @Test + fun `a failure arrives as an error that ReadFailures reads`() { + val delivered = reads.read("test.failure", operation = "TestOperation") { throw generalReadFailure() }.within(WAIT) + + assertThat(delivered.failure?.kind).isEqualTo(ReadFailureKind.GENERAL) + assertThat(delivered.failure?.readName).isEqualTo("test.failure") + } + + @Test + fun `a cancel from the caller is delivered once and reads as no failure`() { + val started = CompletableDeferred() + val delivered = reads.read("test.cancel", operation = "TestOperation") { + started.complete(Unit) + awaitCancellation() + }.begin() + runBlocking { started.await() } + + delivered.cancel() + + waitUntil { delivered.callbacks.value == 1 } + assertThat(delivered.result.value?.cancellation).isNotNull() + assertThat(ReadFailures.from(delivered.result.value!!.cancellation!!)).isNull() + runBlocking { delay(100.milliseconds) } + assertThat(delivered.callbacks.value).isEqualTo(1) + } + + @Test + fun `a session change ends a member read as an error and not as a cancel`() { + val started = CompletableDeferred() + val delivered = reads.read("test.session", operation = "TestOperation") { + started.complete(Unit) + awaitCancellation() + }.begin() + runBlocking { started.await() } + + reads.sessionChanged() + + waitUntil { delivered.result.value != null } + assertThat(delivered.result.value!!.cancellation).isNull() + assertThat(delivered.result.value!!.failure?.kind).isEqualTo(ReadFailureKind.SESSION_ENDED) + } + + @Test + fun `a read built before a session change and awaited after it runs in the new session`() { + val read = reads.read("test.built", operation = "TestOperation") { 4 } + + reads.sessionChanged() + + assertThat(read.within(WAIT).value).isEqualTo(4) + } + + @Test + fun `a logged-out read delivers through the same adapter`() { + assertThat(reads.publicRead("test.public", operation = "PublicOperation") { 6 }.within(WAIT).value).isEqualTo(6) + } + + private companion object { + val WAIT: Duration = 5.seconds + } +} + +internal class Delivered(val value: T?, val error: NSError?, val cancellation: NSError?) { + val failure: ReadFailure? get() = error?.let { ReadFailures.from(it) } +} + +internal class Started { + val result = AtomicReference?>(null) + val callbacks = AtomicInt(0) + internal var cancelCall: NativeCancellable = {} + + fun cancel() { + cancelCall() + } + + fun record(delivered: Delivered) { + callbacks.incrementAndGet() + result.compareAndSet(null, delivered) + } +} + +/** Starts the read as `asyncFunction(for:)` does and records every callback. */ +internal fun NativeSuspend.begin(): Started { + val started = Started() + started.cancelCall = this( + { value, unit -> started.record(Delivered(value, null, null)).let { unit } }, + { error, unit -> started.record(Delivered(null, error, null)).let { unit } }, + { error, unit -> started.record(Delivered(null, null, error)).let { unit } }, + ) + return started +} + +internal fun NativeSuspend.within(timeout: Duration): Delivered { + val started = begin() + waitUntil(timeout) { started.result.value != null } + return started.result.value!! +} diff --git a/app/language/language-core/src/commonMain/kotlin/com/hedvig/android/language/Language.kt b/app/language/language-core/src/commonMain/kotlin/com/hedvig/android/language/Language.kt index 66916f423b..0ae11cb2b0 100644 --- a/app/language/language-core/src/commonMain/kotlin/com/hedvig/android/language/Language.kt +++ b/app/language/language-core/src/commonMain/kotlin/com/hedvig/android/language/Language.kt @@ -1,8 +1,13 @@ +@file:OptIn(ExperimentalObjCName::class) + package com.hedvig.android.language import com.hedvig.android.logger.LogPriority import com.hedvig.android.logger.logcat +import kotlin.experimental.ExperimentalObjCName +import kotlin.native.ObjCName +@ObjCName(name = "HedvigSharedLanguage", swiftName = "Language", exact = true) enum class Language { SV_SE, EN_SE, diff --git a/app/language/language-core/src/nativeMain/kotlin/com/hedvig/android/language/IosLanguageSource.kt b/app/language/language-core/src/nativeMain/kotlin/com/hedvig/android/language/IosLanguageSource.kt new file mode 100644 index 0000000000..ad61080dc9 --- /dev/null +++ b/app/language/language-core/src/nativeMain/kotlin/com/hedvig/android/language/IosLanguageSource.kt @@ -0,0 +1,16 @@ +@file:OptIn(ExperimentalObjCName::class) + +package com.hedvig.android.language + +import kotlin.experimental.ExperimentalObjCName +import kotlin.native.ObjCName + +/** + * The language the iOS app shows, which the iOS app owns and changes without telling Kotlin. Kotlin calls + * [currentLanguage] for every request, from any thread, usually a background one, so an iOS implementation must be safe + * to call from any thread and must not be isolated to the main actor. + */ +@ObjCName(name = "HedvigSharedIosLanguageSource", swiftName = "IosLanguageSource", exact = true) +interface IosLanguageSource { + fun currentLanguage(): Language +} diff --git a/app/language/language-core/src/nativeMain/kotlin/com/hedvig/android/language/LanguageService.native.kt b/app/language/language-core/src/nativeMain/kotlin/com/hedvig/android/language/LanguageService.native.kt index 5e30a10ced..d758a23fa6 100644 --- a/app/language/language-core/src/nativeMain/kotlin/com/hedvig/android/language/LanguageService.native.kt +++ b/app/language/language-core/src/nativeMain/kotlin/com/hedvig/android/language/LanguageService.native.kt @@ -10,35 +10,28 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import platform.Foundation.NSLocale +/** The iOS app's language. The iOS app owns the setting, so [setLanguage] only changes what Kotlin reports. */ @ContributesBinding(AppScope::class) @SingleIn(AppScope::class) @Inject internal class NativeLanguageService( - private val storage: LanguageStorage, + private val source: IosLanguageSource, ) : LanguageService { - private val mutableLanguage = MutableStateFlow(Language.from(storage.getCurrentLanguageTag())) + private val mutableLanguage = MutableStateFlow(source.currentLanguage()) - /** - * Updated only when [setLanguage] or [getLanguage] runs, since the iOS app changes the language without going - * through Kotlin, so read [getLanguage] for the current value. - */ + /** Updated only when [setLanguage] or [getLanguage] runs, so read [getLanguage] for the current value. */ override val language: StateFlow = mutableLanguage.asStateFlow() override fun setLanguage(language: Language) { - storage.setLanguageTag(language.toBcp47Format()) mutableLanguage.value = language } - /** - * Read from the storage on every call, since the iOS app changes the language through its own layer without going - * through [setLanguage]. - */ + /** Asks the iOS app on every call, since it changes the language without telling Kotlin. */ override fun getLanguage(): Language { - val languageTag = storage.getCurrentLanguageTag() - return Language.from(languageTag).also { mutableLanguage.value = it } + return source.currentLanguage().also { mutableLanguage.value = it } } override fun getLocale(): CommonLocale { - return NSLocale(localeIdentifier = storage.getCurrentLanguageTag()) + return NSLocale(localeIdentifier = getLanguage().toBcp47Format()) } } diff --git a/app/language/language-core/src/nativeMain/kotlin/com/hedvig/android/language/LanguageStorage.kt b/app/language/language-core/src/nativeMain/kotlin/com/hedvig/android/language/LanguageStorage.kt deleted file mode 100644 index 6525a256af..0000000000 --- a/app/language/language-core/src/nativeMain/kotlin/com/hedvig/android/language/LanguageStorage.kt +++ /dev/null @@ -1,13 +0,0 @@ -package com.hedvig.android.language - -/** - * iOS-side bridge that provides locale state to the shared Kotlin layer. - * The Swift implementation must perform mutations on the main thread. - */ -interface LanguageStorage { - fun getCurrentLanguageTag(): String - - fun getSelectedLanguageTag(): String? - - fun setLanguageTag(tag: String) -} diff --git a/app/language/language-core/src/nativeTest/kotlin/com/hedvig/android/language/NativeLanguageServiceTest.kt b/app/language/language-core/src/nativeTest/kotlin/com/hedvig/android/language/NativeLanguageServiceTest.kt new file mode 100644 index 0000000000..1cf8cc2af1 --- /dev/null +++ b/app/language/language-core/src/nativeTest/kotlin/com/hedvig/android/language/NativeLanguageServiceTest.kt @@ -0,0 +1,23 @@ +package com.hedvig.android.language + +import kotlin.test.Test +import kotlin.test.assertEquals + +class NativeLanguageServiceTest { + @Test + fun `the language follows the iOS app's current language on every read`() { + var current = Language.SV_SE + val service = NativeLanguageService( + object : IosLanguageSource { + override fun currentLanguage(): Language = current + }, + ) + + val first = service.getLanguage() + current = Language.EN_SE + val second = service.getLanguage() + + assertEquals(listOf(Language.SV_SE, Language.EN_SE), listOf(first, second)) + assertEquals(Language.EN_SE, service.language.value) + } +} diff --git a/app/network/network-clients/src/commonMain/kotlin/com/hedvig/android/network/clients/AccessTokenFetcher.kt b/app/network/network-clients/src/commonMain/kotlin/com/hedvig/android/network/clients/AccessTokenFetcher.kt index 16a2287f86..0799a89a6f 100644 --- a/app/network/network-clients/src/commonMain/kotlin/com/hedvig/android/network/clients/AccessTokenFetcher.kt +++ b/app/network/network-clients/src/commonMain/kotlin/com/hedvig/android/network/clients/AccessTokenFetcher.kt @@ -1,5 +1,17 @@ +@file:OptIn(ExperimentalObjCName::class) + package com.hedvig.android.network.clients +import kotlin.experimental.ExperimentalObjCName +import kotlin.native.ObjCName + +/** + * The member's access token, or null when there is none. Called before every request that sends one, from any thread, + * usually a background one; when it throws, the request fails without being sent. An iOS implementation must complete + * it exactly once: Kotlin cannot cancel it, so one that never completes holds its caller until that caller's own time + * limit. + */ +@ObjCName(name = "HedvigSharedAccessTokenFetcher", swiftName = "AccessTokenFetcher", exact = true) interface AccessTokenFetcher { suspend fun fetch(): String? } diff --git a/app/network/network-clients/src/commonMain/kotlin/com/hedvig/android/network/clients/NetworkLogPolicy.kt b/app/network/network-clients/src/commonMain/kotlin/com/hedvig/android/network/clients/NetworkLogPolicy.kt index 4498e9ab1d..28fdb76056 100644 --- a/app/network/network-clients/src/commonMain/kotlin/com/hedvig/android/network/clients/NetworkLogPolicy.kt +++ b/app/network/network-clients/src/commonMain/kotlin/com/hedvig/android/network/clients/NetworkLogPolicy.kt @@ -1,5 +1,10 @@ +@file:OptIn(ExperimentalObjCName::class) + package com.hedvig.android.network.clients +import kotlin.experimental.ExperimentalObjCName +import kotlin.native.ObjCName + /** * What the network clients log beyond GraphQL operation names, error counts, error types and exception classes. * @@ -9,6 +14,7 @@ package com.hedvig.android.network.clients * adds the GraphQL error messages, the errors with their extensions and the response extensions, and exception * messages; they can quote what was sent, so they have their own switch. */ +@ObjCName(name = "HedvigSharedNetworkLogPolicy", swiftName = "NetworkLogPolicy", exact = true) class NetworkLogPolicy( val logsHttpBodies: Boolean, val logsGraphqlData: Boolean, 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 9eb434feaa..24adfcade6 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 @@ -74,23 +74,21 @@ interface NetworkMetroProviders { } /** - * The app's Apollo client: the normalized cache, [httpClient] with its headers, the Octopus URL, and the interceptor - * chain of [addHedvigInterceptors] with [platformInterceptors] ahead of logging. + * The app's Apollo client: the normalized cache when [normalizedCacheFactory] is given, [httpClient] with its headers, + * the Octopus URL, and the interceptor chain of [addHedvigInterceptors] with [platformInterceptors] ahead of logging. */ internal fun buildHedvigApolloClient( - normalizedCacheFactory: NormalizedCacheFactory, + normalizedCacheFactory: NormalizedCacheFactory?, httpClient: HttpClient, hedvigBuildConstants: HedvigBuildConstants, platformInterceptors: List, networkLogPolicy: NetworkLogPolicy, -): ApolloClient = with(Cache) { - ApolloClient.Builder() - .cache(normalizedCacheFactory) - .ktorClient(httpClient) - .httpServerUrl(hedvigBuildConstants.urlGraphqlOctopus) - .addHedvigInterceptors(platformInterceptors, networkLogPolicy) - .build() -} +): ApolloClient = ApolloClient.Builder() + .apply { if (normalizedCacheFactory != null) with(Cache) { cache(normalizedCacheFactory) } } + .ktorClient(httpClient) + .httpServerUrl(hedvigBuildConstants.urlGraphqlOctopus) + .addHedvigInterceptors(platformInterceptors, networkLogPolicy) + .build() internal fun buildKtorClient( engineFactory: HttpClientEngineFactory<*>, diff --git a/app/network/network-clients/src/jvmAndAndroidMain/kotlin/com/hedvig/android/network/clients/di/ApolloClientMetroProviders.kt b/app/network/network-clients/src/jvmAndAndroidMain/kotlin/com/hedvig/android/network/clients/di/ApolloClientMetroProviders.kt index adab7e4745..29ca8c7823 100644 --- a/app/network/network-clients/src/jvmAndAndroidMain/kotlin/com/hedvig/android/network/clients/di/ApolloClientMetroProviders.kt +++ b/app/network/network-clients/src/jvmAndAndroidMain/kotlin/com/hedvig/android/network/clients/di/ApolloClientMetroProviders.kt @@ -3,9 +3,12 @@ package com.hedvig.android.network.clients.di import com.apollographql.apollo.ApolloClient import com.apollographql.apollo.interceptor.ApolloInterceptor import com.apollographql.cache.normalized.api.NormalizedCacheFactory +import com.apollographql.cache.normalized.memory.MemoryCacheFactory import com.hedvig.android.auth.AuthTokenService 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.demomode.DemoManager import com.hedvig.android.network.clients.NetworkLogPolicy import com.hedvig.android.network.clients.apollo.LogoutOnUnauthenticatedInterceptor @@ -34,6 +37,25 @@ interface ApolloClientMetroProviders { networkLogPolicy, ) + /** + * Built on the token-free [BaseHttpClient], so a request never carries an `Authorization` header and never asks for a + * token. It has its own small cache and no platform interceptors, so a rejected request cannot log the member out. + */ + @Provides + @SingleIn(AppScope::class) + @PublicApolloClient + fun providePublicApolloClient( + @BaseHttpClient httpClient: HttpClient, + hedvigBuildConstants: HedvigBuildConstants, + networkLogPolicy: NetworkLogPolicy, + ): ApolloClient = buildHedvigApolloClient( + MemoryCacheFactory(maxSizeBytes = 1024 * 1024), + httpClient, + hedvigBuildConstants, + platformInterceptors = emptyList(), + networkLogPolicy = networkLogPolicy, + ) + /** HTTP bodies and GraphQL data are logged outside production builds, GraphQL errors in every build. */ @Provides fun provideNetworkLogPolicy(hedvigBuildConstants: HedvigBuildConstants): NetworkLogPolicy = NetworkLogPolicy( diff --git a/app/network/network-clients/src/jvmTest/kotlin/com/hedvig/android/network/clients/di/JvmNetworkBindingsTest.kt b/app/network/network-clients/src/jvmTest/kotlin/com/hedvig/android/network/clients/di/JvmNetworkBindingsTest.kt index 26410d242e..d70f150a3e 100644 --- a/app/network/network-clients/src/jvmTest/kotlin/com/hedvig/android/network/clients/di/JvmNetworkBindingsTest.kt +++ b/app/network/network-clients/src/jvmTest/kotlin/com/hedvig/android/network/clients/di/JvmNetworkBindingsTest.kt @@ -1,11 +1,24 @@ package com.hedvig.android.network.clients.di +import com.apollographql.apollo.ApolloClient +import com.apollographql.apollo.api.Adapter +import com.apollographql.apollo.api.CompiledField +import com.apollographql.apollo.api.CustomScalarAdapters +import com.apollographql.apollo.api.Query +import com.apollographql.apollo.api.json.JsonWriter +import com.apollographql.cache.normalized.FetchPolicy +import com.apollographql.cache.normalized.fetchPolicy import com.hedvig.android.auth.AccessTokenProvider import com.hedvig.android.core.buildconstants.AppBuildConfig import com.hedvig.android.core.buildconstants.Flavor +import com.hedvig.android.core.buildconstants.HedvigBuildConstants +import com.hedvig.android.core.common.ApplicationScope import com.hedvig.android.core.common.di.AppScope import com.hedvig.android.core.common.di.AuthHttpClientEngine +import com.hedvig.android.core.common.di.BaseHttpClient import com.hedvig.android.core.common.di.DesktopDataDirectory +import com.hedvig.android.core.common.di.PublicApolloClient +import com.hedvig.android.logger.TestLogcatLoggingRule import com.hedvig.android.network.clients.AccessTokenFetcher import com.hedvig.android.network.clients.ExtraKtorClientConfiguration import com.hedvig.android.network.clients.NetworkLogPolicy @@ -14,8 +27,16 @@ import com.hedvig.android.network.clients.TlsDiagnostics import dev.zacsweers.metro.DependencyGraph import dev.zacsweers.metro.Provides import dev.zacsweers.metro.createGraphFactory +import io.ktor.client.HttpClient import io.ktor.client.engine.HttpClientEngine +import io.ktor.client.engine.mock.MockEngine +import io.ktor.client.engine.mock.respond import io.ktor.client.engine.okhttp.OkHttpEngine +import io.ktor.client.plugins.HttpSend +import io.ktor.client.plugins.plugin +import io.ktor.client.request.get +import io.ktor.http.Headers +import io.ktor.http.HttpStatusCode import java.io.File import javax.net.ssl.SSLHandshakeException import kotlin.io.path.createTempDirectory @@ -23,8 +44,14 @@ import kotlin.test.AfterTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertIs +import kotlin.test.assertNotNull import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.coroutines.job +import kotlinx.coroutines.joinAll +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runTest +import org.junit.Rule @DependencyGraph(AppScope::class) internal interface NetworkTestGraph { @@ -32,6 +59,14 @@ internal interface NetworkTestGraph { val extraKtorClientConfiguration: ExtraKtorClientConfiguration val tlsDiagnostics: TlsDiagnostics val networkLogPolicy: NetworkLogPolicy + val hedvigBuildConstants: HedvigBuildConstants + val applicationScope: ApplicationScope + + @PublicApolloClient + val publicApolloClient: ApolloClient + + @BaseHttpClient + val baseHttpClient: HttpClient @AuthHttpClientEngine val authHttpClientEngine: HttpClientEngine @@ -46,11 +81,17 @@ internal interface NetworkTestGraph { } class JvmNetworkBindingsTest { + @get:Rule + val testLogcatLogger = TestLogcatLoggingRule() + private val dataDirectory: File = createTempDirectory("network-bindings-test").toFile() private val graph = createGraphFactory().create(dataDirectory, TestAppBuildConfig) @AfterTest fun tearDown() { + // Building the base HTTP client launches the device id's first DataStore write on the application scope. Deleting + // the directory under that write fails it, and the uncaught IOException then fails whichever runTest comes next. + runBlocking { graph.applicationScope.coroutineContext.job.children.toList().joinAll() } dataDirectory.deleteRecursively() } @@ -71,12 +112,100 @@ class JvmNetworkBindingsTest { assertIs(graph.authHttpClientEngine) } + @Test + fun `the public Apollo client sends through the graph's base HTTP client`() = runTest { + val sent = mutableListOf() + graph.baseHttpClient.plugin(HttpSend).intercept { request -> + sent += request.headers.build() + throw RequestRecorded() + } + + val response = graph.publicApolloClient.query(TestQuery).fetchPolicy(FetchPolicy.NetworkOnly).execute() + + assertEquals(REQUEST_RECORDED_MESSAGE, response.exception?.message) + assertEquals(1, sent.size) + assertNotNull(sent.single()["Accept-Language"]) + } + + @Test + fun `the public Apollo client never fetches a token while the member client does`() = runTest { + val fetcher = CountingAccessTokenFetcher() + val received = mutableListOf() + val engine = MockEngine { request -> + received += request.headers + respond("", HttpStatusCode.InternalServerError) + } + val baseClient = HttpClient(engine) { install(HttpSend) } + val providers = object : NetworkMetroProviders {} + val publicClient = object : ApolloClientMetroProviders {}.providePublicApolloClient( + baseClient, + graph.hedvigBuildConstants, + graph.networkLogPolicy, + ) + + publicClient.query(TestQuery).fetchPolicy(FetchPolicy.NetworkOnly).execute() + + assertEquals(1, received.size) + assertNull(received.single()["Authorization"]) + assertEquals(0, fetcher.calls) + + // Control: the member client over the same base client does fetch the token and send it. + providers.provideHttpClient(baseClient, fetcher).get("https://example.com") + + assertEquals(2, received.size) + assertEquals("Bearer token", received.last()["Authorization"]) + assertTrue(fetcher.calls > 0) + + // In the app the member client exists and has been used before the public query runs, so check that order too. + val callsAfterMemberClient = fetcher.calls + publicClient.query(TestQuery).fetchPolicy(FetchPolicy.NetworkOnly).execute() + + assertEquals(3, received.size) + assertNull(received.last()["Authorization"]) + assertEquals(callsAfterMemberClient, fetcher.calls) + } + @Test fun `the TLS diagnostics describe nothing, even for a trust failure`() = runTest { assertNull(graph.tlsDiagnostics.describe(SSLHandshakeException("Trust anchor for certification path not found."))) } } +private object TestQuery : Query { + object Data : Query.Data + + override fun document(): String = "query Test { __typename }" + + override fun name(): String = "Test" + + override fun id(): String = "Test" + + override fun adapter(): Adapter = error("The request is aborted before a response exists") + + override fun serializeVariables( + writer: JsonWriter, + customScalarAdapters: CustomScalarAdapters, + withDefaultValues: Boolean, + ) {} + + override fun rootField(): CompiledField = error("The request is aborted before the cache is read") +} + +/** Thrown by the test's last-stop interceptor so the request never leaves the machine. */ +private class RequestRecorded : RuntimeException(REQUEST_RECORDED_MESSAGE) + +private const val REQUEST_RECORDED_MESSAGE = "Request recorded, not sent" + +private class CountingAccessTokenFetcher : AccessTokenFetcher { + var calls = 0 + private set + + override suspend fun fetch(): String? { + calls++ + return "token" + } +} + private object TestAppBuildConfig : AppBuildConfig { override val debug: Boolean = true override val applicationId: String = "com.hedvig.dev.app" diff --git a/app/network/network-clients/src/nativeMain/kotlin/com/hedvig/android/network/clients/di/NetworkMetroProviders.native.kt b/app/network/network-clients/src/nativeMain/kotlin/com/hedvig/android/network/clients/di/NetworkMetroProviders.native.kt index ee8c1f8902..f95747f3b0 100644 --- a/app/network/network-clients/src/nativeMain/kotlin/com/hedvig/android/network/clients/di/NetworkMetroProviders.native.kt +++ b/app/network/network-clients/src/nativeMain/kotlin/com/hedvig/android/network/clients/di/NetworkMetroProviders.native.kt @@ -1,9 +1,10 @@ package com.hedvig.android.network.clients.di import com.apollographql.apollo.ApolloClient -import com.apollographql.cache.normalized.api.NormalizedCacheFactory 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.network.clients.ExtraKtorClientConfiguration import com.hedvig.android.network.clients.NetworkLogPolicy import com.hedvig.android.network.clients.NoopExtraKtorClientConfiguration @@ -21,18 +22,37 @@ interface NativeNetworkMetroProviders { fun provideExtraKtorClientConfiguration(): ExtraKtorClientConfiguration = NoopExtraKtorClientConfiguration() /** - * The interceptor chain is logging only: an `UNAUTHENTICATED` response is an ordinary error, and the session is - * owned by the iOS app. + * No normalized cache: every iOS read goes to the network and stores nothing, so one member's answer cannot reach + * the next member, and a fetch policy that asks for the cache is answered from the network. The interceptor chain + * is logging only: an `UNAUTHENTICATED` response is an ordinary error, and the session is owned by the iOS app. */ @Provides @SingleIn(AppScope::class) fun provideApolloClient( - normalizedCacheFactory: NormalizedCacheFactory, httpClient: HttpClient, hedvigBuildConstants: HedvigBuildConstants, networkLogPolicy: NetworkLogPolicy, ): ApolloClient = buildHedvigApolloClient( - normalizedCacheFactory, + null, + httpClient, + hedvigBuildConstants, + emptyList(), + networkLogPolicy, + ) + + /** + * Built on the token-free [BaseHttpClient], so a request never carries an `Authorization` header and never asks the + * iOS app for a token. No cache and no platform interceptors, as the member client. + */ + @Provides + @SingleIn(AppScope::class) + @PublicApolloClient + fun providePublicApolloClient( + @BaseHttpClient httpClient: HttpClient, + hedvigBuildConstants: HedvigBuildConstants, + networkLogPolicy: NetworkLogPolicy, + ): ApolloClient = buildHedvigApolloClient( + null, httpClient, hedvigBuildConstants, emptyList(), diff --git a/app/network/network-clients/src/nativeMain/kotlin/com/hedvig/android/network/clients/di/PlatformHeaders.native.kt b/app/network/network-clients/src/nativeMain/kotlin/com/hedvig/android/network/clients/di/PlatformHeaders.native.kt index 2e8611bfe7..e9af07c28a 100644 --- a/app/network/network-clients/src/nativeMain/kotlin/com/hedvig/android/network/clients/di/PlatformHeaders.native.kt +++ b/app/network/network-clients/src/nativeMain/kotlin/com/hedvig/android/network/clients/di/PlatformHeaders.native.kt @@ -1,10 +1,11 @@ package com.hedvig.android.network.clients.di import io.ktor.http.HeadersBuilder -import kotlinx.datetime.TimeZone +import platform.Foundation.NSTimeZone +import platform.Foundation.localTimeZone internal actual fun HeadersBuilder.appendPlatformHeaders() { - append("Hedvig-TimeZone", TimeZone.currentSystemDefault().id) + append("Hedvig-TimeZone", NSTimeZone.localTimeZone.name) } internal actual fun platformClientName(appPackageId: String): String = "iOS:$appPackageId" diff --git a/app/network/network-clients/src/nativeTest/kotlin/com/hedvig/android/network/clients/di/NativeApolloClientTest.kt b/app/network/network-clients/src/nativeTest/kotlin/com/hedvig/android/network/clients/di/NativeApolloClientTest.kt index 5ffa074c93..1134269750 100644 --- a/app/network/network-clients/src/nativeTest/kotlin/com/hedvig/android/network/clients/di/NativeApolloClientTest.kt +++ b/app/network/network-clients/src/nativeTest/kotlin/com/hedvig/android/network/clients/di/NativeApolloClientTest.kt @@ -1,25 +1,41 @@ package com.hedvig.android.network.clients.di -import com.apollographql.cache.normalized.memory.MemoryCacheFactory +import com.apollographql.cache.normalized.apolloStore import com.hedvig.android.core.buildconstants.HedvigBuildConstants import com.hedvig.android.network.clients.NetworkLogPolicy import io.ktor.client.HttpClient import io.ktor.client.engine.darwin.Darwin import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFailsWith class NativeApolloClientTest { @Test - fun `the provided Apollo client only logs`() { + fun `the provided Apollo client only logs and has no normalized cache`() { val httpClient = HttpClient(Darwin) val apolloClient = object : NativeNetworkMetroProviders {}.provideApolloClient( - normalizedCacheFactory = MemoryCacheFactory(), httpClient = httpClient, hedvigBuildConstants = FakeHedvigBuildConstants, networkLogPolicy = NetworkLogPolicy(logsHttpBodies = false, logsGraphqlData = false, logsGraphqlErrors = true), ) assertEquals(listOf("LoggingInterceptor"), apolloClient.interceptors.map { it::class.simpleName }) + assertFailsWith { apolloClient.apolloStore } + apolloClient.close() + httpClient.close() + } + + @Test + fun `the provided public Apollo client only logs and has no normalized cache`() { + val httpClient = HttpClient(Darwin) + val apolloClient = object : NativeNetworkMetroProviders {}.providePublicApolloClient( + httpClient = httpClient, + hedvigBuildConstants = FakeHedvigBuildConstants, + networkLogPolicy = NetworkLogPolicy(logsHttpBodies = false, logsGraphqlData = false, logsGraphqlErrors = true), + ) + + assertEquals(listOf("LoggingInterceptor"), apolloClient.interceptors.map { it::class.simpleName }) + assertFailsWith { apolloClient.apolloStore } apolloClient.close() httpClient.close() } diff --git a/app/network/network-clients/src/nativeTest/kotlin/com/hedvig/android/network/clients/di/NativePlatformHeadersTest.kt b/app/network/network-clients/src/nativeTest/kotlin/com/hedvig/android/network/clients/di/NativePlatformHeadersTest.kt index 94f72bbd9b..f86d162c9c 100644 --- a/app/network/network-clients/src/nativeTest/kotlin/com/hedvig/android/network/clients/di/NativePlatformHeadersTest.kt +++ b/app/network/network-clients/src/nativeTest/kotlin/com/hedvig/android/network/clients/di/NativePlatformHeadersTest.kt @@ -1,11 +1,21 @@ package com.hedvig.android.network.clients.di +import io.ktor.http.HeadersBuilder import kotlin.test.Test import kotlin.test.assertEquals +import platform.Foundation.NSTimeZone +import platform.Foundation.localTimeZone class NativePlatformHeadersTest { @Test fun `the client name matches the iOS format`() { assertEquals("iOS:com.hedvig.test", platformClientName("com.hedvig.test")) } + + @Test + fun `the time zone header is the device's zone identifier`() { + val headers = HeadersBuilder().apply { appendPlatformHeaders() }.build() + + assertEquals(NSTimeZone.localTimeZone.name, headers["Hedvig-TimeZone"]) + } } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 147327fbdb..0f20a066a3 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -212,6 +212,7 @@ jetbrains-navigation3-ui = { module = "org.jetbrains.androidx.navigation3:naviga jetbrains-navigationevent-compose = { module = "org.jetbrains.androidx.navigationevent:navigationevent-compose", version.ref = "jetbrains-navigationevent" } junit = { module = "junit:junit", version.ref = "junit" } kctfork-ksp = { module = "dev.zacsweers.kctfork:ksp", version.ref = "kctfork" } +kmpNativeCoroutines-core = { module = "com.rickclephas.kmp:kmp-nativecoroutines-core", version.ref = "kmpNativeCoroutines" } kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin" } kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib", version.ref = "kotlin" } kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" }