react-native-nitro-sse 2.3.2 → 2.4.0-beta.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 (60) hide show
  1. package/README.md +1 -1
  2. package/android/build.gradle +11 -0
  3. package/android/jacoco.gradle +33 -0
  4. package/android/src/main/java/com/margelo/nitro/nitrosse/AndroidSseDispatcher.kt +27 -0
  5. package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +66 -0
  6. package/android/src/main/java/com/margelo/nitro/nitrosse/NetworkInspector.kt +6 -3
  7. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +306 -655
  8. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSsePackage.kt +4 -0
  9. package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +108 -0
  10. package/android/src/main/java/com/margelo/nitro/nitrosse/SseDispatcher.kt +14 -0
  11. package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +99 -0
  12. package/android/src/main/java/com/margelo/nitro/nitrosse/SseLifecycleManager.kt +52 -0
  13. package/android/src/main/java/com/margelo/nitro/nitrosse/SseNetworkMonitor.kt +81 -0
  14. package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +80 -0
  15. package/ios/NitroSse.swift +413 -613
  16. package/ios/SseConfig+CopyWith.swift +46 -0
  17. package/ios/SseConnectionHandler.swift +113 -0
  18. package/ios/SseDispatchQueueDispatcher.swift +38 -0
  19. package/ios/SseDispatcher.swift +18 -0
  20. package/ios/SseEventBuffer.swift +75 -0
  21. package/ios/SseLifecycleManager.swift +118 -0
  22. package/ios/SseNetworkMonitor.swift +79 -0
  23. package/ios/SseReconnectStrategy.swift +76 -0
  24. package/lib/module/NitroSseClient.js +8 -1
  25. package/lib/module/NitroSseClient.js.map +1 -1
  26. package/lib/typescript/src/NitroSse.nitro.d.ts +5 -1
  27. package/lib/typescript/src/NitroSse.nitro.d.ts.map +1 -1
  28. package/lib/typescript/src/NitroSseClient.d.ts +2 -1
  29. package/lib/typescript/src/NitroSseClient.d.ts.map +1 -1
  30. package/lib/typescript/src/SseInterface.d.ts +10 -1
  31. package/lib/typescript/src/SseInterface.d.ts.map +1 -1
  32. package/nitrogen/generated/android/c++/JFunc_void_std__vector_SseEvent_.hpp +2 -0
  33. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +9 -0
  34. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.hpp +1 -0
  35. package/nitrogen/generated/android/c++/JSseEvent.hpp +9 -3
  36. package/nitrogen/generated/android/c++/JSseEventType.hpp +3 -0
  37. package/nitrogen/generated/android/c++/JSseState.hpp +76 -0
  38. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.kt +0 -2
  39. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/Func_void_std__vector_SseEvent_.kt +0 -2
  40. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HybridNitroSseSpec.kt +6 -0
  41. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEvent.kt +9 -4
  42. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEventType.kt +2 -1
  43. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseState.kt +29 -0
  44. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +27 -0
  45. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +3 -0
  46. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +11 -0
  47. package/nitrogen/generated/ios/swift/HybridNitroSseSpec.swift +1 -0
  48. package/nitrogen/generated/ios/swift/HybridNitroSseSpec_cxx.swift +12 -0
  49. package/nitrogen/generated/ios/swift/SseEvent.swift +12 -1
  50. package/nitrogen/generated/ios/swift/SseEventType.swift +4 -0
  51. package/nitrogen/generated/ios/swift/SseState.swift +64 -0
  52. package/nitrogen/generated/shared/c++/HybridNitroSseSpec.cpp +1 -0
  53. package/nitrogen/generated/shared/c++/HybridNitroSseSpec.hpp +4 -0
  54. package/nitrogen/generated/shared/c++/SseEvent.hpp +9 -2
  55. package/nitrogen/generated/shared/c++/SseEventType.hpp +4 -0
  56. package/nitrogen/generated/shared/c++/SseState.hpp +100 -0
  57. package/package.json +3 -3
  58. package/src/NitroSse.nitro.ts +6 -1
  59. package/src/NitroSseClient.ts +9 -0
  60. package/src/SseInterface.ts +25 -1
@@ -1,96 +1,106 @@
1
1
  import Foundation
2
- import ObjectiveC
3
2
  import NitroModules
4
3
  import LDSwiftEventSource
5
4
  import Network
