react-native-nitro-sse 2.3.2 → 2.4.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 (60) hide show
  1. package/README.md +1 -1
  2. package/android/build.gradle +11 -0
  3. package/android/jacoco.gradle +33 -0
  4. package/android/src/main/java/com/margelo/nitro/nitrosse/AndroidSseDispatcher.kt +27 -0
  5. package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +78 -0
  6. package/android/src/main/java/com/margelo/nitro/nitrosse/NetworkInspector.kt +6 -3
  7. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +309 -656
  8. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSsePackage.kt +4 -0
  9. package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +114 -0
  10. package/android/src/main/java/com/margelo/nitro/nitrosse/SseDispatcher.kt +14 -0
  11. package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +102 -0
  12. package/android/src/main/java/com/margelo/nitro/nitrosse/SseLifecycleManager.kt +52 -0
  13. package/android/src/main/java/com/margelo/nitro/nitrosse/SseNetworkMonitor.kt +87 -0
  14. package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +80 -0
  15. package/ios/NitroSse.swift +433 -637
  16. package/ios/SseConfig+CopyWith.swift +46 -0
  17. package/ios/SseConnectionHandler.swift +114 -0
  18. package/ios/SseDispatchQueueDispatcher.swift +38 -0
  19. package/ios/SseDispatcher.swift +18 -0
  20. package/ios/SseEventBuffer.swift +79 -0
  21. package/ios/SseLifecycleManager.swift +118 -0
  22. package/ios/SseNetworkMonitor.swift +84 -0
  23. package/ios/SseReconnectStrategy.swift +99 -0
  24. package/lib/module/NitroSseClient.js +38 -3
  25. package/lib/module/NitroSseClient.js.map +1 -1
  26. package/lib/typescript/src/NitroSse.nitro.d.ts +5 -1
  27. package/lib/typescript/src/NitroSse.nitro.d.ts.map +1 -1
  28. package/lib/typescript/src/NitroSseClient.d.ts +4 -1
  29. package/lib/typescript/src/NitroSseClient.d.ts.map +1 -1
  30. package/lib/typescript/src/SseInterface.d.ts +10 -1
  31. package/lib/typescript/src/SseInterface.d.ts.map +1 -1
  32. package/nitrogen/generated/android/c++/JFunc_void_std__vector_SseEvent_.hpp +2 -0
  33. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +9 -0
  34. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.hpp +1 -0
  35. package/nitrogen/generated/android/c++/JSseEvent.hpp +9 -3
  36. package/nitrogen/generated/android/c++/JSseEventType.hpp +3 -0
  37. package/nitrogen/generated/android/c++/JSseState.hpp +76 -0
  38. 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 +0 -2
  39. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/Func_void_std__vector_SseEvent_.kt +0 -2
  40. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HybridNitroSseSpec.kt +6 -0
  41. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEvent.kt +9 -4
  42. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEventType.kt +2 -1
  43. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseState.kt +29 -0
  44. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +27 -0
  45. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +3 -0
  46. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +11 -0
  47. package/nitrogen/generated/ios/swift/HybridNitroSseSpec.swift +1 -0
  48. package/nitrogen/generated/ios/swift/HybridNitroSseSpec_cxx.swift +12 -0
  49. package/nitrogen/generated/ios/swift/SseEvent.swift +12 -1
  50. package/nitrogen/generated/ios/swift/SseEventType.swift +4 -0
  51. package/nitrogen/generated/ios/swift/SseState.swift +64 -0
  52. package/nitrogen/generated/shared/c++/HybridNitroSseSpec.cpp +1 -0
  53. package/nitrogen/generated/shared/c++/HybridNitroSseSpec.hpp +4 -0
  54. package/nitrogen/generated/shared/c++/SseEvent.hpp +9 -2
  55. package/nitrogen/generated/shared/c++/SseEventType.hpp +4 -0
  56. package/nitrogen/generated/shared/c++/SseState.hpp +100 -0
  57. package/package.json +3 -3
  58. package/src/NitroSse.nitro.ts +6 -1
  59. package/src/NitroSseClient.ts +42 -2
  60. package/src/SseInterface.ts +25 -1
@@ -1,275 +1,182 @@
1
1
  package com.margelo.nitro.nitrosse
2
2
 
3
3
  import android.os.Handler
4
- import android.os.Looper
5
4
  import android.util.Log
6
5
  import com.facebook.proguard.annotations.DoNotStrip
7
6
  import okhttp3.OkHttpClient
8
7
  import okhttp3.Request
9
8
  import okhttp3.Response
10
- import okhttp3.Interceptor
11
- import okhttp3.ResponseBody
12
9
  import okhttp3.MediaType.Companion.toMediaType
13
10
  import okhttp3.RequestBody.Companion.toRequestBody
14
11
  import okhttp3.sse.EventSource
15
- import okhttp3.sse.EventSources
16
- import okhttp3.sse.EventSourceListener
17
- import okio.Buffer
18
- import okio.ForwardingSource
19
- import okio.buffer
20
- import com.margelo.nitro.core.AnyMap
21
- import org.json.JSONObject
22
- import org.json.JSONArray
23
- import androidx.lifecycle.DefaultLifecycleObserver
24
- import androidx.lifecycle.LifecycleOwner
25
- import androidx.lifecycle.ProcessLifecycleOwner
12
+ import com.margelo.nitro.NitroModules
26
13
  import java.util.concurrent.TimeUnit
27
14
  import java.util.concurrent.atomic.AtomicBoolean
28
15
  import java.util.concurrent.atomic.AtomicLong
29
16
  import java.util.concurrent.atomic.AtomicInteger
30
17
  import java.util.UUID
31
18
  import kotlin.random.Random
32
- import android.content.Context
33
- import android.net.ConnectivityManager
34
- import android.net.Network
35
19
  import android.net.NetworkCapabilities
36
- import android.net.NetworkRequest
37
- import com.margelo.nitro.NitroModules
38
20
 
39
21
  /**
40
- * NitroSse implements a high-performance SSE client using OkHttp.
41
- *
42
- * ARCHITECTURE DECISIONS:
43
- * 1. Threading: Uses a dedicated HandlerThread (sseHandlerThread) to offload all network events
44
- * and buffer management from the Main/JS threads. This prevents UI freezes during high-frequency bursts.
45
- * 2. Backpressure: Implements a producer-consumer pattern with an internal buffer and batching timer.
46
- * This solves the "Bridge Flooding" problem by grouping multiple events into a single JSI call.
47
- * 3. Reliability: Uses exponential backoff with jitter and respects 'Retry-After' headers to
48
- * prevent DoS-ing the server while ensuring resilient reconnections.
49
- * 4. Heartbeat: Since OkHttp-SSE obscures comments, we use a Network Interceptor to manually
50
- * detect ':' bytes, enabling JS-side watchdog timers.
51
- * 5. Lifecycle Management: Implements the Hibernation pattern. When the app enters the background,
52
- * we stop the stream to save battery. It automatically resumes when returning to foreground.
22
+ * Core Android implementation of [HybridNitroSseSpec] managing Server-Sent Events (SSE).
23
+ *
24
+ * Coordinates OkHttp SSE connection state, exponential backoff retries, event buffering,
25
+ * network interface transitions, and Android app lifecycle hibernation. Uses a single-threaded
26
+ * background [SseDispatcher] to ensure thread-safe state mutations and avoid blocking the JS UI thread.
53
27
  */
