react-native-nitro-sse 2.4.2 → 3.0.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 (58) hide show
  1. package/README.md +209 -95
  2. package/android/src/main/java/com/margelo/nitro/nitrosse/AndroidSseDispatcher.kt +5 -0
  3. package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +11 -18
  4. package/android/src/main/java/com/margelo/nitro/nitrosse/NetworkInspector.kt +79 -36
  5. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +164 -88
  6. package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +40 -15
  7. package/android/src/main/java/com/margelo/nitro/nitrosse/SseDispatcher.kt +1 -0
  8. package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +34 -25
  9. package/android/src/main/java/com/margelo/nitro/nitrosse/SseLifecycleManager.kt +8 -1
  10. package/android/src/main/java/com/margelo/nitro/nitrosse/SseNetworkMonitor.kt +7 -4
  11. package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +2 -4
  12. package/ios/NitroSse.swift +229 -191
  13. package/ios/SseConfig+CopyWith.swift +2 -1
  14. package/ios/SseConnectionHandler.swift +40 -29
  15. package/ios/SseDispatchQueueDispatcher.swift +15 -2
  16. package/ios/SseDispatcher.swift +7 -1
  17. package/ios/SseEventBuffer.swift +23 -7
  18. package/ios/SseLifecycleManager.swift +10 -1
  19. package/ios/SseNetworkMonitor.swift +5 -0
  20. package/ios/SseReconnectStrategy.swift +4 -3
  21. package/lib/module/MockSseEngine.js +12 -21
  22. package/lib/module/NitroSseClient.js +385 -12
  23. package/lib/module/NitroSseError.js +61 -0
  24. package/lib/module/SseDriver.js +33 -2
  25. package/lib/module/index.js +6 -3
  26. package/lib/module/useNitroSse.js +359 -0
  27. package/lib/typescript/src/MockSseEngine.d.ts +1 -1
  28. package/lib/typescript/src/NitroSse.nitro.d.ts +25 -2
  29. package/lib/typescript/src/NitroSseClient.d.ts +20 -2
  30. package/lib/typescript/src/NitroSseError.d.ts +38 -0
  31. package/lib/typescript/src/SseDriver.d.ts +10 -2
  32. package/lib/typescript/src/SseInterface.d.ts +23 -7
  33. package/lib/typescript/src/index.d.ts +4 -2
  34. package/lib/typescript/src/useNitroSse.d.ts +69 -0
  35. package/nitrogen/generated/android/c++/JSseConfig.hpp +5 -1
  36. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +9 -4
  37. package/nitrogen/generated/ios/swift/SseConfig.swift +19 -1
  38. package/nitrogen/generated/shared/c++/SseConfig.hpp +5 -1
  39. package/package.json +8 -7
  40. package/android/jacoco.gradle +0 -33
  41. package/lib/module/MockSseEngine.js.map +0 -1
  42. package/lib/module/NitroSse.nitro.js.map +0 -1
  43. package/lib/module/NitroSseClient.js.map +0 -1
  44. package/lib/module/SseDriver.js.map +0 -1
  45. package/lib/module/SseInterface.js.map +0 -1
  46. package/lib/module/index.js.map +0 -1
  47. package/lib/typescript/src/MockSseEngine.d.ts.map +0 -1
  48. package/lib/typescript/src/NitroSse.nitro.d.ts.map +0 -1
  49. package/lib/typescript/src/NitroSseClient.d.ts.map +0 -1
  50. package/lib/typescript/src/SseDriver.d.ts.map +0 -1
  51. package/lib/typescript/src/SseInterface.d.ts.map +0 -1
  52. package/lib/typescript/src/index.d.ts.map +0 -1
  53. package/src/MockSseEngine.ts +0 -254
  54. package/src/NitroSse.nitro.ts +0 -58
  55. package/src/NitroSseClient.ts +0 -154
  56. package/src/SseDriver.ts +0 -161
  57. package/src/SseInterface.ts +0 -274
  58. package/src/index.ts +0 -31
