react-native-nitro-sse 3.0.0-beta.2 → 3.1.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 (50) hide show
  1. package/NitroSse.podspec +0 -1
  2. package/README.md +44 -24
  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 +464 -130
  6. package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +420 -88
  7. package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +23 -0
  8. package/android/src/main/java/com/margelo/nitro/nitrosse/SseNetworkMonitor.kt +29 -2
  9. package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +9 -0
  10. package/ios/NitroSse.swift +353 -64
  11. package/ios/SseConfig+CopyWith.swift +35 -19
  12. package/ios/SseConnectionHandler.swift +647 -97
  13. package/ios/SseEventBuffer.swift +19 -1
  14. package/ios/SseReconnectStrategy.swift +26 -7
  15. package/lib/module/MockSseEngine.js +72 -8
  16. package/lib/module/NitroSseClient.js +79 -8
  17. package/lib/module/createNitroSse.js +24 -0
  18. package/lib/module/index.js +1 -22
  19. package/lib/module/useNitroSse.js +22 -5
  20. package/lib/typescript/src/MockSseEngine.d.ts +16 -0
  21. package/lib/typescript/src/NitroSse.nitro.d.ts +2 -2
  22. package/lib/typescript/src/NitroSseClient.d.ts +7 -3
  23. package/lib/typescript/src/SseInterface.d.ts +60 -10
  24. package/lib/typescript/src/createNitroSse.d.ts +9 -0
  25. package/lib/typescript/src/index.d.ts +1 -8
  26. package/lib/typescript/src/useNitroSse.d.ts +2 -2
  27. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +12 -8
  28. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.hpp +1 -1
  29. package/nitrogen/generated/android/c++/JSseConfig.hpp +1 -18
  30. package/nitrogen/generated/android/c++/JSseDisconnectReason.hpp +67 -0
  31. package/nitrogen/generated/android/c++/JSseStats.hpp +87 -1
  32. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HybridNitroSseSpec.kt +4 -3
  33. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +4 -13
  34. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseDisconnectReason.kt +26 -0
  35. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseStats.kt +108 -3
  36. package/nitrogen/generated/android/nitrosseOnLoad.cpp +2 -2
  37. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.cpp +8 -8
  38. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +114 -96
  39. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +3 -0
  40. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +7 -4
  41. package/nitrogen/generated/ios/swift/HybridNitroSseSpec.swift +1 -1
  42. package/nitrogen/generated/ios/swift/HybridNitroSseSpec_cxx.swift +34 -1
  43. package/nitrogen/generated/ios/swift/SseConfig.swift +1 -48
  44. package/nitrogen/generated/ios/swift/SseDisconnectReason.swift +52 -0
  45. package/nitrogen/generated/ios/swift/SseStats.swift +217 -2
  46. package/nitrogen/generated/shared/c++/HybridNitroSseSpec.hpp +3 -1
  47. package/nitrogen/generated/shared/c++/SseConfig.hpp +2 -8
  48. package/nitrogen/generated/shared/c++/SseDisconnectReason.hpp +88 -0
  49. package/nitrogen/generated/shared/c++/SseStats.hpp +88 -2
  50. package/package.json +2 -2
@@ -8,8 +8,9 @@ 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
+ import com.margelo.nitro.core.Promise
13
14
  import java.util.concurrent.TimeUnit
14
15
  import java.util.concurrent.atomic.AtomicBoolean
15
16
  import java.util.concurrent.atomic.AtomicLong
@@ -32,12 +33,23 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
32
33
  internal constructor(dispatcher: SseDispatcher) : this() {
33
34
  this.sseDispatcher = dispatcher
34
35
  }
36
+ @Volatile
35
37
  private var client: OkHttpClient? = null
36
- private var eventSource: EventSource? = null
38
+ private var eventSource: SseEventSource? = null
37
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
38
43
  private var requestId: String? = null
39
44
 
40
45
  private val isRunning = AtomicBoolean(false)
