react-native-nitro-sse 3.0.0 → 3.2.0-beta.1

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 (49) hide show
  1. package/NitroSse.podspec +0 -1
  2. package/README.md +16 -5
  3. package/android/build.gradle +0 -1
  4. package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +33 -10
  5. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +366 -78
  6. package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +417 -94
  7. package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +20 -0
  8. package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +9 -0
  9. package/ios/NitroSse.swift +302 -49
  10. package/ios/SseConnectionHandler.swift +647 -97
  11. package/ios/SseEventBuffer.swift +19 -1
  12. package/ios/SseReconnectStrategy.swift +26 -7
  13. package/lib/module/FetchSseDriver.js +845 -0
  14. package/lib/module/MockSseEngine.js +72 -3
  15. package/lib/module/NitroSseClient.js +43 -18
  16. package/lib/module/SseDriver.js +31 -15
  17. package/lib/module/SseEventParser.js +238 -0
  18. package/lib/module/createNitroSse.js +12 -5
  19. package/lib/module/createNitroSse.native.js +24 -0
  20. package/lib/module/createNitroSse.web.js +13 -0
  21. package/lib/module/index.js +2 -1
  22. package/lib/module/index.native.js +8 -0
  23. package/lib/module/index.web.js +9 -0
  24. package/lib/module/useNitroSse.js +1 -1
  25. package/lib/typescript/src/FetchSseDriver.d.ts +92 -0
  26. package/lib/typescript/src/MockSseEngine.d.ts +16 -0
  27. package/lib/typescript/src/NitroSseClient.d.ts +4 -1
  28. package/lib/typescript/src/SseDriver.d.ts +8 -4
  29. package/lib/typescript/src/SseEventParser.d.ts +42 -0
  30. package/lib/typescript/src/SseInterface.d.ts +46 -3
  31. package/lib/typescript/src/createNitroSse.d.ts +2 -2
  32. package/lib/typescript/src/createNitroSse.native.d.ts +9 -0
  33. package/lib/typescript/src/createNitroSse.web.d.ts +8 -0
  34. package/lib/typescript/src/index.d.ts +1 -0
  35. package/lib/typescript/src/index.native.d.ts +6 -0
  36. package/lib/typescript/src/index.web.d.ts +7 -0
  37. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +4 -0
  38. package/nitrogen/generated/android/c++/JSseDisconnectReason.hpp +67 -0
  39. package/nitrogen/generated/android/c++/JSseStats.hpp +87 -1
  40. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseDisconnectReason.kt +26 -0
  41. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseStats.kt +108 -3
  42. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +18 -0
  43. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +3 -0
  44. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +3 -0
  45. package/nitrogen/generated/ios/swift/SseDisconnectReason.swift +52 -0
  46. package/nitrogen/generated/ios/swift/SseStats.swift +217 -2
  47. package/nitrogen/generated/shared/c++/SseDisconnectReason.hpp +88 -0
  48. package/nitrogen/generated/shared/c++/SseStats.hpp +88 -2
  49. package/package.json +13 -2
@@ -8,7 +8,7 @@ import okhttp3.Request
8
8
  import okhttp3.Response
9
9
  import okhttp3.MediaType.Companion.toMediaType
10
10
  import okhttp3.RequestBody.Companion.toRequestBody
11
- import okhttp3.sse.EventSource
11
+ import okio.utf8Size
12
12
  import com.margelo.nitro.NitroModules
13
13
  import com.margelo.nitro.core.Promise
14
14
  import java.util.concurrent.TimeUnit
@@ -33,9 +33,13 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
33
33
  internal constructor(dispatcher: SseDispatcher) : this() {
34
34
  this.sseDispatcher = dispatcher
35
35
  }
36
+ @Volatile
36
37
  private var client: OkHttpClient? = null
37
- private var eventSource: EventSource? = null
38
+ private var eventSource: SseEventSource? = null
38
39
  private var config: SseConfig? = null
40
+ // Marked @Volatile to guarantee cross-thread memory visibility between calling thread stop()/dispose()
41
+ // and sseDispatcher/OkHttp callback execution threads without stale reads.
42
+ @Volatile
39
43
  private var requestId: String? = null
40
44
 
41
45
  private val isRunning = AtomicBoolean(false)
@@ -53,13 +57,41 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
53
57
  private var sseDispatcherThread: android.os.HandlerThread? = null
54
58
  internal var sseDispatcher: SseDispatcher? = null
55
59
 
60
+ // Transport Metrics
61
+ private var rawBytesReceived: Double = 0.0
62
+ private var decompressedBytesReceived: Double? = null
63
+ private var sessionRawBytesOffset: Double = 0.0
56
64
  private val totalBytesReceived = AtomicLong(0)
