Skip to content

Commit c5e77bb

Browse files
Rewrite bugsnag module
1 parent acda7b2 commit c5e77bb

18 files changed

Lines changed: 195 additions & 543 deletions

File tree

‎bugsnag/build.gradle.kts‎

Lines changed: 2 additions & 10 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.bugsnag.android)
@@ -79,10 +73,8 @@ kotlin {
7973
val mainCompilation = compilations.getByName("main")
8074

8175
mainCompilation.cinterops.create("bugsnag") {
82-
includeDirs("$projectDir/src/include")
83-
includeDirs("$projectDir/src/include/private")
84-
compilerOpts("-DNS_FORMAT_ARGUMENT(A)=", "-D_Nullable_result=_Nullable")
85-
// extraOpts("-mode", "sourcecode")
76+
// Protocol-only header owned by the Swift package — no SDK symbols.
77+
includeDirs("$rootDir/Sources/CrashKiOSBugsnagObjC/include")
8678
}
8779
}
8880
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
@file:OptIn(ExperimentalForeignApi::class)
2+
3+
package co.touchlab.crashkios.bugsnag
4+
5+
import co.touchlab.crashkios.bugsnag.objc.CrashKiOSBugsnagSinkProtocol
6+
import kotlinx.cinterop.ExperimentalForeignApi
7+
8+
/**
9+
* Registers the Swift-implemented [sink] that forwards CrashKiOS events to Bugsnag,
10+
* and installs the unhandled-exception hook so unhandled Kotlin exceptions are
11+
* reported as fatal crashes.
12+
*
13+
* Call once, from Swift, at startup. Start Bugsnag through the shipped sink so the
14+
* configuration suppresses the duplicate termination crash:
15+
* ```swift
16+
* let sink = BugsnagSink.start(BugsnagConfiguration.loadConfig())
17+
* BugsnagKt.registerBugsnagSink(sink: sink)
18+
* ```
19+
* `BugsnagSink` ships in the `CrashKiOSBugsnag` Swift package (this repo's
20+
* `Package.swift`); custom sink implementations must call
21+
* `configureBugsnagForKotlin(config)` (from the same package) before `Bugsnag.start`
22+
* to keep the duplicate-crash suppression. Add
23+
* `export("co.touchlab.crashkios:bugsnag")` to your framework configuration for
24+
* clean unmangled names.
25+
*
26+
* Replaces `startBugsnag()` / `configureBugsnag()` / `setBugsnagUnhandledExceptionHook()`,
27+
* which were removed along with the Bugsnag cinterop — Bugsnag start and configuration
28+
* now live in Swift.
29+
*
30+
* Calling `enableBugsnag()` (or constructing `BugsnagCallsActual`) on an Apple target
31+
* WITHOUT having registered a sink fails fast with a descriptive error rather than
32+
* silently dropping crash reports.
33+
*/
34+
public fun registerBugsnagSink(sink: CrashKiOSBugsnagSinkProtocol) {
35+
bugsnagRegistry.register(sink, fatalHook(sink))
36+
BugsnagKotlin.implementation = BugsnagCallsActual()
37+
}
38+
39+
/**
40+
* The terminating-hook body: reports the exception, then marks the session so the
41+
* sink's OnSendError filter drops Bugsnag's own report of the termination abort that
42+
* follows. Only the terminating hook path marks: a direct sendFatalException() call
43+
* must NOT poison the session (the caller may keep running, and later genuine crashes
44+
* would be discarded).
45+
*
46+
* A plain function rather than an inline lambda so tests can exercise the
47+
* notify-then-mark sequencing directly, without going through the real
48+
* process-terminating unhandled-exception hook.
49+
*/
50+
internal fun fatalHook(sink: CrashKiOSBugsnagSinkProtocol): (Throwable) -> Unit = { throwable ->
51+
BugsnagKotlin.sendFatalException(throwable)
52+
sink.markFatalCrashRecorded()
53+
}
Lines changed: 20 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,36 @@
1+
@file:OptIn(ExperimentalForeignApi::class)
2+
13
package co.touchlab.crashkios.bugsnag
24