46
+ /**
47
+ * Indicates whether the underlying React Native JS Dispatcher/CallInvoker has been destroyed
48
+ * (e.g. during Fast Refresh, bundle reload, or host teardown).
49
+ * Marked @Volatile to guarantee cross-thread memory visibility between sseDispatcher background
50
+ * thread, network callbacks, and JS/Main threads without stale CPU cache reads.
51
+ */
52
+ @Volatile
41
53
  private var isDispatcherDestroyed = false
42
54
  private var wasRunningBeforePaused = false
43
55
  private val consecutiveAuthErrors = AtomicInteger(0)
@@ -45,16 +57,46 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
45
57
  private var sseDispatcherThread: android.os.HandlerThread? = null
46
58
  internal var sseDispatcher: SseDispatcher? = null
47
59
 
60
+ // Transport Metrics
61
+ private var rawBytesReceived: Double = 0.0
62
+ private var decompressedBytesReceived: Double? = null
63
+ private var sessionRawBytesOffset: Double = 0.0
48
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
+
49
92
  private val connectionAttemptVersion = AtomicInteger(0)
50
93
  private var lastProcessedId: String? = null
51
94
  private var currentState = java.util.concurrent.atomic.AtomicReference(SseState.IDLE)
52
- private val totalReconnectCount = AtomicInteger(0)
53
- private var lastErrorTime: Double? = null
54
- private var lastErrorCode: String? = null
55
95
  private var wasRunningBeforeNetworkLoss = false
56
- private var lastNetworkCapabilities: NetworkCapabilities? = null
57
96
  private var interceptorTimeoutRunnable: Runnable? = null
97
+ private val isDisposed = AtomicBoolean(false)
98
+ /// Dynamic request interceptor decoupled from SseConfig (v3.0)
99
+ private var requestInterceptor: (() -> Promise<Promise<Map<String, String>>>)? = null
58
100
 
59
101
  private lateinit var eventBuffer: SseEventBuffer
60
102
  private val reconnectStrategy = SseReconnectStrategy()
@@ -68,9 +110,22 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
68
110
  private const val DEFAULT_MAX_AUTH_RETRIES = 3
69
111
  }
70
112
 
71
- override fun setup(config: SseConfig, onEvent: (events: Array<SseEvent>) -> Unit) {
113
+ override fun setup(
114
+ config: SseConfig,
115
+ onEvent: (events: Array<SseEvent>) -> Unit,
116
+ onBeforeRequest: (() -> Promise<Promise<Map<String, String>>>)?
117
+ ) {
72
118
  synchronized(this) {
73
119
  this.config = config
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
+ }
74
129
 
75
130
  if (sseDispatcher == null) {
76
131
  sseDispatcherThread = android.os.HandlerThread("NitroSseThread").apply { start() }
@@ -79,6 +134,7 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
79
134
 
80
135
  if (!::eventBuffer.isInitialized) {
81
136
  eventBuffer = SseEventBuffer(onEvent, sseDispatcher)
137
+ eventBuffer.onFlushError = { e -> handleRuntimeOrFlushError(e) }
82
138
  } else {
83
139
  eventBuffer.setCallback(onEvent)
84
140
  }
@@ -99,17 +155,7 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
99
155
  // Enables transparent socket-level retry on route failures (multiple IP fallback, transient resets)
100
156
  // before bubbling up to full SSE stream reconnect.
101
157
  .retryOnConnectionFailure(true)
102
- .addNetworkInterceptor(HeartbeatNetworkInterceptor { heartbeatRid, comment ->
103
- sseDispatcher?.post {
104
- // Guard keep-alive signals by active request ID to ignore residual bytes from closed/closing sockets
105
- val currentRid = synchronized(this@NitroSse) { requestId }
106
- if (heartbeatRid == null || heartbeatRid == currentRid) {
107
- val commentBytes = comment.toByteArray(Charsets.UTF_8).size.toLong()
108
- totalBytesReceived.addAndGet(commentBytes)
109
- eventBuffer.push(SseEvent(SseEventType.HEARTBEAT, null, null, null, null, comment, null, null, null))
110
- }
111
- }
112
- })
158
+ .addNetworkInterceptor(InspectorNetworkInterceptor())
113
159
  this.client = builder.build()
114
160
  } else {
115
161
  this.client = this.client!!.newBuilder()
@@ -129,32 +175,38 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
129
175
  )
130
176
  lifecycleManager?.startObserving()
131
177
  }
132
- }
133
-
134
- if (config.monitorNetwork != false) {
135
- sseDispatcher?.post {
136
- startNetworkMonitoring()
137
- }
138
- } else {
139
- sseDispatcher?.post {
140
- networkMonitor?.stop()
141
- networkMonitor = null
178
+ if (config.monitorNetwork != false) {
179
+ sseDispatcher?.post {
180
+ startNetworkMonitoring()
181
+ }
182
+ } else {
183
+ sseDispatcher?.post {
184
+ networkMonitor?.stop()
185
+ networkMonitor = null
186
+ }
142
187
  }
143
188
  }
144
189
  }
