Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions .github/workflows/ios-shared.yml
Original file line number Diff line number Diff line change
@@ -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
34 changes: 34 additions & 0 deletions .github/workflows/pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
16 changes: 16 additions & 0 deletions .github/workflows/umbrella.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
5 changes: 3 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
41 changes: 38 additions & 3 deletions app/umbrella/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -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<DelegatingProjectDependency> = listOf(
projects.authlib,
projects.iosDataBridge,
projects.loggingPublic,
)
listOf(
Expand All @@ -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()
Original file line number Diff line number Diff line change
@@ -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<Boolean>()
val calls = AtomicInt(0)

protected fun record() {
calls.incrementAndGet()
lock.lock()
try {
mainThreadCalls += NSThread.isMainThread
} finally {
lock.unlock()
}
}

fun calledOnMainThread(): List<Boolean> {
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<Nothing> { }
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<Pair<LogPriority, String>>()

fun entries(): List<Pair<LogPriority, String>> {
lock.lock()
try {
return lines.toList()
} finally {
lock.unlock()
}
}

fun messages(): List<String> = 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"
Loading
Loading