react-native-nitro-sse 3.2.0-beta.1 → 3.3.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 (109) hide show
  1. package/README.md +50 -27
  2. package/android/build.gradle +7 -3
  3. package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +8 -32
  4. package/android/src/main/java/com/margelo/nitro/nitrosse/NetworkInspector.kt +124 -6
  5. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +439 -509
  6. package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +137 -316
  7. package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +18 -8
  8. package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventReader.kt +231 -0
  9. package/android/src/main/java/com/margelo/nitro/nitrosse/SseFailureClassifier.kt +245 -0
  10. package/android/src/main/java/com/margelo/nitro/nitrosse/SseMetrics.kt +237 -0
  11. package/android/src/main/java/com/margelo/nitro/nitrosse/SseNetworkMonitor.kt +13 -6
  12. package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +48 -22
  13. package/ios/NitroSse.swift +402 -484
  14. package/ios/SseConfig+CopyWith.swift +0 -2
  15. package/ios/SseConnectionHandler.swift +238 -446
  16. package/ios/SseDispatchQueueDispatcher.swift +7 -7
  17. package/ios/SseDispatcher.swift +5 -4
  18. package/ios/SseEventBuffer.swift +24 -23
  19. package/ios/SseEventParser.swift +360 -0
  20. package/ios/SseFailureClassifier.swift +249 -0
  21. package/ios/SseLifecycleManager.swift +19 -14
  22. package/ios/SseMetrics.swift +188 -0
  23. package/ios/SseNetworkMonitor.swift +18 -14
  24. package/ios/SseReconnectStrategy.swift +28 -30
  25. package/lib/module/FetchSseDriver.js +398 -170
  26. package/lib/module/MockSseEngine.js +15 -17
  27. package/lib/module/NitroSseClient.js +70 -56
  28. package/lib/module/SseConsoleLogger.js +64 -0
  29. package/lib/module/SseEventParser.js +173 -115
  30. package/lib/module/createNitroSse.js +7 -14
  31. package/lib/module/createNitroSse.native.js +2 -1
  32. package/lib/module/useNitroSse.js +103 -90
  33. package/lib/typescript/src/FetchSseDriver.d.ts +11 -4
  34. package/lib/typescript/src/MockSseEngine.d.ts +2 -2
  35. package/lib/typescript/src/NitroSse.nitro.d.ts +9 -1
  36. package/lib/typescript/src/NitroSseClient.d.ts +4 -1
  37. package/lib/typescript/src/SseConsoleLogger.d.ts +28 -0
  38. package/lib/typescript/src/SseEventParser.d.ts +18 -2
  39. package/lib/typescript/src/SseInterface.d.ts +21 -4
  40. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.hpp +1 -1
  41. package/nitrogen/generated/android/c++/JFunc_void_std__vector_SseEvent_.hpp +1 -1
  42. package/nitrogen/generated/android/c++/JHttpMethod.hpp +1 -1
  43. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +1 -1
  44. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.hpp +1 -1
  45. package/nitrogen/generated/android/c++/JSseConfig.hpp +1 -1
  46. package/nitrogen/generated/android/c++/JSseDisconnectReason.hpp +1 -1
  47. package/nitrogen/generated/android/c++/JSseEvent.hpp +1 -1
  48. package/nitrogen/generated/android/c++/JSseEventType.hpp +1 -1
  49. package/nitrogen/generated/android/c++/JSseMockConfig.hpp +1 -1
  50. package/nitrogen/generated/android/c++/JSseMockEvent.hpp +1 -1
  51. package/nitrogen/generated/android/c++/JSseMockMode.hpp +1 -1
  52. package/nitrogen/generated/android/c++/JSseState.hpp +1 -1
  53. package/nitrogen/generated/android/c++/JSseStats.hpp +1 -1
  54. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.kt +1 -1
  55. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/Func_void_std__vector_SseEvent_.kt +1 -1
  56. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HttpMethod.kt +1 -1
  57. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HybridNitroSseSpec.kt +1 -1
  58. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +1 -1
  59. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseDisconnectReason.kt +1 -1
  60. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEvent.kt +1 -1
  61. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEventType.kt +1 -1
  62. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockConfig.kt +1 -1
  63. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockEvent.kt +1 -1
  64. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockMode.kt +1 -1
  65. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseState.kt +1 -1
  66. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseStats.kt +1 -1
  67. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/nitrosseOnLoad.kt +1 -1
  68. package/nitrogen/generated/android/nitrosse+autolinking.cmake +1 -1
  69. package/nitrogen/generated/android/nitrosse+autolinking.gradle +1 -1
  70. package/nitrogen/generated/android/nitrosseOnLoad.cpp +1 -1
  71. package/nitrogen/generated/android/nitrosseOnLoad.hpp +1 -1
  72. package/nitrogen/generated/ios/NitroSse+autolinking.rb +1 -1
  73. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.cpp +1 -1
  74. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +1 -1
  75. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +1 -1
  76. package/nitrogen/generated/ios/NitroSseAutolinking.mm +1 -1
  77. package/nitrogen/generated/ios/NitroSseAutolinking.swift +1 -5
  78. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.cpp +1 -1
  79. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +1 -1
  80. package/nitrogen/generated/ios/swift/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.swift +1 -1
  81. package/nitrogen/generated/ios/swift/Func_void_std__exception_ptr.swift +1 -1
  82. package/nitrogen/generated/ios/swift/Func_void_std__shared_ptr_Promise_std__unordered_map_std__string__std__string___.swift +1 -1
  83. package/nitrogen/generated/ios/swift/Func_void_std__unordered_map_std__string__std__string_.swift +1 -1
  84. package/nitrogen/generated/ios/swift/Func_void_std__vector_SseEvent_.swift +1 -1
  85. package/nitrogen/generated/ios/swift/HttpMethod.swift +1 -1
  86. package/nitrogen/generated/ios/swift/HybridNitroSseSpec.swift +1 -1
  87. package/nitrogen/generated/ios/swift/HybridNitroSseSpec_cxx.swift +3 -3
  88. package/nitrogen/generated/ios/swift/SseConfig.swift +1 -1
  89. package/nitrogen/generated/ios/swift/SseDisconnectReason.swift +1 -1
  90. package/nitrogen/generated/ios/swift/SseEvent.swift +1 -1
  91. package/nitrogen/generated/ios/swift/SseEventType.swift +1 -1
  92. package/nitrogen/generated/ios/swift/SseMockConfig.swift +1 -1
  93. package/nitrogen/generated/ios/swift/SseMockEvent.swift +1 -1
  94. package/nitrogen/generated/ios/swift/SseMockMode.swift +1 -1
  95. package/nitrogen/generated/ios/swift/SseState.swift +1 -1
  96. package/nitrogen/generated/ios/swift/SseStats.swift +1 -1
  97. package/nitrogen/generated/shared/c++/HttpMethod.hpp +1 -1
  98. package/nitrogen/generated/shared/c++/HybridNitroSseSpec.cpp +1 -1
  99. package/nitrogen/generated/shared/c++/HybridNitroSseSpec.hpp +1 -1
  100. package/nitrogen/generated/shared/c++/SseConfig.hpp +1 -1
  101. package/nitrogen/generated/shared/c++/SseDisconnectReason.hpp +1 -1
  102. package/nitrogen/generated/shared/c++/SseEvent.hpp +1 -1
  103. package/nitrogen/generated/shared/c++/SseEventType.hpp +1 -1
  104. package/nitrogen/generated/shared/c++/SseMockConfig.hpp +1 -1
  105. package/nitrogen/generated/shared/c++/SseMockEvent.hpp +1 -1
  106. package/nitrogen/generated/shared/c++/SseMockMode.hpp +1 -1
  107. package/nitrogen/generated/shared/c++/SseState.hpp +1 -1
  108. package/nitrogen/generated/shared/c++/SseStats.hpp +1 -1
  109. package/package.json +18 -10
@@ -1,32 +1,41 @@
1
1
  package com.margelo.nitro.nitrosse
