react-native-nitro-sse 1.4.1 → 1.6.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 (33) hide show
  1. package/README.md +33 -34
  2. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +265 -84
  3. package/android/src/test/java/com/margelo/nitro/nitrosse/NitroSseLogicTest.kt +60 -13
  4. package/ios/NitroSse.swift +288 -81
  5. package/ios/Tests/NitroSseTests.swift +36 -0
  6. package/lib/module/index.js +3 -2
  7. package/lib/module/index.js.map +1 -1
  8. package/lib/typescript/src/SseInterface.d.ts +31 -4
  9. package/lib/typescript/src/SseInterface.d.ts.map +1 -1
  10. package/lib/typescript/src/index.d.ts.map +1 -1
  11. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.hpp +138 -0
  12. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +5 -2
  13. package/nitrogen/generated/android/c++/JSseConfig.hpp +28 -3
  14. package/nitrogen/generated/android/c++/JSseEvent.hpp +11 -3
  15. 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 +80 -0
  16. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +18 -5
  17. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEvent.kt +9 -3
  18. package/nitrogen/generated/android/nitrosseOnLoad.cpp +2 -0
  19. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.cpp +33 -0
  20. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +130 -0
  21. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +1 -0
  22. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +2 -1
  23. package/nitrogen/generated/ios/swift/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.swift +67 -0
  24. package/nitrogen/generated/ios/swift/Func_void_std__exception_ptr.swift +46 -0
  25. package/nitrogen/generated/ios/swift/Func_void_std__shared_ptr_Promise_std__unordered_map_std__string__std__string___.swift +66 -0
  26. package/nitrogen/generated/ios/swift/Func_void_std__unordered_map_std__string__std__string_.swift +54 -0
  27. package/nitrogen/generated/ios/swift/SseConfig.swift +84 -1
  28. package/nitrogen/generated/ios/swift/SseEvent.swift +37 -1
  29. package/nitrogen/generated/shared/c++/SseConfig.hpp +17 -3
  30. package/nitrogen/generated/shared/c++/SseEvent.hpp +10 -2
  31. package/package.json +1 -1
  32. package/src/SseInterface.ts +31 -4
  33. package/src/{index.tsx → index.ts} +4 -3
package/README.md CHANGED
@@ -33,7 +33,7 @@ npm install react-native-nitro-sse react-native-nitro-modules
33
33
 
34
34
  | react-native-nitro-sse | react-native-nitro-modules |
35
35
  | :--------------------- | :------------------------- |
36
- | **1.4.0 - 1.4.1** | **0.35.0** |
36
+ | **1.4.0 - 1.6.1** | **0.35.0** |
37
37
  | **1.2.2 - 1.3.1** | **0.34.1** |
38
38
  | **1.2.0 - 1.2.1** | **0.34.0** |
39
39
  | **1.1.0** | **0.33.9** |
@@ -62,62 +62,61 @@ nitroSse.setup(
62
62
  },
63
63
  // Batch messages every 100ms to optimize UI rendering
64
64
  batchingIntervalMs: 100,
65
- // Maximum of 1000 messages in the native queue before tail-drop
65
+ // Maximum of 1000 messages in the native queue before forced flush
66
66
  maxBufferSize: 1000,
67
+ // Optional: Auto-refresh tokens or dynamic headers
68
+ onBeforeRequest: async () => {
69
+ const token = await fetchNewToken();
70
+ return { 'Authorization': `Bearer ${token}` };
71
+ }
67
72
  },
68
73
  (events) => {
74
+ // events is an array of SseEvent objects
69
75
  events.forEach((event) => {
70
- if (event.type === 'message') {
71
- console.log('Data received:', event.data);
72
- } else if (event.type === 'heartbeat') {
73
- console.log('Server heartbeat detected...');
74
- }
76
+ console.log('Received:', event);
75
77
  });
76
78
  }
77
79
  );
78
80
 
79
81
  // Start the connection
80
82
  nitroSse.start();
81
-
82
- // Stop the connection when unmounting or no longer needed
83
- // nitroSse.stop();
84
83
  ```
85
84
 
85
+ ### 2. Monitoring & Statistics
86
86
 
87
- ### 2. Check Connection Status
88
-
89
- You can synchronously check the connection status at any time:
87
+ NitroSSE provides synchronous access to connection health and throughput data.
90
88
 
91
89
  ```tsx
