react-native-nitro-sse 2.3.2 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +78 -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 +309 -656
  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 +114 -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 +102 -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 +87 -0
  14. package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +80 -0
  15. package/ios/NitroSse.swift +433 -637
  16. package/ios/SseConfig+CopyWith.swift +46 -0
  17. package/ios/SseConnectionHandler.swift +114 -0
  18. package/ios/SseDispatchQueueDispatcher.swift +38 -0
  19. package/ios/SseDispatcher.swift +18 -0
  20. package/ios/SseEventBuffer.swift +79 -0
  21. package/ios/SseLifecycleManager.swift +118 -0
  22. package/ios/SseNetworkMonitor.swift +84 -0
  23. package/ios/SseReconnectStrategy.swift +99 -0
  24. package/lib/module/NitroSseClient.js +38 -3
  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 +4 -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 +42 -2
  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()
36
24
  }
25
+
26
+ internal init(dispatcher: SseDispatcher) {
27
+ self.dispatcher = dispatcher
28
+ super.init()
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?
74
59
 
60
+ // MARK: - Lifecycle
75
61
 
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
- */
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
+ }
75
+
76
+ // MARK: - HybridNitroSseSpec
77
+
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,138 @@ 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)
137
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
+ guard self.config != nil else { return }
202
+ self.stopInternal(emitClosed: false)
203
+ self.isRunning = true
204
+ self.requestId = nil
205
+ self.connectionAttemptVersion += 1
206
+ self.updateState(.reconnecting)
207
+ self.establishConnection(attemptVersion: self.connectionAttemptVersion)
208
+ }
209
+ }
210
+
211
+ /// Indicates whether the client is currently running or reconnecting.
212
+ func isConnected() -> Bool {
213
+ return dispatcher.sync {
214
+ return isRunning
215
+ }
216
+ }
217
+
218
+ // MARK: - Network Monitoring
219
+
220
+ private func startNetworkMonitoring() {
221
+ dispatcher.assertOnQueue()
222
+ guard networkMonitor == nil else { return }
138
223
 
139
- print("[NitroSse] Network path changed: status=\(path.status), interface=\(String(describing: interfaceType))")
224
+ let monitor = SseNetworkMonitor(dispatcher: dispatcher) { [weak self] isSatisfied, interfaceChanged, interfaceType in
225
+ self?.handleNetworkChange(isSatisfied: isSatisfied, interfaceChanged: interfaceChanged, interfaceType: interfaceType)
226
+ }
227
+ self.networkMonitor = monitor
228
+ monitor.start()
229
+ }
230
+
231
+ private func stopNetworkMonitoring() {
232
+ dispatcher.assertOnQueue()
233
+ networkMonitor?.stop()
234
+ networkMonitor = nil
235
+ }
236
+
237
+ private func handleNetworkChange(isSatisfied: Bool, interfaceChanged: Bool, interfaceType: NWInterface.InterfaceType?) {
238
+ dispatcher.assertOnQueue()
140
239
 
141
240
  if isSatisfied {
142
241
  if wasRunningBeforeNetworkLoss {
143
242
  print("[NitroSse] Network restored. Resuming stream.")
144
243
  wasRunningBeforeNetworkLoss = false
145
- if self.isAppInBackground && self.config?.backgroundExecution != true {
244
+ if lifecycleManager?.isAppInBackground == true && self.config?.backgroundExecution != true {
146
245
  self.wasRunningBeforeHibernation = true
147
246
  } else if isRunning {
148
247
  self.restart()
@@ -150,11 +249,8 @@ class NitroSse: HybridNitroSseSpec {
150
249
  try? self.start()
151
250
  }
152
251
  } 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.")
252
+ if interfaceChanged {
253
+ print("[NitroSse] Network interface changed. Restarting stream.")
158
254
  self.restart()
159
255
  }
160
256
  }
@@ -162,64 +258,49 @@ class NitroSse: HybridNitroSseSpec {
162
258
  if isRunning {
163
259
  print("[NitroSse] Network lost. Hibernating.")
164
260
  wasRunningBeforeNetworkLoss = true
261
+ self.updateState(.paused)
165
262
  self.hibernateConnection()
166
263
  }
167
264
  }
265
+ }
266
+
267
+ // MARK: - App Lifecycle Handling
268
+
269
+ private func handleAppDidEnterBackground() {
270
+ dispatcher.assertOnQueue()
271
+ guard self.isRunning, let config = self.config else { return }
168
272
 
169
- if isSatisfied {
170
- self.lastPathInterface = interfaceType
273
+ if config.backgroundExecution == true {
274
+ print("[NitroSse] App backgrounded. backgroundExecution is true, keeping connection alive.")
275
+ self.lifecycleManager?.beginBackgroundKeepAlive { [weak self] in
276
+ print("[NitroSse] Background task expired. Hibernating now.")
277
+ self?.updateState(.paused)
278
+ self?.hibernateConnection()
279
+ }
280
+ return
171
281
  }
282
+
283
+ self.updateState(.paused)
284
+ self.hibernateConnection()
172
285
  }
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()
286
+
287
+ private func handleAppWillEnterForeground() {
288
+ dispatcher.assertOnQueue()
289
+ if self.wasRunningBeforeHibernation {
290
+ print("[NitroSse] App foregrounded. Resuming stream.")
291
+ self.wasRunningBeforeHibernation = false
292
+ try? self.start()
212
293
  }
213
294
  }
214
295
 
215
296
  private func hibernateConnection() {
216
- dispatchPrecondition(condition: .onQueue(sseQueue))
297
+ dispatcher.assertOnQueue()
217
298
  guard self.isRunning else { return }
218
299
 
219
300
  self.wasRunningBeforeHibernation = true
220
301
  print("[NitroSse] Hibernating NitroSse connection.")
221
302
 
222
- self.flushEventsToJs()
303
+ self.eventBuffer.flush()
223
304
 
224
305
  self.eventSource?.stop()
225
306
  self.eventSource = nil
@@ -229,238 +310,54 @@ class NitroSse: HybridNitroSseSpec {
229
310
  }
230
311
  self.isRunning = false
231
312
 
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
303
- }
304
-
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
- }
313
+ self.lifecycleManager?.cleanupBackgroundTask()
342
314
  }
343
315
 
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
- }
316
+ // MARK: - Connection
357
317
 
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.
318
+ /// Initiates an SSE connection attempt, invoking `onBeforeRequest` interceptor if configured.
319
+ /// Ignores stale calls where `attemptVersion` no longer matches `self.connectionAttemptVersion`.
392
320
  private func establishConnection(attemptVersion: Int) {
393
- dispatchPrecondition(condition: .onQueue(sseQueue))
321
+ dispatcher.assertOnQueue()
394
322
  guard isRunning, let config = config, attemptVersion == self.connectionAttemptVersion else { return }
395
323
 
396
324
  if let interceptor = config.onBeforeRequest {
397
325
 
398
326
  let capturedConfig = config
327
+ // Reference-type completion flag to prevent races between interceptor promise resolution and connection timeout.
399
328
  class CompletionFlag {
400
329
  var isCompleted = false
401
330
  }
402
331
  let flag = CompletionFlag()
403
332
  let timeoutMs = capturedConfig.connectionTimeoutMs ?? 15000.0
404
333
 
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
- }
334
+ // Recovers execution state if JS async interceptor fails to settle within connectionTimeoutMs.
335
+ dispatcher.asyncAfter(delay: (timeoutMs / 1000.0)) { [weak self] in
336
+ guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
337
+ if !flag.isCompleted {
338
+ flag.isCompleted = true
339
+ let error = NSError(domain: "NitroSse", code: -1, userInfo: [NSLocalizedDescriptionKey: "onBeforeRequest interceptor timed out after \(timeoutMs) ms"])
340
+ self.handleInterceptorError(error, attemptVersion: attemptVersion)
416
341
  }
417
342
  }
418
343
 
419
- do {
420
- try interceptor().then { [weak self] promise2 in
421
- promise2.then { [weak self] newHeaders in
422
- self?.sseQueue.async { [weak self] in
423
- guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
424
- if !flag.isCompleted {
425
- flag.isCompleted = true
426
- let currentConfig = self.config ?? capturedConfig
427
- var mergedHeaders = currentConfig.headers ?? [:]
428
- for (k, v) in newHeaders {
429
- mergedHeaders[k] = v
430
- }
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
- )
450
- self.performEstablishConnection(attemptVersion: attemptVersion)
451
- }
452
- }
453
- }.catch { [weak self] error in
454
- self?.sseQueue.async { [weak self] in
455
- guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
456
- if !flag.isCompleted {
457
- flag.isCompleted = true
458
- self.handleInterceptorError(error, attemptVersion: attemptVersion)
344
+ interceptor().then { [weak self] promise2 in
345
+ promise2.then { [weak self] newHeaders in
346
+ self?.dispatcher.async { [weak self] in
347
+ guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
348
+ if !flag.isCompleted {
349
+ flag.isCompleted = true
350
+ let currentConfig = self.config ?? capturedConfig
351
+ var mergedHeaders = currentConfig.headers ?? [:]
352
+ for (k, v) in newHeaders {
353
+ mergedHeaders[k] = v
459
354
  }
355
+ self.config = currentConfig.copyWith(headers: mergedHeaders)
356
+ self.performEstablishConnection(attemptVersion: attemptVersion)
460
357
  }
461
358
  }
462
359
  }.catch { [weak self] error in
463
- self?.sseQueue.async { [weak self] in
360
+ self?.dispatcher.async { [weak self] in
464
361
  guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
465
362
  if !flag.isCompleted {
466
363
  flag.isCompleted = true
@@ -468,10 +365,13 @@ class NitroSse: HybridNitroSseSpec {
468
365
  }
469
366
  }
470
367
  }
471
- } catch {
472
- if !flag.isCompleted {
473
- flag.isCompleted = true
474
- self.handleInterceptorError(error, attemptVersion: attemptVersion)
368
+ }.catch { [weak self] error in
369
+ self?.dispatcher.async { [weak self] in
370
+ guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
371
+ if !flag.isCompleted {
372
+ flag.isCompleted = true
373
+ self.handleInterceptorError(error, attemptVersion: attemptVersion)
374
+ }
475
375
  }
476
376
  }
477
377
  } else {
@@ -480,78 +380,56 @@ class NitroSse: HybridNitroSseSpec {
480
380
  }
481
381
 
482
382
  private func handleInterceptorError(_ error: Error, attemptVersion: Int) {
483
- dispatchPrecondition(condition: .onQueue(sseQueue))
383
+ dispatcher.assertOnQueue()
484
384
  guard self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
485
385
  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.
386
+ // react-native-nitro-modules throws a generic std::runtime_error from C++ when the Dispatcher is destroyed.
387
+ // Message inspection is required as no specialized exception type is surfaced to Swift.
490
388
  if desc.contains("Dispatcher has already been destroyed") {
491
389
  print("[NitroSse] JS Dispatcher destroyed. Stopping SSE stream.")
492
390
  self.isDispatcherDestroyed = true
493
391
  self.stopInternal()
494
392
  return
495
393
  }
496
- self.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Interceptor Error: \(error.localizedDescription)", statusCode: -1, retry: nil))
394
+ 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
395
  self.scheduleAutomaticReconnect(isError: true, attemptVersion: attemptVersion)
498
396
  }
499
397
 
500
398
  private func performEstablishConnection(attemptVersion: Int) {
501
- dispatchPrecondition(condition: .onQueue(sseQueue))
399
+ dispatcher.assertOnQueue()
502
400
  guard isRunning, let config = config, let url = URL(string: config.url), attemptVersion == self.connectionAttemptVersion else { return }
503
401
 
402
+ self.updateState(.connecting)
403
+
504
404
  if let rid = self.requestId {
505
405
  NitroSseNetworkInspector.reportResponseEnd(rid, encodedDataLength: Int(self.totalBytesReceived))
506
406
  self.requestId = nil
507
407
  }
508
408
 
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)
409
+ let es = SseConnectionHandler.createEventSource(
410
+ url: url,
411
+ config: config,
412
+ lastProcessedId: lastProcessedId,
413
+ delegate: self,
414
+ attemptVersion: attemptVersion,
415
+ dispatcher: dispatcher
416
+ )
530
417
  self.eventSource = es
531
- handler.source = es
532
418
 
533
419
  let request = URLRequest(url: url)
534
420
  self.requestId = NitroSseNetworkInspector.reportRequestStart(request, encodedDataLength: 0)
535
-
536
- es.start()
537
421
  }
538
422
 
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
- }
423
+ // MARK: - Stop / Reconnect
548
424
 
549
- private func stopInternal() {
550
- dispatchPrecondition(condition: .onQueue(sseQueue))
425
+ private func stopInternal(emitClosed: Bool = true) {
426
+ dispatcher.assertOnQueue()
551
427
  self.isRunning = false
428
+ if emitClosed && !isDispatcherDestroyed && self.currentState != .failed {
429
+ self.updateState(.closed)
430
+ }
552
431
  if isDispatcherDestroyed {
553
- eventBuffer.removeAll()
554
- isFlushPending = false
432
+ eventBuffer.clear()
555
433
  }
556
434
  self.wasRunningBeforeNetworkLoss = false
557
435
  self.wasRunningBeforeHibernation = false
@@ -561,275 +439,193 @@ class NitroSse: HybridNitroSseSpec {
561
439
  NitroSseNetworkInspector.reportResponseEnd(rid, encodedDataLength: Int(self.totalBytesReceived))
562
440
  self.requestId = nil
563
441
  }
564
- self.backoffCounter = 0
565
- self.isFlushPending = false
566
- self.cleanupBackgroundTask()
442
+ self.reconnectStrategy.reset()
443
+ self.lifecycleManager?.cleanupBackgroundTask()
567
444
  }
568
445
 
569
- /**
570
- * Immediately emit any pending buffered events to the JS bridge.
571
- */
572
- func flush() {
573
- sseQueue.async {
574
- self.flushEventsToJs()
575
- }
576
- }
446
+ private func scheduleAutomaticReconnect(isError: Bool, attemptVersion: Int) {
447
+ dispatcher.assertOnQueue()
448
+ eventSource?.stop()
577
449
 
578
- /**
579
- * Restart the SSE connection by stopping and starting again.
580
- */
581
- func restart() {
582
- sseQueue.async {
450
+ if reconnectStrategy.hasReachedMaxAttempts() {
451
+ let maxAttempts = Int(config?.maxReconnectAttempts ?? -1.0)
452
+ print("[NitroSse] Max reconnection attempts reached (\(maxAttempts)). Stopping.")
453
+ 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))
454
+ self.updateState(.failed)
583
455
  self.stopInternal()
584
- self.isRunning = true
585
- self.requestId = nil
586
- self.connectionAttemptVersion += 1
587
- self.establishConnection(attemptVersion: self.connectionAttemptVersion)
456
+ return
588
457
  }
589
- }
590
458
 
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
459
+ let safeDelay = reconnectStrategy.nextDelay(isError: isError)
460
+ self.updateState(.reconnecting)
461
+ eventSource?.stop()
462
+ eventSource = nil
463
+ dispatcher.asyncAfter(delay: safeDelay) { [weak self] in
464
+ guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
465
+ self.establishConnection(attemptVersion: attemptVersion)
607
466
  }
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
467
  }
618
468
 
619
469
  private func scheduleAutomaticReconnectWithFixedDelay(_ delay: TimeInterval, attemptVersion: Int) {
620
- dispatchPrecondition(condition: .onQueue(sseQueue))
470
+ dispatcher.assertOnQueue()
621
471
  eventSource?.stop()
622
472
  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
- }
473
+ self.updateState(.reconnecting)
474
+ dispatcher.asyncAfter(delay: delay) { [weak self] in
475
+ guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
476
+ self.establishConnection(attemptVersion: attemptVersion)
629
477
  }
630
478
  }
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()
479
+ }
641
480
 
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
481
+ // MARK: - SseConnectionDelegate
645
482
 
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
483
+ extension NitroSse: SseConnectionDelegate {
484
+ func connectionDidOpen(attemptVersion: Int) {
485
+ dispatcher.async { [weak self] in
486
+ guard let self = self, attemptVersion == self.connectionAttemptVersion else { return }
487
+ self.reconnectStrategy.reset()
488
+ self.consecutiveAuthErrors = 0
489
+ self.updateState(.open)
490
+
491
+ NitroSseNetworkInspector.reportResponseStart(
492
+ self.requestId,
493
+ url: self.config?.url,
494
+ response: nil,
495
+ statusCode: 200,
496
+ headers: self.config?.headers ?? [:]
497
+ )
498
+
499
+ self.eventBuffer.push(SseEvent(type: .open, data: nil, parsedData: nil, id: nil, event: nil, message: nil, statusCode: 200, retry: nil, state: nil))
654
500
  }
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)))
501
+ }
502
+
503
+ func connectionDidClose(attemptVersion: Int) {
504
+ dispatcher.async { [weak self] in
505
+ guard let self = self, attemptVersion == self.connectionAttemptVersion else { return }
506
+ if let rid = self.requestId {
507
+ NitroSseNetworkInspector.reportResponseEnd(rid, encodedDataLength: Int(self.totalBytesReceived))
508
+ self.requestId = nil
509
+ }
510
+ if self.isRunning {
511
+ self.scheduleAutomaticReconnect(isError: false, attemptVersion: attemptVersion)
512
+ }
665
513
  }
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)
514
+ }
515
+
516
+ func connectionDidReceiveMessage(eventType: String, data: String, lastEventId: String, attemptVersion: Int) {
517
+ dispatcher.async { [weak self] in
518
+ guard let self = self, attemptVersion == self.connectionAttemptVersion else { return }
519
+ let encodedDataSize = Double(data.utf8.count)
520
+ let metadataSize = Double(eventType.utf8.count) + Double(lastEventId.utf8.count)
521
+ self.totalBytesReceived += encodedDataSize + metadataSize
522
+
523
+ if !lastEventId.isEmpty {
524
+ self.lastProcessedId = lastEventId
675
525
  }
526
+
527
+ let parsedData = (self.config?.autoParseJSON == true) ? SseEventBuffer.parseJsonToAnyMap(data) : nil
528
+
529
+ self.eventBuffer.push(SseEvent(type: .message, data: data, parsedData: parsedData, id: lastEventId, event: eventType, message: nil, statusCode: 200, retry: nil, state: nil))
676
530
  }
677
531
  }
678
532
 
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
533
+ func connectionDidReceiveComment(_ comment: String, attemptVersion: Int) {
534
+ dispatcher.async { [weak self] in
535
+ guard let self = self, attemptVersion == self.connectionAttemptVersion else { return }
536
+ self.totalBytesReceived += Double(comment.utf8.count)
537
+ self.eventBuffer.push(SseEvent(type: .heartbeat, data: nil, parsedData: nil, id: nil, event: nil, message: comment, statusCode: nil, retry: nil, state: nil))
687
538
  }
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
-
539
+ }
540
+
541
+ func connectionDidFail(error: Error, attemptVersion: Int) {
542
+ dispatcher.async { [weak self] in
543
+ guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
544
+
545
+ let nsError = error as NSError
546
+ var statusCode = nsError.code
547
+ if let responseError = error as? UnsuccessfulResponseError {
548
+ statusCode = responseError.responseCode
549
+ }
550
+
551
+ self.reconnectCount += 1
552
+ self.lastErrorTime = Date().timeIntervalSince1970 * 1000
553
+ self.lastErrorCode = "\(nsError.domain)(\(statusCode))"
554
+
555
+ if statusCode >= 100 && statusCode < 600 {
700
556
  NitroSseNetworkInspector.reportResponseStart(
701
- parent.requestId,
702
- url: parent.config?.url,
557
+ self.requestId,
558
+ url: self.config?.url,
703
559
  response: nil,
704
- statusCode: 200,
705
- headers: parent.config?.headers ?? [:]
560
+ statusCode: statusCode,
561
+ headers: [:]
706
562
  )
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
563
  }
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))
564
+ NitroSseNetworkInspector.reportRequestFailed(self.requestId, cancelled: false)
565
+ self.requestId = nil
566
+
567
+ // HTTP 204 No Content indicates the server closed the stream intentionally without error.
568
+ if statusCode == 204 {
569
+ 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))
570
+ self.updateState(.failed)
571
+ self.stopInternal()
572
+ return
753
573
  }
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
574
 
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)
575
+ // HTTP 401/403 Auth errors trigger token refresh via onBeforeRequest interceptor up to maxAuthRetries.
576
+ if statusCode == 401 || statusCode == 403 {
577
+ if self.config?.onBeforeRequest == nil {
578
+ 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))
579
+ self.updateState(.failed)
580
+ self.stopInternal()
805
581
  return