145
190
 
191
+ /**
192
+ * Convenience overload for setup without onBeforeRequest.
193
+ */
194
+ fun setup(config: SseConfig, onEvent: (events: Array<SseEvent>) -> Unit) {
195
+ setup(config, onEvent, null)
196
+ }
197
+
146
198
  private fun startNetworkMonitoring() {
147
199
  val context = NitroModules.applicationContext ?: return
148
200
  if (networkMonitor == null) {
149
- networkMonitor = SseNetworkMonitor(context, sseDispatcher) { isAvailable, capabilities ->
150
- handleNetworkChange(isAvailable, capabilities)
201
+ networkMonitor = SseNetworkMonitor(context, sseDispatcher) { isAvailable, interfaceChanged, capabilities ->
202
+ handleNetworkChange(isAvailable, interfaceChanged, capabilities)
151
203
  }
152
204
  }
153
205
  networkMonitor?.start()
154
206
  }
155
207
 
156
- private fun handleNetworkChange(isAvailable: Boolean, capabilities: NetworkCapabilities?) {
157
- Log.d(TAG, "Network change: available=$isAvailable")
208
+ private fun handleNetworkChange(isAvailable: Boolean, interfaceChanged: Boolean, capabilities: NetworkCapabilities?) {
209
+ Log.d(TAG, "Network change: available=$isAvailable, interfaceChanged=$interfaceChanged")
158
210
  if (isAvailable && capabilities != null) {
159
211
  if (wasRunningBeforeNetworkLoss) {
160
212
  Log.d(TAG, "Network restored. Resuming stream.")
@@ -164,19 +216,10 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
164
216
  } else {
165
217
  start()
166
218
  }
167
- } else if (isRunning.get() && lastNetworkCapabilities != null) {
168
- val isWifi = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
169
- val isCellular = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
170
-
171
- val lastWifi = lastNetworkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ?: false
172
- val lastCellular = lastNetworkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ?: false
173
-
174
- if ((isWifi && !lastWifi) || (isCellular && !lastCellular)) {
175
- Log.d(TAG, "Network interface changed. Restarting stream.")
176
- restart()
177
- }
219
+ } else if (isRunning.get() && interfaceChanged) {
220
+ Log.d(TAG, "Network interface changed. Restarting stream.")
221
+ restart()
178
222
  }
179
- lastNetworkCapabilities = capabilities
180
223
  } else if (!isAvailable) {
181
224
  if (isRunning.get()) {
182
225
  Log.d(TAG, "Network lost. Hibernating.")
@@ -186,7 +229,6 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
186
229
  connectionAttemptVersion.incrementAndGet()
187
230
  performInternalCleanup()
188
231
  }
189
- lastNetworkCapabilities = null
190
232
  }
191
233
  }
192
234
 
@@ -230,11 +272,37 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
230
272
 
231
273
  override fun getStats(): SseStats {
232
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
+
233
280
  return SseStats(
234
- totalBytesReceived.get().toDouble(),
235
- totalReconnectCount.get().toDouble(),
236
- lastErrorTime,
237
- 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
238
306
  )
239
307
  }
240
308
  }
