@app-swiss-knife/react-native-sdk 0.3.1 → 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.
Files changed (28) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  3. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +315 -41
  4. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +13 -4
  5. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +229 -36
  6. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +6 -0
  7. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  8. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +186 -56
  9. package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +182 -0
  10. package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +164 -8
  11. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +418 -58
  12. package/lib/commonjs/index.js.map +1 -1
  13. package/lib/commonjs/modules/crash-reporting.js +525 -35
  14. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  15. package/lib/module/index.js.map +1 -1
  16. package/lib/module/modules/crash-reporting.js +525 -35
  17. package/lib/module/modules/crash-reporting.js.map +1 -1
  18. package/lib/typescript/commonjs/index.d.ts +1 -1
  19. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  20. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +32 -7
  21. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  22. package/lib/typescript/module/index.d.ts +1 -1
  23. package/lib/typescript/module/index.d.ts.map +1 -1
  24. package/lib/typescript/module/modules/crash-reporting.d.ts +32 -7
  25. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  26. package/package.json +2 -1
  27. package/src/index.ts +2 -0
  28. package/src/modules/crash-reporting.ts +625 -68
@@ -24,8 +24,17 @@
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).
32
+ // - 2xx with a body we cannot parse → AMBIGUOUS, not success. We have no
33
+ // evidence the server accepted anything, so the batch stays queued and
34
+ // the worker retries it. Deletion from the durable queue happens only on
35
+ // evidence of acceptance (a parseable result, or an empty body — the
36
+ // server's no-content ack). Bounded by MAX_AMBIGUOUS_ATTEMPTS, after
37
+ // which the batch is dead-lettered rather than retried forever.
29
38
  //
30
39
  // Context primitives (DeviceContext / IDs / Session / Reachability / Clock)
31
40
  // arrive in Commit 3. This commit ships placeholder providers that take
@@ -42,7 +51,6 @@ import androidx.annotation.VisibleForTesting
42
51
  import androidx.work.BackoffPolicy
43
52
  import androidx.work.Constraints
44
53
  import androidx.work.CoroutineWorker
45
- import androidx.work.Data
46
54
  import androidx.work.ExistingWorkPolicy
47
55
  import androidx.work.NetworkType
48
56
  import androidx.work.OneTimeWorkRequestBuilder
@@ -208,7 +216,7 @@ internal object IngestPlaceholderDevice {
208
216
  appBuild = "unknown",
209
217
  locale = Locale.getDefault().toString(),
210
218
  timezone = TimeZone.getDefault().id,
211
- sdkVersion = "0.3.1",
219
+ sdkVersion = "0.4.0",
212
220
  bundleIdentifier = null,
213
221
  )
214
222
  }