65
+ private var chunksReceived: Double = 0.0
66
+ private var lastStatusCode: Double? = null
67
+
68
+ // Parser Metrics
69
+ private var totalEventsReceived: Double = 0.0
70
+ private var commentsReceived: Double = 0.0
71
+ private var linesParsed: Double = 0.0
72
+ private var parseErrors: Double = 0.0
73
+ private var serverRetryDelayMs: Double? = null
74
+
75
+ // Latency & Timing Metrics
76
+ private var connectedAt: Double? = null
77
+ private var connectionAttemptStartTime: Double? = null
78
+ private var timeToFirstByteMs: Double? = null
79
+ private var lastEventTime: Double? = null
80
+ private var lastHeartbeatTime: Double? = null
81
+ private var lastActivityTime: Double = 0.0
82
+ private var maxEventGapMs: Double = 0.0
83
+
84
+ // Lifecycle & Reconnect Metrics
85
+ private var connectionAttempts: Double = 0.0
86
+ private var reconnectCount: Double = 0.0
87
+ private var lastReconnectDelayMs: Double? = null
88
+ private var disconnectReason: SseDisconnectReason? = null
89
+ private var lastErrorTime: Double? = null
90
+ private var lastErrorCode: String? = null
91
+
57
92
  private val connectionAttemptVersion = AtomicInteger(0)
58
93
  private var lastProcessedId: String? = null
59
94
  private var currentState = java.util.concurrent.atomic.AtomicReference(SseState.IDLE)
60
- private val totalReconnectCount = AtomicInteger(0)
61
- private var lastErrorTime: Double? = null
62
- private var lastErrorCode: String? = null
63
95
  private var wasRunningBeforeNetworkLoss = false
64
96
  private var interceptorTimeoutRunnable: Runnable? = null
65
97
  private val isDisposed = AtomicBoolean(false)
