react-native-nitro-sse 1.5.0 → 1.6.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 +34 -37
- package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +130 -77
- package/android/src/test/java/com/margelo/nitro/nitrosse/NitroSseLogicTest.kt +58 -11
- package/ios/NitroSse.swift +154 -79
- package/ios/Tests/NitroSseTests.swift +36 -0
- package/lib/typescript/src/SseInterface.d.ts +18 -8
- package/lib/typescript/src/SseInterface.d.ts.map +1 -1
- package/nitro.json +8 -2
- package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.hpp +2 -2
- package/nitrogen/generated/android/c++/JFunc_void_std__vector_SseEvent_.hpp +2 -2
- package/nitrogen/generated/android/c++/JHttpMethod.hpp +1 -1
- package/nitrogen/generated/android/c++/JHybridNitroSseSpec.hpp +2 -2
- package/nitrogen/generated/android/c++/JSseConfig.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseEvent.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseEventType.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseStats.hpp +1 -1
- package/nitrogen/generated/android/nitrosseOnLoad.cpp +2 -2
- package/package.json +5 -5
- package/src/SseInterface.ts +18 -8
package/README.md
CHANGED
|
@@ -33,7 +33,8 @@ 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.
|
|
36
|
+
| **1.6.2** | **0.35.2** |
|
|
37
|
+
| **1.4.0 - 1.6.1** | **0.35.0** |
|
|
37
38
|
| **1.2.2 - 1.3.1** | **0.34.1** |
|
|
38
39
|
| **1.2.0 - 1.2.1** | **0.34.0** |
|
|
39
40
|
| **1.1.0** | **0.33.9** |
|
|
@@ -62,65 +63,61 @@ nitroSse.setup(
|
|
|
62
63
|
},
|
|
63
64
|
// Batch messages every 100ms to optimize UI rendering
|
|
64
65
|
batchingIntervalMs: 100,
|
|
65
|
-
// Maximum of 1000 messages in the native queue before
|
|
66
|
+
// Maximum of 1000 messages in the native queue before forced flush
|
|
66
67
|
maxBufferSize: 1000,
|
|
68
|
+
// Optional: Auto-refresh tokens or dynamic headers
|
|
69
|
+
onBeforeRequest: async () => {
|
|
70
|
+
const token = await fetchNewToken();
|
|
71
|
+
return { 'Authorization': `Bearer ${token}` };
|
|
72
|
+
}
|
|
67
73
|
},
|
|
68
74
|
(events) => {
|
|
75
|
+
// events is an array of SseEvent objects
|
|
69
76
|
events.forEach((event) => {
|
|
70
|
-
|
|
71
|
-
console.log('Data received:', event.data);
|
|
72
|
-
} else if (event.type === 'heartbeat') {
|
|
73
|
-
console.log('Server heartbeat detected...');
|
|
74
|
-
}
|
|
77
|
+
console.log('Received:', event);
|
|
75
78
|
});
|
|
76
79
|
}
|
|
77
80
|
);
|
|
78
81
|
|
|
79
82
|
// Start the connection
|
|
80
83
|
nitroSse.start();
|
|
81
|
-
|
|
82
|
-
// Stop the connection when unmounting or no longer needed
|
|
83
|
-
// nitroSse.stop();
|
|
84
84
|
```
|
|
85
85
|
|
|
86
|
+
### 2. Monitoring & Statistics
|
|
86
87
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
You can synchronously check the connection status at any time:
|
|
88
|
+
NitroSSE provides synchronous access to connection health and throughput data.
|
|
90
89
|
|
|
91
90
|
```tsx
|
|
92
|
-
const
|
|
93
|
-
console.log(
|
|
91
|
+
const stats = nitroSse.getStats();
|
|
92
|
+
console.log(`Downloaded: ${stats.totalBytesReceived / 1024} KB`);
|
|
93
|
+
console.log(`Reconnections: ${stats.reconnectCount}`);
|
|
94
94
|
```
|
|
95
95
|
|
|
96
|
+
---
|
|
96
97
|
|
|
97
|
-
|
|
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
|
-
```
|
|
98
|
+
## ⚙️ Configuration (SseConfig)
|
|
106
99
|
|
|
100
|
+
| Parameter | Type | Default | Description |
|
|
101
|
+
| :--- | :--- | :--- | :--- |
|
|
102
|
+
| `url` | `string` | - | **Required**. The URL of the SSE endpoint. |
|
|
103
|
+
| `method` | `'get' \| 'post'` | `get` | HTTP method. |
|
|
104
|
+
| `headers` | `Record<string, string>` | `{}` | Custom HTTP headers. |
|
|
105
|
+
| `body` | `string` | - | Request body (payload) for POST requests. |
|
|
106
|
+
| `batchingIntervalMs` | `number` | `0` | Time window (ms) to group events. `0` = real-time. |
|
|
107
|
+
| `maxBufferSize` | `number` | `1000` | Native queue limit to prevent memory overflow. |
|
|
108
|
+
| `connectionTimeoutMs`| `number` | `15000` | Max time for initial handshake / connect. |
|
|
109
|
+
| `readTimeoutMs` | `number` | `300000`| Max idle time between data packets before reconnecting. |
|
|
110
|
+
| `backgroundExecution` | `boolean` | `false` | (iOS) Attempt to maintain connection via background tasks. |
|
|
111
|
+
| `onBeforeRequest` | `function`| - | Async hook to refresh headers/tokens before every attempt. |
|
|
107
112
|
|
|
108
113
|
---
|
|
109
114
|
|
|
110
|
-
##
|
|
115
|
+
## 🛡️ Reliability Features (v1.5.1+)
|
|
111
116
|
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
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. |
|
|
121
|
-
| `connectionTimeoutMs`| `number` | Connection timeout in milliseconds (Default: 15000). |
|
|
122
|
-
| `readTimeoutMs` | `number` | Read/Idle timeout in milliseconds (Default: 35000). |
|
|
123
|
-
| `onBeforeRequest` | `function`| Async callback to refresh headers before every request attempt. |
|
|
117
|
+
- **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.
|
|
118
|
+
- **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.
|
|
119
|
+
- **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.
|
|
120
|
+
- **Cumulative Logic**: Statistics (`totalBytesReceived`) are preserved across reconnections, giving you a true 360-degree view of the session's data usage.
|
|
124
121
|
|
|
125
122
|
---
|
|
126
123
|
|
|
@@ -87,55 +87,11 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
|
|
|
87
87
|
if (this.client == null) {
|
|
88
88
|
this.client = OkHttpClient.Builder()
|
|
89
89
|
.connectTimeout((config.connectionTimeoutMs ?: 15000.0).toLong(), TimeUnit.MILLISECONDS)
|
|
90
|
-
.readTimeout((config.readTimeoutMs ?:
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
val response = chain.proceed(request)
|
|
96
|
-
|
|
97
|
-
rid?.let {
|
|
98
|
-
NetworkInspector.reportResponseStart(it, request, response)
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
val responseBody = response.body
|
|
102
|
-
if (responseBody != null) {
|
|
103
|
-
val countingBody = object : ResponseBody() {
|
|
104
|
-
override fun contentType() = responseBody.contentType()
|
|
105
|
-
override fun contentLength() = responseBody.contentLength()
|
|
106
|
-
override fun source() = (object : okio.ForwardingSource(responseBody.source()) {
|
|
107
|
-
private var isAtStartOfLine = true
|
|
108
|
-
|
|
109
|
-
override fun read(sink: okio.Buffer, byteCount: Long): Long {
|
|
110
|
-
val bufferOffset = sink.size
|
|
111
|
-
val bytesRead = super.read(sink, byteCount)
|
|
112
|
-
if (bytesRead != -1L) {
|
|
113
|
-
totalBytesReceived.addAndGet(bytesRead)
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
try {
|
|
117
|
-
for (i in 0 until bytesRead) {
|
|
118
|
-
val b = sink.get(bufferOffset + i)
|
|
119
|
-
if (isAtStartOfLine && b == ':'.code.toByte()) {
|
|
120
|
-
// This is a comment/heartbeat.
|
|
121
|
-
pushEventToBuffer(SseEvent(SseEventType.HEARTBEAT, null, null, null, "keep-alive", null, null))
|
|
122
|
-
}
|
|
123
|
-
isAtStartOfLine = (b == '\n'.code.toByte() || b == '\r'.code.toByte())
|
|
124
|
-
}
|
|
125
|
-
} catch (e: Exception) {
|
|
126
|
-
// Silent
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
return bytesRead
|
|
130
|
-
}
|
|
131
|
-
}).buffer()
|
|
132
|
-
}
|
|
133
|
-
response.newBuilder().body(countingBody).build()
|
|
134
|
-
} else {
|
|
135
|
-
response
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
.build()
|
|
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()
|
|
139
95
|
}
|
|
140
96
|
|
|
141
97
|
if (sseHandlerThread == null) {
|
|
@@ -169,6 +125,10 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
|
|
|
169
125
|
*/
|
|
170
126
|
override fun onStop(owner: LifecycleOwner) {
|
|
171
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
|
+
}
|
|
172
132
|
Log.d(TAG, "App backgrounded. Hibernating NitroSse connection.")
|
|
173
133
|
wasRunningBeforePaused = true
|
|
174
134
|
stop()
|
|
@@ -179,14 +139,15 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
|
|
|
179
139
|
val batchInterval = config?.batchingIntervalMs ?: 0.0
|
|
180
140
|
val bufferCapacity = config?.maxBufferSize?.toInt() ?: 1000
|
|
181
141
|
|
|
142
|
+
var shouldFlush = false
|
|
182
143
|
synchronized(eventBuffer) {
|
|
183
|
-
while (eventBuffer.size >= bufferCapacity) {
|
|
184
|
-
eventBuffer.removeAt(0)
|
|
185
|
-
}
|
|
186
144
|
eventBuffer.add(event)
|
|
145
|
+
if (eventBuffer.size >= bufferCapacity) {
|
|
146
|
+
shouldFlush = true
|
|
147
|
+
}
|
|
187
148
|
}
|
|
188
149
|
|
|
189
|
-
if (batchInterval <= 0) {
|
|
150
|
+
if (batchInterval <= 0 || shouldFlush) {
|
|
190
151
|
flushBufferToJs()
|
|
191
152
|
} else if (!isFlushPending.getAndSet(true)) {
|
|
192
153
|
sseHandler?.postDelayed({
|
|
@@ -246,13 +207,16 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
|
|
|
246
207
|
* This triggers the initial request and handles subsequent reconnections.
|
|
247
208
|
*/
|
|
248
209
|
override fun start() {
|
|
249
|
-
if (config == null
|
|
250
|
-
isRunning.
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
requestId = null
|
|
210
|
+
if (config == null) return
|
|
211
|
+
if (!isRunning.compareAndSet(false, true)) return
|
|
212
|
+
|
|
213
|
+
consecutiveAuthErrors.set(0)
|
|
254
214
|
val version = connectionAttemptVersion.incrementAndGet()
|
|
255
|
-
sseHandler?.post {
|
|
215
|
+
sseHandler?.post {
|
|
216
|
+
backoffCounter = 0
|
|
217
|
+
requestId = null
|
|
218
|
+
performConnection(version)
|
|
219
|
+
}
|
|
256
220
|
}
|
|
257
221
|
|
|
258
222
|
private fun performConnection(version: Int) {
|
|
@@ -262,22 +226,37 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
|
|
|
262
226
|
val interceptor = currentConfig.onBeforeRequest
|
|
263
227
|
|
|
264
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
|
+
|
|
265
238
|
interceptor.invoke().then { promise2 ->
|
|
266
239
|
promise2.then { newHeaders ->
|
|
267
240
|
sseHandler?.post {
|
|
268
241
|
if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
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)
|
|
273
249
|
}
|
|
274
|
-
executeConnection(version)
|
|
275
250
|
}
|
|
276
251
|
}.catch { error ->
|
|
277
|
-
|
|
252
|
+
if (interceptorCompleted.compareAndSet(false, true)) {
|
|
253
|
+
handleInterceptorError(error, version)
|
|
254
|
+
}
|
|
278
255
|
}
|
|
279
256
|
}.catch { error ->
|
|
280
|
-
|
|
257
|
+
if (interceptorCompleted.compareAndSet(false, true)) {
|
|
258
|
+
handleInterceptorError(error, version)
|
|
259
|
+
}
|
|
281
260
|
}
|
|
282
261
|
} else {
|
|
283
262
|
executeConnection(version)
|
|
@@ -307,7 +286,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
|
|
|
307
286
|
|
|
308
287
|
// Report end for previous request if it was running
|
|
309
288
|
requestId?.let {
|
|
310
|
-
NetworkInspector.reportResponseEnd(it, totalBytesReceived.
|
|
289
|
+
NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
|
|
311
290
|
this.requestId = null
|
|
312
291
|
}
|
|
313
292
|
|
|
@@ -490,34 +469,108 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
|
|
|
490
469
|
* Stop the SSE connection and clear any pending reconnect timers.
|
|
491
470
|
*/
|
|
492
471
|
override fun stop() {
|
|
493
|
-
flushBufferToJs()
|
|
494
472
|
isRunning.set(false)
|
|
495
|
-
|
|
496
|
-
sseHandler?.
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
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)
|
|
502
485
|
}
|
|
503
|
-
isFlushPending.set(false)
|
|
504
486
|
}
|
|
505
487
|
|
|
506
488
|
/**
|
|
507
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.
|
|
508
491
|
*/
|
|
509
492
|
override fun dispose() {
|
|
510
493
|
Log.d(TAG, "Disposing NitroSse instance and cleaning up resources...")
|
|
511
|
-
|
|
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
|
+
|
|
512
509
|
if (hasSubscribedToLifecycle) {
|
|
513
510
|
Handler(Looper.getMainLooper()).post {
|
|
514
511
|
ProcessLifecycleOwner.get().lifecycle.removeObserver(this@NitroSse)
|
|
515
512
|
}
|
|
516
513
|
hasSubscribedToLifecycle = false
|
|
517
514
|
}
|
|
515
|
+
|
|
516
|
+
sseHandler?.removeCallbacksAndMessages(null)
|
|
518
517
|
sseHandlerThread?.quitSafely()
|
|
519
518
|
sseHandlerThread = null
|
|
520
519
|
sseHandler = null
|
|
520
|
+
|
|
521
521
|
super.dispose()
|
|
522
522
|
}
|
|
523
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
|
+
}
|
|
@@ -91,20 +91,67 @@ class NitroSseLogicTest {
|
|
|
91
91
|
}
|
|
92
92
|
|
|
93
93
|
@Test
|
|
94
|
-
fun
|
|
95
|
-
|
|
96
|
-
var isAtStartOfLine = true
|
|
94
|
+
fun testAuthenticationErrorsReset() {
|
|
95
|
+
var consecutiveAuthErrors = 3
|
|
97
96
|
|
|
98
|
-
fun
|
|
99
|
-
|
|
100
|
-
heartbeatCount.incrementAndGet()
|
|
101
|
-
}
|
|
102
|
-
isAtStartOfLine = (b == '\n'.toByte() || b == '\r'.toByte())
|
|
97
|
+
fun onOpened() {
|
|
98
|
+
consecutiveAuthErrors = 0
|
|
103
99
|
}
|
|
100
|
+
|
|
101
|
+
onOpened()
|
|
102
|
+
assertEquals(0, consecutiveAuthErrors)
|
|
103
|
+
}
|
|
104
104
|
|
|
105
|
-
|
|
106
|
-
|
|
105
|
+
@Test
|
|
106
|
+
fun testCumulativeStatsAcrossAttempts() {
|
|
107
|
+
val totalBytesReceived = AtomicInteger(0)
|
|
108
|
+
|
|
109
|
+
fun simulateDataReceived(bytes: Int) {
|
|
110
|
+
totalBytesReceived.addAndGet(bytes)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
fun stopConnection() {
|
|
114
|
+
// New logic: We don't reset totalBytesReceived in stop/reportResponseEnd anymore
|
|
115
|
+
// requestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
simulateDataReceived(100)
|
|
119
|
+
stopConnection()
|
|
120
|
+
simulateDataReceived(200)
|
|
121
|
+
|
|
122
|
+
assertEquals(300, totalBytesReceived.get())
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
@Test
|
|
126
|
+
fun testVersioningSafeguard() {
|
|
127
|
+
val connectionAttemptVersion = AtomicInteger(0)
|
|
128
|
+
var connectionExecutedCount = 0
|
|
129
|
+
|
|
130
|
+
fun start() {
|
|
131
|
+
val versionAtStart = connectionAttemptVersion.get()
|
|
132
|
+
|
|
133
|
+
// Simulate async interceptor delay
|
|
134
|
+
val delayResolvedWithVersion = versionAtStart
|
|
135
|
+
|
|
136
|
+
// Before executing, check version
|
|
137
|
+
if (delayResolvedWithVersion == connectionAttemptVersion.get()) {
|
|
138
|
+
connectionExecutedCount++
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
fun stop() {
|
|
143
|
+
connectionAttemptVersion.incrementAndGet()
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Scenario: Start -> Stop -> Interceptor returns for OLD Start
|
|
147
|
+
val version1 = connectionAttemptVersion.get()
|
|
148
|
+
stop() // User cancels before start finishes
|
|
149
|
+
|
|
150
|
+
// Old "start" logic tries to finish
|
|
151
|
+
if (version1 == connectionAttemptVersion.get()) {
|
|
152
|
+
connectionExecutedCount++
|
|
153
|
+
}
|
|
107
154
|
|
|
108
|
-
assertEquals(
|
|
155
|
+
assertEquals(0, connectionExecutedCount)
|
|
109
156
|
}
|
|
110
157
|
}
|
package/ios/NitroSse.swift
CHANGED
|
@@ -15,6 +15,17 @@ import LDSwiftEventSource
|
|
|
15
15
|
* as a single array after a configurable interval.
|
|
16
16
|
*/
|
|
17
17
|
class NitroSse: HybridNitroSseSpec {
|
|
18
|
+
private static let sseQueueKey = DispatchSpecificKey<Void>()
|
|
19
|
+
|
|
20
|
+
deinit {
|
|
21
|
+
if DispatchQueue.getSpecific(key: NitroSse.sseQueueKey) != nil {
|
|
22
|
+
self.stopInternal()
|
|
23
|
+
} else {
|
|
24
|
+
sseQueue.sync {
|
|
25
|
+
self.stopInternal()
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
18
29
|
private var eventSource: EventSource?
|
|
19
30
|
private var config: SseConfig?
|
|
20
31
|
private var onEventsCallback: ((_ events: [SseEvent]) -> Void)?
|
|
@@ -37,7 +48,11 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
37
48
|
private let baseBackoffDelay: TimeInterval = 1.0
|
|
38
49
|
private let maxBackoffDelay: TimeInterval = 30.0
|
|
39
50
|
|
|
40
|
-
private let sseQueue
|
|
51
|
+
private let sseQueue: DispatchQueue = {
|
|
52
|
+
let queue = DispatchQueue(label: "com.margelo.nitro.sse", qos: .utility)
|
|
53
|
+
queue.setSpecific(key: NitroSse.sseQueueKey, value: ())
|
|
54
|
+
return queue
|
|
55
|
+
}()
|
|
41
56
|
private var connectionAttemptVersion: Int = 0
|
|
42
57
|
private var backgroundTaskIdentifier: UIBackgroundTaskIdentifier = .invalid
|
|
43
58
|
private var wasRunningBeforeHibernation: Bool = false
|
|
@@ -51,38 +66,55 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
51
66
|
* - onEvent: Callback function to receive batched SSE events.
|
|
52
67
|
*/
|
|
53
68
|
func setup(config: SseConfig, onEvent: @escaping ((_ events: [SseEvent]) -> Void)) throws {
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
69
|
+
sseQueue.async {
|
|
70
|
+
self.config = config
|
|
71
|
+
self.onEventsCallback = onEvent
|
|
72
|
+
|
|
73
|
+
NotificationCenter.default.removeObserver(self)
|
|
74
|
+
NotificationCenter.default.addObserver(self, selector: #selector(self.handleAppDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
|
|
75
|
+
NotificationCenter.default.addObserver(self, selector: #selector(self.handleAppWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
|
|
76
|
+
}
|
|
60
77
|
}
|
|
61
78
|
|
|
62
79
|
@objc private func handleAppDidEnterBackground() {
|
|
63
80
|
sseQueue.async {
|
|
64
|
-
guard self.isRunning else { return }
|
|
65
|
-
|
|
66
|
-
self.wasRunningBeforeHibernation = true
|
|
67
|
-
print("[NitroSse] App backgrounded. Hibernating connection.")
|
|
81
|
+
guard self.isRunning, let config = self.config else { return }
|
|
68
82
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
self.requestId = nil
|
|
83
|
+
if config.backgroundExecution == true {
|
|
84
|
+
print("[NitroSse] App backgrounded. backgroundExecution is true, keeping connection alive.")
|
|
85
|
+
// Start a background task to tell the OS we want to keep running
|
|
86
|
+
self.backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(withName: "NitroSse-KeepAlive") { [weak self] in
|
|
87
|
+
self?.sseQueue.async {
|
|
88
|
+
print("[NitroSse] Background task expired. Hibernating now.")
|
|
89
|
+
self?.hibernateConnection()
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return
|
|
80
93
|
}
|
|
81
|
-
self.isRunning = false
|
|
82
94
|
|
|
83
|
-
self.
|
|
95
|
+
self.hibernateConnection()
|
|
84
96
|
}
|
|
85
97
|
}
|
|
98
|
+
|
|
99
|
+
private func hibernateConnection() {
|
|
100
|
+
dispatchPrecondition(condition: .onQueue(sseQueue))
|
|
101
|
+
guard self.isRunning else { return }
|
|
102
|
+
|
|
103
|
+
self.wasRunningBeforeHibernation = true
|
|
104
|
+
print("[NitroSse] Hibernating NitroSse connection.")
|
|
105
|
+
|
|
106
|
+
self.flushEventsToJs()
|
|
107
|
+
|
|
108
|
+
self.eventSource?.stop()
|
|
109
|
+
self.eventSource = nil
|
|
110
|
+
if let rid = self.requestId {
|
|
111
|
+
NitroSseNetworkInspector.reportResponseEnd(rid, encodedDataLength: Int(self.totalBytesReceived))
|
|
112
|
+
self.requestId = nil
|
|
113
|
+
}
|
|
114
|
+
self.isRunning = false
|
|
115
|
+
|
|
116
|
+
self.cleanupBackgroundTask()
|
|
117
|
+
}
|
|
86
118
|
|
|
87
119
|
@objc private func handleAppWillEnterForeground() {
|
|
88
120
|
sseQueue.async {
|
|
@@ -96,6 +128,7 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
96
128
|
}
|
|
97
129
|
|
|
98
130
|
private func cleanupBackgroundTask() {
|
|
131
|
+
dispatchPrecondition(condition: .onQueue(sseQueue))
|
|
99
132
|
if self.backgroundTaskIdentifier != .invalid {
|
|
100
133
|
UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier)
|
|
101
134
|
self.backgroundTaskIdentifier = .invalid
|
|
@@ -108,17 +141,17 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
108
141
|
let batchIntervalMs = config?.batchingIntervalMs ?? 0
|
|
109
142
|
let bufferCapacity = Int(config?.maxBufferSize ?? 1000)
|
|
110
143
|
|
|
111
|
-
while eventBuffer.count >= bufferCapacity {
|
|
112
|
-
eventBuffer.removeFirst()
|
|
113
|
-
}
|
|
114
144
|
eventBuffer.append(event)
|
|
115
145
|
|
|
116
|
-
|
|
146
|
+
// If we reached capacity, flush immediately regardless of interval
|
|
147
|
+
if eventBuffer.count >= bufferCapacity || batchIntervalMs <= 0 {
|
|
117
148
|
flushEventsToJs()
|
|
118
149
|
} else if !isFlushPending {
|
|
119
150
|
isFlushPending = true
|
|
120
151
|
sseQueue.asyncAfter(deadline: .now() + (Double(batchIntervalMs) / 1000.0)) { [weak self] in
|
|
121
|
-
self?.
|
|
152
|
+
self?.sseQueue.async {
|
|
153
|
+
self?.flushEventsToJs()
|
|
154
|
+
}
|
|
122
155
|
}
|
|
123
156
|
}
|
|
124
157
|
}
|
|
@@ -151,7 +184,7 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
151
184
|
*/
|
|
152
185
|
func updateHeaders(headers: [String: String]) throws {
|
|
153
186
|
sseQueue.async {
|
|
154
|
-
guard
|
|
187
|
+
guard let config = self.config else { return }
|
|
155
188
|
self.config = SseConfig(
|
|
156
189
|
url: config.url,
|
|
157
190
|
method: config.method,
|
|
@@ -162,7 +195,7 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
162
195
|
maxBufferSize: config.maxBufferSize,
|
|
163
196
|
connectionTimeoutMs: config.connectionTimeoutMs,
|
|
164
197
|
readTimeoutMs: config.readTimeoutMs,
|
|
165
|
-
onBeforeRequest: config.onBeforeRequest
|
|
198
|
+
onBeforeRequest: config.onBeforeRequest
|
|
166
199
|
)
|
|
167
200
|
print("[NitroSse] Headers updated for subsequent connections.")
|
|
168
201
|
}
|
|
@@ -187,15 +220,28 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
187
220
|
* This triggers the initial request and handles subsequent reconnections.
|
|
188
221
|
*/
|
|
189
222
|
func start() throws {
|
|
190
|
-
|
|
223
|
+
let startBody = {
|
|
191
224
|
guard !self.isRunning else { return }
|
|
225
|
+
|
|
226
|
+
// Critical check: Ensure config is available before starting
|
|
227
|
+
guard self.config != nil else {
|
|
228
|
+
throw NSError(domain: "NitroSse", code: -1, userInfo: [NSLocalizedDescriptionKey: "NitroSse not configured. Call setup() first."])
|
|
229
|
+
}
|
|
230
|
+
|
|
192
231
|
self.isRunning = true
|
|
193
|
-
self.consecutiveAuthErrors = 0
|
|
232
|
+
self.consecutiveAuthErrors = 0
|
|
194
233
|
self.backoffCounter = 0
|
|
195
234
|
self.connectionAttemptVersion += 1
|
|
196
235
|
let version = self.connectionAttemptVersion
|
|
236
|
+
|
|
197
237
|
self.establishConnection(attemptVersion: version)
|
|
198
238
|
}
|
|
239
|
+
|
|
240
|
+
if DispatchQueue.getSpecific(key: NitroSse.sseQueueKey) != nil {
|
|
241
|
+
try startBody()
|
|
242
|
+
} else {
|
|
243
|
+
try sseQueue.sync(execute: startBody)
|
|
244
|
+
}
|
|
199
245
|
}
|
|
200
246
|
|
|
201
247
|
private func establishConnection(attemptVersion: Int) {
|
|
@@ -203,35 +249,69 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
203
249
|
guard isRunning, let config = config, attemptVersion == self.connectionAttemptVersion else { return }
|
|
204
250
|
|
|
205
251
|
if let interceptor = config.onBeforeRequest {
|
|
206
|
-
|
|
252
|
+
|
|
207
253
|
let capturedConfig = config
|
|
254
|
+
class CompletionFlag {
|
|
255
|
+
var isCompleted = false
|
|
256
|
+
}
|
|
257
|
+
let flag = CompletionFlag()
|
|
258
|
+
let timeoutMs = capturedConfig.connectionTimeoutMs ?? 15000.0
|
|
259
|
+
|
|
260
|
+
sseQueue.asyncAfter(deadline: .now() + (timeoutMs / 1000.0)) { [weak self] in
|
|
261
|
+
guard let self = self else { return }
|
|
262
|
+
self.sseQueue.async {
|
|
263
|
+
guard self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
|
|
264
|
+
if !flag.isCompleted {
|
|
265
|
+
flag.isCompleted = true
|
|
266
|
+
let error = NSError(domain: "NitroSse", code: -1, userInfo: [NSLocalizedDescriptionKey: "onBeforeRequest interceptor timed out after \(timeoutMs) ms"])
|
|
267
|
+
self.handleInterceptorError(error, attemptVersion: attemptVersion)
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
208
272
|
interceptor().then { [weak self] promise2 in
|
|
209
273
|
promise2.then { [weak self] newHeaders in
|
|
210
274
|
self?.sseQueue.async {
|
|
211
275
|
guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
276
|
+
if !flag.isCompleted {
|
|
277
|
+
flag.isCompleted = true
|
|
278
|
+
let currentConfig = self.config ?? capturedConfig
|
|
279
|
+
var mergedHeaders = currentConfig.headers ?? [:]
|
|
280
|
+
for (k, v) in newHeaders {
|
|
281
|
+
mergedHeaders[k] = v
|
|
282
|
+
}
|
|
283
|
+
self.config = SseConfig(
|
|
284
|
+
url: currentConfig.url,
|
|
285
|
+
method: currentConfig.method,
|
|
286
|
+
headers: mergedHeaders,
|
|
287
|
+
body: currentConfig.body,
|
|
288
|
+
backgroundExecution: currentConfig.backgroundExecution,
|
|
289
|
+
batchingIntervalMs: currentConfig.batchingIntervalMs,
|
|
290
|
+
maxBufferSize: currentConfig.maxBufferSize,
|
|
291
|
+
connectionTimeoutMs: currentConfig.connectionTimeoutMs,
|
|
292
|
+
readTimeoutMs: currentConfig.readTimeoutMs,
|
|
293
|
+
onBeforeRequest: currentConfig.onBeforeRequest
|
|
294
|
+
)
|
|
295
|
+
self.performEstablishConnection(attemptVersion: attemptVersion)
|
|
215
296
|
}
|
|
216
|
-
self.config = SseConfig(
|
|
217
|
-
url: capturedConfig.url,
|
|
218
|
-
method: capturedConfig.method,
|
|
219
|
-
headers: mergedHeaders,
|
|
220
|
-
body: capturedConfig.body,
|
|
221
|
-
backgroundExecution: capturedConfig.backgroundExecution,
|
|
222
|
-
batchingIntervalMs: capturedConfig.batchingIntervalMs,
|
|
223
|
-
maxBufferSize: capturedConfig.maxBufferSize,
|
|
224
|
-
connectionTimeoutMs: capturedConfig.connectionTimeoutMs,
|
|
225
|
-
readTimeoutMs: capturedConfig.readTimeoutMs,
|
|
226
|
-
onBeforeRequest: capturedConfig.onBeforeRequest
|
|
227
|
-
)
|
|
228
|
-
self.performEstablishConnection(attemptVersion: attemptVersion)
|
|
229
297
|
}
|
|
230
298
|
}.catch { [weak self] error in
|
|
231
|
-
self?.
|
|
299
|
+
self?.sseQueue.async {
|
|
300
|
+
guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
|
|
301
|
+
if !flag.isCompleted {
|
|
302
|
+
flag.isCompleted = true
|
|
303
|
+
self.handleInterceptorError(error, attemptVersion: attemptVersion)
|
|
304
|
+
}
|
|
305
|
+
}
|
|
232
306
|
}
|
|
233
307
|
}.catch { [weak self] error in
|
|
234
|
-
self?.
|
|
308
|
+
self?.sseQueue.async {
|
|
309
|
+
guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
|
|
310
|
+
if !flag.isCompleted {
|
|
311
|
+
flag.isCompleted = true
|
|
312
|
+
self.handleInterceptorError(error, attemptVersion: attemptVersion)
|
|
313
|
+
}
|
|
314
|
+
}
|
|
235
315
|
}
|
|
236
316
|
} else {
|
|
237
317
|
self.performEstablishConnection(attemptVersion: attemptVersion)
|
|
@@ -239,13 +319,12 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
239
319
|
}
|
|
240
320
|
|
|
241
321
|
private func handleInterceptorError(_ error: Error, attemptVersion: Int) {
|
|
242
|
-
sseQueue
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
}
|
|
322
|
+
dispatchPrecondition(condition: .onQueue(sseQueue))
|
|
323
|
+
guard self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
|
|
324
|
+
print("[NitroSse] Interceptor failed: \(error.localizedDescription)")
|
|
325
|
+
self.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Interceptor Error: \(error.localizedDescription)", statusCode: -1, retry: nil))
|
|
326
|
+
// Reconnect after delay
|
|
327
|
+
self.scheduleAutomaticReconnect(isError: true, attemptVersion: attemptVersion)
|
|
249
328
|
}
|
|
250
329
|
|
|
251
330
|
private func performEstablishConnection(attemptVersion: Int) {
|
|
@@ -257,13 +336,10 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
257
336
|
self.requestId = nil
|
|
258
337
|
}
|
|
259
338
|
|
|
260
|
-
|
|
261
339
|
let sessionConfig = URLSessionConfiguration.default
|
|
262
|
-
|
|
263
|
-
sessionConfig.
|
|
264
|
-
|
|
265
|
-
sessionConfig.timeoutIntervalForRequest = connTimeout / 1000.0
|
|
266
|
-
}
|
|
340
|
+
let readTimeout = (config.readTimeoutMs ?? 300000.0) / 1000.0
|
|
341
|
+
sessionConfig.timeoutIntervalForRequest = readTimeout
|
|
342
|
+
sessionConfig.timeoutIntervalForResource = readTimeout
|
|
267
343
|
|
|
268
344
|
let handler = SseHandler(parent: self, attemptVersion: attemptVersion)
|
|
269
345
|
var esConfig = EventSource.Config(handler: handler, url: url)
|
|
@@ -293,11 +369,13 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
293
369
|
*/
|
|
294
370
|
func stop() {
|
|
295
371
|
sseQueue.async {
|
|
372
|
+
self.connectionAttemptVersion += 1
|
|
296
373
|
self.stopInternal()
|
|
297
374
|
}
|
|
298
375
|
}
|
|
299
376
|
|
|
300
377
|
private func stopInternal() {
|
|
378
|
+
dispatchPrecondition(condition: .onQueue(sseQueue))
|
|
301
379
|
self.isRunning = false
|
|
302
380
|
self.eventSource?.stop()
|
|
303
381
|
self.eventSource = nil
|
|
@@ -325,7 +403,6 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
325
403
|
func restart() {
|
|
326
404
|
sseQueue.async {
|
|
327
405
|
self.stopInternal()
|
|
328
|
-
guard !self.isRunning else { return } // Should be false now
|
|
329
406
|
self.isRunning = true
|
|
330
407
|
self.requestId = nil
|
|
331
408
|
self.connectionAttemptVersion += 1
|
|
@@ -361,16 +438,16 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
361
438
|
return nil
|
|
362
439
|
}
|
|
363
440
|
|
|
364
|
-
// EventSource callback handling is done via SseHandler class below.
|
|
365
|
-
|
|
366
|
-
|
|
367
441
|
private func scheduleAutomaticReconnectWithFixedDelay(_ delay: TimeInterval, attemptVersion: Int) {
|
|
368
442
|
dispatchPrecondition(condition: .onQueue(sseQueue))
|
|
369
443
|
eventSource?.stop()
|
|
370
444
|
eventSource = nil
|
|
371
445
|
sseQueue.asyncAfter(deadline: .now() + delay) { [weak self] in
|
|
372
|
-
guard let self = self
|
|
373
|
-
self.
|
|
446
|
+
guard let self = self else { return }
|
|
447
|
+
self.sseQueue.async {
|
|
448
|
+
guard self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
|
|
449
|
+
self.establishConnection(attemptVersion: attemptVersion)
|
|
450
|
+
}
|
|
374
451
|
}
|
|
375
452
|
}
|
|
376
453
|
|
|
@@ -387,12 +464,14 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
387
464
|
delay = defaultRetryDelay * (0.8 + Double.random(in: 0...0.4))
|
|
388
465
|
}
|
|
389
466
|
let safeDelay = max(delay, 2.0)
|
|
390
|
-
let currentSource = self.eventSource
|
|
391
467
|
eventSource?.stop()
|
|
392
468
|
eventSource = nil
|
|
393
469
|
sseQueue.asyncAfter(deadline: .now() + safeDelay) { [weak self] in
|
|
394
|
-
guard let self = self
|
|
395
|
-
self.
|
|
470
|
+
guard let self = self else { return }
|
|
471
|
+
self.sseQueue.async {
|
|
472
|
+
guard self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
|
|
473
|
+
self.establishConnection(attemptVersion: attemptVersion)
|
|
474
|
+
}
|
|
396
475
|
}
|
|
397
476
|
}
|
|
398
477
|
|
|
@@ -411,9 +490,7 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
411
490
|
parent.sseQueue.async { [weak parent] in
|
|
412
491
|
guard let parent = parent, self.attemptVersion == parent.connectionAttemptVersion else { return }
|
|
413
492
|
parent.backoffCounter = 0
|
|
414
|
-
parent.consecutiveAuthErrors = 0
|
|
415
|
-
// LDSwiftEventSource doesn't easily expose the response code in onOpened,
|
|
416
|
-
// but we assume 200 if onOpened is called.
|
|
493
|
+
parent.consecutiveAuthErrors = 0
|
|
417
494
|
parent.pushEventToBuffer(SseEvent(type: .open, data: nil, id: nil, event: nil, message: nil, statusCode: 200, retry: nil))
|
|
418
495
|
}
|
|
419
496
|
}
|
|
@@ -471,14 +548,12 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
471
548
|
NitroSseNetworkInspector.reportRequestFailed(parent.requestId, cancelled: false)
|
|
472
549
|
parent.requestId = nil
|
|
473
550
|
|
|
474
|
-
|
|
475
551
|
if statusCode == 204 {
|
|
476
552
|
parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "No Content (204). Stopping.", statusCode: 204, retry: nil))
|
|
477
553
|
parent.stopInternal()
|
|
478
554
|
return
|
|
479
555
|
}
|
|
480
556
|
|
|
481
|
-
// 401/403 are recoverable if we have an interceptor, but with a limit
|
|
482
557
|
if statusCode == 401 || statusCode == 403 {
|
|
483
558
|
if parent.config?.onBeforeRequest == nil {
|
|
484
559
|
parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Auth Error (\(statusCode)) - No interceptor provided. Stopping.", statusCode: Double(statusCode), retry: nil))
|
|
@@ -83,4 +83,40 @@ class NitroSseTests: XCTestCase {
|
|
|
83
83
|
let size = calculateSize(eventType: "message", data: "{\"id\":1}", lastId: "event-1")
|
|
84
84
|
XCTAssertEqual(size, 22.0) // 8 (data) + 7 (type) + 7 (id) = 22 bytes
|
|
85
85
|
}
|
|
86
|
+
|
|
87
|
+
func testVersioningSafety() {
|
|
88
|
+
var connectionAttemptVersion: Int32 = 0
|
|
89
|
+
var executeCount = 0
|
|
90
|
+
|
|
91
|
+
func stop() {
|
|
92
|
+
connectionAttemptVersion += 1
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Start called, captures version 0
|
|
96
|
+
let capturedVersion = connectionAttemptVersion
|
|
97
|
+
|
|
98
|
+
// User stops immediately
|
|
99
|
+
stop()
|
|
100
|
+
|
|
101
|
+
// Connection logic tries to execute
|
|
102
|
+
func establishConnection(version: Int32) {
|
|
103
|
+
if version == connectionAttemptVersion {
|
|
104
|
+
executeCount += 1
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
establishConnection(version: capturedVersion)
|
|
109
|
+
XCTAssertEqual(executeCount, 0, "Should not execute if version changed")
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
func testAuthErrorReset() {
|
|
113
|
+
var consecutiveAuthErrors = 3
|
|
114
|
+
|
|
115
|
+
func onOpened() {
|
|
116
|
+
consecutiveAuthErrors = 0
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
onOpened()
|
|
120
|
+
XCTAssertEqual(consecutiveAuthErrors, 0, "Errors should reset on success")
|
|
121
|
+
}
|
|
86
122
|
}
|
|
@@ -25,30 +25,40 @@ export interface SseConfig {
|
|
|
25
25
|
body?: string;
|
|
26
26
|
/**
|
|
27
27
|
* Whether to continue processing events when the app is in the background.
|
|
28
|
-
* Note:
|
|
28
|
+
* Note: On iOS, this uses background tasks which are limited in time by the OS.
|
|
29
29
|
* @default false
|
|
30
30
|
*/
|
|
31
31
|
backgroundExecution?: boolean;
|
|
32
32
|
/**
|
|
33
|
-
*
|
|
34
|
-
*
|
|
33
|
+
* How long (in ms) to wait and group multiple events before sending them to the JS side.
|
|
34
|
+
* High-frequency streams should use this to reduce JS bridge overhead and improve UI performance.
|
|
35
|
+
* Set to 0 to deliver events immediately one-by-one.
|
|
36
|
+
* @default 0
|
|
35
37
|
*/
|
|
36
38
|
batchingIntervalMs?: number;
|
|
37
39
|
/**
|
|
38
|
-
* Maximum number of events to
|
|
40
|
+
* Maximum number of events to keep in the native buffer before forcing a flush to JS,
|
|
41
|
+
* regardless of the `batchingIntervalMs`. Prevents memory pressure.
|
|
42
|
+
* @default 1000
|
|
39
43
|
*/
|
|
40
44
|
maxBufferSize?: number;
|
|
41
45
|
/**
|
|
42
|
-
*
|
|
46
|
+
* Maximum time (in ms) to wait for the initial server connection and handshake to complete.
|
|
47
|
+
* Effectively the "Connect Timeout".
|
|
48
|
+
* @default 15000
|
|
43
49
|
*/
|
|
44
50
|
connectionTimeoutMs?: number;
|
|
45
51
|
/**
|
|
46
|
-
*
|
|
52
|
+
* Maximum idle time (in ms) allowed between receiving data packets or heartbeats.
|
|
53
|
+
* If the server remains silent longer than this, the connection is considered stalled and will reconnect.
|
|
54
|
+
* Increase this for streams that transmit data infrequently.
|
|
55
|
+
* @default 300000
|
|
47
56
|
*/
|
|
48
57
|
readTimeoutMs?: number;
|
|
49
58
|
/**
|
|
50
|
-
*
|
|
51
|
-
*
|
|
59
|
+
* Async interceptor called before every connection attempt (including auto-reconnects).
|
|
60
|
+
* Use this to refresh tokens or calculate dynamic headers.
|
|
61
|
+
* Note: This is protected by a native timeout to prevent the app from hanging.
|
|
52
62
|
*/
|
|
53
63
|
onBeforeRequest?: () => Promise<Record<string, string>>;
|
|
54
64
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SseInterface.d.ts","sourceRoot":"","sources":["../../../src/SseInterface.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,MAAM,UAAU,GAAG,KAAK,GAAG,MAAM,CAAC;AAExC;;;;;;;GAOG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,SAAS,GAAG,OAAO,GAAG,OAAO,GAAG,WAAW,CAAC;AAEhF;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,mCAAmC;IACnC,GAAG,EAAE,MAAM,CAAC;IACZ,oCAAoC;IACpC,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,qDAAqD;IACrD,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,8BAA8B;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B
|
|
1
|
+
{"version":3,"file":"SseInterface.d.ts","sourceRoot":"","sources":["../../../src/SseInterface.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,MAAM,UAAU,GAAG,KAAK,GAAG,MAAM,CAAC;AAExC;;;;;;;GAOG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,SAAS,GAAG,OAAO,GAAG,OAAO,GAAG,WAAW,CAAC;AAEhF;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,mCAAmC;IACnC,GAAG,EAAE,MAAM,CAAC;IACZ,oCAAoC;IACpC,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,qDAAqD;IACrD,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,8BAA8B;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B;;;;;OAKG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B;;;;;OAKG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CACzD;AAED;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,6BAA6B;IAC7B,IAAI,EAAE,YAAY,CAAC;IACnB,qCAAqC;IACrC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,iCAAiC;IACjC,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,mEAAmE;IACnE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,2CAA2C;IAC3C,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,sCAAsC;IACtC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,oDAAoD;IACpD,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,mCAAmC;IACnC,kBAAkB,EAAE,MAAM,CAAC;IAC3B,8DAA8D;IAC9D,cAAc,EAAE,MAAM,CAAC;IACvB,yCAAyC;IACzC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,oCAAoC;IACpC,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB"}
|
package/nitro.json
CHANGED
|
@@ -9,8 +9,14 @@
|
|
|
9
9
|
},
|
|
10
10
|
"autolinking": {
|
|
11
11
|
"NitroSse": {
|
|
12
|
-
"
|
|
13
|
-
|
|
12
|
+
"ios": {
|
|
13
|
+
"language": "swift",
|
|
14
|
+
"implementationClassName": "NitroSse"
|
|
15
|
+
},
|
|
16
|
+
"android": {
|
|
17
|
+
"language": "kotlin",
|
|
18
|
+
"implementationClassName": "NitroSse"
|
|
19
|
+
}
|
|
14
20
|
}
|
|
15
21
|
},
|
|
16
22
|
"ignorePaths": ["node_modules"]
|
|
@@ -27,7 +27,7 @@ namespace margelo::nitro::nitrosse {
|
|
|
27
27
|
*/
|
|
28
28
|
struct JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____: public jni::JavaClass<JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____> {
|
|
29
29
|
public:
|
|
30
|
-
static auto
|
|
30
|
+
static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/nitrosse/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____;";
|
|
31
31
|
|
|
32
32
|
public:
|
|
33
33
|
/**
|
|
@@ -122,7 +122,7 @@ namespace margelo::nitro::nitrosse {
|
|
|
122
122
|
}
|
|
123
123
|
|
|
124
124
|
public:
|
|
125
|
-
static auto
|
|
125
|
+
static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/nitrosse/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______cxx;";
|
|
126
126
|
static void registerNatives() {
|
|
127
127
|
registerHybrid({makeNativeMethod("invoke_cxx", JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______cxx::invoke_cxx)});
|
|
128
128
|
}
|
|
@@ -30,7 +30,7 @@ namespace margelo::nitro::nitrosse {
|
|
|
30
30
|
*/
|
|
31
31
|
struct JFunc_void_std__vector_SseEvent_: public jni::JavaClass<JFunc_void_std__vector_SseEvent_> {
|
|
32
32
|
public:
|
|
33
|
-
static auto
|
|
33
|
+
static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/nitrosse/Func_void_std__vector_SseEvent_;";
|
|
34
34
|
|
|
35
35
|
public:
|
|
36
36
|
/**
|
|
@@ -84,7 +84,7 @@ namespace margelo::nitro::nitrosse {
|
|
|
84
84
|
}
|
|
85
85
|
|
|
86
86
|
public:
|
|
87
|
-
static auto
|
|
87
|
+
static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/nitrosse/Func_void_std__vector_SseEvent__cxx;";
|
|
88
88
|
static void registerNatives() {
|
|
89
89
|
registerHybrid({makeNativeMethod("invoke_cxx", JFunc_void_std__vector_SseEvent__cxx::invoke_cxx)});
|
|
90
90
|
}
|
|
@@ -19,7 +19,7 @@ namespace margelo::nitro::nitrosse {
|
|
|
19
19
|
*/
|
|
20
20
|
struct JHttpMethod final: public jni::JavaClass<JHttpMethod> {
|
|
21
21
|
public:
|
|
22
|
-
static auto
|
|
22
|
+
static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/nitrosse/HttpMethod;";
|
|
23
23
|
|
|
24
24
|
public:
|
|
25
25
|
/**
|
|
@@ -21,11 +21,11 @@ namespace margelo::nitro::nitrosse {
|
|
|
21
21
|
class JHybridNitroSseSpec: public virtual HybridNitroSseSpec, public virtual JHybridObject {
|
|
22
22
|
public:
|
|
23
23
|
struct JavaPart: public jni::JavaClass<JavaPart, JHybridObject::JavaPart> {
|
|
24
|
-
static auto
|
|
24
|
+
static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/nitrosse/HybridNitroSseSpec;";
|
|
25
25
|
std::shared_ptr<JHybridNitroSseSpec> getJHybridNitroSseSpec();
|
|
26
26
|
};
|
|
27
27
|
struct CxxPart: public jni::HybridClass<CxxPart, JHybridObject::CxxPart> {
|
|
28
|
-
static auto
|
|
28
|
+
static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/nitrosse/HybridNitroSseSpec$CxxPart;";
|
|
29
29
|
static jni::local_ref<jhybriddata> initHybrid(jni::alias_ref<jhybridobject> jThis);
|
|
30
30
|
static void registerNatives();
|
|
31
31
|
using HybridBase::HybridBase;
|
|
@@ -30,7 +30,7 @@ namespace margelo::nitro::nitrosse {
|
|
|
30
30
|
*/
|
|
31
31
|
struct JSseConfig final: public jni::JavaClass<JSseConfig> {
|
|
32
32
|
public:
|
|
33
|
-
static auto
|
|
33
|
+
static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/nitrosse/SseConfig;";
|
|
34
34
|
|
|
35
35
|
public:
|
|
36
36
|
/**
|
|
@@ -24,7 +24,7 @@ namespace margelo::nitro::nitrosse {
|
|
|
24
24
|
*/
|
|
25
25
|
struct JSseEvent final: public jni::JavaClass<JSseEvent> {
|
|
26
26
|
public:
|
|
27
|
-
static auto
|
|
27
|
+
static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/nitrosse/SseEvent;";
|
|
28
28
|
|
|
29
29
|
public:
|
|
30
30
|
/**
|
|
@@ -19,7 +19,7 @@ namespace margelo::nitro::nitrosse {
|
|
|
19
19
|
*/
|
|
20
20
|
struct JSseEventType final: public jni::JavaClass<JSseEventType> {
|
|
21
21
|
public:
|
|
22
|
-
static auto
|
|
22
|
+
static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/nitrosse/SseEventType;";
|
|
23
23
|
|
|
24
24
|
public:
|
|
25
25
|
/**
|
|
@@ -22,7 +22,7 @@ namespace margelo::nitro::nitrosse {
|
|
|
22
22
|
*/
|
|
23
23
|
struct JSseStats final: public jni::JavaClass<JSseStats> {
|
|
24
24
|
public:
|
|
25
|
-
static auto
|
|
25
|
+
static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/nitrosse/SseStats;";
|
|
26
26
|
|
|
27
27
|
public:
|
|
28
28
|
/**
|
|
@@ -29,9 +29,9 @@ int initialize(JavaVM* vm) {
|
|
|
29
29
|
}
|
|
30
30
|
|
|
31
31
|
struct JHybridNitroSseSpecImpl: public jni::JavaClass<JHybridNitroSseSpecImpl, JHybridNitroSseSpec::JavaPart> {
|
|
32
|
-
static auto
|
|
32
|
+
static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/nitrosse/NitroSse;";
|
|
33
33
|
static std::shared_ptr<JHybridNitroSseSpec> create() {
|
|
34
|
-
static auto constructorFn = javaClassStatic()->getConstructor<JHybridNitroSseSpecImpl::javaobject()>();
|
|
34
|
+
static const auto constructorFn = javaClassStatic()->getConstructor<JHybridNitroSseSpecImpl::javaobject()>();
|
|
35
35
|
jni::local_ref<JHybridNitroSseSpec::JavaPart> javaPart = javaClassStatic()->newObject(constructorFn);
|
|
36
36
|
return javaPart->getJHybridNitroSseSpec();
|
|
37
37
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-native-nitro-sse",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.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",
|
|
@@ -84,12 +84,12 @@
|
|
|
84
84
|
"eslint-plugin-prettier": "^5.5.4",
|
|
85
85
|
"jest": "^29.7.0",
|
|
86
86
|
"lefthook": "^2.0.3",
|
|
87
|
-
"nitrogen": "0.35.
|
|
87
|
+
"nitrogen": "0.35.2",
|
|
88
88
|
"prettier": "^2.8.8",
|
|
89
89
|
"react": "19.2.0",
|
|
90
90
|
"react-native": "0.83.0",
|
|
91
91
|
"react-native-builder-bob": "^0.40.17",
|
|
92
|
-
"react-native-nitro-modules": "0.35.
|
|
92
|
+
"react-native-nitro-modules": "0.35.2",
|
|
93
93
|
"release-it": "^19.0.4",
|
|
94
94
|
"turbo": "^2.5.6",
|
|
95
95
|
"typescript": "^5.9.2"
|
|
@@ -97,7 +97,7 @@
|
|
|
97
97
|
"peerDependencies": {
|
|
98
98
|
"react": "*",
|
|
99
99
|
"react-native": "*",
|
|
100
|
-
"react-native-nitro-modules": "0.35.
|
|
100
|
+
"react-native-nitro-modules": ">= 0.35.2"
|
|
101
101
|
},
|
|
102
102
|
"workspaces": [
|
|
103
103
|
"example"
|
|
@@ -177,4 +177,4 @@
|
|
|
177
177
|
],
|
|
178
178
|
"version": "0.57.0"
|
|
179
179
|
}
|
|
180
|
-
}
|
|
180
|
+
}
|
package/src/SseInterface.ts
CHANGED
|
@@ -27,30 +27,40 @@ export interface SseConfig {
|
|
|
27
27
|
body?: string;
|
|
28
28
|
/**
|
|
29
29
|
* Whether to continue processing events when the app is in the background.
|
|
30
|
-
* Note:
|
|
30
|
+
* Note: On iOS, this uses background tasks which are limited in time by the OS.
|
|
31
31
|
* @default false
|
|
32
32
|
*/
|
|
33
33
|
backgroundExecution?: boolean;
|
|
34
34
|
/**
|
|
35
|
-
*
|
|
36
|
-
*
|
|
35
|
+
* How long (in ms) to wait and group multiple events before sending them to the JS side.
|
|
36
|
+
* High-frequency streams should use this to reduce JS bridge overhead and improve UI performance.
|
|
37
|
+
* Set to 0 to deliver events immediately one-by-one.
|
|
38
|
+
* @default 0
|
|
37
39
|
*/
|
|
38
40
|
batchingIntervalMs?: number;
|
|
39
41
|
/**
|
|
40
|
-
* Maximum number of events to
|
|
42
|
+
* Maximum number of events to keep in the native buffer before forcing a flush to JS,
|
|
43
|
+
* regardless of the `batchingIntervalMs`. Prevents memory pressure.
|
|
44
|
+
* @default 1000
|
|
41
45
|
*/
|
|
42
46
|
maxBufferSize?: number;
|
|
43
47
|
/**
|
|
44
|
-
*
|
|
48
|
+
* Maximum time (in ms) to wait for the initial server connection and handshake to complete.
|
|
49
|
+
* Effectively the "Connect Timeout".
|
|
50
|
+
* @default 15000
|
|
45
51
|
*/
|
|
46
52
|
connectionTimeoutMs?: number;
|
|
47
53
|
/**
|
|
48
|
-
*
|
|
54
|
+
* Maximum idle time (in ms) allowed between receiving data packets or heartbeats.
|
|
55
|
+
* If the server remains silent longer than this, the connection is considered stalled and will reconnect.
|
|
56
|
+
* Increase this for streams that transmit data infrequently.
|
|
57
|
+
* @default 300000
|
|
49
58
|
*/
|
|
50
59
|
readTimeoutMs?: number;
|
|
51
60
|
/**
|
|
52
|
-
*
|
|
53
|
-
*
|
|
61
|
+
* Async interceptor called before every connection attempt (including auto-reconnects).
|
|
62
|
+
* Use this to refresh tokens or calculate dynamic headers.
|
|
63
|
+
* Note: This is protected by a native timeout to prevent the app from hanging.
|
|
54
64
|
*/
|
|
55
65
|
onBeforeRequest?: () => Promise<Record<string, string>>;
|
|
56
66
|
}
|