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