@app-swiss-knife/react-native-sdk 0.4.0 → 0.5.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.
Files changed (177) hide show
  1. package/CHANGELOG.md +385 -2
  2. package/LICENSE +21 -0
  3. package/README.md +229 -42
  4. package/SwissKnifePurchases.podspec +1 -1
  5. package/android/build.gradle +24 -2
  6. package/android/consumer-rules.pro +12 -0
  7. package/android/src/main/AndroidManifest.xml +15 -1
  8. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +5 -4
  9. package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +7 -2
  10. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +168 -6
  11. package/android/src/play/java/com/swissknife/purchases/StoreIntentHandler.kt +7 -0
  12. package/android/src/rustore/java/com/swissknife/purchases/StoreIntentHandler.kt +9 -0
  13. package/android/vendor/java/com/appswissknife/SwissKnife.kt +107 -38
  14. package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
  15. package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
  16. package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
  17. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
  18. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  19. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +365 -206
  20. package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
  21. package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
  22. package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
  23. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +56 -31
  24. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +673 -87
  25. package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
  26. package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
  27. package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
  28. package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
  29. package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
  30. package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
  31. package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
  32. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
  33. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
  34. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +266 -64
  35. package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
  36. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +545 -88
  37. package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
  38. package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +21 -0
  39. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +14 -0
  40. package/android/vendor-rustore/AndroidManifest.xml +59 -0
  41. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
  42. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
  43. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
  44. package/app.plugin.js +287 -0
  45. package/ios/SwissKnifePurchases.m +20 -0
  46. package/ios/SwissKnifePurchases.swift +97 -3
  47. package/ios/SwissKnifePushBootstrap.m +34 -0
  48. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
  49. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  50. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +345 -44
  51. package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
  52. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
  53. package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
  54. package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
  55. package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
  56. package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
  57. package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
  58. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
  59. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
  60. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
  61. package/lib/commonjs/attribution.js +4 -3
  62. package/lib/commonjs/attribution.js.map +1 -1
  63. package/lib/commonjs/identity.js +12 -11
  64. package/lib/commonjs/identity.js.map +1 -1
  65. package/lib/commonjs/index.js +16 -5
  66. package/lib/commonjs/index.js.map +1 -1
  67. package/lib/commonjs/internal/config.js +105 -8
  68. package/lib/commonjs/internal/config.js.map +1 -1
  69. package/lib/commonjs/internal/telemetry-context.js +70 -0
  70. package/lib/commonjs/internal/telemetry-context.js.map +1 -0
  71. package/lib/commonjs/modules/analytics.js +18 -25
  72. package/lib/commonjs/modules/analytics.js.map +1 -1
  73. package/lib/commonjs/modules/crash-reporting.js +27 -6
  74. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  75. package/lib/commonjs/modules/log.js +1 -1
  76. package/lib/commonjs/modules/notifications.js +500 -0
  77. package/lib/commonjs/modules/notifications.js.map +1 -0
  78. package/lib/commonjs/modules/performance.js +57 -8
  79. package/lib/commonjs/modules/performance.js.map +1 -1
  80. package/lib/commonjs/native/module.js +6 -0
  81. package/lib/commonjs/native/module.js.map +1 -1
  82. package/lib/commonjs/native/spec.js +12 -5
  83. package/lib/commonjs/native/spec.js.map +1 -1
  84. package/lib/commonjs/purchases.js +4 -4
  85. package/lib/commonjs/types.js +12 -15
  86. package/lib/commonjs/types.js.map +1 -1
  87. package/lib/module/attribution.js +4 -3
  88. package/lib/module/attribution.js.map +1 -1
  89. package/lib/module/identity.js +12 -11
  90. package/lib/module/identity.js.map +1 -1
  91. package/lib/module/index.js +8 -4
  92. package/lib/module/index.js.map +1 -1
  93. package/lib/module/internal/config.js +103 -8
  94. package/lib/module/internal/config.js.map +1 -1
  95. package/lib/module/internal/telemetry-context.js +63 -0
  96. package/lib/module/internal/telemetry-context.js.map +1 -0
  97. package/lib/module/modules/analytics.js +18 -25
  98. package/lib/module/modules/analytics.js.map +1 -1
  99. package/lib/module/modules/crash-reporting.js +27 -6
  100. package/lib/module/modules/crash-reporting.js.map +1 -1
  101. package/lib/module/modules/log.js +1 -1
  102. package/lib/module/modules/notifications.js +491 -0
  103. package/lib/module/modules/notifications.js.map +1 -0
  104. package/lib/module/modules/performance.js +57 -8
  105. package/lib/module/modules/performance.js.map +1 -1
  106. package/lib/module/native/module.js +6 -1
  107. package/lib/module/native/module.js.map +1 -1
  108. package/lib/module/native/spec.js +11 -4
  109. package/lib/module/native/spec.js.map +1 -1
  110. package/lib/module/purchases.js +4 -4
  111. package/lib/module/types.js +12 -15
  112. package/lib/module/types.js.map +1 -1
  113. package/lib/typescript/commonjs/attribution.d.ts +3 -2
  114. package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
  115. package/lib/typescript/commonjs/identity.d.ts.map +1 -1
  116. package/lib/typescript/commonjs/index.d.ts +2 -0
  117. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  118. package/lib/typescript/commonjs/internal/config.d.ts +16 -2
  119. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
  120. package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
  121. package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
  122. package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
  123. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
  124. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +18 -5
  125. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  126. package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
  127. package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
  128. package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
  129. package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
  130. package/lib/typescript/commonjs/native/module.d.ts +2 -0
  131. package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
  132. package/lib/typescript/commonjs/native/spec.d.ts +33 -4
  133. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
  134. package/lib/typescript/commonjs/purchases.d.ts +4 -4
  135. package/lib/typescript/commonjs/types.d.ts +4 -5
  136. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  137. package/lib/typescript/module/attribution.d.ts +3 -2
  138. package/lib/typescript/module/attribution.d.ts.map +1 -1
  139. package/lib/typescript/module/identity.d.ts.map +1 -1
  140. package/lib/typescript/module/index.d.ts +2 -0
  141. package/lib/typescript/module/index.d.ts.map +1 -1
  142. package/lib/typescript/module/internal/config.d.ts +16 -2
  143. package/lib/typescript/module/internal/config.d.ts.map +1 -1
  144. package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
  145. package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
  146. package/lib/typescript/module/modules/analytics.d.ts +8 -11
  147. package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
  148. package/lib/typescript/module/modules/crash-reporting.d.ts +18 -5
  149. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  150. package/lib/typescript/module/modules/notifications.d.ts +110 -0
  151. package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
  152. package/lib/typescript/module/modules/performance.d.ts +13 -0
  153. package/lib/typescript/module/modules/performance.d.ts.map +1 -1
  154. package/lib/typescript/module/native/module.d.ts +2 -0
  155. package/lib/typescript/module/native/module.d.ts.map +1 -1
  156. package/lib/typescript/module/native/spec.d.ts +33 -4
  157. package/lib/typescript/module/native/spec.d.ts.map +1 -1
  158. package/lib/typescript/module/purchases.d.ts +4 -4
  159. package/lib/typescript/module/types.d.ts +4 -5
  160. package/lib/typescript/module/types.d.ts.map +1 -1
  161. package/package.json +12 -4
  162. package/src/attribution.ts +4 -3
  163. package/src/identity.ts +12 -11
  164. package/src/index.ts +16 -4
  165. package/src/internal/config.ts +113 -8
  166. package/src/internal/telemetry-context.ts +76 -0
  167. package/src/modules/analytics.ts +24 -33
  168. package/src/modules/crash-reporting.ts +50 -9
  169. package/src/modules/log.ts +1 -1
  170. package/src/modules/notifications.ts +557 -0
  171. package/src/modules/performance.ts +94 -14
  172. package/src/native/module.ts +6 -0
  173. package/src/native/spec.ts +45 -10
  174. package/src/purchases.ts +4 -4
  175. package/src/types.ts +12 -15
  176. package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
  177. package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +0 -296
