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.
@@ -55,6 +55,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
55
55
  private var isFlushPending = AtomicBoolean(false)
56
56
 
57
57
  private var backoffCounter = 0
58
+ private var currentReconnectAttempts = 0
58
59
  @Volatile private var lastProcessedId: String? = null
59
60
 
60
61
  private val totalBytesReceived = AtomicLong(0)
@@ -65,10 +66,6 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
65
66
 
66
67
  private var hasSubscribedToLifecycle = false
67
68
 
68
- private val defaultRetryDelayMs = 2000L
69
- private val baseBackoffDelayMs = 1000L
70
- private val maxBackoffDelayMs = 30000L
71
-
72
69
  companion object {
73
70
  private const val TAG = "NitroSse"
74
71
  }
@@ -191,15 +188,27 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
191
188
  }
192
189
 
193
190
  /**
194
- * Returns runtime statistics about the SSE connection.
191
+ * Provide current runtime statistics for the SSE connection.
192
+ *
193
+ * @return An SseStats snapshot with:
194
+ * - the total bytes received (as Double),
195
+ * - the total number of reconnects (as Double),
196
+ * - the timestamp of the last error in milliseconds since epoch (nullable),
197
+ * - the last error code or identifier (nullable).
195
198
  */
196
199
  override fun getStats(): SseStats {
197
- return SseStats(
198
- totalBytesReceived.get().toDouble(),
199
- reconnectCount.toDouble(),
200
- lastErrorTime,
201
- lastErrorCode
202
- )
200
+ // getStats is called from JS thread, so we should sync with sseHandler thread
201
+ // or coordinate carefully. Since we need to return immediately,
202
+ // using the state as-is is okay IF all updates happen on a single thread
203
+ // and we use synchronized or @Volatile.
204
+ synchronized(this) {
205
+ return SseStats(
206
+ totalBytesReceived.get().toDouble(),
207
+ reconnectCount.toDouble(),
208
+ lastErrorTime,
209
+ lastErrorCode
210
+ )
211
+ }
203
212
  }
204
213
 
205
214
  /**
@@ -263,6 +272,16 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
263
272
  }
264
273
  }
265
274
 
275
+ /**
276
+ * Handles a failure from the request-level interceptor by emitting an ERROR event and scheduling a reconnect.
277
+ *
278
+ * Posts work onto the SSE handler that (if the connection attempt version is still current and streaming is running)
279
+ * pushes an ERROR SseEvent describing the interceptor failure and schedules performConnection(...) after a
280
+ * jittered retry delay derived from the current configuration.
281
+ *
282
+ * @param t The throwable from the interceptor failure, or null if unavailable.
283
+ * @param version Snapshot of connectionAttemptVersion used to ignore stale work.
284
+ */
266
285
  private fun handleInterceptorError(t: Throwable?, version: Int) {
267
286
  sseHandler?.post {
268
287
  if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
@@ -270,7 +289,9 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
270
289
  pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Interceptor Error: ${t?.message}", -1.0, null))
271
290
 
272
291
  // Reconnect with delay
273
- val delay = (defaultRetryDelayMs * (0.8 + Random.nextDouble() * 0.4)).toLong()
292
+ val currentJitterFactor = config?.jitterFactor ?: 0.5
293
+ val currentRetryInterval = (config?.retryIntervalMs ?: 1000.0).toLong()
294
+ val delay = (currentRetryInterval * (1.0 - currentJitterFactor + Random.nextDouble() * 2 * currentJitterFactor)).toLong()
274
295
  sseHandler?.postDelayed({ if (isRunning.get()) performConnection(version) }, delay)
275
296
  }
276
297
  }
@@ -333,114 +354,196 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
333
354
  }
334
355
 
335
356
  private val sseListener = object : EventSourceListener() {
357
+ /**
358
+ * Handles a successful SSE connection open by resetting reconnection/auth counters and emitting an OPEN event to the JS bridge.
359
+ *
360
+ * Synchronizes access when pushing the event and includes the HTTP response code in the emitted `SseEvent`.
361
+ *
362
+ * @param eventSource The EventSource instance that was opened.
363
+ * @param response The HTTP response received when the SSE connection was established; its status code is included in the emitted OPEN event.
364
+ */
336
365
  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))
366
+ sseHandler?.post {
367
+ if (eventSource != this@NitroSse.eventSource) return@post
368
+ consecutiveAuthErrors.set(0)
369
+ backoffCounter = 0
370
+ currentReconnectAttempts = 0
371
+ synchronized(this@NitroSse) {
372
+ pushEventToBuffer(SseEvent(SseEventType.OPEN, null, null, null, null, response.code.toDouble(), null))
373
+ }
374
+ }
341
375
  }
