@app-swiss-knife/react-native-sdk 0.2.4 → 0.2.7

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 (27) hide show
  1. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +18 -1
  2. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  3. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +150 -8
  4. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +1 -1
  5. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +53 -9
  6. package/ios/SwissKnifePurchases.swift +16 -1
  7. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  8. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +171 -4
  9. package/lib/commonjs/modules/crash-reporting.js +260 -5
  10. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  11. package/lib/commonjs/purchases.js +195 -32
  12. package/lib/commonjs/purchases.js.map +1 -1
  13. package/lib/module/modules/crash-reporting.js +260 -5
  14. package/lib/module/modules/crash-reporting.js.map +1 -1
  15. package/lib/module/purchases.js +196 -33
  16. package/lib/module/purchases.js.map +1 -1
  17. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +39 -0
  18. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  19. package/lib/typescript/commonjs/purchases.d.ts +65 -13
  20. package/lib/typescript/commonjs/purchases.d.ts.map +1 -1
  21. package/lib/typescript/module/modules/crash-reporting.d.ts +39 -0
  22. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  23. package/lib/typescript/module/purchases.d.ts +65 -13
  24. package/lib/typescript/module/purchases.d.ts.map +1 -1
  25. package/package.json +2 -1
  26. package/src/modules/crash-reporting.ts +274 -4
  27. package/src/purchases.ts +196 -33
@@ -194,7 +194,24 @@ class SwissKnifePurchasesModule(
194
194
  )
195
195
  }
196
196
 
197
- // ----- Identity -----
197
+ // ----- Identity (legacy bridge methods — no longer called by our JS) -----
198
+ //
199
+ // `Purchases.logIn` / `logOut` / `getAppUserID` / `isAnonymous` in JS now
200
+ // delegate to the `Identity` module, which uses the `identity*` methods
201
+ // further down. These four stay on the spec because removing a method from
202
+ // the native-module contract breaks any app pinned to an older JS, but they
203
+ // are dead from this package's point of view.
204
+ //
205
+ // Do NOT re-point JS at them. They bottom out in the deprecated
206
+ // `SwissKnife.*` facades, which on THIS platform are not equivalent to the
207
+ // iOS ones: `SwissKnife.logOut` goes straight to the purchases gateway
208
+ // instead of `Identity.logOut`, and `SwissKnife.appUserID` /
209
+ // `SwissKnife.isAnonymous()` read gateway state — whose anonymous id is a
210
+ // fresh random UUID per process, not the DeviceID-derived
211
+ // `$SKAnonymousID:` subject `Identity.current()` reports, and which
212
+ // `Identity.reset()` / `Identity.wipe()` never clear. That split is what
213
+ // `packages/react-native-sdk/src/identity-parity.test.ts` exists to keep out
214
+ // of the JS surface.
198
215
 
199
216
  @ReactMethod
