react-native-nitro-sse 2.3.1 → 2.3.2

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.
package/README.md CHANGED
@@ -1,23 +1,24 @@
1
- # 🚀 react-native-nitro-sse
1
+ # react-native-nitro-sse
2
2
 
3
- High-performance Server-Sent Events (SSE) client for React Native, built on top of **Nitro Modules (JSI)**. Designed for mission-critical systems requiring extreme stability, high-throughput data streaming, and absolute battery optimization.
3
+ High-performance Server-Sent Events (SSE) client for React Native, built on top of **Nitro Modules (JSI)**. Designed for mission-critical apps requiring high-throughput streaming, battery optimization, and extreme stability.
4
4
 
5
- ## 🌟 Why NitroSSE?
5
+ ---
6
+
7
+ ## Why NitroSSE?
6
8
 
7
- Unlike traditional EventSource libraries that run on the JS thread or use the legacy Bridge, NitroSSE moves the entire control logic down to the deepest Native layer:
9
+ Traditional EventSource libraries run on the JS thread or use the legacy React Native Bridge. NitroSSE moves the entire control logic down to the native layer:
8
10
 
9
- - **🚀 Zero-Latency JSI**: Communication between JS and Native is instantaneous, bypassing the asynchronous bridge.
10
- - **🧠 Smart Reconnect**: Automatic reconnection strategy using **Exponential Backoff** and **Jitter** to prevent thundering herd problems.
11
- - **🛡️ DoS Protection**: Respects RFC `Retry-After` headers and enforces strict connection frequency limits.
12
- - **🌊 Backpressure Handling**: Advanced **Batching** mechanism aggregates messages and employs **Tail Drop** strategies to protect the UI thread from freezing during data surges.
13
- - **🔋 Mobile-First Architecture**: Automatically hibernates when the app enters the background and seamlessly reconnects upon foregrounding to conserve battery.
14
- - **💓 Heartbeat Detection**: Native-side detection of keep-alive signals (comments) to maintain a reliable connection watchdog.
15
- - **🔍 DevTools Integration**: Plug-and-play support for **React Native 0.83+ DevTools Network Tab**. Monitor connection status, request/response headers, and timing directly in the official desktop debugger.
16
- - **🛠️ Full Protocol Support**: Comprehensive support for GET/POST methods and dynamic header updates.
11
+ * **Zero-Latency JSI**: Instantaneous JS-Native communication bypassing the async bridge.
12
+ * **Advanced Backpressure**: Batches high-frequency events and employs tail-drop strategies to keep UI thread fluid under extreme load.
13
+ * **Intelligent Reconnect**: Automatic recovery using **Exponential Backoff** and **Jitter** to prevent server stampedes.
14
+ * **Lifecycles**: Auto-hibernates connections in background and resumes on foreground to preserve battery.
15
+ * **Heartbeat Watchdog**: Native detection of keep-alive/ping comments to auto-reconnect dead sockets.
16
+ * **RN DevTools Integration**: Plug-and-play network tracing in **React Native 0.83+ DevTools** (monitor streams directly).
17
+ * **Local Mocking Engine**: Simulates streams, connection drops, and delays entirely in JS without backend setup.
17
18
 
18
19
  ---
19
20
 
20
- ## 📦 Installation
21
+ ## Installation
21
22
 
22
23
  ```sh
23
24
  yarn add react-native-nitro-sse react-native-nitro-modules
@@ -25,15 +26,18 @@ yarn add react-native-nitro-sse react-native-nitro-modules
25
26
  npm install react-native-nitro-sse react-native-nitro-modules
26
27
  ```
27
28
 
28
- > **Note**: `react-native-nitro-modules` is required as the core foundation for JSI performance.
29
+ > [!NOTE]
30
+ > `react-native-nitro-modules` is a peer dependency and must be installed in the host project.
29
31
 
30
32
  ---
31
33
 
32
- ## 📊 Compatibility
34
+ ## Compatibility
33
35
 
34
36
  | react-native-nitro-sse | react-native-nitro-modules |
35
37
  | :--------------------- | :------------------------- |
36
- | **2.2.0 - latest** | **0.35.4** |
38
+ | **2.3.1 - latest** | **0.35.9** |
39
+ | **2.3.0** | **0.35.6** |
40
+ | **2.2.0 - 2.2.3** | **0.35.4** |
37
41
  | **2.0.0 - 2.1.1** | **0.35.2** |
38
42
  | **1.6.2** | **0.35.2** |
39
43
  | **1.4.0 - 1.6.1** | **0.35.0** |
@@ -42,103 +46,107 @@ npm install react-native-nitro-sse react-native-nitro-modules
42
46
  | **1.1.0** | **0.33.9** |
