react-native-nitro-sse 1.6.2 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +2 -0
  2. package/android/build.gradle +1 -0
  3. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +256 -95
  4. package/ios/NitroSse.swift +90 -39
  5. package/lib/module/NitroSseClient.js +75 -0
  6. package/lib/module/NitroSseClient.js.map +1 -0
  7. package/lib/module/SseInterface.js +2 -0
  8. package/lib/module/index.js +9 -1
  9. package/lib/module/index.js.map +1 -1
  10. package/lib/typescript/src/NitroSseClient.d.ts +21 -0
  11. package/lib/typescript/src/NitroSseClient.d.ts.map +1 -0
  12. package/lib/typescript/src/SseInterface.d.ts +74 -2
  13. package/lib/typescript/src/SseInterface.d.ts.map +1 -1
  14. package/lib/typescript/src/index.d.ts +8 -2
  15. package/lib/typescript/src/index.d.ts.map +1 -1
  16. package/nitrogen/generated/android/c++/JFunc_void_std__vector_SseEvent_.hpp +2 -0
  17. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +2 -0
  18. package/nitrogen/generated/android/c++/JSseConfig.hpp +21 -1
  19. package/nitrogen/generated/android/c++/JSseEvent.hpp +7 -1
  20. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +19 -4
  21. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEvent.kt +6 -3
  22. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +16 -0
  23. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +1 -0
  24. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +1 -0
  25. package/nitrogen/generated/ios/swift/SseConfig.swift +91 -1
  26. package/nitrogen/generated/ios/swift/SseEvent.swift +19 -1
  27. package/nitrogen/generated/shared/c++/SseConfig.hpp +21 -1
  28. package/nitrogen/generated/shared/c++/SseEvent.hpp +6 -1
  29. package/package.json +9 -4
  30. package/src/NitroSseClient.ts +96 -0
  31. package/src/SseInterface.ts +79 -2
  32. package/src/index.ts +10 -2
  33. package/android/src/test/java/com/margelo/nitro/nitrosse/HeartbeatScannerTest.kt +0 -98
  34. package/android/src/test/java/com/margelo/nitro/nitrosse/NitroSseLogicTest.kt +0 -157
  35. package/ios/Tests/NitroSseTests.swift +0 -122
package/README.md CHANGED
@@ -33,6 +33,7 @@ npm install react-native-nitro-sse react-native-nitro-modules
33
33
 
34
34
  | react-native-nitro-sse | react-native-nitro-modules |
35
35
  | :--------------------- | :------------------------- |
36
+ | **2.0.0 - latest** | **0.35.2** |
36
37
  | **1.6.2** | **0.35.2** |
37
38
  | **1.4.0 - 1.6.1** | **0.35.0** |
38
39
  | **1.2.2 - 1.3.1** | **0.34.1** |
@@ -108,6 +109,7 @@ console.log(`Reconnections: ${stats.reconnectCount}`);
108
109
  | `connectionTimeoutMs`| `number` | `15000` | Max time for initial handshake / connect. |
109
110
  | `readTimeoutMs` | `number` | `300000`| Max idle time between data packets before reconnecting. |
110
111
  | `backgroundExecution` | `boolean` | `false` | (iOS) Attempt to maintain connection via background tasks. |
112
+ | `autoParseJSON` | `boolean` | `false` | Automatically parse message data as JSON in a background native thread. Result is in `parsedData`. |
111
113
  | `onBeforeRequest` | `function`| - | Async hook to refresh headers/tokens before every attempt. |
112
114
 
113
115
  ---
@@ -120,4 +120,5 @@ dependencies {
120
120
  implementation "androidx.lifecycle:lifecycle-process:2.8.7"
121
121
 
122
122
  testImplementation "junit:junit:4.13.2"
123
+ testImplementation "org.json:json:20240303"
123
124
  }
@@ -11,6 +11,9 @@ import okhttp3.sse.EventSource
11
11
  import okhttp3.sse.EventSources
12
12
  import okhttp3.sse.EventSourceListener
13
13
  import okio.*
14
+ import com.margelo.nitro.core.AnyMap
15
+ import org.json.JSONObject
16
+ import org.json.JSONArray
14
17
  import androidx.lifecycle.DefaultLifecycleObserver