6
- #if os(iOS)
7
- import UIKit
8
- #endif
9
-
10
- /**
11
- * NitroSse implements a high-performance SSE client for iOS using LDSwiftEventSource.
12
- *
13
- * ARCHITECTURE DECISIONS:
14
- * 1. Threading Serialization: All operations are strictly serialized on a dedicated background queue (sseQueue).
15
- * This ensures thread-safety for internal states (buffer, backoff) and prevents blocking the JS/Main threads.
16
- * 2. Mobile Survival Logic: Implements a "Hibernation" pattern. When the app enters the background,
17
- * we flush remaining events and stop the socket to preserve battery and follow Apple's background policies.
18
- * The connection is automatically resumed from the last known ID when the app returns to foreground.
19
- * 3. Batching: Reduces JSI bridge overhead by accumulating events and dispatching them
20
- * as a single array after a configurable interval.
21
- */
5
+
6
+ /// NitroSse implements a high-performance SSE client for iOS using LDSwiftEventSource.
7
+ ///
8
+ /// Architectural Principles:
9
+ /// 1. Threading Serialization: All mutable state and operations are strictly serialized on a dedicated background dispatcher (`SseDispatcher`)
10
+ /// to eliminate data races and prevent blocking JS/UI threads.
11
+ /// 2. Mobile Lifecycle Hibernation: When entering background without background execution enabled, the connection is gracefully hibernated
12
+ /// (flushing pending events and stopping sockets) to comply with iOS background execution limits and conserve battery.
13
+ /// 3. Event Batching: Events are buffered and flushed in batches to minimize JSI bridge overhead.
14
+ /// 4. Versioned Connection Attempts: Reconnection attempts use `connectionAttemptVersion` counters to discard stale async callbacks.
22
15
  class NitroSse: HybridNitroSseSpec {
23
- private static let sseQueueKey = DispatchSpecificKey<Void>()
16
+ private let dispatcher: SseDispatcher
24
17
 
25
- deinit {
26
- if DispatchQueue.getSpecific(key: NitroSse.sseQueueKey) != nil {
27
- self.stopInternal()
28
- self.stopNetworkMonitoring()
29
- } else {
30
- sseQueue.sync {
31
- self.stopInternal()
32
- self.stopNetworkMonitoring()
33
- }
34
- }
35
- NotificationCenter.default.removeObserver(self)
18
+ public override init() {
19
+ let queue = DispatchQueue(label: "com.margelo.nitro.sse", qos: .utility)
20
+ let key = DispatchSpecificKey<Void>()
21
+ queue.setSpecific(key: key, value: ())
22
+ self.dispatcher = SseDispatchQueueDispatcher(queue: queue, queueKey: key)
23
+ super.init()
24
+ }
25
+
26
+ internal init(dispatcher: SseDispatcher) {
27
+ self.dispatcher = dispatcher
28
+ super.init()
36
29
  }
30
+
31
+ // MARK: - State
32
+
37
33
  private var eventSource: EventSource?
38
34
  private var config: SseConfig?
39
- private var onEventsCallback: ((_ events: [SseEvent]) -> Void)?
40
35
  private var isRunning: Bool = false
41
36
  private var isDispatcherDestroyed: Bool = false
37
+ internal var connectionAttemptVersion: Int = 0
38
+ private var requestId: String? = nil
39
+ private var lastProcessedId: String? = nil
40
+ private var currentState: SseState = .idle
41
+
42
42
  private var consecutiveAuthErrors: Int = 0
43
43
  private let maxAuthRetries: Int = 3
44
- private var requestId: String? = nil
45
- private var eventBuffer: [SseEvent] = []
46
- private var isFlushPending: Bool = false
47
-
48
- private var backoffCounter: Int = 0
49
- private var currentReconnectAttempts: Int = 0
50
- private var lastProcessedId: String? = nil
51
-
44
+
52
45
  private var totalBytesReceived: Double = 0
53
46
  private var reconnectCount: Double = 0
54
47
  private var lastErrorTime: Double? = nil
55
48
  private var lastErrorCode: String? = nil
56
-
57
- private let sseQueue: DispatchQueue = {
58
- let queue = DispatchQueue(label: "com.margelo.nitro.sse", qos: .utility)
59
- queue.setSpecific(key: NitroSse.sseQueueKey, value: ())
60
- return queue
61
- }()
62
- private var connectionAttemptVersion: Int = 0
63
- #if os(iOS)
64
- private var backgroundTaskIdentifier: UIBackgroundTaskIdentifier = .invalid
65
- private var isBackgroundTaskActive: Bool = false
66
- #endif
67
- private var wasRunningBeforeHibernation: Bool = false
68
- private var isAppInBackground: Bool = false
69
49
 
70
- private var pathMonitor: NWPathMonitor?
71
- private var lastPathInterface: NWInterface.InterfaceType?
50
+ private var wasRunningBeforeHibernation: Bool = false
72
51
  private var wasRunningBeforeNetworkLoss: Bool = false
73
52
 
53
+ // MARK: - Collaborators
54
+
55
+ private let eventBuffer = SseEventBuffer()
56
+ private let reconnectStrategy = SseReconnectStrategy()
57
+ private var networkMonitor: SseNetworkMonitor?
58
+ private var lifecycleManager: SseLifecycleManager?
59
+
60
+ // MARK: - Lifecycle
61
+
62
+ deinit {
63
+ // Synchronous cleanup is required during deallocation to avoid executing callbacks on deallocated instances.
64
+ if dispatcher.isCurrentDispatcher() {
65
+ self.stopInternal()
66
+ self.networkMonitor?.stop()
67
+ } else {
68
+ dispatcher.sync {
69
+ self.stopInternal()
70
+ self.networkMonitor?.stop()
71
+ }
72
+ }
73
+ lifecycleManager?.stopObserving()
74
+ }
74
75
 
76
+ // MARK: - HybridNitroSseSpec
75
77
 
76
- /**
77
- * Set up the NitroSse instance with configuration and an event callback.
78
- * This prepares the lifecycle observers and internal dispatch queue.
79
- *
80
- * - Parameters:
81
- * - config: The SSE configuration containing URL, headers, and more.
82
- * - onEvent: Callback function to receive batched SSE events.
83
- */
78
+ /// Configures the SSE client parameters, event buffer, backoff strategy, and lifecycle observers.
84
79
  func setup(config: SseConfig, onEvent: @escaping ((_ events: [SseEvent]) -> Void)) throws {
85
- sseQueue.async {
80
+ dispatcher.async {
86
81
  self.config = config
87
- self.onEventsCallback = onEvent
88
82
 
89
- NotificationCenter.default.removeObserver(self)
90
- #if os(iOS)
91
- NotificationCenter.default.addObserver(self, selector: #selector(self.handleAppDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
92
- NotificationCenter.default.addObserver(self, selector: #selector(self.handleAppWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
93
- #endif
83
+ self.eventBuffer.configure(
84
+ batchingIntervalMs: config.batchingIntervalMs ?? 0,
85
+ maxBufferSize: config.maxBufferSize ?? 1000,
86
+ dispatcher: self.dispatcher,
87
+ onFlush: onEvent
88
+ )
89
+
90
+ self.reconnectStrategy.configure(
91
+ retryIntervalMs: config.retryIntervalMs,
92
+ maxRetryIntervalMs: config.maxRetryIntervalMs,
93
+ jitterFactor: config.jitterFactor,
94
+ maxReconnectAttempts: config.maxReconnectAttempts
95
+ )
96
+
97
+ self.lifecycleManager?.stopObserving()
98
+ self.lifecycleManager = SseLifecycleManager(
99
+ dispatcher: self.dispatcher,
100
+ onBackground: { [weak self] in self?.handleAppDidEnterBackground() },
101
+ onForeground: { [weak self] in self?.handleAppWillEnterForeground() }
102
+ )
103
+ self.lifecycleManager?.startObserving()
94
104
 
95
105
  if config.monitorNetwork != false {
96
106
  self.startNetworkMonitoring()
@@ -100,49 +110,137 @@ class NitroSse: HybridNitroSseSpec {
100
110
  }
101
111
  }
102
112
 
103
- private func stopNetworkMonitoring() {
104
- dispatchPrecondition(condition: .onQueue(sseQueue))
105
- pathMonitor?.cancel()
106
- pathMonitor = nil
107
- lastPathInterface = nil
113
+ /// Sets the Last-Event-ID header to resume streaming from a specific event boundary.
114
+ func setLastProcessedId(id: String) {
115
+ dispatcher.async {
116
+ self.lastProcessedId = id
117
+ }
108
118
  }
109
-
110
- private func startNetworkMonitoring() {
111
- dispatchPrecondition(condition: .onQueue(sseQueue))
112
- guard pathMonitor == nil else { return }
113
-
114
- let monitor = NWPathMonitor()
115
- monitor.pathUpdateHandler = { [weak self] path in
116
- self?.sseQueue.async {
117
- self?.handleNetworkChange(path: path)
118
- }
119
+
120
+ /// Replaces active HTTP headers for subsequent request attempts (e.g. updating authorization tokens).
121
+ func updateHeaders(headers: [String: String]) throws {
122
+ dispatcher.async {
123
+ guard let config = self.config else { return }
124
+ self.config = config.copyWith(headers: headers)
125
+ print("[NitroSse] Headers updated for subsequent connections.")
119
126
  }
120
- self.pathMonitor = monitor
121
- monitor.start(queue: sseQueue)
122
127
  }
123
-
124
- private func handleNetworkChange(path: NWPath) {
125
- dispatchPrecondition(condition: .onQueue(sseQueue))
126
- let isSatisfied = path.status == .satisfied
127
-
128
- var interfaceType: NWInterface.InterfaceType? = nil
129
- if path.usesInterfaceType(.wifi) {
130
- interfaceType = .wifi
131
- } else if path.usesInterfaceType(.cellular) {
132
- interfaceType = .cellular
133
- } else if path.usesInterfaceType(.wiredEthernet) {
134
- interfaceType = .wiredEthernet
128
+
129
+ /// Fetches runtime metrics synchronously on the dispatcher to avoid data races.
130
+ func getStats() throws -> SseStats {
131
+ return dispatcher.sync {
132
+ return SseStats(
133
+ totalBytesReceived: totalBytesReceived,
134
+ reconnectCount: reconnectCount,
135
+ lastErrorTime: lastErrorTime,
136
+ lastErrorCode: lastErrorCode
137
+ )
138
+ }
139
+ }
140
+
141
+ /// Fetches the current connection state synchronously on the dispatcher to avoid data races.
142
+ func getState() throws -> SseState {
143
+ return dispatcher.sync {
144
+ return currentState
145
+ }
146
+ }
147
+
148
+ private func updateState(_ newState: SseState) {
149
+ dispatcher.assertOnQueue()
150
+ if self.currentState != newState {
151
+ self.currentState = newState
152
+ self.eventBuffer.push(SseEvent(type: .state, data: nil, parsedData: nil, id: nil, event: nil, message: nil, statusCode: nil, retry: nil, state: newState))
153
+ }
154
+ }
155
+
156
+ /// Begins connection establishment and resets retry counters.
157
+ func start() throws {
158
+ let startBody = {
159
+ guard !self.isRunning else { return }
160
+
161
+ guard self.config != nil else {
162
+ throw RuntimeError("NitroSse not configured. Call setup() first.")
163
+ }
164
+
165
+ self.isRunning = true
166
+ self.isDispatcherDestroyed = false
167
+ self.consecutiveAuthErrors = 0
168
+ self.reconnectStrategy.reset()
169
+ self.connectionAttemptVersion += 1
170
+ self.updateState(.connecting)
171
+ let version = self.connectionAttemptVersion
172
+
173
+ self.establishConnection(attemptVersion: version)
174
+ }
175
+
176
+ if dispatcher.isCurrentDispatcher() {
177
+ try startBody()
135
178
  } else {
136
- interfaceType = path.availableInterfaces.first?.type
179
+ try dispatcher.sync(startBody)
180
+ }
181
+ }
182
+
183
+ /// Stops active network streaming and invalidates pending reconnection timers by incrementing attempt version.
184
+ func stop() {
185
+ dispatcher.async {
186
+ self.connectionAttemptVersion += 1
187
+ self.stopInternal()
188
+ }
189
+ }
190
+
191
+ /// Immediately flushes all buffered events to JavaScript via the bridge callback.
192
+ func flush() {
193
+ dispatcher.async {
194
+ self.eventBuffer.flush()
195
+ }
196
+ }
197
+
198
+ /// Teardown existing connection and initiate a new request attempt.
199
+ func restart() {
200
+ dispatcher.async {
201
+ self.stopInternal()
202
+ self.isRunning = true
203
+ self.requestId = nil
204
+ self.connectionAttemptVersion += 1
205
+ self.updateState(.connecting)
206
+ self.establishConnection(attemptVersion: self.connectionAttemptVersion)
137
207
  }
208
+ }
209
+
210
+ /// Indicates whether the client is currently running or reconnecting.
211
+ func isConnected() -> Bool {
212
+ return dispatcher.sync {
213
+ return isRunning
214
+ }
215
+ }
216
+
217
+ // MARK: - Network Monitoring
218
+
219
+ private func startNetworkMonitoring() {
220
+ dispatcher.assertOnQueue()
221
+ guard networkMonitor == nil else { return }
138
222
 
139
- print("[NitroSse] Network path changed: status=\(path.status), interface=\(String(describing: interfaceType))")
223
+ let monitor = SseNetworkMonitor(dispatcher: dispatcher) { [weak self] isSatisfied, interfaceChanged, interfaceType in
224
+ self?.handleNetworkChange(isSatisfied: isSatisfied, interfaceChanged: interfaceChanged, interfaceType: interfaceType)
225
+ }
226
+ self.networkMonitor = monitor
227
+ monitor.start()
228
+ }
229
+
230
+ private func stopNetworkMonitoring() {
231
+ dispatcher.assertOnQueue()
232
+ networkMonitor?.stop()
233
+ networkMonitor = nil
234
+ }
235
+
236
+ private func handleNetworkChange(isSatisfied: Bool, interfaceChanged: Bool, interfaceType: NWInterface.InterfaceType?) {
237
+ dispatcher.assertOnQueue()
140
238
 
141
239
  if isSatisfied {
142
240
  if wasRunningBeforeNetworkLoss {
143
241
  print("[NitroSse] Network restored. Resuming stream.")
144
242
  wasRunningBeforeNetworkLoss = false
145
- if self.isAppInBackground && self.config?.backgroundExecution != true {
243
+ if lifecycleManager?.isAppInBackground == true && self.config?.backgroundExecution != true {
146
244
  self.wasRunningBeforeHibernation = true
147
245
  } else if isRunning {
148
246
  self.restart()
@@ -150,11 +248,8 @@ class NitroSse: HybridNitroSseSpec {
150
248
  try? self.start()
151
249
  }
152
250
  } else if isRunning {
153
- if let lastInterface = lastPathInterface, let currentInterface = interfaceType, lastInterface != currentInterface {
154
- print("[NitroSse] Network interface changed (\(lastInterface) -> \(currentInterface)). Restarting stream.")
155
- self.restart()
156
- } else if lastPathInterface == nil {
157
- print("[NitroSse] Network interface acquired. Restarting stream.")
251
+ if interfaceChanged {
252
+ print("[NitroSse] Network interface changed. Restarting stream.")
158
253
  self.restart()
159
254
  }
160
255
  }
@@ -162,64 +257,49 @@ class NitroSse: HybridNitroSseSpec {
162
257
  if isRunning {
163
258
  print("[NitroSse] Network lost. Hibernating.")
164
259
  wasRunningBeforeNetworkLoss = true
260
+ self.updateState(.paused)
165
261
  self.hibernateConnection()
166
262
  }
167
263
  }
264
+ }
265
+
266
+ // MARK: - App Lifecycle Handling
267
+
268
+ private func handleAppDidEnterBackground() {
269
+ dispatcher.assertOnQueue()
270
+ guard self.isRunning, let config = self.config else { return }
168
271
 
169
- if isSatisfied {
170
- self.lastPathInterface = interfaceType
272
+ if config.backgroundExecution == true {
273
+ print("[NitroSse] App backgrounded. backgroundExecution is true, keeping connection alive.")
274
+ self.lifecycleManager?.beginBackgroundKeepAlive { [weak self] in
275
+ print("[NitroSse] Background task expired. Hibernating now.")
276
+ self?.updateState(.paused)
277
+ self?.hibernateConnection()
278
+ }
279
+ return
171
280
  }
281
+
282
+ self.updateState(.paused)
283
+ self.hibernateConnection()
172
284
  }
173
-
174
- @objc private func handleAppDidEnterBackground() {
175
- sseQueue.async {
176
- self.isAppInBackground = true
177
- guard self.isRunning, let config = self.config else { return }
178
-
179
- if config.backgroundExecution == true {
180
- print("[NitroSse] App backgrounded. backgroundExecution is true, keeping connection alive.")
181
- #if os(iOS)
182
- self.cleanupBackgroundTask()
183
- self.isBackgroundTaskActive = true
184
-
185
- DispatchQueue.main.async { [weak self] in
186
- let taskId = UIApplication.shared.beginBackgroundTask(withName: "NitroSse-KeepAlive") {
187
- self?.sseQueue.async {
188
- print("[NitroSse] Background task expired. Hibernating now.")
189
- self?.hibernateConnection()
190
- }
191
- }
192
- self?.sseQueue.async {
193
- if self?.isBackgroundTaskActive == true {
194
- if let oldTaskId = self?.backgroundTaskIdentifier, oldTaskId != .invalid {
195
- DispatchQueue.main.async {
196
- UIApplication.shared.endBackgroundTask(oldTaskId)
197
- }
198
- }
199
- self?.backgroundTaskIdentifier = taskId
200
- } else {
201
- DispatchQueue.main.async {
202
- UIApplication.shared.endBackgroundTask(taskId)
203
- }
204
- }
205
- }
206
- }
207
- #endif
208
- return
209
- }
210
-
211
- self.hibernateConnection()
285
+
286
+ private func handleAppWillEnterForeground() {
287
+ dispatcher.assertOnQueue()
288
+ if self.wasRunningBeforeHibernation {
289
+ print("[NitroSse] App foregrounded. Resuming stream.")
290
+ self.wasRunningBeforeHibernation = false
291
+ try? self.start()
212
292
  }
213
293
  }
214
294
 
215
295
  private func hibernateConnection() {
216
- dispatchPrecondition(condition: .onQueue(sseQueue))
296
+ dispatcher.assertOnQueue()
217
297
  guard self.isRunning else { return }
218
298
 
219
299
  self.wasRunningBeforeHibernation = true
220
300
  print("[NitroSse] Hibernating NitroSse connection.")
221
301
 
222
- self.flushEventsToJs()
302
+ self.eventBuffer.flush()
223
303
 
224
304
  self.eventSource?.stop()
225
305
  self.eventSource = nil
@@ -229,197 +309,41 @@ class NitroSse: HybridNitroSseSpec {
229
309
  }
230
310
  self.isRunning = false
231
311
 
232
- self.cleanupBackgroundTask()
233
- }
234
-
235
- @objc private func handleAppWillEnterForeground() {
236
- sseQueue.async {
237
- self.isAppInBackground = false
238
- self.cleanupBackgroundTask()
239
- if self.wasRunningBeforeHibernation {
240
- print("[NitroSse] App foregrounded. Resuming stream.")
241
- self.wasRunningBeforeHibernation = false
242
- try? self.start()
243
- }
244
- }
245
- }
246
-
247
- private func cleanupBackgroundTask() {
248
- dispatchPrecondition(condition: .onQueue(sseQueue))
249
- #if os(iOS)
250
- self.isBackgroundTaskActive = false
251
- let taskId = self.backgroundTaskIdentifier
252
- if taskId != .invalid {
253
- self.backgroundTaskIdentifier = .invalid
254
- DispatchQueue.main.async {
255
- UIApplication.shared.endBackgroundTask(taskId)
256
- }
257
- }
258
- #endif
259
- }
260
-
261
- private func pushEventToBuffer(_ event: SseEvent) {
262
- dispatchPrecondition(condition: .onQueue(sseQueue))
263
-
264
- let batchIntervalMs = config?.batchingIntervalMs ?? 0
265
- let bufferCapacity = Int(config?.maxBufferSize ?? 1000)
266
-
267
- eventBuffer.append(event)
268
-
269
- // If we reached capacity, flush immediately regardless of interval
270
- if eventBuffer.count >= bufferCapacity || batchIntervalMs <= 0 {
271
- flushEventsToJs()
272
- } else if !isFlushPending {
273
- isFlushPending = true
274
- sseQueue.asyncAfter(deadline: .now() + (Double(batchIntervalMs) / 1000.0)) { [weak self] in
275
- self?.sseQueue.async {
276
- self?.flushEventsToJs()
277
- }
278
- }
279
- }
280
- }
281
- private func flushEventsToJs() {
282
- dispatchPrecondition(condition: .onQueue(sseQueue))
283
- guard !eventBuffer.isEmpty else { return }
284
-
285
- let batch = eventBuffer
286
- eventBuffer.removeAll()
287
- isFlushPending = false
288
-
289
- onEventsCallback?(batch)
290
- }
291
-
292
- internal func parseJsonToAnyMap(_ data: String) -> AnyMap? {
293
- guard let jsonData = data.data(using: .utf8) else { return nil }
294
- do {
295
- if let dictionary = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any?] {
296
- return AnyMap.fromDictionaryIgnoreIncompatible(dictionary)
297
- }
298
- } catch {
299
- // Non-fatal, just log and return nil
300
- print("[NitroSse] Failed to parse JSON: \(error.localizedDescription)")
301
- }
302
- return nil
312
+ self.lifecycleManager?.cleanupBackgroundTask()
303
313
  }
304
314
 
305
- /**
306
- * Manually set the last seen event ID.
307
- * This will be used as the 'Last-Event-ID' header on the next connection attempt.
308
- */
309
- func setLastProcessedId(id: String) {
310
- sseQueue.async {
311
- self.lastProcessedId = id
312
- }
313
- }
314
-
315
- /// Update the HTTP headers that will be used for subsequent SSE connections.
316
- /// - Parameters:
317
- /// - headers: A dictionary of HTTP header names and values to replace the current headers for future connections.
318
- func updateHeaders(headers: [String: String]) throws {
319
- sseQueue.async {
320
- guard let config = self.config else { return }
321
- self.config = SseConfig(
322
- url: config.url,
323
- method: config.method,
324
- headers: headers,
325
- body: config.body,
326
- backgroundExecution: config.backgroundExecution,
327
- batchingIntervalMs: config.batchingIntervalMs,
328
- maxBufferSize: config.maxBufferSize,
329
- connectionTimeoutMs: config.connectionTimeoutMs,
330
- readTimeoutMs: config.readTimeoutMs,
331
- retryIntervalMs: config.retryIntervalMs,
332
- maxRetryIntervalMs: config.maxRetryIntervalMs,
333
- jitterFactor: config.jitterFactor,
334
- maxReconnectAttempts: config.maxReconnectAttempts,
335
- autoParseJSON: config.autoParseJSON,
336
- monitorNetwork: config.monitorNetwork,
337
- onBeforeRequest: config.onBeforeRequest,
338
- mock: config.mock
339
- )
340
- print("[NitroSse] Headers updated for subsequent connections.")
341
- }
342
- }
315
+ // MARK: - Connection
343
316
 
344
- /**
345
- * Returns runtime statistics about the SSE connection.
346
- */
347
- func getStats() throws -> SseStats {
348
- return sseQueue.sync {
349
- return SseStats(
350
- totalBytesReceived: totalBytesReceived,
351
- reconnectCount: reconnectCount,
352
- lastErrorTime: lastErrorTime,
353
- lastErrorCode: lastErrorCode
354
- )
355
- }
356
- }
357
-
358
- /**
359
- * Start the SSE connection.
360
- * This triggers the initial request and handles subsequent reconnections.
361
- */
362
- func start() throws {
363
- let startBody = {
364
- guard !self.isRunning else { return }
365
-
366
- guard self.config != nil else {
367
- throw RuntimeError("NitroSse not configured. Call setup() first.")
368
- }
369
-
370
- self.isRunning = true
371
- self.isDispatcherDestroyed = false
372
- self.consecutiveAuthErrors = 0
373
- self.backoffCounter = 0
374
- self.connectionAttemptVersion += 1
375
- let version = self.connectionAttemptVersion
376
-
377
- self.establishConnection(attemptVersion: version)
378
- }
379
-
380
- if DispatchQueue.getSpecific(key: NitroSse.sseQueueKey) != nil {
381
- try startBody()
382
- } else {
383
- try sseQueue.sync(execute: startBody)
384
- }
385
- }
386
-
387
- /// Initiates a new SSE connection attempt using the current configuration, honoring the provided attempt version to ignore stale async work.
388
- ///
389
- /// If a configured `onBeforeRequest` interceptor is present, this method executes it (with a configurable timeout); when the interceptor resolves with additional headers those headers are merged into the active configuration before proceeding. If the interceptor fails or times out, interceptor error handling is invoked. If no interceptor is configured, the connection is established immediately.
390
- /// - Parameters:
391
- /// - attemptVersion: A numeric token representing the connection attempt version; the method aborts if this does not match the current `connectionAttemptVersion`, ensuring stale asynchronous results are ignored.
317
+ /// Initiates an SSE connection attempt, invoking `onBeforeRequest` interceptor if configured.
318
+ /// Ignores stale calls where `attemptVersion` no longer matches `self.connectionAttemptVersion`.
392
319
  private func establishConnection(attemptVersion: Int) {
393
- dispatchPrecondition(condition: .onQueue(sseQueue))
320
+ dispatcher.assertOnQueue()
394
321
  guard isRunning, let config = config, attemptVersion == self.connectionAttemptVersion else { return }
395
322
 
396
323
  if let interceptor = config.onBeforeRequest {
397
324
 
398
325
  let capturedConfig = config
326
+ // Reference-type completion flag to prevent races between interceptor promise resolution and connection timeout.
399
327
  class CompletionFlag {
400
328
  var isCompleted = false
401
329
  }
402
330
  let flag = CompletionFlag()
403
331
  let timeoutMs = capturedConfig.connectionTimeoutMs ?? 15000.0
404
332
 
405
- // Concurrency Safeguard: If the JS async interceptor does not resolve
406
- // within connectionTimeoutMs, throw a timeout error and recover.
407
- sseQueue.asyncAfter(deadline: .now() + (timeoutMs / 1000.0)) { [weak self] in
408
- guard let self = self else { return }
409
- self.sseQueue.async { [weak self] in
410
- guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
411
- if !flag.isCompleted {
412
- flag.isCompleted = true
413
- let error = NSError(domain: "NitroSse", code: -1, userInfo: [NSLocalizedDescriptionKey: "onBeforeRequest interceptor timed out after \(timeoutMs) ms"])
414
- self.handleInterceptorError(error, attemptVersion: attemptVersion)
415
- }
333
+ // Recovers execution state if JS async interceptor fails to settle within connectionTimeoutMs.
334
+ dispatcher.asyncAfter(delay: (timeoutMs / 1000.0)) { [weak self] in
335
+ guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
336
+ if !flag.isCompleted {
337
+ flag.isCompleted = true
338
+ let error = NSError(domain: "NitroSse", code: -1, userInfo: [NSLocalizedDescriptionKey: "onBeforeRequest interceptor timed out after \(timeoutMs) ms"])
339
+ self.handleInterceptorError(error, attemptVersion: attemptVersion)
416
340
  }
417
341
  }
418
342
 
419
343
  do {
420
344
  try interceptor().then { [weak self] promise2 in
421
345
  promise2.then { [weak self] newHeaders in
422
- self?.sseQueue.async { [weak self] in
346
+ self?.dispatcher.async { [weak self] in
423
347
  guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
424
348
  if !flag.isCompleted {
425
349
  flag.isCompleted = true
@@ -428,30 +352,12 @@ class NitroSse: HybridNitroSseSpec {
428
352
  for (k, v) in newHeaders {
429
353
  mergedHeaders[k] = v
430
354
  }
431
- self.config = SseConfig(
432
- url: currentConfig.url,
433
- method: currentConfig.method,
434
- headers: mergedHeaders,
435
- body: currentConfig.body,
436
- backgroundExecution: currentConfig.backgroundExecution,
437
- batchingIntervalMs: currentConfig.batchingIntervalMs,
438
- maxBufferSize: currentConfig.maxBufferSize,
439
- connectionTimeoutMs: currentConfig.connectionTimeoutMs,
440
- readTimeoutMs: currentConfig.readTimeoutMs,
441
- retryIntervalMs: currentConfig.retryIntervalMs,
442
- maxRetryIntervalMs: currentConfig.maxRetryIntervalMs,
443
- jitterFactor: currentConfig.jitterFactor,
444
- maxReconnectAttempts: currentConfig.maxReconnectAttempts,
445
- autoParseJSON: currentConfig.autoParseJSON,
446
- monitorNetwork: currentConfig.monitorNetwork,
447
- onBeforeRequest: currentConfig.onBeforeRequest,
448
- mock: currentConfig.mock
449
- )
355
+ self.config = currentConfig.copyWith(headers: mergedHeaders)
450
356
  self.performEstablishConnection(attemptVersion: attemptVersion)
451
357
  }
452
358
  }
453
359
  }.catch { [weak self] error in
454
- self?.sseQueue.async { [weak self] in
360
+ self?.dispatcher.async { [weak self] in
455
361
  guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
456
362
  if !flag.isCompleted {
457
363
  flag.isCompleted = true
@@ -460,7 +366,7 @@ class NitroSse: HybridNitroSseSpec {
460
366
  }
461
367
  }
462
368
  }.catch { [weak self] error in
463
- self?.sseQueue.async { [weak self] in
369
+ self?.dispatcher.async { [weak self] in
464
370
  guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
465
371
  if !flag.isCompleted {
466
372
  flag.isCompleted = true
@@ -480,25 +386,23 @@ class NitroSse: HybridNitroSseSpec {
480
386
  }
481
387
 
482
388
  private func handleInterceptorError(_ error: Error, attemptVersion: Int) {
483
- dispatchPrecondition(condition: .onQueue(sseQueue))
389
+ dispatcher.assertOnQueue()
484
390
  guard self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
485
391
  let desc = error.localizedDescription
486
- // Note: We use string matching here because react-native-nitro-modules (as of 0.36.1)
487
- // throws a generic std::runtime_error from C++ when the Dispatcher is destroyed.
488
- // It does not provide a specific Exception class (like DispatcherDestroyedException)
489
- // that we can catch, so checking the message is currently the only workaround.
392
+ // react-native-nitro-modules throws a generic std::runtime_error from C++ when the Dispatcher is destroyed.
393
+ // Message inspection is required as no specialized exception type is surfaced to Swift.
490
394
  if desc.contains("Dispatcher has already been destroyed") {
491
395
  print("[NitroSse] JS Dispatcher destroyed. Stopping SSE stream.")
492
396
  self.isDispatcherDestroyed = true
493
397
  self.stopInternal()
494
398
  return
495
399
  }
496
- self.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Interceptor Error: \(error.localizedDescription)", statusCode: -1, retry: nil))
400
+ self.eventBuffer.push(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Interceptor Error: \(error.localizedDescription)", statusCode: -1, retry: nil, state: nil))
497
401
  self.scheduleAutomaticReconnect(isError: true, attemptVersion: attemptVersion)
498
402
  }
499
403
 
500
404
  private func performEstablishConnection(attemptVersion: Int) {
501
- dispatchPrecondition(condition: .onQueue(sseQueue))
405
+ dispatcher.assertOnQueue()
502
406
  guard isRunning, let config = config, let url = URL(string: config.url), attemptVersion == self.connectionAttemptVersion else { return }
503
407
 
504
408
  if let rid = self.requestId {
@@ -506,52 +410,30 @@ class NitroSse: HybridNitroSseSpec {
506
410
  self.requestId = nil
507
411
  }
508
412
 
509
- let sessionConfig = URLSessionConfiguration.default
510
- let readTimeout = (config.readTimeoutMs ?? 300000.0) / 1000.0
511
- sessionConfig.timeoutIntervalForRequest = readTimeout
512
- sessionConfig.timeoutIntervalForResource = readTimeout
513
-
514
-
515
-
516
- let handler = SseHandler(parent: self, attemptVersion: attemptVersion)
517
- var esConfig = EventSource.Config(handler: handler, url: url)
518
- esConfig.urlSessionConfiguration = sessionConfig
519
- esConfig.headers = config.headers ?? [:]
520
-
521
- if let lastId = self.lastProcessedId, !lastId.isEmpty {
522
- esConfig.headers["Last-Event-ID"] = lastId
523
- }
524
-
525
- esConfig.lastEventId = self.lastProcessedId ?? ""
526
- esConfig.method = config.method?.stringValue.uppercased() ?? "GET"
527
- esConfig.body = config.body?.data(using: .utf8)
528
-
529
- let es = EventSource(config: esConfig)
413
+ let es = SseConnectionHandler.createEventSource(
414
+ url: url,
415
+ config: config,
416
+ lastProcessedId: lastProcessedId,
417
+ delegate: self,
418
+ attemptVersion: attemptVersion,
419
+ dispatcher: dispatcher
420
+ )
530
421
  self.eventSource = es
531
- handler.source = es
532
422
 
533
423
  let request = URLRequest(url: url)
534
424
  self.requestId = NitroSseNetworkInspector.reportRequestStart(request, encodedDataLength: 0)
535
-
536
- es.start()
537
425
  }
538
426
 
539
- /**
540
- * Stop the SSE connection and clear any pending reconnect timers.
541
- */
542
- func stop() {
543
- sseQueue.async {
544
- self.connectionAttemptVersion += 1
545
- self.stopInternal()
546
- }
547
- }
427
+ // MARK: - Stop / Reconnect
548
428
 
549
429
  private func stopInternal() {
550
- dispatchPrecondition(condition: .onQueue(sseQueue))
430
+ dispatcher.assertOnQueue()
551
431
  self.isRunning = false
432
+ if !isDispatcherDestroyed && self.currentState != .failed {
433
+ self.updateState(.closed)
434
+ }
552
435
  if isDispatcherDestroyed {
553
- eventBuffer.removeAll()
554
- isFlushPending = false
436
+ eventBuffer.clear()
555
437
  }
556
438
  self.wasRunningBeforeNetworkLoss = false
557
439
  self.wasRunningBeforeHibernation = false
@@ -561,275 +443,193 @@ class NitroSse: HybridNitroSseSpec {
561
443
  NitroSseNetworkInspector.reportResponseEnd(rid, encodedDataLength: Int(self.totalBytesReceived))
562
444
  self.requestId = nil
563
445
  }
564
- self.backoffCounter = 0
565
- self.isFlushPending = false
566
- self.cleanupBackgroundTask()
446
+ self.reconnectStrategy.reset()
447
+ self.lifecycleManager?.cleanupBackgroundTask()
567
448
  }
568
449
 
569
- /**
570
- * Immediately emit any pending buffered events to the JS bridge.
571
- */
572
- func flush() {
573
- sseQueue.async {
574
- self.flushEventsToJs()
575
- }
576
- }
450
+ private func scheduleAutomaticReconnect(isError: Bool, attemptVersion: Int) {
451
+ dispatcher.assertOnQueue()
452
+ eventSource?.stop()
577
453
 
578
- /**
579
- * Restart the SSE connection by stopping and starting again.
580
- */
581
- func restart() {
582
- sseQueue.async {
454
+ if reconnectStrategy.hasReachedMaxAttempts() {
455
+ let maxAttempts = Int(config?.maxReconnectAttempts ?? -1.0)
456
+ print("[NitroSse] Max reconnection attempts reached (\(maxAttempts)). Stopping.")
457
+ self.eventBuffer.push(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Max reconnection attempts reached (\(maxAttempts)).", statusCode: nil, retry: nil, state: nil))
458
+ self.updateState(.failed)
583
459
  self.stopInternal()
584
- self.isRunning = true
585
- self.requestId = nil
586
- self.connectionAttemptVersion += 1
587
- self.establishConnection(attemptVersion: self.connectionAttemptVersion)
460
+ return
588
461
  }
589
- }
590
462
 
591
- /**
592
- * Indicates if the SSE connection is currently active or trying to connect.
593
- */
594
- func isConnected() -> Bool {
595
- return sseQueue.sync {
596
- return isRunning
597
- }
598
- }
599
-
600
- private func extractRetryAfterSeconds(error: Error) -> TimeInterval? {
601
- let nsError = error as NSError
602
- guard let response = nsError.userInfo["response"] as? HTTPURLResponse else { return nil }
603
- guard let retryAfterHeader = response.allHeaderFields["Retry-After"] as? String else { return nil }
604
-
605
- if let seconds = Double(retryAfterHeader) {
606
- return seconds
463
+ let safeDelay = reconnectStrategy.nextDelay(isError: isError)
464
+ self.updateState(.reconnecting)
465
+ eventSource?.stop()
466
+ eventSource = nil
467
+ dispatcher.asyncAfter(delay: safeDelay) { [weak self] in
468
+ guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
469
+ self.establishConnection(attemptVersion: attemptVersion)
607
470
  }
608
-
609
- let rfc1123Formatter = DateFormatter()
610
- rfc1123Formatter.locale = Locale(identifier: "en_US_POSIX")
611
- rfc1123Formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
612
- if let date = rfc1123Formatter.date(from: retryAfterHeader) {
613
- let timeUntilDate = date.timeIntervalSinceNow
614
- return timeUntilDate > 0 ? timeUntilDate : nil
615
- }
616
- return nil
617
471
  }
618
472
 
619
473
  private func scheduleAutomaticReconnectWithFixedDelay(_ delay: TimeInterval, attemptVersion: Int) {
620
- dispatchPrecondition(condition: .onQueue(sseQueue))
474
+ dispatcher.assertOnQueue()
621
475
  eventSource?.stop()
622
476
  eventSource = nil
623
- sseQueue.asyncAfter(deadline: .now() + delay) { [weak self] in
624
- guard let self = self else { return }
625
- self.sseQueue.async {
626
- guard self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
627
- self.establishConnection(attemptVersion: attemptVersion)
628
- }
477
+ self.updateState(.reconnecting)
478
+ dispatcher.asyncAfter(delay: delay) { [weak self] in
479
+ guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
480
+ self.establishConnection(attemptVersion: attemptVersion)
629
481
  }
630
482
  }
631
-
632
- /// Schedules an automatic reconnection attempt using the configured retry interval, exponential backoff, and jitter.
633
- ///
634
- /// If the configured maximum reconnect attempts has been reached, this method emits an error event and stops the connection instead of scheduling a reconnect. Otherwise it increments the reconnect attempt counter, computes a delay (exponential backoff when `isError` is true, with jitter applied and a minimum delay of 1 second), clears the current event source, and schedules `establishConnection(attemptVersion:)` to run after the computed delay only if the client is still running and the provided `attemptVersion` matches the current connection attempt version.
635
- /// - Parameters:
636
- /// - isError: Whether the reconnect is being scheduled in response to an error (affects use of exponential backoff).
637
- /// - attemptVersion: The connection attempt version that must match the current `connectionAttemptVersion` when the scheduled reconnect fires; used to ignore stale or superseded reconnect attempts.
638
- private func scheduleAutomaticReconnect(isError: Bool, attemptVersion: Int) {
639
- dispatchPrecondition(condition: .onQueue(sseQueue))
640
- eventSource?.stop()
483
+ }
641
484
 
642
- let jitterFactor = config?.jitterFactor ?? 0.5
643
- let retryInterval = (config?.retryIntervalMs ?? 1000.0) / 1000.0
644
- let maxRetryInterval = (config?.maxRetryIntervalMs ?? 30000.0) / 1000.0
485
+ // MARK: - SseConnectionDelegate
645
486
 
646
- var delay: TimeInterval = retryInterval
647
-
648
- let maxAttempts = Int(config?.maxReconnectAttempts ?? -1.0)
649
- if maxAttempts != -1 && currentReconnectAttempts >= maxAttempts {
650
- print("[NitroSse] Max reconnection attempts reached (\(maxAttempts)). Stopping.")
651
- self.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Max reconnection attempts reached (\(maxAttempts)).", statusCode: nil, retry: nil))
652
- self.stopInternal()
653
- return
487
+ extension NitroSse: SseConnectionDelegate {
488
+ func connectionDidOpen(attemptVersion: Int) {
489
+ dispatcher.async { [weak self] in
490
+ guard let self = self, attemptVersion == self.connectionAttemptVersion else { return }
491
+ self.reconnectStrategy.reset()
492
+ self.consecutiveAuthErrors = 0
493
+ self.updateState(.open)
494
+
495
+ NitroSseNetworkInspector.reportResponseStart(
496
+ self.requestId,
497
+ url: self.config?.url,
498
+ response: nil,
499
+ statusCode: 200,
500
+ headers: self.config?.headers ?? [:]
501
+ )
502
+
503
+ self.eventBuffer.push(SseEvent(type: .open, data: nil, parsedData: nil, id: nil, event: nil, message: nil, statusCode: 200, retry: nil, state: nil))
654
504
  }
655
-
656
- currentReconnectAttempts += 1
657
-
658
- if isError {
659
- let exponent = Double(backoffCounter)
660
- let base = min(retryInterval * pow(2.0, exponent), maxRetryInterval)
661
- backoffCounter += 1
662
- delay = base * (1.0 - jitterFactor + Double.random(in: 0...(2 * jitterFactor)))
663
- } else {
664
- delay = retryInterval * (1.0 - jitterFactor + Double.random(in: 0...(2 * jitterFactor)))
505
+ }
506
+
507
+ func connectionDidClose(attemptVersion: Int) {
508
+ dispatcher.async { [weak self] in
509
+ guard let self = self, attemptVersion == self.connectionAttemptVersion else { return }
510
+ if let rid = self.requestId {
511
+ NitroSseNetworkInspector.reportResponseEnd(rid, encodedDataLength: Int(self.totalBytesReceived))
512
+ self.requestId = nil
513
+ }
514
+ if self.isRunning {
515
+ self.scheduleAutomaticReconnect(isError: false, attemptVersion: attemptVersion)
516
+ }
665
517
  }
666
-
667
- let safeDelay = max(delay, 1.0)
668
- eventSource?.stop()
669
- eventSource = nil
670
- sseQueue.asyncAfter(deadline: .now() + safeDelay) { [weak self] in
671
- guard let self = self else { return }
672
- self.sseQueue.async {
673
- guard self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
674
- self.establishConnection(attemptVersion: attemptVersion)
518
+ }
519
+
520
+ func connectionDidReceiveMessage(eventType: String, data: String, lastEventId: String, attemptVersion: Int) {
521
+ dispatcher.async { [weak self] in
522
+ guard let self = self, attemptVersion == self.connectionAttemptVersion else { return }
523
+ let encodedDataSize = Double(data.utf8.count)
524
+ let metadataSize = Double(eventType.utf8.count) + Double(lastEventId.utf8.count)
525
+ self.totalBytesReceived += encodedDataSize + metadataSize
526
+
527
+ if !lastEventId.isEmpty {
528
+ self.lastProcessedId = lastEventId
675
529
  }
530
+
531
+ let parsedData = (self.config?.autoParseJSON == true) ? SseEventBuffer.parseJsonToAnyMap(data) : nil
532
+
533
+ self.eventBuffer.push(SseEvent(type: .message, data: data, parsedData: parsedData, id: lastEventId, event: eventType, message: nil, statusCode: 200, retry: nil, state: nil))
676
534
  }
677
535
  }
678
536
 
679
- private class SseHandler: EventHandler {
680
- weak var parent: NitroSse?
681
- weak var source: EventSource?
682
- let attemptVersion: Int
683
-
684
- init(parent: NitroSse, attemptVersion: Int) {
685
- self.parent = parent
686
- self.attemptVersion = attemptVersion
537
+ func connectionDidReceiveComment(_ comment: String, attemptVersion: Int) {
538
+ dispatcher.async { [weak self] in
539
+ guard let self = self, attemptVersion == self.connectionAttemptVersion else { return }
540
+ self.totalBytesReceived += Double(comment.utf8.count)
541
+ self.eventBuffer.push(SseEvent(type: .heartbeat, data: nil, parsedData: nil, id: nil, event: nil, message: comment, statusCode: nil, retry: nil, state: nil))
687
542
  }
688
-
689
- /// Handle a successful SSE connection open for this handler.
690
- ///
691
- /// If this handler corresponds to the active connection and its attempt version matches the parent's current connectionAttemptVersion, resets `backoffCounter`, `currentReconnectAttempts`, and `consecutiveAuthErrors`, and enqueues an `.open` `SseEvent` with status code 200.
692
- func onOpened() {
693
- guard let parent = self.parent, source === parent.eventSource else { return }
694
- parent.sseQueue.async { [weak parent] in
695
- guard let parent = parent, self.attemptVersion == parent.connectionAttemptVersion else { return }
696
- parent.backoffCounter = 0
697
- parent.currentReconnectAttempts = 0
698
- parent.consecutiveAuthErrors = 0
699
-
543
+ }
544
+
545
+ func connectionDidFail(error: Error, attemptVersion: Int) {
546
+ dispatcher.async { [weak self] in
547
+ guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
548
+
549
+ let nsError = error as NSError
550
+ var statusCode = nsError.code
551
+ if let responseError = error as? UnsuccessfulResponseError {
552
+ statusCode = responseError.responseCode
553
+ }
554
+
555
+ self.reconnectCount += 1
556
+ self.lastErrorTime = Date().timeIntervalSince1970 * 1000
557
+ self.lastErrorCode = "\(nsError.domain)(\(statusCode))"
558
+
559
+ if statusCode >= 100 && statusCode < 600 {
700
560
  NitroSseNetworkInspector.reportResponseStart(
701
- parent.requestId,
702
- url: parent.config?.url,
561
+ self.requestId,
562
+ url: self.config?.url,
703
563
  response: nil,
704
- statusCode: 200,
705
- headers: parent.config?.headers ?? [:]
564
+ statusCode: statusCode,
565
+ headers: [:]
706
566
  )
707
-
708
- parent.pushEventToBuffer(SseEvent(type: .open, data: nil, parsedData: nil, id: nil, event: nil, message: nil, statusCode: 200, retry: nil))
709
- }
710
- }
711
-
712
- func onClosed() {
713
- guard let parent = self.parent, source === parent.eventSource else { return }
714
- parent.sseQueue.async { [weak parent] in
715
- guard let parent = parent, self.attemptVersion == parent.connectionAttemptVersion else { return }
716
- if let rid = parent.requestId {
717
- NitroSseNetworkInspector.reportResponseEnd(rid, encodedDataLength: Int(parent.totalBytesReceived))
718
- parent.requestId = nil
719
- }
720
- if parent.isRunning {
721
- parent.scheduleAutomaticReconnect(isError: false, attemptVersion: self.attemptVersion)
722
- }
723
567
  }
724
- }
725
-
726
- func onMessage(eventType: String, messageEvent: MessageEvent) {
727
- guard let parent = self.parent, source === parent.eventSource else { return }
728
- parent.sseQueue.async { [weak parent] in
729
- guard let parent = parent, self.attemptVersion == parent.connectionAttemptVersion else { return }
730
- let encodedDataSize = Double(messageEvent.data.utf8.count)
731
- let metadataSize = Double(eventType.utf8.count) + Double((messageEvent.lastEventId).utf8.count)
732
- parent.totalBytesReceived += encodedDataSize + metadataSize
733
-
734
- if !messageEvent.lastEventId.isEmpty {
735
- parent.lastProcessedId = messageEvent.lastEventId
736
- }
737
-
738
- let parsedData = (parent.config?.autoParseJSON == true) ? parent.parseJsonToAnyMap(messageEvent.data) : nil
739
-
740
- parent.pushEventToBuffer(SseEvent(type: .message, data: messageEvent.data, parsedData: parsedData, id: messageEvent.lastEventId, event: eventType, message: nil, statusCode: 200, retry: nil))
741
- }
742
- }
743
-
744
- // LDSwiftEventSource natively parses SSE stream comments (lines beginning with ':')
745
- // and triggers onComment. Unlike Android (which requires manual byte scanning),
746
- // on iOS we simply convert comment packets directly into heartbeat events.
747
- func onComment(comment: String) {
748
- guard let parent = self.parent, source === parent.eventSource else { return }
749
- parent.sseQueue.async { [weak parent] in
750
- guard let parent = parent, self.attemptVersion == parent.connectionAttemptVersion else { return }
751
- parent.totalBytesReceived += Double(comment.utf8.count)
752
- parent.pushEventToBuffer(SseEvent(type: .heartbeat, data: nil, parsedData: nil, id: nil, event: nil, message: comment, statusCode: nil, retry: nil))
568
+ NitroSseNetworkInspector.reportRequestFailed(self.requestId, cancelled: false)
569
+ self.requestId = nil
570
+
571
+ // HTTP 204 No Content indicates the server closed the stream intentionally without error.
572
+ if statusCode == 204 {
573
+ self.eventBuffer.push(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "No Content (204). Stopping.", statusCode: 204, retry: nil, state: nil))
574
+ self.updateState(.failed)
575
+ self.stopInternal()
576
+ return
753
577
  }
754
- }
755
-
756
- func onError(error: Error) {
757
- guard let parent = self.parent, source === parent.eventSource else { return }
758
- parent.sseQueue.async { [weak parent] in
759
- guard let parent = parent, parent.isRunning, self.attemptVersion == parent.connectionAttemptVersion else { return }
760
-
761
- let nsError = error as NSError
762
- var statusCode = nsError.code
763
- if let responseError = error as? UnsuccessfulResponseError {
764
- statusCode = responseError.responseCode
765
- }
766
-
767
- parent.reconnectCount += 1
768
- parent.lastErrorTime = Date().timeIntervalSince1970 * 1000
769
- parent.lastErrorCode = "\(nsError.domain)(\(statusCode))"
770
-
771
- if statusCode >= 100 && statusCode < 600 {
772
- NitroSseNetworkInspector.reportResponseStart(
773
- parent.requestId,
774
- url: parent.config?.url,
775
- response: nil,
776
- statusCode: statusCode,
777
- headers: [:]
778
- )
779
- }
780
- NitroSseNetworkInspector.reportRequestFailed(parent.requestId, cancelled: false)
781
- parent.requestId = nil
782
-
783
- if statusCode == 204 {
784
- parent.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "No Content (204). Stopping.", statusCode: 204, retry: nil))
785
- parent.stopInternal()
786
- return
787
- }
788
-
789
- if statusCode == 401 || statusCode == 403 {
790
- if parent.config?.onBeforeRequest == nil {
791
- parent.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Auth Error (\(statusCode)) - No interceptor provided. Stopping.", statusCode: Double(statusCode), retry: nil))
792
- parent.stopInternal()
793
- return
794
- }
795
578
 
796
- parent.consecutiveAuthErrors += 1
797
- if parent.consecutiveAuthErrors >= parent.maxAuthRetries {
798
- parent.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Auth Error (\(statusCode)) - Retry limit reached (\(parent.maxAuthRetries)). Stopping.", statusCode: Double(statusCode), retry: nil))
799
- parent.stopInternal()
800
- return
801
- }
802
-
803
- parent.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Auth Error (\(statusCode)) - Retry \(parent.consecutiveAuthErrors)/\(parent.maxAuthRetries). Refreshing token...", statusCode: Double(statusCode), retry: nil))
804
- parent.scheduleAutomaticReconnect(isError: true, attemptVersion: self.attemptVersion)
579
+ // HTTP 401/403 Auth errors trigger token refresh via onBeforeRequest interceptor up to maxAuthRetries.
580
+ if statusCode == 401 || statusCode == 403 {
581
+ if self.config?.onBeforeRequest == nil {
582
+ self.eventBuffer.push(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Auth Error (\(statusCode)) - No interceptor provided. Stopping.", statusCode: Double(statusCode), retry: nil, state: nil))
583
+ self.updateState(.failed)
584
+ self.stopInternal()
805
585
  return
806
586
  }
807
587
 
808
- let isFatal = (statusCode == 400)
809
- if isFatal {
810
- parent.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Fatal Error (\(statusCode)). Stopping.", statusCode: Double(statusCode), retry: nil))
811
- parent.stopInternal()
588
+ self.consecutiveAuthErrors += 1
589
+ if self.consecutiveAuthErrors >= self.maxAuthRetries {
590
+ self.eventBuffer.push(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Auth Error (\(statusCode)) - Retry limit reached (\(self.maxAuthRetries)). Stopping.", statusCode: Double(statusCode), retry: nil, state: nil))
591
+ self.updateState(.failed)
592
+ self.stopInternal()
812
593
  return
813
594
  }
595
+
596
+ self.eventBuffer.push(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Auth Error (\(statusCode)) - Retry \(self.consecutiveAuthErrors)/\(self.maxAuthRetries). Refreshing token...", statusCode: Double(statusCode), retry: nil, state: nil))
597
+ self.scheduleAutomaticReconnect(isError: true, attemptVersion: attemptVersion)
598
+ return
599
+ }
814
600
 
815
- let retryAfterSeconds = parent.extractRetryAfterSeconds(error: error)
816
- if (statusCode == 429 || statusCode == 503), let retryAfter = retryAfterSeconds {
817
- let jitter = Double.random(in: 0.5...1.5)
818
- let totalDelay = retryAfter + jitter
819
- parent.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Retry-After received: \(Int(totalDelay))s", statusCode: Double(statusCode), retry: totalDelay * 1000.0))
820
- parent.scheduleAutomaticReconnectWithFixedDelay(totalDelay, attemptVersion: self.attemptVersion)
821
- return
822
- }
601
+ let isFatal = (statusCode == 400)
602
+ if isFatal {
603
+ self.eventBuffer.push(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Fatal Error (\(statusCode)). Stopping.", statusCode: Double(statusCode), retry: nil, state: nil))
604
+ self.updateState(.failed)
605
+ self.stopInternal()
606
+ return
607
+ }
823
608
 
824
- if statusCode == 429 {
825
- parent.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Rate Limited (429) without Retry-After. Stopping.", statusCode: 429, retry: nil))
826
- parent.stopInternal()
827
- return
828
- }
609
+ // HTTP 429 Rate Limit / 503 Service Unavailable: Honor server Retry-After delay with randomized jitter to prevent thundering herd.
610
+ let retryAfterSeconds = SseReconnectStrategy.extractRetryAfterSeconds(from: error)
611
+ if (statusCode == 429 || statusCode == 503), let retryAfter = retryAfterSeconds {
612
+ let jitter = Double.random(in: 0.5...1.5)
613
+ let totalDelay = retryAfter + jitter
614
+ self.eventBuffer.push(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Retry-After received: \(Int(totalDelay))s", statusCode: Double(statusCode), retry: totalDelay * 1000.0, state: nil))
615
+ self.scheduleAutomaticReconnectWithFixedDelay(totalDelay, attemptVersion: attemptVersion)
616
+ return
617
+ }
829
618
 
830
- parent.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: error.localizedDescription, statusCode: Double(statusCode), retry: nil))
831
- parent.scheduleAutomaticReconnect(isError: true, attemptVersion: self.attemptVersion)
619
+ if statusCode == 429 {
620
+ self.eventBuffer.push(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Rate Limited (429) without Retry-After. Stopping.", statusCode: 429, retry: nil, state: nil))
621
+ self.updateState(.failed)
622
+ self.stopInternal()
623
+ return
832
624
  }
625
+
626
+ let isTimeout = (nsError.domain == NSURLErrorDomain && nsError.code == NSURLErrorTimedOut) || statusCode == -1001
627
+ if isTimeout {
628
+ self.updateState(.stale)
629
+ }
630
+
631
+ self.eventBuffer.push(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: error.localizedDescription, statusCode: Double(statusCode), retry: nil, state: nil))
632
+ self.scheduleAutomaticReconnect(isError: true, attemptVersion: attemptVersion)
833
633
  }
834
634
  }
835
635
  }