@@ -86,6 +118,14 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
86
118
  synchronized(this) {
87
119
  this.config = config
88
120
  this.requestInterceptor = onBeforeRequest
121
+ this.rawBytesReceived = 0.0
122
+ this.decompressedBytesReceived = null
123
+ this.sessionRawBytesOffset = 0.0
124
+ if (this.lastProcessedId == null) {
125
+ this.lastProcessedId = config.headers?.entries?.firstOrNull {
126
+ it.key.equals("Last-Event-ID", ignoreCase = true)
127
+ }?.value
128
+ }
89
129
 
90
130
  if (sseDispatcher == null) {
91
131
  sseDispatcherThread = android.os.HandlerThread("NitroSseThread").apply { start() }
@@ -116,17 +156,6 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
116
156
  // before bubbling up to full SSE stream reconnect.
117
157
  .retryOnConnectionFailure(true)
118
158
  .addNetworkInterceptor(InspectorNetworkInterceptor())
119
- .addInterceptor(HeartbeatInterceptor { heartbeatRid, comment ->
120
- sseDispatcher?.post {
121
- // Guard keep-alive signals by active request ID to ignore residual bytes from closed/closing sockets
122
- val currentRid = synchronized(this@NitroSse) { requestId }
123
- if (heartbeatRid == null || heartbeatRid == currentRid) {
124
- val commentBytes = comment.toByteArray(Charsets.UTF_8).size.toLong()
125
- totalBytesReceived.addAndGet(commentBytes)
126
- eventBuffer.push(SseEvent(SseEventType.HEARTBEAT, null, null, null, null, comment, null, null, null))
127
- }
128
- }
129
- })
130
159
  this.client = builder.build()
131
160
  } else {
132
161
  this.client = this.client!!.newBuilder()
@@ -243,11 +272,37 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
243
272
 
244
273
  override fun getStats(): SseStats {
245
274
  synchronized(this) {
275
+ val buffered = if (::eventBuffer.isInitialized) eventBuffer.getEventsBuffered().toDouble() else 0.0
276
+ val peak = if (::eventBuffer.isInitialized) eventBuffer.getPeakBufferedEvents().toDouble() else 0.0
277
+ val flushes = if (::eventBuffer.isInitialized) eventBuffer.getBufferFlushCount().toDouble() else 0.0
278
+ val overflows = if (::eventBuffer.isInitialized) eventBuffer.getBufferOverflowCount().toDouble() else 0.0
279
+
246
280
  return SseStats(
247
- totalBytesReceived.get().toDouble(),
248
- totalReconnectCount.get().toDouble(),
249
- lastErrorTime,
250
- lastErrorCode
281
+ rawBytesReceived = rawBytesReceived,
282
+ decompressedBytesReceived = decompressedBytesReceived,
283
+ totalBytesReceived = totalBytesReceived.get().toDouble(),
284
+ chunksReceived = chunksReceived,
285
+ lastStatusCode = lastStatusCode,
286
+ totalEventsReceived = totalEventsReceived,
287
+ commentsReceived = commentsReceived,
288
+ linesParsed = linesParsed,
289
+ parseErrors = parseErrors,
290
+ serverRetryDelayMs = serverRetryDelayMs,
291
+ connectedAt = connectedAt,
292
+ timeToFirstByteMs = timeToFirstByteMs,
293
+ lastEventTime = lastEventTime,
294
+ lastHeartbeatTime = lastHeartbeatTime,
295
+ maxEventGapMs = maxEventGapMs,
296
+ eventsBuffered = buffered,
297
+ peakBufferedEvents = peak,
298
+ bufferFlushCount = flushes,
299
+ bufferOverflowCount = overflows,
300
+ connectionAttempts = connectionAttempts,
301
+ reconnectCount = reconnectCount,
302
+ lastReconnectDelayMs = lastReconnectDelayMs,
303
+ disconnectReason = disconnectReason,
304
+ lastErrorTime = lastErrorTime,
305
+ lastErrorCode = lastErrorCode
251
306
  )
252
307
  }
253
308
  }
@@ -329,8 +384,10 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
329
384
  sseDispatcher?.postDelayed(timeoutRunnable, timeoutMs)
330
385
 
331
386
  try {
332
- interceptor.invoke().then { promise2 ->
333
- promise2.then { newHeaders ->
387
+ // Note: Safe-calls (?.) protect against null/unmocked Promise chains in unit tests and JS bridging.
388
+ // Parameter non-null intrinsics and synchronous errors route to catch(e: Throwable) / safeHandleError.
389
+ interceptor.invoke()?.then { promise2 ->
390
+ promise2?.then { newHeaders ->
334
391
  sseDispatcher?.post {
335
392
  if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
336
393
  if (interceptorCompleted.compareAndSet(false, true)) {
@@ -345,10 +402,10 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
345
402
  executeConnection(version, connectionConfig)
346
403
  }
347
404
  }
348
- }.catch { error ->
405
+ }?.catch { error ->
349
406
  safeHandleError(error)
350
407
  }
351
- }.catch { error ->
408
+ }?.catch { error ->
352
409
  safeHandleError(error)
353
410
  }
354
411
  } catch (e: Throwable) {
@@ -382,6 +439,13 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
382
439
  return@post
383
440
  }
384
441
 
442
+ val maxRetries = synchronized(this@NitroSse) { config?.maxAuthRetries?.toInt() ?: DEFAULT_MAX_AUTH_RETRIES }
443
+ val retries = consecutiveAuthErrors.incrementAndGet()
444
+ if (retries > maxRetries) {
445
+ failAndStop("Auth retry limit reached ($maxRetries). Stopping.", -1.0)
446
+ return@post
447
+ }
448
+
385
449
  eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "Interceptor Error: ${t?.message}", -1.0, null, null))
386
450
  scheduleReconnect(true, version)
387
451
  }
@@ -392,20 +456,35 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
392
456
  val currentLastId: String?
393
457
  val oldRequestId: String?
394
458
  val newRequestId = UUID.randomUUID().toString()
459
+ val safeClient: OkHttpClient
395
460
 
396
461
  synchronized(this) {
397
462
  if (!isRunning.get() || config == null || version != connectionAttemptVersion.get()) return
398
463
  currentConfig = connectionConfig ?: config!!
399
464
  currentLastId = lastProcessedId
465
+ safeClient = client ?: return
400
466
 
401
467
  oldRequestId = requestId
468
+ if (oldRequestId != null && SseNetworkMetricsTracker.isGzip(oldRequestId)) {
469
+ val raw = SseNetworkMetricsTracker.getRawBytes(oldRequestId)
470
+ if (raw != null) {
471
+ sessionRawBytesOffset += raw.toDouble()
472
+ }
473
+ }
402
474
  requestId = newRequestId
403
475
 
404
476
  eventSource?.cancel()
405
477
  eventSource = null
478
+
479
+ connectionAttempts += 1.0
480
+ connectionAttemptStartTime = System.currentTimeMillis().toDouble()
481
+ timeToFirstByteMs = null
406
482
  }
407
483
 
408
- oldRequestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
484
+ oldRequestId?.let {
485
+ NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
486
+ SseNetworkMetricsTracker.clear(it)
487
+ }
409
488
 
410
489
  try {
411
490
  // Set SSE headers explicitly for Network Inspector visibility and encoding control.
@@ -414,9 +493,9 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
414
493
  .header("Accept", "text/event-stream")
415
494
  .header("Cache-Control", "no-cache")
416
495
 
417
- // Populate config headers first, filtering out Last-Event-ID so dynamic reconnection ID takes precedence.
496
+ // Populate config headers first, filtering out Last-Event-ID and Accept-Encoding
418
497
  currentConfig.headers?.forEach { (k, v) ->
419
- if (!k.equals("Last-Event-ID", ignoreCase = true)) {
498
+ if (!k.equals("Last-Event-ID", ignoreCase = true) && !k.equals("Accept-Encoding", ignoreCase = true)) {
420
499
  requestBuilder.header(k, v)
421
500
  }
422
501
  }
@@ -426,7 +505,11 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
426
505
  }
427
506
 
428
507
  if (currentConfig.method == HttpMethod.POST) {
429
- val body = currentConfig.body?.toRequestBody("application/json".toMediaType()) ?: "".toRequestBody()
508
+ val customContentType = currentConfig.headers?.entries?.firstOrNull {
509
+ it.key.equals("Content-Type", ignoreCase = true)
510
+ }?.value
511
+ val mediaType = (customContentType ?: "application/json").toMediaType()
512
+ val body = (currentConfig.body ?: "").toRequestBody(mediaType)
430
513
  requestBuilder.post(body)
431
514
  }
432
515
 
@@ -434,8 +517,15 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
434
517
  val request = requestBuilder.build()
435
518
  NetworkInspector.reportRequestStart(newRequestId, request)
436
519
 
437
- val newEventSource = connectionHandler.createEventSource(client!!, request, newRequestId)
438
- synchronized(this) { eventSource = newEventSource }
520
+ val newEventSource = connectionHandler.createEventSource(safeClient, request, newRequestId)
521
+ synchronized(this) {
522
+ // Ensure socket is cancelled if stop() or dispose() raced with socket initialization
523
+ if (!isRunning.get() || version != connectionAttemptVersion.get()) {
524
+ newEventSource.cancel()
525
+ } else {
526
+ eventSource = newEventSource
527
+ }
528
+ }
439
529
  } catch (e: Exception) {
440
530
  // Standard Java Exception catch: handles IllegalArgumentException (URL/headers), NullPointerException,
441
531
  // and IllegalStateException without catching/suppressing fatal JVM errors (e.g. OutOfMemoryError, VirtualMachineError).
@@ -449,33 +539,144 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
449
539
  if (requestId != this@NitroSse.requestId) return@post
450
540
  consecutiveAuthErrors.set(0)
451
541
  reconnectStrategy.reset()
542
+ synchronized(this@NitroSse) {
543
+ if (currentState.get() == SseState.RECONNECTING) {
544
+ reconnectCount += 1.0
545
+ }
546
+ lastStatusCode = response.code.toDouble()
547
+ connectedAt = System.currentTimeMillis().toDouble()
548
+ }
452
549
  updateState(SseState.OPEN)
453
550
  eventBuffer.push(SseEvent(SseEventType.OPEN, null, null, null, null, null, response.code.toDouble(), null, null))
454
551
  }
455
552
  }
