@app-swiss-knife/react-native-sdk 0.3.2 → 0.4.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.
@@ -24,8 +24,11 @@
24
24
  // - Identity / Session / DeviceContext / Clock are stamped at flush time
25
25
  // (late-bind to mirror RevenueCat's identify semantics).
26
26
  // - 4xx → dead-letter (validation reject is not retriable).
27
- // 5xx / network → retry with shared ExponentialBackoff.
28
- // After budget → dead-letter.
27
+ // 429 / 5xx / network → the batch STAYS QUEUED and a client-wide
28
+ // "do not send before" window is armed: the server's Retry-After when it
29
+ // sent one, else an exponential backoff. The worker books a delayed
30
+ // flush for the end of that window. Nothing is dropped or dead-lettered
31
+ // for being throttled (W4d — the server now rate limits per device).
29
32
  // - 2xx with a body we cannot parse → AMBIGUOUS, not success. We have no
30
33
  // evidence the server accepted anything, so the batch stays queued and
31
34
  // the worker retries it. Deletion from the durable queue happens only on
@@ -48,7 +51,6 @@ import androidx.annotation.VisibleForTesting
48
51
  import androidx.work.BackoffPolicy
49
52
  import androidx.work.Constraints
50
53
  import androidx.work.CoroutineWorker
51
- import androidx.work.Data
52
54
  import androidx.work.ExistingWorkPolicy
53
55
  import androidx.work.NetworkType
54
56
  import androidx.work.OneTimeWorkRequestBuilder
@@ -214,7 +216,7 @@ internal object IngestPlaceholderDevice {
214
216
  appBuild = "unknown",
215
217
  locale = Locale.getDefault().toString(),
216
218
  timezone = TimeZone.getDefault().id,
217
- sdkVersion = "0.3.2",
219
+ sdkVersion = "0.4.0",
218
220
  bundleIdentifier = null,
219
221
  )
220
222
  }