342
376
 
377
+ /**
378
+ * Handles an incoming SSE message by validating the active stream, updating the last processed event id when present,
379
+ * and buffering a `MESSAGE` SseEvent for delivery to the JS bridge.
380
+ *
381
+ * @param eventSource The source that produced the event; ignored if it is not the currently active stream.
382
+ * @param id The event id; when non-empty it is stored as the last processed id.
383
+ * @param type Optional event type.
384
+ * @param data The event payload.
385
+ */
343
386
  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
387
+ sseHandler?.post {
388
+ if (eventSource != this@NitroSse.eventSource) return@post
389
+ if (!id.isNullOrEmpty()) {
390
+ this@NitroSse.lastProcessedId = id
391
+ }
392
+ synchronized(this@NitroSse) {
393
+ pushEventToBuffer(SseEvent(SseEventType.MESSAGE, data, id, type, null, 200.0, null))
394
+ }
347
395
  }
348
- pushEventToBuffer(SseEvent(SseEventType.MESSAGE, data, id, type, null, 200.0, null))
349
396
  }
350
397
 
398
+ /**
399
+ * 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.
400
+ *
401
+ * Behavior by status code:
402
+ * - 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.
403
+ * - 400 or 204: emits a fatal error and stops.
404
+ * - 429 or 503 with a valid `Retry-After`: emits an error describing the computed delay and retries after the server-specified delay plus jitter.
405
+ * - 429 without `Retry-After`: emits an error and stops.
406
+ * - Other or unknown codes: emits an error and schedules a reconnect using the configured backoff and jitter.
407
+ *
408
+ * 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(...)`.
409
+ *
410
+ * @param eventSource The EventSource instance that reported the failure.
411
+ * @param t The throwable that caused the failure, if any.
412
+ * @param response The HTTP response associated with the failure, if any.
413
+ */
351
414
  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) }
415
+ sseHandler?.post {
416
+ if (eventSource != this@NitroSse.eventSource) return@post
417
+ Log.e(TAG, "SSE Failure: ${t?.message}, Code: ${response?.code}")
418
+ if (!isRunning.get()) return@post
419
+
420
+ val statusCode = response?.code ?: -1
421
+
422
+ synchronized(this@NitroSse) {
423
+ reconnectCount++
424
+ lastErrorTime = System.currentTimeMillis().toDouble()
425
+ lastErrorCode = t?.javaClass?.simpleName ?: statusCode.toString()
426
+ }
427
+
428
+ requestId?.let {
429
+ NetworkInspector.reportRequestFailed(it, false)
430
+ this@NitroSse.requestId = null
431
+ }
432
+
433
+ if (statusCode == 401 || statusCode == 403) {
434
+ val currentConfig = synchronized(this@NitroSse) { config }
435
+ if (currentConfig?.onBeforeRequest == null) {
436
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Auth Error ($statusCode) - No interceptor provided. Stopping.", statusCode.toDouble(), null))
437
+ stop()
438
+ return@post
439
+ }
440
+
441
+ val retries = consecutiveAuthErrors.incrementAndGet()
442
+ if (retries >= maxAuthRetries) {
443
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Auth Error ($statusCode) - Retry limit reached ($maxAuthRetries). Stopping.", statusCode.toDouble(), null))
444
+ stop()
445
+ return@post
446
+ }
447
+
448
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Auth Error ($statusCode) - Retry $retries/$maxAuthRetries. Refreshing token...", statusCode.toDouble(), null))
449
+ scheduleReconnect(true)
450
+ return@post
451
+ }
362
452
 
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))
453
+ if (statusCode == 400) {
454
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Fatal Error ($statusCode). Stopping.", statusCode.toDouble(), null))
368
455
  stop()
369
- return
456
+ return@post
370
457
  }