@@ -293,7 +361,7 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
293
361
 
294
362
  val currentConfig = synchronized(this) { config } ?: return
295
363
  // Asynchronously await JS onBeforeRequest interceptor before creating EventSource.
296
- val interceptor = currentConfig.onBeforeRequest
364
+ val interceptor = synchronized(this) { requestInterceptor }
297
365
 
298
366
  if (interceptor != null) {
299
367
  val interceptorCompleted = AtomicBoolean(false)
@@ -316,32 +384,44 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
316
384
  sseDispatcher?.postDelayed(timeoutRunnable, timeoutMs)
317
385
 
318
386
  try {
319
- interceptor.invoke().then { promise2 ->
320
- 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 ->
321
391
  sseDispatcher?.post {
322
392
  if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
323
393
  if (interceptorCompleted.compareAndSet(false, true)) {
324
394
  interceptorTimeoutRunnable?.let { sseDispatcher?.removeCallbacks(it) }
325
395
  interceptorTimeoutRunnable = null
326
- synchronized(this) {
327
- val mergedHeaders = (config?.headers ?: emptyMap()).toMutableMap()
396
+ val connectionConfig = synchronized(this) {
397
+ val base = config ?: return@post
398
+ val mergedHeaders = (base.headers ?: emptyMap()).toMutableMap()
328
399
  newHeaders.forEach { (k, v) -> mergedHeaders[k] = v }
329
- config = config?.copy(headers = mergedHeaders)
400
+ base.copy(headers = mergedHeaders)
330
401
  }
331
- executeConnection(version)
402
+ executeConnection(version, connectionConfig)
332
403
  }
333
404
  }
334
- }.catch { error ->
405
+ }?.catch { error ->
335
406
  safeHandleError(error)
336
407
  }
337
- }.catch { error ->
408
+ }?.catch { error ->
338
409
  safeHandleError(error)
339
410
  }
340
411
  } catch (e: Throwable) {
341
412
  safeHandleError(e)
342
413
  }
343
414
  } else {
344
- executeConnection(version)
415
+ executeConnection(version, null)
416
+ }
417
+ }
418
+
419
+ private fun handleRuntimeOrFlushError(t: Throwable?) {
420
+ val isDispatcherDestroyedMsg = t?.message?.contains("Dispatcher has already been destroyed", ignoreCase = true) == true
421
+ if (isDispatcherDestroyedMsg) {
422
+ Log.w(TAG, "JS Dispatcher destroyed during event flush. Disposing NitroSse instance.")
423
+ this.isDispatcherDestroyed = true
424
+ dispose()
345
425
  }
346
426
  }
347
427
 
@@ -353,37 +433,58 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
353
433
 
354
434
  val isDispatcherDestroyedMsg = t?.message?.contains("Dispatcher has already been destroyed", ignoreCase = true) == true
355
435
  if (isDispatcherDestroyedMsg) {
356
- Log.w(TAG, "JS Dispatcher destroyed. Stopping SSE stream.")
357
- this@NitroSse.isDispatcherDestroyed = true
358
- stopInternal()
436
+ Log.w(TAG, "JS Dispatcher destroyed during interceptor error. Disposing NitroSse instance.")
437
+ this.isDispatcherDestroyed = true
438
+ dispose()
439
+ return@post
440
+ }
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)
359
446
  return@post
360
447
  }
361
448
 
362
449
  eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "Interceptor Error: ${t?.message}", -1.0, null, null))
363
-
364
450
  scheduleReconnect(true, version)
365
451
  }
366
452
  }
367
453
 