15
18
  import androidx.lifecycle.LifecycleOwner
16
19
  import androidx.lifecycle.ProcessLifecycleOwner
@@ -55,6 +58,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
55
58
  private var isFlushPending = AtomicBoolean(false)
56
59
 
57
60
  private var backoffCounter = 0
61
+ private var currentReconnectAttempts = 0
58
62
  @Volatile private var lastProcessedId: String? = null
59
63
 
60
64
  private val totalBytesReceived = AtomicLong(0)
@@ -65,12 +69,42 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
65
69
 
66
70
  private var hasSubscribedToLifecycle = false
67
71
 
68
- private val defaultRetryDelayMs = 2000L
69
- private val baseBackoffDelayMs = 1000L
70
- private val maxBackoffDelayMs = 30000L
71
-
72
72
  companion object {
73
73
  private const val TAG = "NitroSse"
74
+
75
+ internal fun jsonObjectToMap(jsonObject: JSONObject): Map<String, Any?> {
76
+ val map = mutableMapOf<String, Any?>()
77
+ val keys = jsonObject.keys()
78
+ while (keys.hasNext()) {
79
+ val key = keys.next()
80
+ var value = jsonObject.get(key)
81
+ if (value is JSONObject) {
82
+ value = jsonObjectToMap(value)
83
+ } else if (value is JSONArray) {
84
+ value = jsonArrayToList(value)
85
+ } else if (value == JSONObject.NULL) {
86
+ value = null
87
+ }
88
+ map[key] = value
89
+ }
90
+ return map
91
+ }
92
+
93
+ internal fun jsonArrayToList(jsonArray: JSONArray): List<Any?> {
94
+ val list = mutableListOf<Any?>()
95
+ for (i in 0 until jsonArray.length()) {
96
+ var value = jsonArray.get(i)
97
+ if (value is JSONObject) {
98
+ value = jsonObjectToMap(value)
99
+ } else if (value is JSONArray) {
100
+ value = jsonArrayToList(value)
101
+ } else if (value == JSONObject.NULL) {
102
+ value = null
103
+ }
104
+ list.add(value)
105
+ }
106
+ return list
107
+ }
74
108
  }
75
109
 
76
110
  /**
@@ -88,10 +122,10 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
88
122
  this.client = OkHttpClient.Builder()
89
123
  .connectTimeout((config.connectionTimeoutMs ?: 15000.0).toLong(), TimeUnit.MILLISECONDS)
90
124
  .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()
125
+ .addNetworkInterceptor(HeartbeatNetworkInterceptor(totalBytesReceived) {
126
+ pushEventToBuffer(SseEvent(SseEventType.HEARTBEAT, null, null, null, null, "keep-alive", null, null))
127
+ })
128
+ .build()
95
129
  }
96
130
 
97
131
  if (sseHandlerThread == null) {
@@ -170,6 +204,24 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
170
204
  onEventsCallback?.invoke(eventsToEmit)
171
205
  }
172
206
 
207
+ private fun parseJsonToAnyMap(data: String): AnyMap? {
208
+ return try {
209
+ val trimmed = data.trim()
210
+ if (trimmed.startsWith("{")) {
211
+ val jsonObject = JSONObject(trimmed)
212
+ val map = jsonObjectToMap(jsonObject)
213
+ AnyMap.fromMap(map, true)
214
+ } else {
215
+ // AnyMap represents a JS Object (Map).
216
+ // If it's a JSON array or primitive, we currently don't support auto-parsing into AnyMap.
217
+ null
218
+ }
219
+ } catch (e: Exception) {
220
+ Log.w(TAG, "Failed to parse JSON: ${e.message}")
221
+ null
222
+ }
223
+ }
224
+
173
225
  /**
174
226
  * Manually set the last seen event ID.
175
227
  * This will be used as the 'Last-Event-ID' header on the next connection attempt.
@@ -191,15 +243,27 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
191
243
  }
192
244
 
193
245
  /**
194
- * Returns runtime statistics about the SSE connection.
246
+ * Provide current runtime statistics for the SSE connection.
247
+ *
248
+ * @return An SseStats snapshot with:
249
+ * - the total bytes received (as Double),
250
+ * - the total number of reconnects (as Double),
251
+ * - the timestamp of the last error in milliseconds since epoch (nullable),
252
+ * - the last error code or identifier (nullable).
195
253
  */
