react-native-nitro-sse 1.2.3 → 1.4.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.
package/NitroSse.podspec CHANGED
@@ -14,10 +14,18 @@ Pod::Spec.new do |s|
14
14
  s.source = { :git => "https://github.com/IAmTester35/react-native-nitro-sse.git", :tag => "#{s.version}" }
15
15
 
16
16
  s.source_files = [
17
- "ios/**/*.{swift}",
18
- "ios/**/*.{m,mm}",
17
+ "ios/*.{swift}",
18
+ "ios/*.{m,mm}",
19
19
  "cpp/**/*.{hpp,cpp}",
20
20
  ]
21
+
22
+ s.public_header_files = [
23
+ "ios/NitroSseNetworkInspector.h",
24
+ ]
25
+
26
+ s.test_spec 'Tests' do |test_spec|
27
+ test_spec.source_files = 'ios/Tests/**/*.{swift}'
28
+ end
21
29
 
22
30
  s.dependency 'React-jsi'
23
31
  s.dependency 'React-callinvoker'
package/README.md CHANGED
@@ -12,6 +12,7 @@ Unlike traditional EventSource libraries that run on the JS thread or use the le
12
12
  - **🌊 Backpressure Handling**: Advanced **Batching** mechanism aggregates messages and employs **Tail Drop** strategies to protect the UI thread from freezing during data surges.
13
13
  - **🔋 Mobile-First Architecture**: Automatically hibernates when the app enters the background and seamlessly reconnects upon foregrounding to conserve battery.
14
14
  - **💓 Heartbeat Detection**: Native-side detection of keep-alive signals (comments) to maintain a reliable connection watchdog.
15
+ - **🔍 DevTools Integration**: Plug-and-play support for **React Native 0.83+ DevTools Network Tab**. Monitor connection status, request/response headers, and timing directly in the official desktop debugger.
15
16
  - **🛠️ Full Protocol Support**: Comprehensive support for GET/POST methods and dynamic header updates.
16
17
 
17
18
  ---
@@ -26,6 +27,19 @@ npm install react-native-nitro-sse react-native-nitro-modules
26
27
 
27
28
  > **Note**: `react-native-nitro-modules` is required as the core foundation for JSI performance.
28
29
 
30
+ ---
31
+
32
+ ## 📊 Compatibility
33
+
34
+ | react-native-nitro-sse | react-native-nitro-modules |
35
+ | :--------------------- | :------------------------- |
36
+ | **1.4.0** | **0.35.0** |
37
+ | **1.2.2 - 1.3.1** | **0.34.1** |
38
+ | **1.2.0 - 1.2.1** | **0.34.0** |
39
+ | **1.1.0** | **0.33.9** |
40
+ | **1.0.0** | **0.33.8** |
41
+
42
+
29
43
  ---
30
44
 
31
45
  ## 🚀 Usage
@@ -35,9 +49,11 @@ npm install react-native-nitro-sse react-native-nitro-modules
35
49
  Initialize the module with your endpoint configuration and an event listener.
36
50
 
37
51
  ```tsx
38
- import { NitroSseModule } from 'react-native-nitro-sse';
52
+ import { createNitroSse } from 'react-native-nitro-sse';
39
53
 
40
- NitroSseModule.setup(
54
+ const nitroSse = createNitroSse();
55
+
56
+ nitroSse.setup(
41
57
  {
42
58
  url: 'https://api.yourserver.com/stream',
43
59
  method: 'get',
@@ -61,31 +77,34 @@ NitroSseModule.setup(
61
77
  );
62
78
 
63
79
  // Start the connection
64
- NitroSseModule.start();
80
+ nitroSse.start();
65
81
 
66
82
  // Stop the connection when unmounting or no longer needed
67
- // NitroSseModule.stop();
83
+ // nitroSse.stop();
68
84
  ```
69
85
 
86
+
70
87
  ### 2. Check Connection Status
71
88
 
72
89
  You can synchronously check the connection status at any time:
73
90
 
74
91
  ```tsx
75
- const connected = NitroSseModule.isConnected();
92
+ const connected = nitroSse.isConnected();
76
93
  console.log('Is Connected:', connected);
77
94
  ```
78
95
 
96
+
79
97
  ### 3. Dynamic Token Updates
80
98
 
81
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.
82
100
 
