react-native-nitro-sse 2.4.1 → 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 (59) 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 -38
  5. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +194 -100
  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 -28
  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 +6 -4
  12. package/ios/NitroSse.swift +244 -190
  13. package/ios/SseConfig+CopyWith.swift +2 -1
  14. package/ios/SseConnectionHandler.swift +59 -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 +8 -2
  20. package/ios/SseReconnectStrategy.swift +9 -3
  21. package/lib/module/MockSseEngine.js +203 -0
  22. package/lib/module/NitroSseClient.js +411 -214
  23. package/lib/module/NitroSseError.js +61 -0
  24. package/lib/module/SseDriver.js +156 -0
  25. package/lib/module/index.js +6 -3
  26. package/lib/module/useNitroSse.js +359 -0
  27. package/lib/typescript/src/MockSseEngine.d.ts +31 -0
  28. package/lib/typescript/src/NitroSse.nitro.d.ts +25 -2
  29. package/lib/typescript/src/NitroSseClient.d.ts +25 -7
  30. package/lib/typescript/src/NitroSseError.d.ts +38 -0
  31. package/lib/typescript/src/SseDriver.d.ts +80 -0
  32. package/lib/typescript/src/SseInterface.d.ts +25 -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 +7 -1
  36. package/nitrogen/generated/android/c++/JSseMockConfig.hpp +2 -0
  37. package/nitrogen/generated/android/c++/JSseMockEvent.hpp +9 -3
  38. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +9 -4
  39. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockEvent.kt +9 -4
  40. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +15 -15
  41. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +3 -3
  42. package/nitrogen/generated/ios/swift/SseConfig.swift +19 -1
  43. package/nitrogen/generated/ios/swift/SseMockEvent.swift +12 -1
  44. package/nitrogen/generated/shared/c++/SseConfig.hpp +5 -1
  45. package/nitrogen/generated/shared/c++/SseMockEvent.hpp +9 -2
  46. package/package.json +10 -11
  47. package/android/jacoco.gradle +0 -33
  48. package/lib/module/NitroSse.nitro.js.map +0 -1
  49. package/lib/module/NitroSseClient.js.map +0 -1
  50. package/lib/module/SseInterface.js.map +0 -1
  51. package/lib/module/index.js.map +0 -1
  52. package/lib/typescript/src/NitroSse.nitro.d.ts.map +0 -1
  53. package/lib/typescript/src/NitroSseClient.d.ts.map +0 -1
  54. package/lib/typescript/src/SseInterface.d.ts.map +0 -1
  55. package/lib/typescript/src/index.d.ts.map +0 -1
  56. package/src/NitroSse.nitro.ts +0 -58
  57. package/src/NitroSseClient.ts +0 -337
  58. package/src/SseInterface.ts +0 -272
  59. 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,14 +96,26 @@ 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) {
98
- 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
+ }
111
+ }
99
112
  })
100
113
  this.client = builder.build()
101
114
  } else {
102
115
  this.client = this.client!!.newBuilder()
103
116
  .connectTimeout((config.connectionTimeoutMs ?: 15000.0).toLong(), TimeUnit.MILLISECONDS)
104
117
  .readTimeout((config.readTimeoutMs ?: 300000.0).toLong(), TimeUnit.MILLISECONDS)
118
+ .retryOnConnectionFailure(true)
105
119
  .build()
106
120
  }
107
121
 
@@ -195,9 +209,7 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
195
209
  updateState(SseState.PAUSED)
196
210
  isRunning.set(false)
197
211
  connectionAttemptVersion.incrementAndGet()
198
- sseDispatcher?.post {
199
- performInternalCleanup()
200
- }
212
+ performInternalCleanup()
201
213
  }
202
214
  }
203
215
 
@@ -210,7 +222,8 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
210
222
  override fun updateHeaders(headers: Map<String, String>) {
211
223
  synchronized(this) {
212
224
  this.config?.let {
213
- this.config = it.copy(headers = headers)
225
+ val merged = (it.headers ?: emptyMap()) + headers
226
+ this.config = it.copy(headers = merged)
214
227
  }
215
228
  }
216
229
  }