2
2
 
3
+ import android.net.NetworkCapabilities
3
4
  import android.os.Handler
4
- import android.util.Log
5
+ import android.os.HandlerThread
6
+ import android.os.Looper
7
+ import androidx.lifecycle.ProcessLifecycleOwner
5
8
  import com.facebook.proguard.annotations.DoNotStrip
6
- import okhttp3.OkHttpClient
7
- import okhttp3.Request
8
- import okhttp3.Response
9
- import okhttp3.MediaType.Companion.toMediaType
10
- import okhttp3.RequestBody.Companion.toRequestBody
11
- import okio.utf8Size
12
9
  import com.margelo.nitro.NitroModules
13
10
  import com.margelo.nitro.core.Promise
11
+ import java.lang.ref.WeakReference
12
+ import java.util.UUID
14
13
  import java.util.concurrent.TimeUnit
15
14
  import java.util.concurrent.atomic.AtomicBoolean
16
- import java.util.concurrent.atomic.AtomicLong
17
15
  import java.util.concurrent.atomic.AtomicInteger
18
- import java.util.UUID
19
- import kotlin.random.Random
20
- import android.net.NetworkCapabilities
16
+ import java.util.concurrent.atomic.AtomicReference
17
+ import okhttp3.OkHttpClient
18
+ import okhttp3.Response
19
+ import okio.utf8Size
21
20
 
22
21
  /**
23
22
  * Core Android implementation of [HybridNitroSseSpec] managing Server-Sent Events (SSE).
24
23
  *
25
24
  * Coordinates OkHttp SSE connection state, exponential backoff retries, event buffering,
26
- * network interface transitions, and Android app lifecycle hibernation. Uses a single-threaded
27
- * background [SseDispatcher] to ensure thread-safe state mutations and avoid blocking the JS UI thread.
25
+ * network interface transitions, and Android app lifecycle hibernation.
26
+ *
27
+ * Threading & Synchronization Model:
28
+ * - [SseDispatcher] (dedicated [HandlerThread]): Serializes asynchronous connection workflows,
29
+ * reconnection scheduling, backoff timers, and event buffering/flushing.
30
+ * - Intrinsic Monitor ([synchronized]): Guards shared mutable state (metrics, active config,
31
+ * timestamps) to enable thread-safe synchronous reads from the JS/JSI thread (e.g. [getStats])
32
+ * and high-throughput in-line metric updates from OkHttp network callbacks without creating
33
+ * excessive Runnable allocations on the dispatcher.
34
+ * - Lock-free & Atomic Primitives ([AtomicBoolean], [AtomicInteger], [@Volatile]): Guarantee immediate
35
+ * cross-thread visibility and atomic state transitions for lifecycle flags ([isRunning], [requestId]).
28
36
  */
29
37
  @DoNotStrip
