react-native-nitro-sse 1.0.2 → 1.2.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.
@@ -241,15 +241,18 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
241
241
 
242
242
  private val sseListener = object : EventSourceListener() {
243
243
  override fun onOpen(eventSource: EventSource, response: Response) {
244
+ if (eventSource != this@NitroSse.eventSource) return
244
245
  backoffCounter = 0
245
246
  pushEventToBuffer(SseEvent(SseEventType.OPEN, null, null, null, null))
246
247
  }
247
248
 
248
249
  override fun onEvent(eventSource: EventSource, id: String?, type: String?, data: String) {
250
+ if (eventSource != this@NitroSse.eventSource) return
249
251
  pushEventToBuffer(SseEvent(SseEventType.MESSAGE, data, id, type, null))
250
252
  }
251
253
 
252
254
  override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
255
+ if (eventSource != this@NitroSse.eventSource) return
253
256
  Log.e(TAG, "SSE Failure: ${t?.message}, Code: ${response?.code}")
254
257
  if (!isRunning.get()) return
255
258
 
@@ -270,7 +273,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
270
273
  val jitter = (500 + Random.nextInt(1500)).toLong()
271
274
  val totalDelay = retryAfterMillis + jitter
272
275
  pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, "Retry-After received: ${totalDelay/1000}s"))
273
- sseHandler?.postDelayed({ if (isRunning.get()) performConnection() }, totalDelay)
276
+ sseHandler?.postDelayed({ if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection() }, totalDelay)
274
277
  return
275
278
  }
276
279
 
@@ -291,13 +294,14 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
291
294
 
292
295
  val safeReconnectDelay = Math.max(reconnectDelay, 2000L)
293
296
  pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, t?.message ?: "Link lost ($statusCode)"))
294
- sseHandler?.postDelayed({ if (isRunning.get()) performConnection() }, safeReconnectDelay)
297
+ sseHandler?.postDelayed({ if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection() }, safeReconnectDelay)
295
298
  }
296
299
 
297
300
  override fun onClosed(eventSource: EventSource) {
301
+ if (eventSource != this@NitroSse.eventSource) return
298
302
  if (isRunning.get()) {
299
303
  val delay = (defaultRetryDelayMs * (0.8 + Random.nextDouble() * 0.4)).toLong()
300
- sseHandler?.postDelayed({ if (isRunning.get()) performConnection() }, delay)
304
+ sseHandler?.postDelayed({ if (isRunning.get() && eventSource == this@NitroSse.eventSource) performConnection() }, delay)
301
305
  }
302
306
  }
303
307
  }
@@ -14,7 +14,7 @@ import LDSwiftEventSource
14
14
  * 3. Batching: Reduces JSI bridge overhead by accumulating events and dispatching them
15
15
  * as a single array after a configurable interval.
16
16
  */