83
101
  ```tsx
84
- NitroSseModule.updateHeaders({
102
+ nitroSse.updateHeaders({
85
103
  'Authorization': 'Bearer new-fresh-token',
86
104
  });
87
105
  ```
88
106
 
107
+
89
108
  ---
90
109
 
91
110
  ## ⚙️ Configuration (SseConfig)
@@ -118,4 +118,6 @@ dependencies {
118
118
  implementation "com.squareup.okhttp3:okhttp:4.12.0"
119
119
  implementation "com.squareup.okhttp3:okhttp-sse:4.12.0"
120
120
  implementation "androidx.lifecycle:lifecycle-process:2.8.7"
121
+
122
+ testImplementation "junit:junit:4.13.2"
121
123
  }
@@ -1,6 +1,10 @@
1
1
  #include <jni.h>
2
+ #include <fbjni/fbjni.h>
2
3
  #include "nitrosseOnLoad.hpp"
3
4
 
4
5
  JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void*) {
5
- return margelo::nitro::nitrosse::initialize(vm);
6
+ return facebook::jni::initialize(vm, []() {
7
+ margelo::nitro::nitrosse::registerAllNatives();
8
+ });
6
9
  }
10
+
@@ -0,0 +1,94 @@
1
+ package com.margelo.nitro.nitrosse
2
+
3
+ import android.util.Log
4
+ import okhttp3.Request
5
+ import okhttp3.Response
6
+ import java.util.UUID
7
+
8
+ /**
9
+ * A utility to report network events to the React Native DevTools Network Tab.
10
+ * It uses reflection to access the internal InspectorNetworkReporter class in RN.
11
+ */
12
+ object NetworkInspector {
13
+ private const val TAG = "NitroSseNetworkInspector"
14
+ private var reporterClass: Class<*>? = null
15
+ private var isEnabledCached: Boolean = false
16
+
17
+ init {
18
+ try {
19
+ reporterClass = Class.forName("com.facebook.react.modules.network.InspectorNetworkReporter")
20
+ Log.d(TAG, "InspectorNetworkReporter found. Network tracing is available.")
21
+ } catch (e: Exception) {
22
+ Log.d(TAG, "InspectorNetworkReporter not found. Network tracing is disabled.")
23
+ }
24
+ }
25
+
26
+ private fun isEnabled(): Boolean {
27
+ if (reporterClass == null) return false
28
+ return try {
29
+ val method = reporterClass?.getDeclaredMethod("isDebuggingEnabled")
30
+ method?.invoke(null) as? Boolean ?: false
31
+ } catch (e: Exception) {
32
+ false
33
+ }
34
+ }
35
+
36
+ fun reportRequestStart(requestId: String, request: Request) {
37
+ if (reporterClass == null || !isEnabled()) return
38
+ try {
39
+ val method = reporterClass?.getDeclaredMethod(
40
+ "reportRequestStart",
41
+ String::class.java,
42
+ String::class.java,
43
+ String::class.java,
44
+ Map::class.java,
45
+ String::class.java,
46
+ Long::class.javaPrimitiveType
47
+ )
48
+ val headers = request.headers.toMap()
49
+ // We send an empty body string as SSE setup usually doesn't have a large body
50
+ val body = ""
51
+ method?.invoke(null, requestId, request.url.toString(), request.method, headers, body, 0L)
52
+ } catch (e: Exception) {
53
+ Log.e(TAG, "Error reporting request start", e)
54
+ }
55
+ }
56
+
57
+ fun reportResponseStart(requestId: String, request: Request, response: Response) {
58
+ if (reporterClass == null || !isEnabled()) return
59
+ try {
60
+ val method = reporterClass?.getDeclaredMethod(
61
+ "reportResponseStart",
62
+ String::class.java,
63
+ String::class.java,
64
+ Int::class.javaPrimitiveType,
65
+ Map::class.java,
66
+ Long::class.javaPrimitiveType
67
+ )
68
+ val headers = response.headers.toMap()
69
+ method?.invoke(null, requestId, request.url.toString(), response.code, headers, -1L)
70
+ } catch (e: Exception) {
71
+ Log.e(TAG, "Error reporting response start", e)
72
+ }
73
+ }
74
+
75
+ fun reportResponseEnd(requestId: String, totalBytes: Long) {
76
+ if (reporterClass == null || !isEnabled()) return
77
+ try {
78
+ val method = reporterClass?.getDeclaredMethod("reportResponseEnd", String::class.java, Long::class.javaPrimitiveType)
79
+ method?.invoke(null, requestId, totalBytes)
80
+ } catch (e: Exception) {
81
+ Log.e(TAG, "Error reporting response end", e)
82
+ }
83
+ }
84
+
85
+ fun reportRequestFailed(requestId: String, cancelled: Boolean) {
86
+ if (reporterClass == null || !isEnabled()) return
87
+ try {
88
+ val method = reporterClass?.getDeclaredMethod("reportRequestFailed", String::class.java, Boolean::class.javaPrimitiveType)
89
+ method?.invoke(null, requestId, cancelled)
90
+ } catch (e: Exception) {
91
+ Log.e(TAG, "Error reporting request failure", e)
92
+ }
93
+ }
94
+ }
@@ -10,15 +10,14 @@ import okhttp3.RequestBody.Companion.toRequestBody
10
10
  import okhttp3.sse.EventSource
