@app-swiss-knife/react-native-sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +182 -0
- package/SwissKnifePurchases.podspec +40 -0
- package/android/build.gradle +89 -0
- package/android/gradle.properties +3 -0
- package/android/src/main/AndroidManifest.xml +26 -0
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +216 -0
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingPackage.kt +17 -0
- package/android/src/main/java/com/swissknife/purchases/Conversions.kt +15 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +371 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +497 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesPackage.kt +25 -0
- package/android/vendor/GENERATED.md +10 -0
- package/android/vendor/java/com/appswissknife/SwissKnife.kt +533 -0
- package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +326 -0
- package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +296 -0
- package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +503 -0
- package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +188 -0
- package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +204 -0
- package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +447 -0
- package/android/vendor/java/com/appswissknife/context/AppLifecycle.kt +120 -0
- package/android/vendor/java/com/appswissknife/context/Clock.kt +70 -0
- package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +138 -0
- package/android/vendor/java/com/appswissknife/context/IDs.kt +55 -0
- package/android/vendor/java/com/appswissknife/context/Reachability.kt +145 -0
- package/android/vendor/java/com/appswissknife/context/Session.kt +192 -0
- package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +945 -0
- package/android/vendor/java/com/appswissknife/crashreporting/SKScreenshot.kt +201 -0
- package/android/vendor/java/com/appswissknife/device/DeviceID.kt +172 -0
- package/android/vendor/java/com/appswissknife/diagnostics/SKLog.kt +97 -0
- package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +495 -0
- package/android/vendor/java/com/appswissknife/identity/Identity.kt +522 -0
- package/android/vendor/java/com/appswissknife/models/CustomerInfo.kt +67 -0
- package/android/vendor/java/com/appswissknife/models/Enums.kt +35 -0
- package/android/vendor/java/com/appswissknife/models/Offerings.kt +80 -0
- package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +89 -0
- package/android/vendor/java/com/appswissknife/models/StoreTransaction.kt +17 -0
- package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +507 -0
- package/android/vendor/java/com/appswissknife/net/ExponentialBackoff.kt +69 -0
- package/android/vendor/java/com/appswissknife/net/IngestClient.kt +582 -0
- package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +320 -0
- package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +219 -0
- package/android/vendor/java/com/appswissknife/performance/SKFrameTracker.kt +94 -0
- package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +428 -0
- package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +560 -0
- package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +100 -0
- package/android/vendor/java/com/appswissknife/purchases/PriceEnrichmentProvider.kt +36 -0
- package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +120 -0
- package/android/vendor/res/xml/swissknife_data_extraction_rules.xml +20 -0
- package/ios/SwissKnifeCrashReporting.m +32 -0
- package/ios/SwissKnifeCrashReporting.swift +186 -0
- package/ios/SwissKnifeJSON.swift +347 -0
- package/ios/SwissKnifePurchases.m +124 -0
- package/ios/SwissKnifePurchases.swift +523 -0
- package/ios/vendor/GENERATED.md +10 -0
- package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +488 -0
- package/ios/vendor/SwissKnifeiOS/AttributesClient.swift +460 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/Attribution.swift +307 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/AttributionNetwork.swift +92 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/AttributionState.swift +141 -0
- package/ios/vendor/SwissKnifeiOS/Context/AppLifecycle.swift +130 -0
- package/ios/vendor/SwissKnifeiOS/Context/Clock.swift +100 -0
- package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +190 -0
- package/ios/vendor/SwissKnifeiOS/Context/IDs.swift +64 -0
- package/ios/vendor/SwissKnifeiOS/Context/Reachability.swift +121 -0
- package/ios/vendor/SwissKnifeiOS/Context/Session.swift +223 -0
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +1287 -0
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKScreenshot.swift +175 -0
- package/ios/vendor/SwissKnifeiOS/DeviceID.swift +161 -0
- package/ios/vendor/SwissKnifeiOS/Diagnostics/SKLog.swift +128 -0
- package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +323 -0
- package/ios/vendor/SwissKnifeiOS/Identity/IdentityNetwork.swift +70 -0
- package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +329 -0
- package/ios/vendor/SwissKnifeiOS/Net/ExponentialBackoff.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +681 -0
- package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +409 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKFrameTracker.swift +89 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +440 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKURLSessionDelegate.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +646 -0
- package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +458 -0
- package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +374 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+Analytics.swift +46 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+DeviceID.swift +30 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+Session.swift +47 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +417 -0
- package/ios/vendor/SwissKnifeiOS/Types.swift +496 -0
- package/lib/commonjs/attribution.js +55 -0
- package/lib/commonjs/attribution.js.map +1 -0
- package/lib/commonjs/identity.js +126 -0
- package/lib/commonjs/identity.js.map +1 -0
- package/lib/commonjs/index.js +118 -0
- package/lib/commonjs/index.js.map +1 -0
- package/lib/commonjs/modules/analytics.js +646 -0
- package/lib/commonjs/modules/analytics.js.map +1 -0
- package/lib/commonjs/modules/attachments.js +169 -0
- package/lib/commonjs/modules/attachments.js.map +1 -0
- package/lib/commonjs/modules/crash-reporting.js +1327 -0
- package/lib/commonjs/modules/crash-reporting.js.map +1 -0
- package/lib/commonjs/modules/ids.js +50 -0
- package/lib/commonjs/modules/ids.js.map +1 -0
- package/lib/commonjs/modules/log.js +59 -0
- package/lib/commonjs/modules/log.js.map +1 -0
- package/lib/commonjs/modules/offline-store.js +44 -0
- package/lib/commonjs/modules/offline-store.js.map +1 -0
- package/lib/commonjs/modules/performance.js +494 -0
- package/lib/commonjs/modules/performance.js.map +1 -0
- package/lib/commonjs/native/module.js +41 -0
- package/lib/commonjs/native/module.js.map +1 -0
- package/lib/commonjs/native/spec.js +26 -0
- package/lib/commonjs/native/spec.js.map +1 -0
- package/lib/commonjs/package.json +1 -0
- package/lib/commonjs/purchases.js +194 -0
- package/lib/commonjs/purchases.js.map +1 -0
- package/lib/commonjs/types.js +236 -0
- package/lib/commonjs/types.js.map +1 -0
- package/lib/module/attribution.js +51 -0
- package/lib/module/attribution.js.map +1 -0
- package/lib/module/identity.js +122 -0
- package/lib/module/identity.js.map +1 -0
- package/lib/module/index.js +36 -0
- package/lib/module/index.js.map +1 -0
- package/lib/module/modules/analytics.js +642 -0
- package/lib/module/modules/analytics.js.map +1 -0
- package/lib/module/modules/attachments.js +162 -0
- package/lib/module/modules/attachments.js.map +1 -0
- package/lib/module/modules/crash-reporting.js +1320 -0
- package/lib/module/modules/crash-reporting.js.map +1 -0
- package/lib/module/modules/ids.js +44 -0
- package/lib/module/modules/ids.js.map +1 -0
- package/lib/module/modules/log.js +54 -0
- package/lib/module/modules/log.js.map +1 -0
- package/lib/module/modules/offline-store.js +39 -0
- package/lib/module/modules/offline-store.js.map +1 -0
- package/lib/module/modules/performance.js +491 -0
- package/lib/module/modules/performance.js.map +1 -0
- package/lib/module/native/module.js +34 -0
- package/lib/module/native/module.js.map +1 -0
- package/lib/module/native/spec.js +22 -0
- package/lib/module/native/spec.js.map +1 -0
- package/lib/module/package.json +1 -0
- package/lib/module/purchases.js +187 -0
- package/lib/module/purchases.js.map +1 -0
- package/lib/module/types.js +230 -0
- package/lib/module/types.js.map +1 -0
- package/lib/typescript/commonjs/attribution.d.ts +24 -0
- package/lib/typescript/commonjs/attribution.d.ts.map +1 -0
- package/lib/typescript/commonjs/identity.d.ts +37 -0
- package/lib/typescript/commonjs/identity.d.ts.map +1 -0
- package/lib/typescript/commonjs/index.d.ts +15 -0
- package/lib/typescript/commonjs/index.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts +127 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/attachments.d.ts +50 -0
- package/lib/typescript/commonjs/modules/attachments.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts +175 -0
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/ids.d.ts +17 -0
- package/lib/typescript/commonjs/modules/ids.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/log.d.ts +12 -0
- package/lib/typescript/commonjs/modules/log.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/offline-store.d.ts +9 -0
- package/lib/typescript/commonjs/modules/offline-store.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/performance.d.ts +75 -0
- package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -0
- package/lib/typescript/commonjs/native/module.d.ts +6 -0
- package/lib/typescript/commonjs/native/module.d.ts.map +1 -0
- package/lib/typescript/commonjs/native/spec.d.ts +119 -0
- package/lib/typescript/commonjs/native/spec.d.ts.map +1 -0
- package/lib/typescript/commonjs/package.json +1 -0
- package/lib/typescript/commonjs/purchases.d.ts +68 -0
- package/lib/typescript/commonjs/purchases.d.ts.map +1 -0
- package/lib/typescript/commonjs/types.d.ts +384 -0
- package/lib/typescript/commonjs/types.d.ts.map +1 -0
- package/lib/typescript/module/attribution.d.ts +24 -0
- package/lib/typescript/module/attribution.d.ts.map +1 -0
- package/lib/typescript/module/identity.d.ts +37 -0
- package/lib/typescript/module/identity.d.ts.map +1 -0
- package/lib/typescript/module/index.d.ts +15 -0
- package/lib/typescript/module/index.d.ts.map +1 -0
- package/lib/typescript/module/modules/analytics.d.ts +127 -0
- package/lib/typescript/module/modules/analytics.d.ts.map +1 -0
- package/lib/typescript/module/modules/attachments.d.ts +50 -0
- package/lib/typescript/module/modules/attachments.d.ts.map +1 -0
- package/lib/typescript/module/modules/crash-reporting.d.ts +175 -0
- package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -0
- package/lib/typescript/module/modules/ids.d.ts +17 -0
- package/lib/typescript/module/modules/ids.d.ts.map +1 -0
- package/lib/typescript/module/modules/log.d.ts +12 -0
- package/lib/typescript/module/modules/log.d.ts.map +1 -0
- package/lib/typescript/module/modules/offline-store.d.ts +9 -0
- package/lib/typescript/module/modules/offline-store.d.ts.map +1 -0
- package/lib/typescript/module/modules/performance.d.ts +75 -0
- package/lib/typescript/module/modules/performance.d.ts.map +1 -0
- package/lib/typescript/module/native/module.d.ts +6 -0
- package/lib/typescript/module/native/module.d.ts.map +1 -0
- package/lib/typescript/module/native/spec.d.ts +119 -0
- package/lib/typescript/module/native/spec.d.ts.map +1 -0
- package/lib/typescript/module/package.json +1 -0
- package/lib/typescript/module/purchases.d.ts +68 -0
- package/lib/typescript/module/purchases.d.ts.map +1 -0
- package/lib/typescript/module/types.d.ts +384 -0
- package/lib/typescript/module/types.d.ts.map +1 -0
- package/package.json +115 -0
- package/react-native.config.js +23 -0
- package/src/attribution.ts +56 -0
- package/src/identity.ts +133 -0
- package/src/index.ts +54 -0
- package/src/modules/analytics.ts +689 -0
- package/src/modules/attachments.ts +222 -0
- package/src/modules/crash-reporting.ts +1577 -0
- package/src/modules/ids.ts +41 -0
- package/src/modules/log.ts +56 -0
- package/src/modules/offline-store.ts +51 -0
- package/src/modules/performance.ts +589 -0
- package/src/native/module.ts +47 -0
- package/src/native/spec.ts +183 -0
- package/src/purchases.ts +214 -0
- package/src/types.ts +470 -0
|
@@ -0,0 +1,945 @@
|
|
|
1
|
+
// packages/swiss-knife-android/src/main/java/com/appswissknife/crashreporting/SKCrashReporting.kt
|
|
2
|
+
//
|
|
3
|
+
// Sentry-compatible crash reporting SDK for swiss-knife (Android).
|
|
4
|
+
// Captures uncaught JVM exceptions, ANRs, and breadcrumbs.
|
|
5
|
+
// On next init(), any pending crash is sent before normal operation resumes.
|
|
6
|
+
|
|
7
|
+
package com.appswissknife.crashreporting
|
|
8
|
+
|
|
9
|
+
import android.app.ActivityManager
|
|
10
|
+
import android.app.ApplicationExitInfo
|
|
11
|
+
import android.content.Context
|
|
12
|
+
import android.net.ConnectivityManager
|
|
13
|
+
import android.net.Network
|
|
14
|
+
import android.net.NetworkCapabilities
|
|
15
|
+
import android.os.Build
|
|
16
|
+
import android.os.Handler
|
|
17
|
+
import android.os.Looper
|
|
18
|
+
import org.json.JSONArray
|
|
19
|
+
import org.json.JSONObject
|
|
20
|
+
import java.io.File
|
|
21
|
+
import java.text.SimpleDateFormat
|
|
22
|
+
import java.util.Date
|
|
23
|
+
import java.util.Locale
|
|
24
|
+
import java.util.concurrent.CopyOnWriteArrayList
|
|
25
|
+
import com.appswissknife.context.IDs
|
|
26
|
+
import java.util.concurrent.Executors
|
|
27
|
+
|
|
28
|
+
// MARK: - Supporting Types
|
|
29
|
+
|
|
30
|
+
enum class SKErrorLevel { DEBUG, INFO, WARNING, ERROR, FATAL }
|
|
31
|
+
|
|
32
|
+
data class SKStackFrame(
|
|
33
|
+
val filename: String? = null,
|
|
34
|
+
val function: String? = null,
|
|
35
|
+
val module: String? = null,
|
|
36
|
+
val lineno: Int? = null,
|
|
37
|
+
val colno: Int? = null,
|
|
38
|
+
val instructionAddress: String? = null,
|
|
39
|
+
val inApp: Boolean = true
|
|
40
|
+
) {
|
|
41
|
+
fun toJSON(): JSONObject = JSONObject().apply {
|
|
42
|
+
filename?.let { put("filename", it) }
|
|
43
|
+
function?.let { put("function", it) }
|
|
44
|
+
module?.let { put("module", it) }
|
|
45
|
+
lineno?.let { put("lineno", it) }
|
|
46
|
+
colno?.let { put("colno", it) }
|
|
47
|
+
instructionAddress?.let { put("instructionAddress", it) }
|
|
48
|
+
put("inApp", inApp)
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
data class SKBreadcrumb(
|
|
53
|
+
val timestamp: Long = System.currentTimeMillis(),
|
|
54
|
+
val category: String? = null,
|
|
55
|
+
val message: String? = null,
|
|
56
|
+
val level: SKErrorLevel = SKErrorLevel.INFO,
|
|
57
|
+
val data: Map<String, String>? = null
|
|
58
|
+
) {
|
|
59
|
+
fun toJSON(): JSONObject = JSONObject().apply {
|
|
60
|
+
put("timestamp", ISO_DATE.format(Date(timestamp)))
|
|
61
|
+
category?.let { put("category", it) }
|
|
62
|
+
message?.let { put("message", it) }
|
|
63
|
+
put("level", level.name.lowercase())
|
|
64
|
+
data?.let { put("data", JSONObject(it as Map<*, *>)) }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
companion object {
|
|
68
|
+
private val ISO_DATE = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
data class SKUser(
|
|
73
|
+
val id: String? = null,
|
|
74
|
+
val email: String? = null,
|
|
75
|
+
val username: String? = null
|
|
76
|
+
) {
|
|
77
|
+
fun toJSON(): JSONObject = JSONObject().apply {
|
|
78
|
+
id?.let { put("id", it) }
|
|
79
|
+
email?.let { put("email", it) }
|
|
80
|
+
username?.let { put("username", it) }
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* A single entry in the exception cause chain.
|
|
86
|
+
* Mirrors Sentry's exception array: the first entry is the top-level
|
|
87
|
+
* exception, subsequent entries are causes.
|
|
88
|
+
*/
|
|
89
|
+
data class SKExceptionEntry(
|
|
90
|
+
val type: String,
|
|
91
|
+
val value: String,
|
|
92
|
+
val stacktrace: List<SKStackFrame>
|
|
93
|
+
) {
|
|
94
|
+
fun toJSON(): JSONObject = JSONObject().apply {
|
|
95
|
+
put("type", type)
|
|
96
|
+
put("value", value)
|
|
97
|
+
put("stacktrace", JSONArray(stacktrace.map { it.toJSON() }))
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
data class SKErrorEvent(
|
|
102
|
+
val eventId: String = IDs.eventId(),
|
|
103
|
+
val timestamp: Long = System.currentTimeMillis(),
|
|
104
|
+
var level: SKErrorLevel = SKErrorLevel.ERROR,
|
|
105
|
+
var message: String? = null,
|
|
106
|
+
var exceptionType: String? = null,
|
|
107
|
+
var exceptionValue: String? = null,
|
|
108
|
+
var stacktrace: List<SKStackFrame>? = null,
|
|
109
|
+
/** Full exception cause chain (top-level + all causes). */
|
|
110
|
+
var exceptions: List<SKExceptionEntry>? = null,
|
|
111
|
+
var breadcrumbs: List<SKBreadcrumb>? = null,
|
|
112
|
+
var tags: Map<String, String>? = null,
|
|
113
|
+
var extra: Map<String, String>? = null,
|
|
114
|
+
var user: SKUser? = null,
|
|
115
|
+
var environment: String? = null,
|
|
116
|
+
var release: String? = null,
|
|
117
|
+
// Device / OS / app fields used to live here. Dropped — the envelope-level
|
|
118
|
+
// `ContextSnapshot.device` already carries `deviceModel`, `osVersion`,
|
|
119
|
+
// `appVersion`, `bundleIdentifier` (Android: packageName). Duplicating
|
|
120
|
+
// them in the data payload made every error event ~4 keys heavier with
|
|
121
|
+
// the exact same values. `environment` / `release` stay — they are
|
|
122
|
+
// SDK-config specific and not envelope-derived.
|
|
123
|
+
var mechanism: String? = null,
|
|
124
|
+
val platform: String = "java"
|
|
125
|
+
) {
|
|
126
|
+
fun toJSON(): JSONObject = JSONObject().apply {
|
|
127
|
+
put("eventId", eventId)
|
|
128
|
+
put("timestamp", ISO_DATE.format(Date(timestamp)))
|
|
129
|
+
put("level", level.name.lowercase())
|
|
130
|
+
message?.let { put("message", it) }
|
|
131
|
+
exceptionType?.let { put("exceptionType", it) }
|
|
132
|
+
exceptionValue?.let { put("exceptionValue", it) }
|
|
133
|
+
stacktrace?.let { frames ->
|
|
134
|
+
put("stacktrace", JSONArray(frames.map { it.toJSON() }))
|
|
135
|
+
}
|
|
136
|
+
exceptions?.let { chain ->
|
|
137
|
+
put("exceptions", JSONArray(chain.map { it.toJSON() }))
|
|
138
|
+
}
|
|
139
|
+
breadcrumbs?.let { crumbs ->
|
|
140
|
+
put("breadcrumbs", JSONArray(crumbs.map { it.toJSON() }))
|
|
141
|
+
}
|
|
142
|
+
tags?.let { put("tags", JSONObject(it as Map<*, *>)) }
|
|
143
|
+
extra?.let { put("extra", JSONObject(it as Map<*, *>)) }
|
|
144
|
+
user?.let { put("user", it.toJSON()) }
|
|
145
|
+
environment?.let { put("environment", it) }
|
|
146
|
+
release?.let { put("release", it) }
|
|
147
|
+
mechanism?.let { put("mechanism", it) }
|
|
148
|
+
put("platform", platform)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
companion object {
|
|
152
|
+
private val ISO_DATE = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// MARK: - Scope
|
|
157
|
+
|
|
158
|
+
class SKErrorScope {
|
|
159
|
+
internal val tags = mutableMapOf<String, String>()
|
|
160
|
+
internal val extra = mutableMapOf<String, String>()
|
|
161
|
+
internal var user: SKUser? = null
|
|
162
|
+
|
|
163
|
+
fun setTag(key: String, value: String) { tags[key] = value }
|
|
164
|
+
fun setExtra(key: String, value: Any) { extra[key] = value.toString() }
|
|
165
|
+
fun setUser(user: SKUser?) { this.user = user }
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// MARK: - Ring Buffer
|
|
169
|
+
|
|
170
|
+
internal class RingBuffer<T>(private val capacity: Int) {
|
|
171
|
+
private val buffer = CopyOnWriteArrayList<T>()
|
|
172
|
+
|
|
173
|
+
@Synchronized
|
|
174
|
+
fun append(element: T) {
|
|
175
|
+
if (buffer.size >= capacity) buffer.removeAt(0)
|
|
176
|
+
buffer.add(element)
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
fun snapshot(): List<T> = buffer.toList()
|
|
180
|
+
fun clear() = buffer.clear()
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// MARK: - ANR Watchdog
|
|
184
|
+
|
|
185
|
+
internal class AnrWatchdog(
|
|
186
|
+
private val timeoutMs: Long,
|
|
187
|
+
private val onAnr: (String) -> Unit
|
|
188
|
+
) {
|
|
189
|
+
private val executor = Executors.newSingleThreadExecutor()
|
|
190
|
+
private val mainHandler = Handler(Looper.getMainLooper())
|
|
191
|
+
@Volatile private var active = false
|
|
192
|
+
|
|
193
|
+
fun start() {
|
|
194
|
+
active = true
|
|
195
|
+
executor.execute {
|
|
196
|
+
while (active) {
|
|
197
|
+
var responded = false
|
|
198
|
+
mainHandler.post { responded = true }
|
|
199
|
+
Thread.sleep(timeoutMs)
|
|
200
|
+
if (active && !responded) {
|
|
201
|
+
// Main thread did not respond — capture its stack trace
|
|
202
|
+
val mainThread = Looper.getMainLooper().thread
|
|
203
|
+
val stackTrace = mainThread.stackTrace
|
|
204
|
+
.joinToString("\n") { "\tat ${it.className}.${it.methodName}(${it.fileName}:${it.lineNumber})" }
|
|
205
|
+
onAnr(stackTrace)
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
fun stop() {
|
|
212
|
+
active = false
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// MARK: - Main SDK
|
|
217
|
+
|
|
218
|
+
object SKCrashReporting {
|
|
219
|
+
|
|
220
|
+
fun interface BeforeSendCallback {
|
|
221
|
+
fun execute(event: SKErrorEvent): SKErrorEvent?
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
data class Configuration(
|
|
225
|
+
val apiKey: String,
|
|
226
|
+
val serverURL: String = "",
|
|
227
|
+
val environment: String = "production",
|
|
228
|
+
val release: String? = null,
|
|
229
|
+
val maxBreadcrumbs: Int = 100,
|
|
230
|
+
val anrTimeoutMs: Long = 5000,
|
|
231
|
+
val beforeSend: BeforeSendCallback? = null,
|
|
232
|
+
val sampleRate: Double = 1.0,
|
|
233
|
+
val tracesSampleRate: Double = 1.0
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
private var config: Configuration? = null
|
|
237
|
+
private var appContext: Context? = null
|
|
238
|
+
private val scope = SKErrorScope()
|
|
239
|
+
private var breadcrumbs = RingBuffer<SKBreadcrumb>(100)
|
|
240
|
+
private var anrWatchdog: AnrWatchdog? = null
|
|
241
|
+
private var originalExceptionHandler: Thread.UncaughtExceptionHandler? = null
|
|
242
|
+
private val executor = Executors.newSingleThreadExecutor()
|
|
243
|
+
|
|
244
|
+
// Session tracking
|
|
245
|
+
//
|
|
246
|
+
// The session id is sourced from `Session.shared(context).current.id` —
|
|
247
|
+
// the same primitive that stamps envelope-level
|
|
248
|
+
// `ContextSnapshot.session_id`. Prior to this fix SKCrashReporting minted
|
|
249
|
+
// its own `sessionId` via `IDs.sessionId()`, which diverged from the
|
|
250
|
+
// envelope and made session_event payloads disagree with their own
|
|
251
|
+
// enclosing envelope.
|
|
252
|
+
private var sessionErrorCount: Int = 0
|
|
253
|
+
|
|
254
|
+
// Event queue / envelope batching
|
|
255
|
+
private val pendingEvents = CopyOnWriteArrayList<SKErrorEvent>()
|
|
256
|
+
private var flushTimer: java.util.Timer? = null
|
|
257
|
+
private const val FLUSH_INTERVAL_MS = 30_000L
|
|
258
|
+
private const val FLUSH_THRESHOLD = 10
|
|
259
|
+
|
|
260
|
+
private val pendingCrashFile: File?
|
|
261
|
+
get() = appContext?.let { ctx ->
|
|
262
|
+
File(ctx.filesDir, "swiss-knife-crash/pending-crash.json")
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// MARK: - Init
|
|
266
|
+
|
|
267
|
+
fun init(context: Context, config: Configuration) {
|
|
268
|
+
val appCtx = context.applicationContext ?: context
|
|
269
|
+
this.config = config
|
|
270
|
+
this.appContext = appCtx
|
|
271
|
+
this.breadcrumbs = RingBuffer(config.maxBreadcrumbs)
|
|
272
|
+
|
|
273
|
+
// Send any crash from previous session
|
|
274
|
+
flushPendingCrash()
|
|
275
|
+
|
|
276
|
+
// Check for native crashes / ANRs from previous session via ApplicationExitInfo
|
|
277
|
+
// (Android 11+). This catches NDK native crashes and system-confirmed ANRs.
|
|
278
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
|
279
|
+
checkPreviousNativeCrashes(appCtx)
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// Install uncaught exception handler (chain with existing)
|
|
283
|
+
originalExceptionHandler = Thread.getDefaultUncaughtExceptionHandler()
|
|
284
|
+
Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
|
|
285
|
+
val event = buildCrashEvent(throwable)
|
|
286
|
+
writeCrashToDisk(event)
|
|
287
|
+
sendSessionEvent("crashed")
|
|
288
|
+
originalExceptionHandler?.uncaughtException(thread, throwable)
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// Auto-breadcrumbs: activity lifecycle + connectivity
|
|
292
|
+
registerActivityLifecycle(appCtx)
|
|
293
|
+
registerConnectivityObserver(appCtx)
|
|
294
|
+
|
|
295
|
+
// ANR watchdog
|
|
296
|
+
anrWatchdog?.stop()
|
|
297
|
+
anrWatchdog = AnrWatchdog(config.anrTimeoutMs) { stackTrace ->
|
|
298
|
+
val event = buildEvent(SKErrorLevel.ERROR).apply {
|
|
299
|
+
this.message = "Application Not Responding"
|
|
300
|
+
this.mechanism = "anr_watchdog"
|
|
301
|
+
// Parse the main thread's stack trace elements into structured frames
|
|
302
|
+
val mainThread = Looper.getMainLooper().thread
|
|
303
|
+
this.stacktrace = parseStackTraceElements(mainThread.stackTrace)
|
|
304
|
+
}
|
|
305
|
+
sendEvent(event)
|
|
306
|
+
}
|
|
307
|
+
anrWatchdog?.start()
|
|
308
|
+
|
|
309
|
+
// Start session tracking
|
|
310
|
+
startSession()
|
|
311
|
+
|
|
312
|
+
// Restore any persisted event queue from previous failed flush
|
|
313
|
+
restorePersistedQueue()
|
|
314
|
+
|
|
315
|
+
// Start periodic flush timer
|
|
316
|
+
startFlushTimer()
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// MARK: - Sampling & beforeSend
|
|
320
|
+
|
|
321
|
+
private fun applyBeforeSend(event: SKErrorEvent): SKErrorEvent? {
|
|
322
|
+
val cfg = config ?: return event
|
|
323
|
+
if (cfg.sampleRate < 1.0 && Math.random() > cfg.sampleRate) return null
|
|
324
|
+
cfg.beforeSend?.let { hook ->
|
|
325
|
+
return try { hook.execute(event) } catch (e: Exception) {
|
|
326
|
+
println("[SwissKnife CrashReporting] beforeSend threw: ${e.message}")
|
|
327
|
+
event
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
return event
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// MARK: - Public API
|
|
334
|
+
|
|
335
|
+
fun captureException(throwable: Throwable, tags: Map<String, String>? = null): String {
|
|
336
|
+
sessionErrorCount++
|
|
337
|
+
val event = buildEvent(SKErrorLevel.ERROR).apply {
|
|
338
|
+
exceptionType = throwable.javaClass.name
|
|
339
|
+
exceptionValue = throwable.message
|
|
340
|
+
stacktrace = parseStackTrace(throwable)
|
|
341
|
+
exceptions = buildExceptionChain(throwable)
|
|
342
|
+
this.tags = mergeTags(scope.tags, tags ?: emptyMap())
|
|
343
|
+
}
|
|
344
|
+
val finalEvent = applyBeforeSend(event) ?: return event.eventId
|
|
345
|
+
sendEvent(finalEvent)
|
|
346
|
+
return finalEvent.eventId
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
fun captureMessage(message: String, level: SKErrorLevel = SKErrorLevel.INFO) {
|
|
350
|
+
val event = buildEvent(level).apply { this.message = message }
|
|
351
|
+
val finalEvent = applyBeforeSend(event) ?: return
|
|
352
|
+
sendEvent(finalEvent)
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* Submit user feedback for a previously captured error event.
|
|
357
|
+
*/
|
|
358
|
+
fun captureUserFeedback(
|
|
359
|
+
eventId: String,
|
|
360
|
+
name: String? = null,
|
|
361
|
+
email: String? = null,
|
|
362
|
+
comments: String
|
|
363
|
+
) {
|
|
364
|
+
val cfg = config ?: return
|
|
365
|
+
executor.submit {
|
|
366
|
+
try {
|
|
367
|
+
val body = JSONObject().apply {
|
|
368
|
+
put("eventId", eventId)
|
|
369
|
+
if (name != null) put("name", name)
|
|
370
|
+
if (email != null) put("email", email)
|
|
371
|
+
put("comments", comments)
|
|
372
|
+
}
|
|
373
|
+
// Round-D: routed through the unified BackendHttpClient.
|
|
374
|
+
com.appswissknife.net.BackendHttpClient
|
|
375
|
+
.create(cfg.apiKey, cfg.serverURL.ifEmpty { null })
|
|
376
|
+
.simplePost(
|
|
377
|
+
path = "/api/sdk/errors/feedback",
|
|
378
|
+
body = body.toString(),
|
|
379
|
+
)
|
|
380
|
+
} catch (e: Exception) {
|
|
381
|
+
// non-fatal
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Returns the current trace propagation headers.
|
|
388
|
+
* Add these to outbound HTTP requests for distributed tracing.
|
|
389
|
+
*/
|
|
390
|
+
fun traceHeaders(): Map<String, String> {
|
|
391
|
+
val tx = com.appswissknife.performance.SKPerformance.currentTransaction ?: return emptyMap()
|
|
392
|
+
val sampled = if (tx.sampled) "1" else "0"
|
|
393
|
+
return mapOf(
|
|
394
|
+
"sk-trace-id" to tx.traceId,
|
|
395
|
+
"sk-parent-span-id" to tx.spanId,
|
|
396
|
+
"sk-sampled" to sampled,
|
|
397
|
+
)
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
fun captureEvent(event: SKErrorEvent) {
|
|
401
|
+
// Note: device / OS fields used to be hydrated here as a fallback —
|
|
402
|
+
// dropped, the envelope carries them now.
|
|
403
|
+
val e = event.copy(
|
|
404
|
+
environment = event.environment ?: config?.environment,
|
|
405
|
+
release = event.release ?: config?.release,
|
|
406
|
+
user = event.user ?: scope.user,
|
|
407
|
+
tags = mergeTags(scope.tags, event.tags ?: emptyMap()).ifEmpty { null },
|
|
408
|
+
extra = mergeMaps(scope.extra, event.extra ?: emptyMap()).ifEmpty { null },
|
|
409
|
+
breadcrumbs = event.breadcrumbs ?: breadcrumbs.snapshot()
|
|
410
|
+
)
|
|
411
|
+
sendEventPayload(e)
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Flush all pending operations. Blocks until the internal executor drains
|
|
416
|
+
* previously submitted work (pending crash sends, event sends).
|
|
417
|
+
* Useful before app shutdown or when you need delivery guarantees.
|
|
418
|
+
*/
|
|
419
|
+
fun flush() {
|
|
420
|
+
// Submit a no-op task and wait for it — this ensures all previously
|
|
421
|
+
// submitted work on the executor is complete.
|
|
422
|
+
try {
|
|
423
|
+
executor.submit {}.get(10, java.util.concurrent.TimeUnit.SECONDS)
|
|
424
|
+
} catch (_: Exception) {
|
|
425
|
+
// timeout or interrupted — best effort
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
fun addBreadcrumb(breadcrumb: SKBreadcrumb) {
|
|
430
|
+
breadcrumbs.append(breadcrumb)
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
fun configureScope(callback: (SKErrorScope) -> Unit) {
|
|
434
|
+
callback(scope)
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
fun setUser(user: SKUser?) {
|
|
438
|
+
scope.setUser(user)
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
fun setTag(key: String, value: String) {
|
|
442
|
+
scope.setTag(key, value)
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
fun setExtra(key: String, value: Any) {
|
|
446
|
+
scope.setExtra(key, value)
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// MARK: - Private: Build / Send
|
|
450
|
+
|
|
451
|
+
private fun buildEvent(level: SKErrorLevel): SKErrorEvent {
|
|
452
|
+
val cfg = config
|
|
453
|
+
// Device / OS / app fields used to be stamped here. Dropped — the
|
|
454
|
+
// envelope's `ContextSnapshot.device` carries them at flush time.
|
|
455
|
+
return SKErrorEvent(
|
|
456
|
+
level = level,
|
|
457
|
+
environment = cfg?.environment,
|
|
458
|
+
release = cfg?.release,
|
|
459
|
+
tags = scope.tags.toMap().ifEmpty { null },
|
|
460
|
+
extra = scope.extra.toMap().ifEmpty { null },
|
|
461
|
+
user = scope.user,
|
|
462
|
+
breadcrumbs = breadcrumbs.snapshot()
|
|
463
|
+
)
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
private fun buildCrashEvent(throwable: Throwable): SKErrorEvent {
|
|
467
|
+
return buildEvent(SKErrorLevel.FATAL).copy(
|
|
468
|
+
exceptionType = throwable.javaClass.name,
|
|
469
|
+
exceptionValue = throwable.message,
|
|
470
|
+
stacktrace = parseStackTrace(throwable),
|
|
471
|
+
exceptions = buildExceptionChain(throwable),
|
|
472
|
+
mechanism = "uncaught_exception"
|
|
473
|
+
)
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* Walk the Throwable cause chain and produce a structured list.
|
|
478
|
+
* The first entry is the top-level exception; subsequent entries are causes.
|
|
479
|
+
* A `seen` set prevents infinite loops (circular cause references).
|
|
480
|
+
*/
|
|
481
|
+
internal fun buildExceptionChain(throwable: Throwable): List<SKExceptionEntry> {
|
|
482
|
+
val chain = mutableListOf<SKExceptionEntry>()
|
|
483
|
+
val seen = mutableSetOf<Throwable>()
|
|
484
|
+
var current: Throwable? = throwable
|
|
485
|
+
|
|
486
|
+
while (current != null && current !in seen) {
|
|
487
|
+
seen.add(current)
|
|
488
|
+
chain.add(
|
|
489
|
+
SKExceptionEntry(
|
|
490
|
+
type = current.javaClass.name,
|
|
491
|
+
value = current.message ?: "",
|
|
492
|
+
stacktrace = parseStackTraceElements(current.stackTrace)
|
|
493
|
+
)
|
|
494
|
+
)
|
|
495
|
+
current = current.cause
|
|
496
|
+
}
|
|
497
|
+
return chain
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
private fun sendEvent(event: SKErrorEvent) {
|
|
501
|
+
executor.execute { enqueueEvent(event) }
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
private fun enqueueEvent(event: SKErrorEvent) {
|
|
505
|
+
pendingEvents.add(event)
|
|
506
|
+
if (pendingEvents.size >= FLUSH_THRESHOLD) {
|
|
507
|
+
flushEventQueue()
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
private fun startFlushTimer() {
|
|
512
|
+
flushTimer?.cancel()
|
|
513
|
+
flushTimer = java.util.Timer("sk-event-flush", true).also { timer ->
|
|
514
|
+
timer.scheduleAtFixedRate(object : java.util.TimerTask() {
|
|
515
|
+
override fun run() {
|
|
516
|
+
executor.execute { flushEventQueue() }
|
|
517
|
+
}
|
|
518
|
+
}, FLUSH_INTERVAL_MS, FLUSH_INTERVAL_MS)
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
private fun flushEventQueue() {
|
|
523
|
+
if (pendingEvents.isEmpty()) return
|
|
524
|
+
val cfg = config ?: return
|
|
525
|
+
|
|
526
|
+
val batch = pendingEvents.toList()
|
|
527
|
+
pendingEvents.clear()
|
|
528
|
+
|
|
529
|
+
// Round-C: prefer IngestClient when SwissKnife.configure has wired
|
|
530
|
+
// it (the unified /ingest pipeline handles context stamping +
|
|
531
|
+
// offline queue + retry centrally). Fall back to direct HTTP only
|
|
532
|
+
// when the SDK was bootstrapped via SKCrashReporting.initialize
|
|
533
|
+
// alone (e.g. integration tests).
|
|
534
|
+
val ingest = com.appswissknife.net.IngestClient.shared
|
|
535
|
+
val ctx = appContext
|
|
536
|
+
if (ingest != null && ctx != null) {
|
|
537
|
+
val itemsJson = org.json.JSONArray(batch.map { it.toJSON() })
|
|
538
|
+
val data = JSONObject().put("items", itemsJson)
|
|
539
|
+
ingest.enqueue(com.appswissknife.net.IngestItemType.ErrorBatch, data, ctx)
|
|
540
|
+
return
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// Round-D: legacy batch fallback uses the unified BackendHttpClient.
|
|
544
|
+
try {
|
|
545
|
+
val payload = JSONObject().apply {
|
|
546
|
+
put("events", JSONArray(batch.map { it.toJSON() }))
|
|
547
|
+
}
|
|
548
|
+
val r = com.appswissknife.net.BackendHttpClient
|
|
549
|
+
.create(cfg.apiKey, cfg.serverURL.ifEmpty { null })
|
|
550
|
+
.simplePost(
|
|
551
|
+
path = "/api/sdk/errors/event/batch",
|
|
552
|
+
body = payload.toString(),
|
|
553
|
+
)
|
|
554
|
+
if (r.code !in 200..299) {
|
|
555
|
+
println("[SwissKnife CrashReporting] batch send failed: HTTP ${r.code}")
|
|
556
|
+
persistQueueToDisk(batch)
|
|
557
|
+
}
|
|
558
|
+
} catch (e: Exception) {
|
|
559
|
+
println("[SwissKnife CrashReporting] batch send error: ${e.message}")
|
|
560
|
+
persistQueueToDisk(batch)
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
private fun persistQueueToDisk(events: List<SKErrorEvent>) {
|
|
565
|
+
try {
|
|
566
|
+
val ctx = appContext ?: return
|
|
567
|
+
val file = File(ctx.filesDir, "swiss-knife-crash/pending-queue.json")
|
|
568
|
+
file.parentFile?.mkdirs()
|
|
569
|
+
val payload = JSONArray(events.map { it.toJSON() })
|
|
570
|
+
file.writeText(payload.toString())
|
|
571
|
+
} catch (e: Exception) {
|
|
572
|
+
println("[SwissKnife CrashReporting] persistQueue error: ${e.message}")
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
private fun restorePersistedQueue() {
|
|
577
|
+
try {
|
|
578
|
+
val ctx = appContext ?: return
|
|
579
|
+
val file = File(ctx.filesDir, "swiss-knife-crash/pending-queue.json")
|
|
580
|
+
if (!file.exists()) return
|
|
581
|
+
val text = file.readText()
|
|
582
|
+
file.delete()
|
|
583
|
+
val arr = JSONArray(text)
|
|
584
|
+
// Re-enqueue as raw JSON events — send them as-is via the single-event endpoint
|
|
585
|
+
for (i in 0 until arr.length()) {
|
|
586
|
+
val json = arr.getJSONObject(i)
|
|
587
|
+
sendRawPayload(json)
|
|
588
|
+
}
|
|
589
|
+
} catch (e: Exception) {
|
|
590
|
+
println("[SwissKnife CrashReporting] restoreQueue error: ${e.message}")
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
private fun sendRawPayload(json: JSONObject) {
|
|
595
|
+
val cfg = config ?: return
|
|
596
|
+
executor.execute {
|
|
597
|
+
try {
|
|
598
|
+
com.appswissknife.net.BackendHttpClient
|
|
599
|
+
.create(cfg.apiKey, cfg.serverURL.ifEmpty { null })
|
|
600
|
+
.simplePost(
|
|
601
|
+
path = "/api/sdk/errors/event",
|
|
602
|
+
body = json.toString(),
|
|
603
|
+
)
|
|
604
|
+
} catch (_: Exception) { /* best-effort */ }
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/** Legacy single-event send (used for crash flush, pending crash from prev session). */
|
|
609
|
+
internal fun sendEventPayload(event: SKErrorEvent) {
|
|
610
|
+
val cfg = config ?: return
|
|
611
|
+
// Round-C: prefer IngestClient when wired.
|
|
612
|
+
val ingest = com.appswissknife.net.IngestClient.shared
|
|
613
|
+
val ctx = appContext
|
|
614
|
+
if (ingest != null && ctx != null) {
|
|
615
|
+
ingest.enqueue(com.appswissknife.net.IngestItemType.Error, event.toJSON(), ctx)
|
|
616
|
+
return
|
|
617
|
+
}
|
|
618
|
+
try {
|
|
619
|
+
val r = com.appswissknife.net.BackendHttpClient
|
|
620
|
+
.create(cfg.apiKey, cfg.serverURL.ifEmpty { null })
|
|
621
|
+
.simplePost(
|
|
622
|
+
path = "/api/sdk/errors/event",
|
|
623
|
+
body = event.toJSON().toString(),
|
|
624
|
+
)
|
|
625
|
+
if (r.code !in 200..299) {
|
|
626
|
+
println("[SwissKnife CrashReporting] send failed: HTTP ${r.code}")
|
|
627
|
+
}
|
|
628
|
+
} catch (e: Exception) {
|
|
629
|
+
println("[SwissKnife CrashReporting] send error: ${e.message}")
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// MARK: - Pending Crash (disk)
|
|
634
|
+
|
|
635
|
+
internal fun flushPendingCrash() {
|
|
636
|
+
val file = pendingCrashFile ?: return
|
|
637
|
+
if (!file.exists()) return
|
|
638
|
+
|
|
639
|
+
val data = file.readBytes()
|
|
640
|
+
// Delete before sending — best-effort delivery
|
|
641
|
+
file.delete()
|
|
642
|
+
|
|
643
|
+
val cfg = config ?: return
|
|
644
|
+
executor.execute {
|
|
645
|
+
try {
|
|
646
|
+
val r = com.appswissknife.net.BackendHttpClient
|
|
647
|
+
.create(cfg.apiKey, cfg.serverURL.ifEmpty { null })
|
|
648
|
+
.simplePost(
|
|
649
|
+
path = "/api/sdk/errors/event",
|
|
650
|
+
body = String(data, Charsets.UTF_8),
|
|
651
|
+
)
|
|
652
|
+
if (r.code !in 200..299) {
|
|
653
|
+
println("[SwissKnife CrashReporting] pending crash send failed: HTTP ${r.code}")
|
|
654
|
+
}
|
|
655
|
+
} catch (e: Exception) {
|
|
656
|
+
println("[SwissKnife CrashReporting] pending crash send error: ${e.message}")
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
internal fun writeCrashToDisk(event: SKErrorEvent) {
|
|
662
|
+
try {
|
|
663
|
+
val file = pendingCrashFile ?: return
|
|
664
|
+
file.parentFile?.mkdirs()
|
|
665
|
+
file.writeText(event.toJSON().toString())
|
|
666
|
+
} catch (e: Exception) {
|
|
667
|
+
println("[SwissKnife CrashReporting] writeCrashToDisk error: ${e.message}")
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
// MARK: - Session Tracking
|
|
672
|
+
|
|
673
|
+
private fun startSession() {
|
|
674
|
+
sessionErrorCount = 0
|
|
675
|
+
sendSessionEvent("started")
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
private fun endSession() {
|
|
679
|
+
sendSessionEvent("ended")
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
internal fun sendSessionEvent(status: String) {
|
|
683
|
+
val cfg = config ?: return
|
|
684
|
+
val ctx = appContext ?: return
|
|
685
|
+
// Source session_id (and start time) from the canonical Session
|
|
686
|
+
// primitive so the data payload agrees with the envelope-level
|
|
687
|
+
// ContextSnapshot.session_id. No more divergent IDs.
|
|
688
|
+
val snapshot = com.appswissknife.context.Session.shared(ctx).current
|
|
689
|
+
|
|
690
|
+
val duration = (System.currentTimeMillis() - snapshot.startedAtMs) / 1000.0
|
|
691
|
+
|
|
692
|
+
val body = JSONObject().apply {
|
|
693
|
+
put("sessionId", snapshot.id)
|
|
694
|
+
put("status", status)
|
|
695
|
+
put("duration", duration)
|
|
696
|
+
put("errorsCount", sessionErrorCount)
|
|
697
|
+
cfg.release?.let { put("releaseVersion", it) }
|
|
698
|
+
put("environment", cfg.environment)
|
|
699
|
+
put("osName", "Android")
|
|
700
|
+
put("osVersion", Build.VERSION.RELEASE)
|
|
701
|
+
put("deviceModel", Build.MODEL)
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
// Round-C: prefer IngestClient when wired.
|
|
705
|
+
val ingest = com.appswissknife.net.IngestClient.shared
|
|
706
|
+
if (ingest != null) {
|
|
707
|
+
ingest.enqueue(com.appswissknife.net.IngestItemType.Session, body, ctx)
|
|
708
|
+
return
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
executor.execute {
|
|
712
|
+
try {
|
|
713
|
+
com.appswissknife.net.BackendHttpClient
|
|
714
|
+
.create(cfg.apiKey, cfg.serverURL.ifEmpty { null })
|
|
715
|
+
.simplePost(
|
|
716
|
+
path = "/api/sdk/errors/session",
|
|
717
|
+
body = body.toString(),
|
|
718
|
+
)
|
|
719
|
+
} catch (e: Exception) {
|
|
720
|
+
println("[SwissKnife CrashReporting] session event error: ${e.message}")
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
// MARK: - Auto-Breadcrumbs
|
|
726
|
+
|
|
727
|
+
private fun registerActivityLifecycle(context: Context) {
|
|
728
|
+
val app = context as? android.app.Application ?: return
|
|
729
|
+
app.registerActivityLifecycleCallbacks(object : android.app.Application.ActivityLifecycleCallbacks {
|
|
730
|
+
override fun onActivityCreated(activity: android.app.Activity, b: android.os.Bundle?) {
|
|
731
|
+
addBreadcrumb(SKBreadcrumb(category = "activity.lifecycle", message = "${activity.localClassName}: created"))
|
|
732
|
+
}
|
|
733
|
+
override fun onActivityResumed(activity: android.app.Activity) {
|
|
734
|
+
addBreadcrumb(SKBreadcrumb(category = "activity.lifecycle", message = "${activity.localClassName}: resumed"))
|
|
735
|
+
}
|
|
736
|
+
override fun onActivityPaused(activity: android.app.Activity) {
|
|
737
|
+
addBreadcrumb(SKBreadcrumb(category = "activity.lifecycle", message = "${activity.localClassName}: paused"))
|
|
738
|
+
endSession()
|
|
739
|
+
}
|
|
740
|
+
override fun onActivityStarted(activity: android.app.Activity) {}
|
|
741
|
+
override fun onActivityStopped(activity: android.app.Activity) {}
|
|
742
|
+
override fun onActivitySaveInstanceState(activity: android.app.Activity, b: android.os.Bundle) {}
|
|
743
|
+
override fun onActivityDestroyed(activity: android.app.Activity) {}
|
|
744
|
+
})
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
private fun registerConnectivityObserver(context: Context) {
|
|
748
|
+
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager ?: return
|
|
749
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
|
750
|
+
cm.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
|
|
751
|
+
override fun onAvailable(network: Network) {
|
|
752
|
+
addBreadcrumb(SKBreadcrumb(category = "connectivity", message = "network available"))
|
|
753
|
+
}
|
|
754
|
+
override fun onLost(network: Network) {
|
|
755
|
+
addBreadcrumb(SKBreadcrumb(category = "connectivity", message = "network lost"))
|
|
756
|
+
}
|
|
757
|
+
})
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
// MARK: - Native Crash Detection (Android 11+)
|
|
762
|
+
|
|
763
|
+
/**
|
|
764
|
+
* Use ApplicationExitInfo (Android 11+) to detect native crashes (EXC_BAD_ACCESS,
|
|
765
|
+
* Hermes JIT faults, NDK segfaults) and system-confirmed ANRs from previous sessions.
|
|
766
|
+
* The OS records tombstone traces accessible via `getTraceInputStream()`.
|
|
767
|
+
*/
|
|
768
|
+
@Suppress("NewApi")
|
|
769
|
+
private fun checkPreviousNativeCrashes(context: Context) {
|
|
770
|
+
executor.execute {
|
|
771
|
+
try {
|
|
772
|
+
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager ?: return@execute
|
|
773
|
+
val exitInfos = am.getHistoricalProcessExitReasons(context.packageName, 0, 5)
|
|
774
|
+
val prefs = context.getSharedPreferences("sk_crash", Context.MODE_PRIVATE)
|
|
775
|
+
val lastReported = prefs.getLong("last_native_crash_ts", 0)
|
|
776
|
+
|
|
777
|
+
for (info in exitInfos) {
|
|
778
|
+
if (info.timestamp <= lastReported) continue
|
|
779
|
+
if (info.reason != ApplicationExitInfo.REASON_CRASH_NATIVE &&
|
|
780
|
+
info.reason != ApplicationExitInfo.REASON_ANR) continue
|
|
781
|
+
|
|
782
|
+
val isNative = info.reason == ApplicationExitInfo.REASON_CRASH_NATIVE
|
|
783
|
+
val traceText = try {
|
|
784
|
+
info.traceInputStream?.use { stream ->
|
|
785
|
+
stream.bufferedReader().readText()
|
|
786
|
+
}
|
|
787
|
+
} catch (_: Exception) { null }
|
|
788
|
+
|
|
789
|
+
val event = buildEvent(SKErrorLevel.FATAL).copy(
|
|
790
|
+
exceptionType = if (isNative) "NativeCrash" else "ANR",
|
|
791
|
+
exceptionValue = info.description ?: if (isNative) "Native crash detected via ApplicationExitInfo" else "ANR detected via ApplicationExitInfo",
|
|
792
|
+
mechanism = if (isNative) "native_crash" else "anr_system",
|
|
793
|
+
stacktrace = traceText?.let { parseNativeTrace(it) } ?: emptyList()
|
|
794
|
+
)
|
|
795
|
+
|
|
796
|
+
sendEventPayload(event)
|
|
797
|
+
|
|
798
|
+
prefs.edit().putLong("last_native_crash_ts", info.timestamp).apply()
|
|
799
|
+
}
|
|
800
|
+
} catch (e: Exception) {
|
|
801
|
+
println("[SwissKnife CrashReporting] checkPreviousNativeCrashes error: ${e.message}")
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
/**
|
|
807
|
+
* Parse Android tombstone / native trace format.
|
|
808
|
+
* Each frame looks like: " #00 pc 0001a4e8 /system/lib/libc.so (abort+4)"
|
|
809
|
+
*/
|
|
810
|
+
internal fun parseNativeTrace(tombstone: String): List<SKStackFrame> {
|
|
811
|
+
val frames = mutableListOf<SKStackFrame>()
|
|
812
|
+
val regex = Regex("""#\d+\s+pc\s+([0-9a-f]+)\s+(\S+)(?:\s+\((.+)\))?""")
|
|
813
|
+
for (match in regex.findAll(tombstone)) {
|
|
814
|
+
val address = match.groupValues[1]
|
|
815
|
+
val modulePath = match.groupValues[2]
|
|
816
|
+
val funcName = match.groupValues[3].ifEmpty { null }
|
|
817
|
+
frames.add(
|
|
818
|
+
SKStackFrame(
|
|
819
|
+
instructionAddress = "0x$address",
|
|
820
|
+
module = modulePath,
|
|
821
|
+
function = funcName,
|
|
822
|
+
inApp = !modulePath.startsWith("/system/") &&
|
|
823
|
+
!modulePath.startsWith("/apex/") &&
|
|
824
|
+
!modulePath.contains("libart.so") &&
|
|
825
|
+
!modulePath.contains("libandroid_runtime.so")
|
|
826
|
+
)
|
|
827
|
+
)
|
|
828
|
+
}
|
|
829
|
+
return frames
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
// MARK: - Helpers
|
|
833
|
+
|
|
834
|
+
/**
|
|
835
|
+
* Parse a Throwable's stack trace into structured stack frames.
|
|
836
|
+
* Uses StackTraceElement fields for module, function, filename, lineno.
|
|
837
|
+
*/
|
|
838
|
+
internal fun parseStackTrace(throwable: Throwable): List<SKStackFrame> {
|
|
839
|
+
return parseStackTraceElements(throwable.stackTrace)
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
/**
|
|
843
|
+
* Parse an array of StackTraceElement into structured stack frames.
|
|
844
|
+
*/
|
|
845
|
+
internal fun parseStackTraceElements(elements: Array<StackTraceElement>): List<SKStackFrame> {
|
|
846
|
+
return elements.map { el ->
|
|
847
|
+
SKStackFrame(
|
|
848
|
+
filename = el.fileName,
|
|
849
|
+
function = el.methodName,
|
|
850
|
+
module = el.className,
|
|
851
|
+
lineno = el.lineNumber.takeIf { it >= 0 },
|
|
852
|
+
inApp = !el.className.startsWith("android.") &&
|
|
853
|
+
!el.className.startsWith("java.") &&
|
|
854
|
+
!el.className.startsWith("com.android.") &&
|
|
855
|
+
!el.className.startsWith("dalvik.") &&
|
|
856
|
+
!el.className.startsWith("kotlin.") &&
|
|
857
|
+
!el.className.startsWith("kotlinx.")
|
|
858
|
+
)
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
private fun mergeTags(base: Map<String, String>, override: Map<String, String>): Map<String, String> {
|
|
863
|
+
return base.toMutableMap().apply { putAll(override) }
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
private fun mergeMaps(base: Map<String, String>, override: Map<String, String>): Map<String, String> {
|
|
867
|
+
return base.toMutableMap().apply { putAll(override) }
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// MARK: - HTTP Breadcrumb Convenience
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* Convenience method for network layers to record HTTP breadcrumbs.
|
|
874
|
+
* Call this from your OkHttp interceptor, Retrofit callback, or custom
|
|
875
|
+
* network layer.
|
|
876
|
+
*/
|
|
877
|
+
fun captureHTTPBreadcrumb(method: String, url: String, statusCode: Int, durationMs: Long) {
|
|
878
|
+
val level = if (statusCode in 200..399) SKErrorLevel.INFO else SKErrorLevel.WARNING
|
|
879
|
+
addBreadcrumb(SKBreadcrumb(
|
|
880
|
+
category = "http",
|
|
881
|
+
message = "$method $url",
|
|
882
|
+
level = level,
|
|
883
|
+
data = mapOf(
|
|
884
|
+
"method" to method,
|
|
885
|
+
"url" to url,
|
|
886
|
+
"status_code" to statusCode.toString(),
|
|
887
|
+
"duration_ms" to durationMs.toString()
|
|
888
|
+
)
|
|
889
|
+
))
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
// MARK: - Test Hooks
|
|
893
|
+
|
|
894
|
+
internal fun _snapshotBreadcrumbs() = breadcrumbs.snapshot()
|
|
895
|
+
internal fun _clearBreadcrumbs() = breadcrumbs.clear()
|
|
896
|
+
internal fun _resetForTesting() {
|
|
897
|
+
config = null
|
|
898
|
+
appContext = null
|
|
899
|
+
scope.tags.clear()
|
|
900
|
+
scope.extra.clear()
|
|
901
|
+
scope.setUser(null)
|
|
902
|
+
breadcrumbs.clear()
|
|
903
|
+
anrWatchdog?.stop()
|
|
904
|
+
anrWatchdog = null
|
|
905
|
+
sessionErrorCount = 0
|
|
906
|
+
pendingEvents.clear()
|
|
907
|
+
flushTimer?.cancel()
|
|
908
|
+
flushTimer = null
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
// MARK: - OkHttp Interceptor for automatic HTTP breadcrumbs
|
|
913
|
+
|
|
914
|
+
/**
|
|
915
|
+
* OkHttp Interceptor that automatically records HTTP breadcrumbs.
|
|
916
|
+
*
|
|
917
|
+
* Usage:
|
|
918
|
+
* ```kotlin
|
|
919
|
+
* val client = OkHttpClient.Builder()
|
|
920
|
+
* .addInterceptor(SKBreadcrumbInterceptor())
|
|
921
|
+
* .build()
|
|
922
|
+
* ```
|
|
923
|
+
*/
|
|
924
|
+
class SKBreadcrumbInterceptor : okhttp3.Interceptor {
|
|
925
|
+
override fun intercept(chain: okhttp3.Interceptor.Chain): okhttp3.Response {
|
|
926
|
+
val request = chain.request()
|
|
927
|
+
val start = System.currentTimeMillis()
|
|
928
|
+
val response = chain.proceed(request)
|
|
929
|
+
val durationMs = System.currentTimeMillis() - start
|
|
930
|
+
|
|
931
|
+
SKCrashReporting.addBreadcrumb(SKBreadcrumb(
|
|
932
|
+
category = "http",
|
|
933
|
+
message = "${request.method} ${request.url}",
|
|
934
|
+
data = mapOf(
|
|
935
|
+
"method" to request.method,
|
|
936
|
+
"url" to request.url.toString(),
|
|
937
|
+
"status_code" to response.code.toString(),
|
|
938
|
+
"duration_ms" to durationMs.toString()
|
|
939
|
+
),
|
|
940
|
+
level = if (response.isSuccessful) SKErrorLevel.INFO else SKErrorLevel.WARNING
|
|
941
|
+
))
|
|
942
|
+
|
|
943
|
+
return response
|
|
944
|
+
}
|
|
945
|
+
}
|