368
- private fun executeConnection(version: Int) {
454
+ private fun executeConnection(version: Int, connectionConfig: SseConfig? = null) {
369
455
  val currentConfig: SseConfig
370
456
  val currentLastId: String?
371
457
  val oldRequestId: String?
372
458
  val newRequestId = UUID.randomUUID().toString()
459
+ val safeClient: OkHttpClient
373
460
 
374
461
  synchronized(this) {
375
462
  if (!isRunning.get() || config == null || version != connectionAttemptVersion.get()) return
376
- currentConfig = config!!
463
+ currentConfig = connectionConfig ?: config!!
377
464
  currentLastId = lastProcessedId
465
+ safeClient = client ?: return
378
466
 
379
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
+ }
380
474
  requestId = newRequestId
381
475
 
382
476
  eventSource?.cancel()
383
477
  eventSource = null
478
+
479
+ connectionAttempts += 1.0
480
+ connectionAttemptStartTime = System.currentTimeMillis().toDouble()
481
+ timeToFirstByteMs = null
384
482
  }
385
483
 
386
- oldRequestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
484
+ oldRequestId?.let {
485
+ NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
486
+ SseNetworkMetricsTracker.clear(it)
487
+ }
387
488
 
388
489
  try {
389
490
  // Set SSE headers explicitly for Network Inspector visibility and encoding control.
@@ -392,9 +493,9 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
392
493
  .header("Accept", "text/event-stream")
393
494
  .header("Cache-Control", "no-cache")
394
495
 
395
- // 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
396
497
  currentConfig.headers?.forEach { (k, v) ->
397
- if (!k.equals("Last-Event-ID", ignoreCase = true)) {
498
+ if (!k.equals("Last-Event-ID", ignoreCase = true) && !k.equals("Accept-Encoding", ignoreCase = true)) {
398
499
  requestBuilder.header(k, v)
399
500
  }
400
501
  }
@@ -403,13 +504,12 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
403
504
  if (it.isNotEmpty()) requestBuilder.header("Last-Event-ID", it)
404
505
  }
405
506
 
406
- // Explicitly set identity encoding after custom headers to prevent OkHttp from requesting gzip.
407
- // If gzipped, HeartbeatNetworkInterceptor intercepts raw compressed bytes before decompression,
408
- // corrupting byte-level comment scanning for keep-alive events (':').
409
- requestBuilder.header("Accept-Encoding", "identity")
410
-
411
507
  if (currentConfig.method == HttpMethod.POST) {
412
- 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)
413
513
  requestBuilder.post(body)
414
514
  }
415
515
 
@@ -417,9 +517,18 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
417
517
  val request = requestBuilder.build()
418
518
  NetworkInspector.reportRequestStart(newRequestId, request)
419
519
 
420
- val newEventSource = connectionHandler.createEventSource(client!!, request, newRequestId)
421
- 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
+ }
422
529
  } catch (e: Exception) {
530
+ // Standard Java Exception catch: handles IllegalArgumentException (URL/headers), NullPointerException,
531
+ // and IllegalStateException without catching/suppressing fatal JVM errors (e.g. OutOfMemoryError, VirtualMachineError).
423
532
  Log.e(TAG, "Failed to create SSE connection request: ${e.message}", e)
424
533
  failAndStop("Invalid connection request: ${e.message}", -1.0)
425
534
  }
@@ -430,33 +539,144 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
430
539
  if (requestId != this@NitroSse.requestId) return@post
431
540
  consecutiveAuthErrors.set(0)
432
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
+ }
433
549
  updateState(SseState.OPEN)
434
550
  eventBuffer.push(SseEvent(SseEventType.OPEN, null, null, null, null, null, response.code.toDouble(), null, null))
435
551
  }
436
552
  }
437
553
 