@@ -234,11 +247,33 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
234
247
  val oldState = currentState.getAndSet(newState)
235
248
  if (oldState != newState && ::eventBuffer.isInitialized) {
236
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()
237
253
  }
238
254
  }
239
255
 
240
256
  override fun start() {
241
- 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
+
242
277
  if (!isRunning.compareAndSet(false, true)) return
243
278
 
244
279
  consecutiveAuthErrors.set(0)
@@ -257,18 +292,28 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
257
292
  if (!isRunning.get() || version != connectionAttemptVersion.get()) return
258
293
 
259
294
  val currentConfig = synchronized(this) { config } ?: return
295
+ // Asynchronously await JS onBeforeRequest interceptor before creating EventSource.
260
296
  val interceptor = currentConfig.onBeforeRequest
261
297
 
262
298
  if (interceptor != null) {
263
299
  val interceptorCompleted = AtomicBoolean(false)
264
300
  val timeoutMs = (currentConfig.connectionTimeoutMs ?: 15000.0).toLong()
265
301
 
266
- // Enforce timeout guard on JS onBeforeRequest promise to prevent connection hangs
267
- sseDispatcher?.postDelayed({
302
+ val safeHandleError: (Throwable) -> Unit = { error ->
268
303
  if (interceptorCompleted.compareAndSet(false, true)) {
269
- handleInterceptorError(Exception("onBeforeRequest timed out"), version)
304
+ handleInterceptorError(error, version)
270
305
  }
271
- }, 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)
272
317
 
273
318
  try {
274
319
  interceptor.invoke().then { promise2 ->
@@ -276,6 +321,8 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
276
321
  sseDispatcher?.post {
277
322
  if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
278
323
  if (interceptorCompleted.compareAndSet(false, true)) {
324
+ interceptorTimeoutRunnable?.let { sseDispatcher?.removeCallbacks(it) }
325
+ interceptorTimeoutRunnable = null
279
326
  synchronized(this) {
280
327
  val mergedHeaders = (config?.headers ?: emptyMap()).toMutableMap()
281
328
  newHeaders.forEach { (k, v) -> mergedHeaders[k] = v }
@@ -285,13 +332,13 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
285
332
  }
286
333
  }
287
334
  }.catch { error ->
288
- if (interceptorCompleted.compareAndSet(false, true)) handleInterceptorError(error, version)
335
+ safeHandleError(error)
289
336
  }
290
337
  }.catch { error ->
291
- if (interceptorCompleted.compareAndSet(false, true)) handleInterceptorError(error, version)
338
+ safeHandleError(error)
292
339
  }
293
340
  } catch (e: Throwable) {
294
- if (interceptorCompleted.compareAndSet(false, true)) handleInterceptorError(e, version)
341
+ safeHandleError(e)
295
342
  }
296
343
  } else {
297
344
  executeConnection(version)
@@ -299,6 +346,8 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
299
346
  }
300
347
 
301
348
  private fun handleInterceptorError(t: Throwable?, version: Int) {
349
+ interceptorTimeoutRunnable?.let { sseDispatcher?.removeCallbacks(it) }
350
+ interceptorTimeoutRunnable = null
302
351
  sseDispatcher?.post {
303
352
  if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
304
353
 
@@ -336,33 +385,49 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
336
385
 
337
386
  oldRequestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
338
387
 
339
- val requestBuilder = Request.Builder()
340
- .url(currentConfig.url)
341
- .header("Accept", "text/event-stream")
342
- .header("Cache-Control", "no-cache")
343
-
344
- currentLastId?.let {
345
- if (it.isNotEmpty()) requestBuilder.header("Last-Event-ID", it)
346
- }
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
+ }
347
401
 
348
- currentConfig.headers?.forEach { (k, v) -> requestBuilder.header(k, v) }
402
+ currentLastId?.let {
403
+ if (it.isNotEmpty()) requestBuilder.header("Last-Event-ID", it)
404
+ }
349
405
 
350
- if (currentConfig.method == HttpMethod.POST) {
351
- val body = currentConfig.body?.toRequestBody("application/json".toMediaType()) ?: "".toRequestBody()
352
- requestBuilder.post(body)
353
- }
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")
354
410
 
355
- requestBuilder.tag(String::class.java, newRequestId)
356
- val request = requestBuilder.build()
357
- NetworkInspector.reportRequestStart(newRequestId, request)
358
-
359
- val newEventSource = connectionHandler.createEventSource(client!!, request, newRequestId)
360
- synchronized(this) { eventSource = newEventSource }
411
+ if (currentConfig.method == HttpMethod.POST) {
412
+ val body = currentConfig.body?.toRequestBody("application/json".toMediaType()) ?: "".toRequestBody()
413
+ requestBuilder.post(body)
414
+ }
415
+
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
+ }
361
426
  }
362
427
 
363
- override fun connectionDidOpen(response: Response, reqId: String) {
428
+ override fun connectionDidOpen(response: Response, requestId: String) {
364
429
  sseDispatcher?.post {
365
- if (reqId != requestId) return@post
430
+ if (requestId != this@NitroSse.requestId) return@post
366
431
  consecutiveAuthErrors.set(0)
367
432
  reconnectStrategy.reset()
368
433
  updateState(SseState.OPEN)
@@ -370,13 +435,19 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
370
435
  }
371
436
  }
372
437
 
373
- override fun connectionDidReceiveMessage(id: String?, type: String?, data: String, reqId: String) {
438
+ override fun connectionDidReceiveMessage(id: String?, type: String?, data: String, requestId: String) {
374
439
  sseDispatcher?.post {
375
- 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
+
376
446
  val currentConfig: SseConfig?
377
447
  synchronized(this@NitroSse) {
378
- if (!id.isNullOrEmpty()) {
379
- 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
380
451
  }
381
452
  currentConfig = this@NitroSse.config
382
453
  }
@@ -385,9 +456,14 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
385
456
  }
386
457
  }
387
458
 
388
- override fun connectionDidFail(t: Throwable?, response: Response?, reqId: String) {
459
+ override fun connectionDidFail(t: Throwable?, response: Response?, requestId: String) {
389
460
  sseDispatcher?.post {
390
- 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
391
467
  val statusCode = response?.code ?: -1
392
468
 
393
469
  totalReconnectCount.incrementAndGet()
@@ -397,61 +473,63 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
397
473
  }
398
474
 
399
475
  val currentRequestId = synchronized(this@NitroSse) {
400
- val id = requestId
401
- requestId = null
476
+ val id = this@NitroSse.requestId
477
+ this@NitroSse.requestId = null
402
478
  id
403
479
  }
404
480
  currentRequestId?.let { NetworkInspector.reportRequestFailed(it, false) }
405
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.
406
484
  if (statusCode == 401 || statusCode == 403) {
407
485
  val currentConfig = synchronized(this@NitroSse) { config }
408
486
  if (currentConfig?.onBeforeRequest == null) {
409
- eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "Auth Error ($statusCode) - No interceptor provided. Stopping.", statusCode.toDouble(), null, null))
410
- updateState(SseState.FAILED)
411
- stopInternal()
487
+ failAndStop("Auth Error ($statusCode) - No interceptor provided. Stopping.", statusCode.toDouble())
412
488
  return@post
413
489
  }
414
490
  val retries = consecutiveAuthErrors.incrementAndGet()
415
- if (retries >= maxAuthRetries) {
416
- eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "Auth Error ($statusCode) - Retry limit reached ($maxAuthRetries). Stopping.", statusCode.toDouble(), null, null))
417
- updateState(SseState.FAILED)
418
- stopInternal()
491
+ if (retries >= maxRetries) {
492
+ failAndStop("Auth Error ($statusCode) - Retry limit reached ($maxRetries). Stopping.", statusCode.toDouble())
419
493
  return@post
420
494
  }
421
- 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))
422
496
  scheduleReconnect(true, connectionAttemptVersion.get())
423
497
  return@post
424
498
  }
