react-native-nitro-sse 2.4.1 → 3.0.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.
- package/README.md +209 -95
- 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 -38
- package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +194 -100
- 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 -28
- 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 +6 -4
- package/ios/NitroSse.swift +244 -190
- package/ios/SseConfig+CopyWith.swift +2 -1
- package/ios/SseConnectionHandler.swift +59 -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 +8 -2
- package/ios/SseReconnectStrategy.swift +9 -3
- package/lib/module/MockSseEngine.js +203 -0
- package/lib/module/NitroSseClient.js +411 -214
- package/lib/module/NitroSseError.js +61 -0
- package/lib/module/SseDriver.js +156 -0
- package/lib/module/index.js +6 -3
- package/lib/module/useNitroSse.js +359 -0
- package/lib/typescript/src/MockSseEngine.d.ts +31 -0
- package/lib/typescript/src/NitroSse.nitro.d.ts +25 -2
- package/lib/typescript/src/NitroSseClient.d.ts +25 -7
- package/lib/typescript/src/NitroSseError.d.ts +38 -0
- package/lib/typescript/src/SseDriver.d.ts +80 -0
- package/lib/typescript/src/SseInterface.d.ts +25 -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 +7 -1
- package/nitrogen/generated/android/c++/JSseMockConfig.hpp +2 -0
- package/nitrogen/generated/android/c++/JSseMockEvent.hpp +9 -3
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +9 -4
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockEvent.kt +9 -4
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +15 -15
- package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +3 -3
- package/nitrogen/generated/ios/swift/SseConfig.swift +19 -1
- package/nitrogen/generated/ios/swift/SseMockEvent.swift +12 -1
- package/nitrogen/generated/shared/c++/SseConfig.hpp +5 -1
- package/nitrogen/generated/shared/c++/SseMockEvent.hpp +9 -2
- package/package.json +10 -11
- package/android/jacoco.gradle +0 -33
- package/lib/module/NitroSse.nitro.js.map +0 -1
- package/lib/module/NitroSseClient.js.map +0 -1
- package/lib/module/SseInterface.js.map +0 -1
- package/lib/module/index.js.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/SseInterface.d.ts.map +0 -1
- package/lib/typescript/src/index.d.ts.map +0 -1
- package/src/NitroSse.nitro.ts +0 -58
- package/src/NitroSseClient.ts +0 -337
- package/src/SseInterface.ts +0 -272
- package/src/index.ts +0 -31
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import Foundation
|
|
2
2
|
import LDSwiftEventSource
|
|
3
|
-
import NitroModules
|
|
4
3
|
|
|
5
4
|
/// Delegate protocol for receiving lifecycle and stream events from `SseConnectionHandler`.
|
|
6
5
|
protocol SseConnectionDelegate: AnyObject {
|
|
@@ -25,29 +24,39 @@ enum SseConnectionHandler {
|
|
|
25
24
|
) -> EventSource {
|
|
26
25
|
let sessionConfig = URLSessionConfiguration.default
|
|
27
26
|
let readTimeout = (config.readTimeoutMs ?? 300000.0) / 1000.0
|
|
28
|
-
|
|
27
|
+
// Use timeoutIntervalForRequest (resets on incoming chunks) rather than timeoutIntervalForResource.
|
|
28
|
+
// Setting timeoutIntervalForResource would hard-cap the total lifetime of persistent SSE streams.
|
|
29
29
|
sessionConfig.timeoutIntervalForRequest = readTimeout
|
|
30
|
-
sessionConfig.timeoutIntervalForResource = connectionTimeout
|
|
31
30
|
|
|
31
|
+
let connectionTimeout = (config.connectionTimeoutMs ?? 15000.0) / 1000.0
|
|
32
32
|
let handler = SseHandler(delegate: delegate, attemptVersion: attemptVersion, dispatcher: dispatcher)
|
|
33
33
|
var esConfig = EventSource.Config(handler: handler, url: url)
|
|
34
|
+
// Prevent LDSwiftEventSource's default 300s idle timeout override.
|
|
35
|
+
esConfig.idleTimeout = readTimeout
|
|
36
|
+
// Disable LDSwift internal reconnect; reconnection is coordinated externally by NitroSse.
|
|
34
37
|
esConfig.connectionErrorHandler = { [weak handler] error in
|
|
35
38
|
handler?.onError(error: error)
|
|
36
39
|
return .shutdown
|
|
37
40
|
}
|
|
38
41
|
esConfig.urlSessionConfiguration = sessionConfig
|
|
39
|
-
|
|
40
|
-
|
|
42
|
+
// Prevent initial config headers from overriding the dynamic Last-Event-ID on reconnection.
|
|
43
|
+
var initialHeaders = config.headers ?? [:]
|
|
44
|
+
initialHeaders = initialHeaders.filter { $0.key.caseInsensitiveCompare("Last-Event-Id") != .orderedSame }
|
|
45
|
+
esConfig.headers = initialHeaders
|
|
46
|
+
esConfig.lastEventId = lastProcessedId ?? ""
|
|
41
47
|
if let lastId = lastProcessedId, !lastId.isEmpty {
|
|
42
|
-
esConfig.
|
|
48
|
+
esConfig.headerTransform = { headers in
|
|
49
|
+
var transformed = headers
|
|
50
|
+
transformed["Last-Event-Id"] = lastId
|
|
51
|
+
return transformed
|
|
52
|
+
}
|
|
43
53
|
}
|
|
44
|
-
|
|
45
|
-
esConfig.lastEventId = lastProcessedId ?? ""
|
|
46
54
|
esConfig.method = config.method?.stringValue.uppercased() ?? "GET"
|
|
47
55
|
esConfig.body = config.body?.data(using: .utf8)
|
|
48
56
|
|
|
49
57
|
let es = EventSource(config: esConfig)
|
|
50
58
|
handler.source = es
|
|
59
|
+
handler.startConnectionTimer(timeout: connectionTimeout)
|
|
51
60
|
es.start()
|
|
52
61
|
return es
|
|
53
62
|
}
|
|
@@ -62,6 +71,8 @@ private class SseHandler: EventHandler {
|
|
|
62
71
|
weak var source: EventSource?
|
|
63
72
|
let attemptVersion: Int
|
|
64
73
|
let dispatcher: SseDispatcher
|
|
74
|
+
private var isConnectedOrFinished: Bool = false
|
|
75
|
+
private var isTerminalDispatched: Bool = false
|
|
65
76
|
|
|
66
77
|
init(delegate: SseConnectionDelegate, attemptVersion: Int, dispatcher: SseDispatcher) {
|
|
67
78
|
self.delegate = delegate
|
|
@@ -69,27 +80,49 @@ private class SseHandler: EventHandler {
|
|
|
69
80
|
self.dispatcher = dispatcher
|
|
70
81
|
}
|
|
71
82
|
|
|
72
|
-
func
|
|
73
|
-
guard source != nil else { return }
|
|
83
|
+
private func dispatchToDelegate(isTerminal: Bool = false, _ action: @escaping (SseConnectionDelegate) -> Void) {
|
|
74
84
|
dispatcher.async { [weak self] in
|
|
75
|
-
guard let self = self else { return }
|
|
76
|
-
|
|
85
|
+
guard let self = self, self.source != nil else { return }
|
|
86
|
+
if isTerminal {
|
|
87
|
+
guard !self.isTerminalDispatched else { return }
|
|
88
|
+
self.isTerminalDispatched = true
|
|
89
|
+
}
|
|
90
|
+
self.isConnectedOrFinished = true
|
|
91
|
+
guard let delegate = self.delegate else { return }
|
|
92
|
+
action(delegate)
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
func startConnectionTimer(timeout: TimeInterval) {
|
|
97
|
+
guard timeout > 0 else { return }
|
|
98
|
+
dispatcher.asyncAfter(delay: timeout) { [weak self] in
|
|
99
|
+
guard let self = self, !self.isConnectedOrFinished, self.source != nil else { return }
|
|
100
|
+
self.isConnectedOrFinished = true
|
|
101
|
+
self.isTerminalDispatched = true
|
|
102
|
+
self.source?.stop()
|
|
103
|
+
self.source = nil
|
|
104
|
+
self.delegate?.connectionDidFail(
|
|
105
|
+
error: NSError(domain: NSURLErrorDomain, code: NSURLErrorTimedOut, userInfo: [NSLocalizedDescriptionKey: "Connection timed out"]),
|
|
106
|
+
attemptVersion: self.attemptVersion
|
|
107
|
+
)
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
func onOpened() {
|
|
112
|
+
dispatchToDelegate { delegate in
|
|
113
|
+
delegate.connectionDidOpen(attemptVersion: self.attemptVersion)
|
|
77
114
|
}
|
|
78
115
|
}
|
|
79
116
|
|
|
80
117
|
func onClosed() {
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
guard let self = self else { return }
|
|
84
|
-
self.delegate?.connectionDidClose(attemptVersion: self.attemptVersion)
|
|
118
|
+
dispatchToDelegate(isTerminal: true) { delegate in
|
|
119
|
+
delegate.connectionDidClose(attemptVersion: self.attemptVersion)
|
|
85
120
|
}
|
|
86
121
|
}
|
|
87
122
|
|
|
88
123
|
func onMessage(eventType: String, messageEvent: MessageEvent) {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
guard let self = self else { return }
|
|
92
|
-
self.delegate?.connectionDidReceiveMessage(
|
|
124
|
+
dispatchToDelegate { delegate in
|
|
125
|
+
delegate.connectionDidReceiveMessage(
|
|
93
126
|
eventType: eventType,
|
|
94
127
|
data: messageEvent.data,
|
|
95
128
|
lastEventId: messageEvent.lastEventId,
|
|
@@ -99,20 +132,17 @@ private class SseHandler: EventHandler {
|
|
|
99
132
|
}
|
|
100
133
|
|
|
101
134
|
/// Maps native SSE comments (lines starting with ':') to heartbeat events.
|
|
102
|
-
///
|
|
135
|
+
/// Normalizes comment by removing single leading space per WHATWG SSE specification for cross-platform parity.
|
|
103
136
|
func onComment(comment: String) {
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
self.delegate?.connectionDidReceiveComment(comment, attemptVersion: self.attemptVersion)
|
|
137
|
+
let normalized = comment.hasPrefix(" ") ? String(comment.dropFirst()) : comment
|
|
138
|
+
dispatchToDelegate { delegate in
|
|
139
|
+
delegate.connectionDidReceiveComment(normalized, attemptVersion: self.attemptVersion)
|
|
108
140
|
}
|
|
109
141
|
}
|
|
110
142
|
|
|
111
143
|
func onError(error: Error) {
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
guard let self = self else { return }
|
|
115
|
-
self.delegate?.connectionDidFail(error: error, attemptVersion: self.attemptVersion)
|
|
144
|
+
dispatchToDelegate(isTerminal: true) { delegate in
|
|
145
|
+
delegate.connectionDidFail(error: error, attemptVersion: self.attemptVersion)
|
|
116
146
|
}
|
|
117
147
|
}
|
|
118
148
|
}
|
|
@@ -15,8 +15,21 @@ class SseDispatchQueueDispatcher: SseDispatcher {
|
|
|
15
15
|
queue.async(execute: block)
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
-
|
|
19
|
-
|
|
18
|
+
private class WorkItemCancellable: SseCancellable {
|
|
19
|
+
private let item: DispatchWorkItem
|
|
20
|
+
init(item: DispatchWorkItem) {
|
|
21
|
+
self.item = item
|
|
22
|
+
}
|
|
23
|
+
func cancel() {
|
|
24
|
+
item.cancel()
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
@discardableResult
|
|
29
|
+
func asyncAfter(delay: TimeInterval, _ block: @escaping () -> Void) -> SseCancellable? {
|
|
30
|
+
let workItem = DispatchWorkItem(block: block)
|
|
31
|
+
queue.asyncAfter(deadline: .now() + delay, execute: workItem)
|
|
32
|
+
return WorkItemCancellable(item: workItem)
|
|
20
33
|
}
|
|
21
34
|
|
|
22
35
|
/// Executes block inline if already running on queue to avoid re-entrant deadlocks.
|
package/ios/SseDispatcher.swift
CHANGED
|
@@ -1,10 +1,16 @@
|
|
|
1
1
|
import Foundation
|
|
2
2
|
|
|
3
|
+
/// Token representing a scheduled asynchronous delayed work item that can be cancelled.
|
|
4
|
+
protocol SseCancellable: AnyObject {
|
|
5
|
+
func cancel()
|
|
6
|
+
}
|
|
7
|
+
|
|
3
8
|
/// Abstraction layer for serializing operations and scheduling timers across production and test environments.
|
|
4
9
|
/// Enables deterministic synchronous control in unit tests (`MockSseDispatcher`) without real-time wait delays.
|
|
5
10
|
protocol SseDispatcher: AnyObject {
|
|
6
11
|
func async(_ block: @escaping () -> Void)
|
|
7
|
-
|
|
12
|
+
@discardableResult
|
|
13
|
+
func asyncAfter(delay: TimeInterval, _ block: @escaping () -> Void) -> SseCancellable?
|
|
8
14
|
func sync<T>(_ block: () throws -> T) rethrows -> T
|
|
9
15
|
|
|
10
16
|
/// Checks whether the caller is running on the dispatcher's execution context to avoid re-entrant deadlocks on `sync`.
|
package/ios/SseEventBuffer.swift
CHANGED
|
@@ -5,7 +5,7 @@ import NitroModules
|
|
|
5
5
|
/// All mutating operations must be synchronized on the associated `SseDispatcher`.
|
|
6
6
|
class SseEventBuffer {
|
|
7
7
|
private var eventBuffer: [SseEvent] = []
|
|
8
|
-
private var
|
|
8
|
+
private var pendingTimer: SseCancellable?
|
|
9
9
|
private var onFlush: ((_ events: [SseEvent]) -> Void)?
|
|
10
10
|
|
|
11
11
|
private var batchingIntervalMs: Double = 0
|
|
@@ -35,11 +35,14 @@ class SseEventBuffer {
|
|
|
35
35
|
eventBuffer.append(event)
|
|
36
36
|
|
|
37
37
|
if eventBuffer.count >= maxBufferSize || batchingIntervalMs <= 0 {
|
|
38
|
+
cancelPendingTimer()
|
|
38
39
|
flush()
|
|
39
|
-
} else if
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
self?.
|
|
40
|
+
} else if pendingTimer == nil, let dispatcher = dispatcher {
|
|
41
|
+
pendingTimer = dispatcher.asyncAfter(delay: batchingIntervalMs / 1000.0) { [weak self] in
|
|
42
|
+
guard let self = self else { return }
|
|
43
|
+
self.dispatcher?.assertOnQueue()
|
|
44
|
+
self.pendingTimer = nil
|
|
45
|
+
self.flush()
|
|
43
46
|
}
|
|
44
47
|
}
|
|
45
48
|
}
|
|
@@ -47,20 +50,33 @@ class SseEventBuffer {
|
|
|
47
50
|
/// Flushes all pending buffered events to JavaScript.
|
|
48
51
|
func flush() {
|
|
49
52
|
dispatcher?.assertOnQueue()
|
|
53
|
+
cancelPendingTimer()
|
|
50
54
|
guard !eventBuffer.isEmpty else { return }
|
|
51
55
|
|
|
52
56
|
let batch = eventBuffer
|
|
53
57
|
eventBuffer.removeAll()
|
|
54
|
-
isFlushPending = false
|
|
55
58
|
|
|
56
59
|
onFlush?(batch)
|
|
57
60
|
}
|
|
58
61
|
|
|
62
|
+
private func cancelPendingTimer() {
|
|
63
|
+
dispatcher?.assertOnQueue()
|
|
64
|
+
pendingTimer?.cancel()
|
|
65
|
+
pendingTimer = nil
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/// Nullifies the flush callback to prevent invoking a destroyed JS runtime during teardown.
|
|
69
|
+
func clearCallback() {
|
|
70
|
+
dispatcher?.assertOnQueue()
|
|
71
|
+
self.onFlush = nil
|
|
72
|
+
}
|
|
73
|
+
|
|
59
74
|
/// Clears buffered events without invoking the flush callback.
|
|
60
75
|
/// Used during teardown to avoid executing JS callbacks after the bridge runtime is destroyed.
|
|
61
76
|
func clear() {
|
|
77
|
+
dispatcher?.assertOnQueue()
|
|
78
|
+
cancelPendingTimer()
|
|
62
79
|
eventBuffer.removeAll()
|
|
63
|
-
isFlushPending = false
|
|
64
80
|
}
|
|
65
81
|
|
|
66
82
|
/// Converts a raw JSON payload string into a Nitro `AnyMap`.
|
|
@@ -27,10 +27,17 @@ class SseLifecycleManager {
|
|
|
27
27
|
self.onForeground = onForeground
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
+
/// Ensures notification observers are unregistered and active background tasks are ended on deallocation.
|
|
31
|
+
deinit {
|
|
32
|
+
stopObserving()
|
|
33
|
+
cleanupBackgroundTask()
|
|
34
|
+
}
|
|
35
|
+
|
|
30
36
|
/// Registers observer for iOS application state transitions via `NotificationCenter`.
|
|
37
|
+
/// Calls `removeObserver(self)` first to guarantee idempotency without mutable state.
|
|
31
38
|
func startObserving() {
|
|
32
|
-
NotificationCenter.default.removeObserver(self)
|
|
33
39
|
#if os(iOS)
|
|
40
|
+
NotificationCenter.default.removeObserver(self)
|
|
34
41
|
NotificationCenter.default.addObserver(
|
|
35
42
|
self,
|
|
36
43
|
selector: #selector(handleAppDidEnterBackground),
|
|
@@ -48,7 +55,9 @@ class SseLifecycleManager {
|
|
|
48
55
|
|
|
49
56
|
/// Unregisters all lifecycle notification observers.
|
|
50
57
|
func stopObserving() {
|
|
58
|
+
#if os(iOS)
|
|
51
59
|
NotificationCenter.default.removeObserver(self)
|
|
60
|
+
#endif
|
|
52
61
|
}
|
|
53
62
|
|
|
54
63
|
/// Begins a `UIBackgroundTask` to request background execution time from iOS.
|
|
@@ -24,6 +24,11 @@ class SseNetworkMonitor {
|
|
|
24
24
|
self.onChange = onChange
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
/// Synchronously queries whether the active network path is currently satisfied (online).
|
|
28
|
+
var isPathSatisfied: Bool {
|
|
29
|
+
return pathMonitor?.currentPath.status == .satisfied
|
|
30
|
+
}
|
|
31
|
+
|
|
27
32
|
/// Starts observing system network changes. Idempotent call.
|
|
28
33
|
func start() {
|
|
29
34
|
guard pathMonitor == nil else { return }
|
|
@@ -65,12 +70,13 @@ class SseNetworkMonitor {
|
|
|
65
70
|
|
|
66
71
|
print("[NitroSse] Network path changed: status=\(path.status), interface=\(String(describing: interfaceType))")
|
|
67
72
|
|
|
73
|
+
// Only trigger an interface change if both the previous and current interfaces are known and differ.
|
|
74
|
+
// Initial detection (lastPathInterface == nil) must NOT be flagged as an interface change to avoid
|
|
75
|
+
// falsely triggering an immediate stream restart right after connection startup.
|
|
68
76
|
let interfaceChanged: Bool
|
|
69
77
|
if isSatisfied {
|
|
70
78
|
if let lastInterface = lastPathInterface, let currentInterface = interfaceType {
|
|
71
79
|
interfaceChanged = lastInterface != currentInterface
|
|
72
|
-
} else if lastPathInterface == nil && interfaceType != nil {
|
|
73
|
-
interfaceChanged = true
|
|
74
80
|
} else {
|
|
75
81
|
interfaceChanged = false
|
|
76
82
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import Foundation
|
|
2
2
|
|
|
3
|
-
/// Calculates backoff delays using randomized full jitter exponential backoff
|
|
4
|
-
///
|
|
3
|
+
/// Calculates backoff delays using randomized full jitter exponential backoff.
|
|
4
|
+
/// Custom implementation guarantees cross-platform parity with Android and enforces maxReconnectAttempts.
|
|
5
5
|
class SseReconnectStrategy {
|
|
6
6
|
private var backoffCounter: Int = 0
|
|
7
7
|
private var currentReconnectAttempts: Int = 0
|
|
@@ -52,6 +52,11 @@ class SseReconnectStrategy {
|
|
|
52
52
|
guard maxReconnectAttempts != -1 else { return false }
|
|
53
53
|
return currentReconnectAttempts >= maxReconnectAttempts
|
|
54
54
|
}
|
|
55
|
+
|
|
56
|
+
/// Records an explicit reconnection attempt without altering the backoff exponent.
|
|
57
|
+
func recordAttempt() {
|
|
58
|
+
currentReconnectAttempts += 1
|
|
59
|
+
}
|
|
55
60
|
|
|
56
61
|
/// Calculates the next reconnection delay in seconds (enforcing a minimum 1.0s floor).
|
|
57
62
|
/// Exponential backoff is applied for errors (`isError == true`), while normal disconnects use the base interval with jitter.
|
|
@@ -77,7 +82,8 @@ class SseReconnectStrategy {
|
|
|
77
82
|
currentReconnectAttempts = 0
|
|
78
83
|
}
|
|
79
84
|
|
|
80
|
-
/// Parses `Retry-After` HTTP headers per RFC 7231
|
|
85
|
+
/// Parses `Retry-After` HTTP headers per RFC 7231 (integer seconds or RFC 1123 date).
|
|
86
|
+
/// Fallback to full jitter backoff when response metadata is omitted by underlying client.
|
|
81
87
|
static func extractRetryAfterSeconds(from error: Error) -> TimeInterval? {
|
|
82
88
|
let nsError = error as NSError
|
|
83
89
|
guard let response = nsError.userInfo["response"] as? HTTPURLResponse else { return nil }
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Encapsulates mock streaming logic for testing and offline simulation.
|
|
5
|
+
* Handles timer intervals, looping, custom delays, simulated error rates, and mock state tracking.
|
|
6
|
+
*/
|
|
7
|
+
export class MockSseEngine {
|
|
8
|
+
_mockIndex = 0;
|
|
9
|
+
_totalBytesReceived = 0;
|
|
10
|
+
constructor(config, emitEvents) {
|
|
11
|
+
this._config = config;
|
|
12
|
+
this._emitEvents = emitEvents;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Transforms a raw mock event definition or partial SSE event into a full SseEvent DTO.
|
|
17
|
+
*/
|
|
18
|
+
static createSseEvent(rawMock) {
|
|
19
|
+
return {
|
|
20
|
+
type: rawMock.type ?? 'message',
|
|
21
|
+
data: rawMock.data,
|
|
22
|
+
parsedData: rawMock.parsedData,
|
|
23
|
+
id: rawMock.id,
|
|
24
|
+
event: rawMock.event,
|
|
25
|
+
message: rawMock.message,
|
|
26
|
+
statusCode: rawMock.statusCode ?? 200,
|
|
27
|
+
retry: rawMock.retry,
|
|
28
|
+
state: rawMock.state
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
_setMockState(state) {
|
|
32
|
+
if (this._mockState !== state) {
|
|
33
|
+
this._mockState = state;
|
|
34
|
+
const stateEvent = {
|
|
35
|
+
type: 'state',
|
|
36
|
+
state,
|
|
37
|
+
statusCode: 200
|
|
38
|
+
};
|
|
39
|
+
this._emitEvents([stateEvent]);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Starts mock stream scheduling.
|
|
45
|
+
* @returns true if native stream should be skipped (replace mode), false otherwise (inject mode).
|
|
46
|
+
*/
|
|
47
|
+
start() {
|
|
48
|
+
if (this._mockIntervalId) {
|
|
49
|
+
clearTimeout(this._mockIntervalId);
|
|
50
|
+
this._mockIntervalId = undefined;
|
|
51
|
+
}
|
|
52
|
+
const {
|
|
53
|
+
mode,
|
|
54
|
+
data,
|
|
55
|
+
eventsPerSecond = 1,
|
|
56
|
+
loop = false,
|
|
57
|
+
errorRate = 0
|
|
58
|
+
} = this._config;
|
|
59
|
+
this._mockIndex = 0;
|
|
60
|
+
this._totalBytesReceived = 0;
|
|
61
|
+
|
|
62
|
+
// Validate and normalize eventsPerSecond (must be a finite positive number, default to 1)
|
|
63
|
+
let validatedEventsPerSecond = Number(eventsPerSecond);
|
|
64
|
+
if (Number.isNaN(validatedEventsPerSecond) || !Number.isFinite(validatedEventsPerSecond) || validatedEventsPerSecond <= 0) {
|
|
65
|
+
validatedEventsPerSecond = 1;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Validate and normalize errorRate (must be a finite number within [0,1], default to 0)
|
|
69
|
+
let validatedErrorRate = Number(errorRate);
|
|
70
|
+
if (Number.isNaN(validatedErrorRate) || !Number.isFinite(validatedErrorRate)) {
|
|
71
|
+
validatedErrorRate = 0;
|
|
72
|
+
} else {
|
|
73
|
+
validatedErrorRate = Math.max(0, Math.min(1, validatedErrorRate));
|
|
74
|
+
}
|
|
75
|
+
const delayMs = 1000 / validatedEventsPerSecond;
|
|
76
|
+
// Safeguard: if eventsPerSecond is huge (e.g. 1000), setInterval/setTimeout is too slow.
|
|
77
|
+
// We batch events together in chunks if the calculated interval is under 10ms.
|
|
78
|
+
const batchSize = Math.max(1, Math.round(validatedEventsPerSecond / 100)); // chunk size for 10ms intervals
|
|
79
|
+
const intervalMs = Math.max(10, delayMs * batchSize);
|
|
80
|
+
const scheduleNext = () => {
|
|
81
|
+
if (this._mockIndex >= data.length) {
|
|
82
|
+
if (loop && data.length > 0) {
|
|
83
|
+
this._mockIndex = 0;
|
|
84
|
+
} else {
|
|
85
|
+
if (this._mockIntervalId) {
|
|
86
|
+
clearTimeout(this._mockIntervalId);
|
|
87
|
+
this._mockIntervalId = undefined;
|
|
88
|
+
}
|
|
89
|
+
if (mode === 'replace') {
|
|
90
|
+
this._setMockState('closed');
|
|
91
|
+
const closeEvent = {
|
|
92
|
+
type: 'close',
|
|
93
|
+
statusCode: 200
|
|
94
|
+
};
|
|
95
|
+
this._emitEvents([closeEvent]);
|
|
96
|
+
}
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Simulate connection drops
|
|
102
|
+
if (validatedErrorRate && Math.random() < validatedErrorRate) {
|
|
103
|
+
if (mode === 'replace') {
|
|
104
|
+
this._setMockState('reconnecting');
|
|
105
|
+
}
|
|
106
|
+
const errorEvent = {
|
|
107
|
+
type: 'error',
|
|
108
|
+
message: 'Mock Connection Drop (Simulated Error)',
|
|
109
|
+
statusCode: 500
|
|
110
|
+
};
|
|
111
|
+
this._emitEvents([errorEvent]);
|
|
112
|
+
|
|
113
|
+
// Retry / reconnect delay simulator (e.g. 2000ms)
|
|
114
|
+
this._mockIntervalId = setTimeout(scheduleNext, 2000);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
const currentItem = data[this._mockIndex];
|
|
118
|
+
const hasCustomDelay = currentItem && typeof currentItem.delayMs === 'number';
|
|
119
|
+
const batch = [];
|
|
120
|
+
if (hasCustomDelay) {
|
|
121
|
+
const rawMock = data[this._mockIndex++];
|
|
122
|
+
if (rawMock) {
|
|
123
|
+
batch.push(MockSseEngine.createSseEvent(rawMock));
|
|
124
|
+
}
|
|
125
|
+
} else {
|
|
126
|
+
for (let i = 0; i < batchSize && this._mockIndex < data.length; i++) {
|
|
127
|
+
const nextItem = data[this._mockIndex];
|
|
128
|
+
if (nextItem && typeof nextItem.delayMs === 'number') {
|
|
129
|
+
break;
|
|
130
|
+
}
|
|
131
|
+
const rawMock = data[this._mockIndex++];
|
|
132
|
+
if (rawMock) {
|
|
133
|
+
batch.push(MockSseEngine.createSseEvent(rawMock));
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (batch.length > 0) {
|
|
138
|
+
for (const ev of batch) {
|
|
139
|
+
const dataLen = ev.data ? ev.data.length : 0;
|
|
140
|
+
const evLen = ev.event ? ev.event.length : 0;
|
|
141
|
+
const idLen = ev.id ? ev.id.length : 0;
|
|
142
|
+
this._totalBytesReceived += Math.max(1, dataLen + evLen + idLen);
|
|
143
|
+
}
|
|
144
|
+
if (mode === 'replace') {
|
|
145
|
+
this._setMockState('open');
|
|
146
|
+
}
|
|
147
|
+
this._emitEvents(batch);
|
|
148
|
+
}
|
|
149
|
+
const nextItem = this._mockIndex < data.length ? data[this._mockIndex] : data[0];
|
|
150
|
+
const nextDelay = this._mockIndex >= data.length && !loop ? 0 : typeof nextItem?.delayMs === 'number' ? nextItem.delayMs : intervalMs;
|
|
151
|
+
this._mockIntervalId = setTimeout(scheduleNext, nextDelay);
|
|
152
|
+
};
|
|
153
|
+
const firstItem = data[0];
|
|
154
|
+
const firstDelay = firstItem && typeof firstItem.delayMs === 'number' ? firstItem.delayMs : intervalMs;
|
|
155
|
+
if (mode === 'replace') {
|
|
156
|
+
this._setMockState('connecting');
|
|
157
|
+
this._setMockState('open');
|
|
158
|
+
|
|
159
|
+
// Emit simulated open event
|
|
160
|
+
const openEvent = {
|
|
161
|
+
type: 'open',
|
|
162
|
+
statusCode: 200
|
|
163
|
+
};
|
|
164
|
+
this._emitEvents([openEvent]);
|
|
165
|
+
this._mockIntervalId = setTimeout(scheduleNext, firstDelay);
|
|
166
|
+
return true; // Indicates replace mode (skip native start)
|
|
167
|
+
} else if (mode === 'inject') {
|
|
168
|
+
this._mockIntervalId = setTimeout(scheduleNext, firstDelay);
|
|
169
|
+
return false; // Indicates inject mode (continue native start)
|
|
170
|
+
}
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
173
|
+
stop() {
|
|
174
|
+
if (this._mockIntervalId) {
|
|
175
|
+
clearTimeout(this._mockIntervalId);
|
|
176
|
+
this._mockIntervalId = undefined;
|
|
177
|
+
}
|
|
178
|
+
if (this._config.mode === 'replace') {
|
|
179
|
+
this._setMockState('closed');
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
restart() {
|
|
183
|
+
this.stop();
|
|
184
|
+
this.start();
|
|
185
|
+
}
|
|
186
|
+
isConnected() {
|
|
187
|
+
return this._mockState === 'open' || this._mockState === 'connecting' || this._mockState === 'reconnecting';
|
|
188
|
+
}
|
|
189
|
+
getStats() {
|
|
190
|
+
return {
|
|
191
|
+
totalBytesReceived: this._totalBytesReceived,
|
|
192
|
+
reconnectCount: 0
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
getState() {
|
|
196
|
+
return this._mockState ?? 'idle';
|
|
197
|
+
}
|
|
198
|
+
injectEvent(event) {
|
|
199
|
+
const sseEvent = MockSseEngine.createSseEvent(event);
|
|
200
|
+
this._emitEvents([sseEvent]);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
//# sourceMappingURL=MockSseEngine.js.map
|