react-native-nitro-sse 2.4.2 → 3.0.0-beta.2
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 +209 -95
- package/android/build.gradle +4 -1
- package/android/src/main/java/com/margelo/nitro/nitrosse/AndroidSseDispatcher.kt +5 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +11 -18
- package/android/src/main/java/com/margelo/nitro/nitrosse/NetworkInspector.kt +79 -36
- package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +164 -88
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +40 -15
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseDispatcher.kt +1 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +34 -25
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseLifecycleManager.kt +8 -1
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseNetworkMonitor.kt +7 -4
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +2 -4
- package/ios/NitroSse.swift +229 -191
- package/ios/SseConfig+CopyWith.swift +2 -1
- package/ios/SseConnectionHandler.swift +40 -29
- package/ios/SseDispatchQueueDispatcher.swift +15 -2
- package/ios/SseDispatcher.swift +7 -1
- package/ios/SseEventBuffer.swift +23 -7
- package/ios/SseLifecycleManager.swift +10 -1
- package/ios/SseNetworkMonitor.swift +5 -0
- package/ios/SseReconnectStrategy.swift +4 -3
- package/lib/module/MockSseEngine.js +12 -21
- package/lib/module/NitroSseClient.js +385 -12
- package/lib/module/NitroSseError.js +61 -0
- package/lib/module/SseDriver.js +33 -2
- package/lib/module/index.js +6 -3
- package/lib/module/useNitroSse.js +359 -0
- package/lib/typescript/src/MockSseEngine.d.ts +1 -1
- package/lib/typescript/src/NitroSse.nitro.d.ts +25 -2
- package/lib/typescript/src/NitroSseClient.d.ts +20 -2
- package/lib/typescript/src/NitroSseError.d.ts +38 -0
- package/lib/typescript/src/SseDriver.d.ts +10 -2
- package/lib/typescript/src/SseInterface.d.ts +23 -7
- package/lib/typescript/src/index.d.ts +4 -2
- package/lib/typescript/src/useNitroSse.d.ts +69 -0
- package/nitrogen/generated/android/c++/JSseConfig.hpp +5 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +9 -4
- package/nitrogen/generated/ios/swift/SseConfig.swift +19 -1
- package/nitrogen/generated/shared/c++/SseConfig.hpp +5 -1
- package/package.json +8 -7
- package/android/jacoco.gradle +0 -33
- package/lib/module/MockSseEngine.js.map +0 -1
- package/lib/module/NitroSse.nitro.js.map +0 -1
- package/lib/module/NitroSseClient.js.map +0 -1
- package/lib/module/SseDriver.js.map +0 -1
- package/lib/module/SseInterface.js.map +0 -1
- package/lib/module/index.js.map +0 -1
- package/lib/typescript/src/MockSseEngine.d.ts.map +0 -1
- package/lib/typescript/src/NitroSse.nitro.d.ts.map +0 -1
- package/lib/typescript/src/NitroSseClient.d.ts.map +0 -1
- package/lib/typescript/src/SseDriver.d.ts.map +0 -1
- package/lib/typescript/src/SseInterface.d.ts.map +0 -1
- package/lib/typescript/src/index.d.ts.map +0 -1
- package/src/MockSseEngine.ts +0 -254
- package/src/NitroSse.nitro.ts +0 -58
- package/src/NitroSseClient.ts +0 -154
- package/src/SseDriver.ts +0 -161
- package/src/SseInterface.ts +0 -274
- package/src/index.ts +0 -31
package/ios/NitroSse.swift
CHANGED
|
@@ -40,7 +40,7 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
40
40
|
private var currentState: SseState = .idle
|
|
41
41
|
|
|
42
42
|
private var consecutiveAuthErrors: Int = 0
|
|
43
|
-
private let
|
|
43
|
+
private static let defaultMaxAuthRetries: Int = 3
|
|
44
44
|
|
|
45
45
|
private var totalBytesReceived: Double = 0
|
|
46
46
|
private var reconnectCount: Double = 0
|
|
@@ -50,6 +50,11 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
50
50
|
private var wasRunningBeforeHibernation: Bool = false
|
|
51
51
|
private var wasRunningBeforeNetworkLoss: Bool = false
|
|
52
52
|
|
|
53
|
+
private class InterceptorCancellationToken {
|
|
54
|
+
var isCancelled: Bool = false
|
|
55
|
+
}
|
|
56
|
+
private var currentInterceptorToken: InterceptorCancellationToken? = nil
|
|
57
|
+
|
|
53
58
|
// MARK: - Collaborators
|
|
54
59
|
|
|
55
60
|
private let eventBuffer = SseEventBuffer()
|
|
@@ -59,18 +64,27 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
59
64
|
|
|
60
65
|
// MARK: - Lifecycle
|
|
61
66
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
self.stopInternal()
|
|
67
|
+
/// Synchronously cleans up all active network sockets, timers, and lifecycle observers.
|
|
68
|
+
func dispose() {
|
|
69
|
+
let cleanup = {
|
|
70
|
+
self.stopInternal(emitClosed: false)
|
|
71
|
+
self.eventBuffer.clearCallback()
|
|
72
|
+
self.eventBuffer.clear()
|
|
66
73
|
self.networkMonitor?.stop()
|
|
74
|
+
self.networkMonitor = nil
|
|
75
|
+
}
|
|
76
|
+
if dispatcher.isCurrentDispatcher() {
|
|
77
|
+
cleanup()
|
|
67
78
|
} else {
|
|
68
|
-
dispatcher.sync
|
|
69
|
-
self.stopInternal()
|
|
70
|
-
self.networkMonitor?.stop()
|
|
71
|
-
}
|
|
79
|
+
dispatcher.sync(cleanup)
|
|
72
80
|
}
|
|
73
81
|
lifecycleManager?.stopObserving()
|
|
82
|
+
lifecycleManager = nil
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
deinit {
|
|
86
|
+
// Synchronous cleanup is required during deallocation to avoid executing callbacks on deallocated instances.
|
|
87
|
+
dispose()
|
|
74
88
|
}
|
|
75
89
|
|
|
76
90
|
// MARK: - HybridNitroSseSpec
|
|
@@ -117,11 +131,15 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
117
131
|
}
|
|
118
132
|
}
|
|
119
133
|
|
|
120
|
-
///
|
|
134
|
+
/// Updates active HTTP headers for subsequent request attempts (e.g. updating authorization tokens).
|
|
121
135
|
func updateHeaders(headers: [String: String]) throws {
|
|
122
136
|
dispatcher.async {
|
|
123
137
|
guard let config = self.config else { return }
|
|
124
|
-
|
|
138
|
+
var merged = config.headers ?? [:]
|
|
139
|
+
for (k, v) in headers {
|
|
140
|
+
merged[k] = v
|
|
141
|
+
}
|
|
142
|
+
self.config = config.copyWith(headers: merged)
|
|
125
143
|
print("[NitroSse] Headers updated for subsequent connections.")
|
|
126
144
|
}
|
|
127
145
|
}
|
|
@@ -150,13 +168,28 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
150
168
|
if self.currentState != newState {
|
|
151
169
|
self.currentState = newState
|
|
152
170
|
self.eventBuffer.push(SseEvent(type: .state, data: nil, parsedData: nil, id: nil, event: nil, message: nil, statusCode: nil, retry: nil, state: newState))
|
|
171
|
+
// State events represent immediate connection lifecycle transitions and must be flushed
|
|
172
|
+
// to JS immediately to prevent UI and React hook state desynchronization.
|
|
173
|
+
self.eventBuffer.flush()
|
|
153
174
|
}
|
|
154
175
|
}
|
|
155
176
|
|
|
156
177
|
/// Begins connection establishment and resets retry counters.
|
|
178
|
+
/// If the client is currently in a backoff reconnection delay, start() acts as an immediate "Retry Now",
|
|
179
|
+
/// resetting the retry strategy and establishing connection immediately.
|
|
157
180
|
func start() throws {
|
|
158
181
|
let startBody = {
|
|
159
|
-
|
|
182
|
+
if self.isRunning {
|
|
183
|
+
if self.currentState == .reconnecting {
|
|
184
|
+
print("[NitroSse] start() invoked while reconnecting. Resetting backoff and retrying immediately.")
|
|
185
|
+
self.reconnectStrategy.reset()
|
|
186
|
+
self.consecutiveAuthErrors = 0
|
|
187
|
+
self.connectionAttemptVersion += 1
|
|
188
|
+
self.updateState(.connecting)
|
|
189
|
+
self.establishConnection(attemptVersion: self.connectionAttemptVersion)
|
|
190
|
+
}
|
|
191
|
+
return
|
|
192
|
+
}
|
|
160
193
|
|
|
161
194
|
guard self.config != nil else {
|
|
162
195
|
throw RuntimeError("NitroSse not configured. Call setup() first.")
|
|
@@ -273,13 +306,16 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
273
306
|
if config.backgroundExecution == true {
|
|
274
307
|
print("[NitroSse] App backgrounded. backgroundExecution is true, keeping connection alive.")
|
|
275
308
|
self.lifecycleManager?.beginBackgroundKeepAlive { [weak self] in
|
|
309
|
+
guard let self = self, self.isRunning else { return }
|
|
276
310
|
print("[NitroSse] Background task expired. Hibernating now.")
|
|
277
|
-
self
|
|
278
|
-
self
|
|
311
|
+
self.wasRunningBeforeHibernation = true
|
|
312
|
+
self.updateState(.paused)
|
|
313
|
+
self.hibernateConnection()
|
|
279
314
|
}
|
|
280
315
|
return
|
|
281
316
|
}
|
|
282
317
|
|
|
318
|
+
self.wasRunningBeforeHibernation = true
|
|
283
319
|
self.updateState(.paused)
|
|
284
320
|
self.hibernateConnection()
|
|
285
321
|
}
|
|
@@ -287,9 +323,22 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
287
323
|
private func handleAppWillEnterForeground() {
|
|
288
324
|
dispatcher.assertOnQueue()
|
|
289
325
|
if self.wasRunningBeforeHibernation {
|
|
290
|
-
print("[NitroSse] App foregrounded. Resuming stream.")
|
|
291
326
|
self.wasRunningBeforeHibernation = false
|
|
292
|
-
|
|
327
|
+
let isOnline = self.networkMonitor?.isPathSatisfied ?? true
|
|
328
|
+
if isOnline {
|
|
329
|
+
print("[NitroSse] App foregrounded. Resuming stream.")
|
|
330
|
+
try? self.start()
|
|
331
|
+
} else {
|
|
332
|
+
print("[NitroSse] App foregrounded while offline. Handing over intent to network monitor.")
|
|
333
|
+
self.wasRunningBeforeNetworkLoss = true
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
private func finishActiveRequestInspector() {
|
|
339
|
+
if let rid = self.requestId {
|
|
340
|
+
NitroSseNetworkInspector.reportResponseEnd(rid, encodedDataLength: Int(self.totalBytesReceived))
|
|
341
|
+
self.requestId = nil
|
|
293
342
|
}
|
|
294
343
|
}
|
|
295
344
|
|
|
@@ -297,17 +346,17 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
297
346
|
dispatcher.assertOnQueue()
|
|
298
347
|
guard self.isRunning else { return }
|
|
299
348
|
|
|
300
|
-
self.wasRunningBeforeHibernation = true
|
|
301
349
|
print("[NitroSse] Hibernating NitroSse connection.")
|
|
302
350
|
|
|
351
|
+
self.connectionAttemptVersion += 1
|
|
352
|
+
self.currentInterceptorToken?.isCancelled = true
|
|
353
|
+
self.currentInterceptorToken = nil
|
|
354
|
+
|
|
303
355
|
self.eventBuffer.flush()
|
|
304
356
|
|
|
305
357
|
self.eventSource?.stop()
|
|
306
358
|
self.eventSource = nil
|
|
307
|
-
|
|
308
|
-
NitroSseNetworkInspector.reportResponseEnd(rid, encodedDataLength: Int(self.totalBytesReceived))
|
|
309
|
-
self.requestId = nil
|
|
310
|
-
}
|
|
359
|
+
self.finishActiveRequestInspector()
|
|
311
360
|
self.isRunning = false
|
|
312
361
|
|
|
313
362
|
self.lifecycleManager?.cleanupBackgroundTask()
|
|
@@ -322,7 +371,12 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
322
371
|
guard isRunning, let config = config, attemptVersion == self.connectionAttemptVersion else { return }
|
|
323
372
|
|
|
324
373
|
if let interceptor = config.onBeforeRequest {
|
|
374
|
+
self.currentInterceptorToken?.isCancelled = true
|
|
375
|
+
let token = InterceptorCancellationToken()
|
|
376
|
+
self.currentInterceptorToken = token
|
|
325
377
|
|
|
378
|
+
// Await async JS interceptor (with timeout guard) before creating EventSource,
|
|
379
|
+
// as LDSwiftEventSource.Config.headerTransform is synchronous.
|
|
326
380
|
let capturedConfig = config
|
|
327
381
|
// Reference-type completion flag to prevent races between interceptor promise resolution and connection timeout.
|
|
328
382
|
class CompletionFlag {
|
|
@@ -333,20 +387,33 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
333
387
|
|
|
334
388
|
// Recovers execution state if JS async interceptor fails to settle within connectionTimeoutMs.
|
|
335
389
|
dispatcher.asyncAfter(delay: (timeoutMs / 1000.0)) { [weak self] in
|
|
336
|
-
guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
|
|
390
|
+
guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion, !token.isCancelled else { return }
|
|
337
391
|
if !flag.isCompleted {
|
|
338
392
|
flag.isCompleted = true
|
|
393
|
+
token.isCancelled = true
|
|
339
394
|
let error = NSError(domain: "NitroSse", code: -1, userInfo: [NSLocalizedDescriptionKey: "onBeforeRequest interceptor timed out after \(timeoutMs) ms"])
|
|
340
395
|
self.handleInterceptorError(error, attemptVersion: attemptVersion)
|
|
341
396
|
}
|
|
342
397
|
}
|
|
343
398
|
|
|
399
|
+
let safeHandleError: (Error) -> Void = { [weak self] error in
|
|
400
|
+
self?.dispatcher.async { [weak self] in
|
|
401
|
+
guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion, !token.isCancelled else { return }
|
|
402
|
+
if !flag.isCompleted {
|
|
403
|
+
flag.isCompleted = true
|
|
404
|
+
token.isCancelled = true
|
|
405
|
+
self.handleInterceptorError(error, attemptVersion: attemptVersion)
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
344
410
|
interceptor().then { [weak self] promise2 in
|
|
345
411
|
promise2.then { [weak self] newHeaders in
|
|
346
412
|
self?.dispatcher.async { [weak self] in
|
|
347
|
-
guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
|
|
413
|
+
guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion, !token.isCancelled else { return }
|
|
348
414
|
if !flag.isCompleted {
|
|
349
415
|
flag.isCompleted = true
|
|
416
|
+
token.isCancelled = true
|
|
350
417
|
let currentConfig = self.config ?? capturedConfig
|
|
351
418
|
var mergedHeaders = currentConfig.headers ?? [:]
|
|
352
419
|
for (k, v) in newHeaders {
|
|
@@ -356,24 +423,8 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
356
423
|
self.performEstablishConnection(attemptVersion: attemptVersion)
|
|
357
424
|
}
|
|
358
425
|
}
|
|
359
|
-
}.catch
|
|
360
|
-
|
|
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)
|
|
365
|
-
}
|
|
366
|
-
}
|
|
367
|
-
}
|
|
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
|
-
}
|
|
375
|
-
}
|
|
376
|
-
}
|
|
426
|
+
}.catch(safeHandleError)
|
|
427
|
+
}.catch(safeHandleError)
|
|
377
428
|
} else {
|
|
378
429
|
self.performEstablishConnection(attemptVersion: attemptVersion)
|
|
379
430
|
}
|
|
@@ -397,14 +448,15 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
397
448
|
|
|
398
449
|
private func performEstablishConnection(attemptVersion: Int) {
|
|
399
450
|
dispatcher.assertOnQueue()
|
|
400
|
-
guard isRunning, let config = config,
|
|
451
|
+
guard isRunning, let config = config, attemptVersion == self.connectionAttemptVersion else { return }
|
|
452
|
+
guard let url = URL(string: config.url), let scheme = url.scheme, ["http", "https"].contains(scheme.lowercased()) else {
|
|
453
|
+
print("[NitroSse] Invalid SSE URL: \(config.url)")
|
|
454
|
+
self.failAndStop(message: "Invalid URL: \(config.url)", statusCode: -1)
|
|
455
|
+
return
|
|
456
|
+
}
|
|
401
457
|
|
|
402
458
|
self.updateState(.connecting)
|
|
403
|
-
|
|
404
|
-
if let rid = self.requestId {
|
|
405
|
-
NitroSseNetworkInspector.reportResponseEnd(rid, encodedDataLength: Int(self.totalBytesReceived))
|
|
406
|
-
self.requestId = nil
|
|
407
|
-
}
|
|
459
|
+
self.finishActiveRequestInspector()
|
|
408
460
|
|
|
409
461
|
let es = SseConnectionHandler.createEventSource(
|
|
410
462
|
url: url,
|
|
@@ -416,7 +468,16 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
416
468
|
)
|
|
417
469
|
self.eventSource = es
|
|
418
470
|
|
|
419
|
-
|
|
471
|
+
var request = URLRequest(url: url)
|
|
472
|
+
request.httpMethod = config.method?.stringValue.uppercased() ?? "GET"
|
|
473
|
+
request.allHTTPHeaderFields = config.headers
|
|
474
|
+
if let body = config.body {
|
|
475
|
+
request.httpBody = body.data(using: .utf8)
|
|
476
|
+
}
|
|
477
|
+
// Injected explicitly so lastProcessedId outlives EventSource recreation.
|
|
478
|
+
if let lastId = lastProcessedId, !lastId.isEmpty {
|
|
479
|
+
request.setValue(lastId, forHTTPHeaderField: "Last-Event-ID")
|
|
480
|
+
}
|
|
420
481
|
self.requestId = NitroSseNetworkInspector.reportRequestStart(request, encodedDataLength: 0)
|
|
421
482
|
}
|
|
422
483
|
|
|
@@ -433,12 +494,11 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
433
494
|
}
|
|
434
495
|
self.wasRunningBeforeNetworkLoss = false
|
|
435
496
|
self.wasRunningBeforeHibernation = false
|
|
497
|
+
self.currentInterceptorToken?.isCancelled = true
|
|
498
|
+
self.currentInterceptorToken = nil
|
|
436
499
|
self.eventSource?.stop()
|
|
437
500
|
self.eventSource = nil
|
|
438
|
-
|
|
439
|
-
NitroSseNetworkInspector.reportResponseEnd(rid, encodedDataLength: Int(self.totalBytesReceived))
|
|
440
|
-
self.requestId = nil
|
|
441
|
-
}
|
|
501
|
+
self.finishActiveRequestInspector()
|
|
442
502
|
self.reconnectStrategy.reset()
|
|
443
503
|
self.lifecycleManager?.cleanupBackgroundTask()
|
|
444
504
|
}
|
|
@@ -451,7 +511,8 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
451
511
|
self.stopInternal()
|
|
452
512
|
}
|
|
453
513
|
|
|
454
|
-
|
|
514
|
+
/// Reconnects with exponential backoff coordinated externally via SseDispatcher and attemptVersion.
|
|
515
|
+
private func scheduleAutomaticReconnect(isError: Bool, fixedDelay: TimeInterval? = nil, attemptVersion: Int) {
|
|
455
516
|
dispatcher.assertOnQueue()
|
|
456
517
|
guard isRunning, attemptVersion == self.connectionAttemptVersion else { return }
|
|
457
518
|
|
|
@@ -462,38 +523,21 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
462
523
|
return
|
|
463
524
|
}
|
|
464
525
|
|
|
526
|
+
let delay: TimeInterval
|
|
527
|
+
if let customDelay = fixedDelay {
|
|
528
|
+
reconnectStrategy.recordAttempt()
|
|
529
|
+
delay = customDelay
|
|
530
|
+
} else {
|
|
531
|
+
delay = reconnectStrategy.nextDelay(isError: isError)
|
|
532
|
+
}
|
|
533
|
+
|
|
465
534
|
// Increment connectionAttemptVersion before stopping eventSource to invalidate any in-flight
|
|
466
535
|
// or asynchronous onError/onClosed callbacks triggered during shutdown/teardown.
|
|
467
536
|
self.connectionAttemptVersion += 1
|
|
468
537
|
let newVersion = self.connectionAttemptVersion
|
|
469
|
-
let safeDelay = reconnectStrategy.nextDelay(isError: isError)
|
|
470
538
|
self.updateState(.reconnecting)
|
|
471
539
|
eventSource?.stop()
|
|
472
540
|
eventSource = nil
|
|
473
|
-
dispatcher.asyncAfter(delay: safeDelay) { [weak self] in
|
|
474
|
-
guard let self = self, self.isRunning, newVersion == self.connectionAttemptVersion else { return }
|
|
475
|
-
self.establishConnection(attemptVersion: newVersion)
|
|
476
|
-
}
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
private func scheduleAutomaticReconnectWithFixedDelay(_ delay: TimeInterval, attemptVersion: Int) {
|
|
480
|
-
dispatcher.assertOnQueue()
|
|
481
|
-
guard isRunning, attemptVersion == self.connectionAttemptVersion else { return }
|
|
482
|
-
|
|
483
|
-
if reconnectStrategy.hasReachedMaxAttempts() {
|
|
484
|
-
let maxAttempts = Int(config?.maxReconnectAttempts ?? -1.0)
|
|
485
|
-
print("[NitroSse] Max reconnection attempts reached (\(maxAttempts)). Stopping.")
|
|
486
|
-
failAndStop(message: "Max reconnection attempts reached (\(maxAttempts)).")
|
|
487
|
-
return
|
|
488
|
-
}
|
|
489
|
-
reconnectStrategy.recordAttempt()
|
|
490
|
-
|
|
491
|
-
// Increment connectionAttemptVersion to discard stale callbacks from previous cycle
|
|
492
|
-
self.connectionAttemptVersion += 1
|
|
493
|
-
let newVersion = self.connectionAttemptVersion
|
|
494
|
-
eventSource?.stop()
|
|
495
|
-
eventSource = nil
|
|
496
|
-
self.updateState(.reconnecting)
|
|
497
541
|
dispatcher.asyncAfter(delay: delay) { [weak self] in
|
|
498
542
|
guard let self = self, self.isRunning, newVersion == self.connectionAttemptVersion else { return }
|
|
499
543
|
self.establishConnection(attemptVersion: newVersion)
|
|
@@ -505,143 +549,137 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
505
549
|
|
|
506
550
|
extension NitroSse: SseConnectionDelegate {
|
|
507
551
|
func connectionDidOpen(attemptVersion: Int) {
|
|
508
|
-
dispatcher.
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
}
|
|
552
|
+
dispatcher.assertOnQueue()
|
|
553
|
+
guard attemptVersion == self.connectionAttemptVersion else { return }
|
|
554
|
+
self.reconnectStrategy.reset()
|
|
555
|
+
self.consecutiveAuthErrors = 0
|
|
556
|
+
self.updateState(.open)
|
|
557
|
+
|
|
558
|
+
NitroSseNetworkInspector.reportResponseStart(
|
|
559
|
+
self.requestId,
|
|
560
|
+
url: self.config?.url,
|
|
561
|
+
response: nil,
|
|
562
|
+
statusCode: 200,
|
|
563
|
+
headers: [:]
|
|
564
|
+
)
|
|
565
|
+
|
|
566
|
+
self.eventBuffer.push(SseEvent(type: .open, data: nil, parsedData: nil, id: nil, event: nil, message: nil, statusCode: 200, retry: nil, state: nil))
|
|
524
567
|
}
|
|
525
568
|
|
|
526
569
|
func connectionDidClose(attemptVersion: Int) {
|
|
527
|
-
dispatcher.
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
if self.isRunning {
|
|
534
|
-
self.scheduleAutomaticReconnect(isError: false, attemptVersion: attemptVersion)
|
|
535
|
-
}
|
|
570
|
+
dispatcher.assertOnQueue()
|
|
571
|
+
guard attemptVersion == self.connectionAttemptVersion else { return }
|
|
572
|
+
self.finishActiveRequestInspector()
|
|
573
|
+
if self.isRunning {
|
|
574
|
+
// Server clean disconnect invalidates session and stops LDSwift internal timer.
|
|
575
|
+
self.scheduleAutomaticReconnect(isError: false, attemptVersion: attemptVersion)
|
|
536
576
|
}
|
|
537
577
|
}
|
|
538
578
|
|
|
539
579
|
func connectionDidReceiveMessage(eventType: String, data: String, lastEventId: String, attemptVersion: Int) {
|
|
540
|
-
dispatcher.
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
self.eventBuffer.push(SseEvent(type: .message, data: data, parsedData: parsedData, id: lastEventId, event: eventType, message: nil, statusCode: 200, retry: nil, state: nil))
|
|
553
|
-
}
|
|
580
|
+
dispatcher.assertOnQueue()
|
|
581
|
+
guard attemptVersion == self.connectionAttemptVersion else { return }
|
|
582
|
+
let encodedDataSize = Double(data.utf8.count)
|
|
583
|
+
let metadataSize = Double(eventType.utf8.count) + Double(lastEventId.utf8.count)
|
|
584
|
+
self.totalBytesReceived += encodedDataSize + metadataSize
|
|
585
|
+
|
|
586
|
+
// WHATWG SSE Spec: If the server sends an empty id (e.g. 'id:\n'), reset lastProcessedId to nil.
|
|
587
|
+
self.lastProcessedId = lastEventId.isEmpty ? nil : lastEventId
|
|
588
|
+
|
|
589
|
+
let parsedData = (self.config?.autoParseJSON == true) ? SseEventBuffer.parseJsonToAnyMap(data) : nil
|
|
590
|
+
|
|
591
|
+
self.eventBuffer.push(SseEvent(type: .message, data: data, parsedData: parsedData, id: lastEventId, event: eventType, message: nil, statusCode: 200, retry: nil, state: nil))
|
|
554
592
|
}
|
|
555
593
|
|
|
556
594
|
func connectionDidReceiveComment(_ comment: String, attemptVersion: Int) {
|
|
557
|
-
dispatcher.
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
}
|
|
595
|
+
dispatcher.assertOnQueue()
|
|
596
|
+
guard attemptVersion == self.connectionAttemptVersion else { return }
|
|
597
|
+
self.totalBytesReceived += Double(comment.utf8.count)
|
|
598
|
+
self.eventBuffer.push(SseEvent(type: .heartbeat, data: nil, parsedData: nil, id: nil, event: nil, message: comment, statusCode: nil, retry: nil, state: nil))
|
|
562
599
|
}
|
|
563
600
|
|
|
564
601
|
func connectionDidFail(error: Error, attemptVersion: Int) {
|
|
565
|
-
dispatcher.
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
if statusCode >= 100 && statusCode < 600 {
|
|
579
|
-
NitroSseNetworkInspector.reportResponseStart(
|
|
580
|
-
self.requestId,
|
|
581
|
-
url: self.config?.url,
|
|
582
|
-
response: nil,
|
|
583
|
-
statusCode: statusCode,
|
|
584
|
-
headers: [:]
|
|
585
|
-
)
|
|
586
|
-
}
|
|
587
|
-
NitroSseNetworkInspector.reportRequestFailed(self.requestId, cancelled: false)
|
|
588
|
-
self.requestId = nil
|
|
589
|
-
|
|
590
|
-
// HTTP 204 No Content indicates the server closed the stream intentionally without error.
|
|
591
|
-
if statusCode == 204 {
|
|
592
|
-
self.failAndStop(message: "No Content (204). Stopping.", statusCode: 204)
|
|
593
|
-
return
|
|
594
|
-
}
|
|
595
|
-
|
|
596
|
-
// HTTP 401/403 Auth errors trigger token refresh via onBeforeRequest interceptor up to maxAuthRetries.
|
|
597
|
-
if statusCode == 401 || statusCode == 403 {
|
|
598
|
-
if self.config?.onBeforeRequest == nil {
|
|
599
|
-
self.failAndStop(message: "Auth Error (\(statusCode)) - No interceptor provided. Stopping.", statusCode: Double(statusCode))
|
|
600
|
-
return
|
|
601
|
-
}
|
|
602
|
+
dispatcher.assertOnQueue()
|
|
603
|
+
guard self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
|
|
604
|
+
|
|
605
|
+
let nsError = error as NSError
|
|
606
|
+
var statusCode = nsError.code
|
|
607
|
+
if let responseError = error as? UnsuccessfulResponseError {
|
|
608
|
+
statusCode = responseError.responseCode
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
self.reconnectCount += 1
|
|
612
|
+
self.lastErrorTime = Date().timeIntervalSince1970 * 1000
|
|
613
|
+
self.lastErrorCode = "\(nsError.domain)(\(statusCode))"
|
|
602
614
|
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
615
|
+
if statusCode >= 100 && statusCode < 600 {
|
|
616
|
+
NitroSseNetworkInspector.reportResponseStart(
|
|
617
|
+
self.requestId,
|
|
618
|
+
url: self.config?.url,
|
|
619
|
+
response: nil,
|
|
620
|
+
statusCode: statusCode,
|
|
621
|
+
headers: [:]
|
|
622
|
+
)
|
|
623
|
+
}
|
|
624
|
+
NitroSseNetworkInspector.reportRequestFailed(self.requestId, cancelled: false)
|
|
625
|
+
self.requestId = nil
|
|
626
|
+
|
|
627
|
+
// HTTP 204 No Content explicitly terminates stream across platforms.
|
|
628
|
+
if statusCode == 204 {
|
|
629
|
+
self.failAndStop(message: "No Content (204). Stopping.", statusCode: 204)
|
|
630
|
+
return
|
|
631
|
+
}
|
|
613
632
|
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
633
|
+
// HTTP 401/403 Auth errors trigger token refresh via onBeforeRequest interceptor up to maxAuthRetries.
|
|
634
|
+
let limit = Int(self.config?.maxAuthRetries ?? Double(Self.defaultMaxAuthRetries))
|
|
635
|
+
if statusCode == 401 || statusCode == 403 {
|
|
636
|
+
if self.config?.onBeforeRequest == nil {
|
|
637
|
+
self.failAndStop(message: "Auth Error (\(statusCode)) - No interceptor provided. Stopping.", statusCode: Double(statusCode))
|
|
617
638
|
return
|
|
618
639
|
}
|
|
619
640
|
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
let jitter = Double.random(in: 0.5...1.5)
|
|
624
|
-
let totalDelay = retryAfter + jitter
|
|
625
|
-
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))
|
|
626
|
-
self.scheduleAutomaticReconnectWithFixedDelay(totalDelay, attemptVersion: attemptVersion)
|
|
641
|
+
self.consecutiveAuthErrors += 1
|
|
642
|
+
if self.consecutiveAuthErrors >= limit {
|
|
643
|
+
self.failAndStop(message: "Auth Error (\(statusCode)) - Retry limit reached (\(limit)). Stopping.", statusCode: Double(statusCode))
|
|
627
644
|
return
|
|
628
645
|
}
|
|
646
|
+
|
|
647
|
+
self.eventBuffer.push(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Auth Error (\(statusCode)) - Retry \(self.consecutiveAuthErrors)/\(limit). Refreshing token...", statusCode: Double(statusCode), retry: nil, state: nil))
|
|
648
|
+
self.scheduleAutomaticReconnect(isError: true, attemptVersion: attemptVersion)
|
|
649
|
+
return
|
|
650
|
+
}
|
|
629
651
|
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
return
|
|
636
|
-
}
|
|
652
|
+
let isFatal = (statusCode >= 400 && statusCode <= 499 && statusCode != 401 && statusCode != 403 && statusCode != 408 && statusCode != 429)
|
|
653
|
+
if isFatal {
|
|
654
|
+
self.failAndStop(message: "Fatal Error (\(statusCode)). Stopping.", statusCode: Double(statusCode))
|
|
655
|
+
return
|
|
656
|
+
}
|
|
637
657
|
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
658
|
+
// HTTP 429 Rate Limit / 503 Service Unavailable: Honor server Retry-After delay with randomized jitter to prevent thundering herd.
|
|
659
|
+
let retryAfterSeconds = SseReconnectStrategy.extractRetryAfterSeconds(from: error)
|
|
660
|
+
if (statusCode == 429 || statusCode == 503), let retryAfter = retryAfterSeconds {
|
|
661
|
+
let jitter = Double.random(in: 0.5...1.5)
|
|
662
|
+
let totalDelay = retryAfter + jitter
|
|
663
|
+
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))
|
|
664
|
+
self.scheduleAutomaticReconnect(isError: true, fixedDelay: totalDelay, attemptVersion: attemptVersion)
|
|
665
|
+
return
|
|
666
|
+
}
|
|
642
667
|
|
|
643
|
-
|
|
668
|
+
// HTTP 429 without Retry-After: Fallback to exponential backoff rather than stopping permanently,
|
|
669
|
+
// as rate limits are transient and recoverable.
|
|
670
|
+
if statusCode == 429 {
|
|
671
|
+
self.eventBuffer.push(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Rate Limited (429). Retrying with backoff...", statusCode: 429, retry: nil, state: nil))
|
|
644
672
|
self.scheduleAutomaticReconnect(isError: true, attemptVersion: attemptVersion)
|
|
673
|
+
return
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
// Map request timeout to stale state before initiating reconnect.
|
|
677
|
+
let isTimeout = (nsError.domain == NSURLErrorDomain && nsError.code == NSURLErrorTimedOut) || statusCode == -1001
|
|
678
|
+
if isTimeout {
|
|
679
|
+
self.updateState(.stale)
|
|
645
680
|
}
|
|
681
|
+
|
|
682
|
+
self.eventBuffer.push(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: error.localizedDescription, statusCode: Double(statusCode), retry: nil, state: nil))
|
|
683
|
+
self.scheduleAutomaticReconnect(isError: true, attemptVersion: attemptVersion)
|
|
646
684
|
}
|
|
647
685
|
}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import Foundation
|
|
2
1
|
import NitroModules
|
|
3
2
|
|
|
4
3
|
extension SseConfig {
|
|
@@ -18,6 +17,7 @@ extension SseConfig {
|
|
|
18
17
|
maxRetryIntervalMs: Double?? = nil,
|
|
19
18
|
jitterFactor: Double?? = nil,
|
|
20
19
|
maxReconnectAttempts: Double?? = nil,
|
|
20
|
+
maxAuthRetries: Double?? = nil,
|
|
21
21
|
autoParseJSON: Bool?? = nil,
|
|
22
22
|
monitorNetwork: Bool?? = nil,
|
|
23
23
|
onBeforeRequest: (() -> Promise<Promise<Dictionary<String, String>>>)?? = nil,
|
|
@@ -37,6 +37,7 @@ extension SseConfig {
|
|
|
37
37
|
maxRetryIntervalMs: maxRetryIntervalMs ?? self.maxRetryIntervalMs,
|
|
38
38
|
jitterFactor: jitterFactor ?? self.jitterFactor,
|
|
39
39
|
maxReconnectAttempts: maxReconnectAttempts ?? self.maxReconnectAttempts,
|
|
40
|
+
maxAuthRetries: maxAuthRetries ?? self.maxAuthRetries,
|
|
40
41
|
autoParseJSON: autoParseJSON ?? self.autoParseJSON,
|
|
41
42
|
monitorNetwork: monitorNetwork ?? self.monitorNetwork,
|
|
42
43
|
onBeforeRequest: onBeforeRequest ?? self.onBeforeRequest,
|