@@ -3,6 +3,12 @@
3
3
  // Sentry-compatible crash reporting SDK for swiss-knife (Android).
4
4
  // Captures uncaught JVM exceptions, ANRs, and breadcrumbs.
5
5
  // On next init(), any pending crash is sent before normal operation resumes.
6
+ //
7
+ // Every report goes through ONE pipeline: IngestClient (disk queue, POST
8
+ // /ingest), wired by SwissKnife.configureCore / configure /
9
+ // ensureObservabilityBackend. See "Pre-configure buffer" below for what happens
10
+ // when crash reporting starts first. The direct /api/sdk/errors/event,
11
+ // /event/batch and /session fallbacks and their pending-queue.json are gone.
6
12
 
7
13
  package com.appswissknife.crashreporting
8
14
 
@@ -21,9 +27,15 @@ import java.io.File
21
27
  import java.text.SimpleDateFormat
22
28
  import java.util.Date
23
29
  import java.util.Locale
30
+ import java.util.TimeZone
31
+ import java.util.concurrent.ConcurrentHashMap
32
+ import java.util.concurrent.ConcurrentLinkedDeque
24
33
  import java.util.concurrent.CopyOnWriteArrayList
25
34
  import com.appswissknife.context.IDs
35
+ import com.appswissknife.diagnostics.SKLog
26
36
  import com.appswissknife.identity.Identity
37
+ import com.appswissknife.net.IngestClient
38
+ import com.appswissknife.net.IngestItemType
27
39
  import java.util.concurrent.Executors
28
40
  import java.util.concurrent.atomic.AtomicBoolean
29
41
 
@@ -51,6 +63,27 @@ data class SKStackFrame(
51
63
  }
52
64
  }
53
65
 
66
+ /**
67
+ * The wire format of every error and breadcrumb timestamp: ISO-8601 in UTC,
68
+ * millisecond precision, e.g. `2023-11-14T22:13:20.123Z`.
69
+ *
70
+ * Both used to share a `SimpleDateFormat("...'Z'")` with no time zone set,
71
+ * so the device's LOCAL time went out labelled UTC (shifted by up to 14 h),
72
+ * and `SimpleDateFormat` is not thread-safe, so concurrent formatting could
73
+ * garble a value. One formatter per thread, pinned to UTC. (minSdk 24 has no
74
+ * java.time without desugaring.)
75
+ */
76
+ internal object SKIsoTimestamp {
77
+ private val formatter = object : ThreadLocal<SimpleDateFormat>() {
78
+ override fun initialValue(): SimpleDateFormat =
79
+ SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US).apply {
80
+ timeZone = TimeZone.getTimeZone("UTC")
81
+ }
82
+ }
83
+
84
+ fun format(epochMillis: Long): String = formatter.get()!!.format(Date(epochMillis))
85
+ }
86
+
54
87
  data class SKBreadcrumb(
55
88
  val timestamp: Long = System.currentTimeMillis(),
56
89
  val category: String? = null,
@@ -59,16 +92,12 @@ data class SKBreadcrumb(
59
92
  val data: Map<String, String>? = null
60
93
  ) {
61
94
  fun toJSON(): JSONObject = JSONObject().apply {
62
- put("timestamp", ISO_DATE.format(Date(timestamp)))
95
+ put("timestamp", SKIsoTimestamp.format(timestamp))
63
96
  category?.let { put("category", it) }
64
97
  message?.let { put("message", it) }
65
98
  put("level", level.name.lowercase())
66
99
  data?.let { put("data", JSONObject(it as Map<*, *>)) }
67
100
  }
68
-
69
- companion object {
70
- private val ISO_DATE = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)
71
- }
72
101
  }