@@ -250,6 +258,22 @@ internal data class IngestErrorEntry(
250
258
  // IngestClient
251
259
  // ---------------------------------------------------------------------------
252
260
 
261
+ /**
262
+ * The server answered a batch POST with a 2xx status but a non-empty body we
263
+ * could not parse — a truncated response, an HTML error page from a
264
+ * misconfigured proxy, a partial write.
265
+ *
266
+ * Extends [IOException] so it flows through [flushSync]'s existing
267
+ * `@Throws(IOException::class)` contract and the worker's IO retry branch.
268
+ * It is its own type, not a bare IOException, because [flushSync] counts
269
+ * these separately to bound how long an undecodable-but-successful backend
270
+ * can pin the head of the queue. See [IngestClient.MAX_AMBIGUOUS_ATTEMPTS].
271
+ */
272
+ internal class UndecodableIngestResponse(
273
+ val byteCount: Int,
274
+ val preview: String,
275
+ ) : IOException("undecodable success response ($byteCount bytes): $preview")
276
+
253
277
  /**
254
278
  * Unified client for `POST /ingest`. Process-wide singleton wired by
255
279
  * SwissKnife.configure (Commit 3); tests construct their own.
@@ -263,11 +287,37 @@ internal class IngestClient(
263
287
  private val deviceSnapshot: () -> DeviceContextSnapshot = { IngestPlaceholderDevice.supplier() },
264
288
  private val sessionSnapshot: () -> Pair<String, Int> = { IngestPlaceholderSession.supplier() },
265
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() },
266
292
  ) {
267
293
 
268
294
  companion object {
269
295
  const val TAG = "SwissKnife.IngestClient"
270
296
 
297
+ /**
298
+ * How many consecutive undecodable-success responses the SAME batch
299
+ * may collect before [flushSync] stops retrying it and dead-letters
300
+ * it instead.
301
+ *
302
+ * A deliberate bound, not a fallback: without it a backend that
303
+ * permanently answers 200 with garbage would pin the head of the
304
+ * queue forever, re-sending the same batch on every worker run, and
305
+ * the queue behind it would grow to its cap and start dropping the
306
+ * OLDEST items — reintroducing silent loss from the other end. 5
307
+ * matches IngestFlushWorker.MAX_ATTEMPTS and the iOS client's
308
+ * `maxAmbiguousAttempts`.
309
+ */
310
+ const val MAX_AMBIGUOUS_ATTEMPTS = 5
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
+
271
321
  /**
272
322
  * Process-wide instance — wired by SwissKnife.configure (Commit 3).
273
323
  * Tests construct their own. Direct read access is internal-only;
@@ -324,32 +374,53 @@ internal class IngestClient(
324
374
  @Volatile
325
375
  private var isReachable: Boolean = true
326
376
 
377
+ /**
378
+ * Consecutive undecodable-success responses for the batch currently at
379
+ * the head of the queue, and the identity of that batch. The budget is
380
+ * per-batch, not a global "server has been flaky" tally. Only ever
381
+ * touched from flushSync, which the worker serialises.
382
+ */
383
+ private var ambiguousAttempts: Int = 0
384
+ private var ambiguousBatchIds: Set<String> = emptySet()
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
+
327
397
  // -------- Public enqueue API --------
328
398
 
329
399
  /**
330
400
  * Enqueue an IngestItem. Synchronous up to disk write — on return the
331
401
  * item is on disk (fsync'd inside OfflineQueueStore). Crossing
332
- * batchSize triggers a WorkManager flush.
402
+ * batchSize triggers a WorkManager flush. Returns false if the disk
403
+ * write failed (the item is NOT queued).
333
404
  */
334
- fun enqueue(item: IngestItem, context: Context) {
405
+ fun enqueue(item: IngestItem, context: Context): Boolean {
335
406
  try {
336
407
  queue.append(item)
337
408
  } catch (e: IOException) {
338
409
  Log.w(TAG, "enqueue failed", e)
339
- return
410
+ return false
340
411
  }
341
- val count = runCatching { queue.count() }.getOrNull() ?: return
412
+ val count = runCatching { queue.count() }.getOrNull() ?: return true
342
413
  if (count >= batchSize) {
343
414
  scheduleFlush(context)
344
415
  }
416
+ return true
345
417
  }
346
418
 
347
419
  /**
348
420
  * Convenience — build an item from type + JSON data.
349
421
  */
350
- fun enqueue(type: IngestItemType, data: JSONObject, context: Context) {
422
+ fun enqueue(type: IngestItemType, data: JSONObject, context: Context): Boolean =
351
423
  enqueue(IngestItem.create(type, data), context)
352
- }
353
424
 
354
425
  /**
355
426
  * Schedule a flush via WorkManager. KEEP coalesces concurrent enqueues.
@@ -399,6 +470,9 @@ internal class IngestClient(
399
470
  @Throws(IOException::class)
400
471
  fun flushSync(): IngestResult {
401
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())
402
476
  var totalQueued = 0
403
477
  val aggregateErrors = mutableListOf<IngestErrorEntry>()
404
478
  while (true) {
@@ -407,25 +481,59 @@ internal class IngestClient(
407
481
  val batch = items.take(batchSize)
408
482
  val envelope = buildEnvelope(batch)
409
483
  val resp = try {
410
- 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)
411
488
  } catch (e: BackendRejected) {
412
489
  // Whole batch rejected → dead-letter all.
413
490
  queue.deadLetter(batch)
414
491
  queue.remove(batch.map { it.id }.toSet())
415
492
  throw e
416
493
  } catch (e: BackendUnavailable) {
417
- // BackendUnavailable here means the bounded retry budget in
418
- // BackendHttpClient.kt:358 has already been exhausted.
419
- // Do NOT wrap in another retry — that would double-count
420
- // attempts and silently extend the effective retry window.
421
- // The batch is dead-lettered (not discarded) so it can be
422
- // inspected offline; retrying at this layer would only delay
423
- // the dead-letter and mask real backend degradation.
424
- queue.deadLetter(batch)
425
- 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)
426
499
  throw e
427
500
  }
428
- val parsed = parseResult(resp, batch.size)
501
+ val batchIds = batch.map { it.id }.toSet()
502
+ val parsed = try {
503
+ parseResult(resp, batch.size)
504
+ } catch (e: UndecodableIngestResponse) {
505
+ // We do not know what the server did with this batch, so we
506
+ // must not delete it. Leave it queued; the worker's retry
507
+ // brings us back here.
508
+ //
509
+ // Retrying an ambiguous batch can duplicate rather than lose:
510
+ // `analytics` items dedupe server-side on
511
+ // `(app_project_id, event_id)`, but several other item types
512
+ // currently mint a fresh id on ingest and would land twice.
513
+ // That trade is taken deliberately — a duplicate is visible
514
+ // and reconcilable, a silently dropped crash report is not.
515
+ val attempts = noteAmbiguousResponse(batchIds)
516
+ if (attempts < MAX_AMBIGUOUS_ATTEMPTS) throw e
517
+ // Budget spent — retire the batch to the dead-letter file,
518
+ // the same terminal-but-recoverable destination a
519
+ // server-rejected item gets. Never a silent drop.
520
+ Log.w(
521
+ TAG,
522
+ "dead-lettering ${batch.size} item(s) after $attempts undecodable " +
523
+ "success responses; last body: ${e.byteCount} bytes: ${e.preview}",
524
+ )
525
+ queue.deadLetter(batch)
526
+ queue.remove(batchIds)
527
+ clearAmbiguousStreak()
528
+ null
529
+ }
530
+ if (parsed == null) {
531
+ // Batch retired above; keep draining whatever is behind it.
532
+ if (batch.size < batchSize) break else continue
533
+ }
534
+ // A parseable answer — the server is talking sense again.
535
+ clearAmbiguousStreak()
536
+ clearBackoff()
429
537
  totalQueued += parsed.queued
430
538
  aggregateErrors.addAll(parsed.errors)
431
539
  val errorIdxs = parsed.errors.map { it.index }.toSet()
@@ -435,12 +543,75 @@ internal class IngestClient(
435
543
  if (deadLetterItems.isNotEmpty()) {
436
544
  queue.deadLetter(deadLetterItems)
437
545
  }
438
- queue.remove(batch.map { it.id }.toSet())
546
+ queue.remove(batchIds)
439
547
  if (batch.size < batchSize) break
440
548
  }
441
549
  return IngestResult(queued = totalQueued, errors = aggregateErrors)
442
550
  }
443
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
+
596
+ /**
597
+ * Record one undecodable-success response for [batchIds]; returns the
598
+ * running count. A different head-of-queue batch restarts the count.
599
+ */
600
+ private fun noteAmbiguousResponse(batchIds: Set<String>): Int {
601
+ if (batchIds == ambiguousBatchIds) {
602
+ ambiguousAttempts += 1
603
+ } else {
604
+ ambiguousBatchIds = batchIds
605
+ ambiguousAttempts = 1
606
+ }
607
+ return ambiguousAttempts
608
+ }
609
+
610
+ private fun clearAmbiguousStreak() {
611
+ ambiguousAttempts = 0
612
+ ambiguousBatchIds = emptySet()
613
+ }
614
+
444
615
  // -------- Envelope construction --------
445
616
 
446
617
  @VisibleForTesting
@@ -498,8 +669,22 @@ internal class IngestClient(
498
669
  return data
499
670
  }
500
671
 
672
+ /**
673
+ * Parse the server's `{ queued, errors }` answer.
674
+ *
675
+ * An EMPTY body is a genuine ack — the server answers 202 with no content
676
+ * on the fast path, and `postRaw` has already thrown for every non-2xx
677
+ * status, so nothing to read means "all accepted, nothing rejected".
678
+ *
679
+ * A NON-EMPTY body we cannot parse throws [UndecodableIngestResponse].
680
+ * It used to fall through to `IngestResult(queued = batchSize)`, which
681
+ * [flushSync] could not tell apart from a real ack — so it removed the
682
+ * batch from the durable queue and a truncated or corrupted 200 destroyed
683
+ * those items permanently. Absence of evidence is not evidence of
684
+ * acceptance.
685
+ */
501
686
  private fun parseResult(body: String, batchSize: Int): IngestResult {
502
- if (body.isEmpty()) return IngestResult(queued = batchSize, errors = emptyList())
687
+ if (body.isBlank()) return IngestResult(queued = batchSize, errors = emptyList())
503
688
  return runCatching {
504
689
  val obj = JSONObject(body)
505
690
  val queued = obj.optInt("queued", batchSize)
@@ -513,8 +698,10 @@ internal class IngestClient(
513
698
  }
514
699
  IngestResult(queued = queued, errors = errs)
515
700
  }.getOrElse {
516
- // 202 with empty / non-JSON body — assume everything queued.
517
- IngestResult(queued = batchSize, errors = emptyList())
701
+ throw UndecodableIngestResponse(
702
+ byteCount = body.length,
703
+ preview = body.take(200).replace('\n', ' '),
704
+ )
518
705
  }
519
706
  }
520
707
  }
@@ -531,8 +718,9 @@ internal class IngestClient(
531
718
  * Why WorkManager (vs. coroutine on an internal pool)?
532
719
  * - Survives process death — system reschedules after a kill.
533
720
  * - Network constraint is system-managed — waits for connectivity.
534
- * - Exponential backoff is system-managed — no in-app retry loop
535
- * 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).
536
724
  * - Doze + App Standby aware out of the box.
537
725
  */
538
726
  internal class IngestFlushWorker(
@@ -560,15 +748,20 @@ internal class IngestFlushWorker(
560
748
  Log.w(TAG, "ingest 4xx rejected: ${e.code}", e)
561
749
  Result.success()
562
750
  } catch (e: BackendUnavailable) {
563
- if (runAttemptCount + 1 >= MAX_ATTEMPTS) {
564
- Log.w(TAG, "ingest 5xx after $MAX_ATTEMPTS attempts; giving up", e)
565
- Result.success(
566
- Data.Builder().putBoolean("dead_lettered", true).build()
567
- )
568
- } else {
569
- Log.w(TAG, "ingest 5xx attempt ${runAttemptCount + 1}; will retry", e)
570
- Result.retry()
571
- }
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()
759
+ } catch (e: UndecodableIngestResponse) {
760
+ // A 2xx we could not parse. flushSync has kept the batch queued
761
+ // and owns the give-up decision (IngestClient.MAX_AMBIGUOUS_ATTEMPTS),
762
+ // so all this branch does is ask WorkManager to come back.
763
+ Log.w(TAG, "ingest undecodable success response; will retry", e)
764
+ Result.retry()
572
765
  } catch (e: IOException) {
573
766
  if (runAttemptCount + 1 >= MAX_ATTEMPTS) {
574
767
  Log.w(TAG, "ingest IO after $MAX_ATTEMPTS attempts; giving up", e)
@@ -415,6 +415,12 @@ public final class SKAnalytics {
415
415
  ///
416
416
  /// Fire-and-forget by design — the SDK doesn't surface a completion
417
417
  /// handler in its public contract.
418
+ ///
419
+ /// The bare `Task` here is safe only because `flushBestEffort()`
420
+ /// serializes: this call and the `startFlushTimer()` tick below are
421
+ /// two of the six triggers that used to race each other, and every
422
+ /// racing pair re-uploaded whatever was in the queue. Do not
423
+ /// "optimise" this into a direct `ingest.flush()`.
418
424
  public func flush() {
419
425
  Task { [ingest] in
420
426
  await ingest.flushBestEffort()
@@ -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.1"
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?