11
11
  import okhttp3.sse.EventSources
12
12
  import okhttp3.sse.EventSourceListener
13
- import okio.Buffer
14
- import okio.ForwardingSource
15
- import okio.buffer
13
+ import okio.*
16
14
  import androidx.lifecycle.DefaultLifecycleObserver
17
15
  import androidx.lifecycle.LifecycleOwner
18
16
  import androidx.lifecycle.ProcessLifecycleOwner
19
17
  import java.util.concurrent.TimeUnit
20
18
  import java.util.concurrent.atomic.AtomicBoolean
21
19
  import java.util.concurrent.atomic.AtomicLong
20
+ import java.util.UUID
22
21
  import kotlin.random.Random
23
22
 
24
23
  /**
@@ -38,9 +37,10 @@ import kotlin.random.Random
38
37
  */
39
38
  @DoNotStrip
40
39
  class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
41
- private var client: OkHttpClient? = null
42
- private var eventSource: EventSource? = null
43
- private var config: SseConfig? = null
40
+ @Volatile private var client: OkHttpClient? = null
41
+ @Volatile private var eventSource: EventSource? = null
42
+ @Volatile private var config: SseConfig? = null
43
+ @Volatile private var requestId: String? = null
44
44
  private var onEventsCallback: ((events: Array<SseEvent>) -> Unit)? = null
45
45
 
46
46
  private val isRunning = AtomicBoolean(false)
@@ -61,8 +61,8 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
61
61
 
62
62
  private var hasSubscribedToLifecycle = false
63
63
 
64
- private val defaultRetryDelayMs = 3000L
65
- private val baseBackoffDelayMs = 2000L
64
+ private val defaultRetryDelayMs = 2000L
65
+ private val baseBackoffDelayMs = 1000L
66
66
  private val maxBackoffDelayMs = 30000L
67
67
 
