react-native-nitro-sse 1.4.1 → 1.6.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.
- package/README.md +33 -34
- package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +265 -84
- package/android/src/test/java/com/margelo/nitro/nitrosse/NitroSseLogicTest.kt +60 -13
- package/ios/NitroSse.swift +288 -81
- package/ios/Tests/NitroSseTests.swift +36 -0
- package/lib/module/index.js +3 -2
- package/lib/module/index.js.map +1 -1
- package/lib/typescript/src/SseInterface.d.ts +31 -4
- package/lib/typescript/src/SseInterface.d.ts.map +1 -1
- package/lib/typescript/src/index.d.ts.map +1 -1
- package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.hpp +138 -0
- package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +5 -2
- package/nitrogen/generated/android/c++/JSseConfig.hpp +28 -3
- package/nitrogen/generated/android/c++/JSseEvent.hpp +11 -3
- 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 +80 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +18 -5
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEvent.kt +9 -3
- package/nitrogen/generated/android/nitrosseOnLoad.cpp +2 -0
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.cpp +33 -0
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +130 -0
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +1 -0
- package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +2 -1
- package/nitrogen/generated/ios/swift/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.swift +67 -0
- package/nitrogen/generated/ios/swift/Func_void_std__exception_ptr.swift +46 -0
- package/nitrogen/generated/ios/swift/Func_void_std__shared_ptr_Promise_std__unordered_map_std__string__std__string___.swift +66 -0
- package/nitrogen/generated/ios/swift/Func_void_std__unordered_map_std__string__std__string_.swift +54 -0
- package/nitrogen/generated/ios/swift/SseConfig.swift +84 -1
- package/nitrogen/generated/ios/swift/SseEvent.swift +37 -1
- package/nitrogen/generated/shared/c++/SseConfig.hpp +17 -3
- package/nitrogen/generated/shared/c++/SseEvent.hpp +10 -2
- package/package.json +1 -1
- package/src/SseInterface.ts +31 -4
- package/src/{index.tsx → index.ts} +4 -3
package/ios/NitroSse.swift
CHANGED
|
@@ -15,12 +15,24 @@ import LDSwiftEventSource
|
|
|
15
15
|
* as a single array after a configurable interval.
|
|
16
16
|
*/
|
|
17
17
|
class NitroSse: HybridNitroSseSpec {
|
|
18
|
+
private static let sseQueueKey = DispatchSpecificKey<Void>()
|
|
19
|
+
|
|
20
|
+
deinit {
|
|
21
|
+
if DispatchQueue.getSpecific(key: NitroSse.sseQueueKey) != nil {
|
|
22
|
+
self.stopInternal()
|
|
23
|
+
} else {
|
|
24
|
+
sseQueue.sync {
|
|
25
|
+
self.stopInternal()
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
18
29
|
private var eventSource: EventSource?
|
|
19
30
|
private var config: SseConfig?
|
|
20
31
|
private var onEventsCallback: ((_ events: [SseEvent]) -> Void)?
|
|
21
32
|
private var isRunning: Bool = false
|
|
22
|
-
private var
|
|
23
|
-
|
|
33
|
+
private var consecutiveAuthErrors: Int = 0
|
|
34
|
+
private let maxAuthRetries: Int = 3
|
|
35
|
+
private var requestId: String? = nil
|
|
24
36
|
private var eventBuffer: [SseEvent] = []
|
|
25
37
|
private var isFlushPending: Bool = false
|
|
26
38
|
|
|
@@ -33,46 +45,76 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
33
45
|
private var lastErrorCode: String? = nil
|
|
34
46
|
|
|
35
47
|
private let defaultRetryDelay: TimeInterval = 3.0
|
|
36
|
-
private let baseBackoffDelay: TimeInterval =
|
|
48
|
+
private let baseBackoffDelay: TimeInterval = 1.0
|
|
37
49
|
private let maxBackoffDelay: TimeInterval = 30.0
|
|
38
50
|
|
|
39
|
-
private let sseQueue
|
|
51
|
+
private let sseQueue: DispatchQueue = {
|
|
52
|
+
let queue = DispatchQueue(label: "com.margelo.nitro.sse", qos: .utility)
|
|
53
|
+
queue.setSpecific(key: NitroSse.sseQueueKey, value: ())
|
|
54
|
+
return queue
|
|
55
|
+
}()
|
|
56
|
+
private var connectionAttemptVersion: Int = 0
|
|
40
57
|
private var backgroundTaskIdentifier: UIBackgroundTaskIdentifier = .invalid
|
|
41
58
|
private var wasRunningBeforeHibernation: Bool = false
|
|
42
59
|
|
|
60
|
+
/**
|
|
61
|
+
* Set up the NitroSse instance with configuration and an event callback.
|
|
62
|
+
* This prepares the lifecycle observers and internal dispatch queue.
|
|
63
|
+
*
|
|
64
|
+
* - Parameters:
|
|
65
|
+
* - config: The SSE configuration containing URL, headers, and more.
|
|
66
|
+
* - onEvent: Callback function to receive batched SSE events.
|
|
67
|
+
*/
|
|
43
68
|
func setup(config: SseConfig, onEvent: @escaping ((_ events: [SseEvent]) -> Void)) throws {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
69
|
+
sseQueue.async {
|
|
70
|
+
self.config = config
|
|
71
|
+
self.onEventsCallback = onEvent
|
|
72
|
+
|
|
73
|
+
NotificationCenter.default.removeObserver(self)
|
|
74
|
+
NotificationCenter.default.addObserver(self, selector: #selector(self.handleAppDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
|
|
75
|
+
NotificationCenter.default.addObserver(self, selector: #selector(self.handleAppWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
|
|
76
|
+
}
|
|
50
77
|
}
|
|
51
78
|
|
|
52
79
|
@objc private func handleAppDidEnterBackground() {
|
|
53
80
|
sseQueue.async {
|
|
54
|
-
guard self.isRunning else { return }
|
|
55
|
-
|
|
56
|
-
self.wasRunningBeforeHibernation = true
|
|
57
|
-
print("[NitroSse] App backgrounded. Hibernating connection.")
|
|
58
|
-
|
|
59
|
-
self.backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(withName: "NitroSse-GracefulHibernate") {
|
|
60
|
-
self.cleanupBackgroundTask()
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
self.flushEventsToJs()
|
|
81
|
+
guard self.isRunning, let config = self.config else { return }
|
|
64
82
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
83
|
+
if config.backgroundExecution == true {
|
|
84
|
+
print("[NitroSse] App backgrounded. backgroundExecution is true, keeping connection alive.")
|
|
85
|
+
// Start a background task to tell the OS we want to keep running
|
|
86
|
+
self.backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(withName: "NitroSse-KeepAlive") { [weak self] in
|
|
87
|
+
self?.sseQueue.async {
|
|
88
|
+
print("[NitroSse] Background task expired. Hibernating now.")
|
|
89
|
+
self?.hibernateConnection()
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return
|
|
70
93
|
}
|
|
71
|
-
self.isRunning = false
|
|
72
94
|
|
|
73
|
-
self.
|
|
95
|
+
self.hibernateConnection()
|
|
74
96
|
}
|
|
75
97
|
}
|
|
98
|
+
|
|
99
|
+
private func hibernateConnection() {
|
|
100
|
+
dispatchPrecondition(condition: .onQueue(sseQueue))
|
|
101
|
+
guard self.isRunning else { return }
|
|
102
|
+
|
|
103
|
+
self.wasRunningBeforeHibernation = true
|
|
104
|
+
print("[NitroSse] Hibernating NitroSse connection.")
|
|
105
|
+
|
|
106
|
+
self.flushEventsToJs()
|
|
107
|
+
|
|
108
|
+
self.eventSource?.stop()
|
|
109
|
+
self.eventSource = nil
|
|
110
|
+
if let rid = self.requestId {
|
|
111
|
+
NitroSseNetworkInspector.reportResponseEnd(rid, encodedDataLength: Int(self.totalBytesReceived))
|
|
112
|
+
self.requestId = nil
|
|
113
|
+
}
|
|
114
|
+
self.isRunning = false
|
|
115
|
+
|
|
116
|
+
self.cleanupBackgroundTask()
|
|
117
|
+
}
|
|
76
118
|
|
|
77
119
|
@objc private func handleAppWillEnterForeground() {
|
|
78
120
|
sseQueue.async {
|
|
@@ -86,6 +128,7 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
86
128
|
}
|
|
87
129
|
|
|
88
130
|
private func cleanupBackgroundTask() {
|
|
131
|
+
dispatchPrecondition(condition: .onQueue(sseQueue))
|
|
89
132
|
if self.backgroundTaskIdentifier != .invalid {
|
|
90
133
|
UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier)
|
|
91
134
|
self.backgroundTaskIdentifier = .invalid
|
|
@@ -98,17 +141,17 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
98
141
|
let batchIntervalMs = config?.batchingIntervalMs ?? 0
|
|
99
142
|
let bufferCapacity = Int(config?.maxBufferSize ?? 1000)
|
|
100
143
|
|
|
101
|
-
while eventBuffer.count >= bufferCapacity {
|
|
102
|
-
eventBuffer.removeFirst()
|
|
103
|
-
}
|
|
104
144
|
eventBuffer.append(event)
|
|
105
145
|
|
|
106
|
-
|
|
146
|
+
// If we reached capacity, flush immediately regardless of interval
|
|
147
|
+
if eventBuffer.count >= bufferCapacity || batchIntervalMs <= 0 {
|
|
107
148
|
flushEventsToJs()
|
|
108
149
|
} else if !isFlushPending {
|
|
109
150
|
isFlushPending = true
|
|
110
151
|
sseQueue.asyncAfter(deadline: .now() + (Double(batchIntervalMs) / 1000.0)) { [weak self] in
|
|
111
|
-
self?.
|
|
152
|
+
self?.sseQueue.async {
|
|
153
|
+
self?.flushEventsToJs()
|
|
154
|
+
}
|
|
112
155
|
}
|
|
113
156
|
}
|
|
114
157
|
}
|
|
@@ -126,28 +169,41 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
126
169
|
onEventsCallback?(batch)
|
|
127
170
|
}
|
|
128
171
|
|
|
172
|
+
/**
|
|
173
|
+
* Manually set the last seen event ID.
|
|
174
|
+
* This will be used as the 'Last-Event-ID' header on the next connection attempt.
|
|
175
|
+
*/
|
|
129
176
|
func setLastProcessedId(id: String) {
|
|
130
177
|
sseQueue.async {
|
|
131
178
|
self.lastProcessedId = id
|
|
132
179
|
}
|
|
133
180
|
}
|
|
134
181
|
|
|
182
|
+
/**
|
|
183
|
+
* Dynamically update the headers for subsequent connection attempts.
|
|
184
|
+
*/
|
|
135
185
|
func updateHeaders(headers: [String: String]) throws {
|
|
136
186
|
sseQueue.async {
|
|
137
|
-
guard let
|
|
187
|
+
guard let config = self.config else { return }
|
|
138
188
|
self.config = SseConfig(
|
|
139
|
-
url:
|
|
140
|
-
method:
|
|
189
|
+
url: config.url,
|
|
190
|
+
method: config.method,
|
|
141
191
|
headers: headers,
|
|
142
|
-
body:
|
|
143
|
-
backgroundExecution:
|
|
144
|
-
batchingIntervalMs:
|
|
145
|
-
maxBufferSize:
|
|
192
|
+
body: config.body,
|
|
193
|
+
backgroundExecution: config.backgroundExecution,
|
|
194
|
+
batchingIntervalMs: config.batchingIntervalMs,
|
|
195
|
+
maxBufferSize: config.maxBufferSize,
|
|
196
|
+
connectionTimeoutMs: config.connectionTimeoutMs,
|
|
197
|
+
readTimeoutMs: config.readTimeoutMs,
|
|
198
|
+
onBeforeRequest: config.onBeforeRequest
|
|
146
199
|
)
|
|
147
200
|
print("[NitroSse] Headers updated for subsequent connections.")
|
|
148
201
|
}
|
|
149
202
|
}
|
|
150
203
|
|
|
204
|
+
/**
|
|
205
|
+
* Returns runtime statistics about the SSE connection.
|
|
206
|
+
*/
|
|
151
207
|
func getStats() throws -> SseStats {
|
|
152
208
|
return sseQueue.sync {
|
|
153
209
|
return SseStats(
|
|
@@ -159,33 +215,142 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
159
215
|
}
|
|
160
216
|
}
|
|
161
217
|
|
|
218
|
+
/**
|
|
219
|
+
* Start the SSE connection.
|
|
220
|
+
* This triggers the initial request and handles subsequent reconnections.
|
|
221
|
+
*/
|
|
162
222
|
func start() throws {
|
|
163
|
-
|
|
223
|
+
let startBody = {
|
|
164
224
|
guard !self.isRunning else { return }
|
|
225
|
+
|
|
226
|
+
// Critical check: Ensure config is available before starting
|
|
227
|
+
guard self.config != nil else {
|
|
228
|
+
throw NSError(domain: "NitroSse", code: -1, userInfo: [NSLocalizedDescriptionKey: "NitroSse not configured. Call setup() first."])
|
|
229
|
+
}
|
|
230
|
+
|
|
165
231
|
self.isRunning = true
|
|
232
|
+
self.consecutiveAuthErrors = 0
|
|
166
233
|
self.backoffCounter = 0
|
|
167
|
-
self.
|
|
234
|
+
self.connectionAttemptVersion += 1
|
|
235
|
+
let version = self.connectionAttemptVersion
|
|
236
|
+
|
|
237
|
+
self.establishConnection(attemptVersion: version)
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
if DispatchQueue.getSpecific(key: NitroSse.sseQueueKey) != nil {
|
|
241
|
+
try startBody()
|
|
242
|
+
} else {
|
|
243
|
+
try sseQueue.sync(execute: startBody)
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
private func establishConnection(attemptVersion: Int) {
|
|
248
|
+
dispatchPrecondition(condition: .onQueue(sseQueue))
|
|
249
|
+
guard isRunning, let config = config, attemptVersion == self.connectionAttemptVersion else { return }
|
|
250
|
+
|
|
251
|
+
if let interceptor = config.onBeforeRequest {
|
|
252
|
+
|
|
253
|
+
let capturedConfig = config
|
|
254
|
+
class CompletionFlag {
|
|
255
|
+
var isCompleted = false
|
|
256
|
+
}
|
|
257
|
+
let flag = CompletionFlag()
|
|
258
|
+
let timeoutMs = capturedConfig.connectionTimeoutMs ?? 15000.0
|
|
259
|
+
|
|
260
|
+
sseQueue.asyncAfter(deadline: .now() + (timeoutMs / 1000.0)) { [weak self] in
|
|
261
|
+
guard let self = self else { return }
|
|
262
|
+
self.sseQueue.async {
|
|
263
|
+
guard self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
|
|
264
|
+
if !flag.isCompleted {
|
|
265
|
+
flag.isCompleted = true
|
|
266
|
+
let error = NSError(domain: "NitroSse", code: -1, userInfo: [NSLocalizedDescriptionKey: "onBeforeRequest interceptor timed out after \(timeoutMs) ms"])
|
|
267
|
+
self.handleInterceptorError(error, attemptVersion: attemptVersion)
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
interceptor().then { [weak self] promise2 in
|
|
273
|
+
promise2.then { [weak self] newHeaders in
|
|
274
|
+
self?.sseQueue.async {
|
|
275
|
+
guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
|
|
276
|
+
if !flag.isCompleted {
|
|
277
|
+
flag.isCompleted = true
|
|
278
|
+
let currentConfig = self.config ?? capturedConfig
|
|
279
|
+
var mergedHeaders = currentConfig.headers ?? [:]
|
|
280
|
+
for (k, v) in newHeaders {
|
|
281
|
+
mergedHeaders[k] = v
|
|
282
|
+
}
|
|
283
|
+
self.config = SseConfig(
|
|
284
|
+
url: currentConfig.url,
|
|
285
|
+
method: currentConfig.method,
|
|
286
|
+
headers: mergedHeaders,
|
|
287
|
+
body: currentConfig.body,
|
|
288
|
+
backgroundExecution: currentConfig.backgroundExecution,
|
|
289
|
+
batchingIntervalMs: currentConfig.batchingIntervalMs,
|
|
290
|
+
maxBufferSize: currentConfig.maxBufferSize,
|
|
291
|
+
connectionTimeoutMs: currentConfig.connectionTimeoutMs,
|
|
292
|
+
readTimeoutMs: currentConfig.readTimeoutMs,
|
|
293
|
+
onBeforeRequest: currentConfig.onBeforeRequest
|
|
294
|
+
)
|
|
295
|
+
self.performEstablishConnection(attemptVersion: attemptVersion)
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}.catch { [weak self] error in
|
|
299
|
+
self?.sseQueue.async {
|
|
300
|
+
guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
|
|
301
|
+
if !flag.isCompleted {
|
|
302
|
+
flag.isCompleted = true
|
|
303
|
+
self.handleInterceptorError(error, attemptVersion: attemptVersion)
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}.catch { [weak self] error in
|
|
308
|
+
self?.sseQueue.async {
|
|
309
|
+
guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
|
|
310
|
+
if !flag.isCompleted {
|
|
311
|
+
flag.isCompleted = true
|
|
312
|
+
self.handleInterceptorError(error, attemptVersion: attemptVersion)
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
} else {
|
|
317
|
+
self.performEstablishConnection(attemptVersion: attemptVersion)
|
|
168
318
|
}
|
|
169
319
|
}
|
|
170
320
|
|
|
171
|
-
private func
|
|
321
|
+
private func handleInterceptorError(_ error: Error, attemptVersion: Int) {
|
|
172
322
|
dispatchPrecondition(condition: .onQueue(sseQueue))
|
|
173
|
-
guard isRunning,
|
|
323
|
+
guard self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
|
|
324
|
+
print("[NitroSse] Interceptor failed: \(error.localizedDescription)")
|
|
325
|
+
self.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Interceptor Error: \(error.localizedDescription)", statusCode: -1, retry: nil))
|
|
326
|
+
// Reconnect after delay
|
|
327
|
+
self.scheduleAutomaticReconnect(isError: true, attemptVersion: attemptVersion)
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
private func performEstablishConnection(attemptVersion: Int) {
|
|
331
|
+
dispatchPrecondition(condition: .onQueue(sseQueue))
|
|
332
|
+
guard isRunning, let config = config, let url = URL(string: config.url), attemptVersion == self.connectionAttemptVersion else { return }
|
|
174
333
|
|
|
175
334
|
if let rid = self.requestId {
|
|
176
335
|
NitroSseNetworkInspector.reportResponseEnd(rid, encodedDataLength: Int(self.totalBytesReceived))
|
|
177
336
|
self.requestId = nil
|
|
178
337
|
}
|
|
179
338
|
|
|
180
|
-
let
|
|
339
|
+
let sessionConfig = URLSessionConfiguration.default
|
|
340
|
+
let readTimeout = (config.readTimeoutMs ?? 300000.0) / 1000.0
|
|
341
|
+
sessionConfig.timeoutIntervalForRequest = readTimeout
|
|
342
|
+
sessionConfig.timeoutIntervalForResource = readTimeout
|
|
343
|
+
|
|
344
|
+
let handler = SseHandler(parent: self, attemptVersion: attemptVersion)
|
|
181
345
|
var esConfig = EventSource.Config(handler: handler, url: url)
|
|
346
|
+
esConfig.urlSessionConfiguration = sessionConfig
|
|
182
347
|
esConfig.headers = config.headers ?? [:]
|
|
183
348
|
|
|
184
349
|
if let lastId = self.lastProcessedId, !lastId.isEmpty {
|
|
185
350
|
esConfig.headers["Last-Event-ID"] = lastId
|
|
186
351
|
}
|
|
187
352
|
|
|
188
|
-
esConfig.
|
|
353
|
+
esConfig.lastEventId = self.lastProcessedId ?? ""
|
|
189
354
|
esConfig.method = config.method?.stringValue.uppercased() ?? "GET"
|
|
190
355
|
esConfig.body = config.body?.data(using: .utf8)
|
|
191
356
|
|
|
@@ -199,13 +364,18 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
199
364
|
es.start()
|
|
200
365
|
}
|
|
201
366
|
|
|
367
|
+
/**
|
|
368
|
+
* Stop the SSE connection and clear any pending reconnect timers.
|
|
369
|
+
*/
|
|
202
370
|
func stop() {
|
|
203
371
|
sseQueue.async {
|
|
372
|
+
self.connectionAttemptVersion += 1
|
|
204
373
|
self.stopInternal()
|
|
205
374
|
}
|
|
206
375
|
}
|
|
207
376
|
|
|
208
377
|
private func stopInternal() {
|
|
378
|
+
dispatchPrecondition(condition: .onQueue(sseQueue))
|
|
209
379
|
self.isRunning = false
|
|
210
380
|
self.eventSource?.stop()
|
|
211
381
|
self.eventSource = nil
|
|
@@ -214,27 +384,35 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
214
384
|
self.requestId = nil
|
|
215
385
|
}
|
|
216
386
|
self.backoffCounter = 0
|
|
217
|
-
self.eventBuffer.removeAll()
|
|
218
387
|
self.isFlushPending = false
|
|
219
388
|
self.cleanupBackgroundTask()
|
|
220
389
|
}
|
|
221
390
|
|
|
391
|
+
/**
|
|
392
|
+
* Immediately emit any pending buffered events to the JS bridge.
|
|
393
|
+
*/
|
|
222
394
|
func flush() {
|
|
223
395
|
sseQueue.async {
|
|
224
396
|
self.flushEventsToJs()
|
|
225
397
|
}
|
|
226
398
|
}
|
|
227
399
|
|
|
400
|
+
/**
|
|
401
|
+
* Restart the SSE connection by stopping and starting again.
|
|
402
|
+
*/
|
|
228
403
|
func restart() {
|
|
229
404
|
sseQueue.async {
|
|
230
405
|
self.stopInternal()
|
|
231
|
-
guard !self.isRunning else { return } // Should be false now
|
|
232
406
|
self.isRunning = true
|
|
233
407
|
self.requestId = nil
|
|
234
|
-
self.
|
|
408
|
+
self.connectionAttemptVersion += 1
|
|
409
|
+
self.establishConnection(attemptVersion: self.connectionAttemptVersion)
|
|
235
410
|
}
|
|
236
411
|
}
|
|
237
412
|
|
|
413
|
+
/**
|
|
414
|
+
* Indicates if the SSE connection is currently active or trying to connect.
|
|
415
|
+
*/
|
|
238
416
|
func isConnected() -> Bool {
|
|
239
417
|
return sseQueue.sync {
|
|
240
418
|
return isRunning
|
|
@@ -260,20 +438,20 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
260
438
|
return nil
|
|
261
439
|
}
|
|
262
440
|
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
private func scheduleAutomaticReconnectWithFixedDelay(_ delay: TimeInterval) {
|
|
441
|
+
private func scheduleAutomaticReconnectWithFixedDelay(_ delay: TimeInterval, attemptVersion: Int) {
|
|
267
442
|
dispatchPrecondition(condition: .onQueue(sseQueue))
|
|
268
443
|
eventSource?.stop()
|
|
269
444
|
eventSource = nil
|
|
270
445
|
sseQueue.asyncAfter(deadline: .now() + delay) { [weak self] in
|
|
271
|
-
guard let self = self
|
|
272
|
-
self.
|
|
446
|
+
guard let self = self else { return }
|
|
447
|
+
self.sseQueue.async {
|
|
448
|
+
guard self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
|
|
449
|
+
self.establishConnection(attemptVersion: attemptVersion)
|
|
450
|
+
}
|
|
273
451
|
}
|
|
274
452
|
}
|
|
275
453
|
|
|
276
|
-
private func scheduleAutomaticReconnect(isError: Bool) {
|
|
454
|
+
private func scheduleAutomaticReconnect(isError: Bool, attemptVersion: Int) {
|
|
277
455
|
dispatchPrecondition(condition: .onQueue(sseQueue))
|
|
278
456
|
eventSource?.stop()
|
|
279
457
|
var delay: TimeInterval = defaultRetryDelay
|
|
@@ -286,43 +464,47 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
286
464
|
delay = defaultRetryDelay * (0.8 + Double.random(in: 0...0.4))
|
|
287
465
|
}
|
|
288
466
|
let safeDelay = max(delay, 2.0)
|
|
289
|
-
let currentSource = self.eventSource
|
|
290
467
|
eventSource?.stop()
|
|
291
468
|
eventSource = nil
|
|
292
469
|
sseQueue.asyncAfter(deadline: .now() + safeDelay) { [weak self] in
|
|
293
|
-
guard let self = self
|
|
294
|
-
self.
|
|
470
|
+
guard let self = self else { return }
|
|
471
|
+
self.sseQueue.async {
|
|
472
|
+
guard self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
|
|
473
|
+
self.establishConnection(attemptVersion: attemptVersion)
|
|
474
|
+
}
|
|
295
475
|
}
|
|
296
476
|
}
|
|
297
477
|
|
|
298
478
|
private class SseHandler: EventHandler {
|
|
299
479
|
weak var parent: NitroSse?
|
|
300
480
|
weak var source: EventSource?
|
|
481
|
+
let attemptVersion: Int
|
|
301
482
|
|
|
302
|
-
init(parent: NitroSse) {
|
|
483
|
+
init(parent: NitroSse, attemptVersion: Int) {
|
|
303
484
|
self.parent = parent
|
|
485
|
+
self.attemptVersion = attemptVersion
|
|
304
486
|
}
|
|
305
487
|
|
|
306
488
|
func onOpened() {
|
|
307
489
|
guard let parent = parent, source === parent.eventSource else { return }
|
|
308
490
|
parent.sseQueue.async { [weak parent] in
|
|
309
|
-
guard let parent = parent else { return }
|
|
491
|
+
guard let parent = parent, self.attemptVersion == parent.connectionAttemptVersion else { return }
|
|
310
492
|
parent.backoffCounter = 0
|
|
311
|
-
|
|
312
|
-
parent.pushEventToBuffer(SseEvent(type: .open, data: nil, id: nil, event: nil, message: nil))
|
|
493
|
+
parent.consecutiveAuthErrors = 0
|
|
494
|
+
parent.pushEventToBuffer(SseEvent(type: .open, data: nil, id: nil, event: nil, message: nil, statusCode: 200, retry: nil))
|
|
313
495
|
}
|
|
314
496
|
}
|
|
315
497
|
|
|
316
498
|
func onClosed() {
|
|
317
499
|
guard let parent = parent, source === parent.eventSource else { return }
|
|
318
500
|
parent.sseQueue.async { [weak parent] in
|
|
319
|
-
guard let parent = parent else { return }
|
|
501
|
+
guard let parent = parent, self.attemptVersion == parent.connectionAttemptVersion else { return }
|
|
320
502
|
if let rid = parent.requestId {
|
|
321
503
|
NitroSseNetworkInspector.reportResponseEnd(rid, encodedDataLength: Int(parent.totalBytesReceived))
|
|
322
504
|
parent.requestId = nil
|
|
323
505
|
}
|
|
324
506
|
if parent.isRunning {
|
|
325
|
-
parent.scheduleAutomaticReconnect(isError: false)
|
|
507
|
+
parent.scheduleAutomaticReconnect(isError: false, attemptVersion: self.attemptVersion)
|
|
326
508
|
}
|
|
327
509
|
}
|
|
328
510
|
}
|
|
@@ -330,7 +512,7 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
330
512
|
func onMessage(eventType: String, messageEvent: MessageEvent) {
|
|
331
513
|
guard let parent = parent, source === parent.eventSource else { return }
|
|
332
514
|
parent.sseQueue.async { [weak parent] in
|
|
333
|
-
guard let parent = parent else { return }
|
|
515
|
+
guard let parent = parent, self.attemptVersion == parent.connectionAttemptVersion else { return }
|
|
334
516
|
let encodedDataSize = Double(messageEvent.data.utf8.count)
|
|
335
517
|
let metadataSize = Double(eventType.utf8.count) + Double((messageEvent.lastEventId).utf8.count)
|
|
336
518
|
parent.totalBytesReceived += encodedDataSize + metadataSize
|
|
@@ -339,23 +521,23 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
339
521
|
parent.lastProcessedId = messageEvent.lastEventId
|
|
340
522
|
}
|
|
341
523
|
|
|
342
|
-
parent.pushEventToBuffer(SseEvent(type: .message, data: messageEvent.data, id: messageEvent.lastEventId, event: eventType, message: nil))
|
|
524
|
+
parent.pushEventToBuffer(SseEvent(type: .message, data: messageEvent.data, id: messageEvent.lastEventId, event: eventType, message: nil, statusCode: 200, retry: nil))
|
|
343
525
|
}
|
|
344
526
|
}
|
|
345
527
|
|
|
346
528
|
func onComment(comment: String) {
|
|
347
529
|
guard let parent = parent, source === parent.eventSource else { return }
|
|
348
530
|
parent.sseQueue.async { [weak parent] in
|
|
349
|
-
guard let parent = parent else { return }
|
|
531
|
+
guard let parent = parent, self.attemptVersion == parent.connectionAttemptVersion else { return }
|
|
350
532
|
parent.totalBytesReceived += Double(comment.utf8.count)
|
|
351
|
-
parent.pushEventToBuffer(SseEvent(type: .heartbeat, data: nil, id: nil, event: nil, message: comment))
|
|
533
|
+
parent.pushEventToBuffer(SseEvent(type: .heartbeat, data: nil, id: nil, event: nil, message: comment, statusCode: nil, retry: nil))
|
|
352
534
|
}
|
|
353
535
|
}
|
|
354
536
|
|
|
355
537
|
func onError(error: Error) {
|
|
356
538
|
guard let parent = parent, source === parent.eventSource else { return }
|
|
357
539
|
parent.sseQueue.async { [weak parent] in
|
|
358
|
-
guard let parent = parent, parent.isRunning else { return }
|
|
540
|
+
guard let parent = parent, parent.isRunning, self.attemptVersion == parent.connectionAttemptVersion else { return }
|
|
359
541
|
let nsError = error as NSError
|
|
360
542
|
let statusCode = nsError.code
|
|
361
543
|
|
|
@@ -366,30 +548,55 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
366
548
|
NitroSseNetworkInspector.reportRequestFailed(parent.requestId, cancelled: false)
|
|
367
549
|
parent.requestId = nil
|
|
368
550
|
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
parent.
|
|
551
|
+
if statusCode == 204 {
|
|
552
|
+
parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "No Content (204). Stopping.", statusCode: 204, retry: nil))
|
|
553
|
+
parent.stopInternal()
|
|
554
|
+
return
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
if statusCode == 401 || statusCode == 403 {
|
|
558
|
+
if parent.config?.onBeforeRequest == nil {
|
|
559
|
+
parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Auth Error (\(statusCode)) - No interceptor provided. Stopping.", statusCode: Double(statusCode), retry: nil))
|
|
560
|
+
parent.stopInternal()
|
|
561
|
+
return
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
parent.consecutiveAuthErrors += 1
|
|
565
|
+
if parent.consecutiveAuthErrors >= parent.maxAuthRetries {
|
|
566
|
+
parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Auth Error (\(statusCode)) - Retry limit reached (\(parent.maxAuthRetries)). Stopping.", statusCode: Double(statusCode), retry: nil))
|
|
567
|
+
parent.stopInternal()
|
|
568
|
+
return
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Auth Error (\(statusCode)) - Retry \(parent.consecutiveAuthErrors)/\(parent.maxAuthRetries). Refreshing token...", statusCode: Double(statusCode), retry: nil))
|
|
572
|
+
parent.scheduleAutomaticReconnect(isError: true, attemptVersion: self.attemptVersion)
|
|
573
|
+
return
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
let isFatal = (statusCode == 400)
|
|
577
|
+
if isFatal {
|
|
578
|
+
parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Fatal Error (\(statusCode)). Stopping.", statusCode: Double(statusCode), retry: nil))
|
|
372
579
|
parent.stopInternal()
|
|
373
580
|
return
|
|
374
581
|
}
|
|
375
582
|
|
|
376
583
|
let retryAfterSeconds = parent.extractRetryAfterSeconds(error: error)
|
|
377
|
-
if (statusCode == 429 || statusCode == 503), let
|
|
378
|
-
let jitter = Double.random(in: 0.5...
|
|
379
|
-
let totalDelay =
|
|
380
|
-
parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Retry-After received
|
|
381
|
-
parent.scheduleAutomaticReconnectWithFixedDelay(totalDelay)
|
|
584
|
+
if (statusCode == 429 || statusCode == 503), let retryAfter = retryAfterSeconds {
|
|
585
|
+
let jitter = Double.random(in: 0.5...1.5)
|
|
586
|
+
let totalDelay = retryAfter + jitter
|
|
587
|
+
parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Retry-After received: \(Int(totalDelay))s", statusCode: Double(statusCode), retry: totalDelay * 1000.0))
|
|
588
|
+
parent.scheduleAutomaticReconnectWithFixedDelay(totalDelay, attemptVersion: self.attemptVersion)
|
|
382
589
|
return
|
|
383
590
|
}
|
|
384
591
|
|
|
385
592
|
if statusCode == 429 {
|
|
386
|
-
parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Rate Limited (429) without Retry-After. Stopping."))
|
|
593
|
+
parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Rate Limited (429) without Retry-After. Stopping.", statusCode: 429, retry: nil))
|
|
387
594
|
parent.stopInternal()
|
|
388
595
|
return
|
|
389
596
|
}
|
|
390
|
-
|
|
391
|
-
parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: error.localizedDescription))
|
|
392
|
-
parent.scheduleAutomaticReconnect(isError: true)
|
|
597
|
+
|
|
598
|
+
parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: error.localizedDescription, statusCode: Double(statusCode), retry: nil))
|
|
599
|
+
parent.scheduleAutomaticReconnect(isError: true, attemptVersion: self.attemptVersion)
|
|
393
600
|
}
|
|
394
601
|
}
|
|
395
602
|
}
|
|
@@ -83,4 +83,40 @@ class NitroSseTests: XCTestCase {
|
|
|
83
83
|
let size = calculateSize(eventType: "message", data: "{\"id\":1}", lastId: "event-1")
|
|
84
84
|
XCTAssertEqual(size, 22.0) // 8 (data) + 7 (type) + 7 (id) = 22 bytes
|
|
85
85
|
}
|
|
86
|
+
|
|
87
|
+
func testVersioningSafety() {
|
|
88
|
+
var connectionAttemptVersion: Int32 = 0
|
|
89
|
+
var executeCount = 0
|
|
90
|
+
|
|
91
|
+
func stop() {
|
|
92
|
+
connectionAttemptVersion += 1
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Start called, captures version 0
|
|
96
|
+
let capturedVersion = connectionAttemptVersion
|
|
97
|
+
|
|
98
|
+
// User stops immediately
|
|
99
|
+
stop()
|
|
100
|
+
|
|
101
|
+
// Connection logic tries to execute
|
|
102
|
+
func establishConnection(version: Int32) {
|
|
103
|
+
if version == connectionAttemptVersion {
|
|
104
|
+
executeCount += 1
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
establishConnection(version: capturedVersion)
|
|
109
|
+
XCTAssertEqual(executeCount, 0, "Should not execute if version changed")
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
func testAuthErrorReset() {
|
|
113
|
+
var consecutiveAuthErrors = 3
|
|
114
|
+
|
|
115
|
+
func onOpened() {
|
|
116
|
+
consecutiveAuthErrors = 0
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
onOpened()
|
|
120
|
+
XCTAssertEqual(consecutiveAuthErrors, 0, "Errors should reset on success")
|
|
121
|
+
}
|
|
86
122
|
}
|
package/lib/module/index.js
CHANGED
|
@@ -7,9 +7,10 @@ export function createNitroSse() {
|
|
|
7
7
|
let nativeSse;
|
|
8
8
|
try {
|
|
9
9
|
nativeSse = NitroModules.createHybridObject('NitroSse');
|
|
10
|
-
} catch {
|
|
11
|
-
if (!nativeSse) {
|
|
10
|
+
} catch {
|
|
12
11
|
console.debug('Native NitroSse not found. This might be a test environment or web.');
|
|
12
|
+
}
|
|
13
|
+
if (!nativeSse) {
|
|
13
14
|
throw new Error('NitroSse: Native module not found. Ensure you have linked the library and built the app for iOS/Android.');
|
|
14
15
|
}
|
|
15
16
|
return nativeSse;
|
package/lib/module/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["NitroModules","createNitroSse","nativeSse","createHybridObject","console","debug","Error"],"sourceRoot":"../../src","sources":["index.
|
|
1
|
+
{"version":3,"names":["NitroModules","createNitroSse","nativeSse","createHybridObject","console","debug","Error"],"sourceRoot":"../../src","sources":["index.ts"],"mappings":";;AAAA,SAASA,YAAY,QAAQ,4BAA4B;AAGzD,cAAc,mBAAgB;AAC9B,cAAc,qBAAkB;AAEhC,OAAO,SAASC,cAAcA,CAAA,EAAa;EACzC,IAAIC,SAA+B;EACnC,IAAI;IACFA,SAAS,GAAGF,YAAY,CAACG,kBAAkB,CAAW,UAAU,CAAC;EACnE,CAAC,CAAC,MAAM;IACNC,OAAO,CAACC,KAAK,CACX,qEACF,CAAC;EACH;EAEA,IAAI,CAACH,SAAS,EAAE;IACd,MAAM,IAAII,KAAK,CACb,0GACF,CAAC;EACH;EACA,OAAOJ,SAAS;AAClB","ignoreList":[]}
|