3-
import com.rickclephas.kmp.nsexceptionkt.core.asNSException
4-
import com.rickclephas.kmp.nsexceptionkt.core.causes
5+
import co.touchlab.crashkios.bugsnag.objc.CrashKiOSBugsnagSinkProtocol
6+
import co.touchlab.crashkios.core.CrashSinkRegistry
7+
import co.touchlab.crashkios.core.asNSException
8+
import co.touchlab.crashkios.core.causes
59
import kotlinx.cinterop.ExperimentalForeignApi
610

7-
@OptIn(ExperimentalForeignApi::class)
11+
internal val bugsnagRegistry = CrashSinkRegistry<CrashKiOSBugsnagSinkProtocol>("Bugsnag")
12+
813
actual class BugsnagCallsActual : BugsnagCalls {
14+
// Fail-fast: an implementation constructed without a registered Swift sink would
15+
// silently lose every event — refuse loudly instead.
16+
private val sink: CrashKiOSBugsnagSinkProtocol = bugsnagRegistry.requireSink()
17+
918
actual override fun logMessage(message: String) {
10-
Bugsnag.leaveBreadcrumbWithMessage(message)
19+
sink.leaveBreadcrumb(message)
1120
}
1221

13-
actual override fun sendHandledException(throwable: Throwable) {
14-
sendException(throwable, true)
15-
}
22+
actual override fun sendHandledException(throwable: Throwable) = sendException(throwable, true)
1623

17-
actual override fun sendFatalException(throwable: Throwable) {
18-
sendException(throwable, false)
19-
}
24+
actual override fun sendFatalException(throwable: Throwable) = sendException(throwable, false)
2025

2126
actual override fun setCustomValue(section: String, key: String, value: Any) {
22-
Bugsnag.addMetadata(value, key, section)
27+
sink.addMetadata(value, key = key, section = section)
2328
}
2429

2530
private fun sendException(throwable: Throwable, handled: Boolean) {
26-
val exception = throwable.asNSException()
27-
val causes = throwable.causes.map { it.asNSException() }
28-
// Notify will persist unhandled events, so we can safely terminate afterwards.
29-
// https://github.com/bugsnag/bugsnag-cocoa/blob/6bcd46f5f8dc06ac26537875d501f02b27d219a9/Bugsnag/Client/BugsnagClient.m#L744
30-
Bugsnag.notify(exception) { event ->
31-
if (event == null) return@notify true
32-
33-
if (handled) {
34-
event.severity = BSGSeverity.BSGSeverityWarning
35-
} else {
36-
event.unhandled = true
37-
event.severity = BSGSeverity.BSGSeverityError
38-
}
39-
40-
if (causes.isNotEmpty()) {
41-
event.errors += causes.map { it.asBugsnagError() }
42-
}
43-
44-
true
45-
}
31+
val exceptions = listOf(throwable.asNSException()) + throwable.causes.map { it.asNSException() }
32+
// The sink persists unhandled events synchronously (Bugsnag.notify),
33+
// so the caller can safely terminate afterwards.
34+
sink.notifyWithExceptions(exceptions, handled = handled)
4635
}
4736
}

‎bugsnag/src/appleMain/kotlin/co/touchlab/crashkios/bugsnag/BugsnagConfig.kt‎