38
+ @Suppress("TooManyFunctions", "LargeClass")
30
39
  class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDelegate {
31
40
 
32
41
  // Secondary constructor for unit testing to inject virtual-time dispatchers without spawning HandlerThreads
@@ -54,46 +63,17 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
54
63
  private var wasRunningBeforePaused = false
55
64
  private val consecutiveAuthErrors = AtomicInteger(0)
56
65
 
57
- private var sseDispatcherThread: android.os.HandlerThread? = null
66
+ private var sseDispatcherThread: HandlerThread? = null
58
67
  internal var sseDispatcher: SseDispatcher? = null
59
-
60
- // Transport Metrics
61
- private var rawBytesReceived: Double = 0.0
62
- private var decompressedBytesReceived: Double? = null
63
- private var sessionRawBytesOffset: Double = 0.0
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
68
+ internal val metrics = SseMetrics()
91
69
 
92
70
  private val connectionAttemptVersion = AtomicInteger(0)
71
+ private var lastCleanupVersion = 0
93
72
  private var lastProcessedId: String? = null
94
- private var currentState = java.util.concurrent.atomic.AtomicReference(SseState.IDLE)
73
+ private var currentState = AtomicReference(SseState.IDLE)
95
74
  private var wasRunningBeforeNetworkLoss = false
96
75
  private var interceptorTimeoutRunnable: Runnable? = null
76
+ private var networkRestartRunnable: Runnable? = null
97
77
  private val isDisposed = AtomicBoolean(false)
98
78
  /// Dynamic request interceptor decoupled from SseConfig (v3.0)
99
79
  private var requestInterceptor: (() -> Promise<Promise<Map<String, String>>>)? = null
@@ -103,11 +83,17 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
103
83
  private var networkMonitor: SseNetworkMonitor? = null
104
84
  private var lifecycleManager: SseLifecycleManager? = null
105
85
  private val connectionHandler = SseConnectionHandler(this)
106
- private val mainDispatcher = AndroidSseDispatcher(Handler(android.os.Looper.getMainLooper()))
86
+ private val mainDispatcher = AndroidSseDispatcher(Handler(Looper.getMainLooper()))
107
87
 
108
88
  companion object {
109
- private const val TAG = "NitroSse"
89
+ private const val NETWORK_CHANGE_DEBOUNCE_MS = 1000L
110
90
  private const val DEFAULT_MAX_AUTH_RETRIES = 3
91
+ private const val DEFAULT_MAX_BUFFER_SIZE = 1000
92
+ private const val DEFAULT_RETRY_INTERVAL_MS = 1000.0
93
+ private const val DEFAULT_MAX_RETRY_INTERVAL_MS = 30000.0
94
+ private const val DEFAULT_JITTER_FACTOR = 0.5
95
+ private const val DEFAULT_CONNECT_TIMEOUT_MS = 15000.0
96
+ private const val DEFAULT_READ_TIMEOUT_MS = 300000.0
111
97
  }
112
98
 
113
99
  override fun setup(
@@ -118,72 +104,84 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
118
104
  synchronized(this) {
119
105
  this.config = config
120
106
  this.requestInterceptor = onBeforeRequest
121
- this.rawBytesReceived = 0.0
122
- this.decompressedBytesReceived = null
123
- this.sessionRawBytesOffset = 0.0
107
+ metrics.resetSessionByteCounters()
124
108
  if (this.lastProcessedId == null) {
125
- this.lastProcessedId = config.headers?.entries?.firstOrNull {
126
- it.key.equals("Last-Event-ID", ignoreCase = true)
109
+ this.lastProcessedId = config.headers?.entries?.firstOrNull {
110
+ it.key.equals("Last-Event-ID", ignoreCase = true)
127
111
  }?.value
128
112
  }
129
-
130
- if (sseDispatcher == null) {
131
- sseDispatcherThread = android.os.HandlerThread("NitroSseThread").apply { start() }
132
- sseDispatcher = AndroidSseDispatcher(Handler(sseDispatcherThread!!.looper))
133
- }
134
113
 
135
- if (!::eventBuffer.isInitialized) {
136
- eventBuffer = SseEventBuffer(onEvent, sseDispatcher)
137
- eventBuffer.onFlushError = { e -> handleRuntimeOrFlushError(e) }
138
- } else {
139
- eventBuffer.setCallback(onEvent)
140
- }
141
- eventBuffer.configure(config.batchingIntervalMs ?: 0.0, config.maxBufferSize?.toInt() ?: 1000)
114
+ ensureDispatcherAndEventBuffer(config, onEvent)
142
115
 
143
116
  // Custom backoff guarantees cross-platform parity and lifecycle coordination.
144
117
  reconnectStrategy.configure(
145
- config.retryIntervalMs ?: 1000.0,
146
- config.maxRetryIntervalMs ?: 30000.0,
147
- config.jitterFactor ?: 0.5,
148
- (config.maxReconnectAttempts ?: -1.0).toInt()
118
+ config.retryIntervalMs ?: DEFAULT_RETRY_INTERVAL_MS,
119
+ config.maxRetryIntervalMs ?: DEFAULT_MAX_RETRY_INTERVAL_MS,
120
+ config.jitterFactor ?: DEFAULT_JITTER_FACTOR,
121
+ (config.maxReconnectAttempts ?: SseHttpStatus.UNKNOWN_DOUBLE).toInt()
149
122
  )
150
123
 
151
- if (this.client == null) {
152
- val builder = OkHttpClient.Builder()
153
- .connectTimeout((config.connectionTimeoutMs ?: 15000.0).toLong(), TimeUnit.MILLISECONDS)
154
- .readTimeout((config.readTimeoutMs ?: 300000.0).toLong(), TimeUnit.MILLISECONDS)
155
- // Enables transparent socket-level retry on route failures (multiple IP fallback, transient resets)
156
- // before bubbling up to full SSE stream reconnect.
157
- .retryOnConnectionFailure(true)
158
- .addNetworkInterceptor(InspectorNetworkInterceptor())
159
- this.client = builder.build()
160
- } else {
161
- this.client = this.client!!.newBuilder()
162
- .connectTimeout((config.connectionTimeoutMs ?: 15000.0).toLong(), TimeUnit.MILLISECONDS)
163
- .readTimeout((config.readTimeoutMs ?: 300000.0).toLong(), TimeUnit.MILLISECONDS)
164
- .retryOnConnectionFailure(true)
165
- .build()
166
- }
167
-
168
- if (lifecycleManager == null) {
169
- lifecycleManager = SseLifecycleManager(
170
- lifecycleProvider = { androidx.lifecycle.ProcessLifecycleOwner.get().lifecycle },
171
- mainDispatcher = mainDispatcher,
172
- sseDispatcher = sseDispatcher!!,
173
- onBackground = { handleAppBackground() },
174
- onForeground = { handleAppForeground() }
175
- )
176
- lifecycleManager?.startObserving()
177
- }
178
- if (config.monitorNetwork != false) {
179
- sseDispatcher?.post {
180
- startNetworkMonitoring()
181
- }
182
- } else {
183
- sseDispatcher?.post {
184
- networkMonitor?.stop()
185
- networkMonitor = null
186
- }
124
+ configureHttpClient(config)
125
+ configureLifecycleAndNetwork(config)
126
+ }
127
+ }
128
+
129
+ private fun ensureDispatcherAndEventBuffer(
130
+ config: SseConfig,
131
+ onEvent: (events: Array<SseEvent>) -> Unit
132
+ ) {
133
+ if (sseDispatcher == null) {
134
+ sseDispatcherThread = HandlerThread("NitroSseThread").apply { start() }
135
+ sseDispatcher = AndroidSseDispatcher(Handler(sseDispatcherThread!!.looper))
136
+ }
137
+
138
+ if (!::eventBuffer.isInitialized) {
139
+ eventBuffer = SseEventBuffer(onEvent, sseDispatcher)
140
+ eventBuffer.onFlushError = { e -> handleRuntimeOrFlushError(e) }
141
+ } else {
142
+ eventBuffer.setCallback(onEvent)
143
+ }
144
+ eventBuffer.configure(
145
+ config.batchingIntervalMs ?: 0.0,
146
+ config.maxBufferSize?.toInt() ?: DEFAULT_MAX_BUFFER_SIZE
147
+ )
148
+ }
149
+
150
+ private fun configureHttpClient(config: SseConfig) {
151
+ val baseBuilder = this.client?.newBuilder()
152
+ ?: OkHttpClient.Builder().addNetworkInterceptor(InspectorNetworkInterceptor())
153
+ this.client = baseBuilder
154
+ .connectTimeout(
155
+ (config.connectionTimeoutMs ?: DEFAULT_CONNECT_TIMEOUT_MS).toLong(),
156
+ TimeUnit.MILLISECONDS
157
+ )
158
+ .readTimeout(
159
+ (config.readTimeoutMs ?: DEFAULT_READ_TIMEOUT_MS).toLong(),
160
+ TimeUnit.MILLISECONDS
161
+ )
162
+ .retryOnConnectionFailure(true)
163
+ .build()
164
+ }
165
+
166
+ private fun configureLifecycleAndNetwork(config: SseConfig) {
167
+ if (lifecycleManager == null) {
168
+ val weakThis = WeakReference(this)
169
+ val manager = SseLifecycleManager(
170
+ lifecycleProvider = { ProcessLifecycleOwner.get().lifecycle },
171
+ mainDispatcher = mainDispatcher,
172
+ sseDispatcher = sseDispatcher!!,
173
+ onBackground = { weakThis.get()?.handleAppBackground() },
174
+ onForeground = { weakThis.get()?.handleAppForeground() }
175
+ )
176
+ lifecycleManager = manager
177
+ manager.startObserving()
178
+ }
179
+ if (config.monitorNetwork != false) {
180
+ sseDispatcher?.post { startNetworkMonitoring() }
181
+ } else {
182
+ sseDispatcher?.post {
183
+ networkMonitor?.stop()
184
+ networkMonitor = null
187
185
  }
188
186
  }
189
187
  }
@@ -197,44 +195,51 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
197
195
 
198
196
  private fun startNetworkMonitoring() {
199
197
  val context = NitroModules.applicationContext ?: return
200
- if (networkMonitor == null) {
201
- networkMonitor = SseNetworkMonitor(context, sseDispatcher) { isAvailable, interfaceChanged, capabilities ->
202
- handleNetworkChange(isAvailable, interfaceChanged, capabilities)
203
- }
198
+ val monitor = networkMonitor ?: run {
199
+ val weakThis = WeakReference(this)
200
+ SseNetworkMonitor(context, sseDispatcher) { isAvailable, interfaceChanged, capabilities ->
201
+ weakThis.get()?.handleNetworkChange(isAvailable, interfaceChanged, capabilities)
202
+ }.also { networkMonitor = it }
204
203
  }
205
- networkMonitor?.start()
204
+ monitor.start()
206
205
  }
207
206
 
208
- private fun handleNetworkChange(isAvailable: Boolean, interfaceChanged: Boolean, capabilities: NetworkCapabilities?) {
209
- Log.d(TAG, "Network change: available=$isAvailable, interfaceChanged=$interfaceChanged")
207
+ internal fun handleNetworkChange(
208
+ isAvailable: Boolean,
209
+ interfaceChanged: Boolean,
210
+ capabilities: NetworkCapabilities? = null
211
+ ) {
210
212
  if (isAvailable && capabilities != null) {
211
213
  if (wasRunningBeforeNetworkLoss) {
212
- Log.d(TAG, "Network restored. Resuming stream.")
214
+ cancelNetworkRestartDebounce()
213
215
  wasRunningBeforeNetworkLoss = false
214
- if (lifecycleManager?.isAppInBackground == true && config?.backgroundExecution != true) {
216
+ if (lifecycleManager?.isAppInBackground == true && !isBackgroundExecutionEnabled()) {
215
217
  wasRunningBeforePaused = true
216
218
  } else {
217
219
  start()
218
220
  }
219
221
  } else if (isRunning.get() && interfaceChanged) {
220
- Log.d(TAG, "Network interface changed. Restarting stream.")
221
- restart()
222
+ cancelNetworkRestartDebounce()
223
+ val runnable = Runnable {
224
+ networkRestartRunnable = null
225
+ if (isRunning.get()) {
226
+ restart()
227
+ }
228
+ }
229
+ networkRestartRunnable = runnable
230
+ sseDispatcher?.postDelayed(runnable, NETWORK_CHANGE_DEBOUNCE_MS)
222
231
  }
223
232
  } else if (!isAvailable) {
233
+ cancelNetworkRestartDebounce()
224
234
  if (isRunning.get()) {
225
- Log.d(TAG, "Network lost. Hibernating.")
226
235
  wasRunningBeforeNetworkLoss = true
227
- updateState(SseState.PAUSED)
228
- isRunning.set(false)
229
- connectionAttemptVersion.incrementAndGet()
230
- performInternalCleanup()
236
+ hibernate()
231
237
  }
232
238
  }
233
239
  }
234
240
 
235
241
  private fun handleAppForeground() {
236
242
  if (wasRunningBeforePaused) {
237
- Log.d(TAG, "App foregrounded. Resuming NitroSse stream.")
238
243
  wasRunningBeforePaused = false
239
244
  start()
240
245
  }
@@ -242,19 +247,33 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
242
247
 
243
248
  private fun handleAppBackground() {
244
249
  if (isRunning.get()) {
245
- if (config?.backgroundExecution == true) {
246
- Log.d(TAG, "App backgrounded. keeping connection alive.")
250
+ if (isBackgroundExecutionEnabled()) {
247
251
  return
248
252
  }
249
- Log.d(TAG, "App backgrounded. Hibernating.")
250
253
  wasRunningBeforePaused = true
251
- updateState(SseState.PAUSED)
252
- isRunning.set(false)
253
- connectionAttemptVersion.incrementAndGet()
254
- performInternalCleanup()
254
+ hibernate()
255
255
  }
256
256
  }
257
257
 
258
+ /**
259
+ * Reads [SseConfig.backgroundExecution] under the instance monitor, since [config] is written
260
+ * from the JS thread ([setup], [updateHeaders], [dispose]) while this is read on [sseDispatcher].
261
+ */
262
+ private fun isBackgroundExecutionEnabled(): Boolean =
263
+ synchronized(this) { config?.backgroundExecution == true }
264
+
265
+ /**
266
+ * Pauses the active stream (network loss or app background) and invalidates in-flight attempts.
267
+ * Callers set their own resume-intent flag ([wasRunningBeforeNetworkLoss] / [wasRunningBeforePaused]).
268
+ * Always invoked on [sseDispatcher].
269
+ */
270
+ private fun hibernate() {
271
+ updateState(SseState.PAUSED)
272
+ isRunning.set(false)
273
+ connectionAttemptVersion.incrementAndGet()
274
+ performInternalCleanup()
275
+ }
276
+
258
277
  override fun setLastProcessedId(id: String) {
259
278
  synchronized(this) {
260
279
  this.lastProcessedId = id
@@ -271,40 +290,17 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
271
290
  }
272
291
 
273
292
  override fun getStats(): SseStats {
293
+ val buffered: Double
294
+ val peak: Double
295
+ val flushes: Double
296
+ val overflows: Double
274
297
  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
-
280
- return SseStats(
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
306
- )
298
+ buffered = if (::eventBuffer.isInitialized) eventBuffer.getEventsBuffered().toDouble() else 0.0
299
+ peak = if (::eventBuffer.isInitialized) eventBuffer.getPeakBufferedEvents().toDouble() else 0.0
300
+ flushes = if (::eventBuffer.isInitialized) eventBuffer.getBufferFlushCount().toDouble() else 0.0
301
+ overflows = if (::eventBuffer.isInitialized) eventBuffer.getBufferOverflowCount().toDouble() else 0.0
307
302
  }
303
+ return metrics.toSseStats(buffered, peak, flushes, overflows)
308
304
  }
309
305
 
310
306
  override fun getState(): SseState {
@@ -322,201 +318,196 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
322
318
  }
323
319
 
324
320
  override fun start() {
325
- val currentConfig = synchronized(this) { config }
326
- ?: throw IllegalStateException("NitroSse not configured. Call setup() first.")
327
-
328
- if (isRunning.get()) {
321
+ checkNotNull(synchronized(this) { config }) {
322
+ "NitroSse not configured. Call setup() first."
323
+ }
324
+
325
+ if (!isRunning.compareAndSet(false, true)) {
329
326
  // If client is waiting in backoff reconnect loop, start() acts as an immediate "Retry Now",
330
327
  // cancelling pending backoff delay, resetting backoff counter, and attempting connection immediately.
331
328
  if (currentState.get() == SseState.RECONNECTING) {
332
- Log.d(TAG, "start() invoked while reconnecting. Resetting backoff and retrying immediately.")
333
- consecutiveAuthErrors.set(0)
334
- val version = connectionAttemptVersion.incrementAndGet()
335
- updateState(SseState.CONNECTING)
336
- sseDispatcher?.post {
337
- reconnectStrategy.reset()
338
- requestId = null
339
- performConnection(version)
340
- }
329
+ beginConnectionCycle()
341
330
  }
342
331
  return
343
332
  }
344
333
 
345
- if (!isRunning.compareAndSet(false, true)) return
346
-
347
- consecutiveAuthErrors.set(0)
348
334
  isDispatcherDestroyed = false
335
+ beginConnectionCycle()
336
+ }
337
+
338
+ /**
339
+ * Begins a fresh connection cycle from the caller thread: claims a new attempt version
340
+ * (invalidating pending backoff timers), transitions to CONNECTING, and connects on [sseDispatcher].
341
+ */
342
+ private fun beginConnectionCycle() {
343
+ consecutiveAuthErrors.set(0)
349
344
  val version = connectionAttemptVersion.incrementAndGet()
350
345
  updateState(SseState.CONNECTING)
351
- sseDispatcher?.post {
352
- reconnectStrategy.reset()
353
- requestId = null
354
- performConnection(version)
355
- }
346
+ sseDispatcher?.post { connectWithFreshBackoff(version) }
347
+ }
348
+
349
+ /**
350
+ * Resets backoff counters and performs a connection attempt for [version]. Must run on [sseDispatcher].
351
+ */
352
+ private fun connectWithFreshBackoff(version: Int) {
353
+ reconnectStrategy.reset()
354
+ requestId = null
355
+ performConnection(version)
356
356
  }
357
357
 
358
358
  private fun performConnection(version: Int) {
359
359
  // Discard attempt if state has changed or a newer connection cycle was initiated
360
360
  if (!isRunning.get() || version != connectionAttemptVersion.get()) return
361
361
 
362
- val currentConfig = synchronized(this) { config } ?: return
363
- // Asynchronously await JS onBeforeRequest interceptor before creating EventSource.
364
- val interceptor = synchronized(this) { requestInterceptor }
362
+ val (currentConfig, interceptor) = synchronized(this) {
363
+ val cfg = config ?: return
364
+ Pair(cfg, requestInterceptor)
365
+ }
365
366
 
366
367
  if (interceptor != null) {
367
- val interceptorCompleted = AtomicBoolean(false)
368
- val timeoutMs = (currentConfig.connectionTimeoutMs ?: 15000.0).toLong()
368
+ executeWithInterceptor(interceptor, currentConfig, version)
369
+ } else {
370
+ executeConnection(version, null)
371
+ }
372
+ }
369
373
 
370
- val safeHandleError: (Throwable) -> Unit = { error ->
371
- if (interceptorCompleted.compareAndSet(false, true)) {
372
- handleInterceptorError(error, version)
373
- }
374
- }
374
+ @Suppress("TooGenericExceptionCaught")
375
+ private fun executeWithInterceptor(
376
+ interceptor: () -> Promise<Promise<Map<String, String>>>,
377
+ currentConfig: SseConfig,
378
+ version: Int
379
+ ) {
380
+ val interceptorCompleted = AtomicBoolean(false)
381
+ val timeoutMs = (currentConfig.connectionTimeoutMs ?: DEFAULT_CONNECT_TIMEOUT_MS).toLong()
375
382
 
376
- // Proactively cancel any previous in-flight interceptor timeout runnable
377
- interceptorTimeoutRunnable?.let { sseDispatcher?.removeCallbacks(it) }
378
- val timeoutRunnable = Runnable {
379
- safeHandleError(Exception("onBeforeRequest timed out"))
383
+ val safeHandleError: (Throwable) -> Unit = { error ->
384
+ if (interceptorCompleted.compareAndSet(false, true)) {
385
+ handleInterceptorError(error, version)
380
386
  }
381
- interceptorTimeoutRunnable = timeoutRunnable
382
-
383
- // Enforce timeout guard on JS onBeforeRequest promise to prevent connection hangs
384
- sseDispatcher?.postDelayed(timeoutRunnable, timeoutMs)
385
-
386
- try {
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 ->
391
- sseDispatcher?.post {
392
- if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
393
- if (interceptorCompleted.compareAndSet(false, true)) {
394
- interceptorTimeoutRunnable?.let { sseDispatcher?.removeCallbacks(it) }
395
- interceptorTimeoutRunnable = null
396
- val connectionConfig = synchronized(this) {
397
- val base = config ?: return@post
398
- val mergedHeaders = (base.headers ?: emptyMap()).toMutableMap()
399
- newHeaders.forEach { (k, v) -> mergedHeaders[k] = v }
400
- base.copy(headers = mergedHeaders)
401
- }
402
- executeConnection(version, connectionConfig)
387
+ }
388
+
389
+ // Proactively cancel any previous in-flight interceptor timeout runnable
390
+ interceptorTimeoutRunnable?.let { sseDispatcher?.removeCallbacks(it) }
391
+ val timeoutRunnable = Runnable {
392
+ safeHandleError(Exception("onBeforeRequest timed out"))
393
+ }
394
+ interceptorTimeoutRunnable = timeoutRunnable
395
+
396
+ // Enforce timeout guard on JS onBeforeRequest promise to prevent connection hangs
397
+ sseDispatcher?.postDelayed(timeoutRunnable, timeoutMs)
398
+
399
+ try {
400
+ // Safe-calls (?.) protect against null/unmocked Promise chains in unit tests and JS bridging.
401
+ interceptor.invoke()?.then { promise2 ->
402
+ promise2?.then { newHeaders ->
403
+ sseDispatcher?.post {
404
+ if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
405
+ if (interceptorCompleted.compareAndSet(false, true)) {
406
+ interceptorTimeoutRunnable?.let { sseDispatcher?.removeCallbacks(it) }
407
+ interceptorTimeoutRunnable = null
408
+ val connectionConfig = synchronized(this) {
409
+ val base = config ?: return@post
410
+ base.copy(headers = (base.headers ?: emptyMap()) + newHeaders)
403
411
  }
412
+ executeConnection(version, connectionConfig)
404
413
  }
405
- }?.catch { error ->
406
- safeHandleError(error)
407
414
  }
408
- }?.catch { error ->
409
- safeHandleError(error)
410
- }
411
- } catch (e: Throwable) {
412
- safeHandleError(e)
413
- }
414
- } else {
415
- executeConnection(version, null)
415
+ }?.catch(safeHandleError)
416
+ }?.catch(safeHandleError)
417
+ } catch (e: Throwable) {
418
+ safeHandleError(e)
416
419
  }
417
420
  }
418
421
 
422
+ /**
423
+ * Detects the React Native / Nitro "JS Dispatcher destroyed" runtime error (Fast Refresh, bundle reload,
424
+ * host teardown). Originates from third-party C++ (no typed exception available), so message matching
425
+ * is centralized here as the single source of truth.
426
+ */
427
+ private fun isJsDispatcherDestroyedError(t: Throwable?): Boolean =
428
+ t?.message?.contains("Dispatcher has already been destroyed", ignoreCase = true) == true
429
+
419
430
  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.")
431
+ if (isJsDispatcherDestroyedError(t)) {
423
432
  this.isDispatcherDestroyed = true
424
433
  dispose()
425
434
  }
426
435
  }
427
436
 
428
437
  private fun handleInterceptorError(t: Throwable?, version: Int) {
429
- interceptorTimeoutRunnable?.let { sseDispatcher?.removeCallbacks(it) }
430
- interceptorTimeoutRunnable = null
438
+ // May be invoked from the Promise callback thread; hop to sseDispatcher before touching
439
+ // dispatcher-confined state (interceptorTimeoutRunnable). Stale attempts must not cancel a newer
440
+ // attempt's timeout, which is why removal happens after the version guard.
431
441
  sseDispatcher?.post {
432
442
  if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
443
+ interceptorTimeoutRunnable?.let { sseDispatcher?.removeCallbacks(it) }
444
+ interceptorTimeoutRunnable = null
433
445
 
434
- val isDispatcherDestroyedMsg = t?.message?.contains("Dispatcher has already been destroyed", ignoreCase = true) == true
435
- if (isDispatcherDestroyedMsg) {
436
- Log.w(TAG, "JS Dispatcher destroyed during interceptor error. Disposing NitroSse instance.")
446
+ if (isJsDispatcherDestroyedError(t)) {
437
447
  this.isDispatcherDestroyed = true
438
448
  dispose()
439
449
  return@post
440
450
  }
441
451
 
442
- val maxRetries = synchronized(this@NitroSse) { config?.maxAuthRetries?.toInt() ?: DEFAULT_MAX_AUTH_RETRIES }
452
+ val maxRetries = synchronized(this@NitroSse) {
453
+ config?.maxAuthRetries?.toInt() ?: DEFAULT_MAX_AUTH_RETRIES
454
+ }
443
455
  val retries = consecutiveAuthErrors.incrementAndGet()
444
456
  if (retries > maxRetries) {
445
- failAndStop("Auth retry limit reached ($maxRetries). Stopping.", -1.0)
457
+ failAndStop("Auth retry limit reached ($maxRetries). Stopping.", SseHttpStatus.UNKNOWN_DOUBLE)
446
458
  return@post
447
459
  }
448
460
 
449
- eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "Interceptor Error: ${t?.message}", -1.0, null, null))
461
+ eventBuffer.push(
462
+ SseEvent(
463
+ SseEventType.ERROR,
464
+ null,
465
+ null,
466
+ null,
467
+ null,
468
+ "Interceptor Error: ${t?.message}",
469
+ SseHttpStatus.UNKNOWN_DOUBLE,
470
+ null,
471
+ null
472
+ )
473
+ )
450
474
  scheduleReconnect(true, version)
451
475
  }
452
476
  }
453
477
 
478
+ @Suppress("TooGenericExceptionCaught")
454
479
  private fun executeConnection(version: Int, connectionConfig: SseConfig? = null) {
455
480
  val currentConfig: SseConfig
456
481
  val currentLastId: String?
457
482
  val oldRequestId: String?
458
483
  val newRequestId = UUID.randomUUID().toString()
459
484
  val safeClient: OkHttpClient
460
-
485
+
461
486
  synchronized(this) {
462
487
  if (!isRunning.get() || config == null || version != connectionAttemptVersion.get()) return
463
488
  currentConfig = connectionConfig ?: config!!
464
489
  currentLastId = lastProcessedId
465
490
  safeClient = client ?: return
466
-
491
+
467
492
  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
- }
493
+ metrics.accumulateGzipRawBytesOffset(oldRequestId)
474
494
  requestId = newRequestId
475
-
495
+
476
496
  eventSource?.cancel()
477
497
  eventSource = null
478
498
 
479
- connectionAttempts += 1.0
480
- connectionAttemptStartTime = System.currentTimeMillis().toDouble()
481
- timeToFirstByteMs = null
499
+ metrics.recordConnectionAttemptStart(System.currentTimeMillis().toDouble())
482
500
  }
483
-
501
+
484
502
  oldRequestId?.let {
485
- NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
503
+ NetworkInspector.reportResponseEnd(it, metrics.getTotalBytesReceived())
486
504
  SseNetworkMetricsTracker.clear(it)
487
505
  }
488
-
489
- try {
490
- // Set SSE headers explicitly for Network Inspector visibility and encoding control.
491
- val requestBuilder = Request.Builder()
492
- .url(currentConfig.url)
493
- .header("Accept", "text/event-stream")
494
- .header("Cache-Control", "no-cache")
495
-
496
- // Populate config headers first, filtering out Last-Event-ID and Accept-Encoding
497
- currentConfig.headers?.forEach { (k, v) ->
498
- if (!k.equals("Last-Event-ID", ignoreCase = true) && !k.equals("Accept-Encoding", ignoreCase = true)) {
499
- requestBuilder.header(k, v)
500
- }
501
- }
502
-
503
- currentLastId?.let {
504
- if (it.isNotEmpty()) requestBuilder.header("Last-Event-ID", it)
505
- }
506
506
 
507
- if (currentConfig.method == HttpMethod.POST) {
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)
513
- requestBuilder.post(body)
514
- }
515
-
516
- requestBuilder.tag(String::class.java, newRequestId)
517
- val request = requestBuilder.build()
507
+ try {
508
+ val request = SseConnectionHandler.buildRequest(currentConfig, currentLastId, newRequestId)
518
509
  NetworkInspector.reportRequestStart(newRequestId, request)
519
-
510
+
520
511
  val newEventSource = connectionHandler.createEventSource(safeClient, request, newRequestId)
521
512
  synchronized(this) {
522
513
  // Ensure socket is cancelled if stop() or dispose() raced with socket initialization
@@ -527,10 +518,9 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
527
518
  }
528
519
  }
529
520
  } 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).
532
- Log.e(TAG, "Failed to create SSE connection request: ${e.message}", e)
533
- failAndStop("Invalid connection request: ${e.message}", -1.0)
521
+ // Handles IllegalArgumentException (URL/headers), NullPointerException, and IllegalStateException
522
+ // without catching/suppressing fatal JVM errors (e.g. OutOfMemoryError, VirtualMachineError).
523
+ failAndStop("Invalid connection request: ${e.message}", SseHttpStatus.UNKNOWN_DOUBLE)
534
524
  }
535
525
  }
536
526
 
@@ -539,56 +529,51 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
539
529
  if (requestId != this@NitroSse.requestId) return@post
540
530
  consecutiveAuthErrors.set(0)
541
531
  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
- }
532
+ metrics.recordOpen(
533
+ statusCode = response.code,
534
+ isReconnect = currentState.get() == SseState.RECONNECTING,
535
+ now = System.currentTimeMillis().toDouble()
536
+ )
549
537
  updateState(SseState.OPEN)
550
- eventBuffer.push(SseEvent(SseEventType.OPEN, null, null, null, null, null, response.code.toDouble(), null, null))
538
+ eventBuffer.push(
539
+ SseEvent(
540
+ SseEventType.OPEN,
541
+ null,
542
+ null,
543
+ null,
544
+ null,
545
+ null,
546
+ response.code.toDouble(),
547
+ null,
548
+ null
549
+ )
550
+ )
551
551
  }
552
552
  }
553
553
 
554
554
  override fun connectionDidReceiveDataChunk(decompressedBytes: Long, requestId: String) {
555
555
  synchronized(this) {
556
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
- }
557
+ metrics.recordDataChunk(decompressedBytes, requestId, System.currentTimeMillis().toDouble())
569
558
  }
570
559
  }
571
560
 
572
561
  override fun connectionDidParseLines(count: Int, requestId: String) {
573
562
  synchronized(this) {
574
563
  if (requestId != this.requestId) return
575
- linesParsed += count.toDouble()
564
+ metrics.recordLinesParsed(count)
576
565
  }
577
566
  }
578
567
 
579
568
  override fun connectionDidEncounterParseError(requestId: String) {
580
- sseDispatcher?.post {
581
- if (requestId != this@NitroSse.requestId) return@post
582
- synchronized(this@NitroSse) {
583
- parseErrors += 1.0
584
- disconnectReason = SseDisconnectReason.PARSER_ERROR
585
- }
569
+ synchronized(this) {
570
+ if (requestId != this.requestId) return
571
+ metrics.recordParseError()
586
572
  }
587
573
  }
588
574
 
589
575
  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
576
+ if (requestId != this@NitroSse.requestId) return
592
577
  // Spec-compliant logical byte accounting (UTF-8 payload: data + event + id + comment).
593
578
  // Matches iOS (NitroSse.swift) and JS Mock (MockSseEngine.ts). Raw wire headers/framing
594
579
  // are intentionally excluded to maintain cross-platform parity.
@@ -598,55 +583,26 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
598
583
  val currentConfig: SseConfig?
599
584
  synchronized(this@NitroSse) {
600
585
  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
586
  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
620
- }
621
- }
622
- lastActivityTime = now
587
+ metrics.recordMessage(encodedDataSize, eventTypeSize, System.currentTimeMillis().toDouble())
623
588
  }