68
68
  companion object {
@@ -78,25 +78,40 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
78
78
  .connectTimeout(15, TimeUnit.SECONDS)
79
79
  .readTimeout(35, TimeUnit.SECONDS)
80
80
  .addNetworkInterceptor { chain ->
81
- val response = chain.proceed(chain.request())
81
+ val request = chain.request()
82
+ val rid = request.tag(String::class.java)
83
+
84
+ val response = chain.proceed(request)
85
+
86
+ rid?.let {
87
+ NetworkInspector.reportResponseStart(it, request, response)
88
+ }
89
+
82
90
  val responseBody = response.body
83
91
  if (responseBody != null) {
84
92
  val countingBody = object : ResponseBody() {
85
93
  override fun contentType() = responseBody.contentType()
86
94
  override fun contentLength() = responseBody.contentLength()
87
95
  override fun source() = (object : okio.ForwardingSource(responseBody.source()) {
96
+ private var isAtStartOfLine = true
97
+
88
98
  override fun read(sink: okio.Buffer, byteCount: Long): Long {
99
+ val bufferOffset = sink.size
89
100
  val bytesRead = super.read(sink, byteCount)
90
101
  if (bytesRead != -1L) {
91
102
  totalBytesReceived.addAndGet(bytesRead)
92
103
 
104
+
93
105
  try {
94
- val snapshot = sink.snapshot()
95
- if (snapshot.size > 0 && snapshot.get(0) == ':'.toByte()) {
96
- pushEventToBuffer(SseEvent(SseEventType.HEARTBEAT, null, null, null, "keep-alive"))
106
+ for (i in 0 until bytesRead) {
107
+ val b = sink.get(bufferOffset + i)
108
+ if (isAtStartOfLine && b == ':'.code.toByte()) {
109
+ pushEventToBuffer(SseEvent(SseEventType.HEARTBEAT, null, null, null, "keep-alive"))
110
+ }
111
+ isAtStartOfLine = (b == '\n'.code.toByte() || b == '\r'.code.toByte())
97
112
  }
98
113
  } catch (e: Exception) {
99
- // Silent catch for interceptor parsing
114
+ // Silent
100
115
  }
101
116
  }
102
117
  return bytesRead
@@ -179,9 +194,11 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
179
194
  }
180
195
 
181
196
  override fun updateHeaders(headers: Map<String, String>) {
182
- this.config?.let {
183
- this.config = it.copy(headers = headers)
184
- Log.d(TAG, "Headers updated for subsequent connections")
197
+ synchronized(this) {
198
+ this.config?.let {
199
+ this.config = it.copy(headers = headers)
200
+ Log.d(TAG, "Headers updated for subsequent connections")
201
+ }
185
202
  }
186
203
  }
187
204
 
@@ -198,33 +215,53 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
198
215
  if (config == null || isRunning.get()) return
199
216
  isRunning.set(true)
200
217
  backoffCounter = 0
218
+ requestId = null
201
219
  sseHandler?.post { performConnection() }
202
220
  }
203
221
 
204
222
  private fun performConnection() {
205
- if (!isRunning.get()) return
223
+ val currentConfig: SseConfig
224
+ val currentLastId: String?
225
+ synchronized(this) {
226
+ if (!isRunning.get() || config == null) return
227
+ currentConfig = config!!
228
+ currentLastId = lastProcessedId
229
+ }
230
+
231
+ // Report end for previous request if it was running
232
+ requestId?.let {
233
+ NetworkInspector.reportResponseEnd(it, totalBytesReceived.getAndSet(0))
234
+ this.requestId = null
235
+ }
206
236
 
207
237
  // Cancel existing event source if any before starting new one
208
238
  eventSource?.cancel()
209
239
  eventSource = null
210
240
 
241
+ val newRequestId = UUID.randomUUID().toString()
242
+ this.requestId = newRequestId
243
+
211
244
  val requestBuilder = Request.Builder()
212
- .url(config!!.url)
245
+ .url(currentConfig.url)
213
246
  .header("Accept", "text/event-stream")
214
247
  .header("Cache-Control", "no-cache")
215
248
 
216
- lastProcessedId?.let {
249
+ currentLastId?.let {
217
250
  if (it.isNotEmpty()) requestBuilder.header("Last-Event-ID", it)
218
251
  }
219
252
 
220
- config!!.headers?.forEach { (k, v) -> requestBuilder.header(k, v) }
253
+ currentConfig.headers?.forEach { (k, v) -> requestBuilder.header(k, v) }
221
254
 
222
- if (config!!.method == HttpMethod.POST) {
223
- val body = config!!.body?.toRequestBody("application/json".toMediaType()) ?: "".toRequestBody()
255
+ if (currentConfig.method == HttpMethod.POST) {
256
+ val body = currentConfig.body?.toRequestBody("application/json".toMediaType()) ?: "".toRequestBody()
224
257
  requestBuilder.post(body)
225
258
  }
226
259
 
227
- eventSource = EventSources.createFactory(client!!).newEventSource(requestBuilder.build(), sseListener)
260
+ requestBuilder.tag(String::class.java, newRequestId)
261
+ val request = requestBuilder.build()
262
+ NetworkInspector.reportRequestStart(newRequestId, request)
263
+
264
+ eventSource = EventSources.createFactory(client!!).newEventSource(request, sseListener)
228
265
  }
229
266
 
230
267
  private fun extractRetryAfterMillis(response: Response?): Long? {
@@ -248,6 +285,9 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
248
285
 
249
286
  override fun onEvent(eventSource: EventSource, id: String?, type: String?, data: String) {
250
287
  if (eventSource != this@NitroSse.eventSource) return
288
+ if (!id.isNullOrEmpty()) {
289
+ this@NitroSse.lastProcessedId = id
290
+ }
251
291
  pushEventToBuffer(SseEvent(SseEventType.MESSAGE, data, id, type, null))
252
292
  }
253
293
 
@@ -260,6 +300,8 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
260
300
  reconnectCount++
261
301
  lastErrorTime = System.currentTimeMillis().toDouble()
262
302
  lastErrorCode = t?.javaClass?.simpleName ?: statusCode.toString()
303
+
304
+ requestId?.let { NetworkInspector.reportRequestFailed(it, false) }
263
305
 
264
306
  val isFatal = (statusCode == 401 || statusCode == 403 || statusCode == 400)
265
307
  if (isFatal) {
@@ -300,6 +342,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
300
342
  override fun onClosed(eventSource: EventSource) {
301
343
  if (eventSource != this@NitroSse.eventSource) return
302
344
  if (isRunning.get()) {
345
+ requestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
303
346
  val delay = (defaultRetryDelayMs * (0.8 + Random.nextDouble() * 0.4)).toLong()
304
347
  sseHandler?.postDelayed({ if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection() }, delay)
305
348
  }
@@ -325,6 +368,10 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
325
368
  sseHandler?.removeCallbacksAndMessages(null)
326
369
  eventSource?.cancel()
327
370
  eventSource = null
371
+ requestId?.let {
372
+ NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
373
+ requestId = null
374
+ }
328
375
  synchronized(eventBuffer) {
329
376
  eventBuffer.clear()
330
377
  }
@@ -0,0 +1,98 @@
1
+ package com.margelo.nitro.nitrosse
2
+
3
+ import org.junit.Assert.assertEquals
4
+ import org.junit.Test
5
+
6
+ class HeartbeatScanner {
7
+ private var isAtStartOfLine = true
8
+ var heartbeatCount = 0
9
+ private set
10
+
11
+ fun scan(bytes: ByteArray, length: Int) {
12
+ for (i in 0 until length) {
13
+ val b = bytes[i]
14
+ if (isAtStartOfLine && b == ':'.toByte()) {
15
+ heartbeatCount++
16
+ }
17
+ isAtStartOfLine = (b == '\n'.toByte() || b == '\r'.toByte())
18
+ }
19
+ }
20
+ }
21
+
22
+ class HeartbeatScannerTest {
23
+
24
+ @Test
25
+ fun testNormalHeartbeat() {
26
+ val scanner = HeartbeatScanner()
27
+ val data = ":heartbeat\n".toByteArray()
28
+ scanner.scan(data, data.size)
29
+ assertEquals(1, scanner.heartbeatCount)
30
+ }
31
+
32
+ @Test
33
+ fun testHeartbeatAfterNewline() {
34
+ val scanner = HeartbeatScanner()
35
+ val data = "data: hello\n:heartbeat\n".toByteArray()
36
+ scanner.scan(data, data.size)
37
+ assertEquals(1, scanner.heartbeatCount)
38
+ }
39
+
40
+ @Test
41
+ fun testSplitPacketHeartbeat() {
42
+ val scanner = HeartbeatScanner()
43
+
44
+ // Packet 1 ends right before heartbeat
45
+ val p1 = "data: hello\n".toByteArray()
46
+ scanner.scan(p1, p1.size)
47
+
48
+ // Packet 2 starts with heartbeat
49
+ val p2 = ":heartbeat\n".toByteArray()
50
+ scanner.scan(p2, p2.size)
51
+
52
+ assertEquals(1, scanner.heartbeatCount)
53
+ }
54
+
55
+ @Test
56
+ fun testHeartbeatSplitAcrossPackets() {
57
+ val scanner = HeartbeatScanner()
58
+
59
+ // Packet 1 ends with newline
60
+ val p1 = "data: hello\n".toByteArray()
61
+ scanner.scan(p1, p1.size)
62
+
63
+ // Packet 2 starts with ':' but no more
64
+ val p2 = ":".toByteArray()
65
+ scanner.scan(p2, p2.size)
66
+ assertEquals(1, scanner.heartbeatCount)
67
+
68
+ // Packet 3 contains the rest of comment
69
+ val p3 = "heartbeat\n".toByteArray()
70
+ scanner.scan(p3, p3.size)
71
+
72
+ assertEquals(1, scanner.heartbeatCount)
73
+ }
74
+
75
+ @Test
76
+ fun testColonsInDataAreNotHeartbeats() {
77
+ val scanner = HeartbeatScanner()
78
+ val data = "data: something:with:colons\n".toByteArray()
79
+ scanner.scan(data, data.size)
80
+ assertEquals(0, scanner.heartbeatCount)
81
+ }
82
+
83
+ @Test
84
+ fun testMultipleHeartbeats() {
85
+ val scanner = HeartbeatScanner()
86
+ val data = ":h1\n:h2\n\n:h3\n".toByteArray()
87
+ scanner.scan(data, data.size)
88
+ assertEquals(3, scanner.heartbeatCount)
89
+ }
90
+
91
+ @Test
92
+ fun testCRLFHeartbeat() {
93
+ val scanner = HeartbeatScanner()
94
+ val data = "data: ok\r\n:heartbeat\r\n".toByteArray()
95
+ scanner.scan(data, data.size)
96
+ assertEquals(1, scanner.heartbeatCount)
97
+ }
98
+ }
@@ -0,0 +1,110 @@
1
+ package com.margelo.nitro.nitrosse
2
+
3
+ import org.junit.Assert.*
4
+ import org.junit.Before
5
+ import org.junit.Test
6
+ import java.util.concurrent.atomic.AtomicInteger
7
+
8
+ class NitroSseLogicTest {
9
+
10
+ private lateinit var eventBuffer: MutableList<SseEvent>
11
+ private var bufferCapacity = 100
12
+ private var batchInterval = 0.0
13
+
14
+ @Before
15
+ fun setup() {
16
+ eventBuffer = mutableListOf()
17
+ }
18
+
19
+ private fun pushEventToBuffer(event: SseEvent, onFlush: () -> Unit) {
20
+ synchronized(eventBuffer) {
21
+ while (eventBuffer.size >= bufferCapacity) {
22
+ eventBuffer.removeAt(0)
23
+ }
24
+ eventBuffer.add(event)
25
+ }
26
+
27
+ if (batchInterval <= 0) {
28
+ onFlush()
29
+ }
30
+ }
31
+
32
+ @Test
33
+ fun testBufferCapacityLimit() {
34
+ bufferCapacity = 5
35
+ batchInterval = 100.0 // Enable batching so we don't flush immediately
36
+
37
+ for (i in 1..10) {
38
+ pushEventToBuffer(SseEvent(SseEventType.MESSAGE, "data $i", "$i", null, null)) {}
39
+ }
40
+
41
+ assertEquals(5, eventBuffer.size)
42
+ assertEquals("6", eventBuffer[0].id)
43
+ assertEquals("10", eventBuffer[4].id)
44
+ }
45
+
46
+ @Test
47
+ fun testImmediateFlushWhenNoBatching() {
48
+ batchInterval = 0.0
49
+ val flushCount = AtomicInteger(0)
50
+
51
+ pushEventToBuffer(SseEvent(SseEventType.OPEN, null, null, null, null)) {
52
+ flushCount.incrementAndGet()
53
+ }
54
+
55
+ assertEquals(1, flushCount.get())
56
+ }
57
+
58
+ @Test
59
+ fun testRetryAfterExtraction() {
60
+ // Mock non-standard retry after logic (conceptual check of the method)
61
+ fun extractMillis(headerValue: String?): Long? {
62
+ if (headerValue == null) return null
63
+ return try {
64
+ headerValue.toLong() * 1000L
65
+ } catch (e: Exception) {
66
+ null // Simplifying for the logic test
67
+ }
68
+ }
69
+
70
+ assertEquals(5000L, extractMillis("5"))
71
+ 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
+
81
+ fun calculateDelay(counter: Int): Long {
82
+ return Math.min(baseBackoffDelayMs * (1 shl counter), maxBackoffDelayMs)
83
+ }
84
+
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
91
+ }
92
+
93
+ @Test
94
+ fun testHeartbeatScannerLogic_Integrated() {
95
+ val heartbeatCount = AtomicInteger(0)
96
+ var isAtStartOfLine = true
97
+
98
+ fun processByte(b: Byte) {
99
+ if (isAtStartOfLine && b == ':'.toByte()) {
100
+ heartbeatCount.incrementAndGet()
101
+ }
102
+ isAtStartOfLine = (b == '\n'.toByte() || b == '\r'.toByte())
103
+ }
104
+
105
+ val stream = "data: hello\n:heartbeat\n\n:ping\n".toByteArray()
106
+ for (b in stream) processByte(b)
107
+
108
+ assertEquals(2, heartbeatCount.get())
109
+ }
110
+ }