425
499
 
426
- if (statusCode == 400) {
427
- eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "Fatal Error ($statusCode). Stopping.", statusCode.toDouble(), null, null))
428
- updateState(SseState.FAILED)
429
- stopInternal()
500
+ val isFatal = (statusCode in 400..499 && statusCode != 401 && statusCode != 403 && statusCode != 408 && statusCode != 429)
501
+ if (isFatal) {
502
+ failAndStop("Fatal Error ($statusCode). Stopping.", statusCode.toDouble())
430
503
  return@post
431
504
  }
432
505
 
506
+ // Schedule non-blocking Retry-After delay on dispatcher.
433
507
  val retryAfterMillis = SseReconnectStrategy.extractRetryAfterMillis(response)
434
508
  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()
435
516
  val jitter = (500 + Random.nextInt(1001)).toLong()
436
517
  val totalDelay = retryAfterMillis + jitter
437
518
  eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "Retry-After received: ${totalDelay/1000}s", statusCode.toDouble(), totalDelay.toDouble(), null))
438
- val currentAttemptVersion = connectionAttemptVersion.get()
519
+ val newAttemptVersion = connectionAttemptVersion.incrementAndGet()
439
520
  updateState(SseState.RECONNECTING)
440
- sseDispatcher?.postDelayed({ if (isRunning.get()) performConnection(currentAttemptVersion) }, totalDelay)
521
+ sseDispatcher?.postDelayed({ if (isRunning.get() && newAttemptVersion == connectionAttemptVersion.get()) performConnection(newAttemptVersion) }, totalDelay)
441
522
  return@post