624
589
  val parsedData = if (currentConfig?.autoParseJSON == true) JsonUtils.parseJsonToAnyMap(data) else null
625
590
  sseDispatcher?.post {
626
591
  if (requestId != this@NitroSse.requestId) return@post
627
- eventBuffer.push(SseEvent(SseEventType.MESSAGE, data, parsedData, id, type, null, 200.0, null, null))
592
+ eventBuffer.push(
593
+ SseEvent(SseEventType.MESSAGE, data, parsedData, id, type, null, SseHttpStatus.OK_DOUBLE, null, null)
594
+ )
628
595
  }
629
596
  }
630
597
 
631
598
  override fun connectionDidReceiveComment(comment: String, requestId: String) {
632
- val currentRid = synchronized(this@NitroSse) { this@NitroSse.requestId }
633
- if (requestId != currentRid) return
599
+ if (requestId != this@NitroSse.requestId) return
634
600
  val commentBytes = comment.utf8Size()
635
601
  synchronized(this@NitroSse) {
636
602
  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
603
+ metrics.recordComment(commentBytes, System.currentTimeMillis().toDouble())
648
604
  }
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.
605
+ // Note (v4.0 roadmap): Avoid pushing HEARTBEAT event across JSI; use internal watchdog or onHeartbeat.
650
606
  sseDispatcher?.post {
651
607
  if (requestId != this@NitroSse.requestId) return@post
652
608
  eventBuffer.push(SseEvent(SseEventType.HEARTBEAT, null, null, null, null, comment, null, null, null))
@@ -656,7 +612,12 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
656
612
  override fun connectionDidReceiveRetry(retryMs: Long, requestId: String) {
657
613
  synchronized(this@NitroSse) {
658
614
  if (requestId != this@NitroSse.requestId) return
659
- serverRetryDelayMs = retryMs.toDouble()
615
+ metrics.recordServerRetryDelay(retryMs)
616
+ }
617
+ // reconnectStrategy is confined to sseDispatcher (nextDelay/reset run there); FIFO ordering
618
+ // guarantees this update lands before any subsequent close/fail callback from the same stream.
619
+ sseDispatcher?.post {
620
+ if (requestId != this@NitroSse.requestId) return@post
660
621
  reconnectStrategy.updateRetryInterval(retryMs.toDouble())
661
622
  }
662
623
  }
@@ -666,163 +627,111 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
666
627
  synchronized(this@NitroSse) {
667
628
  if (requestId != this@NitroSse.requestId) return
668
629
  if (newId != null && newId != this@NitroSse.lastProcessedId) {
669
- totalBytesReceived.addAndGet(newId.utf8Size())
630
+ metrics.recordLastEventIdBytes(newId.utf8Size())
670
631
  }
671
632
  this@NitroSse.lastProcessedId = newId
672
633
  }
673
634
  }
674
635
 
675
- override fun connectionDidFail(t: Throwable?, response: Response?, requestId: String) {
676
- connectionDidFail(t, response, null, requestId)
636
+ private fun clearFailedRequestAndReportInspector() {
637
+ val currentRequestId = synchronized(this) {
638
+ val id = this.requestId
639
+ metrics.accumulateGzipRawBytesOffset(id)
640
+ this.requestId = null
641
+ id
642
+ }
643
+ currentRequestId?.let {
644
+ NetworkInspector.reportRequestFailed(it, false)
645
+ SseNetworkMetricsTracker.clear(it)
646
+ }
677
647
  }
678
648
 
679
- override fun connectionDidFail(t: Throwable?, response: Response?, errorBody: String?, requestId: String) {
680
- sseDispatcher?.post {
681
- // Note on Stale Callback Protection:
682
- // Android uses a unique UUID `requestId` per connection attempt rather than an integer `attemptVersion`.
683
- // When a connection fails, stops, or restarts, `this@NitroSse.requestId` is immediately cleared (set to null)
684
- // or replaced with a new UUID. Thus, any delayed or asynchronous error/close callbacks from a canceled/previous
685
- // socket are safely and strictly rejected by `if (requestId != this@NitroSse.requestId) return@post`.
686
- if (requestId != this@NitroSse.requestId || !isRunning.get()) return@post
687
- val statusCode = response?.code ?: -1
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
-
693
- synchronized(this@NitroSse) {
694
- connectedAt = null
695
- if (statusCode != -1) {
696
- lastStatusCode = statusCode.toDouble()
697
- }
698
- lastErrorTime = System.currentTimeMillis().toDouble()
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
- }
710
- }
711
-
712
- val currentRequestId = synchronized(this@NitroSse) {
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
- }
720
- this@NitroSse.requestId = null
721
- id
722
- }
723
- currentRequestId?.let {
724
- NetworkInspector.reportRequestFailed(it, false)
725
- SseNetworkMetricsTracker.clear(it)
726
- }
649
+ private fun pushErrorEvent(
650
+ message: String,
651
+ statusCode: Double?,
652
+ retry: Double? = null,
653
+ data: String? = null
654
+ ) {
655
+ eventBuffer.push(SseEvent(SseEventType.ERROR, data, null, null, null, message, statusCode, retry, null))
656
+ }
727
657
 
728
- if (statusCode == 204) {
729
- failAndStop("No Content (204). Stopping.", 204.0)
730
- return@post
658
+ private fun applyFailureDecision(decision: SseFailureDecision, errorBody: String?) {
659
+ when (decision) {
660
+ is SseFailureDecision.FailAndStop ->
661
+ failAndStop(decision.message, decision.statusCode, errorBody)
662
+ is SseFailureDecision.AuthLimitReached -> {
663
+ consecutiveAuthErrors.incrementAndGet()
664
+ failAndStop(decision.message, decision.statusCode, errorBody)
731
665
  }
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
666
+ is SseFailureDecision.AuthRetry -> {
667
+ consecutiveAuthErrors.incrementAndGet()
668
+ pushErrorEvent(decision.message, decision.statusCode, data = errorBody)
669
+ scheduleReconnect(true, connectionAttemptVersion.get())
739
670
  }
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
671
+ is SseFailureDecision.RetryAfter -> {
672
+ pushErrorEvent(decision.message, decision.statusCode, decision.delayMs.toDouble(), data = errorBody)
673
+ scheduleReconnect(true, connectionAttemptVersion.get(), decision.delayMs)
745
674
  }
746
-
747
- val maxRetries = synchronized(this@NitroSse) { config?.maxAuthRetries?.toInt() ?: DEFAULT_MAX_AUTH_RETRIES }
748
- // Handle 401/403 with async token refresh up to maxAuthRetries.
749
- if (statusCode == 401 || statusCode == 403) {
750
- val hasInterceptor = synchronized(this@NitroSse) { requestInterceptor != null }
751
- if (!hasInterceptor) {
752
- failAndStop("Auth Error ($statusCode) - No interceptor provided. Stopping.", statusCode.toDouble())
753
- return@post
754
- }
755
- val retries = consecutiveAuthErrors.incrementAndGet()
756
- if (retries > maxRetries) {
757
- failAndStop("Auth Error ($statusCode) - Retry limit reached ($maxRetries). Stopping.", statusCode.toDouble())
758
- return@post
759
- }
760
- eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "Auth Error ($statusCode) - Retry $retries/$maxRetries. Refreshing token...", statusCode.toDouble(), null, null))
675
+ is SseFailureDecision.RateLimitBackoff -> {
676
+ pushErrorEvent(decision.message, decision.statusCode, data = errorBody)
761
677
  scheduleReconnect(true, connectionAttemptVersion.get())
762
- return@post
763
678
  }
764
-
765
- val isFatal = (statusCode in 400..499 && statusCode != 401 && statusCode != 403 && statusCode != 408 && statusCode != 429)
766
- if (isFatal) {
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."
679
+ is SseFailureDecision.TransientRetry -> {
680
+ // Map request timeout to STALE state before scheduling reconnection.
681
+ // OkHttp readTimeout acts as watchdog; emitting STALE notifies JS listeners before RECONNECTING.
682
+ if (decision.markStale) {
683
+ updateState(SseState.STALE)
772
684
  }
773
- failAndStop(finalMessage, statusCode.toDouble())
774
- return@post
775
- }
776
-
777
- // Schedule non-blocking Retry-After delay on dispatcher.
778
- val retryAfterMillis = SseReconnectStrategy.extractRetryAfterMillis(response)
779
- if ((statusCode == 429 || statusCode == 503) && retryAfterMillis != null) {
780
- val maxInterval = synchronized(this@NitroSse) { (config?.maxRetryIntervalMs ?: 30000.0).toLong() }
781
- val boundedRetryAfter = retryAfterMillis.coerceIn(0L, maxInterval)
782
- val jitter = (500 + Random.nextInt(1001)).toLong()
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)
786
- return@post
787
- }
788
-
789
- if (statusCode == 429) {
790
- eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "Rate Limited (429). Retrying with backoff...", 429.0, null, null))
685
+ pushErrorEvent(decision.message, decision.statusCode, data = errorBody)
791
686
  scheduleReconnect(true, connectionAttemptVersion.get())
792
- return@post
793
687
  }
688
+ }
689
+ }
794
690
 
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.
798
- if (isTimeout) {
799
- updateState(SseState.STALE)
800
- }
691
+ override fun connectionDidFail(t: Throwable?, response: Response?, errorBody: String?, requestId: String) {
692
+ sseDispatcher?.post {
693
+ // Android uses a unique UUID `requestId` per attempt alongside `connectionAttemptVersion`.
694
+ // Delayed callbacks from a previous socket are rejected by `requestId != this@NitroSse.requestId`.
695
+ if (requestId != this@NitroSse.requestId || !isRunning.get()) return@post
801
696
 
802
- val defaultErrorMsg = when {
803
- statusCode >= 500 && !errorBody.isNullOrBlank() -> "Server Error ($statusCode): ${errorBody.trim()}"
804
- else -> t?.message ?: "Link lost ($statusCode)"
805
- }
697
+ val context = SseFailureClassifier.buildContext(t, response, errorBody)
698
+ metrics.recordFailure(
699
+ statusCode = context.statusCode,
700
+ disconnectReason = SseFailureClassifier.disconnectReason(context),
701
+ errorCode = SseFailureClassifier.errorCodeString(context),
702
+ now = System.currentTimeMillis().toDouble()
703
+ )
704
+ clearFailedRequestAndReportInspector()
806
705
 
807
- // Teardown and reconnect on stream or socket failure.
808
- eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, defaultErrorMsg, if (statusCode != -1) statusCode.toDouble() else null, null, null))
809
- scheduleReconnect(true, connectionAttemptVersion.get())
706
+ val (hasInterceptor, maxAuthRetries, maxRetryIntervalMs) = synchronized(this@NitroSse) {
707
+ Triple(
708
+ requestInterceptor != null,
709
+ config?.maxAuthRetries?.toInt() ?: DEFAULT_MAX_AUTH_RETRIES,
710
+ (config?.maxRetryIntervalMs ?: DEFAULT_MAX_RETRY_INTERVAL_MS).toLong()
711
+ )
712
+ }
713
+ val policy = SseFailurePolicyInput(
714
+ hasInterceptor = hasInterceptor,
715
+ nextAuthAttempt = consecutiveAuthErrors.get() + 1,
716
+ maxAuthRetries = maxAuthRetries,
717
+ maxRetryIntervalMs = maxRetryIntervalMs
718
+ )
719
+ val normalizedErrorBody = errorBody?.takeIf { it.isNotEmpty() }
720
+ applyFailureDecision(SseFailureClassifier.classify(context, policy), normalizedErrorBody)
810
721
  }