@@ -285,6 +287,8 @@ internal class IngestClient(
285
287
  private val deviceSnapshot: () -> DeviceContextSnapshot = { IngestPlaceholderDevice.supplier() },
286
288
  private val sessionSnapshot: () -> Pair<String, Int> = { IngestPlaceholderSession.supplier() },
287
289
  private val timestampProvider: () -> Long = { IngestPlaceholderClock.supplier() },
290
+ /** Wall clock for the backoff window (a seam for tests). */
291
+ private val nowMillis: () -> Long = { System.currentTimeMillis() },
288
292
  ) {
289
293
 
290
294
  companion object {
@@ -305,6 +309,15 @@ internal class IngestClient(
305
309
  */
306
310
  const val MAX_AMBIGUOUS_ATTEMPTS = 5
307
311
 
312
+ /** First step of the backoff when the server sent no Retry-After. */
313
+ const val BACKOFF_INITIAL_MS = 1_000L
314
+
315
+ /** Ceiling for the backoff AND for an honoured Retry-After. */
316
+ const val BACKOFF_MAX_MS = 5 * 60_000L
317
+
318
+ /** Unique WorkManager name for the delayed (post-backoff) flush. */
319
+ const val DELAYED_FLUSH_WORK_NAME = "swissknife.ingest_flush_delayed"
320
+
308
321
  /**
309
322
  * Process-wide instance — wired by SwissKnife.configure (Commit 3).
310
323
  * Tests construct their own. Direct read access is internal-only;
@@ -370,32 +383,44 @@ internal class IngestClient(
370
383
  private var ambiguousAttempts: Int = 0
371
384
  private var ambiguousBatchIds: Set<String> = emptySet()
372
385
 
386
+ /**
387
+ * Client-wide backoff window: no drain sends before [backoffUntilMs].
388
+ * Armed by a 429 / 5xx / network failure, cleared by the first accepted
389
+ * batch. [consecutiveFailures] drives the exponential step when the
390
+ * server gave no Retry-After.
391
+ */
392
+ @Volatile
393
+ private var backoffUntilMs: Long = 0L
394
+ @Volatile
395
+ private var consecutiveFailures: Int = 0
396
+
373
397
  // -------- Public enqueue API --------
374
398
 
375
399
  /**
376
400
  * Enqueue an IngestItem. Synchronous up to disk write — on return the
377
401
  * item is on disk (fsync'd inside OfflineQueueStore). Crossing
378
- * batchSize triggers a WorkManager flush.
402
+ * batchSize triggers a WorkManager flush. Returns false if the disk
403
+ * write failed (the item is NOT queued).
379
404
  */
380
- fun enqueue(item: IngestItem, context: Context) {
405
+ fun enqueue(item: IngestItem, context: Context): Boolean {
381
406
  try {
382
407
  queue.append(item)
383
408
  } catch (e: IOException) {
384
409
  Log.w(TAG, "enqueue failed", e)
385
- return
410
+ return false
386
411
  }
387
- val count = runCatching { queue.count() }.getOrNull() ?: return
412
+ val count = runCatching { queue.count() }.getOrNull() ?: return true
388
413
  if (count >= batchSize) {
389
414
  scheduleFlush(context)
390
415
  }
416
+ return true
391
417
  }
392
418
 
393
419
  /**
394
420
  * Convenience — build an item from type + JSON data.
395
421
  */
396
- fun enqueue(type: IngestItemType, data: JSONObject, context: Context) {
422
+ fun enqueue(type: IngestItemType, data: JSONObject, context: Context): Boolean =
397
423
  enqueue(IngestItem.create(type, data), context)
398
- }
399
424
 
400
425
  /**
401
426
  * Schedule a flush via WorkManager. KEEP coalesces concurrent enqueues.
@@ -445,6 +470,9 @@ internal class IngestClient(
445
470
  @Throws(IOException::class)
446
471
  fun flushSync(): IngestResult {
447
472
  if (!isReachable) return IngestResult(queued = 0, errors = emptyList())
473
+ // Inside a backoff window: not now, not never. The items stay on disk
474
+ // and the delayed flush booked with the window comes back for them.
475
+ if (backoffRemainingMillis() > 0L) return IngestResult(queued = 0, errors = emptyList())
448
476
  var totalQueued = 0
449
477
  val aggregateErrors = mutableListOf<IngestErrorEntry>()
450
478
  while (true) {
@@ -453,22 +481,21 @@ internal class IngestClient(
453
481
  val batch = items.take(batchSize)
454
482
  val envelope = buildEnvelope(batch)
455
483
  val resp = try {
456
- http.postRaw(path, envelope.toString())
484
+ // One attempt per drain: the retry lives between drains (the
485
+ // backoff window below), not inside one request — sleeping
486
+ // through Retry-After in-call would hold the worker hostage.
487
+ http.postRaw(path, envelope.toString(), maxRetries = 0)
457
488
  } catch (e: BackendRejected) {
458
489
  // Whole batch rejected → dead-letter all.
459
490
  queue.deadLetter(batch)
460
491
  queue.remove(batch.map { it.id }.toSet())
461
492
  throw e
462
493
  } catch (e: BackendUnavailable) {
463
- // BackendUnavailable here means the bounded retry budget in
464
- // BackendHttpClient.kt:358 has already been exhausted.
465
- // Do NOT wrap in another retry — that would double-count
466
- // attempts and silently extend the effective retry window.
467
- // The batch is dead-lettered (not discarded) so it can be
468
- // inspected offline; retrying at this layer would only delay
469
- // the dead-letter and mask real backend degradation.
470
- queue.deadLetter(batch)
471
- queue.remove(batch.map { it.id }.toSet())
494
+ // 429 / 5xx / network: the server may answer differently in a
495
+ // moment, so the batch stays queued (it used to be
496
+ // dead-lettered here, which silently lost rate-limited crash
497
+ // reports). Arm the window; the worker books the retry.
498
+ armBackoff(e.retryAfterMillis)
472
499
  throw e
473
500
  }
474
501
  val batchIds = batch.map { it.id }.toSet()
@@ -506,6 +533,7 @@ internal class IngestClient(
506
533
  }
507
534
  // A parseable answer — the server is talking sense again.
508
535
  clearAmbiguousStreak()
536
+ clearBackoff()
509
537
  totalQueued += parsed.queued
510
538
  aggregateErrors.addAll(parsed.errors)
511
539
  val errorIdxs = parsed.errors.map { it.index }.toSet()
@@ -521,6 +549,50 @@ internal class IngestClient(
521
549
  return IngestResult(queued = totalQueued, errors = aggregateErrors)
522
550
  }
523
551
 
552
+ /** Milliseconds left in the backoff window; 0 when sends may go out. */
553
+ fun backoffRemainingMillis(): Long =
554
+ (backoffUntilMs - nowMillis()).coerceAtLeast(0L)
555
+
556
+ private fun armBackoff(retryAfterMillis: Long?) {
557
+ val step = BACKOFF_INITIAL_MS shl consecutiveFailures.coerceAtMost(20)
558
+ consecutiveFailures += 1
559
+ val scheduled = step.coerceAtMost(BACKOFF_MAX_MS)
560
+ val honoured = retryAfterMillis?.takeIf { it > 0L }?.coerceAtMost(BACKOFF_MAX_MS)
561
+ val wait = maxOf(scheduled, honoured ?: 0L)
562
+ // The window only ever moves forward.
563
+ backoffUntilMs = maxOf(backoffUntilMs, nowMillis() + wait)
564
+ }
565
+
566
+ private fun clearBackoff() {
567
+ consecutiveFailures = 0
568
+ backoffUntilMs = 0L
569
+ }
570
+
571
+ /**
572
+ * Book a flush for when the backoff window closes. A separate unique
573
+ * work name from [scheduleFlush] so it can be booked from INSIDE the
574
+ * running flush worker (KEEP on the same name would be a no-op against
575
+ * the worker that is still running).
576
+ */
577
+ fun scheduleDelayedFlush(context: Context, delayMillis: Long) {
578
+ val ctx = context.applicationContext ?: context
579
+ val request = OneTimeWorkRequestBuilder<IngestFlushWorker>()
580
+ .setConstraints(
581
+ Constraints.Builder()
582
+ .setRequiredNetworkType(NetworkType.CONNECTED)
583
+ .build()
584
+ )
585
+ .setInitialDelay(delayMillis.coerceAtLeast(0L), TimeUnit.MILLISECONDS)
586
+ .build()
587
+ runCatching {
588
+ WorkManager.getInstance(ctx).enqueueUniqueWork(
589
+ DELAYED_FLUSH_WORK_NAME,
590
+ ExistingWorkPolicy.REPLACE,
591
+ request,
592
+ )
593
+ }
594
+ }
595
+
524
596
  /**
525
597
  * Record one undecodable-success response for [batchIds]; returns the
526
598
  * running count. A different head-of-queue batch restarts the count.
@@ -646,8 +718,9 @@ internal class IngestClient(
646
718
  * Why WorkManager (vs. coroutine on an internal pool)?
647
719
  * - Survives process death — system reschedules after a kill.
648
720
  * - Network constraint is system-managed — waits for connectivity.
649
- * - Exponential backoff is system-managed — no in-app retry loop
650
- * burning wakelocks.
721
+ * - Backoff without an in-app retry loop burning wakelocks: a throttled
722
+ * or failed drain books a delayed one-time request for the end of the
723
+ * client's backoff window (which honours the server's Retry-After).
651
724
  * - Doze + App Standby aware out of the box.
652
725
  */
653
726
  internal class IngestFlushWorker(
@@ -675,15 +748,14 @@ internal class IngestFlushWorker(
675
748
  Log.w(TAG, "ingest 4xx rejected: ${e.code}", e)
676
749
  Result.success()
677
750
  } catch (e: BackendUnavailable) {
678
- if (runAttemptCount + 1 >= MAX_ATTEMPTS) {
679
- Log.w(TAG, "ingest 5xx after $MAX_ATTEMPTS attempts; giving up", e)
680
- Result.success(
681
- Data.Builder().putBoolean("dead_lettered", true).build()
682
- )
683
- } else {
684
- Log.w(TAG, "ingest 5xx attempt ${runAttemptCount + 1}; will retry", e)
685
- Result.retry()
686
- }
751
+ // 429 / 5xx / network. The batch is still queued and flushSync
752
+ // armed the backoff window (Retry-After when the server sent
753
+ // one). Come back when it closes — WorkManager's own backoff
754
+ // cannot honour Retry-After, so book a delayed run instead.
755
+ val delay = client.backoffRemainingMillis()
756
+ Log.w(TAG, "ingest unavailable (${e.code}); retrying in ${delay}ms", e)
757
+ client.scheduleDelayedFlush(applicationContext, delay)
758
+ Result.success()
687
759
  } catch (e: UndecodableIngestResponse) {
688
760
  // A 2xx we could not parse. flushSync has kept the batch queued
689
761
  // and owns the give-up decision (IngestClient.MAX_AMBIGUOUS_ATTEMPTS),
@@ -99,7 +99,7 @@ internal enum DeviceContextProvider {
99
99
  /// Round A baseline. The build pipeline (`swiss-build`) will eventually
100
100
  /// inject this via `-D` flag, but for now keep it in source so we don't
101
101
  /// have to thread build settings through the SPM Package.swift.
102
- static let sdkVersionConstant: String = "0.3.2"
102
+ static let sdkVersionConstant: String = "0.4.0"
103
103
 
104
104
  private static let cacheLock = DispatchQueue(label: "com.swissknife.context.device")
105
105
  private static var cached: DeviceContext?
@@ -454,9 +454,13 @@ public final class SKCrashReporting {
454
454
  // on disk for the whole next session. Schedule a launch-time flush
455
455
  // BEHIND the recovery enqueues on the same serial queue, so the items
456
456
  // are on the ingest queue before the drain starts.
457
- let recoveredSignalCrash = flushSignalMarker()
458
- let recoveredPendingCrash = flushPendingCrash()
459
- if recoveredSignalCrash || recoveredPendingCrash {
457
+ //
458
+ // The NSException report is recovered FIRST: whether the signal report
459
+ // is a duplicate depends on that report having actually been read,
460
+ // decoded and enqueued (see `isNSExceptionAbortDuplicate`).
461
+ let recoveredNSExceptionAt = flushPendingCrash()
462
+ let recoveredSignalCrash = flushSignalMarker(recoveredNSExceptionAt: recoveredNSExceptionAt)
463
+ if recoveredSignalCrash || recoveredNSExceptionAt != nil {
460
464
  queue.async { [ingest] in
461
465
  ingest.scheduleImmediateFlush()
462
466
  }
@@ -886,27 +890,66 @@ public final class SKCrashReporting {
886
890
 
887
891
  // MARK: - Pending Crash (disk)
888
892
 
889
- /// Returns `true` when a pending crash was recovered and enqueued —
890
- /// `start()` uses this to trigger the launch-time ingest flush.
891
- private func flushPendingCrash() -> Bool {
893
+ /// Returns the crash instant (the file's mtime) when a pending
894
+ /// NSException crash was recovered and enqueued, `nil` otherwise. `start()`
895
+ /// uses it to trigger the launch-time ingest flush and to pair the report
896
+ /// with the SIGABRT the same crash left behind.
897
+ private func flushPendingCrash() -> Date? {
892
898
  let url = SKCrashReporting.pendingCrashURL
893
899
  guard FileManager.default.fileExists(atPath: url.path),
894
- let data = try? Data(contentsOf: url) else { return false }
900
+ let data = try? Data(contentsOf: url) else { return nil }
901
+ let crashedAt = (try? FileManager.default.attributesOfItem(atPath: url.path))?[.modificationDate] as? Date
895
902
 
896
903
  // Delete before sending to avoid re-sending on failure (best-effort delivery)
897
904
  try? FileManager.default.removeItem(at: url)
898
905
 
899
- guard configuration != nil else { return false }
906
+ guard configuration != nil else { return nil }
900
907
  // The crash JSON on disk is a single SKErrorEvent. Decode and
901
908
  // re-enqueue through IngestClient so retry / batching / context
902
909
  // stamping all happen uniformly with live errors.
903
910
  let decoder = JSONDecoder()
904
911
  decoder.dateDecodingStrategy = .iso8601
905
- if let event = try? decoder.decode(SKErrorEvent.self, from: data) {
906
- sendEvent(event)
907
- return true
908
- }
909
- return false
912
+ guard let event = try? decoder.decode(SKErrorEvent.self, from: data) else { return nil }
913
+ sendEvent(event)
914
+ return crashedAt ?? Date.distantPast
915
+ }
916
+
917
+ /// How long after the NSException report was written its `abort()` tail
918
+ /// may land in the signal marker. The gap is the rest of the exception
919
+ /// handler (session close) plus any chained incumbent handler — well under
920
+ /// a second in practice. A relaunch plus a new crash cannot fit inside it.
921
+ internal static let nsExceptionAbortPairingWindow: TimeInterval = 10
922
+
923
+ /// Whether a recovered signal report is the `abort()` tail of an uncaught
924
+ /// NSException, and must therefore be dropped.
925
+ ///
926
+ /// An uncaught NSException does not end the process by itself: the ObjC
927
+ /// runtime calls our handler, which writes `pending-crash.json`, and then
928
+ /// `abort()`s, which raises SIGABRT and runs our signal handler too. Both
929
+ /// used to be reported, so every NSException crash arrived as TWO events —
930
+ /// the real one and a "Signal 6" that grouped into its own issue.
931
+ ///
932
+ /// The signal report is dropped only when ALL of these hold, so a crash is
933
+ /// never left with zero events:
934
+ /// - the signal is SIGABRT (any other signal is a separate fault);
935
+ /// - the NSException report was actually recovered — read, decoded and
936
+ /// enqueued (`recoveredNSExceptionAt != nil`). If the handler died before
937
+ /// finishing the write, or the file no longer decodes, the signal report
938
+ /// is the only record and is kept;
939
+ /// - the two files belong to the same crash: the NSException report was
940
+ /// written at most `nsExceptionAbortPairingWindow` before the signal
941
+ /// marker. A stale report left by an earlier run (e.g. unreadable during
942
+ /// a locked-device relaunch) cannot swallow a later, unrelated abort().
943
+ internal static func isNSExceptionAbortDuplicate(
944
+ signal: Int32?,
945
+ recoveredNSExceptionAt: Date?,
946
+ signalAt: Date
947
+ ) -> Bool {
948
+ guard signal == SIGABRT, let nsExceptionAt = recoveredNSExceptionAt else { return false }
949
+ let gap = signalAt.timeIntervalSince(nsExceptionAt)
950
+ // Small negative slack: both mtimes come from the same clock, but
951
+ // filesystem timestamp granularity can order them either way.
952
+ return gap >= -1 && gap <= nsExceptionAbortPairingWindow
910
953
  }
911
954
 
912
955
  /// On next launch, read the signal marker file + backtrace binary +
@@ -915,7 +958,7 @@ public final class SKCrashReporting {
915
958
  /// marker and raw backtrace addresses to the backtrace-bin file.
916
959
  /// Returns `true` when a signal crash was recovered and enqueued —
917
960
  /// `start()` uses this to trigger the launch-time ingest flush.
918
- private func flushSignalMarker() -> Bool {
961
+ private func flushSignalMarker(recoveredNSExceptionAt: Date? = nil) -> Bool {
919
962
  let markerURL = SKCrashReporting.signalMarkerURL
920
963
  let contextURL = SKCrashReporting.persistedContextURL
921
964
  let backtraceURL = SKCrashReporting.backtraceFileURL
@@ -932,6 +975,21 @@ public final class SKCrashReporting {
932
975
 
933
976
  let signalString = String(data: markerData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "unknown"
934
977
 
978
+ // The SIGABRT that follows an uncaught NSException is the same crash
979
+ // the NSException handler already recorded (pending-crash.json, just
980
+ // sent by `flushPendingCrash`) — including its crashed-session close,
981
+ // which that handler sends at crash time. Drop the whole signal report
982
+ // and its artifacts rather than emitting a second, worse event.
983
+ if SKCrashReporting.isNSExceptionAbortDuplicate(
984
+ signal: Int32(signalString),
985
+ recoveredNSExceptionAt: recoveredNSExceptionAt,
986
+ signalAt: crashedAt
987
+ ) {
988
+ try? FileManager.default.removeItem(at: backtraceURL)
989
+ try? FileManager.default.removeItem(at: contextURL)
990
+ return false
991
+ }
992
+
935
993
  // Build event from persisted context (if available)
936
994
  var event = SKErrorEvent(level: .fatal)
937
995
  event.exceptionType = "Signal"
@@ -1076,18 +1134,12 @@ public final class SKCrashReporting {
1076
1134
  // stack of 35 real frames contributed NOTHING and every SIGSEGV in
1077
1135
  // the app fell back to the constant "Signal|Signal 11" and landed
1078
1136
  // in one undifferentiated issue.
1079
- if let path = imagePath,
1080
- !SKCrashReporting.appBundlePath.isEmpty,
1081
- path.hasPrefix(SKCrashReporting.appBundlePath) {
1082
- isInApp = true
1083
- } else if let appExec = appExecutable {
1084
- isInApp = imageName == appExec
1085
- } else {
1086
- let img = imageName ?? ""
1087
- isInApp = !img.hasPrefix("lib") && !img.hasPrefix("_")
1088
- && img != "UIKitCore" && img != "Foundation"
1089
- && img != "CoreFoundation" && img != "libdyld.dylib"
1090
- }
1137
+ isInApp = SKCrashReporting.isInAppImage(
1138
+ imagePath: imagePath,
1139
+ imageName: imageName,
1140
+ appExecutable: appExecutable,
1141
+ appBundlePath: SKCrashReporting.appBundlePath
1142
+ )
1091
1143
  } else {
1092
1144
  symbolName = nil
1093
1145
  imageName = nil
@@ -1105,6 +1157,47 @@ public final class SKCrashReporting {
1105
1157
  )
1106
1158
  }
1107
1159
 
1160
+ /// The ONE in-app rule, shared by `symbolicate(address:)` (signal / ANR
1161
+ /// frames) and `parseCallStackSymbols` (NSException / captured-error
1162
+ /// frames). Two rules used to exist; the symbol-line parser compared the
1163
+ /// image name against the main executable only, so an Xcode 16 debug
1164
+ /// build (whose code lives in `<App>.debug.dylib`) and every embedded
1165
+ /// framework came out not-in-app, and those stacks contributed nothing to
1166
+ /// grouping.
1167
+ ///
1168
+ /// 1. A known image path under the app bundle is in-app — main executable,
1169
+ /// `.debug.dylib`, and everything under `Frameworks/`.
1170
+ /// 2. With no path, the main executable name or its `.debug.dylib` twin.
1171
+ /// 3. With no executable name either, a denylist of system image names.
1172
+ internal static func isInAppImage(
1173
+ imagePath: String?,
1174
+ imageName: String?,
1175
+ appExecutable: String?,
1176
+ appBundlePath: String
1177
+ ) -> Bool {
1178
+ if let path = imagePath, !appBundlePath.isEmpty {
1179
+ let bundle = appBundlePath.hasSuffix("/") ? appBundlePath : appBundlePath + "/"
1180
+ if path.hasPrefix(bundle) { return true }
1181
+ }
1182
+ if let appExec = appExecutable, !appExec.isEmpty {
1183
+ return imageName == appExec || imageName == appExec + ".debug.dylib"
1184
+ }
1185
+ let img = imageName ?? ""
1186
+ return !img.isEmpty && !img.hasPrefix("lib") && !img.hasPrefix("_")
1187
+ && img != "UIKitCore" && img != "Foundation"
1188
+ && img != "CoreFoundation" && img != "libdyld.dylib"
1189
+ }
1190
+
1191
+ /// Image path for a live in-process address, via `dladdr`. Ordinary
1192
+ /// threads only.
1193
+ private static func imagePath(forAddress address: UInt) -> String? {
1194
+ guard address != 0 else { return nil }
1195
+ var info = Dl_info()
1196
+ guard dladdr(UnsafeRawPointer(bitPattern: address), &info) != 0,
1197
+ let fname = info.dli_fname else { return nil }
1198
+ return String(cString: fname)
1199
+ }
1200
+
1108
1201
  internal func writeCrashToDisk(_ event: SKErrorEvent) {
1109
1202
  let encoder = JSONEncoder()
1110
1203
  encoder.dateEncodingStrategy = .iso8601
@@ -1282,18 +1375,35 @@ public final class SKCrashReporting {
1282
1375
  }
1283
1376
 
1284
1377
  private func captureANR() {
1285
- // Capture main thread stack trace via thread_get_state if possible,
1286
- // otherwise fall back to current thread symbols as a hint.
1287
- let frames = captureMainThreadStack()
1288
-
1378
+ // Capture the main thread's stack via thread_get_state. When that is
1379
+ // impossible the event is sent WITHOUT a stack: the only other stack
1380
+ // available is the watchdog thread's own, which is identical for
1381
+ // every ANR and would group them all under the watchdog's frames.
1289
1382
  var event = buildEvent(level: .error)
1290
1383
  event.message = "Application Not Responding"
1291
1384
  event.mechanism = "anr"
1292
- event.stacktrace = frames
1385
+ SKCrashReporting.applyANRStack(captureMainThreadStack(), to: &event)
1293
1386
  guard let finalEvent = applyBeforeSend(event) else { return }
1294
1387
  sendEvent(finalEvent)
1295
1388
  }
1296
1389
 
1390
+ /// Extra key set on an ANR event whose main-thread stack could not be read.
1391
+ internal static let anrStackUnavailableExtraKey = "anr_stack"
1392
+
1393
+ /// Attach the main-thread stack to an ANR event, or — when it could not be
1394
+ /// captured — no stack at all plus an explicit marker, so the dashboard
1395
+ /// can say "stack unavailable" instead of showing the watchdog's frames.
1396
+ internal static func applyANRStack(_ frames: [SKStackFrame]?, to event: inout SKErrorEvent) {
1397
+ if let frames, !frames.isEmpty {
1398
+ event.stacktrace = frames
1399
+ return
1400
+ }
1401
+ event.stacktrace = nil
1402
+ var extra = event.extra ?? [:]
1403
+ extra[anrStackUnavailableExtraKey] = "unavailable"
1404
+ event.extra = extra
1405
+ }
1406
+
1297
1407
  /// Capture the main thread's stack trace using Mach thread APIs.
1298
1408
  ///
1299
1409
  /// The watchdog thread suspends the main thread, reads its register
@@ -1305,21 +1415,20 @@ public final class SKCrashReporting {
1305
1415
  /// here would deadlock the watchdog against it. The address buffer is
1306
1416
  /// therefore pre-allocated before the suspend.
1307
1417
  ///
1308
- /// Falls back to the watchdog thread's own `Thread.callStackSymbols`
1309
- /// (far less useful, but a signal that an ANR happened) if the main
1310
- /// thread cannot be inspected.
1311
- private func captureMainThreadStack() -> [SKStackFrame] {
1418
+ /// Returns `nil` if the main thread cannot be inspected. It deliberately
1419
+ /// does NOT fall back to the watchdog thread's own stack — that is the
1420
+ /// same few frames for every ANR, so it merged unrelated hangs into one
1421
+ /// issue while looking like real data.
1422
+ private func captureMainThreadStack() -> [SKStackFrame]? {
1312
1423
  // Only ever inspect the main thread from OFF the main thread —
1313
1424
  // suspending yourself never resumes.
1314
- guard !Thread.isMainThread else {
1315
- return parseCallStackSymbols(Thread.callStackSymbols)
1316
- }
1425
+ guard !Thread.isMainThread else { return nil }
1317
1426
 
1318
1427
  var threadList: thread_act_array_t?
1319
1428
  var threadCount: mach_msg_type_number_t = 0
1320
1429
  guard task_threads(mach_task_self_, &threadList, &threadCount) == KERN_SUCCESS,
1321
1430
  let threads = threadList, threadCount > 0 else {
1322
- return parseCallStackSymbols(Thread.callStackSymbols)
1431
+ return nil
1323
1432
  }
1324
1433
  defer {
1325
1434
  let ptr = UnsafeMutableRawPointer(threads)
@@ -1338,9 +1447,7 @@ public final class SKCrashReporting {
1338
1447
  var addresses = [UInt](repeating: 0, count: maxFrames)
1339
1448
  var addressCount = 0
1340
1449
 
1341
- guard thread_suspend(mainThread) == KERN_SUCCESS else {
1342
- return parseCallStackSymbols(Thread.callStackSymbols)
1343
- }
1450
+ guard thread_suspend(mainThread) == KERN_SUCCESS else { return nil }
1344
1451
 
1345
1452
  var pc: UInt = 0
1346
1453
  var lr: UInt = 0
@@ -1419,11 +1526,8 @@ public final class SKCrashReporting {
1419
1526
 
1420
1527
  thread_resume(mainThread)
1421
1528
 
1422
- guard addressCount > 0 else {
1423
- // State capture failed — fall back to the watchdog thread's own
1424
- // symbols as a last-resort hint that an ANR happened.
1425
- return parseCallStackSymbols(Thread.callStackSymbols)
1426
- }
1529
+ // State capture failed — no stack rather than the watchdog's own.
1530
+ guard addressCount > 0 else { return nil }
1427
1531
 
1428
1532
  // Main thread is running again — safe to allocate and symbolicate.
1429
1533
  let appExecutable = Bundle.main.infoDictionary?["CFBundleExecutable"] as? String
@@ -1537,8 +1641,31 @@ public final class SKCrashReporting {
1537
1641
  /// Each line has the format:
1538
1642
  /// `<frame_number> <image_name> <address> <symbol> + <offset>`
1539
1643
  /// e.g. `0 MyApp 0x0000000104a8b1c4 $s5MyApp14ViewControllerC11viewDidLoadyyF + 84`
1644
+ ///
1645
+ /// In-app classification goes through `isInAppImage` — the same rule as
1646
+ /// `symbolicate(address:)` — with the image PATH resolved by `dladdr` on
1647
+ /// the frame's address. Symbol lines carry only the image's basename,
1648
+ /// which cannot tell an embedded framework from a system one. This parser
1649
+ /// only ever sees stacks of the current process, so the addresses are
1650
+ /// live.
1540
1651
  internal func parseCallStackSymbols(_ symbols: [String], returnAddresses: [Int] = []) -> [SKStackFrame] {
1541
- let appExecutable = Bundle.main.infoDictionary?["CFBundleExecutable"] as? String
1652
+ parseCallStackSymbols(
1653
+ symbols,
1654
+ returnAddresses: returnAddresses,
1655
+ appExecutable: Bundle.main.infoDictionary?["CFBundleExecutable"] as? String,
1656
+ appBundlePath: SKCrashReporting.appBundlePath
1657
+ )
1658
+ }
1659
+
1660
+ /// Test seam — the parser with the app identity injected, so in-app
1661
+ /// classification is assertable under `swift test` (where the main
1662
+ /// bundle is the test runner's).
1663
+ internal func parseCallStackSymbols(
1664
+ _ symbols: [String],
1665
+ returnAddresses: [Int] = [],
1666
+ appExecutable: String?,
1667
+ appBundlePath: String
1668
+ ) -> [SKStackFrame] {
1542
1669
 
1543
1670
  return symbols.enumerated().map { index, symbol in
1544
1671
  let trimmed = symbol.trimmingCharacters(in: .whitespaces)
@@ -1570,14 +1697,17 @@ public final class SKCrashReporting {
1570
1697
  rawAddress = addressStr.hasPrefix("0x") ? addressStr : nil
1571
1698
  }
1572
1699
 
1573
- let isInApp: Bool
1574
- if let appExec = appExecutable {
1575
- isInApp = imageName == appExec
1576
- } else {
1577
- isInApp = !imageName.hasPrefix("lib") && !imageName.hasPrefix("_")
1578
- && imageName != "UIKitCore" && imageName != "Foundation"
1579
- && imageName != "CoreFoundation" && imageName != "libdyld.dylib"
1580
- }
1700
+ let addressValue: UInt? = {
1701
+ if index < returnAddresses.count { return UInt(bitPattern: returnAddresses[index]) }
1702
+ guard addressStr.hasPrefix("0x") else { return nil }
1703
+ return UInt(addressStr.dropFirst(2), radix: 16)
1704
+ }()
1705
+ let isInApp = SKCrashReporting.isInAppImage(
1706
+ imagePath: addressValue.flatMap { SKCrashReporting.imagePath(forAddress: $0) },
1707
+ imageName: imageName,
1708
+ appExecutable: appExecutable,
1709
+ appBundlePath: appBundlePath
1710
+ )
1581
1711
 
1582
1712
  return SKStackFrame(
1583
1713
  filename: nil,
@@ -1 +1 @@
1
- {"version":3,"names":["_purchases","_interopRequireDefault","require","_swissKnife","_attributes","_types","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_identity","_attribution","_analytics","_crashReporting","_performance","e","__esModule","default","_default","Purchases"],"sourceRoot":"../../src","sources":["index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,IAAAA,UAAA,GAAAC,sBAAA,CAAAC,OAAA;AAgBA,IAAAC,WAAA,GAAAD,OAAA;AAMA,IAAAE,WAAA,GAAAF,OAAA;AAMA,IAAAG,MAAA,GAAAH,OAAA;AAAAI,MAAA,CAAAC,IAAA,CAAAF,MAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,MAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,MAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AAOA,IAAAS,SAAA,GAAAhB,OAAA;AAQA,IAAAiB,YAAA,GAAAjB,OAAA;AAOA,IAAAkB,UAAA,GAAAlB,OAAA;AAEA,IAAAmB,eAAA,GAAAnB,OAAA;AAWA,IAAAoB,YAAA,GAAApB,OAAA;AAAoD,SAAAD,uBAAAsB,CAAA,WAAAA,CAAA,IAAAA,CAAA,CAAAC,UAAA,GAAAD,CAAA,KAAAE,OAAA,EAAAF,CAAA;AAhEpD;AAGA;AAAA,IAAAG,QAAA,GAAAZ,OAAA,CAAAW,OAAA,GACeE,kBAAS,EAExB;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAIA;AACA;AACA;AACA;AACA;AAIA;AACA;AACA;AACA","ignoreList":[]}
1
+ {"version":3,"names":["_purchases","_interopRequireDefault","require","_swissKnife","_attributes","_types","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_identity","_attribution","_analytics","_crashReporting","_performance","e","__esModule","default","_default","Purchases"],"sourceRoot":"../../src","sources":["index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,IAAAA,UAAA,GAAAC,sBAAA,CAAAC,OAAA;AAgBA,IAAAC,WAAA,GAAAD,OAAA;AAMA,IAAAE,WAAA,GAAAF,OAAA;AAMA,IAAAG,MAAA,GAAAH,OAAA;AAAAI,MAAA,CAAAC,IAAA,CAAAF,MAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,MAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,MAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AAOA,IAAAS,SAAA,GAAAhB,OAAA;AAQA,IAAAiB,YAAA,GAAAjB,OAAA;AAOA,IAAAkB,UAAA,GAAAlB,OAAA;AAEA,IAAAmB,eAAA,GAAAnB,OAAA;AAaA,IAAAoB,YAAA,GAAApB,OAAA;AAAoD,SAAAD,uBAAAsB,CAAA,WAAAA,CAAA,IAAAA,CAAA,CAAAC,UAAA,GAAAD,CAAA,KAAAE,OAAA,EAAAF,CAAA;AAlEpD;AAGA;AAAA,IAAAG,QAAA,GAAAZ,OAAA,CAAAW,OAAA,GACeE,kBAAS,EAExB;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAIA;AACA;AACA;AACA;AACA;AAIA;AACA;AACA;AACA","ignoreList":[]}