438
- 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) {
439
580
  sseDispatcher?.post {
440
581
  if (requestId != this@NitroSse.requestId) return@post
441
- val encodedDataSize = data.toByteArray(Charsets.UTF_8).size.toLong()
442
- val metadataSize = (id?.toByteArray(Charsets.UTF_8)?.size?.toLong() ?: 0L) +
443
- (type?.toByteArray(Charsets.UTF_8)?.size?.toLong() ?: 0L)
444
- totalBytesReceived.addAndGet(encodedDataSize + metadataSize)
445
-
446
- val currentConfig: SseConfig?
447
582
  synchronized(this@NitroSse) {
448
- // WHATWG SSE Spec: If the server sends an empty id (e.g. 'id:\n'), reset lastProcessedId to null.
449
- if (id != null) {
450
- 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
451
620
  }
452
- currentConfig = this@NitroSse.config
453
621
  }
454
- 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
455
627
  eventBuffer.push(SseEvent(SseEventType.MESSAGE, data, parsedData, id, type, null, 200.0, null, null))
456
628
  }
457
629
  }
458
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
+
459
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) {
460
680
  sseDispatcher?.post {
461
681
  // Note on Stale Callback Protection:
462
682
  // Android uses a unique UUID `requestId` per connection attempt rather than an integer `attemptVersion`.
@@ -465,30 +685,75 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
465
685
  // socket are safely and strictly rejected by `if (requestId != this@NitroSse.requestId) return@post`.
466
686
  if (requestId != this@NitroSse.requestId || !isRunning.get()) return@post
467
687
  val statusCode = response?.code ?: -1
468
-
469
- 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
+
470
693
  synchronized(this@NitroSse) {
694
+ connectedAt = null
695
+ if (statusCode != -1) {
696
+ lastStatusCode = statusCode.toDouble()
697
+ }
471
698
  lastErrorTime = System.currentTimeMillis().toDouble()
472
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
+ }
473
710
  }
474
711
 
475
712
  val currentRequestId = synchronized(this@NitroSse) {
476
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
+ }
477
720
  this@NitroSse.requestId = null
478
721
  id
479
722
  }
480
- 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
+ }
481
746
 
482
747
  val maxRetries = synchronized(this@NitroSse) { config?.maxAuthRetries?.toInt() ?: DEFAULT_MAX_AUTH_RETRIES }
483
748
  // Handle 401/403 with async token refresh up to maxAuthRetries.
484
749
  if (statusCode == 401 || statusCode == 403) {
485
- val currentConfig = synchronized(this@NitroSse) { config }
486
- if (currentConfig?.onBeforeRequest == null) {
750
+ val hasInterceptor = synchronized(this@NitroSse) { requestInterceptor != null }
751
+ if (!hasInterceptor) {
487
752
  failAndStop("Auth Error ($statusCode) - No interceptor provided. Stopping.", statusCode.toDouble())
488
753
  return@post
489
754
  }
490
755
  val retries = consecutiveAuthErrors.incrementAndGet()
491
- if (retries >= maxRetries) {
756
+ if (retries > maxRetries) {
492
757
  failAndStop("Auth Error ($statusCode) - Retry limit reached ($maxRetries). Stopping.", statusCode.toDouble())
493
758
  return@post
494
759
  }
@@ -499,26 +764,25 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
499
764
 
500
765
  val isFatal = (statusCode in 400..499 && statusCode != 401 && statusCode != 403 && statusCode != 408 && statusCode != 429)
501
766
  if (isFatal) {
502
- 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())
503
774
  return@post
504
775
  }
505
776
 
506
777
  // Schedule non-blocking Retry-After delay on dispatcher.
507
778
  val retryAfterMillis = SseReconnectStrategy.extractRetryAfterMillis(response)
508
779
  if ((statusCode == 429 || statusCode == 503) && retryAfterMillis != null) {
509
- if (reconnectStrategy.hasReachedMaxAttempts()) {
510
- val maxAttempts = reconnectStrategy.currentReconnectAttempts
511
- Log.d(TAG, "Max reconnection attempts reached ($maxAttempts). Stopping.")
512
- failAndStop("Max reconnection attempts reached ($maxAttempts).")
513
- return@post
514
- }
515
- reconnectStrategy.recordAttempt()
780
+ val maxInterval = synchronized(this@NitroSse) { (config?.maxRetryIntervalMs ?: 30000.0).toLong() }
781
+ val boundedRetryAfter = retryAfterMillis.coerceIn(0L, maxInterval)
516
782
  val jitter = (500 + Random.nextInt(1001)).toLong()
517
- val totalDelay = retryAfterMillis + jitter
518
- eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "Retry-After received: ${totalDelay/1000}s", statusCode.toDouble(), totalDelay.toDouble(), null))
519
- val newAttemptVersion = connectionAttemptVersion.incrementAndGet()
520
- updateState(SseState.RECONNECTING)
521
- 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)
522
786
  return@post