@@ -41,7 +41,6 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
41
41
  private var isDispatcherDestroyed = false
42
42
  private var wasRunningBeforePaused = false
43
43
  private val consecutiveAuthErrors = AtomicInteger(0)
44
- private val maxAuthRetries = 3
45
44
 
46
45
  private var sseDispatcherThread: android.os.HandlerThread? = null
47
46
  internal var sseDispatcher: SseDispatcher? = null
@@ -55,6 +54,7 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
55
54
  private var lastErrorCode: String? = null
56
55
  private var wasRunningBeforeNetworkLoss = false
57
56
  private var lastNetworkCapabilities: NetworkCapabilities? = null
57
+ private var interceptorTimeoutRunnable: Runnable? = null
58
58
 
59
59
  private lateinit var eventBuffer: SseEventBuffer
60
60
  private val reconnectStrategy = SseReconnectStrategy()
@@ -65,6 +65,7 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
65
65
 
66
66
  companion object {
67
67
  private const val TAG = "NitroSse"
68
+ private const val DEFAULT_MAX_AUTH_RETRIES = 3
68
69
  }
69
70
 
70
71
  override fun setup(config: SseConfig, onEvent: (events: Array<SseEvent>) -> Unit) {
@@ -77,12 +78,13 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
77
78
  }
78
79
 
79
80
  if (!::eventBuffer.isInitialized) {
80
- eventBuffer = SseEventBuffer(onEvent, sseDispatcher, mainDispatcher)
81
+ eventBuffer = SseEventBuffer(onEvent, sseDispatcher)
81
82
  } else {
82
83
  eventBuffer.setCallback(onEvent)
83
84
  }
84
85
  eventBuffer.configure(config.batchingIntervalMs ?: 0.0, config.maxBufferSize?.toInt() ?: 1000)
85
86
 
87
+ // Custom backoff guarantees cross-platform parity and lifecycle coordination.
86
88
  reconnectStrategy.configure(
87
89
  config.retryIntervalMs ?: 1000.0,
88
90
  config.maxRetryIntervalMs ?: 30000.0,
@@ -94,11 +96,18 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
94
96
  val builder = OkHttpClient.Builder()
95
97
  .connectTimeout((config.connectionTimeoutMs ?: 15000.0).toLong(), TimeUnit.MILLISECONDS)
96
98
  .readTimeout((config.readTimeoutMs ?: 300000.0).toLong(), TimeUnit.MILLISECONDS)
97
- .addNetworkInterceptor(HeartbeatNetworkInterceptor(totalBytesReceived) { heartbeatRid ->
98
- // Guard keep-alive signals by active request ID to ignore residual bytes from closed/closing sockets
99
- val currentRid = synchronized(this@NitroSse) { requestId }
100
- if (heartbeatRid == null || heartbeatRid == currentRid) {
101
- eventBuffer.push(SseEvent(SseEventType.HEARTBEAT, null, null, null, null, "keep-alive", null, null, null))
99
+ // Enables transparent socket-level retry on route failures (multiple IP fallback, transient resets)
100
+ // before bubbling up to full SSE stream reconnect.
101
+ .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
+ }
102
111
  }
103
112
  })
104
113
  this.client = builder.build()
@@ -106,6 +115,7 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
106
115
  this.client = this.client!!.newBuilder()
107
116
  .connectTimeout((config.connectionTimeoutMs ?: 15000.0).toLong(), TimeUnit.MILLISECONDS)
108
117
  .readTimeout((config.readTimeoutMs ?: 300000.0).toLong(), TimeUnit.MILLISECONDS)
118
+ .retryOnConnectionFailure(true)
109
119
  .build()
110
120
  }
111
121
 
@@ -199,9 +209,7 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
199
209
  updateState(SseState.PAUSED)
200
210
  isRunning.set(false)
201
211
  connectionAttemptVersion.incrementAndGet()
202
- sseDispatcher?.post {
203
- performInternalCleanup()
204
- }
212
+ performInternalCleanup()
205
213
  }