196
254
  override fun getStats(): SseStats {
197
- return SseStats(
198
- totalBytesReceived.get().toDouble(),
199
- reconnectCount.toDouble(),
200
- lastErrorTime,
201
- lastErrorCode
202
- )
255
+ // getStats is called from JS thread, so we should sync with sseHandler thread
256
+ // or coordinate carefully. Since we need to return immediately,
257
+ // using the state as-is is okay IF all updates happen on a single thread
258
+ // and we use synchronized or @Volatile.
259
+ synchronized(this) {
260
+ return SseStats(
261
+ totalBytesReceived.get().toDouble(),
262
+ reconnectCount.toDouble(),
263
+ lastErrorTime,
264
+ lastErrorCode
265
+ )
266
+ }
203
267
  }
204
268
 
205
269
  /**
@@ -263,14 +327,26 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
263
327
  }
264
328
  }
265
329
 
330
+ /**
331
+ * Handles a failure from the request-level interceptor by emitting an ERROR event and scheduling a reconnect.
332
+ *
333
+ * Posts work onto the SSE handler that (if the connection attempt version is still current and streaming is running)
334
+ * pushes an ERROR SseEvent describing the interceptor failure and schedules performConnection(...) after a
335
+ * jittered retry delay derived from the current configuration.
336
+ *
337
+ * @param t The throwable from the interceptor failure, or null if unavailable.
338
+ * @param version Snapshot of connectionAttemptVersion used to ignore stale work.
339
+ */
266
340
  private fun handleInterceptorError(t: Throwable?, version: Int) {
267
341
  sseHandler?.post {
268
342
  if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
269
343
  Log.e(TAG, "Request Interceptor Error: ${t?.message}")
270
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Interceptor Error: ${t?.message}", -1.0, null))
344
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Interceptor Error: ${t?.message}", -1.0, null))
271
345
 
272
346
  // Reconnect with delay
273
- val delay = (defaultRetryDelayMs * (0.8 + Random.nextDouble() * 0.4)).toLong()
347
+ val currentJitterFactor = config?.jitterFactor ?: 0.5
348
+ val currentRetryInterval = (config?.retryIntervalMs ?: 1000.0).toLong()
349
+ val delay = (currentRetryInterval * (1.0 - currentJitterFactor + Random.nextDouble() * 2 * currentJitterFactor)).toLong()
274
350
  sseHandler?.postDelayed({ if (isRunning.get()) performConnection(version) }, delay)
275
351
  }
276
352
  }
@@ -333,114 +409,199 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
333
409
  }
334
410
 