371
458
 
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))
459
+ val retryAfterMillis = extractRetryAfterMillis(response)
460
+ if ((statusCode == 429 || statusCode == 503) && retryAfterMillis != null) {
461
+ val jitter = (500 + Random.nextInt(1500)).toLong()
462
+ val totalDelay = retryAfterMillis + jitter
463
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Retry-After received: ${totalDelay/1000}s", statusCode.toDouble(), totalDelay.toDouble()))
464
+ sseHandler?.postDelayed({
465
+ if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection(connectionAttemptVersion.get())
466
+ }, totalDelay)
467
+ return@post
468
+ }
469
+
470
+ if (statusCode == 429) {
471
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Rate Limited (429) without Retry-After. Stopping.", 429.0, null))
375
472
  stop()
376
- return
473
+ return@post
377
474
  }
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
475
 
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
476
+ if (statusCode == 204) {
477
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "No Content (204). Stopping.", 204.0, null))
478
+ stop()
479
+ return@post
480
+ }
481
+
482
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, t?.message ?: "Link lost ($statusCode)", if (statusCode != -1) statusCode.toDouble() else null, null))
483
+ scheduleReconnect(true)
392
484
  }
485
+ }
393
486
 
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
487
+ /**
488
+ * Handles the SSE stream being closed by the server.
489
+ *
490
+ * When the closed `eventSource` is the currently active stream and streaming is running,
491
+ * reports the response end to the network inspector with the total bytes received,
492
+ * clears the stored `requestId`, and schedules a reconnect that is treated as a normal (non-error) reconnect.
493
+ *
494
+ * @param eventSource The EventSource instance that was closed.
495
+ */
496
+ override fun onClosed(eventSource: EventSource) {
497
+ sseHandler?.post {
498
+ if (eventSource != this@NitroSse.eventSource) return@post
499
+ if (isRunning.get()) {
500
+ requestId?.let {
501
+ NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
502
+ this@NitroSse.requestId = null
503
+ }
504
+ scheduleReconnect(false)
505
+ }
403
506
  }
507
+ }
404
508
 
405
- if (statusCode == 429) {
406
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Rate Limited (429) without Retry-After. Stopping.", 429.0, null))
509
+ /**
510
+ * Schedule a future reconnect attempt using configurable backoff, jitter, and attempt limits.
511
+ *
512
+ * If the configured maximum reconnect attempts is reached, emits an ERROR event and stops the stream.
513
+ * Otherwise computes a delay (exponential backoff when `isError` is true, simple retry interval when false),
514
+ * applies jitter, enforces a minimum delay of 1000 ms, increments reconnect counters, and posts a
515
+ * connection retry task to the SSE handler.
516
+ *
517
+ * @param isError True when the reconnect is triggered by an error; false for a normal/non-error reconnect.
518
+ */
519
+ private fun scheduleReconnect(isError: Boolean) {
520
+ val currentConfig = synchronized(this@NitroSse) { config } ?: return
521
+ val currentJitterFactor = currentConfig.jitterFactor ?: 0.5
522
+ val currentRetryInterval = (currentConfig.retryIntervalMs ?: 1000.0).toLong()
523
+ val currentMaxRetryInterval = (currentConfig.maxRetryIntervalMs ?: 30000.0).toLong()
524
+
525
+ val maxAttempts = (currentConfig.maxReconnectAttempts ?: -1.0).toInt()
526
+ if (maxAttempts != -1 && currentReconnectAttempts >= maxAttempts) {
527
+ Log.d(TAG, "Max reconnection attempts reached ($maxAttempts). Stopping.")
528
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Max reconnection attempts reached ($maxAttempts).", null, null))
407
529
  stop()
408
530
  return
409
531
  }
410
532
 
411
- val isHandshakeError = response == null || response.code != 200
412
- val reconnectDelay = if (isHandshakeError) {
413
- val base = Math.min(baseBackoffDelayMs * (1 shl backoffCounter), maxBackoffDelayMs)
533
+ val reconnectDelay = if (isError) {
534
+ val base = Math.min(currentRetryInterval * (1 shl backoffCounter), currentMaxRetryInterval)
414
535
  backoffCounter++
415
- (base * (0.5 + Random.nextDouble())).toLong()
536
+ (base * (1.0 - currentJitterFactor + Random.nextDouble() * 2 * currentJitterFactor)).toLong()
416
537
  } 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
538
+ (currentRetryInterval * (1.0 - currentJitterFactor + Random.nextDouble() * 2 * currentJitterFactor)).toLong()
426
539
  }
427
540
 
428
- pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, t?.message ?: "Link lost ($statusCode)", if (statusCode != -1) statusCode.toDouble() else null, null))
541
+ currentReconnectAttempts++
542
+ val safeReconnectDelay = Math.max(reconnectDelay, 1000L)
429
543
  sseHandler?.postDelayed({
430
- if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection(connectionAttemptVersion.get())
544
+ if (isRunning.get()) performConnection(connectionAttemptVersion.get())
431
545
  }, safeReconnectDelay)
432
546
  }
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
547
  }
445
548
 
446
549
  /**