206
214
  }
207
215
 
@@ -214,7 +222,8 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
214
222
  override fun updateHeaders(headers: Map<String, String>) {
215
223
  synchronized(this) {
216
224
  this.config?.let {
217
- this.config = it.copy(headers = headers)
225
+ val merged = (it.headers ?: emptyMap()) + headers
226
+ this.config = it.copy(headers = merged)
218
227
  }
219
228
  }
220
229
  }
@@ -238,11 +247,33 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
238
247
  val oldState = currentState.getAndSet(newState)
239
248
  if (oldState != newState && ::eventBuffer.isInitialized) {
240
249
  eventBuffer.push(SseEvent(SseEventType.STATE, null, null, null, null, null, null, null, newState))
250
+ // State events represent immediate connection lifecycle transitions and must be flushed
251
+ // to JS immediately to prevent UI and React hook state desynchronization.
252
+ eventBuffer.flush()
241
253
  }
242
254
  }
243
255
 
244
256
  override fun start() {
245
- val currentConfig = synchronized(this) { config } ?: return
257
+ val currentConfig = synchronized(this) { config }
258
+ ?: throw IllegalStateException("NitroSse not configured. Call setup() first.")
259
+
260
+ if (isRunning.get()) {
261
+ // If client is waiting in backoff reconnect loop, start() acts as an immediate "Retry Now",
262
+ // cancelling pending backoff delay, resetting backoff counter, and attempting connection immediately.
263
+ if (currentState.get() == SseState.RECONNECTING) {
264
+ Log.d(TAG, "start() invoked while reconnecting. Resetting backoff and retrying immediately.")
265
+ consecutiveAuthErrors.set(0)
266
+ val version = connectionAttemptVersion.incrementAndGet()
267
+ updateState(SseState.CONNECTING)
268
+ sseDispatcher?.post {
269
+ reconnectStrategy.reset()
270
+ requestId = null
271
+ performConnection(version)
272
+ }
273
+ }
274
+ return
275
+ }
276
+
246
277
  if (!isRunning.compareAndSet(false, true)) return
247
278
 
248
279
  consecutiveAuthErrors.set(0)
@@ -261,18 +292,28 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
261
292
  if (!isRunning.get() || version != connectionAttemptVersion.get()) return
262
293
 
263
294
  val currentConfig = synchronized(this) { config } ?: return
295
+ // Asynchronously await JS onBeforeRequest interceptor before creating EventSource.
264
296
  val interceptor = currentConfig.onBeforeRequest
265
297
 
266
298
  if (interceptor != null) {
267
299
  val interceptorCompleted = AtomicBoolean(false)
268
300
  val timeoutMs = (currentConfig.connectionTimeoutMs ?: 15000.0).toLong()
269
301
 
270
- // Enforce timeout guard on JS onBeforeRequest promise to prevent connection hangs
271
- sseDispatcher?.postDelayed({
302
+ val safeHandleError: (Throwable) -> Unit = { error ->
272
303
  if (interceptorCompleted.compareAndSet(false, true)) {
273
- handleInterceptorError(Exception("onBeforeRequest timed out"), version)
304
+ handleInterceptorError(error, version)
274
305
  }
275
- }, timeoutMs)
306
+ }
307
+
308
+ // Proactively cancel any previous in-flight interceptor timeout runnable
309
+ interceptorTimeoutRunnable?.let { sseDispatcher?.removeCallbacks(it) }
310
+ val timeoutRunnable = Runnable {
311
+ safeHandleError(Exception("onBeforeRequest timed out"))
312
+ }
313
+ interceptorTimeoutRunnable = timeoutRunnable
314
+
315
+ // Enforce timeout guard on JS onBeforeRequest promise to prevent connection hangs
316
+ sseDispatcher?.postDelayed(timeoutRunnable, timeoutMs)
276
317
 
277
318
  try {
278
319
  interceptor.invoke().then { promise2 ->
@@ -280,6 +321,8 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
280
321
  sseDispatcher?.post {
281
322
  if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
282
323
  if (interceptorCompleted.compareAndSet(false, true)) {
324
+ interceptorTimeoutRunnable?.let { sseDispatcher?.removeCallbacks(it) }
325
+ interceptorTimeoutRunnable = null
283
326
  synchronized(this) {
284
327
  val mergedHeaders = (config?.headers ?: emptyMap()).toMutableMap()
285
328
  newHeaders.forEach { (k, v) -> mergedHeaders[k] = v }
@@ -289,13 +332,13 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
289
332
  }
290
333
  }
291
334
  }.catch { error ->
292
- if (interceptorCompleted.compareAndSet(false, true)) handleInterceptorError(error, version)
335
+ safeHandleError(error)
293
336
  }
294
337
  }.catch { error ->
295
- if (interceptorCompleted.compareAndSet(false, true)) handleInterceptorError(error, version)
338
+ safeHandleError(error)
296
339
  }
297
340
  } catch (e: Throwable) {
298
- if (interceptorCompleted.compareAndSet(false, true)) handleInterceptorError(e, version)
341
+ safeHandleError(e)
299
342
  }
300
343
  } else {
301
344
  executeConnection(version)
@@ -303,6 +346,8 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
303
346
  }
304
347
 
305
348
  private fun handleInterceptorError(t: Throwable?, version: Int) {
349
+ interceptorTimeoutRunnable?.let { sseDispatcher?.removeCallbacks(it) }
350
+ interceptorTimeoutRunnable = null
306
351
  sseDispatcher?.post {
307
352
  if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
308
353
 
@@ -340,38 +385,49 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
340
385
 
341
386
  oldRequestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
342
387
 
343
- val requestBuilder = Request.Builder()
344
- .url(currentConfig.url)
345
- .header("Accept", "text/event-stream")
346
- .header("Cache-Control", "no-cache")
347
-
348
- currentLastId?.let {
349
- if (it.isNotEmpty()) requestBuilder.header("Last-Event-ID", it)
350
- }
388
+ try {
389
+ // Set SSE headers explicitly for Network Inspector visibility and encoding control.
390
+ val requestBuilder = Request.Builder()
391
+ .url(currentConfig.url)
392
+ .header("Accept", "text/event-stream")
393
+ .header("Cache-Control", "no-cache")
394
+
395
+ // Populate config headers first, filtering out Last-Event-ID so dynamic reconnection ID takes precedence.
396
+ currentConfig.headers?.forEach { (k, v) ->
397
+ if (!k.equals("Last-Event-ID", ignoreCase = true)) {
398
+ requestBuilder.header(k, v)
399
+ }
400
+ }
351
401
 
352
- currentConfig.headers?.forEach { (k, v) -> requestBuilder.header(k, v) }
402
+ currentLastId?.let {
403
+ if (it.isNotEmpty()) requestBuilder.header("Last-Event-ID", it)
404
+ }
353
405
 
354
- // Explicitly set identity encoding after custom headers to prevent OkHttp from requesting gzip.
355
- // If gzipped, HeartbeatNetworkInterceptor intercepts raw compressed bytes before decompression,
356
- // corrupting byte-level comment scanning for keep-alive events (':').
357
- requestBuilder.header("Accept-Encoding", "identity")
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")
358
410
 
359
- if (currentConfig.method == HttpMethod.POST) {
360
- val body = currentConfig.body?.toRequestBody("application/json".toMediaType()) ?: "".toRequestBody()
361
- requestBuilder.post(body)
362
- }
411
+ if (currentConfig.method == HttpMethod.POST) {
412
+ val body = currentConfig.body?.toRequestBody("application/json".toMediaType()) ?: "".toRequestBody()
413
+ requestBuilder.post(body)
414
+ }
363
415
 
364
- requestBuilder.tag(String::class.java, newRequestId)
365
- val request = requestBuilder.build()
366
- NetworkInspector.reportRequestStart(newRequestId, request)
367
-
368
- val newEventSource = connectionHandler.createEventSource(client!!, request, newRequestId)
369
- synchronized(this) { eventSource = newEventSource }
416
+ requestBuilder.tag(String::class.java, newRequestId)
417
+ val request = requestBuilder.build()
418
+ NetworkInspector.reportRequestStart(newRequestId, request)
419
+
420
+ val newEventSource = connectionHandler.createEventSource(client!!, request, newRequestId)
421
+ synchronized(this) { eventSource = newEventSource }
422
+ } catch (e: Exception) {
423
+ Log.e(TAG, "Failed to create SSE connection request: ${e.message}", e)
424
+ failAndStop("Invalid connection request: ${e.message}", -1.0)
425
+ }
370
426
  }
371
427
 
372
- override fun connectionDidOpen(response: Response, reqId: String) {
428
+ override fun connectionDidOpen(response: Response, requestId: String) {
373
429
  sseDispatcher?.post {
374
- if (reqId != requestId) return@post
430
+ if (requestId != this@NitroSse.requestId) return@post
375
431
  consecutiveAuthErrors.set(0)
376
432
  reconnectStrategy.reset()
377
433
  updateState(SseState.OPEN)
@@ -379,13 +435,19 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
379
435
  }
380
436
  }
381
437
 
382
- override fun connectionDidReceiveMessage(id: String?, type: String?, data: String, reqId: String) {
438
+ override fun connectionDidReceiveMessage(id: String?, type: String?, data: String, requestId: String) {
383
439
  sseDispatcher?.post {
384
- if (reqId != requestId) return@post
440
+ 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
+
385
446
  val currentConfig: SseConfig?
386
447
  synchronized(this@NitroSse) {
387
- if (!id.isNullOrEmpty()) {
388
- this@NitroSse.lastProcessedId = id
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
389
451
  }
390
452
  currentConfig = this@NitroSse.config
391
453
  }
@@ -394,9 +456,14 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
394
456
  }
395
457
  }
396
458
 
397
- override fun connectionDidFail(t: Throwable?, response: Response?, reqId: String) {
459
+ override fun connectionDidFail(t: Throwable?, response: Response?, requestId: String) {
398
460
  sseDispatcher?.post {
399
- if (reqId != requestId || !isRunning.get()) return@post
461
+ // Note on Stale Callback Protection:
462
+ // Android uses a unique UUID `requestId` per connection attempt rather than an integer `attemptVersion`.
463
+ // When a connection fails, stops, or restarts, `this@NitroSse.requestId` is immediately cleared (set to null)
464
+ // or replaced with a new UUID. Thus, any delayed or asynchronous error/close callbacks from a canceled/previous
465
+ // socket are safely and strictly rejected by `if (requestId != this@NitroSse.requestId) return@post`.
466
+ if (requestId != this@NitroSse.requestId || !isRunning.get()) return@post
400
467
  val statusCode = response?.code ?: -1
401
468
 
402
469
  totalReconnectCount.incrementAndGet()
@@ -406,12 +473,14 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
406
473
  }
407
474
 
408
475
  val currentRequestId = synchronized(this@NitroSse) {
409
- val id = requestId
410
- requestId = null
476
+ val id = this@NitroSse.requestId
477
+ this@NitroSse.requestId = null
411
478
  id
412
479
  }
413
480
  currentRequestId?.let { NetworkInspector.reportRequestFailed(it, false) }
414
481
 
482
+ val maxRetries = synchronized(this@NitroSse) { config?.maxAuthRetries?.toInt() ?: DEFAULT_MAX_AUTH_RETRIES }
483
+ // Handle 401/403 with async token refresh up to maxAuthRetries.
415
484
  if (statusCode == 401 || statusCode == 403) {
416
485
  val currentConfig = synchronized(this@NitroSse) { config }
417
486
  if (currentConfig?.onBeforeRequest == null) {
@@ -419,20 +488,22 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
419
488
  return@post
420
489
  }
421
490
  val retries = consecutiveAuthErrors.incrementAndGet()
422
- if (retries >= maxAuthRetries) {
423
- failAndStop("Auth Error ($statusCode) - Retry limit reached ($maxAuthRetries). Stopping.", statusCode.toDouble())
491
+ if (retries >= maxRetries) {
492
+ failAndStop("Auth Error ($statusCode) - Retry limit reached ($maxRetries). Stopping.", statusCode.toDouble())
424
493
  return@post
425
494
  }
426
- eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "Auth Error ($statusCode) - Retry $retries/$maxAuthRetries. Refreshing token...", statusCode.toDouble(), null, null))
495
+ eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "Auth Error ($statusCode) - Retry $retries/$maxRetries. Refreshing token...", statusCode.toDouble(), null, null))
427
496
  scheduleReconnect(true, connectionAttemptVersion.get())
428
497
  return@post
429
498
  }
430
499
 
431
- if (statusCode == 400) {
500
+ val isFatal = (statusCode in 400..499 && statusCode != 401 && statusCode != 403 && statusCode != 408 && statusCode != 429)
501
+ if (isFatal) {
432
502
  failAndStop("Fatal Error ($statusCode). Stopping.", statusCode.toDouble())
433
503
  return@post
434
504
  }
435
505
 
506
+ // Schedule non-blocking Retry-After delay on dispatcher.
436
507
  val retryAfterMillis = SseReconnectStrategy.extractRetryAfterMillis(response)
437
508
  if ((statusCode == 429 || statusCode == 503) && retryAfterMillis != null) {
438
509
  if (reconnectStrategy.hasReachedMaxAttempts()) {
@@ -452,7 +523,8 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
452
523
  }
453
524
 
454
525
  if (statusCode == 429) {
455
- failAndStop("Rate Limited (429) without Retry-After. Stopping.", 429.0)
526
+ eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "Rate Limited (429). Retrying with backoff...", 429.0, null, null))
527
+ scheduleReconnect(true, connectionAttemptVersion.get())
456
528
  return@post
457
529
  }
458
530
 
@@ -466,20 +538,16 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
466
538
  updateState(SseState.STALE)
467
539
  }
468
540
 
541
+ // Teardown and reconnect on stream or socket failure.
469
542
  eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, t?.message ?: "Link lost ($statusCode)", if (statusCode != -1) statusCode.toDouble() else null, null, null))
