Skip to content

Commit 54f171d

Browse files
Rewrite crashlytics module
1 parent c5e77bb commit 54f171d

8 files changed

Lines changed: 162 additions & 201 deletions

File tree

‎Sources/CrashKiOSCrashlytics/CrashlyticsSink.swift‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,8 @@ public final class CrashlyticsSink: NSObject, CrashKiOSCrashlyticsSink {
4343
public func setUserId(_ identifier: String) {
4444
crashlytics.setUserID(identifier)
4545
}
46+
47+
public func setCollectionEnabled(_ enabled: Bool) {
48+
crashlytics.setCrashlyticsCollectionEnabled(enabled)
49+
}
4650
}

‎Sources/CrashKiOSCrashlyticsObjC/include/CrashKiOSCrashlyticsSink.h‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@
3232
/// Crashlytics `setUserID:`.
3333
- (void)setUserId:(NSString * _Nonnull)identifier;
3434

35+
/// Crashlytics `setCrashlyticsCollectionEnabled:`.
36+
- (void)setCollectionEnabled:(BOOL)enabled;
37+
3538
@end
3639

3740
#endif /* CrashKiOSCrashlyticsSink_h */

‎crashlytics/build.gradle.kts‎

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -63,12 +63,6 @@ kotlin {
6363
implementation(kotlin("test"))
6464
}
6565
}
66-
appleMain {
67-
dependencies {
68-
implementation(libs.nsexceptionKt.core)
69-
}
70-
}
71-
7266
androidMain {
7367
dependencies {
7468
compileOnly(libs.firebase.crashlytics)
@@ -78,9 +72,8 @@ kotlin {
7872
targets.withType<org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget>().all {
7973
val mainCompilation = compilations.getByName("main")
8074
mainCompilation.cinterops.create("crashlytics") {
81-
includeDirs("$projectDir/src/include")
82-
compilerOpts("-DNS_FORMAT_ARGUMENT(A)=", "-D_Nullable_result=_Nullable")
83-
// extraOpts("-mode", "sourcecode")
75+
// Protocol-only header owned by the Swift package — no SDK symbols.
76+
includeDirs("$rootDir/Sources/CrashKiOSCrashlyticsObjC/include")
8477
}
8578
}
8679
}
Lines changed: 37 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,43 @@
1+
@file:OptIn(ExperimentalForeignApi::class)
2+
13
package co.touchlab.crashkios.crashlytics
24

3-
import com.rickclephas.kmp.nsexceptionkt.core.wrapUnhandledExceptionHook
5+
import co.touchlab.crashkios.crashlytics.objc.CrashKiOSCrashlyticsSinkProtocol
6+
import kotlinx.cinterop.ExperimentalForeignApi
7+
8+
/**
9+
* Registers the Swift-implemented [sink] that forwards CrashKiOS events to Firebase
10+
* Crashlytics, and installs the unhandled-exception hook so unhandled Kotlin
11+
* exceptions are logged as fatal crashes.
12+
*
13+
* Call once, from Swift, at startup — after `FirebaseApp.configure()` and before any
14+
* Kotlin code runs:
15+
* ```swift
16+
* FirebaseApp.configure()
17+
* CrashlyticsKt.registerCrashlyticsSink(sink: CrashlyticsSink())
18+
* ```
19+
* `CrashlyticsSink` ships in the `CrashKiOSCrashlytics` Swift package (this repo's
20+
* `Package.swift`), or copy it from the docs. Add
21+
* `export("co.touchlab.crashkios:crashlytics")` to your framework configuration for
22+
* clean unmangled names.
23+
*
24+
* Calling `enableCrashlytics()` (or constructing `CrashlyticsCallsActual`) on an Apple
25+
* target WITHOUT having registered a sink fails fast with a descriptive error rather
26+
* than silently dropping crash reports.
27+
*/
28+
public fun registerCrashlyticsSink(sink: CrashKiOSCrashlyticsSinkProtocol) {
29+
crashlyticsRegistry.register(sink) { throwable ->
30+
CrashlyticsKotlin.sendFatalException(throwable)
31+
}
32+
CrashlyticsKotlin.implementation = CrashlyticsCallsActual()
33+
}
434

535
/**
6-
* Sets the unhandled exception hook such that all unhandled exceptions are logged to Crashlytics as fatal exceptions.
7-
* If an unhandled exception hook was already set, that hook will be invoked after the exception is logged.
8-
* Note: once the exception is logged the program will be terminated.
9-
* @see wrapUnhandledExceptionHook
36+
* The unhandled exception hook is now installed by [registerCrashlyticsSink]; this
37+
* function does nothing.
1038
*/
11-
public fun setCrashlyticsUnhandledExceptionHook(): Unit = wrapUnhandledExceptionHook { throwable ->
12-
CrashlyticsKotlin.sendFatalException(throwable)
39+
@Deprecated(
40+
"registerCrashlyticsSink() installs the unhandled-exception hook; remove this call.",
41+
)
42+
public fun setCrashlyticsUnhandledExceptionHook() {
1343
}
Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,49 @@
1+
@file:OptIn(ExperimentalForeignApi::class)
2+
13
package co.touchlab.crashkios.crashlytics
24

3-
import com.rickclephas.kmp.nsexceptionkt.core.asNSException
4-
import com.rickclephas.kmp.nsexceptionkt.core.getFilteredStackTraceAddresses
5-
import kotlinx.cinterop.UnsafeNumber
6-
import kotlinx.cinterop.convert
5+
import co.touchlab.crashkios.core.CrashSinkRegistry
6+
import co.touchlab.crashkios.core.asNSException
7+
import co.touchlab.crashkios.core.getFilteredStackTraceAddresses
8+
import co.touchlab.crashkios.core.throwableName
9+
import co.touchlab.crashkios.crashlytics.objc.CrashKiOSCrashlyticsSinkProtocol
10+
import kotlinx.cinterop.ExperimentalForeignApi
711

8-
@OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
9-
actual class CrashlyticsCallsActual : CrashlyticsCalls {
12+
internal val crashlyticsRegistry = CrashSinkRegistry<CrashKiOSCrashlyticsSinkProtocol>("Crashlytics")
1013

11-
init {
12-
FIRCheckLinkDependencies()
13-
}
14+
actual class CrashlyticsCallsActual : CrashlyticsCalls {
15+
// Fail-fast: an implementation constructed without a registered Swift sink would
16+
// silently lose every event. The pre-1.0 cinterop code failed just as loudly at
17+
// this point via FIRCheckLinkDependencies when Firebase wasn't linked.
18+
private val sink: CrashKiOSCrashlyticsSinkProtocol = crashlyticsRegistry.requireSink()
1419

1520
actual override fun logMessage(message: String) {
16-
FIRCrashlyticsLog(message)
21+
sink.logMessage(message)
1722
}
1823

19-
@OptIn(UnsafeNumber::class)
2024
actual override fun sendHandledException(throwable: Throwable) {
21-
val exceptionClassName = throwable::class.qualifiedName ?: throwable::class.simpleName ?: "kotlin.Throwable"
22-
FIRCrashlyticsRecordHandledException(
23-
exceptionClassName,
24-
throwable.message ?: "",
25-
throwable.getFilteredStackTraceAddresses().map {
26-
FIRStackFrameWithAddress(it.convert())
27-
},
25+
sink.recordHandledExceptionWithName(
26+
name = throwable.throwableName,
27+
reason = throwable.message ?: "",
28+
stackAddresses = throwable.getFilteredStackTraceAddresses(),
2829
)
2930
}
3031

3132
actual override fun sendFatalException(throwable: Throwable) {
32-
val exception = throwable.asNSException(true)
33-
// The recorded exception is persisted, so we can safely terminate afterwards.
34-
// https://github.com/firebase/firebase-ios-sdk/blob/82f163bd86566f83c5d7572a1c2c0024a04eb4dc/Crashlytics/Crashlytics/Handlers/FIRCLSException.mm#L227
35-
tryFIRCLSExceptionRecordNSException(exception)
33+
// The sink persists synchronously (FIRCLSExceptionRecordNSException),
34+
// so the caller can safely terminate afterwards.
35+
sink.recordFatalException(throwable.asNSException(true))
3636
}
3737

3838
actual override fun setCustomValue(key: String, value: Any) {
39-
FIRCrashlyticsSetCustomValue(key, value)
39+
sink.setCustomValue(value, forKey = key)
4040
}
4141

4242
actual override fun setUserId(identifier: String) {
43-
FIRCrashlyticsSetUserID(identifier)
43+
sink.setUserId(identifier)
4444
}
4545

4646
actual override fun setCollectionEnabled(enabled: Boolean) {
47-
FIRCrashlyticsSetCollectionEnabled(enabled)
47+
sink.setCollectionEnabled(enabled)
4848
}
4949
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
@file:OptIn(ExperimentalForeignApi::class)
2+
3+
package co.touchlab.crashkios.crashlytics
4+
5+
import co.touchlab.crashkios.crashlytics.objc.CrashKiOSCrashlyticsSinkProtocol
6+
import kotlin.test.Test
7+
import kotlin.test.assertEquals
8+
import kotlin.test.assertTrue
9+
import kotlinx.cinterop.ExperimentalForeignApi
10+
import platform.Foundation.NSException
11+
import platform.darwin.NSObject
12+
13+
// Kotlin stand-in for the Swift sink: exercises the same ObjC-protocol boundary and
14+
// proves the module links with zero linker flags (the old -U / RND-91 failure mode).
15+
private class FakeCrashlyticsSink :
16+
NSObject(),
17+
CrashKiOSCrashlyticsSinkProtocol {
18+
val logs = mutableListOf<String>()
19+
val handled = mutableListOf<Triple<String, String, List<*>>>()
20+
val fatals = mutableListOf<NSException>()
21+
val custom = mutableMapOf<String, Any?>()
22+
var userId: String? = null
23+
var collectionEnabled: Boolean? = null
24+
25+
override fun logMessage(message: String) {
26+
logs += message
27+
}
28+
29+
override fun recordHandledExceptionWithName(name: String, reason: String, stackAddresses: List<*>) {
30+
handled += Triple(name, reason, stackAddresses)
31+
}
32+
33+
override fun recordFatalException(exception: NSException) {
34+
fatals += exception
35+
}
36+
37+
override fun setCustomValue(value: Any?, forKey: String) {
38+
custom[forKey] = value
39+
}
40+
41+
override fun setUserId(identifier: String) {
42+
userId = identifier
43+
}
44+
45+
override fun setCollectionEnabled(enabled: Boolean) {
46+
collectionEnabled = enabled
47+
}
48+
}
49+
50+
class CrashlyticsSinkTest {
51+
@Test
52+
fun facadeForwardsToRegisteredSink() {
53+
val sink = FakeCrashlyticsSink()
54+
registerCrashlyticsSink(sink)
55+
56+
CrashlyticsKotlin.logMessage("hello")
57+
CrashlyticsKotlin.setCustomValue("answer", "42")
58+
CrashlyticsKotlin.setUserId("user1")
59+
CrashlyticsKotlin.setCollectionEnabled(true)
60+
CrashlyticsKotlin.sendHandledException(RuntimeException("boom"))
61+
CrashlyticsKotlin.sendFatalException(RuntimeException("fatal", IllegalStateException("root cause")))
62+
63+
assertEquals(listOf("hello"), sink.logs)
64+
assertEquals("42", sink.custom["answer"]?.toString())
65+
assertEquals("user1", sink.userId)
66+
assertEquals(true, sink.collectionEnabled)
67+
68+
val (name, reason, addresses) = sink.handled.single()
69+
assertEquals("kotlin.RuntimeException", name)
70+
assertEquals("boom", reason)
71+
assertTrue(addresses.isNotEmpty(), "handled exception should carry stack addresses")
72+
73+
val fatal = sink.fatals.single()
74+
assertEquals("kotlin.RuntimeException", fatal.name)
75+
assertTrue(fatal.reason!!.contains("fatal"))
76+
assertTrue(fatal.reason!!.contains("Caused by: kotlin.IllegalStateException: root cause"))
77+
assertTrue(fatal.callStackReturnAddresses.isNotEmpty(), "fatal exception should carry stack addresses")
78+
}
79+
}

‎crashlytics/src/commonMain/kotlin/co/touchlab/crashkios/crashlytics/CrashlyticsKotlin.kt‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,11 @@ object CrashlyticsKotlin {
3131
}
3232

3333
/**
34-
* Call in startup code in an actual app. Tests should generally skip this. In Kotlin/Native, not calling this
35-
* for tests avoids linker issues.
34+
* Call in startup code on Android. Tests should generally skip this.
35+
*
36+
* On Apple targets this alone is NOT enough: a Swift sink must be registered via
37+
* `registerCrashlyticsSink()` (which also sets the implementation, making this call
38+
* redundant there) — otherwise events are dropped with an NSLog warning.
3639
*/
3740
fun enableCrashlytics() {
3841
CrashlyticsKotlin.implementation = CrashlyticsCallsActual()

0 commit comments

Comments
 (0)