react-native-nitro-sse 1.6.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,154 +4,235 @@ import org.junit.Assert.*
4
4
  import org.junit.Before
5
5
  import org.junit.Test
6
6
  import java.util.concurrent.atomic.AtomicInteger
7
+ import kotlin.random.Random
7
8
 
8
9
  class NitroSseLogicTest {
9
10
 
10
11
  private lateinit var eventBuffer: MutableList<SseEvent>
11
12
  private var bufferCapacity = 100
12
- private var batchInterval = 0.0
13
+ private var flushCount = 0
13
14
 
14
15
  @Before
15
16
  fun setup() {
16
17
  eventBuffer = mutableListOf()
18
+ flushCount = 0
17
19
  }
18
20
 
19
- private fun pushEventToBuffer(event: SseEvent, onFlush: () -> Unit) {
21
+ private fun pushEventToBuffer(event: SseEvent) {
20
22
  synchronized(eventBuffer) {
21
- while (eventBuffer.size >= bufferCapacity) {
22
- eventBuffer.removeAt(0)
23
- }
24
23
  eventBuffer.add(event)
25
- }
26
-
27
- if (batchInterval <= 0) {
28
- onFlush()
24
+ if (eventBuffer.size >= bufferCapacity) {
25
+ // Simulate flush logic from NitroSse.kt
26
+ flushCount++
27
+ eventBuffer.clear()
28
+ }
29
29
  }
30
30
  }
31
31
 
32
32
  @Test
33
- fun testBufferCapacityLimit() {
33
+ fun testZeroLossBufferingFlush() {
34
34
  bufferCapacity = 5
35
- batchInterval = 100.0 // Enable batching so we don't flush immediately
36
35
 
37
- for (i in 1..10) {
38
- pushEventToBuffer(SseEvent(SseEventType.MESSAGE, "data $i", "$i", null, null, null, null)) {}
36
+ // Fill buffer to capacity
37
+ for (i in 1..5) {
38
+ pushEventToBuffer(SseEvent(SseEventType.MESSAGE, "data $i", "$i", null, null, null, null))
39
39
  }
40
40
 
41
- assertEquals(5, eventBuffer.size)
42
- assertEquals("6", eventBuffer[0].id)
43
- assertEquals("10", eventBuffer[4].id)
41
+ assertEquals(1, flushCount)
42
+ assertEquals(0, eventBuffer.size)
43
+
44
+ // Check it doesn't drop items when not at capacity
45
+ for (i in 1..3) {
46
+ pushEventToBuffer(SseEvent(SseEventType.MESSAGE, "data $i", "$i", null, null, null, null))
47
+ }
48
+ assertEquals(3, eventBuffer.size)
49
+ assertEquals(1, flushCount)
50
+ }
51
+
52
+ @Test
53
+ fun testBackoffWithJitterCalculation() {
54
+ val retryIntervalMs = 1000L
55
+ val maxRetryIntervalMs = 30000L
56
+ val jitterFactor = 0.5
57
+
58
+ fun calculateDelay(counter: Int, jitter: Double): Long {
59
+ val base = Math.min(retryIntervalMs * (1 shl counter), maxRetryIntervalMs)
60
+ // Logic from NitroSse.kt: (base * (1.0 - jitterFactor + Random.nextDouble() * 2 * jitterFactor)).toLong()
61
+ return (base * (1.0 - jitterFactor + jitter * 2 * jitterFactor)).toLong()
62
+ }
63
+
64
+ // Test range for counter 0 (Base 1000ms)
65
+ // Min: 1000 * (0.5 + 0) = 500ms
66
+ // Max: 1000 * (0.5 + 1.0) = 1500ms
67
+ assertEquals(500L, calculateDelay(0, 0.0))
68
+ assertEquals(1500L, calculateDelay(0, 1.0))
69
+
70
+ // Test range for counter 5 (Base 32000ms -> Capped 30000ms)
71
+ // Min: 30000 * 0.5 = 15000ms
72
+ // Max: 30000 * 1.5 = 45000ms
73
+ assertEquals(15000L, calculateDelay(5, 0.0))
74
+ assertEquals(45000L, calculateDelay(5, 1.0))
44
75
  }
45
76
 
46
77
  @Test
47
- fun testImmediateFlushWhenNoBatching() {
48
- batchInterval = 0.0
49
- val flushCount = AtomicInteger(0)
78
+ fun testMaxReconnectAttemptsStop() {
79
+ val maxAttempts = 3
80
+ var currentReconnectAttempts = 0
81
+ var isRunning = true
82
+
83
+ fun onFailure() {
84
+ if (currentReconnectAttempts >= maxAttempts) {
85
+ isRunning = false
86
+ return
87
+ }
88
+ currentReconnectAttempts++
89
+ }
50
90
 
51
- pushEventToBuffer(SseEvent(SseEventType.OPEN, null, null, null, null, null, null)) {
52
- flushCount.incrementAndGet()
91
+ for (i in 1..3) {
92
+ onFailure()
53
93
  }
94
+ assertTrue(isRunning)
95
+ assertEquals(3, currentReconnectAttempts)
54
96
 
55
- assertEquals(1, flushCount.get())
97
+ onFailure() // 4th call, current (3) >= max (3)
98
+ assertFalse(isRunning)
99
+ }
100
+
101
+ @Test
102
+ fun testAuthErrorLogic() {
103
+ fun shouldRetry(statusCode: Int, hasInterceptor: Boolean, consecutiveAuthErrors: Int): Boolean {
104
+ val maxAuthRetries = 3
105
+ if (statusCode == 401 || statusCode == 403) {
106
+ if (!hasInterceptor) return false
107
+ if (consecutiveAuthErrors >= maxAuthRetries) return false
108
+ return true
109
+ }
110
+ return false
111
+ }
112
+
113
+ // Case 1: 401 without interceptor -> Fail
114
+ assertFalse(shouldRetry(statusCode = 401, hasInterceptor = false, consecutiveAuthErrors = 0))
115
+
116
+ // Case 2: 401 with interceptor -> Retry
117
+ assertTrue(shouldRetry(statusCode = 401, hasInterceptor = true, consecutiveAuthErrors = 0))
118
+
119
+ // Case 3: 401 reaching limit (3) -> Fail
120
+ assertFalse(shouldRetry(statusCode = 401, hasInterceptor = true, consecutiveAuthErrors = 3))
121
+ }
122
+
123
+ @Test
124
+ fun testFatalErrorLogic() {
125
+ fun isFatal(statusCode: Int): Boolean {
126
+ return statusCode == 400 || statusCode == 204
127
+ }
128
+
129
+ assertTrue(isFatal(400))
130
+ assertTrue(isFatal(204))
131
+ assertFalse(isFatal(500))
132
+ assertFalse(isFatal(401))
56
133
  }
57
134
 
58
135
  @Test
59
136
  fun testRetryAfterExtraction() {
60
- // Mock non-standard retry after logic (conceptual check of the method)
61
137
  fun extractMillis(headerValue: String?): Long? {
62
138
  if (headerValue == null) return null
63
139
  return try {
64
140
  headerValue.toLong() * 1000L
65
141
  } catch (e: Exception) {
66
- null // Simplifying for the logic test
142
+ null // Simplifying for logic test
67
143
  }
68
144
  }
69
145
 
70
146
  assertEquals(5000L, extractMillis("5"))
71
147
  assertEquals(60000L, extractMillis("60"))
72
- assertNull(extractMillis(null))
73
- assertNull(extractMillis("invalid"))
74
- }
75
-
76
- @Test
77
- fun testBackoffCalculation() {
78
- val baseBackoffDelayMs = 2000L
79
- val maxBackoffDelayMs = 30000L
80
148
 
81
- fun calculateDelay(counter: Int): Long {
82
- return Math.min(baseBackoffDelayMs * (1 shl counter), maxBackoffDelayMs)
149
+ // Mocking the date parsing behavior from NitroSse.kt
150
+ fun extractDateMillis(headerValue: String?): Long? {
151
+ if (headerValue == "Wed, 21 Oct 2015 07:28:00 GMT") return 10000L // Mocked diff
152
+ return null
83
153
  }
154
+ assertEquals(10000L, extractDateMillis("Wed, 21 Oct 2015 07:28:00 GMT"))
84
155
 
85
- assertEquals(2000L, calculateDelay(0))
86
- assertEquals(4000L, calculateDelay(1))
87
- assertEquals(8000L, calculateDelay(2))
88
- assertEquals(16000L, calculateDelay(3))
89
- assertEquals(30000L, calculateDelay(4)) // Capped at max
90
- assertEquals(30000L, calculateDelay(10)) // Still capped
156
+ assertNull(extractMillis(null))
157
+ assertNull(extractMillis("invalid"))
91
158
  }
92
159
 
93
160
  @Test
94
- fun testAuthenticationErrorsReset() {
95
- var consecutiveAuthErrors = 3
161
+ fun testStartIdempotency() {
162
+ val isRunning = AtomicInteger(0)
96
163
 
97
- fun onOpened() {
98
- consecutiveAuthErrors = 0
164
+ fun start() {
165
+ // Simulated compareAndSet(false, true) logic
166
+ if (isRunning.get() == 0) {
167
+ isRunning.set(1)
168
+ }
99
169
  }
100
170
 
101
- onOpened()
102
- assertEquals(0, consecutiveAuthErrors)
171
+ start()
172
+ assertEquals(1, isRunning.get())
173
+ start()
174
+ assertEquals(1, isRunning.get()) // Should not have changed
103
175
  }
104
176
 
105
177
  @Test
106
- fun testCumulativeStatsAcrossAttempts() {
107
- val totalBytesReceived = AtomicInteger(0)
178
+ fun testConcurrentStartStopVersioning() {
179
+ val connectionAttemptVersion = AtomicInteger(0)
180
+ var executeCount = 0
108
181
 
109
- fun simulateDataReceived(bytes: Int) {
110
- totalBytesReceived.addAndGet(bytes)
182
+ fun start(): Int {
183
+ return connectionAttemptVersion.get()
111
184
  }
112
185
 
113
- fun stopConnection() {
114
- // New logic: We don't reset totalBytesReceived in stop/reportResponseEnd anymore
115
- // requestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
186
+ fun stop() {
187
+ connectionAttemptVersion.incrementAndGet()
188
+ }
189
+
190
+ fun finishConnection(version: Int) {
191
+ if (version == connectionAttemptVersion.get()) {
192
+ executeCount++
193
+ }
116
194
  }
117
195
 
118
- simulateDataReceived(100)
119
- stopConnection()
120
- simulateDataReceived(200)
196
+ // 1. User starts
197
+ val v1 = start()
121
198
 
122
- assertEquals(300, totalBytesReceived.get())
199
+ // 2. User stops immediately
200
+ stop()
201
+
202
+ // 3. Logic tries to finish with old version
203
+ finishConnection(v1)
204
+ assertEquals(0, executeCount)
205
+
206
+ // 4. New start
207
+ val v2 = start()
208
+ finishConnection(v2)
209
+ assertEquals(1, executeCount)
123
210
  }
124
211
 
125
212
  @Test
126
- fun testVersioningSafeguard() {
127
- val connectionAttemptVersion = AtomicInteger(0)
128
- var connectionExecutedCount = 0
213
+ fun testStatsPersistenceAcrossAttempts() {
214
+ var totalBytes = 0L
215
+ var reconnectCount = 0
129
216
 
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
- }
217
+ fun recordAttempt(bytes: Long) {
218
+ reconnectCount++
219
+ totalBytes += bytes
140
220
  }
141
221
 
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
222
+ recordAttempt(1024)
223
+ recordAttempt(2048)
149
224
 
150
- // Old "start" logic tries to finish
151
- if (version1 == connectionAttemptVersion.get()) {
152
- connectionExecutedCount++
153
- }
225
+ assertEquals(2, reconnectCount)
226
+ assertEquals(3072L, totalBytes)
227
+ }
228
+
229
+ @Test
230
+ fun testHeartbeatDetectionCount() {
231
+ val totalBytes = 100L
232
+ val comment = ":ping"
154
233
 
155
- assertEquals(0, connectionExecutedCount)
234
+ // Just verify math logic for byte counting in Network Interceptor
235
+ val newTotal = totalBytes + comment.toByteArray(Charsets.UTF_8).size
236
+ assertEquals(105L, newTotal)
156
237
  }
157
238
  }
@@ -37,6 +37,7 @@ class NitroSse: HybridNitroSseSpec {
37
37
  private var isFlushPending: Bool = false
38
38
 
39
39
  private var backoffCounter: Int = 0
40
+ private var currentReconnectAttempts: Int = 0
40
41
  private var lastProcessedId: String? = nil
41
42
 
42
43
  private var totalBytesReceived: Double = 0
@@ -44,10 +45,6 @@ class NitroSse: HybridNitroSseSpec {
44
45
  private var lastErrorTime: Double? = nil
45
46
  private var lastErrorCode: String? = nil
46
47
 
47
- private let defaultRetryDelay: TimeInterval = 3.0
48
- private let baseBackoffDelay: TimeInterval = 1.0
49
- private let maxBackoffDelay: TimeInterval = 30.0
50
-
51
48
  private let sseQueue: DispatchQueue = {
52
49
  let queue = DispatchQueue(label: "com.margelo.nitro.sse", qos: .utility)
53
50
  queue.setSpecific(key: NitroSse.sseQueueKey, value: ())
@@ -179,9 +176,9 @@ class NitroSse: HybridNitroSseSpec {
179
176
  }
180
177
  }
181
178
 
182
- /**
183
- * Dynamically update the headers for subsequent connection attempts.
184
- */
179
+ /// Update the HTTP headers that will be used for subsequent SSE connections.
180
+ /// - Parameters:
181
+ /// - headers: A dictionary of HTTP header names and values to replace the current headers for future connections.
185
182
  func updateHeaders(headers: [String: String]) throws {
186
183
  sseQueue.async {
187
184
  guard let config = self.config else { return }
@@ -195,6 +192,10 @@ class NitroSse: HybridNitroSseSpec {
195
192
  maxBufferSize: config.maxBufferSize,
196
193
  connectionTimeoutMs: config.connectionTimeoutMs,
197
194
  readTimeoutMs: config.readTimeoutMs,
195
+ retryIntervalMs: config.retryIntervalMs,
196
+ maxRetryIntervalMs: config.maxRetryIntervalMs,
197
+ jitterFactor: config.jitterFactor,
198
+ maxReconnectAttempts: config.maxReconnectAttempts,
198
199
  onBeforeRequest: config.onBeforeRequest
199
200
  )
200
201
  print("[NitroSse] Headers updated for subsequent connections.")
@@ -244,6 +245,11 @@ class NitroSse: HybridNitroSseSpec {
244
245
  }
245
246
  }
246
247
 
248
+ /// Initiates a new SSE connection attempt using the current configuration, honoring the provided attempt version to ignore stale async work.
249
+ ///
250
+ /// If a configured `onBeforeRequest` interceptor is present, this method executes it (with a configurable timeout); when the interceptor resolves with additional headers those headers are merged into the active configuration before proceeding. If the interceptor fails or times out, interceptor error handling is invoked. If no interceptor is configured, the connection is established immediately.
251
+ /// - Parameters:
252
+ /// - attemptVersion: A numeric token representing the connection attempt version; the method aborts if this does not match the current `connectionAttemptVersion`, ensuring stale asynchronous results are ignored.
247
253
  private func establishConnection(attemptVersion: Int) {
248
254
  dispatchPrecondition(condition: .onQueue(sseQueue))
249
255
  guard isRunning, let config = config, attemptVersion == self.connectionAttemptVersion else { return }
@@ -290,6 +296,10 @@ class NitroSse: HybridNitroSseSpec {
290
296
  maxBufferSize: currentConfig.maxBufferSize,
291
297
  connectionTimeoutMs: currentConfig.connectionTimeoutMs,
292
298
  readTimeoutMs: currentConfig.readTimeoutMs,
299
+ retryIntervalMs: currentConfig.retryIntervalMs,
300
+ maxRetryIntervalMs: currentConfig.maxRetryIntervalMs,
301
+ jitterFactor: currentConfig.jitterFactor,
302
+ maxReconnectAttempts: currentConfig.maxReconnectAttempts,
293
303
  onBeforeRequest: currentConfig.onBeforeRequest
294
304
  )
295
305
  self.performEstablishConnection(attemptVersion: attemptVersion)
@@ -451,19 +461,42 @@ class NitroSse: HybridNitroSseSpec {
451
461
  }
452
462
  }
453
463
 
464
+ /// Schedules an automatic reconnection attempt using the configured retry interval, exponential backoff, and jitter.
465
+ ///
466
+ /// If the configured maximum reconnect attempts has been reached, this method emits an error event and stops the connection instead of scheduling a reconnect. Otherwise it increments the reconnect attempt counter, computes a delay (exponential backoff when `isError` is true, with jitter applied and a minimum delay of 1 second), clears the current event source, and schedules `establishConnection(attemptVersion:)` to run after the computed delay only if the client is still running and the provided `attemptVersion` matches the current connection attempt version.
467
+ /// - Parameters:
468
+ /// - isError: Whether the reconnect is being scheduled in response to an error (affects use of exponential backoff).
469
+ /// - attemptVersion: The connection attempt version that must match the current `connectionAttemptVersion` when the scheduled reconnect fires; used to ignore stale or superseded reconnect attempts.
454
470
  private func scheduleAutomaticReconnect(isError: Bool, attemptVersion: Int) {
455
471
  dispatchPrecondition(condition: .onQueue(sseQueue))
456
472
  eventSource?.stop()
457
- var delay: TimeInterval = defaultRetryDelay
473
+
474
+ let jitterFactor = config?.jitterFactor ?? 0.5
475
+ let retryInterval = (config?.retryIntervalMs ?? 1000.0) / 1000.0
476
+ let maxRetryInterval = (config?.maxRetryIntervalMs ?? 30000.0) / 1000.0
477
+
478
+ var delay: TimeInterval = retryInterval
479
+
480
+ let maxAttempts = Int(config?.maxReconnectAttempts ?? -1.0)
481
+ if maxAttempts != -1 && currentReconnectAttempts >= maxAttempts {
482
+ print("[NitroSse] Max reconnection attempts reached (\(maxAttempts)). Stopping.")
483
+ self.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Max reconnection attempts reached (\(maxAttempts)).", statusCode: nil, retry: nil))
484
+ self.stopInternal()
485
+ return
486
+ }
487
+
488
+ currentReconnectAttempts += 1
489
+
458
490
  if isError {
459
491
  let exponent = Double(backoffCounter)
460
- let base = min(baseBackoffDelay * pow(2.0, exponent), maxBackoffDelay)
492
+ let base = min(retryInterval * pow(2.0, exponent), maxRetryInterval)
461
493
  backoffCounter += 1
462
- delay = base * (0.5 + Double.random(in: 0...1))
494
+ delay = base * (1.0 - jitterFactor + Double.random(in: 0...(2 * jitterFactor)))
463
495
  } else {
464
- delay = defaultRetryDelay * (0.8 + Double.random(in: 0...0.4))
496
+ delay = retryInterval * (1.0 - jitterFactor + Double.random(in: 0...(2 * jitterFactor)))
465
497
  }
466
- let safeDelay = max(delay, 2.0)
498
+
499
+ let safeDelay = max(delay, 1.0)
467
500
  eventSource?.stop()
468
501
  eventSource = nil
469
502
  sseQueue.asyncAfter(deadline: .now() + safeDelay) { [weak self] in
@@ -485,11 +518,15 @@ class NitroSse: HybridNitroSseSpec {
485
518
  self.attemptVersion = attemptVersion
486
519
  }
487
520
 
521
+ /// Handle a successful SSE connection open for this handler.
522
+ ///
523
+ /// If this handler corresponds to the active connection and its attempt version matches the parent's current connectionAttemptVersion, resets `backoffCounter`, `currentReconnectAttempts`, and `consecutiveAuthErrors`, and enqueues an `.open` `SseEvent` with status code 200.
488
524
  func onOpened() {
489
525
  guard let parent = parent, source === parent.eventSource else { return }
490
526
  parent.sseQueue.async { [weak parent] in
491
527
  guard let parent = parent, self.attemptVersion == parent.connectionAttemptVersion else { return }
492
528
  parent.backoffCounter = 0
529
+ parent.currentReconnectAttempts = 0
493
530
  parent.consecutiveAuthErrors = 0
494
531
  parent.pushEventToBuffer(SseEvent(type: .open, data: nil, id: nil, event: nil, message: nil, statusCode: 200, retry: nil))
495
532
  }