470
543
  scheduleReconnect(true, connectionAttemptVersion.get())
471
544
  }
472
545
  }
473
546
 
474
- override fun connectionDidClose(reqId: String) {
547
+ override fun connectionDidClose(requestId: String) {
475
548
  sseDispatcher?.post {
476
- if (reqId != requestId || !isRunning.get()) return@post
477
- val currentRequestId = synchronized(this@NitroSse) {
478
- val id = requestId
479
- requestId = null
480
- id
481
- }
482
- currentRequestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
549
+ if (requestId != this@NitroSse.requestId || !isRunning.get()) return@post
550
+ clearActiveRequestAndReportEnd()
483
551
  scheduleReconnect(false, connectionAttemptVersion.get())
484
552
  }
485
553
  }
@@ -525,8 +593,14 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
525
593
  override fun restart() {
526
594
  synchronized(this) { config } ?: return
527
595
  stopInternal()
596
+ isRunning.set(true)
597
+ val version = connectionAttemptVersion.incrementAndGet()
528
598
  updateState(SseState.RECONNECTING)
529
- start()
599
+ sseDispatcher?.post {
600
+ reconnectStrategy.reset()
601
+ requestId = null
602
+ performConnection(version)
603
+ }
530
604
  }
531
605
 
532
606
  override fun isConnected(): Boolean {
@@ -546,13 +620,7 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
546
620
  }
547
621
  }