73
102
 
74
103
  data class SKUser(
@@ -127,7 +156,7 @@ data class SKErrorEvent(
127
156
  ) {
128
157
  fun toJSON(): JSONObject = JSONObject().apply {
129
158
  put("eventId", eventId)
130
- put("timestamp", ISO_DATE.format(Date(timestamp)))
159
+ put("timestamp", SKIsoTimestamp.format(timestamp))
131
160
  put("level", level.name.lowercase())
132
161
  message?.let { put("message", it) }
133
162
  exceptionType?.let { put("exceptionType", it) }
@@ -149,17 +178,16 @@ data class SKErrorEvent(
149
178
  mechanism?.let { put("mechanism", it) }
150
179
  put("platform", platform)
151
180
  }
152
-
153
- companion object {
154
- private val ISO_DATE = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)
155
- }
156
181
  }
157
182
 
158
183
  // MARK: - Scope
159
184
 
160
185
  class SKErrorScope {
161
- internal val tags = mutableMapOf<String, String>()
162
- internal val extra = mutableMapOf<String, String>()
186
+ // Written from any host thread while events are built (and copied) on
187
+ // others: concurrent maps, so a copy never throws
188
+ // ConcurrentModificationException.
189
+ internal val tags: MutableMap<String, String> = ConcurrentHashMap()
190
+ internal val extra: MutableMap<String, String> = ConcurrentHashMap()
163
191
  internal var user: SKUser? = null
164
192
 
165
193
  fun setTag(key: String, value: String) { tags[key] = value }
@@ -285,7 +313,34 @@ object SKCrashReporting {
285
313
  private val scope = SKErrorScope()
286
314
  private var breadcrumbs = RingBuffer<SKBreadcrumb>(100)
287
315
  private var anrWatchdog: AnrWatchdog? = null
316
+
317
+ // Uncaught-exception chaining. Installed ONCE per process: a second
318
+ // `init()` (the React Native bridge calls it again on every JS reload)
319
+ // used to capture our own handler as "original", so the next crash
320
+ // recursed until StackOverflowError and the host's handler never ran.
321
+ private val crashHandlerInstalled = AtomicBoolean(false)
322
+ @Volatile
288
323
  private var originalExceptionHandler: Thread.UncaughtExceptionHandler? = null
324
+
325
+ private object CrashHandler : Thread.UncaughtExceptionHandler {
326
+ override fun uncaughtException(thread: Thread, throwable: Throwable) {
327
+ handleUncaughtException(thread, throwable)
328
+ }
329
+ }
330
+
331
+ // Lifecycle + connectivity callbacks: registered once per Application
332
+ // (they used to be added again on every `init()`).
333
+ @Volatile
334
+ private var lifecycleRegisteredOn: android.app.Application? = null
335
+ @Volatile
336
+ private var connectivityRegisteredOn: Context? = null
337
+
338
+ /**
339
+ * Activities started and not yet stopped, by identity. Main thread only.
340
+ * The session ends when the last one stops (the app went to the
341
+ * background), not on every pause, which fired on each screen change.
342
+ */
343
+ private val startedActivities = HashSet<Int>()
289
344
  private val executor = Executors.newSingleThreadExecutor()
290
345
 
291
346
  // Session tracking
@@ -304,10 +359,52 @@ object SKCrashReporting {
304
359
  private const val FLUSH_INTERVAL_MS = 30_000L
305
360
  private const val FLUSH_THRESHOLD = 10
306
361
 
307
- private val pendingCrashFile: File?
308
- get() = appContext?.let { ctx ->
309
- File(ctx.filesDir, "swiss-knife-crash/pending-crash.json")
310
- }
362
+ // MARK: - Pre-configure buffer
363
+ //
364
+ // A host may call init() before SwissKnife.configureCore has wired
365
+ // IngestClient. Until it is wired:
366
+ // - reports from THIS process wait in memory, bounded: at most
367
+ // PRE_CONFIGURE_LIMIT captured events (in pendingEvents) and
368
+ // PRE_CONFIGURE_LIMIT other items (sessions, ANR / native-crash /
369
+ // captureEvent reports, in preConfigureItems), oldest dropped first;
370
+ // - reports from EARLIER processes stay where they already are, the
371
+ // crash files on disk (see "Pending crash files") and
372
+ // ApplicationExitInfo in the OS.
373
+ // An init() that finds IngestClient unwired starts a watch that hands all
374
+ // of it over within INGEST_WATCH_MS of the client being wired (for the
375
+ // first five minutes), then stops; the first delivery after that, the 30 s
376
+ // flush tick and flush() do the same. Nothing leaves the device before then.
377
+ internal const val PRE_CONFIGURE_LIMIT = 100
378
+ internal const val INGEST_WATCH_MS = 1_000L
379
+ private const val INGEST_WATCH_MAX_RUNS = 300
380
+ private val preConfigureItems = ConcurrentLinkedDeque<Pair<IngestItemType, JSONObject>>()
381
+ @Volatile private var exitInfoCheckDeferred = false
382
+ @Volatile private var preConfigureOverflowLogged = false
383
+
384
+ /**
385
+ * The retry file of the removed direct-POST path (one failed batch, at
386
+ * most). init() deletes it on an upgraded install; its pipeline is gone.
387
+ */
388
+ internal const val LEGACY_QUEUE_FILE = "swiss-knife-crash/pending-queue.json"
389
+
390
+ // MARK: - Pending crash files
391
+ //
392
+ // The uncaught-exception handler writes the crash to filesDir/CRASH_DIR,
393
+ // and the next hand-off moves every waiting file to IngestClient's durable
394
+ // queue. A file that is still waiting (IngestClient was not wired yet, or
395
+ // its queue refused the write) is never overwritten: the next crash gets a
396
+ // file of its own, so a crash loop before configureCore keeps each report.
397
+ // init() keeps the newest MAX_PENDING_CRASH_FILES. Each file is written
398
+ // aside and renamed into place, so a concurrent hand-off reads all of it
399
+ // or none of it.
400
+ private const val CRASH_DIR = "swiss-knife-crash"
401
+ /** The first slot, and the only file an older SDK version reads. */
402
+ private const val PENDING_CRASH_FILE = "pending-crash.json"
403
+ internal const val MAX_PENDING_CRASH_FILES = 10
404
+ private val crashFileLock = Any()
405
+
406
+ private val crashDir: File?
407
+ get() = appContext?.let { ctx -> File(ctx.filesDir, CRASH_DIR) }
311
408
 
312
409
  // MARK: - Identity-derived subject
313
410
  //
@@ -385,6 +482,7 @@ object SKCrashReporting {
385
482
  this.config = config
386
483
  this.appContext = appCtx
387
484
  this.breadcrumbs = RingBuffer(config.maxBreadcrumbs)
485
+ val ingestWired = IngestClient.shared != null
388
486
 
389
487
  // Pre-capture the identified user BEFORE the crash handler is armed,
390
488
  // and keep the cache warm via an Identity observer. Crash-handler
@@ -397,23 +495,22 @@ object SKCrashReporting {
397
495
  identityUserId = change.current.userId?.takeIf { it.isNotEmpty() }
398
496
  }
399
497
 
400
- // Send any crash from previous session
498
+ // Send any crash from earlier sessions (kept on disk until IngestClient
499
+ // is wired).
500
+ prunePendingCrashFiles()
401
501
  flushPendingCrash()
402
502
 
403
503
  // Check for native crashes / ANRs from previous session via ApplicationExitInfo
404
504
  // (Android 11+). This catches NDK native crashes and system-confirmed ANRs.
505
+ // Deferred until IngestClient is wired: the records stay in the OS, and
506
+ // the high-water mark only moves once a report is on the durable queue.
405
507
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
406
- checkPreviousNativeCrashes(appCtx)
508
+ exitInfoCheckDeferred = !ingestWired
509
+ if (ingestWired) checkPreviousNativeCrashes(appCtx)
407
510
  }
408
511
 
409
- // Install uncaught exception handler (chain with existing)
410
- originalExceptionHandler = Thread.getDefaultUncaughtExceptionHandler()
411
- Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
412
- val event = buildCrashEvent(throwable)
413
- writeCrashToDisk(event)
414
- sendSessionEvent("crashed")
415
- originalExceptionHandler?.uncaughtException(thread, throwable)
416
- }
512
+ // Install uncaught exception handler (chain with existing), once.
513
+ installCrashHandler()
417
514
 
418
515
  // Auto-breadcrumbs: activity lifecycle + connectivity
419
516
  registerActivityLifecycle(appCtx)
@@ -438,11 +535,42 @@ object SKCrashReporting {
438
535
  // Start session tracking
439
536
  startSession()
440
537
 
441
- // Restore any persisted event queue from previous failed flush
442
- restorePersistedQueue()
538
+ // An older SDK's direct-POST retry file; its pipeline is gone.
539
+ runCatching { File(appCtx.filesDir, LEGACY_QUEUE_FILE).delete() }
540
+
541
+ // Start periodic flush timer (and the ingest watch when unwired)
542
+ startFlushTimer(watchForIngest = !ingestWired)
543
+ }
443
544
 
444
- // Start periodic flush timer
445
- startFlushTimer()
545
+ /**
546
+ * Install [CrashHandler] as the default handler, capturing the handler it
547
+ * replaces as the one to chain to. Only the first call installs; a later
548
+ * `init()` leaves the chain alone, so it can never capture our own
549
+ * handler as the original.
550
+ */
551
+ private fun installCrashHandler() {
552
+ if (!crashHandlerInstalled.compareAndSet(false, true)) return
553
+ val previous = Thread.getDefaultUncaughtExceptionHandler()
554
+ originalExceptionHandler = previous?.takeIf { it !== CrashHandler }
555
+ Thread.setDefaultUncaughtExceptionHandler(CrashHandler)
556
+ }
557
+
558
+ /**
559
+ * Record the crash, then ALWAYS chain: a failure while building or
560
+ * writing the report must not swallow the crash or skip the host's own
561
+ * handler (another crash reporter, or the platform's, which kills the
562
+ * process).
563
+ */
564
+ private fun handleUncaughtException(thread: Thread, throwable: Throwable) {
565
+ try {
566
+ val event = buildCrashEvent(throwable)
567
+ writeCrashToDisk(event)
568
+ sendSessionEvent("crashed")
569
+ } catch (t: Throwable) {
570
+ runCatching { println("[SwissKnife CrashReporting] crash report failed: $t") }
571
+ } finally {
572
+ originalExceptionHandler?.takeIf { it !== CrashHandler }?.uncaughtException(thread, throwable)
573
+ }
446
574
  }
447
575
 
448
576
  // MARK: - Sampling & beforeSend
@@ -559,14 +687,14 @@ object SKCrashReporting {
559
687
 
560
688
  /**
561
689
  * Flush all pending operations. Blocks until the internal executor drains
562
- * previously submitted work (pending crash sends, event sends).
563
- * Useful before app shutdown or when you need delivery guarantees.
690
+ * previously submitted work, then hands everything that is waiting to
691
+ * IngestClient's durable queue when it is wired (see "Pre-configure
692
+ * buffer"). Useful before app shutdown or when you need delivery guarantees.
564
693
  */
565
694
  fun flush() {
566
- // Submit a no-op task and wait for it — this ensures all previously
567
- // submitted work on the executor is complete.
695
+ // Runs after all previously submitted work on the executor.
568
696
  try {
569
- executor.submit {}.get(10, java.util.concurrent.TimeUnit.SECONDS)
697
+ executor.submit { handOffToIngest() }.get(10, java.util.concurrent.TimeUnit.SECONDS)
570
698
  } catch (_: Exception) {
571
699
  // timeout or interrupted — best effort
572
700
  }
@@ -680,8 +808,9 @@ object SKCrashReporting {
680
808
  * [pendingEvents] batch is not good enough: it flushes every 30 s and dies
681
809
  * with the process, and the system kills an ANR'd process well within
682
810
  * that. So the event goes through [sendEventPayload] (IngestClient's disk
683
- * queue, or a direct POST) and the mark is written only on success. A
684
- * kill between the two costs a duplicate report, never a lost one.
811
+ * queue) and the mark is written only on success. Before IngestClient is
812
+ * wired the event is only held in memory, so no mark is written. A kill
813
+ * between the two costs a duplicate report, never a lost one.
685
814
  */
686
815
  internal fun reportWatchdogAnr(
687
816
  context: Context,
@@ -710,9 +839,14 @@ object SKCrashReporting {
710
839
  if (pendingEvents.size >= FLUSH_THRESHOLD) {
711
840
  flushEventQueue()
712
841
  }
842
+ // Still held because IngestClient is not wired: keep the newest.
843
+ while (pendingEvents.size > PRE_CONFIGURE_LIMIT) {
844
+ pendingEvents.removeAt(0)
845
+ notePreConfigureOverflow()
846
+ }
713
847
  }
714
848
 
715
- private fun startFlushTimer() {
849
+ private fun startFlushTimer(watchForIngest: Boolean) {
716
850
  flushTimer?.cancel()
717
851
  flushTimer = java.util.Timer("sk-event-flush", true).also { timer ->
718
852
  timer.scheduleAtFixedRate(object : java.util.TimerTask() {
@@ -722,188 +856,198 @@ object SKCrashReporting {
722
856
  // identity through `SwissKnife.configure(appUserID = ...)`
723
857
  // AFTER crash reporting started, which sets the id without
724
858
  // firing an Identity change notification.
725
- executor.execute { refreshIdentityUserId(); flushEventQueue() }
859
+ executor.execute { refreshIdentityUserId(); handOffToIngest() }
726
860
  }
727
861
  }, FLUSH_INTERVAL_MS, FLUSH_INTERVAL_MS)
862
+ if (watchForIngest) {
863
+ // Started before SwissKnife.configureCore: hand the backlog over
864
+ // as soon as IngestClient is wired, not at the next 30 s tick.
865
+ // One volatile read per period; stops after the hand-off, or
866
+ // after INGEST_WATCH_MAX_RUNS, when the tick alone remains.
867
+ timer.schedule(object : java.util.TimerTask() {
868
+ private var runs = 0
869
+ override fun run() {
870
+ if (IngestClient.shared == null) {
871
+ if (++runs >= INGEST_WATCH_MAX_RUNS) cancel()
872
+ return
873
+ }
874
+ cancel()
875
+ executor.execute { handOffToIngest() }
876
+ }
877
+ }, INGEST_WATCH_MS, INGEST_WATCH_MS)
878
+ }
728
879
  }
729
880
  }
730
881
 
882
+ /**
883
+ * Batch the captured events onto IngestClient as `error_batch` items. Not
884
+ * wired yet: they stay in [pendingEvents] (bounded in [enqueueEvent]).
885
+ * Executor thread only.
886
+ */
731
887
  private fun flushEventQueue() {
732
888
  if (pendingEvents.isEmpty()) return
733
- val cfg = config ?: return
889
+ if (config == null) return
890
+ val ingest = IngestClient.shared ?: return
891
+ val ctx = appContext ?: return
734
892
 
735
893
  val batch = pendingEvents.toList()
736
894
  pendingEvents.clear()
737
-
738
- // Round-C: prefer IngestClient when SwissKnife.configure has wired
739
- // it (the unified /ingest pipeline handles context stamping +
740
- // offline queue + retry centrally). Fall back to direct HTTP only
741
- // when the SDK was bootstrapped via SKCrashReporting.initialize
742
- // alone (e.g. integration tests).
743
- val ingest = com.appswissknife.net.IngestClient.shared
744
- val ctx = appContext
745
- if (ingest != null && ctx != null) {
746
- val itemsJson = org.json.JSONArray(batch.map { it.toJSON() })
747
- val data = JSONObject().put("items", itemsJson)
748
- ingest.enqueue(com.appswissknife.net.IngestItemType.ErrorBatch, data, ctx)
749
- return
895
+ // Normally under FLUSH_THRESHOLD, so one item as before; a backlog held
896
+ // before configure goes out in items of the same size.
897
+ for (chunk in batch.chunked(FLUSH_THRESHOLD)) {
898
+ val data = JSONObject().put("items", JSONArray(chunk.map { it.toJSON() }))
899
+ ingest.enqueue(IngestItemType.ErrorBatch, data, ctx)
750
900
  }
901
+ }
751
902
 
752
- // Round-D: legacy batch fallback uses the unified BackendHttpClient.
753
- try {
754
- val payload = JSONObject().apply {
755
- put("events", JSONArray(batch.map { it.toJSON() }))
756
- }
757
- val r = com.appswissknife.net.BackendHttpClient
758
- .create(cfg.apiKey, cfg.serverURL.ifEmpty { null })
759
- .simplePost(
760
- path = "/api/sdk/errors/event/batch",
761
- body = payload.toString(),
762
- )
763
- if (r.code !in 200..299) {
764
- println("[SwissKnife CrashReporting] batch send failed: HTTP ${r.code}")
765
- persistQueueToDisk(batch)
903
+ /**
904
+ * Put one item on IngestClient's durable queue, after anything held in
905
+ * [preConfigureItems]; before IngestClient is wired, hold it there.
906
+ * Returns true only when the item is on the durable queue. Lock-free,
907
+ * because the uncaught-exception handler calls it (session "crashed").
908
+ */
909
+ private fun deliver(type: IngestItemType, data: JSONObject): Boolean {
910
+ val ingest = IngestClient.shared
911
+ val ctx = appContext
912
+ if (ingest == null || ctx == null) {
913
+ preConfigureItems.addLast(type to data)
914
+ while (preConfigureItems.size > PRE_CONFIGURE_LIMIT) {
915
+ preConfigureItems.pollFirst()
916
+ notePreConfigureOverflow()
766
917
  }
767
- } catch (e: Exception) {
768
- println("[SwissKnife CrashReporting] batch send error: ${e.message}")
769
- persistQueueToDisk(batch)
918
+ return false
770
919
  }
920
+ drainPreConfigureItems(ingest, ctx)
921
+ return ingest.enqueue(type, data, ctx)
771
922
  }
772
923
 
773
- private fun persistQueueToDisk(events: List<SKErrorEvent>) {
774
- try {
775
- val ctx = appContext ?: return
776
- val file = File(ctx.filesDir, "swiss-knife-crash/pending-queue.json")
777
- file.parentFile?.mkdirs()
778
- val payload = JSONArray(events.map { it.toJSON() })
779
- file.writeText(payload.toString())
780
- } catch (e: Exception) {
781
- println("[SwissKnife CrashReporting] persistQueue error: ${e.message}")
924
+ /** Returns how many held items were handed to [ingest]. */
925
+ private fun drainPreConfigureItems(ingest: IngestClient, ctx: Context): Int {
926
+ var handed = 0
927
+ while (true) {
928
+ val (type, data) = preConfigureItems.pollFirst() ?: break
929
+ ingest.enqueue(type, data, ctx)
930
+ handed++
782
931
  }
932
+ return handed
783
933
  }
784
934
 
785
- private fun restorePersistedQueue() {
786
- try {
787
- val ctx = appContext ?: return
788
- val file = File(ctx.filesDir, "swiss-knife-crash/pending-queue.json")
789
- if (!file.exists()) return
790
- val text = file.readText()
791
- file.delete()
792
- val arr = JSONArray(text)
793
- // Re-enqueue as raw JSON events — send them as-is via the single-event endpoint
794
- for (i in 0 until arr.length()) {
795
- val json = arr.getJSONObject(i)
796
- sendRawPayload(json)
797
- }
798
- } catch (e: Exception) {
799
- println("[SwissKnife CrashReporting] restoreQueue error: ${e.message}")
935
+ /**
936
+ * Hand everything that waited for IngestClient to it: held items, the
937
+ * previous process's crash file and exit records, captured events.
938
+ * No-op until IngestClient is wired. Executor thread only.
939
+ */
940
+ private fun handOffToIngest() {
941
+ val ingest = IngestClient.shared ?: return
942
+ val ctx = appContext ?: return
943
+ if (config == null) return
944
+ if (drainPreConfigureItems(ingest, ctx) > 0) ingest.scheduleFlush(ctx)
945
+ flushPendingCrash()
946
+ if (exitInfoCheckDeferred && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
947
+ exitInfoCheckDeferred = false
948
+ checkPreviousNativeCrashes(ctx)
800
949
  }
950
+ flushEventQueue()
801
951
  }
802
952
 
803
- private fun sendRawPayload(json: JSONObject) {
804
- val cfg = config ?: return
805
- executor.execute {
806
- try {
807
- com.appswissknife.net.BackendHttpClient
808
- .create(cfg.apiKey, cfg.serverURL.ifEmpty { null })
809
- .simplePost(
810
- path = "/api/sdk/errors/event",
811
- body = json.toString(),
812
- )
813
- } catch (_: Exception) { /* best-effort */ }
953
+ private fun notePreConfigureOverflow() {
954
+ if (preConfigureOverflowLogged) return
955
+ preConfigureOverflowLogged = true
956
+ SKLog.warn("crash") {
957
+ "IngestClient is not wired (call SwissKnife.configureCore); holding the newest " +
958
+ "$PRE_CONFIGURE_LIMIT reports in memory and dropping older ones"
814
959
  }
815
960
  }
816
961
 
817
962
  /**
818
- * Legacy single-event send (used for crash flush, pending crash from prev session).
963
+ * Single-event send (ANR watchdog, ApplicationExitInfo, captureEvent).
819
964
  *
820
- * Returns true when the event is durable: persisted to IngestClient's
821
- * on-disk queue, or accepted (2xx) by the server on the direct path.
965
+ * Returns true when the event is durable: on IngestClient's on-disk
966
+ * queue. Before IngestClient is wired it is held in memory (see
967
+ * "Pre-configure buffer") and this returns false.
822
968
  */
823
969
  internal fun sendEventPayload(event: SKErrorEvent): Boolean {
824
- val cfg = config ?: return false
825
- // Round-C: prefer IngestClient when wired.
826
- val ingest = com.appswissknife.net.IngestClient.shared
827
- val ctx = appContext
828
- if (ingest != null && ctx != null) {
829
- return ingest.enqueue(com.appswissknife.net.IngestItemType.Error, event.toJSON(), ctx)
830
- }
831
- return try {
832
- val r = com.appswissknife.net.BackendHttpClient
833
- .create(cfg.apiKey, cfg.serverURL.ifEmpty { null })
834
- .simplePost(
835
- path = "/api/sdk/errors/event",
836
- body = event.toJSON().toString(),
837
- )
838
- if (r.code !in 200..299) {
839
- println("[SwissKnife CrashReporting] send failed: HTTP ${r.code}")
840
- }
841
- r.code in 200..299
842
- } catch (e: Exception) {
843
- println("[SwissKnife CrashReporting] send error: ${e.message}")
844
- false
845
- }
970
+ if (config == null) return false
971
+ return deliver(IngestItemType.Error, event.toJSON())
846
972
  }
847
973
 
848
974
  // MARK: - Pending Crash (disk)
849
975
 
850
- internal fun flushPendingCrash() {
851
- val file = pendingCrashFile ?: return
852
- if (!file.exists()) return
976
+ private fun isPendingCrashName(name: String) =
977
+ name.startsWith("pending-crash") && name.endsWith(".json")
853
978
 
854
- val cfg = config ?: return
855
- val data = file.readBytes()
979
+ /** Waiting crash files, oldest first. */
980
+ private fun pendingCrashFiles(dir: File): List<File> =
981
+ (dir.listFiles { f -> f.isFile && isPendingCrashName(f.name) } ?: emptyArray())
982
+ .sortedWith(compareBy<File>({ it.lastModified() }, { it.name }))
856
983
 
857
- // Prefer the durable ingest queue: once enqueued, IngestClient owns
858
- // delivery (and its 429 / 5xx backoff), so the file can go.
859
- val ingest = com.appswissknife.net.IngestClient.shared
860
- val ctx = appContext
861
- if (ingest != null && ctx != null) {
862
- val json = runCatching { JSONObject(String(data, Charsets.UTF_8)) }.getOrNull()
863
- if (json == null) {
864
- file.delete() // unreadable — retrying can never help
865
- return
866
- }
867
- if (ingest.enqueue(com.appswissknife.net.IngestItemType.Error, json, ctx)) {
868
- file.delete()
869
- ingest.scheduleFlush(ctx)
870
- }
871
- return
872
- }
984
+ /**
985
+ * Move every waiting crash file onto IngestClient's durable queue. Before
986
+ * IngestClient is wired the files stay where they are (they are already
987
+ * durable) and the next hand-off picks them up.
988
+ */
989
+ internal fun flushPendingCrash() {
990
+ synchronized(crashFileLock) {
991
+ val dir = crashDir ?: return
992
+ if (config == null) return
993
+ val ingest = IngestClient.shared ?: return
994
+ val ctx = appContext ?: return
873
995
 
874
- executor.execute {
875
- try {
876
- val r = com.appswissknife.net.BackendHttpClient
877
- .create(cfg.apiKey, cfg.serverURL.ifEmpty { null })
878
- .simplePost(
879
- path = "/api/sdk/errors/event",
880
- body = String(data, Charsets.UTF_8),
881
- )
882
- if (isRetryableStatus(r.code)) {
883
- // Throttled (429) or server trouble: keep the file for
884
- // the next launch instead of dropping the crash.
885
- println("[SwissKnife CrashReporting] pending crash send deferred: HTTP ${r.code}")
886
- } else {
887
- if (r.code !in 200..299) {
888
- println("[SwissKnife CrashReporting] pending crash rejected: HTTP ${r.code}")
889
- }
890
- file.delete()
996
+ var queued = false
997
+ for (file in pendingCrashFiles(dir)) {
998
+ val text = runCatching { file.readText(Charsets.UTF_8) }.getOrNull() ?: continue
999
+ val json = runCatching { JSONObject(text) }.getOrNull()
1000
+ if (json == null) {
1001
+ file.delete() // unparsable — retrying can never help
1002
+ continue
891
1003
  }
892
- } catch (e: Exception) {
893
- // Network error — keep the file for the next launch.
894
- println("[SwissKnife CrashReporting] pending crash send error: ${e.message}")
1004
+ // Once enqueued, IngestClient owns delivery (and its 429 / 5xx
1005
+ // backoff), so the file can go. A refused write keeps the rest
1006
+ // for the next hand-off.
1007
+ if (!ingest.enqueue(IngestItemType.Error, json, ctx)) break
1008
+ file.delete()
1009
+ queued = true
895
1010
  }
1011
+ if (queued) ingest.scheduleFlush(ctx)
896
1012
  }
897
1013
  }
898
1014
 
899
- /** 429 and 5xx may succeed later; any other status is final. */
900
- internal fun isRetryableStatus(code: Int): Boolean = code == 429 || code >= 500
1015
+ /**
1016
+ * Drop what an interrupted write left behind and the oldest waiting crash
1017
+ * files past [MAX_PENDING_CRASH_FILES]. Called by init(), before this
1018
+ * process can crash into the directory.
1019
+ */
1020
+ private fun prunePendingCrashFiles() {
1021
+ val dir = crashDir ?: return
1022
+ runCatching {
1023
+ dir.listFiles { f -> f.name.startsWith("pending-crash") && f.name.endsWith(".tmp") }
1024
+ ?.forEach { it.delete() }
1025
+ val waiting = pendingCrashFiles(dir)
1026
+ waiting.take((waiting.size - MAX_PENDING_CRASH_FILES).coerceAtLeast(0))
1027
+ .forEach { it.delete() }
1028
+ }
1029
+ }
901
1030
 
1031
+ /**
1032
+ * Crash-handler context: plain file IO, no locks. See "Pending crash
1033
+ * files": a crash that is still waiting is never overwritten.
1034
+ */
902
1035
  internal fun writeCrashToDisk(event: SKErrorEvent) {
903
1036
  try {
904
- val file = pendingCrashFile ?: return
905
- file.parentFile?.mkdirs()
906
- file.writeText(event.toJSON().toString())
1037
+ val dir = crashDir ?: return
1038
+ dir.mkdirs()
1039
+ val first = File(dir, PENDING_CRASH_FILE)
1040
+ val target = if (!first.exists()) first else {
1041
+ val id = event.eventId.filter { it.isLetterOrDigit() || it == '-' }.take(64)
1042
+ File(dir, "pending-crash-${System.currentTimeMillis()}-$id.json")
1043
+ }
1044
+ val json = event.toJSON().toString()
1045
+ val tmp = File(dir, "${target.name}.tmp")
1046
+ tmp.writeText(json)
1047
+ if (!tmp.renameTo(target)) {
1048
+ target.writeText(json)
1049
+ tmp.delete()
1050
+ }
907
1051
  } catch (e: Exception) {
908
1052
  println("[SwissKnife CrashReporting] writeCrashToDisk error: ${e.message}")
909
1053
  }
@@ -942,60 +1086,67 @@ object SKCrashReporting {
942
1086
  put("deviceModel", Build.MODEL)
943
1087
  }
944
1088
 
945
- // Round-C: prefer IngestClient when wired.
946
- val ingest = com.appswissknife.net.IngestClient.shared
947
- if (ingest != null) {
948
- ingest.enqueue(com.appswissknife.net.IngestItemType.Session, body, ctx)
949
- return
950
- }
951
-
952
- executor.execute {
953
- try {
954
- com.appswissknife.net.BackendHttpClient
955
- .create(cfg.apiKey, cfg.serverURL.ifEmpty { null })
956
- .simplePost(
957
- path = "/api/sdk/errors/session",
958
- body = body.toString(),
959
- )
960
- } catch (e: Exception) {
961
- println("[SwissKnife CrashReporting] session event error: ${e.message}")
962
- }
963
- }
1089
+ deliver(IngestItemType.Session, body)
964
1090
  }
965
1091
 
966
1092
  // MARK: - Auto-Breadcrumbs
967
1093
 
968
1094
  private fun registerActivityLifecycle(context: Context) {
969
1095
  val app = context as? android.app.Application ?: return
1096
+ if (lifecycleRegisteredOn === app) return // once per Application
1097
+ lifecycleRegisteredOn = app
970
1098
  app.registerActivityLifecycleCallbacks(object : android.app.Application.ActivityLifecycleCallbacks {
971
1099
  override fun onActivityCreated(activity: android.app.Activity, b: android.os.Bundle?) {
972
1100
  addBreadcrumb(SKBreadcrumb(category = "activity.lifecycle", message = "${activity.localClassName}: created"))
973
1101
  }
1102
+ // A resumed or paused activity is a started one. Recording it here
1103
+ // too tracks an activity that started before `init()` from its
1104
+ // first callback, so a translucent one closing over it (a billing
1105
+ // sheet) does not end the session.
974
1106
  override fun onActivityResumed(activity: android.app.Activity) {
1107
+ startedActivities.add(System.identityHashCode(activity))
975
1108
  addBreadcrumb(SKBreadcrumb(category = "activity.lifecycle", message = "${activity.localClassName}: resumed"))
976
1109
  }
977
1110
  override fun onActivityPaused(activity: android.app.Activity) {
1111
+ startedActivities.add(System.identityHashCode(activity))
978
1112
  addBreadcrumb(SKBreadcrumb(category = "activity.lifecycle", message = "${activity.localClassName}: paused"))
979
- endSession()
980
1113
  }
981
- override fun onActivityStarted(activity: android.app.Activity) {}
982
- override fun onActivityStopped(activity: android.app.Activity) {}
1114
+ override fun onActivityStarted(activity: android.app.Activity) {
1115
+ startedActivities.add(System.identityHashCode(activity))
1116
+ }
1117
+ override fun onActivityStopped(activity: android.app.Activity) {
1118
+ startedActivities.remove(System.identityHashCode(activity))
1119
+ // A rotation stops the activity and starts its replacement
1120
+ // straight away: not the end of a session.
1121
+ if (activity.isChangingConfigurations) return
1122
+ // Nothing left on screen: the app went to the background. An
1123
+ // activity started before `init()` (React Native initialises
1124
+ // from JS, after MainActivity started) is not in the set, so
1125
+ // its stop with nothing else started also lands here.
1126
+ if (startedActivities.isEmpty()) endSession()
1127
+ }
983
1128
  override fun onActivitySaveInstanceState(activity: android.app.Activity, b: android.os.Bundle) {}
984
1129
  override fun onActivityDestroyed(activity: android.app.Activity) {}
985
1130
  })
986
1131
  }
987
1132
 
988
1133
  private fun registerConnectivityObserver(context: Context) {
1134
+ if (connectivityRegisteredOn === context) return // once per context
989
1135
  val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager ?: return
990
1136
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
991
- cm.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
992
- override fun onAvailable(network: Network) {
993
- addBreadcrumb(SKBreadcrumb(category = "connectivity", message = "network available"))
994
- }
995
- override fun onLost(network: Network) {
996
- addBreadcrumb(SKBreadcrumb(category = "connectivity", message = "network lost"))
997
- }
998
- })
1137
+ // Breadcrumbs only: a missing permission or the per-app callback
1138
+ // limit (TooManyRequestsException) must not fail `init()`.
1139
+ runCatching {
1140
+ cm.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
1141
+ override fun onAvailable(network: Network) {
1142
+ addBreadcrumb(SKBreadcrumb(category = "connectivity", message = "network available"))
1143
+ }
1144
+ override fun onLost(network: Network) {
1145
+ addBreadcrumb(SKBreadcrumb(category = "connectivity", message = "network lost"))
1146
+ }
1147
+ })
1148
+ connectivityRegisteredOn = context
1149
+ }.onFailure { println("[SwissKnife CrashReporting] connectivity breadcrumbs unavailable: ${it.message}") }
999
1150
  }
1000
1151
  }
1001
1152
 
@@ -1320,8 +1471,16 @@ object SKCrashReporting {
1320
1471
  anrWatchdog = null
1321
1472
  sessionErrorCount = 0
1322
1473
  pendingEvents.clear()
1474
+ preConfigureItems.clear()
1475
+ exitInfoCheckDeferred = false
1476
+ preConfigureOverflowLogged = false
1323
1477
  flushTimer?.cancel()
1324
1478
  flushTimer = null
1479
+ // Let the next test's `init()` install against ITS default handler.
1480
+ // (Callers restore the default handler themselves.)
1481
+ crashHandlerInstalled.set(false)
1482
+ originalExceptionHandler = null
1483
+ startedActivities.clear()
1325
1484
  }
1326
1485
  }
1327
1486