442
523
  }
443
524
 
444
525
  if (statusCode == 429) {
445
- eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "Rate Limited (429) without Retry-After. Stopping.", 429.0, null, null))
446
- updateState(SseState.FAILED)
447
- stopInternal()
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())
448
528
  return@post
449
529
  }
450
530
 
451
531
  if (statusCode == 204) {
452
- eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "No Content (204). Stopping.", 204.0, null, null))
453
- updateState(SseState.FAILED)
454
- stopInternal()
532
+ failAndStop("No Content (204). Stopping.", 204.0)
455
533
  return@post
456
534
  }
457
535
 
@@ -460,36 +538,44 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
460
538
  updateState(SseState.STALE)
461
539
  }
462
540
 
541
+ // Teardown and reconnect on stream or socket failure.
463
542
  eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, t?.message ?: "Link lost ($statusCode)", if (statusCode != -1) statusCode.toDouble() else null, null, null))
464
543
  scheduleReconnect(true, connectionAttemptVersion.get())
465
544
  }
466
545
  }
467
546
 
468
- override fun connectionDidClose(reqId: String) {
547
+ override fun connectionDidClose(requestId: String) {
469
548
  sseDispatcher?.post {
470
- if (reqId != requestId || !isRunning.get()) return@post
471
- val currentRequestId = synchronized(this@NitroSse) {
472
- val id = requestId
473
- requestId = null
474
- id
475
- }
476
- currentRequestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
549
+ if (requestId != this@NitroSse.requestId || !isRunning.get()) return@post
550
+ clearActiveRequestAndReportEnd()
477
551
  scheduleReconnect(false, connectionAttemptVersion.get())
478
552
  }
479
553
  }
480
554
 
555
+ private fun failAndStop(message: String, statusCode: Double? = null) {
556
+ eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, message, statusCode, null, null))
557
+ updateState(SseState.FAILED)
558
+ stopInternal()
559
+ }
560
+
481
561
  private fun scheduleReconnect(isError: Boolean, attemptVersion: Int) {
562
+ if (!isRunning.get() || attemptVersion != connectionAttemptVersion.get()) return
482
563
  if (reconnectStrategy.hasReachedMaxAttempts()) {
483
564
  val maxAttempts = reconnectStrategy.currentReconnectAttempts
484
565
  Log.d(TAG, "Max reconnection attempts reached ($maxAttempts). Stopping.")
485
- eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "Max reconnection attempts reached ($maxAttempts).", null, null, null))
486
- updateState(SseState.FAILED)
487
- stopInternal()
566
+ failAndStop("Max reconnection attempts reached ($maxAttempts).")
488
567
  return