523
787
  }
524
788
 
@@ -528,18 +792,20 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
528
792
  return@post
529
793
  }
530
794
 
531
- if (statusCode == 204) {
532
- failAndStop("No Content (204). Stopping.", 204.0)
533
- return@post
534
- }
535
-
536
- 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.
537
798
  if (isTimeout) {
538
799
  updateState(SseState.STALE)
539
800
  }
540
801
 
802
+ val defaultErrorMsg = when {
803
+ statusCode >= 500 && !errorBody.isNullOrBlank() -> "Server Error ($statusCode): ${errorBody.trim()}"
804
+ else -> t?.message ?: "Link lost ($statusCode)"
805
+ }
806
+
541
807
  // Teardown and reconnect on stream or socket failure.
542
- 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))
543
809
  scheduleReconnect(true, connectionAttemptVersion.get())
544
810
  }
545
811
  }
@@ -547,6 +813,9 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
547
813
  override fun connectionDidClose(requestId: String) {
548
814
  sseDispatcher?.post {
549
815
  if (requestId != this@NitroSse.requestId || !isRunning.get()) return@post
816
+ synchronized(this@NitroSse) {
817
+ connectedAt = null
818
+ }
550
819
  clearActiveRequestAndReportEnd()
551
820
  scheduleReconnect(false, connectionAttemptVersion.get())
552
821
  }
@@ -558,7 +827,7 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
558
827
  stopInternal()
559
828
  }
560
829
 