335
411
  private val sseListener = object : EventSourceListener() {
412
+ /**
413
+ * Handles a successful SSE connection open by resetting reconnection/auth counters and emitting an OPEN event to the JS bridge.
414
+ *
415
+ * Synchronizes access when pushing the event and includes the HTTP response code in the emitted `SseEvent`.
416
+ *
417
+ * @param eventSource The EventSource instance that was opened.
418
+ * @param response The HTTP response received when the SSE connection was established; its status code is included in the emitted OPEN event.
419
+ */
336
420
  override fun onOpen(eventSource: EventSource, response: Response) {
337
- if (eventSource != this@NitroSse.eventSource) return
338
- consecutiveAuthErrors.set(0) // Successful connection, reset error counter
339
- backoffCounter = 0
340
- pushEventToBuffer(SseEvent(SseEventType.OPEN, null, null, null, null, response.code.toDouble(), null))
421
+ sseHandler?.post {
422
+ if (eventSource != this@NitroSse.eventSource) return@post
423
+ consecutiveAuthErrors.set(0)
424
+ backoffCounter = 0
425
+ currentReconnectAttempts = 0
426
+ synchronized(this@NitroSse) {
427
+ pushEventToBuffer(SseEvent(SseEventType.OPEN, null, null, null, null, null, response.code.toDouble(), null))
428
+ }
429
+ }
341
430
  }
342
431
 
432
+ /**
433
+ * Handles an incoming SSE message by validating the active stream, updating the last processed event id when present,
434
+ * and buffering a `MESSAGE` SseEvent for delivery to the JS bridge.
435
+ *
436
+ * @param eventSource The source that produced the event; ignored if it is not the currently active stream.
437
+ * @param id The event id; when non-empty it is stored as the last processed id.
438
+ * @param type Optional event type.
439
+ * @param data The event payload.
440
+ */
343
441
  override fun onEvent(eventSource: EventSource, id: String?, type: String?, data: String) {
344
- if (eventSource != this@NitroSse.eventSource) return
345
- if (!id.isNullOrEmpty()) {
346
- this@NitroSse.lastProcessedId = id
442
+ sseHandler?.post {
443
+ if (eventSource != this@NitroSse.eventSource) return@post
444
+ if (!id.isNullOrEmpty()) {
445
+ this@NitroSse.lastProcessedId = id
446
+ }
447
+
448
+ val parsedData = if (config?.autoParseJSON == true) parseJsonToAnyMap(data) else null
449
+
450
+ synchronized(this@NitroSse) {
451
+ pushEventToBuffer(SseEvent(SseEventType.MESSAGE, data, parsedData, id, type, null, 200.0, null))
452
+ }
347
453
  }
348
- pushEventToBuffer(SseEvent(SseEventType.MESSAGE, data, id, type, null, 200.0, null))
349
454
  }
350
455
 
456
+ /**
457
+ * Handles an SSE connection failure: records error stats, reports the network failure, emits an appropriate ERROR event, and decides whether to stop or schedule a reconnect.
458
+ *
459
+ * Behavior by status code:
460
+ * - 401/403: if no `onBeforeRequest` interceptor is configured, emits an auth error and stops; otherwise increments an auth-retry counter, stops when the max is reached, or schedules a reconnect to allow token refresh.
461
+ * - 400 or 204: emits a fatal error and stops.
462
+ * - 429 or 503 with a valid `Retry-After`: emits an error describing the computed delay and retries after the server-specified delay plus jitter.
463
+ * - 429 without `Retry-After`: emits an error and stops.
464
+ * - Other or unknown codes: emits an error and schedules a reconnect using the configured backoff and jitter.
465
+ *
466
+ * Side effects: updates reconnect/last-error statistics, reports request failure to NetworkInspector, clears the active request id, pushes events into the internal buffer, may call `stop()` or schedule `performConnection(...)`.
467
+ *
468
+ * @param eventSource The EventSource instance that reported the failure.
469
+ * @param t The throwable that caused the failure, if any.
470
+ * @param response The HTTP response associated with the failure, if any.
471
+ */
351
472
  override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
352
- if (eventSource != this@NitroSse.eventSource) return
353
- Log.e(TAG, "SSE Failure: ${t?.message}, Code: ${response?.code}")
354
- if (!isRunning.get()) return
355
-
356
- val statusCode = response?.code ?: -1
357
- reconnectCount++
358
- lastErrorTime = System.currentTimeMillis().toDouble()
359
- lastErrorCode = t?.javaClass?.simpleName ?: statusCode.toString()
360
-
361
- requestId?.let { NetworkInspector.reportRequestFailed(it, false) }
473
+ sseHandler?.post {
474
+ if (eventSource != this@NitroSse.eventSource) return@post
475
+ Log.e(TAG, "SSE Failure: ${t?.message}, Code: ${response?.code}")
476
+ if (!isRunning.get()) return@post
477
+
478
+ val statusCode = response?.code ?: -1
479
+
480
+ synchronized(this@NitroSse) {
481
+ reconnectCount++
482
+ lastErrorTime = System.currentTimeMillis().toDouble()
483
+ lastErrorCode = t?.javaClass?.simpleName ?: statusCode.toString()
484
+ }
485
+
486
+ requestId?.let {
487
+ NetworkInspector.reportRequestFailed(it, false)
488
+ this@NitroSse.requestId = null
489
+ }
490
+
491
+ if (statusCode == 401 || statusCode == 403) {
492
+ val currentConfig = synchronized(this@NitroSse) { config }
493
+ if (currentConfig?.onBeforeRequest == null) {
494
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Auth Error ($statusCode) - No interceptor provided. Stopping.", statusCode.toDouble(), null))
495
+ stop()
496
+ return@post
497
+ }
362
498
 
363
- // 401/403 are recoverable if we have an interceptor, but with a limit
364
- if (statusCode == 401 || statusCode == 403) {
365
- val hasInterceptor = synchronized(this) { config?.onBeforeRequest != null }
366
- if (!hasInterceptor) {
367
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Auth Error ($statusCode) - No interceptor provided. Stopping.", statusCode.toDouble(), null))
499
+ val retries = consecutiveAuthErrors.incrementAndGet()
500
+ if (retries >= maxAuthRetries) {
501
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Auth Error ($statusCode) - Retry limit reached ($maxAuthRetries). Stopping.", statusCode.toDouble(), null))
502
+ stop()
503
+ return@post
504
+ }
505
+
506
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Auth Error ($statusCode) - Retry $retries/$maxAuthRetries. Refreshing token...", statusCode.toDouble(), null))
507
+ scheduleReconnect(true)
508
+ return@post
509
+ }
510
+
511
+ if (statusCode == 400) {
512
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Fatal Error ($statusCode). Stopping.", statusCode.toDouble(), null))
368
513
  stop()
369
- return
514
+ return@post
370
515
  }
371
516
 
372
- val retries = consecutiveAuthErrors.incrementAndGet()
373
- if (retries >= maxAuthRetries) {
374
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Auth Error ($statusCode) - Retry limit reached ($maxAuthRetries). Stopping.", statusCode.toDouble(), null))
517
+ val retryAfterMillis = extractRetryAfterMillis(response)
518
+ if ((statusCode == 429 || statusCode == 503) && retryAfterMillis != null) {
519
+ val jitter = (500 + Random.nextInt(1500)).toLong()
520
+ val totalDelay = retryAfterMillis + jitter
521
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Retry-After received: ${totalDelay/1000}s", statusCode.toDouble(), totalDelay.toDouble()))
522
+ sseHandler?.postDelayed({
523
+ if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection(connectionAttemptVersion.get())
524
+ }, totalDelay)
525
+ return@post
526
+ }
527
+
528
+ if (statusCode == 429) {
529
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Rate Limited (429) without Retry-After. Stopping.", 429.0, null))
375
530
  stop()
376
- return
531
+ return@post
377
532
  }
378
-
379
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Auth Error ($statusCode) - Retry $retries/$maxAuthRetries. Refreshing token...", statusCode.toDouble(), null))
380
- val delay = (defaultRetryDelayMs * (0.8 + Random.nextDouble() * 0.4)).toLong()
381
- sseHandler?.postDelayed({
382
- if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection(connectionAttemptVersion.get())
383
- }, delay)
384
- return
385
- }
386
533
 
387
- val isFatal = (statusCode == 400)
388
- if (isFatal) {
389
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Fatal Error ($statusCode). Stopping.", statusCode.toDouble(), null))
390
- stop()
391
- return
534
+ if (statusCode == 204) {
535
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "No Content (204). Stopping.", 204.0, null))
536
+ stop()
537
+ return@post
538
+ }
539
+
540
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, t?.message ?: "Link lost ($statusCode)", if (statusCode != -1) statusCode.toDouble() else null, null))
541
+ scheduleReconnect(true)
392
542
  }
543
+ }
393
544
 