200
217
  fun logIn(appUserID: String, promise: Promise) {
@@ -42,7 +42,7 @@ internal object DeviceContextProvider {
42
42
  * eventually inject this via `BuildConfig`, but for now keep it in
43
43
  * source so we don't have to thread build settings through every test.
44
44
  */
45
- const val SDK_VERSION: String = "0.2.4"
45
+ const val SDK_VERSION: String = "0.2.7"
46
46
 
47
47
  private val cacheLock = Any()
48
48
 
@@ -23,6 +23,7 @@ import java.util.Date
23
23
  import java.util.Locale
24
24
  import java.util.concurrent.CopyOnWriteArrayList
25
25
  import com.appswissknife.context.IDs
26
+ import com.appswissknife.identity.Identity
26
27
  import java.util.concurrent.Executors
27
28
 
28
29
  // MARK: - Supporting Types
@@ -262,6 +263,75 @@ object SKCrashReporting {
262
263
  File(ctx.filesDir, "swiss-knife-crash/pending-crash.json")
263
264
  }
264
265
 
266
+ // MARK: - Identity-derived subject
267
+ //
268
+ // Crash reports used to take their subject ONLY from `scope.user` (the
269
+ // separate `setUser(...)` API). Nothing connected `Identity.logIn(...)`
270
+ // to crash reporting, so an app that identified its users but forgot
271
+ // `setUser` shipped subject-less crashes and the dashboard rendered
272
+ // "Affected users: No identified users".
273
+ //
274
+ // Analytics already solved this bug class by PULLING from Identity at
275
+ // event-build time instead of having login PUSH into each module. We do
276
+ // the same — see [effectiveUser].
277
+ //
278
+ // The one Android-specific twist: `Identity.current()` takes Identity's
279
+ // lock and calls `DeviceID.get(ctx)`, which on a cold cache opens
280
+ // EncryptedSharedPreferences (Tink + Android Keystore + disk IO). That is
281
+ // exactly the kind of work you must not do from an uncaught-exception
282
+ // handler or an ANR watchdog. So the resolved user id is cached in this
283
+ // volatile and the crash paths only ever read the cache; the refresh
284
+ // itself runs on ordinary threads.
285
+ @Volatile
286
+ private var identityUserId: String? = null
287
+
288
+ /** Token for the `Identity.addObserver` subscription installed by [init]. */
289
+ @Volatile
290
+ private var identityObserverToken: java.util.UUID? = null
291
+
292
+ /**
293
+ * Re-read the identified user id from [Identity] into [identityUserId].
294
+ *
295
+ * MUST NOT be called from crash-handler context (uncaught-exception
296
+ * handler, ANR watchdog, native-crash callback) — `Identity.current()`
297
+ * acquires Identity's lock and may hit EncryptedSharedPreferences on a
298
+ * cold `DeviceID` cache. Call sites are all ordinary threads: [init],
299
+ * the public `capture*` entry points, and the background flush tick.
300
+ */
301
+ private fun refreshIdentityUserId() {
302
+ identityUserId = try {
303
+ Identity.current().userId?.takeIf { it.isNotEmpty() }
304
+ } catch (_: Throwable) {
305
+ // Identity not linked / not configured — keep whatever we had.
306
+ identityUserId
307
+ }
308
+ }
309
+
310
+ /**
311
+ * The subject stamped onto every report payload.
312
+ *
313
+ * Reads only the pre-captured [identityUserId] volatile, so it is safe to
314
+ * evaluate from a dying process. Returns `null` when neither an explicit
315
+ * `setUser` nor an identified `Identity` user exists — preserving today's
316
+ * behaviour for apps that never log in and never call `setUser`.
317
+ */
318
+ private val effectiveUser: SKUser?
319
+ get() = resolveUser(scope.user)
320
+
321
+ /**
322
+ * Merge an explicit [SKUser] override with the Identity-derived id.
323
+ *
324
+ * `id` falls back to Identity; `email` / `username` are explicit-only
325
+ * because `Identity` has no such fields.
326
+ */
327
+ private fun resolveUser(explicit: SKUser?): SKUser? {
328
+ val id = explicit?.id ?: identityUserId
329
+ val email = explicit?.email
330
+ val username = explicit?.username
331
+ if (id == null && email == null && username == null) return null
332
+ return SKUser(id = id, email = email, username = username)
333
+ }
334
+
265
335
  // MARK: - Init
266
336
 
267
337
  fun init(context: Context, config: Configuration) {
@@ -270,6 +340,17 @@ object SKCrashReporting {
270
340
  this.appContext = appCtx
271
341
  this.breadcrumbs = RingBuffer(config.maxBreadcrumbs)
272
342
 
343
+ // Pre-capture the identified user BEFORE the crash handler is armed,
344
+ // and keep the cache warm via an Identity observer. Crash-handler
345
+ // context can then read `identityUserId` without touching Identity's
346
+ // lock or EncryptedSharedPreferences. Order-independent: identity may
347
+ // be known before or after crash reporting starts.
348
+ refreshIdentityUserId()
349
+ identityObserverToken?.let { Identity.removeObserver(it) }
350
+ identityObserverToken = Identity.addObserver { change ->
351
+ identityUserId = change.current.userId?.takeIf { it.isNotEmpty() }
352
+ }
353
+
273
354
  // Send any crash from previous session
274
355
  flushPendingCrash()
275
356
 
@@ -333,6 +414,7 @@ object SKCrashReporting {
333
414
  // MARK: - Public API
334
415
 
335
416
  fun captureException(throwable: Throwable, tags: Map<String, String>? = null): String {
417
+ refreshIdentityUserId()
336
418
  sessionErrorCount++
337
419
  val event = buildEvent(SKErrorLevel.ERROR).apply {
338
420
  exceptionType = throwable.javaClass.name
@@ -347,6 +429,7 @@ object SKCrashReporting {
347
429
  }
348
430
 
349
431
  fun captureMessage(message: String, level: SKErrorLevel = SKErrorLevel.INFO) {
432
+ refreshIdentityUserId()
350
433
  val event = buildEvent(level).apply { this.message = message }
351
434
  val finalEvent = applyBeforeSend(event) ?: return
352
435
  sendEvent(finalEvent)
@@ -398,17 +481,32 @@ object SKCrashReporting {
398
481
  }
399
482
 
400
483
  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(
484
+ sendEventPayload(hydrateEvent(event))
485
+ }
486
+
487
+ /**
488
+ * Fill a caller-supplied [SKErrorEvent] in with scope / config / Identity
489
+ * state. Split out of [captureEvent] so it is directly assertable.
490
+ *
491
+ * Only reached from the public [captureEvent] entry point — an ordinary
492
+ * caller thread — so it refreshes the Identity cache itself rather than
493
+ * relying on the caller to have done so.
494
+ *
495
+ * Note: device / OS fields used to be hydrated here as a fallback —
496
+ * dropped, the envelope carries them now.
497
+ */
498
+ internal fun hydrateEvent(event: SKErrorEvent): SKErrorEvent {
499
+ refreshIdentityUserId()
500
+ return event.copy(
404
501
  environment = event.environment ?: config?.environment,
405
502
  release = event.release ?: config?.release,
406
- user = event.user ?: scope.user,
503
+ // The event's own user beats the scope user (unchanged); the
504
+ // Identity id then backfills a missing `id` on whichever won.
505
+ user = resolveUser(event.user ?: scope.user),
407
506
  tags = mergeTags(scope.tags, event.tags ?: emptyMap()).ifEmpty { null },
408
507
  extra = mergeMaps(scope.extra, event.extra ?: emptyMap()).ifEmpty { null },
409
508
  breadcrumbs = event.breadcrumbs ?: breadcrumbs.snapshot()
410
509
  )
411
- sendEventPayload(e)
412
510
  }
413
511
 
414
512
  /**
@@ -434,6 +532,26 @@ object SKCrashReporting {
434
532
  callback(scope)
435
533
  }
436
534
 
535
+ /**
536
+ * Explicitly override the crash-report subject.
537
+ *
538
+ * Precedence, relative to the id that `Identity.logIn(...)` establishes:
539
+ *
540
+ * - Explicit `setUser` wins **field-by-field** for `id`. `email` /
541
+ * `username` are explicit-only, because [Identity] has no such fields —
542
+ * `setUser(SKUser(email = "a@b.c"))` therefore yields the Identity id
543
+ * plus the explicit email.
544
+ * - `setUser(null)` clears only the EXPLICIT override. The
545
+ * Identity-derived id still applies afterwards.
546
+ * - Resolution happens at report/crash time, not at login time, so
547
+ * initialisation order is irrelevant: crash reporting routinely starts
548
+ * before the identity is known.
549
+ * - Deliberately does NOT fall back to `Identity.current().anonymousId`.
550
+ * That would inflate "affected users" for every app that never logs in,
551
+ * and it would diverge from Analytics, whose `user_id` is the identified
552
+ * subject only. The anonymous id already travels separately in the
553
+ * envelope's `anonymous_id`.
554
+ */
437
555
  fun setUser(user: SKUser?) {
438
556
  scope.setUser(user)
439
557
  }
@@ -458,12 +576,21 @@ object SKCrashReporting {
458
576
  release = cfg?.release,
459
577
  tags = scope.tags.toMap().ifEmpty { null },
460
578
  extra = scope.extra.toMap().ifEmpty { null },
461
- user = scope.user,
579
+ user = effectiveUser,
462
580
  breadcrumbs = breadcrumbs.snapshot()
463
581
  )
464
582
  }
465
583
 
466
- private fun buildCrashEvent(throwable: Throwable): SKErrorEvent {
584
+ /**
585
+ * Build the FATAL event for an uncaught exception.
586
+ *
587
+ * **Crash-handler context** — called from the default
588
+ * `Thread.UncaughtExceptionHandler` while the process is dying. Everything
589
+ * it touches must be allocation-light and lock-free; the subject comes
590
+ * from the pre-captured [identityUserId] volatile, never from a live
591
+ * `Identity.current()` call.
592
+ */
593
+ internal fun buildCrashEvent(throwable: Throwable): SKErrorEvent {
467
594
  return buildEvent(SKErrorLevel.FATAL).copy(
468
595
  exceptionType = throwable.javaClass.name,
469
596
  exceptionValue = throwable.message,
@@ -513,7 +640,12 @@ object SKCrashReporting {
513
640
  flushTimer = java.util.Timer("sk-event-flush", true).also { timer ->
514
641
  timer.scheduleAtFixedRate(object : java.util.TimerTask() {
515
642
  override fun run() {
516
- executor.execute { flushEventQueue() }
643
+ // Background thread — safe to touch Identity. Keeps
644
+ // `identityUserId` warm even when the host seeds an
645
+ // identity through `SwissKnife.configure(appUserID = ...)`
646
+ // AFTER crash reporting started, which sets the id without
647
+ // firing an Identity change notification.
648
+ executor.execute { refreshIdentityUserId(); flushEventQueue() }
517
649
  }
518
650
  }, FLUSH_INTERVAL_MS, FLUSH_INTERVAL_MS)
519
651
  }
@@ -893,12 +1025,22 @@ object SKCrashReporting {
893
1025
 
894
1026
  internal fun _snapshotBreadcrumbs() = breadcrumbs.snapshot()
895
1027
  internal fun _clearBreadcrumbs() = breadcrumbs.clear()
1028
+
1029
+ /** Test seam — events that have been enqueued but not yet flushed. */
1030
+ internal fun _pendingEventsForTesting(): List<SKErrorEvent> = pendingEvents.toList()
1031
+
896
1032
  internal fun _resetForTesting() {
897
1033
  config = null
898
1034
  appContext = null
899
1035
  scope.tags.clear()
900
1036
  scope.extra.clear()
1037
+ // Clears only the EXPLICIT subject override, matching `setUser(null)`
1038
+ // semantics. The Identity-derived id is dropped separately below —
1039
+ // this is a full reset, not a user-facing "forget the override".
901
1040
  scope.setUser(null)
1041
+ identityObserverToken?.let { Identity.removeObserver(it) }
1042
+ identityObserverToken = null
1043
+ identityUserId = null
902
1044
  breadcrumbs.clear()
903
1045
  anrWatchdog?.stop()
904
1046
  anrWatchdog = null
@@ -208,7 +208,7 @@ internal object IngestPlaceholderDevice {
208
208
  appBuild = "unknown",
209
209
  locale = Locale.getDefault().toString(),
210
210
  timezone = TimeZone.getDefault().id,
211
- sdkVersion = "0.2.4",
211
+ sdkVersion = "0.2.7",
212
212
  bundleIdentifier = null,
213
213
  )
214
214
  }
@@ -47,6 +47,7 @@ import com.appswissknife.StoreTransactionResult
47
47
  import com.appswissknife.entitlements.EntitlementsRepository
48
48
  import com.appswissknife.entitlements.SimpleCustomerInfo
49
49
  import com.appswissknife.entitlements.SimpleEntitlementInfos
50
+ import com.appswissknife.identity.Identity
50
51
  import com.appswissknife.models.CustomerInfo
51
52
  import com.appswissknife.models.LogLevel
52
53
  import com.appswissknife.models.Offerings
@@ -91,12 +92,19 @@ class BillingClientGateway(
91
92
  @Volatile private var serverUrl: String = ""
92
93
  @Volatile private var apiKey: String = ""
93
94
  @Volatile private var explicitAppUserId: String? = null
94
- // Wave 1: unified `$SKAnonymousID:` prefix across iOS / Android / RN.
95
- // Was `$RCAnonymousID:` (RC legacy) before the audit. Per the
96
- // user-locked decision we do NOT backfill on-device caches with the
97
- // new prefix — whatever's already there stays; only fresh installs
98
- // and logOut() rotations pick it up.
99
- @Volatile private var anonymousAppUserId: String = "\$SKAnonymousID:${UUID.randomUUID().toString().replace("-", "")}"
95
+
96
+ /**
97
+ * Last-resort anonymous subject.
98
+ *
99
+ * Used ONLY when [Identity] has no application context yet — i.e. a
100
+ * purchase or entitlement check attempted before `SwissKnife.configure`.
101
+ * It is minted per process and never persisted, so it is not a stable
102
+ * identity and anything keyed on it is unreachable after the process
103
+ * dies. That is precisely why it must not be the normal path; see
104
+ * [getAppUserID].
105
+ */
106
+ @Volatile private var fallbackAnonymousAppUserId: String =
107
+ "\$SKAnonymousID:${UUID.randomUUID().toString().replace("-", "")}"
100
108
 
101
109
  private val configured = AtomicBoolean(false)
102
110
  private val reconnectAttempt = AtomicInteger(0)
@@ -172,9 +180,39 @@ class BillingClientGateway(
172
180
 
173
181
  override fun isConfigured(): Boolean = configured.get()
174
182
 
175
- override fun getAppUserID(): String = explicitAppUserId ?: anonymousAppUserId
183
+ /**
184
+ * The subject the backend keys purchases and entitlements on.
185
+ *
186
+ * Mirrors iOS `SwissKnife.backendSubjectId()`: an explicit id wins,
187
+ * otherwise the [Identity] snapshot.
188
+ *
189
+ * **Why this is not a random UUID any more.** The anonymous branch used to
190
+ * return `"${'$'}SKAnonymousID:" + UUID.randomUUID()`, minted once per
191
+ * process in a field initializer and never persisted, while
192
+ * `Identity.current()` — and therefore the `/api/sdk/users/identify` POST —
193
+ * reported `"${'$'}SKAnonymousID:" + DeviceID.get(ctx)` from
194
+ * EncryptedSharedPreferences. Android was posting two different subjects for
195
+ * the same anonymous person: one on `validate`/entitlements, another on
196
+ * `identify`. The merge looked for rows under the id it was told about and
197
+ * found none, so an anonymous purchase never followed the user into their
198
+ * account. iOS never had this half of the bug because both paths already
199
+ * went through `backendSubjectId()`.
200
+ */
201
+ override fun getAppUserID(): String {
202
+ explicitAppUserId?.takeIf { it.isNotEmpty() }?.let { return it }
203
+ val snapshot = Identity.current()
204
+ val fromIdentity = snapshot.userId ?: snapshot.anonymousId
205
+ return fromIdentity.takeIf { it.isNotEmpty() } ?: fallbackAnonymousAppUserId
206
+ }
176
207
 
177
- override fun isAnonymous(): Boolean = explicitAppUserId == null
208
+ /**
209
+ * Anonymous iff neither this gateway nor [Identity] holds an explicit user.
210
+ * Consulting Identity too keeps this consistent with [getAppUserID] — a
211
+ * host that identified through `Identity.logIn` directly must not be
212
+ * reported as anonymous while its subject is a real user id.
213
+ */
214
+ override fun isAnonymous(): Boolean =
215
+ explicitAppUserId == null && Identity.current().userId == null
178
216
 
179
217
  override fun getCustomerInfo(
180
218
  onSuccess: (CustomerInfo) -> Unit,
@@ -342,7 +380,13 @@ class BillingClientGateway(
342
380
  return
343
381
  }
344
382
  explicitAppUserId = null
345
- anonymousAppUserId = "\$SKAnonymousID:${UUID.randomUUID().toString().replace("-", "")}"
383
+ // Rotates the pre-configure fallback only. The real post-logout subject
384
+ // comes from `Identity`, whose DeviceID deliberately survives logout so
385
+ // analytics stay continuous for the same physical install — same as iOS,
386
+ // where logOut also returns to the stable device anonymous id rather than
387
+ // inventing a new one.
388
+ fallbackAnonymousAppUserId =
389
+ "\$SKAnonymousID:${UUID.randomUUID().toString().replace("-", "")}"
346
390
  val repo = entitlementsRepo
347
391
  repo?.invalidate()
348
392
  onSuccess(emptyCustomerInfo())
@@ -246,7 +246,22 @@ class SwissKnifePurchases: RCTEventEmitter {
246
246
  }
247
247
  }
248
248
 
249
- // MARK: Identity
249
+ // MARK: Identity (legacy bridge methods — no longer called by our JS)
250
+ //
251
+ // `Purchases.logIn` / `logOut` / `getAppUserID` / `isAnonymous` in JS now
252
+ // delegate to the `Identity` module, which uses the `identity*` methods
253
+ // further down. These four stay on the spec because removing a method from
254
+ // the native-module contract breaks any app pinned to an older JS, but they
255
+ // are dead from this package's point of view.
256
+ //
257
+ // Do NOT re-point JS at them. They bottom out in the deprecated
258
+ // `SwissKnife.*` facades, and those facades are not equivalent across
259
+ // platforms: Android's `SwissKnife.logOut` bypasses `Identity.logOut` for
260
+ // the purchases gateway, and its `appUserID` / `isAnonymous` read gateway
261
+ // state whose anonymous id is a per-process random UUID rather than the
262
+ // DeviceID-derived `$SKAnonymousID:` subject this side reports. That split
263
+ // is what `packages/react-native-sdk/src/identity-parity.test.ts` exists to
264
+ // keep out of the JS surface.
250
265
 
251
266
  @objc(logIn:resolver:rejecter:)
252
267
  func logIn(_ appUserID: String,
@@ -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.2.4"
102
+ static let sdkVersionConstant: String = "0.2.7"
103
103
 
104
104
  private static let cacheLock = DispatchQueue(label: "com.swissknife.context.device")
105
105
  private static var cached: DeviceContext?
@@ -217,6 +217,52 @@ public final class SKCrashReporting {
217
217
  /// rotation so signal-path recovery closes the right session.
218
218
  private var sessionPersistToken: UUID?
219
219
 
220
+ // MARK: - Identity-derived subject
221
+ //
222
+ // Crash reports used to take their subject ONLY from `scope.user`, i.e.
223
+ // exclusively from the separate `setUser(_:)` API. A host that called
224
+ // `SwissKnife.Identity.logIn("u_42")` — the documented way to identify a
225
+ // user — but never ALSO called `setUser` shipped subject-less crashes,
226
+ // and the dashboard rendered "Affected users: No identified users": the
227
+ // server derives `affectedPersons` purely from the domain payload's
228
+ // `event.user.id`. (The envelope's `user_id` does not save us — the
229
+ // ingest schema strips it.)
230
+ //
231
+ // Analytics already fixed this bug class by PULLING from Identity when
232
+ // the event is built, instead of having `logIn` PUSH into every
233
+ // consumer. Crash reporting now does the same, through the single
234
+ // `effectiveUser` resolution point below.
235
+ //
236
+ // The pull cannot happen at crash time on every path.
237
+ // `SwissKnife.Identity.current` reads through a `DispatchQueue.sync`,
238
+ // which is NOT async-signal-safe and must never be entered from a
239
+ // signal / Mach-exception handler. So the signal path never touches
240
+ // Identity at all: the resolved subject is baked into the on-disk
241
+ // `PersistedContext` snapshot ahead of time, on an ordinary thread,
242
+ // and the handler still writes nothing but a signal number and raw
243
+ // backtrace addresses. The NSException hook likewise reads only the
244
+ // cache below — never a fresh `Identity.current` — because taking a new
245
+ // lock on a thread that is already unwinding a fatal exception is how
246
+ // you turn a crash report into a hang.
247
+
248
+ /// Identity-derived user id, resolved on an ordinary thread and cached
249
+ /// so crash-time code paths never have to call into `Identity`.
250
+ ///
251
+ /// Refreshed at `start()`, on every `Identity` transition (observer
252
+ /// registered in `start()`), at every `buildEvent`, and at every context
253
+ /// persist. The last two matter because not every identity mutation
254
+ /// notifies observers — `SwissKnife.configure(appUserID:)` seeds the id
255
+ /// directly via `Identity._seedConfiguredUser`.
256
+ ///
257
+ /// Accessed without additional synchronisation, exactly like the
258
+ /// neighbouring `scope` state it is resolved alongside: writes happen on
259
+ /// ordinary threads, and the crash-time reader cannot afford a lock.
260
+ private var identityUserId: String?
261
+
262
+ /// Identity-change observation token, so a repeated `start()` re-arms
263
+ /// the observer instead of stacking duplicates.
264
+ private var identityObserverToken: UUID?
265
+
220
266
  /// IngestClient seam — production wires the shared singleton; tests can
221
267
  /// swap a custom instance via `_setIngestForTesting` to assert on
222
268
  /// enqueued items without a live network. All crash / error / feedback /
@@ -361,6 +407,11 @@ public final class SKCrashReporting {
361
407
  self.configuration = configuration
362
408
  self.breadcrumbs = RingBuffer(capacity: configuration.maxBreadcrumbs)
363
409
 
410
+ // Warm the identity cache before anything can build an event, so a
411
+ // host that logged in BEFORE starting crash reporting is already
412
+ // attributed. The observer below covers the opposite order.
413
+ refreshIdentityUserId()
414
+
364
415
  // Ensure crash directory exists
365
416
  try? FileManager.default.createDirectory(
366
417
  at: SKCrashReporting.crashDirectory,
@@ -417,6 +468,23 @@ public final class SKCrashReporting {
417
468
  self.queue.async { self.persistContextToDisk() }
418
469
  }
419
470
 
471
+ // Keep the crash-time identity cache fresh, and re-persist the
472
+ // on-disk snapshot, whenever the host logs in / out. This is what
473
+ // makes `start()` → `logIn(...)` ordering work for the signal path,
474
+ // where nothing may consult Identity at crash time. The change
475
+ // payload carries the new snapshot, so the observer never has to
476
+ // re-enter `Identity` to read it back.
477
+ if let token = identityObserverToken {
478
+ SwissKnife.Identity.removeObserver(token)
479
+ }
480
+ identityObserverToken = SwissKnife.Identity.addObserver { [weak self] change in
481
+ guard let self else { return }
482
+ self.queue.async {
483
+ self.identityUserId = change.current.userId
484
+ self.persistContextToDisk()
485
+ }
486
+ }
487
+
420
488
  // Auto-breadcrumbs & session tracking
421
489
  if configuration.enableAutoSessionTracking {
422
490
  registerLifecycleObservers()
@@ -556,6 +624,28 @@ public final class SKCrashReporting {
556
624
  queue.async { [weak self] in self?.persistContextToDisk() }
557
625
  }
558
626
 
627
+ /// Explicit override for the crash-report subject.
628
+ ///
629
+ /// You do **not** have to call this to get attributed crashes — a host
630
+ /// that calls `SwissKnife.Identity.logIn(_:)` is already the subject of
631
+ /// its reports. Use `setUser` to override or to attach an email /
632
+ /// username the SDK cannot know.
633
+ ///
634
+ /// Precedence, resolved at report time:
635
+ /// - `id` — the explicit value wins **field-by-field**. When the explicit
636
+ /// user carries no `id`, the `SwissKnife.Identity` user id is used.
637
+ /// - `email` / `username` — explicit-only. `Identity` has no such fields,
638
+ /// so nothing backfills them.
639
+ /// - `setUser(nil)` clears only the EXPLICIT override; the
640
+ /// Identity-derived id still applies afterwards.
641
+ /// - Resolution happens at report/crash time, not at login time, so
642
+ /// initialisation order is irrelevant: crash reporting routinely starts
643
+ /// before the identity is known.
644
+ /// - Deliberately does NOT fall back to `Identity.current.anonymousId`.
645
+ /// That would inflate "affected users" for every app that never logs
646
+ /// in, and would diverge from Analytics, whose `user_id` is the
647
+ /// identified subject only. The anonymous id already travels
648
+ /// separately, as the envelope's `anonymous_id`.
559
649
  public func setUser(_ user: SKUser?) {
560
650
  scope.setUser(user)
561
651
  queue.async { [weak self] in self?.persistContextToDisk() }
@@ -593,13 +683,49 @@ public final class SKCrashReporting {
593
683
 
594
684
  // MARK: - Private: Build / Send
595
685
 
686
+ /// Re-read the identified user id from `SwissKnife.Identity` into the
687
+ /// cache.
688
+ ///
689
+ /// ORDINARY THREADS ONLY. `Identity.current` performs a
690
+ /// `DispatchQueue.sync`; calling it from a signal or Mach-exception
691
+ /// handler is not async-signal-safe and risks deadlock. Every call site
692
+ /// of this method must be reachable only from normal execution.
693
+ private func refreshIdentityUserId() {
694
+ identityUserId = SwissKnife.Identity.current.userId
695
+ }
696
+
697
+ /// The single point where a report's subject is resolved. Every site
698
+ /// that stamps `event.user` — live errors, scope application, the
699
+ /// on-disk crash-context snapshot, signal recovery, and the NSException
700
+ /// hook — reads from here.
701
+ ///
702
+ /// - `id`: explicit `setUser` wins, otherwise the `Identity` user id.
703
+ /// - `email` / `username`: explicit-only — `Identity` has no such fields.
704
+ /// - All three nil ⇒ `nil`, preserving today's behaviour for apps that
705
+ /// never log in and never call `setUser`.
706
+ ///
707
+ /// Reads the cached identity id rather than `Identity.current`, so this
708
+ /// is also safe to evaluate from the NSException hook.
709
+ private var effectiveUser: SKUser? {
710
+ let explicit = scope.user
711
+ let id = explicit?.id ?? identityUserId
712
+ let email = explicit?.email
713
+ let username = explicit?.username
714
+ guard id != nil || email != nil || username != nil else { return nil }
715
+ return SKUser(id: id, email: email, username: username)
716
+ }
717
+
596
718
  private func buildEvent(level: SKErrorLevel) -> SKErrorEvent {
597
719
  var event = SKErrorEvent(level: level)
598
720
  event.environment = configuration?.environment
599
721
  event.release = configuration?.release
600
722
  event.tags = scope.tags.isEmpty ? nil : scope.tags
601
723
  event.extra = scope.extra.isEmpty ? nil : scope.extra
602
- event.user = scope.user
724
+ // Ordinary-thread path — pull the live identity before resolving, so
725
+ // an identity mutation that never notified observers (a
726
+ // `configure(appUserID:)` seed) is still picked up.
727
+ refreshIdentityUserId()
728
+ event.user = effectiveUser
603
729
  event.breadcrumbs = queue.sync { breadcrumbs.snapshot() }
604
730
  applyDeviceContext(to: &event)
605
731
  return event
@@ -624,7 +750,11 @@ public final class SKCrashReporting {
624
750
  private func applyScope(to event: inout SKErrorEvent) {
625
751
  if event.tags == nil { event.tags = scope.tags.isEmpty ? nil : scope.tags }
626
752
  if event.extra == nil { event.extra = scope.extra.isEmpty ? nil : scope.extra }
627
- if event.user == nil { event.user = scope.user }
753
+ if event.user == nil {
754
+ // `captureEvent(_:)` is a public, ordinary-thread entry point.
755
+ refreshIdentityUserId()
756
+ event.user = effectiveUser
757
+ }
628
758
  if event.breadcrumbs == nil { event.breadcrumbs = queue.sync { breadcrumbs.snapshot() } }
629
759
  }
630
760
 
@@ -705,12 +835,19 @@ public final class SKCrashReporting {
705
835
  /// Called periodically (every N breadcrumbs, on scope change) to persist
706
836
  /// crash context so the signal handler doesn't need to touch Swift runtime.
707
837
  private func persistContextToDisk() {
838
+ // Always invoked from `queue.async` — an ordinary thread, never a
839
+ // signal handler — so pulling from Identity here is safe. It is also
840
+ // the ONLY place the signal path can learn who the user was: the
841
+ // handler itself may not call `Identity.current` (DispatchQueue.sync
842
+ // is not async-signal-safe), so the subject has to be resolved into
843
+ // this snapshot ahead of the crash.
844
+ refreshIdentityUserId()
708
845
  let session = Session.shared.current
709
846
  let ctx = PersistedContext(
710
847
  breadcrumbs: breadcrumbs.snapshot(),
711
848
  tags: scope.tags,
712
849
  extra: scope.extra,
713
- user: scope.user,
850
+ user: effectiveUser,
714
851
  environment: configuration?.environment,
715
852
  release: configuration?.release,
716
853
  sessionId: session.id,
@@ -808,6 +945,15 @@ public final class SKCrashReporting {
808
945
  // Fill in defaults from current config if context was missing
809
946
  if event.environment == nil { event.environment = configuration?.environment }
810
947
  if event.release == nil { event.release = configuration?.release }
948
+ // `ctx.user` is the authoritative subject — it was resolved (explicit
949
+ // override merged over the Identity id) on an ordinary thread during
950
+ // the run that crashed. Only when there was no context on disk at all
951
+ // do we fall back to whoever this launch believes the user is. Runs
952
+ // inside `start()`, on an ordinary thread.
953
+ if event.user == nil {
954
+ refreshIdentityUserId()
955
+ event.user = effectiveUser
956
+ }
811
957
 
812
958
  // Send it
813
959
  sendEvent(event)
@@ -939,7 +1085,10 @@ public final class SKCrashReporting {
939
1085
  event.stacktrace = reporting.parseCallStackSymbols(exception.callStackSymbols)
940
1086
  event.breadcrumbs = reporting.queue.sync { reporting.breadcrumbs.snapshot() }
941
1087
  event.tags = reporting.scope.tags.isEmpty ? nil : reporting.scope.tags
942
- event.user = reporting.scope.user
1088
+ // Crash-time context: resolve from the cache only. `effectiveUser`
1089
+ // never calls `Identity.current`, so no new lock is taken on a
1090
+ // thread that is already unwinding a fatal exception.
1091
+ event.user = reporting.effectiveUser
943
1092
  event.environment = reporting.configuration?.environment
944
1093
  event.release = reporting.configuration?.release
945
1094
  reporting.applyDeviceContext(to: &event)
@@ -1431,4 +1580,22 @@ public final class SKCrashReporting {
1431
1580
  }
1432
1581
 
1433
1582
  internal var _pendingCrashURL: URL { SKCrashReporting.pendingCrashURL }
1583
+
1584
+ /// Test seam — the on-disk crash-context snapshot the signal path
1585
+ /// recovers from. Used to assert the subject is baked in AHEAD of the
1586
+ /// crash, which is the whole reason the handler needs no Identity call.
1587
+ internal var _persistedContextURL: URL { SKCrashReporting.persistedContextURL }
1588
+
1589
+ /// Test seam — run a context persist synchronously on the crash queue.
1590
+ internal func _persistContextToDiskForTesting() {
1591
+ queue.sync { persistContextToDisk() }
1592
+ }
1593
+
1594
+ /// Test seam — the subject the NSException hook would stamp, resolved
1595
+ /// from the cache exactly as the crash-time path does (no `Identity`
1596
+ /// call). Lets a test prove the cache path without raising a fatal
1597
+ /// exception in the test process.
1598
+ internal func _effectiveUserFromCacheForTesting() -> SKUser? {
1599
+ effectiveUser
1600
+ }
1434
1601
  }