811
722
  }
812
723
 
813
724
  override fun connectionDidClose(requestId: String) {
814
725
  sseDispatcher?.post {
815
726
  if (requestId != this@NitroSse.requestId || !isRunning.get()) return@post
816
- synchronized(this@NitroSse) {
817
- connectedAt = null
818
- }
727
+ metrics.clearConnectedAt()
819
728
  clearActiveRequestAndReportEnd()
820
729
  scheduleReconnect(false, connectionAttemptVersion.get())
821
730
  }
822
731
  }
823
732
 
824
- private fun failAndStop(message: String, statusCode: Double? = null) {
825
- eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, message, statusCode, null, null))
733
+ private fun failAndStop(message: String, statusCode: Double? = null, data: String? = null) {
734
+ eventBuffer.push(SseEvent(SseEventType.ERROR, data, null, null, null, message, statusCode, null, null))
826
735
  updateState(SseState.FAILED)
827
736
  stopInternal()
828
737
  }
@@ -831,7 +740,6 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
831
740
  if (!isRunning.get() || attemptVersion != connectionAttemptVersion.get()) return
832
741
  if (reconnectStrategy.hasReachedMaxAttempts()) {
833
742
  val maxAttempts = reconnectStrategy.currentReconnectAttempts
834
- Log.d(TAG, "Max reconnection attempts reached ($maxAttempts). Stopping.")
835
743
  failAndStop("Max reconnection attempts reached ($maxAttempts).")
836
744
  return
837
745
  }