43
47
  | **1.0.0** | **0.33.8** |
44
48
 
45
-
46
49
  ---
47
50
 
48
- ## 🚀 Usage
49
-
50
- ### 1. Basic Initialization
51
-
52
- Initialize the module with your endpoint configuration and an event listener.
51
+ ## Usage
53
52
 
54
53
  ```tsx
55
54
  import { createNitroSse } from 'react-native-nitro-sse';
56
55
 
57
- const nitroSse = createNitroSse();
58
-
59
- nitroSse.setup(
60
- {
61
- url: 'https://api.yourserver.com/stream',
62
- method: 'get',
63
- headers: {
64
- 'Authorization': 'Bearer active-token',
65
- },
66
- // Batch messages every 100ms to optimize UI rendering
67
- batchingIntervalMs: 100,
68
- // Maximum of 1000 messages in the native queue before forced flush
69
- maxBufferSize: 1000,
70
- // Optional: Auto-refresh tokens or dynamic headers
71
- onBeforeRequest: async () => {
72
- const token = await fetchNewToken();
73
- return { 'Authorization': `Bearer ${token}` };
74
- }
75
- },
76
- (events) => {
77
- // events is an array of SseEvent objects
78
- events.forEach((event) => {
79
- console.log('Received:', event);
80
- });
81
- }
82
- );
56
+ const sse = createNitroSse();
83
57
 
84
- // Start the connection
85
- nitroSse.start();
86
- ```
58
+ sse.setup({
59
+ url: 'https://api.example.com/stream',
60
+ headers: { 'Authorization': 'Bearer TOKEN' }
61
+ });
87
62
 
88
- ### 2. Monitoring & Statistics
63
+ // Listen to events
64
+ sse.addEventListener('message', (e) => console.log('Received:', e.data));
65
+ sse.addEventListener('error', (e) => console.error('Error:', e.message));
89
66
 
90
- NitroSSE provides synchronous access to connection health and throughput data.
67
+ // Start streaming
68
+ sse.start();
91
69
 
92
- ```tsx
93
- const stats = nitroSse.getStats();
94
- console.log(`Downloaded: ${stats.totalBytesReceived / 1024} KB`);
95
- console.log(`Reconnections: ${stats.reconnectCount}`);
70
+ // Cleanup when done
71
+ // sse.stop();
96
72
  ```
97
73
 
98
74
  ---
99
75
 
100
- ## ⚙️ Configuration (SseConfig)
76
+ ## Configuration Reference (`SseConfig`)
101
77
 
102
78
  | Parameter | Type | Default | Description |
103
79
  | :--- | :--- | :--- | :--- |
104
- | `url` | `string` | - | **Required**. The URL of the SSE endpoint. |
105
- | `method` | `'get' \| 'post'` | `get` | HTTP method. |
106
- | `headers` | `Record<string, string>` | `{}` | Custom HTTP headers. |
107
- | `body` | `string` | - | Request body (payload) for POST requests. |
108
- | `batchingIntervalMs` | `number` | `0` | Time window (ms) to group events. `0` = real-time. |
109
- | `maxBufferSize` | `number` | `1000` | Native queue limit to prevent memory overflow. |
110
- | `connectionTimeoutMs`| `number` | `15000` | Max time for initial handshake / connect. |
111
- | `readTimeoutMs` | `number` | `300000`| Max idle time between data packets before reconnecting. |
112
- | `backgroundExecution` | `boolean` | `false` | (iOS) Attempt to maintain connection via background tasks. |
113
- | `autoParseJSON` | `boolean` | `false` | Automatically parse message data as JSON in a background native thread. Result is in `parsedData`. |
114
- | `monitorNetwork` | `boolean` | `true` | Automatically hibernate connection on system network loss to save battery. |
115
- | `onBeforeRequest` | `function`| - | Async hook to refresh headers/tokens before every attempt. |
80
+ | `url` | `string` | — | **Required**. SSE endpoint target. |
81
+ | `method` | `'get' \| 'post'` | `'get'` | HTTP method. |
82
+ | `headers` | `Record<string, string>` | `{}` | Custom request headers. |
83
+ | `body` | `string` | — | Payload sent during POST requests. |
84
+ | `backgroundExecution` | `boolean` | `false` | (iOS) Keep background execution active when app is minimized. |
85
+ | `batchingIntervalMs` | `number` | `0` | Batch window (ms). `0` sends events instantly. |
86
+ | `maxBufferSize` | `number` | `1000` | Native memory safety threshold. |
87
+ | `connectionTimeoutMs`| `number` | `15000` | Handshake connect timeout threshold. |
88
+ | `readTimeoutMs` | `number` | `300000`| Socket inactivity limit triggers reconnect. |
89
+ | `retryIntervalMs` | `number` | `1000` | Backoff base delay (ms) for reconnect. |
90
+ | `maxRetryIntervalMs` | `number` | `30000` | Cap on backoff reconnect delay (ms). |
91
+ | `jitterFactor` | `number` | `0.5` | Randomization spread ratio (`0.0` to `1.0`). |
92
+ | `maxReconnectAttempts`| `number` | `-1` | Limit reconnections. `-1` = infinite. `0` = disabled. |
93
+ | `autoParseJSON` | `boolean` | `false` | Parses event `data` on native thread; outputs to `parsedData`. |
94
+ | `monitorNetwork` | `boolean` | `true` | Pauses/resumes connection on WiFi <-> Cell or link changes. |
95
+ | `onBeforeRequest` | `() => Promise<Record<string, string>>` | — | Async hook running immediately before every request. |
96
+ | `mock` | `SseMockConfig` | — | Injected mock stream settings (Dev environment only). |
116
97
 