806
582
  }
807
583
 
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()
584
+ self.consecutiveAuthErrors += 1
585
+ if self.consecutiveAuthErrors >= self.maxAuthRetries {
586
+ 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))
587
+ self.updateState(.failed)
588
+ self.stopInternal()
812
589
  return
813
590
  }
591
+
592
+ 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))
593
+ self.scheduleAutomaticReconnect(isError: true, attemptVersion: attemptVersion)
594
+ return
595
+ }
814
596
 
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
- }
597
+ let isFatal = (statusCode == 400)
598
+ if isFatal {
599
+ 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))
600
+ self.updateState(.failed)
601
+ self.stopInternal()
602
+ return
603
+ }
823
604
 
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
- }
605
+ // HTTP 429 Rate Limit / 503 Service Unavailable: Honor server Retry-After delay with randomized jitter to prevent thundering herd.
606
+ let retryAfterSeconds = SseReconnectStrategy.extractRetryAfterSeconds(from: error)
607
+ if (statusCode == 429 || statusCode == 503), let retryAfter = retryAfterSeconds {
608
+ let jitter = Double.random(in: 0.5...1.5)
609
+ let totalDelay = retryAfter + jitter
610
+ 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))
611
+ self.scheduleAutomaticReconnectWithFixedDelay(totalDelay, attemptVersion: attemptVersion)
612
+ return
613
+ }
829
614
 
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)
615
+ if statusCode == 429 {
616
+ 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))
617
+ self.updateState(.failed)
618
+ self.stopInternal()
619
+ return
832
620
  }
621
+
622
+ let isTimeout = (nsError.domain == NSURLErrorDomain && nsError.code == NSURLErrorTimedOut) || statusCode == -1001
623
+ if isTimeout {
624
+ self.updateState(.stale)
625
+ }
626
+
627
+ self.eventBuffer.push(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: error.localizedDescription, statusCode: Double(statusCode), retry: nil, state: nil))
628
+ self.scheduleAutomaticReconnect(isError: true, attemptVersion: attemptVersion)
833
629
  }
834
630
  }
835
631
  }