react-native-nitro-sse 0.1.0-beta.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.
Files changed (72) hide show
  1. package/LICENSE +21 -0
  2. package/NitroSse.podspec +30 -0
  3. package/README.md +121 -0
  4. package/android/CMakeLists.txt +24 -0
  5. package/android/build.gradle +120 -0
  6. package/android/src/main/AndroidManifest.xml +2 -0
  7. package/android/src/main/cpp/cpp-adapter.cpp +6 -0
  8. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +279 -0
  9. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSsePackage.kt +22 -0
  10. package/ios/NitroSse.swift +311 -0
  11. package/lib/module/NitroSse.nitro.js +4 -0
  12. package/lib/module/NitroSse.nitro.js.map +1 -0
  13. package/lib/module/SseInterface.js +2 -0
  14. package/lib/module/SseInterface.js.map +1 -0
  15. package/lib/module/index.js +22 -0
  16. package/lib/module/index.js.map +1 -0
  17. package/lib/module/package.json +1 -0
  18. package/lib/typescript/package.json +1 -0
  19. package/lib/typescript/src/NitroSse.nitro.d.ts +34 -0
  20. package/lib/typescript/src/NitroSse.nitro.d.ts.map +1 -0
  21. package/lib/typescript/src/SseInterface.d.ts +25 -0
  22. package/lib/typescript/src/SseInterface.d.ts.map +1 -0
  23. package/lib/typescript/src/index.d.ts +5 -0
  24. package/lib/typescript/src/index.d.ts.map +1 -0
  25. package/nitro.json +17 -0
  26. package/nitrogen/generated/android/c++/JFunc_void_std__vector_SseEvent_.hpp +100 -0
  27. package/nitrogen/generated/android/c++/JHttpMethod.hpp +58 -0
  28. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +110 -0
  29. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.hpp +71 -0
  30. package/nitrogen/generated/android/c++/JSseConfig.hpp +98 -0
  31. package/nitrogen/generated/android/c++/JSseEvent.hpp +76 -0
  32. package/nitrogen/generated/android/c++/JSseEventType.hpp +67 -0
  33. package/nitrogen/generated/android/c++/JSseStats.hpp +70 -0
  34. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/Func_void_std__vector_SseEvent_.kt +80 -0
  35. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HttpMethod.kt +23 -0
  36. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HybridNitroSseSpec.kt +82 -0
  37. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +56 -0
  38. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEvent.kt +50 -0
  39. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEventType.kt +26 -0
  40. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseStats.kt +47 -0
  41. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/nitrosseOnLoad.kt +35 -0
  42. package/nitrogen/generated/android/nitrosse+autolinking.cmake +81 -0
  43. package/nitrogen/generated/android/nitrosse+autolinking.gradle +27 -0
  44. package/nitrogen/generated/android/nitrosseOnLoad.cpp +46 -0
  45. package/nitrogen/generated/android/nitrosseOnLoad.hpp +25 -0
  46. package/nitrogen/generated/ios/NitroSse+autolinking.rb +60 -0
  47. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.cpp +41 -0
  48. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +210 -0
  49. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +63 -0
  50. package/nitrogen/generated/ios/NitroSseAutolinking.mm +33 -0
  51. package/nitrogen/generated/ios/NitroSseAutolinking.swift +26 -0
  52. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.cpp +11 -0
  53. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +130 -0
  54. package/nitrogen/generated/ios/swift/Func_void_std__vector_SseEvent_.swift +46 -0
  55. package/nitrogen/generated/ios/swift/HttpMethod.swift +40 -0
  56. package/nitrogen/generated/ios/swift/HybridNitroSseSpec.swift +60 -0
  57. package/nitrogen/generated/ios/swift/HybridNitroSseSpec_cxx.swift +212 -0
  58. package/nitrogen/generated/ios/swift/SseConfig.swift +130 -0
  59. package/nitrogen/generated/ios/swift/SseEvent.swift +101 -0
  60. package/nitrogen/generated/ios/swift/SseEventType.swift +52 -0
  61. package/nitrogen/generated/ios/swift/SseStats.swift +63 -0
  62. package/nitrogen/generated/shared/c++/HttpMethod.hpp +76 -0
  63. package/nitrogen/generated/shared/c++/HybridNitroSseSpec.cpp +26 -0
  64. package/nitrogen/generated/shared/c++/HybridNitroSseSpec.hpp +78 -0
  65. package/nitrogen/generated/shared/c++/SseConfig.hpp +111 -0
  66. package/nitrogen/generated/shared/c++/SseEvent.hpp +102 -0
  67. package/nitrogen/generated/shared/c++/SseEventType.hpp +88 -0
  68. package/nitrogen/generated/shared/c++/SseStats.hpp +96 -0
  69. package/package.json +179 -0
  70. package/src/NitroSse.nitro.ts +37 -0
  71. package/src/SseInterface.ts +28 -0
  72. package/src/index.tsx +26 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 IAmTester35
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,30 @@
1
+ require "json"
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = "NitroSse"
7
+ s.version = package["version"]
8
+ s.summary = package["description"]
9
+ s.homepage = package["homepage"]
10
+ s.license = package["license"]
11
+ s.authors = package["author"]
12
+
13
+ s.platforms = { :ios => min_ios_version_supported }
14
+ s.source = { :git => "https://github.com/MaiThanhNam141/react-native-nitro-sse.git", :tag => "#{s.version}" }
15
+
16
+ s.source_files = [
17
+ "ios/**/*.{swift}",
18
+ "ios/**/*.{m,mm}",
19
+ "cpp/**/*.{hpp,cpp}",
20
+ ]
21
+
22
+ s.dependency 'React-jsi'
23
+ s.dependency 'React-callinvoker'
24
+ s.dependency 'LDSwiftEventSource'
25
+
26
+ load 'nitrogen/generated/ios/NitroSse+autolinking.rb'
27
+ add_nitrogen_files(s)
28
+
29
+ install_modules_dependencies(s)
30
+ end
package/README.md ADDED
@@ -0,0 +1,121 @@
1
+ # 🚀 react-native-nitro-sse
2
+
3
+ High-performance Server-Sent Events (SSE) client for React Native, built on top of **Nitro Modules (JSI)**. Designed for mission-critical systems requiring extreme stability, high-throughput data streaming, and absolute battery optimization.
4
+
5
+ ## 🌟 Why NitroSSE?
6
+
7
+ Unlike traditional EventSource libraries that run on the JS thread or use the legacy Bridge, NitroSSE moves the entire control logic down to the deepest Native layer:
8
+
9
+ - **🚀 Zero-Latency JSI**: Communication between JS and Native is instantaneous, bypassing the asynchronous bridge.
10
+ - **🧠 Smart Reconnect**: Automatic reconnection strategy using **Exponential Backoff** and **Jitter** to prevent thundering herd problems.
11
+ - **🛡️ DoS Protection**: Respects RFC `Retry-After` headers and enforces strict connection frequency limits.
12
+ - **🌊 Backpressure Handling**: Advanced **Batching** mechanism aggregates messages and employs **Tail Drop** strategies to protect the UI thread from freezing during data surges.
13
+ - **🔋 Mobile-First Architecture**: Automatically hibernates when the app enters the background and seamlessly reconnects upon foregrounding to conserve battery.
14
+ - **💓 Heartbeat Detection**: Native-side detection of keep-alive signals (comments) to maintain a reliable connection watchdog.
15
+ - **🛠️ Full Protocol Support**: Comprehensive support for GET/POST methods and dynamic header updates.
16
+
17
+ ---
18
+
19
+ ## 📦 Installation
20
+
21
+ ```sh
22
+ yarn add react-native-nitro-sse react-native-nitro-modules
23
+ # or
24
+ npm install react-native-nitro-sse react-native-nitro-modules
25
+ ```
26
+
27
+ > **Note**: `react-native-nitro-modules` is required as the core foundation for JSI performance.
28
+
29
+ ---
30
+
31
+ ## 🚀 Usage
32
+
33
+ ### 1. Basic Initialization
34
+
35
+ Initialize the module with your endpoint configuration and an event listener.
36
+
37
+ ```tsx
38
+ import { NitroSseModule } from 'react-native-nitro-sse';
39
+
40
+ NitroSseModule.setup(
41
+ {
42
+ url: 'https://api.yourserver.com/stream',
43
+ method: 'get',
44
+ headers: {
45
+ 'Authorization': 'Bearer active-token',
46
+ },
47
+ // Batch messages every 100ms to optimize UI rendering
48
+ batchingIntervalMs: 100,
49
+ // Maximum of 1000 messages in the native queue before tail-drop
50
+ maxBufferSize: 1000,
51
+ },
52
+ (events) => {
53
+ events.forEach((event) => {
54
+ if (event.type === 'message') {
55
+ console.log('Data received:', event.data);
56
+ } else if (event.type === 'heartbeat') {
57
+ console.log('Server heartbeat detected...');
58
+ }
59
+ });
60
+ }
61
+ );
62
+
63
+ // Start the connection
64
+ NitroSseModule.start();
65
+
66
+ // Stop the connection when unmounting or no longer needed
67
+ // NitroSseModule.stop();
68
+ ```
69
+
70
+ ### 2. Check Connection Status
71
+
72
+ You can synchronously check the connection status at any time:
73
+
74
+ ```tsx
75
+ const connected = NitroSseModule.isConnected();
76
+ console.log('Is Connected:', connected);
77
+ ```
78
+
79
+ ### 3. Dynamic Token Updates
80
+
81
+ 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
+
83
+ ```tsx
84
+ NitroSseModule.updateHeaders({
85
+ 'Authorization': 'Bearer new-fresh-token',
86
+ });
87
+ ```
88
+
89
+ ---
90
+
91
+ ## ⚙️ Configuration (SseConfig)
92
+
93
+ | Parameter | Type | Description |
94
+ | :--- | :--- | :--- |
95
+ | `url` | `string` | **Required**. The URL of the SSE endpoint. |
96
+ | `method` | `'get' \| 'post'` | HTTP method (Default: `get`). |
97
+ | `headers` | `Record<string, string>` | Custom headers (e.g., Auth, Content-Type). |
98
+ | `body` | `string` | Request body (payload) for POST requests. |
99
+ | `batchingIntervalMs` | `number` | Time window to buffer events before flushing to JS (Default: 0 - immediate). |
100
+ | `maxBufferSize` | `number` | Native queue limit to prevent memory overflow (Default: 1000). |
101
+ | `backgroundExecution` | `boolean` | (iOS) Attempt to maintain a background task for a short period. |
102
+
103
+ ---
104
+
105
+ ## 🏗️ System Architecture
106
+
107
+ This project employs a robust **Producer-Consumer** model:
108
+
109
+ 1. **Native (Producer)**: Collects data from the socket on a dedicated Background Thread, handling all backpressure logic.
110
+ 2. **Nitro (Bridge)**: Snapshots data and securely transports it via the JSI CallInvoker.
111
+ 3. **JavaScript (Consumer)**: Consumes data in batches, ensuring the UI Loop remains buttery smooth even under heavy load.
112
+
113
+ ---
114
+
115
+ ## 📄 License
116
+
117
+ MIT
118
+
119
+ ---
120
+
121
+ Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)
@@ -0,0 +1,24 @@
1
+ project(nitrosse)
2
+ cmake_minimum_required(VERSION 3.9.0)
3
+
4
+ set(PACKAGE_NAME nitrosse)
5
+ set(CMAKE_VERBOSE_MAKEFILE ON)
6
+ set(CMAKE_CXX_STANDARD 20)
7
+
8
+ # Define C++ library and add all sources
9
+ add_library(${PACKAGE_NAME} SHARED src/main/cpp/cpp-adapter.cpp)
10
+
11
+ # Add Nitrogen specs :)
12
+ include(${CMAKE_SOURCE_DIR}/../nitrogen/generated/android/nitrosse+autolinking.cmake)
13
+
14
+ # Set up local includes
15
+ include_directories("src/main/cpp" "../cpp")
16
+
17
+ find_library(LOG_LIB log)
18
+
19
+ # Link all libraries together
20
+ target_link_libraries(
21
+ ${PACKAGE_NAME}
22
+ ${LOG_LIB}
23
+ android # <-- Android core
24
+ )
@@ -0,0 +1,120 @@
1
+ buildscript {
2
+ ext.NitroSse = [
3
+ kotlinVersion: "2.0.21",
4
+ minSdkVersion: 24,
5
+ compileSdkVersion: 36,
6
+ targetSdkVersion: 36
7
+ ]
8
+
9
+ ext.getExtOrDefault = { prop ->
10
+ if (rootProject.ext.has(prop)) {
11
+ return rootProject.ext.get(prop)
12
+ }
13
+
14
+ return NitroSse[prop]
15
+ }
16
+
17
+ repositories {
18
+ google()
19
+ mavenCentral()
20
+ }
21
+
22
+ dependencies {
23
+ classpath "com.android.tools.build:gradle:8.7.2"
24
+ // noinspection DifferentKotlinGradleVersion
25
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${getExtOrDefault('kotlinVersion')}"
26
+ }
27
+ }
28
+
29
+ def reactNativeArchitectures() {
30
+ def value = rootProject.getProperties().get("reactNativeArchitectures")
31
+ return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
32
+ }
33
+
34
+ apply plugin: "com.android.library"
35
+ apply plugin: "kotlin-android"
36
+ apply from: '../nitrogen/generated/android/nitrosse+autolinking.gradle'
37
+
38
+ apply plugin: "com.facebook.react"
39
+
40
+ android {
41
+ namespace "com.margelo.nitro.nitrosse"
42
+
43
+ compileSdkVersion getExtOrDefault("compileSdkVersion")
44
+
45
+ defaultConfig {
46
+ minSdkVersion getExtOrDefault("minSdkVersion")
47
+ targetSdkVersion getExtOrDefault("targetSdkVersion")
48
+
49
+ externalNativeBuild {
50
+ cmake {
51
+ cppFlags "-frtti -fexceptions -Wall -fstack-protector-all"
52
+ arguments "-DANDROID_STL=c++_shared", "-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON"
53
+ abiFilters (*reactNativeArchitectures())
54
+
55
+ buildTypes {
56
+ debug {
57
+ cppFlags "-O1 -g"
58
+ }
59
+ release {
60
+ cppFlags "-O2"
61
+ }
62
+ }
63
+ }
64
+ }
65
+ }
66
+
67
+ externalNativeBuild {
68
+ cmake {
69
+ path "CMakeLists.txt"
70
+ }
71
+ }
72
+
73
+ packagingOptions {
74
+ excludes = [
75
+ "META-INF",
76
+ "META-INF/**",
77
+ "**/libc++_shared.so",
78
+ "**/libfbjni.so",
79
+ "**/libjsi.so",
80
+ "**/libfolly_json.so",
81
+ "**/libfolly_runtime.so",
82
+ "**/libglog.so",
83
+ "**/libhermes.so",
84
+ "**/libhermes-executor-debug.so",
85
+ "**/libhermes_executor.so",
86
+ "**/libreactnative.so",
87
+ "**/libreactnativejni.so",
88
+ "**/libturbomodulejsijni.so",
89
+ "**/libreact_nativemodule_core.so",
90
+ "**/libjscexecutor.so"
91
+ ]
92
+ }
93
+
94
+ buildFeatures {
95
+ buildConfig true
96
+ prefab true
97
+ }
98
+
99
+ buildTypes {
100
+ release {
101
+ minifyEnabled false
102
+ }
103
+ }
104
+
105
+ lint {
106
+ disable "GradleCompatible"
107
+ }
108
+
109
+ compileOptions {
110
+ sourceCompatibility JavaVersion.VERSION_1_8
111
+ targetCompatibility JavaVersion.VERSION_1_8
112
+ }
113
+ }
114
+
115
+ dependencies {
116
+ implementation "com.facebook.react:react-android"
117
+ implementation project(":react-native-nitro-modules")
118
+ implementation "com.squareup.okhttp3:okhttp:4.12.0"
119
+ implementation "com.squareup.okhttp3:okhttp-sse:4.12.0"
120
+ }
@@ -0,0 +1,2 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ </manifest>
@@ -0,0 +1,6 @@
1
+ #include <jni.h>
2
+ #include "nitrosseOnLoad.hpp"
3
+
4
+ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void*) {
5
+ return margelo::nitro::nitrosse::initialize(vm);
6
+ }
@@ -0,0 +1,279 @@
1
+ package com.margelo.nitro.nitrosse
2
+
3
+ import android.os.Handler
4
+ import android.os.Looper
5
+ import android.util.Log
6
+ import com.facebook.proguard.annotations.DoNotStrip
7
+ import okhttp3.*
8
+ import okhttp3.MediaType.Companion.toMediaType
9
+ import okhttp3.RequestBody.Companion.toRequestBody
10
+ import okhttp3.sse.EventSource
11
+ import okhttp3.sse.EventSources
12
+ import okhttp3.sse.EventSourceListener
13
+ import okio.Buffer
14
+ import okio.ForwardingSource
15
+ import okio.buffer
16
+ import java.util.concurrent.TimeUnit
17
+ import java.util.concurrent.atomic.AtomicBoolean
18
+ import java.util.concurrent.atomic.AtomicLong
19
+ import kotlin.random.Random
20
+
21
+ /**
22
+ * NitroSse implements a high-performance SSE client using OkHttp.
23
+ *
24
+ * ARCHITECTURE DECISIONS:
25
+ * 1. Threading: Uses a dedicated HandlerThread (sseHandlerThread) to offload all network events
26
+ * and buffer management from the Main/JS threads. This prevents UI freezes during high-frequency bursts.
27
+ * 2. Backpressure: Implements a producer-consumer pattern with an internal buffer and batching timer.
28
+ * This solves the "Bridge Flooding" problem by grouping multiple events into a single JSI call.
29
+ * 3. Reliability: Uses exponential backoff with jitter and respects 'Retry-After' headers to
30
+ * prevent DoS-ing the server while ensuring resilient reconnections.
31
+ * 4. Heartbeat: Since OkHttp-SSE obscures comments, we use a Network Interceptor to manually
32
+ * detect ':' bytes, enabling JS-side watchdog timers.
33
+ */
34
+ @DoNotStrip
35
+ class NitroSse : HybridNitroSseSpec() {
36
+ private var client: OkHttpClient? = null
37
+ private var eventSource: EventSource? = null
38
+ private var config: SseConfig? = null
39
+ private var onEventsCallback: ((events: Array<SseEvent>) -> Unit)? = null
40
+
41
+ private val isRunning = AtomicBoolean(false)
42
+ private var wasRunningBeforePaused = false
43
+ private var sseHandlerThread: android.os.HandlerThread? = null
44
+ private var sseHandler: Handler? = null
45
+
46
+ private val eventBuffer = mutableListOf<SseEvent>()
47
+ private var isFlushPending = AtomicBoolean(false)
48
+
49
+ private var backoffCounter = 0
50
+ @Volatile private var lastProcessedId: String? = null
51
+
52
+ private val totalBytesReceived = AtomicLong(0)
53
+ private var reconnectCount = 0
54
+ private var lastErrorTime: Double? = null
55
+ private var lastErrorCode: String? = null
56
+
57
+ private val defaultRetryDelayMs = 3000L
58
+ private val baseBackoffDelayMs = 2000L
59
+ private val maxBackoffDelayMs = 30000L
60
+
61
+ companion object {
62
+ private const val TAG = "NitroSse"
63
+ }
64
+
65
+ override fun setup(config: SseConfig, onEvent: (events: Array<SseEvent>) -> Unit) {
66
+ this.config = config
67
+ this.onEventsCallback = onEvent
68
+
69
+ this.client = OkHttpClient.Builder()
70
+ .connectTimeout(15, TimeUnit.SECONDS)
71
+ .readTimeout(35, TimeUnit.SECONDS)
72
+ .addNetworkInterceptor { chain ->
73
+ val response = chain.proceed(chain.request())
74
+ val responseBody = response.body
75
+ if (responseBody != null) {
76
+ val countingBody = object : ResponseBody() {
77
+ override fun contentType() = responseBody.contentType()
78
+ override fun contentLength() = responseBody.contentLength()
79
+ override fun source() = (object : okio.ForwardingSource(responseBody.source()) {
80
+ override fun read(sink: okio.Buffer, byteCount: Long): Long {
81
+ val bytesRead = super.read(sink, byteCount)
82
+ if (bytesRead != -1L) {
83
+ totalBytesReceived.addAndGet(bytesRead)
84
+
85
+ try {
86
+ val snapshot = sink.snapshot()
87
+ if (snapshot.size > 0 && snapshot.get(0) == ':'.toByte()) {
88
+ pushEventToBuffer(SseEvent(SseEventType.HEARTBEAT, null, null, null, "keep-alive"))
89
+ }
90
+ } catch (e: Exception) {
91
+ // Silent catch for interceptor parsing
92
+ }
93
+ }
94
+ return bytesRead
95
+ }
96
+ }).buffer()
97
+ }
98
+ response.newBuilder().body(countingBody).build()
99
+ } else {
100
+ response
101
+ }
102
+ }
103
+ .build()
104
+
105
+ if (sseHandlerThread == null) {
106
+ sseHandlerThread = android.os.HandlerThread("NitroSseThread").apply { start() }
107
+ sseHandler = Handler(sseHandlerThread!!.looper)
108
+ }
109
+ }
110
+
111
+ private fun pushEventToBuffer(event: SseEvent) {
112
+ val batchInterval = config?.batchingIntervalMs ?: 0.0
113
+ val bufferCapacity = config?.maxBufferSize?.toInt() ?: 1000
114
+
115
+ synchronized(eventBuffer) {
116
+ while (eventBuffer.size >= bufferCapacity) {
117
+ eventBuffer.removeAt(0)
118
+ }
119
+ eventBuffer.add(event)
120
+ }
121
+
122
+ if (batchInterval <= 0) {
123
+ flushBufferToJs()
124
+ } else if (!isFlushPending.getAndSet(true)) {
125
+ sseHandler?.postDelayed({
126
+ flushBufferToJs()
127
+ }, batchInterval.toLong())
128
+ }
129
+ }
130
+
131
+ private fun flushBufferToJs() {
132
+ val eventsToEmit: Array<SseEvent>
133
+ synchronized(eventBuffer) {
134
+ if (eventBuffer.isEmpty()) {
135
+ isFlushPending.set(false)
136
+ return
137
+ }
138
+ eventsToEmit = eventBuffer.toTypedArray()
139
+ eventBuffer.clear()
140
+ }
141
+ isFlushPending.set(false)
142
+ onEventsCallback?.invoke(eventsToEmit)
143
+ }
144
+
145
+ override fun setLastProcessedId(id: String) {
146
+ this.lastProcessedId = id
147
+ }
148
+
149
+ override fun updateHeaders(headers: Map<String, String>) {
150
+ this.config?.let {
151
+ this.config = it.copy(headers = headers)
152
+ Log.d(TAG, "Headers updated for subsequent connections")
153
+ }
154
+ }
155
+
156
+ override fun getStats(): SseStats {
157
+ return SseStats(
158
+ totalBytesReceived.get().toDouble(),
159
+ reconnectCount.toDouble(),
160
+ lastErrorTime,
161
+ lastErrorCode
162
+ )
163
+ }
164
+
165
+ override fun start() {
166
+ if (config == null) return
167
+ isRunning.set(true)
168
+ backoffCounter = 0
169
+ sseHandler?.post { performConnection() }
170
+ }
171
+
172
+ private fun performConnection() {
173
+ if (!isRunning.get()) return
174
+
175
+ val requestBuilder = Request.Builder()
176
+ .url(config!!.url)
177
+ .header("Accept", "text/event-stream")
178
+ .header("Cache-Control", "no-cache")
179
+
180
+ lastProcessedId?.let {
181
+ if (it.isNotEmpty()) requestBuilder.header("Last-Event-ID", it)
182
+ }
183
+
184
+ config!!.headers?.forEach { (k, v) -> requestBuilder.header(k, v) }
185
+
186
+ if (config!!.method == HttpMethod.POST) {
187
+ val body = config!!.body?.toRequestBody("application/json".toMediaType()) ?: "".toRequestBody()
188
+ requestBuilder.post(body)
189
+ }
190
+
191
+ eventSource = EventSources.createFactory(client!!).newEventSource(requestBuilder.build(), sseListener)
192
+ }
193
+
194
+ private fun extractRetryAfterMillis(response: Response?): Long? {
195
+ val header = response?.header("Retry-After") ?: return null
196
+ return try {
197
+ header.toLong() * 1000L
198
+ } catch (e: NumberFormatException) {
199
+ response.headers.getDate("Retry-After")?.let {
200
+ val diff = it.time - System.currentTimeMillis()
201
+ if (diff > 0) diff else null
202
+ }
203
+ }
204
+ }
205
+
206
+ private val sseListener = object : EventSourceListener() {
207
+ override fun onOpen(eventSource: EventSource, response: Response) {
208
+ backoffCounter = 0
209
+ pushEventToBuffer(SseEvent(SseEventType.OPEN, null, null, null, null))
210
+ }
211
+
212
+ override fun onEvent(eventSource: EventSource, id: String?, type: String?, data: String) {
213
+ pushEventToBuffer(SseEvent(SseEventType.MESSAGE, data, id, type, null))
214
+ }
215
+
216
+ override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
217
+ Log.e(TAG, "SSE Failure: ${t?.message}, Code: ${response?.code}")
218
+ if (!isRunning.get()) return
219
+
220
+ val statusCode = response?.code ?: -1
221
+ reconnectCount++
222
+ lastErrorTime = System.currentTimeMillis().toDouble()
223
+ lastErrorCode = t?.javaClass?.simpleName ?: statusCode.toString()
224
+
225
+ val isFatal = (statusCode == 401 || statusCode == 403 || statusCode == 400)
226
+ if (isFatal) {
227
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Fatal Error ($statusCode). Stopping."))
228
+ stop()
229
+ return
230
+ }
231
+
232
+ val retryAfterMillis = extractRetryAfterMillis(response)
233
+ if ((statusCode == 429 || statusCode == 503) && retryAfterMillis != null) {
234
+ val jitter = (500 + Random.nextInt(1500)).toLong()
235
+ val totalDelay = retryAfterMillis + jitter
236
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Retry-After received: ${totalDelay/1000}s"))
237
+ sseHandler?.postDelayed({ if (isRunning.get()) performConnection() }, totalDelay)
238
+ return
239
+ }
240
+
241
+ if (statusCode == 429) {
242
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Rate Limited (429) without Retry-After. Stopping."))
243
+ stop()
244
+ return
245
+ }
246
+
247
+ val isHandshakeError = response == null || response.code != 200
248
+ val reconnectDelay = if (isHandshakeError) {
249
+ val base = Math.min(baseBackoffDelayMs * (1 shl backoffCounter), maxBackoffDelayMs)
250
+ backoffCounter++
251
+ (base * (0.5 + Random.nextDouble())).toLong()
252
+ } else {
253
+ (defaultRetryDelayMs * (0.8 + Random.nextDouble() * 0.4)).toLong()
254
+ }
255
+
256
+ val safeReconnectDelay = Math.max(reconnectDelay, 2000L)
257
+ pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, t?.message ?: "Link lost ($statusCode)"))
258
+ sseHandler?.postDelayed({ if (isRunning.get()) performConnection() }, safeReconnectDelay)
259
+ }
260
+
261
+ override fun onClosed(eventSource: EventSource) {
262
+ if (isRunning.get()) {
263
+ val delay = (defaultRetryDelayMs * (0.8 + Random.nextDouble() * 0.4)).toLong()
264
+ sseHandler?.postDelayed({ if (isRunning.get()) performConnection() }, delay)
265
+ }
266
+ }
267
+ }
268
+
269
+ override fun stop() {
270
+ isRunning.set(false)
271
+ backoffCounter = 0
272
+ sseHandler?.removeCallbacksAndMessages(null)
273
+ eventSource?.cancel()
274
+ eventSource = null
275
+ synchronized(eventBuffer) {
276
+ eventBuffer.clear()
277
+ }
278
+ }
279
+ }
@@ -0,0 +1,22 @@
1
+ package com.margelo.nitro.nitrosse
2
+
3
+ import com.facebook.react.BaseReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.module.model.ReactModuleInfoProvider
7
+
8
+ class NitroSsePackage : BaseReactPackage() {
9
+ override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? {
10
+ return null
11
+ }
12
+
13
+ override fun getReactModuleInfoProvider(): ReactModuleInfoProvider {
14
+ return ReactModuleInfoProvider { HashMap() }
15
+ }
16
+
17
+ companion object {
18
+ init {
19
+ System.loadLibrary("nitrosse")
20
+ }
21
+ }
22
+ }