117
98
  ---
118
99
 
119
- ## 🛡️ Reliability Features (v1.5.1+)
100
+ ## Mocking & Testing System (`v2.3.0+`)
120
101
 
121
- - **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.
122
- - **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.
123
- - **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.
124
- - **Cumulative Logic**: Statistics (`totalBytesReceived`) are preserved across reconnections, giving you a true 360-degree view of the session's data usage.
102
+ NitroSSE includes a built-in mock streaming engine to test application responses without running live endpoints. Mocks are automatically disabled in production configurations.
125
103
 
126
- ---
104
+ ### Configuration (`SseMockConfig`)
127
105
 
128
- ## 🏗️ System Architecture
106
+ ```tsx
107
+ sse.setup({
108
+ url: 'https://api.mocked-endpoint.com/stream',
109
+ mock: {
110
+ mode: 'replace', // 'replace' = Pure JS local simulation; 'inject' = Server + injected events
111
+ eventsPerSecond: 2,
112
+ loop: true,
113
+ errorRate: 0.1, // 10% chance to simulate connection drops and trigger reconnects
114
+ data: [
115
+ { type: 'open', statusCode: 200 },
116
+ { type: 'message', data: 'Initial greeting' },
117
+ { event: 'user-updated', data: '{"id":123,"status":"online"}', delayMs: 1500 },
118
+ { type: 'message', data: 'Periodic heartbeat comments' },
119
+ ]
120
+ }
121
+ });
122
+ ```
123
+
124
+ ### Manual Injector
125
+ Inject custom testing events programmatically at runtime to mock specific app situations:
126
+
127
+ ```tsx
128
+ sse.injectMockEvent({
129
+ type: 'message',
130
+ event: 'alert',
131
+ data: 'System maintenance warning!'
132
+ });
133
+ ```
134
+
135
+ ---
129
136
 
130
- This project employs a robust **Producer-Consumer** model:
137
+ ## Advanced Operations
131
138
 
132
- 1. **Native (Producer)**: Collects data from the socket on a dedicated Background Thread, handling all backpressure logic.
133
- 2. **Nitro (Bridge)**: Snapshots data and securely transports it via the JSI CallInvoker.
134
- 3. **JavaScript (Consumer)**: Consumes data in batches, ensuring the UI Loop remains buttery smooth even under heavy load.
139
+ * **`updateHeaders(headers)`**: Change request headers (e.g., updating expired authentication tokens) without closing and opening the connection manually.
140
+ * **`setLastProcessedId(id)`**: Update the native parser's last processed event ID. Native uses this ID as the `Last-Event-ID` header on next reconnection.
141
+ * **`restart()`**: Immediately tears down the current network socket and initializes fresh handshake sequence.
142
+ * **`flush()`**: Explicitly forces dispatch of currently buffered events, ignoring `batchingIntervalMs`.
135
143
 
136
144
  ---
137
145
 
138
- ## 📄 License
146
+ ## License
139
147
 
140
148
  MIT
141
149
 
142
150
  ---
143
151
 
144
- Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)
152
+ *Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)*
@@ -4,13 +4,19 @@ import android.os.Handler
4
4
  import android.os.Looper
5
5
  import android.util.Log
6
6
  import com.facebook.proguard.annotations.DoNotStrip
7
- import okhttp3.*
7
+ import okhttp3.OkHttpClient
8
+ import okhttp3.Request
9
+ import okhttp3.Response
10
+ import okhttp3.Interceptor
11
+ import okhttp3.ResponseBody
8
12
  import okhttp3.MediaType.Companion.toMediaType
9
13
  import okhttp3.RequestBody.Companion.toRequestBody