@@ -841,9 +749,7 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
841
749
  } else {
842
750
  reconnectStrategy.nextDelay(isError)
843
751
  }
844
- synchronized(this) {
845
- lastReconnectDelayMs = safeReconnectDelay.toDouble()
846
- }
752
+ metrics.recordReconnectDelay(safeReconnectDelay.toDouble())
847
753
  // Increment attempt version before scheduling to invalidate pending tasks from previous cycles
848
754
  val newAttemptVersion = connectionAttemptVersion.incrementAndGet()
849
755
  updateState(SseState.RECONNECTING)
@@ -856,9 +762,7 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
856
762
  }
857
763
 
858
764
  private fun stopInternal() {
859
- synchronized(this) {
860
- connectedAt = null
861
- }
765
+ metrics.clearConnectedAt()
862
766
  isRunning.set(false)
863
767
  connectionAttemptVersion.incrementAndGet()
864
768
  performInternalCleanup()
@@ -871,15 +775,34 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
871
775
  }
872
776
 
873
777
  override fun restart() {
874
- synchronized(this) { config } ?: return
778
+ synchronized(this) {
779
+ config ?: return
780
+ metrics.clearConnectedAt()
781
+ }
782
+ // Claim running state and a new attempt version synchronously on the caller thread (mirrors start()/stop()).
783
+ // A subsequent stop()/dispose() bumps the version and thereby invalidates this queued restart, instead of
784
+ // the restart task resurrecting a stream the caller has already stopped.
785
+ isRunning.set(true)
786
+ val version = connectionAttemptVersion.incrementAndGet()
787
+ // Detach the current socket immediately so its late callbacks are rejected as stale (requestId cleared).
788
+ clearActiveRequestAndReportEnd()
789
+ // Deliver events buffered from the retired connection before announcing RECONNECTING so JS observes
790
+ // them in chronological order (not batched together with / after the new state transition).
791
+ eventBuffer.flush()
792
+ updateState(SseState.RECONNECTING)
875
793
  val task = {
876
- stopInternal()
877
- isRunning.set(true)
878
- val version = connectionAttemptVersion.incrementAndGet()
879
- updateState(SseState.RECONNECTING)
880
- reconnectStrategy.reset()
881
- requestId = null
882
- performConnection(version)
794
+ // An explicit restart supersedes any pending hibernation resume intent (mirrors stop()).
795
+ wasRunningBeforeNetworkLoss = false
796
+ wasRunningBeforePaused = false
797
+ // Run cleanup only if a newer cycle on [sseDispatcher] has not already cleaned up past `version`
798
+ // (prevents a stale queued restart() from cancelling a connection installed inline on [sseDispatcher]),
799
+ // while still cleaning up retired timers when JS start() supersedes a queued restart().
800
+ if (lastCleanupVersion < version) {
801
+ performInternalCleanup()
802
+ }
803
+ if (isRunning.get() && version == connectionAttemptVersion.get()) {
804
+ connectWithFreshBackoff(version)
805
+ }
883
806
  }
884
807
  if (sseDispatcher?.isCurrentDispatcher() == true) {
885
808
  task()
@@ -895,9 +818,10 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
895
818
  override fun stop() {
896
819
  synchronized(this) {
897
820
  if (isRunning.get()) {
898
- disconnectReason = SseDisconnectReason.USER_STOP
821
+ metrics.recordUserStop()
822
+ } else {
823
+ metrics.clearConnectedAt()
899
824
  }
900
- connectedAt = null
901
825
  }
902
826
  isRunning.set(false)
903
827
  val stopVersion = connectionAttemptVersion.incrementAndGet()
@@ -907,10 +831,10 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
907
831
  if (connectionAttemptVersion.get() == stopVersion) {
908
832
  wasRunningBeforeNetworkLoss = false
909
833
  wasRunningBeforePaused = false
834
+ // Preserve FAILED as terminal state. When the JS dispatcher is destroyed, dispose() has already
835
+ // cleared this queue, so no state event needs to be (or can be) delivered.
910
836
  if (!isDispatcherDestroyed && currentState.get() != SseState.FAILED) {
911
837
  updateState(SseState.CLOSED)
912
- } else if (isDispatcherDestroyed) {
913
- currentState.set(SseState.CLOSED)
914
838
  }
915
839
  performInternalCleanup()
916
840
  }
@@ -925,28 +849,30 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
925
849
  private fun clearActiveRequestAndReportEnd() {
926
850
  val currentRequestId = synchronized(this) {
927
851
  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
- }
852
+ metrics.accumulateGzipRawBytesOffset(id)
934
853
  eventSource?.cancel()
935
854
  eventSource = null
936
855
  requestId = null
937
856
  id
938
857
  }
939
858
  currentRequestId?.let {
940
- NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
859
+ NetworkInspector.reportResponseEnd(it, metrics.getTotalBytesReceived())
941
860
  SseNetworkMetricsTracker.clear(it)
942
861
  }
943
862
  }
944
863
 
864
+ private fun cancelNetworkRestartDebounce() {
865
+ networkRestartRunnable?.let { sseDispatcher?.removeCallbacks(it) }
866
+ networkRestartRunnable = null
867
+ }
868
+
945
869
  /**
946
870
  * Cleans up timeouts, active socket, and flushes any pending buffered events.
947
871
  * Always invoked within `sseDispatcherThread` execution context (from lifecycle, network, or stop).
948
872
  */
949
873
  private fun performInternalCleanup() {
874
+ lastCleanupVersion = maxOf(lastCleanupVersion, connectionAttemptVersion.get())
875
+ cancelNetworkRestartDebounce()
950
876
  interceptorTimeoutRunnable?.let { sseDispatcher?.removeCallbacks(it) }
951
877
  interceptorTimeoutRunnable = null
952
878
  reconnectStrategy.reset()
@@ -967,16 +893,20 @@ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDe
967
893
  if (!isDisposed.compareAndSet(false, true)) {
968
894
  return
969
895
  }
970
- Log.d(TAG, "Disposing NitroSse instance and cleaning up resources...")
971
-
972
896
  isRunning.set(false)
973
897
  connectionAttemptVersion.incrementAndGet()
898
+ // The dispatcher queue is discarded below, so no queued stop() task can publish the terminal state.
899
+ // Keep getState() accurate (silently: the JS event callback is already unusable) while preserving FAILED.
900
+ if (isDispatcherDestroyed) {
901
+ currentState.updateAndGet { if (it == SseState.FAILED) it else SseState.CLOSED }
902
+ }
974
903
 
975
904
  synchronized(this) {
976
905
  requestInterceptor = null
977
906
  config = null
978
907
  }
979
908
 
909
+ cancelNetworkRestartDebounce()
980
910
  interceptorTimeoutRunnable?.let { sseDispatcher?.removeCallbacks(it) }
981
911
  interceptorTimeoutRunnable = null
982
912