54
28
  @DoNotStrip
55
- class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
56
- @Volatile private var client: OkHttpClient? = null
57
- @Volatile private var eventSource: EventSource? = null
58
- @Volatile private var config: SseConfig? = null
59
- @Volatile private var requestId: String? = null
60
- @Volatile private var onEventsCallback: ((events: Array<SseEvent>) -> Unit)? = null
29
+ class NitroSse @DoNotStrip constructor() : HybridNitroSseSpec(), SseConnectionDelegate {
30
+
31
+ // Secondary constructor for unit testing to inject virtual-time dispatchers without spawning HandlerThreads
32
+ internal constructor(dispatcher: SseDispatcher) : this() {
33
+ this.sseDispatcher = dispatcher
34
+ }
35
+ private var client: OkHttpClient? = null
36
+ private var eventSource: EventSource? = null
37
+ private var config: SseConfig? = null
38
+ private var requestId: String? = null
61
39
 
62
40
  private val isRunning = AtomicBoolean(false)
63
- @Volatile private var isDispatcherDestroyed = false
41
+ private var isDispatcherDestroyed = false
64
42
  private var wasRunningBeforePaused = false
65
43
  private val consecutiveAuthErrors = AtomicInteger(0)
66
44
  private val maxAuthRetries = 3
67
- private var sseHandlerThread: android.os.HandlerThread? = null
68
- private var sseHandler: Handler? = null
69
-
70
- private val eventBuffer = mutableListOf<SseEvent>()
71
- private var isFlushPending = AtomicBoolean(false)
72
- private val flushRunnable = java.lang.Runnable { flushBufferToJs() }
73
45
 
74
- private var backoffCounter = 0
75
- private val isAppInBackground = AtomicBoolean(false)
76
- private var currentReconnectAttempts = 0
77
- @Volatile private var lastProcessedId: String? = null
46
+ private var sseDispatcherThread: android.os.HandlerThread? = null
47
+ internal var sseDispatcher: SseDispatcher? = null
78
48
 
79
49
  private val totalBytesReceived = AtomicLong(0)
80
50
  private val connectionAttemptVersion = AtomicInteger(0)
81
- private var reconnectCount = 0
51
+ private var lastProcessedId: String? = null
52
+ private var currentState = java.util.concurrent.atomic.AtomicReference(SseState.IDLE)
53
+ private val totalReconnectCount = AtomicInteger(0)
82
54
  private var lastErrorTime: Double? = null
83
55
  private var lastErrorCode: String? = null
84
-
85
- private var hasSubscribedToLifecycle = false
86
-
87
- private var networkCallback: ConnectivityManager.NetworkCallback? = null
88
56
  private var wasRunningBeforeNetworkLoss = false
89
57
  private var lastNetworkCapabilities: NetworkCapabilities? = null
90
58
 
59
+ private lateinit var eventBuffer: SseEventBuffer
60
+ private val reconnectStrategy = SseReconnectStrategy()
61
+ private var networkMonitor: SseNetworkMonitor? = null
62
+ private var lifecycleManager: SseLifecycleManager? = null
63
+ private val connectionHandler = SseConnectionHandler(this)
64
+ private val mainDispatcher = AndroidSseDispatcher(Handler(android.os.Looper.getMainLooper()))
65
+
91
66
  companion object {
92
67
  private const val TAG = "NitroSse"
68
+ }
93
69
 
94
- internal fun jsonObjectToMap(jsonObject: JSONObject): Map<String, Any?> {
95
- val map = mutableMapOf<String, Any?>()
96
- val keys = jsonObject.keys()
97
- while (keys.hasNext()) {
98
- val key = keys.next()
99
- var value: Any? = jsonObject.get(key)
100
- if (value is JSONObject) {
101
- value = jsonObjectToMap(value)
102
- } else if (value is JSONArray) {
103
- value = jsonArrayToList(value)
104
- } else if (value == JSONObject.NULL) {
105
- value = null
106
- }
107
- map[key] = value
70
+ override fun setup(config: SseConfig, onEvent: (events: Array<SseEvent>) -> Unit) {
71
+ synchronized(this) {
72
+ this.config = config
73
+
74
+ if (sseDispatcher == null) {
75
+ sseDispatcherThread = android.os.HandlerThread("NitroSseThread").apply { start() }
76
+ sseDispatcher = AndroidSseDispatcher(Handler(sseDispatcherThread!!.looper))
108
77
  }
109
- return map
110
- }
111
78
 
112
- internal fun jsonArrayToList(jsonArray: JSONArray): List<Any?> {
113
- val list = mutableListOf<Any?>()
114
- for (i in 0 until jsonArray.length()) {
115
- var value: Any? = jsonArray.get(i)
116
- if (value is JSONObject) {
117
- value = jsonObjectToMap(value)
118
- } else if (value is JSONArray) {
119
- value = jsonArrayToList(value)
120
- } else if (value == JSONObject.NULL) {
121
- value = null
122
- }
123
- list.add(value)
79
+ if (!::eventBuffer.isInitialized) {
80
+ eventBuffer = SseEventBuffer(onEvent, sseDispatcher, mainDispatcher)
81
+ } else {
82
+ eventBuffer.setCallback(onEvent)
124
83
  }
125
- return list
126
- }
127
- }
128
-
129
- /**
130
- * Set up the NitroSse instance with configuration and an event callback.
131
- * This prepares the OkHttpClient and internal handler threads.
132
- *
133
- * @param config The SSE configuration containing URL, headers, and more.
134
- * @param onEvent Callback function to receive batched SSE events.
135
- */
136
- override fun setup(config: SseConfig, onEvent: (events: Array<SseEvent>) -> Unit) {
137
- this.config = config
138
- this.onEventsCallback = onEvent
139
-
140
- if (this.client == null) {
141
- val builder = OkHttpClient.Builder()
142
- .connectTimeout((config.connectionTimeoutMs ?: 15000.0).toLong(), TimeUnit.MILLISECONDS)
143
- .readTimeout((config.readTimeoutMs ?: 300000.0).toLong(), TimeUnit.MILLISECONDS)
144
- .addNetworkInterceptor(HeartbeatNetworkInterceptor(totalBytesReceived) {
145
- pushEventToBuffer(SseEvent(SseEventType.HEARTBEAT, null, null, null, null, "keep-alive", null, null))
146
- })
84
+ eventBuffer.configure(config.batchingIntervalMs ?: 0.0, config.maxBufferSize?.toInt() ?: 1000)
147
85
 
86
+ reconnectStrategy.configure(
87
+ config.retryIntervalMs ?: 1000.0,
88
+ config.maxRetryIntervalMs ?: 30000.0,
89
+ config.jitterFactor ?: 0.5,
90
+ (config.maxReconnectAttempts ?: -1.0).toInt()
91
+ )
148
92
 
149
- this.client = builder.build()
150
- }
93
+ if (this.client == null) {
94
+ val builder = OkHttpClient.Builder()
95
+ .connectTimeout((config.connectionTimeoutMs ?: 15000.0).toLong(), TimeUnit.MILLISECONDS)
96
+ .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
+ })
100
+ this.client = builder.build()
101
+ } else {
102
+ this.client = this.client!!.newBuilder()
103
+ .connectTimeout((config.connectionTimeoutMs ?: 15000.0).toLong(), TimeUnit.MILLISECONDS)
104
+ .readTimeout((config.readTimeoutMs ?: 300000.0).toLong(), TimeUnit.MILLISECONDS)
105
+ .build()
106
+ }
151
107
 
152
- if (sseHandlerThread == null) {
153
- sseHandlerThread = android.os.HandlerThread("NitroSseThread").apply { start() }
154
- sseHandler = Handler(sseHandlerThread!!.looper)
155
- }
156
-
157
- if (!hasSubscribedToLifecycle) {
158
- Handler(Looper.getMainLooper()).post {
159
- ProcessLifecycleOwner.get().lifecycle.addObserver(this)
160
- hasSubscribedToLifecycle = true
108
+ if (lifecycleManager == null) {
109
+ lifecycleManager = SseLifecycleManager(
110
+ lifecycleProvider = { androidx.lifecycle.ProcessLifecycleOwner.get().lifecycle },
111
+ mainDispatcher = mainDispatcher,
112
+ sseDispatcher = sseDispatcher!!,
113
+ onBackground = { handleAppBackground() },
114
+ onForeground = { handleAppForeground() }
115
+ )
116
+ lifecycleManager?.startObserving()
161
117
  }
162
118
  }
163
119
 
164
120
  if (config.monitorNetwork != false) {
165
- sseHandler?.post {
121
+ sseDispatcher?.post {
166
122
  startNetworkMonitoring()
167
123
  }
168
124
  } else {
169
- sseHandler?.post {
170
- stopNetworkMonitoring()
125
+ sseDispatcher?.post {
126
+ networkMonitor?.stop()
127
+ networkMonitor = null
171
128
  }
172
129
  }
173
130
  }
174
131
 
175
132
  private fun startNetworkMonitoring() {
176
- if (networkCallback != null) return
177
-
178
133
  val context = NitroModules.applicationContext ?: return
179
- val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager ?: return
180
-
181
- networkCallback = object : ConnectivityManager.NetworkCallback() {
182
- override fun onAvailable(network: Network) {
183
- val capabilities = connectivityManager.getNetworkCapabilities(network)
184
- handleNetworkChange(true, capabilities)
185
- }
186
-
187
- override fun onLost(network: Network) {
188
- handleNetworkChange(false, null)
189
- }
190
-
191
- override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) {
192
- handleNetworkChange(true, capabilities)
193
- }
194
- }
195
-
196
- try {
197
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
198
- connectivityManager.registerDefaultNetworkCallback(networkCallback!!)
199
- } else {
200
- val request = NetworkRequest.Builder()
201
- .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
202
- .build()
203
- connectivityManager.registerNetworkCallback(request, networkCallback!!)
134
+ if (networkMonitor == null) {
135
+ networkMonitor = SseNetworkMonitor(context, sseDispatcher) { isAvailable, capabilities ->
136
+ handleNetworkChange(isAvailable, capabilities)
204
137
  }
205
- } catch (e: SecurityException) {
206
- Log.e(TAG, "Failed to register network callback. Missing ACCESS_NETWORK_STATE permission.", e)
207
- networkCallback = null
208
- } catch (e: Exception) {
209
- Log.e(TAG, "Failed to register network callback.", e)
210
- networkCallback = null
211
138
  }
139
+ networkMonitor?.start()
212
140
  }
213
141
 
214
142
  private fun handleNetworkChange(isAvailable: Boolean, capabilities: NetworkCapabilities?) {
215
- sseHandler?.post {
216
- Log.d(TAG, "Network change: available=$isAvailable")
217
-
218
- if (isAvailable && capabilities != null) {
219
- if (wasRunningBeforeNetworkLoss) {
220
- Log.d(TAG, "Network restored. Resuming stream.")
221
- wasRunningBeforeNetworkLoss = false
222
- if (isAppInBackground.get() && config?.backgroundExecution != true) {
223
- wasRunningBeforePaused = true
224
- } else {
225
- start()
226
- }
227
- } else if (isRunning.get() && lastNetworkCapabilities != null) {
228
- // Check if interface changed (e.g. WiFi -> Cellular)
229
- val isWifi = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
230
- val isCellular = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
231
-
232
- val lastWifi = lastNetworkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ?: false
233
- val lastCellular = lastNetworkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ?: false
234
-
235
- if ((isWifi && !lastWifi) || (isCellular && !lastCellular)) {
236
- Log.d(TAG, "Network interface changed. Restarting stream.")
237
- restart()
238
- }
143
+ Log.d(TAG, "Network change: available=$isAvailable")
144
+ if (isAvailable && capabilities != null) {
145
+ if (wasRunningBeforeNetworkLoss) {
146
+ Log.d(TAG, "Network restored. Resuming stream.")
147
+ wasRunningBeforeNetworkLoss = false
148
+ if (lifecycleManager?.isAppInBackground == true && config?.backgroundExecution != true) {
149
+ wasRunningBeforePaused = true
150
+ } else {
151
+ start()
239
152
  }
240
- lastNetworkCapabilities = capabilities
241
- } else if (!isAvailable) {
242
- if (isRunning.get()) {
243
- Log.d(TAG, "Network lost. Hibernating.")
244
- wasRunningBeforeNetworkLoss = true
245
- isRunning.set(false)
246
- connectionAttemptVersion.incrementAndGet()
247
- performInternalCleanup()
153
+ } else if (isRunning.get() && lastNetworkCapabilities != null) {
154
+ val isWifi = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
155
+ val isCellular = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
156
+
157
+ val lastWifi = lastNetworkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ?: false
158
+ val lastCellular = lastNetworkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ?: false
159
+
160
+ if ((isWifi && !lastWifi) || (isCellular && !lastCellular)) {
161
+ Log.d(TAG, "Network interface changed. Restarting stream.")
162
+ restart()
248
163
  }
249
- lastNetworkCapabilities = null
250
164
  }
165
+ lastNetworkCapabilities = capabilities
166
+ } else if (!isAvailable) {
167
+ if (isRunning.get()) {
168
+ Log.d(TAG, "Network lost. Hibernating.")
169
+ wasRunningBeforeNetworkLoss = true
170
+ updateState(SseState.PAUSED)
171
+ isRunning.set(false)
172
+ connectionAttemptVersion.incrementAndGet()
173
+ performInternalCleanup()
174
+ }
175
+ lastNetworkCapabilities = null
251
176
  }
252
177
  }
253
178
 
254
- private fun stopNetworkMonitoring() {
255
- val callback = networkCallback ?: return
256
- try {
257
- val context = NitroModules.applicationContext
258
- val connectivityManager = context?.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
259
- connectivityManager?.unregisterNetworkCallback(callback)
260
- } catch (e: Exception) {
261
- Log.w(TAG, "Failed to unregister network callback: ${e.message}")
262
- }
263
- networkCallback = null
264
- lastNetworkCapabilities = null
265
- }
266
-
267
- /**
268
- * Called when the app enters the foreground.
269
- * Automatically resumes the stream if it was hibernated.
270
- */
271
- override fun onStart(owner: LifecycleOwner) {
272
- isAppInBackground.set(false)
179
+ private fun handleAppForeground() {
273
180
  if (wasRunningBeforePaused) {
274
181
  Log.d(TAG, "App foregrounded. Resuming NitroSse stream.")
275
182
  wasRunningBeforePaused = false
@@ -277,154 +184,76 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
277
184
  }
278
185
  }
279
186
 
280
- /**
281
- * Called when the app enters the background.
282
- * Hibernates the connection to save battery and resources.
283
- */
284
- override fun onStop(owner: LifecycleOwner) {
285
- isAppInBackground.set(true)
187
+ private fun handleAppBackground() {
286
188
  if (isRunning.get()) {
287
189
  if (config?.backgroundExecution == true) {
288
- Log.d(TAG, "App backgrounded. backgroundExecution is true, keeping NitroSse connection alive.")
190
+ Log.d(TAG, "App backgrounded. keeping connection alive.")
289
191
  return
290
192
  }
291
- Log.d(TAG, "App backgrounded. Hibernating NitroSse connection.")
193
+ Log.d(TAG, "App backgrounded. Hibernating.")
292
194
  wasRunningBeforePaused = true
195
+ updateState(SseState.PAUSED)
293
196
  isRunning.set(false)
294
197
  connectionAttemptVersion.incrementAndGet()
295
- sseHandler?.post {
198
+ sseDispatcher?.post {
296
199
  performInternalCleanup()
297
200
  }
298
201
  }
299
202
  }
300
203
 
301
- private fun pushEventToBuffer(event: SseEvent) {
302
- val batchInterval = config?.batchingIntervalMs ?: 0.0
303
- val bufferCapacity = config?.maxBufferSize?.toInt() ?: 1000
304
-
305
- var shouldFlush = false
306
- synchronized(eventBuffer) {
307
- eventBuffer.add(event)
308
- if (eventBuffer.size >= bufferCapacity) {
309
- shouldFlush = true
310
- }
311
- }
312
-
313
- sseHandler?.post {
314
- if (batchInterval <= 0 || shouldFlush) {
315
- sseHandler?.removeCallbacks(flushRunnable)
316
- flushBufferToJs()
317
- } else if (!isFlushPending.getAndSet(true)) {
318
- sseHandler?.postDelayed(flushRunnable, batchInterval.toLong())
319
- }
320
- }
321
- }
322
-
323
- private fun flushBufferToJs() {
324
- val eventsToEmit: Array<SseEvent>
325
- synchronized(eventBuffer) {
326
- if (eventBuffer.isEmpty()) {
327
- isFlushPending.set(false)
328
- return
329
- }
330
- eventsToEmit = eventBuffer.toTypedArray()
331
- eventBuffer.clear()
332
- }
333
- isFlushPending.set(false)
334
-
335
- onEventsCallback?.let { callback ->
336
- Handler(Looper.getMainLooper()).post {
337
- try {
338
- callback.invoke(eventsToEmit)
339
- } catch (e: Exception) {
340
- Log.e(TAG, "Error invoking onEventsCallback: ${e.message}")
341
- }
342
- }
343
- }
344
- }
345
-
346
- private fun parseJsonToAnyMap(data: String): AnyMap? {
347
- return try {
348
- val trimmed = data.trim()
349
- if (trimmed.startsWith("{")) {
350
- val jsonObject = JSONObject(trimmed)
351
- val map = jsonObjectToMap(jsonObject)
352
- AnyMap.fromMap(map, true)
353
- } else {
354
- // AnyMap represents a JS Object (Map).
355
- // If it's a JSON array or primitive, we currently don't support auto-parsing into AnyMap.
356
- null
357
- }
358
- } catch (e: Exception) {
359
- Log.w(TAG, "Failed to parse JSON: ${e.message}")
360
- null
361
- }
362
- }
363
-
364
- /**
365
- * Manually set the last seen event ID.
366
- * This will be used as the 'Last-Event-ID' header on the next connection attempt.
367
- */
368
204
  override fun setLastProcessedId(id: String) {
369
- this.lastProcessedId = id
205
+ synchronized(this) {
206
+ this.lastProcessedId = id
207
+ }
370
208
  }
371
209
 
372
- /**
373
- * Dynamically update the headers for subsequent connection attempts.
374
- */
375
210
  override fun updateHeaders(headers: Map<String, String>) {
376
211
  synchronized(this) {
377
212
  this.config?.let {
378
213
  this.config = it.copy(headers = headers)
379
- Log.d(TAG, "Headers updated manually")
380
214
  }
381
215
  }
382
216
  }
383
217
 
384
- /**
385
- * Provide current runtime statistics for the SSE connection.
386
- *
387
- * @return An SseStats snapshot with:
388
- * - the total bytes received (as Double),
389
- * - the total number of reconnects (as Double),
390
- * - the timestamp of the last error in milliseconds since epoch (nullable),
391
- * - the last error code or identifier (nullable).
392
- */
393
218
  override fun getStats(): SseStats {
394
- // getStats is called from JS thread, so we should sync with sseHandler thread
395
- // or coordinate carefully. Since we need to return immediately,
396
- // using the state as-is is okay IF all updates happen on a single thread
397
- // and we use synchronized or @Volatile.
398
219
  synchronized(this) {
399
220
  return SseStats(
400
221
  totalBytesReceived.get().toDouble(),
401
- reconnectCount.toDouble(),
222
+ totalReconnectCount.get().toDouble(),
402
223
  lastErrorTime,
403
224
  lastErrorCode
404
225
  )
405
226
  }
406
227
  }
407
228
 
408
- /**
409
- * Start the SSE connection.
410
- * This triggers the initial request and handles subsequent reconnections.
411
- */
229
+ override fun getState(): SseState {
230
+ return currentState.get()
231
+ }
232
+
233
+ private fun updateState(newState: SseState) {
234
+ val oldState = currentState.getAndSet(newState)
235
+ if (oldState != newState && ::eventBuffer.isInitialized) {
236
+ eventBuffer.push(SseEvent(SseEventType.STATE, null, null, null, null, null, null, null, newState))
237
+ }
238
+ }
239
+
412
240
  override fun start() {
413
- if (config == null) return
241
+ val currentConfig = synchronized(this) { config } ?: return
414
242
  if (!isRunning.compareAndSet(false, true)) return
415
243
 
416
244
  consecutiveAuthErrors.set(0)
417
245
  isDispatcherDestroyed = false
418
246
  val version = connectionAttemptVersion.incrementAndGet()
419
- sseHandler?.post {
420
- backoffCounter = 0
247
+ updateState(SseState.CONNECTING)
248
+ sseDispatcher?.post {
249
+ reconnectStrategy.reset()
421
250
  requestId = null
422
251
  performConnection(version)
423
252
  }
424
253
  }
425
254
 
426
255
  private fun performConnection(version: Int) {
427
- // Guard: connection attempt is discarded if client is stopped or a newer attempt is in progress
256
+ // Discard attempt if state has changed or a newer connection cycle was initiated
428
257
  if (!isRunning.get() || version != connectionAttemptVersion.get()) return
429
258
 
430
259
  val currentConfig = synchronized(this) { config } ?: return
@@ -434,18 +263,17 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
434
263
  val interceptorCompleted = AtomicBoolean(false)
435
264
  val timeoutMs = (currentConfig.connectionTimeoutMs ?: 15000.0).toLong()
436
265
 
437
- // Concurrency Safeguard: Prevents JS from hanging the native state machine indefinitely.
438
- // If the JS interceptor promise does not resolve within connectionTimeoutMs, we fail safely.
439
- sseHandler?.postDelayed({
266
+ // Enforce timeout guard on JS onBeforeRequest promise to prevent connection hangs
267
+ sseDispatcher?.postDelayed({
440
268
  if (interceptorCompleted.compareAndSet(false, true)) {
441
- handleInterceptorError(Exception("onBeforeRequest interceptor timed out after $timeoutMs ms"), version)
269
+ handleInterceptorError(Exception("onBeforeRequest timed out"), version)
442
270
  }
443
271
  }, timeoutMs)
444
272
 
445
273
  try {
446
274
  interceptor.invoke().then { promise2 ->
447
275
  promise2.then { newHeaders ->
448
- sseHandler?.post {
276
+ sseDispatcher?.post {
449
277
  if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
450
278
  if (interceptorCompleted.compareAndSet(false, true)) {
451
279
  synchronized(this) {
@@ -457,84 +285,56 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
457
285
  }
458
286
  }
459
287
  }.catch { error ->
460
- if (interceptorCompleted.compareAndSet(false, true)) {
461
- handleInterceptorError(error, version)
462
- }
288
+ if (interceptorCompleted.compareAndSet(false, true)) handleInterceptorError(error, version)
463
289
  }
464
290
  }.catch { error ->
465
- if (interceptorCompleted.compareAndSet(false, true)) {
466
- handleInterceptorError(error, version)
467
- }
291
+ if (interceptorCompleted.compareAndSet(false, true)) handleInterceptorError(error, version)
468
292
  }
469
293
  } catch (e: Throwable) {
470
- if (interceptorCompleted.compareAndSet(false, true)) {
471
- handleInterceptorError(e, version)
472
- }
294
+ if (interceptorCompleted.compareAndSet(false, true)) handleInterceptorError(e, version)
473
295
  }
474
296
  } else {
475
297
  executeConnection(version)
476
298
  }
477
299
  }
478
300
 
479
- /**
480
- * Handles a failure from the request-level interceptor by emitting an ERROR event and scheduling a reconnect.
481
- *
482
- * Posts work onto the SSE handler that (if the connection attempt version is still current and streaming is running)
483
- * pushes an ERROR SseEvent describing the interceptor failure and schedules performConnection(...) after a
484
- * jittered retry delay derived from the current configuration.
485
- *
486
- * @param t The throwable from the interceptor failure, or null if unavailable.
487
- * @param version Snapshot of connectionAttemptVersion used to ignore stale work.
488
- */
489
301
  private fun handleInterceptorError(t: Throwable?, version: Int) {
490
- sseHandler?.post {
302
+ sseDispatcher?.post {
491
303
  if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
492
- Log.e(TAG, "Request Interceptor Error: ${t?.message}")
493
-
494
- // Note: We use string matching here because react-native-nitro-modules (as of 0.36.1)
495
- // throws a generic std::runtime_error from C++ when the Dispatcher is destroyed.
496
- // It does not provide a specific Exception class (like DispatcherDestroyedException)
497
- // that we can catch, so checking the message is currently the only workaround.
304
+
498
305
  val isDispatcherDestroyedMsg = t?.message?.contains("Dispatcher has already been destroyed", ignoreCase = true) == true
499
306
  if (isDispatcherDestroyedMsg) {
500
307
  Log.w(TAG, "JS Dispatcher destroyed. Stopping SSE stream.")
501
308
  this@NitroSse.isDispatcherDestroyed = true
502
- isRunning.set(false)
503
- connectionAttemptVersion.incrementAndGet()
504
- performInternalCleanup()
309
+ stopInternal()
505
310
  return@post
506
311
  }
507
312
 
508
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Interceptor Error: ${t?.message}", -1.0, null))
313
+ eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "Interceptor Error: ${t?.message}", -1.0, null, null))
509
314
 
510
- // Reconnect with delay
511
- val currentJitterFactor = config?.jitterFactor ?: 0.5
512
- val currentRetryInterval = (config?.retryIntervalMs ?: 1000.0).toLong()
513
- val delay = (currentRetryInterval * (1.0 - currentJitterFactor + Random.nextDouble() * 2 * currentJitterFactor)).toLong()
514
- sseHandler?.postDelayed({ if (isRunning.get()) performConnection(version) }, delay)
315
+ scheduleReconnect(true, version)
515
316
  }
516
317
  }
517
318
 
518
319
  private fun executeConnection(version: Int) {
519
320
  val currentConfig: SseConfig
520
321
  val currentLastId: String?
322
+ val oldRequestId: String?
323
+ val newRequestId = UUID.randomUUID().toString()
324
+
521
325
  synchronized(this) {
522
326
  if (!isRunning.get() || config == null || version != connectionAttemptVersion.get()) return
523
327
  currentConfig = config!!
524
328
  currentLastId = lastProcessedId
329
+
330
+ oldRequestId = requestId
331
+ requestId = newRequestId
332
+
333
+ eventSource?.cancel()
334
+ eventSource = null
525
335
  }
526
336
 
527
- // Report end for previous request if it was running
528
- requestId?.let {
529
- NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
530
- this.requestId = null
531
- }
532
-
533
- eventSource?.cancel()
534
- eventSource = null
535
-
536
- val newRequestId = UUID.randomUUID().toString()
537
- this.requestId = newRequestId
337
+ oldRequestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
538
338
 
539
339
  val requestBuilder = Request.Builder()
540
340
  .url(currentConfig.url)
@@ -556,373 +356,226 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
556
356
  val request = requestBuilder.build()
557
357
  NetworkInspector.reportRequestStart(newRequestId, request)
558
358
 
559
- eventSource = EventSources.createFactory(client!!).newEventSource(request, sseListener)
359
+ val newEventSource = connectionHandler.createEventSource(client!!, request, newRequestId)
360
+ synchronized(this) { eventSource = newEventSource }
560
361
  }
561
362
 
562
- private fun extractRetryAfterMillis(response: Response?): Long? {
563
- val header = response?.header("Retry-After") ?: return null
564
- return try {
565
- header.toLong() * 1000L
566
- } catch (e: NumberFormatException) {
567
- response.headers.getDate("Retry-After")?.let {
568
- val diff = it.time - System.currentTimeMillis()
569
- if (diff > 0) diff else null
570
- }
363
+ override fun connectionDidOpen(response: Response, reqId: String) {
364
+ sseDispatcher?.post {
365
+ if (reqId != requestId) return@post
366
+ consecutiveAuthErrors.set(0)
367
+ reconnectStrategy.reset()
368
+ updateState(SseState.OPEN)
369
+ eventBuffer.push(SseEvent(SseEventType.OPEN, null, null, null, null, null, response.code.toDouble(), null, null))
571
370
  }
572
371
  }
573
372
 
574
- private val sseListener = object : EventSourceListener() {
575
- /**
576
- * Handles a successful SSE connection open by resetting reconnection/auth counters and emitting an OPEN event to the JS bridge.
577
- *
578
- * Synchronizes access when pushing the event and includes the HTTP response code in the emitted `SseEvent`.
579
- *
580
- * @param eventSource The EventSource instance that was opened.
581
- * @param response The HTTP response received when the SSE connection was established; its status code is included in the emitted OPEN event.
582
- */
583
- override fun onOpen(eventSource: EventSource, response: Response) {
584
- sseHandler?.post {
585
- if (eventSource != this@NitroSse.eventSource) return@post
586
- consecutiveAuthErrors.set(0)
587
- backoffCounter = 0
588
- currentReconnectAttempts = 0
589
- synchronized(this@NitroSse) {
590
- pushEventToBuffer(SseEvent(SseEventType.OPEN, null, null, null, null, null, response.code.toDouble(), null))
591
- }
592
- }
593
- }
594
-
595
- /**
596
- * Handles an incoming SSE message by validating the active stream, updating the last processed event id when present,
597
- * and buffering a `MESSAGE` SseEvent for delivery to the JS bridge.
598
- *
599
- * @param eventSource The source that produced the event; ignored if it is not the currently active stream.
600
- * @param id The event id; when non-empty it is stored as the last processed id.
601
- * @param type Optional event type.
602
- * @param data The event payload.
603
- */
604
- override fun onEvent(eventSource: EventSource, id: String?, type: String?, data: String) {
605
- sseHandler?.post {
606
- if (eventSource != this@NitroSse.eventSource) return@post
373
+ override fun connectionDidReceiveMessage(id: String?, type: String?, data: String, reqId: String) {
374
+ sseDispatcher?.post {
375
+ if (reqId != requestId) return@post
376
+ val currentConfig: SseConfig?
377
+ synchronized(this@NitroSse) {
607
378
  if (!id.isNullOrEmpty()) {
608
379
  this@NitroSse.lastProcessedId = id
609
380
  }
610
-
611
- val parsedData = if (config?.autoParseJSON == true) parseJsonToAnyMap(data) else null
612
-
613
- synchronized(this@NitroSse) {
614
- pushEventToBuffer(SseEvent(SseEventType.MESSAGE, data, parsedData, id, type, null, 200.0, null))
615
- }
381
+ currentConfig = this@NitroSse.config
616
382
  }
383
+ val parsedData = if (currentConfig?.autoParseJSON == true) JsonUtils.parseJsonToAnyMap(data) else null
384
+ eventBuffer.push(SseEvent(SseEventType.MESSAGE, data, parsedData, id, type, null, 200.0, null, null))
617
385
  }
386
+ }
618
387
 
619
- /**
620
- * Handles an SSE connection failure: records error stats, reports the network failure, emits an appropriate ERROR event, and decides whether to stop or schedule a reconnect.
621
- *
622
- * Behavior by status code:
623
- * - 401/403: if no `onBeforeRequest` interceptor is configured, emits an auth error and stops; otherwise increments an auth-retry counter, stops when the max is reached, or schedules a reconnect to allow token refresh.
624
- * - 400 or 204: emits a fatal error and stops.
625
- * - 429 or 503 with a valid `Retry-After`: emits an error describing the computed delay and retries after the server-specified delay plus jitter.
626
- * - 429 without `Retry-After`: emits an error and stops.
627
- * - Other or unknown codes: emits an error and schedules a reconnect using the configured backoff and jitter.
628
- *
629
- * Side effects: updates reconnect/last-error statistics, reports request failure to NetworkInspector, clears the active request id, pushes events into the internal buffer, may call `stop()` or schedule `performConnection(...)`.
630
- *
631
- * @param eventSource The EventSource instance that reported the failure.
632
- * @param t The throwable that caused the failure, if any.
633
- * @param response The HTTP response associated with the failure, if any.
634
- */
635
- override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
636
- sseHandler?.post {
637
- if (eventSource != this@NitroSse.eventSource) return@post
638
- Log.e(TAG, "SSE Failure: ${t?.message}, Code: ${response?.code}")
639
- if (!isRunning.get()) return@post
640
-
641
- val statusCode = response?.code ?: -1
642
-
643
- synchronized(this@NitroSse) {
644
- reconnectCount++
645
- lastErrorTime = System.currentTimeMillis().toDouble()
646
- lastErrorCode = t?.javaClass?.simpleName ?: statusCode.toString()
647
- }
648
-
649
- requestId?.let {
650
- NetworkInspector.reportRequestFailed(it, false)
651
- this@NitroSse.requestId = null
652
- }
653
-
654
- if (statusCode == 401 || statusCode == 403) {
655
- val currentConfig = synchronized(this@NitroSse) { config }
656
- if (currentConfig?.onBeforeRequest == null) {
657
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Auth Error ($statusCode) - No interceptor provided. Stopping.", statusCode.toDouble(), null))
658
- isRunning.set(false)
659
- connectionAttemptVersion.incrementAndGet()
660
- performInternalCleanup()
661
- return@post
662
- }
663
-
664
- val retries = consecutiveAuthErrors.incrementAndGet()
665
- if (retries >= maxAuthRetries) {
666
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Auth Error ($statusCode) - Retry limit reached ($maxAuthRetries). Stopping.", statusCode.toDouble(), null))
667
- isRunning.set(false)
668
- connectionAttemptVersion.incrementAndGet()
669
- performInternalCleanup()
670
- return@post
671
- }
672
-
673
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Auth Error ($statusCode) - Retry $retries/$maxAuthRetries. Refreshing token...", statusCode.toDouble(), null))
674
- scheduleReconnect(true)
675
- return@post
676
- }
677
-
678
- if (statusCode == 400) {
679
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Fatal Error ($statusCode). Stopping.", statusCode.toDouble(), null))
680
- isRunning.set(false)
681
- connectionAttemptVersion.incrementAndGet()
682
- performInternalCleanup()
388
+ override fun connectionDidFail(t: Throwable?, response: Response?, reqId: String) {
389
+ sseDispatcher?.post {
390
+ if (reqId != requestId || !isRunning.get()) return@post
391
+ val statusCode = response?.code ?: -1
392
+
393
+ totalReconnectCount.incrementAndGet()
394
+ synchronized(this@NitroSse) {
395
+ lastErrorTime = System.currentTimeMillis().toDouble()
396
+ lastErrorCode = t?.javaClass?.simpleName ?: statusCode.toString()
397
+ }
398
+
399
+ val currentRequestId = synchronized(this@NitroSse) {
400
+ val id = requestId
401
+ requestId = null
402
+ id
403
+ }
404
+ currentRequestId?.let { NetworkInspector.reportRequestFailed(it, false) }
405
+
406
+ if (statusCode == 401 || statusCode == 403) {
407
+ val currentConfig = synchronized(this@NitroSse) { config }
408
+ 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()
683
412
  return@post
684
413
  }
685
-
686
- val retryAfterMillis = extractRetryAfterMillis(response)
687
- if ((statusCode == 429 || statusCode == 503) && retryAfterMillis != null) {
688
- val jitter = (500 + Random.nextInt(1500)).toLong()
689
- val totalDelay = retryAfterMillis + jitter
690
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Retry-After received: ${totalDelay/1000}s", statusCode.toDouble(), totalDelay.toDouble()))
691
- sseHandler?.postDelayed({
692
- if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection(connectionAttemptVersion.get())
693
- }, totalDelay)
414
+ 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()
694
419
  return@post
695
420
  }
421
+ eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, "Auth Error ($statusCode) - Retry $retries/$maxAuthRetries. Refreshing token...", statusCode.toDouble(), null, null))
422
+ scheduleReconnect(true, connectionAttemptVersion.get())
423
+ return@post
424
+ }
425
+
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()
430
+ return@post
431
+ }
696
432
 
697
- if (statusCode == 429) {
698
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Rate Limited (429) without Retry-After. Stopping.", 429.0, null))
699
- isRunning.set(false)
700
- connectionAttemptVersion.incrementAndGet()
701
- performInternalCleanup()
702
- return@post
703
- }
433
+ val retryAfterMillis = SseReconnectStrategy.extractRetryAfterMillis(response)
434
+ if ((statusCode == 429 || statusCode == 503) && retryAfterMillis != null) {
435
+ val jitter = (500 + Random.nextInt(1001)).toLong()
436
+ val totalDelay = retryAfterMillis + jitter
437
+ 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()
439
+ updateState(SseState.RECONNECTING)
440
+ sseDispatcher?.postDelayed({ if (isRunning.get()) performConnection(currentAttemptVersion) }, totalDelay)
441
+ return@post
442
+ }
704
443
 
705
- if (statusCode == 204) {
706
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "No Content (204). Stopping.", 204.0, null))
707
- isRunning.set(false)
708
- connectionAttemptVersion.incrementAndGet()
709
- performInternalCleanup()
710
- return@post
711
- }
444
+ 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()
448
+ return@post
449
+ }
712
450
 
713
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, t?.message ?: "Link lost ($statusCode)", if (statusCode != -1) statusCode.toDouble() else null, null))
714
- scheduleReconnect(true)
451
+ 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()
455
+ return@post
715
456
  }
716
- }
717
457
 
718
- /**
719
- * Handles the SSE stream being closed by the server.
720
- *
721
- * When the closed `eventSource` is the currently active stream and streaming is running,
722
- * reports the response end to the network inspector with the total bytes received,
723
- * clears the stored `requestId`, and schedules a reconnect that is treated as a normal (non-error) reconnect.
724
- *
725
- * @param eventSource The EventSource instance that was closed.
726
- */
727
- override fun onClosed(eventSource: EventSource) {
728
- sseHandler?.post {
729
- if (eventSource != this@NitroSse.eventSource) return@post
730
- if (isRunning.get()) {
731
- requestId?.let {
732
- NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
733
- this@NitroSse.requestId = null
734
- }
735
- scheduleReconnect(false)
736
- }
458
+ val isTimeout = t is java.net.SocketTimeoutException || t is java.io.InterruptedIOException || t?.message?.contains("timeout", ignoreCase = true) == true
459
+ if (isTimeout) {
460
+ updateState(SseState.STALE)
737
461
  }
462
+
463
+ eventBuffer.push(SseEvent(SseEventType.ERROR, null, null, null, null, t?.message ?: "Link lost ($statusCode)", if (statusCode != -1) statusCode.toDouble() else null, null, null))
464
+ scheduleReconnect(true, connectionAttemptVersion.get())
738
465
  }
466
+ }
739
467
 
740
- /**
741
- * Schedule a future reconnect attempt using configurable backoff, jitter, and attempt limits.
742
- *
743
- * If the configured maximum reconnect attempts is reached, emits an ERROR event and stops the stream.
744
- * Otherwise computes a delay (exponential backoff when `isError` is true, simple retry interval when false),
745
- * applies jitter, enforces a minimum delay of 1000 ms, increments reconnect counters, and posts a
746
- * connection retry task to the SSE handler.
747
- *
748
- * @param isError True when the reconnect is triggered by an error; false for a normal/non-error reconnect.
749
- */
750
- private fun scheduleReconnect(isError: Boolean) {
751
- val currentConfig = synchronized(this@NitroSse) { config } ?: return
752
- val currentJitterFactor = currentConfig.jitterFactor ?: 0.5
753
- val currentRetryInterval = (currentConfig.retryIntervalMs ?: 1000.0).toLong()
754
- val currentMaxRetryInterval = (currentConfig.maxRetryIntervalMs ?: 30000.0).toLong()
755
-
756
- val maxAttempts = (currentConfig.maxReconnectAttempts ?: -1.0).toInt()
757
- if (maxAttempts != -1 && currentReconnectAttempts >= maxAttempts) {
758
- Log.d(TAG, "Max reconnection attempts reached ($maxAttempts). Stopping.")
759
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Max reconnection attempts reached ($maxAttempts).", null, null))
760
- isRunning.set(false)
761
- connectionAttemptVersion.incrementAndGet()
762
- performInternalCleanup()
763
- return
468
+ override fun connectionDidClose(reqId: String) {
469
+ 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
764
475
  }
476
+ currentRequestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
477
+ scheduleReconnect(false, connectionAttemptVersion.get())
478
+ }
479
+ }
765
480
 
766
- val reconnectDelay = if (isError) {
767
- val base = Math.min(currentRetryInterval * (1 shl backoffCounter), currentMaxRetryInterval)
768
- backoffCounter++
769
- (base * (1.0 - currentJitterFactor + Random.nextDouble() * 2 * currentJitterFactor)).toLong()
770
- } else {
771
- (currentRetryInterval * (1.0 - currentJitterFactor + Random.nextDouble() * 2 * currentJitterFactor)).toLong()
772
- }
481
+ private fun scheduleReconnect(isError: Boolean, attemptVersion: Int) {
482
+ if (reconnectStrategy.hasReachedMaxAttempts()) {
483
+ val maxAttempts = reconnectStrategy.currentReconnectAttempts
484
+ 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()
488
+ return
489
+ }
490
+ val safeReconnectDelay = reconnectStrategy.nextDelay(isError)
491
+ updateState(SseState.RECONNECTING)
492
+ sseDispatcher?.postDelayed({ if (isRunning.get()) performConnection(attemptVersion) }, safeReconnectDelay)
493
+ }
773
494
 
774
- currentReconnectAttempts++
775
- val safeReconnectDelay = Math.max(reconnectDelay, 1000L)
776
- sseHandler?.postDelayed({
777
- if (isRunning.get()) performConnection(connectionAttemptVersion.get())
778
- }, safeReconnectDelay)
779
- }
495
+ private fun stopInternal() {
496
+ isRunning.set(false)
497
+ connectionAttemptVersion.incrementAndGet()
498
+ performInternalCleanup()
780
499
  }
781
500
 
782
- /**
783
- * Immediately emit any pending buffered events to the JS bridge.
784
- */
785
501
  override fun flush() {
786
- flushBufferToJs()
502
+ if (::eventBuffer.isInitialized) {
503
+ eventBuffer.flush()
504
+ }
787
505
  }
788
506
 
789
- /**
790
- * Restart the SSE connection by stopping and starting again.
791
- */
792
507
  override fun restart() {
793
- stop()
508
+ synchronized(this) { config } ?: return
509
+ stopInternal()
510
+ updateState(SseState.RECONNECTING)
794
511
  start()
795
512
  }
796
513
 
797
- /**
798
- * Indicates if the SSE connection is currently active or trying to connect.
799
- */
800
514
  override fun isConnected(): Boolean {
801
515
  return isRunning.get()
802
516
  }
803
517
 
804
- /**
805
- * Stop the SSE connection and clear any pending reconnect timers.
806
- */
807
518
  override fun stop() {
808
519
  isRunning.set(false)
809
520
  wasRunningBeforeNetworkLoss = false
810
521
  wasRunningBeforePaused = false
811
- val version = connectionAttemptVersion.incrementAndGet()
812
- sseHandler?.post {
522
+ if (currentState.get() != SseState.FAILED) {
523
+ updateState(SseState.CLOSED)
524
+ }
525
+ connectionAttemptVersion.incrementAndGet()
526
+ sseDispatcher?.post {
813
527
  performInternalCleanup()
814
528
  }
815
529
  }
816
530
 
817
531
  private fun performInternalCleanup() {
532
+ reconnectStrategy.reset()
818
533
  if (!isDispatcherDestroyed) {
819
- flushBufferToJs()
534
+ if (::eventBuffer.isInitialized) eventBuffer.flush()
820
535
  } else {
821
- synchronized(eventBuffer) { eventBuffer.clear() }
822
- isFlushPending.set(false)
536
+ if (::eventBuffer.isInitialized) eventBuffer.clear()
823
537
  }
824
- sseHandler?.removeCallbacks(flushRunnable)
825
- backoffCounter = 0
826
- eventSource?.cancel()
827
- eventSource = null
828
- requestId?.let {
829
- NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
538
+ val currentRequestId = synchronized(this) {
539
+ eventSource?.cancel()
540
+ eventSource = null
541
+ val id = requestId
830
542
  requestId = null
543
+ id
831
544
  }
832
- isFlushPending.set(false)
545
+ currentRequestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
833
546
  }
834
547
 
835
- /**
836
- * Clean up all resources, including background threads and lifecycle observers.
837
- * This is called by Nitro when the HybridObject is being garbage collected or JS reloads.
838
- */
839
548
  override fun dispose() {
840
549
  Log.d(TAG, "Disposing NitroSse instance and cleaning up resources...")
841
-
550
+
551
+ if (::eventBuffer.isInitialized) {
552
+ eventBuffer.clearCallback()
553
+ }
554
+
842
555
  isRunning.set(false)
843
556
  connectionAttemptVersion.incrementAndGet()
844
557
 
845
- stopNetworkMonitoring()
846
-
558
+ networkMonitor?.stop()
559
+ lifecycleManager?.stopObserving()
560
+
847
561
  try {
848
- eventSource?.cancel()
849
- eventSource = null
850
- requestId?.let {
851
- NetworkInspector.reportRequestFailed(it, true)
562
+ val currentRequestId = synchronized(this) {
563
+ eventSource?.cancel()
564
+ eventSource = null
565
+ val id = requestId
852
566
  requestId = null
567
+ id
853
568
  }
569
+ currentRequestId?.let { NetworkInspector.reportRequestFailed(it, true) }
854
570
  } catch (e: Exception) {
855
571
  Log.e(TAG, "Error during synchronous dispose: ${e.message}")
856
572
  }
857
-
858
- if (hasSubscribedToLifecycle) {
859
- Handler(Looper.getMainLooper()).post {
860
- ProcessLifecycleOwner.get().lifecycle.removeObserver(this@NitroSse)
861
- }
862
- hasSubscribedToLifecycle = false
863
- }
864
573
 
865
- sseHandler?.removeCallbacksAndMessages(null)
866
- sseHandlerThread?.quitSafely()
867
- sseHandlerThread = null
868
- sseHandler = null
574
+ sseDispatcher?.removeCallbacksAndMessages(null)
575
+ sseDispatcherThread?.quitSafely()
576
+ sseDispatcherThread = null
577
+ sseDispatcher = null
869
578
 
870
- onEventsCallback = null
871
579
  super.dispose()
872
580
  }
873
581
  }
874
-
875
- /**
876
- * Separates the network interception logic (counting bytes, intercepting SSE heartbeats)
877
- * from the main NitroSse connection manager.
878
- */
879
- internal class HeartbeatNetworkInterceptor(
880
- private val totalBytesReceived: AtomicLong,
881
- private val onHeartbeat: () -> Unit
882
- ) : Interceptor {
883
- override fun intercept(chain: Interceptor.Chain): Response {
884
- val request = chain.request()
885
- val rid = request.tag(String::class.java)
886
-
887
- val response = chain.proceed(request)
888
-
889
- rid?.let {
890
- NetworkInspector.reportResponseStart(it, request, response)
891
- }
892
-
893
- val responseBody = response.body
894
- if (responseBody != null) {
895
- val countingBody = object : ResponseBody() {
896
- override fun contentType() = responseBody.contentType()
897
- override fun contentLength() = responseBody.contentLength()
898
- override fun source() = (object : okio.ForwardingSource(responseBody.source()) {
899
- private var isAtStartOfLine = true
900
-
901
- override fun read(sink: okio.Buffer, byteCount: Long): Long {
902
- val bufferOffset = sink.size
903
- val bytesRead = super.read(sink, byteCount)
904
- if (bytesRead != -1L) {
905
- totalBytesReceived.addAndGet(bytesRead)
906
- try {
907
- // Raw stream sniffing: SSE comments/heartbeats (lines starting with ':') are discarded
908
- // by OkHttp SSE parser. We scan raw bytes before parsing to trigger keep-alive watchdogs.
909
- for (i in 0 until bytesRead) {
910
- val b = sink.get(bufferOffset + i)
911
- if (isAtStartOfLine && b == ':'.code.toByte()) {
912
- onHeartbeat()
913
- }
914
- isAtStartOfLine = (b == '\n'.code.toByte() || b == '\r'.code.toByte())
915
- }
916
- } catch (e: Exception) {
917
- // Silent fallback to prevent crashing the stream reader on random parse bugs
918
- }
919
- }
920
- return bytesRead
921
- }
922
- }).buffer()
923
- }
924
- return response.newBuilder().body(countingBody).build()
925
- }
926
- return response
927
- }
928
- }