456
553
 
457
- override fun connectionDidReceiveMessage(id: String?, type: String?, data: String, requestId: String) {
554
+ override fun connectionDidReceiveDataChunk(decompressedBytes: Long, requestId: String) {
555
+ synchronized(this) {
556
+ if (requestId != this.requestId) return
557
+ chunksReceived += 1.0
558
+ val isGzip = SseNetworkMetricsTracker.isGzip(requestId)
559
+ if (isGzip) {
560
+ decompressedBytesReceived = (decompressedBytesReceived ?: 0.0) + decompressedBytes.toDouble()
561
+ val raw = SseNetworkMetricsTracker.getRawBytes(requestId)
562
+ rawBytesReceived = sessionRawBytesOffset + (raw?.toDouble() ?: decompressedBytes.toDouble())
563
+ } else {
564
+ rawBytesReceived += decompressedBytes.toDouble()
565
+ }
566
+ if (timeToFirstByteMs == null && connectionAttemptStartTime != null) {
567
+ timeToFirstByteMs = System.currentTimeMillis().toDouble() - connectionAttemptStartTime!!
568
+ }
569
+ }
570
+ }
571
+
572
+ override fun connectionDidParseLines(count: Int, requestId: String) {
573
+ synchronized(this) {
574
+ if (requestId != this.requestId) return
575
+ linesParsed += count.toDouble()
576
+ }
577
+ }
578
+
579
+ override fun connectionDidEncounterParseError(requestId: String) {
458
580
  sseDispatcher?.post {
459
581
  if (requestId != this@NitroSse.requestId) return@post
460
- val encodedDataSize = data.toByteArray(Charsets.UTF_8).size.toLong()
461
- val metadataSize = (id?.toByteArray(Charsets.UTF_8)?.size?.toLong() ?: 0L) +
462
- (type?.toByteArray(Charsets.UTF_8)?.size?.toLong() ?: 0L)
463
- totalBytesReceived.addAndGet(encodedDataSize + metadataSize)
464
-
465
- val currentConfig: SseConfig?
466
582
  synchronized(this@NitroSse) {
467
- // WHATWG SSE Spec: If the server sends an empty id (e.g. 'id:\n'), reset lastProcessedId to null.
468
- if (id != null) {
469
- this@NitroSse.lastProcessedId = if (id.isEmpty()) null else id
583
+ parseErrors += 1.0
584
+ disconnectReason = SseDisconnectReason.PARSER_ERROR
585
+ }
586
+ }
587
+ }
588
+
589
+ override fun connectionDidReceiveMessage(id: String?, type: String?, data: String, requestId: String) {
590
+ val currentRid = synchronized(this@NitroSse) { this@NitroSse.requestId }
591
+ if (requestId != currentRid) return
592
+ // Spec-compliant logical byte accounting (UTF-8 payload: data + event + id + comment).
593
+ // Matches iOS (NitroSse.swift) and JS Mock (MockSseEngine.ts). Raw wire headers/framing
594
+ // are intentionally excluded to maintain cross-platform parity.
595
+ val encodedDataSize = data.utf8Size()
596
+ val eventTypeSize = if (type != null && type != "message") type.utf8Size() else 0L
597
+
598
+ val currentConfig: SseConfig?
599
+ synchronized(this@NitroSse) {
600
+ if (requestId != this@NitroSse.requestId) return
601
+ val currentLastId = this@NitroSse.lastProcessedId
602
+ val isNewId = !id.isNullOrEmpty() && id != currentLastId
603
+ val idSize = if (isNewId) id!!.utf8Size() else 0L
604
+ totalBytesReceived.addAndGet(encodedDataSize + eventTypeSize + idSize)
605
+
606
+ // WHATWG SSE Spec: If the server sends an empty id (e.g. 'id:\n'), reset lastProcessedId to null.
607
+ // Note: lastProcessedId is dynamically updated here for every incoming message with an id,
608
+ // feeding into Last-Event-ID for reconnection resumption per WHATWG SSE specification.
609
+ if (id != null) {
610
+ this@NitroSse.lastProcessedId = if (id.isEmpty()) null else id
611
+ }
612
+ currentConfig = this@NitroSse.config
613
+ totalEventsReceived += 1.0
614
+ val now = System.currentTimeMillis().toDouble()
615
+ lastEventTime = now
616
+ if (lastActivityTime > 0.0) {
617
+ val gap = now - lastActivityTime
618
+ if (gap > maxEventGapMs) {
619
+ maxEventGapMs = gap
470
620
  }
471
- currentConfig = this@NitroSse.config
472
621
  }
473
- val parsedData = if (currentConfig?.autoParseJSON == true) JsonUtils.parseJsonToAnyMap(data) else null
622
+ lastActivityTime = now
623
+ }
624
+ val parsedData = if (currentConfig?.autoParseJSON == true) JsonUtils.parseJsonToAnyMap(data) else null
625
+ sseDispatcher?.post {
626
+ if (requestId != this@NitroSse.requestId) return@post
474
627
  eventBuffer.push(SseEvent(SseEventType.MESSAGE, data, parsedData, id, type, null, 200.0, null, null))
475
628
  }
476
629
  }
477
630
 
631
+ override fun connectionDidReceiveComment(comment: String, requestId: String) {
632
+ val currentRid = synchronized(this@NitroSse) { this@NitroSse.requestId }
633
+ if (requestId != currentRid) return
634
+ val commentBytes = comment.utf8Size()
635
+ synchronized(this@NitroSse) {
636
+ if (requestId != this@NitroSse.requestId) return
637
+ totalBytesReceived.addAndGet(commentBytes)
638
+ commentsReceived += 1.0
639
+ val now = System.currentTimeMillis().toDouble()
640
+ lastHeartbeatTime = now
641
+ if (lastActivityTime > 0.0) {
642
+ val gap = now - lastActivityTime
643
+ if (gap > maxEventGapMs) {
644
+ maxEventGapMs = gap
645
+ }
646
+ }
647
+ lastActivityTime = now
648
+ }
649
+ // TODO(breaking-change): In next major version, avoid pushing HEARTBEAT event across JSI; use internal watchdog or dedicated onHeartbeat callback to eliminate bridge overhead.
650
+ sseDispatcher?.post {
651
+ if (requestId != this@NitroSse.requestId) return@post
652
+ eventBuffer.push(SseEvent(SseEventType.HEARTBEAT, null, null, null, null, comment, null, null, null))
653
+ }
654
+ }
655
+
656
+ override fun connectionDidReceiveRetry(retryMs: Long, requestId: String) {
657
+ synchronized(this@NitroSse) {
658
+ if (requestId != this@NitroSse.requestId) return
659
+ serverRetryDelayMs = retryMs.toDouble()
660
+ reconnectStrategy.updateRetryInterval(retryMs.toDouble())
661
+ }
662
+ }
663
+
664
+ override fun connectionDidUpdateLastEventId(id: String?, requestId: String) {
665
+ val newId = if (id.isNullOrEmpty()) null else id
666
+ synchronized(this@NitroSse) {
667
+ if (requestId != this@NitroSse.requestId) return
668
+ if (newId != null && newId != this@NitroSse.lastProcessedId) {
669
+ totalBytesReceived.addAndGet(newId.utf8Size())
670
+ }
671
+ this@NitroSse.lastProcessedId = newId
672
+ }
673
+ }
674
+
478
675
  override fun connectionDidFail(t: Throwable?, response: Response?, requestId: String) {
676
+ connectionDidFail(t, response, null, requestId)
677
+ }
678
+
679
+ override fun connectionDidFail(t: Throwable?, response: Response?, errorBody: String?, requestId: String) {
479
680
  sseDispatcher?.post {
480
681
  // Note on Stale Callback Protection:
481
682
  // Android uses a unique UUID `requestId` per connection attempt rather than an integer `attemptVersion`.
@@ -484,19 +685,64 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
484
685
  // socket are safely and strictly rejected by `if (requestId != this@NitroSse.requestId) return@post`.
485
686
  if (requestId != this@NitroSse.requestId || !isRunning.get()) return@post
486
687
  val statusCode = response?.code ?: -1
487
-
488
- totalReconnectCount.incrementAndGet()
688
+ val isTimeout = t is java.net.SocketTimeoutException || t is java.io.InterruptedIOException || t?.message?.contains("timeout", ignoreCase = true) == true
689
+ val isParserLimit = t?.message?.contains("SSE line exceeded maximum limit", ignoreCase = true) == true ||
690
+ t?.message?.contains("SSE event data exceeded maximum limit", ignoreCase = true) == true ||
691
+ t is InvalidContentTypeException
692
+
489
693
  synchronized(this@NitroSse) {
694
+ connectedAt = null
695
+ if (statusCode != -1) {
696
+ lastStatusCode = statusCode.toDouble()
697
+ }
490
698
  lastErrorTime = System.currentTimeMillis().toDouble()
491
699
  lastErrorCode = t?.javaClass?.simpleName ?: statusCode.toString()
700
+
701
+ if (statusCode >= 400 || statusCode == 204) {
702
+ disconnectReason = SseDisconnectReason.SERVER_ERROR
703
+ } else if (isParserLimit) {
704
+ disconnectReason = SseDisconnectReason.PARSER_ERROR
705
+ } else if (isTimeout) {
706
+ disconnectReason = SseDisconnectReason.TIMEOUT
707
+ } else {
708
+ disconnectReason = SseDisconnectReason.NETWORK_ERROR
709
+ }
492
710
  }
493
711
 
494
712
  val currentRequestId = synchronized(this@NitroSse) {
495
713
  val id = this@NitroSse.requestId
714
+ if (id != null) {
715
+ val raw = SseNetworkMetricsTracker.getRawBytes(id)
716
+ if (raw != null) {
717
+ sessionRawBytesOffset += raw.toDouble()
718
+ }
719
+ }
496
720
  this@NitroSse.requestId = null
497
721
  id
498
722
  }
499
- currentRequestId?.let { NetworkInspector.reportRequestFailed(it, false) }
723
+ currentRequestId?.let {
724
+ NetworkInspector.reportRequestFailed(it, false)
725
+ SseNetworkMetricsTracker.clear(it)
726
+ }
727
+
728
+ if (statusCode == 204) {
729
+ failAndStop("No Content (204). Stopping.", 204.0)
730
+ return@post
731
+ }
732
+
733
+ // Strict WHATWG SSE: permanently close without reconnecting on non-event-stream Content-Type (e.g. captive portal 200 HTML).
734
+ val isInvalidContentType = t is InvalidContentTypeException ||
735
+ (response != null && response.code in 200..299 && !(response.header("Content-Type")?.contains("text/event-stream", ignoreCase = true) ?: false))
736
+ if (isInvalidContentType) {
737
+ failAndStop("Invalid Content-Type: expected text/event-stream. Stopping.", if (statusCode != -1) statusCode.toDouble() else null)
738
+ return@post
739
+ }
740
+
741
+ // Parser resource violations (line length, event data size) are fatal and must not reconnect
742
+ if (isParserLimit) {
743
+ failAndStop(t?.message ?: "Resource limit exceeded. Stopping.", if (statusCode != -1) statusCode.toDouble() else null)
744
+ return@post
745
+ }
500
746
 
501
747
  val maxRetries = synchronized(this@NitroSse) { config?.maxAuthRetries?.toInt() ?: DEFAULT_MAX_AUTH_RETRIES }
502
748
  // Handle 401/403 with async token refresh up to maxAuthRetries.
@@ -518,26 +764,25 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
518
764
 
519
765
  val isFatal = (statusCode in 400..499 && statusCode != 401 && statusCode != 403 && statusCode != 408 && statusCode != 429)
520
766
  if (isFatal) {
521
- failAndStop("Fatal Error ($statusCode). Stopping.", statusCode.toDouble())
767
+ val sanitizedBody = errorBody?.trim()?.ifEmpty { null }
768
+ val finalMessage = if (sanitizedBody != null) {
769
+ "Fatal Error ($statusCode): $sanitizedBody"
770
+ } else {
771
+ "Fatal Error ($statusCode). Stopping."
772
+ }
773
+ failAndStop(finalMessage, statusCode.toDouble())
522
774
  return@post
523
775
  }
524
776
 
525
777
  // Schedule non-blocking Retry-After delay on dispatcher.
526
778
  val retryAfterMillis = SseReconnectStrategy.extractRetryAfterMillis(response)
527
779
  if ((statusCode == 429 || statusCode == 503) && retryAfterMillis != null) {
528
- if (reconnectStrategy.hasReachedMaxAttempts()) {
529
- val maxAttempts = reconnectStrategy.currentReconnectAttempts
530
- Log.d(TAG, "Max reconnection attempts reached ($maxAttempts). Stopping.")
531
- failAndStop("Max reconnection attempts reached ($maxAttempts).")
532
- return@post
533
- }
534
- reconnectStrategy.recordAttempt()
780
+ val maxInterval = synchronized(this@NitroSse) { (config?.maxRetryIntervalMs ?: 30000.0).toLong() }
781
+ val boundedRetryAfter = retryAfterMillis.coerceIn(0L, maxInterval)
535
782
  val jitter = (500 + Random.nextInt(1001)).toLong()
536
- val totalDelay = retryAfterMillis + jitter
537
- eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "Retry-After received: ${totalDelay/1000}s", statusCode.toDouble(), totalDelay.toDouble(), null))
538
- val newAttemptVersion = connectionAttemptVersion.incrementAndGet()
539
- updateState(SseState.RECONNECTING)
540
- sseDispatcher?.postDelayed({ if (isRunning.get() && newAttemptVersion == connectionAttemptVersion.get()) performConnection(newAttemptVersion) }, totalDelay)
783
+ val totalDelay = boundedRetryAfter + jitter
784
+ eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "Retry-After received: ${totalDelay / 1000}s", statusCode.toDouble(), totalDelay.toDouble(), null))
785
+ scheduleReconnect(true, connectionAttemptVersion.get(), totalDelay)
541
786
  return@post
542
787
  }