Lines changed: 0 additions & 67 deletions
This file was deleted.
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
@file:OptIn(ExperimentalForeignApi::class)
2+
3+
package co.touchlab.crashkios.bugsnag
4+
5+
import co.touchlab.crashkios.bugsnag.objc.CrashKiOSBugsnagSinkProtocol
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 FakeBugsnagSink :
16+
NSObject(),
17+
CrashKiOSBugsnagSinkProtocol {
18+
val breadcrumbs = mutableListOf<String>()
19+
val notifications = mutableListOf<Pair<List<*>, Boolean>>()
20+
val metadata = mutableListOf<Triple<Any?, String, String>>()
21+
var fatalMarks = 0
22+
23+
// Call order across notify/mark — proves the hook sequences them correctly,
24+
// not just that both eventually happened.
25+
val events = mutableListOf<String>()
26+
27+
override fun leaveBreadcrumb(message: String) {
28+
breadcrumbs += message
29+
}
30+
31+
override fun markFatalCrashRecorded() {
32+
fatalMarks++
33+
events += "mark"
34+
}
35+
36+
override fun notifyWithExceptions(exceptions: List<*>, handled: Boolean) {
37+
notifications += exceptions to handled
38+
events += "notify"
39+
}
40+
41+
override fun addMetadata(value: Any, key: String, section: String) {
42+
metadata += Triple(value, key, section)
43+
}
44+
}
45+
46+
class BugsnagSinkTest {
47+
// registerBugsnagSink() mutates the module-level `bugsnagRegistry` singleton. Safe
48+
// to call from every test that needs BugsnagKotlin's facade routed to its own sink
49+
// (sinkRef always overwrites) — NOT safe to rely on for the real unhandled-exception
50+
// hook actually firing with a given test's sink: hook-install is a once-ever guard,
51+
// permanently bound to whichever sink registered first. That's why fatalHookNotifiesThenMarksSession
52+
// below calls fatalHook() directly instead of triggering the real hook.
53+
@Test
54+
fun facadeForwardsToRegisteredSink() {
55+
val sink = FakeBugsnagSink()
56+
registerBugsnagSink(sink)
57+
58+
BugsnagKotlin.logMessage("crumb")
59+
BugsnagKotlin.setCustomValue("section1", "key1", "value1")
60+
BugsnagKotlin.sendHandledException(RuntimeException("handled boom"))
61+
BugsnagKotlin.sendFatalException(RuntimeException("fatal boom", IllegalStateException("root cause")))
62+
63+
assertEquals(listOf("crumb"), sink.breadcrumbs)
64+
65+
val (value, key, section) = sink.metadata.single()
66+
assertEquals("value1", value?.toString())
67+
assertEquals("key1", key)
68+
assertEquals("section1", section)
69+
70+
assertEquals(2, sink.notifications.size)
71+
val (handledExceptions, handledFlag) = sink.notifications[0]
72+
assertTrue(handledFlag)
73+
assertEquals(1, handledExceptions.size)
74+
assertEquals("kotlin.RuntimeException", (handledExceptions.single() as NSException).name)
75+
76+
val (fatalExceptions, fatalFlag) = sink.notifications[1]
77+
assertEquals(false, fatalFlag)
78+
assertEquals(2, fatalExceptions.size, "fatal should carry the cause chain")
79+
assertEquals("kotlin.IllegalStateException", (fatalExceptions[1] as NSException).name)
80+
81+
// Only the terminating unhandled-exception hook may mark the session —
82+
// a direct sendFatalException() must not (it would poison the OnSendError filter).
83+
assertEquals(0, sink.fatalMarks)
84+
}
85+
86+
@Test
87+
fun fatalHookNotifiesThenMarksSession() {
88+
// fatalHook() is the terminating hook's actual body (see Bugsnag.kt), exercised
89+
// directly rather than through wrapUnhandledExceptionHook — invoking the real
90+
// hook would terminate the process.
91+
val sink = FakeBugsnagSink()
92+
// Rebinds BugsnagKotlin.implementation to this sink (register() always
93+
// overwrites sinkRef) so fatalHook's sendFatalException() call routes here
94+
// rather than to whatever sink an earlier test left registered. Does NOT wire
95+
// this sink into the real unhandled-exception hook — that binds once, to
96+
// whichever sink registers first — which is exactly why fatalHook is called
97+
// directly below instead of relying on the real hook firing.
98+
registerBugsnagSink(sink)
99+
100+
fatalHook(sink)(RuntimeException("terminating boom"))
101+
102+
assertEquals(1, sink.fatalMarks)
103+
assertEquals(1, sink.notifications.size)
104+
// Order matters: markFatalCrashRecorded() must run AFTER notify, never before —
105+
// marking first would let the OnSendError filter drop a report that was never sent.
106+
assertEquals(listOf("notify", "mark"), sink.events)
107+
}
108+
}

‎bugsnag/src/commonMain/kotlin/co/touchlab/crashkios/bugsnag/BugsnagKotlin.kt‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,11 @@ object BugsnagKotlin {
2323
}
2424

2525
/**
26-
* Call in startup code in an actual app. Tests should generally skip this. In Kotlin/Native, not calling this
27-
* for tests avoids linker issues.
26+
* Call in startup code on Android. Tests should generally skip this.
27+
*
28+
* On Apple targets this alone is NOT enough: a Swift sink must be registered via
29+
* `registerBugsnagSink()` (which also sets the implementation, making this call
30+
* redundant there) — otherwise events are dropped with an NSLog warning.
2831
*/
2932
fun enableBugsnag() {
3033
BugsnagKotlin.implementation = BugsnagCallsActual()

0 commit comments

Comments
 (0)