17
- class NitroSse: HybridNitroSseSpec, EventHandler {
17
+ class NitroSse: HybridNitroSseSpec {
18
18
  private var eventSource: EventSource?
19
19
  private var config: SseConfig?
20
20
  private var onEventsCallback: ((_ events: [SseEvent]) -> Void)?
@@ -165,9 +165,8 @@ class NitroSse: HybridNitroSseSpec, EventHandler {
165
165
 
166
166
  private func establishConnection() {
167
167
  dispatchPrecondition(condition: .onQueue(sseQueue))
168
- guard isRunning, let config = config, let url = URL(string: config.url) else { return }
169
-
170
- var esConfig = EventSource.Config(handler: self, url: url)
168
+ let handler = SseHandler(parent: self)
169
+ var esConfig = EventSource.Config(handler: handler, url: url)
171
170
  esConfig.headers = config.headers ?? [:]
172
171
 
173
172
  if let lastId = self.lastProcessedId, !lastId.isEmpty {
@@ -178,8 +177,10 @@ class NitroSse: HybridNitroSseSpec, EventHandler {
178
177
  esConfig.method = config.method?.stringValue.uppercased() ?? "GET"
179
178
  esConfig.body = config.body?.data(using: .utf8)
180
179
 
181
- eventSource = EventSource(config: esConfig)
182
- eventSource?.start()
180
+ let es = EventSource(config: esConfig)
181
+ self.eventSource = es
182
+ handler.source = es
183
+ es.start()
183
184
  }
184
185
 
185
186
  func stop() {
@@ -329,9 +330,93 @@ class NitroSse: HybridNitroSseSpec, EventHandler {
329
330
  delay = defaultRetryDelay * (0.8 + Double.random(in: 0...0.4))
330
331
  }
331
332
  let safeDelay = max(delay, 2.0)
333
+ let currentSource = self.eventSource
332
334
  sseQueue.asyncAfter(deadline: .now() + safeDelay) { [weak self] in
333
- guard let self = self, self.isRunning else { return }
335
+ guard let self = self, self.isRunning, self.eventSource === currentSource else { return }
334
336
  self.establishConnection()
335
337
  }
336
338
  }
339
+
340
+ private class SseHandler: EventHandler {
341
+ weak var parent: NitroSse?
342
+ weak var source: EventSource?
343
+
344
+ init(parent: NitroSse) {
345
+ self.parent = parent
346
+ }
347
+
348
+ func onOpened() {
349
+ guard let parent = parent, source === parent.eventSource else { return }
350
+ parent.sseQueue.async {
351
+ parent.backoffCounter = 0
352
+ parent.pushEventToBuffer(SseEvent(type: .open, data: nil, id: nil, event: nil, message: nil))
353
+ }
354
+ }
355
+
356
+ func onClosed() {
357
+ guard let parent = parent, source === parent.eventSource else { return }
358
+ parent.sseQueue.async {
359
+ if parent.isRunning {
360
+ parent.scheduleAutomaticReconnect(isError: false)
361
+ }
362
+ }
363
+ }
364
+
365
+ func onMessage(eventType: String, messageEvent: MessageEvent) {
366
+ guard let parent = parent, source === parent.eventSource else { return }
367
+ parent.sseQueue.async {
368
+ let encodedDataSize = Double(messageEvent.data.utf8.count)
369
+ let metadataSize = Double(eventType.utf8.count) + Double((messageEvent.lastEventId).utf8.count)
370
+ parent.totalBytesReceived += encodedDataSize + metadataSize
371
+
372
+ parent.pushEventToBuffer(SseEvent(type: .message, data: messageEvent.data, id: messageEvent.lastEventId, event: eventType, message: nil))
373
+ }
374
+ }
375
+
376
+ func onComment(comment: String) {
377
+ guard let parent = parent, source === parent.eventSource else { return }
378
+ parent.sseQueue.async {
379
+ parent.totalBytesReceived += Double(comment.utf8.count)
380
+ parent.pushEventToBuffer(SseEvent(type: .heartbeat, data: nil, id: nil, event: nil, message: comment))
381
+ }
382
+ }
383
+
384
+ func onError(error: Error) {
385
+ guard let parent = parent, source === parent.eventSource else { return }
386
+ parent.sseQueue.async {
387
+ guard parent.isRunning else { return }
388
+ let nsError = error as NSError
389
+ let statusCode = nsError.code
390
+
391
+ parent.reconnectCount += 1
392
+ parent.lastErrorTime = Date().timeIntervalSince1970 * 1000
393
+ parent.lastErrorCode = "\(nsError.domain)(\(statusCode))"
394
+
395
+ let isFatalError = (statusCode == 401 || statusCode == 403 || statusCode == 400)
396
+ if isFatalError {
397
+ parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Fatal Error (\(statusCode)). Stopping."))
398
+ parent.stopInternal()
399
+ return
400
+ }
401
+
402
+ let retryAfterSeconds = parent.extractRetryAfterSeconds(error: error)
403
+ if (statusCode == 429 || statusCode == 503), let delay = retryAfterSeconds {
404
+ let jitter = Double.random(in: 0.5...2.0)
405
+ let totalDelay = delay + jitter
406
+ parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Retry-After received (\(statusCode))"))
407
+ parent.scheduleAutomaticReconnectWithFixedDelay(totalDelay)
408
+ return
409
+ }
410
+
411
+ if statusCode == 429 {
412
+ parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Rate Limited (429) without Retry-After. Stopping."))
413
+ parent.stopInternal()
414
+ return
415
+ }
416
+
417
+ parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: error.localizedDescription))
418
+ parent.scheduleAutomaticReconnect(isError: true)
419
+ }
420
+ }
421
+ }
337
422
  }
@@ -22,25 +22,28 @@
22
22
  namespace margelo::nitro::nitrosse {
23
23
 
24
24
  int initialize(JavaVM* vm) {
25
+ return facebook::jni::initialize(vm, []() {
26
+ ::margelo::nitro::nitrosse::registerAllNatives();
27
+ });
28
+ }
29
+
30
+ void registerAllNatives() {
25
31
  using namespace margelo::nitro;
26
32
  using namespace margelo::nitro::nitrosse;
27
- using namespace facebook;
28
33
 
29
- return facebook::jni::initialize(vm, [] {
30
34
  // Register native JNI methods
31
- margelo::nitro::nitrosse::JHybridNitroSseSpec::registerNatives();
32
- margelo::nitro::nitrosse::JFunc_void_std__vector_SseEvent__cxx::registerNatives();
33
-
34
- // Register Nitro Hybrid Objects
35
- HybridObjectRegistry::registerHybridObjectConstructor(
36
- "NitroSse",
37
- []() -> std::shared_ptr<HybridObject> {
38
- static DefaultConstructableObject<JHybridNitroSseSpec::javaobject> object("com/margelo/nitro/nitrosse/NitroSse");
39
- auto instance = object.create();
40
- return instance->cthis()->shared();
41
- }
42
- );
43
- });
35
+ margelo::nitro::nitrosse::JHybridNitroSseSpec::registerNatives();
36
+ margelo::nitro::nitrosse::JFunc_void_std__vector_SseEvent__cxx::registerNatives();
37
+
38
+ // Register Nitro Hybrid Objects
39
+ HybridObjectRegistry::registerHybridObjectConstructor(
40
+ "NitroSse",
41
+ []() -> std::shared_ptr<HybridObject> {
42
+ static DefaultConstructableObject<JHybridNitroSseSpec::javaobject> object("com/margelo/nitro/nitrosse/NitroSse");
43
+ auto instance = object.create();
44
+ return instance->cthis()->shared();
45
+ }
46
+ );
44
47
  }
45
48
 
46
49
  } // namespace margelo::nitro::nitrosse
@@ -6,20 +6,29 @@
6
6
  ///
7
7
 
8
8
  #include <jni.h>
9
+ #include <functional>
9
10
  #include <NitroModules/NitroDefines.hpp>
10
11
 
11
12
  namespace margelo::nitro::nitrosse {
12
13
 
14
+ [[deprecated("Use registerNatives() instead.")]]
15
+ int initialize(JavaVM* vm);
16
+
13
17
  /**
14
- * Initializes the native (C++) part of nitrosse, and autolinks all Hybrid Objects.
15
- * Call this in your `JNI_OnLoad` function (probably inside `cpp-adapter.cpp`).
18
+ * Register the native (C++) part of nitrosse, and autolinks all Hybrid Objects.
19
+ * Call this in your `JNI_OnLoad` function (probably inside `cpp-adapter.cpp`),
20
+ * inside a `facebook::jni::initialize(vm, ...)` call.
16
21
  * Example:
17
22
  * ```cpp (cpp-adapter.cpp)
18
23
  * JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void*) {
19
- * return margelo::nitro::nitrosse::initialize(vm);
24
+ * return facebook::jni::initialize(vm, []() {
25
+ * // register all nitrosse HybridObjects
26
+ * margelo::nitro::nitrosse::registerNatives();
27
+ * // any other custom registrations go here.
28
+ * });
20
29
  * }
21
30
  * ```
22
31
  */
23
- int initialize(JavaVM* vm);
32
+ void registerAllNatives();
24
33
 
25
34
  } // namespace margelo::nitro::nitrosse
@@ -56,7 +56,7 @@ namespace margelo::nitro::nitrosse::bridge::swift {
56
56
  return optional.has_value();
57
57
  }
58
58
  inline HttpMethod get_std__optional_HttpMethod_(const std::optional<HttpMethod>& optional) noexcept {
59
- return *optional;
59
+ return optional.value();
60
60
  }
61
61
 
62
62
  // pragma MARK: std::unordered_map<std::string, std::string>
@@ -96,7 +96,7 @@ namespace margelo::nitro::nitrosse::bridge::swift {
96
96
  return optional.has_value();
97
97
  }
98
98
  inline std::unordered_map<std::string, std::string> get_std__optional_std__unordered_map_std__string__std__string__(const std::optional<std::unordered_map<std::string, std::string>>& optional) noexcept {
99
- return *optional;
99
+ return optional.value();
100
100
  }
101
101
 
102
102
  // pragma MARK: std::optional<std::string>
@@ -111,7 +111,7 @@ namespace margelo::nitro::nitrosse::bridge::swift {
111
111
  return optional.has_value();
112
112
  }
113
113
  inline std::string get_std__optional_std__string_(const std::optional<std::string>& optional) noexcept {
114
- return *optional;
114
+ return optional.value();
115
115
  }
116
116
 
117
117
  // pragma MARK: std::optional<bool>
@@ -126,7 +126,7 @@ namespace margelo::nitro::nitrosse::bridge::swift {
126
126
  return optional.has_value();
127
127
  }
128
128
  inline bool get_std__optional_bool_(const std::optional<bool>& optional) noexcept {
129
- return *optional;
129
+ return optional.value();
130
130
  }
131
131
 
132
132
  // pragma MARK: std::optional<double>
@@ -141,7 +141,7 @@ namespace margelo::nitro::nitrosse::bridge::swift {
141
141
  return optional.has_value();
142
142
  }
143
143
  inline double get_std__optional_double_(const std::optional<double>& optional) noexcept {
144
- return *optional;
144
+ return optional.value();
145
145
  }
146
146
 
147
147
  // pragma MARK: std::vector<SseEvent>
@@ -120,11 +120,25 @@ public extension SseConfig {
120
120
 
121
121
  @inline(__always)
122
122
  var batchingIntervalMs: Double? {
123
- return self.__batchingIntervalMs.value
123
+ return { () -> Double? in
124
+ if bridge.has_value_std__optional_double_(self.__batchingIntervalMs) {
125
+ let __unwrapped = bridge.get_std__optional_double_(self.__batchingIntervalMs)
126
+ return __unwrapped
127
+ } else {
128
+ return nil
129
+ }
130
+ }()
124
131
  }
125
132
 
126
133
  @inline(__always)
127
134
  var maxBufferSize: Double? {
128
- return self.__maxBufferSize.value
135
+ return { () -> Double? in
136
+ if bridge.has_value_std__optional_double_(self.__maxBufferSize) {
137
+ let __unwrapped = bridge.get_std__optional_double_(self.__maxBufferSize)
138
+ return __unwrapped
139
+ } else {
140
+ return nil
141
+ }
142
+ }()
129
143
  }
130
144
  }
@@ -46,7 +46,14 @@ public extension SseStats {
46
46
 
47
47
  @inline(__always)
48
48
  var lastErrorTime: Double? {
49
- return self.__lastErrorTime.value
49
+ return { () -> Double? in
50
+ if bridge.has_value_std__optional_double_(self.__lastErrorTime) {
51
+ let __unwrapped = bridge.get_std__optional_double_(self.__lastErrorTime)
52
+ return __unwrapped
53
+ } else {
54
+ return nil
55
+ }
56
+ }()
50
57
  }
51
58
 
52
59
  @inline(__always)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-nitro-sse",
3
- "version": "1.0.2",
3
+ "version": "1.2.0",
4
4
  "description": "High-performance Server-Sent Events (SSE) for React Native, powered by Nitro Modules.",
5
5
  "main": "./lib/module/index.js",
6
6
  "types": "./lib/typescript/src/index.d.ts",
@@ -41,6 +41,7 @@
41
41
  "typecheck": "tsc",
42
42
  "test": "jest",
43
43
  "release": "release-it --only-version",
44
+ "server": "node example/sse-server.js",
44
45
  "lint": "eslint \"**/*.{js,ts,tsx}\""
45
46
  },
46
47
  "keywords": [
@@ -83,12 +84,12 @@
83
84
  "eslint-plugin-prettier": "^5.5.4",
84
85
  "jest": "^29.7.0",
85
86
  "lefthook": "^2.0.3",
86
- "nitrogen": "0.33.8",
87
+ "nitrogen": "0.34.0",
87
88
  "prettier": "^2.8.8",
88
89
  "react": "19.2.0",
89
90
  "react-native": "0.83.0",
90
91
  "react-native-builder-bob": "^0.40.17",
91
- "react-native-nitro-modules": "0.33.8",
92
+ "react-native-nitro-modules": "0.34.0",
92
93
  "release-it": "^19.0.4",
93
94
  "turbo": "^2.5.6",
94
95
  "typescript": "^5.9.2"
@@ -96,7 +97,7 @@
96
97
  "peerDependencies": {
97
98
  "react": "*",
98
99
  "react-native": "*",
99
- "react-native-nitro-modules": "0.33.8"
100
+ "react-native-nitro-modules": "0.34.0"
100
101
  },
101
102
  "workspaces": [
102
103
  "example"
@@ -176,4 +177,4 @@
176
177
  ],
177
178
  "version": "0.57.0"
178
179
  }
179
- }
180
+ }