543
788
 
@@ -547,18 +792,20 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
547
792
  return@post
548
793
  }
549
794
 
550
- if (statusCode == 204) {
551
- failAndStop("No Content (204). Stopping.", 204.0)
552
- return@post
553
- }
554
-
555
- val isTimeout = t is java.net.SocketTimeoutException || t is java.io.InterruptedIOException || t?.message?.contains("timeout", ignoreCase = true) == true
795
+ // Map request timeout to STALE state before scheduling reconnection.
796
+ // Intentionally mirrors iOS (NitroSse.swift). OkHttp readTimeout acts as watchdog;
797
+ // emitting STALE notifies JS listeners of timeout-induced degradation before RECONNECTING.
556
798
  if (isTimeout) {
557
799
  updateState(SseState.STALE)
558
800
  }
559
801
 
802
+ val defaultErrorMsg = when {
803
+ statusCode >= 500 && !errorBody.isNullOrBlank() -> "Server Error ($statusCode): ${errorBody.trim()}"
804
+ else -> t?.message ?: "Link lost ($statusCode)"
805
+ }
806
+
560
807
  // Teardown and reconnect on stream or socket failure.
561
- eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, t?.message ?: "Link lost ($statusCode)", if (statusCode != -1) statusCode.toDouble() else null, null, null))
808
+ eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, defaultErrorMsg, if (statusCode != -1) statusCode.toDouble() else null, null, null))
562
809
  scheduleReconnect(true, connectionAttemptVersion.get())