10
14
  import okhttp3.sse.EventSource
11
15
  import okhttp3.sse.EventSources
12
16
  import okhttp3.sse.EventSourceListener
13
- import okio.*
17
+ import okio.Buffer
18
+ import okio.ForwardingSource
19
+ import okio.buffer
14
20
  import com.margelo.nitro.core.AnyMap
15
21
  import org.json.JSONObject
16
22
  import org.json.JSONArray
@@ -54,6 +60,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
54
60
  @Volatile private var onEventsCallback: ((events: Array<SseEvent>) -> Unit)? = null
55
61
 
56
62
  private val isRunning = AtomicBoolean(false)
63
+ @Volatile private var isDispatcherDestroyed = false
57
64
  private var wasRunningBeforePaused = false
58
65
  private val consecutiveAuthErrors = AtomicInteger(0)
59
66
  private val maxAuthRetries = 3
@@ -89,7 +96,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
89
96
  val keys = jsonObject.keys()
90
97
  while (keys.hasNext()) {
91
98
  val key = keys.next()
92
- var value = jsonObject.get(key)
99
+ var value: Any? = jsonObject.get(key)
93
100
  if (value is JSONObject) {
94
101
  value = jsonObjectToMap(value)
95
102
  } else if (value is JSONArray) {
@@ -105,7 +112,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
105
112
  internal fun jsonArrayToList(jsonArray: JSONArray): List<Any?> {
106
113
  val list = mutableListOf<Any?>()
107
114
  for (i in 0 until jsonArray.length()) {
108
- var value = jsonArray.get(i)
115
+ var value: Any? = jsonArray.get(i)
109
116
  if (value is JSONObject) {
110
117
  value = jsonObjectToMap(value)
111
118
  } else if (value is JSONArray) {
@@ -131,13 +138,15 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
131
138
  this.onEventsCallback = onEvent
132
139
 
133
140
  if (this.client == null) {
134
- this.client = OkHttpClient.Builder()
141
+ val builder = OkHttpClient.Builder()
135
142
  .connectTimeout((config.connectionTimeoutMs ?: 15000.0).toLong(), TimeUnit.MILLISECONDS)
136
143
  .readTimeout((config.readTimeoutMs ?: 300000.0).toLong(), TimeUnit.MILLISECONDS)
137
144
  .addNetworkInterceptor(HeartbeatNetworkInterceptor(totalBytesReceived) {
138
145
  pushEventToBuffer(SseEvent(SseEventType.HEARTBEAT, null, null, null, null, "keep-alive", null, null))
139
146
  })
140
- .build()
147
+
148
+
149
+ this.client = builder.build()
141
150
  }
142
151
 
143
152
  if (sseHandlerThread == null) {
@@ -405,6 +414,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
405
414
  if (!isRunning.compareAndSet(false, true)) return
406
415
 
407
416
  consecutiveAuthErrors.set(0)
417
+ isDispatcherDestroyed = false
408
418
  val version = connectionAttemptVersion.incrementAndGet()
409
419
  sseHandler?.post {
410
420
  backoffCounter = 0
@@ -414,6 +424,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
414
424
  }
415
425
 
416
426
  private fun performConnection(version: Int) {
427
+ // Guard: connection attempt is discarded if client is stopped or a newer attempt is in progress
417
428
  if (!isRunning.get() || version != connectionAttemptVersion.get()) return
418
429
 
419
430
  val currentConfig = synchronized(this) { config } ?: return
@@ -423,23 +434,31 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
423
434
  val interceptorCompleted = AtomicBoolean(false)
424
435
  val timeoutMs = (currentConfig.connectionTimeoutMs ?: 15000.0).toLong()
425
436
 
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.
426
439
  sseHandler?.postDelayed({
427
440
  if (interceptorCompleted.compareAndSet(false, true)) {
428
441
  handleInterceptorError(Exception("onBeforeRequest interceptor timed out after $timeoutMs ms"), version)
429
442
  }
430
443
  }, timeoutMs)
431
444
 
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)
445
+ try {
446
+ interceptor.invoke().then { promise2 ->
447
+ promise2.then { newHeaders ->
448
+ sseHandler?.post {
449
+ if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
450
+ if (interceptorCompleted.compareAndSet(false, true)) {
451
+ synchronized(this) {
452
+ val mergedHeaders = (config?.headers ?: emptyMap()).toMutableMap()
453
+ newHeaders.forEach { (k, v) -> mergedHeaders[k] = v }
454
+ config = config?.copy(headers = mergedHeaders)
455
+ }
456
+ executeConnection(version)
441
457
  }
442
- executeConnection(version)
458
+ }
459
+ }.catch { error ->
460
+ if (interceptorCompleted.compareAndSet(false, true)) {
461
+ handleInterceptorError(error, version)
443
462
  }
444
463
  }
445
464
  }.catch { error ->
@@ -447,9 +466,9 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
447
466
  handleInterceptorError(error, version)
448
467
  }
449
468
  }
450
- }.catch { error ->
469
+ } catch (e: Throwable) {
451
470
  if (interceptorCompleted.compareAndSet(false, true)) {
452
- handleInterceptorError(error, version)
471
+ handleInterceptorError(e, version)
453
472
  }
454
473
  }
455
474
  } else {
@@ -471,8 +490,23 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
471
490
  sseHandler?.post {
472
491
  if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
473
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.
498
+ val isDispatcherDestroyedMsg = t?.message?.contains("Dispatcher has already been destroyed", ignoreCase = true) == true
499
+ if (isDispatcherDestroyedMsg) {
500
+ Log.w(TAG, "JS Dispatcher destroyed. Stopping SSE stream.")
501
+ this@NitroSse.isDispatcherDestroyed = true
502
+ isRunning.set(false)
503
+ connectionAttemptVersion.incrementAndGet()
504
+ performInternalCleanup()
505
+ return@post
506
+ }
507
+
474
508
  pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Interceptor Error: ${t?.message}", -1.0, null))
475
-
509
+
476
510
  // Reconnect with delay
477
511
  val currentJitterFactor = config?.jitterFactor ?: 0.5
478
512
  val currentRetryInterval = (config?.retryIntervalMs ?: 1000.0).toLong()
@@ -496,7 +530,6 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
496
530
  this.requestId = null
497
531
  }
498
532
 
499
- // Cancel existing event source if any before starting new one
500
533
  eventSource?.cancel()
501
534
  eventSource = null
502
535
 
@@ -782,8 +815,12 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
782
815
  }
783
816
 
784
817
  private fun performInternalCleanup() {
785
- // Runs on sseHandler thread
786
- flushBufferToJs()
818
+ if (!isDispatcherDestroyed) {
819
+ flushBufferToJs()
820
+ } else {
821
+ synchronized(eventBuffer) { eventBuffer.clear() }
822
+ isFlushPending.set(false)
823
+ }
787
824
  sseHandler?.removeCallbacks(flushRunnable)
788
825
  backoffCounter = 0
789
826
  eventSource?.cancel()
@@ -867,6 +904,8 @@ internal class HeartbeatNetworkInterceptor(
867
904
  if (bytesRead != -1L) {
868
905
  totalBytesReceived.addAndGet(bytesRead)
869
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.
870
909
  for (i in 0 until bytesRead) {
871
910
  val b = sink.get(bufferOffset + i)
872
911
  if (isAtStartOfLine && b == ':'.code.toByte()) {
@@ -875,7 +914,7 @@ internal class HeartbeatNetworkInterceptor(
875
914
  isAtStartOfLine = (b == '\n'.code.toByte() || b == '\r'.code.toByte())
876
915
  }
877
916
  } catch (e: Exception) {
878
- // Silent
917
+ // Silent fallback to prevent crashing the stream reader on random parse bugs
879
918
  }
880
919
  }
881
920
  return bytesRead
@@ -1,4 +1,5 @@
1
1
  import Foundation
2
+ import ObjectiveC
2
3
  import NitroModules
3
4
  import LDSwiftEventSource
4
5
  import Network
@@ -37,6 +38,7 @@ class NitroSse: HybridNitroSseSpec {
37
38
  private var config: SseConfig?
38
39
  private var onEventsCallback: ((_ events: [SseEvent]) -> Void)?
39
40
  private var isRunning: Bool = false
41
+ private var isDispatcherDestroyed: Bool = false
40
42
  private var consecutiveAuthErrors: Int = 0
41
43
  private let maxAuthRetries: Int = 3
42
44
  private var requestId: String? = nil
@@ -69,6 +71,8 @@ class NitroSse: HybridNitroSseSpec {
69
71
  private var lastPathInterface: NWInterface.InterfaceType?
70
72
  private var wasRunningBeforeNetworkLoss: Bool = false
71
73
 
74
+
75
+
72
76
  /**
73
77
  * Set up the NitroSse instance with configuration and an event callback.
74
78
  * This prepares the lifecycle observers and internal dispatch queue.
@@ -359,12 +363,12 @@ class NitroSse: HybridNitroSseSpec {
359
363
  let startBody = {
360
364
  guard !self.isRunning else { return }
361
365
 
362
- // Critical check: Ensure config is available before starting
363
366
  guard self.config != nil else {
364
367
  throw RuntimeError("NitroSse not configured. Call setup() first.")
365
368
  }
366
369
 
367
370
  self.isRunning = true
371
+ self.isDispatcherDestroyed = false
368
372
  self.consecutiveAuthErrors = 0
369
373
  self.backoffCounter = 0
370
374
  self.connectionAttemptVersion += 1
@@ -398,6 +402,8 @@ class NitroSse: HybridNitroSseSpec {
398
402
  let flag = CompletionFlag()
399
403
  let timeoutMs = capturedConfig.connectionTimeoutMs ?? 15000.0
400
404
 
405
+ // Concurrency Safeguard: If the JS async interceptor does not resolve
406
+ // within connectionTimeoutMs, throw a timeout error and recover.
401
407
  sseQueue.asyncAfter(deadline: .now() + (timeoutMs / 1000.0)) { [weak self] in
402
408
  guard let self = self else { return }
403
409
  self.sseQueue.async { [weak self] in
@@ -410,37 +416,47 @@ class NitroSse: HybridNitroSseSpec {
410
416
  }
411
417
  }
412
418
 
413
- interceptor().then { [weak self] promise2 in
414
- promise2.then { [weak self] newHeaders in
415
- self?.sseQueue.async { [weak self] in
416
- guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
417
- if !flag.isCompleted {
418
- flag.isCompleted = true
419
- let currentConfig = self.config ?? capturedConfig
420
- var mergedHeaders = currentConfig.headers ?? [:]
421
- for (k, v) in newHeaders {
422
- mergedHeaders[k] = v
419
+ do {
420
+ try interceptor().then { [weak self] promise2 in
421
+ promise2.then { [weak self] newHeaders in
422
+ self?.sseQueue.async { [weak self] in
423
+ guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
424
+ if !flag.isCompleted {
425
+ flag.isCompleted = true
426
+ let currentConfig = self.config ?? capturedConfig
427
+ var mergedHeaders = currentConfig.headers ?? [:]
428
+ for (k, v) in newHeaders {
429
+ mergedHeaders[k] = v
430
+ }
431
+ self.config = SseConfig(
432
+ url: currentConfig.url,
433
+ method: currentConfig.method,
434
+ headers: mergedHeaders,
435
+ body: currentConfig.body,
436
+ backgroundExecution: currentConfig.backgroundExecution,
437
+ batchingIntervalMs: currentConfig.batchingIntervalMs,
438
+ maxBufferSize: currentConfig.maxBufferSize,
439
+ connectionTimeoutMs: currentConfig.connectionTimeoutMs,
440
+ readTimeoutMs: currentConfig.readTimeoutMs,
441
+ retryIntervalMs: currentConfig.retryIntervalMs,
442
+ maxRetryIntervalMs: currentConfig.maxRetryIntervalMs,
443
+ jitterFactor: currentConfig.jitterFactor,
444
+ maxReconnectAttempts: currentConfig.maxReconnectAttempts,
445
+ autoParseJSON: currentConfig.autoParseJSON,
446
+ monitorNetwork: currentConfig.monitorNetwork,
447
+ onBeforeRequest: currentConfig.onBeforeRequest,
448
+ mock: currentConfig.mock
449
+ )
450
+ self.performEstablishConnection(attemptVersion: attemptVersion)
451
+ }
452
+ }
453
+ }.catch { [weak self] error in
454
+ self?.sseQueue.async { [weak self] in
455
+ guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
456
+ if !flag.isCompleted {
457
+ flag.isCompleted = true
458
+ self.handleInterceptorError(error, attemptVersion: attemptVersion)
423
459
  }
424
- self.config = SseConfig(
425
- url: currentConfig.url,
426
- method: currentConfig.method,
427
- headers: mergedHeaders,
428
- body: currentConfig.body,
429
- backgroundExecution: currentConfig.backgroundExecution,
430
- batchingIntervalMs: currentConfig.batchingIntervalMs,
431
- maxBufferSize: currentConfig.maxBufferSize,
432
- connectionTimeoutMs: currentConfig.connectionTimeoutMs,
433
- readTimeoutMs: currentConfig.readTimeoutMs,
434
- retryIntervalMs: currentConfig.retryIntervalMs,
435
- maxRetryIntervalMs: currentConfig.maxRetryIntervalMs,
436
- jitterFactor: currentConfig.jitterFactor,
437
- maxReconnectAttempts: currentConfig.maxReconnectAttempts,
438
- autoParseJSON: currentConfig.autoParseJSON,
439
- monitorNetwork: currentConfig.monitorNetwork,
440
- onBeforeRequest: currentConfig.onBeforeRequest,
441
- mock: currentConfig.mock
442
- )
443
- self.performEstablishConnection(attemptVersion: attemptVersion)
444
460
  }
445
461
  }
446
462
  }.catch { [weak self] error in
@@ -452,13 +468,10 @@ class NitroSse: HybridNitroSseSpec {
452
468
  }
453
469
  }
454
470
  }
455
- }.catch { [weak self] error in
456
- self?.sseQueue.async { [weak self] in
457
- guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
458
- if !flag.isCompleted {
459
- flag.isCompleted = true
460
- self.handleInterceptorError(error, attemptVersion: attemptVersion)
461
- }
471
+ } catch {
472
+ if !flag.isCompleted {
473
+ flag.isCompleted = true
474
+ self.handleInterceptorError(error, attemptVersion: attemptVersion)
462
475
  }
463
476
  }
464
477
  } else {
@@ -469,9 +482,18 @@ class NitroSse: HybridNitroSseSpec {
469
482
  private func handleInterceptorError(_ error: Error, attemptVersion: Int) {
470
483
  dispatchPrecondition(condition: .onQueue(sseQueue))
471
484
  guard self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
472
- print("[NitroSse] Interceptor failed: \(error.localizedDescription)")
485
+ let desc = error.localizedDescription
486
+ // Note: We use string matching here because react-native-nitro-modules (as of 0.36.1)
487
+ // throws a generic std::runtime_error from C++ when the Dispatcher is destroyed.
488
+ // It does not provide a specific Exception class (like DispatcherDestroyedException)
489
+ // that we can catch, so checking the message is currently the only workaround.
490
+ if desc.contains("Dispatcher has already been destroyed") {
491
+ print("[NitroSse] JS Dispatcher destroyed. Stopping SSE stream.")
492
+ self.isDispatcherDestroyed = true
493
+ self.stopInternal()
494
+ return
495
+ }
473
496
  self.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Interceptor Error: \(error.localizedDescription)", statusCode: -1, retry: nil))
474
- // Reconnect after delay
475
497
  self.scheduleAutomaticReconnect(isError: true, attemptVersion: attemptVersion)
476
498
  }
477
499
 
@@ -488,6 +510,8 @@ class NitroSse: HybridNitroSseSpec {
488
510
  let readTimeout = (config.readTimeoutMs ?? 300000.0) / 1000.0
489
511
  sessionConfig.timeoutIntervalForRequest = readTimeout
490
512
  sessionConfig.timeoutIntervalForResource = readTimeout
513
+
514
+
491
515
 
492
516
  let handler = SseHandler(parent: self, attemptVersion: attemptVersion)
493
517
  var esConfig = EventSource.Config(handler: handler, url: url)
@@ -525,6 +549,10 @@ class NitroSse: HybridNitroSseSpec {
525
549
  private func stopInternal() {
526
550
  dispatchPrecondition(condition: .onQueue(sseQueue))
527
551
  self.isRunning = false
552
+ if isDispatcherDestroyed {
553
+ eventBuffer.removeAll()
554
+ isFlushPending = false
555
+ }
528
556
  self.wasRunningBeforeNetworkLoss = false
529
557
  self.wasRunningBeforeHibernation = false
530
558
  self.eventSource?.stop()
@@ -713,6 +741,9 @@ class NitroSse: HybridNitroSseSpec {
713
741
  }
714
742
  }
715
743
 
744
+ // LDSwiftEventSource natively parses SSE stream comments (lines beginning with ':')
745
+ // and triggers onComment. Unlike Android (which requires manual byte scanning),
746
+ // on iOS we simply convert comment packets directly into heartbeat events.
716
747
  func onComment(comment: String) {
717
748
  guard let parent = self.parent, source === parent.eventSource else { return }
718
749
  parent.sseQueue.async { [weak parent] in
@@ -15,7 +15,7 @@ namespace margelo::nitro::nitrosse {
15
15
  using namespace facebook;
16
16
 
17
17
  /**
18
- * The C++ JNI bridge between the C++ enum "HttpMethod" and the the Kotlin enum "HttpMethod".
18
+ * The C++ JNI bridge between the C++ enum "HttpMethod" and the Kotlin enum "HttpMethod".
19
19
  */
20
20
  struct JHttpMethod final: public jni::JavaClass<JHttpMethod> {
21
21
  public:
@@ -37,7 +37,7 @@ namespace margelo::nitro::nitrosse {
37
37
  using namespace facebook;
38
38
 
39
39
  /**
40
- * The C++ JNI bridge between the C++ struct "SseConfig" and the the Kotlin data class "SseConfig".
40
+ * The C++ JNI bridge between the C++ struct "SseConfig" and the Kotlin data class "SseConfig".
41
41
  */
42
42
  struct JSseConfig final: public jni::JavaClass<JSseConfig> {
43
43
  public:
@@ -22,7 +22,7 @@ namespace margelo::nitro::nitrosse {
22
22
  using namespace facebook;
23
23
 
24
24
  /**
25
- * The C++ JNI bridge between the C++ struct "SseEvent" and the the Kotlin data class "SseEvent".
25
+ * The C++ JNI bridge between the C++ struct "SseEvent" and the Kotlin data class "SseEvent".
26
26
  */
27
27
  struct JSseEvent final: public jni::JavaClass<JSseEvent> {
28
28
  public:
@@ -15,7 +15,7 @@ namespace margelo::nitro::nitrosse {
15
15
  using namespace facebook;
16
16
 
17
17
  /**
18
- * The C++ JNI bridge between the C++ enum "SseEventType" and the the Kotlin enum "SseEventType".
18
+ * The C++ JNI bridge between the C++ enum "SseEventType" and the Kotlin enum "SseEventType".
19
19
  */
20
20
  struct JSseEventType final: public jni::JavaClass<JSseEventType> {
21
21
  public:
@@ -27,7 +27,7 @@ namespace margelo::nitro::nitrosse {
27
27
  using namespace facebook;
28
28
 
29
29
  /**
30
- * The C++ JNI bridge between the C++ struct "SseMockConfig" and the the Kotlin data class "SseMockConfig".
30
+ * The C++ JNI bridge between the C++ struct "SseMockConfig" and the Kotlin data class "SseMockConfig".
31
31
  */
32
32
  struct JSseMockConfig final: public jni::JavaClass<JSseMockConfig> {
33
33
  public:
@@ -22,7 +22,7 @@ namespace margelo::nitro::nitrosse {
22
22
  using namespace facebook;
23
23
 
24
24
  /**
25
- * The C++ JNI bridge between the C++ struct "SseMockEvent" and the the Kotlin data class "SseMockEvent".
25
+ * The C++ JNI bridge between the C++ struct "SseMockEvent" and the Kotlin data class "SseMockEvent".
26
26
  */
27
27
  struct JSseMockEvent final: public jni::JavaClass<JSseMockEvent> {
28
28
  public:
@@ -15,7 +15,7 @@ namespace margelo::nitro::nitrosse {
15
15
  using namespace facebook;
16
16
 
17
17
  /**
18
- * The C++ JNI bridge between the C++ enum "SseMockMode" and the the Kotlin enum "SseMockMode".
18
+ * The C++ JNI bridge between the C++ enum "SseMockMode" and the Kotlin enum "SseMockMode".
19
19
  */
20
20
  struct JSseMockMode final: public jni::JavaClass<JSseMockMode> {
21
21
  public:
@@ -18,7 +18,7 @@ namespace margelo::nitro::nitrosse {
18
18
  using namespace facebook;
19
19
 
20
20
  /**
21
- * The C++ JNI bridge between the C++ struct "SseStats" and the the Kotlin data class "SseStats".
21
+ * The C++ JNI bridge between the C++ struct "SseStats" and the Kotlin data class "SseStats".
22
22
  */
23
23
  struct JSseStats final: public jni::JavaClass<JSseStats> {
24
24
  public:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-nitro-sse",
3
- "version": "2.3.1",
3
+ "version": "2.3.2",
4
4
  "description": "High-performance Server-Sent Events (SSE) for React Native, powered by Nitro Modules.",
5
5
  "main": "./lib/module/index.js",
6
6
  "types": "./lib/typescript/src/index.d.ts",
@@ -91,12 +91,12 @@
91
91
  "eslint-plugin-prettier": "^5.5.4",
92
92
  "jest": "^29.7.0",
93
93
  "lefthook": "^2.0.3",
94
- "nitrogen": "0.35.9",
94
+ "nitrogen": "0.36.1",
95
95
  "prettier": "^2.8.8",
96
96
  "react": "19.2.3",
97
97
  "react-native": "0.85.3",
98
98
  "react-native-builder-bob": "^0.40.17",
99
- "react-native-nitro-modules": "0.35.9",
99
+ "react-native-nitro-modules": "0.36.1",
100
100
  "release-it": "^19.0.4",
101
101
  "turbo": "^2.5.6",
102
102
  "typescript": "^5.9.2"
@@ -104,7 +104,7 @@
104
104
  "peerDependencies": {
105
105
  "react": "*",
106
106
  "react-native": "*",
107
- "react-native-nitro-modules": ">= 0.35.9"
107
+ "react-native-nitro-modules": ">= 0.36.1"
108
108
  },
109
109
  "workspaces": [
110
110
  "example"