react-native-nitro-sse 2.3.1 → 2.4.0-beta.1

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