563
810
  }
564
811
  }
@@ -566,6 +813,9 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
566
813
  override fun connectionDidClose(requestId: String) {
567
814
  sseDispatcher?.post {
568
815
  if (requestId != this@NitroSse.requestId || !isRunning.get()) return@post
816
+ synchronized(this@NitroSse) {
817
+ connectedAt = null
818
+ }
569
819
  clearActiveRequestAndReportEnd()
570
820
  scheduleReconnect(false, connectionAttemptVersion.get())
571
821
  }
@@ -577,7 +827,7 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
577
827
  stopInternal()
578
828
  }
579
829
 
580
- private fun scheduleReconnect(isError: Boolean, attemptVersion: Int) {
830
+ private fun scheduleReconnect(isError: Boolean, attemptVersion: Int, fixedDelay: Long? = null) {
581
831
  if (!isRunning.get() || attemptVersion != connectionAttemptVersion.get()) return
582
832
  if (reconnectStrategy.hasReachedMaxAttempts()) {
583
833
  val maxAttempts = reconnectStrategy.currentReconnectAttempts
@@ -585,9 +835,17 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
585
835
  failAndStop("Max reconnection attempts reached ($maxAttempts).")
586
836
  return
587
837
  }
838
+ val safeReconnectDelay = if (fixedDelay != null) {
839
+ reconnectStrategy.recordAttempt()
840
+ fixedDelay
841
+ } else {
842
+ reconnectStrategy.nextDelay(isError)
843
+ }
844
+ synchronized(this) {
845
+ lastReconnectDelayMs = safeReconnectDelay.toDouble()
846
+ }
588
847
  // Increment attempt version before scheduling to invalidate pending tasks from previous cycles
589
848
  val newAttemptVersion = connectionAttemptVersion.incrementAndGet()
590
- val safeReconnectDelay = reconnectStrategy.nextDelay(isError)
591
849
  updateState(SseState.RECONNECTING)
592
850
  sseDispatcher?.postDelayed({
593
851
  // Double check version and running state at trigger time to discard stale delayed callbacks
@@ -598,6 +856,9 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
598
856
  }
599
857
 
600
858
  private fun stopInternal() {
859
+ synchronized(this) {
860
+ connectedAt = null
861
+ }
601
862
  isRunning.set(false)
602
863
  connectionAttemptVersion.incrementAndGet()
603
864
  performInternalCleanup()
@@ -632,17 +893,27 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
632
893
  }
633
894
 
634
895
  override fun stop() {
896
+ synchronized(this) {
897
+ if (isRunning.get()) {
898
+ disconnectReason = SseDisconnectReason.USER_STOP
899
+ }
900
+ connectedAt = null
901
+ }
902
+ isRunning.set(false)
903
+ val stopVersion = connectionAttemptVersion.incrementAndGet()
904
+ clearActiveRequestAndReportEnd()
905
+
635
906
  val task = {
636
- isRunning.set(false)
637
- wasRunningBeforeNetworkLoss = false
638
- wasRunningBeforePaused = false
639
- if (!isDispatcherDestroyed && currentState.get() != SseState.FAILED) {
640
- updateState(SseState.CLOSED)
641
- } else if (isDispatcherDestroyed) {
642
- currentState.set(SseState.CLOSED)
907
+ if (connectionAttemptVersion.get() == stopVersion) {
908
+ wasRunningBeforeNetworkLoss = false
909
+ wasRunningBeforePaused = false
910
+ if (!isDispatcherDestroyed && currentState.get() != SseState.FAILED) {
911
+ updateState(SseState.CLOSED)
912
+ } else if (isDispatcherDestroyed) {
913
+ currentState.set(SseState.CLOSED)
914
+ }
915
+ performInternalCleanup()
643
916
  }
644
- connectionAttemptVersion.incrementAndGet()
645
- performInternalCleanup()
646
917
  }
647
918
  if (sseDispatcher?.isCurrentDispatcher() == true) {
648
919
  task()
@@ -653,13 +924,22 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
653
924
 
654
925
  private fun clearActiveRequestAndReportEnd() {
655
926
  val currentRequestId = synchronized(this) {
927
+ val id = requestId
928
+ if (id != null && SseNetworkMetricsTracker.isGzip(id)) {
929
+ val raw = SseNetworkMetricsTracker.getRawBytes(id)
930
+ if (raw != null) {
931
+ sessionRawBytesOffset += raw.toDouble()
932
+ }
933
+ }
656
934
  eventSource?.cancel()
657
935
  eventSource = null
658
- val id = requestId
659
936
  requestId = null
660
937
  id
661
938
  }
662
- currentRequestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
939
+ currentRequestId?.let {
940
+ NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
941
+ SseNetworkMetricsTracker.clear(it)
942
+ }
663
943
  }
664
944
 
665
945
  /**
@@ -680,6 +960,8 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
680
960
 
681
961
  /**
682
962
  * Synchronously cleans up active network sockets, timers, and lifecycle observers.
963
+ * Note: OkHttp Dispatcher uses ThreadPoolExecutor(corePoolSize=0, keepAliveTime=60s).
964
+ * Idle worker threads automatically terminate after 60s, allowing full GC collection.
683
965
  */
684
966
  override fun dispose() {
685
967
  if (!isDisposed.compareAndSet(false, true)) {
@@ -711,6 +993,12 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
711
993
 
712
994
  clearActiveRequestAndReportEnd()
713
995
 
996
+ synchronized(this) {
997
+ client?.dispatcher?.executorService?.shutdown()
998
+ client?.connectionPool?.evictAll()
999
+ client = null
1000
+ }
1001
+
714
1002
  sseDispatcher?.removeCallbacksAndMessages(null)
715
1003
  sseDispatcherThread?.quitSafely()
716
1004
  sseDispatcherThread = null