548
622
 
549
- private fun performInternalCleanup() {
550
- reconnectStrategy.reset()
551
- if (!isDispatcherDestroyed) {
552
- if (::eventBuffer.isInitialized) eventBuffer.flush()
553
- } else {
554
- if (::eventBuffer.isInitialized) eventBuffer.clear()
555
- }
623
+ private fun clearActiveRequestAndReportEnd() {
556
624
  val currentRequestId = synchronized(this) {
557
625
  eventSource?.cancel()
558
626
  eventSource = null
@@ -563,31 +631,39 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
563
631
  currentRequestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
564
632
  }
565
633
 
634
+ private fun performInternalCleanup() {
635
+ interceptorTimeoutRunnable?.let { sseDispatcher?.removeCallbacks(it) }
636
+ interceptorTimeoutRunnable = null
637
+ reconnectStrategy.reset()
638
+ if (!isDispatcherDestroyed) {
639
+ if (::eventBuffer.isInitialized) eventBuffer.flush()
640
+ } else {
641
+ if (::eventBuffer.isInitialized) eventBuffer.clear()
642
+ }
643
+ clearActiveRequestAndReportEnd()
644
+ }
645
+
646
+ /**
647
+ * Synchronously cleans up active network sockets, timers, and lifecycle observers.
648
+ */
566
649
  override fun dispose() {
567
650
  Log.d(TAG, "Disposing NitroSse instance and cleaning up resources...")
568
651
 
652
+ isRunning.set(false)
653
+ connectionAttemptVersion.incrementAndGet()
654
+
569
655
  if (::eventBuffer.isInitialized) {
570
656
  eventBuffer.clearCallback()
657
+ eventBuffer.clear()
571
658
  }
572
659
 
573
- isRunning.set(false)
574
- connectionAttemptVersion.incrementAndGet()
575
-
576
660
  networkMonitor?.stop()
661
+ networkMonitor = null
662
+
577
663
  lifecycleManager?.stopObserving()
664
+ lifecycleManager = null
578
665
 
579
- try {
580
- val currentRequestId = synchronized(this) {
581
- eventSource?.cancel()
582
- eventSource = null
583
- val id = requestId
584
- requestId = null
585
- id
586
- }
587
- currentRequestId?.let { NetworkInspector.reportRequestFailed(it, true) }
588
- } catch (e: Exception) {
589
- Log.e(TAG, "Error during synchronous dispose: ${e.message}")
590
- }
666
+ clearActiveRequestAndReportEnd()
591
667
 
592
668
  sseDispatcher?.removeCallbacksAndMessages(null)
593
669
  sseDispatcherThread?.quitSafely()
@@ -10,6 +10,7 @@ import okhttp3.sse.EventSourceListener
10
10
  import okhttp3.sse.EventSources
11
11
  import okio.Buffer
12
12
  import okio.ForwardingSource
13
+ import okio.GzipSource
13
14
  import okio.buffer
14
15
  import java.util.concurrent.atomic.AtomicLong
15
16
 
@@ -51,16 +52,15 @@ class SseConnectionHandler(private val delegate: SseConnectionDelegate) {
51
52
  }
52
53
 
53
54
  /**
54
- * Network interceptor for byte accounting and SSE heartbeat detection.
55
- *
56
- * Scans the raw response stream before OkHttp's EventSource parser runs, because OkHttp
57
- * discards SSE comment lines (`:`). Sniffing raw bytes at the network layer allows detecting
58
- * keep-alive signals without modifying the SSE parser interface.
55
+ * Network interceptor for byte accounting and SSE heartbeat/comment detection.
56
+ * Sniffs raw stream before EventSourceReader discards SSE comments (`:`).
59
57
  */
60
58
  internal class HeartbeatNetworkInterceptor(
61
- private val totalBytesReceived: AtomicLong,
62
- private val onHeartbeat: (requestId: String?) -> Unit
59
+ private val totalBytesReceived: AtomicLong? = null,
60
+ private val onHeartbeat: (requestId: String?, comment: String) -> Unit
63
61
  ) : Interceptor {
62
+ constructor(onHeartbeat: (requestId: String?, comment: String) -> Unit) : this(null, onHeartbeat)
63
+
64
64
  override fun intercept(chain: Interceptor.Chain): Response {
65
65
  val request = chain.request()
66
66
  val rid = request.tag(String::class.java)
@@ -73,27 +73,48 @@ internal class HeartbeatNetworkInterceptor(
73
73
 
74
74
  val responseBody = response.body
75
75
  if (responseBody != null) {
76
+ val isGzip = "gzip".equals(response.header("Content-Encoding"), ignoreCase = true)
77
+ val rawSource = if (isGzip) {
78
+ GzipSource(responseBody.source())
79
+ } else {
80
+ responseBody.source()
81
+ }
82
+
76
83
  val countingBody = object : ResponseBody() {
77
84
  override fun contentType() = responseBody.contentType()
78
- override fun contentLength() = responseBody.contentLength()
85
+ override fun contentLength() = if (isGzip) -1L else responseBody.contentLength()
79
86
 
80
87
  private val bufferedSource by lazy {
81
- (object : ForwardingSource(responseBody.source()) {
88
+ (object : ForwardingSource(rawSource) {
82
89
  private var isAtStartOfLine = true
90
+ private var isReadingComment = false
91
+ private val commentBuffer = java.io.ByteArrayOutputStream()
83
92
 
84
93
  override fun read(sink: Buffer, byteCount: Long): Long {
85
94
  val scratch = Buffer()
86
95
  val bytesRead = super.read(scratch, byteCount)
87
96
  if (bytesRead != -1L) {
88
- totalBytesReceived.addAndGet(bytesRead)
97
+ totalBytesReceived?.addAndGet(bytesRead)
89
98
  try {
90
- // Scan raw byte buffer for leading ':' character to trigger heartbeat events before OkHttp discards comments
91
99
  val bytes = scratch.snapshot().toByteArray()
92
100
  for (b in bytes) {
93
- if (isAtStartOfLine && b == ':'.code.toByte()) {
94
- onHeartbeat(rid)
101
+ val isNewline = (b == '\n'.code.toByte() || b == '\r'.code.toByte())
102
+ if (isReadingComment) {
103
+ if (isNewline) {
104
+ isReadingComment = false
105
+ val rawComment = commentBuffer.toString("UTF-8")
106
+ // WHATWG SSE Spec: Remove only a single leading space after ':' if present
107
+ val commentText = if (rawComment.startsWith(" ")) rawComment.substring(1) else rawComment
108
+ commentBuffer.reset()
109
+ onHeartbeat(rid, commentText)
110
+ } else {
111
+ commentBuffer.write(b.toInt())
112
+ }
113
+ } else if (isAtStartOfLine && b == ':'.code.toByte()) {
114
+ isReadingComment = true
115
+ commentBuffer.reset()
95
116
  }
96
- isAtStartOfLine = (b == '\n'.code.toByte() || b == '\r'.code.toByte())
117
+ isAtStartOfLine = isNewline
97
118
  }
98
119
  } catch (e: Exception) {
99
120
  // Swallow byte scanning errors to prevent stream reader failure if buffer inspection fails
@@ -107,7 +128,11 @@ internal class HeartbeatNetworkInterceptor(
107
128
 
108
129
  override fun source() = bufferedSource
109
130
  }
110
- return response.newBuilder().body(countingBody).build()
131
+ val responseBuilder = response.newBuilder().body(countingBody)
132
+ if (isGzip) {
133
+ responseBuilder.removeHeader("Content-Encoding").removeHeader("Content-Length")
134
+ }
135
+ return responseBuilder.build()
111
136
  }
112
137
  return response
113
138
  }
@@ -11,4 +11,5 @@ interface SseDispatcher {
11
11
  fun postDelayed(runnable: Runnable, delayMillis: Long)
12
12
  fun removeCallbacks(runnable: Runnable)
13
13
  fun removeCallbacksAndMessages(token: Any?)
14
+ fun isCurrentDispatcher(): Boolean
14
15
  }