489
568
  }
569
+ // Increment attempt version before scheduling to invalidate pending tasks from previous cycles
570
+ val newAttemptVersion = connectionAttemptVersion.incrementAndGet()
490
571
  val safeReconnectDelay = reconnectStrategy.nextDelay(isError)
491
572
  updateState(SseState.RECONNECTING)
492
- sseDispatcher?.postDelayed({ if (isRunning.get()) performConnection(attemptVersion) }, safeReconnectDelay)
573
+ sseDispatcher?.postDelayed({
574
+ // Double check version and running state at trigger time to discard stale delayed callbacks
575
+ if (isRunning.get() && newAttemptVersion == connectionAttemptVersion.get()) {
576
+ performConnection(newAttemptVersion)
577
+ }
578
+ }, safeReconnectDelay)
493
579
  }
494
580
 
495
581
  private fun stopInternal() {
@@ -507,8 +593,14 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
507
593
  override fun restart() {
508
594
  synchronized(this) { config } ?: return
509
595
  stopInternal()
596
+ isRunning.set(true)
597
+ val version = connectionAttemptVersion.incrementAndGet()
510
598
  updateState(SseState.RECONNECTING)
511
- start()
599
+ sseDispatcher?.post {
600
+ reconnectStrategy.reset()
601
+ requestId = null
602
+ performConnection(version)
603
+ }
512
604
  }
513
605
 
514
606
  override fun isConnected(): Boolean {
@@ -528,13 +620,7 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
528
620
  }
529
621
  }
530
622
 
531
- private fun performInternalCleanup() {
532
- reconnectStrategy.reset()
533
- if (!isDispatcherDestroyed) {
534
- if (::eventBuffer.isInitialized) eventBuffer.flush()
535
- } else {
536
- if (::eventBuffer.isInitialized) eventBuffer.clear()
537
- }
623
+ private fun clearActiveRequestAndReportEnd() {
538
624
  val currentRequestId = synchronized(this) {
539
625
  eventSource?.cancel()
540
626
  eventSource = null
@@ -545,31 +631,39 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
545
631
  currentRequestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
546
632
  }
547
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
+ */
548
649
  override fun dispose() {
549
650
  Log.d(TAG, "Disposing NitroSse instance and cleaning up resources...")
550
651
 
652
+ isRunning.set(false)
653
+ connectionAttemptVersion.incrementAndGet()
654
+
551
655
  if (::eventBuffer.isInitialized) {
552
656
  eventBuffer.clearCallback()
657
+ eventBuffer.clear()
553
658
  }
554
659
 
555
- isRunning.set(false)
556
- connectionAttemptVersion.incrementAndGet()
557
-
558
660
  networkMonitor?.stop()
661
+ networkMonitor = null
662
+
559
663
  lifecycleManager?.stopObserving()
664
+ lifecycleManager = null
560
665
 
561
- try {
562
- val currentRequestId = synchronized(this) {
563
- eventSource?.cancel()
564
- eventSource = null
565
- val id = requestId
566
- requestId = null
567
- id
568
- }
569
- currentRequestId?.let { NetworkInspector.reportRequestFailed(it, true) }
570
- } catch (e: Exception) {
571
- Log.e(TAG, "Error during synchronous dispose: ${e.message}")
572
- }
666
+ clearActiveRequestAndReportEnd()
573
667
 
574
668
  sseDispatcher?.removeCallbacksAndMessages(null)
575
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: () -> 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()
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
  }