394
- val retryAfterMillis = extractRetryAfterMillis(response)
395
- if ((statusCode == 429 || statusCode == 503) && retryAfterMillis != null) {
396
- val jitter = (500 + Random.nextInt(1500)).toLong()
397
- val totalDelay = retryAfterMillis + jitter
398
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Retry-After received: ${totalDelay/1000}s", statusCode.toDouble(), totalDelay.toDouble()))
399
- sseHandler?.postDelayed({
400
- if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection(connectionAttemptVersion.get())
401
- }, totalDelay)
402
- return
545
+ /**
546
+ * Handles the SSE stream being closed by the server.
547
+ *
548
+ * When the closed `eventSource` is the currently active stream and streaming is running,
549
+ * reports the response end to the network inspector with the total bytes received,
550
+ * clears the stored `requestId`, and schedules a reconnect that is treated as a normal (non-error) reconnect.
551
+ *
552
+ * @param eventSource The EventSource instance that was closed.
553
+ */
554
+ override fun onClosed(eventSource: EventSource) {
555
+ sseHandler?.post {
556
+ if (eventSource != this@NitroSse.eventSource) return@post
557
+ if (isRunning.get()) {
558
+ requestId?.let {
559
+ NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
560
+ this@NitroSse.requestId = null
561
+ }
562
+ scheduleReconnect(false)
563
+ }
403
564
  }
565
+ }
404
566
 
405
- if (statusCode == 429) {
406
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Rate Limited (429) without Retry-After. Stopping.", 429.0, null))
567
+ /**
568
+ * Schedule a future reconnect attempt using configurable backoff, jitter, and attempt limits.
569
+ *
570
+ * If the configured maximum reconnect attempts is reached, emits an ERROR event and stops the stream.
571
+ * Otherwise computes a delay (exponential backoff when `isError` is true, simple retry interval when false),
572
+ * applies jitter, enforces a minimum delay of 1000 ms, increments reconnect counters, and posts a
573
+ * connection retry task to the SSE handler.
574
+ *
575
+ * @param isError True when the reconnect is triggered by an error; false for a normal/non-error reconnect.
576
+ */
577
+ private fun scheduleReconnect(isError: Boolean) {
578
+ val currentConfig = synchronized(this@NitroSse) { config } ?: return
579
+ val currentJitterFactor = currentConfig.jitterFactor ?: 0.5
580
+ val currentRetryInterval = (currentConfig.retryIntervalMs ?: 1000.0).toLong()
581
+ val currentMaxRetryInterval = (currentConfig.maxRetryIntervalMs ?: 30000.0).toLong()
582
+
583
+ val maxAttempts = (currentConfig.maxReconnectAttempts ?: -1.0).toInt()
584
+ if (maxAttempts != -1 && currentReconnectAttempts >= maxAttempts) {
585
+ Log.d(TAG, "Max reconnection attempts reached ($maxAttempts). Stopping.")
586
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Max reconnection attempts reached ($maxAttempts).", null, null))
407
587
  stop()
408
588
  return
409
589
  }
410
590
 
411
- val isHandshakeError = response == null || response.code != 200
412
- val reconnectDelay = if (isHandshakeError) {
413
- val base = Math.min(baseBackoffDelayMs * (1 shl backoffCounter), maxBackoffDelayMs)
591
+ val reconnectDelay = if (isError) {
592
+ val base = Math.min(currentRetryInterval * (1 shl backoffCounter), currentMaxRetryInterval)
414
593
  backoffCounter++
415
- (base * (0.5 + Random.nextDouble())).toLong()
594
+ (base * (1.0 - currentJitterFactor + Random.nextDouble() * 2 * currentJitterFactor)).toLong()
416
595
  } else {
417
- (defaultRetryDelayMs * (0.8 + Random.nextDouble() * 0.4)).toLong()
418
- }
419
-
420
- val safeReconnectDelay = Math.max(reconnectDelay, 2000L)
421
-
422
- if (statusCode == 204) {
423
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "No Content (204). Stopping.", 204.0, null))
424
- stop()
425
- return
596
+ (currentRetryInterval * (1.0 - currentJitterFactor + Random.nextDouble() * 2 * currentJitterFactor)).toLong()
426
597
  }
427
598
 
428
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, t?.message ?: "Link lost ($statusCode)", if (statusCode != -1) statusCode.toDouble() else null, null))
599
+ currentReconnectAttempts++
600
+ val safeReconnectDelay = Math.max(reconnectDelay, 1000L)
429
601
  sseHandler?.postDelayed({
430
- if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection(connectionAttemptVersion.get())
602
+ if (isRunning.get()) performConnection(connectionAttemptVersion.get())
431
603
  }, safeReconnectDelay)
432
604
  }
433
-
434
- override fun onClosed(eventSource: EventSource) {
435
- if (eventSource != this@NitroSse.eventSource) return
436
- if (isRunning.get()) {
437
- requestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
438
- val delay = (defaultRetryDelayMs * (0.8 + Random.nextDouble() * 0.4)).toLong()
439
- sseHandler?.postDelayed({
440
- if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection(connectionAttemptVersion.get())
441
- }, delay)
442
- }
443
- }
444
605
  }
445
606
 
446
607
  /**