561
- private fun scheduleReconnect(isError: Boolean, attemptVersion: Int) {
830
+ private fun scheduleReconnect(isError: Boolean, attemptVersion: Int, fixedDelay: Long? = null) {
562
831
  if (!isRunning.get() || attemptVersion != connectionAttemptVersion.get()) return
563
832
  if (reconnectStrategy.hasReachedMaxAttempts()) {
564
833
  val maxAttempts = reconnectStrategy.currentReconnectAttempts
@@ -566,9 +835,17 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
566
835
  failAndStop("Max reconnection attempts reached ($maxAttempts).")
567
836
  return
568
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
+ }
569
847
  // Increment attempt version before scheduling to invalidate pending tasks from previous cycles
570
848
  val newAttemptVersion = connectionAttemptVersion.incrementAndGet()
571
- val safeReconnectDelay = reconnectStrategy.nextDelay(isError)
572
849
  updateState(SseState.RECONNECTING)
573
850
  sseDispatcher?.postDelayed({
574
851
  // Double check version and running state at trigger time to discard stale delayed callbacks
@@ -579,6 +856,9 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
579
856
  }
580
857
 
581
858
  private fun stopInternal() {
859
+ synchronized(this) {
860
+ connectedAt = null
861
+ }
582
862
  isRunning.set(false)
583
863
  connectionAttemptVersion.incrementAndGet()
584
864
  performInternalCleanup()
@@ -592,15 +872,20 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
592
872
 
593
873
  override fun restart() {
594
874
  synchronized(this) { config } ?: return
595
- stopInternal()
596
- isRunning.set(true)
597
- val version = connectionAttemptVersion.incrementAndGet()
598
- updateState(SseState.RECONNECTING)
599
- sseDispatcher?.post {
875
+ val task = {
876
+ stopInternal()
877
+ isRunning.set(true)
878
+ val version = connectionAttemptVersion.incrementAndGet()
879
+ updateState(SseState.RECONNECTING)
600
880
  reconnectStrategy.reset()
601
881
  requestId = null
602
882
  performConnection(version)
603
883
  }
884
+ if (sseDispatcher?.isCurrentDispatcher() == true) {
885
+ task()
886
+ } else {
887
+ sseDispatcher?.post(task)
888
+ }
604
889
  }
605
890
 
606
891
  override fun isConnected(): Boolean {
@@ -608,29 +893,59 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
608
893
  }
609
894
 
610
895
  override fun stop() {
896
+ synchronized(this) {
897
+ if (isRunning.get()) {
898
+ disconnectReason = SseDisconnectReason.USER_STOP
899
+ }
900
+ connectedAt = null
901
+ }
611
902
  isRunning.set(false)
612
- wasRunningBeforeNetworkLoss = false
613
- wasRunningBeforePaused = false
614
- if (currentState.get() != SseState.FAILED) {
615
- updateState(SseState.CLOSED)
903
+ val stopVersion = connectionAttemptVersion.incrementAndGet()
904
+ clearActiveRequestAndReportEnd()
905
+
906
+ val task = {
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()
916
+ }
616
917
  }
617
- connectionAttemptVersion.incrementAndGet()
618
- sseDispatcher?.post {
619
- performInternalCleanup()
918
+ if (sseDispatcher?.isCurrentDispatcher() == true) {
919
+ task()
920
+ } else {
921
+ sseDispatcher?.post(task)
620
922
  }
621
923
  }
622
924
 
623
925
  private fun clearActiveRequestAndReportEnd() {
624
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
+ }
625
934
  eventSource?.cancel()
626
935
  eventSource = null
627
- val id = requestId
628
936
  requestId = null
629
937
  id
630
938
  }
631
- currentRequestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
939
+ currentRequestId?.let {
940
+ NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
941
+ SseNetworkMetricsTracker.clear(it)
942
+ }
632
943
  }
633
944
 
945
+ /**
946
+ * Cleans up timeouts, active socket, and flushes any pending buffered events.
947
+ * Always invoked within `sseDispatcherThread` execution context (from lifecycle, network, or stop).
948
+ */
634
949
  private fun performInternalCleanup() {
635
950
  interceptorTimeoutRunnable?.let { sseDispatcher?.removeCallbacks(it) }
636
951
  interceptorTimeoutRunnable = null
@@ -645,13 +960,26 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
645
960
 
646
961
  /**
647
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.
648
965
  */
649
966
  override fun dispose() {
967
+ if (!isDisposed.compareAndSet(false, true)) {
968
+ return
969
+ }
650
970
  Log.d(TAG, "Disposing NitroSse instance and cleaning up resources...")
651
971
 
652
972
  isRunning.set(false)
653
973
  connectionAttemptVersion.incrementAndGet()
654
974
 
975
+ synchronized(this) {
976
+ requestInterceptor = null
977
+ config = null
978
+ }
979
+
980
+ interceptorTimeoutRunnable?.let { sseDispatcher?.removeCallbacks(it) }
981
+ interceptorTimeoutRunnable = null
982
+
655
983
  if (::eventBuffer.isInitialized) {
656
984
  eventBuffer.clearCallback()
657
985
  eventBuffer.clear()
@@ -665,6 +993,12 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
665
993
 
666
994
  clearActiveRequestAndReportEnd()
667
995
 
996
+ synchronized(this) {
997
+ client?.dispatcher?.executorService?.shutdown()
998
+ client?.connectionPool?.evictAll()
999
+ client = null
1000
+ }
1001
+
668
1002
  sseDispatcher?.removeCallbacksAndMessages(null)
669
1003
  sseDispatcherThread?.quitSafely()
670
1004
  sseDispatcherThread = null