92
- const connected = nitroSse.isConnected();
93
- console.log('Is Connected:', connected);
90
+ const stats = nitroSse.getStats();
91
+ console.log(`Downloaded: ${stats.totalBytesReceived / 1024} KB`);
92
+ console.log(`Reconnections: ${stats.reconnectCount}`);
94
93
  ```
95
94
 
95
+ ---
96
96
 
97
- ### 3. Dynamic Token Updates
98
-
99
- When your authentication token expires, update the headers instantly. The native layer will apply these headers to the next automatic reconnection attempt without interrupting the current flow if not necessary.
100
-
101
- ```tsx
102
- nitroSse.updateHeaders({
103
- 'Authorization': 'Bearer new-fresh-token',
104
- });
105
- ```
97
+ ## ⚙️ Configuration (SseConfig)
106
98
 
99
+ | Parameter | Type | Default | Description |
100
+ | :--- | :--- | :--- | :--- |
101
+ | `url` | `string` | - | **Required**. The URL of the SSE endpoint. |
102
+ | `method` | `'get' \| 'post'` | `get` | HTTP method. |
103
+ | `headers` | `Record<string, string>` | `{}` | Custom HTTP headers. |
104
+ | `body` | `string` | - | Request body (payload) for POST requests. |
105
+ | `batchingIntervalMs` | `number` | `0` | Time window (ms) to group events. `0` = real-time. |
106
+ | `maxBufferSize` | `number` | `1000` | Native queue limit to prevent memory overflow. |
107
+ | `connectionTimeoutMs`| `number` | `15000` | Max time for initial handshake / connect. |
108
+ | `readTimeoutMs` | `number` | `300000`| Max idle time between data packets before reconnecting. |
109
+ | `backgroundExecution` | `boolean` | `false` | (iOS) Attempt to maintain connection via background tasks. |
110
+ | `onBeforeRequest` | `function`| - | Async hook to refresh headers/tokens before every attempt. |
107
111
 
108
112
  ---
109
113
 
110
- ## ⚙️ Configuration (SseConfig)
114
+ ## 🛡️ Reliability Features (v1.5.1+)
111
115
 
112
- | Parameter | Type | Description |
113
- | :--- | :--- | :--- |
114
- | `url` | `string` | **Required**. The URL of the SSE endpoint. |
115
- | `method` | `'get' \| 'post'` | HTTP method (Default: `get`). |
116
- | `headers` | `Record<string, string>` | Custom headers (e.g., Auth, Content-Type). |
117
- | `body` | `string` | Request body (payload) for POST requests. |
118
- | `batchingIntervalMs` | `number` | Time window to buffer events before flushing to JS (Default: 0 - immediate). |
119
- | `maxBufferSize` | `number` | Native queue limit to prevent memory overflow (Default: 1000). |
120
- | `backgroundExecution` | `boolean` | (iOS) Attempt to maintain a background task for a short period. |
116
+ - **Atomic State Management**: Calling `.start()` or `.stop()` updates the instance status immediately on the JSI thread, ensuring the UI (e.g., `isConnected()`) never feels laggy or stuck.
117
+ - **Promise Safety**: The `onBeforeRequest` interceptor is wrapped in a native fallback timeout. Even if your JS token refresh hangs indefinitely, the native state machine will recover and retry safely.
118
+ - **Zero-Ghost Reloads**: Seamlessly handles React Native Hot Reloads. The native layer detects when the JS environment is being destroyed and synchronously kills active sockets to prevent duplicate connections.
119
+ - **Cumulative Logic**: Statistics (`totalBytesReceived`) are preserved across reconnections, giving you a true 360-degree view of the session's data usage.
121
120
 
122
121
  ---
123
122
 
@@ -17,6 +17,7 @@ import androidx.lifecycle.ProcessLifecycleOwner
17
17
  import java.util.concurrent.TimeUnit
18
18
  import java.util.concurrent.atomic.AtomicBoolean
19
19
  import java.util.concurrent.atomic.AtomicLong
20
+ import java.util.concurrent.atomic.AtomicInteger
20
21
  import java.util.UUID
21
22
  import kotlin.random.Random
22
23
 
@@ -45,6 +46,8 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
45
46
 
46
47
  private val isRunning = AtomicBoolean(false)
47
48
  private var wasRunningBeforePaused = false
49
+ private val consecutiveAuthErrors = AtomicInteger(0)
50
+ private val maxAuthRetries = 3
48
51
  private var sseHandlerThread: android.os.HandlerThread? = null
49
52
  private var sseHandler: Handler? = null
50
53
 
@@ -55,6 +58,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
55
58
  @Volatile private var lastProcessedId: String? = null
56
59
 
57
60
  private val totalBytesReceived = AtomicLong(0)
61
+ private val connectionAttemptVersion = AtomicInteger(0)
58
62
  private var reconnectCount = 0
59
63
  private var lastErrorTime: Double? = null
60
64
  private var lastErrorCode: String? = null
@@ -69,61 +73,25 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
69
73
  private const val TAG = "NitroSse"
70
74
  }
71
75
 
76
+ /**
77
+ * Set up the NitroSse instance with configuration and an event callback.
78
+ * This prepares the OkHttpClient and internal handler threads.
79
+ *
80
+ * @param config The SSE configuration containing URL, headers, and more.
81
+ * @param onEvent Callback function to receive batched SSE events.
82
+ */
72
83
  override fun setup(config: SseConfig, onEvent: (events: Array<SseEvent>) -> Unit) {
73
84
  this.config = config
74
85
  this.onEventsCallback = onEvent
75
86
 
76
87
  if (this.client == null) {
77
88
  this.client = OkHttpClient.Builder()
78
- .connectTimeout(15, TimeUnit.SECONDS)
79
- .readTimeout(35, TimeUnit.SECONDS)
80
- .addNetworkInterceptor { chain ->
81
- val request = chain.request()
82
- val rid = request.tag(String::class.java)
83
-
84
- val response = chain.proceed(request)
85
-
86
- rid?.let {
87
- NetworkInspector.reportResponseStart(it, request, response)
88
- }
89
-
90
- val responseBody = response.body
91
- if (responseBody != null) {
92
- val countingBody = object : ResponseBody() {
93
- override fun contentType() = responseBody.contentType()
94
- override fun contentLength() = responseBody.contentLength()
95
- override fun source() = (object : okio.ForwardingSource(responseBody.source()) {
96
- private var isAtStartOfLine = true
97
-
98
- override fun read(sink: okio.Buffer, byteCount: Long): Long {
99
- val bufferOffset = sink.size
100
- val bytesRead = super.read(sink, byteCount)
101
- if (bytesRead != -1L) {
102
- totalBytesReceived.addAndGet(bytesRead)
103
-
104
-
105
- try {
106
- for (i in 0 until bytesRead) {
107
- val b = sink.get(bufferOffset + i)
108
- if (isAtStartOfLine && b == ':'.code.toByte()) {
109
- pushEventToBuffer(SseEvent(SseEventType.HEARTBEAT, null, null, null, "keep-alive"))
110
- }
111
- isAtStartOfLine = (b == '\n'.code.toByte() || b == '\r'.code.toByte())
112
- }
113
- } catch (e: Exception) {
114
- // Silent
115
- }
116
- }
117
- return bytesRead
118
- }
119
- }).buffer()
120
- }
121
- response.newBuilder().body(countingBody).build()
122
- } else {
123
- response
124
- }
125
- }
126
- .build()
89
+ .connectTimeout((config.connectionTimeoutMs ?: 15000.0).toLong(), TimeUnit.MILLISECONDS)
90
+ .readTimeout((config.readTimeoutMs ?: 300000.0).toLong(), TimeUnit.MILLISECONDS)
91
+ .addNetworkInterceptor(HeartbeatNetworkInterceptor(totalBytesReceived) {
92
+ pushEventToBuffer(SseEvent(SseEventType.HEARTBEAT, null, null, null, "keep-alive", null, null))
93
+ })
94
+ .build()
127
95
  }
128
96
 
129
97
  if (sseHandlerThread == null) {
@@ -139,6 +107,10 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
139
107
  }
140
108
  }
141
109
 
110
+ /**
111
+ * Called when the app enters the foreground.
112
+ * Automatically resumes the stream if it was hibernated.
113
+ */
142
114
  override fun onStart(owner: LifecycleOwner) {
143
115
  if (wasRunningBeforePaused) {
144
116
  Log.d(TAG, "App foregrounded. Resuming NitroSse stream.")
@@ -147,8 +119,16 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
147
119
  }
148
120
  }
149
121
 
122
+ /**
123
+ * Called when the app enters the background.
124
+ * Hibernates the connection to save battery and resources.
125
+ */
150
126
  override fun onStop(owner: LifecycleOwner) {
151
127
  if (isRunning.get()) {
128
+ if (config?.backgroundExecution == true) {
129
+ Log.d(TAG, "App backgrounded. backgroundExecution is true, keeping NitroSse connection alive.")
130
+ return
131
+ }
152
132
  Log.d(TAG, "App backgrounded. Hibernating NitroSse connection.")
153
133
  wasRunningBeforePaused = true
154
134
  stop()
@@ -159,14 +139,15 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
159
139
  val batchInterval = config?.batchingIntervalMs ?: 0.0
160
140
  val bufferCapacity = config?.maxBufferSize?.toInt() ?: 1000
161
141
 
142
+ var shouldFlush = false
162
143
  synchronized(eventBuffer) {
163
- while (eventBuffer.size >= bufferCapacity) {
164
- eventBuffer.removeAt(0)
165
- }
166
144
  eventBuffer.add(event)
145
+ if (eventBuffer.size >= bufferCapacity) {
146
+ shouldFlush = true
147
+ }
167
148
  }
168
149
 
169
- if (batchInterval <= 0) {
150
+ if (batchInterval <= 0 || shouldFlush) {
170
151
  flushBufferToJs()
171
152
  } else if (!isFlushPending.getAndSet(true)) {
172
153
  sseHandler?.postDelayed({
@@ -189,19 +170,29 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
189
170
  onEventsCallback?.invoke(eventsToEmit)
190
171
  }
191
172
 
173
+ /**
174
+ * Manually set the last seen event ID.
175
+ * This will be used as the 'Last-Event-ID' header on the next connection attempt.
176
+ */
192
177
  override fun setLastProcessedId(id: String) {
193
178
  this.lastProcessedId = id
194
179
  }
195
180
 
181
+ /**
182
+ * Dynamically update the headers for subsequent connection attempts.
183
+ */
196
184
  override fun updateHeaders(headers: Map<String, String>) {
197
185
  synchronized(this) {
198
186
  this.config?.let {
199
187
  this.config = it.copy(headers = headers)
200
- Log.d(TAG, "Headers updated for subsequent connections")
188
+ Log.d(TAG, "Headers updated manually")
201
189
  }
202
190
  }
203
191
  }
204
192
 
193
+ /**
194
+ * Returns runtime statistics about the SSE connection.
195
+ */
205
196
  override fun getStats(): SseStats {
206
197
  return SseStats(
207
198
  totalBytesReceived.get().toDouble(),
@@ -211,26 +202,91 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
211
202
  )
212
203
  }
213
204
 
205
+ /**
206
+ * Start the SSE connection.
207
+ * This triggers the initial request and handles subsequent reconnections.
208
+ */
214
209
  override fun start() {
215
- if (config == null || isRunning.get()) return
216
- isRunning.set(true)
217
- backoffCounter = 0
218
- requestId = null
219
- sseHandler?.post { performConnection() }
210
+ if (config == null) return
211
+ if (!isRunning.compareAndSet(false, true)) return
212
+
213
+ consecutiveAuthErrors.set(0)
214
+ val version = connectionAttemptVersion.incrementAndGet()
215
+ sseHandler?.post {
216
+ backoffCounter = 0
217
+ requestId = null
218
+ performConnection(version)
219
+ }
220
+ }
221
+
222
+ private fun performConnection(version: Int) {
223
+ if (!isRunning.get() || version != connectionAttemptVersion.get()) return
224
+
225
+ val currentConfig = synchronized(this) { config } ?: return
226
+ val interceptor = currentConfig.onBeforeRequest
227
+
228
+ if (interceptor != null) {
229
+ val interceptorCompleted = AtomicBoolean(false)
230
+ val timeoutMs = (currentConfig.connectionTimeoutMs ?: 15000.0).toLong()
231
+
232
+ sseHandler?.postDelayed({
233
+ if (interceptorCompleted.compareAndSet(false, true)) {
234
+ handleInterceptorError(Exception("onBeforeRequest interceptor timed out after $timeoutMs ms"), version)
235
+ }
236
+ }, timeoutMs)
237
+
238
+ interceptor.invoke().then { promise2 ->
239
+ promise2.then { newHeaders ->
240
+ sseHandler?.post {
241
+ if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
242
+ if (interceptorCompleted.compareAndSet(false, true)) {
243
+ synchronized(this) {
244
+ val mergedHeaders = (config?.headers ?: emptyMap()).toMutableMap()
245
+ newHeaders.forEach { (k, v) -> mergedHeaders[k] = v }
246
+ config = config?.copy(headers = mergedHeaders)
247
+ }
248
+ executeConnection(version)
249
+ }
250
+ }
251
+ }.catch { error ->
252
+ if (interceptorCompleted.compareAndSet(false, true)) {
253
+ handleInterceptorError(error, version)
254
+ }
255
+ }
256
+ }.catch { error ->
257
+ if (interceptorCompleted.compareAndSet(false, true)) {
258
+ handleInterceptorError(error, version)
259
+ }
260
+ }
261
+ } else {
262
+ executeConnection(version)
263
+ }
264
+ }
265
+
266
+ private fun handleInterceptorError(t: Throwable?, version: Int) {
267
+ sseHandler?.post {
268
+ if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
269
+ Log.e(TAG, "Request Interceptor Error: ${t?.message}")
270
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Interceptor Error: ${t?.message}", -1.0, null))
271
+
272
+ // Reconnect with delay
273
+ val delay = (defaultRetryDelayMs * (0.8 + Random.nextDouble() * 0.4)).toLong()
274
+ sseHandler?.postDelayed({ if (isRunning.get()) performConnection(version) }, delay)
275
+ }
220
276
  }
221
277
 
222
- private fun performConnection() {
278
+ private fun executeConnection(version: Int) {
223
279
  val currentConfig: SseConfig
224
280
  val currentLastId: String?
225
281
  synchronized(this) {
226
- if (!isRunning.get() || config == null) return
282
+ if (!isRunning.get() || config == null || version != connectionAttemptVersion.get()) return
227
283
  currentConfig = config!!
228
284
  currentLastId = lastProcessedId
229
285
  }
230
286
 
231
287
  // Report end for previous request if it was running
232
288
  requestId?.let {
233
- NetworkInspector.reportResponseEnd(it, totalBytesReceived.getAndSet(0))
289
+ NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
234
290
  this.requestId = null
235
291
  }
236
292
 
@@ -279,8 +335,9 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
279
335
  private val sseListener = object : EventSourceListener() {
280
336
  override fun onOpen(eventSource: EventSource, response: Response) {
281
337
  if (eventSource != this@NitroSse.eventSource) return
338
+ consecutiveAuthErrors.set(0) // Successful connection, reset error counter
282
339
  backoffCounter = 0
283
- pushEventToBuffer(SseEvent(SseEventType.OPEN, null, null, null, null))
340
+ pushEventToBuffer(SseEvent(SseEventType.OPEN, null, null, null, null, response.code.toDouble(), null))
284
341
  }
285
342
 
286
343
  override fun onEvent(eventSource: EventSource, id: String?, type: String?, data: String) {
@@ -288,7 +345,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
288
345
  if (!id.isNullOrEmpty()) {
289
346
  this@NitroSse.lastProcessedId = id
290
347
  }
291
- pushEventToBuffer(SseEvent(SseEventType.MESSAGE, data, id, type, null))
348
+ pushEventToBuffer(SseEvent(SseEventType.MESSAGE, data, id, type, null, 200.0, null))
292
349
  }
293
350
 
294
351
  override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
@@ -303,9 +360,33 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
303
360
 
304
361
  requestId?.let { NetworkInspector.reportRequestFailed(it, false) }
305
362
 
306
- val isFatal = (statusCode == 401 || statusCode == 403 || statusCode == 400)
363
+ // 401/403 are recoverable if we have an interceptor, but with a limit
364
+ if (statusCode == 401 || statusCode == 403) {
365
+ val hasInterceptor = synchronized(this) { config?.onBeforeRequest != null }
366
+ if (!hasInterceptor) {
367
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Auth Error ($statusCode) - No interceptor provided. Stopping.", statusCode.toDouble(), null))
368
+ stop()
369
+ return
370
+ }
371
+
372
+ val retries = consecutiveAuthErrors.incrementAndGet()
373
+ if (retries >= maxAuthRetries) {
374
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Auth Error ($statusCode) - Retry limit reached ($maxAuthRetries). Stopping.", statusCode.toDouble(), null))
375
+ stop()
376
+ return
377
+ }
378
+
379
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Auth Error ($statusCode) - Retry $retries/$maxAuthRetries. Refreshing token...", statusCode.toDouble(), null))
380
+ val delay = (defaultRetryDelayMs * (0.8 + Random.nextDouble() * 0.4)).toLong()
381
+ sseHandler?.postDelayed({
382
+ if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection(connectionAttemptVersion.get())
383
+ }, delay)
384
+ return
385
+ }
386
+
387
+ val isFatal = (statusCode == 400)
307
388
  if (isFatal) {
308
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Fatal Error ($statusCode). Stopping."))
389
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Fatal Error ($statusCode). Stopping.", statusCode.toDouble(), null))
309
390
  stop()
310
391
  return
311
392
  }
@@ -314,13 +395,15 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
314
395
  if ((statusCode == 429 || statusCode == 503) && retryAfterMillis != null) {
315
396
  val jitter = (500 + Random.nextInt(1500)).toLong()
316
397
  val totalDelay = retryAfterMillis + jitter
317
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Retry-After received: ${totalDelay/1000}s"))
318
- sseHandler?.postDelayed({ if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection() }, totalDelay)
398
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Retry-After received: ${totalDelay/1000}s", statusCode.toDouble(), totalDelay.toDouble()))
399
+ sseHandler?.postDelayed({
400
+ if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection(connectionAttemptVersion.get())
401
+ }, totalDelay)
319
402
  return
320
403
  }
321
404
 
322
405
  if (statusCode == 429) {
323
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Rate Limited (429) without Retry-After. Stopping."))
406
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Rate Limited (429) without Retry-After. Stopping.", 429.0, null))
324
407
  stop()
325
408
  return
326
409
  }
@@ -335,8 +418,17 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
335
418
  }
336
419
 
337
420
  val safeReconnectDelay = Math.max(reconnectDelay, 2000L)
338
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, t?.message ?: "Link lost ($statusCode)"))
339
- sseHandler?.postDelayed({ if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection() }, safeReconnectDelay)
421
+
422
+ if (statusCode == 204) {
423
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "No Content (204). Stopping.", 204.0, null))
424
+ stop()
425
+ return
426
+ }
427
+
428
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, t?.message ?: "Link lost ($statusCode)", if (statusCode != -1) statusCode.toDouble() else null, null))
429
+ sseHandler?.postDelayed({
430
+ if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection(connectionAttemptVersion.get())
431
+ }, safeReconnectDelay)
340
432
  }
341
433
 
342
434
  override fun onClosed(eventSource: EventSource) {
@@ -344,52 +436,141 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
344
436
  if (isRunning.get()) {
345
437
  requestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
346
438
  val delay = (defaultRetryDelayMs * (0.8 + Random.nextDouble() * 0.4)).toLong()
347
- sseHandler?.postDelayed({ if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection() }, delay)
439
+ sseHandler?.postDelayed({
440
+ if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection(connectionAttemptVersion.get())
441
+ }, delay)
348
442
  }
349
443
  }
350
444
  }
351
445
 
446
+ /**
447
+ * Immediately emit any pending buffered events to the JS bridge.
448
+ */
352
449
  override fun flush() {
353
450
  flushBufferToJs()
354
451
  }
355
452
 
453
+ /**
454
+ * Restart the SSE connection by stopping and starting again.
455
+ */
356
456
  override fun restart() {
357
457
  stop()
358
458
  start()
359
459
  }
360
460
 
461
+ /**
462
+ * Indicates if the SSE connection is currently active or trying to connect.
463
+ */
361
464
  override fun isConnected(): Boolean {
362
465
  return isRunning.get()
363
466
  }
364
467
 
468
+ /**
469
+ * Stop the SSE connection and clear any pending reconnect timers.
470
+ */
365
471
  override fun stop() {
366
472
  isRunning.set(false)
367
- backoffCounter = 0
368
- sseHandler?.removeCallbacksAndMessages(null)
369
- eventSource?.cancel()
370
- eventSource = null
371
- requestId?.let {
372
- NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
373
- requestId = null
374
- }
375
- synchronized(eventBuffer) {
376
- eventBuffer.clear()
473
+ val version = connectionAttemptVersion.incrementAndGet()
474
+ sseHandler?.post {
475
+ flushBufferToJs()
476
+ backoffCounter = 0
477
+ sseHandler?.removeCallbacksAndMessages(null)
478
+ eventSource?.cancel()
479
+ eventSource = null
480
+ requestId?.let {
481
+ NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
482
+ requestId = null
483
+ }
484
+ isFlushPending.set(false)
377
485
  }
378
- isFlushPending.set(false)
379
486
  }
380
487
 
488
+ /**
489
+ * Clean up all resources, including background threads and lifecycle observers.
490
+ * This is called by Nitro when the HybridObject is being garbage collected or JS reloads.
491
+ */
381
492
  override fun dispose() {
382
493
  Log.d(TAG, "Disposing NitroSse instance and cleaning up resources...")
383
- stop()
494
+
495
+ isRunning.set(false)
496
+ connectionAttemptVersion.incrementAndGet()
497
+
498
+ try {
499
+ eventSource?.cancel()
500
+ eventSource = null
501
+ requestId?.let {
502
+ NetworkInspector.reportRequestFailed(it, true)
503
+ requestId = null
504
+ }
505
+ } catch (e: Exception) {
506
+ Log.e(TAG, "Error during synchronous dispose: ${e.message}")
507
+ }
508
+
384
509
  if (hasSubscribedToLifecycle) {
385
510
  Handler(Looper.getMainLooper()).post {
386
511
  ProcessLifecycleOwner.get().lifecycle.removeObserver(this@NitroSse)
387
512
  }
388
513
  hasSubscribedToLifecycle = false
389
514
  }
515
+
516
+ sseHandler?.removeCallbacksAndMessages(null)
390
517
  sseHandlerThread?.quitSafely()
391
518
  sseHandlerThread = null
392
519
  sseHandler = null
520
+
393
521
  super.dispose()
394
522
  }
395
523
  }
524
+
525
+ /**
526
+ * Separates the network interception logic (counting bytes, intercepting SSE heartbeats)
527
+ * from the main NitroSse connection manager.
528
+ */
529
+ internal class HeartbeatNetworkInterceptor(
530
+ private val totalBytesReceived: AtomicLong,
531
+ private val onHeartbeat: () -> Unit
532
+ ) : Interceptor {
533
+ override fun intercept(chain: Interceptor.Chain): Response {
534
+ val request = chain.request()
535
+ val rid = request.tag(String::class.java)
536
+
537
+ val response = chain.proceed(request)
538
+
539
+ rid?.let {
540
+ NetworkInspector.reportResponseStart(it, request, response)
541
+ }
542
+
543
+ val responseBody = response.body
544
+ if (responseBody != null) {
545
+ val countingBody = object : ResponseBody() {
546
+ override fun contentType() = responseBody.contentType()
547
+ override fun contentLength() = responseBody.contentLength()
548
+ override fun source() = (object : okio.ForwardingSource(responseBody.source()) {
549
+ private var isAtStartOfLine = true
550
+
551
+ override fun read(sink: okio.Buffer, byteCount: Long): Long {
552
+ val bufferOffset = sink.size
553
+ val bytesRead = super.read(sink, byteCount)
554
+ if (bytesRead != -1L) {
555
+ totalBytesReceived.addAndGet(bytesRead)
556
+ try {
557
+ for (i in 0 until bytesRead) {
558
+ val b = sink.get(bufferOffset + i)
559
+ if (isAtStartOfLine && b == ':'.code.toByte()) {
560
+ onHeartbeat()
561
+ }
562
+ isAtStartOfLine = (b == '\n'.code.toByte() || b == '\r'.code.toByte())
563
+ }
564
+ } catch (e: Exception) {
565
+ // Silent
566
+ }
567
+ }
568
+ return bytesRead
569
+ }
570
+ }).buffer()
571
+ }
572
+ return response.newBuilder().body(countingBody).build()
573
+ }
574
+ return response
575
+ }
576
+ }